repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
zen0822/vue2do
package/component/tsDist/module/Nav/Nav.render.js
<gh_stars>10-100 "use strict"; /** * nav.render.js */ Object.defineProperty(exports, "__esModule", { value: true }); function foldContent(h, foldList) { var _this = this; if (!Array.isArray(foldList) || foldList.length === 0) { return false; } var foldChildren = []; foldList.forEach(function (item, index) { var subNav = item.sub; var flodNum = index + 1; var contentChildren = []; if (Array.isArray(subNav) && subNav.length > 0) { contentChildren = foldContent.call(_this, h, subNav); foldChildren.push(h('fold-title', { props: { ui: _this.ui, theme: _this.theme }, slot: 'title-' + flodNum }, item.name)); foldChildren.push(h('fold-content', { props: { ui: _this.ui, theme: _this.theme }, slot: 'content-' + flodNum }, [contentChildren])); } else { foldChildren.push(h('fold-title', { props: { ui: _this.ui, theme: _this.theme }, slot: 'title-' + flodNum }, [ h('router-link', { props: { to: item.route }, nativeOn: { click: function () { if (_this.isSmallDevice) { _this.hide(); } } } }, item.name) ])); } }); return h('fold', { class: [this.xclass('sub-fold')], props: { only: this.isSmallDevice ? true : this.only, spreadAll: this.isSmallDevice ? false : this.spreadAll, ui: this.ui, theme: this.theme }, ref: 'fold' }, foldChildren); } function default_1(h) { var _a, _b, _c; var navStage = []; var contentEle = h('div', { class: [this.xclass('motion-content')], ref: 'motionContent' }, [ h('div', { class: [ this.xclass('close-nav') ], on: { click: this.hide } }, [ h('icon', { props: { kind: 'close', size: 'xs', ui: this.ui, theme: this.theme } }) ]), this.$slots.start, foldContent.call(this, h, this.initOpt), this.$slots.end ]); if (this.isVerticalType) { navStage.push(h('motion-fold', { ref: 'motion' }, [ h('div', { class: [ this.xclass('stage'), this.xclass("animate-" + this.navAnimate) ] }, [contentEle]) ])); } else { navStage.push(h('motion-slide', { props: { direction: 'east', global: true, offset: 0 }, ref: 'motion' }, [ h('div', { class: [ this.xclass('stage'), this.xclass("animate-" + this.navAnimate) ] }, [ contentEle, h('div', { class: [this.xclass('motion-empty')], on: { click: this.hide } }) ]) ])); } return h('div', { class: [ this.cPrefix, this.xclass(this.themeClass), (_a = {}, _a[this.xclass('device-s')] = this.isSmallDevice, _a) ] }, [ h('div', { class: [ this.xclass('trigger'), (_b = {}, _b[this.xclass('active')] = this.isActive, _b) ], directives: [{ name: 'show', value: this.trigger === 'show' }], on: { click: this.toggle } }, [ h('row', [ h('column', { props: { span: 6 } }, this.title), h('column', { class: [this.xclass('arrow')], props: { span: 6 } }, [ h('icon', { class: [this.xclass('arrow-fold'), (_c = {}, _c[this.xclass('arrow-spread')] = this.isActive, _c)], props: { kind: 'arrow-south', size: 's', ui: this.ui, theme: this.theme } }) ]) ]) ]), navStage ]); } exports.default = default_1; //# sourceMappingURL=Nav.render.js.map
pitchbull/bosh
simple_blobstore_server/lib/simple_blobstore_server/version.rb
<filename>simple_blobstore_server/lib/simple_blobstore_server/version.rb module Bosh module SimpleBlobstoreServer VERSION = '1.3163.0' end end
npocmaka/Windows-Server-2003
printscan/ui/uicommon/rescale.h
/******************************************************************************* * * (C) COPYRIGHT MICROSOFT CORPORATION, 1998 * * TITLE: RESCALE.H * * VERSION: 1.0 * * AUTHOR: ShaunIv * * DATE: 10/15/1998 * * DESCRIPTION: Scale HBITMAPs using StretchBlt * *******************************************************************************/ #ifndef _RESCALE_H_INCLUDED #define _RESCALE_H_INCLUDED #include <windows.h> HRESULT ScaleImage( HDC hDC, HBITMAP hBmpSrc, HBITMAP &hBmpTgt, const SIZE &sizeTgt ); #endif
followanalytics/htmllint
test/functional/attr-bans.js
<filename>test/functional/attr-bans.js module.exports = [ { desc: 'should not match style elements', input: '<body><style>hello</style></body>', opts: { 'attr-bans': ['style'] }, output: 0 }, { desc: 'should match style attributes', input: '<button style="color: red;"></button>', opts: { 'attr-bans': ['style'] }, output: 1 }, { desc: 'should not match when disabled', input: '<button style="color: red;"></button>', opts: { 'attr-bans': false }, output: 0 }, { desc: 'should match banned if specified', input: '<body banned></body>', opts: { 'attr-bans': ['banned'] }, output: 1 } ];
KorreMarietta/pls50-E6
pls50e1 Korre/E1ask3/main.c
<filename>pls50e1 Korre/E1ask3/main.c #include <stdio.h> int main( void ) { int decimal = 0; printf("Dose enan akeraio thetiko arithmo:\n "); scanf("%d", &decimal); printf("(Akeraios) %d = (<NAME>) ", decimal ); while ( decimal != 0 ) { printf("%d", decimal % 2 ); decimal /= 2; } putchar('\n'); return 0; }
penghaiYin/bm-work-2020
server/src/main/java/edp/vap/core/enums/UserPermissionEnum.java
<filename>server/src/main/java/edp/vap/core/enums/UserPermissionEnum.java package edp.vap.core.enums; public enum UserPermissionEnum { HIDDEN((short) 0, "hidden"), READ((short) 1, "read only"), WRITE((short) 2, "write"), DELETE((short) 3, "delete"); private short permission; private String permissionName; UserPermissionEnum(short permission, String permissionName) { this.permission = permission; this.permissionName = permissionName; } public static UserPermissionEnum permissionOf(int permission) { for (UserPermissionEnum userPermissionEnum : values()) { if ((int) userPermissionEnum.getPermission() == permission) { return userPermissionEnum; } } return null; } public short getPermission() { return permission; } }
CS2510/Spring-22-CS-2510-In-Class
Archive/Lottery/lottery_game/RocketController.js
import Component from "../engine/Component.js" import Game from "../engine/Game.js" import Input from "../engine/Input.js" import Collisions from "../engine/Collisions.js"; import Time from "../engine/Time.js" import ElevatorScene from "./ElevatorScene.js"; import Constants from "./Constants.js" class RocketContoller extends Component { constructor(parent) { super(parent); this.speed = Constants.rocketSpeed; } update(ctx) { let playerGameObject = Game.findByNameOne("Player"); let player = playerGameObject.getComponent("Circle"); let heights = [ {name:"Sea Level", height:0}, {name:"Low Culumus Clouds", height:1_000}, {name:"The Tallest Skyscraper", height:2_717}, {name:"The Tree Line", height:4_800}, {name:"High Culumus Clouds", height:5_000}, {name:"Denver", height:5_279}, {name:"Mount Everest", height:29_032}, {name:"Jet Cruising Height", height:35_000}, {name:"Highest Flying Birds", height:37_000}, {name:"Troposphere", height:39_600}, ] //57_000 feet is the max player.y -= this.speed * Time.secondsBetweenFrame; Game.cameraX = player.x; Game.cameraY = player.y; let floorIndicatorGameObject = Game.findByNameOne("FloorIndicator"); let floorIndicator = floorIndicatorGameObject.getComponent("Text") let altitudeIndicatorGameObject = Game.findByNameOne("AltitudeIndicator"); let altitudeIndicator = altitudeIndicatorGameObject.getComponent("Text"); let higherThanGameObject = Game.findByNameOne("HigherThan"); let higherThan = higherThanGameObject.getComponent("Text"); let temperatureGameObject = Game.findByNameOne("Temperature"); let temperature = temperatureGameObject.getComponent("Text"); let floorNumber = -Math.ceil(player.y / Constants.platformHeight); floorIndicator.text = "Platform: " + (floorNumber + 1) + " of " + Constants.platforms; let feet = Math.floor(-player.y); let miles = Math.floor(feet / 5280*10)/10; altitudeIndicator.text = "Altitude: " + feet.toLocaleString("en-US") + " feet, (" + miles + " mile(s))"; let heightIndex = 0; for(let i = 0; i < heights.length; i++) { if(heights[i].height > feet) { heightIndex = i-1 break; } } higherThan.text = "(That's higher than: " + heights[heightIndex].name + ")"; temperature.text = "It is " + Math.floor(60 + player.y/1_000*3.5) + "°F"; } } export default RocketContoller;
ai-man-123/MDyoobotz
node_modules/@protobufjs/float/bench/index.js
<gh_stars>100-1000 "use strict"; var float = require(".."), ieee754 = require("ieee754"), newSuite = require("./suite"); var F32 = Float32Array; var F64 = Float64Array; delete global.Float32Array; delete global.Float64Array; var floatFallback = float({}); global.Float32Array = F32; global.Float64Array = F64; var buf = new Buffer(8); newSuite("writeFloat") .add("float", function() { float.writeFloatLE(0.1, buf, 0); }) .add("float (fallback)", function() { floatFallback.writeFloatLE(0.1, buf, 0); }) .add("ieee754", function() { ieee754.write(buf, 0.1, 0, true, 23, 4); }) .add("buffer", function() { buf.writeFloatLE(0.1, 0); }) .add("buffer (noAssert)", function() { buf.writeFloatLE(0.1, 0, true); }) .run(); newSuite("readFloat") .add("float", function() { float.readFloatLE(buf, 0); }) .add("float (fallback)", function() { floatFallback.readFloatLE(buf, 0); }) .add("ieee754", function() { ieee754.read(buf, 0, true, 23, 4); }) .add("buffer", function() { buf.readFloatLE(0); }) .add("buffer (noAssert)", function() { buf.readFloatLE(0, true); }) .run(); newSuite("writeDouble") .add("float", function() { float.writeDoubleLE(0.1, buf, 0); }) .add("float (fallback)", function() { floatFallback.writeDoubleLE(0.1, buf, 0); }) .add("ieee754", function() { ieee754.write(buf, 0.1, 0, true, 52, 8); }) .add("buffer", function() { buf.writeDoubleLE(0.1, 0); }) .add("buffer (noAssert)", function() { buf.writeDoubleLE(0.1, 0, true); }) .run(); newSuite("readDouble") .add("float", function() { float.readDoubleLE(buf, 0); }) .add("float (fallback)", function() { floatFallback.readDoubleLE(buf, 0); }) .add("ieee754", function() { ieee754.read(buf, 0, true, 52, 8); }) .add("buffer", function() { buf.readDoubleLE(0); }) .add("buffer (noAssert)", function() { buf.readDoubleLE(0, true); }) .run();
zealoussnow/chromium
device/fido/cable/fido_cable_handshake_handler_fuzzer.cc
<filename>device/fido/cable/fido_cable_handshake_handler_fuzzer.cc // Copyright 2018 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 <stddef.h> #include <stdint.h> #include <array> #include "base/containers/span.h" #include "base/memory/ref_counted.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "device/fido/cable/fido_cable_device.h" #include "device/fido/cable/fido_cable_handshake_handler.h" #include "device/fido/fido_constants.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace { constexpr std::array<uint8_t, 32> kTestSessionPreKey = {{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }}; constexpr std::array<uint8_t, 8> kTestNonce = {{ 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0x09, 0x08, }}; constexpr char kTestDeviceAddress[] = "Fake_Address"; } // namespace extern "C" int LLVMFuzzerTestOneInput(const uint8_t* raw_data, size_t size) { auto data_span = base::make_span(raw_data, size); auto adapter = base::MakeRefCounted<::testing::NiceMock<device::MockBluetoothAdapter>>(); device::FidoCableDevice test_cable_device(adapter.get(), kTestDeviceAddress); device::FidoCableV1HandshakeHandler handshake_handler_v1( &test_cable_device, kTestNonce, kTestSessionPreKey); handshake_handler_v1.ValidateAuthenticatorHandshakeMessage(data_span); return 0; }
lingnand/Helium
src/srchilite/lineranges.cpp
<filename>src/srchilite/lineranges.cpp /* * lineranges.cpp * * Created on: Sep 17, 2008 * Author: <NAME> <http://www.lorenzobettini.it>, (C) 2008 * Copyright: See COPYING file that comes with this distribution */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "lineranges.h" #include <sstream> #include <boost/regex.hpp> #include <cstdlib> namespace srchilite { /// regular expression for a single line static boost::regex singleNumber("\\s*([[:digit:]]+)\\s*"); /// regular expression for an interval static boost::regex rangeExp("\\s*([[:digit:]]+)\\s*-\\s*([[:digit:]]+)\\s*"); /// regular expression for an interval with only the first element static boost::regex rangeExp1("\\s*([[:digit:]]+)\\s*-\\s*"); /// regular expression for an interval with only the second element static boost::regex rangeExp2("\\s*-\\s*([[:digit:]]+)\\s*"); using namespace std; LineRanges::LineRanges(unsigned int context) : searchFromTheStart(true), contextLines(context) { } LineRanges::~LineRanges() { } RangeError LineRanges::addRange(const std::string &range) { boost::smatch match; if (boost::regex_match(range, match, singleNumber)) { lineRangeSet.insert(make_pair(strtol(match[1].str().c_str(), 0, 0), 0)); } else if (boost::regex_match(range, match, rangeExp)) { lineRangeSet.insert(make_pair(strtol(match[1].str().c_str(), 0, 0), strtol(match[2].str().c_str(), 0, 0))); } else if (boost::regex_match(range, match, rangeExp1)) { lineRangeSet.insert(make_pair(strtol(match[1].str().c_str(), 0, 0), -1)); } else if (boost::regex_match(range, match, rangeExp2)) { lineRangeSet.insert(make_pair(-1, strtol(match[1].str().c_str(), 0, 0))); } else { return INVALID_RANGE_NUMBER; } return NO_ERROR; } RangeResult LineRanges::isInRange(const RangeElemType e) { if (searchFromTheStart) { currentRange = lineRangeSet.begin(); searchFromTheStart = false; } while (currentRange != lineRangeSet.end()) { if (currentRange->first < 0) { // first and second cannot be both < 0 (already checked during add) if (e <= currentRange->second) { return IN_RANGE; } } else if (currentRange->second < 0) { if (e >= currentRange->first) { return IN_RANGE; } else { if ((contextLines > 0) && (currentRange->first - e) <= contextLines) { return CONTEXT_RANGE; } // makes no sense checking further ranges return NOT_IN_RANGE; } } else if (currentRange->second == 0) { // check perfect match if (e == currentRange->first) { return IN_RANGE; } else if (e < currentRange->first) { if (contextLines > 0) { if (((currentRange->first - e) <= contextLines)) { return CONTEXT_RANGE; } } // makes no sense checking further ranges return NOT_IN_RANGE; } else if (contextLines > 0 && ((e - currentRange->first) <= contextLines)) { return CONTEXT_RANGE; } } else if (e >= currentRange->first && e <= currentRange->second) { return IN_RANGE; } else if (contextLines > 0 && (((e < currentRange->first) && ((currentRange->first - e) <= contextLines)) || ((e > currentRange->second) && ((e - currentRange->second) <= contextLines)))) { return CONTEXT_RANGE; } else if (e < currentRange->first) { // makes no sense checking further ranges return NOT_IN_RANGE; } // if we're here we try with another range in the set currentRange++; } return NOT_IN_RANGE; } }
joshuaguite/cloudpassage-halo-python-sdk
tests/integration/test_integration_time_series.py
<reponame>joshuaguite/cloudpassage-halo-python-sdk import imp import os import pprint import pytest import sys from datetime import datetime, timedelta from cloudpassage.utility import Utility as utility module_name = 'cloudpassage' here_dir = os.path.dirname(os.path.abspath(__file__)) module_path = os.path.join(here_dir, '../../') sys.path.append(module_path) fp, pathname, description = imp.find_module(module_name) cloudpassage = imp.load_module(module_name, fp, pathname, description) class TestIntegrationTimeSeries(object): def get_halo_session(self): config_file_name = "portal.yaml.local" tests_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../")) config_file = os.path.join(tests_dir, "configs/", config_file_name) session_info = cloudpassage.ApiKeyManager(config_file=config_file) key_id = session_info.key_id secret_key = session_info.secret_key api_hostname = session_info.api_hostname api_port = session_info.api_port session = cloudpassage.HaloSession(key_id, secret_key, api_host=api_hostname, api_port=api_port, integration_string="SDK-Smoke") return session def test_time_series_iter_events_many_pages_fail(self): """Test against events endpoint.""" session = self.get_halo_session() start_time = utility.datetime_to_8601((datetime.now() - timedelta(30))) start_url = "/v1/eventss" item_key = "events" with pytest.raises(cloudpassage.CloudPassageValidation): cloudpassage.TimeSeries(session, start_time, start_url, item_key) assert False # Should bail and never hit this assertion. assert True def test_time_series_iter_events_many_pages(self): """Test against events endpoint.""" session = self.get_halo_session() start_time = utility.datetime_to_8601((datetime.now() - timedelta(30))) start_url = "/v1/events" item_key = "events" streamer = cloudpassage.TimeSeries(session, start_time, start_url, item_key) dupes = [] item_counter = 0 item_ids = set([]) for item in streamer: print("Item counter: %s Item ID: %s Item timestamp: %s" % (item_counter, item["id"], item["created_at"])) assert "id" in item if item["id"] in item_ids: print("Duplicate ^^^") dupes.append(item["id"]) item_ids.add(item["id"]) item_counter += 1 if item_counter > 60: break if dupes: print("Dupes:") pprint.pprint(dupes) assert False def test_time_series_iter_issues_many_pages(self): """Test against issues endpoint.""" session = self.get_halo_session() start_time = utility.datetime_to_8601((datetime.now() - timedelta(30))) start_url = "/v1/issues" item_key = "issues" streamer = cloudpassage.TimeSeries(session, start_time, start_url, item_key) dupes = [] item_counter = 0 item_ids = set([]) for item in streamer: print("Item counter: %s Item ID: %s Item timestamp: %s" % (item_counter, item["id"], item["created_at"])) assert "id" in item if item["id"] in item_ids: print("Duplicate ^^^") dupes.append(item["id"]) item_ids.add(item["id"]) item_counter += 1 if item_counter > 5: break if dupes: print("Dupes:") pprint.pprint(dupes) assert False def test_time_series_iter_scans_many_pages(self): """Test against scans endpoint.""" session = self.get_halo_session() start_time = utility.datetime_to_8601((datetime.now() - timedelta(30))) start_url = "/v1/scans" item_key = "scans" streamer = cloudpassage.TimeSeries(session, start_time, start_url, item_key) dupes = [] item_counter = 0 item_ids = set([]) for item in streamer: print("Item counter: %s Item ID: %s Item timestamp: %s" % (item_counter, item["id"], item["created_at"])) assert "id" in item if item["id"] in item_ids: print("Duplicate ^^^") dupes.append(item["id"]) item_ids.add(item["id"]) item_counter += 1 if item_counter > 5: break if dupes: print("Dupes:") pprint.pprint(dupes) assert False def test_time_series_iter_events_many_pages_internal_killswitch(self): """Test triggering exit w/ StopIteration in TimeSeries().__iter__()""" session = self.get_halo_session() start_time = utility.datetime_to_8601((datetime.now() - timedelta(30))) start_url = "/v1/events" item_key = "events" streamer = cloudpassage.TimeSeries(session, start_time, start_url, item_key) dupes = [] item_counter = 0 item_ids = set([]) for item in streamer: print("Item counter: %s Item ID: %s Item timestamp: %s" % (item_counter, item["id"], item["created_at"])) assert "id" in item if item["id"] in item_ids: print("Duplicate ^^^") dupes.append(item["id"]) item_ids.add(item["id"]) item_counter += 1 if item_counter > 60: streamer.stop = True # This triggers a StopIteration if dupes: print("Dupes:") pprint.pprint(dupes) assert False
momantang/cobrass
utils/test.py
<reponame>momantang/cobrass<filename>utils/test.py import os import platform import sys sys.path.append(os.path.expanduser('~') + os.sep + 'PycharmProjects' + os.sep + "cobrass") from schedule import snapshot from utils.mail_util import send_mail_table if __name__ == '__main__': print(' utils testcd') df = snapshot.down_market_snapshot(True) send_mail_table(df) # print(df[:3].to_html())
phase/TridentSDK
src/main/java/net/tridentsdk/Handler.java
<reponame>phase/TridentSDK<filename>src/main/java/net/tridentsdk/Handler.java /* * Trident - A Multithreaded Server Alternative * Copyright 2014 The TridentSDK Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tridentsdk; import net.tridentsdk.event.EventHandler; import net.tridentsdk.plugin.TridentPluginHandler; import net.tridentsdk.plugin.channel.ChannelHandler; import net.tridentsdk.plugin.cmd.CommandHandler; import net.tridentsdk.service.ChatHandler; import net.tridentsdk.service.TransactionHandler; import net.tridentsdk.window.WindowHandler; /** * Contains the singleton instances for all the Trident handlers * * @author The TridentSDK Team */ public final class Handler { private static final AccessBridge BRIDGE = AccessBridge.open(); private static final EventHandler EVENT_HANDLER = EventHandler.create(); private static final TridentPluginHandler PLUGIN_HANDLER = new TridentPluginHandler(); private static final CommandHandler COMMAND_HANDLER = new CommandHandler(); private static final ChatHandler CHAT_HANDLER = new ChatHandler(); private static final TransactionHandler TRANSACTION_HANDLER = new TransactionHandler(); private Handler() { } public static EventHandler forEvents() { return EVENT_HANDLER; } public static TridentPluginHandler forPlugins() { return PLUGIN_HANDLER; } public static CommandHandler forCommands() { return COMMAND_HANDLER; } public static ChatHandler forChat() { return CHAT_HANDLER; } public static TransactionHandler forTransactions() { return TRANSACTION_HANDLER; } /** * Obtains the static instance of the channel handler * * @return the channel handler instance */ public static ChannelHandler forChannels() { return BRIDGE.demand(ChannelHandler.class); } public static WindowHandler forWindows() { return BRIDGE.demand(WindowHandler.class); } }
BullyWiiPlaza/Universal-Pointer-Searcher
src/main/java/com/wiiudev/gecko/pointer/swing/preprocessed_search/MemoryDumpDialog.java
<filename>src/main/java/com/wiiudev/gecko/pointer/swing/preprocessed_search/MemoryDumpDialog.java package com.wiiudev.gecko.pointer.swing.preprocessed_search; import com.wiiudev.gecko.pointer.preprocessed_search.data_structures.MemoryDump; import com.wiiudev.gecko.pointer.swing.utilities.JTextAreaLimit; import com.wiiudev.gecko.pointer.swing.utilities.MemoryDumpsByteOrder; import lombok.Getter; import lombok.val; import lombok.var; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.*; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.URI; import java.nio.ByteOrder; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import static com.wiiudev.gecko.pointer.swing.StackTraceUtilities.handleException; import static com.wiiudev.gecko.pointer.swing.utilities.FrameUtilities.getSelectedItem; import static com.wiiudev.gecko.pointer.swing.utilities.FrameUtilities.setWindowIconImage; import static com.wiiudev.gecko.pointer.swing.utilities.MemoryDumpsByteOrder.getMemoryDumpsByteOrder; import static com.wiiudev.gecko.pointer.swing.utilities.ProgramDirectoryUtilities.getProgramDirectory; import static com.wiiudev.gecko.pointer.utilities.FileNameUtilities.getBaseFileName; import static com.wiiudev.gecko.pointer.utilities.FileNameUtilities.getTargetAddressFromFile; import static java.awt.Color.GREEN; import static java.awt.Color.RED; import static java.awt.Desktop.getDesktop; import static java.io.File.separator; import static java.lang.Long.parseUnsignedLong; import static java.lang.Long.toHexString; import static java.nio.file.Files.isDirectory; import static java.nio.file.Files.isRegularFile; import static javax.swing.JOptionPane.*; import static javax.swing.SwingUtilities.invokeLater; public class MemoryDumpDialog extends JDialog { private static final Color INVALID_INPUT_COLOR = RED; private static final Color VALID_INPUT_COLOR = GREEN; private static final String DUMMY_LABEL_TEXT = "dummy"; private static final String STARTING_ADDRESS_CHECK_OK = "Starting address check: OK!"; private static final String STARTING_ADDRESS_INVALID_INTEGER = "Failed parsing starting address"; private static final String INVALID_FOLDER_MEMORY_DUMPS_STARTING_ADDRESS = "Invalid starting address for at least one of the memory dumps/pointer maps"; private static final String FILE_PATH_CHECK_OK = "File path check: OK!"; private static final String INVALID_FILE_PATH = "Invalid file path"; private JPanel contentPane; private JTextField filePathField; private JButton browseButtonField; private JComboBox<MemoryDumpsByteOrder> byteOrderSelection; private JFormattedTextField startingAddressField; private JFormattedTextField targetAddressField; private JButton confirmMemoryDumpButton; private JButton byteOrderInformationButton; private JCheckBox parseEntireFolderCheckBox; private JLabel folderImporterLabel; private JComboBox<FileTypeImport> fileTypeSelection; private JLabel startingAddressFieldLabel; private JLabel targetAddressFieldLabel; private JLabel filePathValidatorLabel; private JCheckBox addModuleDumpsFolderCheckBox; private JComboBox<InputType> inputTypeSelection; private final List<JLabel> statusLabels; @Getter private boolean memoryDumpAdded; @Getter private MemoryDump memoryDump; @Getter private List<MemoryDump> memoryDumps; @Getter private List<MemoryDump> pointerMaps; private final boolean mayParseFolder; public MemoryDumpDialog(MemoryDump memoryDump, boolean mayParseFolder) { this.memoryDump = memoryDump; this.mayParseFolder = mayParseFolder; if (memoryDump != null) { val isAddedAsFolder = memoryDump.isAddedAsFolder(); addModuleDumpsFolderCheckBox.setSelected(isAddedAsFolder); } statusLabels = new ArrayList<>(); statusLabels.add(folderImporterLabel); statusLabels.add(filePathValidatorLabel); statusLabels.add(startingAddressFieldLabel); statusLabels.add(targetAddressFieldLabel); configureFrameProperties(); populateByteOrders(); addFilePathFieldDocumentListener(); addBrowseMemoryDumpButtonListener(); addAddMemoryDumpButtonListener(); addByteOrderInformationButtonListener(); runComponentAvailabilitySetter(); addTextFieldInputRestrictions(); considerPopulatingFields(); fileTypeSelection.setModel(new DefaultComboBoxModel<>(FileTypeImport.values())); inputTypeSelection.setModel(new DefaultComboBoxModel<>(InputType.values())); } private void addTextFieldInputRestrictions() { startingAddressField.setDocument(new JTextAreaLimit()); targetAddressField.setDocument(new JTextAreaLimit()); } public boolean isAddModuleDumpsFolderSelected() { return addModuleDumpsFolderCheckBox.isSelected(); } public boolean shouldParseEntireFolder() { return parseEntireFolderCheckBox.isSelected(); } private void considerPopulatingFields() { if (memoryDump != null) { filePathField.setText(memoryDump.getFilePath().toString()); val startingAddress = memoryDump.getStartingAddress(); startingAddressField.setText(startingAddress == null ? "" : toHexString(startingAddress).toUpperCase()); val targetAddress = memoryDump.getTargetAddress(); targetAddressField.setText(targetAddress == null ? "" : toHexString(targetAddress).toUpperCase()); val byteOrder = memoryDump.getByteOrder(); val memoryDumpsByteOrder = getMemoryDumpsByteOrder(byteOrder); byteOrderSelection.setSelectedItem(memoryDumpsByteOrder); } } private void addByteOrderInformationButtonListener() { byteOrderInformationButton.addActionListener(actionEvent -> { val selectedAnswer = showConfirmDialog( rootPane, "The order of bytes in memory can differ between systems.\n" + "The Wii and Wii U for example use big endian while the 3DS uses little endian.\n" + "Do you want to read more about byte orders?", "Read more?", YES_NO_OPTION); if (selectedAnswer == YES_OPTION) { try { val desktop = getDesktop(); desktop.browse(new URI("https://en.wikipedia.org/wiki/Endianness")); } catch (Exception exception) { handleException(rootPane, exception); } } }); } private void addFilePathFieldDocumentListener() { val document = filePathField.getDocument(); document.addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent documentEvent) { tryPopulatingFields(); } @Override public void removeUpdate(DocumentEvent documentEvent) { tryPopulatingFields(); } @Override public void changedUpdate(DocumentEvent documentEvent) { tryPopulatingFields(); } }); } private void tryPopulatingFields() { tryPopulatingTargetAddress(); tryPopulatingStartingAddress(); } private void tryPopulatingTargetAddress() { val filePath = getFilePath(); if (new File(filePath).isDirectory()) { return; } try { val targetAddress = getTargetAddressFromFile(filePath); targetAddressField.setText(toHexString(targetAddress).toUpperCase()); } catch (NumberFormatException ignored) { } } private void tryPopulatingStartingAddress() { val filePath = getFilePath(); // Beginning of Wii U memory dump try { val randomAccessFile = new RandomAccessFile(filePath, "r"); val firstValue = randomAccessFile.readInt(); if (firstValue == 0x3E8) { startingAddressField.setText("10000000"); } } catch (Exception ignored) { } } private void populateByteOrders() { byteOrderSelection.setModel(new DefaultComboBoxModel<>(MemoryDumpsByteOrder.values())); } private void addBrowseMemoryDumpButtonListener() { browseButtonField.addActionListener(actionEvent -> { val shouldParseFolder = parseEntireFolderCheckBox.isSelected() || addModuleDumpsFolderCheckBox.isSelected(); val fileType = getSelectedItem(fileTypeSelection); val memoryDumpChooser = new MemoryDumpChooser(filePathField, shouldParseFolder, fileType); val approved = memoryDumpChooser.select(this); val background = startingAddressField.getBackground(); if (approved && background.equals(INVALID_INPUT_COLOR)) { startingAddressField.requestFocusInWindow(); } }); } private void runComponentAvailabilitySetter() { val thread = new Thread(() -> { // Wait till the dialog is visible while (!isShowing()) { try { Thread.sleep(10); } catch (InterruptedException exception) { exception.printStackTrace(); } } // Keep setting the availability and background colors while (isShowing()) { // Verify the file path val filePath = getFilePath(); var isFilePathValid = false; val shouldParseEntireFolder = parseEntireFolderCheckBox.isSelected(); String filePathValidatorText; try { val path = Paths.get(filePath); val shouldParseFolder = shouldParseEntireFolder || addModuleDumpsFolderCheckBox.isSelected(); isFilePathValid = shouldParseFolder ? isDirectory(path) : isRegularFile(path); filePathValidatorText = "The file path is not a " + (shouldParseFolder ? "directory" : "file"); } catch (InvalidPathException ignored) { filePathValidatorText = INVALID_FILE_PATH; } val isImportableFilesOkay = new boolean[]{true}; val finalIsFilePathValid = isFilePathValid; val finalFilePathValidatorText = filePathValidatorText; invokeLater(() -> { val isParsingEntireFolderAllowed = mayParseFolder && !addModuleDumpsFolderCheckBox.isSelected(); parseEntireFolderCheckBox.setEnabled(isParsingEntireFolderAllowed); addModuleDumpsFolderCheckBox.setEnabled(mayParseFolder && !parseEntireFolderCheckBox.isSelected()); filePathField.setBackground(finalIsFilePathValid ? VALID_INPUT_COLOR : INVALID_INPUT_COLOR); setValidationLabel(finalIsFilePathValid, FILE_PATH_CHECK_OK, finalFilePathValidatorText, filePathValidatorLabel); targetAddressField.setEnabled(!shouldParseEntireFolder || addModuleDumpsFolderCheckBox.isSelected()); fileTypeSelection.setEnabled(!shouldParseEntireFolder && !addModuleDumpsFolderCheckBox.isSelected()); val detectedFileTypeImport = FileTypeImport.parseFileTypeImport(filePath); if (detectedFileTypeImport != null) { fileTypeSelection.setSelectedItem(detectedFileTypeImport); fileTypeSelection.setEnabled(false); } if (shouldParseEntireFolder && finalIsFilePathValid) { val memoryDumps = new ArrayList<File>(); val pointerMaps = new ArrayList<File>(); findFiles(memoryDumps, pointerMaps); val folderImporterLabelText = getFolderImporterLabelText(memoryDumps, pointerMaps); folderImporterLabel.setText(folderImporterLabelText); int importableFilesCount = memoryDumps.size() + pointerMaps.size(); isImportableFilesOkay[0] = importableFilesCount > 0; } else if (addModuleDumpsFolderCheckBox.isSelected()) { val moduleDumps = new ArrayList<File>(); val pointerMaps = new ArrayList<File>(); findFiles(moduleDumps, pointerMaps); val moduleDumpsLabelText = getModulesMemoryDumpLabelText(moduleDumps); folderImporterLabel.setText(moduleDumpsLabelText); } else { folderImporterLabel.setText(""); } }); // Verify the starting address var startingAddress = -1L; boolean isStartingAddressFieldValid = true; String parsingExceptionMessage = null; val selectedFileType = getSelectedItem(fileTypeSelection); if (!selectedFileType.equals(FileTypeImport.POINTER_MAP)) { try { startingAddress = parseUnsignedLong(startingAddressField.getText(), 16); } catch (NumberFormatException exception) { parsingExceptionMessage = exception.getMessage(); isStartingAddressFieldValid = false; } } var areAllMemoryDumpsOkay = false; if (shouldParseEntireFolder && finalIsFilePathValid) { val memoryDumps = new ArrayList<File>(); val pointerMaps = new ArrayList<File>(); findFiles(memoryDumps, pointerMaps); try { areAllMemoryDumpsOkay = areAllMemoryDumpsOkay(startingAddress, memoryDumps); /* if (areAllMemoryDumpsOkay) { areAllMemoryDumpsOkay = areAllMemoryDumpsOkay(startingAddress, pointerMaps); } */ } catch (IOException exception) { exception.printStackTrace(); } val finalAreAllMemoryDumpsOkay = areAllMemoryDumpsOkay; invokeLater(() -> confirmMemoryDumpButton.setEnabled(finalAreAllMemoryDumpsOkay)); } val finalIsStartingAddressFieldValid = isStartingAddressFieldValid; val finalParsingExceptionMessage = parsingExceptionMessage; invokeLater(() -> { val background = finalIsStartingAddressFieldValid ? VALID_INPUT_COLOR : INVALID_INPUT_COLOR; setValidationLabel(finalIsStartingAddressFieldValid, STARTING_ADDRESS_CHECK_OK, STARTING_ADDRESS_INVALID_INTEGER + ": " + finalParsingExceptionMessage, startingAddressFieldLabel); startingAddressField.setBackground(background); val isPointerMapSelected = isPointerMapSelected(); byteOrderSelection.setEnabled(!isPointerMapSelected); }); if (targetAddressField.isEnabled()) { // Verify the target address val isTargetAddressFieldValid = isTargetAddressFieldValid(filePath, startingAddress, isStartingAddressFieldValid); val isAddingMemoryDumpAllowed = isFilePathValid && isStartingAddressFieldValid && isTargetAddressFieldValid; invokeLater(() -> confirmMemoryDumpButton.setEnabled(isAddingMemoryDumpAllowed)); } else { val finalAreAllMemoryDumpsOkay = areAllMemoryDumpsOkay; invokeLater(() -> { setValidationLabel(finalAreAllMemoryDumpsOkay, "", "", targetAddressFieldLabel); setValidationLabel(finalAreAllMemoryDumpsOkay, STARTING_ADDRESS_CHECK_OK, INVALID_FOLDER_MEMORY_DUMPS_STARTING_ADDRESS, startingAddressFieldLabel); targetAddressField.setText(""); targetAddressField.setBackground(VALID_INPUT_COLOR); startingAddressField.setBackground(finalAreAllMemoryDumpsOkay ? VALID_INPUT_COLOR : INVALID_INPUT_COLOR); confirmMemoryDumpButton.setEnabled(finalAreAllMemoryDumpsOkay && isImportableFilesOkay[0]); }); } invokeLater(() -> startingAddressField.setEnabled(!selectedFileType.equals(FileTypeImport.POINTER_MAP))); try { //noinspection BusyWait Thread.sleep(50); } catch (InterruptedException exception) { exception.printStackTrace(); } } }); thread.start(); } private String getModulesMemoryDumpLabelText(List<File> memoryDumps) { val memoryDumpsSize = memoryDumps.size(); return memoryDumpsSize + " module dump(s) found"; } private boolean areAllMemoryDumpsOkay(long startingAddress, List<File> memoryDumps) throws IOException { for (val memoryDump : memoryDumps) { val absolutePath = memoryDump.getAbsolutePath(); val targetAddress = getTargetAddressFromFile(absolutePath); val offset = targetAddress - startingAddress; val fileSize = getFileSize(absolutePath); val isAddingMemoryDumpAllowed = targetAddress >= startingAddress && offset <= fileSize; if (!isAddingMemoryDumpAllowed) { return false; } } return true; } private void setValidationLabel(boolean validationPassed, String validationPassedText, String validationFailedText, JLabel validationLabel) { if (validationPassed) { validationLabel.setForeground(VALID_INPUT_COLOR); validationLabel.setText(validationPassedText); } else { validationLabel.setForeground(INVALID_INPUT_COLOR); validationLabel.setText(validationFailedText); } } private boolean isPointerMapSelected() { val selectedItem = getSelectedItem(fileTypeSelection); return FileTypeImport.POINTER_MAP.equals(selectedItem); } private boolean isMemoryDumpSelected() { val selectedItem = getSelectedItem(fileTypeSelection); return FileTypeImport.MEMORY_DUMP.equals(selectedItem); } private String getFolderImporterLabelText(ArrayList<File> memoryDumps, ArrayList<File> pointerMaps) { val memoryDumpsSize = memoryDumps.size(); val pointerMapsSize = pointerMaps.size(); return memoryDumpsSize + " memory dump(s) and " + pointerMapsSize + " pointer map(s) found"; } private void findFiles(ArrayList<File> memoryDumps, ArrayList<File> pointerMaps) { val directoryFilePath = getFilePath(); val directory = new File(directoryFilePath); val listedFiles = directory.listFiles(); if (listedFiles != null) { for (val listedFile : listedFiles) { val listedFilePath = listedFile.toString(); if (listedFilePath.endsWith("." + FileTypeImport.MEMORY_DUMP.getExtension()) || listedFilePath.endsWith("." + FileTypeImport.MEMORY_DUMP_EXTENSION)) { memoryDumps.add(listedFile); } else if (listedFilePath.endsWith("." + FileTypeImport.POINTER_MAP.getExtension())) { pointerMaps.add(listedFile); } } } } private String getFilePath() { val filePath = filePathField.getText(); return toRelativeFilePath(filePath); } static String toRelativeFilePath(String filePath) { val programDirectory = getProgramDirectory(); val programDirectoryPrefix = programDirectory + separator; if (filePath.startsWith(programDirectoryPrefix)) { return filePath.replace(programDirectoryPrefix, ""); } return filePath; } private boolean isTargetAddressFieldValid(String filePath, long startingAddress, boolean isStartingAddressFieldValid) { invokeLater(() -> { if (addModuleDumpsFolderCheckBox.isSelected()) { val fileTypeImport = getSelectedItem(fileTypeSelection); if (!fileTypeImport.equals(FileTypeImport.MEMORY_DUMP)) { fileTypeSelection.setSelectedItem(FileTypeImport.MEMORY_DUMP); } if (parseEntireFolderCheckBox.isSelected()) { parseEntireFolderCheckBox.setSelected(false); } startingAddressField.setText("0"); if (startingAddressField.isEnabled()) { startingAddressField.setEnabled(false); } } else { startingAddressField.setEnabled(true); } }); var targetAddress = -1L; var isTargetAddressFieldValid = true; var targetAddressValidationFailedText = ""; try { val targetAddressFieldText = targetAddressField.getText(); targetAddress = parseUnsignedLong(targetAddressFieldText, 16); } catch (NumberFormatException exception) { targetAddressValidationFailedText = "Failed parsing target address: " + exception.getMessage(); isTargetAddressFieldValid = false; } if (isTargetAddressFieldValid) { if (isStartingAddressFieldValid) { val targetOffset = targetAddress - startingAddress; if (isMemoryDumpSelected()) { /* try { val memoryDumpFileSize = getFileSize(filePath); if (memoryDumpFileSize == -1) { isTargetAddressFieldValid = true; } else { isTargetAddressFieldValid = targetOffset >= 0 && targetOffset <= memoryDumpFileSize; } targetAddressValidationFailedText = "Target address outside of memory dump bounds"; } catch (IOException | InvalidPathException exception) { isTargetAddressFieldValid = false; targetAddressValidationFailedText = "Failed validating target address inclusiveness"; } */ } else if (targetOffset < 0) { isTargetAddressFieldValid = false; targetAddressValidationFailedText = "The target address cannot be before the starting address"; } } } if (parseEntireFolderCheckBox.isSelected() && !addModuleDumpsFolderCheckBox.isSelected()) { isTargetAddressFieldValid = true; } val finalIsTargetAddressFieldValid = isTargetAddressFieldValid; val finalTargetAddressValidationFailedText = targetAddressValidationFailedText; invokeLater(() -> { val background = finalIsTargetAddressFieldValid ? VALID_INPUT_COLOR : INVALID_INPUT_COLOR; targetAddressField.setBackground(background); if (targetAddressField.isEnabled()) { setValidationLabel(finalIsTargetAddressFieldValid, "Target address check: OK!", finalTargetAddressValidationFailedText, targetAddressFieldLabel); } else { targetAddressFieldLabel.setText(""); } }); return isTargetAddressFieldValid; } private long getFileSize(String filePath) throws IOException { var memoryDumpFileSize = -1L; val filePathObject = Paths.get(filePath); if (isRegularFile(filePathObject)) { memoryDumpFileSize = Files.size(Paths.get(filePath)); } return memoryDumpFileSize; } private void configureFrameProperties() { setContentPane(contentPane); setModal(true); setWindowIconImage(this); packDialog(); } private void packDialog() { for (val statusLabel : statusLabels) { statusLabel.setText(DUMMY_LABEL_TEXT); } pack(); for (val statusLabel : statusLabels) { statusLabel.setText(""); } } private void addAddMemoryDumpButtonListener() { confirmMemoryDumpButton.addActionListener(actionEvent -> { dispose(); val filePath = getFilePath(); val fileType = getSelectedItem(fileTypeSelection); val startingAddress = fileType.equals(FileTypeImport.POINTER_MAP) ? null : parseUnsignedLong(startingAddressField.getText(), 16); val selectedByteOrder = getSelectedItem(byteOrderSelection); val byteOrder = selectedByteOrder == null ? null : selectedByteOrder.getByteOrder(); val targetAddressFieldText = targetAddressField.getText(); val targetAddress = targetAddressFieldText.equals("") ? null : (Long) parseUnsignedLong(targetAddressFieldText, 16); memoryDump = new MemoryDump(filePath, startingAddress, targetAddress, byteOrder); memoryDump.setInputType(getSelectedItem(inputTypeSelection)); memoryDump.setAddedAsFolder(addModuleDumpsFolderCheckBox.isSelected()); val parseEntireFolderCheckBoxSelected = parseEntireFolderCheckBox.isSelected(); if (parseEntireFolderCheckBoxSelected && !addModuleDumpsFolderCheckBox.isSelected()) { parseFolder(startingAddress, byteOrder); } else { memoryDumpAdded = true; memoryDump.setFileType(fileType); } }); } private void parseFolder(long startingAddress, ByteOrder byteOrder) { val memoryDumpPaths = new ArrayList<File>(); val pointerMapPaths = new ArrayList<File>(); findFiles(memoryDumpPaths, pointerMapPaths); memoryDumpAdded = true; memoryDumps = new ArrayList<>(); for (val memoryDumpPath : memoryDumpPaths) { val absolutePath = memoryDumpPath.getAbsolutePath(); try { val targetAddressFromFile = getTargetAddressFromFile(absolutePath); val memoryDump = new MemoryDump(absolutePath, startingAddress, targetAddressFromFile, byteOrder); memoryDumps.add(memoryDump); } catch (Exception exception) { handleException(rootPane, exception); } } pointerMaps = new ArrayList<>(); for (val pointerMapPath : pointerMapPaths) { val pointerMapAbsolutePath = pointerMapPath.getAbsolutePath(); val pointerMapBaseFileName = getBaseFileName(pointerMapAbsolutePath); for (val memoryDump : memoryDumps) { val memoryDumpFilePath = memoryDump.getFilePath().toString(); val memoryDumpBaseFileName = getBaseFileName(memoryDumpFilePath); if (pointerMapBaseFileName.equals(memoryDumpBaseFileName)) { val targetAddress = getTargetAddressFromFile(memoryDumpFilePath); val pointerMapMemoryDump = new MemoryDump(pointerMapAbsolutePath, startingAddress, targetAddress, null); pointerMapMemoryDump.setFileType(FileTypeImport.POINTER_MAP); pointerMaps.add(pointerMapMemoryDump); } } } } public void setFilePath(Path filePath) { if (filePath != null) { filePathField.setText(filePath.toString()); } } public void setLastAddedStartingAddress(Long startingAddress) { if (startingAddress != null) { startingAddressField.setText(toHexString(startingAddress).toUpperCase()); } } public boolean isParseEntireFolderSelected() { return parseEntireFolderCheckBox.isSelected(); } public void setParseEntireFolder(boolean selected) { parseEntireFolderCheckBox.setSelected(selected); } public void setByteOrder(ByteOrder byteOrder) { if (byteOrder != null) { val memoryDumpsByteOrder = getMemoryDumpsByteOrder(byteOrder); byteOrderSelection.setSelectedItem(memoryDumpsByteOrder); } } public void setLastAddedTargetAddress(Long targetAddress) { if (targetAddress != null) { targetAddressField.setText(toHexString(targetAddress).toUpperCase()); } } public void setAddModuleDumpsFolder(boolean addModuleDumpsFolder) { addModuleDumpsFolderCheckBox.setSelected(addModuleDumpsFolder); } }
dmgerman/gerrit
java/com/google/gerrit/server/query/change/AssigneePredicate.java
<reponame>dmgerman/gerrit begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|// Copyright (C) 2016 The Android Open Source Project end_comment begin_comment comment|// end_comment begin_comment comment|// Licensed under the Apache License, Version 2.0 (the "License"); end_comment begin_comment comment|// you may not use this file except in compliance with the License. end_comment begin_comment comment|// You may obtain a copy of the License at end_comment begin_comment comment|// end_comment begin_comment comment|// http://www.apache.org/licenses/LICENSE-2.0 end_comment begin_comment comment|// end_comment begin_comment comment|// Unless required by applicable law or agreed to in writing, software end_comment begin_comment comment|// distributed under the License is distributed on an "AS IS" BASIS, end_comment begin_comment comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. end_comment begin_comment comment|// See the License for the specific language governing permissions and end_comment begin_comment comment|// limitations under the License. end_comment begin_package DECL|package|com.google.gerrit.server.query.change package|package name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|query operator|. name|change package|; end_package begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|entities operator|. name|Account import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|index operator|. name|change operator|. name|ChangeField import|; end_import begin_class DECL|class|AssigneePredicate specifier|public class|class name|AssigneePredicate extends|extends name|ChangeIndexPredicate block|{ DECL|field|id specifier|protected specifier|final name|Account operator|. name|Id name|id decl_stmt|; DECL|method|AssigneePredicate (Account.Id id) specifier|public name|AssigneePredicate parameter_list|( name|Account operator|. name|Id name|id parameter_list|) block|{ name|super argument_list|( name|ChangeField operator|. name|ASSIGNEE argument_list|, name|id operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|this operator|. name|id operator|= name|id expr_stmt|; block|} annotation|@ name|Override DECL|method|match (ChangeData object) specifier|public name|boolean name|match parameter_list|( name|ChangeData name|object parameter_list|) block|{ if|if condition|( name|id operator|. name|get argument_list|() operator|== name|ChangeField operator|. name|NO_ASSIGNEE condition|) block|{ name|Account operator|. name|Id name|assignee init|= name|object operator|. name|change argument_list|() operator|. name|getAssignee argument_list|() decl_stmt|; return|return name|assignee operator|== literal|null return|; block|} return|return name|id operator|. name|equals argument_list|( name|object operator|. name|change argument_list|() operator|. name|getAssignee argument_list|() argument_list|) return|; block|} annotation|@ name|Override DECL|method|getCost () specifier|public name|int name|getCost parameter_list|() block|{ return|return literal|1 return|; block|} block|} end_class end_unit
emccrckn/go-client
splitio/tasks/eventssync.go
package tasks import ( "errors" "github.com/splitio/go-client/splitio/service" "github.com/splitio/go-client/splitio/storage" "github.com/splitio/go-toolkit/asynctask" "github.com/splitio/go-toolkit/logging" ) func submitEvents( eventStorage storage.EventStorageConsumer, eventRecorder service.EventsRecorder, bulkSize int64, logger logging.LoggerInterface, ) error { queuedEvents, err := eventStorage.PopN(bulkSize) if err != nil { logger.Error("Error reading events queue", err) return errors.New("Error reading events queue") } if len(queuedEvents) == 0 { logger.Debug("No events fetched from queue. Nothing to send") return nil } return eventRecorder.Record(queuedEvents) } func onStopAction( eventStorage storage.EventStorageConsumer, eventRecorder service.EventsRecorder, bulkSize int64, logger logging.LoggerInterface, ) { for !eventStorage.Empty() { submitEvents( eventStorage, eventRecorder, bulkSize, logger, ) } } // NewRecordEventsTask creates a new events recording task func NewRecordEventsTask( eventStorage storage.EventStorageConsumer, eventRecorder service.EventsRecorder, bulkSize int64, period int, logger logging.LoggerInterface, ) *asynctask.AsyncTask { record := func(logger logging.LoggerInterface) error { return submitEvents(eventStorage, eventRecorder, bulkSize, logger) } onStop := func(logger logging.LoggerInterface) { // All this function does is flush events which will clear the storage //record(logger) onStopAction(eventStorage, eventRecorder, bulkSize, logger) } return asynctask.NewAsyncTask("SubmitEvents", record, period, nil, onStop, logger) }
m-moshtagh/Oakjutsu
src/main/java/com/dogigiri/core/concurrency/executiveframework/transformingcompletablefuture/Main.java
<gh_stars>0 package com.dogigiri.core.concurrency.executiveframework.transformingcompletablefuture; import java.util.concurrent.CompletableFuture; public class Main { public static int toFahrenheit(int Celsius) { return (int) (Celsius * 1.8) + 32; } public static void main(String[] args) { var future = CompletableFuture.supplyAsync(() -> 24); future.thenApply(Main::toFahrenheit).thenAccept(System.out::println); } }
ParaSatellite/JPPF
common/src/java/org/jppf/comm/socket/SocketInitializerImpl.java
<gh_stars>1-10 /* * JPPF. * Copyright (C) 2005-2019 JPPF Team. * http://www.jppf.org * * 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.jppf.comm.socket; import org.jppf.utils.*; import org.jppf.utils.concurrent.ThreadSynchronization; import org.jppf.utils.configuration.JPPFProperties; import org.slf4j.*; /** * Instances of this class attempt to connect a {@link org.jppf.comm.socket.SocketWrapper SocketWrapper} to a remote server. * The connection attempts are performed until a configurable amount of time has passed, and at a configurable time interval. * When no attempt succeeded, a <code>JPPFError</code> is thrown, and the application should normally exit. * @author <NAME> */ class SocketInitializerImpl extends ThreadSynchronization implements SocketInitializer { /** * Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(SocketInitializerImpl.class); /** * Determines whether the debug level is enabled in the logging configuration, without the cost of a method call. */ private static final boolean debugEnabled = log.isDebugEnabled(); /** * Determines whether the trace level is enabled in the logging configuration, without the cost of a method call. */ private static final boolean traceEnabled = log.isTraceEnabled(); /** * The configuration to use. */ private final TypedProperties config; /** * The last captured exception. */ Exception lastException; /** * Determine whether this socket initializer has been intentionally closed. */ boolean closed; /** * Name given to this initializer. */ private String name; /** * Instantiate this SocketInitializer with the global JPPF configuration. */ SocketInitializerImpl() { this.config = JPPFConfiguration.getProperties(); } /** * Instantiate this SocketInitializer with a specified configuration. * @param config the configuration to use. */ public SocketInitializerImpl(final TypedProperties config) { this.config = config; } @Override public boolean isClosed() { synchronized(this) { return closed; } } @Override public boolean initialize(final SocketWrapper socketWrapper) { boolean successful = false; if (isClosed()) return false; name = getClass().getSimpleName() + '[' + socketWrapper.getHost() + ':' + socketWrapper.getPort() + ']'; if (debugEnabled) log.debug("initializing connection {}", name); if (socketWrapper.isOpened()) { try { if (debugEnabled) log.debug("{} about to close socket wrapper", name); socketWrapper.close(); } catch(@SuppressWarnings("unused") final Exception e) { } } final long delay = 1000L * config.get(JPPFProperties.RECONNECT_INITIAL_DELAY); final long maxTime = config.get(JPPFProperties.RECONNECT_MAX_TIME); final long maxDuration = (maxTime <= 0) ? Long.MAX_VALUE : 1000L * maxTime; long period = 1000L * config.get(JPPFProperties.RECONNECT_INTERVAL); if (period <= 0L) period = 1000L; if (delay > 0L) goToSleep(delay); final long start = System.nanoTime(); while (((System.nanoTime() - start) / 1_000_000L < maxDuration) && !successful && !isClosed()) { try { if (traceEnabled) log.trace("{} opening the socket connection", name); socketWrapper.open(); successful = true; if (traceEnabled) log.trace("{} socket connection successfully opened", name); } catch(final Exception e) { if (traceEnabled) log.trace("{} socket connection open failed: {}", name, ExceptionUtils.getMessage(e)); lastException = e; if (!isClosed()) goToSleep(period); } } return successful; } @Override public void close() { synchronized(this) { if (!closed) { if (debugEnabled) log.debug("{} closing socket initializer", name); closed = true; wakeUp(); } } } @Override public Exception getLastException() { return lastException; } }
ShmuelFine/COOP
COOP_C_TestProxy/MemManagementUnitTest.h
<gh_stars>10-100 #include "ProxyExportDefs.h" #include "COOP.h" #ifdef __cplusplus extern "C" { #endif COOP_API FUN_DECL(New_WhenAllocatingBuffer_ThenReturnsRightAmountOfMemroy); COOP_API FUN_DECL(New_WhenAllocatingClassInstance_ThenReturnsRightAmountOfMemroy); COOP_API FUN_DECL(Delete_WhenDeletingAllocMemory_ThenItFreesTheResource); #ifdef __cplusplus } #endif
hieuhoang/FasterTransformer
src/fastertransformer/models/swin_int8/SwinINT8Weight.h
<filename>src/fastertransformer/models/swin_int8/SwinINT8Weight.h /* * Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ #pragma once #include "src/fastertransformer/kernels/layernorm_kernels.h" #include "src/fastertransformer/layers/FfnINT8Weight.h" #include "src/fastertransformer/layers/attention_layers_int8/AttentionINT8Weight.h" #include <cuda_fp16.h> #include <cudnn.h> #include <vector> using namespace std; namespace fastertransformer { template<typename T> class SwinTransformerINT8BlockWeight { public: AttentionINT8Weight<T> attention_weights; FfnINT8Weight<T> ffn_weights; LayerNormWeight<T> attn_layernorm_weights; LayerNormWeight<T> ffn_layernorm_weights; const T* attention_relative_pos_bias = nullptr; ScaleList scalelist; }; // SwinTransformerINT8BlockWeight template<typename T> class SwinTransformerINT8BasicLayerWeight { public: LayerNormWeight<T> merge_layernorm_weights; DenseWeight<T> merge_linear_weights; const T* attn_mask = nullptr; vector<SwinTransformerINT8BlockWeight<T>> block_weight_list; }; // SwinTransformerINT8BasicLayerWeight template<typename T> class SwinTransformerINT8Weight { public: DenseWeight<T> patchEmbed_linear_weights; LayerNormWeight<T> patchEmbed_norm_weights; LayerNormWeight<T> norm_weights; vector<SwinTransformerINT8BasicLayerWeight<T>> basic_layer_weight_list; }; // class SwinTransformerINT8Weight } // namespace fastertransformer
codingxu97/hibernate-reactive
hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/ReactiveAfterTransactionCompletionProcess.java
<reponame>codingxu97/hibernate-reactive<gh_stars>100-1000 /* Hibernate, Relational Persistence for Idiomatic Java * * SPDX-License-Identifier: Apache-2.0 * Copyright: Red Hat Inc. and Hibernate Authors */ package org.hibernate.reactive.engine; import org.hibernate.reactive.session.ReactiveSession; import java.util.concurrent.CompletionStage; /** * Contract representing some process that needs to occur during after transaction completion. * * @author <NAME> * @author <NAME> */ public interface ReactiveAfterTransactionCompletionProcess { /** * Perform whatever processing is encapsulated here after completion of the transaction. * * @param success Did the transaction complete successfully? True means it did. * @param session The session on which the transaction is completing. */ CompletionStage<Void> doAfterTransactionCompletion(boolean success, ReactiveSession session); }
ttao-talendbj/tbd-studio-se
main/plugins/org.talend.repository.oozie/src/org/talend/repository/oozie/action/EditOoziePropertiesAction.java
<reponame>ttao-talendbj/tbd-studio-se package org.talend.repository.oozie.action; import org.talend.core.model.repository.ERepositoryObjectType; import org.talend.repository.hadoopcluster.action.common.EditHadoopNodePropertiesAction; import org.talend.repository.oozie.node.model.OozieRepositoryNodeType; public class EditOoziePropertiesAction extends EditHadoopNodePropertiesAction { @Override protected ERepositoryObjectType getNodeType() { return OozieRepositoryNodeType.OOZIE; } }
homobel/makebird-node
test/projects/large/a784.js
//~ name a784 alert(a784); //~ component a785.js
zhixin9001/Algorithm
algs4/algs4-master/src/main/java/edu/princeton/cs/algs4/TrieST.java
<reponame>zhixin9001/Algorithm /****************************************************************************** * Compilation: javac TrieST.java * Execution: java TrieST < words.txt * Dependencies: StdIn.java * Data files: https://algs4.cs.princeton.edu/52trie/shellsST.txt * * A string symbol table for extended ASCII strings, implemented * using a 256-way trie. * * % java TrieST < shellsST.txt * by 4 * sea 6 * sells 1 * she 0 * shells 3 * shore 7 * the 5 * javac edu\princeton\cs\algs4\TrieST.java * cmd /c --% java edu.princeton.cs.algs4.TrieST < ..\..\..\..\algs4-data\shellsST.txt * ******************************************************************************/ package edu.princeton.cs.algs4; /** * The {@code TrieST} class represents an symbol table of key-value * pairs, with string keys and generic values. * It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>, * <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods. * It also provides character-based methods for finding the string * in the symbol table that is the <em>longest prefix</em> of a given prefix, * finding all strings in the symbol table that <em>start with</em> a given prefix, * and finding all strings in the symbol table that <em>match</em> a given pattern. * A symbol table implements the <em>associative array</em> abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * <p> * This implementation uses a 256-way trie. * The <em>put</em>, <em>contains</em>, <em>delete</em>, and * <em>longest prefix</em> operations take time proportional to the length * of the key (in the worst case). Construction takes constant time. * The <em>size</em>, and <em>is-empty</em> operations take constant time. * Construction takes constant time. * <p> * For additional documentation, see <a href="https://algs4.cs.princeton.edu/52trie">Section 5.2</a> of * <i>Algorithms, 4th Edition</i> by <NAME> and <NAME>. */ public class TrieST<Value> { private static final int R = 256; // extended ASCII private Node root; // root of trie private int n; // number of keys in trie // R-way trie node private static class Node { private Object val; private Node[] next = new Node[R]; } /** * Initializes an empty string symbol table. */ public TrieST() { } /** * Returns the value associated with the given key. * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(String key) { if (key == null) throw new IllegalArgumentException("argument to get() is null"); Node x = get(root, key, 0); if (x == null) return null; return (Value) x.val; } /** * Does this symbol table contain the given key? * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(String key) { if (key == null) throw new IllegalArgumentException("argument to contains() is null"); return get(key) != null; } private Node get(Node x, String key, int d) { if (x == null) return null; if (d == key.length()) return x; char c = key.charAt(d); return get(x.next[c], key, d+1); } /** * Inserts the key-value pair into the symbol table, overwriting the old value * with the new value if the key is already in the symbol table. * If the value is {@code null}, this effectively deletes the key from the symbol table. * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ public void put(String key, Value val) { if (key == null) throw new IllegalArgumentException("first argument to put() is null"); if (val == null) delete(key); else root = put(root, key, val, 0); } private Node put(Node x, String key, Value val, int d) { if (x == null) x = new Node(); if (d == key.length()) { if (x.val == null) n++; x.val = val; return x; } char c = key.charAt(d); x.next[c] = put(x.next[c], key, val, d+1); return x; } /** * Returns the number of key-value pairs in this symbol table. * @return the number of key-value pairs in this symbol table */ public int size() { return n; } /** * Is this symbol table empty? * @return {@code true} if this symbol table is empty and {@code false} otherwise */ public boolean isEmpty() { return size() == 0; } /** * Returns all keys in the symbol table as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * @return all keys in the symbol table as an {@code Iterable} */ public Iterable<String> keys() { return keysWithPrefix(""); } /** * Returns all of the keys in the set that start with {@code prefix}. * @param prefix the prefix * @return all of the keys in the set that start with {@code prefix}, * as an iterable */ public Iterable<String> keysWithPrefix(String prefix) { Queue<String> results = new Queue<String>(); Node x = get(root, prefix, 0); collect(x, new StringBuilder(prefix), results); return results; } private void collect(Node x, StringBuilder prefix, Queue<String> results) { if (x == null) return; if (x.val != null) results.enqueue(prefix.toString()); for (char c = 0; c < R; c++) { prefix.append(c); collect(x.next[c], prefix, results); prefix.deleteCharAt(prefix.length() - 1); } } /** * Returns all of the keys in the symbol table that match {@code pattern}, * where . symbol is treated as a wildcard character. * @param pattern the pattern * @return all of the keys in the symbol table that match {@code pattern}, * as an iterable, where . is treated as a wildcard character. */ public Iterable<String> keysThatMatch(String pattern) { Queue<String> results = new Queue<String>(); collect(root, new StringBuilder(), pattern, results); return results; } private void collect(Node x, StringBuilder prefix, String pattern, Queue<String> results) { if (x == null) return; int d = prefix.length(); if (d == pattern.length() && x.val != null) results.enqueue(prefix.toString()); if (d == pattern.length()) return; char c = pattern.charAt(d); if (c == '.') { for (char ch = 0; ch < R; ch++) { prefix.append(ch); collect(x.next[ch], prefix, pattern, results); prefix.deleteCharAt(prefix.length() - 1); } } else { prefix.append(c); collect(x.next[c], prefix, pattern, results); prefix.deleteCharAt(prefix.length() - 1); } } /** * Returns the string in the symbol table that is the longest prefix of {@code query}, * or {@code null}, if no such string. * @param query the query string * @return the string in the symbol table that is the longest prefix of {@code query}, * or {@code null} if no such string * @throws IllegalArgumentException if {@code query} is {@code null} */ public String longestPrefixOf(String query) { if (query == null) throw new IllegalArgumentException("argument to longestPrefixOf() is null"); int length = longestPrefixOf(root, query, 0, -1); if (length == -1) return null; else return query.substring(0, length); } // returns the length of the longest string key in the subtrie // rooted at x that is a prefix of the query string, // assuming the first d character match and we have already // found a prefix match of given length (-1 if no such match) private int longestPrefixOf(Node x, String query, int d, int length) { if (x == null) return length; if (x.val != null) length = d; if (d == query.length()) return length; char c = query.charAt(d); return longestPrefixOf(x.next[c], query, d+1, length); } /** * Removes the key from the set if the key is present. * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(String key) { if (key == null) throw new IllegalArgumentException("argument to delete() is null"); root = delete(root, key, 0); } private Node delete(Node x, String key, int d) { if (x == null) return null; if (d == key.length()) { if (x.val != null) n--; x.val = null; } else { char c = key.charAt(d); x.next[c] = delete(x.next[c], key, d+1); } // remove subtrie rooted at x if it is completely empty if (x.val != null) return x; for (int c = 0; c < R; c++) if (x.next[c] != null) return x; return null; } /** * Unit tests the {@code TrieST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { // build symbol table from standard input TrieST<Integer> st = new TrieST<Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } // print results if (st.size() < 100) { StdOut.println("keys(\"\"):"); for (String key : st.keys()) { StdOut.println(key + " " + st.get(key)); } StdOut.println(); } StdOut.println("longestPrefixOf(\"shellsort\"):"); StdOut.println(st.longestPrefixOf("shellsort")); StdOut.println(); StdOut.println("longestPrefixOf(\"quicksort\"):"); StdOut.println(st.longestPrefixOf("quicksort")); StdOut.println(); StdOut.println("keysWithPrefix(\"shor\"):"); for (String s : st.keysWithPrefix("shor")) StdOut.println(s); StdOut.println(); StdOut.println("keysThatMatch(\".he.l.\"):"); for (String s : st.keysThatMatch(".he.l.")) StdOut.println(s); } } /****************************************************************************** * Copyright 2002-2018, <NAME> and <NAME>. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by <NAME> and <NAME>, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4.jar 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 algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
JoaoBaptMG/INF443-Project
src/scene/Terrain.cpp
#include "Terrain.hpp" #include "colors.hpp" #include <thread> #include <random> #include <algorithm> #include "resources/Cache.hpp" #include "util/Frustum.hpp" #include "util/range.hpp" #include "mesh_utils.hpp" #include <glm/gtx/transform.hpp> #ifdef _WIN32 #include <execution> #define POLICY std::execution::par_unseq, #else #define POLICY #endif using namespace scene; // This is so I can easily parallelize if necessary static std::mutex terrainMutex; constexpr std::make_signed_t<std::size_t> MaxCellDivision = 128; constexpr float Pi = 3.14159265359f; Terrain::Terrain(float width, float height, float resolution, int seed) : terrainFunction(width, height, seed), resolution(resolution), time(0) { // Create the programs terrainProgram = cache::loadProgram({ "resources/shaders/position.vert", "resources/shaders/lighting.frag", "resources/shaders/terrain.vert", "resources/shaders/terrain.frag" }); terrainProgram->setName("Terrain Program"); treesProgram = cache::loadProgram({ "resources/shaders/position.vert", "resources/shaders/lighting.frag", "resources/shaders/commonObjects.vert", "resources/shaders/commonObjects.frag" }); treesProgram->setName("Common Objects Program"); auto hw = ssize(0.5f * width / resolution); auto hh = ssize(0.5f * height / resolution); heights.resize(2 * hw + 1, 2 * hh + 1); nys.resize(2 * hw + 1, 2 * hh + 1); xofs = hw, yofs = hh; // Generate meshes spanning at most 128*128 triangles auto divsX = (2 * hw + 1) / MaxCellDivision; auto divsY = (2 * hh + 1) / MaxCellDivision; maxHeight.resize(divsX, divsY); minHeight.resize(divsX, divsY); std::mt19937 engine(seed); // Simple paralellization std::vector<std::thread> threads; for (ssize j = 0; j < divsY; j++) for (ssize i = 0; i < divsX; i++) { if (i == 0 && j == 0) continue; auto x1 = -hw + MaxCellDivision * i; auto y1 = -hh + MaxCellDivision * j; auto x2 = std::min(hw, -hw + MaxCellDivision * (i + 1)); auto y2 = std::min(hh, -hh + MaxCellDivision * (j + 1)); int seed = engine(); threads.push_back(std::thread([=, wi = i == divsX - 1, wj = j == divsY - 1] { buildTerrain(x1, y1, x2, y2, seed, wi, wj); })); } buildTerrain(-hw, -hh, std::min(hw, -hw + MaxCellDivision), std::min(hh, -hh + MaxCellDivision), engine()); for (auto& thread : threads) thread.join(); for (auto& builder : temporaryBuilders) { terrainMeshes.push_back(builder); terrainMeshes.back().setName("Terrain Mesh " + std::to_string(terrainMeshes.size())); } temporaryBuilders.clear(); // Now, generate the mesh and the instances buildTrees(engine()); // Compute the global min and max height globalMinHeight = *std::min_element(minHeight.begin(), minHeight.end()); globalMaxHeight = *std::max_element(maxHeight.begin(), maxHeight.end()); // Generate the dirt texture generateDirtTexture(engine()); } void Terrain::buildTerrain(ssize xmin, ssize ymin, ssize xmax, ssize ymax, int seed, bool wi, bool wj) { // Some guarantees if (xmin > xmax) std::swap(xmin, xmax); if (ymin > ymax) std::swap(ymin, ymax); if (xmin == xmax || ymin == ymax) return; auto width = xmax - xmin + 1; auto height = ymax - ymin + 1; // Threaded compute of our own min height float localMinHeight = std::numeric_limits<float>::infinity(); float localMaxHeight = -std::numeric_limits<float>::infinity(); // In this phase, I'll only have a single mesh gl::MeshBuilder mesh; // First, we're going to build the vertices mesh.positions.resize(width * height); for (auto j = ymin; j <= ymax; j++) for (auto i = xmin; i <= xmax; i++) { auto idx = (j - ymin) * width + (i - xmin); float x = i * resolution; float y = j * resolution; float height = terrainFunction(x, y); // Push the position mesh.positions[idx] = glm::vec3(x, height, -y); localMinHeight = std::min(localMinHeight, height); localMaxHeight = std::max(localMaxHeight, height); // Write to the grid - no data races here, each rectangle only writes its own part if ((wi || i < xmax) && (wj || j < ymax)) heights(xofs + i, yofs + j) = height; } // The normals mesh.normals.resize(width * height); for (auto j = ymin; j <= ymax; j++) for (auto i = xmin; i <= xmax; i++) { auto idx = (j - ymin) * width + (i - xmin); // Do the grad calculation glm::vec3 gx, gy; // Sample outside of the map to have perfectly seamless normals if (i == xmin) { float x = (i - 1) * resolution; float y = j * resolution; float height = terrainFunction(x, y); gx = mesh.positions[idx + 1] - glm::vec3(x, height, -y); } else if (i == xmax) { float x = (i + 1) * resolution; float y = j * resolution; float height = terrainFunction(x, y); gx = glm::vec3(x, height, -y) - mesh.positions[idx - 1]; } else gx = mesh.positions[idx + 1] - mesh.positions[idx - 1]; if (j == ymin) { float x = i * resolution; float y = (j - 1) * resolution; float height = terrainFunction(x, y); gy = mesh.positions[idx + width] - glm::vec3(x, height, -y); } else if (j == ymax) { float x = i * resolution; float y = (j + 1) * resolution; float height = terrainFunction(x, y); gy = glm::vec3(x, height, -y) - mesh.positions[idx - width]; } else gy = mesh.positions[idx + width] - mesh.positions[idx - width]; mesh.normals[idx] = glm::normalize(glm::cross(gx, gy)); // Write to the grid - no data races here, each rectangle only writes its own part if ((wi || i < xmax) && (wj || j < ymax)) nys(xofs + i, yofs + j) = mesh.normals[idx].y; } // Now for the topology mesh.indices.reserve(6 * (width - 1) * (height - 1)); for (ssize j = 1; j < height; j++) for (ssize i = 1; i < width; i++) { // Push the two triangles mesh.indices.push_back((j - 1) * width + (i - 1)); mesh.indices.push_back((j - 1) * width + i); mesh.indices.push_back(j * width + i); mesh.indices.push_back((j - 1) * width + (i - 1)); mesh.indices.push_back(j * width + i); mesh.indices.push_back(j * width + (i - 1)); } // Compute the min and max height per grid ssize ci = (xofs + xmin) / MaxCellDivision, cj = (yofs + ymin) / MaxCellDivision; minHeight(ci, cj) = localMinHeight; maxHeight(ci, cj) = localMaxHeight; { std::lock_guard lock(terrainMutex); temporaryBuilders.emplace_back(std::move(mesh)); // This will form the AABB for frustum culling terrainMin.emplace_back(xmin * resolution, localMinHeight, -ymax * resolution); terrainMax.emplace_back(xmax * resolution, localMaxHeight, -ymin * resolution); } } constexpr float TreeRadius = 3; constexpr float MinTrunkHeight = 6, MaxTrunkHeight = 15; constexpr float MinConeSize = 2, MaxConeSize = 7; void Terrain::buildTrees(int seed) { // Create the tree mesh trunkMesh = mesh_utils::openCylinder(glm::vec3(0, 0, 0), glm::vec3(0, 1, 0), 1, colors::CocoaBrown, 32); coneMesh = mesh_utils::closedCone(glm::vec3(0, 0, 0), glm::vec3(0, 8, 0), 1, colors::DarkGreen, 32); trunkMesh.setName("Trunk Mesh"); coneMesh.setName("Cone Mesh"); // Generate a random number of trees std::mt19937 random(seed); auto width = heights.width(), height = heights.height(); // Try to fill 0.05% of the terrain with trees ssize radius = std::ceil(TreeRadius / resolution); std::size_t numTrees = width * height / 2000; std::vector<glm::tvec2<ssize>> indices; indices.reserve((width - 2 * radius) * (height - 2 * radius)); for (std::size_t j = radius; j < height - radius; j++) for (std::size_t i = radius; i < height - radius; i++) indices.emplace_back(i, j); std::shuffle(indices.begin(), indices.end(), random); std::uniform_real_distribution heightGen(MinTrunkHeight, MaxTrunkHeight); std::uniform_real_distribution sizeGen(MinConeSize, MaxConeSize); treeHeights.resize(width, height, 0); trunkTransforms.reserve(numTrees); coneTransforms.reserve(numTrees); for (const auto& vec : indices) { auto i = vec.x, j = vec.y; float h = std::min({ heights(i, j), heights(i + 1, j), heights(i - 1, j), heights(i, j - 1), heights(i, j + 1) }); // Don't generate trees in water if (h < 0) continue; // Don't place trees in too step areas float ny = std::min({ nys(i, j), nys(i + 1, j), nys(i - 1, j), nys(i, j - 1), nys(i, j + 1) }); if (ny < 0.75) continue; bool skipTree = false; // Don't place trees too close to each other for (ssize ci = -radius; ci <= radius; ci++) { ssize mj = radius - std::abs(ci); for (ssize cj = -mj; cj <= mj; cj++) if (treeHeights(i + ci, j + cj) > 0) { skipTree = true; break; } if (skipTree) break; } if (skipTree) continue; float trunkHeight = heightGen(random); float coneSize = sizeGen(random); treeHeights(i, j) = trunkHeight + 8; auto ci = i / MaxCellDivision, cj = j / MaxCellDivision; minHeight(ci, cj) = std::min(minHeight(ci, cj), h); maxHeight(ci, cj) = std::max(maxHeight(ci, cj), h + trunkHeight + 8); auto trunkPos = glm::vec3((i - xofs) * resolution, h, -(j - yofs) * resolution); treePositions.emplace_back(trunkPos); auto trunkScale = glm::vec3(1, trunkHeight, 1); trunkTransforms.emplace_back(glm::scale(trunkScale)); auto conePos = glm::vec3(0, trunkHeight, 0); auto coneScale = glm::vec3(coneSize, 1, coneSize); coneTransforms.emplace_back(glm::translate(conePos) * glm::scale(coneScale)); if (trunkTransforms.size() == numTrees) break; } // Generate the shearing parameters constexpr float MaxShearingRadius = 0.25; std::uniform_real_distribution radiusGen(0.0f, MaxShearingRadius); shearingEllipse = glm::vec2(radiusGen(random), radiusGen(random)); shearingRotation = std::uniform_real_distribution(0.0f, 2 * Pi)(random); } constexpr GLsizei TextureSize = 64; void Terrain::generateDirtTexture(int seed) { std::mt19937 random(seed); std::uniform_real_distribution floatGen(0.4f, 1.0f); // Create the size texture std::vector<float> image(TextureSize * TextureSize * TextureSize); std::generate(image.begin(), image.end(), [&] { return floatGen(random); }); // Configure the texture dirtTexture.assign(0, gl::InternalFormat::R16, TextureSize, TextureSize, TextureSize, gl::Format::Red, image.data()); dirtTexture.generateMipmap(); dirtTexture.setMagFilter(gl::MagFilter::Linear); dirtTexture.setMinFilter(gl::MinFilter::LinearMipLinear); dirtTexture.setMaxAnisotropy(16); dirtTexture.setWrapEffectS(gl::WrapEffect::Repeat); dirtTexture.setWrapEffectT(gl::WrapEffect::Repeat); dirtTexture.setWrapEffectR(gl::WrapEffect::Repeat); } void Terrain::update(double delta) { time += delta; // Generate the final transform std::vector<glm::mat4> trunkFinalTransforms(treePositions.size()); std::vector<glm::mat4> coneFinalTransforms(treePositions.size()); auto angle = Pi * time / 2; auto shear = glm::vec2(std::cos(angle), std::sin(angle)) * shearingEllipse; auto cr = std::cos(shearingRotation), sr = std::sin(shearingRotation); auto shearing = glm::mat4(1.0); shearing[1][0] = cr * shear.x + sr * shear.y; shearing[1][2] = -sr * shear.x + cr * shear.y; util::range rng(std::size_t(0), treePositions.size()); std::for_each(POLICY rng.begin(), rng.end(), [&](std::size_t i) { // Compute the final transforms trunkFinalTransforms[i] = glm::translate(treePositions[i]) * shearing * trunkTransforms[i]; coneFinalTransforms[i] = glm::translate(treePositions[i]) * shearing * coneTransforms[i]; }); // Set the instances trunkInstances.setInstances(trunkFinalTransforms); coneInstances.setInstances(coneFinalTransforms); } void Terrain::setColors(const glm::u8vec4& grassColor, const glm::u8vec4& sandColor, const glm::u8vec4& mountainColor) { terrainProgram->setUniform("GrassColor", glm::vec3(grassColor) / 255.0f); terrainProgram->setUniform("SandColor", glm::vec3(sandColor) / 255.0f); terrainProgram->setUniform("MountainColor", glm::vec3(mountainColor) / 255.0f); } void Terrain::setClipPlane(const glm::vec4& plane) { terrainProgram->setUniform("ClipPlane", plane); treesProgram->setUniform("ClipPlane", plane); } void Terrain::draw(const glm::mat4& projection, const glm::mat4& view, const Lighting& lighting) { for (auto prog : { terrainProgram.get(), treesProgram.get() }) { lighting.setLightParams(*prog, view); prog->setUniform("Projection", projection); prog->setUniform("View", view); } auto frustum = util::frustumPlanes(projection * view); terrainProgram->use(); dirtTexture.bindTo(0); terrainProgram->setUniform("NoiseTexture", 0); terrainProgram->setUniform("UnitsPerPeriod", 32.0f); // Sort them from back to front std::vector<std::pair<float, gl::Mesh*>> meshesToDraw; meshesToDraw.reserve(terrainMeshes.size()); for (std::size_t i = 0; i < terrainMeshes.size(); i++) { if (frustum.checkIntersectionAABB(terrainMin[i], terrainMax[i])) meshesToDraw.emplace_back(util::planeDistanceAABB(frustum.near, terrainMin[i], terrainMax[i]), &terrainMeshes[i]); } std::sort(meshesToDraw.begin(), meshesToDraw.end()); for (auto& mesh : meshesToDraw) mesh.second->draw(glm::mat4(1.0)); treesProgram->use(); trunkMesh.draw(trunkInstances); coneMesh.draw(coneInstances); } float Terrain::operator()(float x, float z) const { float i = x / resolution, j = -z / resolution; if (i < -xofs || j < -yofs || i > -xofs + heights.width() - 1 || j > -yofs + heights.height() - 1) return -std::numeric_limits<float>::infinity(); // Get the integer (offsetted) and fractional parts ssize ti = std::floor(i), tj = std::floor(j); auto fi = i - ti, fj = j - tj; ti += xofs; tj += yofs; // Special cases for the end edges if (ti == heights.width() - 1 && tj == heights.height() - 1) return heights(ti, tj); else if (ti == heights.width() - 1) return (1 - fj) * heights(ti, tj) + fj * heights(ti, tj + 1); else if (tj == heights.height() - 1) return (1 - fi) * heights(ti, tj) + fi * heights(ti + 1, tj); else { // Follow the mesh topology, so not really a bilinear interpolation if (fi + fj <= 1.0f) return (1 - fi) * heights(ti, tj) + (fi - fj) * heights(ti + 1, tj) + fj * heights(ti + 1, tj + 1); else return (1 - fj) * heights(ti, tj) + (fj - fi) * heights(ti, tj + 1) + fi * heights(ti + 1, tj + 1); } }
yiemwa123/DREU-AISpy
Nodejs_Code/Test Code/visionNode.js
<gh_stars>0 // Imports the Google Cloud client library const vision = require('@google-cloud/vision'); // Creates a client const client = new vision.ImageAnnotatorClient(); // Performs label detection on the image file client .labelDetection('/Users/gabesaldivar/Desktop/vision_test/NodePics/pill.jpg') .then(results => { const labels = results[0].labelAnnotations; console.log('Labels:'); labels.forEach(label => console.log(label.description)); }) .catch(err => { console.error('Error:', err); })
iicc/django-oscar
tests/__init__.py
import sys class temporary_python_path(object): """ Acts as a context manager to temporarily prepend a list of paths to sys.path """ def __init__(self, paths): self.paths = paths def __enter__(self): self.original_paths = sys.path[:] sys.path = self.paths + self.original_paths def __exit__(self, exc_type, exc_value, traceback): sys.path = self.original_paths
Citytechinc/harbor
harbor-core/src/main/java/com/icfolson/aem/harbor/core/components/content/tabs/v1/DefaultTabs.java
package com.icfolson.aem.harbor.core.components.content.tabs.v1; import com.google.common.collect.Lists; import com.icfolson.aem.harbor.api.components.content.tabs.Tab; import com.icfolson.aem.harbor.api.components.content.tabs.Tabs; import com.icfolson.aem.harbor.api.components.mixins.classifiable.Classification; import com.icfolson.aem.harbor.core.components.mixins.classifiable.TagBasedClassification; import org.apache.sling.api.resource.Resource; import org.apache.sling.models.annotations.Model; import org.apache.sling.models.annotations.injectorspecific.Self; import javax.inject.Inject; import java.util.List; @Model(adaptables = Resource.class, adapters = Tabs.class, resourceType = DefaultTabs.RESOURCE_TYPE) public class DefaultTabs implements Tabs { public static final String RESOURCE_TYPE = "harbor/components/content/tabs/v1/tabs"; @Inject @Self private Resource resource; private List<Tab> tabs; public List<Tab> getTabs() { if (tabs == null) { tabs = Lists.newArrayList(); getResource().getChildren().forEach(tabResource -> { Tab currentTab = tabResource.adaptTo(Tab.class); if (currentTab != null) { tabs.add(currentTab); } }); } return tabs; } @Override public Classification getClassification() { return getResource().adaptTo(TagBasedClassification.class); } public Resource getResource() { return resource; } }
ascartabelli/lamb
src/array/uniques.js
import identity from "../core/identity"; import uniquesBy from "./uniquesBy"; /** * Returns an array comprised of the unique elements of the given array-like object.<br/> * Note that this function uses the ["SameValueZero" comparison]{@link module:lamb.areSVZ|areSVZ} * to test the equality of values.<br/> * When two values are considered equal, the first occurence will be the one included * in the result array.<br/> * See also {@link module:lamb.uniquesBy|uniquesBy} if you need to transform your values before * the comparison or if you have to extract them from complex ones. * @example * _.uniques([-0, 1, 2, 0, 2, 3, 4, 3, 5, 1]) // => [-0, 1, 2, 3, 4, 5] * * @memberof module:lamb * @category Array * @function * @see {@link module:lamb.uniquesBy|uniquesBy} * @since 0.1.0 * @param {ArrayLike} arrayLike * @returns {Array} */ var uniques = uniquesBy(identity); export default uniques;
sanderv32/cosmic
cosmic-core/framework/db/src/test/java/com/cloud/utils/DbUtilTest.java
package com.cloud.utils; import com.cloud.utils.db.DbUtil; import com.cloud.utils.db.TransactionLegacy; import javax.persistence.Column; import javax.persistence.Table; import javax.sql.DataSource; import java.io.IOException; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class DbUtilTest { @Mock Connection connection; @Mock PreparedStatement preparedStatement; @Mock Statement statement; @Mock ResultSet resultSet; @Mock DataSource dataSource; DataSource backup; Map<String, Connection> connectionMapBackup = null; Map<String, Connection> connectionMap = null; @Test public void getColumnName() throws SecurityException, NoSuchFieldException { // if no annotation, then the field name Assert.assertEquals("noAnnotation", DbUtil.getColumnName(Testbean.class.getDeclaredField("noAnnotation"))); // there is annotation with name, take the name Assert.assertEquals("surprise", DbUtil.getColumnName(Testbean.class.getDeclaredField("withAnnotationAndName"))); } @Test @Ignore public void getColumnNameWithAnnotationButWithoutNameAttribute() throws SecurityException, NoSuchFieldException { // there is annotation, but no name defined, fallback to field name // this does not work this way, it probably should Assert.assertEquals("withAnnotation", DbUtil.getColumnName(Testbean.class.getDeclaredField("withAnnotation"))); } @Test public void isPersistable() throws SecurityException, NoSuchFieldException { Assert.assertFalse(DbUtil.isPersistable(IsPersistableTestBean.class.getDeclaredField("staticFinal"))); Assert.assertFalse(DbUtil.isPersistable(IsPersistableTestBean.class.getDeclaredField("justFinal"))); Assert.assertFalse(DbUtil.isPersistable(IsPersistableTestBean.class.getDeclaredField("transientField"))); Assert.assertFalse(DbUtil.isPersistable(IsPersistableTestBean.class.getDeclaredField("strange"))); Assert.assertTrue(DbUtil.isPersistable(IsPersistableTestBean.class.getDeclaredField("instanceField"))); } @Test public void getTableName() { Assert.assertEquals("test_table", DbUtil.getTableName(Testbean.class)); Assert.assertEquals("Bar", DbUtil.getTableName(Bar.class)); } @Before public void setup() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { final Field globalLocks = DbUtil.class.getDeclaredField("s_connectionForGlobalLocks"); globalLocks.setAccessible(true); connectionMapBackup = (Map<String, Connection>) globalLocks.get(null); connectionMap = new HashMap<>(); globalLocks.set(null, connectionMap); final Field dsField = TransactionLegacy.class.getDeclaredField("s_ds"); dsField.setAccessible(true); backup = (DataSource) dsField.get(null); dsField.set(null, dataSource); } @After public void cleanup() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { final Field globalLocks = DbUtil.class.getDeclaredField("s_connectionForGlobalLocks"); globalLocks.setAccessible(true); globalLocks.set(null, connectionMapBackup); final Field dsField = TransactionLegacy.class.getDeclaredField("s_ds"); dsField.setAccessible(true); dsField.set(null, backup); } @Test public void getGlobalLock() throws SQLException { Mockito.when(dataSource.getConnection()).thenReturn(connection); Mockito.when(connection.prepareStatement(Matchers.anyString())).thenReturn(preparedStatement); Mockito.when(preparedStatement.executeQuery()).thenReturn(resultSet); Mockito.when(resultSet.first()).thenReturn(true); Mockito.when(resultSet.getInt(1)).thenReturn(1); Assert.assertTrue(DbUtil.getGlobalLock("TEST", 600)); Mockito.verify(connection).prepareStatement(Matchers.anyString()); Mockito.verify(preparedStatement).close(); Mockito.verify(resultSet).close(); } @Test public void getGlobalLockTimeout() throws SQLException { Mockito.when(dataSource.getConnection()).thenReturn(connection); Mockito.when(connection.prepareStatement(Matchers.anyString())).thenReturn(preparedStatement); Mockito.when(preparedStatement.executeQuery()).thenReturn(resultSet); Mockito.when(resultSet.first()).thenReturn(true); Mockito.when(resultSet.getInt(1)).thenReturn(0); Assert.assertFalse(DbUtil.getGlobalLock("TEST", 600)); Mockito.verify(connection).prepareStatement(Matchers.anyString()); Mockito.verify(preparedStatement).close(); Mockito.verify(resultSet).close(); Mockito.verify(connection).close(); // if any error happens, the connection map must be cleared Assert.assertTrue(connectionMap.isEmpty()); } @Test public void closeNull() { DbUtil.closeStatement((Statement) null); DbUtil.closeConnection((Connection) null); DbUtil.closeResultSet((ResultSet) null); // no exception should be thrown } @Test public void closeConnection() throws IOException, SQLException { DbUtil.closeConnection(connection); Mockito.verify(connection).close(); } @Test public void closeConnectionFail() throws IOException, SQLException { Mockito.doThrow(new SQLException("it is all right")).when(connection).close(); DbUtil.closeConnection(connection); Mockito.verify(connection).close(); } @Test public void closeStatement() throws IOException, SQLException { DbUtil.closeStatement(statement); Mockito.verify(statement).close(); } @Test public void closeStatementFail() throws IOException, SQLException { Mockito.doThrow(new SQLException("it is all right")).when(statement).close(); DbUtil.closeStatement(statement); Mockito.verify(statement).close(); } @Test public void closeResultSet() throws IOException, SQLException { DbUtil.closeResultSet(resultSet); Mockito.verify(resultSet).close(); } @Test public void closeResultSetFail() throws IOException, SQLException { Mockito.doThrow(new SQLException("it is all right")).when(resultSet).close(); DbUtil.closeResultSet(resultSet); Mockito.verify(resultSet).close(); } @Test @Ignore //can not be performed since assertion embedded in this branch of execution public void releaseGlobalLockNotexisting() throws SQLException { Assert.assertFalse(DbUtil.releaseGlobalLock("notexisting")); Mockito.verify(dataSource, Mockito.never()).getConnection(); } @Test public void releaseGlobalLock() throws SQLException { Mockito.when(connection.prepareStatement(Matchers.anyString())).thenReturn(preparedStatement); Mockito.when(preparedStatement.executeQuery()).thenReturn(resultSet); Mockito.when(resultSet.first()).thenReturn(true); Mockito.when(resultSet.getInt(1)).thenReturn(1); connectionMap.put("testLock", connection); Assert.assertTrue(DbUtil.releaseGlobalLock("testLock")); Mockito.verify(resultSet).close(); Mockito.verify(preparedStatement).close(); Mockito.verify(connection).close(); Assert.assertFalse(connectionMap.containsKey("testLock")); } @Table(name = "test_table") static class Testbean { String noAnnotation; @Column() String withAnnotation; @Column(name = "surprise") String withAnnotationAndName; } static class IsPersistableTestBean { static final String staticFinal = "no"; transient static String strange = ""; final String justFinal = "no"; transient String transientField; String instanceField; } class Bar { } }
fzodc/api-stuido
src/pages/Dashboard/OrgCard.js
<filename>src/pages/Dashboard/OrgCard.js<gh_stars>0 import React, { memo } from 'react'; import { Row, Col, Card, Tabs, DatePicker } from 'antd'; import numeral from 'numeral'; import styles from './Analysis.less'; import { Bar } from '@/components/Charts'; const { RangePicker } = DatePicker; const { TabPane } = Tabs; const rankingListData = [{title:'crm',total:323234}, {title:'billing',total:263234},{title:'ose',total:223234}, {title:'tdc',total:173234},{title:'och',total:113234}, {title:'mvno',total:3234},{title:'ali',total:234},]; const OrgCard = memo( ({ rangePickerValue, salesData, isActive, handleRangePickerChange, loading, selectDate }) => ( <Card loading={loading} bordered={false} bodyStyle={{ padding: 0 }}> <div className={styles.salesCard}> <Tabs tabBarExtraContent={ <div className={styles.salesExtraWrap}> <div className={styles.salesExtra}> <a className={isActive('today')} onClick={() => selectDate('today')}> All Day </a> <a className={isActive('week')} onClick={() => selectDate('week')}> All Week </a> <a className={isActive('month')} onClick={() => selectDate('month')}> All Month </a> <a className={isActive('year')} onClick={() => selectDate('year')}> All Year </a> </div> <RangePicker value={rangePickerValue} onChange={handleRangePickerChange} style={{ width: 256 }} /> </div> } size="large" tabBarStyle={{ marginBottom: 24 }} > <TabPane tab="Consumer Calls" key="calls" > <Row> <Col xl={16} lg={12} md={12} sm={24} xs={24}> <div className={styles.salesBar}> <Bar height={295} title="Calls Trend" data={salesData} /> </div> </Col> <Col xl={8} lg={12} md={12} sm={24} xs={24}> <div className={styles.salesRank}> <h4 className={styles.rankingTitle}> Consumer Ranking of Call </h4> <ul className={styles.rankingList}> {rankingListData.map((item, i) => ( <li key={item.title}> <span className={`${styles.rankingItemNumber} ${i < 3 ? styles.active : ''}`} > {i + 1} </span> <span className={styles.rankingItemTitle} title={item.title}> {item.title} </span> <span className={styles.rankingItemValue}> {numeral(item.total).format('0,0')} </span> </li> ))} </ul> </div> </Col> </Row> </TabPane> <TabPane tab="Producer Calleds" key="calleds" > <Row> <Col xl={16} lg={12} md={12} sm={24} xs={24}> <div className={styles.salesBar}> <Bar height={292} title="Called Trend" data={salesData} /> </div> </Col> <Col xl={8} lg={12} md={12} sm={24} xs={24}> <div className={styles.salesRank}> <h4 className={styles.rankingTitle}> Producer Ranking of Called </h4> <ul className={styles.rankingList}> {rankingListData.map((item, i) => ( <li key={item.title}> <span className={`${styles.rankingItemNumber} ${i < 3 ? styles.active : ''}`} > {i + 1} </span> <span className={styles.rankingItemTitle} title={item.title}> {item.title} </span> <span>{numeral(item.total).format('0,0')}</span> </li> ))} </ul> </div> </Col> </Row> </TabPane> </Tabs> </div> </Card> ) ); export default OrgCard;
jakobehmsen/giki-lang
eclipse/src/giki/gui/ResourceView.java
package giki.gui; import giki.parser.Resource; import java.awt.BorderLayout; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.AbstractDocument; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; import javax.swing.text.Document; import javax.swing.text.EditorKit; import javax.swing.text.Element; import javax.swing.text.ParagraphView; import javax.swing.text.StyledEditorKit; import javax.swing.text.TabSet; import javax.swing.text.View; import javax.swing.text.ViewFactory; public class ResourceView extends JPanel { /** * */ private static final long serialVersionUID = 1L; private ResourceHolder resouceHolder; private Resource resource; private JTextPane textPaneIn; private JScrollPane textPaneInScrollPane; private boolean hasLoaded; // private boolean showLineNumbers; private EditorKit createEditorKit(final int defaultTabSize) { return new StyledEditorKit() { /** * */ private static final long serialVersionUID = 1L; @Override public ViewFactory getViewFactory() { final ViewFactory parentViewFactory = super.getViewFactory(); return new ViewFactory() { @Override public View create(Element elem) { String kind = elem.getName(); if (kind != null && kind.equals(AbstractDocument.ParagraphElementName)) { return new ParagraphView(elem) { public float nextTabStop(float x, int tabOffset) { TabSet tabs = getTabSet(); if(tabs == null) { // a tab every 72 pixels. return (float)(getTabBase() + (((int)x / defaultTabSize + 1) * defaultTabSize)); } return super.nextTabStop(x, tabOffset); } }; } return parentViewFactory.create(elem); } }; } }; } public ResourceView(ResourceHolder resouceHolder, Resource resource) { this.resouceHolder = resouceHolder; this.resource = resource; } private void loadUI() { this.setLayout(new BorderLayout()); textPaneInScrollPane = new JScrollPane(); textPaneIn = new JTextPane(); textPaneIn.setEditorKit(createEditorKit(32)); textPaneIn.setFont(MainFrame.CODE_FONT); textPaneIn.setCaret(new javax.swing.text.DefaultCaret(){ /** * */ private static final long serialVersionUID = 1L; public void setSelectionVisible(boolean visible) { super.setSelectionVisible(true); } }); JPanel textPaneInWrapper = new JPanel(); textPaneInWrapper.setLayout(new BorderLayout()); textPaneInWrapper.add(textPaneIn, BorderLayout.CENTER); textPaneInScrollPane.getViewport().add(textPaneInWrapper); textPaneInScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); this.add(textPaneInScrollPane, BorderLayout.CENTER); } private void loadResource() { try { InputStream inputStream = resource.getInputStream(); Reader reader = new InputStreamReader(inputStream); Document textDocument = textPaneIn.getStyledDocument(); // // try { // textDocument.remove(0, textDocument.getLength()); // } catch (BadLocationException e3) { // e3.printStackTrace(); // } // // boolean useSyntaxDecoration = false; // // if(useSyntaxDecoration) { // textDocument.addDocumentListener(new DocumentListener() { // Pattern syntaxIndicatorPattern = Pattern.compile("\\w+"); // Pattern syntaxPattern = Pattern.compile("\\w+"); // // SimpleAttributeSet attributeSetRegular = new SimpleAttributeSet(); // SimpleAttributeSet attributeSetKeyword = new SimpleAttributeSet(); // // { // StyleConstants.setForeground(attributeSetRegular, Color.BLACK); // StyleConstants.setForeground(attributeSetKeyword, Color.BLUE); // } // // @Override // public void removeUpdate(DocumentEvent e) { // invokeLaterSyntaxDecoration((StyledDocument)e.getDocument(), e.getOffset(), 1); // } // // @Override // public void insertUpdate(final DocumentEvent e) { // invokeLaterSyntaxDecoration((StyledDocument)e.getDocument(), e.getOffset(), e.getLength()); // } // // private void invokeLaterSyntaxDecoration(final StyledDocument document, final int offset, final int length) { // SwingUtilities.invokeLater(new Runnable() { // @Override // public void run() { // int minKeywordSize = 3; // // int maxKeywordSize = 4; // int sampleRadiusLeft = maxKeywordSize; // int sampleRadiusRight = maxKeywordSize; // // int sampleOffset = Math.max(offset - sampleRadiusLeft, 0); // int sampleLength = Math.min(sampleRadiusLeft + length + sampleRadiusRight, document.getLength() - sampleOffset); // // if(sampleLength == 0) // return; // // try { // String sample = document.getText(sampleOffset, sampleLength); // // while( // (Character.isLetter(sample.charAt(0)) && sampleOffset != 0) // || // (Character.isLetter(sample.charAt(sample.length() - 1)) && sampleOffset + sampleLength < document.getLength())) { // // if(Character.isLetter(sample.charAt(0))) // sampleOffset = Math.max(sampleOffset - 1, 0); // if(Character.isLetter(sample.charAt(sample.length() - 1))) // sampleLength = Math.min(sampleLength + 1, document.getLength() - sampleOffset); // // sample = document.getText(sampleOffset, sampleLength); // } // // if(sample.length() >= minKeywordSize) { // Matcher keywordMatcher = syntaxPattern.matcher(sample); // // while(keywordMatcher.find()) { // String candidate = keywordMatcher.group(); // // boolean isKeyword = // candidate.equals("def") || candidate.equals("var") || candidate.equals("eof") || // candidate.equals("rest") || candidate.equals("file"); // // int candidateOffset = sampleOffset + keywordMatcher.start(); // int candidateLength = candidate.length(); // // if(isKeyword) // document.setCharacterAttributes(candidateOffset, candidateLength, attributeSetKeyword, true); // else // document.setCharacterAttributes(candidateOffset, candidateLength, attributeSetRegular, true); // } // } // else // document.setCharacterAttributes(offset, length, attributeSetRegular, true); // } catch (BadLocationException e1) { // e1.printStackTrace(); // } // } // }); // } // // @Override // public void changedUpdate(DocumentEvent e) { } // }); // } DefaultCaret caret = (DefaultCaret) textPaneIn.getCaret(); caret.setBlinkRate(366); int caretUpdatePolicy = caret.getUpdatePolicy(); caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE); StringBuilder documentTextBuilder = new StringBuilder(); char[] charBuffer = new char[1024]; while(reader.ready()) { int readCount = reader.read(charBuffer, 0, charBuffer.length); documentTextBuilder.append(charBuffer, 0, readCount); } reader.close(); try { textDocument.insertString(0, documentTextBuilder.toString(), null); textDocument.addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { resouceHolder.resourceChanged(); } @Override public void insertUpdate(final DocumentEvent e) { resouceHolder.resourceChanged(); } @Override public void changedUpdate(DocumentEvent e) { } }); } catch (BadLocationException e2) { e2.printStackTrace(); } textPaneIn.setDocument(textDocument); caret.setUpdatePolicy(caretUpdatePolicy); } catch (IOException e) { e.printStackTrace(); } } public void saveResource() throws IOException { if(hasLoaded) { OutputStream outputStream = resource.getOutputStream(); Writer out = new OutputStreamWriter(outputStream); Document document = textPaneIn.getStyledDocument(); try { String text = document.getText(0, document.getLength()); out.append(text); } catch (BadLocationException e) { e.printStackTrace(); } out.close(); outputStream.close(); } } public String getText() { ensureLoaded(); Document document = textPaneIn.getStyledDocument(); String selectedText = textPaneIn.getSelectedText(); if(selectedText != null) return selectedText; try { return document.getText(0, document.getLength()); } catch (BadLocationException e) { e.printStackTrace(); } return null; // return textPaneIn.getText(); } private void ensureLoaded() { if(!hasLoaded) { loadUI(); loadResource(); hasLoaded = true; } } public void beFocused() { ensureLoaded(); textPaneIn.requestFocusInWindow(); } }
yuan50697105/my-admin-test
my-admin-01/my-admin-gradle/my-admin-commons/src/main/java/org/yuan/admin/commons/controller/ICommonsController.java
package org.yuan.admin.commons.controller; /** * @program: my-admin-gradle * @description: * @author: yuane * @create: 2020-04-19 19:42 */ public class ICommonsController { }
AnneSophieS/manager
packages/manager/apps/dedicated/client/app/billing/autoRenew/disable-domains-bulk/disable-domains-bulk.component.js
<filename>packages/manager/apps/dedicated/client/app/billing/autoRenew/disable-domains-bulk/disable-domains-bulk.component.js<gh_stars>100-1000 import controller from './disable-domains-bulk.controller'; import template from './disable-domains-bulk.html'; export default { bindings: { disableDomainsBulk: '<', goBack: '<', }, controller, template, };
wtwhite/xmp
src/fastdnamp.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <time.h> #include <ctype.h> //#include <mem.h> #include <string.h> #include <assert.h> #include "common.h" #include "seq.h" #include "yanbader.h" #include "measure.h" #include "timer.h" #include "elapsedtime.h" #include <dbgprint.h> // My DBGPRINTn() macros #ifdef TARGETMULTI #include "mpi.h" #include "mpiboss.h" #include "mpiworker.h" #endif // TARGETMULTI int main(int argc, char **argv) { struct tree *root; char *inFileName, *outFileName; FILE *inFile, *outFile = stdout; struct CharData *cd = &gCD; struct TreeData *td = &gTD; #ifdef TARGETMULTI int rank, nProcs; #endif // TARGETMULTI td->startTime = GetTimeNow(); #ifdef TARGETMULTI // MPI initialisation MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &nProcs); #endif // TARGETMULTI //dbgfile = stdout; // Just use stdout for output for SP version dbgfile = stderr; // stderr is easier for debugging MP version -- assertion failures etc. will be in sequence InitTimer(); #ifdef DEBUG #ifdef TARGETMULTI // Only the master outputs settings. if (!rank) { #endif // TARGETMULTI DebugPrintSwitches(); #ifdef TARGETMULTI } #endif // TARGETMULTI #endif // DEBUG SetupDefaults(td); if (!ProcessCmdLineArgs(argc, argv, td, &inFileName, &inFile, &outFileName, &outFile)) { return 0; } #ifdef TARGETMULTI // Only the master outputs settings. if (!rank) { #endif // TARGETMULTI ReportSettings(td, inFileName, inFile, outFileName, outFile); #ifdef TARGETMULTI } #endif // TARGETMULTI // Read a PHYLIP-format sequence alignment into a character matrix ReadPhylipAlignment(inFile, cd); #ifdef TARGETMULTI // Only the master outputs messages. if (!rank) { #endif // TARGETMULTI if (!(td->options & OPT_QUIET)) { fprintf(stderr, "Nucleotide data for %u taxa x %u sites read in.\n", cd->numTaxa, cd->seqLen); } #ifdef TARGETMULTI } #endif // TARGETMULTI if (inFile != stdin) { fclose(inFile); } // Set up the data structure that contains all information relevant to // building a tree on this character matrix InitTreeData(cd, td); if (!(td->options & OPT_ONLYCOMPUTELOWERBOUND)) { root = ConstructBaseTree(td, 1, 2, 3); #ifdef DEBUG branchAndBoundMinNumTaxa = branchAndBoundMaxNumTaxa = 3; #endif // DEBUG // Perform search #ifdef TARGETMULTI // Only the master outputs messages. if (!rank) { #endif // TARGETMULTI if (!(td->options & OPT_QUIET)) { fprintf(stderr, "Beginning branch and bound search...\n"); } #ifdef TARGETMULTI } #endif // TARGETMULTI #ifdef TARGETMULTI td->rank = rank; td->nWorkers = nProcs - 1; if (!rank) { Boss(td, outFile); } else { Worker(root, td); } #else // not TARGETMULTI if (td->updateIntervalSecs) { td->timerHandle = StartTimer(&td->updateProgressNow, td->updateIntervalSecs, 1); DBGPRINT2("Just started timer for the first time. td->timerHandle=%u.\n", td->timerHandle); } td->branchAndBoundStartTime = GetTimeNow(); BranchAndBound(root, 3, td); EMMS; // Needed for MMXASMFITCH td->outputResultsStartTime = GetTimeNow(); // Clean up if (td->updateIntervalSecs) { StopTimer(td->timerHandle); DBGPRINT2("Just stopped timer for the last time. td->timerHandle=%u.\n", td->timerHandle); } OutputResults(td, outFile); td->endTime = GetTimeNow(); #ifdef MEASURE DumpMeasurements(td); #endif // MEASURE ReportTiming(td); #endif // not TARGETMULTI } FinaliseTimer(); DestroyCharData(cd); DestroyTreeData(td); if (dbgfile != stdout && dbgfile != stderr) { fclose(dbgfile); } #ifdef TARGETMULTI MPI_Finalize(); #endif // TARGETMULTI return 0; }
ScalablyTyped/SlinkyTyped
a/angular/src/main/scala/typingsSlinky/angular/mod/ILocaleService.scala
package typingsSlinky.angular.mod import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /////////////////////////////////////////////////////////////////////////// // LocaleService // see http://docs.angularjs.org/api/ng/service/$locale /////////////////////////////////////////////////////////////////////////// @js.native trait ILocaleService extends StObject { var DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor = js.native // These are not documented // Check angular's i18n files for exemples var NUMBER_FORMATS: ILocaleNumberFormatDescriptor = js.native var id: String = js.native def pluralCat(num: js.Any): String = js.native } object ILocaleService { @scala.inline def apply( DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor, NUMBER_FORMATS: ILocaleNumberFormatDescriptor, id: String, pluralCat: js.Any => String ): ILocaleService = { val __obj = js.Dynamic.literal(DATETIME_FORMATS = DATETIME_FORMATS.asInstanceOf[js.Any], NUMBER_FORMATS = NUMBER_FORMATS.asInstanceOf[js.Any], id = id.asInstanceOf[js.Any], pluralCat = js.Any.fromFunction1(pluralCat)) __obj.asInstanceOf[ILocaleService] } @scala.inline implicit class ILocaleServiceMutableBuilder[Self <: ILocaleService] (val x: Self) extends AnyVal { @scala.inline def setDATETIME_FORMATS(value: ILocaleDateTimeFormatDescriptor): Self = StObject.set(x, "DATETIME_FORMATS", value.asInstanceOf[js.Any]) @scala.inline def setId(value: String): Self = StObject.set(x, "id", value.asInstanceOf[js.Any]) @scala.inline def setNUMBER_FORMATS(value: ILocaleNumberFormatDescriptor): Self = StObject.set(x, "NUMBER_FORMATS", value.asInstanceOf[js.Any]) @scala.inline def setPluralCat(value: js.Any => String): Self = StObject.set(x, "pluralCat", js.Any.fromFunction1(value)) } }
AmyliaScarlet/amyliascarletlib
src/test/java/com/amyliascarlet/jsontest/bvt/bug/Issue_for_zuojing.java
package com.amyliascarlet.jsontest.bvt.bug; import com.amyliascarlet.lib.json.JSON; import junit.framework.TestCase; import java.util.List; /** * Created by wenshao on 15/02/2017. */ public class Issue_for_zuojing extends TestCase { public void test_for_zuojing() throws Exception { String rowData = "[{\"@type\":\"java.util.HashMap\",\"end_date\":{\"@type\":\"java.sql.Date\",\"val\":1490803200000},\"gmt_create\":{\"@type\":\"java.sql.Timestamp\",\"val\":1487139144000},\"arr_city\":\"FOC\",\"agent\n" + "_id\":4765L,\"auto_book\":0B,\"sale_rebase\":12,\"channel\":1B,\"dep_city\":\"BJS\",\"gmt_modified\":{\"@type\":\"java.sql.Timestamp\",\"val\":1487139144000},\"is_support_share\":1B,\"sale_retenti\n" + "on\":430S,\"invoice_type\":5B,\"id\":12675100456,\"start_date\":{\"@type\":\"java.sql.Date\",\"val\":1485878400000},\"pat\":1B,\"agent_sub_nick\":\"辰\",\"travel_start_date\":{\"@type\"\n" + ":\"java.sql.Date\",\"val\":1485878400000},\"policy_type\":2B,\"travel_end_date\":{\"@type\":\"java.sql.Date\",\"val\":1490803200000},\"flights_limit_type\":1B,\"officeid\":\"WNZ159\",\"future_tic\n" + "ket\":0B,\"fare_id\":80L,\"source_id\":4653492L,\"source_code\":32B,\"agent_sub_id\":2752916259,\"flights_limit\":\"1100-1999,4000-4999,8200-8230,8960\"},{\"$ref\":\"$[0]\"}]"; List row = JSON.parseObject(rowData,List.class); assertEquals(2, row.size()); assertSame(row.get(0), row.get(1)); } }
anishmo99/CPP
shortestPathInBinaryMatrix.cpp
class Solution { public: int shortestPathBinaryMatrix(vector<vector<int>>& grid) { int count = 0; vector<vector<int>> dir = {{0, -1}, {0, 1}, {1,1}, {1,-1}, {-1,1}, {-1, -1}, {1, 0}, {-1, 0}}; vector<vector<bool>> visited(grid.size(), vector<bool> (grid[0].size(), false)); queue<pair<int, int>> q; if(grid[0][0] or grid[grid.size() - 1][grid[0].size() - 1]) return -1; q.push(make_pair(0, 0)); visited[0][0] = true; while(!q.empty()){ int steps = q.size(); count++; for(int i = 0; i < steps; i++){ auto temp = q.front(); q.pop(); int x = temp.first; int y = temp.second; if(x == grid.size() - 1 and y == grid[0].size() - 1) return count; for(int j = 0; j < 8; j++){ int x1 = x + dir[j][0]; int y1 = y + dir[j][1]; if(x1 >= 0 and y1 >= 0 and x1 < grid.size() and y1 < grid[0].size()){ if(!visited[x1][y1] and !grid[x1][y1]){ visited[x1][y1] = true; q.push(make_pair(x1, y1)); } } } } } return -1; } }; class Solution { public: int shortestPathBinaryMatrix(vector<vector<int>>& grid) { if(grid[0][0]==1) return -1; int n = grid.size(); int m = grid[0].size(); vector<vector<int>> dist(n,vector<int> (m,INT_MAX)); queue<pair<int,int>> q; dist[0][0] = 1; q.push({0,0}); vector<vector<int>> points = {{1,0},{0,1},{1,1},{-1,0},{0,-1},{1,-1},{-1,1},{-1,-1}}; while(!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for(int i=0;i<8;i++) { int xd = x+points[i][0]; int yd = y+points[i][1]; if(xd<0 or yd<0 or xd>=n or yd>=m or grid[xd][yd]==1) // can't take these paths to reach grid[n-1][m-1] continue; if(dist[xd][yd]>dist[x][y]+1) { dist[xd][yd] = dist[x][y]+1; q.push({xd,yd}); } } } if(dist[n-1][m-1]==INT_MAX) return -1; return dist[n-1][m-1]; } };
ammurdoch/where-you-at
node_modules/react-native-keyboard-aware-scroll-view/lib/KeyboardAwareListView.js
/* @flow */ import { ListView } from 'react-native' import listenToKeyboardEvents from './KeyboardAwareHOC' export default listenToKeyboardEvents(ListView)
martinohmann/skeleton-go
internal/testutil/env.go
package testutil import "os" // Unsetenv set an environment variable and returns a func to restore it to // its previous value. // // Usage example in tests: // // defer testutil.Setenv(t, key, value)() // func Setenv(key, value string) func() { oldVal, restoreNeeded := os.LookupEnv(key) os.Setenv(key, value) return func() { if restoreNeeded { os.Setenv(key, oldVal) } else { os.Unsetenv(key) } } } // Unsetenv unset an environment variable and returns a func to restore it to // its previous value. // // Usage example in tests: // // defer testutil.Unsetenv(t, key)() // func Unsetenv(key string) func() { oldVal, restoreNeeded := os.LookupEnv(key) os.Unsetenv(key) return func() { if restoreNeeded { os.Setenv(key, oldVal) } } }
JonathanChiudev/react-chatbot
client/src/components/Common/HobbyItem/__tests__/index.spec.js
<gh_stars>1-10 import React from 'react'; import { create } from 'react-test-renderer'; import HobbyItem from '../../HobbyItem'; const mockComponent = props => ( <HobbyItem {...props} /> ); describe('components/Common/<HobbyItem />', () => { it('should render component', () => { const props = { data: { name: 'name', image: 'image', description: 'description', }, }; const tree = create(mockComponent(props)).toJSON(); expect(tree).toMatchSnapshot(); }); });
subramon/qlu
TMPL_FIX_HASHMAP/src/rs_hmap_pr.c
// EXTERNAL EXPOSURE #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> #include "q_macros.h" #include "pr.h" #include "rs_hmap_pr.h" int rs_hmap_pr( rs_hmap_t *ptr_hmap, FILE *fp ) { int status = 0; bkt_t *bkts = (bkt_t *)ptr_hmap->bkts; bool *bkt_full = ptr_hmap->bkt_full; if ( fp == NULL ) { fp = stdout; } for ( uint32_t i = 0; i < ptr_hmap->size; i++ ) { if ( !bkt_full[i] ) { continue; } pr_key(&(bkts[i].key), fp); cBYE(status); pr_val(&(bkts[i].val), fp); cBYE(status); } BYE: return status; }
jxg01713/zstack
header/src/main/java/org/zstack/header/storage/snapshot/VolumeSnapshotVO_.java
package org.zstack.header.storage.snapshot; /** */ import javax.persistence.metamodel.StaticMetamodel; @StaticMetamodel(VolumeSnapshotVO.class) public class VolumeSnapshotVO_ extends VolumeSnapshotAO_ { }
Gohan/aws-sdk-cpp
aws-cpp-sdk-autoscaling/include/aws/autoscaling/model/CreateLaunchConfigurationRequest.h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/autoscaling/AutoScaling_EXPORTS.h> #include <aws/autoscaling/AutoScalingRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/autoscaling/model/InstanceMonitoring.h> #include <aws/autoscaling/model/BlockDeviceMapping.h> #include <utility> namespace Aws { namespace AutoScaling { namespace Model { /** */ class AWS_AUTOSCALING_API CreateLaunchConfigurationRequest : public AutoScalingRequest { public: CreateLaunchConfigurationRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateLaunchConfiguration"; } Aws::String SerializePayload() const override; protected: void DumpBodyToUrl(Aws::Http::URI& uri ) const override; public: /** * <p>The name of the launch configuration. This name must be unique within the * scope of your AWS account.</p> */ inline const Aws::String& GetLaunchConfigurationName() const{ return m_launchConfigurationName; } /** * <p>The name of the launch configuration. This name must be unique within the * scope of your AWS account.</p> */ inline void SetLaunchConfigurationName(const Aws::String& value) { m_launchConfigurationNameHasBeenSet = true; m_launchConfigurationName = value; } /** * <p>The name of the launch configuration. This name must be unique within the * scope of your AWS account.</p> */ inline void SetLaunchConfigurationName(Aws::String&& value) { m_launchConfigurationNameHasBeenSet = true; m_launchConfigurationName = std::move(value); } /** * <p>The name of the launch configuration. This name must be unique within the * scope of your AWS account.</p> */ inline void SetLaunchConfigurationName(const char* value) { m_launchConfigurationNameHasBeenSet = true; m_launchConfigurationName.assign(value); } /** * <p>The name of the launch configuration. This name must be unique within the * scope of your AWS account.</p> */ inline CreateLaunchConfigurationRequest& WithLaunchConfigurationName(const Aws::String& value) { SetLaunchConfigurationName(value); return *this;} /** * <p>The name of the launch configuration. This name must be unique within the * scope of your AWS account.</p> */ inline CreateLaunchConfigurationRequest& WithLaunchConfigurationName(Aws::String&& value) { SetLaunchConfigurationName(std::move(value)); return *this;} /** * <p>The name of the launch configuration. This name must be unique within the * scope of your AWS account.</p> */ inline CreateLaunchConfigurationRequest& WithLaunchConfigurationName(const char* value) { SetLaunchConfigurationName(value); return *this;} /** * <p>The ID of the Amazon Machine Image (AMI) to use to launch your EC2 * instances.</p> <p>If you do not specify <code>InstanceId</code>, you must * specify <code>ImageId</code>.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding * an AMI</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline const Aws::String& GetImageId() const{ return m_imageId; } /** * <p>The ID of the Amazon Machine Image (AMI) to use to launch your EC2 * instances.</p> <p>If you do not specify <code>InstanceId</code>, you must * specify <code>ImageId</code>.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding * an AMI</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetImageId(const Aws::String& value) { m_imageIdHasBeenSet = true; m_imageId = value; } /** * <p>The ID of the Amazon Machine Image (AMI) to use to launch your EC2 * instances.</p> <p>If you do not specify <code>InstanceId</code>, you must * specify <code>ImageId</code>.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding * an AMI</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetImageId(Aws::String&& value) { m_imageIdHasBeenSet = true; m_imageId = std::move(value); } /** * <p>The ID of the Amazon Machine Image (AMI) to use to launch your EC2 * instances.</p> <p>If you do not specify <code>InstanceId</code>, you must * specify <code>ImageId</code>.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding * an AMI</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetImageId(const char* value) { m_imageIdHasBeenSet = true; m_imageId.assign(value); } /** * <p>The ID of the Amazon Machine Image (AMI) to use to launch your EC2 * instances.</p> <p>If you do not specify <code>InstanceId</code>, you must * specify <code>ImageId</code>.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding * an AMI</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithImageId(const Aws::String& value) { SetImageId(value); return *this;} /** * <p>The ID of the Amazon Machine Image (AMI) to use to launch your EC2 * instances.</p> <p>If you do not specify <code>InstanceId</code>, you must * specify <code>ImageId</code>.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding * an AMI</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithImageId(Aws::String&& value) { SetImageId(std::move(value)); return *this;} /** * <p>The ID of the Amazon Machine Image (AMI) to use to launch your EC2 * instances.</p> <p>If you do not specify <code>InstanceId</code>, you must * specify <code>ImageId</code>.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding * an AMI</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithImageId(const char* value) { SetImageId(value); return *this;} /** * <p>The name of the key pair. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Amazon * EC2 Key Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline const Aws::String& GetKeyName() const{ return m_keyName; } /** * <p>The name of the key pair. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Amazon * EC2 Key Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetKeyName(const Aws::String& value) { m_keyNameHasBeenSet = true; m_keyName = value; } /** * <p>The name of the key pair. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Amazon * EC2 Key Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetKeyName(Aws::String&& value) { m_keyNameHasBeenSet = true; m_keyName = std::move(value); } /** * <p>The name of the key pair. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Amazon * EC2 Key Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetKeyName(const char* value) { m_keyNameHasBeenSet = true; m_keyName.assign(value); } /** * <p>The name of the key pair. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Amazon * EC2 Key Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithKeyName(const Aws::String& value) { SetKeyName(value); return *this;} /** * <p>The name of the key pair. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Amazon * EC2 Key Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithKeyName(Aws::String&& value) { SetKeyName(std::move(value)); return *this;} /** * <p>The name of the key pair. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Amazon * EC2 Key Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithKeyName(const char* value) { SetKeyName(value); return *this;} /** * <p>One or more security groups with which to associate the instances.</p> <p>If * your instances are launched in EC2-Classic, you can either specify security * group names or the security group IDs. For more information about security * groups for EC2-Classic, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon * EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> <p>If your instances are launched into a VPC, specify security * group IDs. For more information, see <a * href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security * Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User * Guide</i>.</p> */ inline const Aws::Vector<Aws::String>& GetSecurityGroups() const{ return m_securityGroups; } /** * <p>One or more security groups with which to associate the instances.</p> <p>If * your instances are launched in EC2-Classic, you can either specify security * group names or the security group IDs. For more information about security * groups for EC2-Classic, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon * EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> <p>If your instances are launched into a VPC, specify security * group IDs. For more information, see <a * href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security * Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User * Guide</i>.</p> */ inline void SetSecurityGroups(const Aws::Vector<Aws::String>& value) { m_securityGroupsHasBeenSet = true; m_securityGroups = value; } /** * <p>One or more security groups with which to associate the instances.</p> <p>If * your instances are launched in EC2-Classic, you can either specify security * group names or the security group IDs. For more information about security * groups for EC2-Classic, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon * EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> <p>If your instances are launched into a VPC, specify security * group IDs. For more information, see <a * href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security * Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User * Guide</i>.</p> */ inline void SetSecurityGroups(Aws::Vector<Aws::String>&& value) { m_securityGroupsHasBeenSet = true; m_securityGroups = std::move(value); } /** * <p>One or more security groups with which to associate the instances.</p> <p>If * your instances are launched in EC2-Classic, you can either specify security * group names or the security group IDs. For more information about security * groups for EC2-Classic, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon * EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> <p>If your instances are launched into a VPC, specify security * group IDs. For more information, see <a * href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security * Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User * Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithSecurityGroups(const Aws::Vector<Aws::String>& value) { SetSecurityGroups(value); return *this;} /** * <p>One or more security groups with which to associate the instances.</p> <p>If * your instances are launched in EC2-Classic, you can either specify security * group names or the security group IDs. For more information about security * groups for EC2-Classic, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon * EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> <p>If your instances are launched into a VPC, specify security * group IDs. For more information, see <a * href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security * Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User * Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithSecurityGroups(Aws::Vector<Aws::String>&& value) { SetSecurityGroups(std::move(value)); return *this;} /** * <p>One or more security groups with which to associate the instances.</p> <p>If * your instances are launched in EC2-Classic, you can either specify security * group names or the security group IDs. For more information about security * groups for EC2-Classic, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon * EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> <p>If your instances are launched into a VPC, specify security * group IDs. For more information, see <a * href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security * Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User * Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& AddSecurityGroups(const Aws::String& value) { m_securityGroupsHasBeenSet = true; m_securityGroups.push_back(value); return *this; } /** * <p>One or more security groups with which to associate the instances.</p> <p>If * your instances are launched in EC2-Classic, you can either specify security * group names or the security group IDs. For more information about security * groups for EC2-Classic, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon * EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> <p>If your instances are launched into a VPC, specify security * group IDs. For more information, see <a * href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security * Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User * Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& AddSecurityGroups(Aws::String&& value) { m_securityGroupsHasBeenSet = true; m_securityGroups.push_back(std::move(value)); return *this; } /** * <p>One or more security groups with which to associate the instances.</p> <p>If * your instances are launched in EC2-Classic, you can either specify security * group names or the security group IDs. For more information about security * groups for EC2-Classic, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon * EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> <p>If your instances are launched into a VPC, specify security * group IDs. For more information, see <a * href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security * Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User * Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& AddSecurityGroups(const char* value) { m_securityGroupsHasBeenSet = true; m_securityGroups.push_back(value); return *this; } /** * <p>The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. * This parameter is supported only if you are launching EC2-Classic instances. For * more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline const Aws::String& GetClassicLinkVPCId() const{ return m_classicLinkVPCId; } /** * <p>The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. * This parameter is supported only if you are launching EC2-Classic instances. For * more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetClassicLinkVPCId(const Aws::String& value) { m_classicLinkVPCIdHasBeenSet = true; m_classicLinkVPCId = value; } /** * <p>The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. * This parameter is supported only if you are launching EC2-Classic instances. For * more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetClassicLinkVPCId(Aws::String&& value) { m_classicLinkVPCIdHasBeenSet = true; m_classicLinkVPCId = std::move(value); } /** * <p>The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. * This parameter is supported only if you are launching EC2-Classic instances. For * more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetClassicLinkVPCId(const char* value) { m_classicLinkVPCIdHasBeenSet = true; m_classicLinkVPCId.assign(value); } /** * <p>The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. * This parameter is supported only if you are launching EC2-Classic instances. For * more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithClassicLinkVPCId(const Aws::String& value) { SetClassicLinkVPCId(value); return *this;} /** * <p>The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. * This parameter is supported only if you are launching EC2-Classic instances. For * more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithClassicLinkVPCId(Aws::String&& value) { SetClassicLinkVPCId(std::move(value)); return *this;} /** * <p>The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. * This parameter is supported only if you are launching EC2-Classic instances. For * more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithClassicLinkVPCId(const char* value) { SetClassicLinkVPCId(value); return *this;} /** * <p>The IDs of one or more security groups for the specified ClassicLink-enabled * VPC. This parameter is required if you specify a ClassicLink-enabled VPC, and is * not supported otherwise. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline const Aws::Vector<Aws::String>& GetClassicLinkVPCSecurityGroups() const{ return m_classicLinkVPCSecurityGroups; } /** * <p>The IDs of one or more security groups for the specified ClassicLink-enabled * VPC. This parameter is required if you specify a ClassicLink-enabled VPC, and is * not supported otherwise. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetClassicLinkVPCSecurityGroups(const Aws::Vector<Aws::String>& value) { m_classicLinkVPCSecurityGroupsHasBeenSet = true; m_classicLinkVPCSecurityGroups = value; } /** * <p>The IDs of one or more security groups for the specified ClassicLink-enabled * VPC. This parameter is required if you specify a ClassicLink-enabled VPC, and is * not supported otherwise. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetClassicLinkVPCSecurityGroups(Aws::Vector<Aws::String>&& value) { m_classicLinkVPCSecurityGroupsHasBeenSet = true; m_classicLinkVPCSecurityGroups = std::move(value); } /** * <p>The IDs of one or more security groups for the specified ClassicLink-enabled * VPC. This parameter is required if you specify a ClassicLink-enabled VPC, and is * not supported otherwise. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithClassicLinkVPCSecurityGroups(const Aws::Vector<Aws::String>& value) { SetClassicLinkVPCSecurityGroups(value); return *this;} /** * <p>The IDs of one or more security groups for the specified ClassicLink-enabled * VPC. This parameter is required if you specify a ClassicLink-enabled VPC, and is * not supported otherwise. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithClassicLinkVPCSecurityGroups(Aws::Vector<Aws::String>&& value) { SetClassicLinkVPCSecurityGroups(std::move(value)); return *this;} /** * <p>The IDs of one or more security groups for the specified ClassicLink-enabled * VPC. This parameter is required if you specify a ClassicLink-enabled VPC, and is * not supported otherwise. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& AddClassicLinkVPCSecurityGroups(const Aws::String& value) { m_classicLinkVPCSecurityGroupsHasBeenSet = true; m_classicLinkVPCSecurityGroups.push_back(value); return *this; } /** * <p>The IDs of one or more security groups for the specified ClassicLink-enabled * VPC. This parameter is required if you specify a ClassicLink-enabled VPC, and is * not supported otherwise. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& AddClassicLinkVPCSecurityGroups(Aws::String&& value) { m_classicLinkVPCSecurityGroupsHasBeenSet = true; m_classicLinkVPCSecurityGroups.push_back(std::move(value)); return *this; } /** * <p>The IDs of one or more security groups for the specified ClassicLink-enabled * VPC. This parameter is required if you specify a ClassicLink-enabled VPC, and is * not supported otherwise. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> * in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& AddClassicLinkVPCSecurityGroups(const char* value) { m_classicLinkVPCSecurityGroupsHasBeenSet = true; m_classicLinkVPCSecurityGroups.push_back(value); return *this; } /** * <p>The user data to make available to the launched EC2 instances. For more * information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">Instance * Metadata and User Data</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> */ inline const Aws::String& GetUserData() const{ return m_userData; } /** * <p>The user data to make available to the launched EC2 instances. For more * information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">Instance * Metadata and User Data</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> */ inline void SetUserData(const Aws::String& value) { m_userDataHasBeenSet = true; m_userData = value; } /** * <p>The user data to make available to the launched EC2 instances. For more * information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">Instance * Metadata and User Data</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> */ inline void SetUserData(Aws::String&& value) { m_userDataHasBeenSet = true; m_userData = std::move(value); } /** * <p>The user data to make available to the launched EC2 instances. For more * information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">Instance * Metadata and User Data</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> */ inline void SetUserData(const char* value) { m_userDataHasBeenSet = true; m_userData.assign(value); } /** * <p>The user data to make available to the launched EC2 instances. For more * information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">Instance * Metadata and User Data</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithUserData(const Aws::String& value) { SetUserData(value); return *this;} /** * <p>The user data to make available to the launched EC2 instances. For more * information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">Instance * Metadata and User Data</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithUserData(Aws::String&& value) { SetUserData(std::move(value)); return *this;} /** * <p>The user data to make available to the launched EC2 instances. For more * information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">Instance * Metadata and User Data</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithUserData(const char* value) { SetUserData(value); return *this;} /** * <p>The ID of the instance to use to create the launch configuration. The new * launch configuration derives attributes from the instance, with the exception of * the block device mapping.</p> <p>If you do not specify <code>InstanceId</code>, * you must specify both <code>ImageId</code> and <code>InstanceType</code>.</p> * <p>To create a launch configuration with a block device mapping or override any * other instance attributes, specify them as part of the same request.</p> <p>For * more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/create-lc-with-instanceID.html">Create * a Launch Configuration Using an EC2 Instance</a> in the <i>Amazon EC2 Auto * Scaling User Guide</i>.</p> */ inline const Aws::String& GetInstanceId() const{ return m_instanceId; } /** * <p>The ID of the instance to use to create the launch configuration. The new * launch configuration derives attributes from the instance, with the exception of * the block device mapping.</p> <p>If you do not specify <code>InstanceId</code>, * you must specify both <code>ImageId</code> and <code>InstanceType</code>.</p> * <p>To create a launch configuration with a block device mapping or override any * other instance attributes, specify them as part of the same request.</p> <p>For * more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/create-lc-with-instanceID.html">Create * a Launch Configuration Using an EC2 Instance</a> in the <i>Amazon EC2 Auto * Scaling User Guide</i>.</p> */ inline void SetInstanceId(const Aws::String& value) { m_instanceIdHasBeenSet = true; m_instanceId = value; } /** * <p>The ID of the instance to use to create the launch configuration. The new * launch configuration derives attributes from the instance, with the exception of * the block device mapping.</p> <p>If you do not specify <code>InstanceId</code>, * you must specify both <code>ImageId</code> and <code>InstanceType</code>.</p> * <p>To create a launch configuration with a block device mapping or override any * other instance attributes, specify them as part of the same request.</p> <p>For * more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/create-lc-with-instanceID.html">Create * a Launch Configuration Using an EC2 Instance</a> in the <i>Amazon EC2 Auto * Scaling User Guide</i>.</p> */ inline void SetInstanceId(Aws::String&& value) { m_instanceIdHasBeenSet = true; m_instanceId = std::move(value); } /** * <p>The ID of the instance to use to create the launch configuration. The new * launch configuration derives attributes from the instance, with the exception of * the block device mapping.</p> <p>If you do not specify <code>InstanceId</code>, * you must specify both <code>ImageId</code> and <code>InstanceType</code>.</p> * <p>To create a launch configuration with a block device mapping or override any * other instance attributes, specify them as part of the same request.</p> <p>For * more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/create-lc-with-instanceID.html">Create * a Launch Configuration Using an EC2 Instance</a> in the <i>Amazon EC2 Auto * Scaling User Guide</i>.</p> */ inline void SetInstanceId(const char* value) { m_instanceIdHasBeenSet = true; m_instanceId.assign(value); } /** * <p>The ID of the instance to use to create the launch configuration. The new * launch configuration derives attributes from the instance, with the exception of * the block device mapping.</p> <p>If you do not specify <code>InstanceId</code>, * you must specify both <code>ImageId</code> and <code>InstanceType</code>.</p> * <p>To create a launch configuration with a block device mapping or override any * other instance attributes, specify them as part of the same request.</p> <p>For * more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/create-lc-with-instanceID.html">Create * a Launch Configuration Using an EC2 Instance</a> in the <i>Amazon EC2 Auto * Scaling User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithInstanceId(const Aws::String& value) { SetInstanceId(value); return *this;} /** * <p>The ID of the instance to use to create the launch configuration. The new * launch configuration derives attributes from the instance, with the exception of * the block device mapping.</p> <p>If you do not specify <code>InstanceId</code>, * you must specify both <code>ImageId</code> and <code>InstanceType</code>.</p> * <p>To create a launch configuration with a block device mapping or override any * other instance attributes, specify them as part of the same request.</p> <p>For * more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/create-lc-with-instanceID.html">Create * a Launch Configuration Using an EC2 Instance</a> in the <i>Amazon EC2 Auto * Scaling User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithInstanceId(Aws::String&& value) { SetInstanceId(std::move(value)); return *this;} /** * <p>The ID of the instance to use to create the launch configuration. The new * launch configuration derives attributes from the instance, with the exception of * the block device mapping.</p> <p>If you do not specify <code>InstanceId</code>, * you must specify both <code>ImageId</code> and <code>InstanceType</code>.</p> * <p>To create a launch configuration with a block device mapping or override any * other instance attributes, specify them as part of the same request.</p> <p>For * more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/create-lc-with-instanceID.html">Create * a Launch Configuration Using an EC2 Instance</a> in the <i>Amazon EC2 Auto * Scaling User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithInstanceId(const char* value) { SetInstanceId(value); return *this;} /** * <p>The instance type of the EC2 instance.</p> <p>If you do not specify * <code>InstanceId</code>, you must specify <code>InstanceType</code>.</p> <p>For * information about available instance types, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes">Available * Instance Types</a> in the <i>Amazon Elastic Compute Cloud User Guide.</i> </p> */ inline const Aws::String& GetInstanceType() const{ return m_instanceType; } /** * <p>The instance type of the EC2 instance.</p> <p>If you do not specify * <code>InstanceId</code>, you must specify <code>InstanceType</code>.</p> <p>For * information about available instance types, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes">Available * Instance Types</a> in the <i>Amazon Elastic Compute Cloud User Guide.</i> </p> */ inline void SetInstanceType(const Aws::String& value) { m_instanceTypeHasBeenSet = true; m_instanceType = value; } /** * <p>The instance type of the EC2 instance.</p> <p>If you do not specify * <code>InstanceId</code>, you must specify <code>InstanceType</code>.</p> <p>For * information about available instance types, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes">Available * Instance Types</a> in the <i>Amazon Elastic Compute Cloud User Guide.</i> </p> */ inline void SetInstanceType(Aws::String&& value) { m_instanceTypeHasBeenSet = true; m_instanceType = std::move(value); } /** * <p>The instance type of the EC2 instance.</p> <p>If you do not specify * <code>InstanceId</code>, you must specify <code>InstanceType</code>.</p> <p>For * information about available instance types, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes">Available * Instance Types</a> in the <i>Amazon Elastic Compute Cloud User Guide.</i> </p> */ inline void SetInstanceType(const char* value) { m_instanceTypeHasBeenSet = true; m_instanceType.assign(value); } /** * <p>The instance type of the EC2 instance.</p> <p>If you do not specify * <code>InstanceId</code>, you must specify <code>InstanceType</code>.</p> <p>For * information about available instance types, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes">Available * Instance Types</a> in the <i>Amazon Elastic Compute Cloud User Guide.</i> </p> */ inline CreateLaunchConfigurationRequest& WithInstanceType(const Aws::String& value) { SetInstanceType(value); return *this;} /** * <p>The instance type of the EC2 instance.</p> <p>If you do not specify * <code>InstanceId</code>, you must specify <code>InstanceType</code>.</p> <p>For * information about available instance types, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes">Available * Instance Types</a> in the <i>Amazon Elastic Compute Cloud User Guide.</i> </p> */ inline CreateLaunchConfigurationRequest& WithInstanceType(Aws::String&& value) { SetInstanceType(std::move(value)); return *this;} /** * <p>The instance type of the EC2 instance.</p> <p>If you do not specify * <code>InstanceId</code>, you must specify <code>InstanceType</code>.</p> <p>For * information about available instance types, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes">Available * Instance Types</a> in the <i>Amazon Elastic Compute Cloud User Guide.</i> </p> */ inline CreateLaunchConfigurationRequest& WithInstanceType(const char* value) { SetInstanceType(value); return *this;} /** * <p>The ID of the kernel associated with the AMI.</p> */ inline const Aws::String& GetKernelId() const{ return m_kernelId; } /** * <p>The ID of the kernel associated with the AMI.</p> */ inline void SetKernelId(const Aws::String& value) { m_kernelIdHasBeenSet = true; m_kernelId = value; } /** * <p>The ID of the kernel associated with the AMI.</p> */ inline void SetKernelId(Aws::String&& value) { m_kernelIdHasBeenSet = true; m_kernelId = std::move(value); } /** * <p>The ID of the kernel associated with the AMI.</p> */ inline void SetKernelId(const char* value) { m_kernelIdHasBeenSet = true; m_kernelId.assign(value); } /** * <p>The ID of the kernel associated with the AMI.</p> */ inline CreateLaunchConfigurationRequest& WithKernelId(const Aws::String& value) { SetKernelId(value); return *this;} /** * <p>The ID of the kernel associated with the AMI.</p> */ inline CreateLaunchConfigurationRequest& WithKernelId(Aws::String&& value) { SetKernelId(std::move(value)); return *this;} /** * <p>The ID of the kernel associated with the AMI.</p> */ inline CreateLaunchConfigurationRequest& WithKernelId(const char* value) { SetKernelId(value); return *this;} /** * <p>The ID of the RAM disk associated with the AMI.</p> */ inline const Aws::String& GetRamdiskId() const{ return m_ramdiskId; } /** * <p>The ID of the RAM disk associated with the AMI.</p> */ inline void SetRamdiskId(const Aws::String& value) { m_ramdiskIdHasBeenSet = true; m_ramdiskId = value; } /** * <p>The ID of the RAM disk associated with the AMI.</p> */ inline void SetRamdiskId(Aws::String&& value) { m_ramdiskIdHasBeenSet = true; m_ramdiskId = std::move(value); } /** * <p>The ID of the RAM disk associated with the AMI.</p> */ inline void SetRamdiskId(const char* value) { m_ramdiskIdHasBeenSet = true; m_ramdiskId.assign(value); } /** * <p>The ID of the RAM disk associated with the AMI.</p> */ inline CreateLaunchConfigurationRequest& WithRamdiskId(const Aws::String& value) { SetRamdiskId(value); return *this;} /** * <p>The ID of the RAM disk associated with the AMI.</p> */ inline CreateLaunchConfigurationRequest& WithRamdiskId(Aws::String&& value) { SetRamdiskId(std::move(value)); return *this;} /** * <p>The ID of the RAM disk associated with the AMI.</p> */ inline CreateLaunchConfigurationRequest& WithRamdiskId(const char* value) { SetRamdiskId(value); return *this;} /** * <p>One or more mappings that specify how block devices are exposed to the * instance. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block * Device Mapping</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline const Aws::Vector<BlockDeviceMapping>& GetBlockDeviceMappings() const{ return m_blockDeviceMappings; } /** * <p>One or more mappings that specify how block devices are exposed to the * instance. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block * Device Mapping</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetBlockDeviceMappings(const Aws::Vector<BlockDeviceMapping>& value) { m_blockDeviceMappingsHasBeenSet = true; m_blockDeviceMappings = value; } /** * <p>One or more mappings that specify how block devices are exposed to the * instance. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block * Device Mapping</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetBlockDeviceMappings(Aws::Vector<BlockDeviceMapping>&& value) { m_blockDeviceMappingsHasBeenSet = true; m_blockDeviceMappings = std::move(value); } /** * <p>One or more mappings that specify how block devices are exposed to the * instance. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block * Device Mapping</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithBlockDeviceMappings(const Aws::Vector<BlockDeviceMapping>& value) { SetBlockDeviceMappings(value); return *this;} /** * <p>One or more mappings that specify how block devices are exposed to the * instance. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block * Device Mapping</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithBlockDeviceMappings(Aws::Vector<BlockDeviceMapping>&& value) { SetBlockDeviceMappings(std::move(value)); return *this;} /** * <p>One or more mappings that specify how block devices are exposed to the * instance. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block * Device Mapping</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& AddBlockDeviceMappings(const BlockDeviceMapping& value) { m_blockDeviceMappingsHasBeenSet = true; m_blockDeviceMappings.push_back(value); return *this; } /** * <p>One or more mappings that specify how block devices are exposed to the * instance. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block * Device Mapping</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& AddBlockDeviceMappings(BlockDeviceMapping&& value) { m_blockDeviceMappingsHasBeenSet = true; m_blockDeviceMappings.push_back(std::move(value)); return *this; } /** * <p>Enables detailed monitoring (<code>true</code>) or basic monitoring * (<code>false</code>) for the Auto Scaling instances. The default is * <code>true</code>.</p> */ inline const InstanceMonitoring& GetInstanceMonitoring() const{ return m_instanceMonitoring; } /** * <p>Enables detailed monitoring (<code>true</code>) or basic monitoring * (<code>false</code>) for the Auto Scaling instances. The default is * <code>true</code>.</p> */ inline void SetInstanceMonitoring(const InstanceMonitoring& value) { m_instanceMonitoringHasBeenSet = true; m_instanceMonitoring = value; } /** * <p>Enables detailed monitoring (<code>true</code>) or basic monitoring * (<code>false</code>) for the Auto Scaling instances. The default is * <code>true</code>.</p> */ inline void SetInstanceMonitoring(InstanceMonitoring&& value) { m_instanceMonitoringHasBeenSet = true; m_instanceMonitoring = std::move(value); } /** * <p>Enables detailed monitoring (<code>true</code>) or basic monitoring * (<code>false</code>) for the Auto Scaling instances. The default is * <code>true</code>.</p> */ inline CreateLaunchConfigurationRequest& WithInstanceMonitoring(const InstanceMonitoring& value) { SetInstanceMonitoring(value); return *this;} /** * <p>Enables detailed monitoring (<code>true</code>) or basic monitoring * (<code>false</code>) for the Auto Scaling instances. The default is * <code>true</code>.</p> */ inline CreateLaunchConfigurationRequest& WithInstanceMonitoring(InstanceMonitoring&& value) { SetInstanceMonitoring(std::move(value)); return *this;} /** * <p>The maximum hourly price to be paid for any Spot Instance launched to fulfill * the request. Spot Instances are launched when the price you specify exceeds the * current Spot market price. For more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-launch-spot-instances.html">Launching * Spot Instances in Your Auto Scaling Group</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline const Aws::String& GetSpotPrice() const{ return m_spotPrice; } /** * <p>The maximum hourly price to be paid for any Spot Instance launched to fulfill * the request. Spot Instances are launched when the price you specify exceeds the * current Spot market price. For more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-launch-spot-instances.html">Launching * Spot Instances in Your Auto Scaling Group</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline void SetSpotPrice(const Aws::String& value) { m_spotPriceHasBeenSet = true; m_spotPrice = value; } /** * <p>The maximum hourly price to be paid for any Spot Instance launched to fulfill * the request. Spot Instances are launched when the price you specify exceeds the * current Spot market price. For more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-launch-spot-instances.html">Launching * Spot Instances in Your Auto Scaling Group</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline void SetSpotPrice(Aws::String&& value) { m_spotPriceHasBeenSet = true; m_spotPrice = std::move(value); } /** * <p>The maximum hourly price to be paid for any Spot Instance launched to fulfill * the request. Spot Instances are launched when the price you specify exceeds the * current Spot market price. For more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-launch-spot-instances.html">Launching * Spot Instances in Your Auto Scaling Group</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline void SetSpotPrice(const char* value) { m_spotPriceHasBeenSet = true; m_spotPrice.assign(value); } /** * <p>The maximum hourly price to be paid for any Spot Instance launched to fulfill * the request. Spot Instances are launched when the price you specify exceeds the * current Spot market price. For more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-launch-spot-instances.html">Launching * Spot Instances in Your Auto Scaling Group</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithSpotPrice(const Aws::String& value) { SetSpotPrice(value); return *this;} /** * <p>The maximum hourly price to be paid for any Spot Instance launched to fulfill * the request. Spot Instances are launched when the price you specify exceeds the * current Spot market price. For more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-launch-spot-instances.html">Launching * Spot Instances in Your Auto Scaling Group</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithSpotPrice(Aws::String&& value) { SetSpotPrice(std::move(value)); return *this;} /** * <p>The maximum hourly price to be paid for any Spot Instance launched to fulfill * the request. Spot Instances are launched when the price you specify exceeds the * current Spot market price. For more information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-launch-spot-instances.html">Launching * Spot Instances in Your Auto Scaling Group</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithSpotPrice(const char* value) { SetSpotPrice(value); return *this;} /** * <p>The name or the Amazon Resource Name (ARN) of the instance profile associated * with the IAM role for the instance.</p> <p>EC2 instances launched with an IAM * role will automatically have AWS security credentials available. You can use IAM * roles with Amazon EC2 Auto Scaling to automatically enable applications running * on your EC2 instances to securely access other AWS resources. For more * information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/us-iam-role.html">Launch * Auto Scaling Instances with an IAM Role</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline const Aws::String& GetIamInstanceProfile() const{ return m_iamInstanceProfile; } /** * <p>The name or the Amazon Resource Name (ARN) of the instance profile associated * with the IAM role for the instance.</p> <p>EC2 instances launched with an IAM * role will automatically have AWS security credentials available. You can use IAM * roles with Amazon EC2 Auto Scaling to automatically enable applications running * on your EC2 instances to securely access other AWS resources. For more * information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/us-iam-role.html">Launch * Auto Scaling Instances with an IAM Role</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline void SetIamInstanceProfile(const Aws::String& value) { m_iamInstanceProfileHasBeenSet = true; m_iamInstanceProfile = value; } /** * <p>The name or the Amazon Resource Name (ARN) of the instance profile associated * with the IAM role for the instance.</p> <p>EC2 instances launched with an IAM * role will automatically have AWS security credentials available. You can use IAM * roles with Amazon EC2 Auto Scaling to automatically enable applications running * on your EC2 instances to securely access other AWS resources. For more * information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/us-iam-role.html">Launch * Auto Scaling Instances with an IAM Role</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline void SetIamInstanceProfile(Aws::String&& value) { m_iamInstanceProfileHasBeenSet = true; m_iamInstanceProfile = std::move(value); } /** * <p>The name or the Amazon Resource Name (ARN) of the instance profile associated * with the IAM role for the instance.</p> <p>EC2 instances launched with an IAM * role will automatically have AWS security credentials available. You can use IAM * roles with Amazon EC2 Auto Scaling to automatically enable applications running * on your EC2 instances to securely access other AWS resources. For more * information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/us-iam-role.html">Launch * Auto Scaling Instances with an IAM Role</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline void SetIamInstanceProfile(const char* value) { m_iamInstanceProfileHasBeenSet = true; m_iamInstanceProfile.assign(value); } /** * <p>The name or the Amazon Resource Name (ARN) of the instance profile associated * with the IAM role for the instance.</p> <p>EC2 instances launched with an IAM * role will automatically have AWS security credentials available. You can use IAM * roles with Amazon EC2 Auto Scaling to automatically enable applications running * on your EC2 instances to securely access other AWS resources. For more * information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/us-iam-role.html">Launch * Auto Scaling Instances with an IAM Role</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithIamInstanceProfile(const Aws::String& value) { SetIamInstanceProfile(value); return *this;} /** * <p>The name or the Amazon Resource Name (ARN) of the instance profile associated * with the IAM role for the instance.</p> <p>EC2 instances launched with an IAM * role will automatically have AWS security credentials available. You can use IAM * roles with Amazon EC2 Auto Scaling to automatically enable applications running * on your EC2 instances to securely access other AWS resources. For more * information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/us-iam-role.html">Launch * Auto Scaling Instances with an IAM Role</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithIamInstanceProfile(Aws::String&& value) { SetIamInstanceProfile(std::move(value)); return *this;} /** * <p>The name or the Amazon Resource Name (ARN) of the instance profile associated * with the IAM role for the instance.</p> <p>EC2 instances launched with an IAM * role will automatically have AWS security credentials available. You can use IAM * roles with Amazon EC2 Auto Scaling to automatically enable applications running * on your EC2 instances to securely access other AWS resources. For more * information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/us-iam-role.html">Launch * Auto Scaling Instances with an IAM Role</a> in the <i>Amazon EC2 Auto Scaling * User Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithIamInstanceProfile(const char* value) { SetIamInstanceProfile(value); return *this;} /** * <p>Indicates whether the instance is optimized for Amazon EBS I/O. By default, * the instance is not optimized for EBS I/O. The optimization provides dedicated * throughput to Amazon EBS and an optimized configuration stack to provide optimal * I/O performance. This optimization is not available with all instance types. * Additional usage charges apply. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html">Amazon * EBS-Optimized Instances</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> */ inline bool GetEbsOptimized() const{ return m_ebsOptimized; } /** * <p>Indicates whether the instance is optimized for Amazon EBS I/O. By default, * the instance is not optimized for EBS I/O. The optimization provides dedicated * throughput to Amazon EBS and an optimized configuration stack to provide optimal * I/O performance. This optimization is not available with all instance types. * Additional usage charges apply. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html">Amazon * EBS-Optimized Instances</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> */ inline void SetEbsOptimized(bool value) { m_ebsOptimizedHasBeenSet = true; m_ebsOptimized = value; } /** * <p>Indicates whether the instance is optimized for Amazon EBS I/O. By default, * the instance is not optimized for EBS I/O. The optimization provides dedicated * throughput to Amazon EBS and an optimized configuration stack to provide optimal * I/O performance. This optimization is not available with all instance types. * Additional usage charges apply. For more information, see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html">Amazon * EBS-Optimized Instances</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>.</p> */ inline CreateLaunchConfigurationRequest& WithEbsOptimized(bool value) { SetEbsOptimized(value); return *this;} /** * <p>Used for groups that launch instances into a virtual private cloud (VPC). * Specifies whether to assign a public IP address to each instance. For more * information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html">Launching * Auto Scaling Instances in a VPC</a> in the <i>Amazon EC2 Auto Scaling User * Guide</i>.</p> <p>If you specify this parameter, be sure to specify at least one * subnet when you create your group.</p> <p>Default: If the instance is launched * into a default subnet, the default is to assign a public IP address. If the * instance is launched into a nondefault subnet, the default is not to assign a * public IP address.</p> */ inline bool GetAssociatePublicIpAddress() const{ return m_associatePublicIpAddress; } /** * <p>Used for groups that launch instances into a virtual private cloud (VPC). * Specifies whether to assign a public IP address to each instance. For more * information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html">Launching * Auto Scaling Instances in a VPC</a> in the <i>Amazon EC2 Auto Scaling User * Guide</i>.</p> <p>If you specify this parameter, be sure to specify at least one * subnet when you create your group.</p> <p>Default: If the instance is launched * into a default subnet, the default is to assign a public IP address. If the * instance is launched into a nondefault subnet, the default is not to assign a * public IP address.</p> */ inline void SetAssociatePublicIpAddress(bool value) { m_associatePublicIpAddressHasBeenSet = true; m_associatePublicIpAddress = value; } /** * <p>Used for groups that launch instances into a virtual private cloud (VPC). * Specifies whether to assign a public IP address to each instance. For more * information, see <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html">Launching * Auto Scaling Instances in a VPC</a> in the <i>Amazon EC2 Auto Scaling User * Guide</i>.</p> <p>If you specify this parameter, be sure to specify at least one * subnet when you create your group.</p> <p>Default: If the instance is launched * into a default subnet, the default is to assign a public IP address. If the * instance is launched into a nondefault subnet, the default is not to assign a * public IP address.</p> */ inline CreateLaunchConfigurationRequest& WithAssociatePublicIpAddress(bool value) { SetAssociatePublicIpAddress(value); return *this;} /** * <p>The tenancy of the instance. An instance with a tenancy of * <code>dedicated</code> runs on single-tenant hardware and can only be launched * into a VPC.</p> <p>You must set the value of this parameter to * <code>dedicated</code> if want to launch Dedicated Instances into a shared * tenancy VPC (VPC with instance placement tenancy attribute set to * <code>default</code>).</p> <p>If you specify this parameter, be sure to specify * at least one subnet when you create your group.</p> <p>For more information, see * <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html">Launching * Auto Scaling Instances in a VPC</a> in the <i>Amazon EC2 Auto Scaling User * Guide</i>.</p> <p>Valid values: <code>default</code> | <code>dedicated</code> * </p> */ inline const Aws::String& GetPlacementTenancy() const{ return m_placementTenancy; } /** * <p>The tenancy of the instance. An instance with a tenancy of * <code>dedicated</code> runs on single-tenant hardware and can only be launched * into a VPC.</p> <p>You must set the value of this parameter to * <code>dedicated</code> if want to launch Dedicated Instances into a shared * tenancy VPC (VPC with instance placement tenancy attribute set to * <code>default</code>).</p> <p>If you specify this parameter, be sure to specify * at least one subnet when you create your group.</p> <p>For more information, see * <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html">Launching * Auto Scaling Instances in a VPC</a> in the <i>Amazon EC2 Auto Scaling User * Guide</i>.</p> <p>Valid values: <code>default</code> | <code>dedicated</code> * </p> */ inline void SetPlacementTenancy(const Aws::String& value) { m_placementTenancyHasBeenSet = true; m_placementTenancy = value; } /** * <p>The tenancy of the instance. An instance with a tenancy of * <code>dedicated</code> runs on single-tenant hardware and can only be launched * into a VPC.</p> <p>You must set the value of this parameter to * <code>dedicated</code> if want to launch Dedicated Instances into a shared * tenancy VPC (VPC with instance placement tenancy attribute set to * <code>default</code>).</p> <p>If you specify this parameter, be sure to specify * at least one subnet when you create your group.</p> <p>For more information, see * <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html">Launching * Auto Scaling Instances in a VPC</a> in the <i>Amazon EC2 Auto Scaling User * Guide</i>.</p> <p>Valid values: <code>default</code> | <code>dedicated</code> * </p> */ inline void SetPlacementTenancy(Aws::String&& value) { m_placementTenancyHasBeenSet = true; m_placementTenancy = std::move(value); } /** * <p>The tenancy of the instance. An instance with a tenancy of * <code>dedicated</code> runs on single-tenant hardware and can only be launched * into a VPC.</p> <p>You must set the value of this parameter to * <code>dedicated</code> if want to launch Dedicated Instances into a shared * tenancy VPC (VPC with instance placement tenancy attribute set to * <code>default</code>).</p> <p>If you specify this parameter, be sure to specify * at least one subnet when you create your group.</p> <p>For more information, see * <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html">Launching * Auto Scaling Instances in a VPC</a> in the <i>Amazon EC2 Auto Scaling User * Guide</i>.</p> <p>Valid values: <code>default</code> | <code>dedicated</code> * </p> */ inline void SetPlacementTenancy(const char* value) { m_placementTenancyHasBeenSet = true; m_placementTenancy.assign(value); } /** * <p>The tenancy of the instance. An instance with a tenancy of * <code>dedicated</code> runs on single-tenant hardware and can only be launched * into a VPC.</p> <p>You must set the value of this parameter to * <code>dedicated</code> if want to launch Dedicated Instances into a shared * tenancy VPC (VPC with instance placement tenancy attribute set to * <code>default</code>).</p> <p>If you specify this parameter, be sure to specify * at least one subnet when you create your group.</p> <p>For more information, see * <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html">Launching * Auto Scaling Instances in a VPC</a> in the <i>Amazon EC2 Auto Scaling User * Guide</i>.</p> <p>Valid values: <code>default</code> | <code>dedicated</code> * </p> */ inline CreateLaunchConfigurationRequest& WithPlacementTenancy(const Aws::String& value) { SetPlacementTenancy(value); return *this;} /** * <p>The tenancy of the instance. An instance with a tenancy of * <code>dedicated</code> runs on single-tenant hardware and can only be launched * into a VPC.</p> <p>You must set the value of this parameter to * <code>dedicated</code> if want to launch Dedicated Instances into a shared * tenancy VPC (VPC with instance placement tenancy attribute set to * <code>default</code>).</p> <p>If you specify this parameter, be sure to specify * at least one subnet when you create your group.</p> <p>For more information, see * <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html">Launching * Auto Scaling Instances in a VPC</a> in the <i>Amazon EC2 Auto Scaling User * Guide</i>.</p> <p>Valid values: <code>default</code> | <code>dedicated</code> * </p> */ inline CreateLaunchConfigurationRequest& WithPlacementTenancy(Aws::String&& value) { SetPlacementTenancy(std::move(value)); return *this;} /** * <p>The tenancy of the instance. An instance with a tenancy of * <code>dedicated</code> runs on single-tenant hardware and can only be launched * into a VPC.</p> <p>You must set the value of this parameter to * <code>dedicated</code> if want to launch Dedicated Instances into a shared * tenancy VPC (VPC with instance placement tenancy attribute set to * <code>default</code>).</p> <p>If you specify this parameter, be sure to specify * at least one subnet when you create your group.</p> <p>For more information, see * <a * href="http://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html">Launching * Auto Scaling Instances in a VPC</a> in the <i>Amazon EC2 Auto Scaling User * Guide</i>.</p> <p>Valid values: <code>default</code> | <code>dedicated</code> * </p> */ inline CreateLaunchConfigurationRequest& WithPlacementTenancy(const char* value) { SetPlacementTenancy(value); return *this;} private: Aws::String m_launchConfigurationName; bool m_launchConfigurationNameHasBeenSet; Aws::String m_imageId; bool m_imageIdHasBeenSet; Aws::String m_keyName; bool m_keyNameHasBeenSet; Aws::Vector<Aws::String> m_securityGroups; bool m_securityGroupsHasBeenSet; Aws::String m_classicLinkVPCId; bool m_classicLinkVPCIdHasBeenSet; Aws::Vector<Aws::String> m_classicLinkVPCSecurityGroups; bool m_classicLinkVPCSecurityGroupsHasBeenSet; Aws::String m_userData; bool m_userDataHasBeenSet; Aws::String m_instanceId; bool m_instanceIdHasBeenSet; Aws::String m_instanceType; bool m_instanceTypeHasBeenSet; Aws::String m_kernelId; bool m_kernelIdHasBeenSet; Aws::String m_ramdiskId; bool m_ramdiskIdHasBeenSet; Aws::Vector<BlockDeviceMapping> m_blockDeviceMappings; bool m_blockDeviceMappingsHasBeenSet; InstanceMonitoring m_instanceMonitoring; bool m_instanceMonitoringHasBeenSet; Aws::String m_spotPrice; bool m_spotPriceHasBeenSet; Aws::String m_iamInstanceProfile; bool m_iamInstanceProfileHasBeenSet; bool m_ebsOptimized; bool m_ebsOptimizedHasBeenSet; bool m_associatePublicIpAddress; bool m_associatePublicIpAddressHasBeenSet; Aws::String m_placementTenancy; bool m_placementTenancyHasBeenSet; }; } // namespace Model } // namespace AutoScaling } // namespace Aws
lkersting/SCR-2123
packages/monte_carlo/core/src/MonteCarlo_SimulationPropertiesFactory.hpp
<gh_stars>0 //---------------------------------------------------------------------------// //! //! \file MonteCarlo_SimulationPropertiesFactory.hpp //! \author <NAME> //! \brief Simulation properties factory class declaration. //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_SIMULATION_PROPERTIES_FACTORY_HPP #define MONTE_CARLO_SIMULATION_PROPERTIES_FACTORY_HPP // Std Lib Includes #include <stdexcept> #include <iostream> // Trilinos Includes #include <Teuchos_ParameterList.hpp> namespace MonteCarlo{ //! The simulation properties factory class SimulationPropertiesFactory { public: //! Initialize the simulation properties static void initializeSimulationProperties( const Teuchos::ParameterList& properties, std::ostream* os_warn = &std::cerr ); private: // The warning output stream std::ostream* d_os_warn; }; } // end MonteCarlo namespace #endif // end MONTE_CARLO_SIMULATION_PROPERTIES_FACTORY_HPP //---------------------------------------------------------------------------// // end MonteCarlo_SimulationPropertiesFactory.hpp //---------------------------------------------------------------------------//
ProjetDeRechercheSurLecriture/FieldDB
api/permission/Permission.js
<reponame>ProjetDeRechercheSurLecriture/FieldDB var FieldDBObject = require("./../FieldDBObject").FieldDBObject; var Users = require("./../user/Users").Users; /** * @class Permission * @name Permission * * @description The permission class specifies which user (User, Consultant or Bot) * can do what action to what component in a given corpus. * The specification needs three arguments: User, Verb, Object * * * @property {UserGeneric} user This is userid or username * @property {String} verb Verb is the action permitted: * admin: corpus admin. admin can handle permission of other users * read: can read * addNew: can add/create new datum etc. * edit: can edit/change the content of datum etc., including delete datum which is basically just changing datum states * comment: can comment on datum etc. * export: can export datum etc. * @property {String} directObject Object is sub-component of the corpus to which * the action is directed: * corpus: corpus and corpus details (description etc.) * datum: datums in the corpus including their states * session: sessions in the corpus * datalist: datalists in the corpus * * @extends FieldDBObject */ var Permission = function Permission(options) { if (!this._fieldDBtype) { this._fieldDBtype = "Permission"; } this.debug("Constructing Permission ", options); FieldDBObject.apply(this, arguments); }; Permission.prototype = Object.create(FieldDBObject.prototype, /** @lends Permission.prototype */ { constructor: { value: Permission }, // Internal models: used by the parse function INTERNAL_MODELS: { value: { users: Users } }, length: { get: function() { if (this.users && this.users.length) { return this.users.length; } return 0; } }, map: { get: function() { if (this.users && typeof this.users.map === "function") { var self = this; return function(callback) { return this.users.map.apply(self.users, [callback]); }; } else { return undefined; } } } }); exports.Permission = Permission;
1347508335/PocketOfMedicine
PocketMedicine/PocketMedicine/class/healthTool/drug/controller/DrugTwoController.h
<reponame>1347508335/PocketOfMedicine // // DrugTwoController.h // PocketMedicine // // Created by lanou3g on 15/10/8. // Copyright © 2015年 organazation. All rights reserved. // #import <UIKit/UIKit.h> @interface DrugTwoController : UITableViewController @property (nonatomic, strong) NSString *myTitle; @property (nonatomic,strong) NSString *myId; @property (nonatomic, assign) NSInteger star; @end
RafaelXokito/Clinics
src/main/java/pt/ipleiria/estg/dei/ei/dae/clinics/ws/AuthService.java
<gh_stars>0 package pt.ipleiria.estg.dei.ei.dae.clinics.ws; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTParser; import pt.ipleiria.estg.dei.ei.dae.clinics.dtos.AdministratorDTO; import pt.ipleiria.estg.dei.ei.dae.clinics.dtos.AuthDTO; import pt.ipleiria.estg.dei.ei.dae.clinics.dtos.NewPasswordDTO; import pt.ipleiria.estg.dei.ei.dae.clinics.dtos.PersonDTO; import pt.ipleiria.estg.dei.ei.dae.clinics.ejbs.JwtBean; import pt.ipleiria.estg.dei.ei.dae.clinics.ejbs.PersonBean; import pt.ipleiria.estg.dei.ei.dae.clinics.entities.Administrator; import pt.ipleiria.estg.dei.ei.dae.clinics.entities.HealthcareProfessional; import pt.ipleiria.estg.dei.ei.dae.clinics.entities.Patient; import pt.ipleiria.estg.dei.ei.dae.clinics.entities.Person; import pt.ipleiria.estg.dei.ei.dae.clinics.exceptions.MyEntityNotFoundException; import pt.ipleiria.estg.dei.ei.dae.clinics.exceptions.MyIllegalArgumentException; import pt.ipleiria.estg.dei.ei.dae.clinics.jwt.Jwt; import javax.annotation.security.RolesAllowed; import javax.ejb.EJB; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.text.ParseException; import java.util.logging.Logger; @Path("/auth") @Produces({MediaType.APPLICATION_JSON}) // injects header “Content-Type: application/json” @Consumes({MediaType.APPLICATION_JSON}) // injects header “Accept: application/json” public class AuthService { private static final Logger log = Logger.getLogger(AuthService.class.getName()); @EJB JwtBean jwtBean; @EJB PersonBean personBean; @POST @Path("/login") public Response authenticateUser(AuthDTO authDTO) { try { Person user = personBean.authenticate(authDTO.getEmail(), authDTO.getPassword()); System.out.println("Login Service"); if (user != null) { if (user.getId() > 0) { log.info("Generating JWT for user " + user.getId()); } String token = jwtBean.createJwt(String.valueOf(user.getId()), new String[]{user.getClass().getSimpleName()}); return Response.ok(new Jwt("Bearer",token)).build(); } } catch (Exception e) { log.info(e.getMessage()); } return Response.status(Response.Status.UNAUTHORIZED).build(); } @GET @Path("/user") @RolesAllowed({"Administrator", "HealthcareProfessional", "Patient"}) public Response demonstrateClaims(@HeaderParam("Authorization") String auth) { if (auth != null && auth.startsWith("Bearer ")) { try { Person person = personBean.getPersonByAuthToken(auth); return Response.ok(toDTO(person)).build(); } catch (ParseException e) { log.warning(e.toString()); return Response.status(Response.Status.BAD_REQUEST).build(); } } return Response.status(Response.Status.NO_CONTENT).build(); //no jwt means no claims to extract } @PATCH @Path("/updatepassword") @RolesAllowed({"Administrator", "HealthcareProfessional", "Patient"}) public Response selfUpdatePasswordWS(@HeaderParam("Authorization") String auth, NewPasswordDTO newPasswordDTO) throws Exception { Person person = personBean.getPersonByAuthToken(auth); personBean.updatePassword( person.getId(), newPasswordDTO.getOldPassword(), newPasswordDTO.getNewPassword()); return Response.status(Response.Status.OK) .build(); } @PUT @Path("/update") @RolesAllowed({"Administrator", "HealthcareProfessional", "Patient"}) public Response selfUpdateWS(@HeaderParam("Authorization") String auth, PersonDTO administratorDTO) throws Exception { Person person = personBean.getPersonByAuthToken(auth); personBean.update( person.getId(), administratorDTO.getEmail(), administratorDTO.getName(), administratorDTO.getGender()); person = personBean.findPerson(person.getId()); return Response.status(Response.Status.OK) .entity(toDTO(person)) .build(); } private PersonDTO toDTO(Person person) { switch (person.getClass().getSimpleName()){ case "Administrator": return new PersonDTO( person.getId(), person.getEmail(), person.getName(), person.getGender(), person.getCreated_at(), person.getUpdated_at(), person.getDeleted_at(), person.getClass().getSimpleName()); case "HealthcareProfessional": return new PersonDTO( person.getId(), person.getEmail(), person.getName(), person.getGender(), person.getCreated_at(), person.getUpdated_at(), person.getDeleted_at(), person.getClass().getSimpleName(), ((HealthcareProfessional)person).getSpecialty()); case "Patient": return new PersonDTO( person.getId(), person.getEmail(), person.getName(), person.getGender(), person.getCreated_at(), person.getUpdated_at(), person.getDeleted_at(), person.getClass().getSimpleName(), ((Patient)person).getHealthNo()); } return new PersonDTO(); } }
k82cn/rtl8821ce
hal/halmac/halmac_88xx/halmac_8821c/halmac_api_8821c_usb.h
<filename>hal/halmac/halmac_88xx/halmac_8821c/halmac_api_8821c_usb.h #ifndef _HALMAC_API_8821C_USB_H_ #define _HALMAC_API_8821C_USB_H_ #include "../../halmac_2_platform.h" #include "../../halmac_type.h" extern HALMAC_INTF_PHY_PARA HALMAC_RTL8821C_USB2_PHY[]; extern HALMAC_INTF_PHY_PARA HALMAC_RTL8821C_USB3_PHY[]; HALMAC_RET_STATUS halmac_mac_power_switch_8821c_usb( IN PHALMAC_ADAPTER pHalmac_adapter, IN HALMAC_MAC_POWER halmac_power ); HALMAC_RET_STATUS halmac_phy_cfg_8821c_usb( IN PHALMAC_ADAPTER pHalmac_adapter, IN HALMAC_INTF_PHY_PLATFORM platform ); HALMAC_RET_STATUS halmac_interface_integration_tuning_8821c_usb( IN PHALMAC_ADAPTER pHalmac_adapter ); #endif/* _HALMAC_API_8821C_USB_H_ */
hwchiu/vortex
src/server/handler_pod_test.go
package server import ( "encoding/json" "math/rand" "net/http" "net/http/httptest" "strings" "testing" "time" restful "github.com/emicklei/go-restful" "github.com/linkernetworks/mongo" "github.com/hwchiu/vortex/src/config" "github.com/hwchiu/vortex/src/entity" p "github.com/hwchiu/vortex/src/pod" "github.com/hwchiu/vortex/src/serviceprovider" "github.com/moby/moby/pkg/namesgenerator" "github.com/stretchr/testify/suite" "gopkg.in/mgo.v2/bson" ) func init() { rand.Seed(time.Now().UnixNano()) } type PodTestSuite struct { suite.Suite sp *serviceprovider.Container wc *restful.Container session *mongo.Session JWTBearer string } func (suite *PodTestSuite) SetupSuite() { cf := config.MustRead("../../config/testing.json") sp := serviceprovider.NewForTesting(cf) suite.sp = sp // init session suite.session = sp.Mongo.NewSession() // init restful container suite.wc = restful.NewContainer() podService := newPodService(suite.sp) userService := newUserService(suite.sp) suite.wc.Add(podService) suite.wc.Add(userService) token, _ := loginGetToken(suite.wc) suite.NotEmpty(token) suite.JWTBearer = "Bearer " + token } func (suite *PodTestSuite) TearDownSuite() {} func TestPodSuite(t *testing.T) { suite.Run(t, new(PodTestSuite)) } func (suite *PodTestSuite) TestCreatePod() { namespace := "default" containers := []entity.Container{ { Name: namesgenerator.GetRandomName(0), Image: "busybox", Command: []string{"sleep", "3600"}, }, } tName := namesgenerator.GetRandomName(0) pod := entity.Pod{ OwnerID: bson.NewObjectId(), Name: tName, Namespace: namespace, Labels: map[string]string{}, EnvVars: map[string]string{}, Containers: containers, Volumes: []entity.PodVolume{}, Networks: []entity.PodNetwork{}, Capability: true, RestartPolicy: "Never", NetworkType: entity.PodHostNetwork, NodeAffinity: []string{}, } bodyBytes, err := json.MarshalIndent(pod, "", " ") suite.NoError(err) bodyReader := strings.NewReader(string(bodyBytes)) httpRequest, err := http.NewRequest("POST", "http://localhost:7890/v1/pods", bodyReader) suite.NoError(err) httpRequest.Header.Add("Content-Type", "application/json") httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter := httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusCreated, httpWriter) defer suite.session.Remove(entity.PodCollectionName, "name", pod.Name) //load data to check retPod := entity.Pod{} err = suite.session.FindOne(entity.PodCollectionName, bson.M{"name": pod.Name}, &retPod) suite.NoError(err) suite.NotEqual("", retPod.ID) suite.Equal(pod.Name, retPod.Name) suite.Equal(len(pod.Containers), len(retPod.Containers)) //We use the new write but empty input which will cause the readEntity Error httpWriter = httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusBadRequest, httpWriter) //Create again and it should fail since the name exist bodyReader = strings.NewReader(string(bodyBytes)) httpRequest, err = http.NewRequest("POST", "http://localhost:7890/v1/pods", bodyReader) suite.NoError(err) httpRequest.Header.Add("Content-Type", "application/json") httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter = httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusConflict, httpWriter) err = p.DeletePod(suite.sp, &retPod) suite.NoError(err) } func (suite *PodTestSuite) TestCreatePodFail() { namespace := "default" containers := []entity.Container{ { Name: namesgenerator.GetRandomName(0), Image: "busybox", Command: []string{"sleep", "3600"}, }, } tName := namesgenerator.GetRandomName(0) pod := entity.Pod{ OwnerID: bson.NewObjectId(), Name: tName, Namespace: namespace, Containers: containers, Volumes: []entity.PodVolume{ {Name: namesgenerator.GetRandomName(0)}, }, } bodyBytes, err := json.MarshalIndent(pod, "", " ") suite.NoError(err) bodyReader := strings.NewReader(string(bodyBytes)) httpRequest, err := http.NewRequest("POST", "http://localhost:7890/v1/pods", bodyReader) suite.NoError(err) httpRequest.Header.Add("Content-Type", "application/json") httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter := httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusBadRequest, httpWriter) } func (suite *PodTestSuite) TestDeletePod() { namespace := "default" containers := []entity.Container{ { Name: namesgenerator.GetRandomName(0), Image: "busybox", Command: []string{"sleep", "3600"}, }, } tName := namesgenerator.GetRandomName(0) pod := entity.Pod{ ID: bson.NewObjectId(), OwnerID: bson.NewObjectId(), Name: tName, Namespace: namespace, Containers: containers, Capability: true, RestartPolicy: "Never", NetworkType: entity.PodHostNetwork, NodeAffinity: []string{}, } err := p.CreatePod(suite.sp, &pod) suite.NoError(err) err = suite.session.Insert(entity.PodCollectionName, &pod) suite.NoError(err) bodyBytes, err := json.MarshalIndent(pod, "", " ") suite.NoError(err) bodyReader := strings.NewReader(string(bodyBytes)) httpRequest, err := http.NewRequest("DELETE", "http://localhost:7890/v1/pods/"+pod.ID.Hex(), bodyReader) suite.NoError(err) httpRequest.Header.Add("Content-Type", "application/json") httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter := httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusOK, httpWriter) n, err := suite.session.Count(entity.PodCollectionName, bson.M{"_id": pod.ID}) suite.NoError(err) suite.Equal(0, n) } func (suite *PodTestSuite) TestDeletePodWithInvalidID() { httpRequest, err := http.NewRequest("DELETE", "http://localhost:7890/v1/pods/"+bson.NewObjectId().Hex(), nil) suite.NoError(err) httpRequest.Header.Add("Content-Type", "application/json") httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter := httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusBadRequest, httpWriter) } //For Get/List, we only return mongo document func (suite *PodTestSuite) TestGetPod() { namespace := "default" containers := []entity.Container{ { Name: namesgenerator.GetRandomName(0), Image: "busybox", Command: []string{"sleep", "3600"}, }, } tName := namesgenerator.GetRandomName(0) pod := entity.Pod{ ID: bson.NewObjectId(), OwnerID: bson.NewObjectId(), Name: tName, Namespace: namespace, Containers: containers, } //Create data into mongo manually suite.session.C(entity.PodCollectionName).Insert(pod) defer suite.session.Remove(entity.PodCollectionName, "name", tName) httpRequest, err := http.NewRequest("GET", "http://localhost:7890/v1/pods/"+pod.ID.Hex(), nil) suite.NoError(err) httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter := httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusOK, httpWriter) pod = entity.Pod{} err = json.Unmarshal(httpWriter.Body.Bytes(), &pod) suite.NoError(err) suite.Equal(tName, pod.Name) suite.Equal(len(containers), len(pod.Containers)) } func (suite *PodTestSuite) TestGetPodWithInvalidID() { //Get data with non-exits ID httpRequest, err := http.NewRequest("GET", "http://localhost:7890/v1/pods/"+bson.NewObjectId().Hex(), nil) suite.NoError(err) httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter := httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusNotFound, httpWriter) } func (suite *PodTestSuite) TestListPod() { namespace := "default" pods := []entity.Pod{} count := 3 for i := 0; i < count; i++ { containers := []entity.Container{ { Name: namesgenerator.GetRandomName(0), Image: "busybox", Command: []string{"sleep", "3600"}, }, } pods = append(pods, entity.Pod{ ID: bson.NewObjectId(), OwnerID: bson.NewObjectId(), Name: namesgenerator.GetRandomName(0), Namespace: namespace, Containers: containers, }) } for _, p := range pods { suite.session.C(entity.PodCollectionName).Insert(p) defer suite.session.Remove(entity.PodCollectionName, "_id", p.ID) } testCases := []struct { page string pageSize string expectSize int }{ {"", "", count}, {"1", "1", count}, {"1", "3", count}, } for _, tc := range testCases { caseName := "page:pageSize" + tc.page + ":" + tc.pageSize suite.T().Run(caseName, func(t *testing.T) { //list data by default page and page_size url := "http://localhost:7890/v1/pods/" if tc.page != "" || tc.pageSize != "" { url = "http://localhost:7890/v1/pods?" url += "page=" + tc.page + "%" + "page_size" + tc.pageSize } httpRequest, err := http.NewRequest("GET", url, nil) suite.NoError(err) httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter := httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusOK, httpWriter) retPods := []entity.Pod{} err = json.Unmarshal(httpWriter.Body.Bytes(), &retPods) suite.NoError(err) suite.Equal(tc.expectSize, len(retPods)) for i, p := range retPods { suite.Equal(pods[i].Name, p.Name) suite.Equal(len(pods[i].Containers), len(p.Containers)) } }) } } func (suite *PodTestSuite) TestListPodWithInvalidPage() { //Get data with non-exits ID httpRequest, err := http.NewRequest("GET", "http://localhost:7890/v1/pods?page=asdd", nil) suite.NoError(err) httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter := httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusBadRequest, httpWriter) httpRequest, err = http.NewRequest("GET", "http://localhost:7890/v1/pods?page_size=asdd", nil) suite.NoError(err) httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter = httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusBadRequest, httpWriter) httpRequest, err = http.NewRequest("GET", "http://localhost:7890/v1/pods?page=-1", nil) suite.NoError(err) httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter = httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusInternalServerError, httpWriter) }
marient/PelePhysics
Support/Fuego/Pythia/pythia-0.4/packages/pyre/pyre/components/Component.py
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of Technology # (C) 1998-2003 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from pyre.inventory.Configurable import Configurable class Component(Configurable): def stage(self): return def execute(self): raise NotImplementedError("class '%s' must override 'execute'" % self.__class__.__name__) def __init__(self, name, facility): Configurable.__init__(self, name) self.facility = facility import journal self._info = journal.info(self.name) self._debug = journal.debug(self.name) return # version __id__ = "$Id$" # End of file
xanderyzwich/Playground
python/tools/lists/birthday_candles.py
<filename>python/tools/lists/birthday_candles.py """ Birthday Cake Candles: You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest. """ from unittest import TestCase def candle_count(input_set): return sum([1 for x in input_set if x == max(input_set)]) class TestCandleCount(TestCase): def test_case(self): candle_heights = [3, 2, 1, 3] assert candle_count(candle_heights) == 2
chengfulin/dujs
lib/dujs/cfgbuilder.js
<reponame>chengfulin/dujs /* * CFG builder with esgraph library * @lastmodifiedBy ChengFuLin(<EMAIL>) * @lastmodifiedDate 2015-08-25 */ var esgraph = require('../esgraph/index'), factoryFlowNode = require('../esgraph/flownodefactory'), FlowNode = require('../esgraph/flownode'); /** * CFGBuilder * @constructor */ function CFGBuilder() { } /** * Get the CFG of the AST with additional information * @param {Object} ast JS parsed AST * @returns {Object} An 3-entries array representing CFG, [start, end, all nodes] */ CFGBuilder.prototype.getCFG = function (ast) { 'use strict'; var cfg = esgraph(ast), maxLine = 0, maxCol = 0; for(var index = 0; index < cfg[2].length; ++index) { /// specify line number and column offset for nodes beside the entry and exit nodes if (cfg[2][index].type !== FlowNode.EXIT_NODE_TYPE) { (cfg[2][index]).line = cfg[2][index].astNode.loc.start.line; (cfg[2][index]).col = cfg[2][index].astNode.loc.start.column; maxLine = (cfg[2][index].line > maxLine)? cfg[2][index].line : maxLine; maxCol = (cfg[2][index].col > maxCol)? cfg[2][index].col : maxCol; } } /// specify the value of line number and column offset for the exit node cfg[1].line = maxLine; cfg[1].col = maxCol + 1; return cfg; }; /** * Create graph for the domain scope * @returns {Object} Graph object */ CFGBuilder.prototype.getDomainScopeGraph = function () { "use strict"; var localStroageNode = factoryFlowNode.createLocalStorageNode(); var graph = [localStroageNode, localStroageNode, [localStroageNode]]; return graph; }; /** * Interface to reset the counter of graph nodes */ CFGBuilder.prototype.resetGraphNodeCounter = function () { "use strict"; factoryFlowNode.resetCounter(); }; var builder = new CFGBuilder(); module.exports = builder;
jotitan/music_server
src/music/share.go
<filename>src/music/share.go package music import ( "bytes" "encoding/json" "fmt" "github.com/jotitan/music_server/logger" "io/ioutil" "net/http" "net/url" "strconv" "strings" "time" ) // SharedSession represent a relation between an interface (original) and copy (clones) type SharedSession struct { // Id of the share, different from sessionID id int original *Device clones []*Device response http.ResponseWriter connected bool latency float64 // Used to monitor heartbeat of real service heartbeartChannel chan struct{} } func (ss *SharedSession)NotifyHeartbeat(sessionID string){ if strings.EqualFold(sessionID,ss.original.sessionID) && ss.heartbeartChannel != nil { ss.heartbeartChannel <- struct{}{} } } func (ss *SharedSession)startHeartbeatChecker(sharedSessions map[int]*SharedSession){ if ss.original.isBrowser { return } ss.heartbeartChannel = make(chan struct{}) go func(){ for{ select { case <-ss.heartbeartChannel: case <- time.NewTimer(3*time.Minute).C: // To late, stop shareSession delete(sharedSessions,ss.id) logger.GetLogger().Info("Remove service session, timeout",ss.id) return } } }() } func (ss SharedSession) isOriginal(sessionID string) bool { return strings.EqualFold(ss.original.sessionID, sessionID) } func (ss SharedSession) isClone(sessionID string) (bool, *Device) { for _, clone := range ss.clones { if strings.EqualFold(clone.sessionID, sessionID) { return true, clone } } return false, nil } func (ss * SharedSession)SetLatency(latency float64){ ss.latency = latency } func (ss SharedSession)GetLatency()float64{ return ss.latency } //ForwardEvent from a remote control. Possible event : add music, remove music, play music, play, pause, next, previous // Detect the sender from his session ID func (ss SharedSession) ForwardEvent(sessionID string, event, data string) { logger.GetLogger().Info("Receive event", event, "from", sessionID,"(",len(ss.clones),")") // Detect sender if ss.isOriginal(sessionID) { // Send to all clone for _, clone := range ss.clones { clone.send(event, data) } if strings.EqualFold(event, "close") { // Remove share removeSharedSession(ss.id) } } else { if v, dev := ss.isClone(sessionID); v { if strings.EqualFold(event, "close") { dev.connected = false ss.removeClone(sessionID) } else { newEvent, newData, success := ss.original.send(event, data) if success && !strings.EqualFold("",newEvent) { logger.GetLogger().Info("Send service new event", newEvent) // Send event to clone for _, clone := range ss.clones { clone.send(newEvent, newData) } } } } } } //Device represent a shared session type Device struct { name string response http.ResponseWriter sessionID string connected bool isBrowser bool // only if isBrowser false url string getMusicsInfo func([]int32) []map[string]string } func (d Device) send(event string, data string) (newEvent, message string,success bool) { if d.isBrowser { return "", "",d.sendBrowser(event, data) }else{ return d.sendService(event, data) } } func jsonToParams(data string)string{ mapData := make(map[string]string) json.Unmarshal([]byte(data),&mapData) params := make([]string,0,len(mapData)) for key,value := range mapData { params = append(params,fmt.Sprintf("%s=%s",key,value)) } return strings.Join(params,"&") } func extractFieldFromJson(data, field string)interface{}{ dataAsMap := make(map[string]interface{}) json.Unmarshal([]byte(data),&dataAsMap) return dataAsMap[field] } // Send event thru api func (d Device) sendService(event string, data string) (newEvent, message string, success bool) { // Work without data for pause, next, previous urlToCall := "" switch event { case "playMusic": // Extract field position from json and send as index urlToCall = fmt.Sprintf("%s/music/play?index=%d",d.url,int(extractFieldFromJson(data,"position").(float64))) case "play","pause","next","previous": urlToCall = fmt.Sprintf("%s/music/%s?%s",d.url,event,jsonToParams(data)) case "add": return d.postMusicsToServer(data) case "askPlaylist": urlToCall = fmt.Sprintf("%s/playlist/state",d.url) case "volumeUp","volumeDown": urlToCall = fmt.Sprintf("%s/control/%s",d.url,event) case "remove": urlToCall = fmt.Sprintf("%s/playlist/%s?index=%s",d.url,event,data) case "cleanPlaylist": urlToCall = fmt.Sprintf("%s/playlist/clean",d.url) case"list": urlToCall = fmt.Sprintf("%s/playlist/%s",d.url,event) case"radio": urlToCall = fmt.Sprintf("%s/radio/play?data=%s",d.url,url.PathEscape(data)) case"stopRadio": urlToCall = fmt.Sprintf("%s/radio/stop",d.url) default: return "","",false } resp,err := http.Get(urlToCall) return manageServiceResponse(event,data,resp,err) } func manageServiceResponse(event, originalData string,resp *http.Response,err error ) (string,string, bool){ if err == nil && resp.StatusCode == 200 { switch event { case "askPlaylist": if data,err := ioutil.ReadAll(resp.Body) ; err == nil { return "playlist",string(data),true } case "remove": return "remove",originalData,true case "cleanPlaylist": return "cleanPlaylist","",true } return "", "", true } return "", "",false } func (d Device)postMusicsToServer(data string)(string,string,bool){ // First unsplit musics := stringArrayToIntArray(data) // Load musics and create request musicsInfo := d.getMusicsInfo(musics) request := make([]map[string]string,len(musicsInfo)) for pos, musicInfo := range musicsInfo { request[pos] = map[string]string{ "id": musicInfo["id"], "path": musicInfo["path"], } } dataRequest,_ := json.Marshal(request) postUrl := fmt.Sprintf("%s/playlist/add",d.url) resp,err := http.Post(postUrl,"application/json",bytes.NewBuffer(dataRequest)) return manageServiceResponse("add","",resp,err) } func stringArrayToIntArray(data string)[]int32{ ids := strings.Split(data,",") musics := make([]int32,0,len(ids)) for _,strId := range ids { if id,err := strconv.ParseInt(strId, 10, 32) ; err == nil { musics = append(musics, int32(id)) } } return musics } func (d Device)isUp()bool{ if d.isBrowser { return true } resp,err := http.Get(fmt.Sprintf("%s/health",d.url)) return err == nil && resp.StatusCode == 200 } func (d Device) sendBrowser(event string, data string) (success bool) { defer func() { if e := recover(); e != nil { success = false } }() logger.GetLogger().Info("SEND", event, data, d.sessionID) if event != "" { d.response.Write([]byte(fmt.Sprintf("event: %s\n", event))) } d.response.Write([]byte("data: " + data + "\n\n")) d.response.(http.Flusher).Flush() success = true return } var sharedSessions = make(map[int]*SharedSession) // Create standard header for SSE func CreateSSEHeader(response http.ResponseWriter) { response.Header().Set("Content-Type", "text/event-stream") response.Header().Set("Cache-Control", "no-cache") response.Header().Set("Connection", "keep-alive") response.Header().Set("Access-Control-Allow-Origin", "*") } func removeSharedSession(id int) { logger.GetLogger().Info("Remove share", id) delete(sharedSessions, id) } //GetShareConnection return a shared connection from ID func GetShareConnection(id int) *SharedSession { if ss, exist := sharedSessions[id]; exist { return ss } return nil } func (ss *SharedSession) removeClone(sessionID string) { for i, d := range ss.clones { if strings.EqualFold(d.sessionID, sessionID) { ss.clones = append(ss.clones[:i], ss.clones[i+1:]...) logger.GetLogger().Info("Remove clone", sessionID, ", ", len(ss.clones), "left") return } } } // create new connection at each time, no connection recup func (ss *SharedSession) ConnectToShare(response http.ResponseWriter, deviceName, sessionID string) { // Check if original still exist if !ss.original.isUp() { logger.GetLogger().Error("Impossible to connect to share") return } var device *Device logger.GetLogger().Info("Connect clone", ss.id, "with sessionID",sessionID) // Check if sessionID exist CreateSSEHeader(response) if v, dev := ss.isClone(sessionID); !v { //check device exist device = &Device{name: deviceName, sessionID: sessionID, response: response, connected: true, isBrowser: true} ss.clones = append(ss.clones, device) } else { dev.response = response device = dev } device.send("id", fmt.Sprintf("%d", ss.id)) newEvent, data, success := ss.original.send("askPlaylist", "") if success && !strings.EqualFold(newEvent,"") { device.send(newEvent, data) } // Block until connexion is up checkConnection(device) ss.removeClone(sessionID) } func checkConnection(d *Device) { disconnect := false go func() { defer func() { if err := recover(); err != nil { disconnect = true } }() <-d.response.(http.CloseNotifier).CloseNotify() disconnect = true }() for { if !d.connected || disconnect { break } time.Sleep(5 * time.Second) } //logger.GetLogger().Info("End device", d.sessionID) } func CreateShareConnectionService(deviceName, url, sessionID string, getMusicsInfo func([]int32)[]map[string]string)int{ device := &Device{name: deviceName, sessionID: sessionID, connected: true, isBrowser: false, url : url, getMusicsInfo:getMusicsInfo} ss := &SharedSession{id: generateShareCode(), connected: true, original: device} // If shared session with device name exist, remove cleanShareDevice(deviceName) sharedSessions[ss.id] = ss logger.GetLogger().Info("Create share service", ss.id,url) ss.startHeartbeatChecker(sharedSessions) return ss.id } //CreateShareConnection create an original connexion func CreateShareConnection(response http.ResponseWriter, deviceName, sessionID string) { CreateSSEHeader(response) // Generate unique code to receive order device := &Device{name: deviceName, response: response, sessionID: sessionID, connected: true, isBrowser: true} ss := &SharedSession{id: generateShareCode(), connected: true, original: device} sharedSessions[ss.id] = ss logger.GetLogger().Info("Create share", ss.id) ss.original.send("id", fmt.Sprintf("%d", ss.id)) //computeLatency(ss.original,ss.id) checkConnection(device) removeSharedSession(ss.id) } func cleanShareDevice(deviceName string){ idToDelete := -1 for id,session := range sharedSessions { if strings.EqualFold(session.original.name,deviceName){ idToDelete = id break } } if idToDelete != -1 { delete(sharedSessions,idToDelete) } } type ShareInfo struct { Name string Id int } func GetSharesInfo() []ShareInfo { shares := make([]ShareInfo, 0, len(sharedSessions)) for id, ss := range sharedSessions { shares = append(shares, ShareInfo{Name: ss.original.name, Id: id}) } return shares } // Generate unique code func generateShareCode() int { return time.Now().Nanosecond() }
janhalasa/demoshop
src/main/java/com/halasa/demoshop/service/repository/ProductRepository.java
<reponame>janhalasa/demoshop<gh_stars>0 package com.halasa.demoshop.service.repository; import com.halasa.demoshop.service.domain.Product; import java.util.List; import java.util.Optional; public interface ProductRepository extends BasicReadOnlyRepository<Product, Long> { ListResult<Product> fulltextSearch(String searchTerm, Optional<Integer> limit, Optional<Integer> offset, List<String> fetches); }
saeschdivara/Adventurer-Conqueror-King-Mobile
lib/src/main/java/com/ack/adventureandconquer/game/creature/npc/dragon/OldDragonType.java
package com.ack.adventureandconquer.game.creature.npc.dragon; import com.ack.adventureandconquer.game.creature.npc.IsNpcType; import com.ack.adventureandconquer.game.creature.npc.Npc; import com.ack.adventureandconquer.game.creature.npc.unusual.Template; import java.util.List; /** * Created by saskyrar on 17/01/15. */ public class OldDragonType implements IsNpcType { public OldDragonType(String type,String breathAttack) { OldDragon.setDragonType(type,breathAttack); } @Override public boolean isLair(int number) { return number <= 20; } // protected static IsDice d6 = new D6(); // @Override // public List<Npc> getNormalWildnessEncounter() { // if (d6.role()<=4) { // return Template.getGroup(); // }else { // return GiantTemplate.getGroup(); // } // } @Override public List<Npc> getNormalWildnessEncounter() { return OldDragon.getGroup(); } @Override public String getNormalWildnessEncounterName() { return "Group"; } @Override public List<Npc> getLairWildnessEncounter() { return null; } @Override public String getLairWildnessEncounterName() { return null; } }
dn0000001/test-automation
taf/src/main/java/com/taf/automation/ui/support/AdHocHolidayManager.java
<reponame>dn0000001/test-automation package com.taf.automation.ui.support; import com.taf.automation.ui.support.util.AssertJUtil; import com.taf.automation.ui.support.util.Helper; import com.taf.automation.ui.support.util.Utils; import de.jollyday.HolidayManager; import de.jollyday.ManagerParameter; import de.jollyday.ManagerParameters; import de.jollyday.config.ChristianHoliday; import de.jollyday.config.EthiopianOrthodoxHoliday; import de.jollyday.config.Fixed; import de.jollyday.config.FixedWeekdayBetweenFixed; import de.jollyday.config.FixedWeekdayInMonth; import de.jollyday.config.FixedWeekdayRelativeToFixed; import de.jollyday.config.HebrewHoliday; import de.jollyday.config.HinduHoliday; import de.jollyday.config.Holiday; import de.jollyday.config.Holidays; import de.jollyday.config.IslamicHoliday; import de.jollyday.config.RelativeToEasterSunday; import de.jollyday.config.RelativeToFixed; import de.jollyday.config.RelativeToWeekdayInMonth; import de.jollyday.datasource.ConfigurationDataSource; import de.jollyday.impl.DefaultHolidayManager; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.ArrayList; import java.util.List; /** * Holiday Manager for Ad Hoc holidays (added by user on the fly) */ @SuppressWarnings("java:S3252") public class AdHocHolidayManager extends DefaultHolidayManager { private final ConfigurationDataSource customConfigurationDataSource; private final ManagerParameter customManagerParameter; public AdHocHolidayManager() { // Use existing holiday list to initialize HolidayManager hm = HolidayManager.getInstance(ManagerParameters.create("ca", null)); customConfigurationDataSource = Utils.deepCopy(hm.getConfigurationDataSource()); customManagerParameter = Utils.deepCopy(hm.getManagerParameter()); configuration = customConfigurationDataSource.getConfiguration(customManagerParameter); configuration.setDescription("AdHocHolidayManager"); configuration.setHierarchy("ad-hoc"); // We don't want any of the previous holidays as such remove them removeAllStoredHolidays(); configuration.getSubConfigurations().removeIf(item -> true); } /** * Remove all the stored holidays from the loading of the holiday manager used for setup */ private void removeAllStoredHolidays() { getStoredHolidays().getFixed().removeIf(item -> true); getStoredHolidays().getRelativeToFixed().removeIf(item -> true); getStoredHolidays().getRelativeToWeekdayInMonth().removeIf(item -> true); getStoredHolidays().getFixedWeekday().removeIf(item -> true); getStoredHolidays().getChristianHoliday().removeIf(item -> true); getStoredHolidays().getIslamicHoliday().removeIf(item -> true); getStoredHolidays().getFixedWeekdayBetweenFixed().removeIf(item -> true); getStoredHolidays().getFixedWeekdayRelativeToFixed().removeIf(item -> true); getStoredHolidays().getHinduHoliday().removeIf(item -> true); getStoredHolidays().getHebrewHoliday().removeIf(item -> true); getStoredHolidays().getEthiopianOrthodoxHoliday().removeIf(item -> true); getStoredHolidays().getRelativeToEasterSunday().removeIf(item -> true); } private Holidays getStoredHolidays() { return configuration.getHolidays(); } @Override public ConfigurationDataSource getConfigurationDataSource() { return customConfigurationDataSource; } @Override public ManagerParameter getManagerParameter() { return customManagerParameter; } /** * Add an Ad Hoc Holiday<BR> * <B>Notes:</B> * <OL> * <LI>There are 2 different Holiday classes in this library. This method is using de.jollyday.config.Holiday * &amp; not the de.jollyday.Holiday</LI> * <LI>For convenience the base holiday class is used for the parameter and cast to the concrete holiday by * the method</LI> * </OL> * <B>Supported Holiday Types/Classes:</B> * <OL> * <LI>Fixed</LI> * <LI>RelativeToFixed</LI> * <LI>RelativeToWeekdayInMonth</LI> * <LI>FixedWeekdayInMonth</LI> * <LI>ChristianHoliday</LI> * <LI>IslamicHoliday</LI> * <LI>FixedWeekdayBetweenFixed</LI> * <LI>FixedWeekdayRelativeToFixed</LI> * <LI>HinduHoliday</LI> * <LI>HebrewHoliday</LI> * <LI>EthiopianOrthodoxHoliday</LI> * <LI>RelativeToEasterSunday</LI> * </OL> * * @param holiday - Concrete Holiday to add from supported types * @return AdHocHolidayManager */ public AdHocHolidayManager withHoliday(Holiday holiday) { if (Fixed.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getFixed().add((Fixed) holiday); } else if (RelativeToFixed.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getRelativeToFixed().add((RelativeToFixed) holiday); } else if (RelativeToWeekdayInMonth.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getRelativeToWeekdayInMonth().add((RelativeToWeekdayInMonth) holiday); } else if (FixedWeekdayInMonth.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getFixedWeekday().add((FixedWeekdayInMonth) holiday); } else if (ChristianHoliday.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getChristianHoliday().add((ChristianHoliday) holiday); } else if (IslamicHoliday.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getIslamicHoliday().add((IslamicHoliday) holiday); } else if (FixedWeekdayBetweenFixed.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getFixedWeekdayBetweenFixed().add((FixedWeekdayBetweenFixed) holiday); } else if (FixedWeekdayRelativeToFixed.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getFixedWeekdayRelativeToFixed().add((FixedWeekdayRelativeToFixed) holiday); } else if (HinduHoliday.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getHinduHoliday().add((HinduHoliday) holiday); } else if (HebrewHoliday.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getHebrewHoliday().add((HebrewHoliday) holiday); } else if (EthiopianOrthodoxHoliday.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getEthiopianOrthodoxHoliday().add((EthiopianOrthodoxHoliday) holiday); } else if (RelativeToEasterSunday.class.isAssignableFrom(holiday.getClass())) { getStoredHolidays().getRelativeToEasterSunday().add((RelativeToEasterSunday) holiday); } else { AssertJUtil.fail("Unsupported Holiday Implementation: " + holiday.getClass()); } return this; } @Override public boolean equals(Object object) { if (object == null) { return false; } if (object.getClass() != this.getClass()) { return false; } AssertAggregator aggregator = new AssertAggregator(); Helper.assertThat(aggregator, getStoredHolidays(), ((AdHocHolidayManager) object).getStoredHolidays()); return aggregator.getFailureCount() == 0; } @Override public int hashCode() { List<String> excludeFields = new ArrayList<>(); return HashCodeBuilder.reflectionHashCode(this, excludeFields); } }
ChipiHenzj/androidLessons
MyApplication/app/src/main/java/com/example/tetianapriadko/myapplication/Lesson42.java
package com.example.tetianapriadko.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class Lesson42 extends AppCompatActivity { String[] names = { "Maris", "Agita", "Ricards", "Janis", "Agnese", "Laima", "Viesturs", "Lauris", "Guntars", "Arvis", "Gatis", "Gita", "Davis", "Kaspars", "Laila", "Kristaps", "Laura", "Liga", "Liene", "Inga", "Martins", "Zanda", "Sandris"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lesson42); ListView lvMain = (ListView) findViewById(R.id.lvMain); // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, // R.layout.activity_lesson42_1, names); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names); lvMain.setAdapter(adapter); } }
tobireinhard/cbmc
regression/goto-instrument/slice_general007/main.c
<gh_stars>100-1000 // This is a benchmark for the full-slicer // This is a simplified version of end-to-end regression tests // 'general005', 'general006', and 'general007' of the security-scanner. #include <assert.h> #include <stdbool.h> #include <stdlib.h> struct object { bool Tainted_stream; }; struct java_array { struct object super; char *data; int length; }; struct java_array_wrapper { struct java_array super; bool Tainted_byte_array; }; struct InputStream { struct object super; struct java_array_wrapper *s; }; struct ServletInputStream { struct InputStream super; }; struct HttpServletRequest { struct ServletInputStream *s; }; void getBytes(struct java_array_wrapper *data, struct InputStream *in) { // These 2 lines are wrongly sliced away! if(in->super.Tainted_stream) data->Tainted_byte_array = true; } struct InputStream *getInputStream(struct HttpServletRequest *this) { return &this->s->super; } struct InputStream *getInStream(struct HttpServletRequest *request) { struct InputStream *x = getInputStream(request); x->super.Tainted_stream = true; return x; } extern void *CProver_nondetWithNull(); int main() { struct HttpServletRequest *request = CProver_nondetWithNull(); struct InputStream *in0 = getInStream(request); struct InputStream *in = in0; struct java_array_wrapper *data, *tmp1 = (struct java_array_wrapper *)malloc(sizeof(struct java_array_wrapper)); tmp1->Tainted_byte_array = false; tmp1->super.super.Tainted_stream = false; data = tmp1; getBytes(data, in); if(data->Tainted_byte_array) assert(false); return 0; }
irresi/algostudy
acmicpcnet/4196.cpp
<filename>acmicpcnet/4196.cpp #include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; const int inf=1e9+3; const int msz=1e5+3; #define all(x) (x).begin(),(x).end() #define sync() {ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);} //do not use int n,m,In[msz],chk[msz],ans,dep[msz]; vector<int> ed[msz],red[msz]; stack<int> st; void dfs(int num){ chk[num]=0; for(int nxt : ed[num])if(chk[nxt]){ dfs(nxt); } st.push(num); } void rdfs(int num, int rep){ chk[num]=rep; for(int nxt : red[num])if(!chk[nxt]){ rdfs(nxt,rep); } return; } int main() { int i,a,b,tc; cin>>tc; while(tc--){ cin>>n>>m; ans=0; fill(chk+1,chk+n+1,1); fill(In+1,In+n+1,0); fill(dep+1,dep+n+1,0); for(i=1;i<=n;i++){ ed[i].clear(); red[i].clear(); } for(i=1;i<=m;i++){ cin>>a>>b; ed[a].push_back(b); red[b].push_back(a); } for(i=1;i<=n;i++)if(chk[i]){ dfs(i); } while(!st.empty()){ int cur = st.top(); st.pop(); if(!chk[cur]){ rdfs(cur,cur); } } for(i=1;i<=n;i++){ for(int nxt : ed[i])if(chk[nxt]!=chk[i]){ dep[chk[nxt]]=1; } } for(i=1;i<=n;i++) ans+=(dep[i]==0 && chk[i]==i); cout<<ans<<'\n'; } return 0; }
dengliming/stagemonitor
stagemonitor-core/src/main/java/org/stagemonitor/core/instrument/CachedClassLoaderMatcher.java
<filename>stagemonitor-core/src/main/java/org/stagemonitor/core/instrument/CachedClassLoaderMatcher.java package org.stagemonitor.core.instrument; import net.bytebuddy.matcher.ElementMatcher; public class CachedClassLoaderMatcher extends ElementMatcher.Junction.AbstractBase<ClassLoader> { private final WeakConcurrentMap<ClassLoader, Boolean> cache = new WeakConcurrentMap.WithInlinedExpunction<ClassLoader, Boolean>(); private final ElementMatcher<ClassLoader> delegate; public static ElementMatcher.Junction.AbstractBase<ClassLoader> cached(ElementMatcher<ClassLoader> delegate) { return new CachedClassLoaderMatcher(delegate); } private CachedClassLoaderMatcher(ElementMatcher<ClassLoader> delegate) { this.delegate = delegate; } @Override public boolean matches(ClassLoader target) { final Boolean result = cache.get(target); if (result != null) { return result; } else { final boolean delegateResult = delegate.matches(target); cache.put(target, delegateResult); return delegateResult; } } }
LJW123/YiLianMall
YiLian/src/main/java/com/yilian/mall/entity/MTComboDetailsEntity.java
package com.yilian.mall.entity; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by liuyuqi on 2016/12/8 0008. * 套餐详情 */ public class MTComboDetailsEntity extends BaseEntity { /** * login_status : * yet_collect : * data : {"package_id":"","package_name":"","package_icon":[{"path":""},{}],"price":"","sell_count":"","evaluate":"","full_minus_fee":"","merchant_info":{"merchant_id":"","merchant_name":"","merchant_desp":"","merchant_longitude":"","merchant_latitude":"","merchant_address":"","merchant_contact":""},"tags":[{"tags_name":"","tags_count":""},{}],"package_info":[{"package_name":"","content":[{"name":"","number":"","cost":""},{}]},{}],"notes_info":{"use_rules":"","usable_time":"","effective_time":""},"evaluate_count":"","evaluate_list":[{"name":"","image_url":"","evaluate":"","commit_date":"","taste":"","environment":"","service":"","consumer_comment":"","merchant_comment":"","album":""}]} */ @SerializedName("login_status") public String loginStatus; @SerializedName("yet_collect") public String yetCollect; /** * package_id : * package_name : * package_icon : [{"path":""},{}] * price : * sell_count : * evaluate : * full_minus_fee : * merchant_info : {"merchant_id":"","merchant_name":"","merchant_desp":"","merchant_longitude":"","merchant_latitude":"","merchant_address":"","merchant_contact":""} * tags : [{"tags_name":"","tags_count":""},{}] * package_info : [{"package_name":"","content":[{"name":"","number":"","cost":""},{}]},{}] * notes_info : {"use_rules":"","usable_time":"","effective_time":""} * evaluate_count : * evaluate_list : [{"name":"","image_url":"","evaluate":"","commit_date":"","taste":"","environment":"","service":"","consumer_comment":"","merchant_comment":"","album":""}] */ @SerializedName("data") public DataBean data; public class DataBean { @SerializedName("return_integral") public String returnIntegral; @SerializedName("package_id") public String packageId; @SerializedName("package_name") public String packageName; @SerializedName("price") public String price; @SerializedName("voucher") public int voucher; @SerializedName("is_profit") public int isProfit; @SerializedName("sell_count") public String sellCount; @SerializedName("evaluate") public String evaluate; @SerializedName("full_minus_fee") public String fullMinusFee; @SerializedName("scope") public String scope; @SerializedName("is_delivery") public String isDelivery; @SerializedName("delivery_amount") public String deliveryAmount; @SerializedName("price_total") public String priceTotal; /** * merchant_id : * merchant_name : * merchant_desp : * merchant_longitude : * merchant_latitude : * merchant_address : * merchant_contact : */ @SerializedName("merchant_info") public MerchantInfoBean merchantInfo; /** * use_rules : * usable_time : * effective_time : */ @SerializedName("notes_info") public NotesInfoBean notesInfo; @SerializedName("evaluate_count") public String evaluateCount; /** * path : */ @SerializedName("package_icon") public List<PackageIconBean> packageIcon; /** * tags_name : * tags_count : */ @SerializedName("tags") public List<TagsBean> tags; /** * package_name : * content : [{"name":"","number":"","cost":""},{}] */ @SerializedName("package_info") public List<PackageInfoBean> packageInfo; /** * name : * image_url : * evaluate : * commit_date : * taste : * environment : * service : * consumer_comment : * merchant_comment : * album : */ @SerializedName("evaluate_list") public List<EvaluateListBean> evaluateList; public class MerchantInfoBean { @SerializedName("merchant_id") public String merchantId; @SerializedName("merchant_name") public String merchantName; @SerializedName("merchant_desp") public String merchantDesp; @SerializedName("merchant_longitude") public String merchantLongitude; @SerializedName("merchant_latitude") public String merchantLatitude; @SerializedName("merchant_address") public String merchantAddress; @SerializedName("merchant_contact") public String merchantContact; } public class NotesInfoBean { @SerializedName("use_rules") public String useRules; @SerializedName("usable_time") public String usableTime; @SerializedName("effective_time") public String effectiveTime; } public class PackageIconBean { @SerializedName("path") public String path; } public class TagsBean { @SerializedName("tags_name") public String tagsName; @SerializedName("tags_count") public String tagsCount; @Override public String toString() { return "TagsBean{" + "tagsName='" + tagsName + '\'' + ", tagsCount='" + tagsCount + '\'' + '}'; } } public class PackageInfoBean { @SerializedName("package_name") public String packageName; /** * name : * number : * cost : */ @SerializedName("content") public List<ContentBean> content; public class ContentBean { @SerializedName("name") public String name; @SerializedName("number") public String number; @SerializedName("cost") public String cost; } } public class EvaluateListBean { @SerializedName("name") public String name; @SerializedName("image_url") public String imageUrl; @SerializedName("evaluate") public String evaluate; @SerializedName("commit_date") public String commitDate; @SerializedName("taste") public String taste; @SerializedName("environment") public String environment; @SerializedName("service") public String service; @SerializedName("consumer_comment") public String consumerComment; @SerializedName("merchant_comment") public String merchantComment; @SerializedName("album") public String album; } } }
golionko/maze_game
src/main/java/com/game/maze/persist/repository/LabyrinthRoomRepository.java
package com.game.maze.persist.repository; import com.game.maze.persist.entity.LabyrinthRoom; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; public interface LabyrinthRoomRepository extends JpaRepository<LabyrinthRoom, Long> { LabyrinthRoom findByXLocationAndYLocationAndZLocation(Long xLocation, Long yLocation, Long zLocation); LabyrinthRoom findByXOriginAndYOriginAndZOrigin(Long xOrigin, Long yOrigin, Long zOrigin); @Query(value = "SELECT count(*) FROM labyrinth", nativeQuery = true) Long findNumberOfRooms(); }
jmgc/pyston
test/extra/routes_test.py
import os, sys, subprocess, shutil sys.path.append(os.path.dirname(__file__) + "/../lib") from test_helper import create_virtenv, run_test ENV_NAME = "routes_test_env_" + os.path.basename(sys.executable) SRC_DIR = os.path.abspath(os.path.join(ENV_NAME, "src")) PYTHON_EXE = os.path.abspath(os.path.join(ENV_NAME, "bin", "python")) pkg = ["nose==1.3.7", "paste==2.0.2", "six==1.10.0"] pkg += ["-e", "git+https://github.com/bbangert/routes.git@v1.7.3#egg=Routes"] create_virtenv(ENV_NAME, pkg, force_create = True) ROUTES_DIR = os.path.abspath(os.path.join(SRC_DIR, "routes")) expected = [{ "ran" : 141 }] expected_log_hash = ''' ggSACQMCAQZABAAUIIMCEABCAAAgQAACDAUABAKgAAgEAAECIAAgIAgBABQICCDoIkNQgQAAIQQE xACSGAIAoIAAAgAQAQEIAAAQAFhWACgBBHAEYAAgIBQAUGAAAAIABCAEQEgAAAFAACAAAo5EgBAA AAAQCSBIURAAwDCAkQA= ''' run_test([PYTHON_EXE, "setup.py", "test"], cwd=ROUTES_DIR, expected=expected, expected_log_hash=expected_log_hash)
jiapeish/leetcode-c-cpp
reference/Algorithms-in-a-Nutshell-master/Releases/ADK/Deployment/JavaCode/src/algs/model/data/points/UniformGenerator.java
<reponame>jiapeish/leetcode-c-cpp package algs.model.data.points; import algs.model.IPoint; import algs.model.data.Generator; import algs.model.twod.TwoDPoint; /** * Generators of sample data points within the [0,1] unit square. * * @author <NAME> * @version 1.0, 6/15/08 * @since 1.0 */ public class UniformGenerator extends Generator<IPoint> { /** parameters for the constructor. */ private String[] params = new String [0]; @Override public String[] parameters() { return params; } /** * Provide reflective behavior to construct instance of generator given * an array of string arguments. */ @Override public Generator<IPoint> construct(String[] args) { return new UniformGenerator(); } /** * Generate a set of uniform random points in the range: * * <x = [0.0, 1.0), y = [0.0, 1.0) > * * @param size number of points to generate. */ public IPoint[] generate (int size) { IPoint[] points = new TwoDPoint[size]; // points. for (int i = 0; i < size; i++) { double x = Math.random(); double y = Math.random(); points[i] = new TwoDPoint(x, y); } return points; } }
overflow-stack/actframework
src/main/java/act/inject/genie/SingletonScope.java
package act.inject.genie; import act.app.App; import org.osgl.inject.ScopeCache; public class SingletonScope implements ScopeCache.SingletonScope { public static final SingletonScope INSTANCE = new act.inject.genie.SingletonScope(); private App app; public SingletonScope() { app = App.instance(); } @Override public <T> T get(Class<T> aClass) { return app.singleton(aClass); } @Override public <T> void put(Class<T> aClass, T t) { app.registerSingleton(aClass, t); } }
sunshl/incubator-weex
weex_core/Source/include/JavaScriptCore/runtime/NumberConstructor.h
/** * 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. */ #pragma once #include "InternalFunction.h" namespace JSC { class NumberPrototype; class GetterSetter; class NumberConstructor : public InternalFunction { public: typedef InternalFunction Base; static const unsigned StructureFlags = Base::StructureFlags | ImplementsHasInstance | HasStaticPropertyTable; static NumberConstructor* create(VM& vm, Structure* structure, NumberPrototype* numberPrototype, GetterSetter*) { NumberConstructor* constructor = new (NotNull, allocateCell<NumberConstructor>(vm.heap)) NumberConstructor(vm, structure); constructor->finishCreation(vm, numberPrototype); return constructor; } DECLARE_INFO; static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto) { return Structure::create(vm, globalObject, proto, TypeInfo(ObjectType, StructureFlags), info()); } protected: void finishCreation(VM&, NumberPrototype*); private: NumberConstructor(VM&, Structure*); static ConstructType getConstructData(JSCell*, ConstructData&); static CallType getCallData(JSCell*, CallData&); }; } // namespace JSC
rontrek/softpixel
sources/SceneGraph/Animation/spAnimation.hpp
/* * Animation interface header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by <NAME>) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_ANIMATION_H__ #define __SP_ANIMATION_H__ #include "Base/spStandard.hpp" #include "SceneGraph/spSceneNode.hpp" #include "SceneGraph/Animation/spAnimationPlayback.hpp" #include <list> namespace sp { namespace scene { //! Types of animation classes. enum EAnimationTypes { ANIMATION_NODE, //!< Node animation. An scene node will be transformed (position, rotation and scale). ANIMATION_MORPHTARGET, //!< Morph-target animation. Vertices of a mesh object will be transformed (vertex coordinate and normal). ANIMATION_SKELETAL, //!< Skeletal animation. Consists of a skeleton (AnimationSkeleton object) which holds all joints (AnimationJoint objects). }; //! Animation flags. enum EAnimationFlags { ANIMFLAG_NO_GROUPING = 0x01, //!< Disables the automatic group-animation for skeletal-animations. ANIMFLAG_NO_TRANSFORMATION = 0x02, //!< Disables the vertex transformation for skeletal-animations. }; /** Animation base class. This is the base class for animation objects. It has the fundamental functions like playing and updating the animation. \see SkeletalAnimation \see NodeAnimation \see MorphTargetAnimation \ingroup group_animation */ class SP_EXPORT Animation { public: virtual ~Animation(); /* === Functions === */ /** Plays the animation. \param Mode: Specifies the animation mode. \param FirstFrame: Specifies the first animation frame. \param LastFrame: Specifies the last animation frame. This can also be smaller than the first frame. By default ANIM_IGNORE_FRAME which means that all frames will be played. \return True if the animation could be played. Otherwise the first- and last frame are equal or there are only less than 2 keyframes. */ virtual bool play(const EAnimPlaybackModes Mode, u32 FirstFrame = 0, u32 LastFrame = ANIM_LAST_FRAME); //! Pauses or resumes the animation. virtual void pause(bool IsPaused = true); //! Stops the animation. virtual void stop(bool IsReset = false); //! Clears all keyframes. virtual void clearKeyframes() = 0; //! Sets the new frame index. Should not be used while the animation is playing. virtual void setFrame(u32 Index); //! Updates the animation process if currently it's playing. virtual void updateAnimation(SceneNode* Node) = 0; //! Returns the count of keyframes. virtual u32 getKeyframeCount() const = 0; //! Makes an interpolation between the two given frames. virtual void interpolate(u32 IndexFrom, u32 IndexTo, f32 Interpolation) = 0; //! Makes an interpolation over the given sequence. In this case the first frame must be smaller then the last frame! virtual bool interpolateRange(u32 FirstFrame, u32 LastFrame, f32 Interpolation); //! Makes an blended interpolation between the two given playback states. This can be used for 'animation blending'. virtual void interpolateBlended( const AnimationPlayback &PlaybackFrom, const AnimationPlayback &PlaybackTo, f32 BlendingFactor ); /** Adds the specified scene node to the animatable object list. All these objects will be animated when this animation is being played using SceneGraph::updateAnimations. */ virtual void addSceneNode(SceneNode* Object); //! Removes the specified scene node from the animatable object list. virtual void removeSceneNode(SceneNode* Object); //! Removes the animatable object list. virtual void clearSceneNodes(); /** Copies the whole animation. \return Pointer to the new animation object. \note You have to delete this pointer by yourself! */ virtual void copy(const Animation* Other) = 0; /* === Inline functions === */ //! Returns the type of animation: Node-, MorphTarget- or SkeletalAnimation. inline EAnimationTypes getType() const { return Type_; } //! Sets the animation name. inline void setName(const io::stringc &Name) { Name_ = Name; } //! Returns the animation name. inline const io::stringc& getName() const { return Name_; } /** Sets the animation flags. \see EAnimationFlags */ inline void setFlags(s32 Flags) { Flags_ = Flags; } //! Returns the animation flags. By default 0. inline s32 getFlags() const { return Flags_; } //! Returns true if the animation is currently playing. inline bool playing() const { return Playback_.playing(); } //! Returns the current frame index. inline u32 getFrame() const { return Playback_.getFrame(); } //! Returns the minimal keyframe index. inline u32 getMinFrame() const { return MinFrame_; } //! Returns the maximal keyframe index. inline u32 getMaxFrame() const { return MaxFrame_; } //! Sets the new frame interpolation. inline void setInterpolation(f32 Interpolation) { Playback_.setInterpolation(Interpolation); } //! Returns the current frame interpolation. inline f32 getInterpolation() const { return Playback_.getInterpolation(); } //! Returns the current animation playback mode. inline EAnimPlaybackModes getPlaybackMode() const { return Playback_.getMode(); } //! Sets the new playback speed (by default 1.0). inline void setSpeed(f32 Speed) { Playback_.setSpeed(Speed); } inline f32 getSpeed() const { return Playback_.getSpeed(); } //! Returns a constant reference to the playback state object. inline const AnimationPlayback& getPlayback() const { return Playback_; } //! Returns a reference to the playback state object. inline AnimationPlayback& getPlayback() { return Playback_; } //! Returns the animatable scene node list. inline const std::list<SceneNode*>& getSceneNodeList() const { return SceneNodes_; } protected: /* === Functions === */ Animation(const EAnimationTypes Type); //! Updates the playback process with the specified interpolation speed. virtual void updatePlayback(f32 Speed); //! Returns the valid keyframe index. u32 getValidFrame(u32 Index) const; void copyBase(const Animation* Other); /* === Members === */ u32 MinFrame_, MaxFrame_; AnimationPlayback Playback_; s32 Flags_; private: /* === Members === */ EAnimationTypes Type_; io::stringc Name_; std::list<SceneNode*> SceneNodes_; }; } // /namespace scene } // /namespace sp #endif // ================================================================================
fiverr/passable
src/core/test/index.js
<reponame>fiverr/passable import { FAIL } from '../../constants'; import { singleton } from '../../lib'; import { isTestFn, TestObject } from './lib'; /** * Run async test. * @param {TestObject} testObject A TestObject instance. */ export const runAsync = (testObject) => { const { fieldName, testFn, statement, ctx } = testObject; ctx.result.markAsync(fieldName); const done = () => { testObject.clearPending(); if (!hasRemainingPendingTests(ctx, fieldName)) { ctx.result.markAsDone(fieldName); } if (!hasRemainingPendingTests(ctx)) { ctx.result.markAsDone(); } }; const fail = (rejectionMessage) => { testObject.statement = typeof rejectionMessage === 'string' ? rejectionMessage : statement; if (ctx.pending.includes(testObject)) { testObject.fail(); } done(); }; try { testFn.then(done, fail); } catch (e) { fail(); } }; /** * Checks if there still are remaining pending tests for given criteria * @param {Object} ctx Parent context * @param {String} [fieldName] Name of the field to test against * @return {Boolean} */ const hasRemainingPendingTests = (ctx, fieldName) => { if (!ctx.pending.length) { return false; } if (fieldName) { return ctx.pending.some((testObject) => testObject.fieldName === fieldName); } return !!ctx.pending.length; }; /** * Performs "shallow" run over test functions, assuming sync tests only. * @param {TestObject} testObject TestObject instance. * @return {*} Result from test function */ const preRun = (testObject) => { let result; try { result = testObject.testFn(); } catch (e) { result = false; } if (result === false) { testObject.fail(); } return result; }; /** * Registers test, if async - adds to pending array * @param {TestObject} testObject A TestObject Instance. */ const register = (testObject) => { const { testFn, ctx, fieldName } = testObject; let pending = false; let result; if (ctx.specific.excludes(fieldName)) { ctx.result.addToSkipped(fieldName); return; } ctx.result.initFieldCounters(fieldName); ctx.result.bumpTestCounter(fieldName); if (testFn && typeof testFn.then === 'function') { pending = true; } else { result = preRun(testObject); } if (result && typeof result.then === 'function') { pending = true; testObject.testFn = result; } if (pending) { testObject.setPending(); } }; /** * Test function used by consumer to provide their own validations. * @param {String} fieldName Name of the field to test. * @param {String} [statement] The message returned in case of a failure. * @param {function | Promise} testFn The actual test callback or promise. * @param {String} [severity] Indicates whether the test should fail or warn. * @return {TestObject} A TestObject instance. */ const test = (fieldName, ...args) => { let statement, testFn, severity; if (typeof args[0] === 'string') { [statement, testFn, severity] = args; } else if (isTestFn(args[0])) { [testFn, severity] = args; } if (!isTestFn(testFn)) { return; } const testObject = new TestObject( singleton.use().ctx, fieldName, statement, testFn, severity || FAIL ); register(testObject); return testObject; }; export default test;
hiepndd/keva
core/src/main/java/dev/keva/core/aof/AOFManager.java
package dev.keva.core.aof; import dev.keva.core.command.mapping.CommandMapper; import dev.keva.core.command.mapping.CommandWrapper; import dev.keva.core.config.KevaConfig; import dev.keva.ioc.annotation.Autowired; import dev.keva.ioc.annotation.Component; import dev.keva.protocol.resp.Command; import dev.keva.util.hashbytes.BytesKey; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.util.List; @Component @Slf4j public class AOFManager { private final KevaConfig kevaConfig; private final CommandMapper commandMapper; private final AOFContainer aof; @Autowired public AOFManager(KevaConfig kevaConfig, CommandMapper commandMapper, AOFContainer aof) { this.kevaConfig = kevaConfig; this.commandMapper = commandMapper; this.aof = aof; } public void init() { if (!kevaConfig.getAof()) { return; } try { List<Command> commands = aof.read(); if (commands != null) { log.info("Processing {} commands from AOF file", commands.size()); for (Command command : commands) { byte[] name = command.getName(); CommandWrapper commandWrapper = commandMapper.getMethods().get(new BytesKey(name)); if (commandWrapper != null) { commandWrapper.execute(null, command); } } log.info("Recovered {} commands from AOF file", commands.size()); } } catch (IOException | InterruptedException e) { log.error("Cannot read AOF file", e); } aof.init(); } }
Aran1018/Sweet
app/src/main/java/com/lucky/sweet/activity/MyLikeStoreActivity.java
package com.lucky.sweet.activity; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.TextView; import com.lucky.sweet.R; import com.lucky.sweet.adapter.HisOrderAdapter; import com.lucky.sweet.adapter.MyLikeStoreAdapter; import com.lucky.sweet.entity.PersonCollectInfo; import com.lucky.sweet.service.CommunicationService; import com.lucky.sweet.widgets.Title; import com.lucky.sweet.widgets.ToolBar; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.List; /** * Created by Qiuyue on 2018/3/8. */ // ╭︿︿︿╮ ╭︿︿︿╮ ╭︿︿︿╮ // {/ o o /} {/ . . /} {/ ︿︿ /} // ( (oo) ) ( (oo) ) ( (oo) ) // ︶︶︶ ︶︶︶ ︶︶︶ public class MyLikeStoreActivity extends BaseActivity { private Title title = null; private ListView lv_likeStore; private TextView collect_name; @Override void onServiceBind(CommunicationService.MyBinder myBinder) { myBinder.getPersonCollect(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mylikestore); setIsBindEventBus(); initTitle(); initViews(); } private void initViews() { lv_likeStore = findViewById(R.id.lv_likeStore); collect_name = findViewById(R.id.tv_person_collec_shop_show); } private void initTitle() { ToolBar toolBar = new ToolBar(this); toolBar.setColorNewBar(getResources().getColor(R.color.white), 0); title = (Title) findViewById(R.id.title); title.setTitleNameStr("收藏店铺"); Title.ButtonInfo buttonLeft = new Title.ButtonInfo(true, Title .BUTTON_LEFT, R.drawable.selector_btn_titleback, null); title.setOnTitleButtonClickListener(new Title .OnTitleButtonClickListener() { @Override public void onClick(int id, Title.ButtonViewHolder viewHolder) { switch (id) { case Title.BUTTON_LEFT: finish(); goPreAnim(); break; } } }); title.mSetButtonInfo(buttonLeft); } @Subscribe(threadMode = ThreadMode.MAIN) public void Event(PersonCollectInfo info) { List<PersonCollectInfo.CollectListBean> collect_list = info.getCollect_list(); if (collect_list.size()!=0) { collect_name.setVisibility(View.GONE); } lv_likeStore.setAdapter(new MyLikeStoreAdapter(info.getCollect_list(), this)); } }
talkable/talkable-ruby
lib/talkable/integration.rb
module Talkable class << self def register_affiliate_member(params = {}) register_origin(Talkable::API::Origin::AFFILIATE_MEMBER, params) end def register_purchase(params = {}) register_origin(Talkable::API::Origin::PURCHASE, params) end def register_event(params = {}) register_origin(Talkable::API::Origin::EVENT, params) end private def register_origin(origin_type, params = {}) origin_params = default_params.merge(params) result = Talkable::API::Origin.create(origin_type, origin_params) origin = Talkable::Origin.parse(result) origin end def default_params { uuid: Talkable.visitor_uuid, r: Talkable.current_url, } end end end
rnarla123/aliyun-openapi-java-sdk
aliyun-java-sdk-dt-oc-info/src/main/java/com/aliyuncs/dt_oc_info/transform/v20200401/GetCompanyPartnersListThreeResponseUnmarshaller.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.dt_oc_info.transform.v20200401; import java.util.ArrayList; import java.util.List; import com.aliyuncs.dt_oc_info.model.v20200401.GetCompanyPartnersListThreeResponse; import com.aliyuncs.transform.UnmarshallerContext; public class GetCompanyPartnersListThreeResponseUnmarshaller { public static GetCompanyPartnersListThreeResponse unmarshall(GetCompanyPartnersListThreeResponse getCompanyPartnersListThreeResponse, UnmarshallerContext _ctx) { getCompanyPartnersListThreeResponse.setRequestId(_ctx.stringValue("GetCompanyPartnersListThreeResponse.RequestId")); getCompanyPartnersListThreeResponse.setCode(_ctx.integerValue("GetCompanyPartnersListThreeResponse.Code")); getCompanyPartnersListThreeResponse.setMessage(_ctx.stringValue("GetCompanyPartnersListThreeResponse.Message")); getCompanyPartnersListThreeResponse.setTotal(_ctx.integerValue("GetCompanyPartnersListThreeResponse.Total")); List<String> data = new ArrayList<String>(); for (int i = 0; i < _ctx.lengthValue("GetCompanyPartnersListThreeResponse.Data.Length"); i++) { data.add(_ctx.stringValue("GetCompanyPartnersListThreeResponse.Data["+ i +"]")); } getCompanyPartnersListThreeResponse.setData(data); return getCompanyPartnersListThreeResponse; } }
mrbrackins/testt
extensions/shoutem.cms/server/src/components/importer-csv-form/index.js
import ImporterCsvForm from './ImporterCsvForm'; export default ImporterCsvForm;
bjornharvold/bearchoke
bearchoke-backend/bearchoke-persistence/bearchoke-persistence-mongo/src/main/java/com/bearchoke/platform/persistence/mongo/document/AbstractDocument.java
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bearchoke.platform.persistence.mongo.document; import org.apache.commons.lang3.builder.ToStringBuilder; import org.springframework.data.annotation.Id; import java.time.LocalDateTime; /** * Created by <NAME> * Date: 7/8/11 * Time: 5:05 PM * Responsibility: */ public abstract class AbstractDocument { /** ID */ @Id private String id; /** Created date */ private LocalDateTime createdDate; /** Last update */ private LocalDateTime lastUpdate; public AbstractDocument() { } public AbstractDocument(AbstractDocument doc) { id = doc.id; createdDate = doc.createdDate; lastUpdate = doc.lastUpdate; } public String getId() { return id; } public void setId(String id) { this.id = id; } public LocalDateTime getCreatedDate() { return createdDate; } public void setCreatedDate(LocalDateTime createdDate) { this.createdDate = createdDate; } public LocalDateTime getLastUpdate() { return lastUpdate; } public void setLastUpdate(LocalDateTime lastUpdate) { this.lastUpdate = lastUpdate; } public String getIdAsString() { String result = null; if (id != null) { result = id.toString(); } return result; } @Override public String toString() { return new ToStringBuilder(this) .append("id", id) .append("createdDate", createdDate) .append("lastUpdate", lastUpdate) .toString(); } }
marcinzh/turbolift
modules/core/src/main/scala/turbolift/abstraction/HandlerExtensions.scala
package turbolift.abstraction import scala.util.{Try, Success, Failure} private [abstraction] trait HandlerExtensions: extension [S, L, N](thiz: Handler[(S, _), L, N]) def eval: Handler.Id[L, N] = dropState def exec: Handler[[X] =>> S, L, N] = justState def justState: Handler[[X] =>> S, L, N] = thiz.map([A] => (pair: (S, A)) => pair._1) def dropState: Handler.Id[L, N] = thiz.map([A] => (pair: (S, A)) => pair._2) def mapState[S2](f: S => S2): Handler[(S2, _), L, N] = thiz.map([A] => (pair: (S, A)) => val (s, a) = pair (f(s), a) ) def ***![S2, L2, N2](that: Handler[(S2, _), L2, N2]): Handler[((S, S2), _), L & L2, N & N2] = thiz.composeWith(that).map([A] => (pairs: (S2, (S, A))) => val (s2, (s, a)) = pairs ((s, s2), a) ) extension [L, N](thiz: Handler[Option, L, N]) def toEither[E](e: => E): Handler[Either[E, _], L, N] = thiz.map([A] => (result: Option[A]) => result.toRight(e)) def toTry(e: => Throwable): Handler[Try, L, N] = thiz.map([A] => (result: Option[A]) => result.fold[Try[A]](Failure(e))(Success(_))) def getOrElse(default: => Nothing): Handler.Id[L, N] = thiz.map([A] => (result: Option[A]) => result.getOrElse(default)) def getOrDie(message: => String): Handler.Id[L, N] = getOrElse(sys.error(message)) def unsafeGet: Handler.Id[L, N] = thiz.map([A] => (result: Option[A]) => result.get) extension [E, L, N](thiz: Handler[Either[E, _], L, N]) def toOption: Handler[Option, L, N] = thiz.map([A] => (result: Either[E, A]) => result.toOption) def toTry(implicit ev: E <:< Throwable): Handler[Try, L, N] = thiz.map([A] => (result: Either[E, A]) => result.toTry) def getOrElse(default: E => Nothing): Handler.Id[L, N] = thiz.map([A] => (result: Either[E, A]) => result.fold(default, x => x)) def getOrDie(message: E => String): Handler.Id[L, N] = getOrElse(e => sys.error(message(e))) def mapLeft[E2](f: E => E2): Handler[Either[E2, _], L, N] = thiz.map([A] => (result: Either[E, A]) => result.swap.map(f).swap)
Marissa4/RPyCA
dimredu/lib/minNucPlusFrob.py
<reponame>Marissa4/RPyCA #! /usr/bin/env python import numpy as np from dimredu.lib.shrink import shrink from dimredu.lib.sparseSVDUpdate import sparseSVDUpdate from dimredu.lib.nuclearNorm import nuclearNorm def minNucPlusFrob(X, U, E, VT, mu, truncateK=0, debug=False, guess=None): """Compute a fast minimization of nuclear norm plus Frobenius norm. The is computes the minium of the following objective. .. math:: \| L \|_* + \mu / 2 \| L - (X + U*E*V^T) \|_F^2 Args: X: A sparse array. U, E, VT: The SVD of a low matrix. mu: The value of :math:`\mu`. truncateK: Ignore the first truncateK singular values to use the truncated nuclear norm debug: Run the algorithm in debugging mode, with additional output and slower run-time. guess: An initial guess for the minimization. In this case the minimization is in closed form, so it is merely used for debugging to see is the value of the objective is reduced. Returns: The SVD of :math:`L` that achieves the minimum. """ assert X.shape[0] == U.shape[0], 'First dim of L and U must match' assert X.shape[1] == VT.shape[1], 'Last dim of L and VT must match' #################################### # DEBUG ############################ if debug and (guess is not None): Um = np.matrix(guess['U']) Em = np.matrix(np.diag(guess['E'])) VTm = np.matrix(guess['VT']) before = objective(Um * Em * VTm, X, U, E, VT, mu, truncateK=truncateK) # DEBUG ############################ #################################### [Unew, Enew, VTnew] = sparseSVDUpdate(X, U, E, VT) # Don't shrink the first truncatedK singular # values to implement the truncated nuclear norm # as in Enew[truncateK:] = shrink(1. / mu, Enew[truncateK:]) #################################### # DEBUG ############################ if debug and (guess is not None): Um = np.matrix(Unew) Em = np.matrix(np.diag(Enew)) VTm = np.matrix(VTnew) after = objective(Um * Em * VTm, X, U, E, VT, mu, truncateK=truncateK) assert before / after + 1e-7 >= 1., 'minNucPludFrob went up!' # DEBUG ############################ #################################### return [Unew, Enew, VTnew] def objective(L, X, U, E, VT, mu, truncateK=0): return (nuclearNorm(L, truncateK) + (mu / 2.) * np.linalg.norm(L - (X + U * np.diag(E) * VT), 'fro')**2) def test_minNucPlusFrob(): np.random.seed(123) A = np.matrix(np.random.random(size=[5, 5])) [U, E, VT] = np.linalg.svd(A) X = np.matrix(np.random.random(size=[5, 5])) # Needs to be bigger than 0. mu = 1.0 [Umin, Emin, VTmin] = minNucPlusFrob(X, U, E, VT, mu, debug=True, guess={'U': U, 'E': E, 'VT': VT}) Lmin = Umin * np.diag(Emin) * VTmin print(Umin) print(Emin) print(VTmin) print(Lmin) LminObj = objective(Lmin, X, U, E, VT, mu) print(('Should be smallest', LminObj)) for i in range(5): perturb = np.random.random(size=[5, 5]) * 1e-5 pObj = objective(Lmin + perturb, X, U, E, VT, mu) print(pObj) assert LminObj < pObj if __name__ == '__main__': test_minNucPlusFrob()
jacobdaddario/railsdevs.io
db/seeds/conversations.rb
<filename>db/seeds/conversations.rb # Core developer developer = User.find_by(email: "<EMAIL>").developer business = User.find_by(email: "<EMAIL>").business conversation = Conversation.find_or_create_by!(developer:, business:) Message.find_or_create_by!(conversation:, sender: business, body: "Your XP looks perfect.") Message.find_or_create_by!(conversation:, sender: developer, body: "Let's chat over Zoom.") # Potential hire developer = User.find_by(email: "<EMAIL>").developer business = User.find_by(email: "<EMAIL>").business conversation = Conversation.find_or_create_by!(developer:, business:) Message.find_or_create_by!(conversation:, sender: business, body: "Let's work together!") Message.find_or_create_by!(conversation:, sender: developer, body: "I'd love to, let's do it.") developer = User.find_by(email: "<EMAIL>").developer business = User.find_by(email: "<EMAIL>").business conversation = Conversation.find_or_create_by!(developer:, business:) Message.find_or_create_by!(conversation:, sender: business, body: "Looking for freelance work?")
FoalFreePress/TestingForgeMods
8162/examplemod/src/main/java/com/example/examplemod/ExampleMod.java
<reponame>FoalFreePress/TestingForgeMods<filename>8162/examplemod/src/main/java/com/example/examplemod/ExampleMod.java package com.example.examplemod; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.example.examplelibrary.ExampleLibrary; import net.minecraftforge.fml.common.Mod; @Mod(ExampleMod.MODID) public class ExampleMod { public static final String MODID = "examplemod"; private static final Logger LOGGER = LogManager.getLogger(); private ExampleLibrary library; public ExampleMod() { LOGGER.info("Loading mod..."); library = new ExampleLibrary(); LOGGER.info("Class of ExampleLibrary " + library.getClass().getName()); LOGGER.info("Completed Loading!"); } }
backupForkRepos/NTTools
src/io/kurumi/nttools/twitter/CleanThread.java
package io.kurumi.nttools.twitter; import twitter4j.*; import io.kurumi.nttools.model.Callback; import io.kurumi.nttools.twitter.TApi; import io.kurumi.nttools.utils.UserData; import java.util.LinkedList; public class CleanThread extends Thread { private UserData userData; private Callback callback; private boolean status; private boolean followers; private boolean friends; public CleanThread(UserData userData, Callback callback, boolean status, boolean followers, boolean friends) { this.userData = userData; this.callback = callback; this.status = status; this.followers = followers; this.friends = friends; } @Override public void run() { Twitter api = callback.data.getUser(userData).createApi(); try { if (status) { ResponseList<Status> tl = api.getUserTimeline(new Paging().count(200)); while (tl.size() != 0) { for(Status s : tl) { api.destroyStatus(s.getId()); callback.send(s.getText()).exec(); } tl = api.getUserTimeline(new Paging().count(200)); } } if (followers) { LinkedList<String> cache = new LinkedList<>(); LinkedList<User> fo = TApi.getAllFo(api, api.getId()); for (User id : fo) { api.createBlock(id.getId()); api.destroyBlock(id.getId()); if (cache.size() < 20) { cache.add(TApi.formatUserNameMarkdown(id)); } else { callback.send(cache.toArray(new String[cache.size()])).markdown().disableLinkPreview().exec(); cache.clear(); } } if (cache.size() > 0) { callback.send(cache.toArray(new String[cache.size()])).markdown().disableLinkPreview().exec(); } } if (friends) { LinkedList<String> cache = new LinkedList<>(); LinkedList<User> fo = TApi.getAllFr(api, api.getId()); for (User id : fo) { api.destroyFriendship(id.getId()); if (cache.size() < 20) { cache.add(TApi.formatUserNameMarkdown(id)); } else { callback.send(cache.toArray(new String[cache.size()])).markdown().disableLinkPreview().exec(); cache.clear(); } } if (cache.size() > 0) { callback.send(cache.toArray(new String[cache.size()])).markdown().disableLinkPreview().exec(); } } } catch (TwitterException e) {} } }
StFS/quarkus
extensions/opentelemetry/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/WithSpanInterceptorTest.java
<reponame>StFS/quarkus package io.quarkus.opentelemetry.deployment; import static io.opentelemetry.api.trace.SpanKind.INTERNAL; import static io.opentelemetry.api.trace.SpanKind.SERVER; import static java.net.HttpURLConnection.HTTP_OK; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.inject.Inject; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.extension.annotations.SpanAttribute; import io.opentelemetry.extension.annotations.WithSpan; import io.opentelemetry.sdk.trace.data.SpanData; import io.quarkus.runtime.StartupEvent; import io.quarkus.test.QuarkusUnitTest; import io.smallrye.config.SmallRyeConfig; import io.vertx.ext.web.Router; public class WithSpanInterceptorTest { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class).addClass(SpanBean.class).addClass(TestSpanExporter.class)); @Inject SpanBean spanBean; @Inject TestSpanExporter spanExporter; @AfterEach void tearDown() { spanExporter.reset(); } @Test void span() { spanBean.span(); List<SpanData> spanItems = spanExporter.getFinishedSpanItems(1); assertEquals("SpanBean.span", spanItems.get(0).getName()); assertEquals(INTERNAL, spanItems.get(0).getKind()); } @Test void spanName() { spanBean.spanName(); List<SpanData> spanItems = spanExporter.getFinishedSpanItems(1); assertEquals("name", spanItems.get(0).getName()); assertEquals(INTERNAL, spanItems.get(0).getKind()); } @Test void spanKind() { spanBean.spanKind(); List<SpanData> spanItems = spanExporter.getFinishedSpanItems(1); assertEquals("SpanBean.spanKind", spanItems.get(0).getName()); assertEquals(SERVER, spanItems.get(0).getKind()); } @Test void spanArgs() { spanBean.spanArgs("argument"); List<SpanData> spanItems = spanExporter.getFinishedSpanItems(1); assertEquals("SpanBean.spanArgs", spanItems.get(0).getName()); assertEquals(INTERNAL, spanItems.get(0).getKind()); assertEquals("argument", spanItems.get(0).getAttributes().get(AttributeKey.stringKey("arg"))); } @Test void spanChild() { spanBean.spanChild(); List<SpanData> spanItems = spanExporter.getFinishedSpanItems(2); assertEquals("SpanChildBean.spanChild", spanItems.get(0).getName()); assertEquals("SpanBean.spanChild", spanItems.get(1).getName()); assertEquals(spanItems.get(0).getParentSpanId(), spanItems.get(1).getSpanId()); } @Test void spanCdiRest() { spanBean.spanRestClient(); List<SpanData> spanItems = spanExporter.getFinishedSpanItems(4); assertEquals(spanItems.get(0).getTraceId(), spanItems.get(1).getTraceId()); assertEquals(spanItems.get(0).getTraceId(), spanItems.get(2).getTraceId()); assertEquals(spanItems.get(0).getTraceId(), spanItems.get(3).getTraceId()); } @ApplicationScoped public static class SpanBean { @WithSpan public void span() { } @WithSpan("name") public void spanName() { } @WithSpan(kind = SERVER) public void spanKind() { } @WithSpan public void spanArgs(@SpanAttribute(value = "arg") String arg) { } @Inject SpanChildBean spanChildBean; @WithSpan public void spanChild() { spanChildBean.spanChild(); } @Inject SpanRestClient spanRestClient; @WithSpan public void spanRestClient() { spanRestClient.spanRestClient(); } } @ApplicationScoped public static class SpanChildBean { @WithSpan public void spanChild() { } } @ApplicationScoped public static class SpanRestClient { @Inject SmallRyeConfig config; @WithSpan public void spanRestClient() { WebTarget target = ClientBuilder.newClient() .target(UriBuilder.fromUri(config.getRawValue("test.url")).path("hello")); Response response = target.request().get(); assertEquals(HTTP_OK, response.getStatus()); } } @ApplicationScoped public static class HelloRouter { @Inject Router router; public void register(@Observes StartupEvent ev) { router.get("/hello").handler(rc -> rc.response().end("hello")); } } }
canfie1d/blueprint
src/components/NumberBlueprint/NumberBlueprint.js
<filename>src/components/NumberBlueprint/NumberBlueprint.js import React from 'react'; import styled from 'styled-components'; const StyledNumberBlueprint = styled.p` box-sizing: border-box; color: #4a6de5; background: #ced8f7; padding: 20px 30px; border: 1px dashed #002082; `; const NumberBlueprint = ({ number }) => { const renderNumber = () => { if (!number) return 'No number found'; if (typeof number !== 'number') return 'Must be of type <number>'; return number; }; return <StyledNumberBlueprint>{renderNumber()}</StyledNumberBlueprint>; }; export default NumberBlueprint;
timfel/netbeans
java/api.java/src/org/netbeans/spi/java/queries/SourceLevelQueryImplementation2.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.netbeans.spi.java.queries; import javax.swing.event.ChangeListener; import org.netbeans.api.annotations.common.CheckForNull; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.java.queries.SourceLevelQuery; import org.openide.filesystems.FileObject; /** * * Permits providers to return specification source level of Java source file. * <p> * A default implementation is registered by the * <code>org.netbeans.modules.java.project</code> module which looks up the * project corresponding to the file (if any) and checks whether that * project has an implementation of this interface in its lookup. If so, it * delegates to that implementation. Therefore it is not generally necessary * for a project type provider to register its own global implementation of * this query, if it depends on the Java Project module and uses this style. * </p> * @see org.netbeans.api.java.queries.SourceLevelQuery * @see org.netbeans.api.queries.FileOwnerQuery * @see org.netbeans.api.project.Project#getLookup * @see org.netbeans.api.java.classpath.ClassPath#BOOT * @author <NAME> * @since 1.30 */ public interface SourceLevelQueryImplementation2 { /** * Returns source level of the given Java file. For acceptable return values * see the documentation of <code>-source</code> command line switch of * <code>javac</code> compiler . * @param javaFile Java source file in question * @return source level of the Java file encapsulated as {@link Result}, or * null if the file is not handled by this provider. */ Result getSourceLevel(FileObject javaFile); /** * Result of finding source level, encapsulating the answer as well as the * ability to listen to it. * @since 1.30 */ interface Result { /** * Get the source level. * @return a source level of the Java file, e.g. "1.3", "1.4", "1.5" * or null if the source level is unknown. It is allowed to return source level synonyms * e.g. "5" for "1.5". These synonyms are always normalized by * {@link SourceLevelQuery#getSourceLevel}. */ @CheckForNull String getSourceLevel(); /** * Add a listener to changes of source level. * @param listener a listener to add */ void addChangeListener(@NonNull ChangeListener listener); /** * Remove a listener to changes of source level. * @param listener a listener to add */ void removeChangeListener(@NonNull ChangeListener listener); } /** * Result of finding a source level and profile as well as the ability * to listen on changes. * @since 1.47 */ interface Result2 extends Result { /** * Returns the required profile. * @return the required profile. If the profile is either unknown * or unsupported by actual source level it returns the {@link SourceLevelQuery.Profile#DEFAULT}. * <div class="nonnormative"> * The JDK 8 provides three limited profiles (compact1, compact2, compact3) in addition * to the full JDK. Each profile specifies a specific set of Java API packages and * contains all of the APIs of the smaller profile, @see http://openjdk.java.net/jeps/161 * </div> */ @NonNull SourceLevelQuery.Profile getProfile(); } }
Evegen55/TIJ4_code
lib/xom-1.2.10/XOM/src/nu/xom/tests/DOMConverterTest.java
/* Copyright 2002-2006 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of version 2.1 of the GNU Lesser General Public License as published by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA You can contact <NAME> by sending e-mail to <EMAIL>. Please include the word "XOM" in the subject line. The XOM home page is located at http://www.xom.nu/ */ package nu.xom.tests; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import nu.xom.Attribute; import nu.xom.Builder; import nu.xom.Comment; import nu.xom.DocType; import nu.xom.Document; import nu.xom.Element; import nu.xom.Elements; import nu.xom.Namespace; import nu.xom.Node; import nu.xom.NodeFactory; import nu.xom.Nodes; import nu.xom.ParsingException; import nu.xom.ProcessingInstruction; import nu.xom.Text; import nu.xom.XMLException; import nu.xom.converters.DOMConverter; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.DOMImplementation; import org.w3c.dom.DocumentFragment; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * <p> * Basic tests for conversion from DOM trees to XOM trees * and back again. * </p> * * @author <NAME> * @version 1.2b2 * */ public class DOMConverterTest extends XOMTestCase { public DOMConverterTest(String name) { super(name); } private String source = "<!DOCTYPE test [ ]>\r\n" + "<?xml-stylesheet href=\"file.css\" type=\"text/css\"?>" + "<!-- test -->" + "<test xmlns:xlink='http://www.w3.org/TR/1999/xlink'>Hello dear" + "\r\n<em id=\"p1\" " + "xmlns:none=\"http://www.example.com\">very important</em>" + "<span xlink:type='simple'>here&apos;s the link</span>\r\n" + "<svg:svg xmlns:svg='http://www.w3.org/TR/2000/svg'><svg:text>" + "text in a namespace</svg:text></svg:svg>\r\n" + "<svg xmlns='http://www.w3.org/TR/2000/svg'><text>text in a " + "namespace</text></svg>" + "</test>\r\n" + "<!--epilog-->"; private Document xomDocument; private org.w3c.dom.Document domDocument; private DOMImplementation impl; private DocumentBuilder builder; protected void setUp() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); builder = factory.newDocumentBuilder(); impl = builder.getDOMImplementation(); DocType type = new DocType("test"); Element root = new Element("test"); xomDocument = new Document(root); xomDocument.insertChild(type, 0); xomDocument.insertChild(new ProcessingInstruction( "xml-stylesheet", "href=\"file.css\" type=\"text/css\""), 1); xomDocument.insertChild(new Comment(" test "), 2); xomDocument.appendChild(new Comment("epilog")); root.addNamespaceDeclaration("xlink", "http://www.w3.org/TR/1999/xlink"); root.appendChild("Hello dear\r\n"); Element em = new Element("em"); root.appendChild(em); em.addAttribute(new Attribute("id", "p1")); em.addNamespaceDeclaration("none", "http://www.example.com"); em.appendChild("very important"); Element span = new Element("span"); root.appendChild(span); span.addAttribute(new Attribute("xlink:type", "http://www.w3.org/TR/1999/xlink", "simple")); span.appendChild("here's the link"); root.appendChild("\r\n"); Element empty = new Element("empty"); root.appendChild(empty); empty.addAttribute(new Attribute("xom:temp", "http://xom.nu/", "Just to see if this can handle namespaced attributes")); root.appendChild("\r\n"); Element svg = new Element("svg:svg", "http://www.w3.org/TR/2000/svg"); root.appendChild(svg); Element text = new Element("svg:text", "http://www.w3.org/TR/2000/svg"); svg.appendChild(text); text.appendChild("text in a namespace"); root.appendChild("\r\n"); svg = new Element("svg", "http://www.w3.org/TR/2000/svg"); root.appendChild(svg); text = new Element("text", "http://www.w3.org/TR/2000/svg"); svg.appendChild(text); text.appendChild("text in a namespace"); Reader reader = new StringReader(source); InputSource inso = new InputSource(reader); try { domDocument = builder.parse(inso); } catch (Exception ex) { // shouldn't happen from known good doc throw new RuntimeException("Oops!"); } } public void testToDOM() { org.w3c.dom.Document domDoc = DOMConverter.convert(xomDocument, impl); org.w3c.dom.DocumentType doctype = domDoc.getDoctype(); assertEquals("test", domDoc.getDocumentElement().getNodeName()); assertTrue(doctype != null); assertEquals(org.w3c.dom.Node.DOCUMENT_TYPE_NODE, domDoc.getFirstChild().getNodeType()); assertEquals(org.w3c.dom.Node.COMMENT_NODE, domDoc.getLastChild().getNodeType()); } public void testToXOM() { Document xomDoc = DOMConverter.convert(domDocument); DocType doctype = xomDoc.getDocType(); Element root = xomDoc.getRootElement(); assertEquals("test", root.getQualifiedName()); assertEquals("test", root.getLocalName()); assertEquals("", root.getNamespaceURI()); assertNotNull(doctype); assertTrue(xomDoc.getChild(0) instanceof DocType); assertTrue(xomDoc.getChild(4) instanceof nu.xom.Comment); assertTrue(xomDoc.getChild(2) instanceof nu.xom.Comment); assertEquals(" test ", xomDoc.getChild(2).getValue()); assertEquals("epilog", xomDoc.getChild(4).getValue()); assertTrue( xomDoc.getChild(1) instanceof nu.xom.ProcessingInstruction); assertEquals("test", doctype.getRootElementName()); assertNull(doctype.getPublicID()); assertNull(doctype.getSystemID()); } public void testDefaultNamespacedElement() throws SAXException, IOException, ParserConfigurationException { byte[] data = "<root xmlns=\"http://www.example.com\"/>".getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); Document xomDoc = DOMConverter.convert(doc); Element root = xomDoc.getRootElement(); assertEquals("root", root.getQualifiedName()); assertEquals("http://www.example.com", root.getNamespaceURI()); } public void testPrefixedElement() throws SAXException, IOException, ParserConfigurationException { byte[] data = "<pre:root xmlns:pre=\"http://www.example.com\"/>".getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); Document xomDoc = DOMConverter.convert(doc); Element root = xomDoc.getRootElement(); assertEquals("pre:root", root.getQualifiedName()); assertEquals("http://www.example.com", root.getNamespaceURI()); } public void testConvertAttr() throws SAXException, IOException, ParserConfigurationException { byte[] data = ("<element name='value' " + "xmlns='http://example.com/' " + "xmlns:pre='http://example.net'/>").getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); org.w3c.dom.Element root = doc.getDocumentElement(); Attribute attribute = DOMConverter.convert(root.getAttributeNode("name")); assertEquals("name", attribute.getQualifiedName()); assertEquals("", attribute.getNamespacePrefix()); assertEquals("", attribute.getNamespaceURI()); assertEquals("value", attribute.getValue()); try { DOMConverter.convert(root.getAttributeNode("xmlns")); fail("Converted xmlns attribute"); } catch (XMLException ex) { assertNotNull(ex.getMessage()); } try { DOMConverter.convert(root.getAttributeNode("xmlns:pre")); fail("Converted xmlns:pre attribute"); } catch (XMLException ex) { assertNotNull(ex.getMessage()); } } public void testConvertElement() throws SAXException, IOException, ParserConfigurationException { byte[] data = ("<element name='value' " + "xmlns='http://example.com/' " + "xmlns:pre='http://example.net'/>").getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); org.w3c.dom.Element root = doc.getDocumentElement(); Element xomRoot = DOMConverter.convert(root); assertEquals("name", xomRoot.getAttribute("name").getQualifiedName()); assertEquals("", xomRoot.getAttribute("name").getNamespacePrefix()); assertEquals("", xomRoot.getAttribute("name").getNamespaceURI()); assertEquals("value", xomRoot.getAttribute("name").getValue()); assertEquals("element", xomRoot.getQualifiedName()); assertEquals("", xomRoot.getValue()); assertEquals(0, xomRoot.getChildCount()); assertEquals("http://example.com/", xomRoot.getNamespaceURI()); assertEquals("http://example.net", xomRoot.getNamespaceURI("pre")); } public void testConvertComment() throws SAXException, IOException, ParserConfigurationException { byte[] data = "<element><!--data--></element>".getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); org.w3c.dom.Element root = doc.getDocumentElement(); org.w3c.dom.Comment comment = (org.w3c.dom.Comment) (root.getChildNodes().item(0)); Comment xomComment = DOMConverter.convert(comment); assertEquals(comment.getNodeValue(), xomComment.getValue()); } public void testConvertText() throws SAXException, IOException, ParserConfigurationException { byte[] data = "<element> here's the text </element>".getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); org.w3c.dom.Element root = doc.getDocumentElement(); org.w3c.dom.Text node = (org.w3c.dom.Text) (root.getChildNodes().item(0)); Text text = DOMConverter.convert(node); assertEquals(node.getNodeValue(), text.getValue()); } public void testConvertCDATASection() throws SAXException, IOException, ParserConfigurationException { byte[] data = "<element><![CDATA[ here's the text ]]></element>".getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); org.w3c.dom.Element root = doc.getDocumentElement(); CDATASection node = (CDATASection) (root.getChildNodes().item(0)); Text text = DOMConverter.convert(node); assertEquals(node.getNodeValue(), text.getValue()); // Now test indirect conversion Document xomDoc = DOMConverter.convert(doc); assertEquals(node.getNodeValue(), xomDoc.getValue()); } public void testConvertProcessingInstruction() throws SAXException, IOException, ParserConfigurationException { byte[] data = "<element><?target PI data?></element>".getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); org.w3c.dom.Element root = doc.getDocumentElement(); org.w3c.dom.ProcessingInstruction node = (org.w3c.dom.ProcessingInstruction) (root.getChildNodes().item(0)); ProcessingInstruction pi = DOMConverter.convert(node); assertEquals(node.getNodeValue(), pi.getValue()); assertEquals(node.getTarget(), pi.getTarget()); } public void testConvertDocType() throws SAXException, IOException, ParserConfigurationException { byte[] data = "<!DOCTYPE root ><element />".getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); org.w3c.dom.DocumentType type = doc.getDoctype(); DocType xomType = DOMConverter.convert(type); assertEquals(type.getName(), xomType.getRootElementName()); } public void testConvertInternalDTDSubset() throws SAXException, IOException, ParserConfigurationException { byte[] data = "<!DOCTYPE root [<!ELEMENT element EMPTY>]><element />".getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); org.w3c.dom.DocumentType type = doc.getDoctype(); DocType xomType = DOMConverter.convert(type); assertEquals(type.getName(), xomType.getRootElementName()); assertEquals(type.getInternalSubset(), xomType.getInternalDTDSubset()); } public void testConvertDocTypePublicAndSystemIdentifier() throws SAXException, IOException, ParserConfigurationException { File inputDir = new File("data"); File f = new File(inputDir, "dtdtest.xhtml"); org.w3c.dom.Document doc = builder.parse(f); org.w3c.dom.DocumentType type = doc.getDoctype(); DocType xomType = DOMConverter.convert(type); assertEquals(type.getName(), xomType.getRootElementName()); assertEquals(type.getSystemId(), xomType.getSystemID()); assertEquals(type.getPublicId(), xomType.getPublicID()); } public void testChildElementAddsNamespace() { Element root = new Element("root"); Element child = new Element("pre:child", "http://www.example.org/"); child.addAttribute(new Attribute("xlink:type", "http://www.w3.org/1999/xlink", "simple")); root.appendChild(child); Document doc = new Document(root); assertEquals( doc, DOMConverter.convert(DOMConverter.convert(doc, impl)) ); } public void testChildElementUsesSameNamespace() { Element root = new Element("pre:root", "http://www.example.org/"); Element child = new Element("pre:child", "http://www.example.org/"); root.appendChild(child); Document doc = new Document(root); assertEquals(doc, DOMConverter.convert(DOMConverter.convert(doc, impl))); } public void testPrefixMappingChanges() { Element root = new Element("pre:root", "http://www.example.org/"); Element child = new Element("pre:child", "http://www.example.net/"); root.appendChild(child); Document doc = new Document(root); assertEquals(doc, DOMConverter.convert(DOMConverter.convert(doc, impl))); } public void testConvertDocumentFragment() { DocumentFragment fragment = domDocument.createDocumentFragment(); org.w3c.dom.Element element = domDocument.createElement("name"); element.setAttribute("name", "value"); fragment.appendChild(element); fragment.appendChild(domDocument.createComment("data")); fragment.appendChild(domDocument.createTextNode("text")); Nodes result = DOMConverter.convert(fragment); Element first = (Element) result.get(0); assertEquals("name", first.getQualifiedName()); assertEquals("name", first.getAttribute("name").getQualifiedName()); assertEquals("value", first.getAttribute("name").getValue()); Comment second = (Comment) result.get(1); assertEquals("data", second.getValue()); Text third = (Text) result.get(2); assertEquals("text", third.getValue()); } // regression found by <NAME> public void testWolfgang() throws ParsingException, IOException { String data = "<m>" + "<a code='3.1415292'>" + "<u>http://www.example.com</u>" + "<h>Some data</h>" + "<s>StockAccess</s>" + "</a>" + "</m>"; Document doc = new Builder().build(data, null); Element article = doc.getRootElement().getChildElements().get(0); Document temp = new Document(new Element(article)); org.w3c.dom.Element domArticle = DOMConverter.convert(temp, impl).getDocumentElement(); assertEquals(3, domArticle.getChildNodes().getLength()); Element out = DOMConverter.convert(domArticle); assertEquals(article, out); } public void testConvertNullXOMDocument() { try { DOMConverter.convert((Document) null, impl); fail("Converted null document"); } catch (NullPointerException success) { } } public void testConvertNullDOMElement() { try { DOMConverter.convert((org.w3c.dom.Element) null); fail("Converted null element"); } catch (NullPointerException success) { } } public void testConvertNullDOMDocument() { try { DOMConverter.convert((org.w3c.dom.Document) null); fail("Converted null element"); } catch (NullPointerException success) { } } /** * Test a bug in a document provided by <NAME>. */ public void testFullHoschek() throws ParsingException, IOException { File f = new File("data"); f = new File(f, "hoschektest.xml"); Builder builder = new Builder(); Document xomDocIn = builder.build(f); org.w3c.dom.Document domDoc = DOMConverter.convert(xomDocIn, impl); Document xomDocOut = DOMConverter.convert(domDoc); assertEquals(xomDocIn, xomDocOut); } /** * Test a bug in identified by <NAME>. */ public void testSimplifiedHoschekDOMToXOM() throws SAXException, IOException { File f = new File("data"); f = new File(f, "simplehoschektest.xml"); org.w3c.dom.Document domDocIn = builder.parse(f); int domRootNumber = domDocIn.getDocumentElement().getChildNodes().getLength(); Document xomDoc = DOMConverter.convert(domDocIn); Element xomRoot = xomDoc.getRootElement(); assertEquals(domRootNumber, xomRoot.getChildCount()); } public void testChildNodesRemainChildNodes() throws ParsingException, IOException { String data = "<root><scope><a>1</a><b>2</b><c /></scope></root>"; Builder builder = new Builder(); Document xomDocIn = builder.build(data, null); int xomRootNumber = xomDocIn.getRootElement().getChildCount(); org.w3c.dom.Document domDoc = DOMConverter.convert(xomDocIn, impl); org.w3c.dom.Element domRoot = domDoc.getDocumentElement(); assertEquals(xomRootNumber, domRoot.getChildNodes().getLength()); Document xomDocOut = DOMConverter.convert(domDoc); assertEquals(xomDocIn, xomDocOut); } public void testLastChildNodeIsLeafNode() throws ParsingException, IOException { String data = "<root><top><empty />ABCD</top></root>"; Builder builder = new Builder(); Document xomDocIn = builder.build(data, null); org.w3c.dom.Document domDoc = DOMConverter.convert(xomDocIn, impl); org.w3c.dom.Element domRoot = domDoc.getDocumentElement(); org.w3c.dom.Node domTop = domRoot.getFirstChild(); assertEquals(2, domTop.getChildNodes().getLength()); } public void testNamespaceAttributes() { Element root = new Element("root", "http://www.example.org/"); root.appendChild("text"); Document xomDocIn = new Document(root); org.w3c.dom.Document domDoc = DOMConverter.convert(xomDocIn, impl); org.w3c.dom.Element domRoot = domDoc.getDocumentElement(); assertTrue(domRoot.hasAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns")); } public void testConvertSingleElementDocumentFromXOMToDOM() { Element root = new Element("root"); Document xomDocIn = new Document(root); org.w3c.dom.Document domDoc = DOMConverter.convert(xomDocIn, impl); org.w3c.dom.Element domRoot = domDoc.getDocumentElement(); assertEquals(0, domRoot.getChildNodes().getLength()); assertEquals("root", domRoot.getNodeName()); } public void testConvertSingleElementDocumentFromDOMToXOM() throws SAXException, IOException { byte[] data = "<element />".getBytes(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(data)); Document xomDoc = DOMConverter.convert(doc); Element root = xomDoc.getRootElement(); assertEquals(0, root.getChildCount()); assertEquals("element", root.getLocalName()); } public void testConvertXMLSpaceAttributeFromXOMToDOM() throws SAXException, IOException { Element root = new Element("element"); Document doc = new Document(root); root.addAttribute(new Attribute("xml:space", "http://www.w3.org/XML/1998/namespace", "preserve")); org.w3c.dom.Document domDoc = DOMConverter.convert(doc, impl); org.w3c.dom.Element domRoot = domDoc.getDocumentElement(); assertEquals(1, domRoot.getAttributes().getLength()); assertEquals("preserve", domRoot.getAttributeNS("http://www.w3.org/XML/1998/namespace", "space")); } public void testConvertXMLSpaceAttributeFromDOMToXOM() throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory df = DocumentBuilderFactory.newInstance(); df.setNamespaceAware(true); org.w3c.dom.Document doc = df.newDocumentBuilder().parse(new InputSource(new StringReader("<root xml:space='preserve'/>"))); Document xom = DOMConverter.convert (doc); assertEquals("preserve", xom.getRootElement().getAttributeValue("space", Namespace.XML_NAMESPACE)); } public void testConvertXMLPrefixedElementFromXOMToDOM() throws SAXException, IOException { Element root = new Element( "xml:element", "http://www.w3.org/XML/1998/namespace"); Document doc = new Document(root); org.w3c.dom.Document domDoc = DOMConverter.convert(doc, impl); org.w3c.dom.Element domRoot = domDoc.getDocumentElement(); assertEquals(0, domRoot.getAttributes().getLength()); } public void testDeepConvert() { Element top = new Element("e"); Element parent = top; for (int i = 0; i < 100; i++) { Element child = new Element("e" + i); parent.appendChild(child); parent = child; } Document xomDocIn = new Document(top); org.w3c.dom.Document domDoc = DOMConverter.convert(xomDocIn, impl); Document xomDocOut = DOMConverter.convert(domDoc); assertEquals(xomDocIn, xomDocOut); } public void testUseFactory() { Document xomDocOut = DOMConverter.convert(domDocument, new ANodeFactory()); assertTrue(xomDocOut instanceof ADocument); Element root = xomDocOut.getRootElement(); assertTrue(root instanceof AElement); Node doctype = xomDocOut.getChild(0); assertTrue(doctype instanceof ADocType); Node pi = xomDocOut.getChild(1); assertTrue(pi instanceof AProcessingInstruction); Node comment = xomDocOut.getChild(2); assertTrue(comment instanceof AComment); assertTrue(root.getChild(0) instanceof AText); Elements children = root.getChildElements(); for (int i = 0; i < children.size(); i++) { Element child = children.get(i); assertTrue(child instanceof AElement); for (int j = 0; j < child.getAttributeCount(); j++) { assertTrue(child.getAttribute(j) instanceof AnAttribute); } } } public void testUseFactoryWithPrologAndEpilog() { org.w3c.dom.Comment before = domDocument.createComment("before"); org.w3c.dom.Comment after = domDocument.createComment("after"); domDocument.appendChild(after); domDocument.insertBefore(before, domDocument.getFirstChild()); Document xomDocOut = DOMConverter.convert(domDocument, new ANodeFactory()); assertTrue(xomDocOut instanceof ADocument); Comment bc = (Comment) xomDocOut.getChild(0); Comment ac = (Comment) xomDocOut.getChild(xomDocOut.getChildCount()-1); assertTrue(bc instanceof AComment); assertTrue(ac instanceof AComment); } public void testUseMinimizingFactory() { Document xomDocOut = DOMConverter.convert( domDocument, new NodeFactoryTest.MinimizingFactory()); assertEquals(0, xomDocOut.getRootElement().getChildCount()); } public void testUseStrippingFactory() { Document xomDocOut = DOMConverter.convert( domDocument, new StrippingFactory()); assertEquals("Hello dear\nvery importanthere's the link\n" + "text in a namespace\ntext in a namespace", xomDocOut.getRootElement().getValue()); } private static class StrippingFactory extends NodeFactory { public Element startMakingElement(String name, String namespaceURI) { if (! "test".equals(name)) return null; return super.startMakingElement(name, namespaceURI); } } }
Tikido/tikido_agent
plugins/elasticsrch/logic.py
from elasticsearch import Elasticsearch, exceptions import logging import time log = logging.getLogger(__name__) from ..agent_core import IAgentCore class Logic(IAgentCore): def __init__(self, options): self.host_port = options.get('host_port') self.index = options.get('index', '') self.doc_type = options.get('doc_type', '') self.sort_field = options.get('sort_field', '') self.src = options.get('src', '').split('|')[0] self.timestamp = options.get('timestamp', '') self.index_wildcard = options.get('index_wildcard', '*') self.node = options.get('node', '') def connect(self): try: self.elastic = Elasticsearch(self.host_port, timeout=5, request_timeout=5, retries=False, max_retries=0) res = self.elastic.ping() if not res: raise ConnectionError except Exception as e: raise ConnectionError def ping(self): try: delay = time.time() self.connect() return round((time.time() - delay) * 1000) except exceptions.ConnectionError: return -1 def status_cluster(self): self.connect() cluster_state = self.elastic.cluster.stats()['nodes'] fs_free_percent = cluster_state['fs']['available_in_bytes'] / cluster_state['fs']['total_in_bytes'] * 100 // 1 os_mem_free_percent = cluster_state['os']['mem']['free_percent'] process_cpu_percent = cluster_state['process']['cpu']['percent'] res = dict() res['fs_free_percent'] = fs_free_percent res['os_mem_free_percent'] = os_mem_free_percent res['process_cpu_percent'] = process_cpu_percent return res def search_direct(self): self.connect() res = self.elastic.search(index=self.index, doc_type=self.doc_type, version=True, size=1, body={"sort": {self.sort_field: {"order": "desc"}}}) return res['hits']['hits'][0]['_source'][self.sort_field] def search_source(self): self.connect() res = self.elastic.search(index=self.index, doc_type=self.doc_type, version=True, size=1, _source=",".join((self.src, self.sort_field)), body={"query": {"bool": {"filter": {"range": {self.sort_field: {"gt": self.timestamp}}}}}, "sort": {self.sort_field: {"order": "asc"}}}) return res def count(self): self.connect() res = self.elastic.count(index=self.index, doc_type=self.doc_type) return res['count'] def indices(self): self.connect() res = self.elastic.indices.get(index=self.index_wildcard) return res def doctypes(self): self.connect() res = self.elastic.indices.get(index=self.index) return res def status_nodes(self): self.connect() nodes_stats = self.elastic.nodes.stats(self.node)['nodes'] nodes = dict() nodes['fs_free_percent'] = nodes_stats[self.node]['fs']['total']['available_in_bytes'] / nodes_stats[self.node]['fs']['total']['total_in_bytes'] * 100 // 1 nodes['os_mem_free_percent'] = nodes_stats[self.node]['os']['mem']['free_percent'] nodes['process_cpu_percent'] = nodes_stats[self.node]['process']['cpu']['percent'] return nodes def nodes_list(self): self.connect() res = self.elastic.nodes.stats()['nodes'] return {el: res[el]['name'] for el in res}
mfullen/ping-pong-net
pingpongnet/src/test/java/ping/pong/net/server/io/IoServerTest.java
package ping.pong.net.server.io; import java.net.SocketAddress; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ping.pong.net.connection.Connection; import ping.pong.net.connection.ConnectionEvent; import ping.pong.net.connection.config.ConnectionConfigFactory; import ping.pong.net.connection.messaging.Envelope; import ping.pong.net.connection.messaging.MessageListener; import ping.pong.net.server.Server; import ping.pong.net.server.ServerConnectionListener; /** * * @author mfullen */ public class IoServerTest { private static final Logger logger = LoggerFactory.getLogger(IoServer.class); Envelope<String> tcpMessage = new Envelope<String>() { @Override public boolean isReliable() { return true; } @Override public String getMessage() { return "Test"; } }; Connection connection1 = new Connection<String>() { @Override public void close() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isConnected() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getConnectionId() { return 1; } @Override public void setConnectionId(int id) { assertTrue(id == 1); } @Override public void sendMessage(Envelope<String> message) { assertTrue(message.isReliable()); assertEquals(message.getMessage(), "Test"); } @Override public void run() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void addConnectionEventListener(ConnectionEvent listener) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void removeConnectionEventListener(ConnectionEvent listener) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isUsingCustomSerialization() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isUdpEnabled() { throw new UnsupportedOperationException("Not supported yet."); } @Override public SocketAddress getSocketAddress() { throw new UnsupportedOperationException("Not supported yet."); } }; public IoServerTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } /** * Test of broadcast method, of class IoServer. */ @Test public void testBroadcast() { IoServer instance = new IoServer(); assertNotNull(instance); assertNotNull(connection1); instance.addConnection(connection1); instance.broadcast(tcpMessage); } /** * Test of start method, of class IoServer. */ @Test public void testStart() { IoServer instance = new IoServer(); instance.start(); assertTrue(instance.isListening()); } @Test public void testConnectionManager() { IoServer instance = new IoServer(); assertFalse(instance.isListening()); assertNull(instance.serverConnectionManager); instance.serverConnectionManager = new ServerConnectionManager(ConnectionConfigFactory.createConnectionConfiguration(), instance); assertNotNull(instance.serverConnectionManager); //assertFalse(instance.isListening()); instance.start(); } /** * Test of shutdown method, of class IoServer. */ @Test public void testShutdown() { IoServer instance = new IoServer(); instance.shutdown(); instance.start(); assertTrue(instance.isListening()); instance.shutdown(); assertFalse(instance.isListening()); } /** * Test of getConnection method, of class IoServer. */ @Test public void testGetConnection() { IoServer instance = new IoServer(); assertNotNull(instance); assertNotNull(connection1); int id = connection1.getConnectionId(); assertNull(instance.getConnection(id)); instance.addConnection(connection1); assertEquals(connection1, instance.getConnection(id)); } /** * Test of getConnections method, of class IoServer. */ @Test public void testGetConnections() { IoServer instance = new IoServer(); assertTrue(instance.getConnections().isEmpty()); instance.addConnection(connection1); assertEquals(instance.getConnections().size(), 1); } /** * Test of hasConnections method, of class IoServer. */ @Test public void testHasConnections() { IoServer instance = new IoServer(); assertFalse(instance.hasConnections()); instance.addConnection(connection1); assertTrue(instance.hasConnections()); } /** * Test of isListening method, of class IoServer. */ @Test public void testIsListening() { IoServer instance = new IoServer(); assertFalse(instance.isListening()); instance.start(); assertTrue(instance.isListening()); instance.shutdown(); assertFalse(instance.isListening()); } @Test public void testIsListening2() { IoServer instance = new IoServer(); assertFalse(instance.isListening()); instance.serverConnectionManager = new ServerConnectionManager(ConnectionConfigFactory.createConnectionConfiguration(), instance); instance.serverConnectionManager.listening = false; assertFalse(instance.isListening()); } /** * Test of addMessageListener method, of class IoServer. */ @Test public void testAddMessageListener() { MessageListener<? super Connection, Envelope> listener = null; IoServer instance = new IoServer(); instance.addMessageListener(listener); assertEquals(0, instance.messageListeners.size()); listener = new MessageListener<Connection, Envelope>() { @Override public void messageReceived(Connection source, Envelope message) { assertNotNull(source); assertNotNull(message); } }; instance.addMessageListener(listener); assertEquals(1, instance.messageListeners.size()); } /** * Test of removeMessageListener method, of class IoServer. */ @Test public void testRemoveMessageListener() { MessageListener<? super Connection, Envelope> listener = null; IoServer instance = new IoServer(); instance.removeMessageListener(listener); assertEquals(0, instance.messageListeners.size()); listener = new MessageListener<Connection, Envelope>() { @Override public void messageReceived(Connection source, Envelope message) { assertNotNull(source); assertNotNull(message); } }; instance.addMessageListener(listener); assertEquals(1, instance.messageListeners.size()); instance.removeMessageListener(listener); assertEquals(0, instance.messageListeners.size()); } /** * Test of addConnectionListener method, of class IoServer. */ @Test public void testAddConnectionListener() { ServerConnectionListener listener = null; IoServer instance = new IoServer(); instance.addConnectionListener(listener); assertEquals(0, instance.connectionListeners.size()); listener = new ServerConnectionListener() { @Override public void connectionAdded(Server server, Connection conn) { assertNotNull(server); assertNotNull(conn); } @Override public void connectionRemoved(Server server, Connection conn) { assertNotNull(server); assertNotNull(conn); } }; instance.addConnectionListener(listener); assertEquals(1, instance.connectionListeners.size()); } /** * Test of removeConnectionListener method, of class IoServer. */ @Test public void testRemoveConnectionListener() { ServerConnectionListener listener = null; IoServer instance = new IoServer(); instance.removeConnectionListener(listener); assertEquals(0, instance.connectionListeners.size()); listener = new ServerConnectionListener() { @Override public void connectionAdded(Server server, Connection conn) { assertNotNull(server); assertNotNull(conn); } @Override public void connectionRemoved(Server server, Connection conn) { assertNotNull(server); assertNotNull(conn); } }; instance.addConnectionListener(listener); assertEquals(1, instance.connectionListeners.size()); instance.removeConnectionListener(listener); assertEquals(0, instance.connectionListeners.size()); } /** * Test of getNextAvailableId method, of class IoServer. */ @Test public void testGetNextAvailableId() { IoServer instance = new IoServer(); int result = instance.getNextAvailableId(); assertEquals(1, result); instance.addConnection(connection1); result = instance.getNextAvailableId(); result = instance.getNextAvailableId(); assertEquals(2, result); } @Test public void testRemoveConnection() { IoServer instance = new IoServer(); ServerConnectionListener listener = new ServerConnectionListener() { @Override public void connectionAdded(Server server, Connection conn) { assertNotNull(server); assertNotNull(conn); } @Override public void connectionRemoved(Server server, Connection conn) { assertNotNull(server); assertNotNull(conn); } }; instance.addConnectionListener(listener); instance.addConnection(connection1); assertEquals(1, instance.getConnections().size()); assertNotNull(instance.getConnection(connection1.getConnectionId())); instance.removeConnection(connection1); assertEquals(0, instance.getConnections().size()); assertNull(instance.getConnection(connection1.getConnectionId())); instance.removeConnectionListener(listener); instance.addConnection(connection1); assertEquals(1, instance.getConnections().size()); assertNotNull(instance.getConnection(connection1.getConnectionId())); instance.removeConnection(connection1.getConnectionId()); assertEquals(0, instance.getConnections().size()); assertNull(instance.getConnection(connection1.getConnectionId())); instance.removeConnection(null); assertEquals(0, instance.getConnections().size()); assertNull(instance.getConnection(connection1.getConnectionId())); } }
ratson/objection.js
lib/relations/manyToMany/delete/ManyToManyDeleteOperation.js
<filename>lib/relations/manyToMany/delete/ManyToManyDeleteOperation.js 'use strict'; const ManyToManyDeleteOperationBase = require('./ManyToManyDeleteOperationBase'); const ManyToManyModifyMixin = require('../ManyToManyModifyMixin'); class ManyToManyDeleteOperation extends ManyToManyModifyMixin(ManyToManyDeleteOperationBase) {} module.exports = ManyToManyDeleteOperation;
corespring/corespring-api
docker/cs-api-docker-util/src/main/scala/org/corespring/docker/CLI.scala
package org.corespring.docker import scala.Some import org.rogach.scallop._; object CLI extends App { import scala.concurrent.ExecutionContext.Implicits.global object Conf extends ScallopConf(args.toList) { val additionalSeedDirs: ScallopOption[String] = opt[String]( "additionalSeedDirs", descr = "additional dirs to seed", required = false, default = Some("")) val mongoUri: ScallopOption[String] = opt[String]( "mongoUri", descr = "the mongo uri to use for seeding + indexing", required = false, default = Some("mongodb://localhost:27017/api")) val elasticSearchUri: ScallopOption[String] = opt[String]( "elasticSearchUri", descr = "the elasticsearch uri to use for indexing", required = false, default = Some("http://localhost:9200")) val componentPath: ScallopOption[String] = opt[String]( "componentPath", descr = "the path to locate corespring-components", required = false, default = Some("corespring-components/components")) } def handleError(e: Throwable) = throw e def getEnv(prop: String): Option[String] = { val env = System.getenv(prop) if (env == null) None else Some(env) } def seedData() = { println(s"seed db - you can only seed the local api db.") if (Conf.mongoUri().contains("localhost")) { val content = { val baseList = List("static", "demo", "debug", "sample", "common", "dev", "exemplar-content") val extras: List[String] = Conf.additionalSeedDirs().split(",").toList (baseList ++ extras).map(s => s"conf/seed-data/$s") } println(s"seed: ${content}") import com.ee.seeder.log.ConsoleLogger.Level com.ee.seeder.MongoDbSeeder.logLevel = Level.DEBUG com.ee.seeder.MongoDbSeeder.seed(Conf.mongoUri(), content, true) } else { throw new RuntimeException(s"[seedDevData] bad mongo uri - can only seed localhost: uri: ${Conf.mongoUri()}") } } def indexElasticSearch() = { import org.corespring.elasticsearch.ContentIndexer println(s"running content indexer for: ${Conf.elasticSearchUri()}") ContentIndexer.reindex(new java.net.URL(Conf.elasticSearchUri()), Conf.mongoUri(), Conf.componentPath()) println("done.") } try { val argsList = args.toList println(s"CsApi Docker Util - Args ${argsList.mkString(" ")}") seedData() indexElasticSearch() System.exit(0) } catch { case io: java.io.IOException => handleError(io) case e: Throwable => handleError(e) } }
Forence1999/SmartWalker
Following/Network/draw_loss_accuracy.py
<reponame>Forence1999/SmartWalker<filename>Following/Network/draw_loss_accuracy.py import numpy as np import os, sys pwd = os.path.abspath(os.path.abspath(__file__)) father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + "..") sys.path.append(father_path) import matplotlib.pyplot as plt def get_data(direction): # 原始信息获取 file = open(direction) list_ir_data = file.readlines() lists = [] for lines in list_ir_data: lines = lines.strip("\n") lines = lines.strip('[') lines = lines.strip(']') lines = lines.split(", ") lists.append(lines) file.close() array_data = np.array(lists) rows_data = array_data.shape[0] columns_data = array_data.shape[1] data = np.zeros((rows_data, columns_data)) for i in range(rows_data): for j in range(columns_data): data[i][j] = float(array_data[i][j]) return data combine_file = "combine_curve.txt" # tendency_curve.txt current_curve.txt tendency_file = "tendency_curve.txt" # tendency_curve.txt current_curve.txt current_file = "current_curve.txt" # tendency_curve.txt current_curve.txt pwd = os.path.abspath(os.path.abspath(__file__)) father_path = os.path.abspath(os.path.dirname(pwd)) combine_path = os.path.abspath(father_path + os.path.sep + combine_file) tendency_path = os.path.abspath(father_path + os.path.sep + tendency_file) current_path = os.path.abspath(father_path + os.path.sep + current_file) # combine_curve = get_data(combine_path) tendency_curve = get_data(tendency_path) current_curve = get_data(current_path) # # length = 200 # # combine_val_loss = combine_curve[0:length,2].tolist() # tendency_val_loss = tendency_curve[0:length,2].tolist() # current_val_loss = current_curve[0:length,2].tolist() # length = range(length) # plt.figure(figsize=(12,8.7)) # plt.plot(length,combine_val_loss,color='#2878B5',label="FFLNet") # plt.plot(length,tendency_val_loss,color='#C82423',label="Tendency$^+$") # plt.plot(length,current_val_loss,color='#F8AC8C',label="Current$^+$") # plt.legend(prop={'family' : 'Times New Roman', 'size': 40}) # plt.xlabel('Iteration',fontdict={'family' : 'Times New Roman', 'size': 38}) # plt.ylabel('Loss',fontdict={'family' : 'Times New Roman', 'size': 38}) # plt.xticks(fontproperties = 'Times New Roman', size = 32) # plt.yticks(fontproperties = 'Times New Roman', size = 32) # plt.show() combine_val_accuracy = (combine_curve[0:length,3]).tolist() tendency_val_accuracy = (tendency_curve[0:length,3]).tolist() current_val_accuracy = (current_curve[0:length,3]).tolist() length = range(length) plt.figure(figsize=(12,8.7)) plt.plot(length,combine_val_accuracy,color='#2878B5',label="FFLNet") plt.plot(length,tendency_val_accuracy,color='#C82423',label="Tendency$^+$") plt.plot(length,current_val_accuracy,color='#F8AC8C',label="Current$^+$") plt.legend(prop={'family' : 'Times New Roman', 'size': 40}) plt.xlabel('Iteration',fontdict={'family' : 'Times New Roman', 'size': 38}) plt.ylabel('Accuracy',fontdict={'family' : 'Times New Roman', 'size': 38}) plt.xticks(fontproperties = 'Times New Roman', size = 32) plt.yticks(fontproperties = 'Times New Roman', size = 32) plt.show() # combine_path = os.path.abspath( # father_path + os.path.sep + "data" + os.path.sep + "classification.txt") # classification = np.loadtxt(combine_path) # print(classification) # print(classification.sum()) # classes = ['Stop', 'Forward', 'Left Forward ', 'Right Forward', 'Spot Left', 'Spot Right'] # # confusion_matrix = classification # confusion_matrix = confusion_matrix.astype('float') / confusion_matrix.sum(axis=1)[:, np.newaxis] # plt.figure(figsize=(11.8,8)) # plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Blues) # 按照像素显示出矩阵 # # plt.title('confusion_matrix') # # plt.colorbar() # tick_marks = np.arange(len(classes)) # plt.xticks(tick_marks, classes,rotation="25",size=20) # plt.yticks(tick_marks, classes,size=20) # thresh = confusion_matrix.max() / 2 # # iters = [[i,j] for i in range(len(classes)) for j in range((classes))] # # ij配对,遍历矩阵迭代器 # iters = np.reshape([[[i, j] for j in range(6)] for i in range(6)], (confusion_matrix.size, 2)) # for i, j in iters: # plt.text(j, i, "%.3f"%(confusion_matrix[i, j]), horizontalalignment="center", # color='white' if confusion_matrix[i, j] > thresh else 'black',size=24) # 显示对应的数字 # plt.ylabel('Real',size=20) # plt.xlabel('Prediction',size=25) # plt.tight_layout() # plt.show()
usegalaxy-no/usegalaxy
venv/lib/python3.6/site-packages/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_template_info.py
# -*- coding: utf-8 -*- # # Dell EMC OpenManage Ansible Modules # Version 2.1.3 # Copyright (C) 2020 Dell Inc. or its subsidiaries. All Rights Reserved. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import pytest import json from ansible_collections.dellemc.openmanage.plugins.modules import ome_template_info from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError from ansible.module_utils.urls import ConnectionError, SSLValidationError from ansible_collections.dellemc.openmanage.tests.unit.plugins.modules.common import FakeAnsibleModule from io import StringIO from ansible.module_utils._text import to_text MODULE_PATH = 'ansible_collections.dellemc.openmanage.plugins.modules.' @pytest.fixture def ome_connection_template_info_mock(mocker, ome_response_mock): connection_class_mock = mocker.patch(MODULE_PATH + 'ome_template_info.RestOME') ome_connection_mock_obj = connection_class_mock.return_value.__enter__.return_value ome_connection_mock_obj.invoke_request.return_value = ome_response_mock return ome_connection_mock_obj class TestOmeTemplateInfo(FakeAnsibleModule): module = ome_template_info @pytest.mark.parametrize("module_params,data", [({"system_query_options": {"filter": "abc"}}, "$filter")]) def test_get_query_parameters(self, module_params, data): res = self.module._get_query_parameters(module_params) if data is not None: assert data in res else: assert res is None def test_get_template_info_success_case01(self, ome_default_args, ome_connection_template_info_mock, ome_response_mock): ome_response_mock.json_data = {"value": [""]} ome_response_mock.status_code = 200 result = self._run_module(ome_default_args) assert 'template_info' in result def test_get_template_info_success_case02(self, mocker, ome_default_args, ome_connection_template_info_mock, ome_response_mock): ome_default_args.update({"template_id": "24"}) ome_response_mock.success = True ome_response_mock.json_data = {"value": [{"template_id": "24"}]} ome_response_mock.status_code = 200 result = self._run_module(ome_default_args) assert result['changed'] is False assert 'template_info' in result def test_get_template_info_success_case03(self, mocker, ome_default_args, ome_connection_template_info_mock, ome_response_mock): mocker.patch(MODULE_PATH + 'ome_template_info._get_query_parameters', return_value={"filter": "abc"}) ome_default_args.update({"system_query_options": {"filter": "abc"}}) ome_response_mock.success = True ome_response_mock.json_data = {"value": [{"filter": "abc"}]} ome_response_mock.status_code = 200 result = self._run_module(ome_default_args) assert result['changed'] is False assert 'template_info' in result def test_get_template_info_failure_case(self, ome_default_args, ome_connection_template_info_mock, ome_response_mock): ome_response_mock.status_code = 500 result = self._run_module_with_fail_json(ome_default_args) assert result['msg'] == 'Failed to fetch the template facts' @pytest.mark.parametrize("exc_type", [URLError, HTTPError, SSLValidationError, ConnectionError, TypeError, ValueError]) def test_ome_template_info_main_exception_handling_case(self, exc_type, mocker, ome_default_args, ome_connection_template_info_mock, ome_response_mock): ome_response_mock.status_code = 400 ome_response_mock.success = False json_str = to_text(json.dumps({"data": "out"})) if exc_type not in [HTTPError, SSLValidationError]: ome_connection_template_info_mock.invoke_request.side_effect = exc_type('test') else: ome_connection_template_info_mock.invoke_request.side_effect = exc_type('http://testhost.com', 400, 'http error message', {"accept-type": "application/json"}, StringIO(json_str)) result = self._run_module_with_fail_json(ome_default_args) assert 'template_info' not in result assert 'msg' in result assert result['failed'] is True
atsuoishimoto/kaaedit
kaa/filetype/html/htmlmode.py
<filename>kaa/filetype/html/htmlmode.py from collections import namedtuple from kaa.filetype.default import defaultmode from gappedbuf import re as gre from kaa.highlight import Tokenizer, Span, SingleToken, Token, SubSection, EndSection, SubTokenizer from kaa.theme import Theme, Style from kaa.filetype.javascript import javascriptmode from kaa.filetype.css import cssmode HTMLThemes = { 'default': Theme([ Style('html-tag', 'red', 'default'), Style('html-attrname', 'blue', 'default'), Style('html-attrvalue', 'yellow', 'default'), # css styles Style('css-selector', 'magenta', 'default'), Style('css-propname', 'green', 'default'), Style('css-propvalue', 'blue', 'default'), ]) } class HTMLTag(Token): def re_start(self): return r'<' def prepare(self, tokenizer): super().prepare(tokenizer) self.span_lt = self.assign_tokenid(tokenizer, 'html-tag') self.span_gt = self.assign_tokenid(tokenizer, 'html-tag') self.span_elemname = self.assign_tokenid(tokenizer, 'html-tag') self.span_attrname = self.assign_tokenid(tokenizer, 'html-attrname') self.span_attrvalue = self.assign_tokenid(tokenizer, 'html-attrvalue') self.span_elemws = self.assign_tokenid(tokenizer, 'default') def resume_pos(self, highlighter, tokenizer, doc, pos): # Returns top of current keyword if 0 < pos < len(doc.styles): p = doc.styles.rfindint([self.span_lt], 0, pos, comp_ne=False) if p != -1: return p return 0 def yield_jsattr(self, tokenizer, doc, match): f, t = match.span('ATTRVALUE') if match.group('Q1'): func = tokenizer.tokens.jsattr2 elif match.group('Q2'): func = tokenizer.tokens.jsattr1 else: # no quotation mark. ignore this value. yield match.start(), match.end(), self.span_attrvalue return match.end() yield f, f+1, self.span_attrvalue js_to, tok, close = yield from func.iter_subtokenizers(None, doc, f+1, None) pos = js_to if js_to < doc.endpos(): yield js_to, js_to+1, self.span_attrvalue pos = js_to + 1 return pos def yield_cssattr(self, tokenizer, doc, match): f, t = match.span('ATTRVALUE') if match.group('Q1'): func = tokenizer.tokens.cssattr2 elif match.group('Q2'): func = tokenizer.tokens.cssattr1 else: # no quotation mark. ignore this value. yield match.start(), match.end(), self.span_attrvalue return match.end() yield f, f+1, self.span_attrvalue pos, tok, close = yield from func.iter_subtokenizers(None, doc, f+1, None) return pos RE_ELEMNAME=gre.compile(r'\s*[^>\s]+') RE_CLOSE=gre.compile(r'\s*/?>', gre.S) RE_ATTRNAME=gre.compile(r'>|(?P<ATTRNAME>[-._:a-zA-Z0-9]+)(?P<EQUAL>\s*=)?\s*') RE_ATTRVALUE=gre.compile(r'\s*(?P<ATTRVALUE>({}))'.format( '|'.join(['[-._:a-zA-Z0-9]+', '(?P<Q1>"[^"]*")', "(?P<Q2>'[^']*')"]))) def iter_attrs(self, tokenizer, doc, pos): buf = doc.buf while True: m = self.RE_ATTRNAME.search(buf, pos) if not m: return pos if m.group() == '>': return pos # yield attribute name f, t = m.span('ATTRNAME') yield f, t, self.span_attrname attrname = m.group('ATTRNAME') # yield after attr-name pos = m.end() if t != pos: yield t, pos, self.span_elemws # has attribute value? if m.group('EQUAL'): # yield values after '=' m = self.RE_ATTRVALUE.match(buf, pos) if m: attrvalue = m.group('ATTRVALUE') f, t = m.span('ATTRVALUE') if attrname.lower().startswith('on'): pos = yield from self.yield_jsattr(tokenizer, doc, m) elif attrname.lower() == 'style': pos = yield from self.yield_cssattr(tokenizer, doc, m) else: yield f, t, self.span_attrvalue pos = t def iter_tokens(self, tokenizer, doc, pos): buf = doc.buf match = self.RE_ELEMNAME.match(buf, pos) if not match: yield pos, len(buf), self.span_elemws return yield (pos, match.end(), self.span_elemname) pos = match.end() pos = yield from self.iter_attrs(tokenizer, doc, pos) m = self.RE_CLOSE.match(buf, pos) if m: yield pos, m.end(), self.span_gt return m.end() else: if pos != len(buf): yield pos, len(buf), self.span_elemws return len(buf) def on_start(self, tokenizer, doc, pos, match): buf = doc.buf yield (match.start(), match.end(), self.span_lt) pos = match.end() for f, t, tokenid in self.iter_tokens(tokenizer, doc, match.end()): assert f < t assert pos <= f if pos != f: yield (pos, f, self.span_elemws) yield (f, t, tokenid) pos = t return pos, None, False def build_tokenizers(): HTMLTOKENS = namedtuple('htmltokens', ['keywords', 'comment', 'endtag', 'jsstart', 'cssstart', 'htmltag', 'jsattr1', 'jsattr2', 'cssattr1', 'cssattr2']) keywords=SingleToken('html-entityrefs', 'keyword', [r'&\w+;', r'&\#x[0-9a-hA-H]+;', r'&\#[0-9]+;']) comment=Span('html-comment', 'comment', r'<!--', r'--\s*>') endtag = Span('html-endtag', 'html-tag', r'</', r'>') htmltag = HTMLTag('html', 'default') jsstop = EndSection('end-javascript', 'html-tag', r'</\s*script\s*>') jstokenizer = javascriptmode.build_tokenizer(jsstop) jsstart = SubSection('start-javascript', 'html-tag', r'<\s*script(\s+[^>]*)*>', jstokenizer) csstokenizer = cssmode.build_tokenizer(r'</\s*style\s*>', 'html-tag') cssstart = SubSection('start-css', 'html-tag', r'<\s*style(\s+[^>]*)*>', csstokenizer) jsattr1 = SubTokenizer('sub-js', '', javascriptmode.build_tokenizer(terminates="'")) jsattr2 = SubTokenizer('sub-js', '', javascriptmode.build_tokenizer(terminates='"')) styleattr1 = SubTokenizer('sub-css', '', cssmode.build_proptokenizer("'", 'html-attrvalue')) styleattr2 = SubTokenizer('sub-css', '', cssmode.build_proptokenizer('"', 'html-attrvalue')) return [Tokenizer( HTMLTOKENS(keywords, comment, endtag, jsstart, cssstart, htmltag, jsattr1, jsattr2, styleattr1, styleattr2)), jstokenizer, csstokenizer] class HTMLMode(defaultmode.DefaultMode): MODENAME = 'HTML' def init_themes(self): super().init_themes() self.themes.append(HTMLThemes) def init_tokenizers(self): self.tokenizers = build_tokenizers()
Raikonen/main
src/test/java/seedu/savenus/model/food/UniqueFoodListTest.java
package seedu.savenus.model.food; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.savenus.logic.commands.CommandTestUtil.VALID_TAG_CHICKEN; import static seedu.savenus.testutil.Assert.assertThrows; import static seedu.savenus.testutil.TypicalMenu.CARBONARA; import static seedu.savenus.testutil.TypicalMenu.NASI_LEMAK; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import seedu.savenus.model.food.exceptions.DuplicateFoodException; import seedu.savenus.model.food.exceptions.FoodNotFoundException; import seedu.savenus.testutil.FoodBuilder; public class UniqueFoodListTest { private final UniqueFoodList uniqueFoodList = new UniqueFoodList(); @Test public void contains_nullfood_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueFoodList.contains(null)); } @Test public void contains_foodNotInList_returnsFalse() { assertFalse(uniqueFoodList.contains(CARBONARA)); } @Test public void contains_foodInList_returnsTrue() { uniqueFoodList.add(CARBONARA); assertTrue(uniqueFoodList.contains(CARBONARA)); } @Test public void contains_foodWithSameIdentityFieldsInList_returnsTrue() { uniqueFoodList.add(CARBONARA); Food editedAlice = new FoodBuilder(CARBONARA).withTags(VALID_TAG_CHICKEN) .build(); assertTrue(uniqueFoodList.contains(editedAlice)); } @Test public void add_nullfood_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueFoodList.add(null)); } @Test public void add_duplicatefood_throwsDuplicatefoodException() { uniqueFoodList.add(CARBONARA); assertThrows(DuplicateFoodException.class, () -> uniqueFoodList.add(CARBONARA)); } @Test public void setFood_nullTargetfood_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueFoodList.setFood(null, CARBONARA)); } @Test public void setFood_nullEditedfood_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueFoodList.setFood(CARBONARA, null)); } @Test public void setFood_targetfoodNotInList_throwsfoodNotFoundException() { assertThrows(FoodNotFoundException.class, () -> uniqueFoodList.setFood(CARBONARA, CARBONARA)); } @Test public void setFood_editedfoodisSameFood_success() { uniqueFoodList.add(CARBONARA); uniqueFoodList.setFood(CARBONARA, CARBONARA); UniqueFoodList expectedUniqueFoodList = new UniqueFoodList(); expectedUniqueFoodList.add(CARBONARA); assertEquals(expectedUniqueFoodList, uniqueFoodList); } @Test public void setFood_editedfoodHasSameIdentity_success() { uniqueFoodList.add(CARBONARA); Food editedAlice = new FoodBuilder(CARBONARA).withTags(VALID_TAG_CHICKEN) .build(); uniqueFoodList.setFood(CARBONARA, editedAlice); UniqueFoodList expectedUniqueFoodList = new UniqueFoodList(); expectedUniqueFoodList.add(editedAlice); assertEquals(expectedUniqueFoodList, uniqueFoodList); } @Test public void setFood_editedfoodHasDifferentIdentity_success() { uniqueFoodList.add(CARBONARA); uniqueFoodList.setFood(CARBONARA, NASI_LEMAK); UniqueFoodList expectedUniqueFoodList = new UniqueFoodList(); expectedUniqueFoodList.add(NASI_LEMAK); assertEquals(expectedUniqueFoodList, uniqueFoodList); } @Test public void setFood_editedfoodHasNonUniqueIdentity_throwsDuplicatefoodException() { uniqueFoodList.add(CARBONARA); uniqueFoodList.add(NASI_LEMAK); assertThrows(DuplicateFoodException.class, () -> uniqueFoodList.setFood(CARBONARA, NASI_LEMAK)); } @Test public void remove_nullfood_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueFoodList.remove(null)); } @Test public void remove_foodDoesNotExist_throwsfoodNotFoundException() { assertThrows(FoodNotFoundException.class, () -> uniqueFoodList.remove(CARBONARA)); } @Test public void remove_existingfood_removesfood() { uniqueFoodList.add(CARBONARA); uniqueFoodList.remove(CARBONARA); UniqueFoodList expectedUniqueFoodList = new UniqueFoodList(); assertEquals(expectedUniqueFoodList, uniqueFoodList); } @Test public void setFoods_nullUniqueFoodList_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueFoodList.setFoods((UniqueFoodList) null)); } @Test public void setFoods_uniqueFoodList_replacesOwnListWithProvidedUniqueFoodList() { uniqueFoodList.add(CARBONARA); UniqueFoodList expectedUniqueFoodList = new UniqueFoodList(); expectedUniqueFoodList.add(NASI_LEMAK); uniqueFoodList.setFoods(expectedUniqueFoodList); assertEquals(expectedUniqueFoodList, uniqueFoodList); } @Test public void setFoods_nullList_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueFoodList.setFoods((List<Food>) null)); } @Test public void setFoods_list_replacesOwnListWithProvidedList() { uniqueFoodList.add(CARBONARA); List<Food> foodList = Collections.singletonList(NASI_LEMAK); uniqueFoodList.setFoods(foodList); UniqueFoodList expectedUniqueFoodList = new UniqueFoodList(); expectedUniqueFoodList.add(NASI_LEMAK); assertEquals(expectedUniqueFoodList, uniqueFoodList); } @Test public void setFoods_listWithDuplicatefoods_throwsDuplicatefoodException() { List<Food> listWithDuplicateFoods = Arrays.asList(CARBONARA, CARBONARA); assertThrows(DuplicateFoodException.class, () -> uniqueFoodList.setFoods(listWithDuplicateFoods)); } @Test public void asUnmodifiableObservableList_modifyList_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> uniqueFoodList.asUnmodifiableObservableList().remove(0)); } }
sammcgeown/vra-sdk-go
pkg/client/blueprint/list_blueprints_using_get1_parameters.go
<reponame>sammcgeown/vra-sdk-go // Code generated by go-swagger; DO NOT EDIT. package blueprint // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" ) // NewListBlueprintsUsingGET1Params creates a new ListBlueprintsUsingGET1Params object, // with the default timeout for this client. // // Default values are not hydrated, since defaults are normally applied by the API server side. // // To enforce default values in parameter, use SetDefaults or WithDefaults. func NewListBlueprintsUsingGET1Params() *ListBlueprintsUsingGET1Params { return &ListBlueprintsUsingGET1Params{ timeout: cr.DefaultTimeout, } } // NewListBlueprintsUsingGET1ParamsWithTimeout creates a new ListBlueprintsUsingGET1Params object // with the ability to set a timeout on a request. func NewListBlueprintsUsingGET1ParamsWithTimeout(timeout time.Duration) *ListBlueprintsUsingGET1Params { return &ListBlueprintsUsingGET1Params{ timeout: timeout, } } // NewListBlueprintsUsingGET1ParamsWithContext creates a new ListBlueprintsUsingGET1Params object // with the ability to set a context for a request. func NewListBlueprintsUsingGET1ParamsWithContext(ctx context.Context) *ListBlueprintsUsingGET1Params { return &ListBlueprintsUsingGET1Params{ Context: ctx, } } // NewListBlueprintsUsingGET1ParamsWithHTTPClient creates a new ListBlueprintsUsingGET1Params object // with the ability to set a custom HTTPClient for a request. func NewListBlueprintsUsingGET1ParamsWithHTTPClient(client *http.Client) *ListBlueprintsUsingGET1Params { return &ListBlueprintsUsingGET1Params{ HTTPClient: client, } } /* ListBlueprintsUsingGET1Params contains all the parameters to send to the API endpoint for the list blueprints using get1 operation. Typically these are written to a http.Request. */ type ListBlueprintsUsingGET1Params struct { /* DollarOrderby. Sorting criteria in the format: property (asc|desc). Default sort order is descending on updatedAt. Sorting is supported on fields createdAt, updatedAt, createdBy, updatedBy, name. */ DollarOrderby []string /* DollarSelect. Fields to include in content. Use * to get all fields. */ DollarSelect []string /* DollarSkip. Number of records you want to skip Format: int32 */ DollarSkip *int32 /* DollarTop. Number of records you want Format: int32 */ DollarTop *int32 /* APIVersion. The version of the API in yyyy-MM-dd format (UTC). For versioning information please refer to /blueprint/api/about */ APIVersion *string /* Name. Filter by name */ Name *string /* Projects. A comma-separated list. Results must be associated with one of these project IDs. */ Projects []string /* PropertyGroups. Filter blueprints with any of the specified property groups */ PropertyGroups []string /* Released. Filter blueprints with at least one released version */ Released *bool /* Search. Search by name and description */ Search *string /* Versioned. Filter blueprints with at least one version */ Versioned *bool timeout time.Duration Context context.Context HTTPClient *http.Client } // WithDefaults hydrates default values in the list blueprints using get1 params (not the query body). // // All values with no default are reset to their zero value. func (o *ListBlueprintsUsingGET1Params) WithDefaults() *ListBlueprintsUsingGET1Params { o.SetDefaults() return o } // SetDefaults hydrates default values in the list blueprints using get1 params (not the query body). // // All values with no default are reset to their zero value. func (o *ListBlueprintsUsingGET1Params) SetDefaults() { // no default values defined for this parameter } // WithTimeout adds the timeout to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithTimeout(timeout time.Duration) *ListBlueprintsUsingGET1Params { o.SetTimeout(timeout) return o } // SetTimeout adds the timeout to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetTimeout(timeout time.Duration) { o.timeout = timeout } // WithContext adds the context to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithContext(ctx context.Context) *ListBlueprintsUsingGET1Params { o.SetContext(ctx) return o } // SetContext adds the context to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetContext(ctx context.Context) { o.Context = ctx } // WithHTTPClient adds the HTTPClient to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithHTTPClient(client *http.Client) *ListBlueprintsUsingGET1Params { o.SetHTTPClient(client) return o } // SetHTTPClient adds the HTTPClient to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetHTTPClient(client *http.Client) { o.HTTPClient = client } // WithDollarOrderby adds the dollarOrderby to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithDollarOrderby(dollarOrderby []string) *ListBlueprintsUsingGET1Params { o.SetDollarOrderby(dollarOrderby) return o } // SetDollarOrderby adds the dollarOrderby to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetDollarOrderby(dollarOrderby []string) { o.DollarOrderby = dollarOrderby } // WithDollarSelect adds the dollarSelect to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithDollarSelect(dollarSelect []string) *ListBlueprintsUsingGET1Params { o.SetDollarSelect(dollarSelect) return o } // SetDollarSelect adds the dollarSelect to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetDollarSelect(dollarSelect []string) { o.DollarSelect = dollarSelect } // WithDollarSkip adds the dollarSkip to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithDollarSkip(dollarSkip *int32) *ListBlueprintsUsingGET1Params { o.SetDollarSkip(dollarSkip) return o } // SetDollarSkip adds the dollarSkip to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetDollarSkip(dollarSkip *int32) { o.DollarSkip = dollarSkip } // WithDollarTop adds the dollarTop to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithDollarTop(dollarTop *int32) *ListBlueprintsUsingGET1Params { o.SetDollarTop(dollarTop) return o } // SetDollarTop adds the dollarTop to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetDollarTop(dollarTop *int32) { o.DollarTop = dollarTop } // WithAPIVersion adds the aPIVersion to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithAPIVersion(aPIVersion *string) *ListBlueprintsUsingGET1Params { o.SetAPIVersion(aPIVersion) return o } // SetAPIVersion adds the apiVersion to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetAPIVersion(aPIVersion *string) { o.APIVersion = aPIVersion } // WithName adds the name to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithName(name *string) *ListBlueprintsUsingGET1Params { o.SetName(name) return o } // SetName adds the name to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetName(name *string) { o.Name = name } // WithProjects adds the projects to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithProjects(projects []string) *ListBlueprintsUsingGET1Params { o.SetProjects(projects) return o } // SetProjects adds the projects to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetProjects(projects []string) { o.Projects = projects } // WithPropertyGroups adds the propertyGroups to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithPropertyGroups(propertyGroups []string) *ListBlueprintsUsingGET1Params { o.SetPropertyGroups(propertyGroups) return o } // SetPropertyGroups adds the propertyGroups to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetPropertyGroups(propertyGroups []string) { o.PropertyGroups = propertyGroups } // WithReleased adds the released to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithReleased(released *bool) *ListBlueprintsUsingGET1Params { o.SetReleased(released) return o } // SetReleased adds the released to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetReleased(released *bool) { o.Released = released } // WithSearch adds the search to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithSearch(search *string) *ListBlueprintsUsingGET1Params { o.SetSearch(search) return o } // SetSearch adds the search to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetSearch(search *string) { o.Search = search } // WithVersioned adds the versioned to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) WithVersioned(versioned *bool) *ListBlueprintsUsingGET1Params { o.SetVersioned(versioned) return o } // SetVersioned adds the versioned to the list blueprints using get1 params func (o *ListBlueprintsUsingGET1Params) SetVersioned(versioned *bool) { o.Versioned = versioned } // WriteToRequest writes these params to a swagger request func (o *ListBlueprintsUsingGET1Params) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if o.DollarOrderby != nil { // binding items for $orderby joinedDollarOrderby := o.bindParamDollarOrderby(reg) // query array param $orderby if err := r.SetQueryParam("$orderby", joinedDollarOrderby...); err != nil { return err } } if o.DollarSelect != nil { // binding items for $select joinedDollarSelect := o.bindParamDollarSelect(reg) // query array param $select if err := r.SetQueryParam("$select", joinedDollarSelect...); err != nil { return err } } if o.DollarSkip != nil { // query param $skip var qrDollarSkip int32 if o.DollarSkip != nil { qrDollarSkip = *o.DollarSkip } qDollarSkip := swag.FormatInt32(qrDollarSkip) if qDollarSkip != "" { if err := r.SetQueryParam("$skip", qDollarSkip); err != nil { return err } } } if o.DollarTop != nil { // query param $top var qrDollarTop int32 if o.DollarTop != nil { qrDollarTop = *o.DollarTop } qDollarTop := swag.FormatInt32(qrDollarTop) if qDollarTop != "" { if err := r.SetQueryParam("$top", qDollarTop); err != nil { return err } } } if o.APIVersion != nil { // query param apiVersion var qrAPIVersion string if o.APIVersion != nil { qrAPIVersion = *o.APIVersion } qAPIVersion := qrAPIVersion if qAPIVersion != "" { if err := r.SetQueryParam("apiVersion", qAPIVersion); err != nil { return err } } } if o.Name != nil { // query param name var qrName string if o.Name != nil { qrName = *o.Name } qName := qrName if qName != "" { if err := r.SetQueryParam("name", qName); err != nil { return err } } } if o.Projects != nil { // binding items for projects joinedProjects := o.bindParamProjects(reg) // query array param projects if err := r.SetQueryParam("projects", joinedProjects...); err != nil { return err } } if o.PropertyGroups != nil { // binding items for propertyGroups joinedPropertyGroups := o.bindParamPropertyGroups(reg) // query array param propertyGroups if err := r.SetQueryParam("propertyGroups", joinedPropertyGroups...); err != nil { return err } } if o.Released != nil { // query param released var qrReleased bool if o.Released != nil { qrReleased = *o.Released } qReleased := swag.FormatBool(qrReleased) if qReleased != "" { if err := r.SetQueryParam("released", qReleased); err != nil { return err } } } if o.Search != nil { // query param search var qrSearch string if o.Search != nil { qrSearch = *o.Search } qSearch := qrSearch if qSearch != "" { if err := r.SetQueryParam("search", qSearch); err != nil { return err } } } if o.Versioned != nil { // query param versioned var qrVersioned bool if o.Versioned != nil { qrVersioned = *o.Versioned } qVersioned := swag.FormatBool(qrVersioned) if qVersioned != "" { if err := r.SetQueryParam("versioned", qVersioned); err != nil { return err } } } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } // bindParamListBlueprintsUsingGET1 binds the parameter $orderby func (o *ListBlueprintsUsingGET1Params) bindParamDollarOrderby(formats strfmt.Registry) []string { dollarOrderbyIR := o.DollarOrderby var dollarOrderbyIC []string for _, dollarOrderbyIIR := range dollarOrderbyIR { // explode []string dollarOrderbyIIV := dollarOrderbyIIR // string as string dollarOrderbyIC = append(dollarOrderbyIC, dollarOrderbyIIV) } // items.CollectionFormat: "multi" dollarOrderbyIS := swag.JoinByFormat(dollarOrderbyIC, "multi") return dollarOrderbyIS } // bindParamListBlueprintsUsingGET1 binds the parameter $select func (o *ListBlueprintsUsingGET1Params) bindParamDollarSelect(formats strfmt.Registry) []string { dollarSelectIR := o.DollarSelect var dollarSelectIC []string for _, dollarSelectIIR := range dollarSelectIR { // explode []string dollarSelectIIV := dollarSelectIIR // string as string dollarSelectIC = append(dollarSelectIC, dollarSelectIIV) } // items.CollectionFormat: "multi" dollarSelectIS := swag.JoinByFormat(dollarSelectIC, "multi") return dollarSelectIS } // bindParamListBlueprintsUsingGET1 binds the parameter projects func (o *ListBlueprintsUsingGET1Params) bindParamProjects(formats strfmt.Registry) []string { projectsIR := o.Projects var projectsIC []string for _, projectsIIR := range projectsIR { // explode []string projectsIIV := projectsIIR // string as string projectsIC = append(projectsIC, projectsIIV) } // items.CollectionFormat: "multi" projectsIS := swag.JoinByFormat(projectsIC, "multi") return projectsIS } // bindParamListBlueprintsUsingGET1 binds the parameter propertyGroups func (o *ListBlueprintsUsingGET1Params) bindParamPropertyGroups(formats strfmt.Registry) []string { propertyGroupsIR := o.PropertyGroups var propertyGroupsIC []string for _, propertyGroupsIIR := range propertyGroupsIR { // explode []string propertyGroupsIIV := propertyGroupsIIR // string as string propertyGroupsIC = append(propertyGroupsIC, propertyGroupsIIV) } // items.CollectionFormat: "multi" propertyGroupsIS := swag.JoinByFormat(propertyGroupsIC, "multi") return propertyGroupsIS }
vietnux/CodeEditorMobile
examples/ru.iiec.cxxdroid/sources/com/google/android/gms/internal/ads/c10.java
package com.google.android.gms.internal.ads; import com.google.android.gms.ads.internal.x0; import java.util.ArrayList; @k2 public final class c10 { private final int a; /* renamed from: b reason: collision with root package name */ private final int f3949b; /* renamed from: c reason: collision with root package name */ private final int f3950c; /* renamed from: d reason: collision with root package name */ private final p10 f3951d; /* renamed from: e reason: collision with root package name */ private final z10 f3952e; /* renamed from: f reason: collision with root package name */ private final Object f3953f = new Object(); /* renamed from: g reason: collision with root package name */ private ArrayList<String> f3954g = new ArrayList<>(); /* renamed from: h reason: collision with root package name */ private ArrayList<String> f3955h = new ArrayList<>(); /* renamed from: i reason: collision with root package name */ private ArrayList<n10> f3956i = new ArrayList<>(); /* renamed from: j reason: collision with root package name */ private int f3957j = 0; /* renamed from: k reason: collision with root package name */ private int f3958k = 0; /* renamed from: l reason: collision with root package name */ private int f3959l = 0; /* renamed from: m reason: collision with root package name */ private int f3960m; private String n = ""; private String o = ""; private String p = ""; public c10(int i2, int i3, int i4, int i5, int i6, int i7, int i8) { this.a = i2; this.f3949b = i3; this.f3950c = i4; this.f3951d = new p10(i5); this.f3952e = new z10(i6, i7, i8); } private static String a(ArrayList<String> arrayList, int i2) { if (arrayList.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); int size = arrayList.size(); int i3 = 0; while (i3 < size) { String str = arrayList.get(i3); i3++; sb.append(str); sb.append(' '); if (sb.length() > 100) { break; } } sb.deleteCharAt(sb.length() - 1); String sb2 = sb.toString(); return sb2.length() < 100 ? sb2 : sb2.substring(0, 100); } private final void c(String str, boolean z, float f2, float f3, float f4, float f5) { if (str != null && str.length() >= this.f3950c) { synchronized (this.f3953f) { this.f3954g.add(str); this.f3957j += str.length(); if (z) { this.f3955h.add(str); this.f3956i.add(new n10(f2, f3, f4, f5, this.f3955h.size() - 1)); } } } } public final int a() { return this.f3960m; } public final void a(int i2) { this.f3958k = i2; } public final void a(String str, boolean z, float f2, float f3, float f4, float f5) { c(str, z, f2, f3, f4, f5); synchronized (this.f3953f) { if (this.f3959l < 0) { qc.b("ActivityContent: negative number of WebViews."); } i(); } } public final String b() { return this.n; } public final void b(String str, boolean z, float f2, float f3, float f4, float f5) { c(str, z, f2, f3, f4, f5); } public final boolean c() { boolean z; synchronized (this.f3953f) { z = this.f3959l == 0; } return z; } public final String d() { return this.o; } public final String e() { return this.p; } public final boolean equals(Object obj) { if (!(obj instanceof c10)) { return false; } if (obj == this) { return true; } String str = ((c10) obj).n; return str != null && str.equals(this.n); } public final void f() { synchronized (this.f3953f) { this.f3960m -= 100; } } public final void g() { synchronized (this.f3953f) { this.f3959l--; } } public final void h() { synchronized (this.f3953f) { this.f3959l++; } } public final int hashCode() { return this.n.hashCode(); } public final void i() { synchronized (this.f3953f) { int i2 = (this.f3957j * this.a) + (this.f3958k * this.f3949b); if (i2 > this.f3960m) { this.f3960m = i2; if (((Boolean) a50.g().a(k80.W)).booleanValue() && !x0.j().m().b()) { this.n = this.f3951d.a(this.f3954g); this.o = this.f3951d.a(this.f3955h); } if (((Boolean) a50.g().a(k80.Y)).booleanValue() && !x0.j().m().d()) { this.p = this.f3952e.a(this.f3955h, this.f3956i); } } } } /* access modifiers changed from: package-private */ public final int j() { return this.f3957j; } public final String toString() { int i2 = this.f3958k; int i3 = this.f3960m; int i4 = this.f3957j; String a2 = a(this.f3954g, 100); String a3 = a(this.f3955h, 100); String str = this.n; String str2 = this.o; String str3 = this.p; StringBuilder sb = new StringBuilder(String.valueOf(a2).length() + 165 + String.valueOf(a3).length() + String.valueOf(str).length() + String.valueOf(str2).length() + String.valueOf(str3).length()); sb.append("ActivityContent fetchId: "); sb.append(i2); sb.append(" score:"); sb.append(i3); sb.append(" total_length:"); sb.append(i4); sb.append("\n text: "); sb.append(a2); sb.append("\n viewableText"); sb.append(a3); sb.append("\n signture: "); sb.append(str); sb.append("\n viewableSignture: "); sb.append(str2); sb.append("\n viewableSignatureForVertical: "); sb.append(str3); return sb.toString(); } }
JaidenAshmore/java-dynamic-sqs-listener
spring/spring-core/src/main/java/com/jashmore/sqs/spring/util/IdentifierUtils.java
package com.jashmore.sqs.spring.util; import static com.jashmore.sqs.util.string.StringUtils.toLowerHyphenCase; import java.lang.reflect.Method; import lombok.experimental.UtilityClass; import org.springframework.util.StringUtils; @UtilityClass public class IdentifierUtils { /** * Builds an identifier from a provided identifier if it is not empty, otherwise build an identifier from the class and method. * * @param identifier the identifier to use if it is not an empty string * @param clazz the class that the method is on, used if no identifier supplied * @param method the method used for the message listener, used if no identifier supplied * @return an identifier for this class' method */ public String buildIdentifierForMethod(final String identifier, final Class<?> clazz, final Method method) { if (!StringUtils.hasText(identifier.trim())) { return toLowerHyphenCase(clazz.getSimpleName() + "-" + method.getName()); } else { return identifier.trim(); } } }
kangsup/maybler0
day2_A.py
<reponame>kangsup/maybler0<filename>day2_A.py<gh_stars>0 print() print() #Ex. 9-3_Concept2 class bread: material='팥' def result(self): print("%s빵" %self.material) class fish_bread(bread): def fish_result(self): print('%s맛 붕어빵' %self.material) a_fish_bread = fish_bread() a_fish_bread.fish_result() a_fish_bread.result()
kiloline/ArrayList_Simulate_DB
src/Data/classes/Sequence.java
<reponame>kiloline/ArrayList_Simulate_DB<gh_stars>0 package Data.classes; /** * * @author rkppo */ public class Sequence { Exception e; String Sequence_name; //序列名 long Serial_number; //序列当前值 long Start_number; //序列最小值/开始值 long Abort_number; //序列最大值/截至值 boolean Recycle; //是否允许循环 int Step_length; //序列步长 public Sequence(String sequence_name) { this.Sequence_name=sequence_name; this.Abort_number=Long.MAX_VALUE; this.Start_number=0; this.Serial_number=0; } public void setStart(long start) { this.Serial_number=start; this.Start_number=start; } public void setAbort(long abort) { this.Abort_number=abort; } public void setRecycle(boolean recycle) { this.Recycle=recycle; } public void setStep(int steplength) { this.Step_length=steplength; } public Long getNextVal() throws Exception { if(checkAbort()) { this.Serial_number=this.Serial_number+this.Step_length; return this.Serial_number; } else throw e; } public Long getCurrVal() throws Exception { if(checkAbort()) { Long temp=this.Serial_number; this.Serial_number=this.Serial_number+this.Step_length; return temp; } else throw e; } public void showSerial() { System.out.println(this.Serial_number); } private boolean checkAbort() { if(this.Serial_number+this.Step_length>this.Abort_number) { if(this.Recycle) { Serial_number=Serial_number-Abort_number+Start_number; return true; } else return false; } else return true; } }
freman/genesysapi
client/external_contacts/put_externalcontacts_organization_trustor_trustor_id_parameters.go
<reponame>freman/genesysapi // Code generated by go-swagger; DO NOT EDIT. package external_contacts // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" ) // NewPutExternalcontactsOrganizationTrustorTrustorIDParams creates a new PutExternalcontactsOrganizationTrustorTrustorIDParams object // with the default values initialized. func NewPutExternalcontactsOrganizationTrustorTrustorIDParams() *PutExternalcontactsOrganizationTrustorTrustorIDParams { var () return &PutExternalcontactsOrganizationTrustorTrustorIDParams{ timeout: cr.DefaultTimeout, } } // NewPutExternalcontactsOrganizationTrustorTrustorIDParamsWithTimeout creates a new PutExternalcontactsOrganizationTrustorTrustorIDParams object // with the default values initialized, and the ability to set a timeout on a request func NewPutExternalcontactsOrganizationTrustorTrustorIDParamsWithTimeout(timeout time.Duration) *PutExternalcontactsOrganizationTrustorTrustorIDParams { var () return &PutExternalcontactsOrganizationTrustorTrustorIDParams{ timeout: timeout, } } // NewPutExternalcontactsOrganizationTrustorTrustorIDParamsWithContext creates a new PutExternalcontactsOrganizationTrustorTrustorIDParams object // with the default values initialized, and the ability to set a context for a request func NewPutExternalcontactsOrganizationTrustorTrustorIDParamsWithContext(ctx context.Context) *PutExternalcontactsOrganizationTrustorTrustorIDParams { var () return &PutExternalcontactsOrganizationTrustorTrustorIDParams{ Context: ctx, } } // NewPutExternalcontactsOrganizationTrustorTrustorIDParamsWithHTTPClient creates a new PutExternalcontactsOrganizationTrustorTrustorIDParams object // with the default values initialized, and the ability to set a custom HTTPClient for a request func NewPutExternalcontactsOrganizationTrustorTrustorIDParamsWithHTTPClient(client *http.Client) *PutExternalcontactsOrganizationTrustorTrustorIDParams { var () return &PutExternalcontactsOrganizationTrustorTrustorIDParams{ HTTPClient: client, } } /*PutExternalcontactsOrganizationTrustorTrustorIDParams contains all the parameters to send to the API endpoint for the put externalcontacts organization trustor trustor Id operation typically these are written to a http.Request */ type PutExternalcontactsOrganizationTrustorTrustorIDParams struct { /*ExternalOrganizationID External Organization ID */ ExternalOrganizationID string /*TrustorID Trustor ID */ TrustorID string timeout time.Duration Context context.Context HTTPClient *http.Client } // WithTimeout adds the timeout to the put externalcontacts organization trustor trustor Id params func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) WithTimeout(timeout time.Duration) *PutExternalcontactsOrganizationTrustorTrustorIDParams { o.SetTimeout(timeout) return o } // SetTimeout adds the timeout to the put externalcontacts organization trustor trustor Id params func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } // WithContext adds the context to the put externalcontacts organization trustor trustor Id params func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) WithContext(ctx context.Context) *PutExternalcontactsOrganizationTrustorTrustorIDParams { o.SetContext(ctx) return o } // SetContext adds the context to the put externalcontacts organization trustor trustor Id params func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) SetContext(ctx context.Context) { o.Context = ctx } // WithHTTPClient adds the HTTPClient to the put externalcontacts organization trustor trustor Id params func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) WithHTTPClient(client *http.Client) *PutExternalcontactsOrganizationTrustorTrustorIDParams { o.SetHTTPClient(client) return o } // SetHTTPClient adds the HTTPClient to the put externalcontacts organization trustor trustor Id params func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } // WithExternalOrganizationID adds the externalOrganizationID to the put externalcontacts organization trustor trustor Id params func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) WithExternalOrganizationID(externalOrganizationID string) *PutExternalcontactsOrganizationTrustorTrustorIDParams { o.SetExternalOrganizationID(externalOrganizationID) return o } // SetExternalOrganizationID adds the externalOrganizationId to the put externalcontacts organization trustor trustor Id params func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) SetExternalOrganizationID(externalOrganizationID string) { o.ExternalOrganizationID = externalOrganizationID } // WithTrustorID adds the trustorID to the put externalcontacts organization trustor trustor Id params func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) WithTrustorID(trustorID string) *PutExternalcontactsOrganizationTrustorTrustorIDParams { o.SetTrustorID(trustorID) return o } // SetTrustorID adds the trustorId to the put externalcontacts organization trustor trustor Id params func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) SetTrustorID(trustorID string) { o.TrustorID = trustorID } // WriteToRequest writes these params to a swagger request func (o *PutExternalcontactsOrganizationTrustorTrustorIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error // path param externalOrganizationId if err := r.SetPathParam("externalOrganizationId", o.ExternalOrganizationID); err != nil { return err } // path param trustorId if err := r.SetPathParam("trustorId", o.TrustorID); err != nil { return err } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
diasbruno/mout
tests/spec/number/spec-MAX_SAFE_INTEGER.js
<filename>tests/spec/number/spec-MAX_SAFE_INTEGER.js<gh_stars>100-1000 define(['mout/number/MAX_SAFE_INTEGER'], function(MAX_SAFE_INTEGER){ describe('number/MAX_SAFE_INTEGER', function(){ it('should be equal (2 ^ 52) - 1', function(){ expect( MAX_SAFE_INTEGER ).toBe( Math.pow(2, 53) - 1 ); }); }); });
06needhamt/intellij-community
plugins/sh/src/com/intellij/sh/shellcheck/intention/ShDisableInspectionIntention.java
<gh_stars>0 // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.sh.shellcheck.intention; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.LowPriorityAction; import com.intellij.codeInspection.ex.InspectionProfileModifiableModelKt; import com.intellij.icons.AllIcons; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.psi.PsiFile; import com.intellij.sh.ShBundle; import com.intellij.sh.shellcheck.ShShellcheckInspection; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class ShDisableInspectionIntention implements IntentionAction, LowPriorityAction, Iconable { private final String myInspectionCode; private final String myMessage; public ShDisableInspectionIntention(String message, String inspectionCode) { myInspectionCode = inspectionCode; myMessage = message; } @NotNull @Override public String getText() { return ShBundle.message("sh.disable.inspection.text", myMessage); } @NotNull @Override public String getFamilyName() { return ShBundle.message("sh.shell.script"); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { return true; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { if (file == null) return; InspectionProfileModifiableModelKt.modifyAndCommitProjectProfile(project, it -> { ShShellcheckInspection tool = (ShShellcheckInspection)it.getUnwrappedTool(ShShellcheckInspection.SHORT_NAME, file); if (tool != null) { tool.disableInspection(myInspectionCode); } }); DaemonCodeAnalyzer.getInstance(project).restart(file); } @Override public boolean startInWriteAction() { return true; } @Override public Icon getIcon(int flags) { return AllIcons.Actions.Cancel; } }