max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
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 "chrome/browser/ui/app_list/search/ranking/burn_in_ranker.h"
namespace app_list {
void BurnInRanker::UpdateResultRanks(ResultsMap& results,
ProviderType provider) {
// TODO(crbug.com/1279686): Implement.
}
} // namespace app_list
| 165 |
764 | {"symbol": "ATT","address": "0x89Fb927240750c1B15d4743cd58440fc5f14A11C","overview":{"en": "ATT is a Decentralized Information Communication Protocol based on Blockchain Technology."},"email": "<EMAIL>","website": "https://www.attnetwork.org/","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/AChainGalaxy","telegram": "https://t.me/AchainGalaxyOfficial","github": "https://github.com/attnetwork/att_server"}} | 141 |
462 | <gh_stars>100-1000
# -*- test-case-name: txdav.base.propertystore.test.test_xattr -*-
##
# Copyright (c) 2010-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
"""
Property store using filesystem extended attributes.
"""
from __future__ import absolute_import
__all__ = [
"PropertyStore",
]
import sys
import errno
import urllib
from zlib import compress, decompress, error as ZlibError
from cPickle import UnpicklingError, loads as unpickle
from xattr import xattr
from twisted.python.reflect import namedAny
from txdav.xml.base import encodeXMLName
from txdav.xml.parser import WebDAVDocument
from txdav.base.propertystore.base import AbstractPropertyStore, PropertyName, \
validKey
from txdav.idav import PropertyStoreError
#
# RFC 2518 Section 12.13.1 says that removal of non-existing property is not an
# error. python-xattr on Linux fails with ENODATA in this case. On OS X, the
# xattr library fails with ENOATTR, which some versions of CPython do not
# expose. Its value is 93.
#
if sys.platform == "darwin" or sys.platform[:7] == "freebsd":
_ERRNO_NO_ATTR = getattr(errno, "ENOATTR", 93)
else:
_ERRNO_NO_ATTR = errno.ENODATA
class PropertyStore(AbstractPropertyStore):
"""
Property store using filesystem extended attributes.
This implementation uses <NAME>'s xattr package, available from::
http://undefined.org/python/#xattr
"""
# Mimic old xattr-prefix behavior by importing it directly.
deadPropertyXattrPrefix = namedAny(
"txweb2.dav.xattrprops.xattrPropertyStore.deadPropertyXattrPrefix"
)
# There is a 127 character limit for xattr keys so we need to
# compress/expand overly long namespaces to help stay under that limit now
# that GUIDs are also encoded in the keys.
_namespaceCompress = {
"urn:ietf:params:xml:ns:caldav": "CALDAV:",
"urn:ietf:params:xml:ns:carddav": "CARDDAV:",
"http://calendarserver.org/ns/": "CS:",
"http://cal.me.com/_namespace/": "ME:",
"http://twistedmatrix.com/xml_namespace/dav/": "TD:",
"http://twistedmatrix.com/xml_namespace/dav/private/": "TDP:",
}
_namespaceExpand = dict(
[(v, k) for k, v in _namespaceCompress.iteritems()]
)
def __init__(self, defaultuser, pathFactory):
"""
Initialize a L{PropertyStore}.
@param pathFactory: a 0-arg callable that returns the L{CachingFilePath}
to set extended attributes on.
"""
super(PropertyStore, self).__init__(defaultuser)
self._pathFactory = pathFactory
# self.attrs = xattr(path.path)
self.removed = set()
self.modified = {}
@property
def path(self):
return self._pathFactory()
@property
def attrs(self):
return xattr(self.path.path)
def __str__(self):
return "<%s %s>" % (self.__class__.__name__, self.path.path)
def _encodeKey(self, effective, compressNamespace=True):
qname, uid = effective
if compressNamespace:
namespace = self._namespaceCompress.get(qname.namespace,
qname.namespace)
else:
namespace = qname.namespace
result = urllib.quote(encodeXMLName(namespace, qname.name), safe="{}:")
if uid and uid != self._defaultUser:
result = uid + result
r = self.deadPropertyXattrPrefix + result
return r
def _decodeKey(self, name):
name = urllib.unquote(name[len(self.deadPropertyXattrPrefix):])
index1 = name.find("{")
index2 = name.find("}")
if (index1 is -1 or index2 is -1 or not len(name) > index2):
raise ValueError("Invalid encoded name: %r" % (name,))
if index1 == 0:
uid = self._defaultUser
else:
uid = name[:index1]
propnamespace = name[index1 + 1:index2]
propnamespace = self._namespaceExpand.get(propnamespace, propnamespace)
propname = name[index2 + 1:]
return PropertyName(propnamespace, propname), uid
#
# Required implementations
#
def _getitem_uid(self, key, uid):
validKey(key)
effectiveKey = (key, uid)
if effectiveKey in self.modified:
return self.modified[effectiveKey]
if effectiveKey in self.removed:
raise KeyError(key)
try:
try:
data = self.attrs[self._encodeKey(effectiveKey)]
except IOError, e:
if e.errno in [_ERRNO_NO_ATTR, errno.ENOENT]:
raise KeyError(key)
raise PropertyStoreError(e)
except KeyError:
# Check for uncompressed namespace
if effectiveKey[0].namespace in self._namespaceCompress:
try:
data = self.attrs[self._encodeKey(effectiveKey,
compressNamespace=False)]
except IOError, e:
raise KeyError(key)
try:
# Write it back using the compressed format
self.attrs[self._encodeKey(effectiveKey)] = data
del self.attrs[self._encodeKey(effectiveKey,
compressNamespace=False)]
except IOError, e:
msg = (
"Unable to upgrade property "
"to compressed namespace: %s" % (key.toString())
)
self.log.error(msg)
raise PropertyStoreError(msg)
else:
raise
#
# Unserialize XML data from an xattr. The storage format has changed
# over time:
#
# 1- Started with XML
# 2- Started compressing the XML due to limits on xattr size
# 3- Switched to pickle which is faster, still compressing
# 4- Back to compressed XML for interoperability, size
#
# We only write the current format, but we also read the old
# ones for compatibility.
#
legacy = False
try:
data = decompress(data)
except ZlibError:
legacy = True
try:
doc = WebDAVDocument.fromString(data)
except ValueError:
try:
doc = unpickle(data)
except UnpicklingError:
msg = "Invalid property value stored on server: %s %s" % (
key.toString(), data
)
self.log.error(msg)
raise PropertyStoreError(msg)
else:
legacy = True
if legacy:
# XXX untested: CDT catches this though.
self._setitem_uid(key, doc.root_element, uid)
return doc.root_element
def _setitem_uid(self, key, value, uid):
validKey(key)
effectiveKey = (key, uid)
if effectiveKey in self.removed:
self.removed.remove(effectiveKey)
self.modified[effectiveKey] = value
def _delitem_uid(self, key, uid):
validKey(key)
effectiveKey = (key, uid)
if effectiveKey in self.modified:
del self.modified[effectiveKey]
elif self._encodeKey(effectiveKey) not in self.attrs:
raise KeyError(key)
self.removed.add(effectiveKey)
def _keys_uid(self, uid):
seen = set()
try:
iterattr = iter(self.attrs)
except IOError, e:
if e.errno != errno.ENOENT:
raise
iterattr = iter(())
for key in iterattr:
if not key.startswith(self.deadPropertyXattrPrefix):
continue
effectivekey = self._decodeKey(key)
if effectivekey[1] == uid and effectivekey not in self.removed:
seen.add(effectivekey)
yield effectivekey[0]
for effectivekey in self.modified:
if effectivekey[1] == uid and effectivekey not in seen:
yield effectivekey[0]
def _removeResource(self):
# xattrs are removed when the underlying file is deleted so just clear
# out cached changes
self.removed.clear()
self.modified.clear()
#
# I/O
#
def flush(self):
# FIXME: The transaction may have deleted the file, and then obviously
# flushing would fail. Let's try to detect that scenario. The
# transaction should not attempt to flush properties if it is also
# deleting the resource, though, and there are other reasons we might
# want to know about that the file doesn't exist, so this should be
# fixed.
self.path.changed()
if not self.path.exists():
return
attrs = self.attrs
removed = self.removed
modified = self.modified
for key in removed:
assert key not in modified
try:
del attrs[self._encodeKey(key)]
except KeyError:
pass
except IOError, e:
if e.errno != _ERRNO_NO_ATTR:
raise
for key in modified:
assert key not in removed
value = modified[key]
attrs[self._encodeKey(key)] = compress(value.toxml())
self.removed.clear()
self.modified.clear()
def abort(self):
self.removed.clear()
self.modified.clear()
def copyAllProperties(self, other):
"""
Copy all the properties from another store into this one. This needs to be done
independently of the UID.
"""
try:
iterattr = iter(other.attrs)
except IOError, e:
if e.errno != errno.ENOENT:
raise
iterattr = iter(())
for key in iterattr:
if not key.startswith(self.deadPropertyXattrPrefix):
continue
self.attrs[key] = other.attrs[key]
| 4,821 |
2,743 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-03 07:28
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('document_states', '0006_auto_20170803_0651'),
]
operations = [
migrations.AlterField(
model_name='workflowinstancelogentry',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='User'),
),
migrations.AlterField(
model_name='workflowtransitiontriggerevent',
name='event_type',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='events.EventType', verbose_name='Event type'),
),
migrations.AlterField(
model_name='workflowtransitiontriggerevent',
name='transition',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='trigger_events', to='document_states.WorkflowTransition', verbose_name='Transition'),
),
]
| 519 |
12,718 | /*
* netevent.h
*
* Network events
*
* This file is part of the ReactOS PSDK package.
*
* Contributors:
* Created by <NAME> <<EMAIL>>
*
* THIS SOFTWARE IS NOT COPYRIGHTED
*
* This source code is offered for use in the public domain. You may
* use, modify or distribute it freely.
*
* This code is distributed in the hope that it will be useful but
* WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
* DISCLAIMED. This includes but is not limited to warranties of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#ifndef __NETEVENT_H
#define __NETEVENT_H
#ifdef __cplusplus
extern "C" {
#endif
#define COULD_NOT_VERIFY_VOLUMES __MSABI_LONG(0xC00037E8)
#define DFS_CONNECTION_FAILURE __MSABI_LONG(0x40003842)
#define DFS_ERROR_ACTIVEDIRECTORY_OFFLINE __MSABI_LONG(0xC00038BB)
#define DFS_ERROR_CLUSTERINFO_FAILED __MSABI_LONG(0xC00038B5)
#define DFS_ERROR_COMPUTERINFO_FAILED __MSABI_LONG(0xC00038B4)
#define DFS_ERROR_CREATEEVENT_FAILED __MSABI_LONG(0xC00038B3)
#define DFS_ERROR_CREATE_REPARSEPOINT_FAILURE __MSABI_LONG(0xC00038A7)
#define DFS_ERROR_CREATE_REPARSEPOINT_SUCCESS __MSABI_LONG(0x400038D2)
#define DFS_ERROR_CROSS_FOREST_TRUST_INFO_FAILED __MSABI_LONG(0xC00038D6)
#define DFS_ERROR_DCINFO_FAILED __MSABI_LONG(0xC00038B6)
#define DFS_ERROR_DSCONNECT_FAILED __MSABI_LONG(0x800038BE)
#define DFS_ERROR_DUPLICATE_LINK __MSABI_LONG(0xC00038D3)
#define DFS_ERROR_HANDLENAMESPACE_FAILED __MSABI_LONG(0xC00038B8)
#define DFS_ERROR_LINKS_OVERLAP __MSABI_LONG(0xC00038D0)
#define DFS_ERROR_LINK_OVERLAP __MSABI_LONG(0xC00038D1)
#define DFS_ERROR_MUTLIPLE_ROOTS_NOT_SUPPORTED __MSABI_LONG(0xC00038C7)
#define DFS_ERROR_NO_DFS_DATA __MSABI_LONG(0xC00038C2)
#define DFS_ERROR_ON_ROOT __MSABI_LONG(0x800038C6)
#define DFS_ERROR_OVERLAPPING_DIRECTORIES __MSABI_LONG(0xC00038A9)
#define DFS_ERROR_PREFIXTABLE_FAILED __MSABI_LONG(0xC00038B7)
#define DFS_ERROR_REFLECTIONENGINE_FAILED __MSABI_LONG(0xC00038BA)
#define DFS_ERROR_REGISTERSTORE_FAILED __MSABI_LONG(0xC00038B9)
#define DFS_ERROR_REMOVE_LINK_FAILED __MSABI_LONG(0xC00038CC)
#define DFS_ERROR_RESYNCHRONIZE_FAILED __MSABI_LONG(0xC00038CB)
#define DFS_ERROR_ROOTSYNCINIT_FAILED __MSABI_LONG(0xC00038B2)
#define DFS_ERROR_SECURITYINIT_FAILED __MSABI_LONG(0xC00038AF)
#define DFS_ERROR_SITECACHEINIT_FAILED __MSABI_LONG(0xC00038B1)
#define DFS_ERROR_SITESUPPOR_FAILED __MSABI_LONG(0xC00038BC)
#define DFS_ERROR_TARGET_LIST_INCORRECT __MSABI_LONG(0xC00038CF)
#define DFS_ERROR_THREADINIT_FAILED __MSABI_LONG(0xC00038B0)
#define DFS_ERROR_TOO_MANY_ERRORS __MSABI_LONG(0xC00038AD)
#define DFS_ERROR_TRUSTED_DOMAIN_INFO_FAILED __MSABI_LONG(0xC00038D4)
#define DFS_ERROR_UNSUPPORTED_FILESYSTEM __MSABI_LONG(0xC00038A8)
#define DFS_ERROR_WINSOCKINIT_FAILED __MSABI_LONG(0xC00038AE)
#define DFS_INFO_ACTIVEDIRECTORY_ONLINE __MSABI_LONG(0x400038AC)
#define DFS_INFO_CROSS_FOREST_TRUST_INFO_SUCCESS __MSABI_LONG(0x400038D7)
#define DFS_INFO_DOMAIN_REFERRAL_MIN_OVERFLOW __MSABI_LONG(0x400038C9)
#define DFS_INFO_DS_RECONNECTED __MSABI_LONG(0x400038C1)
#define DFS_INFO_FINISH_BUILDING_NAMESPACE __MSABI_LONG(0x400038C5)
#define DFS_INFO_FINISH_INIT __MSABI_LONG(0x400038C3)
#define DFS_INFO_RECONNECT_DATA __MSABI_LONG(0x400038C4)
#define DFS_INFO_TRUSTED_DOMAIN_INFO_SUCCESS __MSABI_LONG(0x400038D5)
#define DFS_MAX_DNR_ATTEMPTS __MSABI_LONG(0x40003845)
#define DFS_OPEN_FAILURE __MSABI_LONG(0x40003847)
#define DFS_REFERRAL_FAILURE __MSABI_LONG(0x40003843)
#define DFS_REFERRAL_REQUEST __MSABI_LONG(0x400037EE)
#define DFS_REFERRAL_SUCCESS __MSABI_LONG(0x40003844)
#define DFS_SPECIAL_REFERRAL_FAILURE __MSABI_LONG(0x40003846)
#define DFS_WARN_DOMAIN_REFERRAL_OVERFLOW __MSABI_LONG(0x800038C8)
#define DFS_WARN_INCOMPLETE_MOVE __MSABI_LONG(0x800038CA)
#define DFS_WARN_METADATA_LINK_INFO_INVALID __MSABI_LONG(0x800038CE)
#define DFS_WARN_METADATA_LINK_TYPE_INCORRECT __MSABI_LONG(0x800038CD)
#define EVENT_BAD_ACCOUNT_NAME __MSABI_LONG(0xC0001B60)
#define EVENT_BAD_SERVICE_STATE __MSABI_LONG(0xC0001B68)
#define EVENT_BOOT_SYSTEM_DRIVERS_FAILED __MSABI_LONG(0xC0001B72)
#define EVENT_BOWSER_CANT_READ_REGISTRY __MSABI_LONG(0x40001F5D)
#define EVENT_BOWSER_ELECTION_RECEIVED __MSABI_LONG(0x00001F4C)
#define EVENT_BOWSER_ELECTION_SENT_FIND_MASTER_FAILED __MSABI_LONG(0x40001F4E)
#define EVENT_BOWSER_ELECTION_SENT_GETBLIST_FAILED __MSABI_LONG(0x40001F4D)
#define EVENT_BOWSER_GETBROWSERLIST_THRESHOLD_EXCEEDED __MSABI_LONG(0x40001F5F)
#define EVENT_BOWSER_ILLEGAL_DATAGRAM __MSABI_LONG(0x80001F46)
#define EVENT_BOWSER_ILLEGAL_DATAGRAM_THRESHOLD __MSABI_LONG(0xC0001F50)
#define EVENT_BOWSER_MAILSLOT_DATAGRAM_THRESHOLD_EXCEEDED __MSABI_LONG(0x40001F5E)
#define EVENT_BOWSER_NAME_CONVERSION_FAILED __MSABI_LONG(0xC0001F4A)
#define EVENT_BOWSER_NON_MASTER_MASTER_ANNOUNCE __MSABI_LONG(0x80001F45)
#define EVENT_BOWSER_NON_PDC_WON_ELECTION __MSABI_LONG(0x40001F5C)
#define EVENT_BOWSER_OLD_BACKUP_FOUND __MSABI_LONG(0x40001F58)
#define EVENT_BOWSER_OTHER_MASTER_ON_NET __MSABI_LONG(0xC0001F43)
#define EVENT_BOWSER_PDC_LOST_ELECTION __MSABI_LONG(0x40001F5B)
#define EVENT_BOWSER_PROMOTED_WHILE_ALREADY_MASTER __MSABI_LONG(0x80001F44)
#define EVENT_BRIDGE_ADAPTER_BIND_FAILED __MSABI_LONG(0xC0003970)
#define EVENT_BRIDGE_ADAPTER_FILTER_FAILED __MSABI_LONG(0xC000396E)
#define EVENT_BRIDGE_ADAPTER_LINK_SPEED_QUERY_FAILED __MSABI_LONG(0xC000396C)
#define EVENT_BRIDGE_ADAPTER_MAC_ADDR_QUERY_FAILED __MSABI_LONG(0xC000396D)
#define EVENT_BRIDGE_ADAPTER_NAME_QUERY_FAILED __MSABI_LONG(0xC000396F)
#define EVENT_BRIDGE_BUFFER_POOL_CREATION_FAILED __MSABI_LONG(0xC0003912)
#define EVENT_BRIDGE_DEVICE_CREATION_FAILED __MSABI_LONG(0xC000390B)
#define EVENT_BRIDGE_ETHERNET_NOT_OFFERED __MSABI_LONG(0xC000390E)
#define EVENT_BRIDGE_INIT_MALLOC_FAILED __MSABI_LONG(0xC0003913)
#define EVENT_BRIDGE_MINIPORT_INIT_FAILED __MSABI_LONG(0xC000390D)
#define EVENT_BRIDGE_MINIPORT_REGISTER_FAILED __MSABI_LONG(0xC000390A)
#define EVENT_BRIDGE_MINIPROT_DEVNAME_MISSING __MSABI_LONG(0xC0003909)
#define EVENT_BRIDGE_NO_BRIDGE_MAC_ADDR __MSABI_LONG(0xC000390C)
#define EVENT_BRIDGE_PACKET_POOL_CREATION_FAILED __MSABI_LONG(0xC0003911)
#define EVENT_BRIDGE_PROTOCOL_REGISTER_FAILED __MSABI_LONG(0xC0003908)
#define EVENT_BRIDGE_THREAD_CREATION_FAILED __MSABI_LONG(0xC000390F)
#define EVENT_BRIDGE_THREAD_REF_FAILED __MSABI_LONG(0xC0003910)
#define EVENT_BROWSER_BACKUP_STOPPED __MSABI_LONG(0xC0001F60)
#define EVENT_BROWSER_DEPENDANT_SERVICE_FAILED __MSABI_LONG(0xC0001F51)
#define EVENT_BROWSER_DOMAIN_LIST_FAILED __MSABI_LONG(0x80001F56)
#define EVENT_BROWSER_DOMAIN_LIST_RETRIEVED __MSABI_LONG(0x00001F5A)
#define EVENT_BROWSER_ELECTION_SENT_LANMAN_NT_STARTED __MSABI_LONG(0x40001F4F)
#define EVENT_BROWSER_ELECTION_SENT_LANMAN_NT_STOPPED __MSABI_LONG(0x40001F61)
#define EVENT_BROWSER_ELECTION_SENT_ROLE_CHANGED __MSABI_LONG(0x40001F63)
#define EVENT_BROWSER_GETBLIST_RECEIVED_NOT_MASTER __MSABI_LONG(0xC0001F62)
#define EVENT_BROWSER_ILLEGAL_CONFIG __MSABI_LONG(0x80001F57)
#define EVENT_BROWSER_MASTER_PROMOTION_FAILED __MSABI_LONG(0xC0001F49)
#define EVENT_BROWSER_MASTER_PROMOTION_FAILED_NO_MASTER __MSABI_LONG(0xC0001F54)
#define EVENT_BROWSER_MASTER_PROMOTION_FAILED_STOPPING __MSABI_LONG(0xC0001F53)
#define EVENT_BROWSER_NOT_STARTED_IPX_CONFIG_MISMATCH __MSABI_LONG(0xC0001F64)
#define EVENT_BROWSER_OTHERDOMAIN_ADD_FAILED __MSABI_LONG(0xC0001F4B)
#define EVENT_BROWSER_ROLE_CHANGE_FAILED __MSABI_LONG(0xC0001F48)
#define EVENT_BROWSER_SERVER_LIST_FAILED __MSABI_LONG(0x80001F55)
#define EVENT_BROWSER_SERVER_LIST_RETRIEVED __MSABI_LONG(0x00001F59)
#define EVENT_BROWSER_STATUS_BITS_UPDATE_FAILED __MSABI_LONG(0xC0001F47)
#define EVENT_CALL_TO_FUNCTION_FAILED __MSABI_LONG(0xC0001B5D)
#define EVENT_CALL_TO_FUNCTION_FAILED_II __MSABI_LONG(0xC0001B5E)
#define EVENT_CIRCULAR_DEPENDENCY_AUTO __MSABI_LONG(0xC0001B6A)
#define EVENT_CIRCULAR_DEPENDENCY_DEMAND __MSABI_LONG(0xC0001B69)
#define EVENT_COMMAND_NOT_INTERACTIVE __MSABI_LONG(0xC0001EDC)
#define EVENT_COMMAND_START_FAILED __MSABI_LONG(0xC0001EDD)
#define EVENT_CONNECTION_TIMEOUT __MSABI_LONG(0xC0001B61)
#define EVENT_ComputerNameChange __MSABI_LONG(0x8000177B)
#define EVENT_DAV_REDIR_DELAYED_WRITE_FAILED __MSABI_LONG(0x800039D0)
#define EVENT_DCOM_ASSERTION_FAILURE __MSABI_LONG(0xC000271C)
#define EVENT_DCOM_COMPLUS_DISABLED __MSABI_LONG(0xC000271E)
#define EVENT_DCOM_INVALID_ENDPOINT_DATA __MSABI_LONG(0xC000271D)
#define EVENT_DEPEND_ON_LATER_GROUP __MSABI_LONG(0xC0001B6C)
#define EVENT_DEPEND_ON_LATER_SERVICE __MSABI_LONG(0xC0001B6B)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_NOTSUPP __MSABI_LONG(0x80002BAE)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_NOTSUPP_PRIMARY_DN __MSABI_LONG(0x80002BBA)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_OTHER __MSABI_LONG(0x80002BB1)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_OTHER_PRIMARY_DN __MSABI_LONG(0x80002BBD)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_REFUSED __MSABI_LONG(0x80002BAF)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_REFUSED_PRIMARY_DN __MSABI_LONG(0x80002BBB)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_SECURITY __MSABI_LONG(0x80002BB0)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_SECURITY_PRIMARY_DN __MSABI_LONG(0x80002BBC)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_SERVERFAIL __MSABI_LONG(0x80002BAD)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_SERVERFAIL_PRIMARY_DN __MSABI_LONG(0x80002BB9)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_TIMEOUT __MSABI_LONG(0x80002BAC)
#define EVENT_DNSAPI_DEREGISTRATION_FAILED_TIMEOUT_PRIMARY_DN __MSABI_LONG(0x80002BB8)
#define EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_NOTSUPP __MSABI_LONG(0x80002BB4)
#define EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_OTHER __MSABI_LONG(0x80002BB7)
#define EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_REFUSED __MSABI_LONG(0x80002BB5)
#define EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_SECURITY __MSABI_LONG(0x80002BB6)
#define EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_SERVERFAIL __MSABI_LONG(0x80002BB3)
#define EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_TIMEOUT __MSABI_LONG(0x80002BB2)
#define EVENT_DNSAPI_PTR_REGISTRATION_FAILED_NOTSUPP __MSABI_LONG(0x80002B96)
#define EVENT_DNSAPI_PTR_REGISTRATION_FAILED_OTHER __MSABI_LONG(0x80002B99)
#define EVENT_DNSAPI_PTR_REGISTRATION_FAILED_REFUSED __MSABI_LONG(0x80002B97)
#define EVENT_DNSAPI_PTR_REGISTRATION_FAILED_SECURITY __MSABI_LONG(0x80002B98)
#define EVENT_DNSAPI_PTR_REGISTRATION_FAILED_SERVERFAIL __MSABI_LONG(0x80002B95)
#define EVENT_DNSAPI_PTR_REGISTRATION_FAILED_TIMEOUT __MSABI_LONG(0x80002B94)
#define EVENT_DNSAPI_REGISTERED_ADAPTER __MSABI_LONG(0x40002BC0)
#define EVENT_DNSAPI_REGISTERED_ADAPTER_PRIMARY_DN __MSABI_LONG(0x40002BC2)
#define EVENT_DNSAPI_REGISTERED_PTR __MSABI_LONG(0x40002BC1)
#define EVENT_DNSAPI_REGISTRATION_FAILED_NOTSUPP __MSABI_LONG(0x80002B90)
#define EVENT_DNSAPI_REGISTRATION_FAILED_NOTSUPP_PRIMARY_DN __MSABI_LONG(0x80002B9C)
#define EVENT_DNSAPI_REGISTRATION_FAILED_OTHER __MSABI_LONG(0x80002B93)
#define EVENT_DNSAPI_REGISTRATION_FAILED_OTHER_PRIMARY_DN __MSABI_LONG(0x80002B9F)
#define EVENT_DNSAPI_REGISTRATION_FAILED_REFUSED __MSABI_LONG(0x80002B91)
#define EVENT_DNSAPI_REGISTRATION_FAILED_REFUSED_PRIMARY_DN __MSABI_LONG(0x80002B9D)
#define EVENT_DNSAPI_REGISTRATION_FAILED_SECURITY __MSABI_LONG(0x80002B92)
#define EVENT_DNSAPI_REGISTRATION_FAILED_SECURITY_PRIMARY_DN __MSABI_LONG(0x80002B9E)
#define EVENT_DNSAPI_REGISTRATION_FAILED_SERVERFAIL __MSABI_LONG(0x80002B8F)
#define EVENT_DNSAPI_REGISTRATION_FAILED_SERVERFAIL_PRIMARY_DN __MSABI_LONG(0x80002B9B)
#define EVENT_DNSAPI_REGISTRATION_FAILED_TIMEOUT __MSABI_LONG(0x80002B8E)
#define EVENT_DNSAPI_REGISTRATION_FAILED_TIMEOUT_PRIMARY_DN __MSABI_LONG(0x80002B9A)
#define EVENT_DNSDomainNameChange __MSABI_LONG(0x8000177C)
#define EVENT_DNS_CACHE_NETWORK_PERF_WARNING __MSABI_LONG(0x80002B2A)
#define EVENT_DNS_CACHE_START_FAILURE_LOW_MEMORY __MSABI_LONG(0xC0002AFF)
#define EVENT_DNS_CACHE_START_FAILURE_NO_CONTROL __MSABI_LONG(0xC0002AFA)
#define EVENT_DNS_CACHE_START_FAILURE_NO_DLL __MSABI_LONG(0xC0002AF8)
#define EVENT_DNS_CACHE_START_FAILURE_NO_DONE_EVENT __MSABI_LONG(0xC0002AFB)
#define EVENT_DNS_CACHE_START_FAILURE_NO_ENTRY __MSABI_LONG(0xC0002AF9)
#define EVENT_DNS_CACHE_START_FAILURE_NO_RPC __MSABI_LONG(0xC0002AFC)
#define EVENT_DNS_CACHE_START_FAILURE_NO_SHUTDOWN_NOTIFY __MSABI_LONG(0xC0002AFD)
#define EVENT_DNS_CACHE_START_FAILURE_NO_UPDATE __MSABI_LONG(0xC0002AFE)
#define EVENT_DNS_CACHE_UNABLE_TO_REACH_SERVER_WARNING __MSABI_LONG(0x80002B2B)
#define EVENT_EQOS_ERROR_MACHINE_POLICY_KEYNAME_SIZE_ZERO __MSABI_LONG(0xC0004142)
#define EVENT_EQOS_ERROR_MACHINE_POLICY_KEYNAME_TOO_LONG __MSABI_LONG(0xC0004140)
#define EVENT_EQOS_ERROR_MACHINE_POLICY_REFERESH __MSABI_LONG(0xC000413C)
#define EVENT_EQOS_ERROR_OPENING_MACHINE_POLICY_ROOT_KEY __MSABI_LONG(0xC000413E)
#define EVENT_EQOS_ERROR_OPENING_MACHINE_POLICY_SUBKEY __MSABI_LONG(0xC0004144)
#define EVENT_EQOS_ERROR_OPENING_USER_POLICY_ROOT_KEY __MSABI_LONG(0xC000413F)
#define EVENT_EQOS_ERROR_OPENING_USER_POLICY_SUBKEY __MSABI_LONG(0xC0004145)
#define EVENT_EQOS_ERROR_PROCESSING_MACHINE_POLICY_FIELD __MSABI_LONG(0xC0004146)
#define EVENT_EQOS_ERROR_PROCESSING_USER_POLICY_FIELD __MSABI_LONG(0xC0004147)
#define EVENT_EQOS_ERROR_SETTING_APP_MARKING __MSABI_LONG(0xC0004149)
#define EVENT_EQOS_ERROR_SETTING_TCP_AUTOTUNING __MSABI_LONG(0xC0004148)
#define EVENT_EQOS_ERROR_USER_POLICY_KEYNAME_SIZE_ZERO __MSABI_LONG(0xC0004143)
#define EVENT_EQOS_ERROR_USER_POLICY_KEYNAME_TOO_LONG __MSABI_LONG(0xC0004141)
#define EVENT_EQOS_ERROR_USER_POLICY_REFERESH __MSABI_LONG(0xC000413D)
#define EVENT_EQOS_INFO_APP_MARKING_ALLOWED __MSABI_LONG(0x4000407F)
#define EVENT_EQOS_INFO_APP_MARKING_IGNORED __MSABI_LONG(0x4000407E)
#define EVENT_EQOS_INFO_APP_MARKING_NOT_CONFIGURED __MSABI_LONG(0x4000407D)
#define EVENT_EQOS_INFO_LOCAL_SETTING_DONT_USE_NLA __MSABI_LONG(0x40004080)
#define EVENT_EQOS_INFO_MACHINE_POLICY_REFRESH_NO_CHANGE __MSABI_LONG(0x40004074)
#define EVENT_EQOS_INFO_MACHINE_POLICY_REFRESH_WITH_CHANGE __MSABI_LONG(0x40004075)
#define EVENT_EQOS_INFO_TCP_AUTOTUNING_HIGHLY_RESTRICTED __MSABI_LONG(0x4000407A)
#define EVENT_EQOS_INFO_TCP_AUTOTUNING_NORMAL __MSABI_LONG(0x4000407C)
#define EVENT_EQOS_INFO_TCP_AUTOTUNING_NOT_CONFIGURED __MSABI_LONG(0x40004078)
#define EVENT_EQOS_INFO_TCP_AUTOTUNING_OFF __MSABI_LONG(0x40004079)
#define EVENT_EQOS_INFO_TCP_AUTOTUNING_RESTRICTED __MSABI_LONG(0x4000407B)
#define EVENT_EQOS_INFO_USER_POLICY_REFRESH_NO_CHANGE __MSABI_LONG(0x40004076)
#define EVENT_EQOS_INFO_USER_POLICY_REFRESH_WITH_CHANGE __MSABI_LONG(0x40004077)
#define EVENT_EQOS_URL_QOS_APPLICATION_CONFLICT __MSABI_LONG(0x40004081)
#define EVENT_EQOS_WARNING_MACHINE_POLICY_CONFLICT __MSABI_LONG(0x800040E0)
#define EVENT_EQOS_WARNING_MACHINE_POLICY_NO_FULLPATH_APPNAME __MSABI_LONG(0x800040E2)
#define EVENT_EQOS_WARNING_MACHINE_POLICY_PROFILE_NOT_SPECIFIED __MSABI_LONG(0x800040DC)
#define EVENT_EQOS_WARNING_MACHINE_POLICY_QUOTA_EXCEEDED __MSABI_LONG(0x800040DE)
#define EVENT_EQOS_WARNING_MACHINE_POLICY_VERSION __MSABI_LONG(0x800040DA)
#define EVENT_EQOS_WARNING_TEST_1 __MSABI_LONG(0x800040D8)
#define EVENT_EQOS_WARNING_TEST_2 __MSABI_LONG(0x800040D9)
#define EVENT_EQOS_WARNING_USER_POLICY_CONFLICT __MSABI_LONG(0x800040E1)
#define EVENT_EQOS_WARNING_USER_POLICY_NO_FULLPATH_APPNAME __MSABI_LONG(0x800040E3)
#define EVENT_EQOS_WARNING_USER_POLICY_PROFILE_NOT_SPECIFIED __MSABI_LONG(0x800040DD)
#define EVENT_EQOS_WARNING_USER_POLICY_QUOTA_EXCEEDED __MSABI_LONG(0x800040DF)
#define EVENT_EQOS_WARNING_USER_POLICY_VERSION __MSABI_LONG(0x800040DB)
#define EVENT_EventLogProductInfo __MSABI_LONG(0x80001779)
#define EVENT_EventlogAbnormalShutdown __MSABI_LONG(0x80001778)
#define EVENT_EventlogStarted __MSABI_LONG(0x80001775)
#define EVENT_EventlogStopped __MSABI_LONG(0x80001776)
#define EVENT_EventlogUptime __MSABI_LONG(0x8000177D)
#define EVENT_FIRST_LOGON_FAILED __MSABI_LONG(0xC0001B65)
#define EVENT_FIRST_LOGON_FAILED_II __MSABI_LONG(0xC0001B7E)
#define EVENT_FRS_ACCESS_CHECKS_DISABLED __MSABI_LONG(0x800034CD)
#define EVENT_FRS_ACCESS_CHECKS_FAILED_UNKNOWN __MSABI_LONG(0xC00034CF)
#define EVENT_FRS_ACCESS_CHECKS_FAILED_USER __MSABI_LONG(0x800034CE)
#define EVENT_FRS_ASSERT __MSABI_LONG(0xC00034C2)
#define EVENT_FRS_BAD_REG_DATA __MSABI_LONG(0x800034EB)
#define EVENT_FRS_CANNOT_COMMUNICATE __MSABI_LONG(0xC00034C6)
#define EVENT_FRS_CANNOT_CREATE_UUID __MSABI_LONG(0xC00034D4)
#define EVENT_FRS_CANNOT_START_BACKUP_RESTORE_IN_PROGRESS __MSABI_LONG(0xC00034D1)
#define EVENT_FRS_CANT_OPEN_PREINSTALL __MSABI_LONG(0xC00034EF)
#define EVENT_FRS_CANT_OPEN_STAGE __MSABI_LONG(0xC00034EE)
#define EVENT_FRS_DATABASE_SPACE __MSABI_LONG(0xC00034C7)
#define EVENT_FRS_DISK_WRITE_CACHE_ENABLED __MSABI_LONG(0x800034C8)
#define EVENT_FRS_DS_POLL_ERROR_SUMMARY __MSABI_LONG(0x800034FA)
#define EVENT_FRS_DUPLICATE_IN_CXTION __MSABI_LONG(0xC00034F6)
#define EVENT_FRS_DUPLICATE_IN_CXTION_SYSVOL __MSABI_LONG(0xC00034F5)
#define EVENT_FRS_ERROR __MSABI_LONG(0xC00034BC)
#define EVENT_FRS_ERROR_REPLICA_SET_DELETED __MSABI_LONG(0x800034F8)
#define EVENT_FRS_HUGE_FILE __MSABI_LONG(0x800034D3)
#define EVENT_FRS_IN_ERROR_STATE __MSABI_LONG(0xC00034F3)
#define EVENT_FRS_JET_1414 __MSABI_LONG(0xC00034C9)
#define EVENT_FRS_JOIN_FAIL_TIME_SKEW __MSABI_LONG(0xC00034EC)
#define EVENT_FRS_LONG_JOIN __MSABI_LONG(0x800034C4)
#define EVENT_FRS_LONG_JOIN_DONE __MSABI_LONG(0x800034C5)
#define EVENT_FRS_MOVED_PREEXISTING __MSABI_LONG(0x800034D0)
#define EVENT_FRS_NO_DNS_ATTRIBUTE __MSABI_LONG(0x800034D5)
#define EVENT_FRS_NO_SID __MSABI_LONG(0xC00034D6)
#define EVENT_FRS_OVERLAPS_LOGGING __MSABI_LONG(0xC00034E5)
#define EVENT_FRS_OVERLAPS_OTHER_STAGE __MSABI_LONG(0xC00034E9)
#define EVENT_FRS_OVERLAPS_ROOT __MSABI_LONG(0xC00034E8)
#define EVENT_FRS_OVERLAPS_STAGE __MSABI_LONG(0xC00034E7)
#define EVENT_FRS_OVERLAPS_WORKING __MSABI_LONG(0xC00034E6)
#define EVENT_FRS_PREPARE_ROOT_FAILED __MSABI_LONG(0xC00034EA)
#define EVENT_FRS_REPLICA_IN_JRNL_WRAP_ERROR __MSABI_LONG(0xC00034F9)
#define EVENT_FRS_REPLICA_NO_ROOT_CHANGE __MSABI_LONG(0xC00034F4)
#define EVENT_FRS_REPLICA_SET_CREATE_FAIL __MSABI_LONG(0xC00034F0)
#define EVENT_FRS_REPLICA_SET_CREATE_OK __MSABI_LONG(0x400034F1)
#define EVENT_FRS_REPLICA_SET_CXTIONS __MSABI_LONG(0x400034F2)
#define EVENT_FRS_RMTCO_TIME_SKEW __MSABI_LONG(0xC00034ED)
#define EVENT_FRS_ROOT_HAS_MOVED __MSABI_LONG(0xC00034F7)
#define EVENT_FRS_ROOT_NOT_VALID __MSABI_LONG(0xC00034E3)
#define EVENT_FRS_STAGE_NOT_VALID __MSABI_LONG(0xC00034E4)
#define EVENT_FRS_STAGING_AREA_FULL __MSABI_LONG(0x800034D2)
#define EVENT_FRS_STARTING __MSABI_LONG(0x400034BD)
#define EVENT_FRS_STOPPED __MSABI_LONG(0x400034BF)
#define EVENT_FRS_STOPPED_ASSERT __MSABI_LONG(0xC00034C1)
#define EVENT_FRS_STOPPED_FORCE __MSABI_LONG(0xC00034C0)
#define EVENT_FRS_STOPPING __MSABI_LONG(0x400034BE)
#define EVENT_FRS_SYSVOL_NOT_READY __MSABI_LONG(0x800034CA)
#define EVENT_FRS_SYSVOL_NOT_READY_PRIMARY __MSABI_LONG(0x800034CB)
#define EVENT_FRS_SYSVOL_READY __MSABI_LONG(0x400034CC)
#define EVENT_FRS_VOLUME_NOT_SUPPORTED __MSABI_LONG(0xC00034C3)
#define EVENT_INVALID_DRIVER_DEPENDENCY __MSABI_LONG(0xC0001B67)
#define EVENT_IPX_CREATE_DEVICE __MSABI_LONG(0xC0002522)
#define EVENT_IPX_ILLEGAL_CONFIG __MSABI_LONG(0x8000251F)
#define EVENT_IPX_INTERNAL_NET_INVALID __MSABI_LONG(0xC0002520)
#define EVENT_IPX_NEW_DEFAULT_TYPE __MSABI_LONG(0x4000251D)
#define EVENT_IPX_NO_ADAPTERS __MSABI_LONG(0xC0002523)
#define EVENT_IPX_NO_FRAME_TYPES __MSABI_LONG(0xC0002521)
#define EVENT_IPX_SAP_ANNOUNCE __MSABI_LONG(0x8000251E)
#define EVENT_NBT_BAD_BACKUP_WINS_ADDR __MSABI_LONG(0x800010D0)
#define EVENT_NBT_BAD_PRIMARY_WINS_ADDR __MSABI_LONG(0x800010D1)
#define EVENT_NBT_CREATE_ADDRESS __MSABI_LONG(0xC00010D3)
#define EVENT_NBT_CREATE_CONNECTION __MSABI_LONG(0xC00010D4)
#define EVENT_NBT_CREATE_DEVICE __MSABI_LONG(0xC00010D7)
#define EVENT_NBT_CREATE_DRIVER __MSABI_LONG(0xC00010CC)
#define EVENT_NBT_DUPLICATE_NAME __MSABI_LONG(0xC00010DF)
#define EVENT_NBT_DUPLICATE_NAME_ERROR __MSABI_LONG(0xC00010E1)
#define EVENT_NBT_NAME_RELEASE __MSABI_LONG(0xC00010E0)
#define EVENT_NBT_NAME_SERVER_ADDRS __MSABI_LONG(0xC00010D2)
#define EVENT_NBT_NON_OS_INIT __MSABI_LONG(0xC00010D5)
#define EVENT_NBT_NO_BACKUP_WINS __MSABI_LONG(0x800010CE)
#define EVENT_NBT_NO_DEVICES __MSABI_LONG(0x800010D8)
#define EVENT_NBT_NO_RESOURCES __MSABI_LONG(0xC00010E2)
#define EVENT_NBT_NO_WINS __MSABI_LONG(0x800010CF)
#define EVENT_NBT_OPEN_REG_LINKAGE __MSABI_LONG(0xC00010D9)
#define EVENT_NBT_OPEN_REG_NAMESERVER __MSABI_LONG(0x800010DC)
#define EVENT_NBT_OPEN_REG_PARAMS __MSABI_LONG(0xC00010CD)
#define EVENT_NBT_READ_BIND __MSABI_LONG(0xC00010DA)
#define EVENT_NBT_READ_EXPORT __MSABI_LONG(0xC00010DB)
#define EVENT_NBT_TIMERS __MSABI_LONG(0xC00010D6)
#define EVENT_NDIS_ADAPTER_CHECK_ERROR __MSABI_LONG(0xC00013A7)
#define EVENT_NDIS_ADAPTER_DISABLED __MSABI_LONG(0x80001396)
#define EVENT_NDIS_ADAPTER_NOT_FOUND __MSABI_LONG(0xC000138B)
#define EVENT_NDIS_BAD_IO_BASE_ADDRESS __MSABI_LONG(0xC0001394)
#define EVENT_NDIS_BAD_VERSION __MSABI_LONG(0xC000138E)
#define EVENT_NDIS_CABLE_DISCONNECTED_ERROR __MSABI_LONG(0x800013A9)
#define EVENT_NDIS_DMA_CONFLICT __MSABI_LONG(0x8000139B)
#define EVENT_NDIS_DRIVER_FAILURE __MSABI_LONG(0xC000138D)
#define EVENT_NDIS_HARDWARE_FAILURE __MSABI_LONG(0xC000138A)
#define EVENT_NDIS_INTERRUPT_CONFLICT __MSABI_LONG(0x8000139A)
#define EVENT_NDIS_INTERRUPT_CONNECT __MSABI_LONG(0xC000138C)
#define EVENT_NDIS_INVALID_DOWNLOAD_FILE_ERROR __MSABI_LONG(0xC000139C)
#define EVENT_NDIS_INVALID_VALUE_FROM_ADAPTER __MSABI_LONG(0xC0001392)
#define EVENT_NDIS_IO_PORT_CONFLICT __MSABI_LONG(0x80001397)
#define EVENT_NDIS_LOBE_FAILUE_ERROR __MSABI_LONG(0x800013A3)
#define EVENT_NDIS_MAXFRAMESIZE_ERROR __MSABI_LONG(0x8000139F)
#define EVENT_NDIS_MAXINTERNALBUFS_ERROR __MSABI_LONG(0x800013A0)
#define EVENT_NDIS_MAXMULTICAST_ERROR __MSABI_LONG(0x800013A1)
#define EVENT_NDIS_MAXRECEIVES_ERROR __MSABI_LONG(0x8000139D)
#define EVENT_NDIS_MAXTRANSMITS_ERROR __MSABI_LONG(0x8000139E)
#define EVENT_NDIS_MEMORY_CONFLICT __MSABI_LONG(0x80001399)
#define EVENT_NDIS_MISSING_CONFIGURATION_PARAMETER __MSABI_LONG(0xC0001393)
#define EVENT_NDIS_NETWORK_ADDRESS __MSABI_LONG(0xC0001390)
#define EVENT_NDIS_OUT_OF_RESOURCE __MSABI_LONG(0xC0001389)
#define EVENT_NDIS_PORT_OR_DMA_CONFLICT __MSABI_LONG(0x80001398)
#define EVENT_NDIS_PRODUCTID_ERROR __MSABI_LONG(0x800013A2)
#define EVENT_NDIS_RECEIVE_SPACE_SMALL __MSABI_LONG(0x40001395)
#define EVENT_NDIS_REMOVE_RECEIVED_ERROR __MSABI_LONG(0x800013A5)
#define EVENT_NDIS_RESET_FAILURE_CORRECTION __MSABI_LONG(0x800013AA)
#define EVENT_NDIS_RESET_FAILURE_ERROR __MSABI_LONG(0x800013A8)
#define EVENT_NDIS_RESOURCE_CONFLICT __MSABI_LONG(0xC0001388)
#define EVENT_NDIS_SIGNAL_LOSS_ERROR __MSABI_LONG(0x800013A4)
#define EVENT_NDIS_TIMEOUT __MSABI_LONG(0x8000138F)
#define EVENT_NDIS_TOKEN_RING_CORRECTION __MSABI_LONG(0x400013A6)
#define EVENT_NDIS_UNSUPPORTED_CONFIGURATION __MSABI_LONG(0xC0001391)
#define EVENT_PS_ADMISSIONCONTROL_OVERFLOW __MSABI_LONG(0x8000371F)
#define EVENT_PS_BAD_BESTEFFORT_LIMIT __MSABI_LONG(0x80003714)
#define EVENT_PS_BINDING_FAILED __MSABI_LONG(0xC0003718)
#define EVENT_PS_GPC_REGISTER_FAILED __MSABI_LONG(0xC00036B0)
#define EVENT_PS_INIT_DEVICE_FAILED __MSABI_LONG(0xC000371B)
#define EVENT_PS_MISSING_ADAPTER_REGISTRY_DATA __MSABI_LONG(0xC0003719)
#define EVENT_PS_NETWORK_ADDRESS_FAIL __MSABI_LONG(0xC0003720)
#define EVENT_PS_NO_RESOURCES_FOR_INIT __MSABI_LONG(0xC00036B1)
#define EVENT_PS_QUERY_OID_GEN_LINK_SPEED __MSABI_LONG(0xC0003717)
#define EVENT_PS_QUERY_OID_GEN_MAXIMUM_FRAME_SIZE __MSABI_LONG(0xC0003715)
#define EVENT_PS_QUERY_OID_GEN_MAXIMUM_TOTAL_SIZE __MSABI_LONG(0xC0003716)
#define EVENT_PS_REGISTER_ADDRESS_FAMILY_FAILED __MSABI_LONG(0xC000371A)
#define EVENT_PS_REGISTER_MINIPORT_FAILED __MSABI_LONG(0xC00036B3)
#define EVENT_PS_REGISTER_PROTOCOL_FAILED __MSABI_LONG(0xC00036B2)
#define EVENT_PS_RESOURCE_POOL __MSABI_LONG(0xC000371E)
#define EVENT_PS_WAN_LIMITED_BESTEFFORT __MSABI_LONG(0x8000371D)
#define EVENT_PS_WMI_INSTANCE_NAME_FAILED __MSABI_LONG(0xC000371C)
#define EVENT_RDR_AT_THREAD_MAX __MSABI_LONG(0x80000BD2)
#define EVENT_RDR_CANT_BIND_TRANSPORT __MSABI_LONG(0x80000BD8)
#define EVENT_RDR_CANT_BUILD_SMB_HEADER __MSABI_LONG(0x80000BDB)
#define EVENT_RDR_CANT_CREATE_DEVICE __MSABI_LONG(0x80000BBA)
#define EVENT_RDR_CANT_CREATE_THREAD __MSABI_LONG(0x80000BBB)
#define EVENT_RDR_CANT_GET_SECURITY_CONTEXT __MSABI_LONG(0x80000BDA)
#define EVENT_RDR_CANT_READ_REGISTRY __MSABI_LONG(0x80000BD3)
#define EVENT_RDR_CANT_REGISTER_ADDRESS __MSABI_LONG(0x80000BD9)
#define EVENT_RDR_CANT_SET_THREAD __MSABI_LONG(0x80000BBC)
#define EVENT_RDR_CLOSE_BEHIND __MSABI_LONG(0x80000BC3)
#define EVENT_RDR_CONNECTION __MSABI_LONG(0x80000BCB)
#define EVENT_RDR_CONNECTION_REFERENCE __MSABI_LONG(0x80000BC7)
#define EVENT_RDR_CONTEXTS __MSABI_LONG(0x80000BD0)
#define EVENT_RDR_DELAYED_SET_ATTRIBUTES_FAILED __MSABI_LONG(0x80000BD6)
#define EVENT_RDR_DELETEONCLOSE_FAILED __MSABI_LONG(0x80000BD7)
#define EVENT_RDR_DISPOSITION __MSABI_LONG(0x80000BCF)
#define EVENT_RDR_ENCRYPT __MSABI_LONG(0x80000BCA)
#define EVENT_RDR_FAILED_UNLOCK __MSABI_LONG(0x80000BC1)
#define EVENT_RDR_INVALID_LOCK_REPLY __MSABI_LONG(0x80000BBF)
#define EVENT_RDR_INVALID_OPLOCK __MSABI_LONG(0x80000BC6)
#define EVENT_RDR_INVALID_REPLY __MSABI_LONG(0x80000BBD)
#define EVENT_RDR_INVALID_SMB __MSABI_LONG(0x80000BBE)
#define EVENT_RDR_MAXCMDS __MSABI_LONG(0x80000BCD)
#define EVENT_RDR_OPLOCK_SMB __MSABI_LONG(0x80000BCE)
#define EVENT_RDR_PRIMARY_TRANSPORT_CONNECT_FAILED __MSABI_LONG(0x80000BD5)
#define EVENT_RDR_RESOURCE_SHORTAGE __MSABI_LONG(0x80000BB9)
#define EVENT_RDR_SECURITY_SIGNATURE_MISMATCH __MSABI_LONG(0x80000BDC)
#define EVENT_RDR_SERVER_REFERENCE __MSABI_LONG(0x80000BC8)
#define EVENT_RDR_SMB_REFERENCE __MSABI_LONG(0x80000BC9)
#define EVENT_RDR_TIMEOUT __MSABI_LONG(0x80000BC5)
#define EVENT_RDR_TIMEZONE_BIAS_TOO_LARGE __MSABI_LONG(0x80000BD4)
#define EVENT_RDR_UNEXPECTED_ERROR __MSABI_LONG(0x80000BC4)
#define EVENT_RDR_WRITE_BEHIND_FLUSH_FAILED __MSABI_LONG(0x80000BD1)
#define EVENT_READFILE_TIMEOUT __MSABI_LONG(0xC0001B62)
#define EVENT_REVERTED_TO_LASTKNOWNGOOD __MSABI_LONG(0xC0001B5F)
#define EVENT_RPCSS_ACTIVATION_ERROR __MSABI_LONG(0xC0002717)
#define EVENT_RPCSS_CREATEPROCESS_FAILURE __MSABI_LONG(0xC0002710)
#define EVENT_RPCSS_DEFAULT_LAUNCH_ACCESS_DENIED __MSABI_LONG(0xC0002713)
#define EVENT_RPCSS_LAUNCH_ACCESS_DENIED __MSABI_LONG(0xC0002712)
#define EVENT_RPCSS_REMOTE_SIDE_ERROR __MSABI_LONG(0xC0002716)
#define EVENT_RPCSS_REMOTE_SIDE_ERROR_WITH_FILE __MSABI_LONG(0xC0002718)
#define EVENT_RPCSS_REMOTE_SIDE_UNAVAILABLE __MSABI_LONG(0xC0002719)
#define EVENT_RPCSS_RUNAS_CANT_LOGIN __MSABI_LONG(0xC0002714)
#define EVENT_RPCSS_RUNAS_CREATEPROCESS_FAILURE __MSABI_LONG(0xC0002711)
#define EVENT_RPCSS_SERVER_NOT_RESPONDING __MSABI_LONG(0xC000271B)
#define EVENT_RPCSS_SERVER_START_TIMEOUT __MSABI_LONG(0xC000271A)
#define EVENT_RPCSS_START_SERVICE_FAILURE __MSABI_LONG(0xC0002715)
#define EVENT_RUNNING_LASTKNOWNGOOD __MSABI_LONG(0xC0001B73)
#define EVENT_SCOPE_LABEL_TOO_LONG __MSABI_LONG(0x800010DD)
#define EVENT_SCOPE_TOO_LONG __MSABI_LONG(0x800010DE)
#define EVENT_SECOND_LOGON_FAILED __MSABI_LONG(0xC0001B66)
#define EVENT_SERVICE_CONFIG_BACKOUT_FAILED __MSABI_LONG(0xC0001B7D)
#define EVENT_SERVICE_CONTROL_SUCCESS __MSABI_LONG(0x40001B7B)
#define EVENT_SERVICE_CRASH __MSABI_LONG(0xC0001B77)
#define EVENT_SERVICE_CRASH_NO_ACTION __MSABI_LONG(0xC0001B7A)
#define EVENT_SERVICE_DIFFERENT_PID_CONNECTED __MSABI_LONG(0x80001B7F)
#define EVENT_SERVICE_EXIT_FAILED __MSABI_LONG(0xC0001B6F)
#define EVENT_SERVICE_EXIT_FAILED_SPECIFIC __MSABI_LONG(0xC0001B70)
#define EVENT_SERVICE_LOGON_TYPE_NOT_GRANTED __MSABI_LONG(0xC0001B81)
#define EVENT_SERVICE_NOT_INTERACTIVE __MSABI_LONG(0xC0001B76)
#define EVENT_SERVICE_RECOVERY_FAILED __MSABI_LONG(0xC0001B78)
#define EVENT_SERVICE_SCESRV_FAILED __MSABI_LONG(0xC0001B79)
#define EVENT_SERVICE_SHUTDOWN_FAILED __MSABI_LONG(0xC0001B83)
#define EVENT_SERVICE_START_AT_BOOT_FAILED __MSABI_LONG(0xC0001B71)
#define EVENT_SERVICE_START_FAILED __MSABI_LONG(0xC0001B58)
#define EVENT_SERVICE_START_FAILED_GROUP __MSABI_LONG(0xC0001B5A)
#define EVENT_SERVICE_START_FAILED_II __MSABI_LONG(0xC0001B59)
#define EVENT_SERVICE_START_FAILED_NONE __MSABI_LONG(0xC0001B5B)
#define EVENT_SERVICE_START_HUNG __MSABI_LONG(0xC0001B6E)
#define EVENT_SERVICE_START_TYPE_CHANGED __MSABI_LONG(0x40001B80)
#define EVENT_SERVICE_STATUS_SUCCESS __MSABI_LONG(0x40001B7C)
#define EVENT_SERVICE_STOP_SUCCESS_WITH_REASON __MSABI_LONG(0x40001B82)
#define EVENT_SEVERE_SERVICE_FAILED __MSABI_LONG(0xC0001B6D)
#define EVENT_SRV_CANT_BIND_DUP_NAME __MSABI_LONG(0xC00009C9)
#define EVENT_SRV_CANT_BIND_TO_TRANSPORT __MSABI_LONG(0x800009C8)
#define EVENT_SRV_CANT_CHANGE_DOMAIN_NAME __MSABI_LONG(0x800009D0)
#define EVENT_SRV_CANT_CREATE_DEVICE __MSABI_LONG(0xC00007D2)
#define EVENT_SRV_CANT_CREATE_PROCESS __MSABI_LONG(0xC00007D3)
#define EVENT_SRV_CANT_CREATE_THREAD __MSABI_LONG(0xC00007D4)
#define EVENT_SRV_CANT_GROW_TABLE __MSABI_LONG(0x800007D9)
#define EVENT_SRV_CANT_LOAD_DRIVER __MSABI_LONG(0x800009CC)
#define EVENT_SRV_CANT_MAP_ERROR __MSABI_LONG(0x800009CE)
#define EVENT_SRV_CANT_OPEN_NPFS __MSABI_LONG(0xC00007D7)
#define EVENT_SRV_CANT_RECREATE_SHARE __MSABI_LONG(0x800009CF)
#define EVENT_SRV_CANT_START_SCAVENGER __MSABI_LONG(0xC00007DA)
#define EVENT_SRV_CANT_UNLOAD_DRIVER __MSABI_LONG(0x800009CD)
#define EVENT_SRV_DISK_FULL __MSABI_LONG(0x800007DD)
#define EVENT_SRV_DOS_ATTACK_DETECTED __MSABI_LONG(0x800007E9)
#define EVENT_SRV_INVALID_REGISTRY_VALUE __MSABI_LONG(0x800009CA)
#define EVENT_SRV_INVALID_REQUEST __MSABI_LONG(0xC00007D6)
#define EVENT_SRV_INVALID_SD __MSABI_LONG(0x800009CB)
#define EVENT_SRV_IRP_STACK_SIZE __MSABI_LONG(0xC00007DB)
#define EVENT_SRV_KEY_NOT_CREATED __MSABI_LONG(0xC00009C6)
#define EVENT_SRV_KEY_NOT_FOUND __MSABI_LONG(0xC00009C5)
#define EVENT_SRV_NETWORK_ERROR __MSABI_LONG(0x800007DC)
#define EVENT_SRV_NONPAGED_POOL_LIMIT __MSABI_LONG(0xC00007E1)
#define EVENT_SRV_NO_BLOCKING_IO __MSABI_LONG(0x800007E8)
#define EVENT_SRV_NO_FREE_CONNECTIONS __MSABI_LONG(0x800007E6)
#define EVENT_SRV_NO_FREE_RAW_WORK_ITEM __MSABI_LONG(0x800007E7)
#define EVENT_SRV_NO_NONPAGED_POOL __MSABI_LONG(0xC00007E3)
#define EVENT_SRV_NO_PAGED_POOL __MSABI_LONG(0xC00007E4)
#define EVENT_SRV_NO_TRANSPORTS_BOUND __MSABI_LONG(0xC00009C7)
#define EVENT_SRV_NO_VIRTUAL_MEMORY __MSABI_LONG(0xC00007E0)
#define EVENT_SRV_NO_WORK_ITEM __MSABI_LONG(0x800007E5)
#define EVENT_SRV_OUT_OF_WORK_ITEM_DOS __MSABI_LONG(0x800007EB)
#define EVENT_SRV_PAGED_POOL_LIMIT __MSABI_LONG(0xC00007E2)
#define EVENT_SRV_RESOURCE_SHORTAGE __MSABI_LONG(0xC00007D1)
#define EVENT_SRV_SERVICE_FAILED __MSABI_LONG(0xC00007D0)
#define EVENT_SRV_TOO_MANY_DOS __MSABI_LONG(0x800007EA)
#define EVENT_SRV_TXF_INIT_FAILED __MSABI_LONG(0x800009D1)
#define EVENT_SRV_UNEXPECTED_DISC __MSABI_LONG(0xC00007D5)
#define EVENT_STREAMS_ALLOCB_FAILURE __MSABI_LONG(0x80000FA1)
#define EVENT_STREAMS_ALLOCB_FAILURE_CNT __MSABI_LONG(0x80000FA2)
#define EVENT_STREAMS_ESBALLOC_FAILURE __MSABI_LONG(0x80000FA3)
#define EVENT_STREAMS_ESBALLOC_FAILURE_CNT __MSABI_LONG(0x80000FA4)
#define EVENT_STREAMS_STRLOG __MSABI_LONG(0xC0000FA0)
#define EVENT_TAKE_OWNERSHIP __MSABI_LONG(0xC0001B74)
#define EVENT_TCPIP6_STARTED __MSABI_LONG(0x40000C1C)
#define EVENT_TCPIP_ADAPTER_REG_FAILURE __MSABI_LONG(0xC000105F)
#define EVENT_TCPIP_ADDRESS_CONFLICT1 __MSABI_LONG(0xC0001066)
#define EVENT_TCPIP_ADDRESS_CONFLICT2 __MSABI_LONG(0xC0001067)
#define EVENT_TCPIP_CREATE_DEVICE_FAILED __MSABI_LONG(0xC0001004)
#define EVENT_TCPIP_DHCP_INIT_FAILED __MSABI_LONG(0x8000105E)
#define EVENT_TCPIP_INVALID_ADDRESS __MSABI_LONG(0xC000105B)
#define EVENT_TCPIP_INVALID_DEFAULT_GATEWAY __MSABI_LONG(0x80001060)
#define EVENT_TCPIP_INVALID_MASK __MSABI_LONG(0xC000105C)
#define EVENT_TCPIP_IPV4_UNINSTALLED __MSABI_LONG(0x4000106B)
#define EVENT_TCPIP_IP_INIT_FAILED __MSABI_LONG(0xC0001064)
#define EVENT_TCPIP_MEDIA_CONNECT __MSABI_LONG(0x40001069)
#define EVENT_TCPIP_MEDIA_DISCONNECT __MSABI_LONG(0x4000106A)
#define EVENT_TCPIP_NO_ADAPTER_RESOURCES __MSABI_LONG(0xC000105D)
#define EVENT_TCPIP_NO_ADDRESS_LIST __MSABI_LONG(0xC0001061)
#define EVENT_TCPIP_NO_BINDINGS __MSABI_LONG(0xC0001063)
#define EVENT_TCPIP_NO_MASK __MSABI_LONG(0xC000105A)
#define EVENT_TCPIP_NO_MASK_LIST __MSABI_LONG(0xC0001062)
#define EVENT_TCPIP_NO_RESOURCES_FOR_INIT __MSABI_LONG(0xC0001005)
#define EVENT_TCPIP_NTE_CONTEXT_LIST_FAILURE __MSABI_LONG(0xC0001068)
#define EVENT_TCPIP_TCP_CONNECT_LIMIT_REACHED __MSABI_LONG(0x80001082)
#define EVENT_TCPIP_TCP_INIT_FAILED __MSABI_LONG(0xC0001081)
#define EVENT_TCPIP_TCP_MPP_ATTACKS_DETECTED __MSABI_LONG(0x80001085)
#define EVENT_TCPIP_TCP_TIME_WAIT_COLLISION __MSABI_LONG(0x80001083)
#define EVENT_TCPIP_TCP_WSD_WS_RESTRICTED __MSABI_LONG(0x80001084)
#define EVENT_TCPIP_TOO_MANY_GATEWAYS __MSABI_LONG(0x80001065)
#define EVENT_TCPIP_TOO_MANY_NETS __MSABI_LONG(0xC0001059)
#define EVENT_TCPIP_UDP_LIMIT_REACHED __MSABI_LONG(0x800010A9)
#define EVENT_TRANSACT_INVALID __MSABI_LONG(0xC0001B64)
#define EVENT_TRANSACT_TIMEOUT __MSABI_LONG(0xC0001B63)
#define EVENT_TRANSPORT_ADAPTER_NOT_FOUND __MSABI_LONG(0xC000232E)
#define EVENT_TRANSPORT_BAD_PROTOCOL __MSABI_LONG(0x40002333)
#define EVENT_TRANSPORT_BINDING_FAILED __MSABI_LONG(0xC000232D)
#define EVENT_TRANSPORT_QUERY_OID_FAILED __MSABI_LONG(0xC0002330)
#define EVENT_TRANSPORT_REGISTER_FAILED __MSABI_LONG(0xC000232C)
#define EVENT_TRANSPORT_RESOURCE_LIMIT __MSABI_LONG(0x8000232A)
#define EVENT_TRANSPORT_RESOURCE_POOL __MSABI_LONG(0x80002329)
#define EVENT_TRANSPORT_RESOURCE_SPECIFIC __MSABI_LONG(0x8000232B)
#define EVENT_TRANSPORT_SET_OID_FAILED __MSABI_LONG(0xC000232F)
#define EVENT_TRANSPORT_TOO_MANY_LINKS __MSABI_LONG(0x40002332)
#define EVENT_TRANSPORT_TRANSFER_DATA __MSABI_LONG(0x40002331)
#define EVENT_TRK_INTERNAL_ERROR __MSABI_LONG(0xC00030D4)
#define EVENT_TRK_SERVICE_CORRUPT_LOG __MSABI_LONG(0xC00030D7)
#define EVENT_TRK_SERVICE_DUPLICATE_VOLIDS __MSABI_LONG(0x400030DB)
#define EVENT_TRK_SERVICE_MOVE_QUOTA_EXCEEDED __MSABI_LONG(0x800030DC)
#define EVENT_TRK_SERVICE_START_FAILURE __MSABI_LONG(0xC00030D6)
#define EVENT_TRK_SERVICE_START_SUCCESS __MSABI_LONG(0x400030D5)
#define EVENT_TRK_SERVICE_VOLUME_CLAIM __MSABI_LONG(0x400030DA)
#define EVENT_TRK_SERVICE_VOLUME_CREATE __MSABI_LONG(0x400030D9)
#define EVENT_TRK_SERVICE_VOL_QUOTA_EXCEEDED __MSABI_LONG(0x800030D8)
#define EVENT_UP_DRIVER_ON_MP __MSABI_LONG(0xC00017D4)
#define EVENT_WEBCLIENT_CLOSE_DELETE_FAILED __MSABI_LONG(0x80003A36)
#define EVENT_WEBCLIENT_CLOSE_PROPPATCH_FAILED __MSABI_LONG(0x80003A37)
#define EVENT_WEBCLIENT_CLOSE_PUT_FAILED __MSABI_LONG(0x80003A35)
#define EVENT_WEBCLIENT_SETINFO_PROPPATCH_FAILED __MSABI_LONG(0x80003A38)
#define EVENT_WMI_CANT_GET_EVENT_DATA __MSABI_LONG(0x80002F49)
#define EVENT_WMI_CANT_OPEN_DEVICE __MSABI_LONG(0xC0002EE0)
#define EVENT_WMI_CANT_RESOLVE_INSTANCE __MSABI_LONG(0x80002F48)
#define EVENT_WMI_INVALID_MOF __MSABI_LONG(0x80002F44)
#define EVENT_WMI_INVALID_REGINFO __MSABI_LONG(0x80002F46)
#define EVENT_WMI_INVALID_REGPATH __MSABI_LONG(0x80002F47)
#define EVENT_WMI_MOF_LOAD_FAILURE __MSABI_LONG(0x80002F45)
#define EVENT_WSK_OWNINGTHREAD_PARAMETER_IGNORED __MSABI_LONG(0xC0003E80)
#define EXTRA_EXIT_POINT __MSABI_LONG(0xC00037DC)
#define EXTRA_EXIT_POINT_DELETED __MSABI_LONG(0xC00037E0)
#define EXTRA_EXIT_POINT_NOT_DELETED __MSABI_LONG(0xC00037E1)
#define EXTRA_VOLUME __MSABI_LONG(0xC00037DF)
#define EXTRA_VOLUME_DELETED __MSABI_LONG(0xC00037E6)
#define EXTRA_VOLUME_NOT_DELETED __MSABI_LONG(0xC00037E7)
#define KNOWLEDGE_INCONSISTENCY_DETECTED __MSABI_LONG(0xC00037E9)
#define LM_REDIR_FAILURE __MSABI_LONG(0x40003841)
#define MACHINE_UNJOINED __MSABI_LONG(0xC00037ED)
#define MISSING_EXIT_POINT __MSABI_LONG(0xC00037DD)
#define MISSING_EXIT_POINT_CREATED __MSABI_LONG(0xC00037E2)
#define MISSING_EXIT_POINT_NOT_CREATED __MSABI_LONG(0xC00037E3)
#define MISSING_VOLUME __MSABI_LONG(0xC00037DE)
#define MISSING_VOLUME_CREATED __MSABI_LONG(0xC00037E4)
#define MISSING_VOLUME_NOT_CREATED __MSABI_LONG(0xC00037E5)
#define NET_DFS_ENUM __MSABI_LONG(0x400038A4)
#define NET_DFS_ENUMEX __MSABI_LONG(0x400038A5)
#define NOT_A_DFS_PATH __MSABI_LONG(0x40003840)
#define NTFRSPRF_COLLECT_RPC_BINDING_ERROR_CONN __MSABI_LONG(0xC00034DC)
#define NTFRSPRF_COLLECT_RPC_BINDING_ERROR_SET __MSABI_LONG(0xC00034DB)
#define NTFRSPRF_COLLECT_RPC_CALL_ERROR_CONN __MSABI_LONG(0xC00034DE)
#define NTFRSPRF_COLLECT_RPC_CALL_ERROR_SET __MSABI_LONG(0xC00034DD)
#define NTFRSPRF_OPEN_RPC_BINDING_ERROR_CONN __MSABI_LONG(0xC00034D8)
#define NTFRSPRF_OPEN_RPC_BINDING_ERROR_SET __MSABI_LONG(0xC00034D7)
#define NTFRSPRF_OPEN_RPC_CALL_ERROR_CONN __MSABI_LONG(0xC00034DA)
#define NTFRSPRF_OPEN_RPC_CALL_ERROR_SET __MSABI_LONG(0xC00034D9)
#define NTFRSPRF_REGISTRY_ERROR_CONN __MSABI_LONG(0xC00034E2)
#define NTFRSPRF_REGISTRY_ERROR_SET __MSABI_LONG(0xC00034E1)
#define NTFRSPRF_VIRTUALALLOC_ERROR_CONN __MSABI_LONG(0xC00034E0)
#define NTFRSPRF_VIRTUALALLOC_ERROR_SET __MSABI_LONG(0xC00034DF)
#define NWSAP_EVENT_BADWANFILTER_VALUE __MSABI_LONG(0xC000214A)
#define NWSAP_EVENT_BIND_FAILED __MSABI_LONG(0xC0002138)
#define NWSAP_EVENT_CARDLISTEVENT_FAIL __MSABI_LONG(0xC000214B)
#define NWSAP_EVENT_CARDMALLOC_FAILED __MSABI_LONG(0xC000213C)
#define NWSAP_EVENT_CREATELPCEVENT_ERROR __MSABI_LONG(0xC0002147)
#define NWSAP_EVENT_CREATELPCPORT_ERROR __MSABI_LONG(0xC0002146)
#define NWSAP_EVENT_GETSOCKNAME_FAILED __MSABI_LONG(0xC0002139)
#define NWSAP_EVENT_HASHTABLE_MALLOC_FAILED __MSABI_LONG(0xC0002144)
#define NWSAP_EVENT_INVALID_FILTERNAME __MSABI_LONG(0x8000214D)
#define NWSAP_EVENT_KEY_NOT_FOUND __MSABI_LONG(0xC0002134)
#define NWSAP_EVENT_LPCHANDLEMEMORY_ERROR __MSABI_LONG(0xC0002149)
#define NWSAP_EVENT_LPCLISTENMEMORY_ERROR __MSABI_LONG(0xC0002148)
#define NWSAP_EVENT_NOCARDS __MSABI_LONG(0xC000213D)
#define NWSAP_EVENT_OPTBCASTINADDR_FAILED __MSABI_LONG(0xC000213B)
#define NWSAP_EVENT_OPTEXTENDEDADDR_FAILED __MSABI_LONG(0xC000213A)
#define NWSAP_EVENT_OPTMAXADAPTERNUM_ERROR __MSABI_LONG(0xC0002153)
#define NWSAP_EVENT_RECVSEM_FAIL __MSABI_LONG(0xC000213F)
#define NWSAP_EVENT_SDMDEVENT_FAIL __MSABI_LONG(0xC000214C)
#define NWSAP_EVENT_SENDEVENT_FAIL __MSABI_LONG(0xC0002140)
#define NWSAP_EVENT_SETOPTBCAST_FAILED __MSABI_LONG(0xC0002137)
#define NWSAP_EVENT_SOCKET_FAILED __MSABI_LONG(0xC0002136)
#define NWSAP_EVENT_STARTLPCWORKER_ERROR __MSABI_LONG(0xC0002145)
#define NWSAP_EVENT_STARTRECEIVE_ERROR __MSABI_LONG(0xC0002141)
#define NWSAP_EVENT_STARTWANCHECK_ERROR __MSABI_LONG(0xC0002152)
#define NWSAP_EVENT_STARTWANWORKER_ERROR __MSABI_LONG(0xC0002151)
#define NWSAP_EVENT_STARTWORKER_ERROR __MSABI_LONG(0xC0002142)
#define NWSAP_EVENT_TABLE_MALLOC_FAILED __MSABI_LONG(0xC0002143)
#define NWSAP_EVENT_THREADEVENT_FAIL __MSABI_LONG(0xC000213E)
#define NWSAP_EVENT_WANBIND_FAILED __MSABI_LONG(0xC0002150)
#define NWSAP_EVENT_WANEVENT_ERROR __MSABI_LONG(0xC0002155)
#define NWSAP_EVENT_WANHANDLEMEMORY_ERROR __MSABI_LONG(0xC0002154)
#define NWSAP_EVENT_WANSEM_FAIL __MSABI_LONG(0xC000214E)
#define NWSAP_EVENT_WANSOCKET_FAILED __MSABI_LONG(0xC000214F)
#define NWSAP_EVENT_WSASTARTUP_FAILED __MSABI_LONG(0xC0002135)
#define PREFIX_MISMATCH __MSABI_LONG(0xC00037EA)
#define PREFIX_MISMATCH_FIXED __MSABI_LONG(0xC00037EB)
#define PREFIX_MISMATCH_NOT_FIXED __MSABI_LONG(0xC00037EC)
#define STATUS_SEVERITY_ERROR 0x3
#define STATUS_SEVERITY_INFORMATIONAL 0x1
#define STATUS_SEVERITY_SUCCESS 0x0
#define STATUS_SEVERITY_WARNING 0x2
#define TITLE_SC_MESSAGE_BOX __MSABI_LONG(0xC0001B75)
#ifdef __cplusplus
}
#endif
#endif /* __NETEVENT_H */
| 34,717 |
540 | /* ----------------------------------------------------------------------------
** Copyright (c) 2016 <NAME>, All Rights Reserved.
**
** Object.h
** --------------------------------------------------------------------------*/
#pragma once
#include "JsonConfig.h"
// Constructs a variant that wraps an object
#define ObjectVariant(object) ursine::meta::Variant { object, ursine::meta::variant_policy::WrapObject( ) }
namespace ursine
{
namespace meta
{
class Type;
class Object
{
public:
virtual ~Object(void) { }
virtual Type GetType(void) const = 0;
virtual Object *Clone(void) const = 0;
virtual void OnSerialize(Json::object &output) const { }
virtual void OnDeserialize(const Json &input) { }
};
}
} | 293 |
7,471 | <gh_stars>1000+
#include "mvContext.h"
#include "dearpygui.h"
#include "mvViewport.h"
#include "mvCallbackRegistry.h"
#include <thread>
#include <future>
#include <chrono>
#include "mvProfiler.h"
#include <implot.h>
#include "mvFontManager.h"
#include "mvCallbackRegistry.h"
#include "mvPythonTranslator.h"
#include "mvPythonExceptions.h"
#include "mvGlobalIntepreterLock.h"
#include <frameobject.h>
#include "mvLog.h"
#include "mvToolManager.h"
#include <imnodes.h>
#include <thread>
#include <stb_image.h>
#include "mvBuffer.h"
#include "mvAppItemCommons.h"
#include "mvItemRegistry.h"
namespace Marvel {
extern mvContext* GContext = nullptr;
mv_internal void
UpdateInputs(mvInput& input)
{
MV_PROFILE_SCOPE("Input Routing")
// update mouse
// mouse move event
ImVec2 mousepos = ImGui::GetMousePos();
if (ImGui::IsMousePosValid(&mousepos))
{
if (input.mouseGlobalPos.x != mousepos.x || input.mouseGlobalPos.y != mousepos.y)
{
input.mouseGlobalPos.x = (i32)mousepos.x;
input.mouseGlobalPos.y = (i32)mousepos.y;
}
}
// route key events
for (i32 i = 0; i < IM_ARRAYSIZE(ImGui::GetIO().KeysDown); i++)
{
input.keysdown[i] = ImGui::GetIO().KeysDown[i];
input.keyspressed[i] = ImGui::GetIO().KeysDownDuration[i] == 0.0f;
input.keysreleased[i] = ImGui::GetIO().KeysDownDurationPrev[i] >= 0.0f && !ImGui::GetIO().KeysDown[i];
// route key down event
if (ImGui::GetIO().KeysDownDuration[i] >= 0.0f)
input.keysdownduration[i] = (i32)(ImGui::GetIO().KeysDownDuration[i] * 100.0);
}
// route mouse wheel event
if (ImGui::GetIO().MouseWheel != 0.0f)
input.mousewheel = (i32)ImGui::GetIO().MouseWheel;
// route mouse dragging event
for (i32 i = 0; i < 3; i++)
{
input.mouseDragging[i] = ImGui::IsMouseDragging(i, (f32)input.mouseDragThreshold);
if (ImGui::IsMouseDragging(i, (f32)input.mouseDragThreshold))
{
input.mouseDragDelta.x = (i32)ImGui::GetMouseDragDelta().x;
input.mouseDragDelta.y = (i32)ImGui::GetMouseDragDelta().y;
break;
}
}
// route other mouse events (note mouse move callbacks are handled in mvWindowAppItem)
for (i32 i = 0; i < IM_ARRAYSIZE(ImGui::GetIO().MouseDown); i++)
{
input.mousedown[i] = ImGui::GetIO().MouseDown[i];
// route mouse down event
if (ImGui::GetIO().MouseDownDuration[i] >= 0.0f)
input.mousedownduration[i] = (i32)(ImGui::GetIO().MouseDownDuration[i] * 100.0);
else
input.mousedownduration[i] = 0;
}
}
mvUUID
GenerateUUID()
{
return ++GContext->id;
}
void
SetDefaultTheme()
{
ImGuiStyle* style = &ImGui::GetStyle();
ImVec4* colors = style->Colors;
colors[ImGuiCol_Text] = MV_BASE_COL_textColor;
colors[ImGuiCol_TextDisabled] = MV_BASE_COL_textDisabledColor;
colors[ImGuiCol_WindowBg] = mvImGuiCol_WindowBg;
colors[ImGuiCol_ChildBg] = mvImGuiCol_ChildBg;
colors[ImGuiCol_PopupBg] = mvImGuiCol_PopupBg;
colors[ImGuiCol_Border] = mvImGuiCol_Border;
colors[ImGuiCol_BorderShadow] = mvImGuiCol_BorderShadow;
colors[ImGuiCol_FrameBg] = mvImGuiCol_FrameBg;
colors[ImGuiCol_FrameBgHovered] = mvImGuiCol_FrameBgHovered;
colors[ImGuiCol_FrameBgActive] = mvImGuiCol_FrameBgActive;
colors[ImGuiCol_TitleBg] = mvImGuiCol_TitleBg;
colors[ImGuiCol_TitleBgActive] = mvImGuiCol_TitleBgActive;
colors[ImGuiCol_TitleBgCollapsed] = mvImGuiCol_TitleBgCollapsed;
colors[ImGuiCol_MenuBarBg] = mvImGuiCol_MenuBarBg;
colors[ImGuiCol_ScrollbarBg] = mvImGuiCol_ScrollbarBg;
colors[ImGuiCol_ScrollbarGrab] = mvImGuiCol_ScrollbarGrab;
colors[ImGuiCol_ScrollbarGrabHovered] = mvImGuiCol_ScrollbarGrabHovered;
colors[ImGuiCol_ScrollbarGrabActive] = mvImGuiCol_ScrollbarGrabActive;
colors[ImGuiCol_CheckMark] = mvImGuiCol_CheckMark;
colors[ImGuiCol_SliderGrab] = mvImGuiCol_SliderGrab;
colors[ImGuiCol_SliderGrabActive] = mvImGuiCol_SliderGrabActive;
colors[ImGuiCol_Button] = mvImGuiCol_Button;
colors[ImGuiCol_ButtonHovered] = mvImGuiCol_ButtonHovered;
colors[ImGuiCol_ButtonActive] = mvImGuiCol_ButtonActive;
colors[ImGuiCol_Header] = mvImGuiCol_Header;
colors[ImGuiCol_HeaderHovered] = mvImGuiCol_HeaderHovered;
colors[ImGuiCol_HeaderActive] = mvImGuiCol_HeaderActive;
colors[ImGuiCol_Separator] = mvImGuiCol_Separator;
colors[ImGuiCol_SeparatorHovered] = mvImGuiCol_SeparatorHovered;
colors[ImGuiCol_SeparatorActive] = mvImGuiCol_SeparatorActive;
colors[ImGuiCol_ResizeGrip] = mvImGuiCol_ResizeGrip;
colors[ImGuiCol_ResizeGripHovered] = mvImGuiCol_ResizeGripHovered;
colors[ImGuiCol_ResizeGripActive] = mvImGuiCol_ResizeGripHovered;
colors[ImGuiCol_Tab] = mvImGuiCol_Tab;
colors[ImGuiCol_TabHovered] = mvImGuiCol_TabHovered;
colors[ImGuiCol_TabActive] = mvImGuiCol_TabActive;
colors[ImGuiCol_TabUnfocused] = mvImGuiCol_TabUnfocused;
colors[ImGuiCol_TabUnfocusedActive] = mvImGuiCol_TabUnfocusedActive;
colors[ImGuiCol_DockingPreview] = mvImGuiCol_DockingPreview;
colors[ImGuiCol_DockingEmptyBg] = mvImGuiCol_DockingEmptyBg;
colors[ImGuiCol_PlotLines] = mvImGuiCol_PlotLines;
colors[ImGuiCol_PlotLinesHovered] = mvImGuiCol_PlotLinesHovered;
colors[ImGuiCol_PlotHistogram] = mvImGuiCol_PlotHistogram;
colors[ImGuiCol_PlotHistogramHovered] = mvImGuiCol_PlotHistogramHovered;
colors[ImGuiCol_TableHeaderBg] = mvImGuiCol_TableHeaderBg;
colors[ImGuiCol_TableBorderStrong] = mvImGuiCol_TableBorderStrong; // Prefer using Alpha=1.0 here
colors[ImGuiCol_TableBorderLight] = mvImGuiCol_TableBorderLight; // Prefer using Alpha=1.0 here
colors[ImGuiCol_TableRowBg] = mvImGuiCol_TableRowBg;
colors[ImGuiCol_TableRowBgAlt] = mvImGuiCol_TableRowBgAlt;
colors[ImGuiCol_TextSelectedBg] = mvImGuiCol_TextSelectedBg;
colors[ImGuiCol_DragDropTarget] = mvImGuiCol_DragDropTarget;
colors[ImGuiCol_NavHighlight] = mvImGuiCol_NavHighlight;
colors[ImGuiCol_NavWindowingHighlight] = mvImGuiCol_NavWindowingHighlight;
colors[ImGuiCol_NavWindowingDimBg] = mvImGuiCol_NavWindowingDimBg;
colors[ImGuiCol_ModalWindowDimBg] = mvImGuiCol_ModalWindowDimBg;
imnodes::GetStyle().colors[imnodes::ColorStyle_NodeBackground] = mvColor::ConvertToUnsignedInt(mvColor(62, 62, 62, 255));
imnodes::GetStyle().colors[imnodes::ColorStyle_NodeBackgroundHovered] = mvColor::ConvertToUnsignedInt(mvColor(75, 75, 75, 255));
imnodes::GetStyle().colors[imnodes::ColorStyle_NodeBackgroundSelected] = mvColor::ConvertToUnsignedInt(mvColor(75, 75, 75, 255));
imnodes::GetStyle().colors[imnodes::ColorStyle_NodeOutline] = mvColor::ConvertToUnsignedInt(mvColor(100, 100, 100, 255));
imnodes::GetStyle().colors[imnodes::ColorStyle_TitleBar] = mvColor::ConvertToUnsignedInt(mvImGuiCol_TitleBg);
imnodes::GetStyle().colors[imnodes::ColorStyle_TitleBarHovered] = mvColor::ConvertToUnsignedInt(mvImGuiCol_TitleBgActive);
imnodes::GetStyle().colors[imnodes::ColorStyle_TitleBarSelected] = mvColor::ConvertToUnsignedInt(mvImGuiCol_FrameBgActive);
imnodes::GetStyle().colors[imnodes::ColorStyle_Link] = mvColor::ConvertToUnsignedInt(mvColor(255, 255, 255, 200));
imnodes::GetStyle().colors[imnodes::ColorStyle_LinkHovered] = mvColor::ConvertToUnsignedInt(mvColor(66, 150, 250, 255));
imnodes::GetStyle().colors[imnodes::ColorStyle_LinkSelected] = mvColor::ConvertToUnsignedInt(mvColor(66, 150, 250, 255));
imnodes::GetStyle().colors[imnodes::ColorStyle_Pin] = mvColor::ConvertToUnsignedInt(mvColor(199, 199, 41, 255));
imnodes::GetStyle().colors[imnodes::ColorStyle_PinHovered] = mvColor::ConvertToUnsignedInt(mvColor(255, 255, 50, 255));
imnodes::GetStyle().colors[imnodes::ColorStyle_BoxSelector] = mvColor::ConvertToUnsignedInt(mvColor(61, 133, 224, 30));
imnodes::GetStyle().colors[imnodes::ColorStyle_BoxSelectorOutline] = mvColor::ConvertToUnsignedInt(mvColor(61, 133, 224, 150));
imnodes::GetStyle().colors[imnodes::ColorStyle_GridBackground] = mvColor::ConvertToUnsignedInt(mvColor(35, 35, 35, 255));
imnodes::GetStyle().colors[imnodes::ColorStyle_GridLine] = mvColor::ConvertToUnsignedInt(mvColor(0, 0, 0, 255));
}
void
Render()
{
// update timing
GContext->deltaTime = ImGui::GetIO().DeltaTime;
GContext->time = ImGui::GetTime();
GContext->frame = ImGui::GetFrameCount();
GContext->framerate = (i32)ImGui::GetIO().Framerate;
ImGui::GetIO().FontGlobalScale = mvToolManager::GetFontManager().getGlobalFontScale();
if (GContext->IO.dockingViewport)
ImGui::DockSpaceOverViewport();
mvFrameCallback(ImGui::GetFrameCount());
// route input callbacks
UpdateInputs(GContext->input);
mvToolManager::Draw();
{
std::lock_guard<std::mutex> lk(GContext->mutex);
if (GContext->resetTheme)
{
SetDefaultTheme();
GContext->resetTheme = false;
}
mvRunTasks();
RenderItemRegistry(*GContext->itemRegistry);
mvRunTasks();
}
if (GContext->waitOneFrame == true)
GContext->waitOneFrame = false;
}
std::map<std::string, mvPythonParser>&
GetParsers()
{
return const_cast<std::map<std::string, mvPythonParser>&>(GetModuleParsers());
}
void
InsertConstants_mvContext(std::vector<std::pair<std::string, long>>& constants)
{
//-----------------------------------------------------------------------------
// Mouse Codes
//-----------------------------------------------------------------------------
constants.emplace_back("mvMouseButton_Left", 0);
constants.emplace_back("mvMouseButton_Right", 1);
constants.emplace_back("mvMouseButton_Middle", 2);
constants.emplace_back("mvMouseButton_X1", 3);
constants.emplace_back("mvMouseButton_X2", 4);
//-----------------------------------------------------------------------------
// Key Codes
//-----------------------------------------------------------------------------
constants.emplace_back("mvKey_0", 0x30);
constants.emplace_back("mvKey_1", 0x31);
constants.emplace_back("mvKey_2", 0x32);
constants.emplace_back("mvKey_3", 0x33);
constants.emplace_back("mvKey_4", 0x34);
constants.emplace_back("mvKey_5", 0x35);
constants.emplace_back("mvKey_6", 0x36);
constants.emplace_back("mvKey_7", 0x37);
constants.emplace_back("mvKey_8", 0x38);
constants.emplace_back("mvKey_9", 0x39);
constants.emplace_back("mvKey_A", 0x41);
constants.emplace_back("mvKey_B", 0x42);
constants.emplace_back("mvKey_C", 0x43);
constants.emplace_back("mvKey_D", 0x44);
constants.emplace_back("mvKey_E", 0x45);
constants.emplace_back("mvKey_F", 0x46);
constants.emplace_back("mvKey_G", 0x47);
constants.emplace_back("mvKey_H", 0x48);
constants.emplace_back("mvKey_I", 0x49);
constants.emplace_back("mvKey_J", 0x4A);
constants.emplace_back("mvKey_K", 0x4B);
constants.emplace_back("mvKey_L", 0x4C);
constants.emplace_back("mvKey_M", 0x4D);
constants.emplace_back("mvKey_N", 0x4E);
constants.emplace_back("mvKey_O", 0x4F);
constants.emplace_back("mvKey_P", 0x50);
constants.emplace_back("mvKey_Q", 0x51);
constants.emplace_back("mvKey_R", 0x52);
constants.emplace_back("mvKey_S", 0x53);
constants.emplace_back("mvKey_T", 0x54);
constants.emplace_back("mvKey_U", 0x55);
constants.emplace_back("mvKey_V", 0x56);
constants.emplace_back("mvKey_W", 0x57);
constants.emplace_back("mvKey_X", 0x58);
constants.emplace_back("mvKey_Y", 0x59);
constants.emplace_back("mvKey_Z", 0x5A);
#if defined (_WIN32)
constants.emplace_back("mvKey_Back", 0x08);
constants.emplace_back("mvKey_Tab", 0x09);
constants.emplace_back("mvKey_Clear", 0x0C);
constants.emplace_back("mvKey_Return", 0x0D);
constants.emplace_back("mvKey_Shift", 0x10);
constants.emplace_back("mvKey_Control", 0x11);
constants.emplace_back("mvKey_Alt", 0x12);
constants.emplace_back("mvKey_Pause", 0x13);
constants.emplace_back("mvKey_Capital", 0x14);
constants.emplace_back("mvKey_Escape", 0x1B);
constants.emplace_back("mvKey_Spacebar", 0x20);
constants.emplace_back("mvKey_Prior", 0x21);
constants.emplace_back("mvKey_Next", 0x22);
constants.emplace_back("mvKey_End", 0x23);
constants.emplace_back("mvKey_Home", 0x24);
constants.emplace_back("mvKey_Left", 0x25);
constants.emplace_back("mvKey_Up", 0x26);
constants.emplace_back("mvKey_Right", 0x27);
constants.emplace_back("mvKey_Down", 0x28);
constants.emplace_back("mvKey_Select", 0x29);
constants.emplace_back("mvKey_Print", 0x2A);
constants.emplace_back("mvKey_Execute", 0x2B);
constants.emplace_back("mvKey_PrintScreen", 0x2C);
constants.emplace_back("mvKey_Insert", 0x2D);
constants.emplace_back("mvKey_Delete", 0x2E);
constants.emplace_back("mvKey_Help", 0x2F);
constants.emplace_back("mvKey_LWin", 0x5B);
constants.emplace_back("mvKey_RWin", 0x5C);
constants.emplace_back("mvKey_Apps", 0x5D);
constants.emplace_back("mvKey_Sleep", 0x5F);
constants.emplace_back("mvKey_NumPad0", 0x60);
constants.emplace_back("mvKey_NumPad1", 0x61);
constants.emplace_back("mvKey_NumPad2", 0x62);
constants.emplace_back("mvKey_NumPad3", 0x63);
constants.emplace_back("mvKey_NumPad4", 0x64);
constants.emplace_back("mvKey_NumPad5", 0x65);
constants.emplace_back("mvKey_NumPad6", 0x66);
constants.emplace_back("mvKey_NumPad7", 0x67);
constants.emplace_back("mvKey_NumPad8", 0x68);
constants.emplace_back("mvKey_NumPad9", 0x69);
constants.emplace_back("mvKey_Multiply", 0x6A);
constants.emplace_back("mvKey_Add", 0x6B);
constants.emplace_back("mvKey_Separator", 0x6C);
constants.emplace_back("mvKey_Subtract", 0x6D);
constants.emplace_back("mvKey_Decimal", 0x6E);
constants.emplace_back("mvKey_Divide", 0x6F);
constants.emplace_back("mvKey_F1", 0x70);
constants.emplace_back("mvKey_F2", 0x71);
constants.emplace_back("mvKey_F3", 0x72);
constants.emplace_back("mvKey_F4", 0x73);
constants.emplace_back("mvKey_F5", 0x74);
constants.emplace_back("mvKey_F6", 0x75);
constants.emplace_back("mvKey_F7", 0x76);
constants.emplace_back("mvKey_F8", 0x77);
constants.emplace_back("mvKey_F9", 0x78);
constants.emplace_back("mvKey_F10", 0x79);
constants.emplace_back("mvKey_F11", 0x7A);
constants.emplace_back("mvKey_F12", 0x7B);
constants.emplace_back("mvKey_F13", 0x7C);
constants.emplace_back("mvKey_F14", 0x7D);
constants.emplace_back("mvKey_F15", 0x7E);
constants.emplace_back("mvKey_F16", 0x7F);
constants.emplace_back("mvKey_F17", 0x80);
constants.emplace_back("mvKey_F18", 0x81);
constants.emplace_back("mvKey_F19", 0x82);
constants.emplace_back("mvKey_F20", 0x83);
constants.emplace_back("mvKey_F21", 0x84);
constants.emplace_back("mvKey_F22", 0x85);
constants.emplace_back("mvKey_F23", 0x86);
constants.emplace_back("mvKey_F24", 0x87);
constants.emplace_back("mvKey_NumLock", 0x90);
constants.emplace_back("mvKey_ScrollLock", 0x91);
constants.emplace_back("mvKey_LShift", 0xA0);
constants.emplace_back("mvKey_RShift", 0xA1);
constants.emplace_back("mvKey_LControl", 0xA2);
constants.emplace_back("mvKey_RControl", 0xA3);
constants.emplace_back("mvKey_LMenu", 0xA4);
constants.emplace_back("mvKey_RMenu", 0xA5);
constants.emplace_back("mvKey_Browser_Back", 0xA6);
constants.emplace_back("mvKey_Browser_Forward", 0xA7);
constants.emplace_back("mvKey_Browser_Refresh", 0xA8);
constants.emplace_back("mvKey_Browser_Stop", 0xA9);
constants.emplace_back("mvKey_Browser_Search", 0xAA);
constants.emplace_back("mvKey_Browser_Favorites", 0xAB);
constants.emplace_back("mvKey_Browser_Home", 0xAC);
constants.emplace_back("mvKey_Volume_Mute", 0xAD);
constants.emplace_back("mvKey_Volume_Down", 0xAE);
constants.emplace_back("mvKey_Volume_Up", 0xAF);
constants.emplace_back("mvKey_Media_Next_Track", 0xB0);
constants.emplace_back("mvKey_Media_Prev_Track", 0xB1);
constants.emplace_back("mvKey_Media_Stop", 0xB2);
constants.emplace_back("mvKey_Media_Play_Pause", 0xB3);
constants.emplace_back("mvKey_Launch_Mail", 0xB4);
constants.emplace_back("mvKey_Launch_Media_Select", 0xB5);
constants.emplace_back("mvKey_Launch_App1", 0xB6);
constants.emplace_back("mvKey_Launch_App2", 0xB7);
constants.emplace_back("mvKey_Colon", 0xBA);
constants.emplace_back("mvKey_Plus", 0xBB);
constants.emplace_back("mvKey_Comma", 0xBC);
constants.emplace_back("mvKey_Minus", 0xBD);
constants.emplace_back("mvKey_Period", 0xBE);
constants.emplace_back("mvKey_Slash", 0xBF);
constants.emplace_back("mvKey_Tilde", 0xC0);
constants.emplace_back("mvKey_Open_Brace", 0xDB);
constants.emplace_back("mvKey_Backslash", 0xDC);
constants.emplace_back("mvKey_Close_Brace", 0xDD);
constants.emplace_back("mvKey_Quote", 0xDE);
#else
constants.emplace_back("mvKey_Back", 259);
constants.emplace_back("mvKey_Tab", 258);
constants.emplace_back("mvKey_Clear", 259);
constants.emplace_back("mvKey_Return", 257);
constants.emplace_back("mvKey_Shift", 340);
constants.emplace_back("mvKey_Control", 241);
constants.emplace_back("mvKey_Alt", 342);
constants.emplace_back("mvKey_Pause", 284);
constants.emplace_back("mvKey_Capital", 280);
constants.emplace_back("mvKey_Escape", 256);
constants.emplace_back("mvKey_Spacebar", 32);
constants.emplace_back("mvKey_Prior", 266);
constants.emplace_back("mvKey_Next", 267);
constants.emplace_back("mvKey_End", 269);
constants.emplace_back("mvKey_Home", 268);
constants.emplace_back("mvKey_Left", 263);
constants.emplace_back("mvKey_Up", 265);
constants.emplace_back("mvKey_Right", 262);
constants.emplace_back("mvKey_Down", 264);
constants.emplace_back("mvKey_Select", -1);
constants.emplace_back("mvKey_Print", -1);
constants.emplace_back("mvKey_Execute", -1);
constants.emplace_back("mvKey_PrintScreen", 286);
constants.emplace_back("mvKey_Insert", 260);
constants.emplace_back("mvKey_Delete", 261);
constants.emplace_back("mvKey_Help", -1);
constants.emplace_back("mvKey_LWin", 343);
constants.emplace_back("mvKey_RWin", 347);
constants.emplace_back("mvKey_Apps", -1);
constants.emplace_back("mvKey_Sleep", -1);
constants.emplace_back("mvKey_NumPad0", 320);
constants.emplace_back("mvKey_NumPad1", 321);
constants.emplace_back("mvKey_NumPad2", 322);
constants.emplace_back("mvKey_NumPad3", 323);
constants.emplace_back("mvKey_NumPad4", 324);
constants.emplace_back("mvKey_NumPad5", 325);
constants.emplace_back("mvKey_NumPad6", 326);
constants.emplace_back("mvKey_NumPad7", 327);
constants.emplace_back("mvKey_NumPad8", 328);
constants.emplace_back("mvKey_NumPad9", 329);
constants.emplace_back("mvKey_Multiply", 332);
constants.emplace_back("mvKey_Add", 334);
constants.emplace_back("mvKey_Separator", -1);
constants.emplace_back("mvKey_Subtract", 333);
constants.emplace_back("mvKey_Decimal", 330);
constants.emplace_back("mvKey_Divide", 331);
constants.emplace_back("mvKey_F1", 290);
constants.emplace_back("mvKey_F2", 291);
constants.emplace_back("mvKey_F3", 292);
constants.emplace_back("mvKey_F4", 293);
constants.emplace_back("mvKey_F5", 294);
constants.emplace_back("mvKey_F6", 295);
constants.emplace_back("mvKey_F7", 296);
constants.emplace_back("mvKey_F8", 297);
constants.emplace_back("mvKey_F9", 298);
constants.emplace_back("mvKey_F10", 299);
constants.emplace_back("mvKey_F11", 300);
constants.emplace_back("mvKey_F12", 301);
constants.emplace_back("mvKey_F13", 302);
constants.emplace_back("mvKey_F14", 303);
constants.emplace_back("mvKey_F15", 304);
constants.emplace_back("mvKey_F16", 305);
constants.emplace_back("mvKey_F17", 306);
constants.emplace_back("mvKey_F18", 307);
constants.emplace_back("mvKey_F19", 308);
constants.emplace_back("mvKey_F20", 309);
constants.emplace_back("mvKey_F21", 310);
constants.emplace_back("mvKey_F22", 311);
constants.emplace_back("mvKey_F23", 312);
constants.emplace_back("mvKey_F24", 313);
constants.emplace_back("mvKey_F24", 314);
constants.emplace_back("mvKey_NumLock", 282);
constants.emplace_back("mvKey_ScrollLock", 281);
constants.emplace_back("mvKey_LShift", 340);
constants.emplace_back("mvKey_RShift", 344);
constants.emplace_back("mvKey_LControl", 341);
constants.emplace_back("mvKey_RControl", 345);
constants.emplace_back("mvKey_LMenu", -1);
constants.emplace_back("mvKey_RMenu", -1);
constants.emplace_back("mvKey_Browser_Back", -1);
constants.emplace_back("mvKey_Browser_Forward", -1);
constants.emplace_back("mvKey_Browser_Refresh", -1);
constants.emplace_back("mvKey_Browser_Stop", -1);
constants.emplace_back("mvKey_Browser_Search", -1);
constants.emplace_back("mvKey_Browser_Favorites", -1);
constants.emplace_back("mvKey_Browser_Home", -1);
constants.emplace_back("mvKey_Volume_Mute", -1);
constants.emplace_back("mvKey_Volume_Down", -1);
constants.emplace_back("mvKey_Volume_Up", -1);
constants.emplace_back("mvKey_Media_Next_Track", -1);
constants.emplace_back("mvKey_Media_Prev_Track", -1);
constants.emplace_back("mvKey_Media_Stop", -1);
constants.emplace_back("mvKey_Media_Play_Pause", -1);
constants.emplace_back("mvKey_Launch_Mail", -1);
constants.emplace_back("mvKey_Launch_Media_Select", -1);
constants.emplace_back("mvKey_Launch_App1", -1);
constants.emplace_back("mvKey_Launch_App2", -1);
constants.emplace_back("mvKey_Colon", 59);
constants.emplace_back("mvKey_Plus", 61);
constants.emplace_back("mvKey_Comma", 44);
constants.emplace_back("mvKey_Minus", 45);
constants.emplace_back("mvKey_Period", 46);
constants.emplace_back("mvKey_Slash", 47);
constants.emplace_back("mvKey_Tilde", 96);
constants.emplace_back("mvKey_Open_Brace", 91);
constants.emplace_back("mvKey_Backslash", 92);
constants.emplace_back("mvKey_Close_Brace", 93);
constants.emplace_back("mvKey_Quote", 39);
#endif
}
}
| 11,385 |
563 | <gh_stars>100-1000
package com.gentics.mesh.core.field.binary;
import static com.gentics.mesh.core.field.binary.BinaryFieldTestHelper.CREATE_EMPTY;
import static com.gentics.mesh.core.field.binary.BinaryFieldTestHelper.FETCH;
import static com.gentics.mesh.core.field.binary.BinaryFieldTestHelper.FILL_BASIC;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.core.data.NodeGraphFieldContainer;
import com.gentics.mesh.core.data.binary.HibBinary;
import com.gentics.mesh.core.data.container.impl.NodeGraphFieldContainerImpl;
import com.gentics.mesh.core.data.dao.ContentDaoWrapper;
import com.gentics.mesh.core.data.node.HibNode;
import com.gentics.mesh.core.data.node.field.BinaryGraphField;
import com.gentics.mesh.core.data.node.field.GraphField;
import com.gentics.mesh.core.db.Tx;
import com.gentics.mesh.core.endpoint.node.TransformationResult;
import com.gentics.mesh.core.field.AbstractFieldTest;
import com.gentics.mesh.core.image.ImageInfo;
import com.gentics.mesh.core.rest.node.NodeResponse;
import com.gentics.mesh.core.rest.node.field.BinaryField;
import com.gentics.mesh.core.rest.node.field.Field;
import com.gentics.mesh.core.rest.node.field.impl.BinaryFieldImpl;
import com.gentics.mesh.core.rest.node.field.impl.StringFieldImpl;
import com.gentics.mesh.core.rest.schema.BinaryFieldSchema;
import com.gentics.mesh.core.rest.schema.SchemaVersionModel;
import com.gentics.mesh.core.rest.schema.impl.BinaryFieldSchemaImpl;
import com.gentics.mesh.json.JsonUtil;
import com.gentics.mesh.test.TestSize;
import com.gentics.mesh.test.context.MeshTestSetting;
import com.gentics.mesh.util.FileUtils;
import com.gentics.mesh.util.UUIDUtil;
import io.reactivex.Flowable;
import io.reactivex.Single;
import io.vertx.core.buffer.Buffer;
@MeshTestSetting(testSize = TestSize.PROJECT_AND_NODE, startServer = false)
public class BinaryFieldTest extends AbstractFieldTest<BinaryFieldSchema> {
private static final String BINARY_FIELD = "binaryField";
private static final Base64.Decoder BASE64 = Base64.getDecoder();
@Override
protected BinaryFieldSchema createFieldSchema(boolean isRequired) {
BinaryFieldSchema binaryFieldSchema = new BinaryFieldSchemaImpl();
binaryFieldSchema.setName(BINARY_FIELD);
binaryFieldSchema.setAllowedMimeTypes("image/jpg", "text/plain");
binaryFieldSchema.setRequired(isRequired);
return binaryFieldSchema;
}
@Test
public void testBinaryFieldBase64() {
try (Tx tx = tx()) {
String input = "";
while (input.length() < 32 * 1024) {
input = input.concat("Hallo");
}
HibBinary binary = tx.binaries().create("hashsum", 1L).runInExistingTx(tx);
mesh().binaryStorage().store(Flowable.just(Buffer.buffer(input)), binary.getUuid()).blockingAwait();
String base64 = tx.binaryDao().getBase64ContentSync(binary);
assertEquals(input.toString(), new String(BASE64.decode(base64)));
}
}
@Test
public void testBinaryFieldBase641Char() {
try (Tx tx = tx()) {
String input = " ";
HibBinary binary = tx.binaries().create("hashsum", 1L).runInExistingTx(tx);
mesh().binaryStorage().store(Flowable.just(Buffer.buffer(input)), binary.getUuid()).blockingAwait();
String base64 = tx.binaryDao().getBase64ContentSync(binary);
assertEquals(input.toString(), new String(BASE64.decode(base64)));
}
}
@Test
@Override
public void testFieldTransformation() throws Exception {
String hash = "6a793cf1c7f6ef022ba9fff65ed43ddac9fb9c2131ffc4eaa3f49212244c0d4191ae5877b03bd50fd137bd9e5a16799da4a1f2846f0b26e3d956c4d8423004cc";
HibNode node = folder("2015");
try (Tx tx = tx()) {
ContentDaoWrapper contentDao = tx.contentDao();
// Update the schema and add a binary field
SchemaVersionModel schema = node.getSchemaContainer().getLatestVersion().getSchema();
schema.addField(createFieldSchema(true));
node.getSchemaContainer().getLatestVersion().setSchema(schema);
NodeGraphFieldContainer container = contentDao.getLatestDraftFieldContainer(node, english());
HibBinary binary = tx.binaries().create(hash, 10L).runInExistingTx(tx);
BinaryGraphField field = container.createBinary(BINARY_FIELD, binary);
field.setMimeType("image/jpg");
binary.setImageHeight(200);
binary.setImageWidth(300);
tx.success();
}
try (Tx tx = tx()) {
String json = getJson(node);
assertNotNull(json);
NodeResponse response = JsonUtil.readValue(json, NodeResponse.class);
assertNotNull(response);
BinaryField deserializedNodeField = response.getFields().getBinaryField(BINARY_FIELD);
assertNotNull(deserializedNodeField);
assertEquals(hash, deserializedNodeField.getSha512sum());
assertEquals(200, deserializedNodeField.getHeight().intValue());
assertEquals(300, deserializedNodeField.getWidth().intValue());
}
}
@Test
@Override
public void testFieldUpdate() {
try (Tx tx = tx()) {
NodeGraphFieldContainerImpl container = tx.getGraph().addFramedVertex(NodeGraphFieldContainerImpl.class);
HibBinary binary = tx.binaries().create(
"6a793cf1c7f6ef022ba9fff65ed43ddac9fb9c2131ffc4eaa3f49212244c0d4191ae5877b03bd50fd137bd9e5a16799da4a1f2846f0b26e3d956c4d8423004cc",
0L).runInExistingTx(tx);
BinaryGraphField field = container.createBinary(BINARY_FIELD, binary);
field.getBinary().setSize(220);
assertNotNull(field);
assertEquals(BINARY_FIELD, field.getFieldKey());
field.setFileName("blume.jpg");
field.setMimeType("image/jpg");
field.setImageDominantColor("#22A7F0");
field.getBinary().setImageHeight(133);
field.getBinary().setImageWidth(7);
BinaryGraphField loadedField = container.getBinary(BINARY_FIELD);
HibBinary loadedBinary = loadedField.getBinary();
assertNotNull("The previously created field could not be found.", loadedField);
assertEquals(220, loadedBinary.getSize());
assertEquals("blume.jpg", loadedField.getFileName());
assertEquals("image/jpg", loadedField.getMimeType());
assertEquals("#22A7F0", loadedField.getImageDominantColor());
assertEquals(133, loadedField.getBinary().getImageHeight().intValue());
assertEquals(7, loadedField.getBinary().getImageWidth().intValue());
assertEquals(
"6a793cf1c7f6ef022ba9fff65ed43ddac9fb9c2131ffc4eaa3f49212244c0d4191ae5877b03bd50fd137bd9e5a16799da4a1f2846f0b26e3d956c4d8423004cc",
loadedBinary.getSHA512Sum());
}
}
@Test
@Override
public void testClone() {
try (Tx tx = tx()) {
NodeGraphFieldContainerImpl container = tx.getGraph().addFramedVertex(NodeGraphFieldContainerImpl.class);
HibBinary binary = tx.binaries().create(
"6a793cf1c7f6ef022ba9fff65ed43ddac9fb9c2131ffc4eaa3f49212244c0d4191ae5877b03bd50fd137bd9e5a16799da4a1f2846f0b26e3d956c4d8423004cc",
0L).runInExistingTx(tx);
BinaryGraphField field = container.createBinary(BINARY_FIELD, binary);
field.getBinary().setSize(220);
assertNotNull(field);
assertEquals(BINARY_FIELD, field.getFieldKey());
field.setFileName("blume.jpg");
field.setMimeType("image/jpg");
field.setImageDominantColor("#22A7F0");
field.getBinary().setImageHeight(133);
field.getBinary().setImageWidth(7);
NodeGraphFieldContainerImpl otherContainer = tx.getGraph().addFramedVertex(NodeGraphFieldContainerImpl.class);
field.cloneTo(otherContainer);
BinaryGraphField clonedField = otherContainer.getBinary(BINARY_FIELD);
assertThat(clonedField).as("cloned field").isNotNull().isEqualToIgnoringGivenFields(field, "outV", "id", "uuid", "element");
assertThat(clonedField.getBinary()).as("referenced binary of cloned field").isNotNull().isEqualToComparingFieldByField(field.getBinary());
}
}
@Test
@Override
public void testEquals() {
try (Tx tx = tx()) {
NodeGraphFieldContainerImpl container = tx.getGraph().addFramedVertex(NodeGraphFieldContainerImpl.class);
HibBinary binary = tx.binaries().create(UUIDUtil.randomUUID(), 1L).runInExistingTx(tx);
BinaryGraphField fieldA = container.createBinary("fieldA", binary);
BinaryGraphField fieldB = container.createBinary("fieldB", binary);
assertTrue("The field should be equal to itself", fieldA.equals(fieldA));
fieldA.setFileName("someText");
assertTrue("The field should be equal to itself", fieldA.equals(fieldA));
assertFalse("The field should not be equal to a non-string field", fieldA.equals("bogus"));
assertFalse("The field should not be equal since fieldB has no value", fieldA.equals(fieldB));
fieldB.setFileName("someText");
assertTrue("Both fields have the same value and should be equal", fieldA.equals(fieldB));
}
}
@Test
@Override
public void testEqualsNull() {
try (Tx tx = tx()) {
NodeGraphFieldContainerImpl container = tx.getGraph().addFramedVertex(NodeGraphFieldContainerImpl.class);
HibBinary binary = tx.binaries().create(UUIDUtil.randomUUID(), 0L).runInExistingTx(tx);
BinaryGraphField fieldA = container.createBinary(BINARY_FIELD, binary);
assertFalse(fieldA.equals((Field) null));
assertFalse(fieldA.equals((GraphField) null));
}
}
@Test
@Override
public void testEqualsRestField() {
try (Tx tx = tx()) {
NodeGraphFieldContainerImpl container = tx.getGraph().addFramedVertex(NodeGraphFieldContainerImpl.class);
HibBinary binary = tx.binaries().create("hashsum", 1L).runInExistingTx(tx);
BinaryGraphField fieldA = container.createBinary("fieldA", binary);
// graph empty - rest empty
assertTrue("The field should be equal to the html rest field since both fields have no value.", fieldA.equals(new BinaryFieldImpl()));
// graph set - rest set - same value - different type
fieldA.setFileName("someText");
assertFalse("The field should not be equal to a string rest field. Even if it has the same value", fieldA.equals(new StringFieldImpl()
.setString("someText")));
// graph set - rest set - different value
assertFalse("The field should not be equal to the rest field since the rest field has a different value.", fieldA.equals(
new BinaryFieldImpl().setFileName("blub")));
// graph set - rest set - same value
assertTrue("The binary field filename value should be equal to a rest field with the same value", fieldA.equals(new BinaryFieldImpl()
.setFileName("someText")));
}
}
@Test
@Override
public void testUpdateFromRestNullOnCreate() {
try (Tx tx = tx()) {
invokeUpdateFromRestTestcase(BINARY_FIELD, FETCH, CREATE_EMPTY);
}
}
@Test
@Override
public void testUpdateFromRestNullOnCreateRequired() {
try (Tx tx = tx()) {
invokeUpdateFromRestNullOnCreateRequiredTestcase(BINARY_FIELD, FETCH, false);
}
}
@Test
@Override
public void testRemoveFieldViaNull() {
try (Tx tx = tx()) {
InternalActionContext ac = mockActionContext();
invokeRemoveFieldViaNullTestcase(BINARY_FIELD, FETCH, FILL_BASIC, (node) -> {
updateContainer(ac, node, BINARY_FIELD, null);
});
}
}
@Test
@Override
public void testRemoveRequiredFieldViaNull() {
try (Tx tx = tx()) {
InternalActionContext ac = mockActionContext();
invokeRemoveRequiredFieldViaNullTestcase(BINARY_FIELD, FETCH, FILL_BASIC, (container) -> {
updateContainer(ac, container, BINARY_FIELD, null);
});
}
}
@Test
@Override
public void testUpdateFromRestValidSimpleValue() {
try (Tx tx = tx()) {
InternalActionContext ac = mockActionContext();
invokeUpdateFromRestValidSimpleValueTestcase(BINARY_FIELD, FILL_BASIC, (container) -> {
BinaryField field = new BinaryFieldImpl();
field.setFileName("someFile.txt");
updateContainer(ac, container, BINARY_FIELD, field);
}, (container) -> {
BinaryGraphField field = container.getBinary(BINARY_FIELD);
assertNotNull("The graph field {" + BINARY_FIELD + "} could not be found.", field);
assertEquals("The html of the field was not updated.", "someFile.txt", field.getFileName());
});
}
}
/**
* Verifies that the buffer stream of a source can be handled in parallel for hashing and image prop extraction.
*
* @throws IOException
*/
@Test
public void testMultiStreamHandling() throws IOException {
InputStream ins = getClass().getResourceAsStream("/pictures/blume.jpg");
byte[] bytes = IOUtils.toByteArray(ins);
Flowable<Buffer> obs = Flowable.just(Buffer.buffer(bytes)).publish().autoConnect(2);
File file = new File("target", "file" + System.currentTimeMillis());
try (FileOutputStream fos = new FileOutputStream(file)) {
IOUtils.write(bytes, fos);
fos.flush();
}
Single<ImageInfo> info = mesh().imageManipulator().readImageInfo(file.getAbsolutePath());
// Two obs handler
Single<String> hash = FileUtils.hash(obs);
Single<String> store = mesh().binaryStorage().store(obs, "bogus").toSingleDefault("null");
TransformationResult result = Single.zip(hash, info, store, (hashV, infoV, storeV) -> {
return new TransformationResult(hashV, 0, infoV, "blume.jpg");
}).blockingGet();
assertNotNull(result.getHash());
assertEquals(1376, result.getImageInfo().getHeight().intValue());
assertEquals(1160, result.getImageInfo().getWidth().intValue());
}
}
| 4,840 |
755 | /**
* @project: Overload
* @author: <NAME>.
* @licence: MIT
*/
#include <OvPhysics/Entities/PhysicalSphere.h>
#include <OvUI/Widgets/Drags/DragFloat.h>
#include "OvCore/ECS/Components/CPhysicalSphere.h"
#include "OvCore/ECS/Actor.h"
using namespace OvPhysics::Entities;
OvCore::ECS::Components::CPhysicalSphere::CPhysicalSphere(ECS::Actor & p_owner) :
CPhysicalObject(p_owner)
{
m_physicalObject = std::make_unique<PhysicalSphere>(p_owner.transform.GetFTransform());
m_physicalObject->SetUserData<std::reference_wrapper<CPhysicalObject>>(*this);
BindListener();
Init();
}
std::string OvCore::ECS::Components::CPhysicalSphere::GetName()
{
return "Physical Sphere";
}
void OvCore::ECS::Components::CPhysicalSphere::SetRadius(float p_radius)
{
GetPhysicalObjectAs<PhysicalSphere>().SetRadius(p_radius);
}
float OvCore::ECS::Components::CPhysicalSphere::GetRadius() const
{
return GetPhysicalObjectAs<PhysicalSphere>().GetRadius();
}
void OvCore::ECS::Components::CPhysicalSphere::OnSerialize(tinyxml2::XMLDocument & p_doc, tinyxml2::XMLNode * p_node)
{
CPhysicalObject::OnSerialize(p_doc, p_node);
Helpers::Serializer::SerializeFloat(p_doc, p_node, "radius", GetRadius());
}
void OvCore::ECS::Components::CPhysicalSphere::OnDeserialize(tinyxml2::XMLDocument & p_doc, tinyxml2::XMLNode * p_node)
{
CPhysicalObject::OnDeserialize(p_doc, p_node);
SetRadius(Helpers::Serializer::DeserializeFloat(p_doc, p_node, "radius"));
}
void OvCore::ECS::Components::CPhysicalSphere::OnInspector(OvUI::Internal::WidgetContainer & p_root)
{
CPhysicalObject::OnInspector(p_root);
Helpers::GUIDrawer::DrawScalar<float>(p_root, "Radius", std::bind(&CPhysicalSphere::GetRadius, this), std::bind(&CPhysicalSphere::SetRadius, this, std::placeholders::_1), 0.1f, 0.f, 100000.f);
} | 652 |
831 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.run.activity;
import com.android.tools.idea.apk.ApkFacet;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.psi.PsiClass;
import com.intellij.util.xml.DomElement;
import org.jetbrains.android.dom.converters.PackageClassConverter;
import org.jetbrains.android.dom.manifest.Activity;
import org.jetbrains.android.dom.manifest.ActivityAlias;
import org.jetbrains.android.dom.manifest.Application;
import org.jetbrains.android.dom.manifest.Manifest;
import org.jetbrains.android.util.AndroidUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import static com.android.SdkConstants.*;
import static com.android.xml.AndroidManifest.NODE_ACTION;
import static com.android.xml.AndroidManifest.NODE_CATEGORY;
public class ActivityLocatorUtils {
public static boolean containsAction(@NotNull Element filter, @NotNull String name) {
Node action = filter.getFirstChild();
while (action != null) {
if (action.getNodeType() == Node.ELEMENT_NODE && NODE_ACTION.equals(action.getNodeName())) {
if (name.equals(((Element)action).getAttributeNS(ANDROID_URI, ATTR_NAME))) {
return true;
}
}
action = action.getNextSibling();
}
return false;
}
public static boolean containsCategory(@NotNull Element filter, @NotNull String name) {
Node action = filter.getFirstChild();
while (action != null) {
if (action.getNodeType() == Node.ELEMENT_NODE && NODE_CATEGORY.equals(action.getNodeName())) {
if (name.equals(((Element)action).getAttributeNS(ANDROID_URI, ATTR_NAME))) {
return true;
}
}
action = action.getNextSibling();
}
return false;
}
public static boolean containsLauncherIntent(@NotNull DefaultActivityLocator.ActivityWrapper activity) {
return activity.hasAction(AndroidUtils.LAUNCH_ACTION_NAME) &&
(activity.hasCategory(AndroidUtils.LAUNCH_CATEGORY_NAME) || activity.hasCategory(AndroidUtils.LEANBACK_LAUNCH_CATEGORY_NAME));
}
@Nullable
public static String getQualifiedName(@NotNull Element component) {
Attr nameNode = component.getAttributeNodeNS(ANDROID_URI, ATTR_NAME);
if (nameNode == null) {
return null;
}
String name = nameNode.getValue();
int dotIndex = name.indexOf('.');
if (dotIndex > 0) { // fully qualified
return name;
}
// attempt to retrieve the package name from the manifest in which this alias was defined
Element root = component.getOwnerDocument().getDocumentElement();
Attr pkgNode = root.getAttributeNode(ATTR_PACKAGE);
if (pkgNode != null) {
// if we have a package name, prepend that to the activity alias
String pkg = pkgNode.getValue();
return pkg + (dotIndex == -1 ? "." : "") + name;
}
return name;
}
@Nullable
public static String getQualifiedName(@NotNull ActivityAlias alias) {
ApplicationManager.getApplication().assertReadAccessAllowed();
String name = alias.getName().getStringValue();
if (name == null) {
return null;
}
int dotIndex = name.indexOf('.');
if (dotIndex > 0) { // fully qualified
return name;
}
// attempt to retrieve the package name from the manifest in which this alias was defined
String pkg = null;
DomElement parent = alias.getParent();
if (parent instanceof Application) {
parent = parent.getParent();
if (parent instanceof Manifest) {
Manifest manifest = (Manifest)parent;
pkg = manifest.getPackage().getStringValue();
}
}
// if we have a package name, prepend that to the activity alias
return pkg == null ? name : pkg + (dotIndex == -1 ? "." : "") + name;
}
@Nullable
public static String getQualifiedName(@NotNull Activity activity) {
ApplicationManager.getApplication().assertReadAccessAllowed();
PsiClass psiClass = activity.getActivityClass().getValue();
if (psiClass == null) {
Module module = activity.getModule();
if (module != null && ApkFacet.getInstance(module) != null) {
// In APK project we doesn't necessarily have the source/class file of the activity.
return activity.getActivityClass().getStringValue();
}
return null;
}
return getQualifiedActivityName(psiClass);
}
/**
* Returns a fully qualified activity name as accepted by "am start" command: In particular, rather than return "com.foo.Bar.Inner",
* this will return "com.foo.Bar$Inner" for inner classes.
*/
@Nullable
public static String getQualifiedActivityName(@NotNull PsiClass c) {
return PackageClassConverter.getQualifiedName(c);
}
}
| 1,854 |
746 | <reponame>zhiqwang/mmdeploy<gh_stars>100-1000
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmdeploy.core import FUNCTION_REWRITER
@FUNCTION_REWRITER.register_rewriter(
func_name='mmdet.core.bbox.coder.tblr_bbox_coder.tblr2bboxes',
backend='default')
def tblr2bboxes(ctx,
priors,
tblr,
normalizer=4.0,
normalize_by_wh=True,
max_shape=None,
clip_border=True):
"""Rewrite `tblr2bboxes` for default backend.
Since the need of clip op with dynamic min and max, this function uses
clip_bboxes function to support dynamic shape.
Args:
ctx (ContextCaller): The context with additional information.
priors (Tensor): Prior boxes in point form (x0, y0, x1, y1)
Shape: (N,4) or (B, N, 4).
tblr (Tensor): Coords of network output in tblr form
Shape: (N, 4) or (B, N, 4).
normalizer (Sequence[float] | float): Normalization parameter of
encoded boxes. By list, it represents the normalization factors at
tblr dims. By float, it is the unified normalization factor at all
dims. Default: 4.0
normalize_by_wh (bool): Whether the tblr coordinates have been
normalized by the side length (wh) of prior bboxes.
max_shape (Sequence[int] or torch.Tensor or Sequence[
Sequence[int]],optional): Maximum bounds for boxes, specifies
(H, W, C) or (H, W). If priors shape is (B, N, 4), then
the max_shape should be a Sequence[Sequence[int]]
and the length of max_shape should also be B.
clip_border (bool, optional): Whether clip the objects outside the
border of the image. Defaults to True.
Return:
bboxes (Tensor): Boxes with shape (N, 4) or (B, N, 4)
"""
if not isinstance(normalizer, float):
normalizer = torch.tensor(normalizer, device=priors.device)
assert len(normalizer) == 4, 'Normalizer must have length = 4'
assert priors.size(0) == tblr.size(0)
if priors.ndim == 3:
assert priors.size(1) == tblr.size(1)
loc_decode = tblr * normalizer
prior_centers = (priors[..., 0:2] + priors[..., 2:4]) / 2
if normalize_by_wh:
wh = priors[..., 2:4] - priors[..., 0:2]
w, h = torch.split(wh, 1, dim=-1)
# Inplace operation with slice would fail for exporting to ONNX
th = h * loc_decode[..., :2] # tb
tw = w * loc_decode[..., 2:] # lr
loc_decode = torch.cat([th, tw], dim=-1)
top, bottom, left, right = loc_decode.split((1, 1, 1, 1), dim=-1)
xmin = prior_centers[..., 0].unsqueeze(-1) - left
xmax = prior_centers[..., 0].unsqueeze(-1) + right
ymin = prior_centers[..., 1].unsqueeze(-1) - top
ymax = prior_centers[..., 1].unsqueeze(-1) + bottom
if clip_border and max_shape is not None:
from mmdeploy.codebase.mmdet.deploy import clip_bboxes
xmin, ymin, xmax, ymax = clip_bboxes(xmin, ymin, xmax, ymax, max_shape)
bboxes = torch.cat([xmin, ymin, xmax, ymax], dim=-1).view(priors.size())
return bboxes
| 1,400 |
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.
package org.chromium.chrome.browser.offlinepages;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.chromium.base.test.BaseRobolectricTestRunner;
/** Unit tests for {@link OfflinePageOrigin}. */
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class OfflinePageOriginUnitTest {
@Test
public void testEncodeAsJson() {
String appName = "abc.xyz";
String[] signatures = new String[] {"deadbeef", "00c0ffee"};
OfflinePageOrigin origin = new OfflinePageOrigin(appName, signatures);
assertEquals("[\"abc.xyz\",[\"deadbeef\",\"00c0ffee\"]]", origin.encodeAsJsonString());
}
@Test
public void testEquals() {
String appName = "abc.xyz";
String[] signature1 = new String[] {"deadbeef", "00c0ffee"};
String[] signature2 = new String[] {"deadbeef", "fooba499"};
OfflinePageOrigin origin1 = new OfflinePageOrigin(appName, signature1);
OfflinePageOrigin origin2 = new OfflinePageOrigin(appName, signature2);
OfflinePageOrigin origin3 = new OfflinePageOrigin("", signature1);
OfflinePageOrigin origin4 = new OfflinePageOrigin(appName, signature1);
assertFalse("Equivalent to null", origin1.equals(null));
assertTrue("Not equivalent to self", origin1.equals(origin1));
assertFalse("Equivalent when signatures not equal", origin1.equals(origin2));
assertFalse("Equivalent when name not equal", origin1.equals(origin3));
assertTrue("Equally created items not equal", origin1.equals(origin4));
assertEquals("HashCode not equal to self", origin1.hashCode(), origin1.hashCode());
assertEquals(
"HashCode not equal when items are equal", origin1.hashCode(), origin4.hashCode());
}
}
| 748 |
12,718 | <reponame>Bhuvanesh1208/ruby2.6.1<filename>msys64/mingw64/x86_64-w64-mingw32/include/_bsd_types.h
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#ifndef _BSDTYPES_DEFINED
#define _BSDTYPES_DEFINED
/* Make sure __LONG32 is defined. */
#include <_mingw.h>
typedef unsigned char u_char;
typedef unsigned short u_short;
typedef unsigned int u_int;
#pragma push_macro("u_long")
#undef u_long
typedef unsigned long u_long;
#pragma pop_macro("u_long")
#if defined(__GNUC__) || \
defined(__GNUG__)
__extension__
#endif /* gcc / g++ */
typedef unsigned long long u_int64;
#endif /* _BSDTYPES_DEFINED */
#if defined (__LP64__) && defined (u_long)
typedef unsigned __LONG32 u_long;
#endif
| 335 |
614 | [
{ "home": "Chelsea", "away": "Tottenham Hotspur", "homescore": "2", "awayscore": "2" },
{ "home": "Genoa", "away": "AS Roma", "homescore": "2", "awayscore": "3" },
{ "home": "Napoli", "away": "Atalanta", "homescore": "2", "awayscore": "1" },
{ "home": "Málaga", "away": "Levante", "homescore": "3", "awayscore": "1" },
{ "home": "<NAME>", "away": "VfB Stuttgart", "homescore": "6", "awayscore": "2" },
{ "home": "Brighton & Hove Albion", "away": "Derby County", "homescore": "1", "awayscore": "1" },
{ "home": "Burnley", "away": "Queens Park Rangers", "homescore": "1", "awayscore": "0" },
{ "home": "Chelsea", "away": "Tottenham Hotspur", "homescore": "2", "awayscore": "2" },
{ "home": "Málaga", "away": "Levante", "homescore": "3", "awayscore": "1" },
{ "home": "<NAME>", "away": "VfB Stuttgart", "homescore": "6", "awayscore": "2" },
{ "home": "Genoa", "away": "AS Roma", "homescore": "2", "awayscore": "3" },
{ "home": "Napoli", "away": "Atalanta", "homescore": "2", "awayscore": "1" },
{ "home": "Brighton & Hove Albion", "away": "Derby County", "homescore": "1", "awayscore": "1" },
{ "home": "Burnley", "away": "Queens Park Rangers", "homescore": "1", "awayscore": "0" },
{ "home": "Walsall", "away": "Fleetwood Town", "homescore": "3", "awayscore": "1" },
{ "home": "Dundee", "away": "Dundee United", "homescore": "2", "awayscore": "1" },
{ "home": "<NAME>", "away": "Leganes", "homescore": "1", "awayscore": "2" },
{ "home": "Cesena", "away": "<NAME>", "homescore": "2", "awayscore": "1" },
{ "home": "<NAME>", "away": "<NAME>", "homescore": "3", "awayscore": "0" },
{ "home": "Valenciennes", "away": "AS <NAME>", "homescore": "1", "awayscore": "0" },
{ "home": "Kasimpasa", "away": "Ankaraspor" },
{ "home": "Esbjerg", "away": "O<NAME>K", "homescore": "0", "awayscore": "2" },
{ "home": "AIK", "away": "<NAME>", "homescore": "0", "awayscore": "0" },
{ "home": "Djurgarden", "away": "Ostersunds FK", "homescore": "3", "awayscore": "0" },
{ "home": "<NAME>", "away": "IFK", "homescore": "2", "awayscore": "5" },
{ "home": "IFK Norrkoping", "away": "Helsingborg", "homescore": "3", "awayscore": "0" },
{ "home": "<NAME>", "away": "Orebro SK", "homescore": "3", "awayscore": "2" },
{ "home": "Bodo/Glimt", "away": "Sarpsborg FK", "homescore": "0", "awayscore": "2" },
{ "home": "Rosario Central", "away": "<NAME>", "homescore": "0", "awayscore": "1" },
{ "home": "Tigre", "away": "Lanús", "homescore": "0", "awayscore": "1" },
{ "home": "Temperley", "away": "<NAME>", "homescore": "1", "awayscore": "0" },
{ "home": "<NAME>", "away": "Ctral. Córdoba SE", "homescore": "1", "awayscore": "0" },
{ "home": "<NAME>", "away": "Tall<NAME> Córdoba", "homescore": "0", "awayscore": "1" },
{ "home": "Barracas Central", "away": "Platense", "homescore": "1", "awayscore": "1" },
{ "home": "<NAME>", "away": "Fénix", "homescore": "1", "awayscore": "1" },
{ "home": "<NAME>", "away": "Flandria", "homescore": "1", "awayscore": "2" },
{ "home": "UAI Urquiza", "away": "Atlanta", "homescore": "0", "awayscore": "1" },
{ "home": "Liniers", "away": "Central Córdoba de Rosario", "homescore": "2", "awayscore": "1" },
{ "home": "Midland", "away": "Sacachispas", "homescore": "0", "awayscore": "1" },
{ "home": "<NAME>", "away": "Luján", "homescore": "1", "awayscore": "0" },
{ "home": "<NAME>", "away": "Ituzaingó", "homescore": "1", "awayscore": "1" },
{ "home": "<NAME>", "away": "Deportes Quindío", "homescore": "2", "awayscore": "2" },
{ "home": "Barranquilla FC", "away": "America Cali" },
{ "home": "Silver Stars", "away": "Orlando Pirates", "homescore": "2", "awayscore": "1" }
] | 1,547 |
7,731 | # This file is part of beets.
# Copyright 2016, <NAME>.
#
# 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.
"""Tests for the 'bucket' plugin."""
import unittest
from beetsplug import bucket
from beets import config, ui
from test.helper import TestHelper
class BucketPluginTest(unittest.TestCase, TestHelper):
def setUp(self):
self.setup_beets()
self.plugin = bucket.BucketPlugin()
def tearDown(self):
self.teardown_beets()
def _setup_config(self, bucket_year=[], bucket_alpha=[],
bucket_alpha_regex={}, extrapolate=False):
config['bucket']['bucket_year'] = bucket_year
config['bucket']['bucket_alpha'] = bucket_alpha
config['bucket']['bucket_alpha_regex'] = bucket_alpha_regex
config['bucket']['extrapolate'] = extrapolate
self.plugin.setup()
def test_year_single_year(self):
"""If a single year is given, range starts from this year and stops at
the year preceding the one of next bucket."""
self._setup_config(bucket_year=['1950s', '1970s'])
self.assertEqual(self.plugin._tmpl_bucket('1959'), '1950s')
self.assertEqual(self.plugin._tmpl_bucket('1969'), '1950s')
def test_year_single_year_last_folder(self):
"""If a single year is given for the last bucket, extend it to current
year."""
self._setup_config(bucket_year=['1950', '1970'])
self.assertEqual(self.plugin._tmpl_bucket('2014'), '1970')
self.assertEqual(self.plugin._tmpl_bucket('2025'), '2025')
def test_year_two_years(self):
"""Buckets can be named with the 'from-to' syntax."""
self._setup_config(bucket_year=['1950-59', '1960-1969'])
self.assertEqual(self.plugin._tmpl_bucket('1959'), '1950-59')
self.assertEqual(self.plugin._tmpl_bucket('1969'), '1960-1969')
def test_year_multiple_years(self):
"""Buckets can be named by listing all the years"""
self._setup_config(bucket_year=['1950,51,52,53'])
self.assertEqual(self.plugin._tmpl_bucket('1953'), '1950,51,52,53')
self.assertEqual(self.plugin._tmpl_bucket('1974'), '1974')
def test_year_out_of_range(self):
"""If no range match, return the year"""
self._setup_config(bucket_year=['1950-59', '1960-69'])
self.assertEqual(self.plugin._tmpl_bucket('1974'), '1974')
self._setup_config(bucket_year=[])
self.assertEqual(self.plugin._tmpl_bucket('1974'), '1974')
def test_year_out_of_range_extrapolate(self):
"""If no defined range match, extrapolate all ranges using the most
common syntax amongst existing buckets and return the matching one."""
self._setup_config(bucket_year=['1950-59', '1960-69'],
extrapolate=True)
self.assertEqual(self.plugin._tmpl_bucket('1914'), '1910-19')
# pick single year format
self._setup_config(bucket_year=['1962-81', '2002', '2012'],
extrapolate=True)
self.assertEqual(self.plugin._tmpl_bucket('1983'), '1982')
# pick from-end format
self._setup_config(bucket_year=['1962-81', '2002', '2012-14'],
extrapolate=True)
self.assertEqual(self.plugin._tmpl_bucket('1983'), '1982-01')
# extrapolate add ranges, but never modifies existing ones
self._setup_config(bucket_year=['1932', '1942', '1952', '1962-81',
'2002'], extrapolate=True)
self.assertEqual(self.plugin._tmpl_bucket('1975'), '1962-81')
def test_alpha_all_chars(self):
"""Alphabet buckets can be named by listing all their chars"""
self._setup_config(bucket_alpha=['ABCD', 'FGH', 'IJKL'])
self.assertEqual(self.plugin._tmpl_bucket('garry'), 'FGH')
def test_alpha_first_last_chars(self):
"""Alphabet buckets can be named by listing the 'from-to' syntax"""
self._setup_config(bucket_alpha=['0->9', 'A->D', 'F-H', 'I->Z'])
self.assertEqual(self.plugin._tmpl_bucket('garry'), 'F-H')
self.assertEqual(self.plugin._tmpl_bucket('2pac'), '0->9')
def test_alpha_out_of_range(self):
"""If no range match, return the initial"""
self._setup_config(bucket_alpha=['ABCD', 'FGH', 'IJKL'])
self.assertEqual(self.plugin._tmpl_bucket('errol'), 'E')
self._setup_config(bucket_alpha=[])
self.assertEqual(self.plugin._tmpl_bucket('errol'), 'E')
def test_alpha_regex(self):
"""Check regex is used"""
self._setup_config(bucket_alpha=['foo', 'bar'],
bucket_alpha_regex={'foo': '^[a-d]',
'bar': '^[e-z]'})
self.assertEqual(self.plugin._tmpl_bucket('alpha'), 'foo')
self.assertEqual(self.plugin._tmpl_bucket('delta'), 'foo')
self.assertEqual(self.plugin._tmpl_bucket('zeta'), 'bar')
self.assertEqual(self.plugin._tmpl_bucket('Alpha'), 'A')
def test_alpha_regex_mix(self):
"""Check mixing regex and non-regex is possible"""
self._setup_config(bucket_alpha=['A - D', 'E - L'],
bucket_alpha_regex={'A - D': '^[0-9a-dA-D…äÄ]'})
self.assertEqual(self.plugin._tmpl_bucket('alpha'), 'A - D')
self.assertEqual(self.plugin._tmpl_bucket('Ärzte'), 'A - D')
self.assertEqual(self.plugin._tmpl_bucket('112'), 'A - D')
self.assertEqual(self.plugin._tmpl_bucket('…and Oceans'), 'A - D')
self.assertEqual(self.plugin._tmpl_bucket('Eagles'), 'E - L')
def test_bad_alpha_range_def(self):
"""If bad alpha range definition, a UserError is raised."""
with self.assertRaises(ui.UserError):
self._setup_config(bucket_alpha=['$%'])
def test_bad_year_range_def_no4digits(self):
"""If bad year range definition, a UserError is raised.
Range origin must be expressed on 4 digits.
"""
with self.assertRaises(ui.UserError):
self._setup_config(bucket_year=['62-64'])
def test_bad_year_range_def_nodigits(self):
"""If bad year range definition, a UserError is raised.
At least the range origin must be declared.
"""
with self.assertRaises(ui.UserError):
self._setup_config(bucket_year=['nodigits'])
def check_span_from_str(self, sstr, dfrom, dto):
d = bucket.span_from_str(sstr)
self.assertEqual(dfrom, d['from'])
self.assertEqual(dto, d['to'])
def test_span_from_str(self):
self.check_span_from_str("1980 2000", 1980, 2000)
self.check_span_from_str("1980 00", 1980, 2000)
self.check_span_from_str("1930 00", 1930, 2000)
self.check_span_from_str("1930 50", 1930, 1950)
def suite():
return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| 3,196 |
399 | #pragma once
#ifdef _WIN32
# define NOMINMAX
#endif
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/color_space.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <glm/gtx/io.hpp>
#include <glm/gtc/constants.hpp>
#include <imgui/imgui.h>
#include <string>
#include <vector>
#include <algorithm>
#include <memory>
typedef unsigned char uchar;
typedef unsigned int uint;
typedef unsigned long ulong;
#ifdef _WIN32
# undef near
# undef far
# undef ERROR
#endif
#include "system/Logger.hpp"
#define STD_HASH(ENUM_NAME) \
template <> struct std::hash<ENUM_NAME> { \
std::size_t operator()(const ENUM_NAME & t) const { return static_cast<std::underlying_type< ENUM_NAME >::type>(t); } \
};
| 342 |
307 | <gh_stars>100-1000
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: FBOutput
class DriveAxis(object):
x = 1
y = 2
z = 4
| 60 |
7,409 | # Generated by Django 3.0.11 on 2021-01-12 13:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("posthog", "0112_sessions_filter"),
]
operations = [
migrations.AddField(model_name="cohort", name="is_static", field=models.BooleanField(default=False),),
]
| 130 |
348 | {"nom":"<NAME>","circ":"8ème circonscription","dpt":"Var","inscrits":2396,"abs":1395,"votants":1001,"blancs":69,"nuls":16,"exp":916,"res":[{"nuance":"REM","nom":"<NAME>","voix":527},{"nuance":"FN","nom":"<NAME>","voix":389}]} | 90 |
3,807 | /*
* Copyright 2019 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <Foundation/Foundation.h>
#import "FirebaseInstallations/Source/Library/Public/FirebaseInstallations/FIRInstallationsErrors.h"
@class FIRInstallationsHTTPError;
@class FBLPromise<ResultType>;
NS_ASSUME_NONNULL_BEGIN
void FIRInstallationsItemSetErrorToPointer(NSError *error, NSError **pointer);
@interface FIRInstallationsErrorUtil : NSObject
+ (NSError *)keyedArchiverErrorWithException:(NSException *)exception;
+ (NSError *)keyedArchiverErrorWithError:(NSError *)error;
+ (NSError *)keychainErrorWithFunction:(NSString *)keychainFunction status:(OSStatus)status;
+ (NSError *)installationItemNotFoundForAppID:(NSString *)appID appName:(NSString *)appName;
+ (NSError *)JSONSerializationError:(NSError *)error;
+ (NSError *)networkErrorWithError:(NSError *)error;
+ (NSError *)FIDRegistrationErrorWithResponseMissingField:(NSString *)missingFieldName;
+ (NSError *)corruptedIIDTokenData;
+ (FIRInstallationsHTTPError *)APIErrorWithHTTPResponse:(NSHTTPURLResponse *)HTTPResponse
data:(nullable NSData *)data;
+ (BOOL)isAPIError:(NSError *)error withHTTPCode:(NSInteger)HTTPCode;
+ (NSError *)backoffIntervalWaitError;
/**
* Returns the passed error if it is already in the public domain or a new error with the passed
* error at `NSUnderlyingErrorKey`.
*/
+ (NSError *)publicDomainErrorWithError:(NSError *)error;
+ (FBLPromise *)rejectedPromiseWithError:(NSError *)error;
+ (NSError *)installationsErrorWithCode:(FIRInstallationsErrorCode)code
failureReason:(nullable NSString *)failureReason
underlyingError:(nullable NSError *)underlyingError;
@end
NS_ASSUME_NONNULL_END
| 787 |
1,035 | # coding: utf-8
# flake8: noqa
"""
Penguin Statistics - REST APIs
Backend APIs for Arknights drop rate statistics website 'Penguin Statistics': https://penguin-stats.io/ # noqa: E501
OpenAPI spec version: 2.0.0
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import models into model package
from penguin_client.models.advanced_query_request import AdvancedQueryRequest
from penguin_client.models.advanced_query_response import AdvancedQueryResponse
from penguin_client.models.basic_query_response import BasicQueryResponse
from penguin_client.models.bounds import Bounds
from penguin_client.models.drop_info import DropInfo
from penguin_client.models.drop_matrix_element import DropMatrixElement
from penguin_client.models.event_period import EventPeriod
from penguin_client.models.exist_conditions import ExistConditions
from penguin_client.models.existence import Existence
from penguin_client.models.item import Item
from penguin_client.models.item_quantity import ItemQuantity
from penguin_client.models.item_quantity_bounds import ItemQuantityBounds
from penguin_client.models.limitation import Limitation
from penguin_client.models.matrix_query_response import MatrixQueryResponse
from penguin_client.models.notice import Notice
from penguin_client.models.recall_last_report_request import RecallLastReportRequest
from penguin_client.models.single_query import SingleQuery
from penguin_client.models.single_report_request import SingleReportRequest
from penguin_client.models.single_report_response import SingleReportResponse
from penguin_client.models.site_stats_response import SiteStatsResponse
from penguin_client.models.stage import Stage
from penguin_client.models.stage_times import StageTimes
from penguin_client.models.stage_trend import StageTrend
from penguin_client.models.time_range import TimeRange
from penguin_client.models.trend_detail import TrendDetail
from penguin_client.models.trend_query_response import TrendQueryResponse
from penguin_client.models.typed_drop import TypedDrop
from penguin_client.models.zone import Zone
| 595 |
11,356 | <filename>src/visualization/annotation/build/format/cpp/message.pb.h
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: message.proto
#ifndef PROTOBUF_message_2eproto__INCLUDED
#define PROTOBUF_message_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3003000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include "annotate.pb.h" // IWYU pragma: export
#include "data.pb.h" // IWYU pragma: export
#include "meta.pb.h" // IWYU pragma: export
#include "progress.pb.h" // IWYU pragma: export
#include "similarity.pb.h" // IWYU pragma: export
// @@protoc_insertion_point(includes)
namespace TuriCreate {
namespace Annotation {
namespace Specification {
class ActivityClassificationLabel;
class ActivityClassificationLabelDefaultTypeInternal;
extern ActivityClassificationLabelDefaultTypeInternal _ActivityClassificationLabel_default_instance_;
class ActivityClassificationMeta;
class ActivityClassificationMetaDefaultTypeInternal;
extern ActivityClassificationMetaDefaultTypeInternal _ActivityClassificationMeta_default_instance_;
class Annotation;
class AnnotationDefaultTypeInternal;
extern AnnotationDefaultTypeInternal _Annotation_default_instance_;
class Annotations;
class AnnotationsDefaultTypeInternal;
extern AnnotationsDefaultTypeInternal _Annotations_default_instance_;
class AudioClassificationLabel;
class AudioClassificationLabelDefaultTypeInternal;
extern AudioClassificationLabelDefaultTypeInternal _AudioClassificationLabel_default_instance_;
class AudioClassificationMeta;
class AudioClassificationMetaDefaultTypeInternal;
extern AudioClassificationMetaDefaultTypeInternal _AudioClassificationMeta_default_instance_;
class ClientRequest;
class ClientRequestDefaultTypeInternal;
extern ClientRequestDefaultTypeInternal _ClientRequest_default_instance_;
class Data;
class DataDefaultTypeInternal;
extern DataDefaultTypeInternal _Data_default_instance_;
class DataGetter;
class DataGetterDefaultTypeInternal;
extern DataGetterDefaultTypeInternal _DataGetter_default_instance_;
class Datum;
class DatumDefaultTypeInternal;
extern DatumDefaultTypeInternal _Datum_default_instance_;
class DrawingClassificationLabel;
class DrawingClassificationLabelDefaultTypeInternal;
extern DrawingClassificationLabelDefaultTypeInternal _DrawingClassificationLabel_default_instance_;
class DrawingClassificationMeta;
class DrawingClassificationMetaDefaultTypeInternal;
extern DrawingClassificationMetaDefaultTypeInternal _DrawingClassificationMeta_default_instance_;
class ImageClassificationLabel;
class ImageClassificationLabelDefaultTypeInternal;
extern ImageClassificationLabelDefaultTypeInternal _ImageClassificationLabel_default_instance_;
class ImageClassificationMeta;
class ImageClassificationMetaDefaultTypeInternal;
extern ImageClassificationMetaDefaultTypeInternal _ImageClassificationMeta_default_instance_;
class ImageDatum;
class ImageDatumDefaultTypeInternal;
extern ImageDatumDefaultTypeInternal _ImageDatum_default_instance_;
class Label;
class LabelDefaultTypeInternal;
extern LabelDefaultTypeInternal _Label_default_instance_;
class MetaData;
class MetaDataDefaultTypeInternal;
extern MetaDataDefaultTypeInternal _MetaData_default_instance_;
class MetaLabel;
class MetaLabelDefaultTypeInternal;
extern MetaLabelDefaultTypeInternal _MetaLabel_default_instance_;
class ObjectDetectionLabel;
class ObjectDetectionLabelDefaultTypeInternal;
extern ObjectDetectionLabelDefaultTypeInternal _ObjectDetectionLabel_default_instance_;
class ObjectDetectionMeta;
class ObjectDetectionMetaDefaultTypeInternal;
extern ObjectDetectionMetaDefaultTypeInternal _ObjectDetectionMeta_default_instance_;
class Parcel;
class ParcelDefaultTypeInternal;
extern ParcelDefaultTypeInternal _Parcel_default_instance_;
class ProgressMeta;
class ProgressMetaDefaultTypeInternal;
extern ProgressMetaDefaultTypeInternal _ProgressMeta_default_instance_;
class Similarity;
class SimilarityDefaultTypeInternal;
extern SimilarityDefaultTypeInternal _Similarity_default_instance_;
class TextDatum;
class TextDatumDefaultTypeInternal;
extern TextDatumDefaultTypeInternal _TextDatum_default_instance_;
} // namespace Specification
} // namespace Annotation
} // namespace TuriCreate
namespace TuriCreate {
namespace Annotation {
namespace Specification {
namespace protobuf_message_2eproto {
// Internal implementation detail -- do not call these.
struct TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[];
static const ::google::protobuf::uint32 offsets[];
static void InitDefaultsImpl();
static void Shutdown();
};
void AddDescriptors();
void InitDefaults();
} // namespace protobuf_message_2eproto
// ===================================================================
class Parcel : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:TuriCreate.Annotation.Specification.Parcel) */ {
public:
Parcel();
virtual ~Parcel();
Parcel(const Parcel& from);
inline Parcel& operator=(const Parcel& from) {
CopyFrom(from);
return *this;
}
static const Parcel& default_instance();
enum MessageCase {
kAnnotations = 1,
kData = 2,
kMetadata = 3,
kProgress = 4,
kSimilarity = 5,
MESSAGE_NOT_SET = 0,
};
static inline const Parcel* internal_default_instance() {
return reinterpret_cast<const Parcel*>(
&_Parcel_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
0;
void Swap(Parcel* other);
// implements Message ----------------------------------------------
inline Parcel* New() const PROTOBUF_FINAL { return New(NULL); }
Parcel* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
PROTOBUF_FINAL;
void CopyFrom(const Parcel& from);
void MergeFrom(const Parcel& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
void DiscardUnknownFields();
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Parcel* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// .TuriCreate.Annotation.Specification.Annotations annotations = 1;
bool has_annotations() const;
void clear_annotations();
static const int kAnnotationsFieldNumber = 1;
const ::TuriCreate::Annotation::Specification::Annotations& annotations() const;
::TuriCreate::Annotation::Specification::Annotations* mutable_annotations();
::TuriCreate::Annotation::Specification::Annotations* release_annotations();
void set_allocated_annotations(::TuriCreate::Annotation::Specification::Annotations* annotations);
// .TuriCreate.Annotation.Specification.Data data = 2;
bool has_data() const;
void clear_data();
static const int kDataFieldNumber = 2;
const ::TuriCreate::Annotation::Specification::Data& data() const;
::TuriCreate::Annotation::Specification::Data* mutable_data();
::TuriCreate::Annotation::Specification::Data* release_data();
void set_allocated_data(::TuriCreate::Annotation::Specification::Data* data);
// .TuriCreate.Annotation.Specification.MetaData metadata = 3;
bool has_metadata() const;
void clear_metadata();
static const int kMetadataFieldNumber = 3;
const ::TuriCreate::Annotation::Specification::MetaData& metadata() const;
::TuriCreate::Annotation::Specification::MetaData* mutable_metadata();
::TuriCreate::Annotation::Specification::MetaData* release_metadata();
void set_allocated_metadata(::TuriCreate::Annotation::Specification::MetaData* metadata);
// .TuriCreate.Annotation.Specification.ProgressMeta progress = 4;
bool has_progress() const;
void clear_progress();
static const int kProgressFieldNumber = 4;
const ::TuriCreate::Annotation::Specification::ProgressMeta& progress() const;
::TuriCreate::Annotation::Specification::ProgressMeta* mutable_progress();
::TuriCreate::Annotation::Specification::ProgressMeta* release_progress();
void set_allocated_progress(::TuriCreate::Annotation::Specification::ProgressMeta* progress);
// .TuriCreate.Annotation.Specification.Similarity similarity = 5;
bool has_similarity() const;
void clear_similarity();
static const int kSimilarityFieldNumber = 5;
const ::TuriCreate::Annotation::Specification::Similarity& similarity() const;
::TuriCreate::Annotation::Specification::Similarity* mutable_similarity();
::TuriCreate::Annotation::Specification::Similarity* release_similarity();
void set_allocated_similarity(::TuriCreate::Annotation::Specification::Similarity* similarity);
MessageCase Message_case() const;
// @@protoc_insertion_point(class_scope:TuriCreate.Annotation.Specification.Parcel)
private:
void set_has_annotations();
void set_has_data();
void set_has_metadata();
void set_has_progress();
void set_has_similarity();
inline bool has_Message() const;
void clear_Message();
inline void clear_has_Message();
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
union MessageUnion {
MessageUnion() {}
::TuriCreate::Annotation::Specification::Annotations* annotations_;
::TuriCreate::Annotation::Specification::Data* data_;
::TuriCreate::Annotation::Specification::MetaData* metadata_;
::TuriCreate::Annotation::Specification::ProgressMeta* progress_;
::TuriCreate::Annotation::Specification::Similarity* similarity_;
} Message_;
mutable int _cached_size_;
::google::protobuf::uint32 _oneof_case_[1];
friend struct protobuf_message_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class ClientRequest : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:TuriCreate.Annotation.Specification.ClientRequest) */ {
public:
ClientRequest();
virtual ~ClientRequest();
ClientRequest(const ClientRequest& from);
inline ClientRequest& operator=(const ClientRequest& from) {
CopyFrom(from);
return *this;
}
static const ClientRequest& default_instance();
enum TypeCase {
kGetter = 1,
kAnnotations = 2,
TYPE_NOT_SET = 0,
};
static inline const ClientRequest* internal_default_instance() {
return reinterpret_cast<const ClientRequest*>(
&_ClientRequest_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
1;
void Swap(ClientRequest* other);
// implements Message ----------------------------------------------
inline ClientRequest* New() const PROTOBUF_FINAL { return New(NULL); }
ClientRequest* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
PROTOBUF_FINAL;
void CopyFrom(const ClientRequest& from);
void MergeFrom(const ClientRequest& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
void DiscardUnknownFields();
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(ClientRequest* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// .TuriCreate.Annotation.Specification.DataGetter getter = 1;
bool has_getter() const;
void clear_getter();
static const int kGetterFieldNumber = 1;
const ::TuriCreate::Annotation::Specification::DataGetter& getter() const;
::TuriCreate::Annotation::Specification::DataGetter* mutable_getter();
::TuriCreate::Annotation::Specification::DataGetter* release_getter();
void set_allocated_getter(::TuriCreate::Annotation::Specification::DataGetter* getter);
// .TuriCreate.Annotation.Specification.Annotations annotations = 2;
bool has_annotations() const;
void clear_annotations();
static const int kAnnotationsFieldNumber = 2;
const ::TuriCreate::Annotation::Specification::Annotations& annotations() const;
::TuriCreate::Annotation::Specification::Annotations* mutable_annotations();
::TuriCreate::Annotation::Specification::Annotations* release_annotations();
void set_allocated_annotations(::TuriCreate::Annotation::Specification::Annotations* annotations);
TypeCase Type_case() const;
// @@protoc_insertion_point(class_scope:TuriCreate.Annotation.Specification.ClientRequest)
private:
void set_has_getter();
void set_has_annotations();
inline bool has_Type() const;
void clear_Type();
inline void clear_has_Type();
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
union TypeUnion {
TypeUnion() {}
::TuriCreate::Annotation::Specification::DataGetter* getter_;
::TuriCreate::Annotation::Specification::Annotations* annotations_;
} Type_;
mutable int _cached_size_;
::google::protobuf::uint32 _oneof_case_[1];
friend struct protobuf_message_2eproto::TableStruct;
};
// ===================================================================
// ===================================================================
#if !PROTOBUF_INLINE_NOT_IN_HEADERS
// Parcel
// .TuriCreate.Annotation.Specification.Annotations annotations = 1;
inline bool Parcel::has_annotations() const {
return Message_case() == kAnnotations;
}
inline void Parcel::set_has_annotations() {
_oneof_case_[0] = kAnnotations;
}
inline void Parcel::clear_annotations() {
if (has_annotations()) {
delete Message_.annotations_;
clear_has_Message();
}
}
inline const ::TuriCreate::Annotation::Specification::Annotations& Parcel::annotations() const {
// @@protoc_insertion_point(field_get:TuriCreate.Annotation.Specification.Parcel.annotations)
return has_annotations()
? *Message_.annotations_
: ::TuriCreate::Annotation::Specification::Annotations::default_instance();
}
inline ::TuriCreate::Annotation::Specification::Annotations* Parcel::mutable_annotations() {
if (!has_annotations()) {
clear_Message();
set_has_annotations();
Message_.annotations_ = new ::TuriCreate::Annotation::Specification::Annotations;
}
// @@protoc_insertion_point(field_mutable:TuriCreate.Annotation.Specification.Parcel.annotations)
return Message_.annotations_;
}
inline ::TuriCreate::Annotation::Specification::Annotations* Parcel::release_annotations() {
// @@protoc_insertion_point(field_release:TuriCreate.Annotation.Specification.Parcel.annotations)
if (has_annotations()) {
clear_has_Message();
::TuriCreate::Annotation::Specification::Annotations* temp = Message_.annotations_;
Message_.annotations_ = NULL;
return temp;
} else {
return NULL;
}
}
inline void Parcel::set_allocated_annotations(::TuriCreate::Annotation::Specification::Annotations* annotations) {
clear_Message();
if (annotations) {
set_has_annotations();
Message_.annotations_ = annotations;
}
// @@protoc_insertion_point(field_set_allocated:TuriCreate.Annotation.Specification.Parcel.annotations)
}
// .TuriCreate.Annotation.Specification.Data data = 2;
inline bool Parcel::has_data() const {
return Message_case() == kData;
}
inline void Parcel::set_has_data() {
_oneof_case_[0] = kData;
}
inline void Parcel::clear_data() {
if (has_data()) {
delete Message_.data_;
clear_has_Message();
}
}
inline const ::TuriCreate::Annotation::Specification::Data& Parcel::data() const {
// @@protoc_insertion_point(field_get:TuriCreate.Annotation.Specification.Parcel.data)
return has_data()
? *Message_.data_
: ::TuriCreate::Annotation::Specification::Data::default_instance();
}
inline ::TuriCreate::Annotation::Specification::Data* Parcel::mutable_data() {
if (!has_data()) {
clear_Message();
set_has_data();
Message_.data_ = new ::TuriCreate::Annotation::Specification::Data;
}
// @@protoc_insertion_point(field_mutable:TuriCreate.Annotation.Specification.Parcel.data)
return Message_.data_;
}
inline ::TuriCreate::Annotation::Specification::Data* Parcel::release_data() {
// @@protoc_insertion_point(field_release:TuriCreate.Annotation.Specification.Parcel.data)
if (has_data()) {
clear_has_Message();
::TuriCreate::Annotation::Specification::Data* temp = Message_.data_;
Message_.data_ = NULL;
return temp;
} else {
return NULL;
}
}
inline void Parcel::set_allocated_data(::TuriCreate::Annotation::Specification::Data* data) {
clear_Message();
if (data) {
set_has_data();
Message_.data_ = data;
}
// @@protoc_insertion_point(field_set_allocated:TuriCreate.Annotation.Specification.Parcel.data)
}
// .TuriCreate.Annotation.Specification.MetaData metadata = 3;
inline bool Parcel::has_metadata() const {
return Message_case() == kMetadata;
}
inline void Parcel::set_has_metadata() {
_oneof_case_[0] = kMetadata;
}
inline void Parcel::clear_metadata() {
if (has_metadata()) {
delete Message_.metadata_;
clear_has_Message();
}
}
inline const ::TuriCreate::Annotation::Specification::MetaData& Parcel::metadata() const {
// @@protoc_insertion_point(field_get:TuriCreate.Annotation.Specification.Parcel.metadata)
return has_metadata()
? *Message_.metadata_
: ::TuriCreate::Annotation::Specification::MetaData::default_instance();
}
inline ::TuriCreate::Annotation::Specification::MetaData* Parcel::mutable_metadata() {
if (!has_metadata()) {
clear_Message();
set_has_metadata();
Message_.metadata_ = new ::TuriCreate::Annotation::Specification::MetaData;
}
// @@protoc_insertion_point(field_mutable:TuriCreate.Annotation.Specification.Parcel.metadata)
return Message_.metadata_;
}
inline ::TuriCreate::Annotation::Specification::MetaData* Parcel::release_metadata() {
// @@protoc_insertion_point(field_release:TuriCreate.Annotation.Specification.Parcel.metadata)
if (has_metadata()) {
clear_has_Message();
::TuriCreate::Annotation::Specification::MetaData* temp = Message_.metadata_;
Message_.metadata_ = NULL;
return temp;
} else {
return NULL;
}
}
inline void Parcel::set_allocated_metadata(::TuriCreate::Annotation::Specification::MetaData* metadata) {
clear_Message();
if (metadata) {
set_has_metadata();
Message_.metadata_ = metadata;
}
// @@protoc_insertion_point(field_set_allocated:TuriCreate.Annotation.Specification.Parcel.metadata)
}
// .TuriCreate.Annotation.Specification.ProgressMeta progress = 4;
inline bool Parcel::has_progress() const {
return Message_case() == kProgress;
}
inline void Parcel::set_has_progress() {
_oneof_case_[0] = kProgress;
}
inline void Parcel::clear_progress() {
if (has_progress()) {
delete Message_.progress_;
clear_has_Message();
}
}
inline const ::TuriCreate::Annotation::Specification::ProgressMeta& Parcel::progress() const {
// @@protoc_insertion_point(field_get:TuriCreate.Annotation.Specification.Parcel.progress)
return has_progress()
? *Message_.progress_
: ::TuriCreate::Annotation::Specification::ProgressMeta::default_instance();
}
inline ::TuriCreate::Annotation::Specification::ProgressMeta* Parcel::mutable_progress() {
if (!has_progress()) {
clear_Message();
set_has_progress();
Message_.progress_ = new ::TuriCreate::Annotation::Specification::ProgressMeta;
}
// @@protoc_insertion_point(field_mutable:TuriCreate.Annotation.Specification.Parcel.progress)
return Message_.progress_;
}
inline ::TuriCreate::Annotation::Specification::ProgressMeta* Parcel::release_progress() {
// @@protoc_insertion_point(field_release:TuriCreate.Annotation.Specification.Parcel.progress)
if (has_progress()) {
clear_has_Message();
::TuriCreate::Annotation::Specification::ProgressMeta* temp = Message_.progress_;
Message_.progress_ = NULL;
return temp;
} else {
return NULL;
}
}
inline void Parcel::set_allocated_progress(::TuriCreate::Annotation::Specification::ProgressMeta* progress) {
clear_Message();
if (progress) {
set_has_progress();
Message_.progress_ = progress;
}
// @@protoc_insertion_point(field_set_allocated:TuriCreate.Annotation.Specification.Parcel.progress)
}
// .TuriCreate.Annotation.Specification.Similarity similarity = 5;
inline bool Parcel::has_similarity() const {
return Message_case() == kSimilarity;
}
inline void Parcel::set_has_similarity() {
_oneof_case_[0] = kSimilarity;
}
inline void Parcel::clear_similarity() {
if (has_similarity()) {
delete Message_.similarity_;
clear_has_Message();
}
}
inline const ::TuriCreate::Annotation::Specification::Similarity& Parcel::similarity() const {
// @@protoc_insertion_point(field_get:TuriCreate.Annotation.Specification.Parcel.similarity)
return has_similarity()
? *Message_.similarity_
: ::TuriCreate::Annotation::Specification::Similarity::default_instance();
}
inline ::TuriCreate::Annotation::Specification::Similarity* Parcel::mutable_similarity() {
if (!has_similarity()) {
clear_Message();
set_has_similarity();
Message_.similarity_ = new ::TuriCreate::Annotation::Specification::Similarity;
}
// @@protoc_insertion_point(field_mutable:TuriCreate.Annotation.Specification.Parcel.similarity)
return Message_.similarity_;
}
inline ::TuriCreate::Annotation::Specification::Similarity* Parcel::release_similarity() {
// @@protoc_insertion_point(field_release:TuriCreate.Annotation.Specification.Parcel.similarity)
if (has_similarity()) {
clear_has_Message();
::TuriCreate::Annotation::Specification::Similarity* temp = Message_.similarity_;
Message_.similarity_ = NULL;
return temp;
} else {
return NULL;
}
}
inline void Parcel::set_allocated_similarity(::TuriCreate::Annotation::Specification::Similarity* similarity) {
clear_Message();
if (similarity) {
set_has_similarity();
Message_.similarity_ = similarity;
}
// @@protoc_insertion_point(field_set_allocated:TuriCreate.Annotation.Specification.Parcel.similarity)
}
inline bool Parcel::has_Message() const {
return Message_case() != MESSAGE_NOT_SET;
}
inline void Parcel::clear_has_Message() {
_oneof_case_[0] = MESSAGE_NOT_SET;
}
inline Parcel::MessageCase Parcel::Message_case() const {
return Parcel::MessageCase(_oneof_case_[0]);
}
// -------------------------------------------------------------------
// ClientRequest
// .TuriCreate.Annotation.Specification.DataGetter getter = 1;
inline bool ClientRequest::has_getter() const {
return Type_case() == kGetter;
}
inline void ClientRequest::set_has_getter() {
_oneof_case_[0] = kGetter;
}
inline void ClientRequest::clear_getter() {
if (has_getter()) {
delete Type_.getter_;
clear_has_Type();
}
}
inline const ::TuriCreate::Annotation::Specification::DataGetter& ClientRequest::getter() const {
// @@protoc_insertion_point(field_get:TuriCreate.Annotation.Specification.ClientRequest.getter)
return has_getter()
? *Type_.getter_
: ::TuriCreate::Annotation::Specification::DataGetter::default_instance();
}
inline ::TuriCreate::Annotation::Specification::DataGetter* ClientRequest::mutable_getter() {
if (!has_getter()) {
clear_Type();
set_has_getter();
Type_.getter_ = new ::TuriCreate::Annotation::Specification::DataGetter;
}
// @@protoc_insertion_point(field_mutable:TuriCreate.Annotation.Specification.ClientRequest.getter)
return Type_.getter_;
}
inline ::TuriCreate::Annotation::Specification::DataGetter* ClientRequest::release_getter() {
// @@protoc_insertion_point(field_release:TuriCreate.Annotation.Specification.ClientRequest.getter)
if (has_getter()) {
clear_has_Type();
::TuriCreate::Annotation::Specification::DataGetter* temp = Type_.getter_;
Type_.getter_ = NULL;
return temp;
} else {
return NULL;
}
}
inline void ClientRequest::set_allocated_getter(::TuriCreate::Annotation::Specification::DataGetter* getter) {
clear_Type();
if (getter) {
set_has_getter();
Type_.getter_ = getter;
}
// @@protoc_insertion_point(field_set_allocated:TuriCreate.Annotation.Specification.ClientRequest.getter)
}
// .TuriCreate.Annotation.Specification.Annotations annotations = 2;
inline bool ClientRequest::has_annotations() const {
return Type_case() == kAnnotations;
}
inline void ClientRequest::set_has_annotations() {
_oneof_case_[0] = kAnnotations;
}
inline void ClientRequest::clear_annotations() {
if (has_annotations()) {
delete Type_.annotations_;
clear_has_Type();
}
}
inline const ::TuriCreate::Annotation::Specification::Annotations& ClientRequest::annotations() const {
// @@protoc_insertion_point(field_get:TuriCreate.Annotation.Specification.ClientRequest.annotations)
return has_annotations()
? *Type_.annotations_
: ::TuriCreate::Annotation::Specification::Annotations::default_instance();
}
inline ::TuriCreate::Annotation::Specification::Annotations* ClientRequest::mutable_annotations() {
if (!has_annotations()) {
clear_Type();
set_has_annotations();
Type_.annotations_ = new ::TuriCreate::Annotation::Specification::Annotations;
}
// @@protoc_insertion_point(field_mutable:TuriCreate.Annotation.Specification.ClientRequest.annotations)
return Type_.annotations_;
}
inline ::TuriCreate::Annotation::Specification::Annotations* ClientRequest::release_annotations() {
// @@protoc_insertion_point(field_release:TuriCreate.Annotation.Specification.ClientRequest.annotations)
if (has_annotations()) {
clear_has_Type();
::TuriCreate::Annotation::Specification::Annotations* temp = Type_.annotations_;
Type_.annotations_ = NULL;
return temp;
} else {
return NULL;
}
}
inline void ClientRequest::set_allocated_annotations(::TuriCreate::Annotation::Specification::Annotations* annotations) {
clear_Type();
if (annotations) {
set_has_annotations();
Type_.annotations_ = annotations;
}
// @@protoc_insertion_point(field_set_allocated:TuriCreate.Annotation.Specification.ClientRequest.annotations)
}
inline bool ClientRequest::has_Type() const {
return Type_case() != TYPE_NOT_SET;
}
inline void ClientRequest::clear_has_Type() {
_oneof_case_[0] = TYPE_NOT_SET;
}
inline ClientRequest::TypeCase ClientRequest::Type_case() const {
return ClientRequest::TypeCase(_oneof_case_[0]);
}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace Specification
} // namespace Annotation
} // namespace TuriCreate
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_message_2eproto__INCLUDED
| 8,946 |
3,459 | <filename>Real-Time Corruptor/BizHawk_RTC/libmupen64plus/mupen64plus-video-glide64mk2/src/Glide64/3dmath.h
/*
* Glide64 - Glide video plugin for Nintendo 64 emulators.
* Copyright (c) 2002 Dave2001
* Copyright (c) 2003-2009 Sergey 'Gonetz' Lipski
*
* 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 2 of the License, or
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
//****************************************************************
//
// Glide64 - Glide Plugin for Nintendo 64 emulators
// Project started on December 29th, 2001
//
// Authors:
// Dave2001, original author, founded the project in 2001, left it in 2002
// Gugaman, joined the project in 2002, left it in 2002
// Sergey 'Gonetz' Lipski, joined the project in 2002, main author since fall of 2002
// Hiroshi 'KoolSmoky' Morii, joined the project in 2007
//
//****************************************************************
//
// To modify Glide64:
// * Write your name and (optional)email, commented by your work, so I know who did it, and so that you can find which parts you modified when it comes time to send it to me.
// * Do NOT send me the whole project or file that you modified. Take out your modified code sections, and tell me where to put them. If people sent the whole thing, I would have many different versions, but no idea how to combine them all.
//
//****************************************************************
void calc_light (VERTEX *v);
void calc_linear (VERTEX *v);
void calc_sphere (VERTEX *v);
void math_init();
typedef void (*MULMATRIX)(float m1[4][4],float m2[4][4],float r[4][4]);
extern MULMATRIX MulMatrices;
typedef void (*TRANSFORMVECTOR)(float *src,float *dst,float mat[4][4]);
extern TRANSFORMVECTOR TransformVector;
extern TRANSFORMVECTOR InverseTransformVector;
typedef float (*DOTPRODUCT)(register float *v1, register float *v2);
extern DOTPRODUCT DotProduct;
typedef void (*NORMALIZEVECTOR)(float *v);
extern NORMALIZEVECTOR NormalizeVector;
| 714 |
2,177 | <filename>src/org/nutz/castor/castor/Map2Boolean.java<gh_stars>1000+
package org.nutz.castor.castor;
import java.util.Map;
import org.nutz.castor.Castor;
@SuppressWarnings("rawtypes")
public class Map2Boolean extends Castor<Map, Boolean> {
@Override
public Boolean cast(Map src, Class<?> toType, String... args) {
if (null == src)
return Boolean.FALSE;
return true;
}
} | 172 |
488 | /*!
* \file PrePostTraversal.cc
*
* \brief Implements a top-down/bottom-up traversal without explicit
* attributes, i.e., implements a variation on the simple traversal
* that exposes the top-down and bottom-up visits.
*/
// tps (01/14/2010) : Switching from rose.h to sage3.
#include "sage3basic.h"
#include "PrePostTraversal.hh"
_DummyAttribute
ASTtools::PrePostTraversal::evaluateInheritedAttribute (SgNode* node,
_DummyAttribute d)
{
visitTopDown (node);
return d;
}
_DummyAttribute
ASTtools::PrePostTraversal::evaluateSynthesizedAttribute (SgNode* node,
_DummyAttribute d,
SynthesizedAttributesList)
{
visitBottomUp (node);
return d;
}
void
ASTtools::PrePostTraversal::traverse (SgNode* node)
{
AstTopDownBottomUpProcessing<_DummyAttribute, _DummyAttribute>::traverse (node, _DummyAttribute ());
}
void
ASTtools::PrePostTraversal::traverseWithinFile (SgNode* node)
{
AstTopDownBottomUpProcessing<_DummyAttribute, _DummyAttribute>::traverseWithinFile (node, _DummyAttribute ());
}
// eof
| 521 |
1,433 | <filename>fabric-game-rule-api-v1/src/main/java/net/fabricmc/fabric/api/gamerule/v1/rule/DoubleRule.java
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.fabricmc.fabric.api.gamerule.v1.rule;
import com.mojang.brigadier.context.CommandContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.world.GameRules;
import net.fabricmc.fabric.api.gamerule.v1.GameRuleRegistry;
public final class DoubleRule extends GameRules.Rule<DoubleRule> implements ValidateableRule {
private static final Logger LOGGER = LogManager.getLogger(GameRuleRegistry.class);
private final double minimumValue;
private final double maximumValue;
private double value;
/**
* @deprecated You should not be calling this constructor!
*/
@Deprecated
public DoubleRule(GameRules.Type<DoubleRule> type, double value, double minimumValue, double maximumValue) {
super(type);
this.value = value;
this.minimumValue = minimumValue;
this.maximumValue = maximumValue;
if (Double.isInfinite(value) || Double.isNaN(value)) {
throw new IllegalArgumentException("Value cannot be infinite or NaN");
}
if (Double.isInfinite(minimumValue) || Double.isNaN(minimumValue)) {
throw new IllegalArgumentException("Minimum value cannot be infinite or NaN");
}
if (Double.isInfinite(maximumValue) || Double.isNaN(maximumValue)) {
throw new IllegalArgumentException("Maximum value cannot be infinite or NaN");
}
}
@Override
protected void setFromArgument(CommandContext<ServerCommandSource> context, String name) {
this.value = context.getArgument(name, Double.class);
}
@Override
protected void deserialize(String value) {
if (!value.isEmpty()) {
try {
final double d = Double.parseDouble(value);
if (this.inBounds(d)) {
this.value = d;
} else {
LOGGER.warn("Failed to parse double {}. Was out of bounds {} - {}", value, this.minimumValue, this.maximumValue);
}
} catch (NumberFormatException e) {
LOGGER.warn("Failed to parse double {}", value);
}
}
}
@Override
public String serialize() {
return Double.toString(this.value);
}
@Override
public int getCommandResult() {
return Double.compare(this.value, 0.0D);
}
@Override
protected DoubleRule getThis() {
return this;
}
@Override
protected DoubleRule copy() {
return new DoubleRule(this.type, this.value, this.minimumValue, this.maximumValue);
}
@Override
public void setValue(DoubleRule rule, MinecraftServer minecraftServer) {
if (!this.inBounds(rule.value)) {
throw new IllegalArgumentException(String.format("Could not set value to %s. Was out of bounds %s - %s", rule.value, this.minimumValue, this.maximumValue));
}
this.value = rule.value;
this.changed(minecraftServer);
}
@Override
public boolean validate(String value) {
try {
final double d = Double.parseDouble(value);
return this.inBounds(d);
} catch (NumberFormatException ignored) {
return false;
}
}
public double get() {
return this.value;
}
private boolean inBounds(double value) {
return value >= this.minimumValue && value <= this.maximumValue;
}
}
| 1,231 |
665 | #
# MLDB-2111-group-by-expression.py
# <NAME>, 2017-01-24
# This file is part of MLDB. Copyright 2017 mldb.ai inc. All rights reserved.
#
from mldb import mldb, MldbUnitTest, ResponseException
class Mldb2111GroupByTests(MldbUnitTest): # noqa
@classmethod
def setUpClass(cls):
ds = mldb.create_dataset({'id' : 'ds', 'type' : 'sparse.mutable'})
ds.record_row('0', [['x', 1, 1], ['y', 1, 2]])
ds.record_row('1', [['x', 1, 3], ['y', 2, 4]])
ds.record_row('2', [['x', 2, 5], ['y', 1, 6]])
ds.record_row('3', [['x', 2, 7], ['y', 2, 8]])
ds.commit()
ds2 = mldb.create_dataset({'id' : 'ds2', 'type' : 'sparse.mutable'})
ds2.record_row('0', [['x', 1, 1], ['x', 2, 2]])
ds2.commit()
def test_groupby_expression(self):
res = mldb.query("""
SELECT x+1 FROM (SELECT x:1) GROUP BY x+1
""")
self.assertTableResultEquals(res,
[[ "_rowName", "x+1"],
[ "[2]", 2 ]])
def test_groupby_expression_named(self):
res = mldb.query("""
SELECT x+1 as z FROM (SELECT x:1) GROUP BY x+1
""")
self.assertTableResultEquals(res,
[[ "_rowName", "z"],
[ "[2]", 2 ]])
def test_groupby_sub_expression(self):
res = mldb.query("""
SELECT (x+1)*3 as z FROM (SELECT x:1) GROUP BY x+1
""")
self.assertTableResultEquals(res,
[[ "_rowName", "z"],
[ "[2]", 6 ]])
def test_groupby_expression_multiple_key(self):
res = mldb.query("""
SELECT x+1 FROM ds GROUP BY x+1, y*2
""")
self.assertTableResultEquals(res,
[[ "_rowName", "x+1"],
[ "[2,2]", 2 ],
[ "[2,4]", 2 ],
[ "[3,2]", 3 ],
[ "[3,4]", 3 ]])
## Rowname & rowHash in the select is different than in the group by
def test_groupby_rowname(self):
res = mldb.query("""
SELECT rowName() FROM ds GROUP BY rowName()
""")
self.assertTableResultEquals(res,
[["_rowName", "rowName()"],
["\"[\"\"0\"\"]\"", "\"[\"\"0\"\"]\""],
["\"[\"\"1\"\"]\"", "\"[\"\"1\"\"]\""],
["\"[\"\"2\"\"]\"", "\"[\"\"2\"\"]\""],
["\"[\"\"3\"\"]\"", "\"[\"\"3\"\"]\""]])
res = mldb.query("""
SELECT rowHash() FROM ds GROUP BY rowHash()
""")
self.assertTableResultEquals(res,
[["_rowName","rowHash()"],
["[10408321403207385874]",11729733417614312054],
["[11275350073939794026]",9399015998024610411],
["[11413460447292444913]",4531258406341702386],
["[17472595041006102391]",12806200029519745032]])
def test_groupby_argument(self):
res = mldb.query("""
SELECT sqrt(x * 3) as z FROM ds GROUP BY x * 3
""")
self.assertTableResultEquals(res,
[["_rowName", "z"],
["[3]",1.7320508075688772],
["[6]",2.449489742783178]])
def test_groupby_expression_function(self):
res = mldb.query("""
SELECT horizontal_sum({x,y}) + 1 as z FROM ds GROUP BY horizontal_sum({x,y})
""")
self.assertTableResultEquals(res,
[["_rowName", "z"],
["[2]",3],
["[3]",4],
["[4]",5]])
def test_groupby_named(self):
res = mldb.query("""
SELECT x+1 NAMED (x+1)*2 FROM (SELECT x:1) GROUP BY x+1
""")
self.assertTableResultEquals(res,
[[ "_rowName", "x+1"],
[ "4", 2 ]])
def test_groupby_orderby(self):
res = mldb.query("""
SELECT x+1 FROM ds GROUP BY x+1 ORDER BY x+1
""")
self.assertTableResultEquals(res,
[["_rowName", "x+1"],
["[2]", 2],
["[3]", 3]])
def test_groupby_having(self):
res = mldb.query("""
SELECT 0 as z FROM ds GROUP BY x+1 HAVING x+1 = 3
""")
self.assertTableResultEquals(res,
[["_rowName","z"],
["[3]", 0]])
def test_groupby_temporal(self):
res = mldb.query("""
select temporal_latest({x}) as * from ds2 GROUP BY x
""")
self.assertTableResultEquals(res,
[["_rowName","x"],
["[2]", 2]])
res = mldb.query("""
select temporal_latest({x}) from ds2 group by temporal_latest({x})
""")
self.assertTableResultEquals(res,
[["_rowName","temporal_latest({x}).x"],
["\"[[[\"\"x\"\",[2,\"\"1970-01-01T00:00:02Z\"\"]]]]\"", 2]])
def test_groupby_inexact(self):
msg = "variable 'x' must appear in the GROUP BY clause or be used in an aggregate function"
with self.assertRaisesRegex(ResponseException, msg):
res = mldb.query("""
SELECT x+1 FROM (SELECT x:1) GROUP BY 1+x
""")
msg = "variable 'x' must appear in the GROUP BY clause or be used in an aggregate function"
with self.assertRaisesRegex(ResponseException, msg):
res = mldb.query("""
SELECT x+1*3 FROM (SELECT x:1) GROUP BY x+1
""")
if __name__ == '__main__':
mldb.run_tests() | 2,836 |
938 | <gh_stars>100-1000
{
"replace": false,
"values": [
"tconstruct:molten_signalum",
"tconstruct:flowing_molten_signalum"
]
} | 61 |
411 | <reponame>sumau/tick
// License: BSD 3 clause
//
// poisson.cpp
// Array
//
// Created by bacry on 13/04/2015.
// Copyright (c) 2015 bacry. All rights reserved.
//
#include "tick/hawkes/simulation/simu_poisson_process.h"
Poisson::Poisson(double intensity, int seed) : PP(1, seed) {
intensities = SArrayDouble::new_ptr(1);
(*intensities)[0] = intensity;
}
Poisson::Poisson(SArrayDoublePtr intensities, int seed)
: PP(static_cast<unsigned int>(intensities->size()), seed) {
this->intensities = intensities;
}
void Poisson::init_intensity_(ArrayDouble &intensity,
double *total_intensity_bound1) {
*total_intensity_bound1 = 0;
for (unsigned int i = 0; i < get_n_nodes(); i++) {
intensity[i] = (*intensities)[i];
*total_intensity_bound1 += (*intensities)[i];
}
}
bool Poisson::update_time_shift_(double delay, ArrayDouble &intensity,
double *total_intensity_bound) {
return false;
}
| 394 |
1,444 | <filename>Mage.Sets/src/mage/cards/d/DrippingTongueZubera.java<gh_stars>1000+
package mage.cards.d;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.DiesSourceTriggeredAbility;
import mage.abilities.dynamicvalue.common.ZuberasDiedDynamicValue;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.game.permanent.token.SpiritToken;
import mage.watchers.common.ZuberasDiedWatcher;
/**
*
* @author Loki
*/
public final class DrippingTongueZubera extends CardImpl {
public DrippingTongueZubera (UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{G}");
this.subtype.add(SubType.ZUBERA);
this.subtype.add(SubType.SPIRIT);
this.power = new MageInt(1);
this.toughness = new MageInt(2);
this.addAbility(new DiesSourceTriggeredAbility(new CreateTokenEffect(new SpiritToken(), ZuberasDiedDynamicValue.instance), false), new ZuberasDiedWatcher());
}
public DrippingTongueZubera (final DrippingTongueZubera card) {
super(card);
}
@Override
public DrippingTongueZubera copy() {
return new DrippingTongueZubera(this);
}
}
| 502 |
314 | <reponame>tclfs/rocketmq-client-cpp
/*
* 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.
*/
#include "DefaultMQProducer.h"
#include <MQVersion.h>
#include "DefaultMQProducerImpl.h"
namespace rocketmq {
DefaultMQProducer::DefaultMQProducer(const std::string& groupName) {
impl = new DefaultMQProducerImpl(groupName);
}
DefaultMQProducer::~DefaultMQProducer() {
delete impl;
}
void DefaultMQProducer::start() {
impl->start();
}
void DefaultMQProducer::shutdown() {
impl->shutdown();
}
std::string DefaultMQProducer::version() {
std::string versions = impl->getClientVersionString();
/*
versions.append(", PROTOCOL VERSION: ")
.append(MQVersion::GetVersionDesc(MQVersion::s_CurrentVersion))
.append(", LANGUAGE: ")
.append(MQVersion::s_CurrentLanguage);
*/
return versions;
}
// start mqclient set
const std::string& DefaultMQProducer::getNamesrvAddr() const {
return impl->getNamesrvAddr();
}
void DefaultMQProducer::setNamesrvAddr(const std::string& namesrvAddr) {
impl->setNamesrvAddr(namesrvAddr);
}
const std::string& DefaultMQProducer::getNamesrvDomain() const {
return impl->getNamesrvDomain();
}
void DefaultMQProducer::setNamesrvDomain(const std::string& namesrvDomain) {
impl->setNamesrvDomain(namesrvDomain);
}
void DefaultMQProducer::setSessionCredentials(const std::string& accessKey,
const std::string& secretKey,
const std::string& accessChannel) {
impl->setSessionCredentials(accessKey, secretKey, accessChannel);
}
const SessionCredentials& DefaultMQProducer::getSessionCredentials() const {
return impl->getSessionCredentials();
}
const std::string& DefaultMQProducer::getInstanceName() const {
return impl->getInstanceName();
}
void DefaultMQProducer::setInstanceName(const std::string& instanceName) {
impl->setInstanceName(instanceName);
}
const std::string& DefaultMQProducer::getNameSpace() const {
return impl->getNameSpace();
}
void DefaultMQProducer::setNameSpace(const std::string& nameSpace) {
impl->setNameSpace(nameSpace);
}
const std::string& DefaultMQProducer::getGroupName() const {
return impl->getGroupName();
}
void DefaultMQProducer::setGroupName(const std::string& groupName) {
impl->setGroupName(groupName);
}
void DefaultMQProducer::setSendMsgTimeout(int sendMsgTimeout) {
impl->setSendMsgTimeout(sendMsgTimeout);
}
int DefaultMQProducer::getSendMsgTimeout() const {
return impl->getSendMsgTimeout();
}
void DefaultMQProducer::setRetryTimes(int times) {
impl->setRetryTimes(times);
}
int DefaultMQProducer::getRetryTimes() const {
return impl->getRetryTimes();
}
int DefaultMQProducer::getCompressMsgBodyOverHowmuch() const {
return impl->getCompressMsgBodyOverHowmuch();
}
void DefaultMQProducer::setCompressMsgBodyOverHowmuch(int compressMsgBodyThreshold) {
impl->setCompressMsgBodyOverHowmuch(compressMsgBodyThreshold);
}
int DefaultMQProducer::getCompressLevel() const {
return impl->getCompressLevel();
}
void DefaultMQProducer::setCompressLevel(int compressLevel) {
impl->setCompressLevel(compressLevel);
}
void DefaultMQProducer::setMaxMessageSize(int maxMessageSize) {
impl->setMaxMessageSize(maxMessageSize);
}
int DefaultMQProducer::getMaxMessageSize() const {
return impl->getMaxMessageSize();
}
void DefaultMQProducer::setRetryTimes4Async(int times) {
impl->setRetryTimes4Async(times);
}
int DefaultMQProducer::getRetryTimes4Async() const {
return impl->getRetryTimes4Async();
}
void DefaultMQProducer::setLogLevel(elogLevel inputLevel) {
impl->setLogLevel(inputLevel);
}
elogLevel DefaultMQProducer::getLogLevel() {
return impl->getLogLevel();
}
void DefaultMQProducer::setLogFileSizeAndNum(int fileNum, long perFileSize) {
impl->setLogFileSizeAndNum(fileNum, perFileSize);
}
void DefaultMQProducer::setTcpTransportPullThreadNum(int num) {
impl->setTcpTransportPullThreadNum(num);
}
int DefaultMQProducer::getTcpTransportPullThreadNum() const {
return impl->getTcpTransportPullThreadNum();
}
void DefaultMQProducer::setTcpTransportConnectTimeout(uint64_t timeout) {
impl->setTcpTransportConnectTimeout(timeout);
}
uint64_t DefaultMQProducer::getTcpTransportConnectTimeout() const {
return impl->getTcpTransportConnectTimeout();
}
void DefaultMQProducer::setTcpTransportTryLockTimeout(uint64_t timeout) {
impl->setTcpTransportTryLockTimeout(timeout);
}
uint64_t DefaultMQProducer::getTcpTransportTryLockTimeout() const {
return impl->getTcpTransportTryLockTimeout();
}
void DefaultMQProducer::setUnitName(std::string unitName) {
impl->setUnitName(unitName);
}
const std::string& DefaultMQProducer::getUnitName() const {
return impl->getUnitName();
}
void DefaultMQProducer::setMessageTrace(bool messageTrace) {
impl->setMessageTrace(messageTrace);
}
bool DefaultMQProducer::getMessageTrace() const {
return impl->getMessageTrace();
}
SendResult DefaultMQProducer::send(MQMessage& msg, bool bSelectActiveBroker) {
return impl->send(msg, bSelectActiveBroker);
}
SendResult DefaultMQProducer::send(MQMessage& msg, const MQMessageQueue& mq) {
return impl->send(msg, mq);
}
SendResult DefaultMQProducer::send(MQMessage& msg, MessageQueueSelector* selector, void* arg) {
return impl->send(msg, selector, arg);
}
SendResult DefaultMQProducer::send(MQMessage& msg,
MessageQueueSelector* selector,
void* arg,
int autoRetryTimes,
bool bActiveBroker) {
return impl->send(msg, selector, arg, autoRetryTimes, bActiveBroker);
}
SendResult DefaultMQProducer::send(std::vector<MQMessage>& msgs) {
return impl->send(msgs);
}
SendResult DefaultMQProducer::send(std::vector<MQMessage>& msgs, const MQMessageQueue& mq) {
return impl->send(msgs, mq);
}
void DefaultMQProducer::send(MQMessage& msg, SendCallback* pSendCallback, bool bSelectActiveBroker) {
impl->send(msg, pSendCallback, bSelectActiveBroker);
}
void DefaultMQProducer::send(MQMessage& msg, const MQMessageQueue& mq, SendCallback* pSendCallback) {
impl->send(msg, mq, pSendCallback);
}
void DefaultMQProducer::send(MQMessage& msg, MessageQueueSelector* selector, void* arg, SendCallback* pSendCallback) {
impl->send(msg, selector, arg, pSendCallback);
}
void DefaultMQProducer::sendOneway(MQMessage& msg, bool bSelectActiveBroker) {
impl->sendOneway(msg, bSelectActiveBroker);
}
void DefaultMQProducer::sendOneway(MQMessage& msg, const MQMessageQueue& mq) {
impl->sendOneway(msg, mq);
}
void DefaultMQProducer::sendOneway(MQMessage& msg, MessageQueueSelector* selector, void* arg) {
impl->sendOneway(msg, selector, arg);
}
void DefaultMQProducer::setEnableSsl(bool enableSsl) {
impl->setEnableSsl(enableSsl);
}
bool DefaultMQProducer::getEnableSsl() const {
return impl->getEnableSsl();
}
void DefaultMQProducer::setSslPropertyFile(const std::string& sslPropertyFile) {
impl->setSslPropertyFile(sslPropertyFile);
}
const std::string& DefaultMQProducer::getSslPropertyFile() const {
return impl->getSslPropertyFile();
}
} // namespace rocketmq | 2,659 |
369 | /*
* Copyright © 2020 <NAME>, 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.cdap.cdap.datapipeline.draft;
import com.google.gson.Gson;
import io.cdap.cdap.api.NamespaceSummary;
import io.cdap.cdap.api.artifact.ArtifactSummary;
import io.cdap.cdap.api.common.Bytes;
import io.cdap.cdap.api.dataset.lib.CloseableIterator;
import io.cdap.cdap.datapipeline.service.StudioUtil;
import io.cdap.cdap.etl.proto.v2.DataStreamsConfig;
import io.cdap.cdap.etl.proto.v2.ETLBatchConfig;
import io.cdap.cdap.etl.proto.v2.ETLConfig;
import io.cdap.cdap.spi.data.InvalidFieldException;
import io.cdap.cdap.spi.data.StructuredRow;
import io.cdap.cdap.spi.data.StructuredTable;
import io.cdap.cdap.spi.data.TableNotFoundException;
import io.cdap.cdap.spi.data.table.StructuredTableId;
import io.cdap.cdap.spi.data.table.StructuredTableSpecification;
import io.cdap.cdap.spi.data.table.field.Field;
import io.cdap.cdap.spi.data.table.field.FieldType;
import io.cdap.cdap.spi.data.table.field.Fields;
import io.cdap.cdap.spi.data.table.field.Range;
import io.cdap.cdap.spi.data.transaction.TransactionRunner;
import io.cdap.cdap.spi.data.transaction.TransactionRunners;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
/**
* Schema for draft store.
*/
public class DraftStore {
public static final StructuredTableId TABLE_ID = new StructuredTableId("drafts");
private static final String NAMESPACE_COL = "namespace";
private static final String GENERATION_COL = "generation";
private static final String OWNER_COL = "owner";
private static final String ID_COL = "id";
private static final String ARTIFACT_COL = "artifact";
private static final String NAME_COL = "name";
private static final String DESCRIPTION_COL = "description";
private static final String CREATED_COL = "createdtimemillis";
private static final String UPDATED_COL = "updatedtimemillis";
private static final String PIPELINE_COL = "pipeline";
private static final String REVISION_COL = "revision";
public static final StructuredTableSpecification TABLE_SPEC = new StructuredTableSpecification.Builder()
.withId(TABLE_ID)
.withFields(Fields.stringType(NAMESPACE_COL),
Fields.longType(GENERATION_COL),
Fields.stringType(OWNER_COL),
Fields.stringType(ID_COL),
Fields.stringType(ARTIFACT_COL),
Fields.stringType(NAME_COL),
Fields.stringType(DESCRIPTION_COL),
Fields.longType(CREATED_COL),
Fields.longType(UPDATED_COL),
Fields.stringType(PIPELINE_COL),
Fields.intType(REVISION_COL))
.withPrimaryKeys(NAMESPACE_COL, GENERATION_COL, OWNER_COL, ID_COL)
.build();
private static final Gson GSON = new Gson();
private final TransactionRunner transactionRunner;
public DraftStore(TransactionRunner transactionRunner) {
this.transactionRunner = transactionRunner;
}
/**
* @param namespace the namespace to fetch the drafts from
* @param owner the id of the owner of the drafts
* @param sortRequest The sorting that should be applied to the results, pass null if no sorting is required.
* @return a list of drafts
* @throws TableNotFoundException if the draft store table is not found
* @throws InvalidFieldException if the fields Namespace and owner fields do not match the fields in the
* StructuredTable
*/
public List<Draft> listDrafts(NamespaceSummary namespace, String owner,
SortRequest sortRequest,
boolean includeConfig) throws TableNotFoundException, InvalidFieldException {
List<Field<?>> prefix = new ArrayList<>(3);
prefix.add(Fields.stringField(NAMESPACE_COL, namespace.getName()));
prefix.add(Fields.longField(GENERATION_COL, namespace.getGeneration()));
prefix.add(Fields.stringField(OWNER_COL, owner));
List<StructuredRow> rows;
rows = TransactionRunners.run(transactionRunner, context -> {
StructuredTable table = context.getTable(TABLE_ID);
Range range = Range.singleton(prefix);
List<StructuredRow> temp = new ArrayList<>();
try (CloseableIterator<StructuredRow> rowIter = table.scan(range, Integer.MAX_VALUE)) {
rowIter.forEachRemaining(temp::add);
}
return temp;
}, TableNotFoundException.class, InvalidFieldException.class);
List<StructuredRow> sortedResults = doSort(rows, sortRequest);
return sortedResults.stream().map(row -> fromRow(row, includeConfig)).collect(Collectors.toList());
}
/**
* Helper method to apply the sorting onto a list of rows. Sorting needs to take place at the store-level so it can
* leverage the StructuredRow to enable sorting on any field.
*
* @param rows list of {@link StructuredRow} to be sorted
* @param sortRequest {@link SortRequest} describing the sort to be performed
* @return a sorted list of {@link StructuredRow}
*/
private List<StructuredRow> doSort(List<StructuredRow> rows, @Nullable SortRequest sortRequest) {
if (sortRequest == null) {
return rows;
}
String sortField = sortRequest.getFieldName();
FieldType field = TABLE_SPEC.getFieldTypes().stream()
.filter(f -> f.getName().equals(sortField))
.findFirst()
.orElse(null);
if (field == null) {
throw new IllegalArgumentException(
String
.format("Invalid value '%s' for sortBy. This field does not exist in the Drafts table.",
sortField));
}
FieldType.Type fieldType = field.getType();
Comparator<StructuredRow> comparator;
switch (fieldType) {
case STRING:
comparator = Comparator.<StructuredRow, String>comparing(o -> o.getString(sortField));
break;
case INTEGER:
comparator = Comparator.<StructuredRow, Integer>comparing(o -> o.getInteger(sortField));
break;
case LONG:
comparator = Comparator.<StructuredRow, Long>comparing(o -> o.getLong(sortField));
break;
case FLOAT:
comparator = Comparator.<StructuredRow, Float>comparing(o -> o.getFloat(sortField));
break;
case DOUBLE:
comparator = Comparator.<StructuredRow, Double>comparing(o -> o.getDouble(sortField));
break;
case BYTES:
comparator = Comparator.comparing(o -> o.getBytes(sortField), Bytes.BYTES_COMPARATOR);
break;
default:
throw new UnsupportedOperationException(
String.format("Cannot sort field '%s' because type '%s' is not supported.",
sortField, fieldType.toString()));
}
if (sortRequest.getOrder() != SortRequest.SortOrder.ASC) {
comparator = comparator.reversed();
}
rows.sort(comparator);
return rows;
}
/**
* Fetch a given draft if it exists
*
* @param id {@link DraftId} that is used to uniquely identify a draft
* @return an {@link Optional<Draft>} representing the requested draft
* @throws TableNotFoundException if the draft store table is not found
* @throws InvalidFieldException if the fields in the {@link DraftId} object do not match the fields in the
* StructuredTable
*/
public Optional<Draft> getDraft(DraftId id) throws TableNotFoundException, InvalidFieldException {
return TransactionRunners.run(transactionRunner, context -> {
StructuredTable table = context.getTable(TABLE_ID);
Optional<StructuredRow> row = table.read(getKey(id));
return row.map(this::fromRow);
}, TableNotFoundException.class, InvalidFieldException.class);
}
/**
* Delete the given draft. This is a no-op if the draft does not exist
*
* @param id {@link DraftId} that is used to uniquely identify a draft
* @throws TableNotFoundException if the draft store table is not found
* @throws InvalidFieldException if the fields in the {@link Draft} object do not match the fields in the
* StructuredTable
*/
public void deleteDraft(DraftId id) throws TableNotFoundException, InvalidFieldException {
TransactionRunners.run(transactionRunner, context -> {
StructuredTable table = context.getTable(TABLE_ID);
table.delete(getKey(id));
}, TableNotFoundException.class, InvalidFieldException.class);
}
/**
* Create/update the given draft
*
* @param id {@link DraftId} that is used to uniquely identify a draft
* @param request {@link DraftStoreRequest} that contains the rest of the draft data
* @throws TableNotFoundException if the draft store table is not found
* @throws InvalidFieldException if the fields in the {@link Draft} or {@link DraftStoreRequest} objects do not
* match the fields in the StructuredTable
*/
public <T extends ETLConfig> void writeDraft(DraftId id, DraftStoreRequest<T> request)
throws TableNotFoundException, InvalidFieldException {
Optional<Draft> existing = getDraft(id);
long now = System.currentTimeMillis();
long createTime = existing.map(Draft::getCreatedTimeMillis).orElse(now);
Draft draft = new Draft(request.getConfig(), request.getName(), request.getDescription(), request.getArtifact(),
id.getId(), createTime, now);
TransactionRunners.run(transactionRunner, context -> {
StructuredTable table = context.getTable(TABLE_ID);
table.upsert(getRow(id, draft));
}, TableNotFoundException.class, InvalidFieldException.class);
}
/**
* Returns the count of drafts in the table
*
* @return long value presenting the number of drafts in the table
* @throws TableNotFoundException if the draft store table is not found
*/
public long getDraftCount() throws TableNotFoundException {
return TransactionRunners.run(transactionRunner, context -> {
StructuredTable table = context.getTable(TABLE_ID);
return table.count(Collections.singleton(Range.all()));
}, TableNotFoundException.class);
}
private void addKeyFields(DraftId id, List<Field<?>> fields) {
fields.add(Fields.stringField(NAMESPACE_COL, id.getNamespace().getName()));
fields.add(Fields.longField(GENERATION_COL, id.getNamespace().getGeneration()));
fields.add(Fields.stringField(OWNER_COL, id.getOwner()));
fields.add(Fields.stringField(ID_COL, id.getId()));
}
private List<Field<?>> getKey(DraftId id) {
List<Field<?>> keyFields = new ArrayList<>(4);
addKeyFields(id, keyFields);
return keyFields;
}
private List<Field<?>> getRow(DraftId id, Draft draft) {
List<Field<?>> fields = new ArrayList<>(11);
addKeyFields(id, fields);
fields.add(Fields.stringField(ARTIFACT_COL, GSON.toJson(draft.getArtifact())));
fields.add(Fields.stringField(NAME_COL, draft.getName()));
fields.add(Fields.stringField(DESCRIPTION_COL, draft.getDescription()));
fields.add(Fields.longField(CREATED_COL, draft.getCreatedTimeMillis()));
fields.add(Fields.longField(UPDATED_COL, draft.getUpdatedTimeMillis()));
fields.add(Fields.stringField(PIPELINE_COL, GSON.toJson(draft.getConfig())));
fields.add(Fields.intField(REVISION_COL, draft.getRevision()));
return fields;
}
private Draft fromRow(StructuredRow row) {
return fromRow(row, true);
}
@SuppressWarnings("ConstantConditions")
private Draft fromRow(StructuredRow row, boolean includeConfig) {
String id = row.getString(ID_COL);
String name = row.getString(NAME_COL);
String description = row.getString(DESCRIPTION_COL);
long createTime = row.getLong(CREATED_COL);
long updateTime = row.getLong(UPDATED_COL);
String artifactStr = row.getString(ARTIFACT_COL);
ArtifactSummary artifact = GSON.fromJson(artifactStr, ArtifactSummary.class);
String configStr = row.getString(PIPELINE_COL);
ETLConfig config = null;
if (includeConfig) {
if (StudioUtil.isBatchPipeline(artifact)) {
config = GSON.fromJson(configStr, ETLBatchConfig.class);
} else if (StudioUtil.isStreamingPipeline(artifact)) {
config = GSON.fromJson(configStr, DataStreamsConfig.class);
} else {
throw new
IllegalArgumentException(
String.format("Failed to parse pipeline config string: %s is not a supported pipeline type",
artifact.getName()));
}
}
return new Draft(config, name, description, artifact, id, createTime, updateTime);
}
}
| 4,580 |
997 | <gh_stars>100-1000
#ifndef PQCLEAN_FALCON512_CLEAN_FPR_H
#define PQCLEAN_FALCON512_CLEAN_FPR_H
/*
* Floating-point operations.
*
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2017-2019 Falcon Project
*
* 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.
*
* ===========================(LICENSE END)=============================
*
* @author <NAME> <<EMAIL>>
*/
/* ====================================================================== */
/*
* Custom floating-point implementation with integer arithmetics. We
* use IEEE-754 "binary64" format, with some simplifications:
*
* - Top bit is s = 1 for negative, 0 for positive.
*
* - Exponent e uses the next 11 bits (bits 52 to 62, inclusive).
*
* - Mantissa m uses the 52 low bits.
*
* Encoded value is, in general: (-1)^s * 2^(e-1023) * (1 + m*2^(-52))
* i.e. the mantissa really is a 53-bit number (less than 2.0, but not
* less than 1.0), but the top bit (equal to 1 by definition) is omitted
* in the encoding.
*
* In IEEE-754, there are some special values:
*
* - If e = 2047, then the value is either an infinite (m = 0) or
* a NaN (m != 0).
*
* - If e = 0, then the value is either a zero (m = 0) or a subnormal,
* aka "denormalized number" (m != 0).
*
* Of these, we only need the zeros. The caller is responsible for not
* providing operands that would lead to infinites, NaNs or subnormals.
* If inputs are such that values go out of range, then indeterminate
* values are returned (it would still be deterministic, but no specific
* value may be relied upon).
*
* At the C level, the three parts are stored in a 64-bit unsigned
* word.
*
* One may note that a property of the IEEE-754 format is that order
* is preserved for positive values: if two positive floating-point
* values x and y are such that x < y, then their respective encodings
* as _signed_ 64-bit integers i64(x) and i64(y) will be such that
* i64(x) < i64(y). For negative values, order is reversed: if x < 0,
* y < 0, and x < y, then ia64(x) > ia64(y).
*
* IMPORTANT ASSUMPTIONS:
* ======================
*
* For proper computations, and constant-time behaviour, we assume the
* following:
*
* - 32x32->64 multiplication (unsigned) has an execution time that
* is independent of its operands. This is true of most modern
* x86 and ARM cores. Notable exceptions are the ARM Cortex M0, M0+
* and M3 (in the M0 and M0+, this is done in software, so it depends
* on that routine), and the PowerPC cores from the G3/G4 lines.
* For more info, see: https://www.bearssl.org/ctmul.html
*
* - Left-shifts and right-shifts of 32-bit values have an execution
* time which does not depend on the shifted value nor on the
* shift count. An historical exception is the Pentium IV, but most
* modern CPU have barrel shifters. Some small microcontrollers
* might have varying-time shifts (not the ARM Cortex M*, though).
*
* - Right-shift of a signed negative value performs a sign extension.
* As per the C standard, this operation returns an
* implementation-defined result (this is NOT an "undefined
* behaviour"). On most/all systems, an arithmetic shift is
* performed, because this is what makes most sense.
*/
/*
* Normally we should declare the 'fpr' type to be a struct or union
* around the internal 64-bit value; however, we want to use the
* direct 64-bit integer type to enable a lighter call convention on
* ARM platforms. This means that direct (invalid) use of operators
* such as '*' or '+' will not be caught by the compiler. We rely on
* the "normal" (non-emulated) code to detect such instances.
*/
typedef uint64_t fpr;
/*
* For computations, we split values into an integral mantissa in the
* 2^54..2^55 range, and an (adjusted) exponent. The lowest bit is
* "sticky" (it is set to 1 if any of the bits below it is 1); when
* re-encoding, the low two bits are dropped, but may induce an
* increment in the value for proper rounding.
*/
/*
* Right-shift a 64-bit unsigned value by a possibly secret shift count.
* We assumed that the underlying architecture had a barrel shifter for
* 32-bit shifts, but for 64-bit shifts on a 32-bit system, this will
* typically invoke a software routine that is not necessarily
* constant-time; hence the function below.
*
* Shift count n MUST be in the 0..63 range.
*/
#define fpr_ursh PQCLEAN_FALCON512_CLEAN_fpr_ursh
uint64_t fpr_ursh(uint64_t x, int n);
/*
* Right-shift a 64-bit signed value by a possibly secret shift count
* (see fpr_ursh() for the rationale).
*
* Shift count n MUST be in the 0..63 range.
*/
#define fpr_irsh PQCLEAN_FALCON512_CLEAN_fpr_irsh
int64_t fpr_irsh(int64_t x, int n);
/*
* Left-shift a 64-bit unsigned value by a possibly secret shift count
* (see fpr_ursh() for the rationale).
*
* Shift count n MUST be in the 0..63 range.
*/
#define fpr_ulsh PQCLEAN_FALCON512_CLEAN_fpr_ulsh
uint64_t fpr_ulsh(uint64_t x, int n);
/*
* Expectations:
* s = 0 or 1
* exponent e is "arbitrary" and unbiased
* 2^54 <= m < 2^55
* Numerical value is (-1)^2 * m * 2^e
*
* Exponents which are too low lead to value zero. If the exponent is
* too large, the returned value is indeterminate.
*
* If m = 0, then a zero is returned (using the provided sign).
* If e < -1076, then a zero is returned (regardless of the value of m).
* If e >= -1076 and e != 0, m must be within the expected range
* (2^54 to 2^55-1).
*/
#define FPR PQCLEAN_FALCON512_CLEAN_FPR
fpr FPR(int s, int e, uint64_t m);
#define fpr_scaled PQCLEAN_FALCON512_CLEAN_fpr_scaled
fpr fpr_scaled(int64_t i, int sc);
#define fpr_of PQCLEAN_FALCON512_CLEAN_fpr_of
fpr fpr_of(int64_t i);
static const fpr fpr_q = 4667981563525332992;
static const fpr fpr_inverse_of_q = 4545632735260551042;
static const fpr fpr_inv_2sqrsigma0 = 4594603506513722306;
static const fpr fpr_inv_sigma = 4573359825155195350;
static const fpr fpr_sigma_min_9 = 4608495221497168882;
static const fpr fpr_sigma_min_10 = 4608586345619182117;
static const fpr fpr_log2 = 4604418534313441775;
static const fpr fpr_inv_log2 = 4609176140021203710;
static const fpr fpr_bnorm_max = 4670353323383631276;
static const fpr fpr_zero = 0;
static const fpr fpr_one = 4607182418800017408;
static const fpr fpr_two = 4611686018427387904;
static const fpr fpr_onehalf = 4602678819172646912;
static const fpr fpr_invsqrt2 = 4604544271217802189;
static const fpr fpr_invsqrt8 = 4600040671590431693;
static const fpr fpr_ptwo31 = 4746794007248502784;
static const fpr fpr_ptwo31m1 = 4746794007244308480;
static const fpr fpr_mtwo31m1 = 13970166044099084288U;
static const fpr fpr_ptwo63m1 = 4890909195324358656;
static const fpr fpr_mtwo63m1 = 14114281232179134464U;
static const fpr fpr_ptwo63 = 4890909195324358656;
#define fpr_rint PQCLEAN_FALCON512_CLEAN_fpr_rint
int64_t fpr_rint(fpr x);
#define fpr_floor PQCLEAN_FALCON512_CLEAN_fpr_floor
int64_t fpr_floor(fpr x);
#define fpr_trunc PQCLEAN_FALCON512_CLEAN_fpr_trunc
int64_t fpr_trunc(fpr x);
#define fpr_add PQCLEAN_FALCON512_CLEAN_fpr_add
fpr fpr_add(fpr x, fpr y);
#define fpr_sub PQCLEAN_FALCON512_CLEAN_fpr_sub
fpr fpr_sub(fpr x, fpr y);
#define fpr_neg PQCLEAN_FALCON512_CLEAN_fpr_neg
fpr fpr_neg(fpr x);
#define fpr_half PQCLEAN_FALCON512_CLEAN_fpr_half
fpr fpr_half(fpr x);
#define fpr_double PQCLEAN_FALCON512_CLEAN_fpr_double
fpr fpr_double(fpr x);
#define fpr_mul PQCLEAN_FALCON512_CLEAN_fpr_mul
fpr fpr_mul(fpr x, fpr y);
#define fpr_sqr PQCLEAN_FALCON512_CLEAN_fpr_sqr
fpr fpr_sqr(fpr x);
#define fpr_div PQCLEAN_FALCON512_CLEAN_fpr_div
fpr fpr_div(fpr x, fpr y);
#define fpr_inv PQCLEAN_FALCON512_CLEAN_fpr_inv
fpr fpr_inv(fpr x);
#define fpr_sqrt PQCLEAN_FALCON512_CLEAN_fpr_sqrt
fpr fpr_sqrt(fpr x);
#define fpr_lt PQCLEAN_FALCON512_CLEAN_fpr_lt
int fpr_lt(fpr x, fpr y);
/*
* Compute exp(x) for x such that |x| <= ln 2. We want a precision of 50
* bits or so.
*/
#define fpr_expm_p63 PQCLEAN_FALCON512_CLEAN_fpr_expm_p63
uint64_t fpr_expm_p63(fpr x, fpr ccs);
#define fpr_gm_tab PQCLEAN_FALCON512_CLEAN_fpr_gm_tab
extern const fpr fpr_gm_tab[];
#define fpr_p2_tab PQCLEAN_FALCON512_CLEAN_fpr_p2_tab
extern const fpr fpr_p2_tab[];
/* ====================================================================== */
#endif
| 3,399 |
335 | <gh_stars>100-1000
{
"word": "Remunerative",
"definitions": [
"Financially rewarding; lucrative.",
"Earning a salary; paid."
],
"parts-of-speech": "Adjective"
} | 86 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Vallereuil","circ":"1ère circonscription","dpt":"Dordogne","inscrits":245,"abs":76,"votants":169,"blancs":5,"nuls":4,"exp":160,"res":[{"nuance":"REM","nom":"<NAME>","voix":57},{"nuance":"FN","nom":"Mme <NAME>","voix":31},{"nuance":"SOC","nom":"<NAME>","voix":26},{"nuance":"FI","nom":"Mme <NAME>","voix":21},{"nuance":"LR","nom":"<NAME>","voix":10},{"nuance":"COM","nom":"M. <NAME>","voix":8},{"nuance":"EXG","nom":"Mme <NAME>","voix":4},{"nuance":"ECO","nom":"M. <NAME>","voix":2},{"nuance":"DVD","nom":"<NAME>","voix":1},{"nuance":"DIV","nom":"M. <NAME>","voix":0}]} | 253 |
661 | <reponame>hinca/update4j
/*
* Copyright 2018 <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.update4j;
import java.util.Objects;
import org.update4j.service.Launcher;
/**
* A class that contain details of the launch.
*
* @author <NAME>
*
*/
public class LaunchContext {
private ModuleLayer layer;
private ClassLoader classLoader;
private Configuration config;
LaunchContext(ModuleLayer layer, ClassLoader classLoader, Configuration config) {
this.layer = Objects.requireNonNull(layer);
this.classLoader = Objects.requireNonNull(classLoader);
this.config = Objects.requireNonNull(config);
}
/**
* Returns the {@link ModuleLayer} where modules in the config that were marked
* with {@code modulepath} are dynamically loaded.
*
* @return The dynamic module layer.
*/
public ModuleLayer getModuleLayer() {
return layer;
}
/**
* Returns the class loader that classes in the dynamic classpath or modulepath
* are loaded with. Use this to access dynamic classes in the bootstrap:
*
* <pre>
* Class<?> clazz = ctx.getClassLoader().loadClass("MyBusinessClass");
* </pre>
*
* Once the class was loaded, the class itself has access to the dynamic
* classpath in natural Java.
*
* <p>
* This is also necessary for libraries or frameworks that loads classes
* reflectively (JavaFX {@code FXMLLoader} or Spring to name a few) <i>and those
* libraries were loaded in the bootstrap</i>. Since they are not aware of the
* dynamically augmented classes and they run in a different thread which is not
* a child of the launch thread, {@link Thread#getContextClassLoader()} does not
* return this instance. You might want explicitly set it to the thread that
* does the loading:
*
* <pre>
* Thread.currentThread().setContextClassLoader(ctx.getClassLoader());
* </pre>
*
* <p>
* Or use the libraries' methods that take an explicit class loader, as in
* {@code FXMLLoader}:
*
* <pre>
* FXMLLoader loader = new FXMLLoader(myLocation);
* loader.setClassLoader(ctx.getClassLoader());
* </pre>
*
* You might find using {@link DynamicClassLoader} simpler and suiting better to
* your needs. Check out <a href=
* "https://github.com/update4j/update4j/wiki/Documentation#classloading-model">Classloading
* Model</a> in the GitHub wiki.
*
* <p>
* <b>Note:</b> The thread that calls {@link Launcher#run(LaunchContext)}
* already has this set as the context class loader. New threads spawned from
* this thread will also automatically assign this as the context class loader.
*
* @return The dynamic class loader.
*/
public ClassLoader getClassLoader() {
return classLoader;
}
/**
* Returns the configuration used for this launch.
*
* @return The configuration used for this launch.
*/
public Configuration getConfiguration() {
return config;
}
}
| 1,222 |
4,054 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "monitorreply.h"
namespace search::engine {
MonitorReply::MonitorReply()
: activeDocs(0),
distribution_key(-1),
timestamp(),
is_blocking_writes(false)
{ }
}
| 103 |
576 | <filename>japicmp/src/main/java/japicmp/config/Options.java
package japicmp.config;
import com.google.common.base.Joiner;
import japicmp.util.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import japicmp.cli.CliParser;
import japicmp.cli.JApiCli;
import japicmp.cmp.JApiCmpArchive;
import japicmp.exception.JApiCmpException;
import japicmp.filter.AnnotationBehaviorFilter;
import japicmp.filter.AnnotationClassFilter;
import japicmp.filter.AnnotationFieldFilter;
import japicmp.filter.Filter;
import japicmp.filter.JavaDocLikeClassFilter;
import japicmp.filter.JavadocLikeBehaviorFilter;
import japicmp.filter.JavadocLikeFieldFilter;
import japicmp.filter.JavadocLikePackageFilter;
import japicmp.model.AccessModifier;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
public class Options {
private static final Logger LOGGER = Logger.getLogger(Options.class.getName());
static final String N_A = "n.a.";
private List<JApiCmpArchive> oldArchives = new ArrayList<>();
private List<JApiCmpArchive> newArchives = new ArrayList<>();
private boolean outputOnlyModifications = false;
private boolean outputOnlyBinaryIncompatibleModifications = false;
private Optional<String> xmlOutputFile = Optional.absent();
private Optional<String> htmlOutputFile = Optional.absent();
private Optional<AccessModifier> accessModifier = Optional.of(AccessModifier.PROTECTED);
private List<Filter> includes = new ArrayList<>();
private List<Filter> excludes = new ArrayList<>();
private boolean includeSynthetic = false;
private final IgnoreMissingClasses ignoreMissingClasses = new IgnoreMissingClasses();
private Optional<String> htmlStylesheet = Optional.absent();
private Optional<String> oldClassPath = Optional.absent();
private Optional<String> newClassPath = Optional.absent();
private JApiCli.ClassPathMode classPathMode = JApiCli.ClassPathMode.ONE_COMMON_CLASSPATH;
private boolean noAnnotations = false;
private boolean reportOnlyFilename;
private boolean semanticVersioning;
private boolean errorOnBinaryIncompatibility;
private boolean errorOnSourceIncompatibility;
private boolean errorOnExclusionIncompatibility = true;
private boolean errorOnModifications;
private boolean errorOnSemanticIncompatibility;
private boolean ignoreMissingOldVersion;
private boolean ignoreMissingNewVersion;
private boolean helpRequested;
private boolean errorOnSemanticIncompatibilityForMajorVersionZero;
Options() {
// intentionally left empty
}
public static Options newDefault() {
return new Options();
}
public void verify() {
if (oldArchives.isEmpty()) {
throw new JApiCmpException(JApiCmpException.Reason.CliError, "Required option -o, --old is missing.");
}
if (newArchives.isEmpty()) {
throw new JApiCmpException(JApiCmpException.Reason.CliError, "Required option -n, --new is missing.");
}
for (JApiCmpArchive archive : getOldArchives()) {
verifyExistsCanReadAndJar(archive);
}
for (JApiCmpArchive archive : getNewArchives()) {
verifyExistsCanReadAndJar(archive);
}
if (getHtmlOutputFile().isPresent()) {
if (getHtmlStylesheet().isPresent()) {
String pathname = getHtmlStylesheet().get();
File stylesheetFile = new File(pathname);
if (!stylesheetFile.exists()) {
throw JApiCmpException.cliError("HTML stylesheet '%s' does not exist.", pathname);
}
}
} else {
if (getHtmlStylesheet().isPresent()) {
throw JApiCmpException.cliError("Define a HTML output file, if you want to apply a stylesheet.");
}
}
if (getOldClassPath().isPresent() && getNewClassPath().isPresent()) {
setClassPathMode(JApiCli.ClassPathMode.TWO_SEPARATE_CLASSPATHS);
} else {
if (getOldClassPath().isPresent() || getNewClassPath().isPresent()) {
throw JApiCmpException.cliError("Please provide both options: " + CliParser.OLD_CLASSPATH + " and " + CliParser.NEW_CLASSPATH);
} else {
setClassPathMode(JApiCli.ClassPathMode.ONE_COMMON_CLASSPATH);
}
}
}
private static void verifyExistsCanReadAndJar(JApiCmpArchive jApiCmpArchive) {
verifyExisting(jApiCmpArchive);
verifyCanRead(jApiCmpArchive);
verifyJarArchive(jApiCmpArchive);
}
private static void verifyExisting(JApiCmpArchive jApiCmpArchive) {
if (!jApiCmpArchive.getFile().exists()) {
throw JApiCmpException.cliError("File '%s' does not exist.", jApiCmpArchive.getFile().getAbsolutePath());
}
}
private static void verifyCanRead(JApiCmpArchive jApiCmpArchive) {
if (!jApiCmpArchive.getFile().canRead()) {
throw JApiCmpException.cliError("Cannot read file '%s'.", jApiCmpArchive.getFile().getAbsolutePath());
}
}
private static void verifyJarArchive(JApiCmpArchive jApiCmpArchive) {
JarFile jarFile = null;
try {
jarFile = new JarFile(jApiCmpArchive.getFile());
} catch (IOException e) {
throw JApiCmpException.cliError("File '%s' could not be opened as a jar file: %s", jApiCmpArchive.getFile().getAbsolutePath(), e.getMessage(), e);
} finally {
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException e) {
LOGGER.log(Level.FINE, "Failed to close file: " + e.getLocalizedMessage(), e);
}
}
}
}
public List<JApiCmpArchive> getNewArchives() {
return newArchives;
}
public void setNewArchives(List<JApiCmpArchive> newArchives) {
this.newArchives = newArchives;
}
public List<JApiCmpArchive> getOldArchives() {
return oldArchives;
}
public void setOldArchives(List<JApiCmpArchive> oldArchives) {
this.oldArchives = oldArchives;
}
public boolean isOutputOnlyModifications() {
return outputOnlyModifications;
}
public void setOutputOnlyModifications(boolean outputOnlyModifications) {
this.outputOnlyModifications = outputOnlyModifications;
}
public Optional<String> getXmlOutputFile() {
return xmlOutputFile;
}
public void setXmlOutputFile(Optional<String> xmlOutputFile) {
this.xmlOutputFile = xmlOutputFile;
}
public void setAccessModifier(Optional<AccessModifier> accessModifier) {
this.accessModifier = accessModifier;
}
public AccessModifier getAccessModifier() {
return accessModifier.get();
}
public void setAccessModifier(AccessModifier accessModifier) {
this.accessModifier = Optional.of(accessModifier);
}
public List<Filter> getIncludes() {
return ImmutableList.copyOf(includes);
}
public List<Filter> getExcludes() {
return ImmutableList.copyOf(excludes);
}
public void addExcludeFromArgument(Optional<String> packagesExcludeArg, boolean excludeExclusively) {
excludes = createFilterList(packagesExcludeArg, excludes, "Wrong syntax for exclude option '%s': %s", excludeExclusively);
}
public void addIncludeFromArgument(Optional<String> packagesIncludeArg, boolean includeExclusively) {
includes = createFilterList(packagesIncludeArg, includes, "Wrong syntax for include option '%s': %s", includeExclusively);
}
public List<Filter> createFilterList(Optional<String> argumentString, List<Filter> filters, String errorMessage, boolean exclusive) {
for (String filterString : Splitter.on(";").trimResults().omitEmptyStrings().split(argumentString.or(""))) {
try {
// filter based on annotations
if (filterString.startsWith("@")) {
filters.add(new AnnotationClassFilter(filterString));
filters.add(new AnnotationFieldFilter(filterString));
filters.add(new AnnotationBehaviorFilter(filterString));
}
if (filterString.contains("#")) {
if (filterString.contains("(")) {
JavadocLikeBehaviorFilter behaviorFilter = new JavadocLikeBehaviorFilter(filterString);
filters.add(behaviorFilter);
} else {
JavadocLikeFieldFilter fieldFilter = new JavadocLikeFieldFilter(filterString);
filters.add(fieldFilter);
}
} else {
JavaDocLikeClassFilter classFilter = new JavaDocLikeClassFilter(filterString);
filters.add(classFilter);
JavadocLikePackageFilter packageFilter = new JavadocLikePackageFilter(filterString, exclusive);
filters.add(packageFilter);
}
} catch (Exception e) {
throw new JApiCmpException(JApiCmpException.Reason.CliError, String.format(errorMessage, filterString, e.getMessage()), e);
}
}
return filters;
}
public boolean isOutputOnlyBinaryIncompatibleModifications() {
return outputOnlyBinaryIncompatibleModifications;
}
public void setOutputOnlyBinaryIncompatibleModifications(boolean outputOnlyBinaryIncompatibleModifications) {
this.outputOnlyBinaryIncompatibleModifications = outputOnlyBinaryIncompatibleModifications;
}
public Optional<String> getHtmlOutputFile() {
return htmlOutputFile;
}
public void setHtmlOutputFile(Optional<String> htmlOutputFile) {
this.htmlOutputFile = htmlOutputFile;
}
public boolean isIncludeSynthetic() {
return includeSynthetic;
}
public void setIncludeSynthetic(boolean showSynthetic) {
this.includeSynthetic = showSynthetic;
}
public void setIgnoreMissingClasses(boolean ignoreMissingClasses) {
this.ignoreMissingClasses.setIgnoreAllMissingClasses(ignoreMissingClasses);
}
public Optional<String> getHtmlStylesheet() {
return htmlStylesheet;
}
public void setHtmlStylesheet(Optional<String> htmlStylesheet) {
this.htmlStylesheet = htmlStylesheet;
}
public Optional<String> getOldClassPath() {
return oldClassPath;
}
public void setOldClassPath(Optional<String> oldClassPath) {
this.oldClassPath = oldClassPath;
}
public Optional<String> getNewClassPath() {
return newClassPath;
}
public void setNewClassPath(Optional<String> newClassPath) {
this.newClassPath = newClassPath;
}
public JApiCli.ClassPathMode getClassPathMode() {
return classPathMode;
}
public void setClassPathMode(JApiCli.ClassPathMode classPathMode) {
this.classPathMode = classPathMode;
}
public boolean isNoAnnotations() {
return noAnnotations;
}
public void setNoAnnotations(boolean noAnnotations) {
this.noAnnotations = noAnnotations;
}
public void addIgnoreMissingClassRegularExpression(String missingClassRegEx) {
try {
Pattern pattern = Pattern.compile(missingClassRegEx);
this.ignoreMissingClasses.getIgnoreMissingClassRegularExpression().add(pattern);
} catch (Exception e) {
throw new JApiCmpException(JApiCmpException.Reason.IllegalArgument, "Could not compile provided regular expression: " + e.getMessage(), e);
}
}
public IgnoreMissingClasses getIgnoreMissingClasses() {
return ignoreMissingClasses;
}
public void setReportOnlyFilename(boolean reportOnlyFilename) {
this.reportOnlyFilename = reportOnlyFilename;
}
public String getDifferenceDescription() {
Joiner joiner = Joiner.on(";");
StringBuilder sb = new StringBuilder()
.append("Comparing ")
.append(isOutputOnlyBinaryIncompatibleModifications() ? "binary" :"source")
.append(" compatibility of ");
sb.append(joiner.join(toPathList(newArchives)));
sb.append(" against ");
sb.append(joiner.join(toPathList(oldArchives)));
return sb.toString();
}
private List<String> toPathList(List<JApiCmpArchive> archives) {
List<String> paths = new ArrayList<>(archives.size());
for (JApiCmpArchive archive : archives) {
if (this.reportOnlyFilename) {
paths.add(archive.getFile().getName());
} else {
paths.add(archive.getFile().getAbsolutePath());
}
}
return paths;
}
private List<String> toVersionList(List<JApiCmpArchive> archives) {
List<String> versions = new ArrayList<>(archives.size());
for (JApiCmpArchive archive : archives) {
String stringVersion = archive.getVersion().getStringVersion();
if (stringVersion != null) {
versions.add(stringVersion);
}
}
return versions;
}
public String joinOldArchives() {
Joiner joiner = Joiner.on(";");
String join = joiner.join(toPathList(oldArchives));
if (join.trim().length() == 0) {
return N_A;
}
return join;
}
public String joinNewArchives() {
Joiner joiner = Joiner.on(";");
String join = joiner.join(toPathList(newArchives));
if (join.trim().length() == 0) {
return N_A;
}
return join;
}
public String joinOldVersions() {
Joiner joiner = Joiner.on(";");
String join = joiner.join(toVersionList(oldArchives));
if (join.trim().length() == 0) {
return N_A;
}
return join;
}
public String joinNewVersions() {
Joiner joiner = Joiner.on(";");
String join = joiner.join(toVersionList(newArchives));
if (join.trim().length() == 0) {
return N_A;
}
return join;
}
public void setSemanticVersioning(boolean semanticVersioning) {
this.semanticVersioning = semanticVersioning;
}
public boolean isSemanticVersioning() {
return semanticVersioning;
}
public boolean isErrorOnBinaryIncompatibility() {
return errorOnBinaryIncompatibility;
}
public void setErrorOnBinaryIncompatibility(boolean errorOnBinaryIncompatibility) {
this.errorOnBinaryIncompatibility = errorOnBinaryIncompatibility;
}
public boolean isErrorOnSourceIncompatibility() {
return errorOnSourceIncompatibility;
}
public void setErrorOnSourceIncompatibility(boolean errorOnSourceIncompatibility) {
this.errorOnSourceIncompatibility = errorOnSourceIncompatibility;
}
public boolean isErrorOnExclusionIncompatibility() {
return errorOnExclusionIncompatibility;
}
public void setErrorOnExclusionIncompatibility(boolean errorOnExclusionIncompatibility) {
this.errorOnExclusionIncompatibility = errorOnExclusionIncompatibility;
}
public boolean isErrorOnModifications() {
return errorOnModifications;
}
public void setErrorOnModifications(boolean errorOnModifications) {
this.errorOnModifications = errorOnModifications;
}
public boolean isErrorOnSemanticIncompatibility() {
return errorOnSemanticIncompatibility;
}
public void setErrorOnSemanticIncompatibility(boolean errorOnSemanticIncompatibility) {
this.errorOnSemanticIncompatibility = errorOnSemanticIncompatibility;
}
public boolean isIgnoreMissingOldVersion() {
return ignoreMissingOldVersion;
}
public void setIgnoreMissingOldVersion(boolean ignoreMissingOldVersion) {
this.ignoreMissingOldVersion = ignoreMissingOldVersion;
}
public boolean isIgnoreMissingNewVersion() {
return ignoreMissingNewVersion;
}
public void setIgnoreMissingNewVersion(boolean ignoreMissingNewVersion) {
this.ignoreMissingNewVersion = ignoreMissingNewVersion;
}
public boolean isHelpRequested() {
return helpRequested;
}
public void setHelpRequested(boolean helpRequested) {
this.helpRequested = helpRequested;
}
public boolean isErrorOnSemanticIncompatibilityForMajorVersionZero() {
return errorOnSemanticIncompatibilityForMajorVersionZero;
}
public void setErrorOnSemanticIncompatibilityForMajorVersionZero(boolean errorOnSemanticIncompatibilityForMajorVersionZero) {
this.errorOnSemanticIncompatibilityForMajorVersionZero = errorOnSemanticIncompatibilityForMajorVersionZero;
}
}
| 5,041 |
592 | /*
* Copyright 2016 LinkedIn Corp.
*
* 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.linkedin.gradle.python.extension;
import com.linkedin.gradle.python.extension.internal.DefaultPythonDetails;
import com.linkedin.gradle.python.util.OperatingSystem;
import org.gradle.api.Project;
import java.io.File;
/**
* Intended to dispense Python Details given a project.
*/
public class PythonDetailsFactory {
private PythonDetailsFactory() {
//Private constructor for utility class
}
/**
* Make a new PythonDetails
*/
public static PythonDetails makePythonDetails(Project project, File venv) {
return new DefaultPythonDetails(project, venv);
}
/**
* Make a new PythonDetails
*/
public static PythonDetails withNewVenv(Project project, PythonDetails fromDetails, File venv) {
DefaultPythonDetails nextDetails = new DefaultPythonDetails(project, venv);
nextDetails.setPythonInterpreter(fromDetails.getPythonVersion(), fromDetails.getSystemPythonInterpreter());
return nextDetails;
}
/**
* @return The name of the "exec" dir
*/
public static String getPythonApplicationDirectory() {
return OperatingSystem.current().isWindows() ? "Scripts" : "bin";
}
}
| 544 |
2,329 | package system;
import java.lang.reflect.Method;
/**
* This test class represents a class in the system set for the VM. These classes cannot have their reflective calls directly
* intercepted because we cannot introduce dependencies on types in a lower classloader, so we have to call the reflective
* interceptor reflectively!
*/
public class Five {
String s;
public String runIt() throws Exception {
StringBuilder data = new StringBuilder();
Method method = m("runIt");
data.append("method?" + method + " ");
try {
m("foobar");
data.append("unexpectedly_didn't_fail");
} catch (NoSuchMethodException nsme) {
data.append("nsme");
}
return "complete:" + data.toString().trim();
}
public Method m(String name) throws NoSuchMethodException {
return this.getClass().getDeclaredMethod(name);
}
}
| 246 |
689 | /**
* Copyright (C) Mellanox Technologies Ltd. 2001-2021. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#ifndef UCS_DEBUG_H_
#define UCS_DEBUG_H_
#include <ucs/sys/compiler_def.h>
BEGIN_C_DECLS
/**
* Disable signal handling in UCS for signal.
* Previous signal handler is set.
* @param signum Signal number to disable handling.
*/
void ucs_debug_disable_signal(int signum);
END_C_DECLS
#endif
| 153 |
335 | <filename>P/Pons_noun.json
{
"word": "Pons",
"definitions": [
"The part of the brainstem that links the medulla oblongata and the thalamus."
],
"parts-of-speech": "Noun"
} | 85 |
1,467 | <gh_stars>1000+
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ResolvedImmutableAttribute;
import software.amazon.awssdk.utils.Validate;
/**
* A class that represents an attribute on an mapped immutable item. A {@link StaticImmutableTableSchema} composes
* multiple attributes that map to a common immutable item class.
* <p>
* The recommended way to use this class is by calling
* {@link software.amazon.awssdk.enhanced.dynamodb.TableSchema#builder(Class, Class)}.
* Example:
* {@code
* TableSchema.builder(Customer.class, Customer.Builder.class)
* .addAttribute(String.class,
* a -> a.name("customer_name").getter(Customer::name).setter(Customer.Builder::name))
* // ...
* .build();
* }
* <p>
* It's also possible to construct this class on its own using the static builder. Example:
* {@code
* ImmutableAttribute<Customer, Customer.Builder, ?> customerNameAttribute =
* ImmutableAttribute.builder(Customer.class, Customer.Builder.class, String.class)
* .name("customer_name")
* .getter(Customer::name)
* .setter(Customer.Builder::name)
* .build();
* }
* @param <T> the class of the immutable item this attribute maps into.
* @param <B> the class of the builder for the immutable item this attribute maps into.
* @param <R> the class that the value of this attribute converts to.
*/
@SdkPublicApi
public final class ImmutableAttribute<T, B, R> {
private final String name;
private final Function<T, R> getter;
private final BiConsumer<B, R> setter;
private final Collection<StaticAttributeTag> tags;
private final EnhancedType<R> type;
private final AttributeConverter<R> attributeConverter;
private ImmutableAttribute(Builder<T, B, R> builder) {
this.name = Validate.paramNotNull(builder.name, "name");
this.getter = Validate.paramNotNull(builder.getter, "getter");
this.setter = Validate.paramNotNull(builder.setter, "setter");
this.tags = builder.tags == null ? Collections.emptyList() : Collections.unmodifiableCollection(builder.tags);
this.type = Validate.paramNotNull(builder.type, "type");
this.attributeConverter = builder.attributeConverter;
}
/**
* Constructs a new builder for this class using supplied types.
* @param itemClass The class of the immutable item that this attribute composes.
* @param builderClass The class of the builder for the immutable item that this attribute composes.
* @param attributeType A {@link EnhancedType} that represents the type of the value this attribute stores.
* @return A new typed builder for an attribute.
*/
public static <T, B, R> Builder<T, B, R> builder(Class<T> itemClass,
Class<B> builderClass,
EnhancedType<R> attributeType) {
return new Builder<>(attributeType);
}
/**
* Constructs a new builder for this class using supplied types.
* @param itemClass The class of the item that this attribute composes.
* @param builderClass The class of the builder for the immutable item that this attribute composes.
* @param attributeClass A class that represents the type of the value this attribute stores.
* @return A new typed builder for an attribute.
*/
public static <T, B, R> Builder<T, B, R> builder(Class<T> itemClass,
Class<B> builderClass,
Class<R> attributeClass) {
return new Builder<>(EnhancedType.of(attributeClass));
}
/**
* The name of this attribute
*/
public String name() {
return this.name;
}
/**
* A function that can get the value of this attribute from a modelled immutable item it composes.
*/
public Function<T, R> getter() {
return this.getter;
}
/**
* A function that can set the value of this attribute on a builder for the immutable modelled item it composes.
*/
public BiConsumer<B, R> setter() {
return this.setter;
}
/**
* A collection of {@link StaticAttributeTag} associated with this attribute.
*/
public Collection<StaticAttributeTag> tags() {
return this.tags;
}
/**
* A {@link EnhancedType} that represents the type of the value this attribute stores.
*/
public EnhancedType<R> type() {
return this.type;
}
/**
* A custom {@link AttributeConverter} that will be used to convert this attribute.
* If no custom converter was provided, the value will be null.
* @see Builder#attributeConverter
*/
public AttributeConverter<R> attributeConverter() {
return this.attributeConverter;
}
/**
* Converts an instance of this class to a {@link Builder} that can be used to modify and reconstruct it.
*/
public Builder<T, B, R> toBuilder() {
return new Builder<T, B, R>(this.type).name(this.name)
.getter(this.getter)
.setter(this.setter)
.tags(this.tags)
.attributeConverter(this.attributeConverter);
}
ResolvedImmutableAttribute<T, B> resolve(AttributeConverterProvider attributeConverterProvider) {
return ResolvedImmutableAttribute.create(this,
converterFrom(attributeConverterProvider));
}
private AttributeConverter<R> converterFrom(AttributeConverterProvider attributeConverterProvider) {
return (attributeConverter != null) ? attributeConverter : attributeConverterProvider.converterFor(type);
}
/**
* A typed builder for {@link ImmutableAttribute}.
* @param <T> the class of the item this attribute maps into.
* @param <R> the class that the value of this attribute converts to.
*/
public static final class Builder<T, B, R> {
private final EnhancedType<R> type;
private String name;
private Function<T, R> getter;
private BiConsumer<B, R> setter;
private List<StaticAttributeTag> tags;
private AttributeConverter<R> attributeConverter;
private Builder(EnhancedType<R> type) {
this.type = type;
}
/**
* The name of this attribute
*/
public Builder<T, B, R> name(String name) {
this.name = name;
return this;
}
/**
* A function that can get the value of this attribute from a modelled item it composes.
*/
public Builder<T, B, R> getter(Function<T, R> getter) {
this.getter = getter;
return this;
}
/**
* A function that can set the value of this attribute on a modelled item it composes.
*/
public Builder<T, B, R> setter(BiConsumer<B, R> setter) {
this.setter = setter;
return this;
}
/**
* A collection of {@link StaticAttributeTag} associated with this attribute. Overwrites any existing tags.
*/
public Builder<T, B, R> tags(Collection<StaticAttributeTag> tags) {
this.tags = new ArrayList<>(tags);
return this;
}
/**
* A collection of {@link StaticAttributeTag} associated with this attribute. Overwrites any existing tags.
*/
public Builder<T, B, R> tags(StaticAttributeTag... tags) {
this.tags = Arrays.asList(tags);
return this;
}
/**
* Associates a single {@link StaticAttributeTag} with this attribute. Adds to any existing tags.
*/
public Builder<T, B, R> addTag(StaticAttributeTag tag) {
if (this.tags == null) {
this.tags = new ArrayList<>();
}
this.tags.add(tag);
return this;
}
/**
* An {@link AttributeConverter} for the attribute type ({@link EnhancedType}), that can convert this attribute.
* It takes precedence over any converter for this type provided by the table schema
* {@link AttributeConverterProvider}.
*/
public Builder<T, B, R> attributeConverter(AttributeConverter<R> attributeConverter) {
this.attributeConverter = attributeConverter;
return this;
}
/**
* Builds a {@link StaticAttributeTag} from the values stored in this builder.
*/
public ImmutableAttribute<T, B, R> build() {
return new ImmutableAttribute<>(this);
}
}
}
| 3,977 |
1,290 | <filename>Z - Tool Box/LaZagne/Linux/lazagne/config/lib/memorpy/WinProcess.py<gh_stars>1000+
# Author: <NAME>
# This file is part of memorpy.
#
# memorpy 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.
#
# memorpy 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 memorpy. If not, see <http://www.gnu.org/licenses/>.
from ctypes import pointer, sizeof, windll, create_string_buffer, c_ulong, byref, GetLastError, c_bool, WinError
from .structures import *
import copy
import struct
# import utils
import platform
from .BaseProcess import BaseProcess, ProcessException
psapi = windll.psapi
kernel32 = windll.kernel32
advapi32 = windll.advapi32
IsWow64Process=None
if hasattr(kernel32,'IsWow64Process'):
IsWow64Process=kernel32.IsWow64Process
IsWow64Process.restype = c_bool
IsWow64Process.argtypes = [c_void_p, POINTER(c_bool)]
class WinProcess(BaseProcess):
def __init__(self, pid=None, name=None, debug=True):
""" Create and Open a process object from its pid or from its name """
super(WinProcess, self).__init__()
if pid:
self._open(int(pid), debug=debug)
elif name:
self._open_from_name(name, debug=debug)
else:
raise ValueError("You need to instanciate process with at least a name or a pid")
if self.is_64bit():
si = self.GetNativeSystemInfo()
self.max_addr = si.lpMaximumApplicationAddress
else:
si = self.GetSystemInfo()
self.max_addr = 2147418111
self.min_addr = si.lpMinimumApplicationAddress
def __del__(self):
self.close()
def is_64bit(self):
if not "64" in platform.machine():
return False
iswow64 = c_bool(False)
if IsWow64Process is None:
return False
if not IsWow64Process(self.h_process, byref(iswow64)):
raise WinError()
return not iswow64.value
@staticmethod
def list():
processes=[]
arr = c_ulong * 256
lpidProcess= arr()
cb = sizeof(lpidProcess)
cbNeeded = c_ulong()
hModule = c_ulong()
count = c_ulong()
modname = create_string_buffer(100)
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
psapi.EnumProcesses(byref(lpidProcess), cb, byref(cbNeeded))
nReturned = cbNeeded.value/sizeof(c_ulong())
pidProcess = [i for i in lpidProcess][:nReturned]
for pid in pidProcess:
proc={ "pid": int(pid) }
hProcess = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
if hProcess:
psapi.EnumProcessModules(hProcess, byref(hModule), sizeof(hModule), byref(count))
psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, sizeof(modname))
proc["name"]=modname.value
kernel32.CloseHandle(hProcess)
processes.append(proc)
return processes
@staticmethod
def processes_from_name(processName):
processes = []
for process in WinProcess.list():
if processName == process.get("name", None) or (process.get("name","").lower().endswith(".exe") and process.get("name","")[:-4]==processName):
processes.append(process)
if len(processes) > 0:
return processes
@staticmethod
def name_from_process(dwProcessId):
process_list = WinProcess.list()
for process in process_list:
if process.pid == dwProcessId:
return process.get("name", None)
return False
def _open(self, dwProcessId, debug=False):
if debug:
ppsidOwner = DWORD()
ppsidGroup = DWORD()
ppDacl = DWORD()
ppSacl = DWORD()
ppSecurityDescriptor = SECURITY_DESCRIPTOR()
process = kernel32.OpenProcess(262144, 0, dwProcessId)
advapi32.GetSecurityInfo(kernel32.GetCurrentProcess(), 6, 0, byref(ppsidOwner), byref(ppsidGroup), byref(ppDacl), byref(ppSacl), byref(ppSecurityDescriptor))
advapi32.SetSecurityInfo(process, 6, DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION, None, None, ppSecurityDescriptor.dacl, ppSecurityDescriptor.group)
kernel32.CloseHandle(process)
self.h_process = kernel32.OpenProcess(2035711, 0, dwProcessId)
if self.h_process is not None:
self.isProcessOpen = True
self.pid = dwProcessId
return True
return False
def close(self):
if self.h_process is not None:
ret = kernel32.CloseHandle(self.h_process) == 1
if ret:
self.h_process = None
self.pid = None
self.isProcessOpen = False
return ret
return False
def _open_from_name(self, processName, debug=False):
processes = self.processes_from_name(processName)
if not processes:
raise ProcessException("can't get pid from name %s" % processName)
elif len(processes)>1:
raise ValueError("There is multiple processes with name %s. Please select a process from its pid instead"%processName)
if debug:
self._open(processes[0]["pid"], debug=True)
else:
self._open(processes[0]["pid"], debug=False)
def GetSystemInfo(self):
si = SYSTEM_INFO()
kernel32.GetSystemInfo(byref(si))
return si
def GetNativeSystemInfo(self):
si = SYSTEM_INFO()
kernel32.GetNativeSystemInfo(byref(si))
return si
def VirtualQueryEx(self, lpAddress):
mbi = MEMORY_BASIC_INFORMATION()
if not VirtualQueryEx(self.h_process, lpAddress, byref(mbi), sizeof(mbi)):
raise ProcessException('Error VirtualQueryEx: 0x%08X' % lpAddress)
return mbi
def VirtualQueryEx64(self, lpAddress):
mbi = MEMORY_BASIC_INFORMATION64()
if not VirtualQueryEx64(self.h_process, lpAddress, byref(mbi), sizeof(mbi)):
raise ProcessException('Error VirtualQueryEx: 0x%08X' % lpAddress)
return mbi
def VirtualProtectEx(self, base_address, size, protection):
old_protect = c_ulong(0)
if not kernel32.VirtualProtectEx(self.h_process, base_address, size, protection, byref(old_protect)):
raise ProcessException('Error: VirtualProtectEx(%08X, %d, %08X)' % (base_address, size, protection))
return old_protect.value
def iter_region(self, start_offset=None, end_offset=None, protec=None, optimizations=None):
offset = start_offset or self.min_addr
end_offset = end_offset or self.max_addr
while True:
if offset >= end_offset:
break
mbi = self.VirtualQueryEx(offset)
offset = mbi.BaseAddress
chunk = mbi.RegionSize
protect = mbi.Protect
state = mbi.State
#print "offset: %s, chunk:%s"%(offset, chunk)
if state & MEM_FREE or state & MEM_RESERVE:
offset += chunk
continue
if protec:
if not protect & protec or protect & PAGE_NOCACHE or protect & PAGE_WRITECOMBINE or protect & PAGE_GUARD:
offset += chunk
continue
yield offset, chunk
offset += chunk
def write_bytes(self, address, data):
address = int(address)
if not self.isProcessOpen:
raise ProcessException("Can't write_bytes(%s, %s), process %s is not open" % (address, data, self.pid))
buffer = create_string_buffer(data)
sizeWriten = c_size_t(0)
bufferSize = sizeof(buffer) - 1
_address = address
_length = bufferSize + 1
try:
old_protect = self.VirtualProtectEx(_address, _length, PAGE_EXECUTE_READWRITE)
except:
pass
res = kernel32.WriteProcessMemory(self.h_process, address, buffer, bufferSize, byref(sizeWriten))
try:
self.VirtualProtectEx(_address, _length, old_protect)
except:
pass
return res
def read_bytes(self, address, bytes = 4, use_NtWow64ReadVirtualMemory64=False):
#print "reading %s bytes from addr %s"%(bytes, address)
if use_NtWow64ReadVirtualMemory64:
if NtWow64ReadVirtualMemory64 is None:
raise WindowsError("NtWow64ReadVirtualMemory64 is not available from a 64bit process")
RpM = NtWow64ReadVirtualMemory64
else:
RpM = ReadProcessMemory
address = int(address)
buffer = create_string_buffer(bytes)
bytesread = c_size_t(0)
data = b''
length = bytes
while length:
if RpM(self.h_process, address, buffer, bytes, byref(bytesread)) or (use_NtWow64ReadVirtualMemory64 and GetLastError() == 0):
if bytesread.value:
data += buffer.raw[:bytesread.value]
length -= bytesread.value
address += bytesread.value
if not len(data):
raise ProcessException('Error %s in ReadProcessMemory(%08x, %d, read=%d)' % (GetLastError(),
address,
length,
bytesread.value))
return data
else:
if GetLastError()==299: #only part of ReadProcessMemory has been done, let's return it
data += buffer.raw[:bytesread.value]
return data
raise WinError()
# data += buffer.raw[:bytesread.value]
# length -= bytesread.value
# address += bytesread.value
return data
def list_modules(self):
module_list = []
if self.pid is not None:
hModuleSnap = CreateToolhelp32Snapshot(TH32CS_CLASS.SNAPMODULE, self.pid)
if hModuleSnap is not None:
module_entry = MODULEENTRY32()
module_entry.dwSize = sizeof(module_entry)
success = Module32First(hModuleSnap, byref(module_entry))
while success:
if module_entry.th32ProcessID == self.pid:
module_list.append(copy.copy(module_entry))
success = Module32Next(hModuleSnap, byref(module_entry))
kernel32.CloseHandle(hModuleSnap)
return module_list
def get_symbolic_name(self, address):
for m in self.list_modules():
if int(m.modBaseAddr) <= int(address) < int(m.modBaseAddr + m.modBaseSize):
return '%s+0x%08X' % (m.szModule, int(address) - m.modBaseAddr)
return '0x%08X' % int(address)
def hasModule(self, module):
if module[-4:] != '.dll':
module += '.dll'
module_list = self.list_modules()
for m in module_list:
if module in m.szExePath.split('\\'):
return True
return False
def get_instruction(self, address):
"""
Pydasm disassemble utility function wrapper. Returns the pydasm decoded instruction in self.instruction.
"""
import pydasm
try:
data = self.read_bytes(int(address), 32)
except:
return 'Unable to disassemble at %08x' % address
return pydasm.get_instruction(data, pydasm.MODE_32)
| 5,498 |
356 | #include "test_functions.hpp"
BOOST_AFIO_AUTO_TEST_CASE(async_io_pagesize, "Tests that the utility functions work", 120)
{
using namespace BOOST_AFIO_V2_NAMESPACE;
namespace asio = BOOST_AFIO_V2_NAMESPACE::asio;
typedef chrono::duration<double, ratio<1, 1>> secs_type;
std::cout << "\n\nSystem page sizes are: " << std::endl;
for(auto &i : utils::page_sizes(false))
std::cout << " " << i << " bytes" << std::endl;
BOOST_CHECK(!utils::page_sizes(false).empty());
std::cout << "\n\nActually available system page sizes are: " << std::endl;
for(auto &i : utils::page_sizes(true))
std::cout << " " << i << " bytes" << std::endl;
BOOST_CHECK(!utils::page_sizes(true).empty());
std::vector<char, utils::page_allocator<char>> fba(8*1024*1024);
auto fba_detail(utils::detail::calculate_large_page_allocation(8*1024*1024));
std::cout << "\n\nAllocating 8Mb with the file buffer allocator yields an address at " << ((void *) fba.data())
<< " and may use pages of " << fba_detail.page_size_used << " and be actually "
<< fba_detail.actual_size << " bytes allocated." << std::endl;
auto randomstring(utils::random_string(32));
std::cout << "\n\n256 bits of random string might be: " << randomstring << " which is " << randomstring.size() << " bytes long." << std::endl;
BOOST_CHECK(randomstring.size()==64);
auto begin=chrono::high_resolution_clock::now();
while(chrono::duration_cast<secs_type>(chrono::high_resolution_clock::now()-begin).count()<3);
static const size_t ITEMS=1000000;
std::vector<char> buffer(32*ITEMS, ' ');
begin=chrono::high_resolution_clock::now();
for(size_t n=0; n<buffer.size()/32; n++)
utils::random_fill(buffer.data()+n*32, 32);
auto end=chrono::high_resolution_clock::now();
auto diff=chrono::duration_cast<secs_type>(end-begin);
std::cout << "\n\nKernel can generate " << (buffer.size()/diff.count()/1024/1024) << " Mb/sec of 256 bit cryptographic randomness" << std::endl;
std::vector<std::vector<char>> filenames1(ITEMS, std::vector<char>(64, ' '));
begin=chrono::high_resolution_clock::now();
for(size_t n=0; n<ITEMS; n++)
utils::to_hex_string(const_cast<char *>(filenames1[n].data()), 64, buffer.data()+n*32, 32);
end=chrono::high_resolution_clock::now();
diff=chrono::duration_cast<secs_type>(end-begin);
std::cout << "\n\nto_hex_string can convert " << (ITEMS*64/diff.count()/1024/1024) << " Mb/sec of 256 bit numbers to hex" << std::endl;
std::vector<char> buffer1(32*ITEMS, ' ');
begin=chrono::high_resolution_clock::now();
for(size_t n=0; n<ITEMS; n++)
utils::from_hex_string(buffer1.data()+n*32, 32, filenames1[n].data(), 64);
end=chrono::high_resolution_clock::now();
diff=chrono::duration_cast<secs_type>(end-begin);
std::cout << "\n\nfrom_hex_string can convert " << (ITEMS*64/diff.count()/1024/1024) << " Mb/sec of hex to 256 bit numbers" << std::endl;
BOOST_CHECK(!memcmp(buffer.data(), buffer1.data(), buffer.size()));
#if !RUNNING_ON_SANITIZER
#ifndef _MSC_VER
#if defined(__i386__) || defined(__x86_64__)
static int have_popcnt=[]{
size_t cx, dx;
#if defined(__x86_64__)
asm("cpuid": "=c" (cx), "=d" (dx) : "a" (1), "b" (0), "c" (0), "d" (0));
#else
asm("pushl %%ebx\n\tcpuid\n\tpopl %%ebx\n\t": "=c" (cx), "=d" (dx) : "a" (1), "c" (0), "d" (0));
#endif
return (dx&(1<<26))!=0/*SSE2*/ && (cx&(1<<23))!=0/*POPCNT*/;
}();
std::cout << "\n\nThis CPU has the popcnt instruction: " << have_popcnt << std::endl;
#endif
#endif
{
static BOOST_CONSTEXPR_OR_CONST size_t bytes=4096;
std::vector<char> buffer(bytes);
utils::random_fill(buffer.data(), bytes);
utils::secded_ecc<bytes> engine;
typedef utils::secded_ecc<bytes>::result_type ecc_type;
ecc_type eccbits=engine.result_bits_valid();
std::cout << "\n\nECC will be " << eccbits << " bits long" << std::endl;
ecc_type ecc=engine(buffer.data());
std::cout << "ECC was calculated to be " << std::hex << ecc << std::dec << std::endl;
auto end=std::chrono::high_resolution_clock::now(), begin=std::chrono::high_resolution_clock::now();
auto diff=std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(end-begin);
#ifdef _MSC_VER
auto rdtsc=[]
{
return (unsigned long long) __rdtsc();
};
#else
#ifdef __rdtsc
return (unsigned long long) __rdtsc();
#elif defined(__x86_64__)
auto rdtsc=[]
{
unsigned lo, hi;
asm volatile ("rdtsc" : "=a"(lo), "=d"(hi));
return (unsigned long long) lo | ((unsigned long long) hi<<32);
};
#elif defined(__i386__)
auto rdtsc=[]
{
unsigned count;
asm volatile ("rdtsc" : "=a"(count));
return (unsigned long long) count;
};
#endif
#if __ARM_ARCH>=6
auto rdtsc=[]
{
unsigned count;
asm volatile ("MRC p15, 0, %0, c9, c13, 0" : "=r"(count));
return (unsigned long long) count * 64;
};
#endif
#endif
unsigned long long _begin=rdtsc(), _end;
#if 1
do
{
end=std::chrono::high_resolution_clock::now();
} while(std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(end-begin).count()<1);
_end=rdtsc();
std::cout << "There are " << (_end-_begin) << " TSCs in 1 second." << std::endl;
#endif
std::cout << "Flipping every bit in the buffer to see if it is correctly detected ..." << std::endl;
begin=std::chrono::high_resolution_clock::now();
for(size_t toflip=0; toflip<bytes*8; toflip++)
{
buffer[toflip/8]^=((size_t)1<<(toflip%8));
ecc_type newecc=engine(buffer.data());
if(ecc==newecc)
{
std::cerr << "ERROR: Flipping bit " << toflip << " not detected!" << std::endl;
BOOST_CHECK(ecc!=newecc);
}
else
{
ecc_type badbit=engine.find_bad_bit(ecc, newecc);
if(badbit!=toflip)
{
std::cerr << "ERROR: Bad bit " << badbit << " is not the bit " << toflip << " we flipped!" << std::endl;
BOOST_CHECK(badbit==toflip);
}
// else
// std::cout << "SUCCESS: Bit flip " << toflip << " correctly detected" << std::endl;
}
if(2!=engine.verify(buffer.data(), ecc))
{
std::cerr << "ERROR: verify() did not heal the buffer!" << std::endl;
BOOST_CHECK(false);
}
}
end=std::chrono::high_resolution_clock::now();
diff=std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(end-begin);
std::cout << "Checking and fixing is approximately " << (bytes*10000/diff.count()/1024/1024) << " Mb/sec" << std::endl;
std::cout << "\nFlipping two bits in the buffer to see if it is correctly detected ..." << std::endl;
buffer[0]^=1;
begin=std::chrono::high_resolution_clock::now();
for(size_t toflip=1; toflip<bytes*8; toflip++)
{
buffer[toflip/8]^=((size_t)1<<(toflip%8));
ecc_type newecc=engine(buffer.data());
if(ecc==newecc)
{
std::cerr << "ERROR: Flipping bits 0 and " << toflip << " not detected!" << std::endl;
BOOST_CHECK(ecc!=newecc);
}
buffer[toflip/8]^=((size_t)1<<(toflip%8));
}
end=std::chrono::high_resolution_clock::now();
diff=std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(end-begin);
std::cout << "Calculating is approximately " << (bytes*10000/diff.count()/1024/1024) << " Mb/sec" << std::endl;
std::cout << "\nCalculating speeds ..." << std::endl;
size_t foo=0;
begin=std::chrono::high_resolution_clock::now();
_begin=rdtsc();
for(size_t n=0; n<10000; n++)
{
buffer[0]=(char)n;
foo+=engine(buffer.data());
}
_end=rdtsc();
end=std::chrono::high_resolution_clock::now();
diff=std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(end-begin);
if(foo)
std::cout << "Fixed buffer size calculating is approximately " << (bytes*10000/diff.count()/1024/1024) << " Mb/sec, or " << ((_end-_begin)/10000.0/4096) << " cycles/byte" << std::endl;
foo=0;
begin=std::chrono::high_resolution_clock::now();
_begin=rdtsc();
for(size_t n=0; n<10000; n++)
{
buffer[0]=(char)n;
foo+=engine(buffer.data(), bytes);
}
_end=rdtsc();
end=std::chrono::high_resolution_clock::now();
diff=std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(end-begin);
if(foo)
std::cout << "Variable buffer size calculating is approximately " << (bytes*10000/diff.count()/1024/1024) << " Mb/sec, or " << ((_end-_begin)/10000.0/4096) << " cycles/byte" << std::endl;
foo=0;
begin=std::chrono::high_resolution_clock::now();
for(size_t n=0; n<1000; n++)
{
buffer[0]=(char)n;
foo+=engine.verify(buffer.data(), ecc);
}
end=std::chrono::high_resolution_clock::now();
diff=std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(end-begin);
if(foo)
std::cout << "Checking and fixing is approximately " << (bytes*1000/diff.count()/1024/1024) << " Mb/sec" << std::endl;
}
#endif
auto dispatcher=make_dispatcher().get();
std::cout << "\n\nThread source use count is: " << dispatcher->threadsource().use_count() << std::endl;
BOOST_AFIO_CHECK_THROWS(dispatcher->op_from_scheduled_id(78));
} | 4,406 |
2,151 | <reponame>zipated/src
// Copyright (c) 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.
#include "chrome/installer/util/channel_info.h"
#include <utility>
#include "chrome/installer/util/util_constants.h"
#include "testing/gtest/include/gtest/gtest.h"
using installer::ChannelInfo;
TEST(ChannelInfoTest, FullInstall) {
ChannelInfo ci;
ci.set_value(L"");
EXPECT_TRUE(ci.SetFullSuffix(true));
EXPECT_TRUE(ci.HasFullSuffix());
EXPECT_EQ(L"-full", ci.value());
EXPECT_FALSE(ci.SetFullSuffix(true));
EXPECT_TRUE(ci.HasFullSuffix());
EXPECT_EQ(L"-full", ci.value());
EXPECT_TRUE(ci.SetFullSuffix(false));
EXPECT_FALSE(ci.HasFullSuffix());
EXPECT_EQ(L"", ci.value());
EXPECT_FALSE(ci.SetFullSuffix(false));
EXPECT_FALSE(ci.HasFullSuffix());
EXPECT_EQ(L"", ci.value());
ci.set_value(L"2.0-beta");
EXPECT_TRUE(ci.SetFullSuffix(true));
EXPECT_TRUE(ci.HasFullSuffix());
EXPECT_EQ(L"2.0-beta-full", ci.value());
EXPECT_FALSE(ci.SetFullSuffix(true));
EXPECT_TRUE(ci.HasFullSuffix());
EXPECT_EQ(L"2.0-beta-full", ci.value());
EXPECT_TRUE(ci.SetFullSuffix(false));
EXPECT_FALSE(ci.HasFullSuffix());
EXPECT_EQ(L"2.0-beta", ci.value());
EXPECT_FALSE(ci.SetFullSuffix(false));
EXPECT_FALSE(ci.HasFullSuffix());
EXPECT_EQ(L"2.0-beta", ci.value());
}
TEST(ChannelInfoTest, MultiInstall) {
ChannelInfo ci;
ci.set_value(L"");
EXPECT_TRUE(ci.SetMultiInstall(true));
EXPECT_TRUE(ci.IsMultiInstall());
EXPECT_EQ(L"-multi", ci.value());
EXPECT_FALSE(ci.SetMultiInstall(true));
EXPECT_TRUE(ci.IsMultiInstall());
EXPECT_EQ(L"-multi", ci.value());
EXPECT_TRUE(ci.SetMultiInstall(false));
EXPECT_FALSE(ci.IsMultiInstall());
EXPECT_EQ(L"", ci.value());
EXPECT_FALSE(ci.SetMultiInstall(false));
EXPECT_FALSE(ci.IsMultiInstall());
EXPECT_EQ(L"", ci.value());
ci.set_value(L"2.0-beta");
EXPECT_TRUE(ci.SetMultiInstall(true));
EXPECT_TRUE(ci.IsMultiInstall());
EXPECT_EQ(L"2.0-beta-multi", ci.value());
EXPECT_FALSE(ci.SetMultiInstall(true));
EXPECT_TRUE(ci.IsMultiInstall());
EXPECT_EQ(L"2.0-beta-multi", ci.value());
EXPECT_TRUE(ci.SetMultiInstall(false));
EXPECT_FALSE(ci.IsMultiInstall());
EXPECT_EQ(L"2.0-beta", ci.value());
EXPECT_FALSE(ci.SetMultiInstall(false));
EXPECT_FALSE(ci.IsMultiInstall());
EXPECT_EQ(L"2.0-beta", ci.value());
}
TEST(ChannelInfoTest, Migration) {
ChannelInfo ci;
ci.set_value(L"");
EXPECT_TRUE(ci.SetMigratingSuffix(true));
EXPECT_TRUE(ci.HasMigratingSuffix());
EXPECT_EQ(L"-migrating", ci.value());
EXPECT_FALSE(ci.SetMigratingSuffix(true));
EXPECT_TRUE(ci.HasMigratingSuffix());
EXPECT_EQ(L"-migrating", ci.value());
EXPECT_TRUE(ci.SetMigratingSuffix(false));
EXPECT_FALSE(ci.HasMigratingSuffix());
EXPECT_EQ(L"", ci.value());
EXPECT_FALSE(ci.SetMigratingSuffix(false));
EXPECT_FALSE(ci.HasMigratingSuffix());
EXPECT_EQ(L"", ci.value());
ci.set_value(L"2.0-beta");
EXPECT_TRUE(ci.SetMigratingSuffix(true));
EXPECT_TRUE(ci.HasMigratingSuffix());
EXPECT_EQ(L"2.0-beta-migrating", ci.value());
EXPECT_FALSE(ci.SetMigratingSuffix(true));
EXPECT_TRUE(ci.HasMigratingSuffix());
EXPECT_EQ(L"2.0-beta-migrating", ci.value());
EXPECT_TRUE(ci.SetMigratingSuffix(false));
EXPECT_FALSE(ci.HasMigratingSuffix());
EXPECT_EQ(L"2.0-beta", ci.value());
EXPECT_FALSE(ci.SetMigratingSuffix(false));
EXPECT_FALSE(ci.HasMigratingSuffix());
EXPECT_EQ(L"2.0-beta", ci.value());
}
TEST(ChannelInfoTest, Combinations) {
ChannelInfo ci;
ci.set_value(L"2.0-beta-chromeframe");
EXPECT_FALSE(ci.IsChrome());
ci.set_value(L"2.0-beta-chromeframe-chrome");
EXPECT_TRUE(ci.IsChrome());
}
TEST(ChannelInfoTest, ClearStage) {
ChannelInfo ci;
ci.set_value(L"");
EXPECT_FALSE(ci.ClearStage());
EXPECT_EQ(L"", ci.value());
ci.set_value(L"-stage:spammy");
EXPECT_TRUE(ci.ClearStage());
EXPECT_EQ(L"", ci.value());
ci.set_value(L"-multi");
EXPECT_FALSE(ci.ClearStage());
EXPECT_EQ(L"-multi", ci.value());
ci.set_value(L"-stage:spammy-multi");
EXPECT_TRUE(ci.ClearStage());
EXPECT_EQ(L"-multi", ci.value());
ci.set_value(L"2.0-beta-multi");
EXPECT_FALSE(ci.ClearStage());
EXPECT_EQ(L"2.0-beta-multi", ci.value());
ci.set_value(L"2.0-beta-stage:spammy-multi");
EXPECT_TRUE(ci.ClearStage());
EXPECT_EQ(L"2.0-beta-multi", ci.value());
ci.set_value(L"2.0-beta-stage:-multi");
EXPECT_TRUE(ci.ClearStage());
EXPECT_EQ(L"2.0-beta-multi", ci.value());
}
TEST(ChannelInfoTest, GetStatsDefault) {
const base::string16 base_values[] = {
L"", L"x64-stable", L"1.1-beta", L"x64-beta", L"2.0-dev", L"x64-dev",
};
const base::string16 suffixes[] = {L"", L"-multi", L"-multi-chrome"};
for (const auto& base_value : base_values) {
for (const auto& suffix : suffixes) {
ChannelInfo ci;
base::string16 channel;
ci.set_value(base_value + suffix);
EXPECT_EQ(L"", ci.GetStatsDefault());
ci.set_value(base_value + L"-statsdef" + suffix);
EXPECT_EQ(L"", ci.GetStatsDefault());
ci.set_value(base_value + L"-statsdef_" + suffix);
EXPECT_EQ(L"", ci.GetStatsDefault());
ci.set_value(base_value + L"-statsdef_0" + suffix);
EXPECT_EQ(L"0", ci.GetStatsDefault());
ci.set_value(base_value + L"-statsdef_1" + suffix);
EXPECT_EQ(L"1", ci.GetStatsDefault());
}
}
}
TEST(ChannelInfoTest, RemoveAllModifiersAndSuffixes) {
ChannelInfo ci;
ci.set_value(L"");
EXPECT_FALSE(ci.RemoveAllModifiersAndSuffixes());
EXPECT_EQ(L"", ci.value());
ci.set_value(L"2.0-dev-multi-chrome-chromeframe-migrating");
EXPECT_TRUE(ci.RemoveAllModifiersAndSuffixes());
EXPECT_EQ(L"2.0-dev", ci.value());
}
| 2,578 |
606 | <filename>base/src/main/java/org/arend/term/abs/AbstractLevelExpressionVisitor.java
package org.arend.term.abs;
import org.arend.naming.reference.Referable;
import org.jetbrains.annotations.Nullable;
public interface AbstractLevelExpressionVisitor<P, R> {
R visitInf(@Nullable Object data, P param);
R visitLP(@Nullable Object data, P param);
R visitLH(@Nullable Object data, P param);
R visitNumber(@Nullable Object data, int number, P param);
R visitId(@Nullable Object data, Referable ref, P param);
R visitSuc(@Nullable Object data, /* @NotNull */ @Nullable Abstract.LevelExpression expr, P param);
R visitMax(@Nullable Object data, /* @NotNull */ @Nullable Abstract.LevelExpression left, /* @NotNull */ @Nullable Abstract.LevelExpression right, P param);
R visitError(@Nullable Object data, P param);
}
| 262 |
2,151 | // 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 THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_REPORTING_CONTEXT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_REPORTING_CONTEXT_H_
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/supplementable.h"
namespace blink {
class ExecutionContext;
class Report;
class ReportingObserver;
// ReportingContext is used as a container for all active ReportingObservers for
// an ExecutionContext.
class CORE_EXPORT ReportingContext final
: public GarbageCollectedFinalized<ReportingContext>,
public Supplement<ExecutionContext> {
USING_GARBAGE_COLLECTED_MIXIN(ReportingContext)
public:
static const char kSupplementName[];
explicit ReportingContext(ExecutionContext&);
// Returns the ReportingContext for an ExecutionContext. If one does not
// already exist for the given context, one is created.
static ReportingContext* From(ExecutionContext*);
// Queues a report to be reported to all observers.
void QueueReport(Report*);
// Sends all queued reports to all observers.
void SendReports();
void RegisterObserver(ReportingObserver*);
void UnregisterObserver(ReportingObserver*);
// Returns whether there is at least one active ReportingObserver.
bool ObserverExists();
void Trace(blink::Visitor*) override;
private:
HeapListHashSet<Member<ReportingObserver>> observers_;
HeapVector<Member<Report>> reports_;
Member<ExecutionContext> execution_context_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_REPORTING_CONTEXT_H_
| 548 |
14,668 | // 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.
#ifndef CHROME_BROWSER_ASH_APP_MODE_ARC_ARC_KIOSK_APP_LAUNCHER_H_
#define CHROME_BROWSER_ASH_APP_MODE_ARC_ARC_KIOSK_APP_LAUNCHER_H_
#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
#include "components/exo/wm_helper.h"
#include "ui/aura/env_observer.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
namespace ash {
// Starts Android app in kiosk mode.
// Keeps track of start progress and pins app window
// when it's finally opened.
class ArcKioskAppLauncher : public ArcAppListPrefs::Observer,
public exo::WMHelper::ExoWindowObserver,
public aura::WindowObserver {
public:
class Delegate {
public:
Delegate() = default;
Delegate(const Delegate&) = delete;
Delegate& operator=(const Delegate&) = delete;
virtual void OnAppWindowLaunched() = 0;
protected:
virtual ~Delegate() = default;
};
ArcKioskAppLauncher(content::BrowserContext* context,
ArcAppListPrefs* prefs,
const std::string& app_id,
Delegate* delegate);
ArcKioskAppLauncher(const ArcKioskAppLauncher&) = delete;
ArcKioskAppLauncher& operator=(const ArcKioskAppLauncher&) = delete;
~ArcKioskAppLauncher() override;
// ArcAppListPrefs::Observer overrides.
void OnTaskCreated(int32_t task_id,
const std::string& package_name,
const std::string& activity,
const std::string& intent,
int32_t session_id) override;
// exo::WMHelper::ExoWindowObserver
void OnExoWindowCreated(aura::Window* window) override;
// aura::WindowObserver overrides.
void OnWindowDestroying(aura::Window* window) override;
private:
// Check whether it's the app's window and pins it.
bool CheckAndPinWindow(aura::Window* const window);
void StopObserving();
const std::string app_id_;
ArcAppListPrefs* const prefs_;
int task_id_ = -1;
std::set<aura::Window*> windows_;
// Not owning the delegate, delegate owns this class.
Delegate* const delegate_;
};
} // namespace ash
#endif // CHROME_BROWSER_ASH_APP_MODE_ARC_ARC_KIOSK_APP_LAUNCHER_H_
| 945 |
393 | <filename>src/TopicModel/PA.h
#pragma once
#include "LDA.h"
namespace tomoto
{
template<TermWeight _tw>
struct DocumentPA : public DocumentLDA<_tw>
{
using BaseDocument = DocumentLDA<_tw>;
using DocumentLDA<_tw>::DocumentLDA;
using WeightType = typename DocumentLDA<_tw>::WeightType;
tvector<Tid> Z2s;
Eigen::Matrix<WeightType, -1, -1> numByTopic1_2;
template<typename _TopicModel> void update(WeightType* ptr, const _TopicModel& mdl);
DEFINE_SERIALIZER_AFTER_BASE_WITH_VERSION(BaseDocument, 0, Z2s);
DEFINE_TAGGED_SERIALIZER_AFTER_BASE_WITH_VERSION(BaseDocument, 1, 0x00010001, Z2s);
};
struct PAArgs : public LDAArgs
{
size_t k2 = 1;
std::vector<Float> subalpha = { 0.1 };
};
class IPAModel : public ILDAModel
{
public:
using DefaultDocType = DocumentPA<TermWeight::one>;
static IPAModel* create(TermWeight _weight, const PAArgs& args,
bool scalarRng = false);
virtual size_t getDirichletEstIteration() const = 0;
virtual void setDirichletEstIteration(size_t iter) = 0;
virtual size_t getK2() const = 0;
virtual Float getSubAlpha(Tid k1, Tid k2) const = 0;
virtual std::vector<Float> getSubAlpha(Tid k1) const = 0;
virtual std::vector<Float> getSubTopicBySuperTopic(Tid k, bool normalize = true) const = 0;
virtual std::vector<std::pair<Tid, Float>> getSubTopicBySuperTopicSorted(Tid k, size_t topN) const = 0;
virtual std::vector<Float> getSubTopicsByDoc(const DocumentBase* doc, bool normalize = true) const = 0;
virtual std::vector<std::pair<Tid, Float>> getSubTopicsByDocSorted(const DocumentBase* doc, size_t topN) const = 0;
virtual std::vector<uint64_t> getCountBySuperTopic() const = 0;
};
}
| 648 |
375 | /*
* Copyright 2016 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.robotframework.ide.eclipse.main.plugin.model.cmd.settings;
import java.util.List;
import java.util.Objects;
import org.rf.ide.core.testdata.model.IDocumentationHolder;
import org.rf.ide.core.testdata.model.presenter.DocumentationServiceHandler;
import org.robotframework.ide.eclipse.main.plugin.model.RobotModelEvents;
import org.robotframework.ide.eclipse.main.plugin.model.RobotSetting;
import org.robotframework.ide.eclipse.main.plugin.tableeditor.EditorCommand;
public class SetDocumentationCommand extends EditorCommand {
private final RobotSetting docSetting;
private final String value;
private String oldDoc;
public SetDocumentationCommand(final RobotSetting docSetting, final String value) {
this.docSetting = docSetting;
this.value = value;
}
@Override
public void execute() throws CommandExecutionException {
final IDocumentationHolder docHolder = (IDocumentationHolder) docSetting.getLinkedElement();
oldDoc = DocumentationServiceHandler.toEditConsolidated(docHolder);
if (!Objects.equals(value, oldDoc)) {
DocumentationServiceHandler.update(docHolder, value);
eventBroker.send(RobotModelEvents.ROBOT_KEYWORD_CALL_ARGUMENT_CHANGE, docSetting);
}
}
@Override
public List<EditorCommand> getUndoCommands() {
return newUndoCommands(new SetDocumentationCommand(docSetting, oldDoc));
}
}
| 582 |
3,372 | <gh_stars>1000+
/*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.lexmodelsv2.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/models.lex.v2-2020-08-07/DescribeBotLocale" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeBotLocaleResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The identifier of the bot associated with the locale.
* </p>
*/
private String botId;
/**
* <p>
* The identifier of the version of the bot associated with the locale.
* </p>
*/
private String botVersion;
/**
* <p>
* The unique identifier of the described locale.
* </p>
*/
private String localeId;
/**
* <p>
* The name of the locale.
* </p>
*/
private String localeName;
/**
* <p>
* The description of the locale.
* </p>
*/
private String description;
/**
* <p>
* The confidence threshold where Amazon Lex inserts the <code>AMAZON.FallbackIntent</code> and
* <code>AMAZON.KendraSearchIntent</code> intents in the list of possible intents for an utterance.
* </p>
*/
private Double nluIntentConfidenceThreshold;
/**
* <p>
* The Amazon Polly voice Amazon Lex uses for voice interaction with the user.
* </p>
*/
private VoiceSettings voiceSettings;
/**
* <p>
* The number of intents defined for the locale.
* </p>
*/
private Integer intentsCount;
/**
* <p>
* The number of slot types defined for the locale.
* </p>
*/
private Integer slotTypesCount;
/**
* <p>
* The status of the bot. If the status is <code>Failed</code>, the reasons for the failure are listed in the
* <code>failureReasons</code> field.
* </p>
*/
private String botLocaleStatus;
/**
* <p>
* if <code>botLocaleStatus</code> is <code>Failed</code>, Amazon Lex explains why it failed to build the bot.
* </p>
*/
private java.util.List<String> failureReasons;
/**
* <p>
* The date and time that the locale was created.
* </p>
*/
private java.util.Date creationDateTime;
/**
* <p>
* The date and time that the locale was last updated.
* </p>
*/
private java.util.Date lastUpdatedDateTime;
/**
* <p>
* The date and time that the locale was last submitted for building.
* </p>
*/
private java.util.Date lastBuildSubmittedDateTime;
/**
* <p>
* History of changes, such as when a locale is used in an alias, that have taken place for the locale.
* </p>
*/
private java.util.List<BotLocaleHistoryEvent> botLocaleHistoryEvents;
/**
* <p>
* The identifier of the bot associated with the locale.
* </p>
*
* @param botId
* The identifier of the bot associated with the locale.
*/
public void setBotId(String botId) {
this.botId = botId;
}
/**
* <p>
* The identifier of the bot associated with the locale.
* </p>
*
* @return The identifier of the bot associated with the locale.
*/
public String getBotId() {
return this.botId;
}
/**
* <p>
* The identifier of the bot associated with the locale.
* </p>
*
* @param botId
* The identifier of the bot associated with the locale.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withBotId(String botId) {
setBotId(botId);
return this;
}
/**
* <p>
* The identifier of the version of the bot associated with the locale.
* </p>
*
* @param botVersion
* The identifier of the version of the bot associated with the locale.
*/
public void setBotVersion(String botVersion) {
this.botVersion = botVersion;
}
/**
* <p>
* The identifier of the version of the bot associated with the locale.
* </p>
*
* @return The identifier of the version of the bot associated with the locale.
*/
public String getBotVersion() {
return this.botVersion;
}
/**
* <p>
* The identifier of the version of the bot associated with the locale.
* </p>
*
* @param botVersion
* The identifier of the version of the bot associated with the locale.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withBotVersion(String botVersion) {
setBotVersion(botVersion);
return this;
}
/**
* <p>
* The unique identifier of the described locale.
* </p>
*
* @param localeId
* The unique identifier of the described locale.
*/
public void setLocaleId(String localeId) {
this.localeId = localeId;
}
/**
* <p>
* The unique identifier of the described locale.
* </p>
*
* @return The unique identifier of the described locale.
*/
public String getLocaleId() {
return this.localeId;
}
/**
* <p>
* The unique identifier of the described locale.
* </p>
*
* @param localeId
* The unique identifier of the described locale.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withLocaleId(String localeId) {
setLocaleId(localeId);
return this;
}
/**
* <p>
* The name of the locale.
* </p>
*
* @param localeName
* The name of the locale.
*/
public void setLocaleName(String localeName) {
this.localeName = localeName;
}
/**
* <p>
* The name of the locale.
* </p>
*
* @return The name of the locale.
*/
public String getLocaleName() {
return this.localeName;
}
/**
* <p>
* The name of the locale.
* </p>
*
* @param localeName
* The name of the locale.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withLocaleName(String localeName) {
setLocaleName(localeName);
return this;
}
/**
* <p>
* The description of the locale.
* </p>
*
* @param description
* The description of the locale.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The description of the locale.
* </p>
*
* @return The description of the locale.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The description of the locale.
* </p>
*
* @param description
* The description of the locale.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The confidence threshold where Amazon Lex inserts the <code>AMAZON.FallbackIntent</code> and
* <code>AMAZON.KendraSearchIntent</code> intents in the list of possible intents for an utterance.
* </p>
*
* @param nluIntentConfidenceThreshold
* The confidence threshold where Amazon Lex inserts the <code>AMAZON.FallbackIntent</code> and
* <code>AMAZON.KendraSearchIntent</code> intents in the list of possible intents for an utterance.
*/
public void setNluIntentConfidenceThreshold(Double nluIntentConfidenceThreshold) {
this.nluIntentConfidenceThreshold = nluIntentConfidenceThreshold;
}
/**
* <p>
* The confidence threshold where Amazon Lex inserts the <code>AMAZON.FallbackIntent</code> and
* <code>AMAZON.KendraSearchIntent</code> intents in the list of possible intents for an utterance.
* </p>
*
* @return The confidence threshold where Amazon Lex inserts the <code>AMAZON.FallbackIntent</code> and
* <code>AMAZON.KendraSearchIntent</code> intents in the list of possible intents for an utterance.
*/
public Double getNluIntentConfidenceThreshold() {
return this.nluIntentConfidenceThreshold;
}
/**
* <p>
* The confidence threshold where Amazon Lex inserts the <code>AMAZON.FallbackIntent</code> and
* <code>AMAZON.KendraSearchIntent</code> intents in the list of possible intents for an utterance.
* </p>
*
* @param nluIntentConfidenceThreshold
* The confidence threshold where Amazon Lex inserts the <code>AMAZON.FallbackIntent</code> and
* <code>AMAZON.KendraSearchIntent</code> intents in the list of possible intents for an utterance.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withNluIntentConfidenceThreshold(Double nluIntentConfidenceThreshold) {
setNluIntentConfidenceThreshold(nluIntentConfidenceThreshold);
return this;
}
/**
* <p>
* The Amazon Polly voice Amazon Lex uses for voice interaction with the user.
* </p>
*
* @param voiceSettings
* The Amazon Polly voice Amazon Lex uses for voice interaction with the user.
*/
public void setVoiceSettings(VoiceSettings voiceSettings) {
this.voiceSettings = voiceSettings;
}
/**
* <p>
* The Amazon Polly voice Amazon Lex uses for voice interaction with the user.
* </p>
*
* @return The Amazon Polly voice Amazon Lex uses for voice interaction with the user.
*/
public VoiceSettings getVoiceSettings() {
return this.voiceSettings;
}
/**
* <p>
* The Amazon Polly voice Amazon Lex uses for voice interaction with the user.
* </p>
*
* @param voiceSettings
* The Amazon Polly voice Amazon Lex uses for voice interaction with the user.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withVoiceSettings(VoiceSettings voiceSettings) {
setVoiceSettings(voiceSettings);
return this;
}
/**
* <p>
* The number of intents defined for the locale.
* </p>
*
* @param intentsCount
* The number of intents defined for the locale.
*/
public void setIntentsCount(Integer intentsCount) {
this.intentsCount = intentsCount;
}
/**
* <p>
* The number of intents defined for the locale.
* </p>
*
* @return The number of intents defined for the locale.
*/
public Integer getIntentsCount() {
return this.intentsCount;
}
/**
* <p>
* The number of intents defined for the locale.
* </p>
*
* @param intentsCount
* The number of intents defined for the locale.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withIntentsCount(Integer intentsCount) {
setIntentsCount(intentsCount);
return this;
}
/**
* <p>
* The number of slot types defined for the locale.
* </p>
*
* @param slotTypesCount
* The number of slot types defined for the locale.
*/
public void setSlotTypesCount(Integer slotTypesCount) {
this.slotTypesCount = slotTypesCount;
}
/**
* <p>
* The number of slot types defined for the locale.
* </p>
*
* @return The number of slot types defined for the locale.
*/
public Integer getSlotTypesCount() {
return this.slotTypesCount;
}
/**
* <p>
* The number of slot types defined for the locale.
* </p>
*
* @param slotTypesCount
* The number of slot types defined for the locale.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withSlotTypesCount(Integer slotTypesCount) {
setSlotTypesCount(slotTypesCount);
return this;
}
/**
* <p>
* The status of the bot. If the status is <code>Failed</code>, the reasons for the failure are listed in the
* <code>failureReasons</code> field.
* </p>
*
* @param botLocaleStatus
* The status of the bot. If the status is <code>Failed</code>, the reasons for the failure are listed in the
* <code>failureReasons</code> field.
* @see BotLocaleStatus
*/
public void setBotLocaleStatus(String botLocaleStatus) {
this.botLocaleStatus = botLocaleStatus;
}
/**
* <p>
* The status of the bot. If the status is <code>Failed</code>, the reasons for the failure are listed in the
* <code>failureReasons</code> field.
* </p>
*
* @return The status of the bot. If the status is <code>Failed</code>, the reasons for the failure are listed in
* the <code>failureReasons</code> field.
* @see BotLocaleStatus
*/
public String getBotLocaleStatus() {
return this.botLocaleStatus;
}
/**
* <p>
* The status of the bot. If the status is <code>Failed</code>, the reasons for the failure are listed in the
* <code>failureReasons</code> field.
* </p>
*
* @param botLocaleStatus
* The status of the bot. If the status is <code>Failed</code>, the reasons for the failure are listed in the
* <code>failureReasons</code> field.
* @return Returns a reference to this object so that method calls can be chained together.
* @see BotLocaleStatus
*/
public DescribeBotLocaleResult withBotLocaleStatus(String botLocaleStatus) {
setBotLocaleStatus(botLocaleStatus);
return this;
}
/**
* <p>
* The status of the bot. If the status is <code>Failed</code>, the reasons for the failure are listed in the
* <code>failureReasons</code> field.
* </p>
*
* @param botLocaleStatus
* The status of the bot. If the status is <code>Failed</code>, the reasons for the failure are listed in the
* <code>failureReasons</code> field.
* @return Returns a reference to this object so that method calls can be chained together.
* @see BotLocaleStatus
*/
public DescribeBotLocaleResult withBotLocaleStatus(BotLocaleStatus botLocaleStatus) {
this.botLocaleStatus = botLocaleStatus.toString();
return this;
}
/**
* <p>
* if <code>botLocaleStatus</code> is <code>Failed</code>, Amazon Lex explains why it failed to build the bot.
* </p>
*
* @return if <code>botLocaleStatus</code> is <code>Failed</code>, Amazon Lex explains why it failed to build the
* bot.
*/
public java.util.List<String> getFailureReasons() {
return failureReasons;
}
/**
* <p>
* if <code>botLocaleStatus</code> is <code>Failed</code>, Amazon Lex explains why it failed to build the bot.
* </p>
*
* @param failureReasons
* if <code>botLocaleStatus</code> is <code>Failed</code>, Amazon Lex explains why it failed to build the
* bot.
*/
public void setFailureReasons(java.util.Collection<String> failureReasons) {
if (failureReasons == null) {
this.failureReasons = null;
return;
}
this.failureReasons = new java.util.ArrayList<String>(failureReasons);
}
/**
* <p>
* if <code>botLocaleStatus</code> is <code>Failed</code>, Amazon Lex explains why it failed to build the bot.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setFailureReasons(java.util.Collection)} or {@link #withFailureReasons(java.util.Collection)} if you want
* to override the existing values.
* </p>
*
* @param failureReasons
* if <code>botLocaleStatus</code> is <code>Failed</code>, Amazon Lex explains why it failed to build the
* bot.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withFailureReasons(String... failureReasons) {
if (this.failureReasons == null) {
setFailureReasons(new java.util.ArrayList<String>(failureReasons.length));
}
for (String ele : failureReasons) {
this.failureReasons.add(ele);
}
return this;
}
/**
* <p>
* if <code>botLocaleStatus</code> is <code>Failed</code>, Amazon Lex explains why it failed to build the bot.
* </p>
*
* @param failureReasons
* if <code>botLocaleStatus</code> is <code>Failed</code>, Amazon Lex explains why it failed to build the
* bot.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withFailureReasons(java.util.Collection<String> failureReasons) {
setFailureReasons(failureReasons);
return this;
}
/**
* <p>
* The date and time that the locale was created.
* </p>
*
* @param creationDateTime
* The date and time that the locale was created.
*/
public void setCreationDateTime(java.util.Date creationDateTime) {
this.creationDateTime = creationDateTime;
}
/**
* <p>
* The date and time that the locale was created.
* </p>
*
* @return The date and time that the locale was created.
*/
public java.util.Date getCreationDateTime() {
return this.creationDateTime;
}
/**
* <p>
* The date and time that the locale was created.
* </p>
*
* @param creationDateTime
* The date and time that the locale was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withCreationDateTime(java.util.Date creationDateTime) {
setCreationDateTime(creationDateTime);
return this;
}
/**
* <p>
* The date and time that the locale was last updated.
* </p>
*
* @param lastUpdatedDateTime
* The date and time that the locale was last updated.
*/
public void setLastUpdatedDateTime(java.util.Date lastUpdatedDateTime) {
this.lastUpdatedDateTime = lastUpdatedDateTime;
}
/**
* <p>
* The date and time that the locale was last updated.
* </p>
*
* @return The date and time that the locale was last updated.
*/
public java.util.Date getLastUpdatedDateTime() {
return this.lastUpdatedDateTime;
}
/**
* <p>
* The date and time that the locale was last updated.
* </p>
*
* @param lastUpdatedDateTime
* The date and time that the locale was last updated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withLastUpdatedDateTime(java.util.Date lastUpdatedDateTime) {
setLastUpdatedDateTime(lastUpdatedDateTime);
return this;
}
/**
* <p>
* The date and time that the locale was last submitted for building.
* </p>
*
* @param lastBuildSubmittedDateTime
* The date and time that the locale was last submitted for building.
*/
public void setLastBuildSubmittedDateTime(java.util.Date lastBuildSubmittedDateTime) {
this.lastBuildSubmittedDateTime = lastBuildSubmittedDateTime;
}
/**
* <p>
* The date and time that the locale was last submitted for building.
* </p>
*
* @return The date and time that the locale was last submitted for building.
*/
public java.util.Date getLastBuildSubmittedDateTime() {
return this.lastBuildSubmittedDateTime;
}
/**
* <p>
* The date and time that the locale was last submitted for building.
* </p>
*
* @param lastBuildSubmittedDateTime
* The date and time that the locale was last submitted for building.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withLastBuildSubmittedDateTime(java.util.Date lastBuildSubmittedDateTime) {
setLastBuildSubmittedDateTime(lastBuildSubmittedDateTime);
return this;
}
/**
* <p>
* History of changes, such as when a locale is used in an alias, that have taken place for the locale.
* </p>
*
* @return History of changes, such as when a locale is used in an alias, that have taken place for the locale.
*/
public java.util.List<BotLocaleHistoryEvent> getBotLocaleHistoryEvents() {
return botLocaleHistoryEvents;
}
/**
* <p>
* History of changes, such as when a locale is used in an alias, that have taken place for the locale.
* </p>
*
* @param botLocaleHistoryEvents
* History of changes, such as when a locale is used in an alias, that have taken place for the locale.
*/
public void setBotLocaleHistoryEvents(java.util.Collection<BotLocaleHistoryEvent> botLocaleHistoryEvents) {
if (botLocaleHistoryEvents == null) {
this.botLocaleHistoryEvents = null;
return;
}
this.botLocaleHistoryEvents = new java.util.ArrayList<BotLocaleHistoryEvent>(botLocaleHistoryEvents);
}
/**
* <p>
* History of changes, such as when a locale is used in an alias, that have taken place for the locale.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setBotLocaleHistoryEvents(java.util.Collection)} or
* {@link #withBotLocaleHistoryEvents(java.util.Collection)} if you want to override the existing values.
* </p>
*
* @param botLocaleHistoryEvents
* History of changes, such as when a locale is used in an alias, that have taken place for the locale.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withBotLocaleHistoryEvents(BotLocaleHistoryEvent... botLocaleHistoryEvents) {
if (this.botLocaleHistoryEvents == null) {
setBotLocaleHistoryEvents(new java.util.ArrayList<BotLocaleHistoryEvent>(botLocaleHistoryEvents.length));
}
for (BotLocaleHistoryEvent ele : botLocaleHistoryEvents) {
this.botLocaleHistoryEvents.add(ele);
}
return this;
}
/**
* <p>
* History of changes, such as when a locale is used in an alias, that have taken place for the locale.
* </p>
*
* @param botLocaleHistoryEvents
* History of changes, such as when a locale is used in an alias, that have taken place for the locale.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeBotLocaleResult withBotLocaleHistoryEvents(java.util.Collection<BotLocaleHistoryEvent> botLocaleHistoryEvents) {
setBotLocaleHistoryEvents(botLocaleHistoryEvents);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getBotId() != null)
sb.append("BotId: ").append(getBotId()).append(",");
if (getBotVersion() != null)
sb.append("BotVersion: ").append(getBotVersion()).append(",");
if (getLocaleId() != null)
sb.append("LocaleId: ").append(getLocaleId()).append(",");
if (getLocaleName() != null)
sb.append("LocaleName: ").append(getLocaleName()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getNluIntentConfidenceThreshold() != null)
sb.append("NluIntentConfidenceThreshold: ").append(getNluIntentConfidenceThreshold()).append(",");
if (getVoiceSettings() != null)
sb.append("VoiceSettings: ").append(getVoiceSettings()).append(",");
if (getIntentsCount() != null)
sb.append("IntentsCount: ").append(getIntentsCount()).append(",");
if (getSlotTypesCount() != null)
sb.append("SlotTypesCount: ").append(getSlotTypesCount()).append(",");
if (getBotLocaleStatus() != null)
sb.append("BotLocaleStatus: ").append(getBotLocaleStatus()).append(",");
if (getFailureReasons() != null)
sb.append("FailureReasons: ").append(getFailureReasons()).append(",");
if (getCreationDateTime() != null)
sb.append("CreationDateTime: ").append(getCreationDateTime()).append(",");
if (getLastUpdatedDateTime() != null)
sb.append("LastUpdatedDateTime: ").append(getLastUpdatedDateTime()).append(",");
if (getLastBuildSubmittedDateTime() != null)
sb.append("LastBuildSubmittedDateTime: ").append(getLastBuildSubmittedDateTime()).append(",");
if (getBotLocaleHistoryEvents() != null)
sb.append("BotLocaleHistoryEvents: ").append(getBotLocaleHistoryEvents());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeBotLocaleResult == false)
return false;
DescribeBotLocaleResult other = (DescribeBotLocaleResult) obj;
if (other.getBotId() == null ^ this.getBotId() == null)
return false;
if (other.getBotId() != null && other.getBotId().equals(this.getBotId()) == false)
return false;
if (other.getBotVersion() == null ^ this.getBotVersion() == null)
return false;
if (other.getBotVersion() != null && other.getBotVersion().equals(this.getBotVersion()) == false)
return false;
if (other.getLocaleId() == null ^ this.getLocaleId() == null)
return false;
if (other.getLocaleId() != null && other.getLocaleId().equals(this.getLocaleId()) == false)
return false;
if (other.getLocaleName() == null ^ this.getLocaleName() == null)
return false;
if (other.getLocaleName() != null && other.getLocaleName().equals(this.getLocaleName()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getNluIntentConfidenceThreshold() == null ^ this.getNluIntentConfidenceThreshold() == null)
return false;
if (other.getNluIntentConfidenceThreshold() != null && other.getNluIntentConfidenceThreshold().equals(this.getNluIntentConfidenceThreshold()) == false)
return false;
if (other.getVoiceSettings() == null ^ this.getVoiceSettings() == null)
return false;
if (other.getVoiceSettings() != null && other.getVoiceSettings().equals(this.getVoiceSettings()) == false)
return false;
if (other.getIntentsCount() == null ^ this.getIntentsCount() == null)
return false;
if (other.getIntentsCount() != null && other.getIntentsCount().equals(this.getIntentsCount()) == false)
return false;
if (other.getSlotTypesCount() == null ^ this.getSlotTypesCount() == null)
return false;
if (other.getSlotTypesCount() != null && other.getSlotTypesCount().equals(this.getSlotTypesCount()) == false)
return false;
if (other.getBotLocaleStatus() == null ^ this.getBotLocaleStatus() == null)
return false;
if (other.getBotLocaleStatus() != null && other.getBotLocaleStatus().equals(this.getBotLocaleStatus()) == false)
return false;
if (other.getFailureReasons() == null ^ this.getFailureReasons() == null)
return false;
if (other.getFailureReasons() != null && other.getFailureReasons().equals(this.getFailureReasons()) == false)
return false;
if (other.getCreationDateTime() == null ^ this.getCreationDateTime() == null)
return false;
if (other.getCreationDateTime() != null && other.getCreationDateTime().equals(this.getCreationDateTime()) == false)
return false;
if (other.getLastUpdatedDateTime() == null ^ this.getLastUpdatedDateTime() == null)
return false;
if (other.getLastUpdatedDateTime() != null && other.getLastUpdatedDateTime().equals(this.getLastUpdatedDateTime()) == false)
return false;
if (other.getLastBuildSubmittedDateTime() == null ^ this.getLastBuildSubmittedDateTime() == null)
return false;
if (other.getLastBuildSubmittedDateTime() != null && other.getLastBuildSubmittedDateTime().equals(this.getLastBuildSubmittedDateTime()) == false)
return false;
if (other.getBotLocaleHistoryEvents() == null ^ this.getBotLocaleHistoryEvents() == null)
return false;
if (other.getBotLocaleHistoryEvents() != null && other.getBotLocaleHistoryEvents().equals(this.getBotLocaleHistoryEvents()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getBotId() == null) ? 0 : getBotId().hashCode());
hashCode = prime * hashCode + ((getBotVersion() == null) ? 0 : getBotVersion().hashCode());
hashCode = prime * hashCode + ((getLocaleId() == null) ? 0 : getLocaleId().hashCode());
hashCode = prime * hashCode + ((getLocaleName() == null) ? 0 : getLocaleName().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getNluIntentConfidenceThreshold() == null) ? 0 : getNluIntentConfidenceThreshold().hashCode());
hashCode = prime * hashCode + ((getVoiceSettings() == null) ? 0 : getVoiceSettings().hashCode());
hashCode = prime * hashCode + ((getIntentsCount() == null) ? 0 : getIntentsCount().hashCode());
hashCode = prime * hashCode + ((getSlotTypesCount() == null) ? 0 : getSlotTypesCount().hashCode());
hashCode = prime * hashCode + ((getBotLocaleStatus() == null) ? 0 : getBotLocaleStatus().hashCode());
hashCode = prime * hashCode + ((getFailureReasons() == null) ? 0 : getFailureReasons().hashCode());
hashCode = prime * hashCode + ((getCreationDateTime() == null) ? 0 : getCreationDateTime().hashCode());
hashCode = prime * hashCode + ((getLastUpdatedDateTime() == null) ? 0 : getLastUpdatedDateTime().hashCode());
hashCode = prime * hashCode + ((getLastBuildSubmittedDateTime() == null) ? 0 : getLastBuildSubmittedDateTime().hashCode());
hashCode = prime * hashCode + ((getBotLocaleHistoryEvents() == null) ? 0 : getBotLocaleHistoryEvents().hashCode());
return hashCode;
}
@Override
public DescribeBotLocaleResult clone() {
try {
return (DescribeBotLocaleResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| 12,864 |
479 | <gh_stars>100-1000
import windows.pipe
from .pfwtest import *
import time
PIPE_NAME = "PFW_Test_Pipe"
rcode_test_ipc_pipe = """
import windows; import windows.pipe
windows.pipe.send_object("{pipe}", {{'Hello': 2}})
"""
@python_injection
def test_ipc_pipe(proc32_64):
with windows.pipe.create(PIPE_NAME) as np:
proc32_64.execute_python(rcode_test_ipc_pipe.format(pipe=PIPE_NAME))
obj = np.recv()
assert obj == {'Hello': 2}
rcode_test_echo_pipe = """
import windows; import windows.pipe
with windows.pipe.create("{pipe}") as np:
np.wait_connection()
obj = np.recv()
np.send(obj)
"""
@python_injection
def test_pipe_echo_server(proc32_64):
t = proc32_64.execute_python_unsafe(rcode_test_echo_pipe.format(pipe=PIPE_NAME))
time.sleep(0.5)
assert not t.is_exit
obj = {'MYPID': windows.current_process.pid}
pipe = windows.pipe.connect(PIPE_NAME)
pipe.send(obj)
echoobj = pipe.recv()
assert obj == echoobj
@python_injection
def test_pipe_recv_object(proc32_64):
# not the good way to do the exchange (race possible)
# Just for the sake of the test
proc32_64.execute_python_unsafe(rcode_test_ipc_pipe.format(pipe=PIPE_NAME))
obj = windows.pipe.recv_object(PIPE_NAME)
assert obj == {'Hello': 2}
| 538 |
5,941 | <reponame>PoseidonKEN/FreeRDP
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* Terminal Server Gateway (utils)
*
* Copyright 2021 <NAME> <<EMAIL>>
* Copyright 2021 Thincast Technologies GmbH
*
* 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.
*/
#ifndef FREERDP_LIB_CORE_UTILS_H
#define FREERDP_LIB_CORE_UTILS_H
#include <winpr/winpr.h>
#include <freerdp/freerdp.h>
typedef enum
{
AUTH_SUCCESS,
AUTH_SKIP,
AUTH_NO_CREDENTIALS,
AUTH_FAILED
} auth_status;
auth_status utils_authenticate_gateway(freerdp* instance, rdp_auth_reason reason);
auth_status utils_authenticate(freerdp* instance, rdp_auth_reason reason, BOOL override);
BOOL utils_sync_credentials(rdpSettings* settings, BOOL toGateway);
BOOL utils_str_is_empty(const char* str);
BOOL utils_str_copy(const char* value, char** dst);
#endif /* FREERDP_LIB_CORE_UTILS_H */
| 452 |
335 | {
"word": "Oxidase",
"definitions": [
"An enzyme which promotes the transfer of a hydrogen atom from a particular substrate to an oxygen molecule, forming water or hydrogen peroxide."
],
"parts-of-speech": "Noun"
} | 79 |
1,711 | /*
_____ _____ _____ __
| __| | | | | The SOUL language
|__ | | | | | |__ Copyright (c) 2019 - ROLI Ltd.
|_____|_____|_____|_____|
The code in this file is provided under the terms of the ISC license:
Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice and
this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 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.
*/
namespace soul
{
//==============================================================================
/** Represents a structure.
@see Type::createStruct()
*/
class Structure : public RefCountedObject
{
public:
Structure (std::string name, void* backlinkToASTObject);
Structure (const Structure&) = default;
Structure (Structure&&) = default;
Structure& operator= (const Structure&) = delete;
Structure& operator= (Structure&&) = delete;
struct Member
{
Type type;
std::string name;
ReadWriteCount readWriteCount;
};
bool empty() const { return members.empty(); }
const std::string& getName() const noexcept { return name; }
size_t getNumMembers() const { return members.size(); }
ArrayWithPreallocation<Member, 8>& getMembers() { return members; }
const ArrayWithPreallocation<Member, 8>& getMembers() const { return members; }
const Type& getMemberType (size_t i) const { return members[i].type; }
const std::string& getMemberName (size_t i) const { return members[i].name; }
const ReadWriteCount& getMemberReadWriteCount (size_t i) const { return members[i].readWriteCount; }
void removeMember (std::string_view memberName);
// Because the Structure class has no dependency on any AST classes,
// this opaque pointer is a necessary evil for us to provide a way to
// quickly trace a structure instance back to its originating AST object.
void* backlinkToASTObject = nullptr;
bool activeUseFlag = false;
Member& getMemberWithName (std::string_view memberName);
bool hasMemberWithName (std::string_view memberName) const;
size_t getMemberIndex (std::string_view memberName) const;
void addMember (Type, std::string memberName);
std::string addMemberWithUniqueName (Type, const std::string& memberName);
bool isEmpty() const noexcept;
uint64_t getPackedSizeInBytes() const;
void checkForRecursiveNestedStructs (const CodeLocation&);
bool containsMemberOfType (const Type& type, bool checkSubStructs) const;
void updateMemberType (std::string_view memberName, const Type& newType);
private:
ArrayWithPreallocation<Member, 8> members;
std::string name;
std::unordered_map<std::string, size_t> memberIndexMap;
};
} // namespace soul
| 1,185 |
674 | #ifndef HONEST_PROFILER_COMMON_H
#define HONEST_PROFILER_COMMON_H
#include <jvmti.h>
#include "globals.h"
jthread newThread(JNIEnv *jniEnv, const char *threadName);
JNIEnv *getJNIEnv(JavaVM *jvm);
#endif
| 101 |
338 | <reponame>XmobiTea-Family/ezyfox-server<gh_stars>100-1000
package com.tvd12.ezyfoxserver.testing.event;
import org.testng.annotations.Test;
import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason;
import com.tvd12.ezyfoxserver.entity.EzyUser;
import com.tvd12.ezyfoxserver.event.EzySimpleUserRemovedEvent;
import com.tvd12.ezyfoxserver.event.EzyUserRemovedEvent;
import com.tvd12.ezyfoxserver.testing.BaseCoreTest;
public class EzyDisconnectEventImplTest extends BaseCoreTest {
@Test
public void test() {
EzyUser user = newUser();
EzyUserRemovedEvent event = new EzySimpleUserRemovedEvent(
user, EzyDisconnectReason.IDLE);
assert event.getUser() == user;
assert event.getReason() == EzyDisconnectReason.IDLE;
}
}
| 309 |
11,396 | # Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
from django.db.migrations import Migration
class ActivityStreamDisabledMigration(Migration):
def apply(self, project_state, schema_editor, collect_sql=False):
from awx.main.signals import disable_activity_stream
with disable_activity_stream():
return Migration.apply(self, project_state, schema_editor, collect_sql)
| 135 |
2,002 | <filename>dev/MRTCore/mrt/mrm/mrmex/FileListBuilder.cpp
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#include "StdAfx.h"
namespace Microsoft::Resources::Build
{
/*!
* FileInfoPrivateData - abstract base class for per-file private data
*/
FileInfoPrivateData::FileInfoPrivateData(__in const void* pOwner, __in int index) : m_pOwner(pOwner), m_index(index), m_pNext(NULL) {}
FileInfoPrivateData::~FileInfoPrivateData()
{
delete m_pNext;
m_pNext = NULL;
}
HRESULT FileInfoPrivateData::SetNext(__in_opt FileInfoPrivateData* pNext)
{
RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_MRM_DUPLICATE_ENTRY), m_pNext != NULL);
m_pNext = pNext;
return S_OK;
}
bool FileInfoPrivateData::TryGetNext(__in_opt const void* pOwner, __in int index, __out FileInfoPrivateData** ppDataOut) const
{
if ((ppDataOut == nullptr) || ((pOwner == nullptr) && (index >= 0)))
{
return false;
}
*ppDataOut = NULL;
FileInfoPrivateData* pNext = m_pNext;
while (pNext && (!pNext->Matches(pOwner, index)))
{
pNext = pNext->m_pNext;
}
*ppDataOut = pNext;
return (pNext != NULL);
}
/*
* FileInfo - describes a single file of interest
*/
FileInfo::FileInfo(__in FolderInfo* pParent) : m_pName(nullptr), m_pParentFolder(pParent), m_index(-1), m_pPrivates(nullptr), m_flags(0) {}
HRESULT FileInfo::Init(_In_ PCWSTR name)
{
RETURN_IF_FAILED(DefString_Dup(name, &m_pName));
m_nameIsAscii = (DefString_ChooseBestEncoding(name) == DEFSTRING_ENCODING_ASCII);
return S_OK;
}
FileInfo::~FileInfo()
{
if (m_pName)
{
_DefFree(m_pName);
m_pName = NULL;
}
delete m_pPrivates;
m_pPrivates = NULL;
}
HRESULT FileInfo::CreateInstance(__in PCWSTR pName, __in FolderInfo* pParent, _Outptr_ FileInfo** result)
{
*result = nullptr;
RETURN_HR_IF(E_INVALIDARG, DefString_IsEmpty(pName) || (pParent == nullptr));
AutoDeletePtr<FileInfo> pRtrn = new FileInfo(pParent);
RETURN_IF_NULL_ALLOC(pRtrn);
RETURN_IF_FAILED(pRtrn->Init(pName));
*result = pRtrn.Detach();
return S_OK;
}
HRESULT FileInfo::GetFileName(__inout StringResult* pNameOut) const
{
RETURN_HR_IF_NULL(E_INVALIDARG, pNameOut);
RETURN_IF_FAILED(pNameOut->SetRef(m_pName));
return S_OK;
}
HRESULT FileInfo::GetFullPath(__inout StringResult* pPathOut) const
{
RETURN_HR_IF_NULL(E_INVALIDARG, pPathOut);
RETURN_IF_FAILED(m_pParentFolder->GetFullPath(pPathOut));
RETURN_IF_FAILED(pPathOut->ConcatPathElement(m_pName));
return S_OK;
}
bool FileInfo::TryGetPrivateData(__in_opt const void* pOwner, __in int index, __out FileInfoPrivateData** ppDataOut) const
{
if (ppDataOut == nullptr)
{
return false;
}
*ppDataOut = NULL;
if (!m_pPrivates)
{
return false;
}
if (m_pPrivates->Matches(pOwner, index))
{
*ppDataOut = m_pPrivates;
return true;
}
return m_pPrivates->TryGetNext(pOwner, index, ppDataOut);
}
HRESULT FileInfo::AddPrivateData(__in FileInfoPrivateData* pPrivate, __in bool allowDuplicates)
{
RETURN_HR_IF(E_INVALIDARG, (pPrivate == nullptr) || (pPrivate->GetNext() != nullptr));
if (m_pPrivates != NULL)
{
if (!allowDuplicates)
{
FileInfoPrivateData* pNext = m_pPrivates;
while (pNext)
{
if (pNext->Matches(pPrivate))
{
return HRESULT_FROM_WIN32(ERROR_MRM_DUPLICATE_ENTRY);
}
}
}
RETURN_IF_FAILED(pPrivate->SetNext(m_pPrivates));
}
m_pPrivates = pPrivate;
return S_OK;
}
/*
* FolderInfo - Describes a single folder of interest and its contents
*/
FolderInfo::FolderInfo(__in PCWSTR pName, __in_opt FolderInfo* pParent) :
m_pParentFolder(pParent),
m_pSubfolders(nullptr),
m_pFiles(nullptr),
m_pName(nullptr),
m_numFiles(0),
m_sizeFiles(0),
m_numSubfolders(0),
m_sizeSubfolders(0),
m_totalNumFiles(0),
m_totalNumFolders((pName && pName[0]) ? 1 : 0), // No files, and just this folder. Don't count this folder if it's a "hidden" root.
m_index(-1)
{}
HRESULT FolderInfo::Init(_In_ PCWSTR name)
{
RETURN_IF_FAILED(DefString_Dup(name, &m_pName));
m_nameIsAscii = (DefString_ChooseBestEncoding(name) == DEFSTRING_ENCODING_ASCII);
return S_OK;
}
FolderInfo::~FolderInfo()
{
if (m_pName)
{
_DefFree(m_pName);
m_pName = NULL;
}
if (m_pSubfolders)
{
for (int i = 0; i < m_numSubfolders; i++)
{
if (!m_pSubfolders[i])
continue;
delete m_pSubfolders[i];
m_pSubfolders[i] = NULL;
}
_DefFree(m_pSubfolders);
m_pSubfolders = NULL;
m_numSubfolders = m_sizeSubfolders = 0;
}
if (m_pFiles)
{
for (int i = 0; i < m_numFiles; i++)
{
if (!m_pFiles[i])
continue;
delete m_pFiles[i];
m_pFiles[i] = NULL;
}
_DefFree(m_pFiles);
m_numFiles = m_sizeFiles = NULL;
}
}
HRESULT FolderInfo::CreateInstance(__in PCWSTR pName, __in FolderInfo* pParent, _Outptr_ FolderInfo** result)
{
*result = nullptr;
RETURN_HR_IF(E_INVALIDARG, DefString_IsEmpty(pName) || (pParent == nullptr));
AutoDeletePtr<FolderInfo> pRtrn = new FolderInfo(pName, pParent);
RETURN_IF_NULL_ALLOC(pRtrn);
RETURN_IF_FAILED(pRtrn->Init(pName));
*result = pRtrn.Detach();
return S_OK;
}
bool FolderInfo::NoteSubfolderChanges(__in int numFoldersAdded, __in int numFilesAdded)
{
m_totalNumFolders += numFoldersAdded;
m_totalNumFiles += numFilesAdded;
return (m_pParentFolder ? m_pParentFolder->NoteSubfolderChanges(numFoldersAdded, numFilesAdded) : true);
}
HRESULT FolderInfo::ExtendSubfolders()
{
if (!m_pSubfolders)
{
m_sizeSubfolders = 0;
m_pSubfolders = _DefArray_Alloc(FolderInfo*, 5);
RETURN_IF_NULL_ALLOC(m_pSubfolders);
m_sizeSubfolders = 5;
return S_OK;
}
if (m_numSubfolders >= m_sizeSubfolders)
{
UINT32 newSize = m_sizeSubfolders * 2;
FolderInfo** pTmp;
RETURN_IF_FAILED(_DefArray_Expand(m_pSubfolders, FolderInfo*, m_sizeSubfolders, newSize, &pTmp));
m_sizeSubfolders = newSize;
m_pSubfolders = pTmp;
}
return S_OK;
}
HRESULT FolderInfo::ExtendFiles()
{
if (!m_pFiles)
{
m_sizeFiles = 0;
m_pFiles = _DefArray_Alloc(FileInfo*, 5);
RETURN_IF_NULL_ALLOC(m_pFiles);
m_sizeFiles = 5;
return S_OK;
}
if (m_numFiles >= m_sizeFiles)
{
UINT32 newSize = m_sizeFiles * 2;
FileInfo** pTmp;
RETURN_IF_FAILED(_DefArray_Expand(m_pFiles, FileInfo*, m_sizeFiles, newSize, &pTmp));
m_sizeFiles = newSize;
m_pFiles = pTmp;
}
return S_OK;
}
HRESULT FolderInfo::NewRootFolder(_Outptr_ FolderInfo** result)
{
*result = nullptr;
AutoDeletePtr<FolderInfo> pRtrn = new FolderInfo(L"", nullptr);
RETURN_IF_NULL_ALLOC(pRtrn);
RETURN_IF_FAILED(pRtrn->Init(L""));
*result = pRtrn.Detach();
return S_OK;
}
HRESULT FolderInfo::GetFolderName(__inout StringResult* pPathOut) const
{
RETURN_HR_IF_NULL(E_INVALIDARG, pPathOut);
RETURN_IF_FAILED(pPathOut->SetRef(m_pName));
return S_OK;
}
HRESULT FolderInfo::GetFullPath(__inout StringResult* pPathOut) const
{
RETURN_HR_IF_NULL(E_INVALIDARG, pPathOut);
if (!m_pParentFolder)
{
RETURN_IF_FAILED(pPathOut->SetRef(m_pName));
}
else
{
RETURN_IF_FAILED(m_pParentFolder->GetFullPath(pPathOut));
RETURN_IF_FAILED(pPathOut->ConcatPathElement(m_pName));
}
return S_OK;
}
HRESULT FolderInfo::GetSubfolder(__in int index, _Out_ FolderInfo** result) const
{
*result = nullptr;
RETURN_HR_IF(E_INVALIDARG, (index < 0) || (index > m_numSubfolders - 1));
*result = m_pSubfolders[index];
return S_OK;
}
HRESULT FolderInfo::GetSubfolder(__in PCWSTR pName, _Out_ FolderInfo** result) const
{
if (!TryGetSubfolder(pName, result))
{
return E_DEF_FOLDER_NOT_FOUND;
}
return S_OK;
}
bool FolderInfo::TryGetSubfolder(__in PCWSTR pName, __inout FolderInfo** ppFolderOut) const
{
if (ppFolderOut)
{
*ppFolderOut = NULL;
}
if (DefString_IsEmpty(pName) || (ppFolderOut == nullptr) || (!m_pSubfolders))
{
return false;
}
for (int i = 0; i < m_numSubfolders; i++)
{
if (!m_pSubfolders[i])
{
continue;
}
if (DefString_ICompare(pName, m_pSubfolders[i]->GetFolderName()) == Def_Equal)
{
*ppFolderOut = m_pSubfolders[i];
return true;
}
}
return false;
}
int FolderInfo::GetSubfolderIndex(__in PCWSTR pName) const
{
int index = -1;
if (!TryGetSubfolderIndex(pName, &index))
{
return -1;
}
return index;
}
bool FolderInfo::TryGetSubfolderIndex(__in PCWSTR pName, __out int* ppIndexOut) const
{
if (ppIndexOut)
{
*ppIndexOut = -1;
}
if (DefString_IsEmpty(pName) || (ppIndexOut == nullptr) || (!m_pSubfolders))
{
return false;
}
for (int i = 0; i < m_numSubfolders; i++)
{
if (!m_pSubfolders[i])
{
continue;
}
if (DefString_ICompare(pName, m_pSubfolders[i]->GetFolderName()) == Def_Equal)
{
*ppIndexOut = i;
return true;
}
}
return false;
}
HRESULT FolderInfo::GetOrAddSubfolder(__in PCWSTR pName, _Out_ FolderInfo** result)
{
*result = nullptr;
RETURN_HR_IF(E_INVALIDARG, DefString_IsEmpty(pName));
if (TryGetSubfolder(pName, result))
{
return S_OK;
}
if (m_numSubfolders >= m_sizeSubfolders)
{
RETURN_IF_FAILED(ExtendSubfolders());
}
FolderInfo* pRtrn;
RETURN_IF_FAILED(FolderInfo::CreateInstance(pName, this, &pRtrn));
m_pSubfolders[m_numSubfolders++] = pRtrn;
NoteSubfolderChanges(1, 0);
*result = pRtrn;
return S_OK;
}
HRESULT FolderInfo::GetFile(__in int index, _Out_ FileInfo** result) const
{
*result = nullptr;
RETURN_HR_IF(E_INVALIDARG, (index < 0) || (index > m_numFiles - 1));
*result = m_pFiles[index];
return S_OK;
}
HRESULT FolderInfo::GetFile(__in PCWSTR pName, _Out_ FileInfo** result) const
{
*result = nullptr;
if (!TryGetFile(pName, result))
{
return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
return S_OK;
}
bool FolderInfo::TryGetFile(__in PCWSTR pName, __out FileInfo** ppFileOut) const
{
if (ppFileOut)
{
*ppFileOut = NULL;
}
if (DefString_IsEmpty(pName) || (ppFileOut == nullptr) || (!m_pFiles))
{
return false;
}
for (int i = 0; i < m_numFiles; i++)
{
if (!m_pFiles[i])
{
continue;
}
if (DefString_ICompare(pName, m_pFiles[i]->GetFileName()) == Def_Equal)
{
*ppFileOut = m_pFiles[i];
return true;
}
}
return false;
}
int FolderInfo::GetFileIndex(__in PCWSTR pName) const
{
int index = -1;
if (!TryGetFileIndex(pName, &index))
{
return -1;
}
return index;
}
bool FolderInfo::TryGetFileIndex(__in PCWSTR pName, __out int* ppIndexOut) const
{
if (ppIndexOut)
{
*ppIndexOut = -1;
}
if (DefString_IsEmpty(pName) || (ppIndexOut == nullptr) || (!m_pFiles))
{
return false;
}
for (int i = 0; i < m_numFiles; i++)
{
if (!m_pFiles[i])
{
continue;
}
if (DefString_ICompare(pName, m_pFiles[i]->GetFileName()) == Def_Equal)
{
*ppIndexOut = i;
return true;
}
}
return false;
}
HRESULT FolderInfo::GetOrAddFile(__in PCWSTR pName, _Out_ FileInfo** result)
{
*result = nullptr;
RETURN_HR_IF(E_INVALIDARG, DefString_IsEmpty(pName));
if (TryGetFile(pName, result))
{
return S_OK;
}
if (m_numFiles >= m_sizeFiles)
{
RETURN_IF_FAILED(ExtendFiles());
}
FileInfo* pRtrn;
RETURN_IF_FAILED(FileInfo::CreateInstance(pName, this, &pRtrn));
m_pFiles[m_numFiles++] = pRtrn;
NoteSubfolderChanges(0, 1);
*result = pRtrn;
return S_OK;
}
/*!
* An \ref IFileList representation of the finalized contents of
* an \ref FileListBuilder.
*/
class FileListBuilder::FinalizedBuilder : public DefObject, public IFileList
{
protected:
const FileListBuilder* m_pBuilder;
int m_numFolders;
int m_numFiles;
FolderInfo** m_pAllFolders;
FileInfo** m_pAllFiles;
int m_cchLongestPath;
FinalizedBuilder(__in const FileListBuilder* pBuilder, __in int numFolders, __in int numFiles) :
m_pBuilder(pBuilder), m_numFolders(numFolders), m_numFiles(numFiles), m_pAllFolders(NULL), m_pAllFiles(NULL), m_cchLongestPath(-1)
{}
HRESULT Init(__in const FileListBuilder* pBuilder, __in int numFolders, __in int numFiles)
{
RETURN_HR_IF(E_INVALIDARG, (pBuilder == nullptr) || (numFolders < 0) || (numFiles < 0));
if (m_numFolders > 0)
{
m_pAllFolders = _DefArray_AllocZeroed(FolderInfo*, m_numFolders);
RETURN_IF_NULL_ALLOC(m_pAllFolders);
}
if (m_numFiles > 0)
{
m_pAllFiles = _DefArray_AllocZeroed(FileInfo*, m_numFiles);
RETURN_IF_NULL_ALLOC(m_pAllFiles);
}
return S_OK;
}
public:
~FinalizedBuilder()
{
m_numFolders = 0;
m_numFiles = 0;
if (m_pAllFolders != NULL)
{
Def_Free(m_pAllFolders);
m_pAllFolders = NULL;
}
if (m_pAllFiles != NULL)
{
Def_Free(m_pAllFiles);
m_pAllFiles = NULL;
}
}
static HRESULT CreateInstance(
__in const FileListBuilder* pBuilder,
__in int numFolders,
__in int numFiles,
_Outptr_ FinalizedBuilder** result)
{
*result = nullptr;
RETURN_HR_IF(E_INVALIDARG, (pBuilder == nullptr) || (numFolders < 0) || (numFiles < 0));
AutoDeletePtr<FinalizedBuilder> pRtrn = new FinalizedBuilder(pBuilder, numFolders, numFiles);
RETURN_IF_NULL_ALLOC(pRtrn);
RETURN_IF_FAILED(pRtrn->Init(pBuilder, numFolders, numFiles));
*result = pRtrn.Detach();
return S_OK;
}
int GetNumFolders() const { return m_numFolders; }
int GetNumFiles() const { return m_numFiles; }
FolderInfo** GetFolders() { return m_pAllFolders; }
FileInfo** GetFiles() { return m_pAllFiles; }
HRESULT GetFolder(__in int index, __out FolderInfo** ppFolderOut) const
{
RETURN_HR_IF(E_INVALIDARG, (ppFolderOut == nullptr) || (index < 0) || (index > m_numFolders - 1));
*ppFolderOut = this->m_pAllFolders[index];
return ((*ppFolderOut) != nullptr) ? S_OK : HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
HRESULT GetFile(__in int index, __out FileInfo** ppFileOut) const
{
RETURN_HR_IF(E_INVALIDARG, (ppFileOut == nullptr) || (index < 0) || (index > m_numFiles - 1));
*ppFileOut = this->m_pAllFiles[index];
return ((*ppFileOut) != nullptr) ? S_OK : HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
HRESULT InitFolderIndex(__in FolderInfo* pFolderInfo, __inout int* pNumInitialized) const
{
RETURN_HR_IF(E_INVALIDARG, (pFolderInfo == nullptr) || (pNumInitialized == nullptr));
RETURN_HR_IF(E_ABORT, (!m_pAllFolders) || (m_numFolders < 0));
int index = pFolderInfo->GetIndex();
if ((index < 0) || (index >= m_numFolders) || (m_pAllFolders[index] != NULL))
{
return E_ABORT;
}
m_pAllFolders[index] = pFolderInfo;
*pNumInitialized = (*pNumInitialized) + 1;
for (int i = 0; i < pFolderInfo->GetNumSubfolders(); i++)
{
FolderInfo* pSubFolder;
RETURN_IF_FAILED(pFolderInfo->GetSubfolder(i, &pSubFolder));
RETURN_IF_FAILED(InitFolderIndex(pSubFolder, pNumInitialized));
}
return S_OK;
}
HRESULT InitFileIndex(__in FolderInfo* pFolderInfo, __inout int* pNumInitialized) const
{
RETURN_HR_IF(E_INVALIDARG, (pFolderInfo == nullptr) || (pNumInitialized == nullptr));
RETURN_HR_IF(E_ABORT, (!m_pAllFolders) || (m_numFiles < 0));
int i;
for (i = 0; i < pFolderInfo->GetNumFiles(); i++)
{
FileInfo* pFile;
RETURN_IF_FAILED(pFolderInfo->GetFile(i, &pFile));
int index = pFile->GetIndex();
if ((index < 0) || (index >= m_numFiles) || (m_pAllFiles[index] != NULL))
{
return E_ABORT;
}
m_pAllFiles[index] = pFile;
*pNumInitialized = (*pNumInitialized) + 1;
}
for (i = 0; i < pFolderInfo->GetNumSubfolders(); i++)
{
FolderInfo* pSubFolder;
RETURN_IF_FAILED(pFolderInfo->GetSubfolder(i, &pSubFolder));
RETURN_IF_FAILED(InitFileIndex(pSubFolder, pNumInitialized));
}
return S_OK;
}
/*!
* \name IFileList Implementation
* @{
*/
//! \see IFileList::GetNumRootFolders
int GetNumRootFolders() const { return m_pBuilder->GetNumRootFolders(); }
//! \see IFileList::GetTotalNumFolders
int GetTotalNumFolders() const { return m_pBuilder->GetTotalNumFolders(); }
//! \see IFileList::GetTotalNumFiles
int GetTotalNumFiles() const { return m_pBuilder->GetTotalNumFiles(); }
//! \see IFileList::GetLongestPath
int GetLongestPath() const { return 0; /* return m_pBuilder->GetLongestPath();*/ }
//! \see IFileList::GetFolderName
HRESULT GetFolderName(__in int folderIndex, __inout StringResult* pNameOut) const
{
RETURN_HR_IF(E_INVALIDARG, (folderIndex < 0) || (folderIndex > m_numFolders - 1) || (pNameOut == nullptr));
RETURN_HR_IF(E_DEF_NOT_READY, m_pAllFolders[folderIndex] == nullptr);
RETURN_IF_FAILED(m_pAllFolders[folderIndex]->GetFolderName(pNameOut));
return S_OK;
}
//! \see IFileList::GetFileName
HRESULT GetFileName(__in int fileIndex, __inout StringResult* pNameOut) const
{
RETURN_HR_IF(E_INVALIDARG, (fileIndex < 0) || (fileIndex > m_numFiles - 1) || (pNameOut == nullptr));
RETURN_HR_IF(E_DEF_NOT_READY, m_pAllFiles[fileIndex] == nullptr);
RETURN_IF_FAILED(m_pAllFiles[fileIndex]->GetFileName(pNameOut));
return S_OK;
}
//! \see IFileList::GetSubfolders
HRESULT GetSubfolders(__in int folderIndex, __out_opt int* pFirstSubfolderOut, __out_opt int* pNumSubfoldersOut) const
{
RETURN_HR_IF(E_INVALIDARG, (folderIndex < 0) || (folderIndex > m_numFolders - 1));
RETURN_HR_IF(E_DEF_NOT_READY, m_pAllFolders[folderIndex] == nullptr);
FolderInfo* pFolder = m_pAllFolders[folderIndex];
if (pNumSubfoldersOut != NULL)
{
*pNumSubfoldersOut = pFolder->GetNumSubfolders();
}
if (pFirstSubfolderOut != NULL)
{
if (pFolder->GetNumSubfolders() > 0)
{
FolderInfo* pSubFolder;
RETURN_IF_FAILED(pFolder->GetSubfolder(0, &pSubFolder));
*pFirstSubfolderOut = pSubFolder->GetIndex();
}
else
{
*pFirstSubfolderOut = -1;
}
}
return S_OK;
}
//! \see IFileList::GetFiles
HRESULT GetFiles(__in int folderIndex, __out_opt int* pFirstFileOut, __out_opt int* pNumFilesOut) const
{
RETURN_HR_IF(E_INVALIDARG, (folderIndex < 0) || (folderIndex > m_numFolders - 1));
RETURN_HR_IF(E_DEF_NOT_READY, m_pAllFolders[folderIndex] == nullptr);
FolderInfo* pFolder = m_pAllFolders[folderIndex];
if (pNumFilesOut != NULL)
{
*pNumFilesOut = pFolder->GetNumFiles();
}
if (pFirstFileOut != NULL)
{
if (pFolder->GetNumFiles() > 0)
{
FileInfo* pFile;
RETURN_IF_FAILED(pFolder->GetFile(0, &pFile));
*pFirstFileOut = pFile->GetIndex();
}
else
{
*pFirstFileOut = -1;
}
}
return S_OK;
}
//! \see IFileList::GetFolderParentIndex
HRESULT GetFolderParentFolderIndex(__in int folderIndex, __out int* pParentFolderIndexOut) const
{
RETURN_HR_IF(E_INVALIDARG, (folderIndex < 0) || (folderIndex > m_numFolders - 1) || (pParentFolderIndexOut == nullptr));
RETURN_HR_IF(E_DEF_NOT_READY, m_pAllFolders[folderIndex] == nullptr);
FolderInfo* pParent = m_pAllFolders[folderIndex]->GetParentFolder();
*pParentFolderIndexOut = (pParent ? pParent->GetIndex() : -1);
return S_OK;
}
//! \see IFileList::GetFileParentFolderIndex
HRESULT GetFileParentFolderIndex(__in int fileIndex, __out int* pParentFolderIndexOut) const
{
RETURN_HR_IF(E_INVALIDARG, (fileIndex < 0) || (fileIndex > m_numFiles - 1) || (pParentFolderIndexOut == nullptr));
RETURN_HR_IF(E_DEF_NOT_READY, m_pAllFiles[fileIndex] == nullptr);
FolderInfo* pParent = m_pAllFiles[fileIndex]->GetParentFolder();
*pParentFolderIndexOut = (pParent ? pParent->GetIndex() : -1);
return S_OK;
}
//! \see IFileList::GetFilePath
HRESULT GetFilePath(__in int fileIndex, __inout StringResult* pPathOut) const { return GetFilePath(fileIndex, pPathOut, nullptr); }
//! \see IFileList::GetFilePath
HRESULT GetFilePath(_In_ int fileIndex, _Inout_ StringResult* pPathOut, _Out_ UINT16* /*pFlags*/) const
{
RETURN_HR_IF(E_INVALIDARG, (fileIndex < 0) || (fileIndex > m_numFiles - 1) || (pPathOut == nullptr));
RETURN_HR_IF(E_DEF_NOT_READY, m_pAllFiles[fileIndex] == nullptr);
RETURN_IF_FAILED(m_pAllFiles[fileIndex]->GetFullPath(pPathOut));
return S_OK;
}
//! \see IFileList::GetFolderPath
HRESULT GetFolderPath(__in int folderIndex, __inout StringResult* pPathOut) const
{
RETURN_HR_IF(E_INVALIDARG, (folderIndex < 0) || (folderIndex > m_numFolders - 1) || (pPathOut == nullptr));
RETURN_HR_IF(E_DEF_NOT_READY, m_pAllFolders[folderIndex] == nullptr);
RETURN_IF_FAILED(m_pAllFolders[folderIndex]->GetFullPath(pPathOut));
return S_OK;
}
/*!@}*/
};
/*!
* Section builder for a file list section.
*/
FileListBuilder::FileListBuilder(_In_ FileBuilder* pParentFile, _In_ UINT32 flags) :
m_pParentFile(pParentFile),
m_sectionIndex(-1),
m_numFinalizedFiles(-1),
m_numFinalizedFolders(-1),
m_pFinalized(nullptr),
m_flags(flags),
m_pRootFolder(nullptr)
{}
HRESULT FileListBuilder::Init()
{
RETURN_IF_FAILED(FolderInfo::NewRootFolder(&m_pRootFolder));
return S_OK;
}
HRESULT FileListBuilder::CreateInstance(_In_ FileBuilder* pParentFile, _In_ UINT32 flags, _Outptr_ FileListBuilder** result)
{
*result = nullptr;
RETURN_HR_IF_NULL(E_INVALIDARG, pParentFile);
AutoDeletePtr<FileListBuilder> builder = new FileListBuilder(pParentFile, flags);
RETURN_IF_NULL_ALLOC(builder);
RETURN_IF_FAILED(builder->Init());
*result = builder.Detach();
return S_OK;
}
FileListBuilder::~FileListBuilder()
{
delete m_pRootFolder;
delete m_pFinalized;
m_pRootFolder = NULL;
m_pFinalized = NULL;
}
int FileListBuilder::GetNumRootFolders() const { return m_pRootFolder->GetNumSubfolders(); }
int FileListBuilder::GetTotalNumFolders() const { return m_pRootFolder->GetTotalNumFolders(); }
int FileListBuilder::GetTotalNumFiles() const { return m_pRootFolder->GetTotalNumFiles(); }
HRESULT FileListBuilder::GetRootFolder(__in int index, _Out_ FolderInfo** result) const
{
return m_pRootFolder->GetSubfolder(index, result);
}
HRESULT FileListBuilder::GetRootFolder(__in PCWSTR pPath, _Out_ FolderInfo** result) const
{
return m_pRootFolder->GetSubfolder(pPath, result);
}
bool FileListBuilder::TryGetRootFolder(__inout PCWSTR pPath, __inout FolderInfo** ppFolderOut) const
{
return m_pRootFolder->TryGetSubfolder(pPath, ppFolderOut);
}
HRESULT FileListBuilder::GetOrAddRootFolder(__in PCWSTR pPath, _Out_ FolderInfo** result)
{
return m_pRootFolder->GetOrAddSubfolder(pPath, result);
}
bool FileListBuilder::TryGetFolderByIndex(__in int index, __out FolderInfo** ppFolderOut) const
{
if ((ppFolderOut == nullptr) || (m_numFinalizedFolders < 0) || (index < 0) || (index > m_numFinalizedFolders - 1))
{
return false;
}
IFileList* tmp = NULL;
if ((!m_pFinalized) && (FAILED(GetFileList(&tmp))))
{
return false;
}
return SUCCEEDED(m_pFinalized->GetFolder(index, ppFolderOut));
}
bool FileListBuilder::TryGetFileByIndex(__in int index, __out FileInfo** ppFileOut) const
{
if ((ppFileOut == nullptr) || (m_numFinalizedFiles < 0) || (index < 0) || (index > m_numFinalizedFiles - 1))
{
return false;
}
IFileList* tmp = NULL;
if ((!m_pFinalized) && (FAILED(GetFileList(&tmp))))
{
return false;
}
return SUCCEEDED(m_pFinalized->GetFile(index, ppFileOut));
}
size_t FileListBuilder::ComputeTotalStringsSizeInBytes(_In_ const FolderInfo* pFolder, _In_ UINT32 flags)
{
size_t cchUtf16Total = 0;
size_t cchAsciiTotal = 0;
if (SUCCEEDED(ComputeTotalStringsSize(pFolder, flags, &cchAsciiTotal, &cchUtf16Total)))
{
size_t cbRaw = _DEFFILE_PAD(cchAsciiTotal, 2) + (cchUtf16Total * sizeof(WCHAR));
return _DEFFILE_PAD(cbRaw, 4);
}
return 0;
}
HRESULT
FileListBuilder::ComputeTotalStringsSize(
_In_ const FolderInfo* pFolder,
_In_ UINT32 flags,
_Inout_ size_t* pCchAsciiTotal,
_Inout_ size_t* pCchUtf16Total)
{
int i;
size_t cchName;
StringResult name;
PCWSTR pName;
bool buildAscii = ((flags & BuildEncodingFlags) == BuildAsciiOrUtf16);
RETURN_HR_IF_NULL(E_INVALIDARG, pFolder);
// Reserve space for the name of this folder, unless it's the root folder.
RETURN_IF_FAILED(pFolder->GetFolderName(&name));
pName = name.GetRef();
if (pName && pName[0])
{
cchName = wcslen(pName) + 1;
if (buildAscii && pFolder->NameIsAscii())
{
(*pCchAsciiTotal) += cchName;
}
else
{
(*pCchUtf16Total) += cchName;
}
}
// Now reserve space for each of the files in this folder
for (i = 0; i < pFolder->GetNumFiles(); i++)
{
FileInfo* pFile;
RETURN_IF_FAILED(pFolder->GetFile(i, &pFile));
RETURN_IF_FAILED(pFile->GetFileName(&name));
pName = name.GetRef();
cchName = wcslen(pName) + 1;
if (buildAscii && pFile->NameIsAscii())
{
(*pCchAsciiTotal) += cchName;
}
else
{
(*pCchUtf16Total) += cchName;
}
}
// Reserve space for all subfolders
for (i = 0; i < pFolder->GetNumSubfolders(); i++)
{
FolderInfo* pSubfolder;
RETURN_IF_FAILED(pFolder->GetSubfolder(i, &pSubfolder));
RETURN_IF_FAILED(ComputeTotalStringsSize(pSubfolder, flags, pCchAsciiTotal, pCchUtf16Total));
}
return S_OK;
}
bool FileListBuilder::IsFinalized() const
{
return ((m_numFinalizedFolders == GetTotalNumFolders()) && (m_numFinalizedFiles == GetTotalNumFiles()));
}
HRESULT FileListBuilder::GetFileList(__out IFileList** ppFileListOut) const
{
RETURN_HR_IF_NULL(E_INVALIDARG, ppFileListOut);
RETURN_HR_IF(E_DEF_NOT_READY, !IsFinalized());
if (m_pFinalized == NULL)
{
AutoDeletePtr<FinalizedBuilder> builder;
RETURN_IF_FAILED(FinalizedBuilder::CreateInstance(this, m_numFinalizedFolders, m_numFinalizedFiles, &builder));
int numFilesInitialized = 0;
int numFoldersInitialized = 0;
for (int i = 0; i < GetNumRootFolders(); i++)
{
FolderInfo* pFolder;
RETURN_IF_FAILED(m_pRootFolder->GetSubfolder(i, &pFolder));
RETURN_IF_FAILED(builder->InitFolderIndex(pFolder, &numFoldersInitialized));
RETURN_IF_FAILED(builder->InitFileIndex(pFolder, &numFilesInitialized));
}
if ((numFoldersInitialized != m_numFinalizedFolders) || (numFilesInitialized != m_numFinalizedFiles))
{
return E_ABORT;
}
m_pFinalized = builder.Detach();
}
*ppFileListOut = m_pFinalized;
return S_OK;
}
bool FileListBuilder::IsValidFileIndex(__inout int indexIn) const
{
if ((indexIn < 0) || (indexIn > IFileList::MaxFileIndex) || (!IsFinalized()))
{
return false;
}
return (indexIn < m_numFinalizedFiles);
}
bool FileListBuilder::IsValidFolderIndex(__inout int indexIn) const
{
if ((indexIn < 0) || (indexIn > IFileList::MaxFileIndex) || (!IsFinalized()))
{
return false;
}
return (indexIn < m_numFinalizedFolders);
}
UINT32 FileListBuilder::GetMaxSizeInBytes() const
{
size_t totalSize = sizeof(DEFFILE_FILELIST_HEADER);
totalSize += GetTotalNumFolders() * sizeof(DEFFILE_FILELIST_FOLDER_ENTRY);
totalSize += GetTotalNumFiles() * sizeof(DEFFILE_FILELIST_FILE_ENTRY);
// add a WCHAR to string size for leading NUL on string pool
size_t cbStringPool = sizeof(WCHAR) + ComputeTotalStringsSizeInBytes(m_pRootFolder, m_flags);
totalSize += _DEFFILE_PAD(cbStringPool, 4);
totalSize = _DEFFILE_PAD_SECTION(totalSize);
return static_cast<UINT32>(totalSize);
}
HRESULT FileListBuilder::AssignFolderIndices(
__in FolderInfo* pFolderInfo,
__in int index,
__inout UINT32* pNextFolder,
__in UINT32 sizeFolders,
__inout UINT32* pNextFile,
__in UINT32 sizeFiles)
{
RETURN_HR_IF(E_INVALIDARG, (pFolderInfo == nullptr) || (pNextFile == nullptr) || (pNextFolder == nullptr));
RETURN_HR_IF(E_INVALIDARG, (index < 0) || (index > ((INT32)sizeFolders) - 1));
// Let OACR know what's going on
__analysis_assume(index >= 0);
__analysis_assume(index < sizeFolders);
pFolderInfo->SetIndex(index);
UINT32 numSubfolders = pFolderInfo->GetNumSubfolders();
UINT32 numFiles = pFolderInfo->GetNumFiles();
INT32 nFirstSubfolder = ((numSubfolders > 0) ? (*pNextFolder) : -1);
INT32 nFirstFile = ((numFiles > 0) ? (*pNextFile) : -1);
if (numFiles > 0)
{
if (nFirstFile + numFiles > sizeFiles)
{
return E_DEFFILE_BUILD_SECTION_DATA_TOO_LARGE;
}
*pNextFile += numFiles;
for (int i = 0; i < (int)numFiles; i++)
{
FileInfo* pFileInfo;
RETURN_IF_FAILED(pFolderInfo->GetFile(i, &pFileInfo));
pFileInfo->SetIndex(nFirstFile + i + 1); // 1 based file index since runtime use 0 index as its own file
}
}
if (numSubfolders > 0)
{
if (nFirstSubfolder + numSubfolders > sizeFolders)
{
return E_DEFFILE_BUILD_SECTION_DATA_TOO_LARGE;
}
*pNextFolder += numSubfolders;
for (int i = 0; i < (int)numSubfolders; i++)
{
FolderInfo* pSubfolder;
RETURN_IF_FAILED(pFolderInfo->GetSubfolder(i, &pSubfolder));
RETURN_IF_FAILED(AssignFolderIndices(
pSubfolder, // folder
nFirstSubfolder + i, // folder index
pNextFolder,
sizeFolders,
pNextFile,
sizeFiles));
}
}
return S_OK;
}
HRESULT FileListBuilder::BuildFolderInfo(
__in const FolderInfo* pFolderInfo,
__in int index,
__in int parentIndex,
__inout_ecount(sizeFolders) DEFFILE_FILELIST_FOLDER_ENTRY* pFolders,
__inout UINT32* pNextFolder,
__in UINT32 sizeFolders,
__out_ecount(sizeFiles) DEFFILE_FILELIST_FILE_ENTRY* pFiles,
__inout UINT32* pNextFile,
__in UINT32 sizeFiles,
__in WriteableStringPool* pNames) const
{
DEFFILE_FILELIST_FOLDER_ENTRY* pParent = NULL;
UINT32 parentPathLen = 0;
RETURN_HR_IF(E_INVALIDARG, (pFolderInfo == nullptr) || (pNextFile == nullptr) || (pNextFolder == nullptr) || (pNames == nullptr));
RETURN_HR_IF(E_INVALIDARG, (index < 0) || (index > ((INT32)sizeFolders) - 1) || (parentIndex >= (INT32)sizeFolders));
// let OACR know what we've figured out
__analysis_assume(index >= 0);
__analysis_assume(index < sizeFolders);
// If we've been assigned an index, we have to build to it. If we haven't
// been assigned an index, any index is okay.
if ((pFolderInfo->GetIndex() >= 0) && (pFolderInfo->GetIndex() != index))
{
return E_ABORT;
}
if (parentIndex >= 0)
{
pParent = &pFolders[parentIndex];
parentPathLen = pParent->cchFullPath + 1;
}
StringResult name;
RETURN_IF_FAILED(pFolderInfo->GetFolderName(&name));
UINT32 numSubfolders = pFolderInfo->GetNumSubfolders();
UINT32 numFiles = pFolderInfo->GetNumFiles();
INT32 nFirstSubfolder = ((numSubfolders > 0) ? (*pNextFolder) : -1);
INT32 nFirstFile = ((numFiles > 0) ? (*pNextFile) : -1);
pFolders[index].flags = 0;
pFolders[index].parentFolderIndex = (INT16)parentIndex;
pFolders[index].numSubfolders = (UINT16)numSubfolders;
pFolders[index].firstSubfolder = (INT16)nFirstSubfolder;
pFolders[index].numFiles = (UINT16)numFiles;
pFolders[index].firstFile = (INT16)nFirstFile;
pFolders[index].cchName = (UINT16)wcslen(name.GetRef());
pFolders[index].cchFullPath = (UINT16)(parentPathLen + pFolders[index].cchName);
pFolders[index].nameOffset = pNames->GetOrAddStringOffset(name.GetRef());
RETURN_HR_IF(E_ABORT, pFolders[index].nameOffset == -1);
if (numFiles > 0)
{
DEFFILE_FILELIST_FILE_ENTRY* pFile = &pFiles[nFirstFile];
if (nFirstFile + numFiles > sizeFiles)
{
return E_DEFFILE_BUILD_SECTION_DATA_TOO_LARGE;
}
*pNextFile += numFiles;
for (int i = 0; i < (int)numFiles; i++, pFile++)
{
FileInfo* pFileInfo;
RETURN_IF_FAILED(pFolderInfo->GetFile(i, &pFileInfo));
RETURN_IF_FAILED(pFileInfo->GetFileName(&name));
if ((pFileInfo->GetIndex() >= 0) && (pFileInfo->GetIndex() != (nFirstFile + i + 1)))
{ // fileIndex is based on 1 during Finalize
return E_ABORT;
}
pFile->flags = pFileInfo->GetFlag();
pFile->parentFolderIndex = (INT16)index;
pFile->cchName = (UINT16)wcslen(name.GetRef());
pFile->cchFullPath = (UINT16)(pFolders[index].cchFullPath + 1 + pFile->cchName);
pFile->nameOffset = pNames->GetOrAddStringOffset(name.GetRef());
RETURN_HR_IF(E_ABORT, pFile->nameOffset == -1);
}
}
if (numSubfolders > 0)
{
if (nFirstSubfolder + numSubfolders > sizeFolders)
{
return E_DEFFILE_BUILD_SECTION_DATA_TOO_LARGE;
}
*pNextFolder += numSubfolders;
for (int i = 0; i < (int)numSubfolders; i++)
{
FolderInfo* pSubfolder;
RETURN_IF_FAILED(pFolderInfo->GetSubfolder(i, &pSubfolder));
RETURN_IF_FAILED(BuildFolderInfo(
pSubfolder, // folder
nFirstSubfolder + i, // folder index
index, // parent folder index
pFolders,
pNextFolder,
sizeFolders,
pFiles,
pNextFile,
sizeFiles,
pNames));
}
}
return S_OK;
}
HRESULT FileListBuilder::Finalize()
{
UINT32 nextFile = 0;
UINT32 nextFolder = GetNumRootFolders();
UINT32 sizeFolders = GetTotalNumFolders();
UINT32 sizeFiles = GetTotalNumFiles();
if (m_pFinalized != NULL)
{
delete m_pFinalized;
m_pFinalized = NULL;
}
for (int i = 0; i < GetNumRootFolders(); i++)
{
FolderInfo* pFolder;
RETURN_IF_FAILED(m_pRootFolder->GetSubfolder(i, &pFolder));
RETURN_IF_FAILED(AssignFolderIndices(pFolder, i, &nextFolder, sizeFolders, &nextFile, sizeFiles));
}
if ((nextFile != sizeFiles) || (nextFolder != sizeFolders))
{
return E_ABORT;
}
m_numFinalizedFolders = sizeFolders;
m_numFinalizedFiles = sizeFiles;
return S_OK;
}
/*!
* Serializes the file list into the provided buffer.
*
* \param pBuffer
* The buffer into which the file list is generated.
*
* \param cbBuffer
* Size of the destination buffer, in bytes.
*
* \param pStatus
* If the Build method returns false, pStatus contains additional
* information about the cause of the error.
*
* \param cbWrittenOut
* If pcbWrittenOut is non-NULL, the Build method uses it to return
* the number of bytes actually written.
*
* \return bool
* Returns true on success, false if an error occurs.
*/
_Use_decl_annotations_ HRESULT FileListBuilder::Build(VOID* pBuffer, UINT32 cbBuffer, UINT32* pcbWrittenOut) const
{
DEFFILE_FILELIST_HEADER* pHeader;
DEFFILE_FILELIST_FOLDER_ENTRY* pFolders;
DEFFILE_FILELIST_FILE_ENTRY* pFiles;
WCHAR* pNamesPool;
AutoDeletePtr<WriteableStringPool> pStrings = NULL;
UINT32 numFolders = GetTotalNumFolders();
UINT32 numFiles = GetTotalNumFiles();
UINT32 cbFixed = sizeof(DEFFILE_FILELIST_HEADER) + (numFolders * sizeof(DEFFILE_FILELIST_FOLDER_ENTRY)) +
(numFiles * sizeof(DEFFILE_FILELIST_FILE_ENTRY));
RETURN_HR_IF(E_INVALIDARG, (pBuffer == nullptr) || (cbBuffer < cbFixed));
pHeader = reinterpret_cast<DEFFILE_FILELIST_HEADER*>(pBuffer);
pFolders = reinterpret_cast<DEFFILE_FILELIST_FOLDER_ENTRY*>(&pHeader[1]);
pFiles = reinterpret_cast<DEFFILE_FILELIST_FILE_ENTRY*>(&pFolders[numFolders]);
pNamesPool = reinterpret_cast<WCHAR*>(&pFiles[numFiles]);
UINT32 cchRemaining = (cbBuffer - cbFixed) / sizeof(WCHAR);
RETURN_IF_FAILED(
WriteableStringPool::CreateInstance(pNamesPool, cchRemaining, WriteableStringPool::fCompareCaseInsensitive, &pStrings));
RETURN_HR_IF(E_INVALIDARG, cbBuffer < sizeof(DEFFILE_FILELIST_HEADER));
_Analysis_assume_(cbBuffer >= sizeof(DEFFILE_FILELIST_HEADER));
// Initialize the header
pHeader->numRootFolders = (UINT16)m_pRootFolder->GetNumSubfolders();
pHeader->numFolderEntries = (UINT16)numFolders;
pHeader->numFileEntries = (UINT16)numFiles;
pHeader->cchLongestPath = 0;
pHeader->cchNamesPool = 0;
UINT32 nextFile = 0;
UINT32 nextFolder = pHeader->numRootFolders;
for (int i = 0; i < pHeader->numRootFolders; i++)
{
FolderInfo* pFolder;
RETURN_IF_FAILED(m_pRootFolder->GetSubfolder(i, &pFolder));
RETURN_IF_FAILED(BuildFolderInfo(
pFolder, i, -1, pFolders, &nextFolder, pHeader->numFolderEntries, pFiles, &nextFile, pHeader->numFileEntries, pStrings));
}
if ((nextFile != pHeader->numFileEntries) || (nextFolder != pHeader->numFolderEntries) ||
(pStrings->GetNumCharsInPool() > cchRemaining))
{
return E_ABORT;
}
pHeader->cchNamesPool = pStrings->GetNumCharsInPool();
// Don't need to copy the pool because pStrings generated the pool
// in the right spot directly.
UINT32 totalSize = sizeof(DEFFILE_FILELIST_HEADER) + sizeof(DEFFILE_FILELIST_FOLDER_ENTRY) * pHeader->numFolderEntries +
sizeof(DEFFILE_FILELIST_FILE_ENTRY) * pHeader->numFileEntries + sizeof(WCHAR) * pHeader->cchNamesPool;
totalSize = _DEFFILE_PAD_SECTION(totalSize);
if (totalSize > cbBuffer)
{
return E_ABORT;
}
*pcbWrittenOut = totalSize;
return S_OK;
}
} // namespace Microsoft::Resources::Build | 19,897 |
879 | <gh_stars>100-1000
package org.zstack.core.gc;
/**
* Created by xing5 on 2017/3/5.
*/
public interface GarbageCollectorMessage {
String getGCJobUuid();
}
| 61 |
868 | <reponame>ekmixon/opentelemetry-python
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: opentelemetry/proto/resource/v1/resource.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from opentelemetry.proto.common.v1 import common_pb2 as opentelemetry_dot_proto_dot_common_dot_v1_dot_common__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='opentelemetry/proto/resource/v1/resource.proto',
package='opentelemetry.proto.resource.v1',
syntax='proto3',
serialized_options=b'\n\"io.opentelemetry.proto.resource.v1B\rResourceProtoP\001Z@github.com/open-telemetry/opentelemetry-proto/gen/go/resource/v1',
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n.opentelemetry/proto/resource/v1/resource.proto\x12\x1fopentelemetry.proto.resource.v1\x1a*opentelemetry/proto/common/v1/common.proto\"i\n\x08Resource\x12;\n\nattributes\x18\x01 \x03(\x0b\x32\'.opentelemetry.proto.common.v1.KeyValue\x12 \n\x18\x64ropped_attributes_count\x18\x02 \x01(\rBw\n\"io.opentelemetry.proto.resource.v1B\rResourceProtoP\x01Z@github.com/open-telemetry/opentelemetry-proto/gen/go/resource/v1b\x06proto3'
,
dependencies=[opentelemetry_dot_proto_dot_common_dot_v1_dot_common__pb2.DESCRIPTOR,])
_RESOURCE = _descriptor.Descriptor(
name='Resource',
full_name='opentelemetry.proto.resource.v1.Resource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='attributes', full_name='opentelemetry.proto.resource.v1.Resource.attributes', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='dropped_attributes_count', full_name='opentelemetry.proto.resource.v1.Resource.dropped_attributes_count', index=1,
number=2, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=127,
serialized_end=232,
)
_RESOURCE.fields_by_name['attributes'].message_type = opentelemetry_dot_proto_dot_common_dot_v1_dot_common__pb2._KEYVALUE
DESCRIPTOR.message_types_by_name['Resource'] = _RESOURCE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Resource = _reflection.GeneratedProtocolMessageType('Resource', (_message.Message,), {
'DESCRIPTOR' : _RESOURCE,
'__module__' : 'opentelemetry.proto.resource.v1.resource_pb2'
# @@protoc_insertion_point(class_scope:opentelemetry.proto.resource.v1.Resource)
})
_sym_db.RegisterMessage(Resource)
DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)
| 1,349 |
988 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.db.sql.visualeditor.querymodel;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;
import org.netbeans.api.db.sql.support.SQLIdentifiers;
public class QueryNode implements Query {
// Fields
SelectNode _select;
FromNode _from;
WhereNode _where;
GroupByNode _groupBy;
HavingNode _having;
OrderByNode _orderBy;
// Constructors
public QueryNode() {
}
public QueryNode(SelectNode select, FromNode from, WhereNode where,
GroupByNode groupBy, HavingNode having, OrderByNode orderBy) {
_select = select;
_from = from;
_where = where;
_groupBy = groupBy;
_having = having;
_orderBy = orderBy;
}
public QueryNode(SelectNode select, FromNode from) {
this(select, from, null, null, null, null);
}
// Methods
// Generate the SQL string corresponding to this model
public String genText(SQLIdentifiers.Quoter quoter) {
String res = _select.genText(quoter) + " " + _from.genText(quoter); // NOI18N
if (_where!=null)
res += _where.genText(quoter);
if (_groupBy!=null)
res += _groupBy.genText(quoter);
if (_having!=null)
res += _having.genText(quoter);
if (_orderBy!=null)
res += _orderBy.genText(quoter);
return res;
}
// Dump out the model, for debugging purposes
public String toString() {
return (_select.toString() +
_from.toString() +
_where.toString() );
}
// Accessors/Mutators
public Select getSelect() {
return _select;
}
public void setSelect(Select select) {
_select = (SelectNode)select;
}
public From getFrom() {
return _from;
}
public void setFrom(From from) {
_from = (FromNode)from;
}
public Where getWhere() {
return _where;
}
public void setWhere(Where where) {
_where = (WhereNode)where;
}
public GroupBy getGroupBy() {
return _groupBy;
}
public void setGroupBy(GroupBy groupBy) {
_groupBy = (GroupByNode)groupBy;
}
public OrderBy getOrderBy() {
return _orderBy;
}
public void setOrderBy(OrderBy orderBy) {
_orderBy = (OrderByNode)orderBy;
}
public Having getHaving() {
return _having;
}
public void setHaving(Having having) {
_having = (HavingNode)having;
}
public void removeTable (String tableSpec) {
// Find the FROM clause for this tableName, and remove it
_from.removeTable(tableSpec);
// ToDo: Remove any other joins that mention this table?
// Find any SELECT targets for this tableName, and remove them
_select.removeTable(tableSpec);
// Find any WHERE clauses that mention this table, and remove them
if (_where!=null) {
_where.removeTable(tableSpec);
if (_where.getExpression() == null)
_where = null;
}
// Find any GROUPBY clauses that mention this table, and remove them
if (_groupBy!=null)
{
_groupBy.removeTable(tableSpec);
if (_from._tableList.size() == 0)
_groupBy = null;
}
removeSortSpecification(tableSpec);
}
public void replaceStar(ColumnProvider tableReader) {
if (_select.hasAsteriskQualifier()) { // NOI18N
// Hack - if there's a star, just replace the whole list
List<ColumnNode> columns = new ArrayList<>();
// Get the list of table objects from FROM
List<Table> tables = _from.getTables();
// Iterate through it
for (int i=0; i<tables.size(); i++) {
TableNode tbl = (TableNode) tables.get(i);
String fullTableName = tbl.getFullTableName();
List<String> columnNames = new ArrayList<>();
tableReader.getColumnNames(fullTableName, columnNames);
String corrName=tbl.getCorrName();
String tableName=tbl.getTableName();
String schemaName=tbl.getSchemaName();
for (int j=0; j<columnNames.size(); j++) {
String columnName = columnNames.get(j);
columns.add(new ColumnNode(tableName, columnName, corrName, schemaName));
}
}
_select.setColumnList(columns);
}
}
public void addColumn(String tableSpec, String columnName) {
// Get the corresponding Table object from the FROM, to resolve issues
// of corrName/tableName
Table table = _from.findTable(tableSpec);
ColumnNode col = new ColumnNode(table, columnName);
// Note that they will share the column. Copy if this causes problem
_select.addColumn(col);
if (_groupBy != null)
_groupBy.addColumn(col);
}
public void removeColumn(String tableSpec, String columnName) {
_select.removeColumn(tableSpec, columnName);
if (_groupBy != null)
_groupBy.removeColumn(tableSpec, columnName);
// Remove the sort spec for this column if there was one
removeSortSpecification(tableSpec, columnName);
}
public void renameTableSpec(String oldTableSpec, String corrName) {
_from.renameTableSpec(oldTableSpec, corrName);
_select.renameTableSpec(oldTableSpec, corrName);
if (_where!=null)
_where.renameTableSpec(oldTableSpec, corrName);
if (_groupBy!=null)
_groupBy.renameTableSpec(oldTableSpec, corrName);
if (_having!=null)
_having.renameTableSpec(oldTableSpec, corrName);
if (_orderBy!=null)
_orderBy.renameTableSpec(oldTableSpec, corrName);
}
public void getReferencedColumns(Collection columns) {
_from.getReferencedColumns(columns);
_select.getReferencedColumns(columns);
if (_where!=null)
_where.getReferencedColumns(columns);
if (_groupBy!=null)
_groupBy.getReferencedColumns(columns);
if (_having!=null)
_having.getReferencedColumns(columns);
if (_orderBy!=null)
_orderBy.getReferencedColumns(columns);
}
//
// private implementation
//
private void removeSortSpecification(String tableSpec) {
if (_orderBy!=null)
_orderBy.removeSortSpecification(tableSpec);
}
private void removeSortSpecification(String tableSpec, String columnName) {
if (_orderBy!=null)
_orderBy.removeSortSpecification(tableSpec, columnName);
}
}
| 3,138 |
2,606 | /**
*
*/
package weixin.popular.bean.shakearound.device.group.deletedevice;
import weixin.popular.bean.shakearound.device.group.adddevice.DeviceGroupAddDevice;
/**
* 微信摇一摇周边-从分组中移除设备-请求参数
* @author Moyq5
* @date 2016年7月31日
*/
public class DeviceGroupDeleteDevice extends DeviceGroupAddDevice {
}
| 166 |
864 | <reponame>swigger/mxe<filename>src/wxwidgets-test.cpp
/*
* This file is part of MXE. See LICENSE.md for licensing information.
*/
#include <wx/wx.h>
class TestApp: public wxApp
{
private:
bool OnInit()
{
wxFrame *frame = new wxFrame(0, -1, _("Hello, World!"));
frame->Show(true);
SetTopWindow(frame);
return true;
}
};
IMPLEMENT_APP(TestApp)
| 173 |
2,113 | /*
* Copyright 2006 Sony Computer Entertainment Inc.
*
* Licensed under the SCEA Shared Source License, Version 1.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://research.scea.com/scea_shared_source_license.html
*
* 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.
*/
#ifndef __domGles_sampler_state_h__
#define __domGles_sampler_state_h__
#include <dae/daeDocument.h>
#include <dom/domTypes.h>
#include <dom/domElements.h>
#include <dom/domExtra.h>
class DAE;
/**
* Two-dimensional texture sampler state for profile_GLES. This is a bundle
* of sampler-specific states that will be referenced by one or more texture_units.
*/
class domGles_sampler_state_complexType
{
public:
class domWrap_s;
typedef daeSmartRef<domWrap_s> domWrap_sRef;
typedef daeTArray<domWrap_sRef> domWrap_s_Array;
class domWrap_s : public daeElement
{
public:
virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::WRAP_S; }
static daeInt ID() { return 157; }
virtual daeInt typeID() const { return ID(); }
protected: // Value
/**
* The domGles_sampler_wrap value of the text data of this element.
*/
domGles_sampler_wrap _value;
public: //Accessors and Mutators
/**
* Gets the value of this element.
* @return a domGles_sampler_wrap of the value.
*/
domGles_sampler_wrap getValue() const { return _value; }
/**
* Sets the _value of this element.
* @param val The new value for this element.
*/
void setValue( domGles_sampler_wrap val ) { _value = val; }
protected:
/**
* Constructor
*/
domWrap_s(DAE& dae) : daeElement(dae), _value() {}
/**
* Destructor
*/
virtual ~domWrap_s() {}
/**
* Overloaded assignment operator
*/
virtual domWrap_s &operator=( const domWrap_s &cpy ) { (void)cpy; return *this; }
public: // STATIC METHODS
/**
* Creates an instance of this class and returns a daeElementRef referencing it.
* @return a daeElementRef referencing an instance of this object.
*/
static DLLSPEC daeElementRef create(DAE& dae);
/**
* Creates a daeMetaElement object that describes this element in the meta object reflection framework.
* If a daeMetaElement already exists it will return that instead of creating a new one.
* @return A daeMetaElement describing this COLLADA element.
*/
static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};
class domWrap_t;
typedef daeSmartRef<domWrap_t> domWrap_tRef;
typedef daeTArray<domWrap_tRef> domWrap_t_Array;
class domWrap_t : public daeElement
{
public:
virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::WRAP_T; }
static daeInt ID() { return 158; }
virtual daeInt typeID() const { return ID(); }
protected: // Value
/**
* The domGles_sampler_wrap value of the text data of this element.
*/
domGles_sampler_wrap _value;
public: //Accessors and Mutators
/**
* Gets the value of this element.
* @return a domGles_sampler_wrap of the value.
*/
domGles_sampler_wrap getValue() const { return _value; }
/**
* Sets the _value of this element.
* @param val The new value for this element.
*/
void setValue( domGles_sampler_wrap val ) { _value = val; }
protected:
/**
* Constructor
*/
domWrap_t(DAE& dae) : daeElement(dae), _value() {}
/**
* Destructor
*/
virtual ~domWrap_t() {}
/**
* Overloaded assignment operator
*/
virtual domWrap_t &operator=( const domWrap_t &cpy ) { (void)cpy; return *this; }
public: // STATIC METHODS
/**
* Creates an instance of this class and returns a daeElementRef referencing it.
* @return a daeElementRef referencing an instance of this object.
*/
static DLLSPEC daeElementRef create(DAE& dae);
/**
* Creates a daeMetaElement object that describes this element in the meta object reflection framework.
* If a daeMetaElement already exists it will return that instead of creating a new one.
* @return A daeMetaElement describing this COLLADA element.
*/
static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};
class domMinfilter;
typedef daeSmartRef<domMinfilter> domMinfilterRef;
typedef daeTArray<domMinfilterRef> domMinfilter_Array;
class domMinfilter : public daeElement
{
public:
virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::MINFILTER; }
static daeInt ID() { return 159; }
virtual daeInt typeID() const { return ID(); }
protected: // Value
/**
* The domFx_sampler_filter_common value of the text data of this element.
*/
domFx_sampler_filter_common _value;
public: //Accessors and Mutators
/**
* Gets the value of this element.
* @return a domFx_sampler_filter_common of the value.
*/
domFx_sampler_filter_common getValue() const { return _value; }
/**
* Sets the _value of this element.
* @param val The new value for this element.
*/
void setValue( domFx_sampler_filter_common val ) { _value = val; }
protected:
/**
* Constructor
*/
domMinfilter(DAE& dae) : daeElement(dae), _value() {}
/**
* Destructor
*/
virtual ~domMinfilter() {}
/**
* Overloaded assignment operator
*/
virtual domMinfilter &operator=( const domMinfilter &cpy ) { (void)cpy; return *this; }
public: // STATIC METHODS
/**
* Creates an instance of this class and returns a daeElementRef referencing it.
* @return a daeElementRef referencing an instance of this object.
*/
static DLLSPEC daeElementRef create(DAE& dae);
/**
* Creates a daeMetaElement object that describes this element in the meta object reflection framework.
* If a daeMetaElement already exists it will return that instead of creating a new one.
* @return A daeMetaElement describing this COLLADA element.
*/
static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};
class domMagfilter;
typedef daeSmartRef<domMagfilter> domMagfilterRef;
typedef daeTArray<domMagfilterRef> domMagfilter_Array;
class domMagfilter : public daeElement
{
public:
virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::MAGFILTER; }
static daeInt ID() { return 160; }
virtual daeInt typeID() const { return ID(); }
protected: // Value
/**
* The domFx_sampler_filter_common value of the text data of this element.
*/
domFx_sampler_filter_common _value;
public: //Accessors and Mutators
/**
* Gets the value of this element.
* @return a domFx_sampler_filter_common of the value.
*/
domFx_sampler_filter_common getValue() const { return _value; }
/**
* Sets the _value of this element.
* @param val The new value for this element.
*/
void setValue( domFx_sampler_filter_common val ) { _value = val; }
protected:
/**
* Constructor
*/
domMagfilter(DAE& dae) : daeElement(dae), _value() {}
/**
* Destructor
*/
virtual ~domMagfilter() {}
/**
* Overloaded assignment operator
*/
virtual domMagfilter &operator=( const domMagfilter &cpy ) { (void)cpy; return *this; }
public: // STATIC METHODS
/**
* Creates an instance of this class and returns a daeElementRef referencing it.
* @return a daeElementRef referencing an instance of this object.
*/
static DLLSPEC daeElementRef create(DAE& dae);
/**
* Creates a daeMetaElement object that describes this element in the meta object reflection framework.
* If a daeMetaElement already exists it will return that instead of creating a new one.
* @return A daeMetaElement describing this COLLADA element.
*/
static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};
class domMipfilter;
typedef daeSmartRef<domMipfilter> domMipfilterRef;
typedef daeTArray<domMipfilterRef> domMipfilter_Array;
class domMipfilter : public daeElement
{
public:
virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::MIPFILTER; }
static daeInt ID() { return 161; }
virtual daeInt typeID() const { return ID(); }
protected: // Value
/**
* The domFx_sampler_filter_common value of the text data of this element.
*/
domFx_sampler_filter_common _value;
public: //Accessors and Mutators
/**
* Gets the value of this element.
* @return a domFx_sampler_filter_common of the value.
*/
domFx_sampler_filter_common getValue() const { return _value; }
/**
* Sets the _value of this element.
* @param val The new value for this element.
*/
void setValue( domFx_sampler_filter_common val ) { _value = val; }
protected:
/**
* Constructor
*/
domMipfilter(DAE& dae) : daeElement(dae), _value() {}
/**
* Destructor
*/
virtual ~domMipfilter() {}
/**
* Overloaded assignment operator
*/
virtual domMipfilter &operator=( const domMipfilter &cpy ) { (void)cpy; return *this; }
public: // STATIC METHODS
/**
* Creates an instance of this class and returns a daeElementRef referencing it.
* @return a daeElementRef referencing an instance of this object.
*/
static DLLSPEC daeElementRef create(DAE& dae);
/**
* Creates a daeMetaElement object that describes this element in the meta object reflection framework.
* If a daeMetaElement already exists it will return that instead of creating a new one.
* @return A daeMetaElement describing this COLLADA element.
*/
static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};
class domMipmap_maxlevel;
typedef daeSmartRef<domMipmap_maxlevel> domMipmap_maxlevelRef;
typedef daeTArray<domMipmap_maxlevelRef> domMipmap_maxlevel_Array;
class domMipmap_maxlevel : public daeElement
{
public:
virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::MIPMAP_MAXLEVEL; }
static daeInt ID() { return 162; }
virtual daeInt typeID() const { return ID(); }
protected: // Value
/**
* The xsUnsignedByte value of the text data of this element.
*/
xsUnsignedByte _value;
public: //Accessors and Mutators
/**
* Gets the value of this element.
* @return a xsUnsignedByte of the value.
*/
xsUnsignedByte getValue() const { return _value; }
/**
* Sets the _value of this element.
* @param val The new value for this element.
*/
void setValue( xsUnsignedByte val ) { _value = val; }
protected:
/**
* Constructor
*/
domMipmap_maxlevel(DAE& dae) : daeElement(dae), _value() {}
/**
* Destructor
*/
virtual ~domMipmap_maxlevel() {}
/**
* Overloaded assignment operator
*/
virtual domMipmap_maxlevel &operator=( const domMipmap_maxlevel &cpy ) { (void)cpy; return *this; }
public: // STATIC METHODS
/**
* Creates an instance of this class and returns a daeElementRef referencing it.
* @return a daeElementRef referencing an instance of this object.
*/
static DLLSPEC daeElementRef create(DAE& dae);
/**
* Creates a daeMetaElement object that describes this element in the meta object reflection framework.
* If a daeMetaElement already exists it will return that instead of creating a new one.
* @return A daeMetaElement describing this COLLADA element.
*/
static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};
class domMipmap_bias;
typedef daeSmartRef<domMipmap_bias> domMipmap_biasRef;
typedef daeTArray<domMipmap_biasRef> domMipmap_bias_Array;
class domMipmap_bias : public daeElement
{
public:
virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::MIPMAP_BIAS; }
static daeInt ID() { return 163; }
virtual daeInt typeID() const { return ID(); }
protected: // Value
/**
* The xsFloat value of the text data of this element.
*/
xsFloat _value;
public: //Accessors and Mutators
/**
* Gets the value of this element.
* @return a xsFloat of the value.
*/
xsFloat getValue() const { return _value; }
/**
* Sets the _value of this element.
* @param val The new value for this element.
*/
void setValue( xsFloat val ) { _value = val; }
protected:
/**
* Constructor
*/
domMipmap_bias(DAE& dae) : daeElement(dae), _value() {}
/**
* Destructor
*/
virtual ~domMipmap_bias() {}
/**
* Overloaded assignment operator
*/
virtual domMipmap_bias &operator=( const domMipmap_bias &cpy ) { (void)cpy; return *this; }
public: // STATIC METHODS
/**
* Creates an instance of this class and returns a daeElementRef referencing it.
* @return a daeElementRef referencing an instance of this object.
*/
static DLLSPEC daeElementRef create(DAE& dae);
/**
* Creates a daeMetaElement object that describes this element in the meta object reflection framework.
* If a daeMetaElement already exists it will return that instead of creating a new one.
* @return A daeMetaElement describing this COLLADA element.
*/
static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};
protected: // Attribute
/**
* The sid attribute is a text string value containing the sub-identifier
* of this element. This value must be unique within the scope of the parent
* element. Optional attribute.
*/
xsNCName attrSid;
protected: // Elements
domWrap_sRef elemWrap_s;
domWrap_tRef elemWrap_t;
domMinfilterRef elemMinfilter;
domMagfilterRef elemMagfilter;
domMipfilterRef elemMipfilter;
domMipmap_maxlevelRef elemMipmap_maxlevel;
domMipmap_biasRef elemMipmap_bias;
/**
* The extra element may appear any number of times. OpenGL ES extensions
* may be used here. @see domExtra
*/
domExtra_Array elemExtra_array;
public: //Accessors and Mutators
/**
* Gets the sid attribute.
* @return Returns a xsNCName of the sid attribute.
*/
xsNCName getSid() const { return attrSid; }
/**
* Sets the sid attribute.
* @param atSid The new value for the sid attribute.
*/
void setSid( xsNCName atSid ) { *(daeStringRef*)&attrSid = atSid;}
/**
* Gets the wrap_s element.
* @return a daeSmartRef to the wrap_s element.
*/
const domWrap_sRef getWrap_s() const { return elemWrap_s; }
/**
* Gets the wrap_t element.
* @return a daeSmartRef to the wrap_t element.
*/
const domWrap_tRef getWrap_t() const { return elemWrap_t; }
/**
* Gets the minfilter element.
* @return a daeSmartRef to the minfilter element.
*/
const domMinfilterRef getMinfilter() const { return elemMinfilter; }
/**
* Gets the magfilter element.
* @return a daeSmartRef to the magfilter element.
*/
const domMagfilterRef getMagfilter() const { return elemMagfilter; }
/**
* Gets the mipfilter element.
* @return a daeSmartRef to the mipfilter element.
*/
const domMipfilterRef getMipfilter() const { return elemMipfilter; }
/**
* Gets the mipmap_maxlevel element.
* @return a daeSmartRef to the mipmap_maxlevel element.
*/
const domMipmap_maxlevelRef getMipmap_maxlevel() const { return elemMipmap_maxlevel; }
/**
* Gets the mipmap_bias element.
* @return a daeSmartRef to the mipmap_bias element.
*/
const domMipmap_biasRef getMipmap_bias() const { return elemMipmap_bias; }
/**
* Gets the extra element array.
* @return Returns a reference to the array of extra elements.
*/
domExtra_Array &getExtra_array() { return elemExtra_array; }
/**
* Gets the extra element array.
* @return Returns a constant reference to the array of extra elements.
*/
const domExtra_Array &getExtra_array() const { return elemExtra_array; }
protected:
/**
* Constructor
*/
domGles_sampler_state_complexType(DAE& dae, daeElement* elt) : attrSid(), elemWrap_s(), elemWrap_t(), elemMinfilter(), elemMagfilter(), elemMipfilter(), elemMipmap_maxlevel(), elemMipmap_bias(), elemExtra_array() {}
/**
* Destructor
*/
virtual ~domGles_sampler_state_complexType() {}
/**
* Overloaded assignment operator
*/
virtual domGles_sampler_state_complexType &operator=( const domGles_sampler_state_complexType &cpy ) { (void)cpy; return *this; }
};
/**
* An element of type domGles_sampler_state_complexType.
*/
class domGles_sampler_state : public daeElement, public domGles_sampler_state_complexType
{
public:
virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::GLES_SAMPLER_STATE; }
static daeInt ID() { return 164; }
virtual daeInt typeID() const { return ID(); }
public: //Accessors and Mutators
/**
* Gets the sid attribute.
* @return Returns a xsNCName of the sid attribute.
*/
xsNCName getSid() const { return attrSid; }
/**
* Sets the sid attribute.
* @param atSid The new value for the sid attribute.
*/
void setSid( xsNCName atSid ) { *(daeStringRef*)&attrSid = atSid; _validAttributeArray[0] = true; }
protected:
/**
* Constructor
*/
domGles_sampler_state(DAE& dae) : daeElement(dae), domGles_sampler_state_complexType(dae, this) {}
/**
* Destructor
*/
virtual ~domGles_sampler_state() {}
/**
* Overloaded assignment operator
*/
virtual domGles_sampler_state &operator=( const domGles_sampler_state &cpy ) { (void)cpy; return *this; }
public: // STATIC METHODS
/**
* Creates an instance of this class and returns a daeElementRef referencing it.
* @return a daeElementRef referencing an instance of this object.
*/
static DLLSPEC daeElementRef create(DAE& dae);
/**
* Creates a daeMetaElement object that describes this element in the meta object reflection framework.
* If a daeMetaElement already exists it will return that instead of creating a new one.
* @return A daeMetaElement describing this COLLADA element.
*/
static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};
#endif
| 6,186 |
1,532 | <gh_stars>1000+
#!/usr/bin/env python
"""
Example script to train (unconditional) template creation.
If you use this code, please cite the following:
Learning Conditional Deformable Templates with Convolutional Networks
<NAME>, <NAME>, <NAME>, <NAME>
NeurIPS 2019. https://arxiv.org/abs/1908.02738
Copyright 2020 <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.
"""
import os
import random
import argparse
import numpy as np
import tensorflow as tf
import voxelmorph as vxm
# disable eager execution
tf.compat.v1.disable_eager_execution()
# parse the commandline
parser = argparse.ArgumentParser()
# data organization parameters
parser.add_argument('--img-list', required=True, help='line-seperated list of training files')
parser.add_argument('--img-prefix', help='optional input image file prefix')
parser.add_argument('--img-suffix', help='optional input image file suffix')
parser.add_argument('--init-template', help='initial template image')
parser.add_argument('--model-dir', default='models',
help='model output directory (default: models)')
parser.add_argument('--multichannel', action='store_true',
help='specify that data has multiple channels')
# training parameters
parser.add_argument('--gpu', default='0', help='GPU ID numbers (default: 0)')
parser.add_argument('--batch-size', type=int, default=1, help='batch size (default: 1)')
parser.add_argument('--epochs', type=int, default=1500,
help='number of training epochs (default: 1500)')
parser.add_argument('--steps-per-epoch', type=int, default=100,
help='frequency of model saves (default: 100)')
parser.add_argument('--load-weights', help='optional weights file to initialize with')
parser.add_argument('--initial-epoch', type=int, default=0,
help='initial epoch number (default: 0)')
parser.add_argument('--lr', type=float, default=1e-4, help='learning rate (default: 1e-4)')
# network architecture parameters
parser.add_argument('--enc', type=int, nargs='+',
help='list of unet encoder filters (default: 16 32 32 32)')
parser.add_argument('--dec', type=int, nargs='+',
help='list of unet decorder filters (default: 32 32 32 32 32 16 16)')
# loss hyperparameters
parser.add_argument('--image-loss', default='mse',
help='image reconstruction loss - can be mse or ncc (default: mse)')
parser.add_argument('--image-loss-weight', type=float, default=0.5,
help='relative weight of transformed atlas loss (default: 1.0)')
parser.add_argument('--mean-loss-weight', type=float, default=1.0,
help='weight of mean stream loss (default: 1.0)')
parser.add_argument('--grad-loss-weight', type=float, default=0.01,
help='weight of gradient loss (lamba) (default: 0.01)')
args = parser.parse_args()
# load and prepare training data
train_files = vxm.py.utils.read_file_list(args.img_list, prefix=args.img_prefix,
suffix=args.img_suffix)
assert len(train_files) > 0, 'Could not find any training data.'
# prepare model folder
model_dir = args.model_dir
os.makedirs(model_dir, exist_ok=True)
# no need to append an extra feature axis if data is multichannel
add_feat_axis = not args.multichannel
# prepare the initial weights for the template
if args.init_template:
# load template from file
template = vxm.py.utils.load_volfile(args.init_template,
add_batch_axis=True, add_feat_axis=add_feat_axis)
else:
# generate rough atlas by averaging inputs
navgs = min((100, len(train_files)))
print('Creating starting template by averaging first %d scans.' % navgs)
template = 0
for scan in train_files[:navgs]:
template += vxm.py.utils.load_volfile(scan, add_batch_axis=True,
add_feat_axis=add_feat_axis)
template /= navgs
# save average input atlas for the record
vxm.py.utils.save_volfile(template.squeeze(), os.path.join(model_dir, 'init_template.nii.gz'))
# get template shape (might differ from image input shape)
template_shape = template.shape[1:-1]
nfeats = template.shape[-1]
# tensorflow device handling
device, nb_devices = vxm.tf.utils.setup_device(args.gpu)
# unet architecture
enc_nf = args.enc if args.enc else [16, 32, 32, 32]
dec_nf = args.dec if args.dec else [32, 32, 32, 32, 32, 16, 16]
# configure generator
generator = vxm.generators.template_creation(
train_files, bidir=True, batch_size=args.batch_size, add_feat_axis=add_feat_axis)
# prepare model checkpoint save path
save_filename = os.path.join(model_dir, '{epoch:04d}.h5')
# build model
model = vxm.networks.TemplateCreation(
template_shape,
nb_unet_features=[enc_nf, dec_nf],
atlas_feats=nfeats,
src_feats=nfeats
)
# set initial template weights
model.set_atlas(template)
# load initial weights (if provided)
if args.load_weights:
model.load_weights(args.load_weights, by_name=True)
# prepare image loss
if args.image_loss == 'ncc':
image_loss_func = vxm.losses.NCC().loss
elif args.image_loss == 'mse':
image_loss_func = vxm.losses.MSE().loss
else:
raise ValueError('Image loss should be "mse" or "ncc", but found "%s"' % args.image_loss)
# make sure the warped target is compared to the generated atlas and not the input atlas
neg_loss_func = lambda _, y_pred: image_loss_func(model.references.atlas_tensor, y_pred)
losses = [image_loss_func, neg_loss_func,
vxm.losses.MSE().loss, vxm.losses.Grad('l2', loss_mult=2).loss]
weights = [args.image_loss_weight, 1 - args.image_loss_weight,
args.mean_loss_weight, args.grad_loss_weight]
# multi-gpu support
if nb_devices > 1:
save_callback = vxm.networks.ModelCheckpointParallel(save_filename)
model = tf.keras.utils.multi_gpu_model(model, gpus=nb_devices)
else:
save_callback = tf.keras.callbacks.ModelCheckpoint(save_filename, period=20)
model.compile(optimizer=tf.keras.optimizers.Adam(lr=args.lr), loss=losses, loss_weights=weights)
# save starting weights
model.save(save_filename.format(epoch=args.initial_epoch))
model.fit_generator(generator,
initial_epoch=args.initial_epoch,
epochs=args.epochs,
callbacks=[save_callback],
steps_per_epoch=args.steps_per_epoch,
verbose=1
)
vxm.py.utils.save_volfile(model.get_atlas(), os.path.join(model_dir, 'template.nii.gz'))
| 2,687 |
630 | <filename>src/main/java/com/bmwcarit/barefoot/matcher/MatcherTransition.java
/*
* Copyright (C) 2015, BMW Car IT GmbH
*
* Author: <NAME> <<EMAIL>>
*
* 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.bmwcarit.barefoot.matcher;
import org.json.JSONException;
import org.json.JSONObject;
import com.bmwcarit.barefoot.markov.StateTransition;
import com.bmwcarit.barefoot.roadmap.RoadMap;
import com.bmwcarit.barefoot.roadmap.Route;
/**
* State transition between matching candidates in Hidden Markov Model (HMM) map matching and
* contains a route between respective map positions.
*/
public class MatcherTransition extends StateTransition {
private Route route = null;
/**
* Creates {@link MatcherTransition} object.
*
* @param route {@link Route} object as state transition in map matching.
*/
public MatcherTransition(Route route) {
this.route = route;
}
/**
* Creates {@link MatcherTransition} object from its JSON representation.
*
* @param json JSON representation of {@link MatcherTransition} object.
* @param map {@link RoadMap} object
* @throws JSONException thrown on JSON parse error.
*/
public MatcherTransition(JSONObject json, RoadMap map) throws JSONException {
super(json);
route = Route.fromJSON(json.getJSONObject("route"), map);
}
/**
* Gets {@link Route} object of the state transition.
*
* @return {@link Route} object of the state transition.
*/
public Route route() {
return route;
}
@Override
public JSONObject toJSON() throws JSONException {
JSONObject json = super.toJSON();
json.put("route", route.toJSON());
return json;
}
}
| 735 |
438 | //
// UIScrollView+FWPlayer.h
// FWPlayerCore
//
// Created by <NAME> on 2019-06-26.
// Copyright © 2019 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/*
* The scroll direction of scrollView.
*/
typedef NS_ENUM(NSUInteger, FWPlayerScrollDirection) {
FWPlayerScrollDirectionNone,
FWPlayerScrollDirectionUp, // Scroll up
FWPlayerScrollDirectionDown, // Scroll Down
FWPlayerScrollDirectionLeft, // Scroll left
FWPlayerScrollDirectionRight // Scroll right
};
/*
* The scrollView direction.
*/
typedef NS_ENUM(NSInteger, FWPlayerScrollViewDirection) {
FWPlayerScrollViewDirectionVertical,
FWPlayerScrollViewDirectionHorizontal
};
/*
* The player container type
*/
typedef NS_ENUM(NSInteger, FWPlayerContainerType) {
FWPlayerContainerTypeCell,
FWPlayerContainerTypeView
};
@interface UIScrollView (FWPlayer)
/// When the FWPlayerScrollViewDirection is FWPlayerScrollViewDirectionVertical,the property has value.
@property (nonatomic, readonly) CGFloat fw_lastOffsetY;
/// When the FWPlayerScrollViewDirection is FWPlayerScrollViewDirectionHorizontal,the property has value.
@property (nonatomic, readonly) CGFloat fw_lastOffsetX;
/// The indexPath is playing.
@property (nonatomic, nullable) NSIndexPath *fw_playingIndexPath;
/// The indexPath that should play, the one that lights up.
@property (nonatomic, nullable) NSIndexPath *fw_shouldPlayIndexPath;
/// WWANA networks play automatically,default NO.
@property (nonatomic, getter=fw_isWWANAutoPlay) BOOL fw_WWANAutoPlay;
/// The player should auto player,default is YES.
@property (nonatomic) BOOL fw_shouldAutoPlay;
/// The view tag that the player display in scrollView.
@property (nonatomic) NSInteger fw_containerViewTag;
/// The scrollView scroll direction, default is FWPlayerScrollViewDirectionVertical.
@property (nonatomic) FWPlayerScrollViewDirection fw_scrollViewDirection;
/// The scroll direction of scrollView while scrolling.
/// When the FWPlayerScrollViewDirection is FWPlayerScrollViewDirectionVertical,this value can only be FWPlayerScrollDirectionUp or FWPlayerScrollDirectionDown.
/// When the FWPlayerScrollViewDirection is FWPlayerScrollViewDirectionVertical,this value can only be FWPlayerScrollDirectionLeft or FWPlayerScrollDirectionRight.
@property (nonatomic, readonly) FWPlayerScrollDirection fw_scrollDirection;
/// The video contrainerView type.
@property (nonatomic, assign) FWPlayerContainerType fw_containerType;
/// The video contrainerView in normal model.
@property (nonatomic, strong) UIView *fw_containerView;
/// The currently playing cell stop playing when the cell has out off the screen,defalut is YES.
@property (nonatomic, assign) BOOL fw_stopWhileNotVisible;
/// Has stopped playing
@property (nonatomic, assign) BOOL fw_stopPlay;
/// The block invoked When the player did stop scroll.
@property (nonatomic, copy, nullable) void(^fw_scrollViewDidStopScrollCallback)(NSIndexPath *indexPath);
/// The block invoked When the player did scroll.
@property (nonatomic, copy, nullable) void(^fw_scrollViewDidScrollCallback)(NSIndexPath *indexPath);
/// The block invoked When the player should play.
@property (nonatomic, copy, nullable) void(^fw_shouldPlayIndexPathCallback)(NSIndexPath *indexPath);
/// Filter the cell that should be played when the scroll is stopped (to play when the scroll is stopped).
- (void)fw_filterShouldPlayCellWhileScrolled:(void (^ __nullable)(NSIndexPath *indexPath))handler;
/// Filter the cell that should be played while scrolling (you can use this to filter the highlighted cell).
- (void)fw_filterShouldPlayCellWhileScrolling:(void (^ __nullable)(NSIndexPath *indexPath))handler;
/// Get the cell according to indexPath.
- (UIView *)fw_getCellForIndexPath:(NSIndexPath *)indexPath;
/// Scroll to indexPath with animations.
- (void)fw_scrollToRowAtIndexPath:(NSIndexPath *)indexPath completionHandler:(void (^ __nullable)(void))completionHandler;
/// add in 3.2.4 version.
/// Scroll to indexPath with animations.
- (void)fw_scrollToRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated completionHandler:(void (^ __nullable)(void))completionHandler;
/// add in 3.2.8 version.
/// Scroll to indexPath with animations duration.
- (void)fw_scrollToRowAtIndexPath:(NSIndexPath *)indexPath animateWithDuration:(NSTimeInterval)duration completionHandler:(void (^ __nullable)(void))completionHandler;
///------------------------------------
/// The following method must be implemented in UIScrollViewDelegate.
///------------------------------------
- (void)fw_scrollViewDidEndDecelerating;
- (void)fw_scrollViewDidEndDraggingWillDecelerate:(BOOL)decelerate;
- (void)fw_scrollViewDidScrollToTop;
- (void)fw_scrollViewDidScroll;
- (void)fw_scrollViewWillBeginDragging;
///------------------------------------
/// end
///------------------------------------
@end
@interface UIScrollView (FWPlayerCannotCalled)
/// The block invoked When the player appearing.
@property (nonatomic, copy, nullable) void(^fw_playerAppearingInScrollView)(NSIndexPath *indexPath, CGFloat playerApperaPercent);
/// The block invoked When the player disappearing.
@property (nonatomic, copy, nullable) void(^fw_playerDisappearingInScrollView)(NSIndexPath *indexPath, CGFloat playerDisapperaPercent);
/// The block invoked When the player will appeared.
@property (nonatomic, copy, nullable) void(^fw_playerWillAppearInScrollView)(NSIndexPath *indexPath);
/// The block invoked When the player did appeared.
@property (nonatomic, copy, nullable) void(^fw_playerDidAppearInScrollView)(NSIndexPath *indexPath);
/// The block invoked When the player will disappear.
@property (nonatomic, copy, nullable) void(^fw_playerWillDisappearInScrollView)(NSIndexPath *indexPath);
/// The block invoked When the player did disappeared.
@property (nonatomic, copy, nullable) void(^fw_playerDidDisappearInScrollView)(NSIndexPath *indexPath);
/// The current player scroll slides off the screen percent.
/// the property used when the `stopWhileNotVisible` is YES, stop the current playing player.
/// the property used when the `stopWhileNotVisible` is NO, the current playing player add to small container view.
/// 0.0~1.0, defalut is 0.5.
/// 0.0 is the player will disappear.
/// 1.0 is the player did disappear.
@property (nonatomic) CGFloat fw_playerDisapperaPercent;
/// The current player scroll to the screen percent to play the video.
/// 0.0~1.0, defalut is 0.0.
/// 0.0 is the player will appear.
/// 1.0 is the player did appear.
@property (nonatomic) CGFloat fw_playerApperaPercent;
/// The current player controller is disappear, not dealloc
@property (nonatomic) BOOL fw_viewControllerDisappear;
@end
NS_ASSUME_NONNULL_END
| 1,998 |
2,151 | // Copyright (C) 2014 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <libaddressinput/address_normalizer.h>
#include <libaddressinput/address_data.h>
#include <libaddressinput/callback.h>
#include <libaddressinput/null_storage.h>
#include <libaddressinput/preload_supplier.h>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "testdata_source.h"
namespace {
using i18n::addressinput::AddressData;
using i18n::addressinput::AddressNormalizer;
using i18n::addressinput::BuildCallback;
using i18n::addressinput::NullStorage;
using i18n::addressinput::PreloadSupplier;
using i18n::addressinput::TestdataSource;
class AddressNormalizerTest : public testing::Test {
public:
AddressNormalizerTest(const AddressNormalizerTest&) = delete;
AddressNormalizerTest& operator=(const AddressNormalizerTest&) = delete;
protected:
AddressNormalizerTest()
: supplier_(new TestdataSource(true), new NullStorage),
loaded_(BuildCallback(this, &AddressNormalizerTest::OnLoaded)),
normalizer_(&supplier_) {}
PreloadSupplier supplier_;
const std::unique_ptr<const PreloadSupplier::Callback> loaded_;
const AddressNormalizer normalizer_;
private:
void OnLoaded(bool success, const std::string& region_code, int num_rules) {
ASSERT_TRUE(success);
ASSERT_FALSE(region_code.empty());
ASSERT_LT(0, num_rules);
}
};
TEST_F(AddressNormalizerTest, CountryWithNoLanguageNoAdminArea) {
// This test is to make sure that Normalize would not crash for the case where
// there is neither a language, nor an admin area listed for the rule.
supplier_.LoadRules("IR", *loaded_);
i18n::addressinput::AddressData address;
address.region_code = "IR";
address.administrative_area = "Tehran";
normalizer_.Normalize(&address);
EXPECT_EQ("Tehran", address.administrative_area);
}
TEST_F(AddressNormalizerTest, BrazilAdminAreaAndLocality) {
// A country with more than two levels of data
supplier_.LoadRules("BR", *loaded_);
i18n::addressinput::AddressData address;
address.region_code = "BR";
address.administrative_area = "Maranhão";
address.locality = "Cantanhede";
normalizer_.Normalize(&address);
EXPECT_EQ("MA", address.administrative_area); // For Maranhão
EXPECT_EQ("Cantanhede", address.locality);
}
TEST_F(AddressNormalizerTest, FrenchCanadaNameLanguageNotConsistent) {
supplier_.LoadRules("CA", *loaded_);
i18n::addressinput::AddressData address;
address.language_code = "en-CA";
address.region_code = "CA";
address.administrative_area = "Nouveau-Brunswick";
normalizer_.Normalize(&address);
// Normalize will look into every available language for that region,
// not only the supplied or the default language.
EXPECT_EQ("NB", address.administrative_area);
}
TEST_F(AddressNormalizerTest, FrenchCanadaName) {
supplier_.LoadRules("CA", *loaded_);
i18n::addressinput::AddressData address;
address.language_code = "fr-CA";
address.region_code = "CA";
address.administrative_area = "Nouveau-Brunswick";
normalizer_.Normalize(&address);
EXPECT_EQ("NB", address.administrative_area);
}
TEST_F(AddressNormalizerTest, FrenchCanadaNameLanguageNotListed) {
supplier_.LoadRules("CA", *loaded_);
i18n::addressinput::AddressData address;
address.language_code = "fa-CA";
address.region_code = "CA";
address.administrative_area = "Colombie-Britannique";
normalizer_.Normalize(&address);
EXPECT_EQ("BC", address.administrative_area);
}
TEST_F(AddressNormalizerTest, CaliforniaShortNameCa) {
supplier_.LoadRules("US", *loaded_);
AddressData address;
address.language_code = "en-US";
address.region_code = "US";
address.administrative_area = "California";
address.locality = "Mountain View";
normalizer_.Normalize(&address);
EXPECT_EQ("CA", address.administrative_area);
}
TEST_F(AddressNormalizerTest, CountryWithNonStandardData) {
// This test is to make sure that Normalize would not crash for the case where
// the data is not standard and key--language does not exist.
supplier_.LoadRules("HK", *loaded_);
i18n::addressinput::AddressData address;
address.region_code = "HK";
address.administrative_area = "香港島";
normalizer_.Normalize(&address);
EXPECT_EQ("香港島", address.administrative_area);
}
TEST_F(AddressNormalizerTest, GangwonLatinNameStaysUnchanged) {
supplier_.LoadRules("KR", *loaded_);
AddressData address;
address.language_code = "ko-Latn";
address.region_code = "KR";
address.administrative_area = "Gangwon";
normalizer_.Normalize(&address);
EXPECT_EQ("Gangwon", address.administrative_area);
}
TEST_F(AddressNormalizerTest, GangwonKoreanName) {
supplier_.LoadRules("KR", *loaded_);
AddressData address;
address.language_code = "ko-KR";
address.region_code = "KR";
address.administrative_area = u8"강원";
normalizer_.Normalize(&address);
EXPECT_EQ(u8"강원도", address.administrative_area);
}
TEST_F(AddressNormalizerTest, DontSwitchLatinScriptForUnknownLanguage) {
supplier_.LoadRules("KR", *loaded_);
AddressData address;
address.region_code = "KR";
address.administrative_area = "Gangwon";
normalizer_.Normalize(&address);
EXPECT_EQ("Gangwon", address.administrative_area);
}
TEST_F(AddressNormalizerTest, DontSwitchLocalScriptForUnknownLanguage) {
supplier_.LoadRules("KR", *loaded_);
AddressData address;
address.region_code = "KR";
address.administrative_area = u8"강원";
normalizer_.Normalize(&address);
EXPECT_EQ(u8"강원도", address.administrative_area);
}
} // namespace
| 1,956 |
356 | <gh_stars>100-1000
/*
* Copyright (C) 2019 University of South Florida
*
* 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.onebusaway.android.travelbehavior.io.task;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.gson.Gson;
import org.apache.commons.io.FileUtils;
import org.onebusaway.android.app.Application;
import org.onebusaway.android.travelbehavior.constants.TravelBehaviorConstants;
import org.onebusaway.android.travelbehavior.io.TravelBehaviorFileSaverExecutorManager;
import org.onebusaway.android.travelbehavior.model.DestinationReminderData;
import org.onebusaway.android.travelbehavior.model.DestinationReminderInfo;
import org.onebusaway.android.util.PreferenceUtils;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DestinationReminderDataSaverTask implements Runnable {
private static final String TAG = "TravelBehaviorDestRmdr";
private String mCurrStopId;
private String mDestStopId;
private String mTripId;
private String mRouteId;
private long mServerTime;
private Context mApplicationContext;
public DestinationReminderDataSaverTask(String currStopId, String destStopId,
String tripId, String routeId, long serverTime, Context applicationContext) {
mCurrStopId = currStopId;
mDestStopId = destStopId;
mTripId = tripId;
mRouteId = routeId;
mServerTime = serverTime;
mApplicationContext = applicationContext;
}
@Override
public void run() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
mApplicationContext.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
mApplicationContext.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
saveDestinationReminders(null);
} else {
requestFusedLocation();
}
}
@SuppressLint("MissingPermission")
private void requestFusedLocation() {
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(mApplicationContext);
client.getLastLocation().addOnSuccessListener(TravelBehaviorFileSaverExecutorManager.
getInstance().getThreadPoolExecutor(), location -> {
saveDestinationReminders(location);
});
}
private void saveDestinationReminders(Location location) {
try {
// Get the counter that's incremented for each test
int counter = Application.getPrefs().getInt(TravelBehaviorConstants.DESTINATION_REMINDER_COUNTER, 0);
PreferenceUtils.saveInt(TravelBehaviorConstants.DESTINATION_REMINDER_COUNTER, ++counter);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d yyyy, hh:mm aaa");
Date time = Calendar.getInstance().getTime();
String readableDate = sdf.format(time);
File subFolder = new File(Application.get().getApplicationContext()
.getFilesDir().getAbsolutePath() + File.separator +
TravelBehaviorConstants.LOCAL_DESTINATION_REMINDER_FOLDER);
if (!subFolder.exists()) {
subFolder.mkdirs();
}
Long localElapsedRealtimeNanos = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
localElapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos();
}
File file = new File(subFolder, counter + "-" + readableDate + ".json");
DestinationReminderData drd = new DestinationReminderData(mCurrStopId ,mDestStopId,
mTripId, mRouteId, Application.get().getCurrentRegion().getId(),
localElapsedRealtimeNanos, time.getTime(), mServerTime, location);
// Used Gson instead of Jackson library - Jackson had problems while deserializing
// nested objects. When we deserialize the object and push it to Firebase, Firebase API
// throws a null pointer exception. Serializing and deserializing this arrival and
// departure data with Gson fixed the problem.
Gson gson = new Gson();
String data = gson.toJson(drd);
FileUtils.write(file, data, false);
} catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
}
| 2,016 |
460 | <gh_stars>100-1000
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "BT_Gesture.h"
class ShoveGesture : public Gesture
{
private:
// Maximum distance between a finger and line of best fit between fingers for recognition
static const float MAXIMUM_LINE_DEVIATION;
// Minimum squared hypotenuse of touch point to be recognized as side of finger / hand
static const int MINIMUM_SIDE_CONTACT_HYPOTENUSE;
bool _horizontal; // whether shove is horizontal or vertical (opposite of contact edge)
Path * _shoveGesturePath; // The active gesture path used to calculated movement direction
TouchPoint * _lastTouchPoint; // Touch point in _shoveGesturePath used to calculate movement direction
protected:
virtual void clearGesture();
virtual Detected isRecognizedImpl(GestureContext *gestureContext);
virtual bool processGestureImpl(GestureContext *gestureContext);
public:
ShoveGesture();
}; | 444 |
1,010 | <filename>src/test/preload/shd-test-preload-dl-main.c
/*
* The Shadow Simulator
* See LICENSE for licensing information
*/
#if !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
typedef int (*run_test_func)(void);
int main(int argc, char* argv[]) {
fprintf(stdout, "########## preload test starting ##########\n");
if(argc != 2) {
fprintf(stdout, "incorrect arg count '%i'\n", argc);
fprintf(stdout, "########## preload test failed\n");
return EXIT_FAILURE;
}
char* plugin_path = argv[1];
fprintf(stdout, "dynamically loading test from '%s'\n", plugin_path);
/* clear error string */
dlerror();
/* open the plugin that contains our test function */
void* plugin_handle = dlmopen(LM_ID_NEWLM, plugin_path, RTLD_LAZY|RTLD_LOCAL);
//void* plugin_handle = dlopen(plugin_path, RTLD_LAZY|RTLD_LOCAL);
if(!plugin_handle) {
fprintf(stdout, "dlmopen() for path '%s' returned NULL, dlerror is '%s'\n", plugin_path, dlerror());
fprintf(stdout, "########## preload test failed\n");
return EXIT_FAILURE;
}
/* clear dlerror */
dlerror();
/* get our test function symbol so we can call it */
run_test_func run_test = dlsym(plugin_handle, "run_test");
if(!run_test) {
fprintf(stdout, "dlsym() for symbol 'run_test' returned NULL, dlerror is '%s'\n", dlerror());
fprintf(stdout, "########## preload test failed\n");
return EXIT_FAILURE;
}
if(run_test() != 0) {
fprintf(stdout, "test case returned failure\n");
fprintf(stdout, "########## preload test failed\n");
return EXIT_FAILURE;
} else {
fprintf(stdout, "########## preload test passed! ##########\n");
return EXIT_SUCCESS;
}
}
| 775 |
799 | import json
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
def calculate_overall(data: dict = None) -> str:
if not data:
return ""
results = [x["Result"] for x in data]
if "Not Achieved" in results:
return "Not Achieved"
elif "Partially Achieved" in results:
return "Partially Achieved"
else:
return "Achieved"
def main():
query = '-status:closed -category:job type:"NCSC CAF Assessment"'
incidents = demisto.executeCommand("getIncidents", {"query": query})[0]["Contents"][
"data"
]
if len(incidents) < 1:
return ""
incidents = sorted(incidents, key=lambda x: x["id"])
incident = incidents[0]
if incident:
md: str = ""
custom_fields = incident.get("CustomFields")
assessment_a_details = json.loads(custom_fields.get("cafaresultraw"))
assessment_b_details = json.loads(custom_fields.get("cafbresultraw"))
assessment_c_details = json.loads(custom_fields.get("cafcresultraw"))
assessment_d_details = json.loads(custom_fields.get("cafdresultraw"))
assessments = [
{
"assessment": "CAF Objective A - Managing security risk",
"details": assessment_a_details,
},
{
"assessment": "CAF Objective B - Protecting against cyber-attack",
"details": assessment_b_details,
},
{
"assessment": "CAF Objective C - Detecting cyber security events",
"details": assessment_c_details,
},
{
"assessment": "CAF Objective D - Minimising the impact of cyber security incidents",
"details": assessment_d_details,
},
]
for assessment in assessments:
table = tableToMarkdown(
assessment["assessment"],
assessment["details"],
["Question", "Result", "Reason"],
)
md += f"{table}\n\n"
else:
md = ""
demisto.results(md)
if __name__ in ["__main__", "__builtin__", "builtins"]:
main()
| 1,001 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
// include required headers
#include "StandardHeaders.h"
// some c++11 concurrency features
#include <AzCore/std/functional.h>
#include <AzCore/std/parallel/mutex.h>
#include <AzCore/std/parallel/lock.h>
#include <AzCore/std/parallel/atomic.h>
#include <AzCore/std/parallel/condition_variable.h>
namespace MCore
{
class MCORE_API Mutex
{
friend class ConditionVariable;
public:
MCORE_INLINE Mutex() {}
MCORE_INLINE ~Mutex() {}
MCORE_INLINE void Lock() { mMutex.lock(); }
MCORE_INLINE void Unlock() { mMutex.unlock(); }
MCORE_INLINE bool TryLock() { return mMutex.try_lock(); }
private:
AZStd::mutex mMutex;
};
class MCORE_API MutexRecursive
{
public:
MCORE_INLINE MutexRecursive() {}
MCORE_INLINE ~MutexRecursive() {}
MCORE_INLINE void Lock() { mMutex.lock(); }
MCORE_INLINE void Unlock() { mMutex.unlock(); }
MCORE_INLINE bool TryLock() { return mMutex.try_lock(); }
private:
AZStd::recursive_mutex mMutex;
};
class MCORE_API ConditionVariable
{
public:
MCORE_INLINE ConditionVariable() {}
MCORE_INLINE ~ConditionVariable() {}
MCORE_INLINE void Wait(Mutex& mtx, const AZStd::function<bool()>& predicate) { AZStd::unique_lock<AZStd::mutex> lock(mtx.mMutex); mVariable.wait(lock, predicate); }
MCORE_INLINE void WaitWithTimeout(Mutex& mtx, uint32 microseconds, const AZStd::function<bool()>& predicate) { AZStd::unique_lock<AZStd::mutex> lock(mtx.mMutex); mVariable.wait_for(lock, AZStd::chrono::microseconds(microseconds), predicate); }
MCORE_INLINE void NotifyOne() { mVariable.notify_one(); }
MCORE_INLINE void NotifyAll() { mVariable.notify_all(); }
private:
AZStd::condition_variable mVariable;
};
class MCORE_API AtomicInt32
{
public:
MCORE_INLINE AtomicInt32() { SetValue(0); }
MCORE_INLINE ~AtomicInt32() {}
MCORE_INLINE void SetValue(int32 value) { mAtomic.store(value); }
MCORE_INLINE int32 GetValue() const { int32 value = mAtomic.load(); return value; }
MCORE_INLINE int32 Increment() { return mAtomic++; }
MCORE_INLINE int32 Decrement() { return mAtomic--; }
private:
AZStd::atomic<int32> mAtomic;
};
class MCORE_API AtomicUInt32
{
public:
MCORE_INLINE AtomicUInt32() { SetValue(0); }
MCORE_INLINE ~AtomicUInt32() {}
MCORE_INLINE void SetValue(uint32 value) { mAtomic.store(value); }
MCORE_INLINE uint32 GetValue() const { uint32 value = mAtomic.load(); return value; }
MCORE_INLINE uint32 Increment() { return mAtomic++; }
MCORE_INLINE uint32 Decrement() { return mAtomic--; }
private:
AZStd::atomic<uint32> mAtomic;
};
class MCORE_API Thread
{
public:
Thread() {}
Thread(const AZStd::function<void()>& threadFunction) { Init(threadFunction); }
~Thread() {}
void Init(const AZStd::function<void()>& threadFunction) { mThread = AZStd::thread(threadFunction); }
void Join() { mThread.join(); }
private:
AZStd::thread mThread;
};
class MCORE_API LockGuard
{
public:
MCORE_INLINE LockGuard(Mutex& mutex) { mMutex = &mutex; mutex.Lock(); }
MCORE_INLINE ~LockGuard() { mMutex->Unlock(); }
private:
Mutex* mMutex;
};
class MCORE_API LockGuardRecursive
{
public:
MCORE_INLINE LockGuardRecursive(MutexRecursive& mutex) { mMutex = &mutex; mutex.Lock(); }
MCORE_INLINE ~LockGuardRecursive() { mMutex->Unlock(); }
private:
MutexRecursive* mMutex;
};
class MCORE_API ConditionEvent
{
public:
ConditionEvent() { mConditionValue = false; }
~ConditionEvent() { }
void Reset() { mConditionValue = false; }
void Wait()
{
mCV.Wait(mMutex, [this] { return mConditionValue; });
}
void WaitWithTimeout(uint32 microseconds)
{
mCV.WaitWithTimeout(mMutex, microseconds, [this] { return mConditionValue; });
}
void NotifyAll() { { LockGuard lockMutex(mMutex); mConditionValue = true; } mCV.NotifyAll(); }
void NotifyOne() { { LockGuard lockMutex(mMutex); mConditionValue = true; } mCV.NotifyOne(); }
private:
Mutex mMutex;
ConditionVariable mCV;
bool mConditionValue;
};
} // namespace MCore
| 2,593 |
945 | // This is core/vnl/io/vnl_io_real_polynomial.h
#ifndef vnl_io_real_polynomial_h
#define vnl_io_real_polynomial_h
//:
// \file
// \author iscott
// \date 21-Mar-2001
#include <vsl/vsl_binary_io.h>
#include <vnl/vnl_real_polynomial.h>
//: Binary save vnl_real_polynomial to stream.
// \relatesalso vnl_real_polynomial
void vsl_b_write(vsl_b_ostream &os, const vnl_real_polynomial & v);
//: Binary load vnl_real_polynomial from stream.
// \relatesalso vnl_real_polynomial
void vsl_b_read(vsl_b_istream &is, vnl_real_polynomial & v);
//: Print human readable summary of object to a stream
// \relatesalso vnl_real_polynomial
void vsl_print_summary(std::ostream& os,const vnl_real_polynomial & b);
#endif // vnl_io_real_polynomial_h
| 310 |
5,169 | <filename>Specs/a/a/5/WeexGrowingIO/0.1.0/WeexGrowingIO.podspec.json
{
"name": "WeexGrowingIO",
"version": "0.1.0",
"summary": "GrowingIO Weex Plugin",
"description": "This Pod contains GrowingIO SDK plugin for weex. For more informations, please read https://github.com/growingio/weex-growingio",
"homepage": "https://www.growingio.com/",
"license": {
"type": "MIT",
"text": "Copyright (c) 2015-2018 GrowingIO <<EMAIL>>\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
},
"authors": {
"GrowingIO": "<EMAIL>"
},
"platforms": {
"ios": "7.0"
},
"source": {
"git": "https://github.com/growingio/weex-growingio.git",
"branch": "master",
"tag": "v0.1.0"
},
"source_files": "ios/Sources/*.{h,m,mm}",
"requires_arc": true,
"dependencies": {
"WeexPluginLoader": [
],
"WeexSDK": [
],
"GrowingIO": [
]
}
}
| 629 |
473 | <filename>challenges/Terrible_Ticket_Tracker/src/service.cc
/*
* Copyright (c) 2016 Kaprica Security, Inc.
*
* 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.
*
*/
#include "cgc_cstdio.h"
#include "cgc_cstring.h"
#include "cgc_deque.h"
#include "cgc_dispatcher.h"
#include "cgc_ticket.h"
#include "cgc_time.h"
#include "cgc_support.h"
#include "cgc__defines.h"
#define COMPONENT_DELIM '|'
#define MAX_COMPONENTS 8
#define MAX_COMPONENT MAX_DESC
#define NUM_PRIOS CRITICAL
#define TOSTR(x) #x
#define WITHIN(a, b, v) ((v) >= (a) && (v) <= (b))
class Scheduler
{
private:
List* workers_;
Dispatcher* dispatcher_;
public:
Scheduler(List* cgc_workers, Dispatcher* cgc_dispatcher);
void Run(void);
};
Scheduler::Scheduler(List* workers, Dispatcher* dispatcher)
{
dispatcher_ = dispatcher;
workers_ = workers;
}
void Scheduler::Run(void)
{
for (cgc_size_t i = 0; i < workers_->Length(); ++i)
{
Support* worker = workers_->Get(i);
if (worker->CurrentTicket() == nullptr)
{
Ticket* ticket = dispatcher_->GetTicket(worker->max_priority());
if (ticket != nullptr)
{
if (ticket->prev != worker)
{
worker->AssignTicket(ticket);
ticket->UpdateStatus(IN_PROGRESS);
}
else
{
dispatcher_->AddTicket(ticket);
}
}
}
else
{
Ticket* ticket = worker->CurrentTicket();
ticket->WorkOn();
if (ticket->CheckDone())
{
ticket->UpdateStatus(RESOLVED);
dispatcher_->RecordFinished(worker);
}
else if (dispatcher_->GetRandomTicks(10) < 2)
{
if (ticket->priority() > HIGH)
continue;
ticket->UpdateStatus(REJECTED);
worker->RemoveTicket();
}
else if (dispatcher_->GetRandomTicks(10) < 3)
{
worker->RemoveTicket();
dispatcher_->AddTicket(ticket);
ticket->UpdateStatus(OPEN);
}
}
}
}
List workers;
Dispatcher* dispatcher;
Scheduler* cgc_scheduler;
typedef enum
{
COMMAND_ERROR = 0,
ADD_TICKET,
CANCEL_TICKET,
LIST_SUPPORT,
LIST_FREE_SUPPORT,
HIRE,
FIRE,
VIEW,
VSTATUS,
QUIT,
} COMMAND;
typedef int (*handler)(FILE* in, FILE* out, char** components, cgc_size_t num_components);
int handle_command_error(FILE* in, FILE* out, char** components, cgc_size_t num_components)
{
cgc_fprintf(out, "Invalid command" EOL);
return 0;
}
int handle_add_command(FILE* in, FILE* out, char** components, cgc_size_t num_components)
{
PRIORITY p = LOW;
if (components[3])
{
p = (PRIORITY)cgc_strtol(components[3], nullptr, 10);
}
if (p < LOW || p > CRITICAL)
{
p = LOW;
}
Ticket* new_ticket = Ticket::GetTicket(
components[1], components[2], Time::GetTime(),
dispatcher->GetRandomTicks(100), p
);
if (new_ticket)
{
dispatcher->AddTicket(new_ticket);
}
return 0;
}
int handle_cancel_command(FILE* in, FILE* out, char** components, cgc_size_t num_components)
{
uint32_t cur_id = cgc_strtol(components[1], nullptr, 10);
dispatcher->CancelTicket(cur_id);
return 0;
}
int handle_list_command(FILE* in, FILE* out, char** components, cgc_size_t num_components)
{
for (cgc_size_t i = 0; i < workers.Length(); i++)
{
workers.Get(i)->Display();
}
return 0;
}
int handle_list_free_command(FILE* in, FILE* out, char** components, cgc_size_t num_components)
{
for (cgc_size_t i = 0; i < workers.Length(); i++)
{
Support* s = workers.Get(i);
if (!s->CurrentTicket())
{
s->Display();
}
}
return 0;
}
int handle_hire_command(FILE* in, FILE* out, char** components, cgc_size_t num_components)
{
PRIORITY p = (PRIORITY)cgc_strtol(components[1], nullptr, 10);
if (p < LOW || p > CRITICAL)
return 0;
Support* s = new Support(0, p);
workers.Append(s);
return 0;
}
int handle_fire_command(FILE* in, FILE* out, char** components, cgc_size_t num_components)
{
PRIORITY p = (PRIORITY)cgc_strtol(components[1], nullptr, 10);
if (p < LOW || p > CRITICAL)
return 0;
for (cgc_size_t i = 0; i < workers.Length(); i++)
{
Support* s = workers.Get(i);
if (s->max_priority() == p)
{
if (s->CurrentTicket())
{
dispatcher->AddTicket(s->CurrentTicket());
}
workers.Remove(i);
break;
}
}
return 0;
}
int handle_view_command(FILE* in, FILE* out, char** components, cgc_size_t num_components)
{
STATUS s = (STATUS)0;
if (num_components == 2)
{
s = (STATUS)cgc_strtol(components[1], nullptr, 10);
if (s > RESOLVED)
s = (STATUS)0;
}
if (s)
{
dispatcher->ViewTickets(s);
}
else
{
for (cgc_size_t i = OPEN; i < RESOLVED; i++)
{
dispatcher->ViewTickets((STATUS)i);
}
}
return 0;
}
int handle_status_command(FILE* in, FILE* out, char** components, cgc_size_t num_components)
{
uint32_t tid = cgc_strtol(components[1], nullptr, 10);
dispatcher->ViewTicket(tid);
return 0;
}
int handle_quit(FILE* in, FILE* out, char** components, cgc_size_t num_components)
{
cgc_fprintf(out, "TERMINATING TERRIBLE TICKET TRACKER" EOL);
return -1;
}
handler command_handlers[] = {
handle_command_error,
handle_add_command,
handle_cancel_command,
handle_list_command,
handle_list_free_command,
handle_hire_command,
handle_fire_command,
handle_view_command,
handle_status_command,
handle_quit,
};
COMMAND read_command(FILE* f, char*** components, cgc_size_t* num_components)
{
COMMAND c = COMMAND_ERROR;
char* component = nullptr;
char** comps = *components;
*num_components = 0;
for (cgc_size_t i = 0; i < MAX_COMPONENTS; ++i)
{
component = new char[MAX_COMPONENT + 1];
cgc_memset(component, 0, MAX_COMPONENT + 1);
c = COMMAND_ERROR;
int ret = cgc_freaduntil(component, MAX_COMPONENT, COMPONENT_DELIM, f);
if (ret > 1) // So two successive COMPONENT_DELIM ends command
{
comps[i] = component;
*num_components = i + 1;
}
else
{
delete component;
break;
}
}
if (comps[0] == nullptr)
{
goto done;
}
if (cgc_strcmp(comps[0], TOSTR(ADD_TICKET)) == 0)
{
if (!WITHIN(3, 4, *num_components))
goto done;
c = ADD_TICKET;
}
else if (cgc_strcmp(comps[0], TOSTR(CANCEL_TICKET)) == 0)
{
if (!WITHIN(2, 2, *num_components))
goto done;
c = CANCEL_TICKET;
}
else if (cgc_strcmp(comps[0], TOSTR(LIST_SUPPORT)) == 0)
{
if (!WITHIN(1, 1, *num_components))
goto done;
c = LIST_SUPPORT;
}
else if (cgc_strcmp(comps[0], TOSTR(LIST_FREE_SUPPORT)) == 0)
{
if (!WITHIN(1, 1, *num_components))
goto done;
c = LIST_FREE_SUPPORT;
}
else if (cgc_strcmp(comps[0], TOSTR(HIRE)) == 0)
{
if (!WITHIN(2, 2, *num_components))
goto done;
c = HIRE;
}
else if (cgc_strcmp(comps[0], TOSTR(FIRE)) == 0)
{
if (!WITHIN(2, 2, *num_components))
goto done;
c = FIRE;
}
else if (cgc_strcmp(comps[0], TOSTR(VIEW)) == 0)
{
if (!WITHIN(1, 2, *num_components))
goto done;
c = VIEW;
}
else if (cgc_strcmp(comps[0], TOSTR(VSTATUS)) == 0)
{
if (!WITHIN(2, 2, *num_components))
goto done;
c = VSTATUS;
}
else if (cgc_strcmp(comps[0], TOSTR(QUIT)) == 0)
{
c = QUIT;
}
done:
return c;
}
void run_server(FILE* in, FILE* out, unsigned char* secrets)
{
COMMAND command;
cgc_size_t num_components;
char** components = new char*[MAX_COMPONENTS];
Time::Reset();
dispatcher = new Dispatcher(&workers, (uint32_t*)(secrets));
cgc_scheduler = new Scheduler(&workers, dispatcher);
// Setup two starter workers
char *commands[2] = {(char *)"HIRE", (char *)"3"};
handle_hire_command(in, out, commands, 2);
commands[1] = (char *)"5";
handle_hire_command(in, out, commands, 2);
cgc_fprintf(out, "Welcome to the terrible ticket tracker" EOL);
for (;;)
{
// Tick
Time::GetTime();
cgc_scheduler->Run();
// Clear previous components
for (cgc_size_t i = 0; i < MAX_COMPONENTS; ++i)
{
if (components[i] != nullptr)
{
delete components[i];
components[i] = nullptr;
}
}
// Read components
cgc_fprintf(out, "$ ");
command = read_command(in, &components, &num_components);
// Dispatch command
int ret = command_handlers[command](in, out, components, num_components);
if (ret != 0)
{
break;
}
cgc_fprintf(out, "OK" EOL);
}
}
extern "C" int main(int secret_page_i, char *unused[]) {
secret_page_i = CGC_FLAG_PAGE_ADDRESS;
unsigned char *secret_page = (unsigned char *)secret_page_i;
cgc_fxlat(cgc_stdin, "EREH_EULAV_MODNAR");
cgc_fxlat(cgc_stdout, "EREH_EULAV_MODNAR");
run_server(cgc_stdin, cgc_stdout, secret_page);
return 0;
}
| 4,170 |
575 | //
// WaypointV2ViewController.h
// DJISdkDemo
//
// Created by ethan.jiang on 2020/5/7.
// Copyright © 2020 DJI. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <DJISDK/DJISDK.h>
NS_ASSUME_NONNULL_BEGIN
@interface WaypointV2ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *startButton;
@end
NS_ASSUME_NONNULL_END
| 156 |
307 | <filename>modules/app-version-common/src/main/java/com/tairanchina/csp/avm/dto/AdminUpdateNickNameRequestDTO.java
package com.tairanchina.csp.avm.dto;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.validator.constraints.NotBlank;
public class AdminUpdateNickNameRequestDTO {
@ApiModelProperty(value = "用户Id", required = true)
@NotBlank(message = "userId不能为空")
private String userId;
@ApiModelProperty(value = "用户昵称", required = true)
@NotBlank(message = "nickName不能为空")
private String nickName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}
| 353 |
388 | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates.
* 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.
*/
#ifndef AWS_METRICS_METRICS_CONSTANTS_H_
#define AWS_METRICS_METRICS_CONSTANTS_H_
#include <list>
#include <string>
#include <unordered_map>
#include <vector>
#include <boost/assign/list_of.hpp>
#include <aws/utils/logging.h>
namespace aws {
namespace metrics {
namespace constants {
enum class Level {
None = 0,
Summary = 100,
Detailed = 200
};
enum class Granularity {
Global = 0,
Stream = 100,
Shard = 200
};
#define DEF_NAME(X) static constexpr const char* X = #X;
struct Names {
DEF_NAME(Test);
DEF_NAME(UserRecordsReceived);
DEF_NAME(UserRecordsPending);
DEF_NAME(UserRecordsPut);
DEF_NAME(UserRecordsDataPut);
DEF_NAME(KinesisRecordsPut);
DEF_NAME(KinesisRecordsDataPut);
DEF_NAME(ErrorsByCode);
DEF_NAME(AllErrors);
DEF_NAME(RetriesPerRecord);
DEF_NAME(UserRecordExpired);
DEF_NAME(BufferingTime);
DEF_NAME(RequestTime);
DEF_NAME(UserRecordsPerKinesisRecord);
DEF_NAME(KinesisRecordsPerPutRecordsRequest);
DEF_NAME(UserRecordsPerPutRecordsRequest);
};
struct Units {
DEF_NAME(Count);
DEF_NAME(Milliseconds);
DEF_NAME(Bytes);
DEF_NAME(None);
};
struct DimensionNames {
DEF_NAME(MetricName);
DEF_NAME(StreamName);
DEF_NAME(ShardId);
DEF_NAME(ErrorCode);
};
#undef DEF_NAME
bool filter(const std::vector<std::pair<std::string, std::string>>& dimensions,
Level max_level,
Granularity max_granularity);
std::string unit(const std::string& name);
Level level(const std::string& s);
Granularity granularity(const std::string& s);
} //namespace constants
} //namespace metrics
} //namespace aws
#endif //AWS_METRICS_METRICS_CONSTANTS_H_
| 787 |
1,531 | /**
* Copyright 2012-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.
*/
package com.googlecode.cqengine.resultset.connective;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.common.ResultSets;
import com.googlecode.cqengine.resultset.filter.FilteringIterator;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.*;
/**
* A ResultSet which provides a view onto the set difference of two ResultSets.
* <p/>
* The set difference is elements contained in the first ResultSet which are NOT contained in the second ResultSet.
*
* @author <NAME>
*/
public class ResultSetDifference<O> extends ResultSet<O> {
final ResultSet<O> firstResultSet;
final ResultSet<O> secondResultSet;
final Query<O> query;
final QueryOptions queryOptions;
final boolean indexMergeStrategyEnabled;
public ResultSetDifference(ResultSet<O> firstResultSet, ResultSet<O> secondResultSet, Query<O> query, QueryOptions queryOptions) {
this(firstResultSet, secondResultSet, query, queryOptions, false);
}
public ResultSetDifference(ResultSet<O> firstResultSet, ResultSet<O> secondResultSet, Query<O> query, QueryOptions queryOptions, boolean indexMergeStrategyEnabled) {
this.firstResultSet = ResultSets.wrapWithCostCachingIfNecessary(firstResultSet);
this.secondResultSet = ResultSets.wrapWithCostCachingIfNecessary(secondResultSet);
this.query = query;
this.queryOptions = queryOptions;
// If index merge strategy is enabled, validate that we can actually use it for this particular negation...
if (indexMergeStrategyEnabled) {
if (this.secondResultSet.getRetrievalCost() == Integer.MAX_VALUE) { //note getRetrievalCost() is on the cost-caching wrapper
// We cannot use index merge strategy for this negation
// because the second ResultSet is not backed by an index...
indexMergeStrategyEnabled = false;
}
}
this.indexMergeStrategyEnabled = indexMergeStrategyEnabled;
}
@Override
public Iterator<O> iterator() {
if (indexMergeStrategyEnabled) {
return new FilteringIterator<O>(firstResultSet.iterator(), queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return !secondResultSet.contains(object);
}
};
}
else {
return new FilteringIterator<O>(firstResultSet.iterator(), queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return !secondResultSet.matches(object);
}
};
}
}
/**
* Returns true if the given object is contained in the first ResultSet,
* but is NOT contained in the second ResultSet.
*
* @param object An object to check if contained
* @return true if the given object is contained in the first ResultSet,
* but is NOT contained in the second ResultSet, otherwise false
*/
@Override
public boolean contains(O object) {
return firstResultSet.contains(object) && !secondResultSet.contains(object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
return IteratorUtil.countElements(this);
}
/**
* Returns the retrieval cost from the first ResultSet.
* @return the retrieval cost from the first ResultSet
*/
@Override
public int getRetrievalCost() {
return firstResultSet.getRetrievalCost();
}
/**
* Returns the merge cost from the first ResultSet.
* @return the merge cost from the first ResultSet
*/
@Override
public int getMergeCost() {
return firstResultSet.getMergeCost();
}
@Override
public void close() {
firstResultSet.close();
secondResultSet.close();
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
}
| 1,756 |
1,816 | <reponame>cercos/masonite
from .NotificationProvider import NotificationProvider
| 21 |
810 | <filename>document/Android/app/src/main/java/com/example/nanchen/aiyaschoolpush/ui/view/ColorButton.java
package com.example.nanchen.aiyaschoolpush.ui.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.example.nanchen.aiyaschoolpush.R;
import com.example.nanchen.aiyaschoolpush.utils.DisplayMetricsUtil;
/**
* 支持点击变色的ImageButton 通过过滤实现按下和抬起切换背景色
*
* @author nanchen
* @fileName AiYaSchoolPush
* @packageName com.example.nanchen.aiyaschoolpush.view
* @date 2016/09/12 15:40
*/
public class ColorButton extends View {
private Context mContext;
private String mTitleText;
private int mTitleFontSize;
private int mTitleFontColor;
public final float[] BT_SELECTED = new float[] { 1, 0, 0, 0, -50, 0, 1, 0, 0, -50, 0, 0, 1, 0, -50, 0, 0, 0, 1, 0 };
public final float[] BT_NOT_SELECTED = new float[] { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 };
public ColorButton(Context context) {
super(context);
mContext = context;
setOnTouchListener(onTouchListener);
}
public ColorButton(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
initView(attrs);
setOnTouchListener(onTouchListener);
}
public ColorButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
initView(attrs);
setOnTouchListener(onTouchListener);
}
private void initView(AttributeSet attrs) {
TypedArray array = mContext.obtainStyledAttributes(attrs, R.styleable.colorButtonStyle);
mTitleText = array.getString(R.styleable.colorButtonStyle_text_title);
mTitleFontColor = array.getColor(R.styleable.colorButtonStyle_fontcolor_title, -1);
mTitleFontSize = array.getInt(R.styleable.colorButtonStyle_fontsize_title, -1);
/*
* 在TypedArray后调用recycle主要是为了缓存。
* 当recycle被调用后,这就说明这个对象从现在可以被重用了。
* TypedArray 内部持有部分数组,它们缓存在Resources类中的静态字段中,
* 这样就不用每次使用前都需要分配内存。
*/
array.recycle();
}
public OnTouchListener onTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
view.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));
view.setBackgroundDrawable(view.getBackground());
break;
case MotionEvent.ACTION_DOWN:
view.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_SELECTED));
view.setBackgroundDrawable(view.getBackground());
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_CANCEL:
view.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));
view.setBackgroundDrawable(view.getBackground());
break;
default:
break;
}
return false;
}
};
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (TextUtils.isEmpty(mTitleText)) {
return;
}
Paint mPaint = new Paint();
mPaint.setStrokeWidth(3);
if (mTitleFontSize != -1) {
mPaint.setTextSize(DisplayMetricsUtil.dip2px(mContext, mTitleFontSize));
} else {
mPaint.setTextSize(DisplayMetricsUtil.dip2px(mContext, 18));
}
if (mTitleFontColor != -1) {
mPaint.setColor(mTitleFontColor);
} else {
mPaint.setColor(Color.WHITE);
}
mPaint.setTextAlign(Align.LEFT);
Rect bounds = new Rect();
mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), bounds);
FontMetricsInt fontMetrics = mPaint.getFontMetricsInt();
int baseline = (getMeasuredHeight() - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
canvas.drawText(mTitleText, getMeasuredWidth() / 2 - bounds.width() / 2, baseline, mPaint);
}
public void setText(String text){
if(!TextUtils.isEmpty(text)){
mTitleText = text;
invalidate();
}
}
}
| 2,318 |
303 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from django.contrib.auth.models import User
from ..admin.user import TeamListFilter, UserAdmin
from model_mommy import mommy
class UserTest(TestCase):
DEV_NAME = "Dev_User"
DBA_NAME = "DBA_User"
WITHOUT_TEAM_NAME = "New_User"
PASSWORD = "<PASSWORD>"
def setUp(self):
self.role = mommy.make_recipe('account.role')
self.organization = mommy.make('Organization')
self.team_dba = mommy.make_recipe(
'account.team',
role=self.role,
organization=self.organization
)
self.team_dev = mommy.make_recipe(
'account.team',
role=self.role,
organization=self.organization
)
self.team_ops = mommy.make_recipe(
'account.team',
role=self.role,
organization=self.organization
)
self.team_bkp = mommy.make_recipe(
'account.team',
role=self.role,
organization=self.organization
)
self.user_dev = User.objects.create_superuser(
self.DEV_NAME,
email="<EMAIL>" % self.DEV_NAME, password=self.PASSWORD
)
self.team_dev.users.add(self.user_dev)
self.user_dba = User.objects.create_superuser(
self.DBA_NAME,
email="%s<EMAIL>" % self.DBA_NAME, password=self.PASSWORD
)
self.team_dba.users.add(self.user_dba)
self.user_without_team = User.objects.create_superuser(
self.WITHOUT_TEAM_NAME,
email="<EMAIL>" % self.WITHOUT_TEAM_NAME,
password=self.PASSWORD
)
def _build_team_filter(self, id=None):
params = {}
if id:
params[TeamListFilter.parameter_name] = str(id)
return TeamListFilter(None, params, User, UserAdmin)
def _choices_in_team_filter(self):
team_filter = self._build_team_filter()
choices = []
for choice in team_filter.lookup_choices:
choices.append(choice[1])
return choices
def _do_team_filter(self, id=None):
filter = self._build_team_filter(id)
return filter.queryset(None, User.objects.all())
def test_has_without_team_in_filter(self):
self.assertIn("without team", self._choices_in_team_filter())
def test_has_all_teams_in_filter(self):
choices = self._choices_in_team_filter()
self.assertIn(self.team_dba.name, choices)
self.assertIn(self.team_dev.name, choices)
self.assertIn(self.team_ops.name, choices)
self.assertIn(self.team_bkp.name, choices)
def test_empty_team_filter(self):
users = self._do_team_filter()
self.assertEqual(len(users), 3)
def test_can_filter_by_team(self):
users = self._do_team_filter(self.team_dba.id)
self.assertEqual(len(users), 1)
def test_can_filter_users_without_team(self):
users = self._do_team_filter(-1)
self.assertEqual(len(users), 1)
| 1,469 |
411 | /*
* 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.giraph.types.ops.collections;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.giraph.function.Consumer;
import org.apache.giraph.function.Predicate;
import org.apache.giraph.types.ops.PrimitiveTypeOps;
import org.apache.hadoop.io.Writable;
/**
* Collection over mutable elements, which are probably
* internally stored differently/efficiently, and are accessed
* through methods providing "return" value.
*
* @param <T> Element type
*/
public interface WCollection<T> extends Writable {
/** Removes all of the elements from this */
void clear();
/**
* Number of elements in this list
* @return size
*/
int size();
/**
* Capacity of currently allocated memory
* @return capacity
*/
int capacity();
/**
* Forces allocated memory to hold exactly N values
* @param n new capacity
*/
void setCapacity(int n);
/**
* Add value to the collection
* @param value Value
*/
void addW(T value);
/**
* TypeOps for type of elements this object holds
* @return TypeOps
*/
PrimitiveTypeOps<T> getElementTypeOps();
/**
* Fast iterator over collection objects, which doesn't allocate new
* element for each returned element, and can be iterated multiple times
* using reset().
*
* Object returned by next() is only valid until next() is called again,
* because it is reused.
*
* @return RessettableIterator
*/
ResettableIterator<T> fastIteratorW();
/**
* Fast iterator over collection objects, which doesn't allocate new
* element for each returned element, and can be iterated multiple times
* using reset().
*
* Each call to next() populates passed value.
*
* @param iterationValue Value that call to next() will populate
* @return RessettableIterator
*/
ResettableIterator<T> fastIteratorW(T iterationValue);
/**
* Traverse all elements of the collection, calling given function on each
* element. Passed values are valid only during the call to the passed
* function, so data needs to be consumed during the function.
*
* @param f Function to call on each element.
*/
void fastForEachW(Consumer<T> f);
/**
* Traverse all elements of the collection, calling given function on each
* element, or until predicate returns false.
* Passed values are valid only during the call to the passed
* function, so data needs to be consumed during the function.
*
* @param f Function to call on each element.
* @return true if the predicate returned true for all elements,
* false if it returned false for some element.
*/
boolean fastForEachWhileW(Predicate<T> f);
/**
* Write elements to the DataOutput stream, without the size itself.
* Can be read back using readElements function.
*
* @param out Data output
*/
void writeElements(DataOutput out) throws IOException;
/**
* Read elements from DataInput stream, with passing the size instead
* reading it from the stream.
*
* @param in Data Input
* @param size Number of elements
*/
void readElements(DataInput in, int size) throws IOException;
}
| 1,135 |
2,637 | <filename>vendors/mediatek/sdk/driver/chip/mt7687/src/common/cos_api.c<gh_stars>1000+
/* Copyright Statement:
*
* (C) 2005-2016 MediaTek Inc. All rights reserved.
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. ("MediaTek") and/or its licensors.
* Without the prior written permission of MediaTek and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
* You may only use, reproduce, modify, or distribute (as applicable) MediaTek Software
* if you have agreed to and been bound by the applicable license agreement with
* MediaTek ("License Agreement") and been granted explicit permission to do so within
* the License Agreement ("Permitted User"). If you are not a Permitted User,
* please cease any access or use of MediaTek Software immediately.
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT MEDIATEK SOFTWARE RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES
* ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*/
#include "type_def.h"
#include "gpt.h"
#include "cos_api.h"
#include "hal_lp.h"
#include "mt7687_cm4_hw_memmap.h"
extern void delay_time(kal_uint32 count);
/**
* Get currenct system time
*
* @param None
*
* @return current system time in unit of 32k clock tick
*/
kal_uint32 cos_get_systime(void)
{
return GPT_return_current_count(2);
}
/**
* System delay time function
*
* @param count delay time unit is 32k clock unit
*
* @return None
*/
void cos_delay_time(kal_uint32 count)
{
delay_time(count);
}
void cos_delay_ms(kal_uint32 ms)
{
cos_delay_time(32 * ms);
}
void cos_delay_100us(kal_uint32 unit)
{
//cos_delay_time(3*unit);
cos_delay_time(4 * unit);
}
unsigned long randomseed;
unsigned long SYSrand_Get_Rand(void) /* reentrant */
{
unsigned long result;
unsigned long next_seed = randomseed;
next_seed = (next_seed * 1103515245) + 12345; /* permutate seed */
result = next_seed & 0xfffc0000; /* use only top 14 bits */
next_seed = (next_seed * 1103515245) + 12345; /* permutate seed */
result = result + ((next_seed & 0xffe00000) >> 14); /* top 11 bits */
next_seed = (next_seed * 1103515245) + 12345; /* permutate seed */
result = result + ((next_seed & 0xfe000000) >> (25)); /* use only top 7 bits */
randomseed = next_seed;
return (result & 0xffffffff);
}
void cos_control_force_pwm_mode(cos_module_on_off_state module)
{
// Raise flag to claim using the PMU
if (module == COS_MODULE_ON_OFF_STATE_CM4_ADC) {
mSetHWEntry(TOP_CFG_AON_N9_CM4_MESSAGE_CM4_ADC, 1);
} else if (module == COS_MODULE_ON_OFF_STATE_CM4_AUDIO) {
mSetHWEntry(TOP_CFG_AON_N9_CM4_MESSAGE_CM4_AUDIO, 1);
} else {
return;
}
// delay to prevent from racing
cos_delay_time(1);
// get own bit from firmware
//if (hal_lp_connsys_get_own_enable_int() != 0)
//{
// return;
//}
// Force PWM mode
// Set 0x8102140C bit[22] and bit[14] = 11
mSetHWEntry(TOP_CFG_AON_PMU_RG_BUCK_FORCE_PWM, 0x101);
// set firmware own if necessary
//if (hal_lp_connsys_give_n9_own() != 0)
//{
// return;
//}
}
void cos_control_force_pwm_mode_exit(cos_module_on_off_state module)
{
uint32_t volatile_reg1 = 0, volatile_reg2 = 0;
// Clear flag to disclaim using the PMU
if (module == COS_MODULE_ON_OFF_STATE_CM4_ADC) {
mSetHWEntry(TOP_CFG_AON_N9_CM4_MESSAGE_CM4_ADC, 0);
} else if (module == COS_MODULE_ON_OFF_STATE_CM4_AUDIO) {
mSetHWEntry(TOP_CFG_AON_N9_CM4_MESSAGE_CM4_AUDIO, 0);
} else {
return;
}
// Check all modules
volatile_reg1 = mGetHWEntry(TOP_CFG_AON_N9_MESSAGE);
volatile_reg2 = mGetHWEntry(TOP_CFG_AON_N9_CM4_MESSAGE);
if ((volatile_reg1 & volatile_reg2) != 0) {
return;
}
// get own bit from firmware
if (hal_lp_connsys_get_own_enable_int() != 0) {
return;
}
// Exit force PWM mode
// Set 0x8102140C bit[22] and bit[14] = 00
mSetHWEntry(TOP_CFG_AON_PMU_RG_BUCK_FORCE_PWM, 0x000);
// set firmware own if necessary
//if (hal_lp_connsys_give_n9_own() != 0)
//{
// return;
//}
}
| 2,171 |
1,822 | // Copyright (c) 2015-2017 <NAME>
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <cstdint>
namespace hpx { namespace threads { namespace policies {
/// This enumeration describes the possible modes of a scheduler.
enum scheduler_mode : std::uint32_t
{
/// As the name suggests, this option can be used to disable all other
/// options.
nothing_special = 0x000,
/// The scheduler will periodically call a provided callback function
/// from a special HPX thread to enable performing background-work, for
/// instance driving networking progress or garbage-collect AGAS.
do_background_work = 0x001,
/// The kernel priority of the os-thread driving the scheduler will be
/// reduced below normal.
reduce_thread_priority = 0x002,
/// The scheduler will wait for some unspecified amount of time before
/// exiting the scheduling loop while being terminated to make sure no
/// other work is being scheduled during processing the shutdown
/// request.
delay_exit = 0x004,
/// Some schedulers have the capability to act as 'embedded'
/// schedulers. In this case it needs to periodically invoke a provided
/// callback into the outer scheduler more frequently than normal. This
/// option enables this behavior.
fast_idle_mode = 0x008,
/// This option allows for the scheduler to dynamically increase and
/// reduce the number of processing units it runs on. Setting this value
/// not succeed for schedulers that do not support this functionality.
enable_elasticity = 0x010,
/// This option allows schedulers that support work thread/stealing to
/// enable/disable it
enable_stealing = 0x020,
/// This option allows schedulersthat support it to disallow stealing
/// between numa domains
enable_stealing_numa = 0x040,
/// This option tells schedulersthat support it to add tasks round
/// robin to queues on each core
assign_work_round_robin = 0x080,
/// This option tells schedulers that support it to add tasks round to
/// the same core/queue that the parent task is running on
assign_work_thread_parent = 0x100,
/// This option tells schedulers that support it to always (try to)
/// steal high priority tasks from other queues before finishing their
/// own lower priority tasks
steal_high_priority_first = 0x200,
/// This option tells schedulers that support it to steal tasks only
/// when their local queues are empty
steal_after_local = 0x400,
/// This option allows for certain schedulers to explicitly disable
/// exponential idle-back off
enable_idle_backoff = 0x0800,
// clang-format off
/// This option represents the default mode.
default_mode =
do_background_work |
reduce_thread_priority |
delay_exit |
enable_stealing |
enable_stealing_numa |
assign_work_round_robin |
steal_after_local |
enable_idle_backoff,
/// This enables all available options.
all_flags =
do_background_work |
reduce_thread_priority |
delay_exit |
fast_idle_mode |
enable_elasticity |
enable_stealing |
enable_stealing_numa |
assign_work_round_robin |
assign_work_thread_parent |
steal_high_priority_first |
steal_after_local |
enable_idle_backoff
// clang-format on
};
}}} // namespace hpx::threads::policies
| 1,496 |
1,145 | import pytest
from omnizart.music.labels import LabelType
def test_invalid_label_conversion_mode():
with pytest.raises(ValueError):
LabelType("unknown-mode")
CUSTOM_LABEL_DATA = [
{60: {0: 1}}, {60: {0: 1}}, {60: {0: 1}}, {60: {0: 1}}, {60: {0: 1}}, {60: {0: 1}},
{99: {41: 1}}, {99: {41: 1}}, {99: {41: 1}}, {99: {41: 1}}, {99: {41: 1}}, {99: {41: 1}}
]
@pytest.mark.parametrize("mode, expected_out_shape", [
("true-frame", (12, 352, 2)),
("frame", (12, 352, 3)),
("note", (12, 352, 3)),
("true-frame-stream", (12, 352, 12)),
("frame-stream", (12, 352, 23)),
("note-stream", (12, 352, 23)),
("pop-note-stream", (12, 352, 13))
])
def test_normal_label_conversion(mode, expected_out_shape):
conv_func = LabelType(mode).get_conversion_func()
output = conv_func(CUSTOM_LABEL_DATA)
assert output.shape == expected_out_shape
| 399 |
3,102 | <reponame>clayne/DirectXShaderCompiler<gh_stars>1000+
// Helper 1 for chain-external-defs.c test
// Tentative definitions
int x;
int x2;
// Should not show up
static int z;
int incomplete_array[];
int incomplete_array2[];
struct S s;
| 86 |
1,139 | <filename>scispacy/__init__.py
from scispacy.version import VERSION as __version__
| 27 |
1,133 | <gh_stars>1000+
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <cdb2api.h>
int main(int argc, char **argv)
{
cdb2_hndl_tp *hndl = NULL;
char *conf = getenv("CDB2_CONFIG");
char *tier = "local";
void *blob;
int i, rc;
if (conf != NULL) {
cdb2_set_comdb2db_config(conf);
tier = "default";
}
puts("CREATING TABLE...");
cdb2_open(&hndl, argv[1], tier, 0);
cdb2_run_statement(hndl, "DROP TABLE IF EXISTS t");
cdb2_run_statement(hndl, "CREATE TABLE t (b blob)");
puts("INSERTING DATA...");
blob = malloc(1 << 20);
cdb2_bind_param(hndl, "b", CDB2_BLOB, blob, 1 << 20);
for (i = 0; i != 8; ++i)
cdb2_run_statement(hndl, "INSERT INTO t VALUES(@b)");
while ((rc = cdb2_next_record(hndl)) == CDB2_OK);
if (rc != CDB2_OK_DONE) {
puts("FAILED");
puts(cdb2_errstr(hndl));
return rc;
}
puts("DONATING FD TO SOCK POOL...");
cdb2_close(hndl);
puts("REOPENING FROM SOCK POOL...");
hndl = NULL;
cdb2_open(&hndl, argv[1], tier, 0);
puts("RUNNING QUERY TO FILL UP TCP SND BUFFER ON SERVER...");
cdb2_run_statement(hndl, "SELECT * FROM t a, t b, t c");
puts("SLEEPING 20 SECONDS...");
sleep(20);
puts("I'M AWAKE. FETCHING ROWS...");
while ((rc = cdb2_next_record(hndl)) == CDB2_OK);
if (rc != CDB2_OK_DONE) {
puts("FAILED");
puts(cdb2_errstr(hndl));
return rc;
}
return 0;
}
| 755 |
487 | {
"name": "gliojs",
"version": "0.0.7",
"description": "Detects if the mouse of a user leaves the viewport / document borders of your website — and when this happens, trigger your callback",
"main": "glio.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"gliojs",
"mousemove",
"screencorner",
"move",
"exit"
],
"homepage": "http://luisvinicius167.github.io/gliojs",
"author": "<NAME>",
"license": "MIT"
}
| 191 |
886 | /*!
@file
Forward declares `boost::hana::Struct`.
@copyright <NAME> 2013-2016
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_FWD_CONCEPT_STRUCT_HPP
#define BOOST_HANA_FWD_CONCEPT_STRUCT_HPP
#include <boost/hana/config.hpp>
BOOST_HANA_NAMESPACE_BEGIN
//! @ingroup group-concepts
//! @defgroup group-Struct Struct
//! The `Struct` concept represents `struct`-like user-defined types.
//!
//! The `Struct` concept allows restricted compile-time reflection over
//! user-defined types. In particular, it allows accessing the names of
//! the members of a user-defined type, and also the value of those
//! members. `Struct`s can also be folded, searched and converted to
//! some types of containers, where more advanced transformations can
//! be performed.
//!
//! While all types can _in theory_ be made `Struct`s, only a subset of
//! them are actually interesting to see as such. More precisely, it is
//! only interesting to make a type a `Struct` when it is conceptually
//! a C++ `struct`, i.e. a mostly dumb aggregate of named data. The way
//! this data is accessed is mostly unimportant to the `Struct` concept;
//! it could be through getters and setters, through public members,
//! through non-member functions or it could even be generated on-the-fly.
//! The important part, which is made precise below, is that those accessor
//! methods should be move-independent.
//!
//! Another way to see a `Struct` is as a map where the keys are the names
//! of the members and the values are the values of those members. However,
//! there are subtle differences like the fact that one can't add a member
//! to a `Struct`, and also that the order of the members inside a `Struct`
//! plays a role in determining the equality of `Struct`s, which is not
//! the case for maps.
//!
//!
//! Minimal complete definition
//! ---------------------------
//! `accessors`
//!
//! A model of `Struct` is created by specifying a sequence of key/value
//! pairs with the `accessors` function. The first element of a pair in
//! this sequence represents the "name" of a member of the `Struct`, while
//! the second element is a function which retrieves this member from an
//! object. The "names" do not have to be in any special form; they just
//! have to be compile-time `Comparable`. For example, it is common to
//! provide "names" that are `hana::string`s representing the actual names
//! of the members, but one could provide `hana::integral_constant`s just
//! as well. The values must be functions which, when given an object,
//! retrieve the appropriate member from it.
//!
//! There are several ways of providing the `accessors` method, some of
//! which are more flexible and others which are more convenient. First,
//! one can define it through tag-dispatching, as usual.
//! @snippet example/struct.mcd.tag_dispatching.cpp main
//!
//! Secondly, it is possible to provide a nested `hana_accessors_impl`
//! type, which should be equivalent to a specialization of
//! `accessors_impl` for tag-dispatching. However, for a type `S`, this
//! technique only works when the data type of `S` is `S` itself, which
//! is the case unless you explicitly asked for something else.
//! @snippet example/struct.mcd.nested.cpp main
//!
//! Finally, the most convenient (but least flexible) option is to use
//! the `BOOST_HANA_DEFINE_STRUCT`, the `BOOST_HANA_ADAPT_STRUCT` or the
//! `BOOST_HANA_ADAPT_ADT` macro, which provide a minimal syntactic
//! overhead. See the documentation of these macros for details on how
//! to use them.
//!
//! Also note that it is not important that the accessor functions retrieve
//! an actual member of the struct (e.g. `x.member`). Indeed, an accessor
//! function could call a custom getter or even compute the value of the
//! member on the fly:
//! @snippet example/struct.custom_accessor.cpp main
//!
//! The only important thing is that the accessor functions are
//! move-independent, a notion which is defined below.
//!
//!
//! @anchor move-independence
//! Move-independence
//! -----------------
//! The notion of move-independence presented here defines rigorously
//! when it is legitimate to "double-move" from an object.
//!
//! A collection of functions `f1, ..., fn` sharing the same domain is
//! said to be _move-independent_ if for every fresh (not moved-from)
//! object `x` in the domain, any permutation of the following statements
//! is valid and leaves the `zk` objects in a fresh (not moved-from) state:
//! @code
//! auto z1 = f1(std::move(x));
//! ...
//! auto zn = fn(std::move(x));
//! @endcode
//!
//! @note
//! In the special case where some functions return objects that can't be
//! bound to with `auto zk =` (like `void` or a non-movable, non-copyable
//! type), just pretend the return value is ignored.
//!
//! Intuitively, this ensures that we can treat `f1, ..., fn` as
//! "accessors" that decompose `x` into independent subobjects, and
//! that do so without moving from `x` more than that subobject. This
//! is important because it allows us to optimally decompose `Struct`s
//! into their subparts inside the library.
//!
//!
//! Laws
//! ----
//! For any `Struct` `S`, the accessors in the `accessors<S>()` sequence
//! must be move-independent, as defined above.
//!
//!
//! Refined concepts
//! ----------------
//! 1. `Comparable` (free model)\n
//! `Struct`s are required to be `Comparable`. Specifically, two `Struct`s
//! of the same data type `S` must be equal if and only if all of their
//! members are equal. By default, a model of `Comparable` doing just that
//! is provided for models of `Struct`. In particular, note that the
//! comparison of the members is made in the same order as they appear in
//! the `hana::members` sequence.
//! @include example/struct/comparable.cpp
//!
//! 2. `Foldable` (free model)\n
//! A `Struct` can be folded by considering it as a list of pairs each
//! containing the name of a member and the value associated to that
//! member, in the same order as they appear in the `hana::members`
//! sequence. By default, a model of `Foldable` doing just that is
//! provided for models of the `Struct` concept.
//! @include example/struct/foldable.cpp
//! Being a model of `Foldable` makes it possible to turn a `Struct`
//! into basically any `Sequence`, but also into a `hana::map` by simply
//! using the `to<...>` function!
//! @include example/struct/to.cpp
//!
//! 3. `Searchable` (free model)\n
//! A `Struct` can be searched by considering it as a map where the keys
//! are the names of the members of the `Struct`, and the values are the
//! members associated to those names. By default, a model of `Searchable`
//! is provided for any model of the `Struct` concept.
//! @include example/struct/searchable.cpp
template <typename S>
struct Struct;
BOOST_HANA_NAMESPACE_END
#endif // !BOOST_HANA_FWD_CONCEPT_STRUCT_HPP
| 2,484 |
2,542 | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
#include "IConstraint.h"
namespace Reliability
{
namespace LoadBalancingComponent
{
class LoadEntry;
class NodeCapacitySubspace : public ISubspace
{
DENY_COPY(NodeCapacitySubspace);
public:
NodeCapacitySubspace(bool relaxed,
std::map<NodeEntry const*, PlacementReplicaSet> && nodeExtraLoads,
std::map<NodeEntry const*, std::set<ApplicationEntry const*>> && nodeExtraApplications,
std::map<NodeEntry const*, std::set<ServicePackageEntry const*>> && nodeExtraServicePackages)
: relaxed_(relaxed),
nodeExtraLoads_(move(nodeExtraLoads)),
nodeExtraApplications_(move(nodeExtraApplications)),
nodeExtraServicePackages_(move(nodeExtraServicePackages))
{
}
__declspec (property(get = get_NodeExtraLoads)) std::map<NodeEntry const*, PlacementReplicaSet> const& NodeExtraLoads;
std::map<NodeEntry const*, PlacementReplicaSet> const& get_NodeExtraLoads() const { return nodeExtraLoads_; }
virtual void GetTargetNodes(
TempSolution const& tempSolution,
PlacementReplica const* replica,
NodeSet & candidateNodes,
bool useNodeBufferCapacity,
NodeToConstraintDiagnosticsDataMapSPtr const nodeToConstraintDiagnosticsDataMapSPtr = nullptr) const;
virtual void GetTargetNodesForReplicas(
TempSolution const& tempSolution,
std::vector<PlacementReplica const*> const& replicas,
NodeSet & candidateNodes,
bool useNodeBufferCapacity,
NodeToConstraintDiagnosticsDataMapSPtr const nodeToConstraintDiagnosticsDataMapSPtr = nullptr) const;
virtual bool PromoteSecondary(
TempSolution const& tempSolution,
PartitionEntry const* partition,
NodeSet & candidateNodes) const;
virtual void PrimarySwapback(TempSolution const& tempSolution, PartitionEntry const* partition, NodeSet & candidateNodes) const;
virtual void PromoteSecondaryForPartitions(
TempSolution const& tempSolution,
std::vector<PartitionEntry const*> const& partitions,
NodeSet & candidateNodes) const;
virtual IConstraint::Enum get_Type() const { return IConstraint::NodeCapacity; }
virtual bool FilterByNodeCapacity(
NodeEntry const *node,
TempSolution const& tempSolution,
std::vector<PlacementReplica const*> const& replicas,
int64 replicaLoadValue,
bool useNodeBufferCapacity,
size_t capacityIndex,
size_t globalMetricIndex,
IConstraintDiagnosticsDataSPtr const constraintDiagnosticsDataSPtr = nullptr) const;
virtual ~NodeCapacitySubspace() {}
private:
bool relaxed_;
// if a node is not in this table, it either has no capacity
// or it doesn't violate capacity during constraint check
std::map<NodeEntry const*, PlacementReplicaSet> nodeExtraLoads_;
// Because of reserved load we may have to move entire application from the node.
// If application is in this set, then it needs to be moved.
std::map<NodeEntry const*, std::set<ApplicationEntry const*>> nodeExtraApplications_;
// We may need to move the entire Service Package off the node if it is in violation
std::map<NodeEntry const*, std::set<ServicePackageEntry const*>> nodeExtraServicePackages_;
};
class NodeCapacityConstraint : public IDynamicConstraint
{
DENY_COPY(NodeCapacityConstraint);
public:
NodeCapacityConstraint(int priority);
static bool FindAllInvalidReplicas(
TempSolution const& tempSolution,
PlacementReplicaSet const& candidatesToMoveOut,
size_t const globalMetricStartIndex,
Common::Random & random,
LoadEntry & diff,
PlacementReplicaSet & invalidReplicas,
PlacementReplicaSet & nodeInvalidReplicas,
std::set<ApplicationEntry const*> & nodeInvalidApplications,
std::set<ServicePackageEntry const*>& nodeInvalidServicePackages,
NodeEntry const* node,
bool forApplicationCapacity = false);
virtual Enum get_Type() const { return Enum::NodeCapacity; }
virtual IViolationUPtr GetViolations(
TempSolution const& solution,
bool changedOnly,
bool relaxed,
bool useNodeBufferCapacity,
Common::Random& random) const;
virtual void CorrectViolations(TempSolution & solution, std::vector<ISubspaceUPtr> const& subspaces, Common::Random & random) const;
virtual ConstraintCheckResult CheckSolutionAndGenerateSubspace(
TempSolution const& tempSolution,
bool changedOnly,
bool relaxed,
bool useNodeBufferCapacity,
Common::Random & random,
std::shared_ptr<IConstraintDiagnosticsData> const diagnosticsDataPtr = nullptr) const;
virtual ~NodeCapacityConstraint(){}
};
}
}
| 2,459 |
1,309 | <filename>engine/source/bitmapFont/BitmapFontCharacter.h<gh_stars>1000+
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
#ifndef _BITMAP_FONT_CHARACTER_H_
#define _BITMAP_FONT_CHARACTER_H_
#ifndef _UTILITY_H_
#include "2d/core/Utility.h"
#endif
#ifndef _VECTOR2_H_
#include "2d/core/Vector2.h"
#endif
namespace font
{
class BitmapFontCharacter
{
public:
U16 mCharID;
U16 mX, mY;
U16 mWidth, mHeight;
F32 mXOffset, mYOffset;
F32 mXAdvance;
U16 mPage;
U16 mPageWidth, mPageHeight;
Vector2 mOOBB[4];
BitmapFontCharacter() : mX(0), mY(0), mWidth(0), mHeight(0), mXOffset(0), mYOffset(0), mXAdvance(0), mPage(0)
{
}
void ProcessCharacter(U16 width, U16 height);
};
}
#endif // _BITMAP_FONT_CHARACTER_H_
| 658 |
1,792 | package org.hongxi.whatsmars.spring.dbrouter;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Component
public class DbRouteInterceptor {
private DbRouter dbRouter;
public DbRouteInterceptor() {}
@Pointcut("@annotation(org.hongxi.whatsmars.dbrouter.DbRoute)")
public void aopPoint() {}
@Before("aopPoint()")
public Object doRoute(JoinPoint jp) throws Throwable {
boolean result = true;
Method method = this.getMethod(jp);
DbRoute dbRoute = method.getAnnotation(DbRoute.class);
String routeField = dbRoute.field(); // userId
Object[] args = jp.getArgs();
if(args != null && args.length > 0) {
for(int i = 0; i < args.length; ++i) {
String routeFieldValue = BeanUtils.getProperty(args[i], routeField);
if(StringUtils.isNotEmpty(routeFieldValue)) {
if("userId".equals(routeField)) {
this.dbRouter.route(routeField);
}
break;
}
}
}
return Boolean.valueOf(result);
}
private Method getMethod(JoinPoint jp) throws NoSuchMethodException {
Signature sig = jp.getSignature();
MethodSignature msig = (MethodSignature)sig;
return this.getClass(jp).getMethod(msig.getName(), msig.getParameterTypes());
}
private Class<? extends Object> getClass(JoinPoint jp) throws NoSuchMethodException {
return jp.getTarget().getClass();
}
public DbRouter getDbRouter() {
return dbRouter;
}
public void setDbRouter(DbRouter dbRouter) {
this.dbRouter = dbRouter;
}
} | 926 |
4,901 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static com.google.common.truth.Truth.assertThat;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.testing.proto.TestProto3Optional;
/** Tests for proto3 optional feature. */
public class Proto3OptionalTest extends ProtobufTest {
public void testHasMethodForProto3Optional() throws Exception {
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalInt32()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalInt64()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalUint32()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalUint64()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalSint32()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalSint64()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalFixed32()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalFixed64()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalFloat()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalDouble()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalBool()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalString()).isFalse();
assertThat(TestProto3Optional.getDefaultInstance().hasOptionalBytes()).isFalse();
TestProto3Optional.Builder builder = TestProto3Optional.newBuilder().setOptionalInt32(0);
assertThat(builder.hasOptionalInt32()).isTrue();
assertThat(builder.build().hasOptionalInt32()).isTrue();
TestProto3Optional.Builder otherBuilder = TestProto3Optional.newBuilder().setOptionalInt32(1);
otherBuilder.mergeFrom(builder.build());
assertThat(otherBuilder.hasOptionalInt32()).isTrue();
assertThat(otherBuilder.getOptionalInt32()).isEqualTo(0);
assertThat(builder.build().toByteArray()).isEqualTo(new byte[] {0x8, 0x0});
// TODO(tball): b/197406391 optional enum setter method not found in generated proto.
// TestProto3Optional.Builder builder3 =
// TestProto3Optional.newBuilder().setOptionalNestedEnumValue(5);
// assertThat(builder3.hasOptionalNestedEnum()).isTrue();
TestProto3Optional.Builder builder4 =
TestProto3Optional.newBuilder().setOptionalNestedEnum(TestProto3Optional.NestedEnum.FOO);
assertThat(builder4.hasOptionalNestedEnum()).isTrue();
TestProto3Optional proto =
TestProto3Optional.parseFrom(
builder.build().toByteArray(), ExtensionRegistry.newInstance());
assertThat(proto.hasOptionalInt32()).isTrue();
assertThat(proto.toBuilder().hasOptionalInt32()).isTrue();
}
public void testEquals() throws Exception {
TestProto3Optional.Builder builder = TestProto3Optional.newBuilder();
TestProto3Optional message1 = builder.build();
// Set message2's optional string field to default value. The two
// messages should be different.
builder.setOptionalString("");
TestProto3Optional message2 = builder.build();
assertThat(message1.equals(message2)).isFalse();
}
}
| 1,151 |
471 | <reponame>dimagilg/commcare-hq
from django.conf import settings
def get_custom_login_page(host):
"""
Returns the configured custom login template for the request, if matched, else None
:param request:
:return:
"""
custom_landing_page = settings.CUSTOM_LANDING_TEMPLATE
if custom_landing_page:
if isinstance(custom_landing_page, str):
return custom_landing_page
else:
template_name = custom_landing_page.get(host)
if template_name is None:
return custom_landing_page.get('default')
else:
return template_name
| 275 |
6,059 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "RefChecker.h"
#include "EditableCfgAdapter.h"
#include "Resolver.h"
#include "TypeUtil.h"
CodeRefs::CodeRefs(const DexMethod* method) {
if (!method->get_code()) {
return;
}
std::unordered_set<const DexType*> types_set;
std::unordered_set<const DexMethod*> methods_set;
std::unordered_set<const DexField*> fields_set;
editable_cfg_adapter::iterate(
method->get_code(), [&](const MethodItemEntry& mie) {
auto insn = mie.insn;
if (insn->has_type()) {
always_assert(insn->get_type());
types_set.insert(insn->get_type());
} else if (insn->has_method()) {
auto callee_ref = insn->get_method();
auto callee =
resolve_method(callee_ref, opcode_to_search(insn), method);
if (!callee) {
invalid_refs = true;
return editable_cfg_adapter::LOOP_BREAK;
}
if (callee != callee_ref) {
types_set.insert(callee_ref->get_class());
}
methods_set.insert(callee);
} else if (insn->has_field()) {
auto field_ref = insn->get_field();
auto field = resolve_field(field_ref);
if (!field) {
invalid_refs = true;
return editable_cfg_adapter::LOOP_BREAK;
}
if (field != field_ref) {
types_set.insert(field_ref->get_class());
}
fields_set.insert(field);
}
return editable_cfg_adapter::LOOP_CONTINUE;
});
if (invalid_refs) {
return;
}
std::vector<DexType*> catch_types;
method->get_code()->gather_catch_types(catch_types);
for (auto type : catch_types) {
if (type) {
types_set.insert(type);
}
}
std::copy(types_set.begin(), types_set.end(), std::back_inserter(types));
std::copy(methods_set.begin(), methods_set.end(),
std::back_inserter(methods));
std::copy(fields_set.begin(), fields_set.end(), std::back_inserter(fields));
}
bool RefChecker::check_type(const DexType* type) const {
auto res = m_type_cache.get(type, boost::none);
if (res == boost::none) {
res = check_type_internal(type);
m_type_cache.update(
type, [res](const DexType*, boost::optional<bool>& value, bool exists) {
always_assert(!exists || value == res);
value = res;
});
}
return *res;
}
bool RefChecker::check_method(const DexMethod* method) const {
auto res = m_method_cache.get(method, boost::none);
if (res == boost::none) {
res = check_method_internal(method);
m_method_cache.update(
method,
[res](const DexMethod*, boost::optional<bool>& value, bool exists) {
always_assert(!exists || value == res);
value = res;
});
}
return *res;
}
bool RefChecker::check_field(const DexField* field) const {
auto res = m_field_cache.get(field, boost::none);
if (res == boost::none) {
res = check_field_internal(field);
m_field_cache.update(
field,
[res](const DexField*, boost::optional<bool>& value, bool exists) {
always_assert(!exists || value == res);
value = res;
});
}
return *res;
}
bool RefChecker::check_class(const DexClass* cls) const {
if (!check_type(cls->get_type())) {
return false;
}
const auto fields = cls->get_all_fields();
if (std::any_of(fields.begin(), fields.end(),
[this](DexField* field) { return !check_field(field); })) {
return false;
}
const auto methods = cls->get_all_methods();
if (std::any_of(methods.begin(), methods.end(), [this](DexMethod* method) {
return !check_method_and_code(method);
})) {
return false;
}
return true;
}
bool RefChecker::check_code_refs(const CodeRefs& code_refs) const {
if (code_refs.invalid_refs) {
return false;
}
for (auto type : code_refs.types) {
if (!check_type(type)) {
return false;
}
}
for (auto method : code_refs.methods) {
if (!check_method(method)) {
return false;
}
}
for (auto field : code_refs.fields) {
if (!check_field(field)) {
return false;
}
}
return true;
}
bool RefChecker::check_type_internal(const DexType* type) const {
type = type::get_element_type_if_array(type);
if (type::is_primitive(type)) {
return true;
}
while (true) {
auto cls = type_class(type);
if (cls == nullptr) {
if (type == type::java_lang_String() || type == type::java_lang_Class() ||
type == type::java_lang_Enum() || type == type::java_lang_Object() ||
type == type::java_lang_Void() ||
type == type::java_lang_Throwable() ||
type == type::java_lang_Boolean() || type == type::java_lang_Byte() ||
type == type::java_lang_Short() ||
type == type::java_lang_Character() ||
type == type::java_lang_Integer() || type == type::java_lang_Long() ||
type == type::java_lang_Float() || type == type::java_lang_Double()) {
// This shouldn't be needed, as ideally we have a min-sdk loaded with
// Object in it, but in some tests we don't set up the full
// environment and do need this.
return true;
}
return false;
}
if (cls->is_external()) {
return m_min_sdk_api && m_min_sdk_api->has_type(type);
}
if (m_xstores && m_xstores->illegal_ref(m_store_idx, type)) {
return false;
}
auto interfaces = cls->get_interfaces();
for (auto t : *interfaces) {
if (!check_type(t)) {
return false;
}
}
type = cls->get_super_class();
}
}
bool RefChecker::check_method_internal(const DexMethod* method) const {
auto cls = type_class(method->get_class());
if (cls->is_external()) {
return m_min_sdk_api && m_min_sdk_api->has_method(method);
}
if (!check_type(method->get_class())) {
return false;
}
auto args = method->get_proto()->get_args();
for (auto t : *args) {
if (!check_type(t)) {
return false;
}
}
return check_type(method->get_proto()->get_rtype());
}
bool RefChecker::check_field_internal(const DexField* field) const {
auto cls = type_class(field->get_class());
if (cls->is_external()) {
return m_min_sdk_api && m_min_sdk_api->has_field(field);
}
return check_type(field->get_class()) && check_type(field->get_type());
}
bool RefChecker::is_in_primary_dex(const DexType* type) const {
return m_xstores && m_xstores->is_in_primary_dex(type);
}
| 2,868 |