max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,664 | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ambari.server.controller.spi;
/**
* A response for a single page of resources when pagination is used.
*/
public interface PageResponse {
/**
* Get the iterable set of resources for the page.
*
* @return the iterable set of resources
*/
Iterable<Resource> getIterable();
/**
* Get the offset of the first resource of the page.
*
* @return the offset
*/
int getOffset();
/**
* Get the last resource before this page.
*
* @return the last resource before this page; null if this is the first page
*/
Resource getPreviousResource();
/**
* Get the next resource after this page.
*
* @return the next resource after this page; null if this is the last page
*/
Resource getNextResource();
/**
* Get the count of total resources without account for paging request.
* @return total count
*/
Integer getTotalResourceCount();
}
| 478 |
971 | /**
* Description: BulkDocumentVo.java
* All Rights Reserved.
* @version 4.1 2016-6-1 上午10:49:50 by 李洪波(<EMAIL>)创建
*/
package com.ucar.datalink.flinker.plugin.reader.esreader.client.rest.vo;
import com.ucar.datalink.flinker.plugin.reader.esreader.client.rest.utils.Assert;
import org.apache.commons.lang.StringUtils;
import java.io.Serializable;
/**
* 批量提交vo
* <br/> Created on 2016-6-1 上午10:49:50
* @author 李洪波(<EMAIL>)
* @since 4.1
*/
public class BatchDocVo extends VoItf implements Serializable {
private String batchType ;
/**
* 记录拼装后的批量操作内容,监控统计使用
*/
private String contents;
public BatchDocVo() {}
public BatchDocVo(String clusterName) {
super.clusterName = clusterName;
}
public String getBatchType() {
return batchType;
}
public void setBatchType(String batchType) {
this.batchType = batchType;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
/* (non-Javadoc)
* @see com.ucar.datalink.flinker.plugin.reader.esreader.vo.VoItf#getUrl()
*/
@Override
public String getUrl() {
if(StringUtils.isEmpty(this.batchType)){
throw new IllegalArgumentException("batchType is not null!");
}
String url = "http://" + host ;
if(!StringUtils.isEmpty(index)){
url = url + "/" + index ;
}
if(!StringUtils.isEmpty(type)) {
Assert.notNull(index, "when type is not null,index con't be null!");
url = url + "/" + type ;
}
url = url + "/" + this.batchType;
return url;
}
@Override
public String toString() {
return "BatchDocVo{" +
"batchType='" + batchType + '\'' +
", contents='" + contents + '\'' +
", index='" + index + '\'' +
", type='" + type + '\'' +
", clusterName='" + clusterName + '\'' +
", host='" + host + '\'' +
'}';
}
}
| 885 |
2,780 | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "beringei/lib/PersistentKeyList.h"
#include <folly/compression/Compression.h>
#include <folly/io/IOBuf.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include "beringei/lib/GorillaStatsManager.h"
namespace facebook {
namespace gorilla {
// For reads and compaction. Can probably be arbitrarily large.
const static size_t kLargeBufferSize = 1 << 24;
// Flush after 4k of keys.
const static size_t kSmallBufferSize = 1 << 12;
const static int kTempFileId = 0;
const int KRetryFileOpen = 3;
constexpr static char kCompressedFileWithTimestampsMarker = '2';
constexpr static char kUncompressedFileWithTimestampsMarker = '3';
constexpr static char kAppendMarker = 'a';
constexpr static char kDeleteMarker = 'd';
const static std::string kFileType = "key_list";
const static std::string kFailedCounter = "failed_writes." + kFileType;
// Marker bytes to determine if the file is compressed or not and if
// there are categories or not.
const static uint32_t kHardFlushIntervalSecs = 120;
PersistentKeyList::PersistentKeyList(
int64_t shardId,
const std::string& dataDirectory)
: activeList_({nullptr, ""}),
files_(shardId, kFileType, dataDirectory),
lock_(),
shard_(shardId) {
GorillaStatsManager::addStatExportType(kFailedCounter, SUM);
// Randomly select the next flush time within the interval to spread
// the fflush calls between shards.
nextHardFlushTimeSecs_ = time(nullptr) + random() % kHardFlushIntervalSecs;
openNext();
}
bool PersistentKeyList::appendKey(
uint32_t id,
const char* key,
uint16_t category,
int32_t timestamp) {
std::lock_guard<std::mutex> guard(lock_);
if (activeList_.file == nullptr) {
return false;
}
writeKey(id, key, category, timestamp);
return true;
}
bool PersistentKeyList::compactToFile(
FILE* f,
const std::string& fileName,
std::function<std::tuple<uint32_t, const char*, uint16_t, int32_t>()>
generator) {
folly::fbstring buffer;
for (auto key = generator(); std::get<1>(key) != nullptr; key = generator()) {
appendBuffer(
buffer,
std::get<0>(key),
std::get<1>(key),
std::get<2>(key),
std::get<3>(key));
}
if (buffer.length() == 0) {
fclose(f);
return false;
}
try {
auto ioBuffer = folly::IOBuf::wrapBuffer(buffer.data(), buffer.length());
auto codec = folly::io::getCodec(
folly::io::CodecType::ZLIB, folly::io::COMPRESSION_LEVEL_BEST);
auto compressed = codec->compress(ioBuffer.get());
compressed->coalesce();
if (fwrite(&kCompressedFileWithTimestampsMarker, sizeof(char), 1, f) != 1 ||
fwrite(compressed->data(), sizeof(char), compressed->length(), f) !=
compressed->length()) {
PLOG(ERROR) << "Could not write to the temporary key file " << fileName;
GorillaStatsManager::addStatValue(kFailedCounter, 1);
fclose(f);
return false;
}
LOG(INFO) << "Compressed key list from " << buffer.length() << " bytes to "
<< compressed->length();
} catch (std::exception& e) {
LOG(ERROR) << "Compression failed:" << e.what();
fclose(f);
return false;
}
// Swap the new data in for the old.
fclose(f);
return true;
}
bool PersistentKeyList::compactToBuffer(
std::function<std::tuple<uint32_t, const char*, uint16_t, int32_t>()>
generator,
uint64_t seq,
folly::fbstring& out) {
folly::fbstring buffer;
for (auto key = generator(); std::get<1>(key) != nullptr; key = generator()) {
appendBuffer(
buffer,
std::get<0>(key),
std::get<1>(key),
std::get<2>(key),
std::get<3>(key));
}
if (buffer.empty()) {
return false;
}
try {
auto ioBuffer = folly::IOBuf::wrapBuffer(buffer.data(), buffer.length());
auto codec = folly::io::getCodec(
folly::io::CodecType::ZLIB, folly::io::COMPRESSION_LEVEL_BEST);
auto compressed = codec->compress(ioBuffer.get());
compressed->coalesce();
out.reserve(compressed->length() + 1 + 8);
out.append((char*)(&seq), 8);
out.append(&kCompressedFileWithTimestampsMarker, 1);
out.append((char*)compressed->data(), compressed->length());
} catch (const std::exception& e) {
LOG(ERROR) << "Compression failed:" << e.what();
return false;
}
return true;
}
void PersistentKeyList::compact(
std::function<std::tuple<uint32_t, const char*, uint16_t, int32_t>()>
generator) {
// Direct appends to a new file.
int64_t prev = openNext();
// Create a temporary compressed file.
auto tempFile = files_.open(kTempFileId, "wb", kLargeBufferSize);
if (!tempFile.file) {
PLOG(ERROR) << "Could not open a temp file for writing keys";
GorillaStatsManager::addStatValue(kFailedCounter, 1);
return;
}
if (!compactToFile(tempFile.file, tempFile.name, generator)) {
return;
}
files_.rename(kTempFileId, prev);
// Clean up remaining files.
files_.clearTo(prev);
}
void PersistentKeyList::flush(bool hardFlush) {
if (activeList_.file == nullptr) {
openNext();
}
if (activeList_.file != nullptr) {
if (buffer_.length() > 0) {
size_t written = fwrite(
buffer_.data(), sizeof(char), buffer_.length(), activeList_.file);
if (written != buffer_.length()) {
PLOG(ERROR) << "Failed to flush key list file " << activeList_.name;
GorillaStatsManager::addStatValue(kFailedCounter, 1);
}
buffer_ = "";
}
if (hardFlush) {
fflush(activeList_.file);
}
} else {
// No file to flush to.
LOG(ERROR) << "Could not flush key list for shard " << shard_
<< " to disk. No open key_list file";
GorillaStatsManager::addStatValue(kFailedCounter, 1);
}
}
void PersistentKeyList::clearEntireListForTests() {
files_.clearAll();
openNext();
}
int64_t PersistentKeyList::openNext() {
std::lock_guard<std::mutex> guard(lock_);
if (activeList_.file != nullptr) {
fclose(activeList_.file);
}
std::vector<int64_t> ids = files_.ls();
int64_t activeId = ids.empty() ? 1 : ids.back() + 1;
activeList_ = files_.open(activeId, "wb", kSmallBufferSize);
int i = 0;
while (activeList_.file == nullptr && i < KRetryFileOpen) {
activeList_ = files_.open(activeId, "wb", kSmallBufferSize);
i++;
}
if (activeList_.file == nullptr) {
PLOG(ERROR) << "Couldn't open key_list." << activeId
<< " for writes (shard " << shard_ << ")";
return activeId - 1;
}
if (fwrite(
&kUncompressedFileWithTimestampsMarker,
sizeof(char),
1,
activeList_.file) != 1) {
PLOG(ERROR) << "Could not write to the key list file " << activeList_.name;
GorillaStatsManager::addStatValue(kFailedCounter, 1);
}
return activeId - 1;
}
void PersistentKeyList::appendBuffer(
folly::fbstring& buffer,
uint32_t id,
const char* key,
uint16_t category,
int32_t timestamp) {
const char* bytes = (const char*)&id;
for (int i = 0; i < sizeof(id); i++) {
buffer += bytes[i];
}
const char* categoryBytes = (const char*)&category;
for (int i = 0; i < sizeof(category); i++) {
buffer += categoryBytes[i];
}
const char* timestampBytes = (const char*)×tamp;
for (int i = 0; i < sizeof(timestamp); i++) {
buffer += timestampBytes[i];
}
buffer += key;
buffer += '\0';
}
void PersistentKeyList::writeKey(
uint32_t id,
const char* key,
uint16_t category,
int32_t timestamp) {
// Write to the internal buffer and only flush when needed.
appendBuffer(buffer_, id, key, category, timestamp);
bool flushHard = time(nullptr) > nextHardFlushTimeSecs_;
if (flushHard) {
nextHardFlushTimeSecs_ = time(nullptr) + kHardFlushIntervalSecs;
}
if (buffer_.length() >= kSmallBufferSize || flushHard) {
flush(flushHard);
}
}
std::unique_ptr<PersistentKeyListIf>
LocalPersistentKeyListFactory::getPersistentKeyList(
int64_t shardId,
const std::string& dir) const {
return std::make_unique<PersistentKeyList>(shardId, dir);
}
void PersistentKeyList::appendMarker(folly::fbstring& buffer, bool compressed) {
if (compressed) {
buffer += kCompressedFileWithTimestampsMarker;
} else {
buffer += kUncompressedFileWithTimestampsMarker;
}
}
void PersistentKeyList::appendOpMarker(folly::fbstring& buffer, bool append) {
if (append) {
buffer += kAppendMarker;
} else {
buffer += kDeleteMarker;
}
}
} // namespace gorilla
} // namespace facebook
| 3,339 |
410 | <reponame>PlayMe-Martin/XiMapper<gh_stars>100-1000
#pragma once
#include "BaseCmd.h"
#include "Application.h"
namespace ofx {
namespace piMapper {
class Application;
class ApplicationBaseMode;
class SetApplicationModeCmd : public BaseUndoCmd {
public:
SetApplicationModeCmd(
Application * app,
ApplicationBaseMode * st);
void exec();
void undo();
private:
Application * _application;
ApplicationBaseMode * _prevApplicationState;
ApplicationBaseMode * _applicationState;
ofPoint _translation;
};
} // namespace piMapper
} // namespace ofx
| 189 |
14,668 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/app_history/app_history_navigate_event.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_app_history_navigate_event_init.h"
#include "third_party/blink/renderer/core/app_history/app_history_destination.h"
#include "third_party/blink/renderer/core/dom/abort_signal.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/event_type_names.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/html/forms/form_data.h"
namespace blink {
AppHistoryNavigateEvent::AppHistoryNavigateEvent(
ExecutionContext* context,
const AtomicString& type,
AppHistoryNavigateEventInit* init)
: Event(type, init),
ExecutionContextClient(context),
navigation_type_(init->navigationType()),
destination_(init->destination()),
can_transition_(init->canTransition()),
user_initiated_(init->userInitiated()),
hash_change_(init->hashChange()),
signal_(init->signal()),
form_data_(init->formData()),
info_(init->hasInfo()
? init->info()
: ScriptValue(context->GetIsolate(),
v8::Undefined(context->GetIsolate()))) {
DCHECK(IsA<LocalDOMWindow>(context));
}
void AppHistoryNavigateEvent::transitionWhile(ScriptState* script_state,
ScriptPromise newNavigationAction,
ExceptionState& exception_state) {
if (!DomWindow()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"transitionWhile() may not be called in a "
"detached window");
return;
}
if (!isTrusted()) {
exception_state.ThrowSecurityError(
"transitionWhile() may only be called on a "
"trusted event during event dispatch");
return;
}
if (!can_transition_) {
exception_state.ThrowSecurityError(
"A navigation with URL '" + url_.ElidedString() +
"' cannot be intercepted by transitionWhile() in a window with origin "
"'" +
DomWindow()->GetSecurityOrigin()->ToString() + "' and URL '" +
DomWindow()->Url().ElidedString() + "'.");
return;
}
if (!IsBeingDispatched() || defaultPrevented()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"transitionWhile() may only be called during "
"the first dispatch of this event");
return;
}
navigation_action_promises_list_.push_back(newNavigationAction);
}
const AtomicString& AppHistoryNavigateEvent::InterfaceName() const {
return event_interface_names::kAppHistoryNavigateEvent;
}
void AppHistoryNavigateEvent::Trace(Visitor* visitor) const {
Event::Trace(visitor);
ExecutionContextClient::Trace(visitor);
visitor->Trace(destination_);
visitor->Trace(signal_);
visitor->Trace(form_data_);
visitor->Trace(info_);
visitor->Trace(navigation_action_promises_list_);
}
} // namespace blink
| 1,271 |
428 | <reponame>cping/LGame
/**
* Copyright 2008 - 2019 The Loon Game Engine 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.
*
* @project loon
* @author cping
* @email:<EMAIL>
* @version 0.5
*/
package loon.fx;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import loon.LSystem;
import loon.SoundImpl;
import loon.event.Updateable;
public class JavaFXAudio {
protected static <I> void dispatchLoaded(final SoundImpl<I> sound,
final I impl) {
Updateable update = new Updateable() {
@Override
public void action(Object a) {
sound.onLoaded(impl);
}
};
LSystem.unload(update);
}
protected static <I> void dispatchLoadError(final SoundImpl<I> sound,
final Throwable error) {
Updateable update = new Updateable() {
@Override
public void action(Object a) {
sound.onLoadError(error);
}
};
LSystem.unload(update);
}
public JavaFXMusic createSound(final String path, final InputStream in,
final boolean music) {
return null;
}
public void onPause() {
}
public void onResume() {
}
public void onDestroy() {
}
}
| 584 |
1,338 | <gh_stars>1000+
/*
** Copyright 2001, <NAME>. All rights reserved.
** Distributed under the terms of the NewOS License.
*/
#ifndef _ALPHA_KERNEL_H
#define _ALPHA_KERNEL_H
// memory layout
#define KERNEL_BASE 0x80000000
#define KERNEL_SIZE 0x80000000
#define USER_BASE 0x00000000
#define USER_SIZE 0x80000000
#endif
| 127 |
711 | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apiman.gateway.test.policies.beans;
/**
* A simple data bean. Used for testing.
*
* @author <EMAIL>
*/
public class DataBean {
private String property1;
private boolean property2;
private int property3;
/**
* Constructor.
*/
public DataBean() {
}
/**
* @return the property1
*/
public String getProperty1() {
return property1;
}
/**
* @param property1 the property1 to set
*/
public void setProperty1(String property1) {
this.property1 = property1;
}
/**
* @return the property2
*/
public boolean isProperty2() {
return property2;
}
/**
* @param property2 the property2 to set
*/
public void setProperty2(boolean property2) {
this.property2 = property2;
}
/**
* @return the property3
*/
public int getProperty3() {
return property3;
}
/**
* @param property3 the property3 to set
*/
public void setProperty3(int property3) {
this.property3 = property3;
}
}
| 618 |
1,514 | <reponame>Udbhavbisarya23/owtf
"""
PASSIVE Plugin for Testing for Cross site flashing (OWASP-DV-004)
"""
from owtf.managers.resource import get_resources
from owtf.plugin.helper import plugin_helper
DESCRIPTION = "Google Hacking for Cross Site Flashing"
def run(PluginInfo):
resource = get_resources("PassiveCrossSiteFlashingLnk")
Content = plugin_helper.resource_linklist("Online Resources", resource)
return Content
| 137 |
335 | <gh_stars>100-1000
{
"word": "Infrastructure",
"definitions": [
"The basic physical and organizational structures and facilities (e.g. buildings, roads, power supplies) needed for the operation of a society or enterprise."
],
"parts-of-speech": "Noun"
} | 91 |
1,210 | <filename>tools/SDKTool/src/WrappedDeviceAPI/deviceAPI/pcDevice/windows/windowsDeviceAPI.py<gh_stars>1000+
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making GameAISDK available.
This source code file is licensed under the GNU General Public License Version 3.
For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
"""
import time
import traceback
import logging
import win32gui
from ..iPcDeviceAPI import IPcDeviceAPI
from .APIDefine import LOG_DEFAULT
from .win32driver.capture import get_image, roi
from .win32driver.keyboard import Keyboard
from .win32driver.mouse import Mouse, MouseClickType, MouseFlag
from .win32driver.probe import Win32Probe, set_foreground_window
from .win32driver.by import QPath
class WindowsDeviceAPI(IPcDeviceAPI):
def __init__(self, platform):
IPcDeviceAPI.__init__(self, platform)
self.__logger = logging.getLogger(LOG_DEFAULT)
self._is_desktop_window = False
self._hwnd = None
self._qpath = None
self._windows_size = None
self._kwargs = {}
def Initialize(self, **kwargs):
hwnd = kwargs.get('hwnd', None)
query_path = kwargs.get('query_path', None)
window_size = kwargs.get('window_size', None)
if not hwnd and query_path is None:
hwnd = win32gui.GetDesktopWindow()
self._is_desktop_window = True
if not hwnd and query_path:
# hwnd = 0xE019DC
hwnds = Win32Probe().search_element(QPath(query_path))
cnt = len(hwnds)
if cnt > 1:
raise Exception('found multi windows by qpath(%s)' % query_path)
elif cnt == 0:
raise Exception('failed to find window by qpath(%s)' % query_path)
hwnd = hwnds[0]
if isinstance(hwnd, str) and hwnd.isdigit():
hwnd = int(hwnd)
if not win32gui.IsWindow(hwnd):
raise ValueError('hwnd(%s) is not valid' % hwnd)
if window_size:
l, t, r, b = win32gui.GetWindowRect(hwnd)
w = r - l
h = b - t
if abs(w - window_size[0]) > 50 or abs(h - window_size[1]) > 50:
raise Exception('window size is not equal, real(%s) != %s' % (str([w, h]), str(window_size)))
top_hwnd = Win32Probe().get_property(hwnd, 'TOPLEVELWINDOW')
if top_hwnd:
set_foreground_window(top_hwnd)
self._hwnd = hwnd
self._qpath = query_path
self._kwargs = kwargs
self._windows_size = window_size
return True
@property
def window_handle(self):
return self._hwnd
def DeInitialize(self):
return True
def ScreenCap(self, subrect=None):
"""
:param subrect:
:return:
"""
try:
img_data = get_image(self._hwnd)
if img_data is not None and subrect:
img_data = roi(img_data, subrect)
return img_data
except Exception as e:
self.__logger.error('screencap error: %s', e)
raise e
def _to_screen_pos(self, client_pos):
""" 将相对于窗口的坐标转成屏幕坐标
:param client_pos:
:return:
"""
if self._is_desktop_window:
return client_pos
x, y = client_pos
rc = win32gui.GetWindowRect(self._hwnd)
pt = (x + rc[0], y + rc[1])
return pt
def PressKey(self, key):
Keyboard.press_key(key)
def ReleaseKey(self, key):
Keyboard.release_key(key)
def InputKeys(self, keys, long_click_time):
# self.keyboard.inputKeys(keys)
Keyboard.input_keys(keys)
if long_click_time > 0:
time.sleep(long_click_time/1000)
def InputStrings(self, key_string):
Keyboard.input_keys(key_string)
# self.keyboard.inputString(key_string)
def MouseMove(self, px, py):
sx, sy = self._to_screen_pos((px, py))
Mouse.move(sx, sy)
# percent_x, percent_y = self.pixel_to_percent(px, py)
# self.mouse.move((percent_x, percent_y))
def MouseClick(self, px, py, by_post=False):
if by_post:
Mouse.post_click(self._hwnd, px, py)
else:
sx, sy = self._to_screen_pos((px, py))
Mouse.click(sx, sy)
# percent_x, percent_y = self.pixel_to_percent(px, py)
# self.mouse.click((percent_x, percent_y))
def MouseDoubleClick(self, px, py):
sx, sy = self._to_screen_pos((px, py))
Mouse.click(sx, sy, click_type=MouseClickType.DoubleClick)
# percent_x, percent_y = self.pixel_to_percent(px, py)
# self.mouse.doubleclick((percent_x, percent_y))
def MouseRightClick(self, px, py):
sx, sy = self._to_screen_pos((px, py))
Mouse.click(sx, sy, MouseFlag.RightButton)
# percent_x, percent_y = self.pixel_to_percent(px, py)
# self.mouse.rightclick((percent_x, percent_y))
def MouseLongClick(self, px, py, long_click_time):
"""
:param px:
:param py:
:param long_click_time: 长按时间,以毫秒为单位
:return:
"""
sx, sy = self._to_screen_pos((px, py))
Mouse.click(sx, sy)
time.sleep(long_click_time/1000)
# percent_x, percent_y = self.pixel_to_percent(px, py)
# self.mouse.longclick(long_click_time / 1000, (percent_x, percent_y))
def MouseDrag(self, from_x, from_y, to_x, to_y):
""" 从起点(from_x, from_y)拖动到(to_x, to_y)
:param from_x:
:param from_y:
:param to_x:
:param to_y:
:return:
"""
sfx, sfy = self._to_screen_pos((from_x, from_y))
stx, sty = self._to_screen_pos((to_x, to_y))
Mouse.drag(sfx, sfy, stx, sty)
| 2,852 |
367 | """Utility functions to create toy input for Cockpit's tests."""
import torch
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataset import Dataset
def load_toy_data(batch_size):
"""Build a ``DataLoader`` with specified batch size from the toy data."""
return DataLoader(ToyData(), batch_size=batch_size)
class ToyData(Dataset):
"""Toy data set used for testing. Consists of small random "images" and labels."""
def __init__(self, center=0.1):
"""Init the toy data set.
Args:
center (float): Center around which the data is randomly distributed.
"""
super(ToyData, self).__init__()
self._center = center
def __getitem__(self, index):
"""Return item with index `index` of data set.
Args:
index (int): Index of sample to access. Ignored for now.
Returns:
[tuple]: Tuple of (random) input and (random) label.
"""
item_input = torch.rand(1, 5, 5) + self._center
item_label = torch.randint(size=(), low=0, high=3)
return (item_input, item_label)
def __len__(self):
"""Length of dataset. Arbitrarily set to 10 000."""
return 10000 # of how many examples(images?) you have
| 492 |
897 | <gh_stars>100-1000
/******************************************************************************
Author - @Suvraneel
<NAME>
* Implementation of a Polynomial Addition & multiplication using Linked Lists in Java *
******************************************************************************/
import java.util.*;
class LinkedList
{
// Structure containing exponent and coefficient of variable
static class Term {
int coefficient;
int exponent;
//Link to next Term in singly LL
Term link;
}
// Function add a new Term at the end of list
static Term addTerm(Term head, int coefficient, int exponent)
{
// Create a new Term
Term nd = new Term();
nd.coefficient = coefficient;
nd.exponent = exponent;
//Link pointing to null because this is leaf node as of yet
nd.link = null;
// If linked list is empty
if (head == null)
return nd;
// Initiate a pointer at the head to start traversal
Term ptr = head;
// Traverse until leaf Term
while (ptr.link != null)
ptr = ptr.link;
//return leaf term
ptr.link = nd;
return head;
}
// Function to collapse the expanded form by merging duplicates in 1 term
static void collapse(Term head)
{
Term polyA;
Term polyB;
polyA = head;
//outer loop => for every term in poynomial,
while (polyA != null && polyA.link != null) {
polyB = polyA;
//inner loop => iterate through the rest of the loop to find redundant elements
while (polyB.link != null) {
// If exponent of two elements are same
if (polyA.exponent == polyB.link.exponent) {
// Collapse them onto the 1st occurance of that term (ie, term currently in outer loop)
polyA.coefficient += polyB.link.coefficient;
polyB.link = polyB.link.link;
}
// If exponent not same, check the other terms - inner loop
else polyB = polyB.link;
}
//check similarly for the next term as well - outer loop
polyA = polyA.link;
}
}
// Function two Add two polynomial Numbers
static Term sum(Term poly1, Term poly2, Term sumPoly)
{
// Initiate 2 pointers for the 2 polynomials
Term polyA;
polyA = poly1;
Term polyB;
polyB = poly2;
// Copy the terms of 1st polynomial to sumpoly
while (polyA != null) {
sumPoly = addTerm(sumPoly, polyA.coefficient, polyA.exponent);
polyA = polyA.link;
}
//Add the terms of 2nd polynomial to sumPoly
while (polyB != null) {
sumPoly = addTerm(sumPoly, polyB.coefficient, polyB.exponent);
polyB = polyB.link;
}
//call collapse function to minimise number of similar terms
collapse(sumPoly);
return sumPoly;
}
// Function two Multiply two polynomial Numbers
static Term multiply(Term poly1, Term poly2, Term pdtPoly)
{
// Initiate 2 pointers for traversing the 2 polynomials
Term polyA;
Term polyB;
polyA = poly1;
polyB = poly2;
//for every term in 1st polynomial, multiply it with each term in 2nd polynomial
while (polyA != null) {
while (polyB != null) {
int coefficient;
int exponent;
// Add the exponents to get result exponent
exponent = polyA.exponent + polyB.exponent;
// Call Multiply function passing the coefficients
coefficient = polyA.coefficient * polyB.coefficient;
// call addTerm function passing 3 parameters
// thus adding the resultant term as node in the resultant polynomial
pdtPoly = addTerm(pdtPoly, coefficient, exponent);
// move the pointer to the next term (node)
polyB = polyB.link;
}
// Reset the pointer for new loop
polyB = poly2;
//move the pointer to the next term (node)
polyA = polyA.link;
}
// collapse function (since pdt is in expanded form, minimise it)
collapse(pdtPoly);
return pdtPoly;
}
// Function To Display The passed polynomial's LL
static void displayPoly(Term ptr)
{
//traverse & keep printing as long as leaf node is not found
while (ptr.link != null) {
System.out.print( ptr.coefficient + "x^" + ptr.exponent + " + ");
ptr = ptr.link;
}
// Print the leaf node (ie, coefficient of x^0 term)
System.out.print( ptr.coefficient +"\n");
}
// Main Driver Code
public static void main(String[] args)
{
//Initiate nodes for holding input polynomials & resultant polynomials to null
Term poly1 = null;
Term poly2 = null;
Term sumPoly = null;
Term pdtPoly = null;
Scanner myObj = new Scanner(System.in);
//Take input for 1st polynomial
System.out.print("Enter number of terms in 1st Polynomial: \t");
int noOfTerms = myObj.nextInt();
System.out.print("Enter 1st Polynomial as <coefficient exponent> : \t");
for (int i=0; i<noOfTerms; i++){
int coff = myObj.nextInt();
int exp = myObj.nextInt();
// Add the term as a node into the 1st polynomial LL
poly1 = addTerm(poly1, coff, exp);
}
//Take input for 2nd polynomial
System.out.print("Enter number of terms in 2nd Polynomial: \t");
noOfTerms = myObj.nextInt();
System.out.print("Enter 2nd Polynomial as <coefficient exponent> : \t");
for (int i=0; i<noOfTerms; i++){
int coff = myObj.nextInt();
int exp = myObj.nextInt();
// Add the term as a node into the 2nd polynomial LL
poly2 = addTerm(poly2, coff, exp);
}
// Displaying 1st polynomial
System.out.print("1st Polynomial = \t\t");
displayPoly(poly1);
// Displaying 2nd polynomial
System.out.print("2nd Polynomial = \t\t");
displayPoly(poly2);
//calling sum function to evaluate (poly1 + poly2)
sumPoly = sum(poly1, poly2, sumPoly);
System.out.print( "Resultant Sum Polynomial = \t");
displayPoly(sumPoly);
// calling multiply function to evaluate (poly1 * poly2)
pdtPoly = multiply(poly1, poly2, pdtPoly);
// Displaying Resultant Polynomial
System.out.print( "Resultant Product Polynomial = \t");
displayPoly(pdtPoly);
}
}
/*
Time Complexity: O(n^2)
AddTerm = O(n)
Collapse = O(n^2)
Sum = O(n^2) (for collapse call)
Multiply = O(n^2)
Print LL = O(n)
Sample Run:
Enter number of terms in 1st Polynomial: 5
Enter 1st Polynomial as <coefficient exponent> : 10 6 5 4 3 3 4 1 7 0
Enter number of terms in 2nd Polynomial: 3
Enter 2nd Polynomial as <coefficient exponent> : 6 3 2 1 5 0
1st Polynomial = 10x^6 + 5x^4 + 3x^3 + 4x^1 + 7
2nd Polynomial = 6x^3 + 2x^1 + 5
Resultant Sum Polynomial = 10x^6 + 5x^4 + 9x^3 + 6x^1 + 12
Resultant Product Polynomial = 60x^9 + 50x^7 + 68x^6 + 10x^5 + 55x^4 + 57x^3 + 8x^2 + 34x^1 + 35
*/
| 2,448 |
5,098 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Simple generator and discriminator models.
Based on the convolutional and "deconvolutional" models presented in
"Unsupervised Representation Learning with Deep Convolutional Generative
Adversarial Networks" by <NAME>. al.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
def _leaky_relu(x):
return tf.nn.leaky_relu(x, alpha=0.2)
def _batch_norm(x, is_training, name):
return tf.layers.batch_normalization(
x, momentum=0.9, epsilon=1e-5, training=is_training, name=name)
def _dense(x, channels, name):
return tf.layers.dense(
x, channels,
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name=name)
def _conv2d(x, filters, kernel_size, stride, name):
return tf.layers.conv2d(
x, filters, [kernel_size, kernel_size],
strides=[stride, stride], padding='same',
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name=name)
def _deconv2d(x, filters, kernel_size, stride, name):
return tf.layers.conv2d_transpose(
x, filters, [kernel_size, kernel_size],
strides=[stride, stride], padding='same',
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name=name)
def discriminator(x, is_training=True, scope='Discriminator'):
# conv64-lrelu + conv128-bn-lrelu + fc1024-bn-lrelu + fc1
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
x = _conv2d(x, 64, 4, 2, name='d_conv1')
x = _leaky_relu(x)
x = _conv2d(x, 128, 4, 2, name='d_conv2')
x = _leaky_relu(_batch_norm(x, is_training, name='d_bn2'))
x = tf.reshape(x, [-1, 7 * 7 * 128])
x = _dense(x, 1024, name='d_fc3')
x = _leaky_relu(_batch_norm(x, is_training, name='d_bn3'))
x = _dense(x, 1, name='d_fc4')
return x
def generator(x, is_training=True, scope='Generator'):
# fc1024-bn-relu + fc6272-bn-relu + deconv64-bn-relu + deconv1-tanh
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
x = _dense(x, 1024, name='g_fc1')
x = tf.nn.relu(_batch_norm(x, is_training, name='g_bn1'))
x = _dense(x, 7 * 7 * 128, name='g_fc2')
x = tf.nn.relu(_batch_norm(x, is_training, name='g_bn2'))
x = tf.reshape(x, [-1, 7, 7, 128])
x = _deconv2d(x, 64, 4, 2, name='g_dconv3')
x = tf.nn.relu(_batch_norm(x, is_training, name='g_bn3'))
x = _deconv2d(x, 1, 4, 2, name='g_dconv4')
x = tf.tanh(x)
return x
# TODO(chrisying): objective score (e.g. MNIST score)
| 1,257 |
1,592 | # -*- coding: UTF-8 -*-
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2006-2021 NV Access Limited, <NAME>
# This file may be used under the terms of the GNU General Public License, version 2 or later.
# For more details see: https://www.gnu.org/licenses/gpl-2.0.html
import os
import sys
import globalVars
import languageHandler
def getDocFilePath(fileName, localized=True):
if not getDocFilePath.rootPath:
if hasattr(sys, "frozen"):
getDocFilePath.rootPath = os.path.join(globalVars.appDir, "documentation")
else:
getDocFilePath.rootPath = os.path.join(globalVars.appDir, "..", "user_docs")
if localized:
lang = languageHandler.getLanguage()
tryLangs = [lang]
if "_" in lang:
# This locale has a sub-locale, but documentation might not exist for the sub-locale, so try stripping it.
tryLangs.append(lang.split("_")[0])
# If all else fails, use English.
tryLangs.append("en")
fileName, fileExt = os.path.splitext(fileName)
for tryLang in tryLangs:
tryDir = os.path.join(getDocFilePath.rootPath, tryLang)
if not os.path.isdir(tryDir):
continue
# Some out of date translations might include .txt files which are now .html files in newer translations.
# Therefore, ignore the extension and try both .html and .txt.
for tryExt in ("html", "txt"):
tryPath = os.path.join(tryDir, f"{fileName}.{tryExt}")
if os.path.isfile(tryPath):
return tryPath
return None
else:
# Not localized.
if not hasattr(sys, "frozen") and fileName in ("copying.txt", "contributors.txt"):
# If running from source, these two files are in the root dir.
return os.path.join(globalVars.appDir, "..", fileName)
else:
return os.path.join(getDocFilePath.rootPath, fileName)
getDocFilePath.rootPath = None
| 644 |
365 | # -*- coding: utf-8 -*-
from benedict.dicts.io import IODict
from .test_io_dict import io_dict_test_case
class io_dict_xml_test_case(io_dict_test_case):
def test_from_xml_with_valid_data(self):
j = """
<?xml version="1.0" ?>
<root>
<a>1</a>
<b>
<c>3</c>
<d>4</d>
</b>
</root>
"""
# static method
d = IODict.from_xml(j)
self.assertTrue(isinstance(d, dict))
self.assertEqual(d.get('root'), { 'a':'1', 'b':{ 'c':'3', 'd':'4' },})
# constructor
d = IODict(j, format='xml')
self.assertTrue(isinstance(d, dict))
self.assertEqual(d.get('root'), { 'a':'1', 'b':{ 'c':'3', 'd':'4' },})
def test_from_xml_with_invalid_data(self):
j = 'Lorem ipsum est in ea occaecat nisi officia.'
# static method
with self.assertRaises(ValueError):
IODict.from_xml(j)
# constructor
with self.assertRaises(ValueError):
IODict(j, format='xml')
def test_from_xml_with_valid_file_valid_content(self):
filepath = self.input_path('valid-content.xml')
# static method
d = IODict.from_xml(filepath)
self.assertTrue(isinstance(d, dict))
# constructor
d = IODict(filepath, format='xml')
self.assertTrue(isinstance(d, dict))
# constructor with format autodetection
d = IODict(filepath)
self.assertTrue(isinstance(d, dict))
def test_from_xml_with_valid_file_valid_content_invalid_format(self):
filepath = self.input_path('valid-content.base64')
with self.assertRaises(ValueError):
IODict.from_xml(filepath)
filepath = self.input_path('valid-content.json')
with self.assertRaises(ValueError):
IODict.from_xml(filepath)
filepath = self.input_path('valid-content.qs')
with self.assertRaises(ValueError):
IODict.from_xml(filepath)
filepath = self.input_path('valid-content.toml')
with self.assertRaises(ValueError):
IODict.from_xml(filepath)
filepath = self.input_path('valid-content.yml')
with self.assertRaises(ValueError):
IODict.from_xml(filepath)
def test_from_xml_with_valid_file_invalid_content(self):
filepath = self.input_path('invalid-content.xml')
# static method
with self.assertRaises(ValueError):
IODict.from_xml(filepath)
# constructor
with self.assertRaises(ValueError):
IODict(filepath, format='xml')
def test_from_xml_with_invalid_file(self):
filepath = self.input_path('invalid-file.xml')
# static method
with self.assertRaises(ValueError):
IODict.from_xml(filepath)
# constructor
with self.assertRaises(ValueError):
IODict(filepath, format='xml')
def test_from_xml_with_valid_url_valid_content(self):
url = self.input_url('valid-content.xml')
# static method
d = IODict.from_xml(url)
self.assertTrue(isinstance(d, dict))
# constructor
d = IODict(url, format='xml')
self.assertTrue(isinstance(d, dict))
# constructor with format autodetection
d = IODict(url)
self.assertTrue(isinstance(d, dict))
def test_from_xml_with_valid_url_invalid_content(self):
url = 'https://github.com/fabiocaccamo/python-benedict'
# static method
with self.assertRaises(ValueError):
IODict.from_xml(url)
# constructor
with self.assertRaises(ValueError):
IODict(url, format='xml')
def test_from_xml_with_invalid_url(self):
url = 'https://github.com/fabiocaccamo/python-benedict-invalid'
# static method
with self.assertRaises(ValueError):
IODict.from_xml(url)
# constructor
with self.assertRaises(ValueError):
IODict(url, format='xml')
def test_to_xml(self):
d = IODict({
'root': {
'x': '7',
'y': '8',
'z': '9',
'a': '1',
'b': '2',
'c': '3',
},
})
s = d.to_xml()
self.assertEqual(d, IODict.from_xml(s))
def test_to_xml_file(self):
d = IODict({
'root': {
'x': '7',
'y': '8',
'z': '9',
'a': '1',
'b': '2',
'c': '3',
},
})
filepath = self.output_path('test_to_xml_file.xml')
d.to_xml(filepath=filepath)
self.assertFileExists(filepath)
self.assertEqual(d, IODict.from_xml(filepath))
| 2,400 |
593 | <reponame>dineshsonachalam/deeplearning4nlp-tutorial<filename>2016-11_Seminar/Session 4 - LSTM Sequence Classification/code/NER_BiLSTM.py
# -*- coding: utf-8 -*-
"""
This is a German NER implementation for the dataset GermEval 2014. Also check the folder 'Session 1 - SENNA' for some further information.
This model uses a bi-directional LSTM and runs over an input sentence. The output of the BiLSTM is inputted to a softmax-layer to derive
the probabilities for the different tags.
Single BiLSTM (100 hidden units), after 15 epochs:
Dev-Data: Prec: 0.789, Rec: 0.739, F1: 0.763
Test-Data: Prec: 0.781, Rec: 0.717, F1: 0.747
Stacked BiLSTM (2 layers, 64 hidden states), after 25 epochs:
Dev-Data: Prec: 0.804, Rec: 0.763, F1: 0.783
Test-Data: Prec: 0.795, Rec: 0.738, F1: 0.766
Code was written & tested with:
- Python 2.7
- Theano 0.8.2
- Keras 1.1.1
@author: <NAME>
"""
import numpy as np
import random
import time
import gzip
import cPickle as pkl
import BIOF1Validation
import keras
from keras.models import Sequential
from keras.layers.core import *
from keras.layers.wrappers import *
from keras.optimizers import *
from keras.utils import np_utils
from keras.layers.embeddings import Embedding
from keras.layers import LSTM
from docutils.languages.af import labels
f = gzip.open('pkl/embeddings.pkl.gz', 'rb')
embeddings = pkl.load(f)
f.close()
label2Idx = embeddings['label2Idx']
wordEmbeddings = embeddings['wordEmbeddings']
caseEmbeddings = embeddings['caseEmbeddings']
#Inverse label mapping
idx2Label = {v: k for k, v in label2Idx.items()}
f = gzip.open('pkl/data.pkl.gz', 'rb')
train_data = pkl.load(f)
dev_data = pkl.load(f)
test_data = pkl.load(f)
f.close()
#####################################
#
# Create the Network
#
#####################################
n_out = len(label2Idx)
tokens = Sequential()
tokens.add(Embedding(input_dim=wordEmbeddings.shape[0], output_dim=wordEmbeddings.shape[1], weights=[wordEmbeddings], trainable=False))
casing = Sequential()
casing.add(Embedding(output_dim=caseEmbeddings.shape[1], input_dim=caseEmbeddings.shape[0], weights=[caseEmbeddings], trainable=False))
model = Sequential();
model.add(Merge([tokens, casing], mode='concat'))
model.add(Bidirectional(LSTM(10, return_sequences=True, dropout_W=0.2)))
model.add(TimeDistributed(Dense(n_out, activation='softmax')))
sgd = SGD(lr=0.1, decay=1e-7, momentum=0.0, nesterov=False, clipvalue=3)
rmsprop = RMSprop(clipvalue=3)
model.compile(loss='sparse_categorical_crossentropy', optimizer=sgd)
model.summary()
##################################
#
# Training of the Network
#
##################################
def iterate_minibatches(dataset, startIdx, endIdx):
endIdx = min(len(dataset), endIdx)
for idx in xrange(startIdx, endIdx):
tokens, casing, labels = dataset[idx]
labels = np.expand_dims([labels], -1)
yield labels, np.asarray([tokens]), np.asarray([casing])
def tag_dataset(dataset):
correctLabels = []
predLabels = []
for tokens, casing, labels in dataset:
tokens = np.asarray([tokens])
casing = np.asarray([casing])
pred = model.predict_classes([tokens, casing], verbose=False)[0]
correctLabels.append(labels)
predLabels.append(pred)
return predLabels, correctLabels
number_of_epochs = 20
stepsize = 24000
print "%d epochs" % number_of_epochs
print "%d train sentences" % len(train_data)
print "%d dev sentences" % len(dev_data)
print "%d test sentences" % len(test_data)
for epoch in xrange(number_of_epochs):
print "--------- Epoch %d -----------" % epoch
random.shuffle(train_data)
for startIdx in xrange(0, len(train_data), stepsize):
start_time = time.time()
for batch in iterate_minibatches(train_data, startIdx, startIdx+stepsize):
labels, tokens, casing = batch
model.train_on_batch([tokens, casing], labels)
print "%.2f sec for training" % (time.time() - start_time)
#Train Dataset
start_time = time.time()
predLabels, correctLabels = tag_dataset(train_data)
pre_train, rec_train, f1_train = BIOF1Validation.compute_f1(predLabels, correctLabels, idx2Label)
print "Train-Data: Prec: %.3f, Rec: %.3f, F1: %.3f" % (pre_train, rec_train, f1_train)
#Dev Dataset
predLabels, correctLabels = tag_dataset(dev_data)
pre_dev, rec_dev, f1_dev = BIOF1Validation.compute_f1(predLabels, correctLabels, idx2Label)
print "Dev-Data: Prec: %.3f, Rec: %.3f, F1: %.3f" % (pre_dev, rec_dev, f1_dev)
#Test Dataset
predLabels, correctLabels = tag_dataset(test_data)
pre_test, rec_test, f1_test= BIOF1Validation.compute_f1(predLabels, correctLabels, idx2Label)
print "Test-Data: Prec: %.3f, Rec: %.3f, F1: %.3f" % (pre_test, rec_test, f1_test)
print "%.2f sec for evaluation" % (time.time() - start_time)
print ""
| 2,191 |
777 | <gh_stars>100-1000
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/components/tether/initializer.h"
namespace chromeos {
namespace tether {
void Initializer::Initialize() {}
Initializer::Initializer() {}
Initializer::~Initializer() {}
} // namespace tether
} // namespace chromeos
| 126 |
2,648 | # Copyright 2018 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://www.apache.org/licenses/LICENSE-2.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.
# Standard library imports
from typing import List, Optional
from itertools import product
# Third-party imports
import mxnet as mx
import numpy as np
# First-party imports
from gluonts.core.component import validated
from gluonts.mx import Tensor
from gluonts.mx.distribution import Distribution, DistributionOutput
from gluonts.mx.distribution import EmpiricalDistribution
from gluonts.mx.util import assert_shape
from gluonts.mx.distribution import LowrankMultivariateGaussian
from gluonts.model.deepvar._network import (
DeepVARNetwork,
DeepVARTrainingNetwork,
DeepVARPredictionNetwork,
)
def reconcile_samples(
reconciliation_mat: Tensor,
samples: Tensor,
seq_axis: Optional[List] = None,
) -> Tensor:
"""
Computes coherent samples by multiplying unconstrained `samples` with `reconciliation_mat`.
Parameters
----------
reconciliation_mat
Shape: (target_dim, target_dim)
samples
Unconstrained samples
Shape: `(*batch_shape, target_dim)`
During training: (num_samples, batch_size, seq_len, target_dim)
During prediction: (num_parallel_samples x batch_size, seq_len, target_dim)
seq_axis
Specifies the list of axes that should be reconciled sequentially.
By default, all axes are processeed in parallel.
Returns
-------
Tensor, shape same as that of `samples`
Coherent samples
"""
if not seq_axis:
return mx.nd.dot(samples, reconciliation_mat, transpose_b=True)
else:
num_dims = len(samples.shape)
last_dim_in_seq_axis = num_dims - 1 in seq_axis or -1 in seq_axis
assert (
not last_dim_in_seq_axis
), f"The last dimension cannot be processed iteratively. Remove axis {num_dims - 1} (or -1) from `seq_axis`."
# In this case, reconcile samples by going over each index in `seq_axis` iteratively.
# Note that `seq_axis` can be more than one dimension.
num_seq_axes = len(seq_axis)
# bring the axes to iterate in the beginning
samples = mx.nd.moveaxis(samples, seq_axis, list(range(num_seq_axes)))
seq_axes_sizes = samples.shape[:num_seq_axes]
out = [
mx.nd.dot(samples[idx], reconciliation_mat, transpose_b=True)
# get the sequential index from the cross-product of their sizes.
for idx in product(*[range(size) for size in seq_axes_sizes])
]
# put the axis in the correct order again
out = mx.nd.concat(*out, dim=0).reshape(samples.shape)
out = mx.nd.moveaxis(out, list(range(len(seq_axis))), seq_axis)
return out
def reconciliation_error(A: Tensor, samples: Tensor) -> float:
r"""
Computes the maximum relative reconciliation error among all the aggregated time series
.. math::
\max_i \frac{|y_i - s_i|} {|y_i|},
where :math:`i` refers to the aggregated time series index, :math:`y_i` is the (direct) forecast obtained for
the :math:`i^{th}` time series and :math:`s_i` is its aggregated forecast obtained by summing the corresponding
bottom-level forecasts. If :math:`y_i` is zero, then the absolute difference, :math:`|s_i|`, is used instead.
This can be comupted as follows given the constraint matrix A:
.. math::
\max \frac{|A \times samples|} {|samples[:r]|},
where :math:`r` is the number aggregated time series.
Parameters
----------
A
The constraint matrix A in the equation: Ay = 0 (y being the values/forecasts of all time series in the
hierarchy).
samples
Samples. Shape: `(*batch_shape, target_dim)`.
Returns
-------
Float
Reconciliation error
"""
num_agg_ts = A.shape[0]
forecasts_agg_ts = samples.slice_axis(
axis=-1, begin=0, end=num_agg_ts
).asnumpy()
abs_err = mx.nd.abs(mx.nd.dot(samples, A, transpose_b=True)).asnumpy()
rel_err = np.where(
forecasts_agg_ts == 0,
abs_err,
abs_err / np.abs(forecasts_agg_ts),
)
return np.max(rel_err)
class DeepVARHierarchicalNetwork(DeepVARNetwork):
@validated()
def __init__(
self,
M,
A,
num_layers: int,
num_cells: int,
cell_type: str,
history_length: int,
context_length: int,
prediction_length: int,
distr_output: DistributionOutput,
dropout_rate: float,
lags_seq: List[int],
target_dim: int,
cardinality: List[int] = [1],
embedding_dimension: int = 1,
scaling: bool = True,
seq_axis: List[int] = None,
**kwargs,
) -> None:
super().__init__(
num_layers=num_layers,
num_cells=num_cells,
cell_type=cell_type,
history_length=history_length,
context_length=context_length,
prediction_length=prediction_length,
distr_output=distr_output,
dropout_rate=dropout_rate,
lags_seq=lags_seq,
target_dim=target_dim,
cardinality=cardinality,
embedding_dimension=embedding_dimension,
scaling=scaling,
**kwargs,
)
self.M = M
self.A = A
self.seq_axis = seq_axis
def get_samples_for_loss(self, distr: Distribution) -> Tensor:
"""
Get samples to compute the final loss. These are samples directly drawn from the given `distr` if coherence is
not enforced yet; otherwise the drawn samples are reconciled.
Parameters
----------
distr
Distribution instances
Returns
-------
samples
Tensor with shape (num_samples, batch_size, seq_len, target_dim)
"""
samples = distr.sample_rep(
num_samples=self.num_samples_for_loss, dtype="float32"
)
# Determine which epoch we are currently in.
self.batch_no += 1
epoch_no = self.batch_no // self.num_batches_per_epoch + 1
epoch_frac = epoch_no / self.epochs
if (
self.coherent_train_samples
and epoch_frac > self.warmstart_epoch_frac
):
coherent_samples = reconcile_samples(
reconciliation_mat=self.M,
samples=samples,
seq_axis=self.seq_axis,
)
assert_shape(coherent_samples, samples.shape)
return coherent_samples
else:
return samples
def loss(self, F, target: Tensor, distr: Distribution) -> Tensor:
"""
Computes loss given the output of the network in the form of distribution.
The loss is given by:
`self.CRPS_weight` * `loss_CRPS` + `self.likelihood_weight` * `neg_likelihoods`,
where
* `loss_CRPS` is computed on the samples drawn from the predicted `distr` (optionally after reconciling them),
* `neg_likelihoods` are either computed directly using the predicted `distr` or from the estimated
distribution based on (coherent) samples, depending on the `sample_LH` flag.
Parameters
----------
F
target
Tensor with shape (batch_size, seq_len, target_dim)
distr
Distribution instances
Returns
-------
Loss
Tensor with shape (batch_size, seq_length, 1)
"""
# Sample from the predicted distribution if we are computing CRPS loss or likelihood using the distribution
# based on (coherent) samples.
# Samples shape: (num_samples, batch_size, seq_len, target_dim)
if self.sample_LH or (self.CRPS_weight > 0.0):
samples = self.get_samples_for_loss(distr=distr)
if self.sample_LH:
# Estimate the distribution based on (coherent) samples.
distr = LowrankMultivariateGaussian.fit(F, samples=samples, rank=0)
neg_likelihoods = -distr.log_prob(target).expand_dims(axis=-1)
loss_CRPS = F.zeros_like(neg_likelihoods)
if self.CRPS_weight > 0.0:
loss_CRPS = (
EmpiricalDistribution(samples=samples, event_dim=1)
.crps_univariate(x=target)
.expand_dims(axis=-1)
)
return (
self.CRPS_weight * loss_CRPS
+ self.likelihood_weight * neg_likelihoods
)
def post_process_samples(self, samples: Tensor) -> Tensor:
"""
Reconcile samples if `coherent_pred_samples` is True.
Parameters
----------
samples
Tensor of shape (num_parallel_samples*batch_size, 1, target_dim)
Returns
-------
Tensor of coherent samples.
"""
if not self.coherent_pred_samples:
return samples
else:
coherent_samples = reconcile_samples(
reconciliation_mat=self.M,
samples=samples,
seq_axis=self.seq_axis,
)
assert_shape(coherent_samples, samples.shape)
# assert that A*X_proj ~ 0
if self.assert_reconciliation:
assert (
reconciliation_error(self.A, samples=coherent_samples)
< self.reconciliation_tol
)
return coherent_samples
class DeepVARHierarchicalTrainingNetwork(
DeepVARHierarchicalNetwork, DeepVARTrainingNetwork
):
def __init__(
self,
num_samples_for_loss: int,
likelihood_weight: float,
CRPS_weight: float,
coherent_train_samples: bool,
warmstart_epoch_frac: float,
epochs: float,
num_batches_per_epoch: float,
sample_LH: bool,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.num_samples_for_loss = num_samples_for_loss
self.likelihood_weight = likelihood_weight
self.CRPS_weight = CRPS_weight
self.coherent_train_samples = coherent_train_samples
self.warmstart_epoch_frac = warmstart_epoch_frac
self.epochs = epochs
self.num_batches_per_epoch = num_batches_per_epoch
self.batch_no = 0
self.sample_LH = sample_LH
# Assert CRPS_weight, likelihood_weight, and coherent_train_samples have harmonious values
assert self.CRPS_weight >= 0.0, "CRPS weight must be non-negative"
assert (
self.likelihood_weight >= 0.0
), "Likelihood weight must be non-negative!"
assert (
self.likelihood_weight + self.CRPS_weight > 0.0
), "At least one of CRPS or likelihood weights must be non-zero"
if self.CRPS_weight == 0.0 and self.coherent_train_samples:
assert "No sampling being performed. coherent_train_samples flag is ignored"
if not self.sample_LH == 0.0 and self.coherent_train_samples:
assert "No sampling being performed. coherent_train_samples flag is ignored"
if self.likelihood_weight == 0.0 and self.sample_LH:
assert (
"likelihood_weight is 0 but sample likelihoods are still being calculated. "
"Set sample_LH=0 when likelihood_weight=0"
)
class DeepVARHierarchicalPredictionNetwork(
DeepVARHierarchicalNetwork, DeepVARPredictionNetwork
):
@validated()
def __init__(
self,
num_parallel_samples: int,
assert_reconciliation: bool,
coherent_pred_samples: bool,
reconciliation_tol: float,
**kwargs,
) -> None:
super().__init__(num_parallel_samples=num_parallel_samples, **kwargs)
self.coherent_pred_samples = coherent_pred_samples
self.assert_reconciliation = assert_reconciliation
self.reconciliation_tol = reconciliation_tol
| 5,452 |
1,514 | <gh_stars>1000+
#!/usr/bin/env python
"""
This is the command-line front-end in charge of processing arguments and call the framework
"""
import getopt
import os
import subprocess
import sys
from collections import defaultdict
def GetName():
return sys.argv[0]
def Usage(Message):
print("Usage:")
print(
GetName()
+ " EMAIL_TARGET=? EMAIL_FROM=? SMTP_LOGIN=? SMTP_PASS=? SMTP_HOST=? SMTP_PORT=? EMAIL_PRIORITY=? PDF_TEMPLATE=? MSF_LISTENER_PORT=? MSF_LISTENER_SETUP=? ATTACHMENT_NAME=? SET_EMAIL_TEMPLATE=? PHISHING_PAYLOAD=? PHISHING_SCRIPT_DIR=? TOOL_SET_DIR=?"
)
print("ERROR: " + Message)
sys.exit(-1)
def ShellExec(Command):
print("\nExecuting (Control+C to abort THIS COMMAND ONLY):\n" + Command)
Output = ""
try: # Stolen from: http://stackoverflow.com/questions/5833716/how-to-capture-output-of-a-shell-script-running-in-a-separate-process-in-a-wxpyt
proc = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1)
while True:
line = proc.stdout.readline()
if not line:
break
print(multi_replace(line, {"\n": "", "\r": ""})) # Show progress on the screen too!
Output += line # Save as much output as possible before a tool crashes! :)
except KeyboardInterrupt:
Output += self.Core.Error.user_abort("Command", Output) # Identify as Command Level abort
return Output
# Perform multiple replacements in one go using the replace dictionary in format: { 'search' : 'replace' }
def multi_replace(Text, ReplaceDict):
NewText = Text
for Search, Replace in ReplaceDict.items():
NewText = NewText.replace(Search, str(Replace))
return NewText
def GetParams(): # Basic validation and parameter retrieval:
MandatoryParams = [
"EMAIL_TARGET",
"EMAIL_FROM",
"SMTP_LOGIN",
"SMTP_PASS",
"SMTP_HOST",
"SMTP_PORT",
"EMAIL_PRIORITY",
"PDF_TEMPLATE",
"MSF_LISTENER_PORT",
"MSF_LISTENER_SETUP",
"ATTACHMENT_NAME",
"SET_EMAIL_TEMPLATE",
"PHISHING_PAYLOAD",
"PHISHING_SCRIPT_DIR",
"TOOL_SET_DIR",
]
ScriptName = GetName()
try:
Opts, Args = getopt.getopt(sys.argv[1:], "a:")
except getopt.GetoptError:
Usage("Invalid " + ScriptName + " option(s)")
Params = defaultdict(list)
for Arg in Args:
Chunks = Arg.split("=")
if len(Chunks) != 2:
Usage("'" + str(Arg) + "' is incorrect: The parameter format is ARGNAME=ARGVALUE")
ArgName = Chunks[0]
ArgValue = Arg.replace(ArgName + "=", "")
Params[ArgName] = ArgValue
for Mandatory in MandatoryParams:
if Mandatory not in Params:
Usage("Must include parameter: " + Mandatory)
SETScript = Params["PHISHING_SCRIPT_DIR"] + "/set_scripts/payload" + Params["PHISHING_PAYLOAD"] + ".set"
SETDebugAutomate = Params["PHISHING_SCRIPT_DIR"] + "/set_debug_automate.sh"
MandatoryPaths = [
Params["TOOL_SET_DIR"], Params["PDF_TEMPLATE"], Params["EMAIL_TARGET"], SETScript, SETDebugAutomate
]
for Path in MandatoryPaths:
if not os.path.exists(Path):
Usage("The path '" + str(Path) + "' must exist in your filesystem")
Params["SET_PARAMS_SCRIPT"] = SETScript
Params["SET_TMP_SCRIPT"] = "/tmp/set_tmp_script.set"
Params["SET_DEBUG_AUTOMATE"] = SETDebugAutomate
return Params
Params = GetParams() # Step 1 - Retrieve params and basic validation
with open(
Params["SET_TMP_SCRIPT"], "w"
) as file: # Step 2 - Create temporary script with hard-coded values from parameters:
file.write(multi_replace(open(Params["SET_PARAMS_SCRIPT"]).read(), Params))
ShellExec(
Params["SET_DEBUG_AUTOMATE"] + " " + Params["TOOL_SET_DIR"] + " " + Params["SET_TMP_SCRIPT"]
) # Step 3 - Run SET script
ShellExec("rm -f " + Params["SET_TMP_SCRIPT"]) # Step 4 - Remove temporary script with hard-coded values
| 1,702 |
1,338 | <gh_stars>1000+
// SMReplyTarget.h
#ifndef SM_REPLY_TARGET_H
#define SM_REPLY_TARGET_H
#include <Messenger.h>
class SMHandler;
class SMLooper;
class SMReplyTarget {
public:
SMReplyTarget(bool preferred = false);
virtual ~SMReplyTarget();
virtual BHandler *Handler();
virtual BMessenger Messenger();
virtual bool ReplySuccess();
private:
SMHandler *fHandler;
SMLooper *fLooper;
};
#endif // SM_REPLY_TARGET_H
| 162 |
10,002 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "pch.h"
#include "RadixType.h"
// export enum RadixType
| 49 |
521 | <reponame>Fimbure/icebox-1<gh_stars>100-1000
/* $Id: VBoxManageInfo.cpp $ */
/** @file
* VBoxManage - The 'showvminfo' command and helper routines.
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifndef VBOX_ONLY_DOCS
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#include <VBox/com/com.h>
#include <VBox/com/string.h>
#include <VBox/com/Guid.h>
#include <VBox/com/array.h>
#include <VBox/com/ErrorInfo.h>
#include <VBox/com/errorprint.h>
#include <VBox/com/VirtualBox.h>
#ifdef VBOX_WITH_PCI_PASSTHROUGH
#include <VBox/pci.h>
#endif
#include <VBox/log.h>
#include <VBox/version.h>
#include <iprt/stream.h>
#include <iprt/time.h>
#include <iprt/string.h>
#include <iprt/getopt.h>
#include <iprt/ctype.h>
#include "VBoxManage.h"
using namespace com;
// funcs
///////////////////////////////////////////////////////////////////////////////
HRESULT showSnapshots(ComPtr<ISnapshot> &rootSnapshot,
ComPtr<ISnapshot> ¤tSnapshot,
VMINFO_DETAILS details,
const Utf8Str &prefix /* = ""*/,
int level /*= 0*/)
{
/* start with the root */
Bstr name;
Bstr uuid;
Bstr description;
CHECK_ERROR2I_RET(rootSnapshot, COMGETTER(Name)(name.asOutParam()), hrcCheck);
CHECK_ERROR2I_RET(rootSnapshot, COMGETTER(Id)(uuid.asOutParam()), hrcCheck);
CHECK_ERROR2I_RET(rootSnapshot, COMGETTER(Description)(description.asOutParam()), hrcCheck);
bool fCurrent = (rootSnapshot == currentSnapshot);
if (details == VMINFO_MACHINEREADABLE)
{
/* print with hierarchical numbering */
RTPrintf("SnapshotName%s=\"%ls\"\n", prefix.c_str(), name.raw());
RTPrintf("SnapshotUUID%s=\"%s\"\n", prefix.c_str(), Utf8Str(uuid).c_str());
if (!description.isEmpty())
RTPrintf("SnapshotDescription%s=\"%ls\"\n", prefix.c_str(), description.raw());
if (fCurrent)
{
RTPrintf("CurrentSnapshotName=\"%ls\"\n", name.raw());
RTPrintf("CurrentSnapshotUUID=\"%s\"\n", Utf8Str(uuid).c_str());
RTPrintf("CurrentSnapshotNode=\"SnapshotName%s\"\n", prefix.c_str());
}
}
else
{
/* print with indentation */
RTPrintf(" %sName: %ls (UUID: %s)%s\n",
prefix.c_str(),
name.raw(),
Utf8Str(uuid).c_str(),
(fCurrent) ? " *" : "");
if (!description.isEmpty())
RTPrintf(" %sDescription:\n%ls\n", prefix.c_str(), description.raw());
}
/* get the children */
HRESULT hrc = S_OK;
SafeIfaceArray <ISnapshot> coll;
CHECK_ERROR2I_RET(rootSnapshot,COMGETTER(Children)(ComSafeArrayAsOutParam(coll)), hrcCheck);
if (!coll.isNull())
{
for (size_t index = 0; index < coll.size(); ++index)
{
ComPtr<ISnapshot> snapshot = coll[index];
if (snapshot)
{
Utf8Str newPrefix;
if (details == VMINFO_MACHINEREADABLE)
newPrefix = Utf8StrFmt("%s-%d", prefix.c_str(), index + 1);
else
{
newPrefix = Utf8StrFmt("%s ", prefix.c_str());
}
/* recursive call */
HRESULT hrc2 = showSnapshots(snapshot, currentSnapshot, details, newPrefix, level + 1);
if (FAILED(hrc2))
hrc = hrc2;
}
}
}
return hrc;
}
static void makeTimeStr(char *s, int cb, int64_t millies)
{
RTTIME t;
RTTIMESPEC ts;
RTTimeSpecSetMilli(&ts, millies);
RTTimeExplode(&t, &ts);
RTStrPrintf(s, cb, "%04d/%02d/%02d %02d:%02d:%02d UTC",
t.i32Year, t.u8Month, t.u8MonthDay,
t.u8Hour, t.u8Minute, t.u8Second);
}
const char *machineStateToName(MachineState_T machineState, bool fShort)
{
switch (machineState)
{
case MachineState_PoweredOff:
return fShort ? "poweroff" : "powered off";
case MachineState_Saved:
return "saved";
case MachineState_Teleported:
return "teleported";
case MachineState_Aborted:
return "aborted";
case MachineState_Running:
return "running";
case MachineState_Paused:
return "paused";
case MachineState_Stuck:
return fShort ? "gurumeditation" : "guru meditation";
case MachineState_Teleporting:
return "teleporting";
case MachineState_LiveSnapshotting:
return fShort ? "livesnapshotting" : "live snapshotting";
case MachineState_Starting:
return "starting";
case MachineState_Stopping:
return "stopping";
case MachineState_Saving:
return "saving";
case MachineState_Restoring:
return "restoring";
case MachineState_TeleportingPausedVM:
return fShort ? "teleportingpausedvm" : "teleporting paused vm";
case MachineState_TeleportingIn:
return fShort ? "teleportingin" : "teleporting (incoming)";
case MachineState_FaultTolerantSyncing:
return fShort ? "faulttolerantsyncing" : "fault tolerant syncing";
case MachineState_DeletingSnapshotOnline:
return fShort ? "deletingsnapshotlive" : "deleting snapshot live";
case MachineState_DeletingSnapshotPaused:
return fShort ? "deletingsnapshotlivepaused" : "deleting snapshot live paused";
case MachineState_OnlineSnapshotting:
return fShort ? "onlinesnapshotting" : "online snapshotting";
case MachineState_RestoringSnapshot:
return fShort ? "restoringsnapshot" : "restoring snapshot";
case MachineState_DeletingSnapshot:
return fShort ? "deletingsnapshot" : "deleting snapshot";
case MachineState_SettingUp:
return fShort ? "settingup" : "setting up";
case MachineState_Snapshotting:
return fShort ? "snapshotting" : "offline snapshotting";
default:
break;
}
return "unknown";
}
const char *facilityStateToName(AdditionsFacilityStatus_T faStatus, bool fShort)
{
switch (faStatus)
{
case AdditionsFacilityStatus_Inactive:
return fShort ? "inactive" : "not active";
case AdditionsFacilityStatus_Paused:
return "paused";
case AdditionsFacilityStatus_PreInit:
return fShort ? "preinit" : "pre-initializing";
case AdditionsFacilityStatus_Init:
return fShort ? "init" : "initializing";
case AdditionsFacilityStatus_Active:
return fShort ? "active" : "active/running";
case AdditionsFacilityStatus_Terminating:
return "terminating";
case AdditionsFacilityStatus_Terminated:
return "terminated";
case AdditionsFacilityStatus_Failed:
return "failed";
case AdditionsFacilityStatus_Unknown:
default:
break;
}
return "unknown";
}
/**
* This takes care of escaping double quotes and slashes that the string might
* contain.
*
* @param pszName The variable name.
* @param pbstrValue The value.
*/
static void outputMachineReadableString(const char *pszName, Bstr const *pbstrValue)
{
Assert(strpbrk(pszName, "\"\\") == NULL);
com::Utf8Str strValue(*pbstrValue);
if ( strValue.isEmpty()
|| ( !strValue.count('"')
&& !strValue.count('\\')))
RTPrintf("%s=\"%s\"\n", pszName, strValue.c_str());
else
{
/* The value needs escaping. */
RTPrintf("%s=\"", pszName);
const char *psz = strValue.c_str();
for (;;)
{
const char *pszNext = strpbrk(psz, "\"\\");
if (!pszNext)
{
RTPrintf("%s", psz);
break;
}
RTPrintf("%.*s\\%c", pszNext - psz, psz, *pszNext);
psz = pszNext + 1;
}
RTPrintf("\"\n");
}
}
/**
* Converts bandwidth group type to a string.
* @returns String representation.
* @param enmType Bandwidth control group type.
*/
inline const char * bwGroupTypeToString(BandwidthGroupType_T enmType)
{
switch (enmType)
{
case BandwidthGroupType_Null: return "Null";
case BandwidthGroupType_Disk: return "Disk";
case BandwidthGroupType_Network: return "Network";
}
return "unknown";
}
HRESULT showBandwidthGroups(ComPtr<IBandwidthControl> &bwCtrl,
VMINFO_DETAILS details)
{
int rc = S_OK;
SafeIfaceArray<IBandwidthGroup> bwGroups;
CHECK_ERROR_RET(bwCtrl, GetAllBandwidthGroups(ComSafeArrayAsOutParam(bwGroups)), rc);
if (bwGroups.size() && details != VMINFO_MACHINEREADABLE)
RTPrintf("\n\n");
for (size_t i = 0; i < bwGroups.size(); i++)
{
Bstr strName;
LONG64 cMaxBytesPerSec;
BandwidthGroupType_T enmType;
CHECK_ERROR_RET(bwGroups[i], COMGETTER(Name)(strName.asOutParam()), rc);
CHECK_ERROR_RET(bwGroups[i], COMGETTER(Type)(&enmType), rc);
CHECK_ERROR_RET(bwGroups[i], COMGETTER(MaxBytesPerSec)(&cMaxBytesPerSec), rc);
const char *pszType = bwGroupTypeToString(enmType);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("BandwidthGroup%zu=%ls,%s,%lld\n", i, strName.raw(), pszType, cMaxBytesPerSec);
else
{
const char *pszUnits = "";
LONG64 cBytes = cMaxBytesPerSec;
if (cBytes == 0)
{
RTPrintf("Name: '%ls', Type: %s, Limit: none (disabled)\n", strName.raw(), pszType);
continue;
}
else if (!(cBytes % _1G))
{
pszUnits = "G";
cBytes /= _1G;
}
else if (!(cBytes % _1M))
{
pszUnits = "M";
cBytes /= _1M;
}
else if (!(cBytes % _1K))
{
pszUnits = "K";
cBytes /= _1K;
}
const char *pszNetUnits = NULL;
if (enmType == BandwidthGroupType_Network)
{
/*
* We want to report network rate limit in bits/s, not bytes.
* Only if it cannot be express it in kilobits we will fall
* back to reporting it in bytes.
*/
LONG64 cBits = cMaxBytesPerSec;
if (!(cBits % 125))
{
cBits /= 125;
pszNetUnits = "k";
if (!(cBits % 1000000))
{
cBits /= 1000000;
pszNetUnits = "g";
}
else if (!(cBits % 1000))
{
cBits /= 1000;
pszNetUnits = "m";
}
RTPrintf("Name: '%ls', Type: %s, Limit: %lld %sbits/sec (%lld %sbytes/sec)\n", strName.raw(), pszType, cBits, pszNetUnits, cBytes, pszUnits);
}
}
if (!pszNetUnits)
RTPrintf("Name: '%ls', Type: %s, Limit: %lld %sbytes/sec\n", strName.raw(), pszType, cBytes, pszUnits);
}
}
if (details != VMINFO_MACHINEREADABLE)
RTPrintf(bwGroups.size() != 0 ? "\n" : "<none>\n\n");
return rc;
}
static const char *paravirtProviderToString(ParavirtProvider_T provider, VMINFO_DETAILS details)
{
switch (provider)
{
case ParavirtProvider_None:
if (details == VMINFO_MACHINEREADABLE)
return "none";
return "None";
case ParavirtProvider_Default:
if (details == VMINFO_MACHINEREADABLE)
return "default";
return "Default";
case ParavirtProvider_Legacy:
if (details == VMINFO_MACHINEREADABLE)
return "legacy";
return "Legacy";
case ParavirtProvider_Minimal:
if (details == VMINFO_MACHINEREADABLE)
return "minimal";
return "Minimal";
case ParavirtProvider_HyperV:
if (details == VMINFO_MACHINEREADABLE)
return "hyperv";
return "HyperV";
case ParavirtProvider_KVM:
if (details == VMINFO_MACHINEREADABLE)
return "kvm";
return "KVM";
default:
if (details == VMINFO_MACHINEREADABLE)
return "unknown";
return "Unknown";
}
}
/* Disable global optimizations for MSC 8.0/64 to make it compile in reasonable
time. MSC 7.1/32 doesn't have quite as much trouble with it, but still
sufficient to qualify for this hack as well since this code isn't performance
critical and probably won't gain much from the extra optimizing in real life. */
#if defined(_MSC_VER)
# pragma optimize("g", off)
# pragma warning(push)
# if _MSC_VER < RT_MSC_VER_VC120
# pragma warning(disable: 4748)
# endif
#endif
HRESULT showVMInfo(ComPtr<IVirtualBox> pVirtualBox,
ComPtr<IMachine> machine,
ComPtr<ISession> pSession,
VMINFO_DETAILS details /*= VMINFO_NONE*/)
{
HRESULT rc;
ComPtr<IConsole> pConsole;
if (pSession)
pSession->COMGETTER(Console)(pConsole.asOutParam());
#define SHOW_BOOLEAN_PROP(a_pObj, a_Prop, a_szMachine, a_szHuman) \
SHOW_BOOLEAN_PROP_EX(a_pObj, a_Prop, a_szMachine, a_szHuman, "on", "off")
#define SHOW_BOOLEAN_PROP_EX(a_pObj, a_Prop, a_szMachine, a_szHuman, a_szTrue, a_szFalse) \
do \
{ \
BOOL f; \
CHECK_ERROR2I_RET(a_pObj, COMGETTER(a_Prop)(&f), hrcCheck); \
if (details == VMINFO_MACHINEREADABLE) \
RTPrintf( a_szMachine "=\"%s\"\n", f ? "on" : "off"); \
else \
RTPrintf("%-16s %s\n", a_szHuman ":", f ? a_szTrue : a_szFalse); \
} while (0)
#define SHOW_BOOLEAN_METHOD(a_pObj, a_Invocation, a_szMachine, a_szHuman) \
do \
{ \
BOOL f; \
CHECK_ERROR2I_RET(a_pObj, a_Invocation, hrcCheck); \
if (details == VMINFO_MACHINEREADABLE) \
RTPrintf( a_szMachine "=\"%s\"\n", f ? "on" : "off"); \
else \
RTPrintf("%-16s %s\n", a_szHuman ":", f ? "on" : "off"); \
} while (0)
#define SHOW_STRING_PROP(a_pObj, a_Prop, a_szMachine, a_szHuman) \
do \
{ \
Bstr bstr; \
CHECK_ERROR2I_RET(a_pObj, COMGETTER(a_Prop)(bstr.asOutParam()), hrcCheck); \
if (details == VMINFO_MACHINEREADABLE) \
outputMachineReadableString(a_szMachine, &bstr); \
else \
RTPrintf("%-16s %ls\n", a_szHuman ":", bstr.raw()); \
} while (0)
/** @def SHOW_STRING_PROP_MAJ
* For not breaking the output in a dot release we don't show default values. */
#define SHOW_STRING_PROP_MAJ(a_pObj, a_Prop, a_szMachine, a_szHuman, a_szUnless, a_uMajorVer) \
do \
{ \
Bstr bstr; \
CHECK_ERROR2I_RET(a_pObj, COMGETTER(a_Prop)(bstr.asOutParam()), hrcCheck); \
if ((a_uMajorVer) <= VBOX_VERSION_MAJOR || !bstr.equals(a_szUnless)) \
{ \
if (details == VMINFO_MACHINEREADABLE)\
outputMachineReadableString(a_szMachine, &bstr); \
else \
RTPrintf("%-16s %ls\n", a_szHuman ":", bstr.raw()); \
} \
} while (0)
#define SHOW_STRINGARRAY_PROP(a_pObj, a_Prop, a_szMachine, a_szHuman) \
do \
{ \
SafeArray<BSTR> array; \
CHECK_ERROR2I_RET(a_pObj, COMGETTER(a_Prop)(ComSafeArrayAsOutParam(array)), hrcCheck); \
Utf8Str str; \
for (size_t i = 0; i < array.size(); i++) \
{ \
if (i != 0) \
str.append(","); \
str.append(Utf8Str(array[i]).c_str()); \
} \
Bstr bstr(str); \
if (details == VMINFO_MACHINEREADABLE) \
outputMachineReadableString(a_szMachine, &bstr); \
else \
RTPrintf("%-16s %ls\n", a_szHuman ":", bstr.raw()); \
} while (0)
#define SHOW_UUID_PROP(a_pObj, a_Prop, a_szMachine, a_szHuman) \
SHOW_STRING_PROP(a_pObj, a_Prop, a_szMachine, a_szHuman)
#define SHOW_ULONG_PROP(a_pObj, a_Prop, a_szMachine, a_szHuman, a_szUnit) \
do \
{ \
ULONG u32; \
CHECK_ERROR2I_RET(a_pObj, COMGETTER(a_Prop)(&u32), hrcCheck); \
if (details == VMINFO_MACHINEREADABLE) \
RTPrintf(a_szMachine "=%u\n", u32); \
else \
RTPrintf("%-16s %u" a_szUnit "\n", a_szHuman ":", u32); \
} while (0)
#define SHOW_LONG64_PROP(a_pObj, a_Prop, a_szMachine, a_szHuman, a_szUnit) \
do \
{ \
LONG64 i64; \
CHECK_ERROR2I_RET(a_pObj, COMGETTER(a_Prop)(&i64), hrcCheck); \
if (details == VMINFO_MACHINEREADABLE) \
RTPrintf(a_szMachine "=%lld\n", i64); \
else \
RTPrintf("%-16s %'lld" a_szUnit "\n", a_szHuman ":", i64); \
} while (0)
/*
* The rules for output in -argdump format:
* 1) the key part (the [0-9a-zA-Z_\-]+ string before the '=' delimiter)
* is all lowercase for "VBoxManage modifyvm" parameters. Any
* other values printed are in CamelCase.
* 2) strings (anything non-decimal) are printed surrounded by
* double quotes '"'. If the strings themselves contain double
* quotes, these characters are escaped by '\'. Any '\' character
* in the original string is also escaped by '\'.
* 3) numbers (containing just [0-9\-]) are written out unchanged.
*/
BOOL fAccessible;
CHECK_ERROR2I_RET(machine, COMGETTER(Accessible)(&fAccessible), hrcCheck);
if (!fAccessible)
{
Bstr uuid;
machine->COMGETTER(Id)(uuid.asOutParam());
if (details == VMINFO_COMPACT)
RTPrintf("\"<inaccessible>\" {%s}\n", Utf8Str(uuid).c_str());
else
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("name=\"<inaccessible>\"\n");
else
RTPrintf("Name: <inaccessible!>\n");
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("UUID=\"%s\"\n", Utf8Str(uuid).c_str());
else
RTPrintf("UUID: %s\n", Utf8Str(uuid).c_str());
if (details != VMINFO_MACHINEREADABLE)
{
Bstr settingsFilePath;
rc = machine->COMGETTER(SettingsFilePath)(settingsFilePath.asOutParam());
RTPrintf("Config file: %ls\n", settingsFilePath.raw());
ComPtr<IVirtualBoxErrorInfo> accessError;
rc = machine->COMGETTER(AccessError)(accessError.asOutParam());
RTPrintf("Access error details:\n");
ErrorInfo ei(accessError);
GluePrintErrorInfo(ei);
RTPrintf("\n");
}
}
return S_OK;
}
if (details == VMINFO_COMPACT)
{
Bstr machineName;
machine->COMGETTER(Name)(machineName.asOutParam());
Bstr uuid;
machine->COMGETTER(Id)(uuid.asOutParam());
RTPrintf("\"%ls\" {%s}\n", machineName.raw(), Utf8Str(uuid).c_str());
return S_OK;
}
SHOW_STRING_PROP( machine, Name, "name", "Name");
Bstr osTypeId;
CHECK_ERROR2I_RET(machine, COMGETTER(OSTypeId)(osTypeId.asOutParam()), hrcCheck);
ComPtr<IGuestOSType> osType;
CHECK_ERROR2I_RET(pVirtualBox, GetGuestOSType(osTypeId.raw(), osType.asOutParam()), hrcCheck);
SHOW_STRINGARRAY_PROP( machine, Groups, "groups", "Groups");
SHOW_STRING_PROP( osType, Description, "ostype", "Guest OS");
SHOW_UUID_PROP( machine, Id, "UUID", "UUID");
SHOW_STRING_PROP( machine, SettingsFilePath, "CfgFile", "Config file");
SHOW_STRING_PROP( machine, SnapshotFolder, "SnapFldr", "Snapshot folder");
SHOW_STRING_PROP( machine, LogFolder, "LogFldr", "Log folder");
SHOW_UUID_PROP( machine, HardwareUUID, "hardwareuuid", "Hardware UUID");
SHOW_ULONG_PROP( machine, MemorySize, "memory", "Memory size", "MB");
SHOW_BOOLEAN_PROP( machine, PageFusionEnabled, "pagefusion", "Page Fusion");
SHOW_ULONG_PROP( machine, VRAMSize, "vram", "VRAM size", "MB");
SHOW_ULONG_PROP( machine, CPUExecutionCap, "cpuexecutioncap", "CPU exec cap", "%%");
SHOW_BOOLEAN_PROP( machine, HPETEnabled, "hpet", "HPET");
SHOW_STRING_PROP_MAJ( machine, CPUProfile, "cpu-profile", "CPUProfile", "host", 6);
ChipsetType_T chipsetType;
CHECK_ERROR2I_RET(machine, COMGETTER(ChipsetType)(&chipsetType), hrcCheck);
const char *pszChipsetType;
switch (chipsetType)
{
case ChipsetType_Null: pszChipsetType = "invalid"; break;
case ChipsetType_PIIX3: pszChipsetType = "piix3"; break;
case ChipsetType_ICH9: pszChipsetType = "ich9"; break;
default: AssertFailed(); pszChipsetType = "unknown"; break;
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("chipset=\"%s\"\n", pszChipsetType);
else
RTPrintf("Chipset: %s\n", pszChipsetType);
FirmwareType_T firmwareType;
CHECK_ERROR2I_RET(machine, COMGETTER(FirmwareType)(&firmwareType), hrcCheck);
const char *pszFirmwareType;
switch (firmwareType)
{
case FirmwareType_BIOS: pszFirmwareType = "BIOS"; break;
case FirmwareType_EFI: pszFirmwareType = "EFI"; break;
case FirmwareType_EFI32: pszFirmwareType = "EFI32"; break;
case FirmwareType_EFI64: pszFirmwareType = "EFI64"; break;
case FirmwareType_EFIDUAL: pszFirmwareType = "EFIDUAL"; break;
default: AssertFailed(); pszFirmwareType = "unknown"; break;
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("firmware=\"%s\"\n", pszFirmwareType);
else
RTPrintf("Firmware: %s\n", pszFirmwareType);
SHOW_ULONG_PROP( machine, CPUCount, "cpus", "Number of CPUs", "");
SHOW_BOOLEAN_METHOD( machine, GetCPUProperty(CPUPropertyType_PAE, &f), "pae", "PAE");
SHOW_BOOLEAN_METHOD( machine, GetCPUProperty(CPUPropertyType_LongMode, &f), "longmode", "Long Mode");
SHOW_BOOLEAN_METHOD( machine, GetCPUProperty(CPUPropertyType_TripleFaultReset, &f), "triplefaultreset", "Triple Fault Reset");
SHOW_BOOLEAN_METHOD( machine, GetCPUProperty(CPUPropertyType_APIC, &f), "apic", "APIC");
SHOW_BOOLEAN_METHOD( machine, GetCPUProperty(CPUPropertyType_X2APIC, &f), "x2apic", "X2APIC");
SHOW_ULONG_PROP( machine, CPUIDPortabilityLevel, "cpuid-portability-level", "CPUID Portability Level", "");
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("CPUID overrides: ");
ULONG uOrdinal = 0;
for (uOrdinal = 0; uOrdinal < _4K; uOrdinal++)
{
ULONG uLeaf, uSubLeaf, uEAX, uEBX, uECX, uEDX;
rc = machine->GetCPUIDLeafByOrdinal(uOrdinal, &uLeaf, &uSubLeaf, &uEAX, &uEBX, &uECX, &uEDX);
if (SUCCEEDED(rc))
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("cpuid=%08x,%08x,%08x,%08x,%08x,%08x", uLeaf, uSubLeaf, uEAX, uEBX, uECX, uEDX);
else
{
if (!uOrdinal)
RTPrintf("Leaf no. EAX EBX ECX EDX\n");
RTPrintf(" %08x/%03x %08x %08x %08x %08x\n", uLeaf, uSubLeaf, uEAX, uEBX, uECX, uEDX);
}
}
else
{
if (rc != E_INVALIDARG)
com::GlueHandleComError(machine, "GetCPUIDLeaf", rc, __FILE__, __LINE__);
break;
}
}
if (!uOrdinal && details != VMINFO_MACHINEREADABLE)
RTPrintf("None\n");
ComPtr<IBIOSSettings> biosSettings;
CHECK_ERROR2I_RET(machine, COMGETTER(BIOSSettings)(biosSettings.asOutParam()), hrcCheck);
BIOSBootMenuMode_T bootMenuMode;
CHECK_ERROR2I_RET(biosSettings, COMGETTER(BootMenuMode)(&bootMenuMode), hrcCheck);
const char *pszBootMenu;
switch (bootMenuMode)
{
case BIOSBootMenuMode_Disabled:
pszBootMenu = "disabled";
break;
case BIOSBootMenuMode_MenuOnly:
if (details == VMINFO_MACHINEREADABLE)
pszBootMenu = "menuonly";
else
pszBootMenu = "menu only";
break;
default:
if (details == VMINFO_MACHINEREADABLE)
pszBootMenu = "messageandmenu";
else
pszBootMenu = "message and menu";
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("bootmenu=\"%s\"\n", pszBootMenu);
else
RTPrintf("Boot menu mode: %s\n", pszBootMenu);
ComPtr<ISystemProperties> systemProperties;
CHECK_ERROR2I_RET(pVirtualBox, COMGETTER(SystemProperties)(systemProperties.asOutParam()), hrcCheck);
ULONG maxBootPosition = 0;
CHECK_ERROR2I_RET(systemProperties, COMGETTER(MaxBootPosition)(&maxBootPosition), hrcCheck);
for (ULONG i = 1; i <= maxBootPosition; i++)
{
DeviceType_T bootOrder;
CHECK_ERROR2I_RET(machine, GetBootOrder(i, &bootOrder), hrcCheck);
if (bootOrder == DeviceType_Floppy)
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("boot%d=\"floppy\"\n", i);
else
RTPrintf("Boot Device (%d): Floppy\n", i);
}
else if (bootOrder == DeviceType_DVD)
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("boot%d=\"dvd\"\n", i);
else
RTPrintf("Boot Device (%d): DVD\n", i);
}
else if (bootOrder == DeviceType_HardDisk)
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("boot%d=\"disk\"\n", i);
else
RTPrintf("Boot Device (%d): HardDisk\n", i);
}
else if (bootOrder == DeviceType_Network)
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("boot%d=\"net\"\n", i);
else
RTPrintf("Boot Device (%d): Network\n", i);
}
else if (bootOrder == DeviceType_USB)
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("boot%d=\"usb\"\n", i);
else
RTPrintf("Boot Device (%d): USB\n", i);
}
else if (bootOrder == DeviceType_SharedFolder)
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("boot%d=\"sharedfolder\"\n", i);
else
RTPrintf("Boot Device (%d): Shared Folder\n", i);
}
else
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("boot%d=\"none\"\n", i);
else
RTPrintf("Boot Device (%d): Not Assigned\n", i);
}
}
SHOW_BOOLEAN_PROP(biosSettings, ACPIEnabled, "acpi", "ACPI");
SHOW_BOOLEAN_PROP(biosSettings, IOAPICEnabled, "ioapic", "IOAPIC");
APICMode_T apicMode;
CHECK_ERROR2I_RET(biosSettings, COMGETTER(APICMode)(&apicMode), hrcCheck);
const char *pszAPIC;
switch (apicMode)
{
case APICMode_Disabled:
pszAPIC = "disabled";
break;
case APICMode_APIC:
default:
if (details == VMINFO_MACHINEREADABLE)
pszAPIC = "apic";
else
pszAPIC = "APIC";
break;
case APICMode_X2APIC:
if (details == VMINFO_MACHINEREADABLE)
pszAPIC = "x2apic";
else
pszAPIC = "x2APIC";
break;
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("biosapic=\"%s\"\n", pszAPIC);
else
RTPrintf("BIOS APIC mode: %s\n", pszAPIC);
SHOW_LONG64_PROP(biosSettings, TimeOffset, "biossystemtimeoffset", "Time offset", "ms");
SHOW_BOOLEAN_PROP_EX(machine, RTCUseUTC, "rtcuseutc", "RTC", "UTC", "local time");
SHOW_BOOLEAN_METHOD(machine, GetHWVirtExProperty(HWVirtExPropertyType_Enabled, &f), "hwvirtex", "Hardw. virt.ext");
SHOW_BOOLEAN_METHOD(machine, GetHWVirtExProperty(HWVirtExPropertyType_NestedPaging, &f),"nestedpaging", "Nested Paging");
SHOW_BOOLEAN_METHOD(machine, GetHWVirtExProperty(HWVirtExPropertyType_LargePages, &f), "largepages", "Large Pages");
SHOW_BOOLEAN_METHOD(machine, GetHWVirtExProperty(HWVirtExPropertyType_VPID, &f), "vtxvpid", "VT-x VPID");
SHOW_BOOLEAN_METHOD(machine, GetHWVirtExProperty(HWVirtExPropertyType_UnrestrictedExecution, &f), "vtxux", "VT-x unr. exec.");
ParavirtProvider_T paravirtProvider;
CHECK_ERROR2I_RET(machine, COMGETTER(ParavirtProvider)(¶virtProvider), hrcCheck);
const char *pszParavirtProvider = paravirtProviderToString(paravirtProvider, details);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("paravirtprovider=\"%s\"\n", pszParavirtProvider);
else
RTPrintf("Paravirt. Provider: %s\n", pszParavirtProvider);
ParavirtProvider_T effParavirtProvider;
CHECK_ERROR2I_RET(machine, GetEffectiveParavirtProvider(&effParavirtProvider), hrcCheck);
const char *pszEffParavirtProvider = paravirtProviderToString(effParavirtProvider, details);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("effparavirtprovider=\"%s\"\n", pszEffParavirtProvider);
else
RTPrintf("Effective Paravirt. Provider: %s\n", pszEffParavirtProvider);
Bstr paravirtDebug;
CHECK_ERROR2I_RET(machine, COMGETTER(ParavirtDebug)(paravirtDebug.asOutParam()), hrcCheck);
if (paravirtDebug.isNotEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("paravirtdebug=\"%ls\"\n", paravirtDebug.raw());
else
RTPrintf("Paravirt. Debug: %ls\n", paravirtDebug.raw());
}
MachineState_T machineState;
CHECK_ERROR2I_RET(machine, COMGETTER(State)(&machineState), hrcCheck);
const char *pszState = machineStateToName(machineState, details == VMINFO_MACHINEREADABLE /*=fShort*/);
LONG64 stateSince;
machine->COMGETTER(LastStateChange)(&stateSince);
RTTIMESPEC timeSpec;
RTTimeSpecSetMilli(&timeSpec, stateSince);
char pszTime[30] = {0};
RTTimeSpecToString(&timeSpec, pszTime, sizeof(pszTime));
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("VMState=\"%s\"\n", pszState);
RTPrintf("VMStateChangeTime=\"%s\"\n", pszTime);
Bstr stateFile;
machine->COMGETTER(StateFilePath)(stateFile.asOutParam());
if (!stateFile.isEmpty())
RTPrintf("VMStateFile=\"%ls\"\n", stateFile.raw());
}
else
RTPrintf("State: %s (since %s)\n", pszState, pszTime);
GraphicsControllerType_T enmGraphics;
rc = machine->COMGETTER(GraphicsControllerType)(&enmGraphics);
if (SUCCEEDED(rc))
{
const char *pszCtrl = "Unknown";
switch (enmGraphics)
{
case GraphicsControllerType_Null:
if (details == VMINFO_MACHINEREADABLE)
pszCtrl = "null";
else
pszCtrl = "Null";
break;
case GraphicsControllerType_VBoxVGA:
if (details == VMINFO_MACHINEREADABLE)
pszCtrl = "vboxvga";
else
pszCtrl = "VBoxVGA";
break;
case GraphicsControllerType_VMSVGA:
if (details == VMINFO_MACHINEREADABLE)
pszCtrl = "vmsvga";
else
pszCtrl = "VMSVGA";
break;
default:
if (details == VMINFO_MACHINEREADABLE)
pszCtrl = "unknown";
break;
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("graphicscontroller=\"%s\"\n", pszCtrl);
else
RTPrintf("%-28s %s\n", "Graphics Controller:", pszCtrl);
}
SHOW_ULONG_PROP( machine, MonitorCount, "monitorcount", "Monitor count", "");
SHOW_BOOLEAN_PROP( machine, Accelerate3DEnabled, "accelerate3d", "3D Acceleration");
#ifdef VBOX_WITH_VIDEOHWACCEL
SHOW_BOOLEAN_PROP( machine, Accelerate2DVideoEnabled, "accelerate2dvideo", "2D Video Acceleration");
#endif
SHOW_BOOLEAN_PROP( machine, TeleporterEnabled, "teleporterenabled", "Teleporter Enabled");
SHOW_ULONG_PROP( machine, TeleporterPort, "teleporterport", "Teleporter Port", "");
SHOW_STRING_PROP( machine, TeleporterAddress, "teleporteraddress", "Teleporter Address");
SHOW_STRING_PROP( machine, TeleporterPassword, "teleporterpassword", "Teleporter Password");
SHOW_BOOLEAN_PROP( machine, TracingEnabled, "tracing-enabled", "Tracing Enabled");
SHOW_BOOLEAN_PROP( machine, AllowTracingToAccessVM, "tracing-allow-vm-access", "Allow Tracing to Access VM");
SHOW_STRING_PROP( machine, TracingConfig, "tracing-config", "Tracing Configuration");
SHOW_BOOLEAN_PROP( machine, AutostartEnabled, "autostart-enabled", "Autostart Enabled");
SHOW_ULONG_PROP( machine, AutostartDelay, "autostart-delay", "Autostart Delay", "");
SHOW_STRING_PROP( machine, DefaultFrontend, "defaultfrontend", "Default Frontend");
/** @todo Convert the remainder of the function to SHOW_XXX macros and add error
* checking where missing. */
/*
* Storage Controllers and their attached Mediums.
*/
com::SafeIfaceArray<IStorageController> storageCtls;
CHECK_ERROR(machine, COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(storageCtls)));
for (size_t i = 0; i < storageCtls.size(); ++ i)
{
ComPtr<IStorageController> storageCtl = storageCtls[i];
StorageControllerType_T enmCtlType = StorageControllerType_Null;
const char *pszCtl = NULL;
ULONG ulValue = 0;
BOOL fBootable = FALSE;
Bstr storageCtlName;
storageCtl->COMGETTER(Name)(storageCtlName.asOutParam());
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("storagecontrollername%u=\"%ls\"\n", i, storageCtlName.raw());
else
RTPrintf("Storage Controller Name (%u): %ls\n", i, storageCtlName.raw());
storageCtl->COMGETTER(ControllerType)(&enmCtlType);
switch (enmCtlType)
{
case StorageControllerType_LsiLogic:
pszCtl = "LsiLogic";
break;
case StorageControllerType_LsiLogicSas:
pszCtl = "LsiLogicSas";
break;
case StorageControllerType_BusLogic:
pszCtl = "BusLogic";
break;
case StorageControllerType_IntelAhci:
pszCtl = "IntelAhci";
break;
case StorageControllerType_PIIX3:
pszCtl = "PIIX3";
break;
case StorageControllerType_PIIX4:
pszCtl = "PIIX4";
break;
case StorageControllerType_ICH6:
pszCtl = "ICH6";
break;
case StorageControllerType_I82078:
pszCtl = "I82078";
break;
case StorageControllerType_USB:
pszCtl = "USB";
break;
default:
pszCtl = "unknown";
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("storagecontrollertype%u=\"%s\"\n", i, pszCtl);
else
RTPrintf("Storage Controller Type (%u): %s\n", i, pszCtl);
storageCtl->COMGETTER(Instance)(&ulValue);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("storagecontrollerinstance%u=\"%lu\"\n", i, ulValue);
else
RTPrintf("Storage Controller Instance Number (%u): %lu\n", i, ulValue);
storageCtl->COMGETTER(MaxPortCount)(&ulValue);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("storagecontrollermaxportcount%u=\"%lu\"\n", i, ulValue);
else
RTPrintf("Storage Controller Max Port Count (%u): %lu\n", i, ulValue);
storageCtl->COMGETTER(PortCount)(&ulValue);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("storagecontrollerportcount%u=\"%lu\"\n", i, ulValue);
else
RTPrintf("Storage Controller Port Count (%u): %lu\n", i, ulValue);
storageCtl->COMGETTER(Bootable)(&fBootable);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("storagecontrollerbootable%u=\"%s\"\n", i, fBootable ? "on" : "off");
else
RTPrintf("Storage Controller Bootable (%u): %s\n", i, fBootable ? "on" : "off");
}
for (size_t j = 0; j < storageCtls.size(); ++ j)
{
ComPtr<IStorageController> storageCtl = storageCtls[j];
ComPtr<IMedium> medium;
Bstr storageCtlName;
Bstr filePath;
ULONG cDevices;
ULONG cPorts;
storageCtl->COMGETTER(Name)(storageCtlName.asOutParam());
storageCtl->COMGETTER(MaxDevicesPerPortCount)(&cDevices);
storageCtl->COMGETTER(PortCount)(&cPorts);
for (ULONG i = 0; i < cPorts; ++ i)
{
for (ULONG k = 0; k < cDevices; ++ k)
{
ComPtr<IMediumAttachment> mediumAttach;
machine->GetMediumAttachment(storageCtlName.raw(),
i, k,
mediumAttach.asOutParam());
BOOL fIsEjected = FALSE;
BOOL fTempEject = FALSE;
DeviceType_T devType = DeviceType_Null;
if (mediumAttach)
{
mediumAttach->COMGETTER(TemporaryEject)(&fTempEject);
mediumAttach->COMGETTER(IsEjected)(&fIsEjected);
mediumAttach->COMGETTER(Type)(&devType);
}
rc = machine->GetMedium(storageCtlName.raw(), i, k,
medium.asOutParam());
if (SUCCEEDED(rc) && medium)
{
BOOL fPassthrough = FALSE;
if (mediumAttach)
mediumAttach->COMGETTER(Passthrough)(&fPassthrough);
medium->COMGETTER(Location)(filePath.asOutParam());
Bstr uuid;
medium->COMGETTER(Id)(uuid.asOutParam());
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("\"%ls-%d-%d\"=\"%ls\"\n", storageCtlName.raw(),
i, k, filePath.raw());
RTPrintf("\"%ls-ImageUUID-%d-%d\"=\"%s\"\n",
storageCtlName.raw(), i, k, Utf8Str(uuid).c_str());
if (fPassthrough)
RTPrintf("\"%ls-dvdpassthrough\"=\"%s\"\n", storageCtlName.raw(),
fPassthrough ? "on" : "off");
if (devType == DeviceType_DVD)
{
RTPrintf("\"%ls-tempeject\"=\"%s\"\n", storageCtlName.raw(),
fTempEject ? "on" : "off");
RTPrintf("\"%ls-IsEjected\"=\"%s\"\n", storageCtlName.raw(),
fIsEjected ? "on" : "off");
}
}
else
{
RTPrintf("%ls (%d, %d): %ls (UUID: %s)",
storageCtlName.raw(), i, k, filePath.raw(),
Utf8Str(uuid).c_str());
if (fPassthrough)
RTPrintf(" (passthrough enabled)");
if (fTempEject)
RTPrintf(" (temp eject)");
if (fIsEjected)
RTPrintf(" (ejected)");
RTPrintf("\n");
}
}
else if (SUCCEEDED(rc))
{
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("\"%ls-%d-%d\"=\"emptydrive\"\n", storageCtlName.raw(), i, k);
if (devType == DeviceType_DVD)
RTPrintf("\"%ls-IsEjected\"=\"%s\"\n", storageCtlName.raw(),
fIsEjected ? "on" : "off");
}
else
{
RTPrintf("%ls (%d, %d): Empty", storageCtlName.raw(), i, k);
if (fTempEject)
RTPrintf(" (temp eject)");
if (fIsEjected)
RTPrintf(" (ejected)");
RTPrintf("\n");
}
}
else
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("\"%ls-%d-%d\"=\"none\"\n", storageCtlName.raw(), i, k);
}
}
}
}
/* get the maximum amount of NICS */
ULONG maxNICs = getMaxNics(pVirtualBox, machine);
for (ULONG currentNIC = 0; currentNIC < maxNICs; currentNIC++)
{
ComPtr<INetworkAdapter> nic;
rc = machine->GetNetworkAdapter(currentNIC, nic.asOutParam());
if (SUCCEEDED(rc) && nic)
{
BOOL fEnabled;
nic->COMGETTER(Enabled)(&fEnabled);
if (!fEnabled)
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("nic%d=\"none\"\n", currentNIC + 1);
else
RTPrintf("NIC %d: disabled\n", currentNIC + 1);
}
else
{
Bstr strMACAddress;
nic->COMGETTER(MACAddress)(strMACAddress.asOutParam());
Utf8Str strAttachment;
Utf8Str strNatSettings = "";
Utf8Str strNatForwardings = "";
NetworkAttachmentType_T attachment;
nic->COMGETTER(AttachmentType)(&attachment);
switch (attachment)
{
case NetworkAttachmentType_Null:
if (details == VMINFO_MACHINEREADABLE)
strAttachment = "null";
else
strAttachment = "none";
break;
case NetworkAttachmentType_NAT:
{
Bstr strNetwork;
ComPtr<INATEngine> engine;
nic->COMGETTER(NATEngine)(engine.asOutParam());
engine->COMGETTER(Network)(strNetwork.asOutParam());
com::SafeArray<BSTR> forwardings;
engine->COMGETTER(Redirects)(ComSafeArrayAsOutParam(forwardings));
strNatForwardings = "";
for (size_t i = 0; i < forwardings.size(); ++i)
{
bool fSkip = false;
BSTR r = forwardings[i];
Utf8Str utf = Utf8Str(r);
Utf8Str strName;
Utf8Str strProto;
Utf8Str strHostPort;
Utf8Str strHostIP;
Utf8Str strGuestPort;
Utf8Str strGuestIP;
size_t pos, ppos;
pos = ppos = 0;
#define ITERATE_TO_NEXT_TERM(res, str, pos, ppos) \
do { \
pos = str.find(",", ppos); \
if (pos == Utf8Str::npos) \
{ \
Log(( #res " extracting from %s is failed\n", str.c_str())); \
fSkip = true; \
} \
res = str.substr(ppos, pos - ppos); \
Log2((#res " %s pos:%d, ppos:%d\n", res.c_str(), pos, ppos)); \
ppos = pos + 1; \
} while (0)
ITERATE_TO_NEXT_TERM(strName, utf, pos, ppos);
if (fSkip) continue;
ITERATE_TO_NEXT_TERM(strProto, utf, pos, ppos);
if (fSkip) continue;
ITERATE_TO_NEXT_TERM(strHostIP, utf, pos, ppos);
if (fSkip) continue;
ITERATE_TO_NEXT_TERM(strHostPort, utf, pos, ppos);
if (fSkip) continue;
ITERATE_TO_NEXT_TERM(strGuestIP, utf, pos, ppos);
if (fSkip) continue;
strGuestPort = utf.substr(ppos, utf.length() - ppos);
#undef ITERATE_TO_NEXT_TERM
switch (strProto.toUInt32())
{
case NATProtocol_TCP:
strProto = "tcp";
break;
case NATProtocol_UDP:
strProto = "udp";
break;
default:
strProto = "unk";
break;
}
if (details == VMINFO_MACHINEREADABLE)
{
strNatForwardings = Utf8StrFmt("%sForwarding(%d)=\"%s,%s,%s,%s,%s,%s\"\n",
strNatForwardings.c_str(), i, strName.c_str(), strProto.c_str(),
strHostIP.c_str(), strHostPort.c_str(),
strGuestIP.c_str(), strGuestPort.c_str());
}
else
{
strNatForwardings = Utf8StrFmt("%sNIC %d Rule(%d): name = %s, protocol = %s,"
" host ip = %s, host port = %s, guest ip = %s, guest port = %s\n",
strNatForwardings.c_str(), currentNIC + 1, i, strName.c_str(), strProto.c_str(),
strHostIP.c_str(), strHostPort.c_str(),
strGuestIP.c_str(), strGuestPort.c_str());
}
}
ULONG mtu = 0;
ULONG sockSnd = 0;
ULONG sockRcv = 0;
ULONG tcpSnd = 0;
ULONG tcpRcv = 0;
engine->GetNetworkSettings(&mtu, &sockSnd, &sockRcv, &tcpSnd, &tcpRcv);
/** @todo r=klaus dnsproxy etc needs to be dumped, too */
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("natnet%d=\"%ls\"\n", currentNIC + 1, strNetwork.length() ? strNetwork.raw(): Bstr("nat").raw());
strAttachment = "nat";
strNatSettings = Utf8StrFmt("mtu=\"%d\"\nsockSnd=\"%d\"\nsockRcv=\"%d\"\ntcpWndSnd=\"%d\"\ntcpWndRcv=\"%d\"\n",
mtu, sockSnd ? sockSnd : 64, sockRcv ? sockRcv : 64, tcpSnd ? tcpSnd : 64, tcpRcv ? tcpRcv : 64);
}
else
{
strAttachment = "NAT";
strNatSettings = Utf8StrFmt("NIC %d Settings: MTU: %d, Socket (send: %d, receive: %d), TCP Window (send:%d, receive: %d)\n",
currentNIC + 1, mtu, sockSnd ? sockSnd : 64, sockRcv ? sockRcv : 64, tcpSnd ? tcpSnd : 64, tcpRcv ? tcpRcv : 64);
}
break;
}
case NetworkAttachmentType_Bridged:
{
Bstr strBridgeAdp;
nic->COMGETTER(BridgedInterface)(strBridgeAdp.asOutParam());
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("bridgeadapter%d=\"%ls\"\n", currentNIC + 1, strBridgeAdp.raw());
strAttachment = "bridged";
}
else
strAttachment = Utf8StrFmt("Bridged Interface '%ls'", strBridgeAdp.raw());
break;
}
case NetworkAttachmentType_Internal:
{
Bstr strNetwork;
nic->COMGETTER(InternalNetwork)(strNetwork.asOutParam());
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("intnet%d=\"%ls\"\n", currentNIC + 1, strNetwork.raw());
strAttachment = "intnet";
}
else
strAttachment = Utf8StrFmt("Internal Network '%s'", Utf8Str(strNetwork).c_str());
break;
}
case NetworkAttachmentType_HostOnly:
{
Bstr strHostonlyAdp;
nic->COMGETTER(HostOnlyInterface)(strHostonlyAdp.asOutParam());
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("hostonlyadapter%d=\"%ls\"\n", currentNIC + 1, strHostonlyAdp.raw());
strAttachment = "hostonly";
}
else
strAttachment = Utf8StrFmt("Host-only Interface '%ls'", strHostonlyAdp.raw());
break;
}
case NetworkAttachmentType_Generic:
{
Bstr strGenericDriver;
nic->COMGETTER(GenericDriver)(strGenericDriver.asOutParam());
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("generic%d=\"%ls\"\n", currentNIC + 1, strGenericDriver.raw());
strAttachment = "Generic";
}
else
{
strAttachment = Utf8StrFmt("Generic '%ls'", strGenericDriver.raw());
// show the generic properties
com::SafeArray<BSTR> aProperties;
com::SafeArray<BSTR> aValues;
rc = nic->GetProperties(NULL,
ComSafeArrayAsOutParam(aProperties),
ComSafeArrayAsOutParam(aValues));
if (SUCCEEDED(rc))
{
strAttachment += " { ";
for (unsigned i = 0; i < aProperties.size(); ++i)
strAttachment += Utf8StrFmt(!i ? "%ls='%ls'" : ", %ls='%ls'",
aProperties[i], aValues[i]);
strAttachment += " }";
}
}
break;
}
case NetworkAttachmentType_NATNetwork:
{
Bstr strNetwork;
nic->COMGETTER(NATNetwork)(strNetwork.asOutParam());
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("nat-network%d=\"%ls\"\n", currentNIC + 1, strNetwork.raw());
strAttachment = "natnetwork";
}
else
strAttachment = Utf8StrFmt("NAT Network '%s'", Utf8Str(strNetwork).c_str());
break;
}
default:
strAttachment = "unknown";
break;
}
/* cable connected */
BOOL fConnected;
nic->COMGETTER(CableConnected)(&fConnected);
/* promisc policy */
NetworkAdapterPromiscModePolicy_T enmPromiscModePolicy;
CHECK_ERROR2I_RET(nic, COMGETTER(PromiscModePolicy)(&enmPromiscModePolicy), hrcCheck);
const char *pszPromiscuousGuestPolicy;
switch (enmPromiscModePolicy)
{
case NetworkAdapterPromiscModePolicy_Deny: pszPromiscuousGuestPolicy = "deny"; break;
case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPromiscuousGuestPolicy = "allow-vms"; break;
case NetworkAdapterPromiscModePolicy_AllowAll: pszPromiscuousGuestPolicy = "allow-all"; break;
default: AssertFailedReturn(E_INVALIDARG);
}
/* trace stuff */
BOOL fTraceEnabled;
nic->COMGETTER(TraceEnabled)(&fTraceEnabled);
Bstr traceFile;
nic->COMGETTER(TraceFile)(traceFile.asOutParam());
/* NIC type */
NetworkAdapterType_T NICType;
nic->COMGETTER(AdapterType)(&NICType);
const char *pszNICType;
switch (NICType)
{
case NetworkAdapterType_Am79C970A: pszNICType = "Am79C970A"; break;
case NetworkAdapterType_Am79C973: pszNICType = "Am79C973"; break;
#ifdef VBOX_WITH_E1000
case NetworkAdapterType_I82540EM: pszNICType = "82540EM"; break;
case NetworkAdapterType_I82543GC: pszNICType = "82543GC"; break;
case NetworkAdapterType_I82545EM: pszNICType = "82545EM"; break;
#endif
#ifdef VBOX_WITH_VIRTIO
case NetworkAdapterType_Virtio: pszNICType = "virtio"; break;
#endif
default: AssertFailed(); pszNICType = "unknown"; break;
}
/* reported line speed */
ULONG ulLineSpeed;
nic->COMGETTER(LineSpeed)(&ulLineSpeed);
/* boot priority of the adapter */
ULONG ulBootPriority;
nic->COMGETTER(BootPriority)(&ulBootPriority);
/* bandwidth group */
ComObjPtr<IBandwidthGroup> pBwGroup;
Bstr strBwGroup;
nic->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam());
if (!pBwGroup.isNull())
pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam());
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("macaddress%d=\"%ls\"\n", currentNIC + 1, strMACAddress.raw());
RTPrintf("cableconnected%d=\"%s\"\n", currentNIC + 1, fConnected ? "on" : "off");
RTPrintf("nic%d=\"%s\"\n", currentNIC + 1, strAttachment.c_str());
RTPrintf("nictype%d=\"%s\"\n", currentNIC + 1, pszNICType);
RTPrintf("nicspeed%d=\"%d\"\n", currentNIC + 1, ulLineSpeed);
}
else
RTPrintf("NIC %u: MAC: %ls, Attachment: %s, Cable connected: %s, Trace: %s (file: %ls), Type: %s, Reported speed: %d Mbps, Boot priority: %d, Promisc Policy: %s, Bandwidth group: %ls\n",
currentNIC + 1, strMACAddress.raw(), strAttachment.c_str(),
fConnected ? "on" : "off",
fTraceEnabled ? "on" : "off",
traceFile.isEmpty() ? Bstr("none").raw() : traceFile.raw(),
pszNICType,
ulLineSpeed / 1000,
(int)ulBootPriority,
pszPromiscuousGuestPolicy,
strBwGroup.isEmpty() ? Bstr("none").raw() : strBwGroup.raw());
if (strNatSettings.length())
RTPrintf(strNatSettings.c_str());
if (strNatForwardings.length())
RTPrintf(strNatForwardings.c_str());
}
}
}
/* Pointing device information */
PointingHIDType_T aPointingHID;
const char *pszHID = "Unknown";
const char *pszMrHID = "unknown";
machine->COMGETTER(PointingHIDType)(&aPointingHID);
switch (aPointingHID)
{
case PointingHIDType_None:
pszHID = "None";
pszMrHID = "none";
break;
case PointingHIDType_PS2Mouse:
pszHID = "PS/2 Mouse";
pszMrHID = "ps2mouse";
break;
case PointingHIDType_USBMouse:
pszHID = "USB Mouse";
pszMrHID = "usbmouse";
break;
case PointingHIDType_USBTablet:
pszHID = "USB Tablet";
pszMrHID = "usbtablet";
break;
case PointingHIDType_ComboMouse:
pszHID = "USB Tablet and PS/2 Mouse";
pszMrHID = "combomouse";
break;
case PointingHIDType_USBMultiTouch:
pszHID = "USB Multi-Touch";
pszMrHID = "usbmultitouch";
break;
default:
break;
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("hidpointing=\"%s\"\n", pszMrHID);
else
RTPrintf("Pointing Device: %s\n", pszHID);
/* Keyboard device information */
KeyboardHIDType_T aKeyboardHID;
machine->COMGETTER(KeyboardHIDType)(&aKeyboardHID);
pszHID = "Unknown";
pszMrHID = "unknown";
switch (aKeyboardHID)
{
case KeyboardHIDType_None:
pszHID = "None";
pszMrHID = "none";
break;
case KeyboardHIDType_PS2Keyboard:
pszHID = "PS/2 Keyboard";
pszMrHID = "ps2kbd";
break;
case KeyboardHIDType_USBKeyboard:
pszHID = "USB Keyboard";
pszMrHID = "usbkbd";
break;
case KeyboardHIDType_ComboKeyboard:
pszHID = "USB and PS/2 Keyboard";
pszMrHID = "combokbd";
break;
default:
break;
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("hidkeyboard=\"%s\"\n", pszMrHID);
else
RTPrintf("Keyboard Device: %s\n", pszHID);
ComPtr<ISystemProperties> sysProps;
pVirtualBox->COMGETTER(SystemProperties)(sysProps.asOutParam());
/* get the maximum amount of UARTs */
ULONG maxUARTs = 0;
sysProps->COMGETTER(SerialPortCount)(&maxUARTs);
for (ULONG currentUART = 0; currentUART < maxUARTs; currentUART++)
{
ComPtr<ISerialPort> uart;
rc = machine->GetSerialPort(currentUART, uart.asOutParam());
if (SUCCEEDED(rc) && uart)
{
/* show the config of this UART */
BOOL fEnabled;
uart->COMGETTER(Enabled)(&fEnabled);
if (!fEnabled)
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("uart%d=\"off\"\n", currentUART + 1);
else
RTPrintf("UART %d: disabled\n", currentUART + 1);
}
else
{
ULONG ulIRQ, ulIOBase;
PortMode_T HostMode;
Bstr path;
BOOL fServer;
uart->COMGETTER(IRQ)(&ulIRQ);
uart->COMGETTER(IOBase)(&ulIOBase);
uart->COMGETTER(Path)(path.asOutParam());
uart->COMGETTER(Server)(&fServer);
uart->COMGETTER(HostMode)(&HostMode);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("uart%d=\"%#06x,%d\"\n", currentUART + 1,
ulIOBase, ulIRQ);
else
RTPrintf("UART %d: I/O base: %#06x, IRQ: %d",
currentUART + 1, ulIOBase, ulIRQ);
switch (HostMode)
{
default:
case PortMode_Disconnected:
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("uartmode%d=\"disconnected\"\n", currentUART + 1);
else
RTPrintf(", disconnected\n");
break;
case PortMode_RawFile:
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("uartmode%d=\"file,%ls\"\n", currentUART + 1,
path.raw());
else
RTPrintf(", attached to raw file '%ls'\n",
path.raw());
break;
case PortMode_TCP:
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("uartmode%d=\"%s,%ls\"\n", currentUART + 1,
fServer ? "tcpserver" : "tcpclient", path.raw());
else
RTPrintf(", attached to tcp (%s) '%ls'\n",
fServer ? "server" : "client", path.raw());
break;
case PortMode_HostPipe:
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("uartmode%d=\"%s,%ls\"\n", currentUART + 1,
fServer ? "server" : "client", path.raw());
else
RTPrintf(", attached to pipe (%s) '%ls'\n",
fServer ? "server" : "client", path.raw());
break;
case PortMode_HostDevice:
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("uartmode%d=\"%ls\"\n", currentUART + 1,
path.raw());
else
RTPrintf(", attached to device '%ls'\n", path.raw());
break;
}
}
}
}
/* get the maximum amount of LPTs */
ULONG maxLPTs = 0;
sysProps->COMGETTER(ParallelPortCount)(&maxLPTs);
for (ULONG currentLPT = 0; currentLPT < maxLPTs; currentLPT++)
{
ComPtr<IParallelPort> lpt;
rc = machine->GetParallelPort(currentLPT, lpt.asOutParam());
if (SUCCEEDED(rc) && lpt)
{
/* show the config of this LPT */
BOOL fEnabled;
lpt->COMGETTER(Enabled)(&fEnabled);
if (!fEnabled)
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("lpt%d=\"off\"\n", currentLPT + 1);
else
RTPrintf("LPT %d: disabled\n", currentLPT + 1);
}
else
{
ULONG ulIRQ, ulIOBase;
Bstr path;
lpt->COMGETTER(IRQ)(&ulIRQ);
lpt->COMGETTER(IOBase)(&ulIOBase);
lpt->COMGETTER(Path)(path.asOutParam());
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("lpt%d=\"%#06x,%d\"\n", currentLPT + 1,
ulIOBase, ulIRQ);
else
RTPrintf("LPT %d: I/O base: %#06x, IRQ: %d",
currentLPT + 1, ulIOBase, ulIRQ);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("lptmode%d=\"%ls\"\n", currentLPT + 1,
path.raw());
else
RTPrintf(", attached to device '%ls'\n", path.raw());
}
}
}
ComPtr<IAudioAdapter> AudioAdapter;
rc = machine->COMGETTER(AudioAdapter)(AudioAdapter.asOutParam());
if (SUCCEEDED(rc))
{
const char *pszDrv = "Unknown";
const char *pszCtrl = "Unknown";
const char *pszCodec = "Unknown";
BOOL fEnabled;
rc = AudioAdapter->COMGETTER(Enabled)(&fEnabled);
if (SUCCEEDED(rc) && fEnabled)
{
AudioDriverType_T enmDrvType;
rc = AudioAdapter->COMGETTER(AudioDriver)(&enmDrvType);
switch (enmDrvType)
{
case AudioDriverType_Null:
if (details == VMINFO_MACHINEREADABLE)
pszDrv = "null";
else
pszDrv = "Null";
break;
case AudioDriverType_WinMM:
if (details == VMINFO_MACHINEREADABLE)
pszDrv = "winmm";
else
pszDrv = "WINMM";
break;
case AudioDriverType_DirectSound:
if (details == VMINFO_MACHINEREADABLE)
pszDrv = "dsound";
else
pszDrv = "DSOUND";
break;
case AudioDriverType_OSS:
if (details == VMINFO_MACHINEREADABLE)
pszDrv = "oss";
else
pszDrv = "OSS";
break;
case AudioDriverType_ALSA:
if (details == VMINFO_MACHINEREADABLE)
pszDrv = "alsa";
else
pszDrv = "ALSA";
break;
case AudioDriverType_Pulse:
if (details == VMINFO_MACHINEREADABLE)
pszDrv = "pulse";
else
pszDrv = "PulseAudio";
break;
case AudioDriverType_CoreAudio:
if (details == VMINFO_MACHINEREADABLE)
pszDrv = "coreaudio";
else
pszDrv = "CoreAudio";
break;
case AudioDriverType_SolAudio:
if (details == VMINFO_MACHINEREADABLE)
pszDrv = "solaudio";
else
pszDrv = "SolAudio";
break;
default:
if (details == VMINFO_MACHINEREADABLE)
pszDrv = "unknown";
break;
}
AudioControllerType_T enmCtrlType;
rc = AudioAdapter->COMGETTER(AudioController)(&enmCtrlType);
switch (enmCtrlType)
{
case AudioControllerType_AC97:
if (details == VMINFO_MACHINEREADABLE)
pszCtrl = "ac97";
else
pszCtrl = "AC97";
break;
case AudioControllerType_SB16:
if (details == VMINFO_MACHINEREADABLE)
pszCtrl = "sb16";
else
pszCtrl = "SB16";
break;
case AudioControllerType_HDA:
if (details == VMINFO_MACHINEREADABLE)
pszCtrl = "hda";
else
pszCtrl = "HDA";
break;
default:
break;
}
AudioCodecType_T enmCodecType;
rc = AudioAdapter->COMGETTER(AudioCodec)(&enmCodecType);
switch (enmCodecType)
{
case AudioCodecType_SB16:
pszCodec = "SB16";
break;
case AudioCodecType_STAC9700:
pszCodec = "STAC9700";
break;
case AudioCodecType_AD1980:
pszCodec = "AD1980";
break;
case AudioCodecType_STAC9221:
pszCodec = "STAC9221";
break;
case AudioCodecType_Null: break; /* Shut up MSC. */
default: break;
}
}
else
fEnabled = FALSE;
BOOL fEnabledIn = false;
CHECK_ERROR(AudioAdapter, COMGETTER(EnabledIn)(&fEnabledIn));
BOOL fEnabledOut = false;
CHECK_ERROR(AudioAdapter, COMGETTER(EnabledOut)(&fEnabledOut));
if (details == VMINFO_MACHINEREADABLE)
{
if (fEnabled)
RTPrintf("audio=\"%s\"\n", pszDrv);
else
RTPrintf("audio=\"none\"\n");
RTPrintf("audio_in=\"%s\"\n", fEnabledIn ? "true" : "false");
RTPrintf("audio_out=\"%s\"\n", fEnabledOut ? "true" : "false");
}
else
{
RTPrintf("Audio: %s",
fEnabled ? "enabled" : "disabled");
if (fEnabled)
RTPrintf(" (Driver: %s, Controller: %s, Codec: %s)",
pszDrv, pszCtrl, pszCodec);
RTPrintf("\n");
RTPrintf("Audio playback: %s\n", fEnabledOut ? "enabled" : "disabled");
RTPrintf("Audio capture: %s\n", fEnabledIn ? "enabled" : "disabled");
}
}
/* Shared clipboard */
{
const char *psz = "Unknown";
ClipboardMode_T enmMode;
rc = machine->COMGETTER(ClipboardMode)(&enmMode);
switch (enmMode)
{
case ClipboardMode_Disabled:
if (details == VMINFO_MACHINEREADABLE)
psz = "disabled";
else
psz = "disabled";
break;
case ClipboardMode_HostToGuest:
if (details == VMINFO_MACHINEREADABLE)
psz = "hosttoguest";
else
psz = "HostToGuest";
break;
case ClipboardMode_GuestToHost:
if (details == VMINFO_MACHINEREADABLE)
psz = "guesttohost";
else
psz = "GuestToHost";
break;
case ClipboardMode_Bidirectional:
if (details == VMINFO_MACHINEREADABLE)
psz = "bidirectional";
else
psz = "Bidirectional";
break;
default:
if (details == VMINFO_MACHINEREADABLE)
psz = "unknown";
break;
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("clipboard=\"%s\"\n", psz);
else
RTPrintf("Clipboard Mode: %s\n", psz);
}
/* Drag and drop */
{
const char *psz = "Unknown";
DnDMode_T enmMode;
rc = machine->COMGETTER(DnDMode)(&enmMode);
switch (enmMode)
{
case DnDMode_Disabled:
if (details == VMINFO_MACHINEREADABLE)
psz = "disabled";
else
psz = "disabled";
break;
case DnDMode_HostToGuest:
if (details == VMINFO_MACHINEREADABLE)
psz = "hosttoguest";
else
psz = "HostToGuest";
break;
case DnDMode_GuestToHost:
if (details == VMINFO_MACHINEREADABLE)
psz = "guesttohost";
else
psz = "GuestToHost";
break;
case DnDMode_Bidirectional:
if (details == VMINFO_MACHINEREADABLE)
psz = "bidirectional";
else
psz = "Bidirectional";
break;
default:
if (details == VMINFO_MACHINEREADABLE)
psz = "unknown";
break;
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("draganddrop=\"%s\"\n", psz);
else
RTPrintf("Drag and drop Mode: %s\n", psz);
}
{
SessionState_T sessState;
rc = machine->COMGETTER(SessionState)(&sessState);
if (SUCCEEDED(rc) && sessState != SessionState_Unlocked)
{
Bstr sessName;
rc = machine->COMGETTER(SessionName)(sessName.asOutParam());
if (SUCCEEDED(rc) && !sessName.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("SessionName=\"%ls\"\n", sessName.raw());
else
RTPrintf("Session name: %ls\n", sessName.raw());
}
}
}
if (pConsole)
{
do
{
ComPtr<IDisplay> display;
rc = pConsole->COMGETTER(Display)(display.asOutParam());
if (rc == E_ACCESSDENIED || display.isNull())
break; /* VM not powered up */
if (FAILED(rc))
{
com::GlueHandleComError(pConsole, "COMGETTER(Display)(display.asOutParam())", rc, __FILE__, __LINE__);
return rc;
}
ULONG xRes, yRes, bpp;
LONG xOrigin, yOrigin;
GuestMonitorStatus_T monitorStatus;
rc = display->GetScreenResolution(0, &xRes, &yRes, &bpp, &xOrigin, &yOrigin, &monitorStatus);
if (rc == E_ACCESSDENIED)
break; /* VM not powered up */
if (FAILED(rc))
{
com::ErrorInfo info(display, COM_IIDOF(IDisplay));
GluePrintErrorInfo(info);
return rc;
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("VideoMode=\"%d,%d,%d\"@%d,%d %d\n", xRes, yRes, bpp, xOrigin, yOrigin, monitorStatus);
else
{
const char *pszMonitorStatus = "unknown status";
switch (monitorStatus)
{
case GuestMonitorStatus_Blank: pszMonitorStatus = "blank"; break;
case GuestMonitorStatus_Enabled: pszMonitorStatus = "enabled"; break;
case GuestMonitorStatus_Disabled: pszMonitorStatus = "disabled"; break;
default: break;
}
RTPrintf("Video mode: %dx%dx%d at %d,%d %s\n", xRes, yRes, bpp, xOrigin, yOrigin, pszMonitorStatus);
}
}
while (0);
}
/*
* Remote Desktop
*/
ComPtr<IVRDEServer> vrdeServer;
rc = machine->COMGETTER(VRDEServer)(vrdeServer.asOutParam());
if (SUCCEEDED(rc) && vrdeServer)
{
BOOL fEnabled = false;
vrdeServer->COMGETTER(Enabled)(&fEnabled);
if (fEnabled)
{
LONG currentPort = -1;
Bstr ports;
vrdeServer->GetVRDEProperty(Bstr("TCP/Ports").raw(), ports.asOutParam());
Bstr address;
vrdeServer->GetVRDEProperty(Bstr("TCP/Address").raw(), address.asOutParam());
BOOL fMultiCon;
vrdeServer->COMGETTER(AllowMultiConnection)(&fMultiCon);
BOOL fReuseCon;
vrdeServer->COMGETTER(ReuseSingleConnection)(&fReuseCon);
Bstr videoChannel;
vrdeServer->GetVRDEProperty(Bstr("VideoChannel/Enabled").raw(), videoChannel.asOutParam());
BOOL fVideoChannel = (videoChannel.compare(Bstr("true"), Bstr::CaseInsensitive)== 0)
|| (videoChannel == "1");
Bstr videoChannelQuality;
vrdeServer->GetVRDEProperty(Bstr("VideoChannel/Quality").raw(), videoChannelQuality.asOutParam());
AuthType_T authType;
const char *strAuthType;
vrdeServer->COMGETTER(AuthType)(&authType);
switch (authType)
{
case AuthType_Null:
strAuthType = "null";
break;
case AuthType_External:
strAuthType = "external";
break;
case AuthType_Guest:
strAuthType = "guest";
break;
default:
strAuthType = "unknown";
break;
}
if (pConsole)
{
ComPtr<IVRDEServerInfo> vrdeServerInfo;
CHECK_ERROR_RET(pConsole, COMGETTER(VRDEServerInfo)(vrdeServerInfo.asOutParam()), rc);
if (!vrdeServerInfo.isNull())
{
rc = vrdeServerInfo->COMGETTER(Port)(¤tPort);
if (rc == E_ACCESSDENIED)
{
currentPort = -1; /* VM not powered up */
}
else if (FAILED(rc))
{
com::ErrorInfo info(vrdeServerInfo, COM_IIDOF(IVRDEServerInfo));
GluePrintErrorInfo(info);
return rc;
}
}
}
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("vrde=\"on\"\n");
RTPrintf("vrdeport=%d\n", currentPort);
RTPrintf("vrdeports=\"%ls\"\n", ports.raw());
RTPrintf("vrdeaddress=\"%ls\"\n", address.raw());
RTPrintf("vrdeauthtype=\"%s\"\n", strAuthType);
RTPrintf("vrdemulticon=\"%s\"\n", fMultiCon ? "on" : "off");
RTPrintf("vrdereusecon=\"%s\"\n", fReuseCon ? "on" : "off");
RTPrintf("vrdevideochannel=\"%s\"\n", fVideoChannel ? "on" : "off");
if (fVideoChannel)
RTPrintf("vrdevideochannelquality=\"%ls\"\n", videoChannelQuality.raw());
}
else
{
if (address.isEmpty())
address = "0.0.0.0";
RTPrintf("VRDE: enabled (Address %ls, Ports %ls, MultiConn: %s, ReuseSingleConn: %s, Authentication type: %s)\n", address.raw(), ports.raw(), fMultiCon ? "on" : "off", fReuseCon ? "on" : "off", strAuthType);
if (pConsole && currentPort != -1 && currentPort != 0)
RTPrintf("VRDE port: %d\n", currentPort);
if (fVideoChannel)
RTPrintf("Video redirection: enabled (Quality %ls)\n", videoChannelQuality.raw());
else
RTPrintf("Video redirection: disabled\n");
}
com::SafeArray<BSTR> aProperties;
if (SUCCEEDED(vrdeServer->COMGETTER(VRDEProperties)(ComSafeArrayAsOutParam(aProperties))))
{
unsigned i;
for (i = 0; i < aProperties.size(); ++i)
{
Bstr value;
vrdeServer->GetVRDEProperty(aProperties[i], value.asOutParam());
if (details == VMINFO_MACHINEREADABLE)
{
if (value.isEmpty())
RTPrintf("vrdeproperty[%ls]=<not set>\n", aProperties[i]);
else
RTPrintf("vrdeproperty[%ls]=\"%ls\"\n", aProperties[i], value.raw());
}
else
{
if (value.isEmpty())
RTPrintf("VRDE property: %-10lS = <not set>\n", aProperties[i]);
else
RTPrintf("VRDE property: %-10lS = \"%ls\"\n", aProperties[i], value.raw());
}
}
}
}
else
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("vrde=\"off\"\n");
else
RTPrintf("VRDE: disabled\n");
}
}
/*
* USB.
*/
SafeIfaceArray<IUSBController> USBCtlColl;
rc = machine->COMGETTER(USBControllers)(ComSafeArrayAsOutParam(USBCtlColl));
if (SUCCEEDED(rc))
{
bool fOhciEnabled = false;
bool fEhciEnabled = false;
bool fXhciEnabled = false;
for (unsigned i = 0; i < USBCtlColl.size(); i++)
{
USBControllerType_T enmType;
rc = USBCtlColl[i]->COMGETTER(Type)(&enmType);
if (SUCCEEDED(rc))
{
switch (enmType)
{
case USBControllerType_OHCI:
fOhciEnabled = true;
break;
case USBControllerType_EHCI:
fEhciEnabled = true;
break;
case USBControllerType_XHCI:
fXhciEnabled = true;
break;
default:
break;
}
}
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("usb=\"%s\"\n", fOhciEnabled ? "on" : "off");
else
RTPrintf("USB: %s\n", fOhciEnabled ? "enabled" : "disabled");
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("ehci=\"%s\"\n", fEhciEnabled ? "on" : "off");
else
RTPrintf("EHCI: %s\n", fEhciEnabled ? "enabled" : "disabled");
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("xhci=\"%s\"\n", fXhciEnabled ? "on" : "off");
else
RTPrintf("XHCI: %s\n", fXhciEnabled ? "enabled" : "disabled");
}
ComPtr<IUSBDeviceFilters> USBFlts;
rc = machine->COMGETTER(USBDeviceFilters)(USBFlts.asOutParam());
if (SUCCEEDED(rc))
{
SafeIfaceArray <IUSBDeviceFilter> Coll;
rc = USBFlts->COMGETTER(DeviceFilters)(ComSafeArrayAsOutParam(Coll));
if (SUCCEEDED(rc))
{
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("\nUSB Device Filters:\n\n");
if (Coll.size() == 0)
{
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("<none>\n\n");
}
else
{
for (size_t index = 0; index < Coll.size(); ++index)
{
ComPtr<IUSBDeviceFilter> DevPtr = Coll[index];
/* Query info. */
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("Index: %zu\n", index);
BOOL bActive = FALSE;
CHECK_ERROR_RET(DevPtr, COMGETTER(Active)(&bActive), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBFilterActive%zu=\"%s\"\n", index + 1, bActive ? "on" : "off");
else
RTPrintf("Active: %s\n", bActive ? "yes" : "no");
Bstr bstr;
CHECK_ERROR_RET(DevPtr, COMGETTER(Name)(bstr.asOutParam()), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBFilterName%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Name: %ls\n", bstr.raw());
CHECK_ERROR_RET(DevPtr, COMGETTER(VendorId)(bstr.asOutParam()), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBFilterVendorId%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("VendorId: %ls\n", bstr.raw());
CHECK_ERROR_RET(DevPtr, COMGETTER(ProductId)(bstr.asOutParam()), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBFilterProductId%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("ProductId: %ls\n", bstr.raw());
CHECK_ERROR_RET(DevPtr, COMGETTER(Revision)(bstr.asOutParam()), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBFilterRevision%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Revision: %ls\n", bstr.raw());
CHECK_ERROR_RET(DevPtr, COMGETTER(Manufacturer)(bstr.asOutParam()), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBFilterManufacturer%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Manufacturer: %ls\n", bstr.raw());
CHECK_ERROR_RET(DevPtr, COMGETTER(Product)(bstr.asOutParam()), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBFilterProduct%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Product: %ls\n", bstr.raw());
CHECK_ERROR_RET(DevPtr, COMGETTER(Remote)(bstr.asOutParam()), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBFilterRemote%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Remote: %ls\n", bstr.raw());
CHECK_ERROR_RET(DevPtr, COMGETTER(SerialNumber)(bstr.asOutParam()), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBFilterSerialNumber%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Serial Number: %ls\n", bstr.raw());
if (details != VMINFO_MACHINEREADABLE)
{
ULONG fMaskedIfs;
CHECK_ERROR_RET(DevPtr, COMGETTER(MaskedInterfaces)(&fMaskedIfs), rc);
if (fMaskedIfs)
RTPrintf("Masked Interfaces: %#010x\n", fMaskedIfs);
RTPrintf("\n");
}
}
}
}
if (pConsole)
{
/* scope */
{
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("Available remote USB devices:\n\n");
SafeIfaceArray <IHostUSBDevice> coll;
CHECK_ERROR_RET(pConsole, COMGETTER(RemoteUSBDevices)(ComSafeArrayAsOutParam(coll)), rc);
if (coll.size() == 0)
{
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("<none>\n\n");
}
else
{
for (size_t index = 0; index < coll.size(); ++index)
{
ComPtr<IHostUSBDevice> dev = coll[index];
/* Query info. */
Bstr id;
CHECK_ERROR_RET(dev, COMGETTER(Id)(id.asOutParam()), rc);
USHORT usVendorId;
CHECK_ERROR_RET(dev, COMGETTER(VendorId)(&usVendorId), rc);
USHORT usProductId;
CHECK_ERROR_RET(dev, COMGETTER(ProductId)(&usProductId), rc);
USHORT bcdRevision;
CHECK_ERROR_RET(dev, COMGETTER(Revision)(&bcdRevision), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBRemoteUUID%zu=\"%s\"\n"
"USBRemoteVendorId%zu=\"%#06x\"\n"
"USBRemoteProductId%zu=\"%#06x\"\n"
"USBRemoteRevision%zu=\"%#04x%02x\"\n",
index + 1, Utf8Str(id).c_str(),
index + 1, usVendorId,
index + 1, usProductId,
index + 1, bcdRevision >> 8, bcdRevision & 0xff);
else
RTPrintf("UUID: %s\n"
"VendorId: %#06x (%04X)\n"
"ProductId: %#06x (%04X)\n"
"Revision: %u.%u (%02u%02u)\n",
Utf8Str(id).c_str(),
usVendorId, usVendorId, usProductId, usProductId,
bcdRevision >> 8, bcdRevision & 0xff,
bcdRevision >> 8, bcdRevision & 0xff);
/* optional stuff. */
Bstr bstr;
CHECK_ERROR_RET(dev, COMGETTER(Manufacturer)(bstr.asOutParam()), rc);
if (!bstr.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBRemoteManufacturer%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Manufacturer: %ls\n", bstr.raw());
}
CHECK_ERROR_RET(dev, COMGETTER(Product)(bstr.asOutParam()), rc);
if (!bstr.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBRemoteProduct%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Product: %ls\n", bstr.raw());
}
CHECK_ERROR_RET(dev, COMGETTER(SerialNumber)(bstr.asOutParam()), rc);
if (!bstr.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBRemoteSerialNumber%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("SerialNumber: %ls\n", bstr.raw());
}
CHECK_ERROR_RET(dev, COMGETTER(Address)(bstr.asOutParam()), rc);
if (!bstr.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBRemoteAddress%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Address: %ls\n", bstr.raw());
}
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("\n");
}
}
}
/* scope */
{
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("Currently Attached USB Devices:\n\n");
SafeIfaceArray <IUSBDevice> coll;
CHECK_ERROR_RET(pConsole, COMGETTER(USBDevices)(ComSafeArrayAsOutParam(coll)), rc);
if (coll.size() == 0)
{
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("<none>\n\n");
}
else
{
for (size_t index = 0; index < coll.size(); ++index)
{
ComPtr<IUSBDevice> dev = coll[index];
/* Query info. */
Bstr id;
CHECK_ERROR_RET(dev, COMGETTER(Id)(id.asOutParam()), rc);
USHORT usVendorId;
CHECK_ERROR_RET(dev, COMGETTER(VendorId)(&usVendorId), rc);
USHORT usProductId;
CHECK_ERROR_RET(dev, COMGETTER(ProductId)(&usProductId), rc);
USHORT bcdRevision;
CHECK_ERROR_RET(dev, COMGETTER(Revision)(&bcdRevision), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBAttachedUUID%zu=\"%s\"\n"
"USBAttachedVendorId%zu=\"%#06x\"\n"
"USBAttachedProductId%zu=\"%#06x\"\n"
"USBAttachedRevision%zu=\"%#04x%02x\"\n",
index + 1, Utf8Str(id).c_str(),
index + 1, usVendorId,
index + 1, usProductId,
index + 1, bcdRevision >> 8, bcdRevision & 0xff);
else
RTPrintf("UUID: %s\n"
"VendorId: %#06x (%04X)\n"
"ProductId: %#06x (%04X)\n"
"Revision: %u.%u (%02u%02u)\n",
Utf8Str(id).c_str(),
usVendorId, usVendorId, usProductId, usProductId,
bcdRevision >> 8, bcdRevision & 0xff,
bcdRevision >> 8, bcdRevision & 0xff);
/* optional stuff. */
Bstr bstr;
CHECK_ERROR_RET(dev, COMGETTER(Manufacturer)(bstr.asOutParam()), rc);
if (!bstr.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBAttachedManufacturer%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Manufacturer: %ls\n", bstr.raw());
}
CHECK_ERROR_RET(dev, COMGETTER(Product)(bstr.asOutParam()), rc);
if (!bstr.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBAttachedProduct%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Product: %ls\n", bstr.raw());
}
CHECK_ERROR_RET(dev, COMGETTER(SerialNumber)(bstr.asOutParam()), rc);
if (!bstr.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBAttachedSerialNumber%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("SerialNumber: %ls\n", bstr.raw());
}
CHECK_ERROR_RET(dev, COMGETTER(Address)(bstr.asOutParam()), rc);
if (!bstr.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("USBAttachedAddress%zu=\"%ls\"\n", index + 1, bstr.raw());
else
RTPrintf("Address: %ls\n", bstr.raw());
}
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("\n");
}
}
}
}
} /* USB */
#ifdef VBOX_WITH_PCI_PASSTHROUGH
/* Host PCI passthrough devices */
{
SafeIfaceArray <IPCIDeviceAttachment> assignments;
rc = machine->COMGETTER(PCIDeviceAssignments)(ComSafeArrayAsOutParam(assignments));
if (SUCCEEDED(rc))
{
if (assignments.size() > 0 && (details != VMINFO_MACHINEREADABLE))
{
RTPrintf("\nAttached physical PCI devices:\n\n");
}
for (size_t index = 0; index < assignments.size(); ++index)
{
ComPtr<IPCIDeviceAttachment> Assignment = assignments[index];
char szHostPCIAddress[32], szGuestPCIAddress[32];
LONG iHostPCIAddress = -1, iGuestPCIAddress = -1;
Bstr DevName;
Assignment->COMGETTER(Name)(DevName.asOutParam());
Assignment->COMGETTER(HostAddress)(&iHostPCIAddress);
Assignment->COMGETTER(GuestAddress)(&iGuestPCIAddress);
PCIBusAddress().fromLong(iHostPCIAddress).format(szHostPCIAddress, sizeof(szHostPCIAddress));
PCIBusAddress().fromLong(iGuestPCIAddress).format(szGuestPCIAddress, sizeof(szGuestPCIAddress));
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("AttachedHostPCI=%s,%s\n", szHostPCIAddress, szGuestPCIAddress);
else
RTPrintf(" Host device %ls at %s attached as %s\n", DevName.raw(), szHostPCIAddress, szGuestPCIAddress);
}
if (assignments.size() > 0 && (details != VMINFO_MACHINEREADABLE))
{
RTPrintf("\n");
}
}
}
/* Host PCI passthrough devices */
#endif
/*
* Bandwidth groups
*/
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("Bandwidth groups: ");
{
ComPtr<IBandwidthControl> bwCtrl;
CHECK_ERROR_RET(machine, COMGETTER(BandwidthControl)(bwCtrl.asOutParam()), rc);
rc = showBandwidthGroups(bwCtrl, details);
}
/*
* Shared folders
*/
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("Shared folders: ");
uint32_t numSharedFolders = 0;
#if 0 // not yet implemented
/* globally shared folders first */
{
SafeIfaceArray <ISharedFolder> sfColl;
CHECK_ERROR_RET(pVirtualBox, COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(sfColl)), rc);
for (size_t i = 0; i < sfColl.size(); ++i)
{
ComPtr<ISharedFolder> sf = sfColl[i];
Bstr name, hostPath;
sf->COMGETTER(Name)(name.asOutParam());
sf->COMGETTER(HostPath)(hostPath.asOutParam());
RTPrintf("Name: '%ls', Host path: '%ls' (global mapping)\n", name.raw(), hostPath.raw());
++numSharedFolders;
}
}
#endif
/* now VM mappings */
{
com::SafeIfaceArray <ISharedFolder> folders;
CHECK_ERROR_RET(machine, COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders)), rc);
for (size_t i = 0; i < folders.size(); ++i)
{
ComPtr<ISharedFolder> sf = folders[i];
Bstr name, hostPath;
BOOL writable;
sf->COMGETTER(Name)(name.asOutParam());
sf->COMGETTER(HostPath)(hostPath.asOutParam());
sf->COMGETTER(Writable)(&writable);
if (!numSharedFolders && details != VMINFO_MACHINEREADABLE)
RTPrintf("\n\n");
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("SharedFolderNameMachineMapping%zu=\"%ls\"\n", i + 1,
name.raw());
RTPrintf("SharedFolderPathMachineMapping%zu=\"%ls\"\n", i + 1,
hostPath.raw());
}
else
RTPrintf("Name: '%ls', Host path: '%ls' (machine mapping), %s\n",
name.raw(), hostPath.raw(), writable ? "writable" : "readonly");
++numSharedFolders;
}
}
/* transient mappings */
if (pConsole)
{
com::SafeIfaceArray <ISharedFolder> folders;
CHECK_ERROR_RET(pConsole, COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders)), rc);
for (size_t i = 0; i < folders.size(); ++i)
{
ComPtr<ISharedFolder> sf = folders[i];
Bstr name, hostPath;
sf->COMGETTER(Name)(name.asOutParam());
sf->COMGETTER(HostPath)(hostPath.asOutParam());
if (!numSharedFolders && details != VMINFO_MACHINEREADABLE)
RTPrintf("\n\n");
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("SharedFolderNameTransientMapping%zu=\"%ls\"\n", i + 1,
name.raw());
RTPrintf("SharedFolderPathTransientMapping%zu=\"%ls\"\n", i + 1,
hostPath.raw());
}
else
RTPrintf("Name: '%ls', Host path: '%ls' (transient mapping)\n", name.raw(), hostPath.raw());
++numSharedFolders;
}
}
if (!numSharedFolders && details != VMINFO_MACHINEREADABLE)
RTPrintf("<none>\n");
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("\n");
if (pConsole)
{
/*
* Live VRDE info.
*/
ComPtr<IVRDEServerInfo> vrdeServerInfo;
CHECK_ERROR_RET(pConsole, COMGETTER(VRDEServerInfo)(vrdeServerInfo.asOutParam()), rc);
BOOL Active = FALSE;
ULONG NumberOfClients = 0;
LONG64 BeginTime = 0;
LONG64 EndTime = 0;
LONG64 BytesSent = 0;
LONG64 BytesSentTotal = 0;
LONG64 BytesReceived = 0;
LONG64 BytesReceivedTotal = 0;
Bstr User;
Bstr Domain;
Bstr ClientName;
Bstr ClientIP;
ULONG ClientVersion = 0;
ULONG EncryptionStyle = 0;
if (!vrdeServerInfo.isNull())
{
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(Active)(&Active), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(NumberOfClients)(&NumberOfClients), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(BeginTime)(&BeginTime), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(EndTime)(&EndTime), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(BytesSent)(&BytesSent), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(BytesSentTotal)(&BytesSentTotal), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(BytesReceived)(&BytesReceived), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(BytesReceivedTotal)(&BytesReceivedTotal), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(User)(User.asOutParam()), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(Domain)(Domain.asOutParam()), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(ClientName)(ClientName.asOutParam()), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(ClientIP)(ClientIP.asOutParam()), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(ClientVersion)(&ClientVersion), rc);
CHECK_ERROR_RET(vrdeServerInfo, COMGETTER(EncryptionStyle)(&EncryptionStyle), rc);
}
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("VRDEActiveConnection=\"%s\"\n", Active ? "on": "off");
else
RTPrintf("VRDE Connection: %s\n", Active? "active": "not active");
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("VRDEClients=%d\n", NumberOfClients);
else
RTPrintf("Clients so far: %d\n", NumberOfClients);
if (NumberOfClients > 0)
{
char timestr[128];
if (Active)
{
makeTimeStr(timestr, sizeof(timestr), BeginTime);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("VRDEStartTime=\"%s\"\n", timestr);
else
RTPrintf("Start time: %s\n", timestr);
}
else
{
makeTimeStr(timestr, sizeof(timestr), BeginTime);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("VRDELastStartTime=\"%s\"\n", timestr);
else
RTPrintf("Last started: %s\n", timestr);
makeTimeStr(timestr, sizeof(timestr), EndTime);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("VRDELastEndTime=\"%s\"\n", timestr);
else
RTPrintf("Last ended: %s\n", timestr);
}
int64_t ThroughputSend = 0;
int64_t ThroughputReceive = 0;
if (EndTime != BeginTime)
{
ThroughputSend = (BytesSent * 1000) / (EndTime - BeginTime);
ThroughputReceive = (BytesReceived * 1000) / (EndTime - BeginTime);
}
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("VRDEBytesSent=%lld\n", BytesSent);
RTPrintf("VRDEThroughputSend=%lld\n", ThroughputSend);
RTPrintf("VRDEBytesSentTotal=%lld\n", BytesSentTotal);
RTPrintf("VRDEBytesReceived=%lld\n", BytesReceived);
RTPrintf("VRDEThroughputReceive=%lld\n", ThroughputReceive);
RTPrintf("VRDEBytesReceivedTotal=%lld\n", BytesReceivedTotal);
}
else
{
RTPrintf("Sent: %lld Bytes\n", BytesSent);
RTPrintf("Average speed: %lld B/s\n", ThroughputSend);
RTPrintf("Sent total: %lld Bytes\n", BytesSentTotal);
RTPrintf("Received: %lld Bytes\n", BytesReceived);
RTPrintf("Speed: %lld B/s\n", ThroughputReceive);
RTPrintf("Received total: %lld Bytes\n", BytesReceivedTotal);
}
if (Active)
{
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("VRDEUserName=\"%ls\"\n", User.raw());
RTPrintf("VRDEDomain=\"%ls\"\n", Domain.raw());
RTPrintf("VRDEClientName=\"%ls\"\n", ClientName.raw());
RTPrintf("VRDEClientIP=\"%ls\"\n", ClientIP.raw());
RTPrintf("VRDEClientVersion=%d\n", ClientVersion);
RTPrintf("VRDEEncryption=\"%s\"\n", EncryptionStyle == 0? "RDP4": "RDP5 (X.509)");
}
else
{
RTPrintf("User name: %ls\n", User.raw());
RTPrintf("Domain: %ls\n", Domain.raw());
RTPrintf("Client name: %ls\n", ClientName.raw());
RTPrintf("Client IP: %ls\n", ClientIP.raw());
RTPrintf("Client version: %d\n", ClientVersion);
RTPrintf("Encryption: %s\n", EncryptionStyle == 0? "RDP4": "RDP5 (X.509)");
}
}
}
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("\n");
}
#ifdef VBOX_WITH_VIDEOREC
{
/* Video capture */
BOOL fCaptureVideo = FALSE;
# ifdef VBOX_WITH_AUDIO_VIDEOREC
BOOL fCaptureAudio = FALSE;
# endif
CHECK_ERROR_RET(machine, COMGETTER(VideoCaptureEnabled)(&fCaptureVideo), rc);
com::SafeArray<BOOL> screens;
CHECK_ERROR_RET(machine, COMGETTER(VideoCaptureScreens)(ComSafeArrayAsOutParam(screens)), rc);
ULONG Width;
CHECK_ERROR_RET(machine, COMGETTER(VideoCaptureWidth)(&Width), rc);
ULONG Height;
CHECK_ERROR_RET(machine, COMGETTER(VideoCaptureHeight)(&Height), rc);
ULONG Rate;
CHECK_ERROR_RET(machine, COMGETTER(VideoCaptureRate)(&Rate), rc);
ULONG Fps;
CHECK_ERROR_RET(machine, COMGETTER(VideoCaptureFPS)(&Fps), rc);
Bstr bstrFile;
CHECK_ERROR_RET(machine, COMGETTER(VideoCaptureFile)(bstrFile.asOutParam()), rc);
Bstr bstrOptions;
CHECK_ERROR_RET(machine, COMGETTER(VideoCaptureOptions)(bstrOptions.asOutParam()), rc);
Utf8Str strOptions(bstrOptions);
size_t pos = 0;
com::Utf8Str key, value;
while ((pos = strOptions.parseKeyValue(key, value, pos)) != com::Utf8Str::npos)
{
if (key.compare("vc_enabled", Utf8Str::CaseInsensitive) == 0)
{
fCaptureVideo = value.compare("true", Utf8Str::CaseInsensitive) == 0;
}
else if (key.compare("ac_enabled", Utf8Str::CaseInsensitive) == 0)
{
# ifdef VBOX_WITH_AUDIO_VIDEOREC
fCaptureAudio = value.compare("true", Utf8Str::CaseInsensitive) == 0;
# endif
}
}
if (details == VMINFO_MACHINEREADABLE)
{
RTPrintf("videocap=\"%s\"\n", fCaptureVideo ? "on" : "off");
# ifdef VBOX_WITH_AUDIO_VIDEOREC
RTPrintf("videocap_audio=\"%s\"\n", fCaptureAudio ? "on" : "off");
# endif
RTPrintf("videocapscreens=");
bool fComma = false;
for (unsigned i = 0; i < screens.size(); i++)
if (screens[i])
{
RTPrintf("%s%u", fComma ? "," : "", i);
fComma = true;
}
RTPrintf("\n");
RTPrintf("videocapfile=\"%ls\"\n", bstrFile.raw());
RTPrintf("videocapres=%ux%u\n", (unsigned)Width, (unsigned)Height);
RTPrintf("videocaprate=%u\n", (unsigned)Rate);
RTPrintf("videocapfps=%u\n", (unsigned)Fps);
RTPrintf("videocapopts=%ls\n", bstrOptions.raw());
}
else
{
RTPrintf("Capturing: %s\n", fCaptureVideo ? "active" : "not active");
# ifdef VBOX_WITH_AUDIO_VIDEOREC
RTPrintf("Capture audio: %s\n", fCaptureAudio ? "active" : "not active");
# endif
RTPrintf("Capture screens: ");
bool fComma = false;
for (unsigned i = 0; i < screens.size(); i++)
if (screens[i])
{
RTPrintf("%s%u", fComma ? "," : "", i);
fComma = true;
}
RTPrintf("\n");
RTPrintf("Capture file: %ls\n", bstrFile.raw());
RTPrintf("Capture dimensions: %ux%u\n", Width, Height);
RTPrintf("Capture rate: %u kbps\n", Rate);
RTPrintf("Capture FPS: %u\n", Fps);
RTPrintf("Capture options: %ls\n", bstrOptions.raw());
RTPrintf("\n");
/** @todo Add more audio capturing profile / information here. */
}
}
#endif /* VBOX_WITH_VIDEOREC */
if ( details == VMINFO_STANDARD
|| details == VMINFO_FULL
|| details == VMINFO_MACHINEREADABLE)
{
Bstr description;
machine->COMGETTER(Description)(description.asOutParam());
if (!description.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
outputMachineReadableString("description", &description);
else
RTPrintf("Description:\n%ls\n", description.raw());
}
}
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("Guest:\n\n");
ULONG guestVal;
rc = machine->COMGETTER(MemoryBalloonSize)(&guestVal);
if (SUCCEEDED(rc))
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("GuestMemoryBalloon=%d\n", guestVal);
else
RTPrintf("Configured memory balloon size: %d MB\n", guestVal);
}
if (pConsole)
{
ComPtr<IGuest> guest;
rc = pConsole->COMGETTER(Guest)(guest.asOutParam());
if (SUCCEEDED(rc) && !guest.isNull())
{
Bstr guestString;
rc = guest->COMGETTER(OSTypeId)(guestString.asOutParam());
if ( SUCCEEDED(rc)
&& !guestString.isEmpty())
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("GuestOSType=\"%ls\"\n", guestString.raw());
else
RTPrintf("OS type: %ls\n", guestString.raw());
}
AdditionsRunLevelType_T guestRunLevel; /** @todo Add a runlevel-to-string (e.g. 0 = "None") method? */
rc = guest->COMGETTER(AdditionsRunLevel)(&guestRunLevel);
if (SUCCEEDED(rc))
{
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("GuestAdditionsRunLevel=%u\n", guestRunLevel);
else
RTPrintf("Additions run level: %u\n", guestRunLevel);
}
rc = guest->COMGETTER(AdditionsVersion)(guestString.asOutParam());
if ( SUCCEEDED(rc)
&& !guestString.isEmpty())
{
ULONG uRevision;
rc = guest->COMGETTER(AdditionsRevision)(&uRevision);
if (FAILED(rc))
uRevision = 0;
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("GuestAdditionsVersion=\"%ls r%u\"\n", guestString.raw(), uRevision);
else
RTPrintf("Additions version: %ls r%u\n\n", guestString.raw(), uRevision);
}
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("\nGuest Facilities:\n\n");
/* Print information about known Guest Additions facilities: */
SafeIfaceArray <IAdditionsFacility> collFac;
CHECK_ERROR_RET(guest, COMGETTER(Facilities)(ComSafeArrayAsOutParam(collFac)), rc);
LONG64 lLastUpdatedMS;
char szLastUpdated[32];
AdditionsFacilityStatus_T curStatus;
for (size_t index = 0; index < collFac.size(); ++index)
{
ComPtr<IAdditionsFacility> fac = collFac[index];
if (fac)
{
CHECK_ERROR_RET(fac, COMGETTER(Name)(guestString.asOutParam()), rc);
if (!guestString.isEmpty())
{
CHECK_ERROR_RET(fac, COMGETTER(Status)(&curStatus), rc);
CHECK_ERROR_RET(fac, COMGETTER(LastUpdated)(&lLastUpdatedMS), rc);
if (details == VMINFO_MACHINEREADABLE)
RTPrintf("GuestAdditionsFacility_%ls=%u,%lld\n",
guestString.raw(), curStatus, lLastUpdatedMS);
else
{
makeTimeStr(szLastUpdated, sizeof(szLastUpdated), lLastUpdatedMS);
RTPrintf("Facility \"%ls\": %s (last update: %s)\n",
guestString.raw(), facilityStateToName(curStatus, false /* No short naming */), szLastUpdated);
}
}
else
AssertMsgFailed(("Facility with undefined name retrieved!\n"));
}
else
AssertMsgFailed(("Invalid facility returned!\n"));
}
if (!collFac.size() && details != VMINFO_MACHINEREADABLE)
RTPrintf("No active facilities.\n");
}
}
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("\n");
/*
* snapshots
*/
ComPtr<ISnapshot> snapshot;
rc = machine->FindSnapshot(Bstr().raw(), snapshot.asOutParam());
if (SUCCEEDED(rc) && snapshot)
{
ComPtr<ISnapshot> currentSnapshot;
rc = machine->COMGETTER(CurrentSnapshot)(currentSnapshot.asOutParam());
if (SUCCEEDED(rc))
{
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("Snapshots:\n\n");
showSnapshots(snapshot, currentSnapshot, details);
}
}
if (details != VMINFO_MACHINEREADABLE)
RTPrintf("\n");
return S_OK;
}
#if defined(_MSC_VER)
# pragma optimize("", on)
# pragma warning(pop)
#endif
static const RTGETOPTDEF g_aShowVMInfoOptions[] =
{
{ "--details", 'D', RTGETOPT_REQ_NOTHING },
{ "-details", 'D', RTGETOPT_REQ_NOTHING }, // deprecated
{ "--machinereadable", 'M', RTGETOPT_REQ_NOTHING },
{ "-machinereadable", 'M', RTGETOPT_REQ_NOTHING }, // deprecated
{ "--log", 'l', RTGETOPT_REQ_UINT32 },
};
RTEXITCODE handleShowVMInfo(HandlerArg *a)
{
HRESULT rc;
const char *VMNameOrUuid = NULL;
bool fLog = false;
uint32_t uLogIdx = 0;
bool fDetails = false;
bool fMachinereadable = false;
int c;
RTGETOPTUNION ValueUnion;
RTGETOPTSTATE GetState;
// start at 0 because main() has hacked both the argc and argv given to us
RTGetOptInit(&GetState, a->argc, a->argv, g_aShowVMInfoOptions, RT_ELEMENTS(g_aShowVMInfoOptions),
0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
while ((c = RTGetOpt(&GetState, &ValueUnion)))
{
switch (c)
{
case 'D': // --details
fDetails = true;
break;
case 'M': // --machinereadable
fMachinereadable = true;
break;
case 'l': // --log
fLog = true;
uLogIdx = ValueUnion.u32;
break;
case VINF_GETOPT_NOT_OPTION:
if (!VMNameOrUuid)
VMNameOrUuid = ValueUnion.psz;
else
return errorSyntax(USAGE_SHOWVMINFO, "Invalid parameter '%s'", ValueUnion.psz);
break;
default:
return errorGetOpt(USAGE_SHOWVMINFO, c, &ValueUnion);
}
}
/* check for required options */
if (!VMNameOrUuid)
return errorSyntax(USAGE_SHOWVMINFO, "VM name or UUID required");
/* try to find the given machine */
ComPtr<IMachine> machine;
CHECK_ERROR(a->virtualBox, FindMachine(Bstr(VMNameOrUuid).raw(),
machine.asOutParam()));
if (FAILED(rc))
return RTEXITCODE_FAILURE;
/* Printing the log is exclusive. */
if (fLog && (fMachinereadable || fDetails))
return errorSyntax(USAGE_SHOWVMINFO, "Option --log is exclusive");
if (fLog)
{
ULONG64 uOffset = 0;
SafeArray<BYTE> aLogData;
size_t cbLogData;
while (true)
{
/* Reset the array */
aLogData.setNull();
/* Fetch a chunk of the log file */
CHECK_ERROR_BREAK(machine, ReadLog(uLogIdx, uOffset, _1M,
ComSafeArrayAsOutParam(aLogData)));
cbLogData = aLogData.size();
if (cbLogData == 0)
break;
/* aLogData has a platform dependent line ending, standardize on
* Unix style, as RTStrmWrite does the LF -> CR/LF replacement on
* Windows. Otherwise we end up with CR/CR/LF on Windows. */
size_t cbLogDataPrint = cbLogData;
for (BYTE *s = aLogData.raw(), *d = s;
s - aLogData.raw() < (ssize_t)cbLogData;
s++, d++)
{
if (*s == '\r')
{
/* skip over CR, adjust destination */
d--;
cbLogDataPrint--;
}
else if (s != d)
*d = *s;
}
RTStrmWrite(g_pStdOut, aLogData.raw(), cbLogDataPrint);
uOffset += cbLogData;
}
}
else
{
/* 2nd option can be -details or -argdump */
VMINFO_DETAILS details = VMINFO_NONE;
if (fMachinereadable)
details = VMINFO_MACHINEREADABLE;
else if (fDetails)
details = VMINFO_FULL;
else
details = VMINFO_STANDARD;
/* open an existing session for the VM */
rc = machine->LockMachine(a->session, LockType_Shared);
if (SUCCEEDED(rc))
/* get the session machine */
rc = a->session->COMGETTER(Machine)(machine.asOutParam());
rc = showVMInfo(a->virtualBox, machine, a->session, details);
a->session->UnlockMachine();
}
return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}
#endif /* !VBOX_ONLY_DOCS */
/* vi: set tabstop=4 shiftwidth=4 expandtab: */
| 69,802 |
2,151 | <filename>src/set_unittest.cc
// Copyright (c) 2011 The Chromium OS 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 <gtest/gtest.h>
#include "gestures/include/set.h"
namespace gestures {
class SetTest : public ::testing::Test {};
TEST(SetTest, SimpleTest) {
const int kMax = 5;
set<short, kMax> set_a;
set<short, kMax> set_b;
EXPECT_EQ(0, set_a.size());
EXPECT_EQ(0, set_b.size());
EXPECT_TRUE(set_a.empty());
set<short, kMax>::iterator a_end = set_a.end();
set<short, kMax>::iterator a_f = set_a.find(1);
EXPECT_EQ(a_end, a_f);
EXPECT_EQ(set_a.end(), set_a.find(1));
set_a.insert(1);
EXPECT_EQ(1, set_a.size());
EXPECT_FALSE(set_a.empty());
EXPECT_NE(set_a.end(), set_a.find(1));
set_b.insert(3);
EXPECT_EQ(1, set_b.size());
set_b.insert(3);
EXPECT_EQ(1, set_b.size());
EXPECT_TRUE(set_a != set_b);
set_b.erase(3);
set_b.insert(2);
set_b.insert(1);
EXPECT_EQ(2, set_b.size());
EXPECT_NE(set_b.end(), set_b.find(1));
EXPECT_NE(set_b.end(), set_b.find(2));
EXPECT_TRUE(set_b != set_a);
set_a.insert(2);
EXPECT_EQ(2, set_a.size());
EXPECT_TRUE(set_b == set_a);
set_a.insert(3);
EXPECT_EQ(3, set_a.size());
set_b.insert(3);
EXPECT_EQ(3, set_b.size());
EXPECT_TRUE(set_b == set_a);
EXPECT_EQ(0, set_a.erase(4));
EXPECT_EQ(3, set_a.size());
EXPECT_TRUE(set_b == set_a);
EXPECT_EQ(1, set_a.erase(1));
EXPECT_EQ(2, set_a.size());
EXPECT_EQ(1, set_b.erase(1));
EXPECT_EQ(2, set_b.size());
EXPECT_TRUE(set_b == set_a);
set_a.clear();
EXPECT_EQ(0, set_a.size());
EXPECT_TRUE(set_b != set_a);
set_b.clear();
EXPECT_EQ(0, set_b.size());
EXPECT_TRUE(set_b == set_a);
}
TEST(SetTest, OverflowTest) {
const int kMax = 3;
set<short, kMax> the_set; // holds 3 elts
the_set.insert(4);
the_set.insert(5);
the_set.insert(6);
the_set.insert(7);
EXPECT_EQ(kMax, the_set.size());
EXPECT_NE(the_set.end(), the_set.find(4));
EXPECT_NE(the_set.end(), the_set.find(5));
EXPECT_NE(the_set.end(), the_set.find(6));
EXPECT_EQ(the_set.end(), the_set.find(7));
}
TEST(SetTest, SizeTest) {
set<short, 2> small;
set<short, 3> big;
EXPECT_TRUE(small == big);
EXPECT_FALSE(small != big);
small.insert(3);
big = small;
EXPECT_TRUE(small == big);
big.insert(2);
big.insert(1);
small = big;
}
template<typename ReducedSet, typename RequiredSet>
void DoSetRemoveMissingTest(ReducedSet* reduced,
RequiredSet* required,
bool revserse_insert_order) {
if (!revserse_insert_order) {
reduced->insert(10);
reduced->insert(11);
required->insert(11);
required->insert(12);
} else {
required->insert(12);
required->insert(11);
reduced->insert(11);
reduced->insert(10);
}
SetRemoveMissing(reduced, *required);
EXPECT_EQ(1, reduced->size());
EXPECT_EQ(2, required->size());
EXPECT_TRUE(SetContainsValue(*reduced, 11));
EXPECT_TRUE(SetContainsValue(*required, 11));
EXPECT_TRUE(SetContainsValue(*required, 12));
}
TEST(SetTest, SetRemoveMissingTest) {
for (size_t i = 0; i < 2; i++) {
set<short, 3> small;
set<short, 4> big;
DoSetRemoveMissingTest(&small, &big, i == 0);
}
for (size_t i = 0; i < 2; i++) {
set<short, 3> small;
set<short, 4> big;
DoSetRemoveMissingTest(&big, &small, i == 0);
}
for (size_t i = 0; i < 2; i++) {
set<short, 2> small;
set<short, 3> big;
DoSetRemoveMissingTest(&small, &big, i == 0);
}
for (size_t i = 0; i < 2; i++) {
set<short, 2> small;
set<short, 3> big;
DoSetRemoveMissingTest(&big, &small, i == 0);
}
for (size_t i = 0; i < 2; i++) {
std::set<short> small;
std::set<short> big;
DoSetRemoveMissingTest(&small, &big, i == 0);
}
}
template<typename LeftSet, typename RightSet>
void DoSetSubtractTest() {
LeftSet left;
RightSet right;
left.insert(4);
left.insert(2);
right.insert(1);
right.insert(2);
LeftSet out = SetSubtract(left, right);
EXPECT_EQ(1, out.size());
EXPECT_EQ(4, *out.begin());
EXPECT_EQ(2, left.size());
left.clear();
EXPECT_EQ(0, SetSubtract(left, right).size());
left.insert(5);
EXPECT_EQ(1, SetSubtract(left, right).size());
right.clear();
EXPECT_EQ(1, SetSubtract(left, right).size());
}
TEST(SetTest, SetSubtractTest) {
DoSetSubtractTest<std::set<short>, std::set<short>>();
DoSetSubtractTest<set<short, 3>, set<short, 4>>();
DoSetSubtractTest<set<short, 2>, set<short, 2>>();
DoSetSubtractTest<set<short, 4>, set<short, 2>>();
}
} // namespace gestures
| 2,088 |
1,442 | <filename>gcompiler/delta_infer/custom_ops/ops_utils.h
#ifndef _DELTA_INFER_CUSTOM_OPS_UTILS_H_
#define _DELTA_INFER_CUSTOM_OPS_UTILS_H_
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#ifdef WITH_CUDA
#include "delta_infer/custom_ops/platform/CUDA/cuda_checks.h"
#endif
namespace tensorflow {
using CPUDevice = Eigen::ThreadPoolDevice;
using GPUDevice = Eigen::GpuDevice;
enum class DeltaOpType { INT32, FP32, HALF };
template <typename Device, typename T>
struct DeltaTraits;
#ifdef WITH_CUDA
template <>
struct DeltaTraits<GPUDevice, float> {
typedef float DataType;
static const DeltaOpType OpType = DeltaOpType::FP32;
static const cudaDataType_t ComputeType = CUDA_R_32F;
};
template <>
struct DeltaTraits<GPUDevice, int> {
typedef int DataType;
static const DeltaOpType OpType = DeltaOpType::INT32;
static const cudaDataType_t ComputeType = CUDA_R_32F;
};
#endif
template <>
struct DeltaTraits<CPUDevice, float> {
typedef float DataType;
static const DeltaOpType OpType = DeltaOpType::FP32;
typedef float ComputeType;
};
template <>
struct DeltaTraits<CPUDevice, int> {
typedef int DataType;
static const DeltaOpType OpType = DeltaOpType::INT32;
typedef float ComputeType;
};
/*template<>
struct DeltaTraits<Eigen::half> {
// __half from cuda define
typedef __half DataType;
static const DeltaOpType OpType = DeltaOpType::HALF;
};*/
} /* namespace tensorflow */
#endif
| 650 |
1,120 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Associated header
//
#include "k4adevicecorrelator.h"
// System headers
//
#include <regex>
// Library headers
//
// Project headers
//
#include "k4aviewererrormanager.h"
#include "k4asoundio_util.h"
using namespace k4aviewer;
bool K4ADeviceCorrelator::GetSoundIoBackendIdToSerialNumberMapping(SoundIo *soundio,
std::map<std::string, std::string> *result)
{
const int inputCount = soundio_input_device_count(soundio);
bool foundDevices = false;
for (int i = 0; i < inputCount; i++)
{
std::unique_ptr<SoundIoDevice, SoundIoDeviceDeleter> device(soundio_get_input_device(soundio, i));
if (device)
{
// Each device is listed twice - a 'raw' device and a not-'raw' device.
// We only want the non-raw ones.
//
if (device->is_raw)
{
continue;
}
// On ALSA/Pulse, the device ID contains the serial number, so we can just extract it from the name
//
static const std::regex nameRegex(".*Kinect.*_([0-9]+)-.*");
std::cmatch match;
if (!std::regex_match(device->id, match, nameRegex))
{
continue;
}
foundDevices = true;
(*result)[device->id] = match.str(1);
}
}
return foundDevices;
}
| 723 |
17,037 | <filename>diagrams/base/__init__.py
"""
Base provides a set of general services for backend infrastructure.
"""
from diagrams import Node
class _Base(Node):
_provider = "base"
_icon_dir = "resources/base"
fontcolor = "#ffffff"
| 81 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-p7vc-9g4v-42gh",
"modified": "2021-12-31T00:00:42Z",
"published": "2021-12-29T00:00:44Z",
"aliases": [
"CVE-2021-3095"
],
"details": "A remote attacker with write access to PI Vision could inject code into a display. Unauthorized information disclosure, modification, or deletion is possible if a victim views or interacts with the infected display using Microsoft Internet Explorer. The impact affects PI System data and other data accessible with victim’s user permissions.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3095"
},
{
"type": "WEB",
"url": "https://us-cert.cisa.gov/ics/advisories/icsa-21-313-05"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": null,
"github_reviewed": false
}
} | 361 |
521 | <reponame>Fimbure/icebox-1
/* $Id: tstClipboardServiceHost.cpp $ */
/** @file
* Shared Clipboard host service test case.
*/
/*
* Copyright (C) 2011-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include "../VBoxClipboard.h"
#include <VBox/HostServices/VBoxClipboardSvc.h>
#include <iprt/assert.h>
#include <iprt/string.h>
#include <iprt/test.h>
extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad (VBOXHGCMSVCFNTABLE *ptable);
static VBOXCLIPBOARDCLIENTDATA g_Client;
static VBOXHGCMSVCHELPERS g_Helpers = { NULL };
/** Simple call handle structure for the guest call completion callback */
struct VBOXHGCMCALLHANDLE_TYPEDEF
{
/** Where to store the result code */
int32_t rc;
};
/** Call completion callback for guest calls. */
static DECLCALLBACK(void) callComplete(VBOXHGCMCALLHANDLE callHandle, int32_t rc)
{
callHandle->rc = rc;
}
static int setupTable(VBOXHGCMSVCFNTABLE *pTable)
{
pTable->cbSize = sizeof(*pTable);
pTable->u32Version = VBOX_HGCM_SVC_VERSION;
g_Helpers.pfnCallComplete = callComplete;
pTable->pHelpers = &g_Helpers;
return VBoxHGCMSvcLoad(pTable);
}
static void testSetMode(void)
{
struct VBOXHGCMSVCPARM parms[2];
VBOXHGCMSVCFNTABLE table;
uint32_t u32Mode;
int rc;
RTTestISub("Testing HOST_FN_SET_MODE");
rc = setupTable(&table);
RTTESTI_CHECK_MSG_RETV(RT_SUCCESS(rc), ("rc=%Rrc\n", rc));
/* Reset global variable which doesn't reset itself. */
parms[0].setUInt32(VBOX_SHARED_CLIPBOARD_MODE_OFF);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE,
1, parms);
RTTESTI_CHECK_RC_OK(rc);
u32Mode = TestClipSvcGetMode();
RTTESTI_CHECK_MSG(u32Mode == VBOX_SHARED_CLIPBOARD_MODE_OFF,
("u32Mode=%u\n", (unsigned) u32Mode));
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE,
0, parms);
RTTESTI_CHECK_RC(rc, VERR_INVALID_PARAMETER);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE,
2, parms);
RTTESTI_CHECK_RC(rc, VERR_INVALID_PARAMETER);
parms[0].setUInt64(99);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE,
1, parms);
RTTESTI_CHECK_RC(rc, VERR_INVALID_PARAMETER);
parms[0].setUInt32(VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE,
1, parms);
RTTESTI_CHECK_RC_OK(rc);
u32Mode = TestClipSvcGetMode();
RTTESTI_CHECK_MSG(u32Mode == VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST,
("u32Mode=%u\n", (unsigned) u32Mode));
parms[0].setUInt32(99);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE,
1, parms);
RTTESTI_CHECK_RC_OK(rc);
u32Mode = TestClipSvcGetMode();
RTTESTI_CHECK_MSG(u32Mode == VBOX_SHARED_CLIPBOARD_MODE_OFF,
("u32Mode=%u\n", (unsigned) u32Mode));
table.pfnUnload(NULL);
}
static void testGetHostMsg(void)
{
struct VBOXHGCMSVCPARM parms[2];
VBOXHGCMSVCFNTABLE table;
VBOXHGCMCALLHANDLE_TYPEDEF call;
int rc;
RTTestISub("Setting up VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG test");
rc = setupTable(&table);
RTTESTI_CHECK_MSG_RETV(RT_SUCCESS(rc), ("rc=%Rrc\n", rc));
/* Unless we are bidirectional the host message requests will be dropped. */
parms[0].setUInt32(VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE,
1, parms);
RTTESTI_CHECK_RC_OK(rc);
RTTestISub("Testing FN_GET_HOST_MSG, one format, waiting guest call.");
RT_ZERO(g_Client);
parms[0].setUInt32(0);
parms[1].setUInt32(0);
call.rc = VERR_TRY_AGAIN;
table.pfnCall(NULL, &call, 1 /* clientId */, &g_Client, VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG,
2, parms);
RTTESTI_CHECK_RC(call.rc, VERR_TRY_AGAIN); /* This should get updated only when the guest call completes. */
vboxSvcClipboardReportMsg (&g_Client, VBOX_SHARED_CLIPBOARD_HOST_MSG_READ_DATA,
VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT);
RTTESTI_CHECK(parms[0].u.uint32 == VBOX_SHARED_CLIPBOARD_HOST_MSG_READ_DATA);
RTTESTI_CHECK(parms[1].u.uint32 == VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT);
RTTESTI_CHECK_RC_OK(call.rc);
call.rc = VERR_TRY_AGAIN;
table.pfnCall(NULL, &call, 1 /* clientId */, &g_Client, VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG,
2, parms);
RTTESTI_CHECK_RC(call.rc, VERR_TRY_AGAIN); /* This call should not complete yet. */
RTTestISub("Testing FN_GET_HOST_MSG, one format, no waiting guest calls.");
RT_ZERO(g_Client);
vboxSvcClipboardReportMsg (&g_Client, VBOX_SHARED_CLIPBOARD_HOST_MSG_READ_DATA,
VBOX_SHARED_CLIPBOARD_FMT_HTML);
parms[0].setUInt32(0);
parms[1].setUInt32(0);
call.rc = VERR_TRY_AGAIN;
table.pfnCall(NULL, &call, 1 /* clientId */, &g_Client, VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG,
2, parms);
RTTESTI_CHECK(parms[0].u.uint32 == VBOX_SHARED_CLIPBOARD_HOST_MSG_READ_DATA);
RTTESTI_CHECK(parms[1].u.uint32 == VBOX_SHARED_CLIPBOARD_FMT_HTML);
RTTESTI_CHECK_RC_OK(call.rc);
call.rc = VERR_TRY_AGAIN;
table.pfnCall(NULL, &call, 1 /* clientId */, &g_Client, VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG,
2, parms);
RTTESTI_CHECK_RC(call.rc, VERR_TRY_AGAIN); /* This call should not complete yet. */
RTTestISub("Testing FN_GET_HOST_MSG, two formats, waiting guest call.");
RT_ZERO(g_Client);
parms[0].setUInt32(0);
parms[1].setUInt32(0);
call.rc = VERR_TRY_AGAIN;
table.pfnCall(NULL, &call, 1 /* clientId */, &g_Client, VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG,
2, parms);
RTTESTI_CHECK_RC(call.rc, VERR_TRY_AGAIN); /* This should get updated only when the guest call completes. */
vboxSvcClipboardReportMsg (&g_Client, VBOX_SHARED_CLIPBOARD_HOST_MSG_READ_DATA,
VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT | VBOX_SHARED_CLIPBOARD_FMT_HTML);
RTTESTI_CHECK(parms[0].u.uint32 == VBOX_SHARED_CLIPBOARD_HOST_MSG_READ_DATA);
RTTESTI_CHECK(parms[1].u.uint32 == VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT);
RTTESTI_CHECK_RC_OK(call.rc);
call.rc = VERR_TRY_AGAIN;
table.pfnCall(NULL, &call, 1 /* clientId */, &g_Client, VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG,
2, parms);
RTTESTI_CHECK(parms[0].u.uint32 == VBOX_SHARED_CLIPBOARD_HOST_MSG_READ_DATA);
RTTESTI_CHECK(parms[1].u.uint32 == VBOX_SHARED_CLIPBOARD_FMT_HTML);
RTTESTI_CHECK_RC_OK(call.rc);
call.rc = VERR_TRY_AGAIN;
table.pfnCall(NULL, &call, 1 /* clientId */, &g_Client, VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG,
2, parms);
RTTESTI_CHECK_RC(call.rc, VERR_TRY_AGAIN); /* This call should not complete yet. */
RTTestISub("Testing FN_GET_HOST_MSG, two formats, no waiting guest calls.");
RT_ZERO(g_Client);
vboxSvcClipboardReportMsg (&g_Client, VBOX_SHARED_CLIPBOARD_HOST_MSG_READ_DATA,
VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT | VBOX_SHARED_CLIPBOARD_FMT_HTML);
parms[0].setUInt32(0);
parms[1].setUInt32(0);
call.rc = VERR_TRY_AGAIN;
table.pfnCall(NULL, &call, 1 /* clientId */, &g_Client, VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG,
2, parms);
RTTESTI_CHECK(parms[0].u.uint32 == VBOX_SHARED_CLIPBOARD_HOST_MSG_READ_DATA);
RTTESTI_CHECK(parms[1].u.uint32 == VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT);
RTTESTI_CHECK_RC_OK(call.rc);
call.rc = VERR_TRY_AGAIN;
table.pfnCall(NULL, &call, 1 /* clientId */, &g_Client, VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG,
2, parms);
RTTESTI_CHECK(parms[0].u.uint32 == VBOX_SHARED_CLIPBOARD_HOST_MSG_READ_DATA);
RTTESTI_CHECK(parms[1].u.uint32 == VBOX_SHARED_CLIPBOARD_FMT_HTML);
RTTESTI_CHECK_RC_OK(call.rc);
call.rc = VERR_TRY_AGAIN;
table.pfnCall(NULL, &call, 1 /* clientId */, &g_Client, VBOX_SHARED_CLIPBOARD_FN_GET_HOST_MSG,
2, parms);
RTTESTI_CHECK_RC(call.rc, VERR_TRY_AGAIN); /* This call should not complete yet. */
table.pfnUnload(NULL);
}
static void testSetHeadless(void)
{
struct VBOXHGCMSVCPARM parms[2];
VBOXHGCMSVCFNTABLE table;
bool fHeadless;
int rc;
RTTestISub("Testing HOST_FN_SET_HEADLESS");
rc = setupTable(&table);
RTTESTI_CHECK_MSG_RETV(RT_SUCCESS(rc), ("rc=%Rrc\n", rc));
/* Reset global variable which doesn't reset itself. */
parms[0].setUInt32(false);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_HEADLESS,
1, parms);
RTTESTI_CHECK_RC_OK(rc);
fHeadless = vboxSvcClipboardGetHeadless();
RTTESTI_CHECK_MSG(fHeadless == false, ("fHeadless=%RTbool\n", fHeadless));
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_HEADLESS,
0, parms);
RTTESTI_CHECK_RC(rc, VERR_INVALID_PARAMETER);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_HEADLESS,
2, parms);
RTTESTI_CHECK_RC(rc, VERR_INVALID_PARAMETER);
parms[0].setUInt64(99);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_HEADLESS,
1, parms);
RTTESTI_CHECK_RC(rc, VERR_INVALID_PARAMETER);
parms[0].setUInt32(true);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_HEADLESS,
1, parms);
RTTESTI_CHECK_RC_OK(rc);
fHeadless = vboxSvcClipboardGetHeadless();
RTTESTI_CHECK_MSG(fHeadless == true, ("fHeadless=%RTbool\n", fHeadless));
parms[0].setUInt32(99);
rc = table.pfnHostCall(NULL, VBOX_SHARED_CLIPBOARD_HOST_FN_SET_HEADLESS,
1, parms);
RTTESTI_CHECK_RC_OK(rc);
fHeadless = vboxSvcClipboardGetHeadless();
RTTESTI_CHECK_MSG(fHeadless == true, ("fHeadless=%RTbool\n", fHeadless));
table.pfnUnload(NULL);
}
static void testHostCall(void)
{
testSetMode();
testSetHeadless();
}
int main(int argc, char *argv[])
{
/*
* Init the runtime, test and say hello.
*/
const char *pcszExecName;
NOREF(argc);
pcszExecName = strrchr(argv[0], '/');
pcszExecName = pcszExecName ? pcszExecName + 1 : argv[0];
RTTEST hTest;
RTEXITCODE rcExit = RTTestInitAndCreate(pcszExecName, &hTest);
if (rcExit != RTEXITCODE_SUCCESS)
return rcExit;
RTTestBanner(hTest);
/*
* Run the tests.
*/
testHostCall();
testGetHostMsg();
/*
* Summary
*/
return RTTestSummaryAndDestroy(hTest);
}
int vboxClipboardInit() { return VINF_SUCCESS; }
void vboxClipboardDestroy() {}
void vboxClipboardDisconnect(_VBOXCLIPBOARDCLIENTDATA*) { AssertFailed(); }
int vboxClipboardConnect(_VBOXCLIPBOARDCLIENTDATA*, bool)
{ AssertFailed(); return VERR_WRONG_ORDER; }
void vboxClipboardFormatAnnounce(_VBOXCLIPBOARDCLIENTDATA*, unsigned int)
{ AssertFailed(); }
int vboxClipboardReadData(_VBOXCLIPBOARDCLIENTDATA*, unsigned int, void*, unsigned int, unsigned int*)
{ AssertFailed(); return VERR_WRONG_ORDER; }
void vboxClipboardWriteData(_VBOXCLIPBOARDCLIENTDATA*, void*, unsigned int, unsigned int) { AssertFailed(); }
int vboxClipboardSync(_VBOXCLIPBOARDCLIENTDATA*)
{ AssertFailed(); return VERR_WRONG_ORDER; }
| 5,805 |
2,059 | #include <Python.h>
#include "graph/proxy/base_datum.h"
#include "canvas/connection/connection.h"
#include "viewport/render/instance.h"
#include "viewport/view.h"
#include "viewport/scene.h"
#include "graph/datum.h"
#include "fab/fab.h"
BaseDatumProxy::BaseDatumProxy(
Datum* d, QObject* parent, ViewportScene* scene, bool sub)
: QObject(parent), datum(d), sub(sub),
should_render(d->getType() == fab::ShapeType)
{
scene->installDatum(this);
}
BaseDatumProxy::~BaseDatumProxy()
{
// I don't understand why this is necessary, but doing the deletions
// directly from the QHash causes crashes.
QList<Connection*> cs;
for (auto c : connections)
cs.push_back(c);
for (auto c : cs)
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void BaseDatumProxy::addViewport(ViewportView* view)
{
if (should_render)
{
auto r = new RenderInstance(this, view, sub);
connect(view, &QObject::destroyed,
r, &RenderInstance::makeOrphan);
connect(this, &BaseDatumProxy::datumChanged,
r, &RenderInstance::datumChanged);
}
}
| 462 |
5,169 | {
"name": "MFStoryboardPushSegue",
"version": "1.0",
"license": "BSD",
"summary": "UIStoryboardPushSegue for use outside a navigation controller",
"homepage": "https://github.com/MentallyFriendly/MFStoryboardPushSegue",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/MentallyFriendly/MFStoryboardPushSegue.git",
"tag": "1.0"
},
"requires_arc": true,
"platforms": {
"ios": "7.0"
},
"source_files": "*.{h,m}",
"frameworks": [
"UIKit",
"QuartzCore"
]
}
| 224 |
1,506 | <reponame>termim/geocoder<gh_stars>1000+
#!/usr/bin/python
# coding: utf8
from __future__ import absolute_import
import logging
from geocoder.base import OneResult, MultipleResultsQuery
class MaxmindResults(OneResult):
def __init__(self, json_content):
# create safe shortcuts
self._location = json_content.get('location', {})
self._traits = json_content.get('traits', {})
# proceed with super.__init__
super(MaxmindResults, self).__init__(json_content)
@property
def lat(self):
return self._location.get('latitude')
@property
def lng(self):
return self._location.get('longitude')
@property
def timezone(self):
return self._location.get('time_zone')
@property
def metro_code(self):
return self._location.get('metro_code')
@property
def domain(self):
return self._traits.get('domain')
@property
def isp(self):
return self._traits.get('isp')
@property
def organization(self):
return self._traits.get('organization')
@property
def ip(self):
return self._traits.get('ip_address')
@property
def postal(self):
return self.raw.get('postal', {}).get('code')
@property
def city(self):
return self.raw.get('city', {}).get('names', {}).get('en')
@property
def state(self):
return self.raw.get('subdivision', {}).get('names', {}).get('en')
@property
def country(self):
return self.raw.get('country', {}).get('names', {}).get('en')
@property
def country_code(self):
return self.raw.get('country', {}).get('iso_code')
@property
def continent(self):
return self.raw.get('continent', {}).get('names', {}).get('en')
@property
def continent_code(self):
return self.raw.get('continent', {}).get('code')
@property
def address(self):
if self.city:
return u'{0}, {1}, {2}'.format(self.city, self.state, self.country)
elif self.state:
return u'{0}, {1}'.format(self.state, self.country)
elif self.country:
return u'{0}'.format(self.country)
else:
return u''
class MaxmindQuery(MultipleResultsQuery):
"""
MaxMind's GeoIP2
=======================
MaxMind's GeoIP2 products enable you to identify the location,
organization, connection speed, and user type of your Internet
visitors. The GeoIP2 databases are among the most popular and
accurate IP geolocation databases available.
API Reference
-------------
https://www.maxmind.com/en/geolocation_landing
"""
provider = 'maxmind'
method = 'geocode'
_URL = 'https://www.maxmind.com/geoip/v2.0/city_isp_org/{0}'
_RESULT_CLASS = MaxmindResults
_KEY_MANDATORY = False
def _build_headers(self, provider_key, **kwargs):
return {
'Referer': 'https://www.maxmind.com/en/geoip_demo',
'Host': 'www.maxmind.com',
}
def _build_params(self, location, provider_key, **kwargs):
return {'demo': 1}
def _before_initialize(self, location, **kwargs):
location = location or 'me'
self.url = self._URL.format(location)
def _catch_errors(self, json_response):
error = json_response.get('error')
if error:
self.error = json_response.get('code')
return self.error
def _adapt_results(self, json_response):
return [json_response]
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
g = MaxmindQuery('8.8.8.8')
g.debug()
| 1,507 |
806 | package org2.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org2.apache.commons.io.IOCase;
public class SuffixFileFilter extends AbstractFileFilter implements Serializable {
private final IOCase caseSensitivity;
private final String[] suffixes;
public SuffixFileFilter(String suffix) {
this(suffix, IOCase.SENSITIVE);
}
public SuffixFileFilter(String suffix, IOCase caseSensitivity) {
if (suffix == null) {
throw new IllegalArgumentException("The suffix must not be null");
}
this.suffixes = new String[]{suffix};
if (caseSensitivity == null) {
caseSensitivity = IOCase.SENSITIVE;
}
this.caseSensitivity = caseSensitivity;
}
public SuffixFileFilter(String[] suffixes) {
this(suffixes, IOCase.SENSITIVE);
}
public SuffixFileFilter(String[] suffixes, IOCase caseSensitivity) {
if (suffixes == null) {
throw new IllegalArgumentException("The array of suffixes must not be null");
}
this.suffixes = new String[suffixes.length];
System.arraycopy(suffixes, 0, this.suffixes, 0, suffixes.length);
if (caseSensitivity == null) {
caseSensitivity = IOCase.SENSITIVE;
}
this.caseSensitivity = caseSensitivity;
}
public SuffixFileFilter(List<String> suffixes) {
this((List) suffixes, IOCase.SENSITIVE);
}
public SuffixFileFilter(List<String> suffixes, IOCase caseSensitivity) {
if (suffixes == null) {
throw new IllegalArgumentException("The list of suffixes must not be null");
}
this.suffixes = (String[]) suffixes.toArray(new String[suffixes.size()]);
if (caseSensitivity == null) {
caseSensitivity = IOCase.SENSITIVE;
}
this.caseSensitivity = caseSensitivity;
}
public boolean accept(File file) {
String name = file.getName();
for (String suffix : this.suffixes) {
if (this.caseSensitivity.checkEndsWith(name, suffix)) {
return true;
}
}
return false;
}
public boolean accept(File file, String name) {
for (String suffix : this.suffixes) {
if (this.caseSensitivity.checkEndsWith(name, suffix)) {
return true;
}
}
return false;
}
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(super.toString());
buffer.append("(");
if (this.suffixes != null) {
for (int i = 0; i < this.suffixes.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(this.suffixes[i]);
}
}
buffer.append(")");
return buffer.toString();
}
}
| 1,297 |
343 | <gh_stars>100-1000
// 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.
#ifndef BASE_TRACE_EVENT_CFI_BACKTRACE_ANDROID_H_
#define BASE_TRACE_EVENT_CFI_BACKTRACE_ANDROID_H_
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/base_export.h"
#include "base/debug/debugging_buildflags.h"
#include "base/files/memory_mapped_file.h"
#include "base/gtest_prod_util.h"
#include "base/threading/thread_local_storage.h"
namespace base {
namespace trace_event {
// This class is used to unwind stack frames in the current thread. The unwind
// information (dwarf debug info) is stripped from the chrome binary and we do
// not build with exception tables (ARM EHABI) in release builds. So, we use a
// custom unwind table which is generated and added to specific android builds,
// when add_unwind_tables_in_apk build option is specified. This unwind table
// contains information for unwinding stack frames when the functions calls are
// from lib[mono]chrome.so. The file is added as an asset to the apk and the
// table is used to unwind stack frames for profiling. This class implements
// methods to read and parse the unwind table and unwind stack frames using this
// data.
class BASE_EXPORT CFIBacktraceAndroid {
public:
// Creates and initializes by memory mapping the unwind tables from apk assets
// on first call.
static CFIBacktraceAndroid* GetInitializedInstance();
// Returns true if the given program counter |pc| is mapped in chrome library.
static bool is_chrome_address(uintptr_t pc) {
return pc >= executable_start_addr() && pc < executable_end_addr();
}
// Returns the start and end address of the current library.
static uintptr_t executable_start_addr();
static uintptr_t executable_end_addr();
// Returns true if stack unwinding is possible using CFI unwind tables in apk.
// There is no need to check this before each unwind call. Will always return
// the same value based on CFI tables being present in the binary.
bool can_unwind_stack_frames() const { return can_unwind_stack_frames_; }
// Returns the program counters by unwinding stack in the current thread in
// order of latest call frame first. Unwinding works only if
// can_unwind_stack_frames() returns true. This function allocates memory from
// heap for cache on the first call of the calling thread, unless
// AllocateCacheForCurrentThread() is called from the thread. For each stack
// frame, this method searches through the unwind table mapped in memory to
// find the unwind information for function and walks the stack to find all
// the return address. This only works until the last function call from the
// chrome.so. We do not have unwind information to unwind beyond any frame
// outside of chrome.so. Calls to Unwind() are thread safe and lock free, once
// Initialize() returns success.
size_t Unwind(const void** out_trace, size_t max_depth);
// Same as above function, but starts from a given program counter |pc| and
// stack pointer |sp|. This can be from current thread or any other thread.
// But the caller must make sure that the thread's stack segment is not racy
// to read.
size_t Unwind(uintptr_t pc,
uintptr_t sp,
const void** out_trace,
size_t max_depth);
// Allocates memory for CFI cache for the current thread so that Unwind()
// calls are safe for signal handlers.
void AllocateCacheForCurrentThread();
// The CFI information that correspond to an instruction.
struct CFIRow {
bool operator==(const CFIBacktraceAndroid::CFIRow& o) const {
return cfa_offset == o.cfa_offset && ra_offset == o.ra_offset;
}
// The offset of the call frame address of previous function from the
// current stack pointer. Rule for unwinding SP: SP_prev = SP_cur +
// cfa_offset.
uint16_t cfa_offset = 0;
// The offset of location of return address from the previous call frame
// address. Rule for unwinding PC: PC_prev = * (SP_prev - ra_offset).
uint16_t ra_offset = 0;
};
// Finds the CFI row for the given |func_addr| in terms of offset from
// the start of the current binary. Concurrent calls are thread safe.
bool FindCFIRowForPC(uintptr_t func_addr, CFIRow* out);
private:
FRIEND_TEST_ALL_PREFIXES(CFIBacktraceAndroidTest, TestCFICache);
FRIEND_TEST_ALL_PREFIXES(CFIBacktraceAndroidTest, TestFindCFIRow);
FRIEND_TEST_ALL_PREFIXES(CFIBacktraceAndroidTest, TestUnwinding);
// A simple cache that stores entries in table using prime modulo hashing.
// This cache with 500 entries already gives us 95% hit rate, and fits in a
// single system page (usually 4KiB). Using a thread local cache for each
// thread gives us 30% improvements on performance of heap profiling.
class CFICache {
public:
// Add new item to the cache. It replaces an existing item with same hash.
// Constant time operation.
void Add(uintptr_t address, CFIRow cfi);
// Finds the given address and fills |cfi| with the info for the address.
// returns true if found, otherwise false. Assumes |address| is never 0.
bool Find(uintptr_t address, CFIRow* cfi);
private:
FRIEND_TEST_ALL_PREFIXES(CFIBacktraceAndroidTest, TestCFICache);
// Size is the highest prime which fits the cache in a single system page,
// usually 4KiB. A prime is chosen to make sure addresses are hashed evenly.
static const int kLimit = 509;
struct AddrAndCFI {
uintptr_t address;
CFIRow cfi;
};
AddrAndCFI cache_[kLimit] = {};
};
static_assert(sizeof(CFIBacktraceAndroid::CFICache) < 4096,
"The cache does not fit in a single page.");
CFIBacktraceAndroid();
~CFIBacktraceAndroid();
// Initializes unwind tables using the CFI asset file in the apk if present.
// Also stores the limits of mapped region of the lib[mono]chrome.so binary,
// since the unwind is only feasible for addresses within the .so file. Once
// initialized, the memory map of the unwind table is never cleared since we
// cannot guarantee that all the threads are done using the memory map when
// heap profiling is turned off. But since we keep the memory map is clean,
// the system can choose to evict the unused pages when needed. This would
// still reduce the total amount of address space available in process.
void Initialize();
// Finds the UNW_INDEX and UNW_DATA tables in from the CFI file memory map.
void ParseCFITables();
CFICache* GetThreadLocalCFICache();
// The start address of the memory mapped unwind table asset file. Unique ptr
// because it is replaced in tests.
std::unique_ptr<MemoryMappedFile> cfi_mmap_;
// The UNW_INDEX table: Start address of the function address column. The
// memory segment corresponding to this column is treated as an array of
// uintptr_t.
const uintptr_t* unw_index_function_col_ = nullptr;
// The UNW_INDEX table: Start address of the index column. The memory segment
// corresponding to this column is treated as an array of uint16_t.
const uint16_t* unw_index_indices_col_ = nullptr;
// The number of rows in UNW_INDEX table.
size_t unw_index_row_count_ = 0;
// The start address of UNW_DATA table.
const uint16_t* unw_data_start_addr_ = nullptr;
bool can_unwind_stack_frames_ = false;
ThreadLocalStorage::Slot thread_local_cfi_cache_;
};
} // namespace trace_event
} // namespace base
#endif // BASE_TRACE_EVENT_CFI_BACKTRACE_ANDROID_H_
| 2,314 |
1,500 | #include "napi.h"
using namespace Napi;
// Wrappers for testing Object::Get() for global Objects
Value GetPropertyWithCppStyleStringAsKey(const CallbackInfo& info);
Value GetPropertyWithCStyleStringAsKey(const CallbackInfo& info);
Value GetPropertyWithInt32AsKey(const CallbackInfo& info);
Value GetPropertyWithNapiValueAsKey(const CallbackInfo& info);
void CreateMockTestObject(const CallbackInfo& info);
// Wrapper for testing Object::Set() for global Objects
void SetPropertyWithCStyleStringAsKey(const CallbackInfo& info);
void SetPropertyWithCppStyleStringAsKey(const CallbackInfo& info);
void SetPropertyWithInt32AsKey(const CallbackInfo& info);
void SetPropertyWithNapiValueAsKey(const CallbackInfo& info);
Value HasPropertyWithCStyleStringAsKey(const CallbackInfo& info);
Value HasPropertyWithCppStyleStringAsKey(const CallbackInfo& info);
Value HasPropertyWithNapiValueAsKey(const CallbackInfo& info);
Value DeletePropertyWithCStyleStringAsKey(const CallbackInfo& info);
Value DeletePropertyWithCppStyleStringAsKey(const CallbackInfo& info);
Value DeletePropertyWithInt32AsKey(const CallbackInfo& info);
Value DeletePropertyWithNapiValueAsKey(const CallbackInfo& info);
Object InitGlobalObject(Env env) {
Object exports = Object::New(env);
exports["getPropertyWithInt32"] =
Function::New(env, GetPropertyWithInt32AsKey);
exports["getPropertyWithNapiValue"] =
Function::New(env, GetPropertyWithNapiValueAsKey);
exports["getPropertyWithCppString"] =
Function::New(env, GetPropertyWithCppStyleStringAsKey);
exports["getPropertyWithCString"] =
Function::New(env, GetPropertyWithCStyleStringAsKey);
exports["createMockTestObject"] = Function::New(env, CreateMockTestObject);
exports["setPropertyWithCStyleString"] =
Function::New(env, SetPropertyWithCStyleStringAsKey);
exports["setPropertyWithCppStyleString"] =
Function::New(env, SetPropertyWithCppStyleStringAsKey);
exports["setPropertyWithNapiValue"] =
Function::New(env, SetPropertyWithNapiValueAsKey);
exports["setPropertyWithInt32"] =
Function::New(env, SetPropertyWithInt32AsKey);
exports["hasPropertyWithCStyleString"] =
Function::New(env, HasPropertyWithCStyleStringAsKey);
exports["hasPropertyWithCppStyleString"] =
Function::New(env, HasPropertyWithCppStyleStringAsKey);
exports["hasPropertyWithNapiValue"] =
Function::New(env, HasPropertyWithNapiValueAsKey);
exports["deletePropertyWithCStyleString"] =
Function::New(env, DeletePropertyWithCStyleStringAsKey);
exports["deletePropertyWithCppStyleString"] =
Function::New(env, DeletePropertyWithCppStyleStringAsKey);
exports["deletePropertyWithInt32"] =
Function::New(env, DeletePropertyWithInt32AsKey);
exports["deletePropertyWithNapiValue"] =
Function::New(env, DeletePropertyWithNapiValueAsKey);
return exports;
}
| 891 |
882 | package water.nbhm;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import sun.misc.Unsafe;
/*
* Written by <NAME> and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/**
* A multi-threaded bit-vector set, implemented as an array of primitive
* {@code longs}. All operations are non-blocking and multi-threaded safe.
* {@link #contains(int)} calls are roughly the same speed as a {load, mask}
* sequence. {@link #add(int)} and {@link #remove(int)} calls are a tad more
* expensive than a {load, mask, store} sequence because they must use a CAS.
* The bit-vector is auto-sizing.
*
* <p><em>General note of caution:</em> The Set API allows the use of {@link Integer}
* with silent autoboxing - which can be very expensive if many calls are
* being made. Since autoboxing is silent you may not be aware that this is
* going on. The built-in API takes lower-case {@code ints} and is much more
* efficient.
*
* <p>Space: space is used in proportion to the largest element, as opposed to
* the number of elements (as is the case with hash-table based Set
* implementations). Space is approximately (largest_element/8 + 64) bytes.
*
* The implementation is a simple bit-vector using CAS for update.
*
* @since 1.5
* @author <NAME>
*/
public class NonBlockingSetInt extends AbstractSet<Integer> implements Serializable {
private static final long serialVersionUID = 1234123412341234123L;
private static final Unsafe _unsafe = UtilUnsafe.getUnsafe();
// --- Bits to allow atomic update of the NBSI
private static final long _nbsi_offset;
static { // <clinit>
Field f = null;
try {
f = NonBlockingSetInt.class.getDeclaredField("_nbsi");
} catch( java.lang.NoSuchFieldException e ) {
}
_nbsi_offset = _unsafe.objectFieldOffset(f);
}
private final boolean CAS_nbsi( NBSI old, NBSI nnn ) {
return _unsafe.compareAndSwapObject(this, _nbsi_offset, old, nnn );
}
// The actual Set of Joy, which changes during a resize event. The
// Only Field for this class, so I can atomically change the entire
// set implementation with a single CAS.
private transient NBSI _nbsi;
/** Create a new empty bit-vector */
public NonBlockingSetInt( ) {
_nbsi = new NBSI(63, new ConcurrentAutoTable(), this); // The initial 1-word set
}
/**
* Add {@code i} to the set. Uppercase {@link Integer} version of add,
* requires auto-unboxing. When possible use the {@code int} version of
* {@link #add(int)} for efficiency.
* @throws IllegalArgumentException if i is negative.
* @return <tt>true</tt> if i was added to the set.
*/
public boolean add ( final Integer i ) {
return add(i.intValue());
}
/**
* Test if {@code o} is in the set. This is the uppercase {@link Integer}
* version of contains, requires a type-check and auto-unboxing. When
* possible use the {@code int} version of {@link #contains(int)} for
* efficiency.
* @return <tt>true</tt> if i was in the set.
*/
public boolean contains( final Object o ) {
return o instanceof Integer ? contains(((Integer)o).intValue()) : false;
}
/**
* Remove {@code o} from the set. This is the uppercase {@link Integer}
* version of remove, requires a type-check and auto-unboxing. When
* possible use the {@code int} version of {@link #remove(int)} for
* efficiency.
* @return <tt>true</tt> if i was removed to the set.
*/
public boolean remove( final Object o ) {
return o instanceof Integer ? remove (((Integer)o).intValue()) : false;
}
/**
* Add {@code i} to the set. This is the lower-case '{@code int}' version
* of {@link #add} - no autoboxing. Negative values throw
* IllegalArgumentException.
* @throws IllegalArgumentException if i is negative.
* @return <tt>true</tt> if i was added to the set.
*/
public boolean add( final int i ) {
if( i < 0 ) throw new IllegalArgumentException(""+i);
return _nbsi.add(i);
}
/**
* Test if {@code i} is in the set. This is the lower-case '{@code int}'
* version of {@link #contains} - no autoboxing.
* @return <tt>true</tt> if i was int the set.
*/
public boolean contains( final int i ) { return i<0 ? false : _nbsi.contains(i); }
/**
* Remove {@code i} from the set. This is the fast lower-case '{@code int}'
* version of {@link #remove} - no autoboxing.
* @return <tt>true</tt> if i was added to the set.
*/
public boolean remove ( final int i ) { return i<0 ? false : _nbsi.remove (i); }
/**
* Current count of elements in the set. Due to concurrent racing updates,
* the size is only ever approximate. Updates due to the calling thread are
* immediately visible to calling thread.
* @return count of elements.
*/
public int size ( ) { return _nbsi.size( ); }
/** Approx largest element in set; at least as big (but max might be smaller). */
public int length() { return _nbsi._bits.length<<6; }
/** Empty the bitvector. */
public void clear ( ) {
NBSI cleared = new NBSI(63, new ConcurrentAutoTable(), this); // An empty initial NBSI
while( !CAS_nbsi( _nbsi, cleared ) ) // Spin until clear works
;
}
/** Verbose printout of internal structure for debugging. */
public void print() { _nbsi.print(0); }
/**
* Standard Java {@link Iterator}. Not very efficient because it
* auto-boxes the returned values.
*/
public Iterator<Integer> iterator( ) { return new iter(); }
private class iter implements Iterator<Integer> {
NBSI _nbsi2;
int _idx = -1;
int _prev = -1;
iter() { _nbsi2 = _nbsi; advance(); }
public boolean hasNext() { return _idx != -2; }
private void advance() {
while( true ) {
_idx++; // Next index
while( (_idx>>6) >= _nbsi2._bits.length ) { // Index out of range?
if( _nbsi2._new == null ) { // New table?
_idx = -2; // No, so must be all done
return; //
}
_nbsi2 = _nbsi2._new; // Carry on, in the new table
}
if( _nbsi2.contains(_idx) ) return;
}
}
public Integer next() {
if( _idx == -1 ) throw new NoSuchElementException();
_prev = _idx;
advance();
return _prev;
}
public void remove() {
if( _prev == -1 ) throw new IllegalStateException();
_nbsi2.remove(_prev);
_prev = -1;
}
}
// --- writeObject -------------------------------------------------------
// Write a NBSI to a stream
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
s.defaultWriteObject(); // Nothing to write
final NBSI nbsi = _nbsi; // The One Field is transient
final int len = _nbsi._bits.length<<6;
s.writeInt(len); // Write max element
for( int i=0; i<len; i++ )
s.writeBoolean( _nbsi.contains(i) );
}
// --- readObject --------------------------------------------------------
// Read a CHM from a stream
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject(); // Read nothing
final int len = s.readInt(); // Read max element
_nbsi = new NBSI(len, new ConcurrentAutoTable(), this);
for( int i=0; i<len; i++ ) // Read all bits
if( s.readBoolean() )
_nbsi.add(i);
}
// --- NBSI ----------------------------------------------------------------
private static final class NBSI {
// Back pointer to the parent wrapper; sorta like make the class non-static
private transient final NonBlockingSetInt _non_blocking_set_int;
// Used to count elements: a high-performance counter.
private transient final ConcurrentAutoTable _size;
// The Bits
private final long _bits[];
// --- Bits to allow Unsafe access to arrays
private static final int _Lbase = _unsafe.arrayBaseOffset(long[].class);
private static final int _Lscale = _unsafe.arrayIndexScale(long[].class);
private static long rawIndex(final long[] ary, final int idx) {
assert idx >= 0 && idx < ary.length;
return _Lbase + idx * _Lscale;
}
private final boolean CAS( int idx, long old, long nnn ) {
return _unsafe.compareAndSwapLong( _bits, rawIndex(_bits, idx), old, nnn );
}
// --- Resize
// The New Table, only set once to non-zero during a resize.
// Must be atomically set.
private NBSI _new;
private static final long _new_offset;
static { // <clinit>
Field f = null;
try {
f = NBSI.class.getDeclaredField("_new");
} catch( java.lang.NoSuchFieldException e ) {
}
_new_offset = _unsafe.objectFieldOffset(f);
}
private final boolean CAS_new( NBSI nnn ) {
return _unsafe.compareAndSwapObject(this, _new_offset, null, nnn );
}
private transient final AtomicInteger _copyIdx; // Used to count bits started copying
private transient final AtomicInteger _copyDone; // Used to count words copied in a resize operation
private transient final int _sum_bits_length; // Sum of all nested _bits.lengths
private static final long mask( int i ) { return 1L<<(i&63); }
// I need 1 free bit out of 64 to allow for resize. I do this by stealing
// the high order bit - but then I need to do something with adding element
// number 63 (and friends). I could use a mod63 function but it's more
// efficient to handle the mod-64 case as an exception.
//
// Every 64th bit is put in it's own recursive bitvector. If the low 6 bits
// are all set, we shift them off and recursively operate on the _nbsi64 set.
private final NBSI _nbsi64;
private NBSI( int max_elem, ConcurrentAutoTable ctr, NonBlockingSetInt nonb ) {
super();
_non_blocking_set_int = nonb;
_size = ctr;
_copyIdx = ctr == null ? null : new AtomicInteger();
_copyDone = ctr == null ? null : new AtomicInteger();
// The main array of bits
_bits = new long[(int)(((long)max_elem+63)>>>6)];
// Every 64th bit is moved off to it's own subarray, so that the
// sign-bit is free for other purposes
_nbsi64 = ((max_elem+1)>>>6) == 0 ? null : new NBSI((max_elem+1)>>>6, null, null);
_sum_bits_length = _bits.length + (_nbsi64==null ? 0 : _nbsi64._sum_bits_length);
}
// Lower-case 'int' versions - no autoboxing, very fast.
// 'i' is known positive.
public boolean add( final int i ) {
// Check for out-of-range for the current size bit vector.
// If so we need to grow the bit vector.
if( (i>>6) >= _bits.length )
return install_larger_new_bits(i). // Install larger pile-o-bits (duh)
help_copy().add(i); // Finally, add to the new table
// Handle every 64th bit via using a nested array
NBSI nbsi = this; // The bit array being added into
int j = i; // The bit index being added
while( (j&63) == 63 ) { // Bit 64? (low 6 bits are all set)
nbsi = nbsi._nbsi64; // Recurse
j = j>>6; // Strip off low 6 bits (all set)
}
final long mask = mask(j);
long old;
do {
old = nbsi._bits[j>>6]; // Read old bits
if( old < 0 ) // Not mutable?
// Not mutable: finish copy of word, and retry on copied word
return help_copy_impl(i).help_copy().add(i);
if( (old & mask) != 0 ) return false; // Bit is already set?
} while( !nbsi.CAS( j>>6, old, old | mask ) );
_size.add(1);
return true;
}
public boolean remove( final int i ) {
if( (i>>6) >= _bits.length ) // Out of bounds? Not in this array!
return _new==null ? false : help_copy().remove(i);
// Handle every 64th bit via using a nested array
NBSI nbsi = this; // The bit array being added into
int j = i; // The bit index being added
while( (j&63) == 63 ) { // Bit 64? (low 6 bits are all set)
nbsi = nbsi._nbsi64; // Recurse
j = j>>6; // Strip off low 6 bits (all set)
}
final long mask = mask(j);
long old;
do {
old = nbsi._bits[j>>6]; // Read old bits
if( old < 0 ) // Not mutable?
// Not mutable: finish copy of word, and retry on copied word
return help_copy_impl(i).help_copy().remove(i);
if( (old & mask) == 0 ) return false; // Bit is already clear?
} while( !nbsi.CAS( j>>6, old, old & ~mask ) );
_size.add(-1);
return true;
}
public boolean contains( final int i ) {
if( (i>>6) >= _bits.length ) // Out of bounds? Not in this array!
return _new==null ? false : help_copy().contains(i);
// Handle every 64th bit via using a nested array
NBSI nbsi = this; // The bit array being added into
int j = i; // The bit index being added
while( (j&63) == 63 ) { // Bit 64? (low 6 bits are all set)
nbsi = nbsi._nbsi64; // Recurse
j = j>>6; // Strip off low 6 bits (all set)
}
final long mask = mask(j);
long old = nbsi._bits[j>>6]; // Read old bits
if( old < 0 ) // Not mutable?
// Not mutable: finish copy of word, and retry on copied word
return help_copy_impl(i).help_copy().contains(i);
// Yes mutable: test & return bit
return (old & mask) != 0;
}
public int size() { return (int)_size.get(); }
// Must grow the current array to hold an element of size i
private NBSI install_larger_new_bits( final int i ) {
if( _new == null ) {
// Grow by powers of 2, to avoid minor grow-by-1's.
// Note: must grow by exact powers-of-2 or the by-64-bit trick doesn't work right
int sz = (_bits.length<<6)<<1;
// CAS to install a new larger size. Did it work? Did it fail? We
// don't know and don't care. Only One can be installed, so if
// another thread installed a too-small size, we can't help it - we
// must simply install our new larger size as a nested-resize table.
CAS_new(new NBSI(sz, _size, _non_blocking_set_int));
}
// Return self for 'fluid' programming style
return this;
}
// Help any top-level NBSI to copy until completed.
// Always return the _new version of *this* NBSI, in case we're nested.
private NBSI help_copy() {
// Pick some words to help with - but only help copy the top-level NBSI.
// Nested NBSI waits until the top is done before we start helping.
NBSI top_nbsi = _non_blocking_set_int._nbsi;
final int HELP = 8; // Tuning number: how much copy pain are we willing to inflict?
// We "help" by forcing individual bit indices to copy. However, bits
// come in lumps of 64 per word, so we just advance the bit counter by 64's.
int idx = top_nbsi._copyIdx.getAndAdd(64*HELP);
for( int i=0; i<HELP; i++ ) {
int j = idx+i*64;
j %= (top_nbsi._bits.length<<6); // Limit, wrap to array size; means we retry indices
top_nbsi.help_copy_impl(j );
top_nbsi.help_copy_impl(j+63); // Also force the nested-by-64 bit
}
// Top level guy ready to promote?
// Note: WE may not be the top-level guy!
if( top_nbsi._copyDone.get() == top_nbsi._sum_bits_length )
// One shot CAS to promote - it may fail since we are racing; others
// may promote as well
if( _non_blocking_set_int.CAS_nbsi( top_nbsi, top_nbsi._new ) ) {
//System.out.println("Promote at top level to size "+(_non_blocking_set_int._nbsi._bits.length<<6));
}
// Return the new bitvector for 'fluid' programming style
return _new;
}
// Help copy this one word. State Machine.
// (1) If not "made immutable" in the old array, set the sign bit to make
// it immutable.
// (2) If non-zero in old array & zero in new, CAS new from 0 to copy-of-old
// (3) If non-zero in old array & non-zero in new, CAS old to zero
// (4) Zero in old, new is valid
// At this point, old should be immutable-zero & new has a copy of bits
private NBSI help_copy_impl( int i ) {
// Handle every 64th bit via using a nested array
NBSI old = this; // The bit array being copied from
NBSI nnn = _new; // The bit array being copied to
if( nnn == null ) return this; // Promoted already
int j = i; // The bit index being added
while( (j&63) == 63 ) { // Bit 64? (low 6 bits are all set)
old = old._nbsi64; // Recurse
nnn = nnn._nbsi64; // Recurse
j = j>>6; // Strip off low 6 bits (all set)
}
// Transit from state 1: word is not immutable yet
// Immutable is in bit 63, the sign bit.
long bits = old._bits[j>>6];
while( bits >= 0 ) { // Still in state (1)?
long oldbits = bits;
bits |= mask(63); // Target state of bits: sign-bit means immutable
if( old.CAS( j>>6, oldbits, bits ) ) {
if( oldbits == 0 ) _copyDone.addAndGet(1);
break; // Success - old array word is now immutable
}
bits = old._bits[j>>6]; // Retry if CAS failed
}
// Transit from state 2: non-zero in old and zero in new
if( bits != mask(63) ) { // Non-zero in old?
long new_bits = nnn._bits[j>>6];
if( new_bits == 0 ) { // New array is still zero
new_bits = bits & ~mask(63); // Desired new value: a mutable copy of bits
// One-shot CAS attempt, no loop, from 0 to non-zero.
// If it fails, somebody else did the copy for us
if( !nnn.CAS( j>>6, 0, new_bits ) )
new_bits = nnn._bits[j>>6]; // Since it failed, get the new value
assert new_bits != 0;
}
// Transit from state 3: non-zero in old and non-zero in new
// One-shot CAS attempt, no loop, from non-zero to 0 (but immutable)
if( old.CAS( j>>6, bits, mask(63) ) )
_copyDone.addAndGet(1); // One more word finished copying
}
// Now in state 4: zero (and immutable) in old
// Return the self bitvector for 'fluid' programming style
return this;
}
private void print( int d, String msg ) {
for( int i=0; i<d; i++ )
System.out.print(" ");
System.out.println(msg);
}
private void print(int d) {
StringBuffer buf = new StringBuffer();
buf.append("NBSI - _bits.len=");
NBSI x = this;
while( x != null ) {
buf.append(" "+x._bits.length);
x = x._nbsi64;
}
print(d,buf.toString());
x = this;
while( x != null ) {
for( int i=0; i<x._bits.length; i++ )
System.out.print(Long.toHexString(x._bits[i])+" ");
x = x._nbsi64;
System.out.println();
}
if( _copyIdx.get() != 0 || _copyDone.get() != 0 )
print(d,"_copyIdx="+_copyIdx.get()+" _copyDone="+_copyDone.get()+" _words_to_cpy="+_sum_bits_length);
if( _new != null ) {
print(d,"__has_new - ");
_new.print(d+1);
}
}
}
}
| 7,896 |
370 | /*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.util;
public class Countable<T> implements Comparable<Countable<T>> {
private T id;
private int amount;
/**
* Construct the object.
*
* @param id the ID
* @param amount the count of
*/
public Countable(T id, int amount) {
this.id = id;
this.amount = amount;
}
public T getID() {
return id;
}
public void setID(T id) {
this.id = id;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
/**
* Decrement the amount.
*/
public void decrement() {
--this.amount;
}
/**
* Increment the amount.
*/
public void increment() {
++this.amount;
}
@Override
public int compareTo(Countable<T> other) {
return Integer.compare(amount, other.amount);
}
}
| 626 |
937 | package com.oath.cyclops.react;
import com.oath.cyclops.types.persistent.PersistentList;
import cyclops.reactive.collections.immutable.LinkedListX;
import lombok.AllArgsConstructor;
/**
* Class that returned to blocking predicates for short circuiting result toX
*
* @author johnmcclean
*
* @param <T> Result type
*/
@AllArgsConstructor
public class Status<T> {
private final int completed;
private final int errors;
private final int total;
private final long elapsedNanos;
private final LinkedListX<T> resultsSoFar;
public final int getAllCompleted() {
return completed + errors;
}
public final long getElapsedMillis() {
return elapsedNanos / 1000000;
}
public int getCompleted() {
return completed;
}
public int getErrors() {
return errors;
}
public int getTotal() {
return total;
}
public long getElapsedNanos() {
return elapsedNanos;
}
public PersistentList<T> getResultsSoFar() {
return resultsSoFar;
}
}
| 388 |
1,755 | #!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# this test covers a lot of the code in vtkAbstractTransform that
# is not covered elsewhere
# create a rendering window
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.SetSize(600,300)
# set up first set of polydata
p1 = vtk.vtkPlaneSource()
p1.SetOrigin(0.5,0.508,-0.5)
p1.SetPoint1(-0.5,0.508,-0.5)
p1.SetPoint2(0.5,0.508,0.5)
p1.SetXResolution(5)
p1.SetYResolution(5)
p1.Update()
p2 = vtk.vtkPlaneSource()
p2.SetOrigin(-0.508,0.5,-0.5)
p2.SetPoint1(-0.508,-0.5,-0.5)
p2.SetPoint2(-0.508,0.5,0.5)
p2.SetXResolution(5)
p2.SetYResolution(5)
p2.Update()
p3 = vtk.vtkPlaneSource()
p3.SetOrigin(-0.5,-0.508,-0.5)
p3.SetPoint1(0.5,-0.508,-0.5)
p3.SetPoint2(-0.5,-0.508,0.5)
p3.SetXResolution(5)
p3.SetYResolution(5)
p3.Update()
p4 = vtk.vtkPlaneSource()
p4.SetOrigin(0.508,-0.5,-0.5)
p4.SetPoint1(0.508,0.5,-0.5)
p4.SetPoint2(0.508,-0.5,0.5)
p4.SetXResolution(5)
p4.SetYResolution(5)
p4.Update()
p5 = vtk.vtkPlaneSource()
p5.SetOrigin(0.5,0.5,-0.508)
p5.SetPoint1(0.5,-0.5,-0.508)
p5.SetPoint2(-0.5,0.5,-0.508)
p5.SetXResolution(5)
p5.SetYResolution(5)
p5.Update()
p6 = vtk.vtkPlaneSource()
p6.SetOrigin(0.5,0.5,0.508)
p6.SetPoint1(-0.5,0.5,0.508)
p6.SetPoint2(0.5,-0.5,0.508)
p6.SetXResolution(5)
p6.SetYResolution(5)
p6.Update()
# append together
ap = vtk.vtkAppendPolyData()
ap.AddInputData(p1.GetOutput())
ap.AddInputData(p2.GetOutput())
ap.AddInputData(p3.GetOutput())
ap.AddInputData(p4.GetOutput())
ap.AddInputData(p5.GetOutput())
ap.AddInputData(p6.GetOutput())
#--------------------------
tLinear = vtk.vtkTransform()
tPerspective = vtk.vtkPerspectiveTransform()
tGeneral = vtk.vtkGeneralTransform()
# set up a linear transformation
tLinear.Scale(1.2,1.0,0.8)
tLinear.RotateX(30)
tLinear.RotateY(10)
tLinear.RotateZ(80)
tLinear.Translate(0.2,0.3,-0.1)
tLinear.Update()
# set up a perspective transform
tPerspective.SetInput(tLinear)
tPerspective.SetInput(tLinear.GetInverse())
tPerspective.Scale(2,2,2)
# these should cancel
tPerspective.AdjustViewport(-0.5,0.5,-0.5,0.5,-1,1,-1,1)
tPerspective.AdjustViewport(-1,1,-1,1,-0.5,0.5,-0.5,0.5)
# test shear transformation
tPerspective.Shear(0.2,0.3,0.0)
tPerspective.Update()
# the following 6 operations cancel out
tPerspective.RotateWXYZ(30,1,1,1)
tPerspective.RotateWXYZ(-30,1,1,1)
tPerspective.Scale(2,2,2)
tPerspective.Scale(0.5,0.5,0.5)
tPerspective.Translate(10,0.1,0.3)
tPerspective.Translate(-10,-0.1,-0.3)
tPerspective.Concatenate(tLinear)
# test push and pop
tPerspective.Push()
tPerspective.RotateX(30)
tPerspective.RotateY(10)
tPerspective.RotateZ(80)
tPerspective.Translate(0.1,-0.2,0.0)
# test copy of transforms
tNew = tPerspective.MakeTransform()
tNew.DeepCopy(tPerspective)
tPerspective.Pop()
# test general transform
tGeneral.SetInput(tLinear)
tGeneral.SetInput(tPerspective)
tGeneral.PostMultiply()
tGeneral.Concatenate(tNew)
tGeneral.Concatenate(tNew.GetInverse())
tGeneral.PreMultiply()
# the following 6 operations cancel out
tGeneral.RotateWXYZ(30,1,1,1)
tGeneral.RotateWXYZ(-30,1,1,1)
tGeneral.Scale(2,2,2)
tGeneral.Scale(0.5,0.5,0.5)
tGeneral.Translate(10,0.1,0.3)
tGeneral.Translate(-10,-0.1,-0.3)
#--------------------------
# identity transform
f11 = vtk.vtkTransformPolyDataFilter()
f11.SetInputConnection(ap.GetOutputPort())
f11.SetTransform(tLinear)
m11 = vtk.vtkDataSetMapper()
m11.SetInputConnection(f11.GetOutputPort())
a11 = vtk.vtkActor()
a11.SetMapper(m11)
a11.GetProperty().SetColor(1,0,0)
a11.GetProperty().SetRepresentationToWireframe()
ren11 = vtk.vtkRenderer()
ren11.SetViewport(0.0,0.5,0.25,1.0)
ren11.ResetCamera(-0.5,0.5,-0.5,0.5,-1,1)
ren11.AddActor(a11)
renWin.AddRenderer(ren11)
# inverse identity transform
f12 = vtk.vtkTransformPolyDataFilter()
f12.SetInputConnection(ap.GetOutputPort())
f12.SetTransform(tLinear.GetInverse())
m12 = vtk.vtkDataSetMapper()
m12.SetInputConnection(f12.GetOutputPort())
a12 = vtk.vtkActor()
a12.SetMapper(m12)
a12.GetProperty().SetColor(0.9,0.9,0)
a12.GetProperty().SetRepresentationToWireframe()
ren12 = vtk.vtkRenderer()
ren12.SetViewport(0.0,0.0,0.25,0.5)
ren12.ResetCamera(-0.5,0.5,-0.5,0.5,-1,1)
ren12.AddActor(a12)
renWin.AddRenderer(ren12)
#--------------------------
# linear transform
f21 = vtk.vtkTransformPolyDataFilter()
f21.SetInputConnection(ap.GetOutputPort())
f21.SetTransform(tPerspective)
m21 = vtk.vtkDataSetMapper()
m21.SetInputConnection(f21.GetOutputPort())
a21 = vtk.vtkActor()
a21.SetMapper(m21)
a21.GetProperty().SetColor(1,0,0)
a21.GetProperty().SetRepresentationToWireframe()
ren21 = vtk.vtkRenderer()
ren21.SetViewport(0.25,0.5,0.50,1.0)
ren21.ResetCamera(-0.5,0.5,-0.5,0.5,-1,1)
ren21.AddActor(a21)
renWin.AddRenderer(ren21)
# inverse linear transform
f22 = vtk.vtkTransformPolyDataFilter()
f22.SetInputConnection(ap.GetOutputPort())
f22.SetTransform(tPerspective.GetInverse())
m22 = vtk.vtkDataSetMapper()
m22.SetInputConnection(f22.GetOutputPort())
a22 = vtk.vtkActor()
a22.SetMapper(m22)
a22.GetProperty().SetColor(0.9,0.9,0)
a22.GetProperty().SetRepresentationToWireframe()
ren22 = vtk.vtkRenderer()
ren22.SetViewport(0.25,0.0,0.50,0.5)
ren22.ResetCamera(-0.5,0.5,-0.5,0.5,-1,1)
ren22.AddActor(a22)
renWin.AddRenderer(ren22)
#--------------------------
# perspective transform
matrix = vtk.vtkMatrix4x4()
matrix.SetElement(3,0,0.1)
matrix.SetElement(3,1,0.2)
matrix.SetElement(3,2,0.5)
f31 = vtk.vtkTransformPolyDataFilter()
f31.SetInputConnection(ap.GetOutputPort())
f31.SetTransform(tNew)
m31 = vtk.vtkDataSetMapper()
m31.SetInputConnection(f31.GetOutputPort())
a31 = vtk.vtkActor()
a31.SetMapper(m31)
a31.GetProperty().SetColor(1,0,0)
a31.GetProperty().SetRepresentationToWireframe()
ren31 = vtk.vtkRenderer()
ren31.SetViewport(0.50,0.5,0.75,1.0)
ren31.ResetCamera(-0.5,0.5,-0.5,0.5,-1,1)
ren31.AddActor(a31)
renWin.AddRenderer(ren31)
# inverse linear transform
f32 = vtk.vtkTransformPolyDataFilter()
f32.SetInputConnection(ap.GetOutputPort())
f32.SetTransform(tNew.GetInverse())
m32 = vtk.vtkDataSetMapper()
m32.SetInputConnection(f32.GetOutputPort())
a32 = vtk.vtkActor()
a32.SetMapper(m32)
a32.GetProperty().SetColor(0.9,0.9,0)
a32.GetProperty().SetRepresentationToWireframe()
ren32 = vtk.vtkRenderer()
ren32.SetViewport(0.5,0.0,0.75,0.5)
ren32.ResetCamera(-0.5,0.5,-0.5,0.5,-1,1)
ren32.AddActor(a32)
renWin.AddRenderer(ren32)
#--------------------------
# perspective transform concatenation
f41 = vtk.vtkTransformPolyDataFilter()
f41.SetInputConnection(ap.GetOutputPort())
f41.SetTransform(tGeneral)
m41 = vtk.vtkDataSetMapper()
m41.SetInputConnection(f41.GetOutputPort())
a41 = vtk.vtkActor()
a41.SetMapper(m41)
a41.GetProperty().SetColor(1,0,0)
a41.GetProperty().SetRepresentationToWireframe()
ren41 = vtk.vtkRenderer()
ren41.SetViewport(0.75,0.5,1.0,1.0)
ren41.ResetCamera(-0.5,0.5,-0.5,0.5,-1,1)
ren41.AddActor(a41)
renWin.AddRenderer(ren41)
# inverse linear transform
f42 = vtk.vtkTransformPolyDataFilter()
f42.SetInputConnection(ap.GetOutputPort())
f42.SetTransform(tGeneral.GetInverse())
m42 = vtk.vtkDataSetMapper()
m42.SetInputConnection(f42.GetOutputPort())
a42 = vtk.vtkActor()
a42.SetMapper(m42)
a42.GetProperty().SetColor(0.9,0.9,0)
a42.GetProperty().SetRepresentationToWireframe()
ren42 = vtk.vtkRenderer()
ren42.SetViewport(0.75,0.0,1.0,0.5)
ren42.ResetCamera(-0.5,0.5,-0.5,0.5,-1,1)
ren42.AddActor(a42)
renWin.AddRenderer(ren42)
renWin.Render()
# free what we did a MakeTransform on
tNew.UnRegister(None) # not needed in python
# --- end of script --
| 3,362 |
372 | <filename>sasl2-sys/sasl2/mac/mac_lib/mac_dyn_dlopen.c
/*
* load the sasl plugins
* $Id: mac_dyn_dlopen.c,v 1.3 2003/02/13 19:55:59 rjs3 Exp $
*/
/*
* Copyright (c) 1998-2003 Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any other legal
* details, please contact
* Office of Technology Transfer
* Carnegie Mellon University
* 5000 Forbes Avenue
* Pittsburgh, PA 15213-3890
* (412) 268-4387, fax: (412) 268-7395
* <EMAIL>
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <sasl.h>
#include "saslint.h"
#include <CodeFragments.h>
#include <Errors.h>
#include <Resources.h>
#include <Strings.h>
#include <Folders.h>
#ifdef RUBBISH
#include <FSpCompat.h>
#endif
/*
* The following data structure defines the structure of a code fragment
* resource. We can cast the resource to be of this type to access
* any fields we need to see.
*/
struct CfrgHeader {
long res1;
long res2;
long version;
long res3;
long res4;
long filler1;
long filler2;
long itemCount;
char arrayStart; /* Array of externalItems begins here. */
};
typedef struct CfrgHeader CfrgHeader, *CfrgHeaderPtr, **CfrgHeaderPtrHand;
/*
* The below structure defines a cfrag item within the cfrag resource.
*/
struct CfrgItem {
OSType archType;
long updateLevel;
long currVersion;
long oldDefVersion;
long appStackSize;
short appSubFolder;
char usage;
char location;
long codeOffset;
long codeLength;
long res1;
long res2;
short itemSize;
Str255 name; /* This is actually variable sized. */
};
typedef struct CfrgItem CfrgItem;
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#if TARGET_API_MAC_CARBON
#define SASL_PLUGIN_DIR "\p:sasl v2:carbon:biff"
#else
#define SASL_PLUGIN_DIR "\p:sasl v2:biff"
#endif
typedef struct lib_list
{
struct lib_list *next;
void *library;
} lib_list_t;
static lib_list_t *lib_list_head = NULL;
/*
* add the passed extension
*/
int _macsasl_get_fsspec(FSSpec *fspec,
void **libraryptr)
{
int rc;
CFragConnectionID connID;
Ptr dummy;
unsigned long offset = 0;
unsigned long length = kCFragGoesToEOF;
unsigned char package_name[255];
Str255 error_text;
lib_list_t *newhead;
newhead = sasl_ALLOC(sizeof(lib_list_t));
if(!newhead) return SASL_NOMEM;
package_name[0] = 0;
rc=GetDiskFragment(fspec,offset,length,package_name,
kLoadCFrag,&connID,&dummy,error_text);
if(rc!=0) {
sasl_FREE(newhead);
return rc;
}
newhead->library = (void *)connID;
newhead->next = lib_list_head;
lib_list_head = newhead;
*libraryptr = (void *)connID;
return SASL_OK;
}
int _sasl_locate_entry(void *library, const char *entryname,
void **entry_point)
{
int result;
#if TARGET_API_MAC_CARBON
char cstr[256];
#endif
Str255 pentry;
CFragSymbolClass symClass;
OSErr rc;
if(!entryname) {
return SASL_BADPARAM;
}
if(!library) {
return SASL_BADPARAM;
}
if(!entry_point) {
return SASL_BADPARAM;
}
#if TARGET_API_MAC_CARBON
strcpy(cstr,entryname);
CopyCStringToPascal(cstr, pentry);
#else
strcpy(pentry,entryname);
c2pstr(pentry);
#endif
rc = FindSymbol((CFragConnectionID)library,pentry,entry_point, &symClass);
if ((rc!=noErr) || (symClass==kDataCFragSymbol))
return SASL_FAIL;
return SASL_OK;
}
static int _sasl_plugin_load(char *plugin, void *library,
const char *entryname,
int (*add_plugin)(const char *, void *))
{
void *entry_point;
int result;
result = _sasl_locate_entry(library, entryname, &entry_point);
if(result == SASL_OK) {
result = add_plugin(plugin, entry_point);
// if(result != SASL_OK)
// _sasl_log(NULL, SASL_LOG_ERR,
// "_sasl_plugin_load failed on %s for plugin: %s\n",
// entryname, plugin);
}
return result;
}
/*
* does the passed string a occur and the end of string b?
*/
int _macsasl_ends_in(char *a, char *b)
{
int alen=strlen(a);
int blen=strlen(b);
if(blen<alen)
return FALSE;
return (memcmp(a,b+(blen-alen),alen)==0);
}
/*
* scan the passed directory loading sasl extensions
*/
int _macsasl_find_extensions_in_dir(short vref,long dir_id,
const add_plugin_list_t *entrypoints)
{
CInfoPBRec cinfo;
unsigned char aname[300];
char plugname[256];
int findex=0;
FSSpec a_plugin;
lib_list_t *library;
char *c;
const add_plugin_list_t *cur_ep;
while(TRUE) {
int os;
memset(&cinfo,0,sizeof(cinfo));
aname[0] = 0;
cinfo.hFileInfo.ioVRefNum=vref;
cinfo.hFileInfo.ioNamePtr=aname;
cinfo.hFileInfo.ioFDirIndex=findex++;
cinfo.hFileInfo.ioDirID=dir_id;
os=PBGetCatInfo(&cinfo,FALSE);
if(os!=0)
return SASL_OK;
aname[aname[0]+1] = 0;
/* skip over non shlb files */
if(!_macsasl_ends_in(".shlb",aname+1))
continue;
os=FSMakeFSSpec(vref,dir_id,aname,&a_plugin);
if(os!=0)
continue;
/* skip "lib" and cut off suffix --
this only need be approximate */
strcpy(plugname, aname + 1);
c = strchr(plugname, (int)'.');
if(c) *c = '\0';
if (!_macsasl_get_fsspec(&a_plugin,&library))
for(cur_ep = entrypoints; cur_ep->entryname; cur_ep++) {
_sasl_plugin_load(plugname, library, cur_ep->entryname,
cur_ep->add_plugin);
/* If this fails, it's not the end of the world */
}
}
return SASL_OK;
}
/* gets the list of mechanisms */
int _sasl_load_plugins(const add_plugin_list_t *entrypoints,
const sasl_callback_t *getpath_cb,
const sasl_callback_t *verifyfile_cb)
{
int rc;
short extensions_vref;
long extensions_dirid;
FSSpec sasl_dir;
/* find the extensions folder */
rc=FindFolder(kOnSystemDisk,kExtensionFolderType,FALSE,
&extensions_vref,&extensions_dirid);
if(rc!=0)
return SASL_BADPARAM;
rc=FSMakeFSSpec(extensions_vref,extensions_dirid,SASL_PLUGIN_DIR,&sasl_dir);
/*
* if a plugin named biff exits or not we really dont care
* if it does get rc 0 if it does not get -43 (fnfErr)
* if the sasl dir doesnt exist we get -120 (dirNFFErr)
*/
if((rc!=0)&&(rc!=fnfErr))
return SASL_BADPARAM;
/*
* now extensions_vref is volume
* sasl_dir.parID is dirid for sasl plugins folder
*/
return _macsasl_find_extensions_in_dir(extensions_vref,sasl_dir.parID,entrypoints);
}
int
_sasl_done_with_plugins(void)
{
lib_list_t *libptr, *libptr_next;
for(libptr = lib_list_head; libptr; libptr = libptr_next) {
libptr_next = libptr->next;
if(libptr->library)
CloseConnection((CFragConnectionID*)&libptr->library);
sasl_FREE(libptr);
}
lib_list_head = NULL;
return SASL_OK;
}
| 3,318 |
798 | /*
* The MIT License
*
* Copyright (c) 2018 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package picard.analysis.directed;
/**
* TargetMetrics, are metrics to measure how well we hit specific targets (or baits) when using a targeted sequencing process like hybrid selection
* or Targeted PCR Techniques (TSCA). TargetMetrics at the moment are the metrics that are shared by both HybridSelection and TargetedPcrMetrics.
*/
public class TargetMetricsBase extends PanelMetricsBase {
/** Tracks the number of read pairs that we see that are PF (used to calculate library size) */
public long PF_SELECTED_PAIRS;
/** Tracks the number of unique PF_SELECTED_PAIRS we see (used to calc library size) */
public long PF_SELECTED_UNIQUE_PAIRS;
/** The number of PF aligned bases that are mapped in pair to a targeted region of the genome. */
public long ON_TARGET_FROM_PAIR_BASES;
}
| 525 |
582 | <reponame>oleksandr-pavlyk/dlpack<filename>apps/numpy_dlpack/dlpack/to_numpy.py
import ctypes
import numpy as np
from .dlpack import _c_str_dltensor, DLManagedTensor, DLTensor
ctypes.pythonapi.PyCapsule_IsValid.restype = ctypes.c_int
ctypes.pythonapi.PyCapsule_IsValid.argtypes = [ctypes.py_object, ctypes.c_char_p]
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
def _array_interface_from_dl_tensor(dlt):
"""Constructs NumPy's array_interface dictionary
from `dlpack.DLTensor` descriptor."""
assert isinstance(dlt, DLTensor)
shape = tuple(dlt.shape[dim] for dim in range(dlt.ndim))
itemsize = dlt.dtype.lanes * dlt.dtype.bits // 8
if dlt.strides:
strides = tuple(
dlt.strides[dim] * itemsize for dim in range(dlt.ndim)
)
else:
# Array is compact, make it numpy compatible.
strides = []
for i, s in enumerate(shape):
cumulative = 1
for e in range(i + 1, dlt.ndim):
cumulative *= shape[e]
strides.append(cumulative * itemsize)
strides = tuple(strides)
typestr = "|" + str(dlt.dtype.type_code)[0] + str(itemsize)
return dict(
version=3,
shape=shape,
strides=strides,
data=(dlt.data, True),
offset=dlt.byte_offset,
typestr=typestr,
)
class _Holder:
"""A wrapper that combines a pycapsule and array_interface for consumption by numpy.
Parameters
----------
array_interface : dict
A description of the underlying memory.
pycapsule : PyCapsule
A wrapper around the dlpack tensor that will be converted to numpy.
"""
def __init__(self, array_interface, pycapsule) -> None:
self.__array_interface__ = array_interface
self._pycapsule = pycapsule
def to_numpy(pycapsule) -> np.ndarray:
"""Convert a dlpack tensor into a numpy array without copying.
Parameters
----------
pycapsule : PyCapsule
A pycapsule wrapping a dlpack tensor that will be converted.
Returns
-------
np_array : np.ndarray
A new numpy array that uses the same underlying memory as the input
pycapsule.
"""
assert ctypes.pythonapi.PyCapsule_IsValid(pycapsule, _c_str_dltensor)
dl_managed_tensor = ctypes.pythonapi.PyCapsule_GetPointer(
pycapsule, _c_str_dltensor
)
dl_managed_tensor_ptr = ctypes.cast(dl_managed_tensor, ctypes.POINTER(DLManagedTensor))
dl_managed_tensor = dl_managed_tensor_ptr.contents
holder = _Holder(_array_interface_from_dl_tensor(dl_managed_tensor.dl_tensor), pycapsule)
return np.ctypeslib.as_array(holder)
| 1,175 |
766 | /* Copyright 2013-2015 www.snakerflow.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.snaker.engine.impl;
import java.util.Map;
import java.util.Map.Entry;
import javax.el.ExpressionFactory;
import org.snaker.engine.Expression;
import de.odysseus.el.ExpressionFactoryImpl;
import de.odysseus.el.util.SimpleContext;
/**
* Juel 表达式引擎实现
* @author yuqs
* @since 1.2
*/
public class JuelExpression implements Expression {
ExpressionFactory factory = new ExpressionFactoryImpl();
@SuppressWarnings("unchecked")
public <T> T eval(Class<T> T, String expr, Map<String, Object> args) {
SimpleContext context = new SimpleContext();
for(Entry<String, Object> entry : args.entrySet()) {
context.setVariable(entry.getKey(), factory.createValueExpression(entry.getValue(), Object.class));
}
return (T)factory.createValueExpression(context, expr, T).getValue(context);
}
}
| 446 |
587 | <gh_stars>100-1000
#include "../hedley.h"
#if HEDLEY_HAS_WARNING("-Wcovered-switch-default")
# pragma clang diagnostic warning "-Wcovered-switch-default"
#endif
enum Foo {
FOO_BAR,
FOO_BAZ,
FOO_QUX,
FOO_QUUX
};
static int test_unreachable(enum Foo code) {
switch (code) {
case FOO_BAR:
case FOO_BAZ:
case FOO_QUX:
return 0;
case FOO_QUUX:
default:
HEDLEY_UNREACHABLE();
}
HEDLEY_UNREACHABLE_RETURN(0);
}
int main(void) {
test_unreachable(FOO_BAR);
return 0;
}
| 230 |
30,023 | <filename>homeassistant/components/sentry/manifest.json<gh_stars>1000+
{
"domain": "sentry",
"name": "Sentry",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/sentry",
"requirements": ["sentry-sdk==1.5.12"],
"codeowners": ["@dcramer", "@frenck"],
"iot_class": "cloud_polling"
}
| 128 |
377 | import pandas as pd
import numpy as np
import pyaf.ForecastEngine as autof
import pyaf.Bench.TS_datasets as tsds
import datetime
#get_ipython().magic('matplotlib inline')
def read_dataset():
trainfile = "data/Hierarchical/hts_dataset.csv"
lDateColumn = 'Date'
df = pd.read_csv(trainfile, sep=r',', engine='python', skiprows=0);
df[lDateColumn] = df[lDateColumn].apply(lambda x : datetime.datetime.strptime(x, "%Y-%m-%d"))
print(df.tail(10))
# df[:-10].tail()
# df[:-10:-1]
print(df.info())
print(df.describe())
return df;
def define_hierarchy_info():
rows_list = [];
# Sydney NSW Melbourne VIC BrisbaneGC QLD Capitals Other
rows_list.append(['Sydney' , 'NSW_State' , 'Australia']);
rows_list.append(['NSW' , 'NSW_State' , 'Australia']);
# rows_list.append(['Melbourne' , 'VIC_State' , 'Australia']);
# rows_list.append(['VIC' , 'VIC_State' , 'Australia']);
# rows_list.append(['BrisbaneGC' , 'QLD_State' , 'Australia']);
# rows_list.append(['QLD' , 'QLD_State' , 'Australia']);
rows_list.append(['Capitals' , 'Other_State' , 'Australia']);
rows_list.append(['Other' , 'Other_State' , 'Australia']);
lLevels = ['City' , 'State' , 'Country'];
lHierarcyInfo = {};
lHierarcyInfo['Levels'] = lLevels;
lHierarcyInfo['Data'] = pd.DataFrame(rows_list, columns = lLevels);
print(lHierarcyInfo['Data'].head(lHierarcyInfo['Data'].shape[0]));
return lHierarcyInfo;
def enrich_dataset(df , hier):
df1 = df.copy();
lLevelCount = len(hier['Levels']);
lContent = {};
df = hier['Data'];
for level in range(lLevelCount):
lContent[level] = {};
for row in range(df.shape[0]):
for level in range(lLevelCount):
col = df[df.columns[level]][row];
if(col not in lContent[level].keys()):
lContent[level][col] = set();
if(level > 0):
col1 = df[df.columns[level - 1]][row];
lContent[level][col].add(col1);
print(lContent);
for level in range(lLevelCount):
if(level > 0):
for col in lContent[level].keys():
new_col = None;
for col1 in lContent[level][col]:
if(new_col is None):
new_col = df1[col1];
else:
new_col = new_col + df1[col1];
df1[col] = new_col;
return df1;
df = read_dataset();
hier = define_hierarchy_info();
df1 = enrich_dataset(df, hier);
print(df1.head())
lDateColumn = 'Date'
lAllLevelColumns = [col for col in df1.columns if col != lDateColumn]
print("ALL_LEVEL_COLUMNS" , lAllLevelColumns);
H = 4;
for signal in lAllLevelColumns:
lEngine = autof.cForecastEngine()
lEngine
# lEngine.mOptions.enable_slow_mode();
# lEngine.mOptions.mDebugPerformance = True;
lEngine.mOptions.set_active_autoregressions([]);
lEngine.train(df1 , lDateColumn , signal, H);
lEngine.getModelInfo();
print(lEngine.mSignalDecomposition.mTrPerfDetails.head());
lEngine.mSignalDecomposition.mBestModel.mTimeInfo.mResolution
#lEngine.standardPlots("outputs/hierarchical_" + signal);
dfapp_in = df1.copy();
dfapp_in.tail()
dfapp_out = lEngine.forecast(dfapp_in, H);
#dfapp_out.to_csv("outputs/ozone_apply_out.csv")
dfapp_out.tail(2 * H)
print("Forecast Columns " , dfapp_out.columns);
Forecast_DF = dfapp_out[[lDateColumn , signal, signal + '_Forecast']]
print(Forecast_DF.info())
print("Forecasts\n" , Forecast_DF.tail(H));
print("\n\n<ModelInfo>")
print(lEngine.to_json());
print("</ModelInfo>\n\n")
print("\n\n<Forecast>")
print(Forecast_DF.tail(2*H).to_json(date_format='iso'))
print("</Forecast>\n\n")
| 1,754 |
14,668 | <reponame>chromium/chromium
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.h"
#include <memory>
#include <utility>
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/core/animation/interpolable_value.h"
#include "third_party/blink/renderer/core/animation/non_interpolable_value.h"
#include "third_party/blink/renderer/core/animation/string_keyframe.h"
#include "third_party/blink/renderer/core/animation/svg_interpolation_environment.h"
#include "third_party/blink/renderer/core/svg/svg_transform.h"
#include "third_party/blink/renderer/core/svg/svg_transform_list.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "ui/gfx/geometry/size_f.h"
namespace blink {
class SVGTransformNonInterpolableValue : public NonInterpolableValue {
public:
~SVGTransformNonInterpolableValue() override = default;
static scoped_refptr<SVGTransformNonInterpolableValue> Create(
Vector<SVGTransformType>& transform_types) {
return base::AdoptRef(
new SVGTransformNonInterpolableValue(transform_types));
}
const Vector<SVGTransformType>& TransformTypes() const {
return transform_types_;
}
DECLARE_NON_INTERPOLABLE_VALUE_TYPE();
private:
SVGTransformNonInterpolableValue(Vector<SVGTransformType>& transform_types) {
transform_types_.swap(transform_types);
}
Vector<SVGTransformType> transform_types_;
};
DEFINE_NON_INTERPOLABLE_VALUE_TYPE(SVGTransformNonInterpolableValue);
template <>
struct DowncastTraits<SVGTransformNonInterpolableValue> {
static bool AllowFrom(const NonInterpolableValue* value) {
return value && AllowFrom(*value);
}
static bool AllowFrom(const NonInterpolableValue& value) {
return value.GetType() == SVGTransformNonInterpolableValue::static_type_;
}
};
namespace {
std::unique_ptr<InterpolableValue> TranslateToInterpolableValue(
SVGTransform* transform) {
gfx::Vector2dF translate = transform->Translate();
auto result = std::make_unique<InterpolableList>(2);
result->Set(0, std::make_unique<InterpolableNumber>(translate.x()));
result->Set(1, std::make_unique<InterpolableNumber>(translate.y()));
return std::move(result);
}
SVGTransform* TranslateFromInterpolableValue(const InterpolableValue& value) {
const auto& list = To<InterpolableList>(value);
auto* transform =
MakeGarbageCollected<SVGTransform>(SVGTransformType::kTranslate);
transform->SetTranslate(To<InterpolableNumber>(list.Get(0))->Value(),
To<InterpolableNumber>(list.Get(1))->Value());
return transform;
}
std::unique_ptr<InterpolableValue> ScaleToInterpolableValue(
SVGTransform* transform) {
gfx::Vector2dF scale = transform->Scale();
auto result = std::make_unique<InterpolableList>(2);
result->Set(0, std::make_unique<InterpolableNumber>(scale.x()));
result->Set(1, std::make_unique<InterpolableNumber>(scale.y()));
return std::move(result);
}
SVGTransform* ScaleFromInterpolableValue(const InterpolableValue& value) {
const auto& list = To<InterpolableList>(value);
auto* transform =
MakeGarbageCollected<SVGTransform>(SVGTransformType::kScale);
transform->SetScale(To<InterpolableNumber>(list.Get(0))->Value(),
To<InterpolableNumber>(list.Get(1))->Value());
return transform;
}
std::unique_ptr<InterpolableValue> RotateToInterpolableValue(
SVGTransform* transform) {
gfx::PointF rotation_center = transform->RotationCenter();
auto result = std::make_unique<InterpolableList>(3);
result->Set(0, std::make_unique<InterpolableNumber>(transform->Angle()));
result->Set(1, std::make_unique<InterpolableNumber>(rotation_center.x()));
result->Set(2, std::make_unique<InterpolableNumber>(rotation_center.y()));
return std::move(result);
}
SVGTransform* RotateFromInterpolableValue(const InterpolableValue& value) {
const auto& list = To<InterpolableList>(value);
auto* transform =
MakeGarbageCollected<SVGTransform>(SVGTransformType::kRotate);
transform->SetRotate(To<InterpolableNumber>(list.Get(0))->Value(),
To<InterpolableNumber>(list.Get(1))->Value(),
To<InterpolableNumber>(list.Get(2))->Value());
return transform;
}
std::unique_ptr<InterpolableValue> SkewXToInterpolableValue(
SVGTransform* transform) {
return std::make_unique<InterpolableNumber>(transform->Angle());
}
SVGTransform* SkewXFromInterpolableValue(const InterpolableValue& value) {
auto* transform =
MakeGarbageCollected<SVGTransform>(SVGTransformType::kSkewx);
transform->SetSkewX(To<InterpolableNumber>(value).Value());
return transform;
}
std::unique_ptr<InterpolableValue> SkewYToInterpolableValue(
SVGTransform* transform) {
return std::make_unique<InterpolableNumber>(transform->Angle());
}
SVGTransform* SkewYFromInterpolableValue(const InterpolableValue& value) {
auto* transform =
MakeGarbageCollected<SVGTransform>(SVGTransformType::kSkewy);
transform->SetSkewY(To<InterpolableNumber>(value).Value());
return transform;
}
std::unique_ptr<InterpolableValue> ToInterpolableValue(
SVGTransform* transform,
SVGTransformType transform_type) {
switch (transform_type) {
case SVGTransformType::kTranslate:
return TranslateToInterpolableValue(transform);
case SVGTransformType::kScale:
return ScaleToInterpolableValue(transform);
case SVGTransformType::kRotate:
return RotateToInterpolableValue(transform);
case SVGTransformType::kSkewx:
return SkewXToInterpolableValue(transform);
case SVGTransformType::kSkewy:
return SkewYToInterpolableValue(transform);
case SVGTransformType::kMatrix:
case SVGTransformType::kUnknown:
NOTREACHED();
}
NOTREACHED();
return nullptr;
}
SVGTransform* FromInterpolableValue(const InterpolableValue& value,
SVGTransformType transform_type) {
switch (transform_type) {
case SVGTransformType::kTranslate:
return TranslateFromInterpolableValue(value);
case SVGTransformType::kScale:
return ScaleFromInterpolableValue(value);
case SVGTransformType::kRotate:
return RotateFromInterpolableValue(value);
case SVGTransformType::kSkewx:
return SkewXFromInterpolableValue(value);
case SVGTransformType::kSkewy:
return SkewYFromInterpolableValue(value);
case SVGTransformType::kMatrix:
case SVGTransformType::kUnknown:
NOTREACHED();
}
NOTREACHED();
return nullptr;
}
const Vector<SVGTransformType>& GetTransformTypes(
const InterpolationValue& value) {
return To<SVGTransformNonInterpolableValue>(*value.non_interpolable_value)
.TransformTypes();
}
class SVGTransformListChecker : public InterpolationType::ConversionChecker {
public:
explicit SVGTransformListChecker(const InterpolationValue& underlying)
: underlying_(underlying.Clone()) {}
bool IsValid(const InterpolationEnvironment&,
const InterpolationValue& underlying) const final {
// TODO(suzyh): change maybeConvertSingle so we don't have to recalculate
// for changes to the interpolable values
if (!underlying && !underlying_)
return true;
if (!underlying || !underlying_)
return false;
return underlying_.interpolable_value->Equals(
*underlying.interpolable_value) &&
GetTransformTypes(underlying_) == GetTransformTypes(underlying);
}
private:
const InterpolationValue underlying_;
};
} // namespace
InterpolationValue SVGTransformListInterpolationType::MaybeConvertNeutral(
const InterpolationValue&,
ConversionCheckers&) const {
NOTREACHED();
// This function is no longer called, because maybeConvertSingle has been
// overridden.
return nullptr;
}
InterpolationValue SVGTransformListInterpolationType::MaybeConvertSVGValue(
const SVGPropertyBase& svg_value) const {
const auto* svg_list = DynamicTo<SVGTransformList>(svg_value);
if (!svg_list)
return nullptr;
auto result = std::make_unique<InterpolableList>(svg_list->length());
Vector<SVGTransformType> transform_types;
for (wtf_size_t i = 0; i < svg_list->length(); i++) {
const SVGTransform* transform = svg_list->at(i);
SVGTransformType transform_type(transform->TransformType());
if (transform_type == SVGTransformType::kMatrix) {
// TODO(ericwilligers): Support matrix interpolation.
return nullptr;
}
result->Set(i, ToInterpolableValue(transform->Clone(), transform_type));
transform_types.push_back(transform_type);
}
return InterpolationValue(
std::move(result),
SVGTransformNonInterpolableValue::Create(transform_types));
}
InterpolationValue SVGTransformListInterpolationType::MaybeConvertSingle(
const PropertySpecificKeyframe& keyframe,
const InterpolationEnvironment& environment,
const InterpolationValue& underlying,
ConversionCheckers& conversion_checkers) const {
Vector<SVGTransformType> types;
Vector<std::unique_ptr<InterpolableValue>> interpolable_parts;
if (keyframe.Composite() == EffectModel::kCompositeAdd) {
if (underlying) {
types.AppendVector(GetTransformTypes(underlying));
interpolable_parts.push_back(underlying.interpolable_value->Clone());
}
conversion_checkers.push_back(
std::make_unique<SVGTransformListChecker>(underlying));
} else {
DCHECK(!keyframe.IsNeutral());
}
if (!keyframe.IsNeutral()) {
auto* svg_value =
To<SVGInterpolationEnvironment>(environment)
.SvgBaseValue()
.CloneForAnimation(
To<SVGPropertySpecificKeyframe>(keyframe).Value());
InterpolationValue value = MaybeConvertSVGValue(*svg_value);
if (!value)
return nullptr;
types.AppendVector(GetTransformTypes(value));
interpolable_parts.push_back(std::move(value.interpolable_value));
}
auto interpolable_list = std::make_unique<InterpolableList>(types.size());
wtf_size_t interpolable_list_index = 0;
for (auto& part : interpolable_parts) {
auto& list = To<InterpolableList>(*part);
for (wtf_size_t i = 0; i < list.length(); ++i) {
interpolable_list->Set(interpolable_list_index,
std::move(list.GetMutable(i)));
++interpolable_list_index;
}
}
return InterpolationValue(std::move(interpolable_list),
SVGTransformNonInterpolableValue::Create(types));
}
SVGPropertyBase* SVGTransformListInterpolationType::AppliedSVGValue(
const InterpolableValue& interpolable_value,
const NonInterpolableValue* non_interpolable_value) const {
auto* result = MakeGarbageCollected<SVGTransformList>();
const auto& list = To<InterpolableList>(interpolable_value);
const Vector<SVGTransformType>& transform_types =
To<SVGTransformNonInterpolableValue>(non_interpolable_value)
->TransformTypes();
for (wtf_size_t i = 0; i < list.length(); ++i)
result->Append(FromInterpolableValue(*list.Get(i), transform_types.at(i)));
return result;
}
PairwiseInterpolationValue SVGTransformListInterpolationType::MaybeMergeSingles(
InterpolationValue&& start,
InterpolationValue&& end) const {
if (GetTransformTypes(start) != GetTransformTypes(end))
return nullptr;
return PairwiseInterpolationValue(std::move(start.interpolable_value),
std::move(end.interpolable_value),
std::move(end.non_interpolable_value));
}
void SVGTransformListInterpolationType::Composite(
UnderlyingValueOwner& underlying_value_owner,
double underlying_fraction,
const InterpolationValue& value,
double interpolation_fraction) const {
underlying_value_owner.Set(*this, value);
}
} // namespace blink
| 4,248 |
17,242 | // Copyright 2019 The MediaPipe 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.google.mediapipe.glutil;
import android.graphics.SurfaceTexture;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.view.Surface;
import java.nio.FloatBuffer;
import java.util.HashMap;
import java.util.Map;
/**
* Textures from {@link SurfaceTexture} are only supposed to be bound to target {@link
* GLES11Ext#GL_TEXTURE_EXTERNAL_OES}, which is accessed using samplerExternalOES in the shader.
* This means they cannot be used with a regular shader that expects a sampler2D. This class renders
* the external texture to the current framebuffer. By binding the framebuffer to a texture, this
* can be used to convert the input into a normal 2D texture.
*/
public class ExternalTextureRenderer {
private static final FloatBuffer TEXTURE_VERTICES =
ShaderUtil.floatBuffer(
0.0f, 0.0f, // bottom left
1.0f, 0.0f, // bottom right
0.0f, 1.0f, // top left
1.0f, 1.0f // top right
);
private static final FloatBuffer FLIPPED_TEXTURE_VERTICES =
ShaderUtil.floatBuffer(
0.0f, 1.0f, // top left
1.0f, 1.0f, // top right
0.0f, 0.0f, // bottom left
1.0f, 0.0f // bottom right
);
private static final Vertex BOTTOM_LEFT = new Vertex(-1.0f, -1.0f);
private static final Vertex BOTTOM_RIGHT = new Vertex(1.0f, -1.0f);
private static final Vertex TOP_LEFT = new Vertex(-1.0f, 1.0f);
private static final Vertex TOP_RIGHT = new Vertex(1.0f, 1.0f);
private static final Vertex[] POSITION_VERTICIES = {
BOTTOM_LEFT, BOTTOM_RIGHT, TOP_LEFT, TOP_RIGHT
};
private static final FloatBuffer POSITION_VERTICIES_0 = fb(POSITION_VERTICIES, 0, 1, 2, 3);
private static final FloatBuffer POSITION_VERTICIES_90 = fb(POSITION_VERTICIES, 2, 0, 3, 1);
private static final FloatBuffer POSITION_VERTICIES_180 = fb(POSITION_VERTICIES, 3, 2, 1, 0);
private static final FloatBuffer POSITION_VERTICIES_270 = fb(POSITION_VERTICIES, 1, 3, 0, 2);
private static final String TAG = "ExternalTextureRend"; // Max length of a tag is 23.
private static final int ATTRIB_POSITION = 1;
private static final int ATTRIB_TEXTURE_COORDINATE = 2;
private int program = 0;
private int frameUniform;
private int textureTransformUniform;
private float[] textureTransformMatrix = new float[16];
private boolean flipY;
private int rotation = Surface.ROTATION_0;
/** Call this to setup the shader program before rendering. */
public void setup() {
Map<String, Integer> attributeLocations = new HashMap<>();
attributeLocations.put("position", ATTRIB_POSITION);
attributeLocations.put("texture_coordinate", ATTRIB_TEXTURE_COORDINATE);
program =
ShaderUtil.createProgram(
CommonShaders.VERTEX_SHADER,
CommonShaders.FRAGMENT_SHADER_EXTERNAL,
attributeLocations);
frameUniform = GLES20.glGetUniformLocation(program, "video_frame");
textureTransformUniform = GLES20.glGetUniformLocation(program, "texture_transform");
ShaderUtil.checkGlError("glGetUniformLocation");
}
/**
* Flips rendering output vertically, useful for conversion between coordinate systems with
* top-left v.s. bottom-left origins. Effective in subsequent {@link #render(SurfaceTexture)}
* calls.
*/
public void setFlipY(boolean flip) {
flipY = flip;
}
/**
* Rotates the rendering output, useful for supporting landscape orientations. The value should
* correspond to Display.getRotation(), e.g. Surface.ROTATION_0. Flipping (if any) is applied
* before rotation. Effective in subsequent {@link #render(SurfaceTexture)} calls.
*/
public void setRotation(int rotation) {
this.rotation = rotation;
}
/**
* Renders the surfaceTexture to the framebuffer with optional vertical flip.
*
* <p>Before calling this, {@link #setup} must have been called.
*
* <p>NOTE: Calls {@link SurfaceTexture#updateTexImage()} on passed surface texture.
*/
public void render(SurfaceTexture surfaceTexture) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
ShaderUtil.checkGlError("glActiveTexture");
surfaceTexture.updateTexImage(); // This implicitly binds the texture.
surfaceTexture.getTransformMatrix(textureTransformMatrix);
GLES20.glTexParameteri(
GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(
GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(
GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(
GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
ShaderUtil.checkGlError("glTexParameteri");
GLES20.glUseProgram(program);
ShaderUtil.checkGlError("glUseProgram");
GLES20.glUniform1i(frameUniform, 0);
ShaderUtil.checkGlError("glUniform1i");
GLES20.glUniformMatrix4fv(textureTransformUniform, 1, false, textureTransformMatrix, 0);
ShaderUtil.checkGlError("glUniformMatrix4fv");
GLES20.glEnableVertexAttribArray(ATTRIB_POSITION);
GLES20.glVertexAttribPointer(
ATTRIB_POSITION, 2, GLES20.GL_FLOAT, false, 0, getPositionVerticies());
GLES20.glEnableVertexAttribArray(ATTRIB_TEXTURE_COORDINATE);
GLES20.glVertexAttribPointer(
ATTRIB_TEXTURE_COORDINATE,
2,
GLES20.GL_FLOAT,
false,
0,
flipY ? FLIPPED_TEXTURE_VERTICES : TEXTURE_VERTICES);
ShaderUtil.checkGlError("program setup");
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
ShaderUtil.checkGlError("glDrawArrays");
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
ShaderUtil.checkGlError("glBindTexture");
// TODO: add sync and go back to glFlush()
GLES20.glFinish();
}
/**
* Call this to delete the shader program.
*
* <p>This is only necessary if one wants to release the program while keeping the context around.
*/
public void release() {
GLES20.glDeleteProgram(program);
}
private FloatBuffer getPositionVerticies() {
switch (rotation) {
case Surface.ROTATION_90:
return POSITION_VERTICIES_90;
case Surface.ROTATION_180:
return POSITION_VERTICIES_180;
case Surface.ROTATION_270:
return POSITION_VERTICIES_270;
case Surface.ROTATION_0:
default:
return POSITION_VERTICIES_0;
}
}
private static FloatBuffer fb(Vertex[] v, int i0, int i1, int i2, int i3) {
return ShaderUtil.floatBuffer(
v[i0].x, v[i0].y, v[i1].x, v[i1].y, v[i2].x, v[i2].y, v[i3].x, v[i3].y);
}
/** Convenience class to make rotations easier. */
private static class Vertex {
float x;
float y;
Vertex(float x, float y) {
this.x = x;
this.y = y;
}
}
}
| 2,844 |
489 | /*
* Copyright 2009-present, <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joda.money;
/**
* Provides a uniform interface to obtain a {@code BigMoney}.
* <p>
* This interface provides an abstraction over {@link Money} and {@link BigMoney}.
* In general, applications should use the concrete types, not this interface.
* However, utilities and frameworks may choose to make use of this abstraction.
* <p>
* Implementations of {@code BigMoneyProvider} may be mutable.
* To minimise the risk of the value of the provider changing while processing,
* any method that takes a {@code BigMoneyProvider} as a parameter should convert
* it to a {@code BigMoney} immediately and use that directly from then on.
* The method {@link BigMoney#of(BigMoneyProvider)} performs the conversion
* safely with null checks and is recommended for this purpose.
* <p>
* This interface makes no guarantees about the immutability or
* thread-safety of implementations.
*/
public interface BigMoneyProvider {
/**
* Returns a {@code BigMoney} instance equivalent to the value of this object.
* <p>
* It is recommended that {@link BigMoney#of(BigMoneyProvider)} is used in
* preference to calling this method directly. It is also recommended that the
* converted {@code BigMoney} is cached in a local variable instead of
* performing the conversion multiple times.
*
* @return the converted money instance, never null
* @throws RuntimeException if conversion is not possible
*/
BigMoney toBigMoney();
}
| 617 |
307 | <gh_stars>100-1000
package org.cobbzilla.s3s3mirror;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
public class DeleteMaster extends KeyMaster {
public DeleteMaster(AmazonS3Client client, MirrorContext context, BlockingQueue<Runnable> workQueue, ThreadPoolExecutor executorService) {
super(client, context, workQueue, executorService);
}
protected String getPrefix(MirrorOptions options) {
return options.hasDestPrefix() ? options.getDestPrefix() : options.getPrefix();
}
protected String getBucket(MirrorOptions options) { return options.getDestinationBucket(); }
@Override
protected KeyJob getTask(S3ObjectSummary summary) {
return new KeyDeleteJob(client, context, summary, notifyLock);
}
}
| 294 |
14,668 | <reponame>zealoussnow/chromium<filename>chrome/android/javatests/src/org/chromium/chrome/browser/provider/ProviderBookmarksUriTest.java
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.provider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import androidx.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.ContextUtils;
import org.chromium.base.test.util.Batch;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
/**
* Tests the use of the Bookmark URI as part of the Android provider public API.
*/
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
@Batch(Batch.UNIT_TESTS)
public class ProviderBookmarksUriTest {
@Rule
public ProviderTestRule mProviderTestRule = new ProviderTestRule();
private static final String TAG = "ProviderBookmarkUriTest";
private static final byte[] FAVICON_DATA = { 1, 2, 3 };
private Uri mBookmarksUri;
@Before
public void setUp() {
mBookmarksUri =
ChromeBrowserProviderImpl.getBookmarksApiUri(ContextUtils.getApplicationContext());
}
private Uri addBookmark(String url, String title, long lastVisitTime, long created, int visits,
byte[] icon, int isBookmark) {
ContentValues values = new ContentValues();
values.put(BookmarkColumns.BOOKMARK, isBookmark);
values.put(BookmarkColumns.DATE, lastVisitTime);
values.put(BookmarkColumns.CREATED, created);
values.put(BookmarkColumns.FAVICON, icon);
values.put(BookmarkColumns.URL, url);
values.put(BookmarkColumns.VISITS, visits);
values.put(BookmarkColumns.TITLE, title);
return mProviderTestRule.getContentResolver().insert(mBookmarksUri, values);
}
@Test
@SmallTest
@Feature({"Android-ContentProvider"})
public void testAddBookmark() {
final long lastUpdateTime = System.currentTimeMillis();
final long createdTime = lastUpdateTime - 1000 * 60 * 60;
final String url = "http://www.google.com/";
final int visits = 2;
final String title = "Google";
ContentValues values = new ContentValues();
values.put(BookmarkColumns.BOOKMARK, 0);
values.put(BookmarkColumns.DATE, lastUpdateTime);
values.put(BookmarkColumns.CREATED, createdTime);
values.put(BookmarkColumns.FAVICON, FAVICON_DATA);
values.put(BookmarkColumns.URL, url);
values.put(BookmarkColumns.VISITS, visits);
values.put(BookmarkColumns.TITLE, title);
Assert.assertNull(mProviderTestRule.getContentResolver().insert(mBookmarksUri, values));
}
@Test
@SmallTest
@Feature({"Android-ContentProvider"})
public void testQueryBookmark() {
final long lastUpdateTime = System.currentTimeMillis();
final String url = "http://www.google.com/";
final int visits = 2;
final int isBookmark = 1;
String[] selectionArgs = {url, String.valueOf(lastUpdateTime), String.valueOf(visits),
String.valueOf(isBookmark)};
Cursor cursor = mProviderTestRule.getContentResolver().query(mBookmarksUri, null,
BookmarkColumns.URL + " = ? AND " + BookmarkColumns.DATE + " = ? AND "
+ BookmarkColumns.VISITS + " = ? AND " + BookmarkColumns.BOOKMARK
+ " = ? AND " + BookmarkColumns.FAVICON + " IS NOT NULL",
selectionArgs, null);
try {
Assert.assertEquals(0, cursor.getCount());
} finally {
cursor.close();
}
}
@Test
@SmallTest
@Feature({"Android-ContentProvider"})
public void testUpdateBookmark() {
final long now = System.currentTimeMillis();
final long lastUpdateTime[] = {now, now - 1000 * 60};
final String url[] = {"http://www.google.com/", "http://mail.google.com/"};
final int visits[] = {2, 20};
final String title[] = {"Google", "Mail"};
final int isBookmark[] = {1, 0};
ContentValues values = new ContentValues();
values.put(BookmarkColumns.BOOKMARK, isBookmark[1]);
values.put(BookmarkColumns.DATE, lastUpdateTime[1]);
values.put(BookmarkColumns.URL, url[1]);
values.putNull(BookmarkColumns.FAVICON);
values.put(BookmarkColumns.TITLE, title[1]);
values.put(BookmarkColumns.VISITS, visits[1]);
String[] selectionArgs = {String.valueOf(lastUpdateTime[0]), String.valueOf(isBookmark[0])};
Assert.assertEquals(0,
mProviderTestRule.getContentResolver().update(Uri.parse(""), values,
BookmarkColumns.FAVICON + " IS NOT NULL AND " + BookmarkColumns.DATE
+ "= ? AND " + BookmarkColumns.BOOKMARK + " = ?",
selectionArgs));
}
@Test
@SmallTest
@Feature({"Android-ContentProvider"})
public void testDeleteBookmark() {
final long now = System.currentTimeMillis();
final long lastUpdateTime[] = { now, now - 1000 * 60 };
final int isBookmark[] = { 1, 0 };
String[] selectionArgs = {String.valueOf(lastUpdateTime[0]), String.valueOf(isBookmark[0])};
Assert.assertEquals(0,
mProviderTestRule.getContentResolver().delete(mBookmarksUri,
BookmarkColumns.FAVICON + " IS NOT NULL AND " + BookmarkColumns.DATE
+ "= ? AND " + BookmarkColumns.BOOKMARK + " = ?",
selectionArgs));
}
}
| 2,463 |
494 | /*
* Copyright 2017 By_syk
*
* 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.by_syk.lib.nanoiconpack.dialog;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.SpannableString;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import com.by_syk.lib.nanoiconpack.R;
import com.by_syk.lib.nanoiconpack.bean.IconBean;
import com.by_syk.lib.nanoiconpack.util.C;
import com.by_syk.lib.nanoiconpack.util.ExtraUtil;
import com.by_syk.lib.nanoiconpack.util.InstalledAppReader;
import com.by_syk.lib.nanoiconpack.util.PkgUtil;
import com.by_syk.lib.globaltoast.GlobalToast;
import com.by_syk.lib.texttag.TextTag;
/**
* Created by By_syk on 2017-01-27.
*/
public class IconDialog extends DialogFragment {
private ImageView ivIcon;
private View iconGridView;
private View iconViewSmall;
private View viewActionSave;
private View viewActionSend2Home;
private View viewActionChoose;
private IconBean iconBean;
private boolean isAppInstalled = true;
private boolean isExecuted = false;
private static boolean promptActionSave = true;
private static boolean promptActionSend2Home = true;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View viewContent = getActivity().getLayoutInflater().inflate(R.layout.dialog_icon, null);
initView(viewContent);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
.setView(viewContent);
Bundle bundle = getArguments();
if (bundle != null) {
iconBean = (IconBean) bundle.getSerializable("bean");
if (iconBean != null) {
builder.setTitle(getTitle(iconBean));
// ivIcon.setImageResource(iconBean.getId());
int hdIconId = getResources().getIdentifier(iconBean.getName(), "mipmap",
getContext().getPackageName());
ivIcon.setImageResource(hdIconId != 0 ? hdIconId : iconBean.getId());
viewActionSave.setVisibility(iconBean.getId() != 0 || hdIconId != 0
? View.VISIBLE : View.GONE);
viewActionSend2Home.setVisibility(iconBean.containsInstalledComponent()
? View.VISIBLE : View.GONE);
}
if (bundle.getBoolean("pick")) {
viewActionSave.setVisibility(View.GONE);
viewActionSend2Home.setVisibility(View.GONE);
viewActionChoose.setVisibility(View.VISIBLE);
}
}
return builder.create();
}
@Override
public void onStart() {
super.onStart();
if (iconBean == null) {
dismiss();
return;
}
if (!isExecuted) {
isExecuted = true;
(new ExtractRawIconTask()).execute();
// 浮入浮出动画
Window window = getDialog().getWindow();
if (window != null) {
window.setWindowAnimations(android.R.style.Animation_InputMethod);
}
}
}
private void initView(View viewContent) {
iconViewSmall = viewContent.findViewById(R.id.small_icon_view);
iconViewSmall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
iconViewSmall.setVisibility(View.GONE);
iconGridView.setVisibility(View.INVISIBLE);
}
});
iconGridView = viewContent.findViewById(R.id.icon_grid);
ivIcon = (ImageView) viewContent.findViewById(R.id.iv_icon);
ivIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (iconGridView.getVisibility() == View.VISIBLE) {
iconGridView.setVisibility(View.INVISIBLE);
} else {
iconGridView.setVisibility(View.VISIBLE);
}
if (!isAppInstalled) {
return;
}
if (iconViewSmall == null) {
(new ExtractRawIconTask()).execute();
} else {
if (iconViewSmall.getVisibility() == View.VISIBLE) {
iconViewSmall.setVisibility(View.GONE);
} else {
iconViewSmall.setVisibility(View.VISIBLE);
}
}
}
});
viewActionSave = viewContent.findViewById(R.id.iv_save);
viewActionSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (promptActionSave) {
promptActionSave = false;
GlobalToast.showLong(getContext(), R.string.toast_tap_save_icon);
} else {
saveIcon();
}
}
});
viewActionSend2Home = viewContent.findViewById(R.id.iv_send_to_home);
viewActionSend2Home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (promptActionSend2Home) {
promptActionSend2Home = false;
GlobalToast.showLong(getContext(), R.string.toast_tap_send_to_home);
} else {
sendIcon();
}
}
});
viewActionChoose = viewContent.findViewById(R.id.iv_choose);
viewActionChoose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
returnPickIcon();
}
});
}
private SpannableString getTitle(@NonNull IconBean bean) {
TextTag.Builder builder = new TextTag.Builder()
.text(iconBean.getLabel() != null ? iconBean.getLabel() : iconBean.getName())
.bgColor(Color.GRAY);
if (!bean.isRecorded()) {
builder.tag(getString(R.string.icon_tag_undefined));
} else if (!bean.isDef()) {
builder.tag(getString(R.string.icon_tag_alternative));
}
return builder.build().render();
}
@TargetApi(23)
private void saveIcon() {
if (C.SDK >= 23 && getContext().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
return;
}
int iconId = getResources().getIdentifier(iconBean.getName(), "mipmap",
getContext().getPackageName());
if (iconId == 0) {
iconId = iconBean.getId();
}
boolean ok = ExtraUtil.saveIcon(getContext(), getResources().getDrawable(iconId),
iconBean.getName());
if (ok) {
((ImageView) viewActionSave).getDrawable().mutate()
.setTint(ContextCompat.getColor(getContext(), R.color.positive));
}
GlobalToast.show(getContext(), ok ? R.string.toast_icon_saved
: R.string.toast_icon_save_failed);
}
private void sendIcon() {
IconBean.Component targetComponent = null;
for (IconBean.Component component : iconBean.getComponents()) { // TODO
if (component.isInstalled()) {
targetComponent = component;
break;
}
}
boolean ok = false;
if (targetComponent != null) {
String label = targetComponent.getLabel();
if (label == null) {
label = iconBean.getLabel();
}
if (label == null) {
label = iconBean.getName();
}
ok = ExtraUtil.sendIcon2HomeScreen(getContext(), iconBean.getId(), label,
targetComponent.getPkg(), targetComponent.getLauncher());
}
// Not .getDrawable().setTint()
((ImageView) viewActionSend2Home).getDrawable().mutate().setTint(ContextCompat
.getColor(getContext(), ok ? R.color.positive : R.color.negative));
GlobalToast.showLong(getContext(),
ok ? R.string.toast_sent_to_home : R.string.toast_failed_send_to_home);
}
private void returnPickIcon() {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeResource(getResources(), iconBean.getId());
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent();
if (bitmap != null) {
intent.putExtra("icon", bitmap);
intent.putExtra("android.intent.extra.shortcut.ICON_RESOURCE", iconBean.getId());
intent.setData(Uri.parse("android.resource://" + getContext().getPackageName()
+ "/" + String.valueOf(iconBean.getId())));
getActivity().setResult(Activity.RESULT_OK, intent);
} else {
getActivity().setResult(Activity.RESULT_CANCELED, intent);
}
getActivity().finish();
}
class ExtractRawIconTask extends AsyncTask<String, String, Drawable> {
@Override
protected Drawable doInBackground(String... strings) {
if (!isAdded()) {
return null;
}
PackageManager packageManager = getContext().getPackageManager();
for (IconBean.Component component : iconBean.getComponents()) {
if (!component.isInstalled()) {
continue;
}
Drawable icon = PkgUtil.getIcon(packageManager,
component.getPkg(), component.getLauncher());
if (icon != null) {
return icon;
}
}
return null;
}
@Override
protected void onPostExecute(Drawable drawable) {
super.onPostExecute(drawable);
if (!isAdded()) {
return;
}
if (drawable == null) {
isAppInstalled = false;
return;
}
((ImageView) iconViewSmall.findViewById(R.id.iv_icon_small)).setImageDrawable(drawable);
iconViewSmall.postDelayed(new Runnable() {
@Override
public void run() {
iconGridView.setVisibility(View.VISIBLE);
iconViewSmall.setVisibility(View.VISIBLE);
}
}, 100);
}
}
public static IconDialog newInstance(IconBean bean, boolean isPick) {
IconDialog dialog = new IconDialog();
Bundle bundle = new Bundle();
bundle.putSerializable("bean", bean);
bundle.putBoolean("pick", isPick);
dialog.setArguments(bundle);
return dialog;
}
}
| 5,621 |
369 | <gh_stars>100-1000
/*--------------------------------------------------------------------
Copyright(c) 2015 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Intel Corporation nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------*/
#ifndef __GPIO_I2C_H__
#define __GPIO_I2C_H__
#ifdef __cplusplus
extern "C" {
#endif
//---------------------------------------------------------------------
// Any required includes
//---------------------------------------------------------------------
#include "galileo_gen_defs.h"
//---------------------------------------------------------------------
// PCI Configuration Map Register Offsets
//---------------------------------------------------------------------
#define PCI_REG_VID 0x00 // Vendor ID Register
#define PCI_REG_DID 0x02 // Device ID Register
#define PCI_REG_PCICMD 0x04 // PCI Command Register
#define PCI_REG_PCISTS 0x06 // PCI Status Register
#define PCI_REG_RID 0x08 // PCI Revision ID Register
#define PCI_REG_PI 0x09 // Programming Interface
#define PCI_REG_SCC 0x0a // Sub Class Code Register
#define PCI_REG_BCC 0x0b // Base Class Code Register
#define PCI_REG_PMLT 0x0d // Primary Master Latency Timer
#define PCI_REG_HDR 0x0e // Header Type Register
#define PCI_REG_PBUS 0x18 // Primary Bus Number Register
#define PCI_REG_SBUS 0x19 // Secondary Bus Number Register
#define PCI_REG_SUBUS 0x1a // Subordinate Bus Number Register
#define PCI_REG_SMLT 0x1b // Secondary Master Latency Timer
#define PCI_REG_IOBASE 0x1c // I/O base Register
#define PCI_REG_IOLIMIT 0x1d // I/O Limit Register
#define PCI_REG_SECSTATUS 0x1e // Secondary Status Register
#define PCI_REG_MEMBASE 0x20 // Memory Base Register
#define PCI_REG_MEMLIMIT 0x22 // Memory Limit Register
#define PCI_REG_PRE_MEMBASE 0x24 // Prefetchable memory Base register
#define PCI_REG_PRE_MEMLIMIT 0x26 // Prefetchable memory Limit register
#define PCI_REG_SVID0 0x2c // Subsystem Vendor ID low byte
#define PCI_REG_SVID1 0x2d // Subsystem Vendor ID high byte
#define PCI_REG_SID0 0x2e // Subsystem ID low byte
#define PCI_REG_SID1 0x2f // Subsystem ID high byte
#define PCI_REG_IOBASE_U 0x30 // I/O base Upper Register
#define PCI_REG_IOLIMIT_U 0x32 // I/O Limit Upper Register
#define PCI_REG_INTLINE 0x3c // Interrupt Line Register
#define PCI_REG_BRIDGE_CNTL 0x3e // Bridge Control Register
#define IO_PCI_ADDRESS(bus, dev, fn, reg) \
(0x80000000 | (bus << 16) | (dev << 11) | (fn << 8) | (reg & ~3))
//---------------------------------------------------------------------
// PCI Read/Write IO Data
//---------------------------------------------------------------------
#define IO_PCI_ADDRESS_PORT 0xcf8
#define IO_PCI_DATA_PORT 0xcfc
//---------------------------------------------------------------------
// GPIO structures
//---------------------------------------------------------------------
struct __attribute__ ((__packed__)) BOARD_GPIO_CONTROLLER_CONFIG
{
uint32_t PortADR; ///< Value for IOH REG GPIO_SWPORTA_DR.
uint32_t PortADir; ///< Value for IOH REG GPIO_SWPORTA_DDR.
uint32_t IntEn; ///< Value for IOH REG GPIO_INTEN.
uint32_t IntMask; ///< Value for IOH REG GPIO_INTMASK.
uint32_t IntType; ///< Value for IOH REG GPIO_INTTYPE_LEVEL.
uint32_t IntPolarity; ///< Value for IOH REG GPIO_INT_POLARITY.
uint32_t Debounce; ///< Value for IOH REG GPIO_DEBOUNCE.
uint32_t LsSync; ///< Value for IOH REG GPIO_LS_SYNC.
};
struct __attribute__ ((__packed__)) BOARD_LEGACY_GPIO_CONFIG
{
uint32_t CoreWellEnable; ///< Value for QNC NC Reg R_QNC_GPIO_CGEN_CORE_WELL.
uint32_t CoreWellIoSelect; ///< Value for QNC NC Reg R_QNC_GPIO_CGIO_CORE_WELL.
uint32_t CoreWellLvlForInputOrOutput; ///< Value for QNC NC Reg R_QNC_GPIO_CGLVL_CORE_WELL.
uint32_t CoreWellTriggerPositiveEdge; ///< Value for QNC NC Reg R_QNC_GPIO_CGTPE_CORE_WELL.
uint32_t CoreWellTriggerNegativeEdge; ///< Value for QNC NC Reg R_QNC_GPIO_CGTNE_CORE_WELL.
uint32_t CoreWellGPEEnable; ///< Value for QNC NC Reg R_QNC_GPIO_CGGPE_CORE_WELL.
uint32_t CoreWellSMIEnable; ///< Value for QNC NC Reg R_QNC_GPIO_CGSMI_CORE_WELL.
uint32_t CoreWellTriggerStatus; ///< Value for QNC NC Reg R_QNC_GPIO_CGTS_CORE_WELL.
uint32_t CoreWellNMIEnable; ///< Value for QNC NC Reg R_QNC_GPIO_CGNMIEN_CORE_WELL.
uint32_t ResumeWellEnable; ///< Value for QNC NC Reg R_QNC_GPIO_RGEN_RESUME_WELL.
uint32_t ResumeWellIoSelect; ///< Value for QNC NC Reg R_QNC_GPIO_RGIO_RESUME_WELL.
uint32_t ResumeWellLvlForInputOrOutput;///< Value for QNC NC Reg R_QNC_GPIO_RGLVL_RESUME_WELL.
uint32_t ResumeWellTriggerPositiveEdge;///< Value for QNC NC Reg R_QNC_GPIO_RGTPE_RESUME_WELL.
uint32_t ResumeWellTriggerNegativeEdge;///< Value for QNC NC Reg R_QNC_GPIO_RGTNE_RESUME_WELL.
uint32_t ResumeWellGPEEnable; ///< Value for QNC NC Reg R_QNC_GPIO_RGGPE_RESUME_WELL.
uint32_t ResumeWellSMIEnable; ///< Value for QNC NC Reg R_QNC_GPIO_RGSMI_RESUME_WELL.
uint32_t ResumeWellTriggerStatus; ///< Value for QNC NC Reg R_QNC_GPIO_RGTS_RESUME_WELL.
uint32_t ResumeWellNMIEnable; ///< Value for QNC NC Reg R_QNC_GPIO_RGNMIEN_RESUME_WELL.
} ;
//---------------------------------------------------------------------
// GPIO definitions
//---------------------------------------------------------------------
#define GALILEO_GEN2_GPIO_CONTROLLER_INITIALIZER {0x05, 0x05, 0, 0, 0, 0, 0, 0}
#define GALILEO_GEN2_LEGACY_GPIO_INITIALIZER {0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x03, 0x00, 0x3f, 0x1c, 0x02, 0x00, 0x00, \
0x00, 0x00, 0x3f, 0x00}
#define PLATFORM_GPIO_CONTROLLER_CONFIG_DEFINITION \
/* EFI_PLATFORM_TYPE - Galileo Gen 2 */ \
GALILEO_GEN2_GPIO_CONTROLLER_INITIALIZER ,\
#define PLATFORM_LEGACY_GPIO_CONFIG_DEFINITION \
/* EFI_PLATFORM_TYPE - Galileo Gen 2 */ \
GALILEO_GEN2_LEGACY_GPIO_INITIALIZER , \
#define IOH_I2C_GPIO_BUS_NUMBER 0x00
#define IOH_I2C_GPIO_DEVICE_NUMBER 0x15
#define IOH_I2C_GPIO_FUNCTION_NUMBER 0x02
#define INTEL_VENDOR_ID 0x8086
#define V_IOH_I2C_GPIO_VENDOR_ID INTEL_VENDOR_ID
#define V_IOH_I2C_GPIO_DEVICE_ID 0x0934
#define R_IOH_I2C_MEMBAR 0x10
#define R_IOH_GPIO_MEMBAR 0x14
#define GPIO_SWPORTA_DR 0x00
#define GPIO_SWPORTA_DDR 0x04
#define GPIO_SWPORTB_DR 0x0C
#define GPIO_SWPORTB_DDR 0x10
#define GPIO_SWPORTC_DR 0x18
#define GPIO_SWPORTC_DDR 0x1C
#define GPIO_SWPORTD_DR 0x24
#define GPIO_SWPORTD_DDR 0x28
#define GPIO_INTEN 0x30
#define GPIO_INTMASK 0x34
#define GPIO_INTTYPE_LEVEL 0x38
#define GPIO_INT_POLARITY 0x3C
#define GPIO_INTSTATUS 0x40
#define GPIO_RAW_INTSTATUS 0x44
#define GPIO_DEBOUNCE 0x48
#define GPIO_PORTA_EOI 0x4C
#define GPIO_EXT_PORTA 0x50
#define GPIO_EXT_PORTB 0x54
#define GPIO_EXT_PORTC 0x58
#define GPIO_EXT_PORTD 0x5C
#define GPIO_LS_SYNC 0x60
#define GPIO_CONFIG_REG2 0x70
#define GPIO_CONFIG_REG1 0x74
//---------------------------------------------------------------------
// GPIO defines for cypress chip
//---------------------------------------------------------------------
#define PCAL9555_REG_OUT_PORT0 0x02
#define PCAL9555_REG_OUT_PORT1 0x03
#define PCAL9555_REG_CFG_PORT0 0x06
#define PCAL9555_REG_CFG_PORT1 0x07
#define PCAL9555_REG_PULL_EN_PORT0 0x46
#define PCAL9555_REG_PULL_EN_PORT1 0x47
//---------------------------------------------------------------------
// Three IO Expanders at fixed addresses on Galileo Gen2.
//---------------------------------------------------------------------
#define GALILEO_GEN2_IOEXP0_7BIT_SLAVE_ADDR 0x25
#define GALILEO_GEN2_IOEXP1_7BIT_SLAVE_ADDR 0x26
#define GALILEO_GEN2_IOEXP2_7BIT_SLAVE_ADDR 0x27
//---------------------------------------------------------------------
// Legacy GPIO defines
//---------------------------------------------------------------------
#define LEGACY_GPIO_BUS_NUMBER 0
#define LEGACY_GPIO_DEVICE_NUMBER 31
#define LEGACY_GPIO_FUNCTION_NUMBER 0
#define R_QNC_LPC_GBA_BASE 0x44
#define B_QNC_LPC_GPA_BASE_MASK 0x0000FFC0
//---------------------------------------------------------------------
// I2C structures and enums
//---------------------------------------------------------------------
typedef struct
{
/// The I2C hardware address to which the I2C device is preassigned or allocated.
uintn_t I2CDeviceAddress : 10;
} I2C_DEVICE_ADDRESS;
typedef enum _I2C_ADDR_MODE
{
EfiI2CSevenBitAddrMode,
EfiI2CTenBitAddrMode,
} I2C_ADDR_MODE;
//---------------------------------------------------------------------
// I2C definitions
//---------------------------------------------------------------------
#define GALILEO_GEN2_FLASH_UPDATE_LED_RESUMEWELL_GPIO 5
#define R_QNC_GPIO_CGEN_CORE_WELL 0x00
#define R_QNC_GPIO_CGIO_CORE_WELL 0x04
#define R_QNC_GPIO_CGLVL_CORE_WELL 0x08
#define R_QNC_GPIO_CGTPE_CORE_WELL 0x0C // Core well GPIO Trigger Positive Edge Enable
#define R_QNC_GPIO_CGTNE_CORE_WELL 0x10 // Core well GPIO Trigger Negative Edge Enable
#define R_QNC_GPIO_CGGPE_CORE_WELL 0x14 // Core well GPIO GPE Enable
#define R_QNC_GPIO_CGSMI_CORE_WELL 0x18 // Core well GPIO SMI Enable
#define R_QNC_GPIO_CGTS_CORE_WELL 0x1C // Core well GPIO Trigger Status
#define R_QNC_GPIO_RGEN_RESUME_WELL 0x20
#define R_QNC_GPIO_RGIO_RESUME_WELL 0x24
#define R_QNC_GPIO_RGLVL_RESUME_WELL 0x28
#define R_QNC_GPIO_RGTPE_RESUME_WELL 0x2C // Resume well GPIO Trigger Positive Edge Enable
#define R_QNC_GPIO_RGTNE_RESUME_WELL 0x30 // Resume well GPIO Trigger Negative Edge Enable
#define R_QNC_GPIO_RGGPE_RESUME_WELL 0x34 // Resume well GPIO GPE Enable
#define R_QNC_GPIO_RGSMI_RESUME_WELL 0x38 // Resume well GPIO SMI Enable
#define R_QNC_GPIO_RGTS_RESUME_WELL 0x3C // Resume well GPIO Trigger Status
#define R_QNC_GPIO_CNMIEN_CORE_WELL 0x40 // Core well GPIO NMI Enable
#define R_QNC_GPIO_RNMIEN_RESUME_WELL 0x44 // Resume well GPIO NMI Enable
#define B_IOH_I2C_GPIO_MEMBAR_ADDR_MASK 0xFFFFF000 // [31:12].
#define I2C_REG_CLR_START_DET 0x64 // Clear START DET Interrupt Register
#define I2C_REG_CLR_STOP_DET 0x60 // Clear STOP DET Interrupt Register
#define B_I2C_REG_CLR_START_DET (BIT0) // Clear START DET Interrupt Register
#define B_I2C_REG_CLR_STOP_DET (BIT0) // Clear STOP DET Interrupt Register
#define B_I2C_REG_CON_10BITADD_MASTER (BIT4) // 7-bit addressing (0) or 10-bit addressing (1)
#define B_I2C_REG_CON_SPEED (BIT2+BIT1) // standard mode (01) or fast mode (10)
#define I2C_REG_CON 0x00 // Control Register
#define I2C_REG_ENABLE 0x6C // Enable Register
#define B_I2C_REG_ENABLE (BIT0) // Enable (1) or disable (0) I2C Controller
#define I2C_REG_ENABLE_STATUS 0x9C // Enable Status Register
#define I2C_REG_CLR_INT 0x40 // Clear Combined and Individual Interrupt Register
#define MAX_T_POLL_COUNT 100
#define TI2C_POLL 25 // microseconds
#define I2C_REG_CLR_RX_OVER 0x48 // Clear RX Over Interrupt Register
#define I2C_REG_CLR_TX_OVER 0x4C // Clear TX Over Interrupt Register
#define I2C_REG_CLR_TX_ABRT 0x54 // Clear TX ABRT Interrupt Register
#define I2C_FIFO_SIZE 16
#define I2C_REG_TAR 0x04 // Master Target Address Register
#define B_I2C_REG_TAR (BIT9+BIT8+BIT7+BIT6+BIT5+BIT4+BIT3+BIT2+BIT1+BIT0) // Master Target Address bits
#define I2C_REG_DATA_CMD 0x10 // Data Buffer and Command Register
#define B_I2C_REG_DATA_CMD_RW (BIT8) // Data Buffer and Command Register Read/Write bit
#define I2C_REG_RXFLR 0x78 // Receive FIFO Level Register
#define B_I2C_REG_DATA_CMD_STOP (BIT9) // Data Buffer and Command Register STOP bit
#define I2C_REG_RAW_INTR_STAT 0x34 // Raw Interrupt Status Register
#define I2C_REG_RAW_INTR_STAT_RX_OVER (BIT1) // Raw Interrupt Status Register RX Overflow signal status.
#define I2C_REG_RAW_INTR_STAT_RX_UNDER (BIT0) // Raw Interrupt Status Register RX Underflow signal status.
#define I2C_REG_CLR_RX_UNDER 0x44 // Clear RX Under Interrupt Register
#define MAX_STOP_DET_POLL_COUNT ((1000 * 1000) / TI2C_POLL) // Extreme for expected Stop detect.
#define I2C_REG_RAW_INTR_STAT_TX_ABRT (BIT6) // Raw Interrupt Status Register TX Abort status.
#define I2C_REG_RAW_INTR_STAT_TX_OVER (BIT3) // Raw Interrupt Status Register TX Overflow signal status.
#define I2C_REG_RAW_INTR_STAT_STOP_DET (BIT9) // Raw Interrupt Status Register STOP_DET signal status.
//---------------------------------------------------------------------
// GPIO Prototypes
//---------------------------------------------------------------------
#define GPIO_OUTPUT (0)
#define GPIO_INPUT (1)
#define LOW (0)
#define HIGH (1)
#define GPIO_NUMBER (7UL)
void vMicroSecondDelay(uint32_t DelayTime);
void vMilliSecondDelay(uint32_t DelayTime);
void vGalileoInitializeLegacyGPIO(void);
void vGalileoInitializeGpioController(void);
void vGalileoLegacyGPIOInitializationForLED(void);
void vGalileoSetGPIOBitDirection(uint32_t GPIONumber, uint32_t Direction);
void vGalileoSetGPIOBitLevel(uint32_t GPIONumber, uint32_t Level);
void vGalileoBlinkLEDUsingLegacyGPIO(uint32_t Level);
#ifdef __cplusplus
} /* extern C */
#endif
#endif /* __GPIO_I2C_H__ */
| 7,099 |
653 | /** //
* Copyright (c) 2015-2018, The Kovri I2P Router Project //
* //
* All rights reserved. //
* //
* Redistribution and use in source and binary forms, with or without modification, are //
* permitted provided that the following conditions are met: //
* //
* 1. Redistributions of source code must retain the above copyright notice, this list of //
* conditions and the following disclaimer. //
* //
* 2. Redistributions in binary form must reproduce the above copyright notice, this list //
* of conditions and the following disclaimer in the documentation and/or other //
* materials provided with the distribution. //
* //
* 3. Neither the name of the copyright holder nor the names of its contributors may be //
* used to endorse or promote products derived from this software without specific //
* prior written permission. //
* //
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY //
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF //
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL //
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, //
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS //
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, //
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF //
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //
*/
#include "core/util/byte_stream.h"
#include <boost/asio/ip/address.hpp>
#include <cassert>
#include <cstring>
#include <iomanip>
#include <memory>
#include <sstream>
#include <stdexcept>
#include "core/util/log.h"
// TODO(anonimal): a secure bytestream implementation that ensures wiped memory when needed.
// Otherwise, and preferably, use existing standard library containers with crypto++.
// TODO(unassigned): std::bitset implementation, see #823
namespace kovri
{
namespace core
{
// Input
ByteStream::ByteStream(const std::uint8_t* data, const std::size_t len)
: m_DataPtr(const_cast<std::uint8_t*>(data)), m_Length(len), m_Counter{}
// TODO(anonimal): remove const cast!
{
assert(data || len);
if (!data)
throw std::invalid_argument("ByteStream: null data");
if (!len)
throw std::length_error("ByteStream: null length");
}
// Output
ByteStream::ByteStream(std::uint8_t* data, const std::size_t len)
: m_DataPtr(data), m_Length(len), m_Counter{}
{
assert(data || len);
if (!data)
throw std::invalid_argument("ByteStream: null data");
if (!len)
throw std::length_error("ByteStream: null length");
}
ByteStream::ByteStream(const std::size_t len) : m_Length(len), m_Counter{}
{
assert(len);
if (!len)
throw std::length_error("ByteStream: null length");
m_Data.reserve(len);
m_DataPtr = m_Data.data();
}
void ByteStream::Advance(const std::size_t len)
{
assert(len && len <= m_Length);
if (!len || len > m_Length)
throw std::length_error("ByteStream: invalid length advancement");
m_DataPtr += len;
m_Counter += len;
m_Length -= len;
}
// Input
InputByteStream::InputByteStream(
const std::uint8_t* data,
const std::size_t len)
: ByteStream(data, len)
{
}
std::uint8_t* InputByteStream::ReadBytes(const std::size_t len)
{
std::uint8_t* ptr = m_DataPtr;
Advance(len);
return ptr;
}
void InputByteStream::SkipBytes(const std::size_t len)
{
Advance(len);
}
// Output
OutputByteStream::OutputByteStream(std::uint8_t* data, const std::size_t len)
: ByteStream(data, len)
{
}
OutputByteStream::OutputByteStream(const std::size_t len) : ByteStream(len) {}
void OutputByteStream::WriteData(
const std::uint8_t* data,
const std::size_t len,
const bool allow_null_data)
{
assert((data && allow_null_data) || len);
if (!data && !allow_null_data)
throw std::invalid_argument("OutputByteStream: null data");
if (!len)
throw std::length_error("OutputByteStream: null length");
std::uint8_t* ptr = m_DataPtr;
Advance(len);
if (!data)
std::memset(ptr, 0, len);
else
std::memcpy(ptr, data, len);
}
void OutputByteStream::SkipBytes(const std::size_t len)
{
WriteData(nullptr, len, true);
}
// Misc
const std::string GetFormattedHex(
const std::uint8_t* data,
const std::size_t size)
{
std::ostringstream hex;
hex << "\n\t"
<< " | ";
std::size_t count{}, sub_count{};
for (std::size_t i = 0; i < size; i++)
{
hex << std::hex << std::setfill('0') << std::setw(2)
<< static_cast<std::uint16_t>(data[i]) << " ";
count++;
if (count == 32 || (i == size - 1))
{
hex << " |"
<< "\n\t";
count = 0;
}
sub_count++;
if (sub_count == 8 && (i != size - 1))
{
hex << " | ";
sub_count = 0;
}
}
return hex.str() + "\n";
}
std::vector<std::uint8_t> AddressToByteVector(
const boost::asio::ip::address& address)
{
bool is_v4(address.is_v4());
std::vector<std::uint8_t> data(is_v4 ? 4 : 16);
std::memcpy(
data.data(),
is_v4 ? address.to_v4().to_bytes().data()
: address.to_v6().to_bytes().data(),
data.size());
return data;
}
boost::asio::ip::address BytesToAddress(
const std::uint8_t* host,
const std::uint8_t size)
{
boost::asio::ip::address address;
assert(size == 4 || size == 16);
switch (size)
{
case 4:
{
boost::asio::ip::address_v4::bytes_type bytes;
std::memcpy(bytes.data(), host, size);
address = boost::asio::ip::address_v4(bytes);
}
break;
case 16:
{
boost::asio::ip::address_v6::bytes_type bytes;
std::memcpy(bytes.data(), host, size);
address = boost::asio::ip::address_v6(bytes);
}
break;
default:
throw std::length_error("invalid address size");
};
return address;
}
} // namespace core
} // namespace kovri
| 3,392 |
427 | """
Test some expressions involving STL data types.
"""
from __future__ import print_function
import unittest2
import os
import time
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class STLTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Find the line number to break inside main().
self.source = 'main.cpp'
self.line = line_number(
self.source, '// Set break point at this line.')
@expectedFailureAll(bugnumber="rdar://problem/10400981")
def test(self):
"""Test some expressions involving STL data types."""
self.build()
exe = os.path.join(os.getcwd(), "a.out")
# The following two lines, if uncommented, will enable loggings.
#self.ci.HandleCommand("log enable -f /tmp/lldb.log lldb default", res)
# self.assertTrue(res.Succeeded())
self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
# rdar://problem/8543077
# test/stl: clang built binaries results in the breakpoint locations = 3,
# is this a problem with clang generated debug info?
lldbutil.run_break_set_by_file_and_line(
self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
self.runCmd("run", RUN_SUCCEEDED)
# Stop at 'std::string hello_world ("Hello World!");'.
self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
substrs=['main.cpp:%d' % self.line,
'stop reason = breakpoint'])
# The breakpoint should have a hit count of 1.
self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
substrs=[' resolved, hit count = 1'])
# Now try some expressions....
self.runCmd(
'expr for (int i = 0; i < hello_world.length(); ++i) { (void)printf("%c\\n", hello_world[i]); }')
# rdar://problem/10373783
# rdar://problem/10400981
self.expect('expr associative_array.size()',
substrs=[' = 3'])
self.expect('expr associative_array.count(hello_world)',
substrs=[' = 1'])
self.expect('expr associative_array[hello_world]',
substrs=[' = 1'])
self.expect('expr associative_array["hello"]',
substrs=[' = 2'])
@expectedFailureAll(
compiler="icc",
bugnumber="ICC (13.1, 14-beta) do not emit DW_TAG_template_type_parameter.")
@add_test_categories(['pyapi'])
def test_SBType_template_aspects(self):
"""Test APIs for getting template arguments from an SBType."""
self.build()
exe = os.path.join(os.getcwd(), 'a.out')
# Create a target by the debugger.
target = self.dbg.CreateTarget(exe)
self.assertTrue(target, VALID_TARGET)
# Create the breakpoint inside function 'main'.
breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
self.assertTrue(breakpoint, VALID_BREAKPOINT)
# Now launch the process, and do not stop at entry point.
process = target.LaunchSimple(
None, None, self.get_process_working_directory())
self.assertTrue(process, PROCESS_IS_VALID)
# Get Frame #0.
self.assertTrue(process.GetState() == lldb.eStateStopped)
thread = lldbutil.get_stopped_thread(
process, lldb.eStopReasonBreakpoint)
self.assertTrue(
thread.IsValid(),
"There should be a thread stopped due to breakpoint condition")
frame0 = thread.GetFrameAtIndex(0)
# Get the type for variable 'associative_array'.
associative_array = frame0.FindVariable('associative_array')
self.DebugSBValue(associative_array)
self.assertTrue(associative_array, VALID_VARIABLE)
map_type = associative_array.GetType()
self.DebugSBType(map_type)
self.assertTrue(map_type, VALID_TYPE)
num_template_args = map_type.GetNumberOfTemplateArguments()
self.assertTrue(num_template_args > 0)
# We expect the template arguments to contain at least 'string' and
# 'int'.
expected_types = {'string': False, 'int': False}
for i in range(num_template_args):
t = map_type.GetTemplateArgumentType(i)
self.DebugSBType(t)
self.assertTrue(t, VALID_TYPE)
name = t.GetName()
if 'string' in name:
expected_types['string'] = True
elif 'int' == name:
expected_types['int'] = True
# Check that both entries of the dictionary have 'True' as the value.
self.assertTrue(all(expected_types.values()))
| 2,133 |
561 | {
"blurb": "Implement the `accumulate` operation, which, given a collection and an operation to perform on each element of the collection, returns a new collection containing the result of applying that operation to each element of the input collection.",
"authors": [
"zilkey"
],
"contributors": [
"alebaffa",
"amullins83",
"bitfield",
"brugnara",
"ekingery",
"ernesto-jimenez",
"ferhatelmas",
"hilary",
"kytrinyx",
"leenipper",
"mmozuras",
"ooransoy",
"petertseng",
"robphoenix",
"sebito91",
"strangeman",
"tleen",
"tompao"
],
"files": {
"solution": [
"accumulate.go"
],
"test": [
"accumulate_test.go"
],
"example": [
".meta/example.go"
]
},
"source": "Conversation with <NAME> II",
"source_url": "https://twitter.com/jeg2"
}
| 377 |
829 | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
//#import "NSObject.h"
//#import "DVTInvalidation.h"
//#import "IDEDebugNavigableModel.h"
#import <Cocoa/Cocoa.h>
@class DVTStackBacktrace, IDECodeModule, IDELaunchSession, IDEThread, NSNumber, NSString, NSURL;
@interface IDEStackFrame : NSObject /*<IDEDebugNavigableModel, DVTInvalidation>*/
{
BOOL _hasSymbols;
BOOL _recorded;
BOOL _causedCrash;
NSString *_associatedProcessUUID;
NSString *_displayName;
NSString *_filePath;
IDEThread *_parentThread;
NSString *_name;
NSNumber *_frameNumber;
NSNumber *_framePointer;
NSURL *_fileURL;
NSNumber *_lineNumber;
IDECodeModule *_module;
}
+ (id)keyPathsForValuesAffectingDisplayName;
+ (id)compressedStackFrames:(id)arg1 usingCompressionValue:(long long)arg2;
+ (void)initialize;
@property(nonatomic, getter=hasCausedCrash) BOOL causedCrash; // @synthesize causedCrash=_causedCrash;
@property(nonatomic, getter=isRecorded) BOOL recorded; // @synthesize recorded=_recorded;
@property(retain, nonatomic) IDECodeModule *module; // @synthesize module=_module;
@property(copy, nonatomic) NSNumber *lineNumber; // @synthesize lineNumber=_lineNumber;
@property(copy, nonatomic) NSURL *fileURL; // @synthesize fileURL=_fileURL;
@property(nonatomic) BOOL hasSymbols; // @synthesize hasSymbols=_hasSymbols;
@property(copy, nonatomic) NSNumber *framePointer; // @synthesize framePointer=_framePointer;
@property(copy, nonatomic) NSNumber *frameNumber; // @synthesize frameNumber=_frameNumber;
@property(copy, nonatomic) NSString *name; // @synthesize name=_name;
@property(retain, nonatomic) IDEThread *parentThread; // @synthesize parentThread=_parentThread;
@property(readonly, copy) NSString *associatedProcessUUID; // @synthesize associatedProcessUUID=_associatedProcessUUID;
//- (void).cxx_destruct;
- (void)primitiveInvalidate;
@property(readonly, nonatomic) NSString *filePath; // @synthesize filePath=_filePath;
@property(readonly, nonatomic) NSString *displayName; // @synthesize displayName=_displayName;
@property(readonly) IDELaunchSession *launchSession;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
- (BOOL)isEqual:(id)arg1;
- (id)initWithParentThread:(id)arg1 frameNumber:(id)arg2 framePointer:(id)arg3 name:(id)arg4;
// Remaining properties
@property(retain) DVTStackBacktrace *creationBacktrace;
@property(readonly, copy) NSString *debugDescription;
@property(readonly) DVTStackBacktrace *invalidationBacktrace;
@property(readonly) Class superclass;
@property(readonly, nonatomic, getter=isValid) BOOL valid;
@end
| 953 |
14,668 | <filename>chrome/common/pdf_util.cc
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/pdf_util.h"
#include "base/metrics/histogram_macros.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/renderer_resources.h"
#include "components/strings/grit/components_strings.h"
#include "extensions/buildflags/buildflags.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/jstemplate_builder.h"
#include "ui/base/webui/web_ui_util.h"
#include "url/gurl.h"
#include "url/origin.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "extensions/common/constants.h"
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
void ReportPDFLoadStatus(PDFLoadStatus status) {
UMA_HISTOGRAM_ENUMERATION("PDF.LoadStatus", status,
PDFLoadStatus::kPdfLoadStatusCount);
}
std::string GetPDFPlaceholderHTML(const GURL& pdf_url) {
std::string template_html =
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
IDR_PDF_PLUGIN_HTML);
webui::AppendWebUiCssTextDefaults(&template_html);
base::DictionaryValue values;
values.SetString("fileName", pdf_url.ExtractFileName());
values.SetString("open", l10n_util::GetStringUTF8(IDS_ACCNAME_OPEN));
values.SetString("pdfUrl", pdf_url.spec());
return webui::GetI18nTemplateHtml(template_html, &values);
}
bool IsPdfExtensionOrigin(const url::Origin& origin) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
return origin.scheme() == extensions::kExtensionScheme &&
origin.host() == extension_misc::kPdfExtensionId;
#else
return false;
#endif
}
bool IsPdfInternalPluginAllowedOrigin(const url::Origin& origin) {
if (IsPdfExtensionOrigin(origin))
return true;
// Allow embedding the internal PDF plugin in chrome://print.
if (origin == url::Origin::Create(GURL(chrome::kChromeUIPrintURL)))
return true;
// Only allow the PDF plugin in the known, trustworthy origins that are
// allowlisted above. See also https://crbug.com/520422 and
// https://crbug.com/1027173.
return false;
}
| 795 |
1,457 | <filename>flash/core/data/utilities/classification.py
# Copyright The PyTorch Lightning 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.
from enum import auto, Enum
from functools import reduce
from typing import Any, cast, List, Optional, Tuple, Union
import numpy as np
import torch
from flash.core.data.utilities.sort import sorted_alphanumeric
def _is_list_like(x: Any) -> bool:
try:
_ = x[0]
_ = len(x)
return True
except (TypeError, IndexError): # Single element tensors raise an `IndexError`
return False
def _as_list(x: Union[List, torch.Tensor, np.ndarray]) -> List:
if torch.is_tensor(x) or isinstance(x, np.ndarray):
return cast(List, x.tolist())
return x
def _strip(x: str) -> str:
return x.strip(", ")
class TargetMode(Enum):
"""The ``TargetMode`` Enum describes the different supported formats for targets in Flash."""
MULTI_TOKEN = auto()
MULTI_NUMERIC = auto()
MUTLI_COMMA_DELIMITED = auto()
MUTLI_SPACE_DELIMITED = auto()
MULTI_BINARY = auto()
SINGLE_TOKEN = auto()
SINGLE_NUMERIC = auto()
SINGLE_BINARY = auto()
@classmethod
def from_target(cls, target: Any) -> "TargetMode":
"""Determine the ``TargetMode`` for a given target.
Multi-label targets can be:
* Comma delimited string - ``TargetMode.MUTLI_COMMA_DELIMITED`` (e.g. ["blue,green", "red"])
* List of strings - ``TargetMode.MULTI_TOKEN`` (e.g. [["blue", "green"], ["red"]])
* List of numbers - ``TargetMode.MULTI_NUMERIC`` (e.g. [[0, 1], [2]])
* Binary list - ``TargetMode.MULTI_BINARY`` (e.g. [[1, 1, 0], [0, 0, 1]])
Single-label targets can be:
* Single string - ``TargetMode.SINGLE_TOKEN`` (e.g. ["blue", "green", "red"])
* Single number - ``TargetMode.SINGLE_NUMERIC`` (e.g. [0, 1, 2])
* One-hot binary list - ``TargetMode.SINGLE_BINARY`` (e.g. [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
Args:
target: A target that is one of: a single target, a list of targets, a comma delimited string.
"""
if isinstance(target, str):
target = _strip(target)
# TODO: This could be a dangerous assumption if people happen to have a label that contains a comma or space
if "," in target:
return TargetMode.MUTLI_COMMA_DELIMITED
elif " " in target:
return TargetMode.MUTLI_SPACE_DELIMITED
else:
return TargetMode.SINGLE_TOKEN
elif _is_list_like(target):
if isinstance(target[0], str):
return TargetMode.MULTI_TOKEN
elif len(target) > 1:
if all(t == 0 or t == 1 for t in target):
if sum(target) == 1:
return TargetMode.SINGLE_BINARY
return TargetMode.MULTI_BINARY
return TargetMode.MULTI_NUMERIC
return TargetMode.SINGLE_NUMERIC
@property
def multi_label(self) -> bool:
return any(
[
self is TargetMode.MUTLI_COMMA_DELIMITED,
self is TargetMode.MUTLI_SPACE_DELIMITED,
self is TargetMode.MULTI_NUMERIC,
self is TargetMode.MULTI_TOKEN,
self is TargetMode.MULTI_BINARY,
]
)
@property
def numeric(self) -> bool:
return any(
[
self is TargetMode.MULTI_NUMERIC,
self is TargetMode.SINGLE_NUMERIC,
]
)
@property
def binary(self) -> bool:
return any(
[
self is TargetMode.MULTI_BINARY,
self is TargetMode.SINGLE_BINARY,
]
)
_RESOLUTION_MAPPING = {
TargetMode.MULTI_BINARY: [TargetMode.MULTI_NUMERIC],
TargetMode.SINGLE_BINARY: [TargetMode.MULTI_BINARY, TargetMode.MULTI_NUMERIC],
TargetMode.SINGLE_TOKEN: [TargetMode.MUTLI_COMMA_DELIMITED, TargetMode.MUTLI_SPACE_DELIMITED],
TargetMode.SINGLE_NUMERIC: [TargetMode.MULTI_NUMERIC],
}
def _resolve_target_mode(a: TargetMode, b: TargetMode) -> TargetMode:
"""The purpose of the addition here is to reduce the ``TargetMode`` over multiple targets. If one target mode
is a comma delimited string and the other a single string then their sum will be comma delimited. If one target
is multi binary and the other is single binary, their sum will be multi binary. Otherwise, we expect that both
target modes are the same.
Raises:
ValueError: If the two target modes could not be resolved to a single mode.
"""
if a is b:
return a
elif a in _RESOLUTION_MAPPING and b in _RESOLUTION_MAPPING[a]:
return b
elif b in _RESOLUTION_MAPPING and a in _RESOLUTION_MAPPING[b]:
return a
raise ValueError(
"Found inconsistent target modes. All targets should be either: single values, lists of values, or "
"comma-delimited strings."
)
def get_target_mode(targets: List[Any]) -> TargetMode:
"""Aggregate the ``TargetMode`` for a list of targets.
Args:
targets: The list of targets to get the label mode for.
Returns:
The total ``TargetMode`` of the list of targets.
"""
targets = _as_list(targets)
return reduce(_resolve_target_mode, [TargetMode.from_target(target) for target in targets])
class TargetFormatter:
"""A ``TargetFormatter`` is used to convert targets of a given type to a standard format required by the
task."""
def __call__(self, target: Any) -> Any:
return self.format(target)
def format(self, target: Any) -> Any:
return _as_list(target)
class SingleNumericTargetFormatter(TargetFormatter):
def format(self, target: Any) -> Any:
result = super().format(target)
if _is_list_like(result):
result = result[0]
return result
class SingleLabelTargetFormatter(TargetFormatter):
def __init__(self, labels: List[Any]):
self.label_to_idx = {label: idx for idx, label in enumerate(labels)}
def format(self, target: Any) -> Any:
return self.label_to_idx[_strip(target[0] if not isinstance(target, str) else target)]
class MultiLabelTargetFormatter(SingleLabelTargetFormatter):
def __init__(self, labels: List[Any]):
super().__init__(labels)
self.num_classes = len(labels)
def format(self, target: Any) -> Any:
result = [0] * self.num_classes
for t in target:
idx = super().format(t)
result[idx] = 1
return result
class CommaDelimitedTargetFormatter(MultiLabelTargetFormatter):
def format(self, target: Any) -> Any:
return super().format(target.split(","))
class SpaceDelimitedTargetFormatter(MultiLabelTargetFormatter):
def format(self, target: Any) -> Any:
return super().format(target.split(" "))
class MultiNumericTargetFormatter(TargetFormatter):
def __init__(self, num_classes: int):
self.num_classes = num_classes
def format(self, target: Any) -> Any:
result = [0] * self.num_classes
for idx in target:
result[idx] = 1
return result
class OneHotTargetFormatter(TargetFormatter):
def format(self, target: Any) -> Any:
for idx, t in enumerate(target):
if t == 1:
return idx
return 0
def get_target_formatter(
target_mode: TargetMode, labels: Optional[List[Any]], num_classes: Optional[int]
) -> TargetFormatter:
"""Get the ``TargetFormatter`` object to use for the given ``TargetMode``, ``labels``, and ``num_classes``.
Args:
target_mode: The target mode to format.
labels: Labels used by the target (if available).
num_classes: The number of classes in the targets.
Returns:
The target formatter to use when formatting targets.
"""
if target_mode is TargetMode.MULTI_BINARY:
return TargetFormatter()
elif target_mode is TargetMode.SINGLE_NUMERIC:
return SingleNumericTargetFormatter()
elif target_mode is TargetMode.SINGLE_BINARY:
return OneHotTargetFormatter()
elif target_mode is TargetMode.MULTI_NUMERIC:
return MultiNumericTargetFormatter(num_classes)
elif target_mode is TargetMode.SINGLE_TOKEN:
return SingleLabelTargetFormatter(labels)
elif target_mode is TargetMode.MUTLI_COMMA_DELIMITED:
return CommaDelimitedTargetFormatter(labels)
elif target_mode is TargetMode.MUTLI_SPACE_DELIMITED:
return SpaceDelimitedTargetFormatter(labels)
return MultiLabelTargetFormatter(labels)
def get_target_details(targets: List[Any], target_mode: TargetMode) -> Tuple[Optional[List[Any]], int]:
"""Given a list of targets and their ``TargetMode``, this function determines the ``labels`` and
``num_classes``. Targets can be:
* Token-based: ``labels`` is the unique tokens, ``num_classes`` is the number of unique tokens.
* Numeric: ``labels`` is ``None`` and ``num_classes`` is the maximum value plus one.
* Binary: ``labels`` is ``None`` and ``num_classes`` is the length of the binary target.
Args:
targets: A list of targets.
target_mode: The ``TargetMode`` of the targets from ``get_target_mode``.
Returns:
(labels, num_classes): Tuple containing the inferred ``labels`` (or ``None`` if no labels could be inferred)
and ``num_classes``.
"""
targets = _as_list(targets)
if target_mode.numeric:
# Take a max over all values
if target_mode is TargetMode.MULTI_NUMERIC:
values = []
for target in targets:
values.extend(target)
else:
values = targets
num_classes = _as_list(max(values))
if _is_list_like(num_classes):
num_classes = num_classes[0]
num_classes = num_classes + 1
labels = None
elif target_mode.binary:
# Take a length
# TODO: Add a check here and error if target lengths are not all equal
num_classes = len(targets[0])
labels = None
else:
# Compute tokens
tokens = []
if target_mode is TargetMode.MUTLI_COMMA_DELIMITED:
for target in targets:
tokens.extend(target.split(","))
elif target_mode is TargetMode.MUTLI_SPACE_DELIMITED:
for target in targets:
tokens.extend(target.split(" "))
elif target_mode is TargetMode.MULTI_TOKEN:
for target in targets:
tokens.extend(target)
else:
tokens = targets
tokens = [_strip(token) for token in tokens]
labels = list(sorted_alphanumeric(set(tokens)))
num_classes = len(labels)
return labels, num_classes
| 4,776 |
14,668 | <gh_stars>1000+
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ASH_SCANNING_LORGNETTE_SCANNER_MANAGER_FACTORY_H_
#define CHROME_BROWSER_ASH_SCANNING_LORGNETTE_SCANNER_MANAGER_FACTORY_H_
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace base {
template <typename T>
struct DefaultSingletonTraits;
} // namespace base
namespace content {
class BrowserContext;
} // namespace content
namespace ash {
class LorgnetteScannerManager;
// Factory for LorgnetteScannerManager.
class LorgnetteScannerManagerFactory
: public BrowserContextKeyedServiceFactory {
public:
static LorgnetteScannerManager* GetForBrowserContext(
content::BrowserContext* context);
static LorgnetteScannerManagerFactory* GetInstance();
private:
friend struct base::DefaultSingletonTraits<LorgnetteScannerManagerFactory>;
LorgnetteScannerManagerFactory();
~LorgnetteScannerManagerFactory() override;
LorgnetteScannerManagerFactory(const LorgnetteScannerManagerFactory&) =
delete;
LorgnetteScannerManagerFactory& operator=(
const LorgnetteScannerManagerFactory&) = delete;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
bool ServiceIsCreatedWithBrowserContext() const override;
bool ServiceIsNULLWhileTesting() const override;
};
} // namespace ash
#endif // CHROME_BROWSER_ASH_SCANNING_LORGNETTE_SCANNER_MANAGER_FACTORY_H_
| 510 |
413 | <gh_stars>100-1000
package org.github.jamm;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.RuntimeMXBean;
abstract class MemoryLayoutSpecification
{
abstract int getArrayHeaderSize();
abstract int getObjectHeaderSize();
abstract int getObjectAlignment();
abstract int getReferenceSize();
abstract int getSuperclassFieldPadding();
abstract String impl();
public String toString() {
return "MemoryLayoutSpecification[" +
"getArrayHeaderSize=" + getArrayHeaderSize() +
",getObjectHeaderSize=" + getObjectHeaderSize() +
",getObjectAlignment=" + getObjectAlignment() +
",getReferenceSize=" + getReferenceSize() +
",getSuperclassFieldPadding=" + getSuperclassFieldPadding() +
",impl=" + impl() +
"]";
}
static MemoryLayoutSpecification getEffectiveMemoryLayoutSpecification() {
final String dataModel = System.getProperty("sun.arch.data.model");
if ("32".equals(dataModel)) {
// Running with 32-bit data model
return new MemoryLayoutSpecification() {
public String impl() {
return "32";
}
public int getArrayHeaderSize() {
return 12;
}
public int getObjectHeaderSize() {
return 8;
}
public int getObjectAlignment() {
return 8;
}
public int getReferenceSize() {
return 4;
}
public int getSuperclassFieldPadding() {
return 4;
}
};
}
boolean modernJvm = true;
final String strSpecVersion = System.getProperty("java.specification.version");
final boolean hasDot = strSpecVersion.indexOf('.') != -1;
if (hasDot) {
if ("1".equals(strSpecVersion.substring(0, strSpecVersion.indexOf('.')))) {
// Java 1.6, 1.7, 1.8
final String strVmVersion = System.getProperty("java.vm.version");
if (strVmVersion.startsWith("openj9"))
{
modernJvm = true;
}
else
{
final int vmVersion = Integer.parseInt(strVmVersion.substring(0, strVmVersion.indexOf('.')));
modernJvm = vmVersion >= 17;
}
}
}
final int alignment = getAlignment();
if (modernJvm) {
long maxMemory = 0;
for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) {
maxMemory += mp.getUsage().getMax();
}
if (maxMemory < 30L * 1024 * 1024 * 1024) {
// HotSpot 17.0 and above use compressed OOPs below 30GB of RAM
// total for all memory pools (yes, including code cache).
return new MemoryLayoutSpecification() {
public String impl() {
return "modern";
}
public int getArrayHeaderSize() {
return 16;
}
public int getObjectHeaderSize() {
return 12;
}
public int getObjectAlignment() {
return alignment;
}
public int getReferenceSize() {
return 4;
}
public int getSuperclassFieldPadding() {
return 4;
}
};
}
}
/* Worst case we over count. */
// In other cases, it's a 64-bit uncompressed OOPs object model
return new MemoryLayoutSpecification() {
public String impl() {
return "64";
}
public int getArrayHeaderSize() {
return 24;
}
public int getObjectHeaderSize() {
return 16;
}
public int getObjectAlignment() {
return alignment;
}
public int getReferenceSize() {
return 8;
}
public int getSuperclassFieldPadding() {
return 8;
}
};
}
// check if we have a non-standard object alignment we need to round to
private static int getAlignment() {
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
for (String arg : runtimeMxBean.getInputArguments()) {
if (arg.startsWith("-XX:ObjectAlignmentInBytes=")) {
try {
return Integer.parseInt(arg.substring("-XX:ObjectAlignmentInBytes=".length()));
} catch (Exception ignore) {}
}
}
return 8;
}
}
| 2,632 |
4,283 | /*
* Copyright 2021 Hazelcast Inc.
*
* Licensed under the Hazelcast Community License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://hazelcast.com/hazelcast-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.sql.impl.schema;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.RelDistribution;
import org.apache.calcite.rel.RelReferentialConstraint;
import org.apache.calcite.schema.Statistic;
import org.apache.calcite.util.ImmutableBitSet;
import java.util.List;
import static java.util.Collections.emptyList;
public final class UnknownStatistic implements Statistic {
public static final UnknownStatistic INSTANCE = new UnknownStatistic();
private UnknownStatistic() {
}
@Override
public Double getRowCount() {
return null;
}
@Override
public boolean isKey(ImmutableBitSet columns) {
return false;
}
@Override
public List<ImmutableBitSet> getKeys() {
return null;
}
@Override
public List<RelReferentialConstraint> getReferentialConstraints() {
return null;
}
@Override
public List<RelCollation> getCollations() {
return emptyList();
}
@Override
public RelDistribution getDistribution() {
return null;
}
}
| 540 |
364 | <reponame>Victor333Huesca/TimelineExtension
{
"name": "timeline-extension",
"version": "1.1.0",
"description": "Windows Timeline + Project Rome support for browsers.",
"scripts": {
"watch": "webpack --config webpack/webpack.dev.js --watch",
"build": "webpack --config webpack/webpack.prod.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/DominicMaas/TimelineExtension.git"
},
"author": "<NAME>",
"license": "MIT",
"bugs": {
"url": "https://github.com/DominicMaas/TimelineExtension/issues"
},
"homepage": "https://github.com/DominicMaas/TimelineExtension#readme",
"dependencies": {
"adaptivecards": "1.1.0"
},
"devDependencies": {
"@types/chrome": "0.0.75",
"web-ext-types": "3.0.0",
"typescript": "3.2.2",
"ts-loader": "5.3.1",
"tslint": "5.11.0",
"webpack": "4.27.1",
"webpack-cli": "3.1.2",
"webpack-merge": "4.1.5"
}
}
| 413 |
2,350 | <reponame>avivazran/UnrealEnginePython
#pragma once
#include "UEPyModule.h"
#if WITH_EDITOR
#include "AssetRegistryModule.h"
#include "Runtime/AssetRegistry/Public/ARFilter.h"
typedef struct
{
PyObject_HEAD
/* Type-specific fields go here. */
FARFilter filter;
PyObject *class_names;
PyObject *object_paths;
PyObject *package_names;
PyObject *package_paths;
PyObject *recursive_classes_exclusion_set;
PyObject *tags_and_values;
} ue_PyFARFilter;
PyObject *py_ue_new_farfilter(FARFilter);
ue_PyFARFilter *py_ue_is_farfilter(PyObject *);
void ue_python_init_farfilter(PyObject *);
void py_ue_sync_farfilter(PyObject *);
void py_ue_clear_farfilter(ue_PyFARFilter *);
#endif
| 271 |
1,023 | {
"snapshot.verify_repository": {
"url_params": {
"master_timeout": "",
"timeout": ""
},
"methods": [
"POST"
],
"patterns": [
"_snapshot/{repository}/_verify"
],
"documentation": "https://opensearch.org/docs/latest/opensearch/snapshot-restore/"
}
}
| 146 |
1,388 | //
// Copyright 2011-2015 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "line.h"
namespace librender
{
namespace
{
// Clip masks
const unsigned int kBottom = 1;
const unsigned int kTop = 2;
const unsigned int kLeft = 4;
const unsigned int kRight = 8;
inline int vertClip(int x1, int y1, int x2, int y2, int x)
{
return y1 + (x - x1) * (y2 - y1) / (x2 - x1);
}
inline int horzClip(int x1, int y1, int x2, int y2, int y)
{
return x1 + (y - y1) * (x2 - x1) / (y2 - y1);
}
inline unsigned int clipmask(int x, int y, int left, int top, int right, int bottom)
{
unsigned mask = 0;
if (x < left)
mask |= kLeft;
else if (x > right)
mask |= kRight;
if (y < top)
mask |= kTop;
else if (y > bottom)
mask |= kBottom;
return mask;
}
} // namespace
// Cohen/Sutherland line clipping
void drawLineClipped(Surface *dest, int x1, int y1, int x2, int y2, unsigned int color,
int left, int top, int right, int bottom)
{
int clippedX1 = x1;
int clippedY1 = y1;
int clippedX2 = x2;
int clippedY2 = y2;
unsigned point1mask = clipmask(clippedX1, clippedY1, left, top, right, bottom);
unsigned point2mask = clipmask(clippedX2, clippedY2, left, top, right, bottom);
bool rejected = false;
while (point1mask != 0 || point2mask != 0)
{
if ((point1mask & point2mask) != 0)
{
rejected = true;
break;
}
unsigned mask = point1mask ? point1mask : point2mask;
int x, y;
if (mask & kBottom)
{
y = bottom;
x = horzClip(clippedX1, clippedY1, clippedX2, clippedY2, y);
}
else if (mask & kTop)
{
y = top;
x = horzClip(clippedX1, clippedY1, clippedX2, clippedY2, y);
}
else if (mask & kRight)
{
x = right;
y = vertClip(clippedX1, clippedY1, clippedX2, clippedY2, x);
}
else if (mask & kLeft)
{
x = left;
y = vertClip(clippedX1, clippedY1, clippedX2, clippedY2, x);
}
if (point1mask)
{
// Clip point 1
point1mask = clipmask(x, y, left, top, right, bottom);
clippedX1 = x;
clippedY1 = y;
}
else
{
// Clip point 2
point2mask = clipmask(x, y, left, top, right, bottom);
clippedX2 = x;
clippedY2 = y;
}
}
if (!rejected)
drawLine(dest, clippedX1, clippedY1, clippedX2, clippedY2, color);
}
void drawLine(Surface *dest, int x1, int y1, int x2, int y2, unsigned int color)
{
// Swap if necessary so we always draw top to bottom
if (y1 > y2)
{
int temp = y1;
y1 = y2;
y2 = temp;
temp = x1;
x1 = x2;
x2 = temp;
}
int deltaY = (y2 - y1) + 1;
int deltaX = x2 > x1 ? (x2 - x1) + 1 : (x1 - x2) + 1;
int xDir = x2 > x1 ? 1 : -1;
int error = 0;
unsigned int *ptr = (static_cast<unsigned int*>(dest->bits())) + x1 + y1 * dest->getWidth();
int stride = dest->getWidth();
if (deltaX == 0)
{
// Vertical line
for (int y = deltaY; y > 0; y--)
{
*ptr = color;
ptr += stride;
}
}
else if (deltaY == 0)
{
// Horizontal line
for (int x = deltaX; x > 0; x--)
{
*ptr = color;
ptr += xDir;
}
}
else if (deltaX > deltaY)
{
// Diagonal with horizontal major axis
int x = x1;
for (;;)
{
*ptr = color;
error += deltaY;
if (error > deltaX)
{
ptr += stride;
error -= deltaX;
}
ptr += xDir;
if (x == x2)
break;
x += xDir;
}
}
else
{
// Diagonal with vertical major axis
for (int y = y1; y <= y2; y++)
{
*ptr = color;
error += deltaX;
if (error > deltaY)
{
ptr += xDir;
error -= deltaY;
}
ptr += stride;
}
}
}
} // namespace librender
| 2,418 |
2,552 | {
"bugs": "https://github.com/alrra/browser-logos/issues",
"description": "Cốc Cốc browser logo",
"homepage": "https://github.com/alrra/browser-logos",
"keywords": [
"browser-logos",
"logo",
"cốc-cốc",
"cốc-cốc-logo"
],
"name": "@browser-logos/coc-coc",
"repository": {
"directory": "src/coc-coc",
"type": "git",
"url": "https://github.com/alrra/browser-logos.git"
},
"version": "1.0.3"
}
| 224 |
310 | package org.seasar.doma.it.sqlfile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.seasar.doma.it.Dbms;
import org.seasar.doma.it.IntegrationTestEnvironment;
import org.seasar.doma.it.Run;
import org.seasar.doma.it.dao.EmployeeDao;
import org.seasar.doma.it.dao.EmployeeDaoImpl;
import org.seasar.doma.it.entity.Employee;
import org.seasar.doma.jdbc.Config;
import org.seasar.doma.jdbc.JdbcException;
import org.seasar.doma.jdbc.SelectOptions;
import org.seasar.doma.message.Message;
@ExtendWith(IntegrationTestEnvironment.class)
public class SqlFileSelectForUpdateTest {
@Test
@Run(unless = {Dbms.H2, Dbms.POSTGRESQL, Dbms.ORACLE, Dbms.MYSQL, Dbms.DB2, Dbms.SQLSERVER})
public void testUnsupported(Config config) throws Exception {
EmployeeDao dao = new EmployeeDaoImpl(config);
try {
dao.selectById(1, SelectOptions.get().forUpdate());
fail();
} catch (JdbcException expected) {
assertEquals(Message.DOMA2023, expected.getMessageResource());
}
}
@Test
@Run(unless = {Dbms.HSQLDB, Dbms.SQLITE})
public void testForUpdate(Config config) throws Exception {
EmployeeDao dao = new EmployeeDaoImpl(config);
Employee employee = dao.selectById(1, SelectOptions.get().forUpdate());
assertNotNull(employee);
}
@Test
@Run(
unless = {
Dbms.HSQLDB,
Dbms.H2,
Dbms.POSTGRESQL,
Dbms.MYSQL,
Dbms.DB2,
Dbms.SQLSERVER,
Dbms.SQLITE
})
public void testForUpdateWithColumns(Config config) throws Exception {
EmployeeDao dao = new EmployeeDaoImpl(config);
Employee employee =
dao.selectById(1, SelectOptions.get().forUpdate("employee_name", "address_id"));
assertNotNull(employee);
}
@Test
@Run(
unless = {
Dbms.HSQLDB,
Dbms.H2,
Dbms.ORACLE,
Dbms.MYSQL,
Dbms.DB2,
Dbms.SQLSERVER,
Dbms.SQLITE
})
public void testForUpdateWithTables(Config config) throws Exception {
EmployeeDao dao = new EmployeeDaoImpl(config);
Employee employee = dao.selectById(1, SelectOptions.get().forUpdate("employee"));
assertNotNull(employee);
}
@Test
@Run(unless = {Dbms.HSQLDB, Dbms.H2, Dbms.POSTGRESQL, Dbms.MYSQL, Dbms.DB2, Dbms.SQLITE})
public void testForUpdateNowait(Config config) throws Exception {
EmployeeDao dao = new EmployeeDaoImpl(config);
Employee employee = dao.selectById(1, SelectOptions.get().forUpdateNowait());
assertNotNull(employee);
}
@Test
@Run(
unless = {
Dbms.HSQLDB,
Dbms.H2,
Dbms.POSTGRESQL,
Dbms.MYSQL,
Dbms.DB2,
Dbms.SQLSERVER,
Dbms.SQLITE
})
public void testForUpdateNowaitWithColumns(Config config) throws Exception {
EmployeeDao dao = new EmployeeDaoImpl(config);
Employee employee =
dao.selectById(1, SelectOptions.get().forUpdateNowait("employee_name", "address_id"));
assertNotNull(employee);
}
@Test
@Run(
unless = {
Dbms.HSQLDB,
Dbms.H2,
Dbms.POSTGRESQL,
Dbms.MYSQL,
Dbms.DB2,
Dbms.SQLSERVER,
Dbms.SQLITE
})
public void testForUpdateWait(Config config) throws Exception {
EmployeeDao dao = new EmployeeDaoImpl(config);
Employee employee = dao.selectById(1, SelectOptions.get().forUpdateWait(10));
assertNotNull(employee);
}
@Test
@Run(
unless = {
Dbms.HSQLDB,
Dbms.H2,
Dbms.POSTGRESQL,
Dbms.MYSQL,
Dbms.DB2,
Dbms.SQLSERVER,
Dbms.SQLITE
})
public void testForUpdateWaitWithColumns(Config config) throws Exception {
EmployeeDao dao = new EmployeeDaoImpl(config);
Employee employee =
dao.selectById(1, SelectOptions.get().forUpdateWait(10, "employee_name", "address_id"));
assertNotNull(employee);
}
}
| 1,817 |
4,020 | package me.coley.recaf.ui.controls.text.model;
import java.util.*;
/**
* A collection of rules that match against a language's feature set and themes to apply distinct
* styles to each of these rules.
*
* @author <NAME>
* @author Matt
*/
public class Language {
private final List<Rule> rules;
private final String name;
private final boolean wrap;
/**
* @param name
* Identifier.
* @param rules
* Rules for matching against language features.
* @param wrap
* Should text wrapping be enabled.
*/
public Language(String name, List<Rule> rules, boolean wrap) {
if(name == null)
throw new IllegalStateException("Language name must not be null");
if(rules == null)
throw new IllegalStateException("Language rule list must not be null");
this.name = name;
this.rules = rules;
this.wrap = wrap;
}
/**
* @return Identifier.
*/
public String getName() {
return name;
}
/**
* @return Rules for matching against language features.
*/
public List<Rule> getRules() {
return rules;
}
/**
* @return Should text wrapping be enabled.
*/
public boolean doWrap() {
return wrap;
}
}
| 368 |
2,180 | <filename>kafka-manager-common/src/main/java/com/xiaojukeji/kafka/manager/common/entity/pojo/TopicThrottledMetricsDO.java
package com.xiaojukeji.kafka.manager.common.entity.pojo;
import java.util.Date;
/**
* @author zhongyuankai
* @date 20/4/3
*/
public class TopicThrottledMetricsDO {
private Long id;
private Long clusterId;
private String topicName;
private String appId;
private Integer produceThrottled;
private Integer fetchThrottled;
private Date gmtCreate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getClusterId() {
return clusterId;
}
public void setClusterId(Long clusterId) {
this.clusterId = clusterId;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public Integer getProduceThrottled() {
return produceThrottled;
}
public void setProduceThrottled(Integer produceThrottled) {
this.produceThrottled = produceThrottled;
}
public Integer getFetchThrottled() {
return fetchThrottled;
}
public void setFetchThrottled(Integer fetchThrottled) {
this.fetchThrottled = fetchThrottled;
}
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
@Override
public String toString() {
return "TopicThrottleDO{" +
"id=" + id +
", clusterId=" + clusterId +
", topicName='" + topicName + '\'' +
", appId='" + appId + '\'' +
", produceThrottled=" + produceThrottled +
", fetchThrottled=" + fetchThrottled +
", gmtCreate=" + gmtCreate +
'}';
}
}
| 926 |
332 | <gh_stars>100-1000
// Autogenerated from vk-api-schema. Please don't edit it manually.
package com.vk.api.sdk.objects.utils;
import com.google.gson.annotations.SerializedName;
import com.vk.api.sdk.queries.EnumParam;
/**
* Interval.
*/
public enum GetLinkStatsInterval implements EnumParam {
@SerializedName("day")
DAY("day"),
@SerializedName("forever")
FOREVER("forever"),
@SerializedName("hour")
HOUR("hour"),
@SerializedName("month")
MONTH("month"),
@SerializedName("week")
WEEK("week");
private final String value;
GetLinkStatsInterval(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return value.toLowerCase();
}
}
| 313 |
852 | #ifndef SiTrackerMRHTools_SimpleDAFHitCollector_h
#define SiTrackerMRHTools_SimpleDAFHitCollector_h
#include "RecoTracker/SiTrackerMRHTools/interface/MultiRecHitCollector.h"
#include "DataFormats/TrackerRecHit2D/interface/SiStripRecHit1D.h"
#include "RecoTracker/TransientTrackingRecHit/interface/TkClonerImpl.h"
#include "RecoTracker/TransientTrackingRecHit/interface/TkTransientTrackingRecHitBuilder.h"
#include "RecoTracker/SiTrackerMRHTools/interface/SiTrackerMultiRecHitUpdator.h"
#include <Geometry/CommonDetUnit/interface/GeomDetType.h>
#include <vector>
#include <memory>
class Propagator;
class MeasurementEstimator;
//class SiTrackerMultiRecHitUpdator;
class StripRecHit1D;
class SimpleDAFHitCollector : public MultiRecHitCollector {
public:
explicit SimpleDAFHitCollector(const TrackerTopology* trackerTopology,
const MeasurementTracker* measurementTracker,
const SiTrackerMultiRecHitUpdator* updator,
const MeasurementEstimator* est,
const Propagator* propagator,
bool debug)
: MultiRecHitCollector(measurementTracker),
theTopology(trackerTopology),
theUpdator(updator),
theEstimator(est),
thePropagator(propagator),
debug_(debug) {
theHitCloner = static_cast<TkTransientTrackingRecHitBuilder const*>(theUpdator->getBuilder())->cloner();
}
~SimpleDAFHitCollector() override {}
//given a trajectory it returns a collection
//of SiTrackerMultiRecHits and InvalidTransientRecHits.
//For each measurement in the trajectory, measurements are looked for according to the
//MeasurementDet::fastMeasurements method only in the detector where the original measurement lays.
//If measurements are found a SiTrackerMultiRecHit is built.
//All the components will lay on the same detector
std::vector<TrajectoryMeasurement> recHits(const Trajectory&, const MeasurementTrackerEvent* theMTE) const override;
const SiTrackerMultiRecHitUpdator* getUpdator() const { return theUpdator; }
const MeasurementEstimator* getEstimator() const { return theEstimator; }
const Propagator* getPropagator() const { return thePropagator; }
void Debug(const std::vector<TrajectoryMeasurement> TM) const;
private:
//TransientTrackingRecHit::ConstRecHitContainer buildMultiRecHits(const std::vector<TrajectoryMeasurementGroup>& measgroup) const;
//void buildMultiRecHits(const std::vector<TrajectoryMeasurement>& measgroup, std::vector<TrajectoryMeasurement>& result) const;
std::unique_ptr<TrackingRecHit> rightdimension(TrackingRecHit const& hit) const {
if (!hit.isValid() || (hit.dimension() != 2)) {
return std::unique_ptr<TrackingRecHit>{hit.clone()};
}
auto const& thit = static_cast<BaseTrackerRecHit const&>(hit);
auto const& clus = thit.firstClusterRef();
if (clus.isPixel())
return std::unique_ptr<TrackingRecHit>{hit.clone()};
else if (clus.isPhase2())
return std::unique_ptr<TrackingRecHit>{hit.clone()};
else if (thit.isMatched()) {
LogDebug("MultiRecHitCollector") << " SiStripMatchedRecHit2D to check!!!";
return std::unique_ptr<TrackingRecHit>{hit.clone()};
} else if (thit.isProjected()) {
edm::LogError("MultiRecHitCollector") << " ProjectedSiStripRecHit2D should not be present at this stage!!!";
return std::unique_ptr<TrackingRecHit>{hit.clone()};
} else
return clone(thit);
}
std::unique_ptr<TrackingRecHit> clone(BaseTrackerRecHit const& hit2D) const {
auto const& detU = *hit2D.detUnit();
//Use 2D SiStripRecHit in endcap
bool endcap = detU.type().isEndcap();
if (endcap)
return std::unique_ptr<TrackingRecHit>{hit2D.clone()};
return std::unique_ptr<TrackingRecHit>{
new SiStripRecHit1D(hit2D.localPosition(),
LocalError(hit2D.localPositionError().xx(), 0.f, std::numeric_limits<float>::max()),
*hit2D.det(),
hit2D.firstClusterRef())};
}
private:
const TrackerTopology* theTopology;
const SiTrackerMultiRecHitUpdator* theUpdator;
const MeasurementEstimator* theEstimator;
//this actually is not used in the fastMeasurement method
const Propagator* thePropagator;
TkClonerImpl theHitCloner;
const bool debug_;
};
#endif
| 1,673 |
615 | package org.byron4j.cookbook.designpattern.prototype;
/**
* 蛋糕的接口类型;可以clone
*/
public interface Cake extends Cloneable{
/**
* 准备生产蛋糕
* @return
*/
public Cake prepareCake();
}
| 122 |
473 | #!/usr/bin/env python
from generator.actions import Actions, Variable
import random
import string
import struct
import sys
from collections import OrderedDict
CMD_AUTH = 0
CMD_NEW_PERMIT = 1
CMD_NEW_PERMIT_RING = 2
CMD_REFACTOR_RING = 3
CMD_TEST_PERMIT = 4
CMD_TEST_PERMIT_RING = 5
CMD_INVALID = 6
MAX_SPOT_NUMBER = 200
def random_string_n(size=20):
return ''.join([random.choice(string.ascii_letters) for x in xrange(size)])
def random_string(size=20):
return ''.join([random.choice(string.ascii_letters) for x in xrange(random.randint(1,size))])
def random_digits(size=20):
return ''.join([random.choice(string.digits) for x in xrange(random.randint(1,size))])
class APPMS(Actions):
def start(self):
self.state['g_mkey'] = 'I_AM_YOUR_FATHER'
self.state['g_session_key'] = None
self.state['g_auth'] = 0
def commands(self):
pass
def get_error(self):
self.read(length=1, expect='\x10')
def license_number(self):
s = random_string(8)
n = random_digits(4)
r = s + n + random_string_n()
return (s+n)[:9]
def permit_token(self):
token = random_string_n(4) + chr(0x55) + random_string_n(2)
cs = 0;
for c in token:
cs += ord(c)
cs %= 0xAB
token = token + chr(cs)
return token
def cmd_auth(self):
cmd = struct.pack('<b16s', CMD_AUTH, self.state['g_mkey'])
cmd = struct.pack('<I', len(cmd)) + cmd
self.write(cmd)
skey = Variable('skey')
skey.set_re('(.*)')
self.read(length=1, expect='\x00')
self.read(length=4, expect=struct.pack('<I', 16))
self.read(length=16, assign=skey)
self.state['g_session_key'] = skey
self.state['g_auth'] = 3
def cmd_new_permit(self):
if self.state['g_session_key'] == None:
return
lic = self.license_number()
n_e = random.randint(0, 1000)
spot = random.randint(1, MAX_SPOT_NUMBER)
cmd = struct.pack('<b16s10sII', CMD_NEW_PERMIT, '_SESSION_KEY_', lic, n_e, spot)
cmd = struct.pack('<I', len(cmd)) + cmd
self.write(cmd[:5], self.state['g_session_key'], cmd[21:])
if self.state['g_auth'] > 0:
self.read(length=(1 + 4), expect='\x00' + struct.pack('<I', 26))
self.read(length=(8 + 10 + 2 * 4))
self.state['g_auth'] -= 1
else:
self.get_error()
def cmd_new_permit_ring(self):
if self.state['g_session_key'] == None:
return
lics = []
n_es = []
spots = []
tokens = []
valid = True
n = random.randint(0, 5)
for i in xrange(n):
while True:
lic = self.license_number()
if lic not in lics:
lics.append(lic)
break
while True:
spot = random.randint(1, MAX_SPOT_NUMBER)
if spot not in spots:
spots.append(spot)
break
if random.randint(1,100) <= 20:
n_e = 0
valid = False
else:
n_e = random.randint(1, 1000)
n_es.append(n_e)
token = self.permit_token()
tokens.append(token)
cmd = struct.pack('<b16sI', CMD_NEW_PERMIT_RING, '_SESSION_KEY_', n)
for i in xrange(n):
cmd += struct.pack('<8s10sII', tokens[i], lics[i], n_es[i], spots[i])
ns = (5 - n) * 26
if ns > 0:
cmd += '\x00' * ns
cmd = struct.pack('<I', len(cmd)) + cmd
self.write(cmd[:5], self.state['g_session_key'], cmd[21:])
if self.state['g_auth'] > 0 and valid:
self.read(length=(1 + 4), expect='\x00' + struct.pack('<I', 4 + 5 * 26))
self.read(length=4, expect=struct.pack('<I', n))
for i in xrange(n):
self.read(length=(8 + 10 + 2 * 4))
n = (5 - n) * 26
if n > 0:
self.read(length=n, expect='\x00'*n)
self.state['g_auth'] -= 1
else:
self.get_error()
def cmd_refactor_ring(self):
if self.state['g_session_key'] == None:
return
lics = []
n_es = []
spots = []
tokens = []
n = random.randint(0, 5)
for i in xrange(n):
while True:
lic = self.license_number()
if lic not in lics:
lics.append(lic)
break
while True:
spot = random.randint(1, MAX_SPOT_NUMBER)
if spot not in spots:
spots.append(spot)
break
if random.randint(1, 100) <= 20:
n_e = 0
else:
n_e = random.randint(1, 1000)
n_es.append(n_e)
token = self.permit_token()
tokens.append(token)
cmd = struct.pack('<b16sI', CMD_REFACTOR_RING, '_SESSION_KEY_', n)
for i in xrange(n):
cmd += struct.pack('<8s10sII', tokens[i], lics[i], n_es[i], spots[i])
ns = (5 - n) * 26
if ns > 0:
cmd += '\x00' * ns
cmd = struct.pack('<I', len(cmd)) + cmd
self.write(cmd[:5], self.state['g_session_key'], cmd[21:])
il = []
for i in xrange(n):
if n_es[i] > 0:
il.append(i)
if self.state['g_auth'] > 0:
self.read(length=(1 + 4), expect='\x00' + struct.pack('<I', 4 + 5 * 26))
self.read(length=4, expect=struct.pack('<I', len(il)))
for i in il:
self.read(length=(8 + 10 + 2 * 4))
n = (5 - len(il)) * 26
if n > 0:
self.read(length=n, expect='\x00'*n)
self.state['g_auth'] -= 1
else:
self.get_error()
def cmd_test_permit(self):
if self.state['g_session_key'] == None:
return
valid = True
token = self.permit_token()
lic = self.license_number()
n_e = random.randint(0, 1000)
if n_e == 0:
valid = False
spot = random.randint(1, MAX_SPOT_NUMBER)
cmd = struct.pack('<b16s8s10sIII10s', CMD_TEST_PERMIT, '_SESSION_KEY_', token, lic, n_e, spot, spot, lic)
cmd = struct.pack('<I', len(cmd)) + cmd
self.write(cmd[:5], self.state['g_session_key'], cmd[21:])
if self.state['g_auth'] > 0 and valid:
self.read(length=1, expect='\x00')
self.state['g_auth'] -= 1
else:
self.get_error()
def cmd_test_permit_ring(self):
if self.state['g_session_key'] == None:
return
valid = True
lics = []
n_es = []
spots = []
tokens = []
n = random.randint(0, 5)
for i in xrange(n):
while True:
lic = self.license_number()
if lic not in lics:
lics.append(lic)
break
while True:
spot = random.randint(1, MAX_SPOT_NUMBER)
if spot not in spots:
spots.append(spot)
break
if random.randint(1,100) <= 20:
n_e = 0
valid = False
else:
n_e = random.randint(1, 1000)
n_es.append(n_e)
token = self.permit_token()
tokens.append(token)
cmd = struct.pack('<b16sI', CMD_TEST_PERMIT_RING, '_SESSION_KEY_', n)
for i in xrange(n):
cmd += struct.pack('<8s10sII', tokens[i], lics[i], n_es[i], spots[i])
ns = (5 - n) * 26
if ns > 0:
cmd += '\x00' * ns
for i in xrange(n):
cmd += struct.pack('<I', spots[i])
ns = (5 - n) * 4
if ns > 0:
cmd += '\x00' * ns
for i in xrange(n):
cmd += struct.pack('10s', lics[i])
ns = (5 - n) * 10
if ns > 0:
cmd += '\x00' * ns
cmd = struct.pack('<I', len(cmd)) + cmd
self.write(cmd[:5], self.state['g_session_key'], cmd[21:])
if self.state['g_auth'] > 0 and valid:
self.read(length=1, expect='\x00')
self.state['g_auth'] -= 1
else:
self.get_error()
def quit(self):
cmd = struct.pack('<b', CMD_INVALID)
cmd = struct.pack('<I', len(cmd)) + cmd
self.write(cmd)
| 3,589 |
3,444 | <reponame>huihui7987/blade
package com.hellokaton.blade.websocket.annotaion;
import java.lang.annotation.*;
/**
* @author darren
* @description invoke websocketHandler onDisConnect method
* @date 2018/12/17 18:41
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OnClose {
}
| 113 |
2,757 | // Copyright (c) 2016-2017 Dr. <NAME> and <NAME>
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAOCPP_PEGTL_INCLUDE_INTERNAL_MINUS_HPP
#define TAOCPP_PEGTL_INCLUDE_INTERNAL_MINUS_HPP
#include "../config.hpp"
#include "skip_control.hpp"
#include "../apply_mode.hpp"
#include "../memory_input.hpp"
#include "../rewind_mode.hpp"
namespace tao
{
namespace TAOCPP_PEGTL_NAMESPACE
{
namespace internal
{
inline const char* source_pointer( const char* source ) noexcept
{
return source;
}
inline const char* source_pointer( const std::string& source ) noexcept
{
return source.c_str();
}
template< typename R, typename S >
struct minus
{
using analyze_t = typename R::analyze_t; // NOTE: S is currently ignored for analyze().
template< apply_mode A,
rewind_mode,
template< typename... > class Action,
template< typename... > class Control,
typename Input,
typename... States >
static bool match( Input& in, States&&... st )
{
auto m = in.template mark< rewind_mode::REQUIRED >();
if( !Control< R >::template match< A, rewind_mode::ACTIVE, Action, Control >( in, st... ) ) {
return false;
}
memory_input< tracking_mode::LAZY, typename Input::eol_t, const char* > i2( m.iterator(), in.current(), source_pointer( in.source() ) );
if( !Control< S >::template match< apply_mode::NOTHING, rewind_mode::ACTIVE, Action, Control >( i2, st... ) ) {
return m( true );
}
return m( !i2.empty() );
}
};
template< typename R, typename S >
struct skip_control< minus< R, S > > : std::true_type
{
};
} // namespace internal
} // namespace TAOCPP_PEGTL_NAMESPACE
} // namespace tao
#endif
| 1,028 |
759 | <reponame>z-chu/RxWebSocket
package com.dhh.rxwebsocket;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.dhh.rxlifecycle.RxLifecycle;
import com.dhh.websocket.Config;
import com.dhh.websocket.RxWebSocket;
import com.dhh.websocket.WebSocketInfo;
import com.dhh.websocket.WebSocketSubscriber;
import com.dhh.websocket.WebSocketSubscriber2;
import java.util.List;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okio.ByteString;
import rx.Subscription;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
public class MainActivity extends AppCompatActivity {
private WebSocket mWebSocket;
private EditText editText;
private Button send;
private Button centect;
private Subscription mSubscription;
private TextView textview;
private String url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//init config
Config config = new Config.Builder()
.setShowLog(true) //show log
// .setClient(yourClient) //if you want to set your okhttpClient
// .setShowLog(true, "your logTag")
// .setReconnectInterval(2, TimeUnit.SECONDS) //set reconnect interval
// .setSSLSocketFactory(yourSSlSocketFactory, yourX509TrustManager) // wss support
.build();
RxWebSocket.setConfig(config);
// please use WebSocketSubscriber
RxWebSocket.get("your url")
//RxLifecycle : https://github.com/dhhAndroid/RxLifecycle
.compose(RxLifecycle.with(this).<WebSocketInfo>bindOnDestroy())
.subscribe(new WebSocketSubscriber() {
@Override
public void onOpen(@NonNull WebSocket webSocket) {
Log.d("MainActivity", "onOpen1:");
}
@Override
public void onMessage(@NonNull String text) {
Log.d("MainActivity", "返回数据:" + text);
}
@Override
public void onMessage(@NonNull ByteString byteString) {
}
@Override
protected void onReconnect() {
Log.d("MainActivity", "重连:");
}
});
/**
*
*如果你想将String类型的text解析成具体的实体类,比如{@link List<String>},
* 请使用 {@link WebSocketSubscriber2},仅需要将泛型传入即可
*/
RxWebSocket.get("your url")
.compose(RxLifecycle.with(this).<WebSocketInfo>bindToLifecycle())
.subscribe(new WebSocketSubscriber2<List<String>>() {
@Override
protected void onMessage(List<String> strings) {
}
});
mSubscription = RxWebSocket.get("ws://sdfsd")
.subscribe(new WebSocketSubscriber() {
@Override
protected void onClose() {
Log.d("MainActivity", "直接关闭");
}
});
initDemo();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mSubscription != null && !mSubscription.isUnsubscribed()) {
mSubscription.unsubscribe();
}
}
@Override
protected void onResume() {
super.onResume();
RxWebSocket.get("url")
.subscribe(new WebSocketSubscriber() {
@Override
protected void onMessage(@NonNull String text) {
}
});
RxWebSocket.get("your url")
//RxLifecycle : https://github.com/dhhAndroid/RxLifecycle
.compose(RxLifecycle.with(this).<WebSocketInfo>bindToLifecycle())
.subscribe(new WebSocketSubscriber() {
@Override
public void onOpen(@NonNull WebSocket webSocket) {
Log.d("MainActivity", "onOpen1:");
}
@Override
public void onMessage(@NonNull String text) {
Log.d("MainActivity", "返回数据:" + text);
}
@Override
public void onMessage(@NonNull ByteString byteString) {
}
@Override
protected void onReconnect() {
Log.d("MainActivity", "重连:");
}
@Override
protected void onClose() {
Log.d("MainActivity", "onClose:");
}
});
}
private void initDemo() {
Schedulers.io().createWorker().schedule(new Action0() {
@Override
public void call() {
initServerWebsocket();
}
});
setListener();
// unsubscribe
Subscription subscription = RxWebSocket.get("ws://sdfs").subscribe();
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
private void initServerWebsocket() {
final MockWebServer mockWebServer = new MockWebServer();
url = "ws://" + mockWebServer.getHostName() + ":" + mockWebServer.getPort() + "/";
mockWebServer.enqueue(new MockResponse().withWebSocketUpgrade(new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("hello, I am dhhAndroid !");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
Log.d("MainActivity", "收到客户端消息:" + text);
webSocket.send("Server response:" + text);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
}
}));
}
private void setListener() {
//send message
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = editText.getText().toString();
if (mWebSocket != null) {
mWebSocket.send(msg);
} else {
send();
}
}
});
centect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//注意取消订阅,有多种方式,比如 rxlifecycle
connect();
}
});
}
private void connect() {
RxWebSocket.get(url)
//RxLifecycle : https://github.com/dhhAndroid/RxLifecycle
.compose(RxLifecycle.with(this).<WebSocketInfo>bindOnDestroy())
.subscribe(new WebSocketSubscriber() {
@Override
protected void onOpen(@NonNull WebSocket webSocket) {
Log.d("MainActivity", " on WebSocket open");
}
@Override
protected void onMessage(@NonNull String text) {
Log.d("MainActivity", text);
textview.setText(Html.fromHtml(text));
}
@Override
protected void onMessage(@NonNull ByteString byteString) {
Log.d("MainActivity", byteString.toString());
}
@Override
protected void onReconnect() {
Log.d("MainActivity", "onReconnect");
}
@Override
protected void onClose() {
Log.d("MainActivity", "onClose");
}
@Override
public void onError(Throwable e) {
super.onError(e);
}
});
}
public void send() {
//url 对应的WebSocket 必须打开,否则报错
RxWebSocket.send(url, "hello");
RxWebSocket.send(url, ByteString.EMPTY);
//异步发送,若WebSocket已经打开,直接发送,若没有打开,打开一个WebSocket发送完数据,直接关闭.
RxWebSocket.asyncSend(url, "hello");
RxWebSocket.asyncSend(url, ByteString.EMPTY);
}
private void initView() {
editText = (EditText) findViewById(R.id.editText);
send = (Button) findViewById(R.id.send);
centect = (Button) findViewById(R.id.centect);
textview = (TextView) findViewById(R.id.textview);
}
}
| 4,987 |
1,374 | <reponame>norzak/jsweet
/*
* TypeScript definitions to Java translator - http://www.jsweet.org
* Copyright (C) 2015 CINCHEO SAS <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jsweet.input.typescriptdef.visitor;
import org.jsweet.input.typescriptdef.ast.Context;
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
import org.jsweet.input.typescriptdef.ast.Scanner;
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
import org.jsweet.input.typescriptdef.ast.TypeMacroDeclaration;
/**
* Registers declarations in the context for further lookup.
*
* @author <NAME>
*/
public class DeclarationBinder extends Scanner {
public DeclarationBinder(Context context) {
super(context);
}
public DeclarationBinder(Scanner parentScanner) {
super(parentScanner);
}
@Override
public void visitModuleDeclaration(ModuleDeclaration moduleDeclaration) {
context.registerModule(getCurrentContainerName(), moduleDeclaration);
super.visitModuleDeclaration(moduleDeclaration);
}
@Override
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
if (!typeDeclaration.isAnonymous()) {
context.registerType(getCurrentContainerName(), typeDeclaration);
}
super.visitTypeDeclaration(typeDeclaration);
}
@Override
public void visitTypeMacro(TypeMacroDeclaration typeMacroDeclaration) {
context.registerType(getCurrentContainerName(), typeMacroDeclaration);
super.visitTypeMacro(typeMacroDeclaration);
}
}
| 626 |
477 | <filename>tests/test_cmds_goplot_rels.py
#!/usr/bin/env python3
"""Test commands run in notebooks/get_isa_and_partof.ipynb"""
from __future__ import print_function
__copyright__ = "Copyright (C) 2010-2019, <NAME>, <NAME>. All rights reserved."
import os
import sys
# REPO = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
def test_plotgos(run_all=False):
"""RUn an enrichments using all annotation file formats"""
if run_all:
for idx, cmd in enumerate(_get_cmds()):
print('------------------- TEST {I} ------------------------------------'.format(I=idx))
print('CMD: {CMD}'.format(CMD=cmd))
assert os.system(cmd) == 0
print("TEST PASSED")
else:
print('RUN THIS TEST WITH AN ARGUMENT')
def _get_cmds():
"""Get commands used in ./doc/md/README_find_enrichment.md"""
# pylint: disable=line-too-long
return [
'python3 scripts/go_plot.py -o viral_r0.png GO:0019222#d8dcd6 GO:0060150 --obo=tests/data/i126/viral_gene_silence.obo --go_color_file=tests/data/i126/viral_gene_silence.txt',
'python3 scripts/go_plot.py -o viral_r1.png -r GO:0010468#d8dcd6 GO:0060150 --obo=tests/data/i126/viral_gene_silence.obo --go_color_file=tests/data/i126/viral_gene_silence.txt',
'python3 scripts/go_plot.py -o viral_r_partof.png --relationships=part_of GO:0010468#d8dcd6 GO:0060150 --obo=tests/data/i126/viral_gene_silence.obo --go_color_file=tests/data/i126/viral_gene_silence.txt',
'python3 scripts/go_plot.py -o viral_reg.png --relationships=regulates GO:0050794#d8dcd6 GO:0060150 --obo=tests/data/i126/viral_gene_silence.obo --go_color_file=tests/data/i126/viral_gene_silence.txt',
'python3 scripts/go_plot.py -o viral_rp.png --relationships=positively_regulates GO:0048522#d8dcd6 GO:0060150 --obo=tests/data/i126/viral_gene_silence.obo --go_color_file=tests/data/i126/viral_gene_silence.txt',
'python3 scripts/go_plot.py -o viral_rn.png --relationships=regulates,negatively_regulates GO:0050794#d8dcd6 GO:0060150 --obo=tests/data/i126/viral_gene_silence.obo --go_color_file=tests/data/i126/viral_gene_silence.txt',
]
if __name__ == '__main__':
test_plotgos(len(sys.argv) != 1)
# Copyright (C) 2010-2019, <NAME>, <NAME>. All rights reserved.
| 1,122 |
1,760 | <gh_stars>1000+
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)
#define pb push_back
#define ub upper_bound
#define s second
void setIO(string name) {
ios_base::sync_with_stdio(0); cin.tie(0);
freopen((name+".in").c_str(),"r",stdin);
freopen((name+".out").c_str(),"w",stdout);
}
const int MX = 100005;
template<class T, int SZ> struct BIT {
T bit[SZ+1];
void upd(int pos, T x) {
for (; pos <= SZ; pos += (pos&-pos))
bit[pos] += x;
}
T sum(int r) {
T res = 0; for (; r; r -= (r&-r))
res += bit[r];
return res;
}
T query(int l, int r) {
return sum(r)-sum(l-1);
}
};
BIT<ll,MX> A,B;
map<int,int> col[MX];
int st[MX], en[MX],sub[MX];
int N,Q;
vi adj[MX];
int co;
void dfs(int x, int y) {
st[x] = ++co;
trav(t,adj[x]) if (t != y) dfs(t,x);
en[x] = co;
sub[x] = en[x]-st[x]+1;
}
void upd(int x, int y) {
A.upd(st[x],y); A.upd(en[x]+1,-y);
B.upd(st[x],y*sub[x]);
}
int main() {
setIO("snowcow");
cin >> N >> Q;
F0R(i,N-1) {
int a,b; cin >> a >> b;
adj[a].pb(b), adj[b].pb(a);
}
dfs(1,0);
F0R(i,Q) {
int t; cin >> t;
if (t == 1) {
int x,c; cin >> x >> c;
auto it = col[c].ub(st[x]);
if (it != begin(col[c]) && en[prev(it)->s] >= en[x]) continue;
while (it != end(col[c]) && en[it->s] <= en[x]) {
upd(it->s,-1);
col[c].erase(it++);
}
col[c][st[x]] = x; upd(x,1);
} else {
int x; cin >> x;
cout << sub[x]*A.sum(st[x])+B.query(st[x]+1,en[x]) << "\n";
}
}
} | 937 |
409 | #ifndef SIM_LINK_H_
#define SIM_LINK_H_
#include <string>
#include <vector>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include "decoder.h"
namespace sim{
class Link{
private:
int sock;
bool noblock_;
bool error_;
Decoder decoder_;
Link(bool is_server=false);
// TODO: max_recv_buf_size, max_send_buf_size
public:
std::string output;
char remote_ip[INET_ADDRSTRLEN];
int remote_port;
double create_time;
double active_time;
~Link();
void close();
void nodelay(bool enable=true);
// noblock(true) is supposed to corperate with IO Multiplex,
// otherwise, flush() may cause a lot unneccessary write calls.
void noblock(bool enable=true);
void keepalive(bool enable=true);
int fd() const{
return sock;
}
bool error() const{
return error_;
}
void mark_error(){
error_ = true;
}
static Link* connect(const char *ip, int port);
static Link* connect(const std::string &ip, int port);
static Link* listen(const char *ip, int port);
static Link* listen(const std::string &ip, int port);
Link* accept();
// read network data info buffer
int read();
int write();
// flush buffered data to network
// REQUIRES: nonblock
int flush();
int recv(Message *msg);
int send(const Message &msg);
};
}; // namespace sim
#endif
| 487 |
903 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.analysis.compound;
import org.apache.lucene.analysis.CharArraySet;
import org.apache.lucene.analysis.TokenStream;
/**
* A {@link org.apache.lucene.analysis.TokenFilter} that decomposes compound words found in many
* Germanic languages.
*
* <p>"Donaudampfschiff" becomes Donau, dampf, schiff so that you can find "Donaudampfschiff" even
* when you only enter "schiff". It uses a brute-force algorithm to achieve this.
*/
public class DictionaryCompoundWordTokenFilter extends CompoundWordTokenFilterBase {
/**
* Creates a new {@link DictionaryCompoundWordTokenFilter}
*
* @param input the {@link org.apache.lucene.analysis.TokenStream} to process
* @param dictionary the word dictionary to match against.
*/
public DictionaryCompoundWordTokenFilter(TokenStream input, CharArraySet dictionary) {
super(input, dictionary);
if (dictionary == null) {
throw new IllegalArgumentException("dictionary must not be null");
}
}
/**
* Creates a new {@link DictionaryCompoundWordTokenFilter}
*
* @param input the {@link org.apache.lucene.analysis.TokenStream} to process
* @param dictionary the word dictionary to match against.
* @param minWordSize only words longer than this get processed
* @param minSubwordSize only subwords longer than this get to the output stream
* @param maxSubwordSize only subwords shorter than this get to the output stream
* @param onlyLongestMatch Add only the longest matching subword to the stream
*/
public DictionaryCompoundWordTokenFilter(
TokenStream input,
CharArraySet dictionary,
int minWordSize,
int minSubwordSize,
int maxSubwordSize,
boolean onlyLongestMatch) {
super(input, dictionary, minWordSize, minSubwordSize, maxSubwordSize, onlyLongestMatch);
if (dictionary == null) {
throw new IllegalArgumentException("dictionary must not be null");
}
}
@Override
protected void decompose() {
final int len = termAtt.length();
for (int i = 0; i <= len - this.minSubwordSize; ++i) {
CompoundToken longestMatchToken = null;
for (int j = this.minSubwordSize; j <= this.maxSubwordSize; ++j) {
if (i + j > len) {
break;
}
if (dictionary.contains(termAtt.buffer(), i, j)) {
if (this.onlyLongestMatch) {
if (longestMatchToken != null) {
if (longestMatchToken.txt.length() < j) {
longestMatchToken = new CompoundToken(i, j);
}
} else {
longestMatchToken = new CompoundToken(i, j);
}
} else {
tokens.add(new CompoundToken(i, j));
}
}
}
if (this.onlyLongestMatch && longestMatchToken != null) {
tokens.add(longestMatchToken);
}
}
}
}
| 1,238 |
12,940 | {
"$schema": "https://aka.ms/azure-quickstart-templates-metadata-schema#",
"itemDisplayName": "Create a subscription under an EA account",
"description": "This template is a management group template that will create a subscription via an alias. It can be used for an Enterprise Agreement billing mode only. The official documentation shows modifications needed for other types of accounts.",
"summary": "This template is a management group template that will create a subscription via an alias under an EA account",
"type": "ManagementGroupDeployment",
"validationType": "Manual",
"githubUsername": "bmoore-msft",
"dateUpdated": "2021-04-23"
}
| 188 |
325 | #pragma once
namespace mcl { namespace fp {
template<>
struct EnableKaratsuba<Ltag> {
#if MCL_SIZEOF_UNIT == 4
static const size_t minMulN = 10;
static const size_t minSqrN = 10;
#else
static const size_t minMulN = 8;
static const size_t minSqrN = 6;
#endif
};
#if MCL_SIZEOF_UNIT == 4
#define MCL_GMP_IS_FASTER_THAN_LLVM // QQQ : check later
#endif
#ifdef MCL_GMP_IS_FASTER_THAN_LLVM
#define MCL_DEF_MUL(n, tag, suf)
#else
#define MCL_DEF_MUL(n, tag, suf) \
template<>const void3u MulPreCore<n, tag>::f = &mcl_fpDbl_mulPre ## n ## suf; \
template<>const void2u SqrPreCore<n, tag>::f = &mcl_fpDbl_sqrPre ## n ## suf;
#endif
#define MCL_DEF_LLVM_FUNC2(n, tag, suf) \
template<>const u3u AddPre<n, tag>::f = &mcl_fp_addPre ## n ## suf; \
template<>const u3u SubPre<n, tag>::f = &mcl_fp_subPre ## n ## suf; \
template<>const void2u Shr1<n, tag>::f = &mcl_fp_shr1_ ## n ## suf; \
MCL_DEF_MUL(n, tag, suf) \
template<>const void2uI MulUnitPre<n, tag>::f = &mcl_fp_mulUnitPre ## n ## suf; \
template<>const void4u Add<n, true, tag>::f = &mcl_fp_add ## n ## suf; \
template<>const void4u Add<n, false, tag>::f = &mcl_fp_addNF ## n ## suf; \
template<>const void4u Sub<n, true, tag>::f = &mcl_fp_sub ## n ## suf; \
template<>const void4u Sub<n, false, tag>::f = &mcl_fp_subNF ## n ## suf; \
template<>const void4u Mont<n, true, tag>::f = &mcl_fp_mont ## n ## suf; \
template<>const void4u Mont<n, false, tag>::f = &mcl_fp_montNF ## n ## suf; \
template<>const void3u MontRed<n, true, tag>::f = &mcl_fp_montRed ## n ## suf; \
template<>const void3u MontRed<n, false, tag>::f = &mcl_fp_montRedNF ## n ## suf; \
template<>const void4u DblAdd<n, tag>::f = &mcl_fpDbl_add ## n ## suf; \
template<>const void4u DblSub<n, tag>::f = &mcl_fpDbl_sub ## n ## suf; \
#if MCL_LLVM_BMI2 == 1
#define MCL_DEF_LLVM_FUNC(n) \
MCL_DEF_LLVM_FUNC2(n, Ltag, L) \
MCL_DEF_LLVM_FUNC2(n, LBMI2tag, Lbmi2)
#else
#define MCL_DEF_LLVM_FUNC(n) \
MCL_DEF_LLVM_FUNC2(n, Ltag, L)
#endif
#if MCL_SIZEOF_UNIT == 4
MCL_DEF_LLVM_FUNC(6)
MCL_DEF_LLVM_FUNC(7)
MCL_DEF_LLVM_FUNC(8)
#if MCL_MAX_UNIT_SIZE >= 12
MCL_DEF_LLVM_FUNC(12)
#endif
#if MCL_MAX_UNIT_SIZE >= 16
MCL_DEF_LLVM_FUNC(16)
#endif
#else
MCL_DEF_LLVM_FUNC(3)
MCL_DEF_LLVM_FUNC(4)
#if MCL_MAX_UNIT_SIZE >= 6
MCL_DEF_LLVM_FUNC(6)
#endif
#if MCL_MAX_UNIT_SIZE >= 8
MCL_DEF_LLVM_FUNC(8)
#endif
#endif
} } // mcl::fp
| 1,175 |
1,587 | package io.reflectoring.resilience4j.springboot.predicates;
import io.reflectoring.resilience4j.springboot.model.SearchResponse;
import java.util.function.Predicate;
public class ConditionalRetryPredicate implements Predicate<SearchResponse> {
@Override
public boolean test(SearchResponse searchResponse) {
if (searchResponse.getErrorCode() != null) {
System.out.println("Search returned error code = " + searchResponse.getErrorCode());
return searchResponse.getErrorCode().equals("FS-167");
}
return false;
}
} | 166 |
349 | <reponame>alexanderbock/inviwo
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015-2021 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/openglqt/shaderwidget.h>
#include <inviwo/core/util/raiiutils.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/colorconversion.h>
#include <modules/opengl/shader/shaderresource.h>
#include <modules/opengl/shader/shadermanager.h>
#include <modules/qtwidgets/syntaxhighlighter.h>
#include <modules/qtwidgets/inviwoqtutils.h>
#include <modules/qtwidgets/codeedit.h>
#include <modules/openglqt/glslsyntaxhighlight.h>
#include <fmt/format.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QToolBar>
#include <QMainWindow>
#include <QMenuBar>
#include <QCloseEvent>
#include <QMessageBox>
#include <QSignalBlocker>
#include <QScrollBar>
#include <warn/pop>
namespace inviwo {
ShaderWidget::ShaderWidget(ShaderObject* obj, QWidget* parent)
: InviwoDockWidget(utilqt::toQString(obj->getFileName()) + "[*]", parent, "ShaderEditorWidget")
, obj_{obj}
, shaderObjOnChange_{obj->onChange([this](ShaderObject*) { shaderObjectChanged(); })} {
setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
resize(utilqt::emToPx(this, QSizeF(50, 70))); // default size
setFloating(true);
setSticky(false);
QMainWindow* mainWindow = new QMainWindow();
mainWindow->setContextMenuPolicy(Qt::NoContextMenu);
QToolBar* toolBar = new QToolBar();
mainWindow->addToolBar(toolBar);
toolBar->setFloatable(false);
toolBar->setMovable(false);
setWidget(mainWindow);
shadercode_ = new CodeEdit{this};
auto settings = InviwoApplication::getPtr()->getSettingsByType<GLSLSyntaxHighlight>();
codeCallbacks_ = utilqt::setGLSLSyntaxHighlight(shadercode_->syntaxHighlighter(), *settings);
shadercode_->setObjectName("shaderwidgetcode");
shadercode_->setPlainText(utilqt::toQString(obj->print(false, false)));
apply_ = toolBar->addAction(QIcon(":/svgicons/run-script.svg"), tr("&Apply Changes"));
apply_->setToolTip(
"Replace the ShaderTesource in the shader with a new one with this contents. The "
"changes will only affect this shader and will not be persistent.");
apply_->setShortcut(Qt::CTRL | Qt::Key_R);
apply_->setShortcutContext(Qt::WidgetWithChildrenShortcut);
mainWindow->addAction(apply_);
connect(apply_, &QAction::triggered, this, &ShaderWidget::apply);
save_ = toolBar->addAction(QIcon(":/svgicons/save.svg"), tr("&Save Shader"));
save_->setToolTip(
"If we have a FileShaderResoruce save the changes to disk, the change will be persistent "
"and all shaders using the file will be reloaded. If we have a StringShaderResource, "
"update the string. The change will affect all shaders using the resource but will not be "
"persistent");
save_->setShortcut(QKeySequence::Save);
save_->setShortcutContext(Qt::WidgetWithChildrenShortcut);
mainWindow->addAction(save_);
connect(save_, &QAction::triggered, this, &ShaderWidget::save);
revert_ = toolBar->addAction(QIcon(":/svgicons/revert.svg"), tr("Revert"));
revert_->setToolTip("Revert changes");
revert_->setShortcutContext(Qt::WidgetWithChildrenShortcut);
revert_->setEnabled(false);
QObject::connect(shadercode_, &QPlainTextEdit::modificationChanged, revert_,
&QAction::setEnabled);
QObject::connect(revert_, &QAction::triggered, this, &ShaderWidget::revert);
QPixmap enabled(":/svgicons/precompiled-enabled.svg");
QPixmap disabled(":/svgicons/precompiled-disabled.svg");
QIcon preicon;
preicon.addPixmap(enabled, QIcon::Normal, QIcon::Off);
preicon.addPixmap(disabled, QIcon::Normal, QIcon::On);
preprocess_ = toolBar->addAction(preicon, "Show Preprocessed Shader");
preprocess_->setChecked(false);
preprocess_->setCheckable(true);
toolBar->addSeparator();
auto undo = toolBar->addAction(QIcon(":/svgicons/undo.svg"), "&Undo");
undo->setShortcut(QKeySequence::Undo);
undo->setEnabled(false);
QObject::connect(undo, &QAction::triggered, this, [this]() { shadercode_->undo(); });
QObject::connect(shadercode_, &QPlainTextEdit::undoAvailable, undo, &QAction::setEnabled);
auto redo = toolBar->addAction(QIcon(":/svgicons/redo.svg"), "&Redo");
redo->setShortcut(QKeySequence::Redo);
redo->setEnabled(false);
QObject::connect(redo, &QAction::triggered, this, [this]() { shadercode_->redo(); });
QObject::connect(shadercode_, &QPlainTextEdit::redoAvailable, redo, &QAction::setEnabled);
QObject::connect(preprocess_, &QAction::toggled, this, [=](bool checked) {
if (checked && shadercode_->document()->isModified()) {
QMessageBox msgBox(
QMessageBox::Question, "Shader Editor", "Do you want to save unsaved changes?",
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, this);
int retval = msgBox.exec();
if (retval == static_cast<int>(QMessageBox::Save)) {
this->save();
} else if (retval == static_cast<int>(QMessageBox::Cancel)) {
QSignalBlocker block(preprocess_);
preprocess_->setChecked(false);
return;
}
}
updateState();
});
QObject::connect(shadercode_, &QPlainTextEdit::modificationChanged, this,
&QDockWidget::setWindowModified);
shadercode_->installEventFilter(this);
mainWindow->setCentralWidget(shadercode_);
updateState();
loadState();
}
ShaderWidget::~ShaderWidget() = default;
void ShaderWidget::closeEvent(QCloseEvent* event) {
if (shadercode_->document()->isModified()) {
QMessageBox msgBox(QMessageBox::Question, "Shader Editor",
"Do you want to save unsaved changes?",
QMessageBox::Save | QMessageBox::Discard, this);
int retval = msgBox.exec();
if (retval == static_cast<int>(QMessageBox::Save)) {
save();
} else if (retval == static_cast<int>(QMessageBox::Cancel)) {
return;
}
}
InviwoDockWidget::closeEvent(event);
}
bool ShaderWidget::eventFilter(QObject* obj, QEvent* event) {
if (event->type() == QEvent::FocusIn) {
if (fileChangedInBackground_) {
queryReloadFile();
}
return false;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
}
void ShaderWidget::save() {
ignoreNextUpdate_ = true;
// get the non-const version from the manager.
if (auto resource = ShaderManager::getPtr()->getShaderResource(obj_->getResource()->key())) {
resource->setSource(utilqt::fromQString(shadercode_->toPlainText()));
shadercode_->document()->setModified(false);
} else {
LogWarn(fmt::format(
"Could not save, the ShaderResource \"{}\" was not found in the ShaderManager. The "
"ShaderResource needs to be registered with the ShaderManager for saving to work",
obj_->getResource()->key()));
}
}
void ShaderWidget::apply() {
ignoreNextUpdate_ = true;
if (!orignal_) {
orignal_ = obj_->getResource();
}
auto tmp = std::make_shared<StringShaderResource>(
"[tmp]", utilqt::fromQString(shadercode_->toPlainText()));
obj_->setResource(tmp);
setWindowTitle("<tmp file>[*]");
revert_->setEnabled(true);
shadercode_->document()->setModified(false);
}
void ShaderWidget::revert() {
if (orignal_) {
ignoreNextUpdate_ = true;
obj_->setResource(orignal_);
setWindowTitle(utilqt::toQString(obj_->getFileName()) + "[*]");
orignal_ = nullptr;
}
updateState();
}
void ShaderWidget::updateState() {
const bool checked = preprocess_->isChecked();
const auto code = obj_->print(false, checked);
const auto vPosition = shadercode_->verticalScrollBar()->value();
const auto hPosition = shadercode_->horizontalScrollBar()->value();
shadercode_->setPlainText(utilqt::toQString(code));
shadercode_->verticalScrollBar()->setValue(vPosition);
shadercode_->horizontalScrollBar()->setValue(hPosition);
if (checked) {
const auto lines = std::count(code.begin(), code.end(), '\n') + 1;
std::string::size_type width = 0;
for (size_t l = 0; l < static_cast<size_t>(lines); ++l) {
auto info = obj_->resolveLine(l);
auto pos = info.first.find_last_of('/');
width = std::max(width, info.first.size() - (pos + 1)); // note string::npos+1==0
}
const auto numberSize = std::to_string(lines).size();
shadercode_->setLineAnnotation([this, width, numberSize](int line) {
const auto&& [tag, num] = obj_->resolveLine(line - 1);
const auto pos = tag.find_last_of('/');
const auto file = std::string_view{tag}.substr(pos + 1);
return fmt::format(FMT_STRING("{0:<{2}}{1:>{3}}"), file, num, width + 1u, numberSize);
});
shadercode_->setAnnotationSpace(
[width, numberSize](int) { return static_cast<int>(width + 1 + numberSize); });
shadercode_->setLineAnnotationColor([this](int line, vec4 org) {
const auto&& [tag, num] = obj_->resolveLine(line - 1);
if (auto pos = tag.find_first_of('['); pos != std::string::npos) {
const auto resource = std::string_view{tag}.substr(0, pos);
auto hsv = color::rgb2hsv(vec3(org));
auto randH = static_cast<double>(std::hash<std::string_view>{}(resource)) /
static_cast<double>(std::numeric_limits<size_t>::max());
auto adjusted =
vec4{color::hsv2rgb(vec3(static_cast<float>(randH), std::max(0.75f, hsv.y),
std::max(0.25f, hsv.z))),
org.w};
return adjusted;
} else {
return org;
}
});
} else {
shadercode_->setLineAnnotation([](int line) { return std::to_string(line); });
shadercode_->setLineAnnotationColor([](int, vec4 org) { return org; });
shadercode_->setAnnotationSpace([](int maxDigits) { return maxDigits; });
}
shadercode_->setReadOnly(checked);
save_->setEnabled(!checked);
apply_->setEnabled(!checked);
preprocess_->setText(checked ? "Show Plain Shader Only" : "Show Preprocessed Shader");
shadercode_->document()->setModified(false);
}
inline void ShaderWidget::queryReloadFile() {
if (preprocess_->isChecked()) {
util::KeepTrueWhileInScope guard{&reloadQueryInProgress_};
updateState();
fileChangedInBackground_ = false;
return;
}
auto children = findChildren<QWidget*>();
auto focus =
std::any_of(children.begin(), children.end(), [](auto w) { return w->hasFocus(); });
if (focus && fileChangedInBackground_ && !reloadQueryInProgress_) {
util::KeepTrueWhileInScope guard{&reloadQueryInProgress_};
std::string msg =
"The shader source has been modified, do you want to reload its contents?";
QMessageBox msgBox(QMessageBox::Question, "Shader Editor", utilqt::toQString(msg),
QMessageBox::Yes | QMessageBox::No, this);
msgBox.setWindowModality(Qt::WindowModal);
if (msgBox.exec() == QMessageBox::Yes) {
updateState();
} else {
shadercode_->document()->setModified(true);
}
fileChangedInBackground_ = false;
}
}
void ShaderWidget::shaderObjectChanged() {
if (ignoreNextUpdate_) {
ignoreNextUpdate_ = false;
return;
}
fileChangedInBackground_ = true;
queryReloadFile();
}
} // namespace inviwo
| 5,421 |
2,338 | <reponame>mkinsner/llvm
int main() {
// Disable clang-format as it gets confused by the keyword identifiers.
// clang-format off
int alignas = 1;
int alignof = 1;
int and = 1;
int and_eq = 1;
int atomic_cancel = 1;
int atomic_commit = 1;
int atomic_noexcept = 1;
int bitand = 1;
int bitor = 1;
int bool = 1;
int catch = 1;
int char8_t = 1;
int char16_t = 1;
int char32_t = 1;
int class = 1;
int compl = 1;
int concept = 1;
int consteval = 1;
int constexpr = 1;
int constinit = 1;
int const_cast = 1;
int co_await = 1;
int co_return = 1;
int co_yield = 1;
int decltype = 1;
int delete = 1;
int dynamic_cast = 1;
int explicit = 1;
int export = 1;
int false = 1;
int friend = 1;
int mutable = 1;
int namespace = 1;
int new = 1;
int noexcept = 1;
int not = 1;
int not_eq = 1;
int operator= 1;
int or = 1;
int or_eq = 1;
int private = 1;
int protected = 1;
int public = 1;
int reflexpr = 1;
int reinterpret_cast = 1;
int requires = 1;
int static_assert = 1;
int static_cast = 1;
int synchronized = 1;
int template = 1;
int this = 1;
int thread_local = 1;
int throw = 1;
int true = 1;
int try = 1;
int typeid = 1;
int typename = 1;
int using = 1;
int virtual = 1;
int wchar_t = 1;
int xor = 1;
int xor_eq = 1;
// clang-format on
return 0; // break here
}
| 558 |
1,645 | /*
* Seldon -- open source prediction engine
* =======================================
*
* Copyright 2011-2015 Seldon Technologies Ltd and Rummble Ltd (http://www.seldon.io/)
*
* ********************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ********************************************************************************************
*/
package io.seldon.general.jdo;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.Collection;
import java.util.Iterator;
import io.seldon.general.Version;
import io.seldon.general.VersionPeer;
/**
* Created by: marc on 12/08/2011 at 16:21
*/
public class SqlVersionPeer implements VersionPeer {
private final PersistenceManager persistenceManager;
public SqlVersionPeer(PersistenceManager persistenceManager) {
this.persistenceManager = persistenceManager;
}
@SuppressWarnings({"unchecked"})
public Version getVersion() {
Query query = persistenceManager.newQuery(Version.class);
Collection<Version> retrieved = (Collection<Version>) query.execute();
Iterator<Version> iterator = retrieved.iterator();
return (iterator.hasNext() ? iterator.next() : null);
}
}
| 491 |
1,104 | <filename>Unisystem-Buffy or Angel/sheet.json
{
"html": "Buffy_or_Angel.html",
"css": "Buffy_or_Angel.css",
"authors": "MattBx8",
"roll20userid": "115594",
"preview": "Buffy_PC.jpg",
"instructions": "# Character Sheet\r## Whole Sheet:\rIn order for the font to show up correctly in Chrome, you will have to *load unsafe scripts* using the gray sheild in the address bar of the browser. \r ## Character tab\r Primary attribute names are buttons, rolling 1d10 plus twice the attribute. The Difficult button rolls 1d10 plus just the attribute.\r ## Skills and Spells tab:\rThe roll button rolls 1d10 plus skill ratingm plus the attribute selected in the dropdown menu. \r ## CombatTab:\rThe roll button rolls a 1d10, plus the listed skill rating as well as the damage. Damage is listed as the base damage and a multiplier. The multiplier should be already incorporated into the base damage, the multiplier is used when a two-handed weapon is used. When the two-handed checkbox adds strength plus one.\r##Possessions Tab:\rA place to list the gear you gathered..\r. ## Notes:/rPlaces to store information you have gathered while running from the walking dead\r\r## Modified from All Flesh Must Be Eaten character sheet by <NAME>.\r\r\r## Current Version: 1.0",
"legacy": true
} | 358 |
4,403 | package cn.hutool.core.collection;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.nio.charset.Charset;
/**
* 将Reader包装为一个按照行读取的Iterator<br>
* 此对象遍历结束后,应关闭之,推荐使用方式:
*
* <pre>
* LineIterator it = null;
* try {
* it = new LineIterator(reader);
* while (it.hasNext()) {
* String line = it.nextLine();
* // do something with line
* }
* } finally {
* it.close();
* }
* </pre>
*
* 此类来自于Apache Commons io
*
* @author looly
* @since 4.1.1
*/
public class LineIter extends ComputeIter<String> implements IterableIter<String>, Closeable, Serializable {
private static final long serialVersionUID = 1L;
private final BufferedReader bufferedReader;
/**
* 构造
*
* @param in {@link InputStream}
* @param charset 编码
* @throws IllegalArgumentException reader为null抛出此异常
*/
public LineIter(InputStream in, Charset charset) throws IllegalArgumentException {
this(IoUtil.getReader(in, charset));
}
/**
* 构造
*
* @param reader {@link Reader}对象,不能为null
* @throws IllegalArgumentException reader为null抛出此异常
*/
public LineIter(Reader reader) throws IllegalArgumentException {
Assert.notNull(reader, "Reader must not be null");
this.bufferedReader = IoUtil.getReader(reader);
}
// -----------------------------------------------------------------------
@Override
protected String computeNext() {
try {
while (true) {
String line = bufferedReader.readLine();
if (line == null) {
return null;
} else if (isValidLine(line)) {
return line;
}
// 无效行,则跳过进入下一行
}
} catch (IOException ioe) {
close();
throw new IORuntimeException(ioe);
}
}
/**
* 关闭Reader
*/
@Override
public void close() {
super.finish();
IoUtil.close(bufferedReader);
}
/**
* 重写此方法来判断是否每一行都被返回,默认全部为true
*
* @param line 需要验证的行
* @return 是否通过验证
*/
protected boolean isValidLine(String line) {
return true;
}
}
| 980 |
2,542 | <gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace std;
using namespace ServiceModel;
using namespace Management::HealthManager;
StringLiteral const TraceSource("ClusterUpgradeStateSnapshot");
UnhealthyState::UnhealthyState()
: ErrorCount(0)
, TotalCount(0)
{
}
UnhealthyState::UnhealthyState(ULONG errorCount, ULONG totalCount)
: ErrorCount(errorCount)
, TotalCount(totalCount)
{
}
bool UnhealthyState::operator == (UnhealthyState const & other) const
{
return ErrorCount == other.ErrorCount && TotalCount == other.TotalCount;
}
bool UnhealthyState::operator != (UnhealthyState const & other) const
{
return !(*this == other);
}
float UnhealthyState::GetUnhealthyPercent() const
{
return GetUnhealthyPercent(ErrorCount, TotalCount);
}
float UnhealthyState::GetUnhealthyPercent(ULONG errorCount, ULONG totalCount)
{
if (totalCount == 0)
{
return 0.0f;
}
return static_cast<float>(errorCount)* 100.0f / static_cast<float>(totalCount);
}
ClusterUpgradeStateSnapshot::ClusterUpgradeStateSnapshot()
: globalUnhealthyState_()
, upgradeDomainUnhealthyStates_()
{
}
ClusterUpgradeStateSnapshot::~ClusterUpgradeStateSnapshot()
{
}
ClusterUpgradeStateSnapshot::ClusterUpgradeStateSnapshot(ClusterUpgradeStateSnapshot && other)
: globalUnhealthyState_(move(other.globalUnhealthyState_))
, upgradeDomainUnhealthyStates_(move(other.upgradeDomainUnhealthyStates_))
{
}
ClusterUpgradeStateSnapshot & ClusterUpgradeStateSnapshot::operator = (ClusterUpgradeStateSnapshot && other)
{
if (this != &other)
{
globalUnhealthyState_ = move(other.globalUnhealthyState_);
upgradeDomainUnhealthyStates_ = move(other.upgradeDomainUnhealthyStates_);
}
return *this;
}
void ClusterUpgradeStateSnapshot::SetGlobalState(ULONG errorCount, ULONG totalCount)
{
globalUnhealthyState_.ErrorCount = errorCount;
globalUnhealthyState_.TotalCount = totalCount;
}
bool ClusterUpgradeStateSnapshot::IsValid() const
{
return globalUnhealthyState_.TotalCount > 0 && upgradeDomainUnhealthyStates_.size() > 0;
}
void ClusterUpgradeStateSnapshot::AddUpgradeDomainEntry(
std::wstring const & upgradeDomainName,
ULONG errorCount,
ULONG totalCount)
{
auto result = upgradeDomainUnhealthyStates_.insert(
UpgradeDomainStatusPair(upgradeDomainName, UnhealthyState(errorCount, totalCount)));
if (!result.second)
{
// The item is already in the map
result.first->second.ErrorCount = errorCount;
result.first->second.TotalCount = totalCount;
}
}
bool ClusterUpgradeStateSnapshot::HasUpgradeDomainEntry(std::wstring const & upgradeDomainName) const
{
return upgradeDomainUnhealthyStates_.find(upgradeDomainName) != upgradeDomainUnhealthyStates_.end();
}
Common::ErrorCode ClusterUpgradeStateSnapshot::TryGetUpgradeDomainEntry(
std::wstring const & upgradeDomainName,
__inout ULONG & errorCount,
__inout ULONG & totalCount) const
{
auto it = upgradeDomainUnhealthyStates_.find(upgradeDomainName);
if (it == upgradeDomainUnhealthyStates_.end())
{
return ErrorCode(ErrorCodeValue::NotFound);
}
errorCount = it->second.ErrorCount;
totalCount = it->second.TotalCount;
return ErrorCode::Success();
}
bool ClusterUpgradeStateSnapshot::IsGlobalDeltaRespected(
ULONG errorCount,
ULONG totalCount,
BYTE maxPercentDelta) const
{
return IsDeltaRespected(
GlobalUnhealthyState.ErrorCount,
GlobalUnhealthyState.TotalCount,
errorCount,
totalCount,
maxPercentDelta);
}
bool ClusterUpgradeStateSnapshot::IsDeltaRespected(
ULONG baselineErrorCount,
ULONG baselineTotalCount,
ULONG errorCount,
ULONG totalCount,
BYTE maxPercentDelta)
{
float baseUnhealthyPercent = UnhealthyState::GetUnhealthyPercent(baselineErrorCount, baselineTotalCount);
float newUnhealthyPercent = UnhealthyState::GetUnhealthyPercent(errorCount, totalCount);
return newUnhealthyPercent - baseUnhealthyPercent <= static_cast<float>(maxPercentDelta);
}
void ClusterUpgradeStateSnapshot::WriteTo(__in Common::TextWriter & w, Common::FormatOptions const &) const
{
if (!IsValid())
{
w.Write("-Invalid-");
}
else
{
w.Write("global:{0}/{1}, UDs:", globalUnhealthyState_.ErrorCount, globalUnhealthyState_.TotalCount);
for (auto const & entry : upgradeDomainUnhealthyStates_)
{
w.Write(" {0}:{1}/{2}", entry.first, entry.second.ErrorCount, entry.second.TotalCount);
}
}
}
| 1,623 |
1,062 | //
// LxGridViewFlowLayout.h
// LxGridView
//
#import <UIKit/UIKit.h>
@interface LxGridViewFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, assign) BOOL panGestureRecognizerEnable;
@end
@protocol LxGridViewDataSource <UICollectionViewDataSource>
@optional
- (void)collectionView:(UICollectionView *)collectionView
itemAtIndexPath:(NSIndexPath *)sourceIndexPath
willMoveToIndexPath:(NSIndexPath *)destinationIndexPath;
- (void)collectionView:(UICollectionView *)collectionView
itemAtIndexPath:(NSIndexPath *)sourceIndexPath
didMoveToIndexPath:(NSIndexPath *)destinationIndexPath;
- (BOOL)collectionView:(UICollectionView *)collectionView
canMoveItemAtIndexPath:(NSIndexPath *)indexPath;
- (BOOL)collectionView:(UICollectionView *)collectionView
itemAtIndexPath:(NSIndexPath *)sourceIndexPath
canMoveToIndexPath:(NSIndexPath *)destinationIndexPath;
@end
@protocol LxGridViewDelegateFlowLayout <UICollectionViewDelegateFlowLayout>
@optional
- (void)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
willBeginDraggingItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
didBeginDraggingItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
willEndDraggingItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
didEndDraggingItemAtIndexPath:(NSIndexPath *)indexPath;
@end | 645 |
334 | {
"method": "GET",
"resourceFormat": "/profile/profiles/me",
"requestUrl": "https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=1.0",
"requestHeaders": {
"Authorization": "bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im9PdmN6NU1fN3AtSGpJS2xGWHo5M3VfVjBabyJ9.eyJuYW1laWQiOiJkNjI0NWYyMC0yYWY4LTQ0ZjQtOTQ1MS04MTA3Y2IyNzY3ZGIiLCJzY3AiOiJwcmV2aWV3X2FwaV9hbGwgcHJldmlld19tc2RuX2xpY2Vuc2luZyIsImlzcyI6ImFwcC52c3Nwcy52aXN1YWxzdHVkaW8uY29tIiwiYXVkIjoiYXBwLnZzc3BzLnZpc3VhbHN0dWRpby5jb20iLCJuYmYiOjE0MTM1NjUyODMsImV4cCI6MTQxMzU2NjE4M30.d6TM4ENq7j9dJBS2G2GYBUexQGdlzoZWGiEn9GrQgMAoV-VFHX80q81HsnONusyExV8a_qDWUebmbM6_IjyhEtfn9aCKMjtPqNyubZAnebiA6fzxnYK1MKbinKeH6t2CweXcG7L7OkuVAQQ_GswHUUHZn7AnGqRHquh1brSVFafv4_9aObCKIXmaGhl5ohbSNiSQrEZ0IvtN5t2AG69HIOrA3BkFFdbrHiDNtjuAXWUVN06knaijuAFZVszFaPIEDr5_veVfRV70RsX7a4Q04wbbjTDJk98sYaqGXH0cjdSELeWJjMRapmdkxlDpSie1JgnuRwu_mAnsIdXL0hqzpg",
"Accept": "application/json"
},
"statusCode": 200,
"responseHeaders": {
"cache-control": "no-cache",
"pragma": "no-cache",
"content-type": "application/json; charset=utf-8; api-version=1.0",
"expires": "-1",
"last-modified": "Mon, 12 May 2014 22:23:07 GMT",
"etag": "\"1647\"",
"server": "Microsoft-IIS/8.5",
"x-tfs-processid": "282311fd-65e5-498e-979e-e47e50f69c95",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"x-frame-options": "SAMEORIGIN",
"set-cookie": [
"Tfs-SessionId=bc7b438c-e72f-0002-114b-35bd2fe7cf01; path=/; secure",
"Tfs-SessionActive=2014-10-17T17:01:43; path=/; secure"
],
"x-vss-userdata": "d6245f20-2af8-44f4-9451-8107cb2767db:<EMAIL>",
"activityid": "bc7b438c-e72f-0002-114b-35bd2fe7cf01",
"x-aspnet-version": "4.0.30319",
"x-powered-by": "ASP.NET",
"p3p": "CP=\"CAO DSP COR ADMa DEV CONo TELo CUR PSA PSD TAI IVDo OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR LOC CNT\"",
"x-content-type-options": "nosniff",
"date": "Fri, 17 Oct 2014 17:01:42 GMT",
"content-length": "252"
},
"responseBody": {
"displayName": "<NAME>",
"publicAlias": "d6245f20-2af8-44f4-9451-8107cb2767db",
"emailAddress": "<EMAIL>",
"coreRevision": 1647,
"timeStamp": "2014-05-12T22:23:07.727+00:00",
"id": "d6245f20-2af8-44f4-9451-8107cb2767db",
"revision": 1647
}
} | 1,393 |
14,668 | // Copyright 2017 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.
#ifndef IOS_CHROME_BROWSER_UI_MAIN_CONTENT_TEST_TEST_MAIN_CONTENT_UI_STATE_H_
#define IOS_CHROME_BROWSER_UI_MAIN_CONTENT_TEST_TEST_MAIN_CONTENT_UI_STATE_H_
#import "ios/chrome/browser/ui/main_content/main_content_ui_state.h"
// A test version of MainContentUIState that can be updated directly without
// the use of a MainContentUIStateUpdater.
@interface TestMainContentUIState : MainContentUIState
// Redefine broadcast properties as readwrite.
@property(nonatomic, assign) CGFloat yContentOffset;
@property(nonatomic, assign, getter=isScrolling) BOOL scrolling;
@property(nonatomic, assign, getter=isDragging) BOOL dragging;
@end
#endif // IOS_CHROME_BROWSER_UI_MAIN_CONTENT_TEST_TEST_MAIN_CONTENT_UI_STATE_H_
| 308 |
502 | <gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
/**
* API for removing old {@link Snapshot snapshots} from a table.
* <p>
* This API accumulates snapshot deletions and commits the new list to the table. This API does not
* allow deleting the current snapshot.
* <p>
* When committing, these changes will be applied to the latest table metadata. Commit conflicts
* will be resolved by applying the changes to the new latest metadata and reattempting the commit.
* <p>
* Manifest files that are no longer used by valid snapshots will be deleted. Data files that were
* deleted by snapshots that are expired will be deleted. {@link #deleteWith(Consumer)} can be used
* to pass an alternative deletion method.
*
* {@link #apply()} returns a list of the snapshots that will be removed.
*/
public interface ExpireSnapshots extends PendingUpdate<List<Snapshot>> {
/**
* Expires a specific {@link Snapshot} identified by id.
*
* @param snapshotId long id of the snapshot to expire
* @return this for method chaining
*/
ExpireSnapshots expireSnapshotId(long snapshotId);
/**
* Expires all snapshots older than the given timestamp.
*
* @param timestampMillis a long timestamp, as returned by {@link System#currentTimeMillis()}
* @return this for method chaining
*/
ExpireSnapshots expireOlderThan(long timestampMillis);
/**
* Retains the most recent ancestors of the current snapshot.
* <p>
* If a snapshot would be expired because it is older than the expiration timestamp, but is one of
* the {@code numSnapshots} most recent ancestors of the current state, it will be retained. This
* will not cause snapshots explicitly identified by id from expiring.
* <p>
* This may keep more than {@code numSnapshots} ancestors if snapshots are added concurrently. This
* may keep less than {@code numSnapshots} ancestors if the current table state does not have that many.
*
* @param numSnapshots the number of snapshots to retain
* @return this for method chaining
*/
ExpireSnapshots retainLast(int numSnapshots);
/**
* Passes an alternative delete implementation that will be used for manifests and data files.
* <p>
* Manifest files that are no longer used by valid snapshots will be deleted. Data files that were
* deleted by snapshots that are expired will be deleted.
* <p>
* If this method is not called, unnecessary manifests and data files will still be deleted.
*
* @param deleteFunc a function that will be called to delete manifests and data files
* @return this for method chaining
*/
ExpireSnapshots deleteWith(Consumer<String> deleteFunc);
/**
* Passes an alternative executor service that will be used for manifests and data files deletion.
* <p>
* Manifest files that are no longer used by valid snapshots will be deleted. Data files that were
* deleted by snapshots that are expired will be deleted.
* <p>
* If this method is not called, unnecessary manifests and data files will still be deleted using a single threaded
* executor service.
*
* @param executorService an executor service to parallelize tasks to delete manifests and data files
* @return this for method chaining
*/
ExpireSnapshots executeDeleteWith(ExecutorService executorService);
/**
* Passes an alternative executor service that will be used for planning.
* If this method is not called, the default worker pool will be used.
*
* @param executorService an executor service to plan
* @return this for method chaining
*/
ExpireSnapshots planWith(ExecutorService executorService);
/**
* Allows expiration of snapshots without any cleanup of underlying manifest or data files.
* <p>
* Allows control in removing data and manifest files which may be more efficiently removed using
* a distributed framework through the actions API.
*
* @param clean setting this to false will skip deleting expired manifests and files
* @return this for method chaining
*/
ExpireSnapshots cleanExpiredFiles(boolean clean);
}
| 1,313 |
380 | <gh_stars>100-1000
import sys
IS_WINDOWS = sys.platform.startswith('win')
if IS_WINDOWS:
from winreg import ConnectRegistry, OpenKey, QueryInfoKey, QueryValueEx, EnumKey, HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, \
HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_PERFORMANCE_DATA, HKEY_CURRENT_CONFIG, HKEY_DYN_DATA
import os
import enum
from .installed_software import InstalledSoftware
ROOTS_HIVES = {
"hkey_classes_root": HKEY_CLASSES_ROOT,
"hkey_current_user": HKEY_CURRENT_USER,
"hkey_local_machine": HKEY_LOCAL_MACHINE,
"hkey_users": HKEY_USERS,
"hkey_performance_data": HKEY_PERFORMANCE_DATA,
"hkey_current_config": HKEY_CURRENT_CONFIG,
"hkey_dyn_data": HKEY_DYN_DATA
}
class WindowsPath(enum.Enum):
"""
Enum do przechowywania scieżek, z których odczytujemy lokalnie na Windze zainstalowane oprogramowania
"""
hkey_local_machine = r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
hkey_local_machine_wow6432node = r'HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
class WindowsRegistry:
"""
Wybiera dane które są dostępne w rejestrze Windows
"""
def __init__(self):
self.__paths = [path for path in WindowsPath]
def __parse_key(self, key):
key = key.lower()
parts = key.split('\\')
root_hive_name = parts[0]
root_hive = ROOTS_HIVES.get(root_hive_name)
partial_key = '\\'.join(parts[1:])
if not root_hive:
raise Exception('root hive "{}" was not found'.format(root_hive_name))
return partial_key, root_hive
def __get_sub_keys(self, key):
partial_key, root_hive = self.__parse_key(key)
with ConnectRegistry(None, root_hive) as reg:
with OpenKey(reg, partial_key) as key_object:
sub_keys_count, values_count, last_modified = QueryInfoKey(key_object)
try:
for i in range(sub_keys_count):
sub_key_name = EnumKey(key_object, i)
yield sub_key_name
except WindowsError:
pass
def __get_values(self, key, fields):
partial_key, root_hive = self.__parse_key(key)
with ConnectRegistry(None, root_hive) as reg:
with OpenKey(reg, partial_key) as key_object:
data = {}
for field in fields:
try:
value, type = QueryValueEx(key_object, field)
data[field] = value
except WindowsError:
pass
return data
def __join_keys(self, path, *paths):
path = path.strip('/\\')
paths = map(lambda x: x.strip('/\\'), paths)
paths = list(paths)
result = os.path.join(path, *paths)
result = result.replace('/', '\\')
return result
def get_software_key(self, key):
all_key_softwares = []
for sub_key in self.__get_sub_keys(key):
path = self.__join_keys(key, sub_key)
value = self.__get_values(path,
['DisplayName', 'DisplayVersion', 'InstallDate', 'InstallLocation', 'Publisher'])
if value:
software = InstalledSoftware(value)
all_key_softwares.append(software.to_dict)
return all_key_softwares
def get_all_software(self):
all_softwares = []
paths = [path.value for path in WindowsPath]
for path in paths:
all_softwares.append({"key": path, "softwares": self.get_software_key(path)})
return all_softwares
| 2,084 |
521 | //
// ADJLinkResolution.h
// Adjust
//
// Created by <NAME>. on 26.04.21.
// Copyright © 2021 adjust GmbH. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ADJLinkResolution : NSObject
+ (void)resolveLinkWithUrl:(nonnull NSURL *)url
resolveUrlSuffixArray:(nullable NSArray<NSString *> *)resolveUrlSuffixArray
callback:(nonnull void (^)(NSURL *_Nullable resolvedLink))callback;
@end
| 163 |
381 | package org.apache.helix.task;
/*
* 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.
*/
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.apache.helix.task.beans.ScheduleBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Configuration for scheduling both one-time and recurring workflows in Helix
*/
public class ScheduleConfig {
private static final Logger LOG = LoggerFactory.getLogger(ScheduleConfig.class);
/** Enforce that a workflow can recur at most once per minute */
private static final long MIN_RECURRENCE_MILLIS = 60 * 1000;
private final Date _startTime;
private final TimeUnit _recurUnit;
private final Long _recurInterval;
private ScheduleConfig(Date startTime, TimeUnit recurUnit, Long recurInterval) {
_startTime = startTime;
_recurUnit = recurUnit;
_recurInterval = recurInterval;
}
/**
* When the workflow should be started
* @return Date object representing the start time
*/
public Date getStartTime() {
return _startTime;
}
/**
* The unit of the recurrence interval if this is a recurring workflow
* @return the recurrence interval unit, or null if this workflow is a one-time workflow
*/
public TimeUnit getRecurrenceUnit() {
return _recurUnit;
}
/**
* The magnitude of the recurrence interval if this is a recurring task
* @return the recurrence interval magnitude, or null if this workflow is a one-time workflow
*/
public Long getRecurrenceInterval() {
return _recurInterval;
}
/**
* Check if this workflow is recurring
* @return true if recurring, false if one-time
*/
public boolean isRecurring() {
return _recurUnit != null && _recurInterval != null;
}
/**
* Check if the configured schedule is valid given these constraints:
* <ul>
* <li>All workflows must have a start time</li>
* <li>Recurrence unit and interval must both be present if either is present</li>
* <li>Recurring workflows must have a positive interval magnitude</li>
* <li>Intervals must be at least one minute</li>
* </ul>
* @return true if valid, false if invalid
*/
public boolean isValid() {
// All schedules must have a start time even if they are recurring
if (_startTime == null) {
LOG.error("All schedules must have a start time!");
return false;
}
// Recurrence properties must both either be present or absent
if ((_recurUnit == null && _recurInterval != null)
|| (_recurUnit != null && _recurInterval == null)) {
LOG.error("Recurrence interval and unit must either both be present or both be absent");
return false;
}
// Only positive recurrence intervals are allowed if present
if (_recurInterval != null && _recurInterval <= 0) {
LOG.error("Recurrence interval must be positive");
return false;
}
// Enforce minimum interval length
if (_recurUnit != null) {
long converted = _recurUnit.toMillis(_recurInterval);
if (converted < MIN_RECURRENCE_MILLIS) {
LOG.error("Recurrence must be at least {} ms", MIN_RECURRENCE_MILLIS);
return false;
}
}
return true;
}
/**
* Create this configuration from a serialized bean
* @param bean flat configuration of the schedule
* @return instantiated ScheduleConfig
*/
public static ScheduleConfig from(ScheduleBean bean) {
return new ScheduleConfig(bean.startTime, bean.recurUnit, bean.recurInterval);
}
/**
* Create a schedule for a workflow that runs once at a specified time
* @param startTime the time to start the workflow
* @return instantiated ScheduleConfig
*/
public static ScheduleConfig oneTimeDelayedStart(Date startTime) {
return new ScheduleConfig(startTime, null, null);
}
/**
* Create a schedule for a recurring workflow that should start immediately
* @param recurUnit the unit of the recurrence interval
* @param recurInterval the magnitude of the recurrence interval
* @return instantiated ScheduleConfig
*/
public static ScheduleConfig recurringFromNow(TimeUnit recurUnit, long recurInterval) {
return new ScheduleConfig(new Date(), recurUnit, recurInterval);
}
/**
* Create a schedule for a recurring workflow that should start at a specific time
* @param startTime the time to start the workflow the first time, or null if now
* @param recurUnit the unit of the recurrence interval
* @param recurInterval the magnitude of the recurrence interval
* @return instantiated ScheduleConfig
*/
public static ScheduleConfig recurringFromDate(Date startTime, TimeUnit recurUnit,
long recurInterval) {
if (startTime == null) {
startTime = new Date();
}
return new ScheduleConfig(startTime, recurUnit, recurInterval);
}
}
| 1,672 |
575 | <reponame>Yannic/chromium<filename>components/autofill/core/browser/ui/payments/card_name_fix_flow_controller_impl.cc<gh_stars>100-1000
// Copyright 2019 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 "components/autofill/core/browser/ui/payments/card_name_fix_flow_controller_impl.h"
#include <utility>
#include "base/check.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "components/autofill/core/browser/autofill_metrics.h"
#include "components/autofill/core/browser/ui/payments/card_name_fix_flow_view.h"
#include "components/grit/components_scaled_resources.h"
#include "components/strings/grit/components_strings.h"
#include "ui/base/l10n/l10n_util.h"
namespace autofill {
CardNameFixFlowControllerImpl::CardNameFixFlowControllerImpl() {}
CardNameFixFlowControllerImpl::~CardNameFixFlowControllerImpl() {
if (card_name_fix_flow_view_)
card_name_fix_flow_view_->ControllerGone();
if (shown_ && !had_user_interaction_) {
AutofillMetrics::LogCardholderNameFixFlowPromptEvent(
AutofillMetrics::
CARDHOLDER_NAME_FIX_FLOW_PROMPT_CLOSED_WITHOUT_INTERACTION);
}
}
void CardNameFixFlowControllerImpl::Show(
CardNameFixFlowView* card_name_fix_flow_view,
const std::u16string& inferred_cardholder_name,
base::OnceCallback<void(const std::u16string&)> name_accepted_callback) {
DCHECK(!name_accepted_callback.is_null());
DCHECK(card_name_fix_flow_view);
if (card_name_fix_flow_view_)
card_name_fix_flow_view_->ControllerGone();
card_name_fix_flow_view_ = card_name_fix_flow_view;
name_accepted_callback_ = std::move(name_accepted_callback);
inferred_cardholder_name_ = inferred_cardholder_name;
AutofillMetrics::LogSaveCardCardholderNamePrefilled(
!inferred_cardholder_name_.empty());
card_name_fix_flow_view_->Show();
AutofillMetrics::LogCardholderNameFixFlowPromptEvent(
AutofillMetrics::CARDHOLDER_NAME_FIX_FLOW_PROMPT_SHOWN);
shown_ = true;
}
void CardNameFixFlowControllerImpl::OnConfirmNameDialogClosed() {
card_name_fix_flow_view_ = nullptr;
}
void CardNameFixFlowControllerImpl::OnNameAccepted(const std::u16string& name) {
AutofillMetrics::LogCardholderNameFixFlowPromptEvent(
AutofillMetrics::CARDHOLDER_NAME_FIX_FLOW_PROMPT_ACCEPTED);
had_user_interaction_ = true;
AutofillMetrics::LogSaveCardCardholderNameWasEdited(
inferred_cardholder_name_ != name);
std::u16string trimmed_name;
base::TrimWhitespace(name, base::TRIM_ALL, &trimmed_name);
std::move(name_accepted_callback_).Run(trimmed_name);
}
void CardNameFixFlowControllerImpl::OnDismissed() {
AutofillMetrics::LogCardholderNameFixFlowPromptEvent(
AutofillMetrics::CARDHOLDER_NAME_FIX_FLOW_PROMPT_DISMISSED);
had_user_interaction_ = true;
}
int CardNameFixFlowControllerImpl::GetIconId() const {
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
return IDR_AUTOFILL_GOOGLE_PAY_WITH_DIVIDER;
#else
return 0;
#endif
}
std::u16string CardNameFixFlowControllerImpl::GetCancelButtonLabel() const {
return l10n_util::GetStringUTF16(IDS_CANCEL);
}
std::u16string CardNameFixFlowControllerImpl::GetInferredCardholderName()
const {
return inferred_cardholder_name_;
}
std::u16string CardNameFixFlowControllerImpl::GetInferredNameTooltipText()
const {
return l10n_util::GetStringUTF16(
IDS_AUTOFILL_SAVE_CARD_PROMPT_CARDHOLDER_NAME_TOOLTIP);
}
std::u16string CardNameFixFlowControllerImpl::GetInputLabel() const {
return l10n_util::GetStringUTF16(
IDS_AUTOFILL_SAVE_CARD_PROMPT_CARDHOLDER_NAME);
}
std::u16string CardNameFixFlowControllerImpl::GetInputPlaceholderText() const {
return l10n_util::GetStringUTF16(
IDS_AUTOFILL_SAVE_CARD_PROMPT_CARDHOLDER_NAME);
}
std::u16string CardNameFixFlowControllerImpl::GetSaveButtonLabel() const {
#if defined(OS_IOS)
return l10n_util::GetStringUTF16(IDS_SAVE);
#else
return l10n_util::GetStringUTF16(
IDS_AUTOFILL_FIX_FLOW_PROMPT_SAVE_CARD_LABEL);
#endif
}
std::u16string CardNameFixFlowControllerImpl::GetTitleText() const {
return l10n_util::GetStringUTF16(
IDS_AUTOFILL_SAVE_CARD_CARDHOLDER_NAME_FIX_FLOW_HEADER);
}
} // namespace autofill
| 1,670 |
1,408 | package com.pancm.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pancm.dao.BaseDao;
import com.pancm.dao.cluster.StudentDao;
import com.pancm.pojo.Student;
import com.pancm.service.StudentService;
/**
*
* Title: StudentServiceImpl
* Description:
* 用户操作实现类
* Version:1.0.0
* @author pancm
* @date 2018年3月19日
*/
@Service
public class StudentServiceImpl extends BaseServiceImpl<Student> implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
protected BaseDao<Student> getMapper() {
return this.studentDao;
}
}
| 250 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.