max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
852
<filename>CondFormats/RPCObjects/interface/RPCObFebAssmap.h<gh_stars>100-1000 /* * Payload definition(s): Feb Map (RPCObFebAssmap) * * $Date: 2009/11/16 12:53:47 $ * $Revision: 1.3 $ * \author <NAME> - <NAME>. e Teo. & INFN Pavia */ #ifndef RPCObFebAssmap_h #define RPCObFebAssmap_h #include <vector> #include <string> class RPCObFebAssmap { public: struct FebAssmap_Item { int dpid; int region; int ring; int station; int sector; int layer; int subsector; int chid; }; RPCObFebAssmap() {} virtual ~RPCObFebAssmap() {} std::vector<FebAssmap_Item> ObFebAssmap_rpc; }; #endif
269
1,139
#!/usr/bin/python3 # # This tool connects to the given Exchange's hostname/IP address and then # by collects various internal information being leaked while interacting # with different Exchange protocols. Exchange may give away following helpful # during OSINT or breach planning stages insights: # - Internal IP address # - Internal Domain Name (ActiveDirectory) # - Exchange Server Version # - support for various SMTP User Enumeration techniques # - Version of underlying software such as ASP.NET, IIS which # may point at OS version indirectly # # This tool will be helpful before mounting social engieering attack against # victim's premises or to aid Password-Spraying efforts against exposed OWA # interface. # # OPSEC: # All of the traffic that this script generates is not invasive and should # not be picked up by SOC/Blue Teams as it closely resembles random usual traffic # directed at both OWA, or Exchange SMTP protocols/interfaces. The only potentially # shady behaviour could be observed on one-shot attempts to perform SMTP user # enumeration, however it is unlikely that single commands would trigger SIEM use cases. # # TODO: # - introduce some fuzzy logic for Exchange version recognition # - Extend SMTP User Enumeration validation capabilities # # Requirements: # - pyOpenSSL # - packaging # # Author: # <NAME>. / mgeeky, '19, <<EMAIL>> # import re import sys import ssl import time import base64 import struct import string import socket import smtplib import urllib3 import requests import argparse import threading import collections import packaging.version from urllib.parse import urlparse import OpenSSL.crypto as crypto VERSION = '0.2' config = { 'debug' : False, 'verbose' : False, 'timeout' : 6.0, } found_dns_domain = '' urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) class Logger: @staticmethod def _out(x): if config['verbose'] or config['debug']: sys.stdout.write(x + '\n') @staticmethod def out(x): Logger._out('[.] ' + x) @staticmethod def info(x): Logger._out('[.] ' + x) @staticmethod def dbg(x): if config['debug']: Logger._out('[DEBUG] ' + x) @staticmethod def err(x): sys.stdout.write('[!] ' + x + '\n') @staticmethod def fail(x): Logger._out('[-] ' + x) @staticmethod def ok(x): Logger._out('[+] ' + x) def hexdump(data): s = '' n = 0 lines = [] tableline = '-----+' + '-' * 24 + '|' \ + '-' * 25 + '+' + '-' * 18 + '+\n' if isinstance(data, str): data = data.encode() if len(data) == 0: return '<empty>' for i in range(0, len(data), 16): line = '' line += '%04x | ' % (i) n += 16 for j in range(n-16, n): if j >= len(data): break line += '%02x' % (data[j] & 0xff) if j % 8 == 7 and j % 16 != 15: line += '-' else: line += ' ' line += ' ' * (3 * 16 + 7 - len(line)) + ' | ' for j in range(n-16, n): if j >= len(data): break c = data[j] if not (data[j] < 0x20 or data[j] > 0x7e) else '.' line += '%c' % c line = line.ljust(74, ' ') + ' |' lines.append(line) return tableline + '\n'.join(lines) + '\n' + tableline class NtlmParser: # # Based on: # https://gist.github.com/aseering/829a2270b72345a1dc42 # VALID_CHRS = set(string.ascii_letters + string.digits + string.punctuation) flags_tbl_str = ( (0x00000001, "Negotiate Unicode"), (0x00000002, "Negotiate OEM"), (0x00000004, "Request Target"), (0x00000008, "unknown"), (0x00000010, "Negotiate Sign"), (0x00000020, "Negotiate Seal"), (0x00000040, "Negotiate Datagram Style"), (0x00000080, "Negotiate Lan Manager Key"), (0x00000100, "Negotiate Netware"), (0x00000200, "Negotiate NTLM"), (0x00000400, "unknown"), (0x00000800, "Negotiate Anonymous"), (0x00001000, "Negotiate Domain Supplied"), (0x00002000, "Negotiate Workstation Supplied"), (0x00004000, "Negotiate Local Call"), (0x00008000, "Negotiate Always Sign"), (0x00010000, "Target Type Domain"), (0x00020000, "Target Type Server"), (0x00040000, "Target Type Share"), (0x00080000, "Negotiate NTLM2 Key"), (0x00100000, "Request Init Response"), (0x00200000, "Request Accept Response"), (0x00400000, "Request Non-NT Session Key"), (0x00800000, "Negotiate Target Info"), (0x01000000, "unknown"), (0x02000000, "unknown"), (0x04000000, "unknown"), (0x08000000, "unknown"), (0x10000000, "unknown"), (0x20000000, "Negotiate 128"), (0x40000000, "Negotiate Key Exchange"), (0x80000000, "Negotiate 56") ) def __init__(self): self.output = {} self.flags_tbl = NtlmParser.flags_tbl_str self.msg_types = collections.defaultdict(lambda: "UNKNOWN") self.msg_types[1] = "Request" self.msg_types[2] = "Challenge" self.msg_types[3] = "Response" self.target_field_types = collections.defaultdict(lambda: "UNKNOWN") self.target_field_types[0] = ("TERMINATOR", str) self.target_field_types[1] = ("Server name", str) self.target_field_types[2] = ("AD domain name", str) self.target_field_types[3] = ("FQDN", str) self.target_field_types[4] = ("DNS domain name", str) self.target_field_types[5] = ("Parent DNS domain", str) self.target_field_types[7] = ("Server Timestamp", int) def flags_lst(self, flags): return [desc for val, desc in self.flags_tbl if val & flags] def flags_str(self, flags): return ['%s' % s for s in self.flags_lst(flags)] def clean_str(self, st): return ''.join((s if s in NtlmParser.VALID_CHRS else '?') for s in st) class StrStruct(object): def __init__(self, pos_tup, raw): length, alloc, offset = pos_tup self.length = length self.alloc = alloc self.offset = offset self.raw = raw[offset:offset+length] self.utf16 = False if len(self.raw) >= 2 and self.raw[1] == 0: try: self.string = self.raw.decode('utf-16') except: self.string = ''.join(filter(lambda x: str(x) != str('\0'), self.raw)) self.utf16 = True else: self.string = self.raw def __str__(self): return ''.join((s if s in NtlmParser.VALID_CHRS else '?') for s in self.string) def parse(self, data): st = base64.b64decode(data) if st[:len('NTLMSSP')].decode() == "NTLMSSP": pass else: raise Exception("NTLMSSP header not found at start of input string") ver = struct.unpack("<i", st[8:12])[0] if ver == 1: self.request(st) elif ver == 2: self.challenge(st) elif ver == 3: self.response(st) else: o = "Unknown message structure. Have a raw (hex-encoded) message:" o += st.encode("hex") raise Exception(o) return self.output def opt_str_struct(self, name, st, offset): nxt = st[offset:offset+8] if len(nxt) == 8: hdr_tup = struct.unpack("<hhi", nxt) self.output[name] = str(NtlmParser.StrStruct(hdr_tup, st)) else: self.output[name] = "" def opt_inline_str(self, name, st, offset, sz): nxt = st[offset:offset+sz] if len(nxt) == sz: self.output[name] = self.clean_str(nxt) else: self.output[name] = "" def request(self, st): hdr_tup = struct.unpack("<i", st[12:16]) flags = hdr_tup[0] self.opt_str_struct("Domain", st, 16) self.opt_str_struct("Workstation", st, 24) self.opt_inline_str("OS Ver", st, 32, 8) self.output['Flags'] = self.flags_str(flags) @staticmethod def win_file_time_to_datetime(ft): from datetime import datetime EPOCH_AS_FILETIME = 116444736000000000 # January 1, 1970 as MS file time utc = datetime.utcfromtimestamp((ft - EPOCH_AS_FILETIME) / 10000000) return utc.strftime('%y-%m-%d %a %H:%M:%S UTC') def challenge(self, st): hdr_tup = struct.unpack("<hhiiQ", st[12:32]) self.output['Target Name'] = str(NtlmParser.StrStruct(hdr_tup[0:3], st)) self.output['Challenge'] = hdr_tup[4] flags = hdr_tup[3] self.opt_str_struct("Context", st, 32) nxt = st[40:48] if len(nxt) == 8: hdr_tup = struct.unpack("<hhi", nxt) tgt = NtlmParser.StrStruct(hdr_tup, st) self.output['Target'] = {} raw = tgt.raw pos = 0 while pos+4 < len(raw): rec_hdr = struct.unpack("<hh", raw[pos : pos+4]) rec_type_id = rec_hdr[0] rec_type, rec_type_type = self.target_field_types[rec_type_id] rec_sz = rec_hdr[1] subst = raw[pos+4 : pos+4+rec_sz] if rec_type_type == int: if 'Timestamp' in rec_type: self.output['Target'][rec_type] = NtlmParser.win_file_time_to_datetime( struct.unpack("<Q", subst)[0] ) else: self.output['Target'][rec_type] = struct.unpack("<Q", subst)[0] elif rec_type_type == str: try: self.output['Target'][rec_type] = subst.decode('utf-16') except: self.output['Target'][rec_type] = subst pos += 4 + rec_sz self.opt_inline_str("OS Ver", st, 48, 8) self.output['Flags'] = self.flags_str(flags) def response(self, st): hdr_tup = struct.unpack("<hhihhihhihhihhi", st[12:52]) self.output['LM Resp'] = str(NtlmParser.StrStruct(hdr_tup[0:3], st)) self.output['NTLM Resp'] = str(NtlmParser.StrStruct(hdr_tup[3:6], st)) self.output['Target Name'] = str(NtlmParser.StrStruct(hdr_tup[6:9], st)) self.output['User Name'] = str(NtlmParser.StrStruct(hdr_tup[9:12], st)) self.output['Host Name'] = str(NtlmParser.StrStruct(hdr_tup[12:15], st)) self.opt_str_struct("Session Key", st, 52) self.opt_inline_str("OS Ver", st, 64, 8) nxt = st[60:64] if len(nxt) == 4: flg_tup = struct.unpack("<i", nxt) flags = flg_tup[0] self.output['Flags'] = self.flags_str(flags) else: self.output['Flags'] = "" class ExchangeRecon: COMMON_PORTS = (443, 80, 8080, 8000) MAX_RECONNECTS = 3 MAX_REDIRECTS = 10 HEADERS = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', #'Connection': 'close', } leakedInternalIp = 'Leaked Internal IP address' leakedInternalDomainNTLM = 'Leaked Internal Domain name in NTLM challenge packet' iisVersion = 'IIS Version' aspVersion = 'ASP.Net Version' unusualHeaders = 'Unusual HTTP headers observed' owaVersionInHttpHeader = 'Outlook Web App version HTTP header' legacyMailCapabilities = "Exchange supports legacy SMTP and returned following banner/unusual capabilities" usualHeaders = { 'accept-ranges', 'access-control-allow-origin', 'age', 'cache', 'cache-control', 'connection', 'content-encoding', 'content-length', 'content-security-policy', 'content-type', 'cookie', 'date', 'etag', 'expires', 'last-modified', 'link', 'location', 'pragma', 'referrer-policy', 'request-id', 'server', 'set-cookie', 'status', 'strict-transport-security', 'vary', 'via', 'www-authenticate', 'x-aspnet-version', 'x-content-type-options', 'x-frame-options', 'x-powered-by', 'x-xss-protection', } htmlregexes = { 'Outlook Web App version leaked in OWA HTML source' : r'/owa/(?:auth/)?((?:\d+\.)+\d+)/(?:themes|scripts)/' } class Verstring(object): def __init__(self, name, date, *versions): self.name = name self.date = date self.version = versions[0].split(' ')[0] def __eq__(self, other): if isinstance(other, Verstring): return packaging.version.parse(self.version) == packaging.version.parse(other.version) \ and self.name == other.name elif isinstance(other, str): return packaging.version.parse(self.version) == packaging.version.parse(other) def __lt__(self, other): return packaging.version.parse(self.version) < packaging.version.parse(other.version) def __str__(self): return f'{self.name}; {self.date}; {self.version}' # https://docs.microsoft.com/en-us/exchange/new-features/build-numbers-and-release-dates?view=exchserver-2019 exchangeVersions = ( Verstring('Exchange Server 4.0 SP5 ', 'May 5, 1998', '4.0.996'), Verstring('Exchange Server 4.0 SP4 ', 'March 28, 1997', '4.0.995'), Verstring('Exchange Server 4.0 SP3 ', 'October 29, 1996', '4.0.994'), Verstring('Exchange Server 4.0 SP2 ', 'July 19, 1996', '4.0.993'), Verstring('Exchange Server 4.0 SP1 ', 'May 1, 1996', '4.0.838'), Verstring('Exchange Server 4.0 Standard Edition', 'June 11, 1996', '4.0.837'), Verstring('Exchange Server 5.0 SP2 ', 'February 19, 1998', '5.0.1460'), Verstring('Exchange Server 5.0 SP1 ', 'June 18, 1997', '5.0.1458'), Verstring('Exchange Server 5.0 ', 'May 23, 1997', '5.0.1457'), Verstring('Exchange Server version 5.5 SP4 ', 'November 1, 2000', '5.5.2653'), Verstring('Exchange Server version 5.5 SP3 ', 'September 9, 1999', '5.5.2650'), Verstring('Exchange Server version 5.5 SP2 ', 'December 23, 1998', '5.5.2448'), Verstring('Exchange Server version 5.5 SP1 ', 'August 5, 1998', '5.5.2232'), Verstring('Exchange Server version 5.5 ', 'February 3, 1998', '5.5.1960'), Verstring('Exchange 2000 Server post-SP3', 'August 2008', '6.0.6620.7'), Verstring('Exchange 2000 Server post-SP3', 'March 2008', '6.0.6620.5'), Verstring('Exchange 2000 Server post-SP3', 'August 2004', '6.0.6603'), Verstring('Exchange 2000 Server post-SP3', 'April 2004', '6.0.6556'), Verstring('Exchange 2000 Server post-SP3', 'September 2003', '6.0.6487'), Verstring('Exchange 2000 Server SP3', 'July 18, 2002', '6.0.6249'), Verstring('Exchange 2000 Server SP2', 'November 29, 2001', '6.0.5762'), Verstring('Exchange 2000 Server SP1', 'June 21, 2001', '6.0.4712'), Verstring('Exchange 2000 Server', 'November 29, 2000', '6.0.4417'), Verstring('Exchange Server 2003 post-SP2', 'August 2008', '6.5.7654.4'), Verstring('Exchange Server 2003 post-SP2', 'March 2008', '6.5.7653.33'), Verstring('Exchange Server 2003 SP2', 'October 19, 2005', '6.5.7683'), Verstring('Exchange Server 2003 SP1', 'May25, 2004', '6.5.7226'), Verstring('Exchange Server 2003', 'September 28, 2003', '6.5.6944'), Verstring('Update Rollup 5 for Exchange Server 2007 SP2', 'December 7, 2010', '8.2.305.3', '8.02.0305.003'), Verstring('Update Rollup 4 for Exchange Server 2007 SP2', 'April 9, 2010', '192.168.127.12', '8.02.0254.000'), Verstring('Update Rollup 3 for Exchange Server 2007 SP2', 'March 17, 2010', '172.16.31.10', '8.02.0247.002'), Verstring('Update Rollup 2 for Exchange Server 2007 SP2', 'January 22, 2010', '192.168.127.12', '8.02.0234.001'), Verstring('Update Rollup 1 for Exchange Server 2007 SP2', 'November 19, 2009', '172.16.31.10', '8.02.0217.003'), Verstring('Exchange Server 2007 SP2', 'August 24, 2009', '192.168.3.11', '8.02.0176.002'), Verstring('Update Rollup 10 for Exchange Server 2007 SP1', 'April 13, 2010', '8.1.436.0', '8.01.0436.000'), Verstring('Update Rollup 9 for Exchange Server 2007 SP1', 'July 16, 2009', '8.1.393.1', '8.01.0393.001'), Verstring('Update Rollup 8 for Exchange Server 2007 SP1', 'May 19, 2009', '8.1.375.2', '8.01.0375.002'), Verstring('Update Rollup 7 for Exchange Server 2007 SP1', 'March 18, 2009', '8.1.359.2', '8.01.0359.002'), Verstring('Update Rollup 6 for Exchange Server 2007 SP1', 'February 10, 2009', '8.1.340.1', '8.01.0340.001'), Verstring('Update Rollup 5 for Exchange Server 2007 SP1', 'November 20, 2008', '8.1.336.1', '8.01.0336.01'), Verstring('Update Rollup 4 for Exchange Server 2007 SP1', 'October 7, 2008', '8.1.311.3', '8.01.0311.003'), Verstring('Update Rollup 3 for Exchange Server 2007 SP1', 'July 8, 2008', '8.1.291.2', '8.01.0291.002'), Verstring('Update Rollup 2 for Exchange Server 2007 SP1', 'May 9, 2008', '8.1.278.2', '8.01.0278.002'), Verstring('Update Rollup 1 for Exchange Server 2007 SP1', 'February 28, 2008', '8.1.263.1', '8.01.0263.001'), Verstring('Exchange Server 2007 SP1', 'November 29, 2007', '192.168.127.12', '8.01.0240.006'), Verstring('Update Rollup 7 for Exchange Server 2007', 'July 8, 2008', '8.0.813.0', '8.00.0813.000'), Verstring('Update Rollup 6 for Exchange Server 2007', 'February 21, 2008', '8.0.783.2', '8.00.0783.002'), Verstring('Update Rollup 5 for Exchange Server 2007', 'October 25, 2007', '8.0.754.0', '8.00.0754.000'), Verstring('Update Rollup 4 for Exchange Server 2007', 'August 23, 2007', '8.0.744.0', '8.00.0744.000'), Verstring('Update Rollup 3 for Exchange Server 2007', 'June 28, 2007', '8.0.730.1', '8.00.0730.001'), Verstring('Update Rollup 2 for Exchange Server 2007', 'May 8, 2007', '8.0.711.2', '8.00.0711.002'), Verstring('Update Rollup 1 for Exchange Server 2007', 'April 17, 2007', '8.0.708.3', '8.00.0708.003'), Verstring('Exchange Server 2007 RTM', 'March 8, 2007', '8.0.685.25 8.00.0685.025'), Verstring('Update Rollup 23 for Exchange Server 2007 SP3', 'March 21, 2017', '8.3.517.0', '8.03.0517.000'), Verstring('Update Rollup 22 for Exchange Server 2007 SP3', 'December 13, 2016', '8.3.502.0', '8.03.0502.000'), Verstring('Update Rollup 21 for Exchange Server 2007 SP3', 'September 20, 2016', '8.3.485.1', '8.03.0485.001'), Verstring('Update Rollup 20 for Exchange Server 2007 SP3', 'June 21, 2016', '8.3.468.0', '8.03.0468.000'), Verstring('Update Rollup 19 forExchange Server 2007 SP3', 'March 15, 2016', '8.3.459.0', '8.03.0459.000'), Verstring('Update Rollup 18 forExchange Server 2007 SP3', 'December, 2015', '8.3.445.0', '8.03.0445.000'), Verstring('Update Rollup 17 forExchange Server 2007 SP3', 'June 17, 2015', '8.3.417.1', '8.03.0417.001'), Verstring('Update Rollup 16 for Exchange Server 2007 SP3', 'March 17, 2015', '8.3.406.0', '8.03.0406.000'), Verstring('Update Rollup 15 for Exchange Server 2007 SP3', 'December 9, 2014', '8.3.389.2', '8.03.0389.002'), Verstring('Update Rollup 14 for Exchange Server 2007 SP3', 'August 26, 2014', '8.3.379.2', '8.03.0379.002'), Verstring('Update Rollup 13 for Exchange Server 2007 SP3', 'February 24, 2014', '8.3.348.2', '8.03.0348.002'), Verstring('Update Rollup 12 for Exchange Server 2007 SP3', 'December 9, 2013', '8.3.342.4', '8.03.0342.004'), Verstring('Update Rollup 11 for Exchange Server 2007 SP3', 'August 13, 2013', '8.3.327.1', '8.03.0327.001'), Verstring('Update Rollup 10 for Exchange Server 2007 SP3', 'February 11, 2013', '8.3.298.3', '8.03.0298.003'), Verstring('Update Rollup 9 for Exchange Server 2007 SP3', 'December 10, 2012', '8.3.297.2', '8.03.0297.002'), Verstring('Update Rollup 8-v3 for Exchange Server 2007 SP3 ', 'November 13, 2012', '8.3.279.6', '8.03.0279.006'), Verstring('Update Rollup 8-v2 for Exchange Server 2007 SP3 ', 'October 9, 2012', '8.3.279.5', '8.03.0279.005'), Verstring('Update Rollup 8 for Exchange Server 2007 SP3', 'August 13, 2012', '8.3.279.3', '8.03.0279.003'), Verstring('Update Rollup 7 for Exchange Server 2007 SP3', 'April 16, 2012', '8.3.264.0', '8.03.0264.000'), Verstring('Update Rollup 6 for Exchange Server 2007 SP3', 'January 26, 2012', '192.168.127.12', '8.03.0245.002'), Verstring('Update Rollup 5 for Exchange Server 2007 SP3', 'September 21, 2011', '172.16.58.3', '8.03.0213.001'), Verstring('Update Rollup 4 for Exchange Server 2007 SP3', 'May 28, 2011', '172.16.17.32', '8.03.0192.001'), Verstring('Update Rollup 3-v2 for Exchange Server 2007 SP3 ', 'March 30, 2011', '172.16.31.10', '8.03.0159.002'), Verstring('Update Rollup 2 for Exchange Server 2007 SP3', 'December 10, 2010', '172.16.17.32', '8.03.0137.003'), Verstring('Update Rollup 1 for Exchange Server 2007 SP3', 'September 9, 2010', '172.16.58.3', '8.03.0106.002'), Verstring('Exchange Server 2007 SP3', 'June 7, 2010', '172.16.31.10', '8.03.0083.006'), Verstring('Update Rollup 8 for Exchange Server 2010 SP2', 'December 9, 2013', '14.2.390.3 14.02.0390.003'), Verstring('Update Rollup 7 for Exchange Server 2010 SP2', 'August 3, 2013', '14.2.375.0 14.02.0375.000'), Verstring('Update Rollup 6 Exchange Server 2010 SP2', 'February 12, 2013', '14.2.342.3 14.02.0342.003'), Verstring('Update Rollup 5 v2 for Exchange Server 2010 SP2 ', 'December 10, 2012', '14.2.328.10 14.02.0328.010'), Verstring('Update Rollup 5 for Exchange Server 2010 SP2', 'November 13, 2012', '14.3.328.5 14.03.0328.005'), Verstring('Update Rollup 4 v2 for Exchange Server 2010 SP2 ', 'October 9, 2012', '14.2.318.4 14.02.0318.004'), Verstring('Update Rollup 4 for Exchange Server 2010 SP2', 'August 13, 2012', '14.2.318.2 14.02.0318.002'), Verstring('Update Rollup 3 for Exchange Server 2010 SP2', 'May 29, 2012', '14.2.309.2 14.02.0309.002'), Verstring('Update Rollup 2 for Exchange Server 2010 SP2', 'April 16, 2012', '14.2.298.4 14.02.0298.004'), Verstring('Update Rollup 1 for Exchange Server 2010 SP2', 'February 13, 2012', '14.2.283.3 14.02.0283.003'), Verstring('Exchange Server 2010 SP2', 'December 4, 2011', '172.16.58.3 14.02.0247.005'), Verstring('Update Rollup 8 for Exchange Server 2010 SP1', 'December 10, 2012', '14.1.438.0 14.01.0438.000'), Verstring('Update Rollup 7 v3 for Exchange Server 2010 SP1 ', 'November 13, 2012', '14.1.421.3 14.01.0421.003'), Verstring('Update Rollup 7 v2 for Exchange Server 2010 SP1 ', 'October 10, 2012', '14.1.421.2 14.01.0421.002'), Verstring('Update Rollup 7 for Exchange Server 2010 SP1', 'August 8, 2012', '14.1.421.0 14.01.0421.000'), Verstring('Update Rollup 6 for Exchange Server 2010 SP1', 'October 27, 2011', '14.1.355.2 14.01.0355.002'), Verstring('Update Rollup 5 for Exchange Server 2010 SP1', 'August 23, 2011', '14.1.339.1 14.01.0339.001'), Verstring('Update Rollup 4 for Exchange Server 2010 SP1', 'July 27, 2011', '14.1.323.6 14.01.0323.006'), Verstring('Update Rollup 3 for Exchange Server 2010 SP1', 'April 6, 2011', '14.1.289.7 14.01.0289.007'), Verstring('Update Rollup 2 for Exchange Server 2010 SP1', 'December 9, 2010', '14.1.270.1 14.01.0270.001'), Verstring('Update Rollup 1 for Exchange Server 2010 SP1', 'October 4, 2010', '192.168.3.11 14.01.0255.002'), Verstring('Exchange Server 2010 SP1', 'August 23, 2010', '192.168.3.11 14.01.0218.015'), Verstring('Update Rollup 5 for Exchange Server 2010', 'December 13, 2010', '14.0.726.0 14.00.0726.000'), Verstring('Update Rollup 4 for Exchange Server 2010', 'June 10, 2010', '14.0.702.1 14.00.0702.001'), Verstring('Update Rollup 3 for Exchange Server 2010', 'April 13, 2010', '14.0.694.0 14.00.0694.000'), Verstring('Update Rollup 2 for Exchange Server 2010', 'March 4, 2010', '14.0.689.0 14.00.0689.000'), Verstring('Update Rollup 1 for Exchange Server 2010', 'December 9, 2009', '14.0.682.1 14.00.0682.001'), Verstring('Exchange Server 2010 RTM', 'November 9, 2009', '14.0.639.21 14.00.0639.021'), Verstring('Update Rollup 29 for Exchange Server 2010 SP3', 'July 9, 2019', '14.3.468.0 14.03.0468.000'), Verstring('Update Rollup 28 for Exchange Server 2010 SP3', 'June 7, 2019', '14.3.461.1 14.03.0461.001'), Verstring('Update Rollup 27 for Exchange Server 2010 SP3', 'April 9, 2019', '14.3.452.0 14.03.0452.000'), Verstring('Update Rollup 26 for Exchange Server 2010 SP3', 'February 12, 2019', '14.3.442.0 14.03.0442.000'), Verstring('Update Rollup 25 for Exchange Server 2010 SP3', 'January 8, 2019', '14.3.435.0 14.03.0435.000'), Verstring('Update Rollup 24 for Exchange Server 2010 SP3', 'September 5, 2018', '14.3.419.0 14.03.0419.000'), Verstring('Update Rollup 23 for Exchange Server 2010 SP3', 'August 13, 2018', '14.3.417.1 14.03.0417.001'), Verstring('Update Rollup 22 for Exchange Server 2010 SP3', 'June 19, 2018', '14.3.411.0 14.03.0411.000'), Verstring('Update Rollup 21 for Exchange Server 2010 SP3', 'May 7, 2018', '14.3.399.2 14.03.0399.002'), Verstring('Update Rollup 20 for Exchange Server 2010 SP3', 'March 5, 2018', '14.3.389.1 14.03.0389.001'), Verstring('Update Rollup 19 for Exchange Server 2010 SP3', 'December 19, 2017', '14.3.382.0 14.03.0382.000'), Verstring('Update Rollup 18 for Exchange Server 2010 SP3', 'July 11, 2017', '14.3.361.1 14.03.0361.001'), Verstring('Update Rollup 17 for Exchange Server 2010 SP3', 'March 21, 2017', '14.3.352.0 14.03.0352.000'), Verstring('Update Rollup 16 for Exchange Server 2010 SP3', 'December 13, 2016', '14.3.336.0 14.03.0336.000'), Verstring('Update Rollup 15 for Exchange Server 2010 SP3', 'September 20, 2016', '14.3.319.2 14.03.0319.002'), Verstring('Update Rollup 14 for Exchange Server 2010 SP3', 'June 21, 2016', '14.3.301.0 14.03.0301.000'), Verstring('Update Rollup 13 for Exchange Server 2010 SP3', 'March 15, 2016', '14.3.294.0 14.03.0294.000'), Verstring('Update Rollup 12 for Exchange Server 2010 SP3', 'December 15, 2015', '14.3.279.2 14.03.0279.002'), Verstring('Update Rollup 11 for Exchange Server 2010 SP3', 'September 15, 2015', '14.3.266.2 14.03.0266.002'), Verstring('Update Rollup 10 for Exchange Server 2010 SP3', 'June 17, 2015', '172.16.17.32 14.03.0248.002'), Verstring('Update Rollup 9 for Exchange Server 2010 SP3', 'March 17, 2015', '172.16.17.32 14.03.0235.001'), Verstring('Update Rollup 8 v2 for Exchange Server 2010 SP3 ', 'December 12, 2014', '192.168.127.12 14.03.0224.002'), Verstring('Update Rollup 8 v1 for Exchange Server 2010 SP3 (recalled) ', 'December 9, 2014', '172.16.17.32 14.03.0224.001'), Verstring('Update Rollup 7 for Exchange Server 2010 SP3', 'August 26, 2014', '172.16.31.10 14.03.0210.002'), Verstring('Update Rollup 6 for Exchange Server 2010 SP3', 'May 27, 2014', '192.168.127.12 14.03.0195.001'), Verstring('Update Rollup 5 for Exchange Server 2010 SP3', 'February 24, 2014', '172.16.17.32 14.03.0181.006'), Verstring('Update Rollup 4 for Exchange Server 2010 SP3', 'December 9, 2013', '192.168.127.12 14.03.0174.001'), Verstring('Update Rollup 3 for Exchange Server 2010 SP3', 'November 25, 2013', '192.168.127.12 14.03.0169.001'), Verstring('Update Rollup 2 for Exchange Server 2010 SP3', 'August 8, 2013', '172.16.58.3 14.03.0158.001'), Verstring('Update Rollup 1 for Exchange Server 2010 SP3', 'May 29, 2013', '192.168.127.12 14.03.0146.000'), Verstring('Exchange Server 2010 SP3', 'February 12, 2013', '172.16.31.10 14.03.0123.004'), Verstring('Exchange Server 2013 CU23', 'June 18, 2019', '15.0.1497.2 15.00.1497.002'), Verstring('Exchange Server 2013 CU22', 'February 12, 2019', '15.0.1473.3 15.00.1473.003'), Verstring('Exchange Server 2013 CU21', 'June 19, 2018', '15.0.1395.4 15.00.1395.004'), Verstring('Exchange Server 2013 CU20', 'March 20, 2018', '15.0.1367.3 15.00.1367.003'), Verstring('Exchange Server 2013 CU19', 'December 19, 2017', '15.0.1365.1 15.00.1365.001'), Verstring('Exchange Server 2013 CU18', 'September 19, 2017', '15.0.1347.2 15.00.1347.002'), Verstring('Exchange Server 2013 CU17', 'June 27, 2017', '15.0.1320.4 15.00.1320.004'), Verstring('Exchange Server 2013 CU16', 'March 21, 2017', '15.0.1293.2 15.00.1293.002'), Verstring('Exchange Server 2013 CU15', 'December 13, 2016', '15.0.1263.5 15.00.1263.005'), Verstring('Exchange Server 2013 CU14', 'September 20, 2016', '15.0.1236.3 15.00.1236.003'), Verstring('Exchange Server 2013 CU13', 'June 21, 2016', '15.0.1210.3 15.00.1210.003'), Verstring('Exchange Server 2013 CU12', 'March 15, 2016', '15.0.1178.4 15.00.1178.004'), Verstring('Exchange Server 2013 CU11', 'December 15, 2015', '15.0.1156.6 15.00.1156.006'), Verstring('Exchange Server 2013 CU10', 'September 15, 2015', '15.0.1130.7 15.00.1130.007'), Verstring('Exchange Server 2013 CU9', 'June 17, 2015', '15.0.1104.5 15.00.1104.005'), Verstring('Exchange Server 2013 CU8', 'March 17, 2015', '15.0.1076.9 15.00.1076.009'), Verstring('Exchange Server 2013 CU7', 'December 9, 2014', '15.0.1044.25', '15.00.1044.025'), Verstring('Exchange Server 2013 CU6', 'August 26, 2014', '15.0.995.29 15.00.0995.029'), Verstring('Exchange Server 2013 CU5', 'May 27, 2014', '15.0.913.22 15.00.0913.022'), Verstring('Exchange Server 2013 SP1', 'February 25, 2014', '15.0.847.32 15.00.0847.032'), Verstring('Exchange Server 2013 CU3', 'November 25, 2013', '15.0.775.38 15.00.0775.038'), Verstring('Exchange Server 2013 CU2', 'July 9, 2013', '15.0.712.24 15.00.0712.024'), Verstring('Exchange Server 2013 CU1', 'April 2, 2013', '15.0.620.29 15.00.0620.029'), Verstring('Exchange Server 2013 RTM', 'December 3, 2012', '15.0.516.32 15.00.0516.03'), Verstring('Exchange Server 2016 CU14', 'September 17, 2019', '15.1.1847.3 15.01.1847.003'), Verstring('Exchange Server 2016 CU13', 'June 18, 2019', '15.1.1779.2 15.01.1779.002'), Verstring('Exchange Server 2016 CU12', 'February 12, 2019', '15.1.1713.5 15.01.1713.005'), Verstring('Exchange Server 2016 CU11', 'October 16, 2018', '15.1.1591.10', '15.01.1591.010'), Verstring('Exchange Server 2016 CU10', 'June 19, 2018', '15.1.1531.3 15.01.1531.003'), Verstring('Exchange Server 2016 CU9', 'March 20, 2018', '15.1.1466.3 15.01.1466.003'), Verstring('Exchange Server 2016 CU8', 'December 19, 2017', '15.1.1415.2 15.01.1415.002'), Verstring('Exchange Server 2016 CU7', 'September 19, 2017', '15.1.1261.35', '15.01.1261.035'), Verstring('Exchange Server 2016 CU6', 'June 27, 2017', '15.1.1034.26', '15.01.1034.026'), Verstring('Exchange Server 2016 CU5', 'March 21, 2017', '15.1.845.34 15.01.0845.034'), Verstring('Exchange Server 2016 CU4', 'December 13, 2016', '15.1.669.32 15.01.0669.032'), Verstring('Exchange Server 2016 CU3', 'September 20, 2016', '15.1.544.27 15.01.0544.027'), Verstring('Exchange Server 2016 CU2', 'June 21, 2016', '15.1.466.34 15.01.0466.034'), Verstring('Exchange Server 2016 CU1', 'March 15, 2016', '15.1.396.30 15.01.0396.030'), Verstring('Exchange Server 2016 RTM', 'October 1, 2015', '172.16.58.3 15.01.0225.042'), Verstring('Exchange Server 2016 Preview', 'July 22, 2015', '172.16.31.10 15.01.0225.016'), Verstring('Exchange Server 2019 CU3', 'September 17, 2019', '15.2.464.5 15.02.0464.005'), Verstring('Exchange Server 2019 CU2', 'June 18, 2019', '15.2.397.3 15.02.0397.003'), Verstring('Exchange Server 2019 CU1', 'February 12, 2019', '15.2.330.5 15.02.0330.005'), Verstring('Exchange Server 2019 RTM', 'October 22, 2018', '172.16.17.32 15.02.0221.012'), Verstring('Exchange Server 2019 Preview', 'July 24, 2018', '172.16.17.32 15.02.0196.000'), Verstring('Exchange Server 2019 CU11', 'October 12, 2021', '15.2.986.9'), Verstring('Exchange Server 2019 CU11', 'September 28, 2021', '15.2.986.5'), Verstring('Exchange Server 2019 CU10', 'October 12, 2021', '15.2.922.14'), Verstring('Exchange Server 2019 CU10', 'July 13, 2021', '15.2.922.13'), Verstring('Exchange Server 2019 CU10', 'June 29, 2021', '15.2.922.7'), Verstring('Exchange Server 2019 CU9', 'July 13, 2021', '15.2.858.15'), Verstring('Exchange Server 2019 CU9', 'May 11, 2021', '15.2.858.12'), Verstring('Exchange Server 2019 CU9', 'April 13, 2021', '15.2.858.10'), Verstring('Exchange Server 2019 CU9', 'March 16, 2021', '15.2.858.5'), Verstring('Exchange Server 2019 CU8', 'May 11, 2021', '15.2.792.15'), Verstring('Exchange Server 2019 CU8', 'April 13, 2021', '15.2.792.13'), Verstring('Exchange Server 2019 CU8', 'March 2, 2021', '15.2.792.10'), Verstring('Exchange Server 2019 CU8', 'December 15, 2020', '15.2.792.3'), Verstring('Exchange Server 2019 CU7', 'March 2, 2021', '15.2.721.13'), Verstring('Exchange Server 2019 CU7', 'September 15, 2020', '15.2.721.2'), Verstring('Exchange Server 2019 CU6', 'March 2, 2021', '15.2.659.12'), Verstring('Exchange Server 2019 CU6', 'June 16, 2020', '15.2.659.4'), Verstring('Exchange Server 2019 CU5', 'March 2, 2021', '15.2.595.8'), Verstring('Exchange Server 2019 CU5', 'March 17, 2020', '15.2.595.3'), Verstring('Exchange Server 2019 CU4', 'March 2, 2021', '15.2.529.13'), Verstring('Exchange Server 2019 CU4', 'December 17, 2019', '15.2.529.5'), Verstring('Exchange Server 2019 CU3', 'March 2, 2021', '15.2.464.15') ) def __init__(self, hostname): self.socket = None self.server_tls_params = None self.hostname = hostname self.port = None self.reconnect = 0 self.results = {} def disconnect(self): if self.socket != None: self.socket.close() self.socket = None def connect(self, host, port, _ssl = True): try: Logger.dbg(f"Attempting to reach {host}:{port}...") with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: if self.socket != None: self.socket.close() self.socket = None sock.settimeout(config['timeout']) if _ssl: context = ssl.create_default_context() # Allow unsecure ciphers like SSLv2 and SSLv3 context.options &= ~(ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) context.check_hostname = False context.verify_mode = ssl.CERT_NONE conn = context.wrap_socket(sock) conn.connect((host, port)) self.socket = conn self.server_tls_params = { 'cipher' : conn.cipher(), 'version': conn.version(), 'shared_ciphers': conn.shared_ciphers(), 'compression': conn.compression(), 'DER_peercert': conn.getpeercert(True), 'selected_alpn_protocol': conn.selected_alpn_protocol(), 'selected_npn_protocol': conn.selected_npn_protocol(), } x509 = crypto.load_certificate(crypto.FILETYPE_ASN1,self.server_tls_params['DER_peercert']) out = '' for elem in x509.get_subject().get_components(): out += f'\t{elem[0].decode()} = {elem[1].decode()}\n' Logger.dbg(out) self.results['SSL Certificate Subject components'] = out[1:-1] else: sock.connect((host, port)) self.socket = sock Logger.dbg("Succeeded.") self.reconnect = 0 return True except (socket.gaierror, socket.timeout, ConnectionResetError) as e: Logger.dbg(f"Failed.: {e}") return False @staticmethod def recvall(the_socket, timeout = 1.0): the_socket.setblocking(0) total_data = [] data = '' begin = time.time() if not timeout: timeout = 1 while 1: if total_data and time.time() - begin > timeout: break elif time.time() - begin > timeout * 2: break wait = 0 try: data = the_socket.recv(4096).decode() if data: total_data.append(data) begin = time.time() data = '' wait = 0 else: time.sleep(0.1) except: pass result = ''.join(total_data) return result def send(self, data, dontReconnect = False): Logger.dbg(f"================= [SEND] =================\n{data}\n") try: self.socket.send(data.encode()) except Exception as e: Logger.fail(f"Could not send data: {e}") if not self.reconnect < ExchangeRecon.MAX_RECONNECTS and not dontReconnect: self.reconnect += 1 Logger.dbg("Reconnecing...") if self.connect(self.hostname, self.port): return self.send(data, True) else: Logger.err("Could not reconnect with remote host. Failure.") sys.exit(-1) out = ExchangeRecon.recvall(self.socket, config['timeout']) if not out and self.reconnect < ExchangeRecon.MAX_RECONNECTS and not dontReconnect: Logger.dbg("No data returned. Reconnecting...") self.reconnect += 1 if self.connect(self.hostname, self.port): return self.send(data, True) else: Logger.err("Could not reconnect with remote host. Failure.") sys.exit(-1) Logger.dbg(f"================= [RECV] =================\n{out}\n") return out def http(self, method = 'GET', url = '/', host = None, httpver = 'HTTP/1.1', data = None, headers = None, followRedirect = False, redirect = 0 ): hdrs = ExchangeRecon.HEADERS.copy() if headers: hdrs.update(headers) if host: hdrs['Host'] = host headersstr = '' for k, v in hdrs.items(): headersstr += f'{k}: {v}\r\n' if data: data = f'\r\n{data}' else: data = '' packet = f'{method} {url} {httpver}\r\n{headersstr}{data}\r\n\r\n' raw = self.send(packet) resp = ExchangeRecon.response(raw) if resp['code'] in [301, 302, 303] and followRedirect: Logger.dbg(f'Following redirect. Depth: {redirect}...') location = urlparse(resp['headers']['location']) port = 80 if location.scheme == 'http' else 443 host = location.netloc if not host: host = self.hostname if ':' in location.netloc: port = int(location.netloc.split(':')[1]) host = location.netloc.split(':')[0] if self.connect(host, port): pos = resp['headers']['location'].find(location.path) return self.http( method = 'GET', url = resp['headers']['location'][pos:], host = host, data = '', headers = headers, followRedirect = redirect < ExchangeRecon.MAX_REDIRECTS, redirect = redirect + 1) return resp, raw @staticmethod def response(data): resp = { 'version' : '', 'code' : 0, 'message' : '', 'headers' : {}, 'data' : '' } num = 0 parsed = 0 for line in data.split('\r\n'): parsed += len(line) + 2 line = line.strip() if not line: break if num == 0: splitted = line.split(' ') resp['version'] = splitted[0] resp['code'] = int(splitted[1]) resp['message'] = ' '.join(splitted[2:]) num += 1 continue num += 1 pos = line.find(':') name = line[:pos] val = line[pos+1:].strip() if name in resp['headers'].keys(): if isinstance(resp['headers'][name], str): old = resp['headers'][name] resp['headers'][name] = [old] if val not in resp['headers'][name]: try: resp['headers'][name].append(int(val)) except ValueError: resp['headers'][name].append(val) else: try: resp['headers'][name] = int(val) except ValueError: resp['headers'][name] = val if parsed > 0 and parsed < len(data): resp['data'] = data[parsed:] if 'content-length' in resp['headers'].keys() and len(resp['data']) != resp['headers']['content-length']: Logger.fail(f"Received data is not of declared by server length ({len(resp['data'])} / {resp['headers']['content-length']})!") return resp def inspect(self, resp): global found_dns_domain if resp['code'] == 0: return for k, v in resp['headers'].items(): vals = [] if isinstance(v, str): vals.append(v) elif isinstance(v, int): vals.append(str(v)) else: vals.extend(v) lowervals = [x.lower() for x in vals] kl = k.lower() if kl == 'x-owa-version': ver = ExchangeRecon.parseVersion(v) if ver: self.results[ExchangeRecon.owaVersionInHttpHeader] += '\n\t({})'.format(str(ver)) elif kl == 'www-authenticate': realms = list(filter(lambda x: 'basic realm="' in x, lowervals)) if len(realms): Logger.dbg(f"Got basic realm.: {str(realms)}") m = re.search(r'([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})', realms[0]) if m: self.results[ExchangeRecon.leakedInternalIp] = m.group(1) negotiates = list(filter(lambda x: 'Negotiate ' in x, vals)) if len(negotiates): val = negotiates[0][len('Negotiate '):] Logger.dbg('NTLM Message hex dump:\n' + hexdump(base64.b64decode(val))) parsed = NtlmParser().parse(val) Logger.dbg(f"Parsed NTLM Message:\n{str(parsed)}") foo = '' for k2, v2 in parsed.items(): if isinstance(v2, str): try: foo += f'\t{k2}:\n\t\t{v2}\n' except: pass elif isinstance(v2, dict): foo += f'\t{k2}:\n' for k3, v3 in v2.items(): if k3 == 'DNS domain name': found_dns_domain = v3 try: foo += f"\t\t{k3: <18}:\t{v3}\n" except: pass elif isinstance(v2, list): try: foo += f'\t{k2}:\n\t\t- ' + '\n\t\t- '.join(v2) + '\n' except: pass self.results[ExchangeRecon.leakedInternalDomainNTLM] = foo[1:] if kl == 'server': self.results[ExchangeRecon.iisVersion] = vals[0] if kl == 'x-aspnet-version': self.results[ExchangeRecon.aspVersion] = vals[0] if kl not in ExchangeRecon.usualHeaders: l = f'{k}: {v}' if ExchangeRecon.unusualHeaders not in self.results.keys() or \ l not in self.results[ExchangeRecon.unusualHeaders]: Logger.info("Came across unusual HTTP header: " + l) if ExchangeRecon.unusualHeaders not in self.results: self.results[ExchangeRecon.unusualHeaders] = set() self.results[ExchangeRecon.unusualHeaders].add(l) for name, rex in ExchangeRecon.htmlregexes.items(): m = re.search(rex, resp['data']) if m: self.results[name] = m.group(1) if 'Outlook Web App version leaked' in name: ver = ExchangeRecon.parseVersion(m.group(1)) if ver: self.results[name] += '\n\t({})'.format(str(ver)) @staticmethod def parseVersion(lookup): # Try strict matching for ver in ExchangeRecon.exchangeVersions: if ver.version == lookup: return ver lookupparsed = packaging.version.parse(lookup) # Go with version-wise comparison to fuzzily find proper version name sortedversions = sorted(ExchangeRecon.exchangeVersions) for i in range(len(sortedversions)): if sortedversions[i].version.startswith(lookup): sortedversions[i].name = 'fuzzy match: ' + sortedversions[i].name return sortedversions[i] for i in range(len(sortedversions)): prevver = packaging.version.parse('0.0') nextver = packaging.version.parse('99999.0') if i > 0: prevver = packaging.version.parse(sortedversions[i-1].version) thisver = packaging.version.parse(sortedversions[i].version) if i + 1 < len(sortedversions): nextver = packaging.version.parse(sortedversions[i+1].version) if lookupparsed >= thisver and lookupparsed < nextver: sortedversions[i].name = 'fuzzy match: ' + sortedversions[i].name return sortedversions[i] return None def verifyExchange(self): # Fetching these paths as unauthorized must result in 401 verificationPaths = ( # (path, redirect, sendHostHeader /* HTTP/1.1 */) ('/owa', True, True), ('/autodiscover/autodiscover.xml', True, False), ('/Microsoft-Server-ActiveSync', True, False), ('/EWS/Exchange.asmx', True, False), ('/ecp/?ExchClientVer=15', False, False), ) definitiveMarks = ( '<title>Outlook Web App</title>', '<!-- OwaPage = ASP.auth_logon_aspx -->', 'Set-Cookie: exchangecookie=', 'Set-Cookie: OutlookSession=', '/owa/auth/logon.aspx?url=https://', '{57A118C6-2DA9-419d-BE9A-F92B0F9A418B}', 'To use Outlook Web App, browser settings must allow scripts to run. For ' +\ 'information about how to allow scripts' ) otherMarks = ( 'Location: /owa/', 'Microsoft-IIS/', 'Negotiate TlRM', 'WWW-Authenticate: Negotiate', 'ASP.NET' ) score = 0 definitive = False for path, redirect, sendHostHeader in verificationPaths: if not sendHostHeader: resp, raw = self.http(url = path, httpver = 'HTTP/1.0', followRedirect = redirect) else: r = requests.get(f'https://{self.hostname}{path}', verify = False, allow_redirects = True) resp = { 'version' : 'HTTP/1.1', 'code' : r.status_code, 'message' : r.reason, 'headers' : r.headers, 'data' : r.text } raw = r.text Logger.info(f"Got HTTP Code={resp['code']} on access to ({path})") if resp['code'] in [301, 302]: loc = f'https://{self.hostname}/owa/auth/logon.aspx?url=https://{self.hostname}/owa/&reason=0' if loc in raw: definitive = True score += 2 if resp['code'] == 401: score += 1 for mark in otherMarks: if mark in str(raw): score += 1 for mark in definitiveMarks: if mark in str(raw): score += 2 definitive = True self.inspect(resp) Logger.info(f"Exchange scored with: {score}. Definitively sure it's an Exchange? {definitive}") return score > 15 or definitive def tryToTriggerNtlmAuthentication(self): verificationPaths = ( '/autodiscover/autodiscover.xml', ) for path in verificationPaths: auth = { 'Authorization': 'Negotiate TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAGAbEdAAAADw==', 'X-Nego-Capability': 'Negotiate, Kerberos, NTLM', 'X-User-Identity': '<EMAIL>', 'Content-Length': '0', } resp, raw = self.http(method = 'POST', host = self.hostname, url = path, headers = auth) self.inspect(resp) def process(self): for port in ExchangeRecon.COMMON_PORTS: if self.connect(self.hostname, port): self.port = port Logger.ok(f"Connected with {self.hostname}:{port}\n") break if not self.port: Logger.err(f"Could not contact {self.hostname}. Failure.\n") return False print("[.] Probing for Exchange fingerprints...") if not self.verifyExchange(): Logger.err("Specified target hostname is not an Exchange server.") return False print("[.] Triggering NTLM authentication...") self.tryToTriggerNtlmAuthentication() print("[.] Probing support for legacy mail protocols and their capabilities...") self.legacyMailFingerprint() def legacyMailFingerprint(self): self.socket.close() self.socket = None for port in (25, 465, 587): try: Logger.dbg(f"Trying smtp on port {port}...") if self.smtpInteract(self.hostname, port, _ssl = False): break else: Logger.dbg(f"Trying smtp SSL on port {port}...") if self.smtpInteract(self.hostname, port, _ssl = True): break except Exception as e: Logger.dbg(f"Failed fetching SMTP replies: {e}") raise continue @staticmethod def _smtpconnect(host, port, _ssl): server = None try: if _ssl: server = smtplib.SMTP_SSL(host = host, port = port, local_hostname = 'smtp.gmail.com', timeout = config['timeout']) else: server = smtplib.SMTP(host = host, port = port, local_hostname = 'smtp.gmail.com', timeout = config['timeout']) if config['debug']: server.set_debuglevel(True) return server except Exception as e: Logger.dbg(f"Could not connect to SMTP server on SSL={_ssl} port={port}. Error: {e}") return None def smtpInteract(self, host, port, _ssl): server = ExchangeRecon._smtpconnect(host, port, _ssl) if not server: return None capabilities = [] with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((host, port)) banner = ExchangeRecon.recvall(sock) Logger.info(f"SMTP server returned following banner:\n\t{banner}") capabilities.append(banner.strip()) try: code, msg = server.ehlo() except Exception: server = ExchangeRecon._smtpconnect(host, port, _ssl) if not server: return None code, msg = server.ehlo() msg = msg.decode() for line in msg.split('\n'): capabilities.append(line.strip()) try: server.starttls() code, msg = server.ehlo() except Exception: server = ExchangeRecon._smtpconnect(host, port, _ssl) if not server: return None server.ehlo() server.starttls() code, msg = server.ehlo() msg = msg.decode() Logger.info(f"SMTP server banner & capabilities:\n-------\n{msg}\n-------\n") for line in msg.split('\n'): capabilities.append(line.strip()) try: msg = server.help() except Exception: server = ExchangeRecon._smtpconnect(host, port, _ssl) if not server: return None server.ehlo() try: server.starttls() server.ehlo() except: pass msg = server.help() msg = msg.decode() for line in msg.split('\n'): capabilities.append(line.strip()) skipThese = ( '8BITMIME', 'STARTTLS', 'PIPELINING', 'AUTH', 'CHUNKING', 'SIZE ', 'ENHANCEDSTATUSCODES', 'SMTPUTF8', 'DSN', 'BINARYMIME', 'HELP', 'QUIT', 'DATA', 'EHLO', 'HELO', #'GSSAPI', #'X-EXPS', #'X-ANONYMOUSTLS', 'This server supports the following commands' ) unfiltered = set() for line in capabilities: skip = False for n in skipThese: if n in line: skip = True break if not skip: unfiltered.add(line) if len(unfiltered): self.results[ExchangeRecon.legacyMailCapabilities] = \ '\t- ' + '\n\t- '.join(unfiltered) try: server.quit() except: pass self.verifyEnumerationOpportunities(host, port, _ssl) return True def verifyEnumerationOpportunities(self, host, port, _ssl): def _reconnect(host, port, _ssl): server = ExchangeRecon._smtpconnect(host, port, _ssl) server.ehlo() try: server.starttls() server.ehlo() except: pass return server Logger.info("Examining potential methods for SMTP user enumeration...") server = ExchangeRecon._smtpconnect(host, port, _ssl) if not server: return None ip = '[{}]'.format(socket.gethostbyname(self.hostname)) if found_dns_domain: ip = found_dns_domain techniques = { f'VRFY root' : None, f'EXPN root' : None, f'MAIL FROM:<test@{ip}>' : None, f'RCPT TO:<test@{ip}>' : None, } server = _reconnect(host, port, _ssl) likely = 0 for data in techniques.keys(): for i in range(3): try: code, msg = server.docmd(data) msg = msg.decode() techniques[data] = f'({code}, "{msg}")' Logger.dbg(f"Attempted user enumeration using: ({data}). Result: {techniques[data]}") if code >= 200 and code <= 299: Logger.ok(f"Method {data} may allow SMTP user enumeration.") likely += 1 else: Logger.fail(f"Method {data} is unlikely to allow SMTP user enumeration.") break except Exception as e: Logger.dbg(f"Exception occured during SMTP User enumeration attempt: {e}") server.quit() server = _reconnect(host, port, _ssl) continue out = '' for k, v in techniques.items(): code = eval(v)[0] c = '?' if code >= 200 and code <= 299: c = '+' if code >= 500 and code <= 599: c = '-' out += f'\n\t- [{c}] {k: <40} returned: {v}' self.results["Results for SMTP User Enumeration attempts"] = out[2:] def parseOptions(argv): global config print(''' :: Exchange Fingerprinter Tries to obtain internal IP address, Domain name and other clues by talking to Exchange <NAME>. / mgeeky '19, <<EMAIL>> v{} '''.format(VERSION)) parser = argparse.ArgumentParser(prog = argv[0], usage='%(prog)s [options] <hostname>') parser.add_argument('hostname', metavar='<domain|ip>', type=str, help='Hostname of the Exchange server (or IP address).') parser.add_argument('-v', '--verbose', action='store_true', help='Display verbose output.') parser.add_argument('-d', '--debug', action='store_true', help='Display debug output.') args = parser.parse_args() if not 'hostname' in args: Logger.err('You must specify a hostname to launch!') return False config['verbose'] = args.verbose config['debug'] = args.debug return args def output(hostname, out): print("\n======[ Leaked clues about internal environment ]======\n") print(f"\nHostname: {hostname}\n") for k, v in out.items(): if not v: continue if isinstance(v, str): print(f"*) {k}:\n\t{v.strip()}\n") elif isinstance(v, list) or isinstance(v, set): v2 = '\n\t- '.join(v) print(f"*) {k}:\n\t- {v2}\n") def main(argv): opts = parseOptions(argv) if not opts: Logger.err('Options parsing failed.') return False recon = ExchangeRecon(opts.hostname) try: t = threading.Thread(target = recon.process) t.setDaemon(True) t.start() while t.is_alive(): t.join(3.0) except KeyboardInterrupt: Logger.fail("Interrupted by user.") if len(recon.results) > 1: output(opts.hostname, recon.results) if __name__ == '__main__': main(sys.argv)
30,314
322
<gh_stars>100-1000 /* sftpclient.c * * Copyright (C) 2014-2020 wolfSSL Inc. * * This file is part of wolfSSH. * * wolfSSH 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. * * wolfSSH 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 wolfSSH. If not, see <http://www.gnu.org/licenses/>. */ #define WOLFSSH_TEST_CLIENT #include <wolfssh/ssh.h> #include <wolfssh/wolfsftp.h> #include <wolfssh/test.h> #include <wolfssh/port.h> #include <wolfssl/wolfcrypt/ecc.h> #include <wolfssl/wolfcrypt/coding.h> #include "examples/sftpclient/sftpclient.h" #ifndef USE_WINDOWS_API #include <termios.h> #endif #ifdef WOLFSSH_SFTP /* static so that signal handler can access and interrupt get/put */ static WOLFSSH* ssh = NULL; static char* workingDir; #define fin stdin #define fout stdout #define MAX_CMD_SZ 7 #define AUTOPILOT_OFF 0 #define AUTOPILOT_GET 1 #define AUTOPILOT_PUT 2 static void err_msg(const char* s) { printf("%s\n", s); } #ifndef WOLFSSH_NO_TIMESTAMP #include <sys/time.h> static char currentFile[WOLFSSH_MAX_FILENAME+1] = ""; static word32 startTime; #define TIMEOUT_VALUE 120 word32 current_time(int); /* return number of seconds*/ word32 current_time(int reset) { struct timeval tv; (void)reset; gettimeofday(&tv, 0); return (word32)tv.tv_sec; } #endif static void myStatusCb(WOLFSSH* sshIn, word32* bytes, char* name) { word32 currentTime; char buf[80]; word64 longBytes = ((word64)bytes[1] << 32) | bytes[0]; #ifndef WOLFSSH_NO_TIMESTAMP if (WSTRNCMP(currentFile, name, WSTRLEN(name)) != 0) { startTime = current_time(1); WMEMSET(currentFile, 0, WOLFSSH_MAX_FILENAME); WSTRNCPY(currentFile, name, WOLFSSH_MAX_FILENAME); } currentTime = current_time(0) - startTime; WSNPRINTF(buf, sizeof(buf), "Processed %8llu\t bytes in %d seconds\r", (unsigned long long)longBytes, currentTime); if (currentTime > TIMEOUT_VALUE) { WSNPRINTF(buf, sizeof(buf), "\nProcess timed out at %d seconds, " "stopping\r", currentTime); WMEMSET(currentFile, 0, WOLFSSH_MAX_FILENAME); wolfSSH_SFTP_Interrupt(ssh); } #else WSNPRINTF(buf, sizeof(buf), "Processed %8llu\t bytes \r", (unsigned long long)longBytes); (void)currentTime; #endif WFPUTS(buf, fout); (void)name; (void)sshIn; } static int NonBlockSSH_connect(void) { int ret; int error; SOCKET_T sockfd; int select_ret = 0; ret = wolfSSH_SFTP_connect(ssh); error = wolfSSH_get_error(ssh); sockfd = (SOCKET_T)wolfSSH_get_fd(ssh); while (ret != WS_SUCCESS && (error == WS_WANT_READ || error == WS_WANT_WRITE)) { if (error == WS_WANT_READ) printf("... client would read block\n"); else if (error == WS_WANT_WRITE) printf("... client would write block\n"); select_ret = tcp_select(sockfd, 1); if (select_ret == WS_SELECT_RECV_READY || select_ret == WS_SELECT_ERROR_READY || error == WS_WANT_WRITE) { ret = wolfSSH_SFTP_connect(ssh); error = wolfSSH_get_error(ssh); } else if (select_ret == WS_SELECT_TIMEOUT) error = WS_WANT_READ; else error = WS_FATAL_ERROR; } return ret; } #ifndef WS_NO_SIGNAL /* for command reget and reput to handle saving offset after interrupt during * get and put */ #include <signal.h> static byte interrupt = 0; static void sig_handler(const int sig) { (void)sig; interrupt = 1; wolfSSH_SFTP_Interrupt(ssh); } #endif /* WS_NO_SIGNAL */ /* cleans up absolute path */ static void clean_path(char* path) { int i; long sz = (long)WSTRLEN(path); byte found; /* remove any double '/' chars */ for (i = 0; i < sz; i++) { if (path[i] == '/' && path[i+1] == '/') { WMEMMOVE(path + i, path + i + 1, sz - i); sz -= 1; i--; } } /* remove any trailing '/' chars */ sz = (long)WSTRLEN(path); for (i = (int)sz - 1; i > 0; i--) { if (path[i] == '/') { path[i] = '\0'; } else { break; } } if (path != NULL) { /* go through path until no cases are found */ do { int prIdx = 0; /* begin of cut */ int enIdx = 0; /* end of cut */ sz = (long)WSTRLEN(path); found = 0; for (i = 0; i < sz; i++) { if (path[i] == '/') { int z; /* if next two chars are .. then delete */ if (path[i+1] == '.' && path[i+2] == '.') { enIdx = i + 3; /* start at one char before / and retrace path */ for (z = i - 1; z > 0; z--) { if (path[z] == '/') { prIdx = z; break; } } /* cut out .. and previous */ WMEMMOVE(path + prIdx, path + enIdx, sz - enIdx); path[sz - (enIdx - prIdx)] = '\0'; if (enIdx == sz) { path[prIdx] = '\0'; } /* case of at / */ if (WSTRLEN(path) == 0) { path[0] = '/'; path[1] = '\0'; } found = 1; break; } } } } while (found); } } #define WS_MAX_EXAMPLE_RW 1024 static int SetEcho(int on) { #ifndef USE_WINDOWS_API static int echoInit = 0; static struct termios originalTerm; if (!echoInit) { if (tcgetattr(STDIN_FILENO, &originalTerm) != 0) { printf("Couldn't get the original terminal settings.\n"); return -1; } echoInit = 1; } if (on) { if (tcsetattr(STDIN_FILENO, TCSANOW, &originalTerm) != 0) { printf("Couldn't restore the terminal settings.\n"); return -1; } } else { struct termios newTerm; memcpy(&newTerm, &originalTerm, sizeof(struct termios)); newTerm.c_lflag &= ~ECHO; newTerm.c_lflag |= (ICANON | ECHONL); if (tcsetattr(STDIN_FILENO, TCSANOW, &newTerm) != 0) { printf("Couldn't turn off echo.\n"); return -1; } } #else static int echoInit = 0; static DWORD originalTerm; HANDLE stdinHandle = GetStdHandle(STD_INPUT_HANDLE); if (!echoInit) { if (GetConsoleMode(stdinHandle, &originalTerm) == 0) { printf("Couldn't get the original terminal settings.\n"); return -1; } echoInit = 1; } if (on) { if (SetConsoleMode(stdinHandle, originalTerm) == 0) { printf("Couldn't restore the terminal settings.\n"); return -1; } } else { DWORD newTerm = originalTerm; newTerm &= ~ENABLE_ECHO_INPUT; if (SetConsoleMode(stdinHandle, newTerm) == 0) { printf("Couldn't turn off echo.\n"); return -1; } } #endif return 0; } static void ShowCommands(void) { printf("\n\nCommands :\n"); printf("\tcd <string> change directory\n"); printf("\tchmod <mode> <path> change mode\n"); printf("\tget <remote file> <local file> pulls file(s) from server\n"); printf("\tls list current directory\n"); printf("\tmkdir <dir name> creates new directory on server\n"); printf("\tput <local file> <remote file> push file(s) to server\n"); printf("\tpwd list current path\n"); printf("\tquit exit\n"); printf("\trename <old> <new> renames remote file\n"); printf("\treget <remote file> <local file> resume pulling file\n"); printf("\treput <remote file> <local file> resume pushing file\n"); printf("\t<crtl + c> interrupt get/put cmd\n"); } static void ShowUsage(void) { printf("client %s\n", LIBWOLFSSH_VERSION_STRING); printf(" -? display this help and exit\n"); printf(" -h <host> host to connect to, default %s\n", wolfSshIp); printf(" -p <num> port to connect on, default %d\n", wolfSshPort); printf(" -u <username> username to authenticate as (REQUIRED)\n"); printf(" -P <password> password for username, prompted if omitted\n"); printf(" -d <path> set the default local path\n"); printf(" -N use non blocking sockets\n"); printf(" -e use ECC user authentication\n"); /*printf(" -E use ECC server authentication\n");*/ printf(" -l <filename> local filename\n"); printf(" -r <filename> remote filename\n"); printf(" -g put local filename as remote filename\n"); printf(" -G get remote filename as local filename\n"); ShowCommands(); } static byte userPassword[256]; static byte userPublicKeyType[32]; static byte userPublicKey[512]; static word32 userPublicKeySz; static const byte* userPrivateKey; static word32 userPrivateKeySz; static const char hanselPublicRsa[] = "<KEY>" "<KEY>" "p2yEhUZUEkDhtOXyqjns1ickC9Gh4u80aSVtwHRnJZh9xPhSq5tLOhId4eP61s+a5pwjTj" "nEhBaIPUJO2C/M0pFnnbZxKgJlX7t1Doy7h5eXxviymOIvaCZKU+x5OopfzM/wFkey0EPW" "NmzI5y/+pzU5afsdeEWdiQDIQc80H6Pz8fsoFPvYSG+s4/wz0duu7yeeV1Ypoho65Zr+pE" "nIf7dO0B8EblgWt+ud+JI8wrAhfE4x"; static const byte hanselPrivateRsa[] = { 0x30, 0x82, 0x04, 0xa3, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0xbd, 0x3f, 0x76, 0x45, 0xa3, 0x03, 0xac, 0x38, 0xd5, 0xc7, 0x0f, 0x93, 0x30, 0x5a, 0x20, 0x9c, 0x89, 0x7c, 0xad, 0x05, 0x16, 0x46, 0x86, 0x83, 0x0d, 0x8a, 0x2b, 0x16, 0x4a, 0x05, 0x2c, 0xe4, 0x77, 0x47, 0x70, 0x00, 0xae, 0x1d, 0x83, 0xe2, 0xd9, 0x6e, 0x99, 0xd4, 0xf0, 0x45, 0x98, 0x15, 0x93, 0xf6, 0x87, 0x4e, 0xac, 0x64, 0x63, 0xa1, 0x95, 0xc9, 0x7c, 0x30, 0xe8, 0x3e, 0x2f, 0xa3, 0xf1, 0x24, 0x9f, 0x0c, 0x6b, 0x1c, 0xfe, 0x1b, 0x02, 0x99, 0xcd, 0xc6, 0xa7, 0x6c, 0x84, 0x85, 0x46, 0x54, 0x12, 0x40, 0xe1, 0xb4, 0xe5, 0xf2, 0xaa, 0x39, 0xec, 0xd6, 0x27, 0x24, 0x0b, 0xd1, 0xa1, 0xe2, 0xef, 0x34, 0x69, 0x25, 0x6d, 0xc0, 0x74, 0x67, 0x25, 0x98, 0x7d, 0xc4, 0xf8, 0x52, 0xab, 0x9b, 0x4b, 0x3a, 0x12, 0x1d, 0xe1, 0xe3, 0xfa, 0xd6, 0xcf, 0x9a, 0xe6, 0x9c, 0x23, 0x4e, 0x39, 0xc4, 0x84, 0x16, 0x88, 0x3d, 0x42, 0x4e, 0xd8, 0x2f, 0xcc, 0xd2, 0x91, 0x67, 0x9d, 0xb6, 0x71, 0x2a, 0x02, 0x65, 0x5f, 0xbb, 0x75, 0x0e, 0x8c, 0xbb, 0x87, 0x97, 0x97, 0xc6, 0xf8, 0xb2, 0x98, 0xe2, 0x2f, 0x68, 0x26, 0x4a, 0x53, 0xec, 0x79, 0x3a, 0x8a, 0x5f, 0xcc, 0xcf, 0xf0, 0x16, 0x47, 0xb2, 0xd0, 0x43, 0xd6, 0x36, 0x6c, 0xc8, 0xe7, 0x2f, 0xfe, 0xa7, 0x35, 0x39, 0x69, 0xfb, 0x1d, 0x78, 0x45, 0x9d, 0x89, 0x00, 0xc8, 0x41, 0xcf, 0x34, 0x1f, 0xa3, 0xf3, 0xf1, 0xfb, 0x28, 0x14, 0xfb, 0xd8, 0x48, 0x6f, 0xac, 0xe3, 0xfc, 0x33, 0xd1, 0xdb, 0xae, 0xef, 0x27, 0x9e, 0x57, 0x56, 0x29, 0xa2, 0x1a, 0x3a, 0xe5, 0x9a, 0xfe, 0xa4, 0x49, 0xc8, 0x7f, 0xb7, 0x4e, 0xd0, 0x1f, 0x04, 0x6e, 0x58, 0x16, 0xb7, 0xeb, 0x9d, 0xf8, 0x92, 0x3c, 0xc2, 0xb0, 0x21, 0x7c, 0x4e, 0x31, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, 0x01, 0x00, 0x8d, 0xa4, 0x61, 0x06, 0x2f, 0xc3, 0x40, 0xf4, 0x6c, 0xf4, 0x87, 0x30, 0xb8, 0x00, 0xcc, 0xe5, 0xbc, 0x75, 0x87, 0x1e, 0x06, 0x95, 0x14, 0x7a, 0x23, 0xf9, 0x24, 0xd4, 0x92, 0xe4, 0x1a, 0xbc, 0x88, 0x95, 0xfc, 0x3b, 0x56, 0x16, 0x1b, 0x2e, 0xff, 0x64, 0x2b, 0x58, 0xd7, 0xd8, 0x8e, 0xc2, 0x9f, 0xb2, 0xe5, 0x84, 0xb9, 0xbc, 0x8d, 0x61, 0x54, 0x35, 0xb0, 0x70, 0xfe, 0x72, 0x04, 0xc0, 0x24, 0x6d, 0x2f, 0x69, 0x61, 0x06, 0x1b, 0x1d, 0xe6, 0x2d, 0x6d, 0x79, 0x60, 0xb7, 0xf4, 0xdb, 0xb7, 0x4e, 0x97, 0x36, 0xde, 0x77, 0xc1, 0x9f, 0x85, 0x4e, 0xc3, 0x77, 0x69, 0x66, 0x2e, 0x3e, 0x61, 0x76, 0xf3, 0x67, 0xfb, 0xc6, 0x9a, 0xc5, 0x6f, 0x99, 0xff, 0xe6, 0x89, 0x43, 0x92, 0x44, 0x75, 0xd2, 0x4e, 0x54, 0x91, 0x58, 0xb2, 0x48, 0x2a, 0xe6, 0xfa, 0x0d, 0x4a, 0xca, 0xd4, 0x14, 0x9e, 0xf6, 0x27, 0x67, 0xb7, 0x25, 0x7a, 0x43, 0xbb, 0x2b, 0x67, 0xd1, 0xfe, 0xd1, 0x68, 0x23, 0x06, 0x30, 0x7c, 0xbf, 0x60, 0x49, 0xde, 0xcc, 0x7e, 0x26, 0x5a, 0x3b, 0xfe, 0xa6, 0xa6, 0xe7, 0xa8, 0xdd, 0xac, 0xb9, 0xaf, 0x82, 0x9a, 0x3a, 0x41, 0x7e, 0x61, 0x21, 0x37, 0xa3, 0x08, 0xe4, 0xc4, 0xbc, 0x11, 0xf5, 0x3b, 0x8e, 0x4d, 0x51, 0xf3, 0xbd, 0xda, 0xba, 0xb2, 0xc5, 0xee, 0xfb, 0xcf, 0xdf, 0x83, 0xa1, 0x82, 0x01, 0xe1, 0x51, 0x9d, 0x07, 0x5a, 0x5d, 0xd8, 0xc7, 0x5b, 0x3f, 0x97, 0x13, 0x6a, 0x4d, 0x1e, 0x8d, 0x39, 0xac, 0x40, 0x95, 0x82, 0x6c, 0xa2, 0xa1, 0xcc, 0x8a, 0x9b, 0x21, 0x32, 0x3a, 0x58, 0xcc, 0xe7, 0x2d, 0x1a, 0x79, 0xa4, 0x31, 0x50, 0xb1, 0x4b, 0x76, 0x23, 0x1b, 0xb3, 0x40, 0x3d, 0x3d, 0x72, 0x72, 0x32, 0xec, 0x5f, 0x38, 0xb5, 0x8d, 0xb2, 0x8d, 0x02, 0x81, 0x81, 0x00, 0xed, 0x5a, 0x7e, 0x8e, 0xa1, 0x62, 0x7d, 0x26, 0x5c, 0x78, 0xc4, 0x87, 0x71, 0xc9, 0x41, 0x57, 0x77, 0x94, 0x93, 0x93, 0x26, 0x78, 0xc8, 0xa3, 0x15, 0xbd, 0x59, 0xcb, 0x1b, 0xb4, 0xb2, 0x6b, 0x0f, 0xe7, 0x80, 0xf2, 0xfa, 0xfc, 0x8e, 0x32, 0xa9, 0x1b, 0x1e, 0x7f, 0xe1, 0x26, 0xef, 0x00, 0x25, 0xd8, 0xdd, 0xc9, 0x1a, 0x23, 0x00, 0x26, 0x3b, 0x46, 0x23, 0xc0, 0x50, 0xe7, 0xce, 0x62, 0xb2, 0x36, 0xb2, 0x98, 0x09, 0x16, 0x34, 0x18, 0x9e, 0x46, 0xbc, 0xaf, 0x2c, 0x28, 0x94, 0x2f, 0xe0, 0x5d, 0xc9, 0xb2, 0xc8, 0xfb, 0x5d, 0x13, 0xd5, 0x36, 0xaa, 0x15, 0x0f, 0x89, 0xa5, 0x16, 0x59, 0x5d, 0x22, 0x74, 0xa4, 0x47, 0x5d, 0xfa, 0xfb, 0x0c, 0x5e, 0x80, 0xbf, 0x0f, 0xc2, 0x9c, 0x95, 0x0f, 0xe7, 0xaa, 0x7f, 0x16, 0x1b, 0xd4, 0xdb, 0x38, 0x7d, 0x58, 0x2e, 0x57, 0x78, 0x2f, 0x02, 0x81, 0x81, 0x00, 0xcc, 0x1d, 0x7f, 0x74, 0x36, 0x6d, 0xb4, 0x92, 0x25, 0x62, 0xc5, 0x50, 0xb0, 0x5c, 0xa1, 0xda, 0xf3, 0xb2, 0xfd, 0x1e, 0x98, 0x0d, 0x8b, 0x05, 0x69, 0x60, 0x8e, 0x5e, 0xd2, 0x89, 0x90, 0x4a, 0x0d, 0x46, 0x7e, 0xe2, 0x54, 0x69, 0xae, 0x16, 0xe6, 0xcb, 0xd5, 0xbd, 0x7b, 0x30, 0x2b, 0x7b, 0x5c, 0xee, 0x93, 0x12, 0xcf, 0x63, 0x89, 0x9c, 0x3d, 0xc8, 0x2d, 0xe4, 0x7a, 0x61, 0x09, 0x5e, 0x80, 0xfb, 0x3c, 0x03, 0xb3, 0x73, 0xd6, 0x98, 0xd0, 0x84, 0x0c, 0x59, 0x9f, 0x4e, 0x80, 0xf3, 0x46, 0xed, 0x03, 0x9d, 0xd5, 0xdc, 0x8b, 0xe7, 0xb1, 0xe8, 0xaa, 0x57, 0xdc, 0xd1, 0x41, 0x55, 0x07, 0xc7, 0xdf, 0x67, 0x3c, 0x72, 0x78, 0xb0, 0x60, 0x8f, 0x85, 0xa1, 0x90, 0x99, 0x0c, 0xa5, 0x67, 0xab, 0xf0, 0xb6, 0x74, 0x90, 0x03, 0x55, 0x7b, 0x5e, 0xcc, 0xc5, 0xbf, 0xde, 0xa7, 0x9f, 0x02, 0x81, 0x80, 0x40, 0x81, 0x6e, 0x91, 0xae, 0xd4, 0x88, 0x74, 0xab, 0x7e, 0xfa, 0xd2, 0x60, 0x9f, 0x34, 0x8d, 0xe3, 0xe6, 0xd2, 0x30, 0x94, 0xad, 0x10, 0xc2, 0x19, 0xbf, 0x6b, 0x2e, 0xe2, 0xe9, 0xb9, 0xef, 0x94, 0xd3, 0xf2, 0xdc, 0x96, 0x4f, 0x9b, 0x09, 0xb3, 0xa1, 0xb6, 0x29, 0x44, 0xf4, 0x82, 0xd1, 0xc4, 0x77, 0x6a, 0xd7, 0x23, 0xae, 0x4d, 0x75, 0x16, 0x78, 0xda, 0x70, 0x82, 0xcc, 0x6c, 0xef, 0xaf, 0xc5, 0x63, 0xc6, 0x23, 0xfa, 0x0f, 0xd0, 0x7c, 0xfb, 0x76, 0x7e, 0x18, 0xff, 0x32, 0x3e, 0xcc, 0xb8, 0x50, 0x7f, 0xb1, 0x55, 0x77, 0x17, 0x53, 0xc3, 0xd6, 0x77, 0x80, 0xd0, 0x84, 0xb8, 0x4d, 0x33, 0x1d, 0x91, 0x1b, 0xb0, 0x75, 0x9f, 0x27, 0x29, 0x56, 0x69, 0xa1, 0x03, 0x54, 0x7d, 0x9f, 0x99, 0x41, 0xf9, 0xb9, 0x2e, 0x36, 0x04, 0x24, 0x4b, 0xf6, 0xec, 0xc7, 0x33, 0x68, 0x6b, 0x02, 0x81, 0x80, 0x60, 0x35, 0xcb, 0x3c, 0xd0, 0xe6, 0xf7, 0x05, 0x28, 0x20, 0x1d, 0x57, 0x82, 0x39, 0xb7, 0x85, 0x07, 0xf7, 0xa7, 0x3d, 0xc3, 0x78, 0x26, 0xbe, 0x3f, 0x44, 0x66, 0xf7, 0x25, 0x0f, 0xf8, 0x76, 0x1f, 0x39, 0xca, 0x57, 0x0e, 0x68, 0xdd, 0xc9, 0x27, 0xb2, 0x8e, 0xa6, 0x08, 0xa9, 0xd4, 0xe5, 0x0a, 0x11, 0xde, 0x3b, 0x30, 0x8b, 0xff, 0x72, 0x28, 0xe0, 0xf1, 0x58, 0xcf, 0xa2, 0x6b, 0x93, 0x23, 0x02, 0xc8, 0xf0, 0x09, 0xa7, 0x21, 0x50, 0xd8, 0x80, 0x55, 0x7d, 0xed, 0x0c, 0x48, 0xd5, 0xe2, 0xe9, 0x97, 0x19, 0xcf, 0x93, 0x6c, 0x52, 0xa2, 0xd6, 0x43, 0x6c, 0xb4, 0xc5, 0xe1, 0xa0, 0x9d, 0xd1, 0x45, 0x69, 0x58, 0xe1, 0xb0, 0x27, 0x9a, 0xec, 0x2b, 0x95, 0xd3, 0x1d, 0x81, 0x0b, 0x7a, 0x09, 0x5e, 0xa5, 0xf1, 0xdd, 0x6b, 0xe4, 0xe0, 0x08, 0xf8, 0x46, 0x81, 0xc1, 0x06, 0x8b, 0x02, 0x81, 0x80, 0x00, 0xf6, 0xf2, 0xeb, 0x25, 0xba, 0x78, 0x04, 0xad, 0x0e, 0x0d, 0x2e, 0xa7, 0x69, 0xd6, 0x57, 0xe6, 0x36, 0x32, 0x50, 0xd2, 0xf2, 0xeb, 0xad, 0x31, 0x46, 0x65, 0xc0, 0x07, 0x97, 0x83, 0x6c, 0x66, 0x27, 0x3e, 0x94, 0x2c, 0x05, 0x01, 0x5f, 0x5c, 0xe0, 0x31, 0x30, 0xec, 0x61, 0xd2, 0x74, 0x35, 0xb7, 0x9f, 0x38, 0xe7, 0x8e, 0x67, 0xb1, 0x50, 0x08, 0x68, 0xce, 0xcf, 0xd8, 0xee, 0x88, 0xfd, 0x5d, 0xc4, 0xcd, 0xe2, 0x86, 0x3d, 0x4a, 0x0e, 0x04, 0x7f, 0xee, 0x8a, 0xe8, 0x9b, 0x16, 0xa1, 0xfc, 0x09, 0x82, 0xe2, 0x62, 0x03, 0x3c, 0xe8, 0x25, 0x7f, 0x3c, 0x9a, 0xaa, 0x83, 0xf8, 0xd8, 0x93, 0xd1, 0x54, 0xf9, 0xce, 0xb4, 0xfa, 0x35, 0x36, 0xcc, 0x18, 0x54, 0xaa, 0xf2, 0x90, 0xb7, 0x7c, 0x97, 0x0b, 0x27, 0x2f, 0xae, 0xfc, 0xc3, 0x93, 0xaf, 0x1a, 0x75, 0xec, 0x18, 0xdb }; static const unsigned int hanselPrivateRsaSz = 1191; static const char hanselPublicEcc[] = "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNkI5JTP6D0lF42tbx" "X19cE87hztUS6FSDoGvPfiU0CgeNSbI+aFdKIzTP5CQEJSvm25qUzgDtH7oyaQROUnNvk="; static const byte hanselPrivateEcc[] = { 0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0x03, 0x6e, 0x17, 0xd3, 0xb9, 0xb8, 0xab, 0xc8, 0xf9, 0x1f, 0xf1, 0x2d, 0x44, 0x4c, 0x3b, 0x12, 0xb1, 0xa4, 0x77, 0xd8, 0xed, 0x0e, 0x6a, 0xbe, 0x60, 0xc2, 0xf6, 0x8b, 0xe7, 0xd3, 0x87, 0x83, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xd9, 0x08, 0xe4, 0x94, 0xcf, 0xe8, 0x3d, 0x25, 0x17, 0x8d, 0xad, 0x6f, 0x15, 0xf5, 0xf5, 0xc1, 0x3c, 0xee, 0x1c, 0xed, 0x51, 0x2e, 0x85, 0x48, 0x3a, 0x06, 0xbc, 0xf7, 0xe2, 0x53, 0x40, 0xa0, 0x78, 0xd4, 0x9b, 0x23, 0xe6, 0x85, 0x74, 0xa2, 0x33, 0x4c, 0xfe, 0x42, 0x40, 0x42, 0x52, 0xbe, 0x6d, 0xb9, 0xa9, 0x4c, 0xe0, 0x0e, 0xd1, 0xfb, 0xa3, 0x26, 0x90, 0x44, 0xe5, 0x27, 0x36, 0xf9 }; static const unsigned int hanselPrivateEccSz = 121; static int wsUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) { int ret = WOLFSSH_USERAUTH_INVALID_AUTHTYPE; #ifdef DEBUG_WOLFSSH /* inspect supported types from server */ printf("Server supports "); if (authData->type & WOLFSSH_USERAUTH_PASSWORD) { printf("password authentication"); } if (authData->type & WOLFSSH_USERAUTH_PUBLICKEY) { printf(" and public key authentication"); } printf("\n"); printf("wolfSSH requesting to use type %d\n", authType); #endif /* We know hansel has a key, wait for request of public key */ if (authData->type & WOLFSSH_USERAUTH_PUBLICKEY && authData->username != NULL && authData->usernameSz > 0 && XSTRNCMP((char*)authData->username, "hansel", authData->usernameSz) == 0) { if (authType == WOLFSSH_USERAUTH_PASSWORD) { printf("rejecting password type with hansel in favor of pub key\n"); return WOLFSSH_USERAUTH_FAILURE; } } if (authType == WOLFSSH_USERAUTH_PASSWORD) { const char* defaultPassword = (const char*)ctx; word32 passwordSz; ret = WOLFSSH_USERAUTH_SUCCESS; if (defaultPassword != NULL) { passwordSz = (word32)strlen(defaultPassword); memcpy(userPassword, defaultPassword, passwordSz); } else { printf("Password: "); fflush(stdout); SetEcho(0); if (WFGETS((char*)userPassword, sizeof(userPassword), stdin) == NULL) { printf("Getting password failed.\n"); ret = WOLFSSH_USERAUTH_FAILURE; } else { char* c = strpbrk((char*)userPassword, "\r\n"); if (c != NULL) *c = '\0'; } passwordSz = (word32)strlen((const char*)userPassword); SetEcho(1); #ifdef USE_WINDOWS_API printf("\r\n"); #endif } if (ret == WOLFSSH_USERAUTH_SUCCESS) { authData->sf.password.password = <PASSWORD>; authData->sf.password.passwordSz = <PASSWORD>; } } else if (authType == WOLFSSH_USERAUTH_PUBLICKEY) { WS_UserAuthData_PublicKey* pk = &authData->sf.publicKey; /* we only have hansel's key loaded */ if (authData->username != NULL && authData->usernameSz > 0 && XSTRNCMP((char*)authData->username, "hansel", authData->usernameSz) == 0) { pk->publicKeyType = userPublicKeyType; pk->publicKeyTypeSz = (word32)WSTRLEN((char*)userPublicKeyType); pk->publicKey = userPublicKey; pk->publicKeySz = userPublicKeySz; pk->privateKey = userPrivateKey; pk->privateKeySz = userPrivateKeySz; ret = WOLFSSH_USERAUTH_SUCCESS; } } return ret; } static int wsPublicKeyCheck(const byte* pubKey, word32 pubKeySz, void* ctx) { #ifdef DEBUG_WOLFSSH printf("Sample public key check callback\n" " public key = %p\n" " public key size = %u\n" " ctx = %s\n", pubKey, pubKeySz, (const char*)ctx); #else (void)pubKey; (void)pubKeySz; (void)ctx; #endif return 0; } /* returns 0 on success */ static INLINE int SFTP_FPUTS(func_args* args, const char* msg) { int ret; if (args && args->sftp_cb) ret = args->sftp_cb(msg, NULL, 0); else ret = WFPUTS(msg, fout); return ret; } /* returns pointer on success, NULL on failure */ static INLINE char* SFTP_FGETS(func_args* args, char* msg, int msgSz) { char* ret = NULL; WMEMSET(msg, 0, msgSz); if (args && args->sftp_cb) { if (args->sftp_cb(NULL, msg, msgSz) == 0) ret = msg; } else ret = WFGETS(msg, msgSz, fin); return ret; } /* main loop for handling commands */ static int doCmds(func_args* args) { byte quit = 0; int ret = WS_SUCCESS, err; byte resume = 0; int i; do { char msg[WOLFSSH_MAX_FILENAME * 2]; char* pt; if (wolfSSH_get_error(ssh) == WS_SOCKET_ERROR_E) { if (SFTP_FPUTS(args, "peer disconnected\n") < 0) { err_msg("fputs error"); return -1; } return WS_SOCKET_ERROR_E; } if (SFTP_FPUTS(args, "wolfSSH sftp> ") < 0) { err_msg("fputs error"); return -1; } fflush(stdout); WMEMSET(msg, 0, sizeof(msg)); if (SFTP_FGETS(args, msg, sizeof(msg) - 1) == NULL) { err_msg("fgets error"); return -1; } msg[WOLFSSH_MAX_FILENAME * 2 - 1] = '\0'; if ((pt = WSTRNSTR(msg, "mkdir", sizeof(msg))) != NULL) { WS_SFTP_FILEATRB atrb; int sz; char* f = NULL; pt += sizeof("mkdir"); sz = (int)WSTRLEN(pt); if (pt[sz - 1] == '\n') pt[sz - 1] = '\0'; if (pt[0] != '/') { int maxSz = (int)WSTRLEN(workingDir) + sz + 2; f = (char*)WMALLOC(maxSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (f == NULL) return WS_MEMORY_E; f[0] = '\0'; WSTRNCAT(f, workingDir, maxSz); WSTRNCAT(f, "/", maxSz); WSTRNCAT(f, pt, maxSz); pt = f; } do { err = WS_SUCCESS; if ((ret = wolfSSH_SFTP_MKDIR(ssh, pt, &atrb)) != WS_SUCCESS) { err = wolfSSH_get_error(ssh); if (ret == WS_PERMISSIONS) { if (SFTP_FPUTS(args, "Insufficient permissions\n") < 0) { err_msg("fputs error"); return -1; } } else if (err != WS_WANT_READ && err != WS_WANT_WRITE) { if (SFTP_FPUTS(args, "Error writing directory\n") < 0) { err_msg("fputs error"); return -1; } } } } while ((err == WS_WANT_READ || err == WS_WANT_WRITE) && ret != WS_SUCCESS); WFREE(f, NULL, DYNAMIC_TYPE_TMP_BUFFER); continue; } if ((pt = WSTRNSTR(msg, "reget", MAX_CMD_SZ)) != NULL) { resume = 1; } if ((pt = WSTRNSTR(msg, "get", MAX_CMD_SZ)) != NULL) { int sz; char* f = NULL; char* to = NULL; pt += sizeof("get"); sz = (int)WSTRLEN(pt); if (pt[sz - 1] == '\n') pt[sz - 1] = '\0'; /* search for space delimiter */ to = pt; for (i = 0; i < sz; i++) { to++; if (pt[i] == ' ') { pt[i] = '\0'; break; } } /* check if local file path listed */ if (WSTRLEN(to) <= 0) { to = pt; /* if local path not listed follow path till at the tail */ for (i = 0; i < sz; i++) { if (pt[i] == '/') { to = pt + i + 1; } } } if (pt[0] != '/') { int maxSz = (int)(WSTRLEN(workingDir) + sz + 2); f = (char*)WMALLOC(maxSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (f == NULL) { err_msg("Error malloc'ing"); return -1; } f[0] = '\0'; WSTRNCAT(f, workingDir, maxSz); if (WSTRLEN(workingDir) > 1) { WSTRNCAT(f, "/", maxSz); } WSTRNCAT(f, pt, maxSz); pt = f; } { char buf[WOLFSSH_MAX_FILENAME * 3]; if (resume) { WSNPRINTF(buf, sizeof(buf), "resuming %s to %s\n", pt, to); } else { WSNPRINTF(buf, sizeof(buf), "fetching %s to %s\n", pt, to); } if (SFTP_FPUTS(args, buf) < 0) { err_msg("fputs error"); return -1; } } do { ret = wolfSSH_SFTP_Get(ssh, pt, to, resume, &myStatusCb); if (ret != WS_SUCCESS) { ret = wolfSSH_get_error(ssh); } } while (ret == WS_WANT_READ || ret == WS_WANT_WRITE); if (ret != WS_SUCCESS) { if (SFTP_FPUTS(args, "Error getting file\n") < 0) { err_msg("fputs error"); return -1; } } else { if (SFTP_FPUTS(args, "\n") < 0) { /* new line after status output */ err_msg("fputs error"); return -1; } } resume = 0; WFREE(f, NULL, DYNAMIC_TYPE_TMP_BUFFER); continue; } if ((pt = WSTRNSTR(msg, "reput", MAX_CMD_SZ)) != NULL) { resume = 1; } if ((pt = WSTRNSTR(msg, "put", MAX_CMD_SZ)) != NULL) { int sz; char* f = NULL; char* to = NULL; pt += sizeof("put"); sz = (int)WSTRLEN(pt); if (pt[sz - 1] == '\n') pt[sz - 1] = '\0'; to = pt; for (i = 0; i < sz; i++) { to++; if (pt[i] == ' ') { pt[i] = '\0'; break; } } /* check if local file path listed */ if (WSTRLEN(to) <= 0) { to = pt; /* if local path not listed follow path till at the tail */ for (i = 0; i < sz; i++) { if (pt[i] == '/') { to = pt + i + 1; } } } if (to[0] != '/') { int maxSz = (int)WSTRLEN(workingDir) + sz + 2; f = (char*)WMALLOC(maxSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (f == NULL) { err_msg("Error malloc'ing"); return -1; } f[0] = '\0'; WSTRNCAT(f, workingDir, maxSz); if (WSTRLEN(workingDir) > 1) { WSTRNCAT(f, "/", maxSz); } WSTRNCAT(f, to, maxSz); to = f; } { char buf[WOLFSSH_MAX_FILENAME * 3]; if (resume) { WSNPRINTF(buf, sizeof(buf), "resuming %s to %s\n", pt, to); } else { WSNPRINTF(buf, sizeof(buf), "pushing %s to %s\n", pt, to); } if (SFTP_FPUTS(args, buf) < 0) { err_msg("fputs error"); return -1; } } do { ret = wolfSSH_SFTP_Put(ssh, pt, to, resume, &myStatusCb); err = wolfSSH_get_error(ssh); } while ((err == WS_WANT_READ || err == WS_WANT_WRITE) && ret != WS_SUCCESS); if (ret != WS_SUCCESS) { if (SFTP_FPUTS(args, "Error pushing file\n") < 0) { err_msg("fputs error"); return -1; } } else { if (SFTP_FPUTS(args, "\n") < 0) { /* new line after status output */ err_msg("fputs error"); return -1; } } resume = 0; WFREE(f, NULL, DYNAMIC_TYPE_TMP_BUFFER); continue; } if ((pt = WSTRNSTR(msg, "cd", MAX_CMD_SZ)) != NULL) { WS_SFTP_FILEATRB atrb; int sz; char* f = NULL; pt += sizeof("cd"); sz = (int)WSTRLEN(pt); if (pt[sz - 1] == '\n') pt[sz - 1] = '\0'; if (pt[0] != '/') { int maxSz = (int)WSTRLEN(workingDir) + sz + 2; f = (char*)WMALLOC(maxSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (f == NULL) { err_msg("Error malloc'ing"); return -1; } f[0] = '\0'; WSTRNCAT(f, workingDir, maxSz); if (WSTRLEN(workingDir) > 1) { WSTRNCAT(f, "/", maxSz); } WSTRNCAT(f, pt, maxSz); pt = f; } /* check directory is valid */ do { ret = wolfSSH_SFTP_STAT(ssh, pt, &atrb); err = wolfSSH_get_error(ssh); } while ((err == WS_WANT_READ || err == WS_WANT_WRITE) && ret != WS_SUCCESS); if (ret != WS_SUCCESS) { if (SFTP_FPUTS(args, "Error changing directory\n") < 0) { err_msg("fputs error"); return -1; } } if (ret == WS_SUCCESS) { sz = (int)WSTRLEN(pt); WFREE(workingDir, NULL, DYNAMIC_TYPE_TMP_BUFFER); workingDir = (char*)WMALLOC(sz + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (workingDir == NULL) { err_msg("Error malloc'ing"); return -1; } WMEMCPY(workingDir, pt, sz); workingDir[sz] = '\0'; clean_path(workingDir); } WFREE(f, NULL, DYNAMIC_TYPE_TMP_BUFFER); continue; } if ((pt = WSTRNSTR(msg, "chmod", MAX_CMD_SZ)) != NULL) { int sz; char* f = NULL; char mode[WOLFSSH_MAX_OCTET_LEN]; pt += sizeof("chmod"); sz = (int)WSTRLEN(pt); if (pt[sz - 1] == '\n') pt[sz - 1] = '\0'; /* advance pointer to first location of non space character */ for (i = 0; i < sz && pt[0] == ' '; i++, pt++); sz = (int)WSTRLEN(pt); /* get mode */ sz = (sz < WOLFSSH_MAX_OCTET_LEN - 1)? sz : WOLFSSH_MAX_OCTET_LEN -1; WMEMCPY(mode, pt, sz); mode[WOLFSSH_MAX_OCTET_LEN - 1] = '\0'; for (i = 0; i < sz; i++) { if (mode[i] == ' ') { mode[i] = '\0'; break; } } if (i == 0) { printf("error with getting mode\r\n"); continue; } pt += (int)WSTRLEN(mode); sz = (int)WSTRLEN(pt); for (i = 0; i < sz && pt[0] == ' '; i++, pt++); if (pt[0] != '/') { int maxSz = (int)WSTRLEN(workingDir) + sz + 2; f = (char*)WMALLOC(maxSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (f == NULL) { err_msg("Error malloc'ing"); return -1; } f[0] = '\0'; WSTRNCAT(f, workingDir, maxSz); if (WSTRLEN(workingDir) > 1) { WSTRNCAT(f, "/", maxSz); } WSTRNCAT(f, pt, maxSz); pt = f; } /* update permissions */ do { ret = wolfSSH_SFTP_CHMOD(ssh, pt, mode); err = wolfSSH_get_error(ssh); } while ((err == WS_WANT_READ || err == WS_WANT_WRITE) && ret != WS_SUCCESS); if (ret != WS_SUCCESS) { if (SFTP_FPUTS(args, "Unable to change permissions of ") < 0) { err_msg("fputs error"); return -1; } if (SFTP_FPUTS(args, pt) < 0) { err_msg("fputs error"); return -1; } if (SFTP_FPUTS(args, "\n") < 0) { err_msg("fputs error"); return -1; } } WFREE(f, NULL, DYNAMIC_TYPE_TMP_BUFFER); continue; } if ((pt = WSTRNSTR(msg, "rmdir", MAX_CMD_SZ)) != NULL) { int sz; char* f = NULL; pt += sizeof("rmdir"); sz = (int)WSTRLEN(pt); if (pt[sz - 1] == '\n') pt[sz - 1] = '\0'; if (pt[0] != '/') { int maxSz = (int)WSTRLEN(workingDir) + sz + 2; f = (char*)WMALLOC(maxSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (f == NULL) { err_msg("Error malloc'ing"); return -1; } f[0] = '\0'; WSTRNCAT(f, workingDir, maxSz); if (WSTRLEN(workingDir) > 1) { WSTRNCAT(f, "/", maxSz); } WSTRNCAT(f, pt, maxSz); pt = f; } do { ret = wolfSSH_SFTP_RMDIR(ssh, pt); err = wolfSSH_get_error(ssh); } while ((err == WS_WANT_READ || err == WS_WANT_WRITE) && ret != WS_SUCCESS); if (ret != WS_SUCCESS) { if (ret == WS_PERMISSIONS) { if (SFTP_FPUTS(args, "Insufficient permissions\n") < 0) { err_msg("fputs error"); return -1; } } else { if (SFTP_FPUTS(args, "Error writing directory\n") < 0) { err_msg("fputs error"); return -1; } } } WFREE(f, NULL, DYNAMIC_TYPE_TMP_BUFFER); continue; } if ((pt = WSTRNSTR(msg, "rm", MAX_CMD_SZ)) != NULL) { int sz; char* f = NULL; pt += sizeof("rm"); sz = (int)WSTRLEN(pt); if (pt[sz - 1] == '\n') pt[sz - 1] = '\0'; if (pt[0] != '/') { int maxSz = (int)WSTRLEN(workingDir) + sz + 2; f = (char*)WMALLOC(maxSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); f[0] = '\0'; WSTRNCAT(f, workingDir, maxSz); if (WSTRLEN(workingDir) > 1) { WSTRNCAT(f, "/", maxSz); } WSTRNCAT(f, pt, maxSz); pt = f; } do { ret = wolfSSH_SFTP_Remove(ssh, pt); err = wolfSSH_get_error(ssh); } while ((err == WS_WANT_READ || err == WS_WANT_WRITE) && ret != WS_SUCCESS); if (ret != WS_SUCCESS) { if (ret == WS_PERMISSIONS) { if (SFTP_FPUTS(args, "Insufficient permissions\n") < 0) { err_msg("fputs error"); return -1; } } else { if (SFTP_FPUTS(args, "Error writing directory\n") < 0) { err_msg("fputs error"); return -1; } } } WFREE(f, NULL, DYNAMIC_TYPE_TMP_BUFFER); continue; } if ((pt = WSTRNSTR(msg, "rename", MAX_CMD_SZ)) != NULL) { int sz; char* f = NULL; char* fTo = NULL; char* to; int toSz; pt += sizeof("rename"); sz = (int)WSTRLEN(pt); if (pt[sz - 1] == '\n') pt[sz - 1] = '\0'; /* search for space delimiter */ to = pt; for (i = 0; i < sz; i++) { to++; if (pt[i] == ' ') { pt[i] = '\0'; break; } } if ((toSz = (int)WSTRLEN(to)) <= 0 || i == sz) { printf("bad usage, expected <old> <new> input\n"); continue; } sz = (int)WSTRLEN(pt); if (pt[0] != '/') { int maxSz = (int)WSTRLEN(workingDir) + sz + 2; f = (char*)WMALLOC(maxSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (f == NULL) { err_msg("Error malloc'ing"); return -1; } f[0] = '\0'; WSTRNCAT(f, workingDir, maxSz); if (WSTRLEN(workingDir) > 1) { WSTRNCAT(f, "/", maxSz); } WSTRNCAT(f, pt, maxSz); pt = f; } if (to[0] != '/') { int maxSz = (int)WSTRLEN(workingDir) + toSz + 2; fTo = (char*)WMALLOC(maxSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); fTo[0] = '\0'; WSTRNCAT(fTo, workingDir, maxSz); if (WSTRLEN(workingDir) > 1) { WSTRNCAT(fTo, "/", maxSz); } WSTRNCAT(fTo, to, maxSz); to = fTo; } do { ret = wolfSSH_SFTP_Rename(ssh, pt, to); err = wolfSSH_get_error(ssh); } while ((err == WS_WANT_READ || err == WS_WANT_WRITE) && ret != WS_SUCCESS); if (ret != WS_SUCCESS) { if (SFTP_FPUTS(args, "Error with rename\n") < 0) { err_msg("fputs error"); return -1; } } WFREE(f, NULL, DYNAMIC_TYPE_TMP_BUFFER); WFREE(fTo, NULL, DYNAMIC_TYPE_TMP_BUFFER); continue; } if ((pt = WSTRNSTR(msg, "ls", MAX_CMD_SZ)) != NULL) { WS_SFTPNAME* tmp; WS_SFTPNAME* current; do { current = wolfSSH_SFTP_LS(ssh, workingDir); err = wolfSSH_get_error(ssh); } while ((err == WS_WANT_READ || err == WS_WANT_WRITE) && current == NULL && err != WS_SUCCESS); tmp = current; while (tmp != NULL) { if (SFTP_FPUTS(args, tmp->fName) < 0) { err_msg("fputs error"); return -1; } if (SFTP_FPUTS(args, "\n") < 0) { err_msg("fputs error"); return -1; } tmp = tmp->next; } wolfSSH_SFTPNAME_list_free(current); continue; } /* display current working directory */ if ((pt = WSTRNSTR(msg, "pwd", MAX_CMD_SZ)) != NULL) { if (SFTP_FPUTS(args, workingDir) < 0 || SFTP_FPUTS(args, "\n") < 0) { err_msg("fputs error"); return -1; } continue; } if (WSTRNSTR(msg, "help", MAX_CMD_SZ) != NULL) { ShowCommands(); continue; } if (WSTRNSTR(msg, "quit", MAX_CMD_SZ) != NULL) { quit = 1; continue; } if (WSTRNSTR(msg, "exit", MAX_CMD_SZ) != NULL) { quit = 1; continue; } SFTP_FPUTS(args, "Unknown command\n"); } while (!quit); return WS_SUCCESS; } /* alternate main loop for the autopilot get/receive */ static int doAutopilot(int cmd, char* local, char* remote) { int err; int ret = WS_SUCCESS; char fullpath[128] = "."; WS_SFTPNAME* name; do { name = wolfSSH_SFTP_RealPath(ssh, fullpath); err = wolfSSH_get_error(ssh); } while ((err == WS_WANT_READ || err == WS_WANT_WRITE) && ret != WS_SUCCESS); snprintf(fullpath, sizeof(fullpath), "%s/%s", name == NULL ? "." : name->fName, remote); do { if (cmd == AUTOPILOT_PUT) { ret = wolfSSH_SFTP_Put(ssh, local, fullpath, 0, NULL); } else if (cmd == AUTOPILOT_GET) { ret = wolfSSH_SFTP_Get(ssh, fullpath, local, 0, NULL); } err = wolfSSH_get_error(ssh); } while ((err == WS_WANT_READ || err == WS_WANT_WRITE) && ret != WS_SUCCESS); if (ret != WS_SUCCESS) { if (cmd == AUTOPILOT_PUT) { fprintf(stderr, "Unable to copy local file %s to remote file %s\n", local, fullpath); } else if (cmd == AUTOPILOT_GET) { fprintf(stderr, "Unable to copy remote file %s to local file %s\n", fullpath, local); } } wolfSSH_SFTPNAME_list_free(name); return ret; } THREAD_RETURN WOLFSSH_THREAD sftpclient_test(void* args) { WOLFSSH_CTX* ctx = NULL; SOCKET_T sockFd = WOLFSSH_SOCKET_INVALID; SOCKADDR_IN_T clientAddr; socklen_t clientAddrSz = sizeof(clientAddr); int ret; int ch; int userEcc = 0; /* int peerEcc = 0; */ word16 port = wolfSshPort; char* host = (char*)wolfSshIp; const char* username = NULL; const char* password = NULL; const char* defaultSftpPath = NULL; byte nonBlock = 0; int autopilot = AUTOPILOT_OFF; char* apLocal = NULL; char* apRemote = NULL; int argc = ((func_args*)args)->argc; char** argv = ((func_args*)args)->argv; ((func_args*)args)->return_code = 0; while ((ch = mygetopt(argc, argv, "?d:egh:l:p:r:u:AEGNP:")) != -1) { switch (ch) { case 'd': defaultSftpPath = myoptarg; break; case 'e': userEcc = 1; break; case 'E': /* peerEcc = 1; */ err_sys("wolfSFTP ECC server authentication " "not yet supported."); break; case 'h': host = myoptarg; break; case 'p': port = (word16)atoi(myoptarg); #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API) if (port == 0) err_sys("port number cannot be 0"); #endif break; case 'u': username = myoptarg; break; case 'l': apLocal = myoptarg; break; case 'r': apRemote = myoptarg; break; case 'g': autopilot = AUTOPILOT_PUT; break; case 'G': autopilot = AUTOPILOT_GET; break; case 'P': password = <PASSWORD>; break; case 'N': nonBlock = 1; break; case '?': ShowUsage(); exit(EXIT_SUCCESS); default: ShowUsage(); exit(MY_EX_USAGE); } } myoptind = 0; /* reset for test cases */ if (username == NULL) err_sys("client requires a username parameter."); #ifdef NO_RSA userEcc = 1; /* peerEcc = 1; */ #endif if (autopilot != AUTOPILOT_OFF) { if (apLocal == NULL || apRemote == NULL) { err_sys("Options -G and -g require both -l and -r."); } } #ifdef WOLFSSH_TEST_BLOCK if (!nonBlock) { err_sys("Use -N when testing forced non blocking"); } #endif if (userEcc) { userPublicKeySz = (word32)sizeof(userPublicKey); Base64_Decode((byte*)hanselPublicEcc, (word32)WSTRLEN(hanselPublicEcc), (byte*)userPublicKey, &userPublicKeySz); WSTRNCPY((char*)userPublicKeyType, "ecdsa-sha2-nistp256", sizeof(userPublicKeyType)); userPrivateKey = hanselPrivateEcc; userPrivateKeySz = hanselPrivateEccSz; } else { userPublicKeySz = (word32)sizeof(userPublicKey); Base64_Decode((byte*)hanselPublicRsa, (word32)WSTRLEN(hanselPublicRsa), (byte*)userPublicKey, &userPublicKeySz); WSTRNCPY((char*)userPublicKeyType, "ssh-rsa", sizeof(userPublicKeyType)); userPrivateKey = hanselPrivateRsa; userPrivateKeySz = hanselPrivateRsaSz; } ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL); if (ctx == NULL) err_sys("Couldn't create wolfSSH client context."); if (((func_args*)args)->user_auth == NULL) wolfSSH_SetUserAuth(ctx, wsUserAuth); else wolfSSH_SetUserAuth(ctx, ((func_args*)args)->user_auth); #ifndef WS_NO_SIGNAL /* handle interrupt with get and put */ signal(SIGINT, sig_handler); #endif ssh = wolfSSH_new(ctx); if (ssh == NULL) err_sys("Couldn't create wolfSSH session."); if (defaultSftpPath != NULL) { if (wolfSSH_SFTP_SetDefaultPath(ssh, defaultSftpPath) != WS_SUCCESS) { fprintf(stderr, "Couldn't store default sftp path.\n"); exit(EXIT_FAILURE); } } if (password != NULL) wolfSSH_SetUserAuthCtx(ssh, (void*)password); wolfSSH_CTX_SetPublicKeyCheck(ctx, wsPublicKeyCheck); wolfSSH_SetPublicKeyCheckCtx(ssh, (void*)"You've been sampled!"); ret = wolfSSH_SetUsername(ssh, username); if (ret != WS_SUCCESS) err_sys("Couldn't set the username."); build_addr(&clientAddr, host, port); tcp_socket(&sockFd); ret = connect(sockFd, (const struct sockaddr *)&clientAddr, clientAddrSz); if (ret != 0) err_sys("Couldn't connect to server."); if (nonBlock) tcp_set_nonblocking(&sockFd); ret = wolfSSH_set_fd(ssh, (int)sockFd); if (ret != WS_SUCCESS) err_sys("Couldn't set the session's socket."); if (!nonBlock) ret = wolfSSH_SFTP_connect(ssh); else ret = NonBlockSSH_connect(); if (ret != WS_SUCCESS) err_sys("Couldn't connect SFTP"); { /* get current working directory */ WS_SFTPNAME* n = NULL; do { n = wolfSSH_SFTP_RealPath(ssh, (char*)"."); ret = wolfSSH_get_error(ssh); } while (ret == WS_WANT_READ || ret == WS_WANT_WRITE); if (n == NULL) { err_sys("Unable to get real path for working directory"); } workingDir = (char*)WMALLOC(n->fSz + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (workingDir == NULL) { err_sys("Unable to create working directory"); } WMEMCPY(workingDir, n->fName, n->fSz); workingDir[n->fSz] = '\0'; /* free after done with names */ wolfSSH_SFTPNAME_list_free(n); n = NULL; } if (autopilot == AUTOPILOT_OFF) { ret = doCmds((func_args*)args); } else { ret = doAutopilot(autopilot, apLocal, apRemote); } WFREE(workingDir, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (ret == WS_SUCCESS) { if (wolfSSH_shutdown(ssh) != WS_SUCCESS) { printf("error with wolfSSH_shutdown(), already disconnected?\n"); } } WCLOSESOCKET(sockFd); wolfSSH_free(ssh); wolfSSH_CTX_free(ctx); if (ret != WS_SUCCESS) { printf("error %d encountered\n", ret); ((func_args*)args)->return_code = ret; } #if defined(HAVE_ECC) && defined(FP_ECC) && defined(HAVE_THREAD_LS) wc_ecc_fp_free(); /* free per thread cache */ #endif return 0; } #else THREAD_RETURN WOLFSSH_THREAD sftpclient_test(void* args) { printf("Not compiled in!\nPlease recompile with WOLFSSH_SFTP or --enable-sftp"); (void)args; return 0; } #endif /* WOLFSSH_SFTP */ #ifndef NO_MAIN_DRIVER int main(int argc, char** argv) { func_args args; args.argc = argc; args.argv = argv; args.return_code = 0; args.user_auth = NULL; #ifdef WOLFSSH_SFTP args.sftp_cb = NULL; #endif WSTARTTCP(); #ifdef DEBUG_WOLFSSH wolfSSH_Debugging_ON(); #endif wolfSSH_Init(); ChangeToWolfSshRoot(); sftpclient_test(&args); wolfSSH_Cleanup(); return args.return_code; } int myoptind = 0; char* myoptarg = NULL; #endif /* NO_MAIN_DRIVER */
30,794
72,551
<filename>unittests/Parse/SyntaxParsingCacheTests.cpp #include "swift/Parse/SyntaxParsingCache.h" #include "gtest/gtest.h" #include <iostream> using namespace swift; using namespace llvm; namespace llvm { template <typename T> void PrintTo(const Optional<T> &optVal, ::std::ostream *os) { if (optVal.hasValue()) *os << *optVal; else *os << "None"; } } // namespace llvm void check(ArrayRef<SourceEdit> Edits, ArrayRef<Optional<size_t>> expected) { for (size_t Pos = 0; Pos != expected.size(); ++Pos) { Optional<size_t> PrePos = SyntaxParsingCache::translateToPreEditPosition(Pos, Edits); EXPECT_EQ(PrePos, expected[Pos]) << "At post-edit position " << Pos; } } class TranslateToPreEditPositionTest : public ::testing::Test {}; TEST_F(TranslateToPreEditPositionTest, SingleEdit1) { // Old: ab_xy // New: c_xy llvm::SmallVector<SourceEdit, 4> Edits = { {0, 2, 1} // ab -> c }; // c _ x y check(Edits, {None, 2, 3, 4}); } TEST_F(TranslateToPreEditPositionTest, SingleEdit) { // Old: ab_xy // New: ablah_xy llvm::SmallVector<SourceEdit, 4> Edits = { {1, 2, 4} // b -> blah }; // a b l a h _ x y check(Edits, {0, None, None, None, None, 2, 3, 4}); } TEST_F(TranslateToPreEditPositionTest, SingleInsert) { // Old: ab_xy // New: 0123ab_xy llvm::SmallVector<SourceEdit, 4> Edits = { {0, 0, 4} // '' -> 0123 }; // 0 1 2 3 a b _ x y check(Edits, { None, None, None, None, 0, 1, 2, 3, 4}); } TEST_F(TranslateToPreEditPositionTest, SingleDelete) { // Old: ab_xyz // New: ab_z llvm::SmallVector<SourceEdit, 4> Edits = { {3, 5, 0} // xy -> '' }; // a b _ z check(Edits, { 0, 1, 2, 5 }); } TEST_F(TranslateToPreEditPositionTest, SimpleMultiEdit) { // Old: _ab_xy // New: _a1b2_x3y4 llvm::SmallVector<SourceEdit, 4> Edits = { {1, 2, 2}, // a -> a1 {2, 3, 2}, // b -> b2 {4, 5, 2}, // x -> x3 {5, 6, 2}, // y -> y4 }; // _ a 1 b 1 _ x 3 y 4 check(Edits, {0, None, None, None, None, 3, None, None, None, None}); } TEST_F(TranslateToPreEditPositionTest, ComplexMultiEdit) { // Old: foo_bar_baz // New: xx_edits_baz llvm::SmallVector<SourceEdit, 4> Edits = { {0, 3, 2}, // foo -> xx {4, 7, 0}, // bar -> '' {7, 7, 5}, // '' -> edits }; // x x _ e d i t s _ b a z check(Edits, {None, None, 3, None, None, None, None, None, 7, 8, 9, 10}); }
1,233
760
package de.codecentric.spring.boot.chaos.monkey.configuration.toggles; public class DefaultChaosToggles implements ChaosToggles { @Override public boolean isEnabled(String toggleName) { return true; } }
64
453
/* Copied from libc/posix/usleep.c, removed the check for HAVE_NANOSLEEP */ /* Written 2002 by <NAME> */ #include <errno.h> #include <time.h> #include <unistd.h> int usleep(useconds_t useconds) { struct timespec ts; ts.tv_sec = (long int)useconds / 1000000; ts.tv_nsec = ((long int)useconds % 1000000) * 1000; if (!nanosleep(&ts,&ts)) return 0; if (errno == EINTR) return ts.tv_sec; return -1; }
186
2,298
# -*- coding: utf-8 -*- from pandas_ta.overlap import sma from pandas_ta.utils import get_offset, verify_series def dpo(close, length=None, centered=True, offset=None, **kwargs): """Indicator: Detrend Price Oscillator (DPO)""" # Validate Arguments length = int(length) if length and length > 0 else 20 close = verify_series(close, length) offset = get_offset(offset) if not kwargs.get("lookahead", True): centered = False if close is None: return # Calculate Result t = int(0.5 * length) + 1 ma = sma(close, length) dpo = close - ma.shift(t) if centered: dpo = (close.shift(t) - ma).shift(-t) # Offset if offset != 0: dpo = dpo.shift(offset) # Handle fills if "fillna" in kwargs: dpo.fillna(kwargs["fillna"], inplace=True) if "fill_method" in kwargs: dpo.fillna(method=kwargs["fill_method"], inplace=True) # Name and Categorize it dpo.name = f"DPO_{length}" dpo.category = "trend" return dpo dpo.__doc__ = \ """Detrend Price Oscillator (DPO) Is an indicator designed to remove trend from price and make it easier to identify cycles. Sources: https://www.tradingview.com/scripts/detrendedpriceoscillator/ https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/dpo http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:detrended_price_osci Calculation: Default Inputs: length=20, centered=True SMA = Simple Moving Average t = int(0.5 * length) + 1 DPO = close.shift(t) - SMA(close, length) if centered: DPO = DPO.shift(-t) Args: close (pd.Series): Series of 'close's length (int): It's period. Default: 1 centered (bool): Shift the dpo back by int(0.5 * length) + 1. Default: True offset (int): How many periods to offset the result. Default: 0 Kwargs: fillna (value, optional): pd.DataFrame.fillna(value) fill_method (value, optional): Type of fill method Returns: pd.Series: New feature generated. """
819
534
{ "parent": "mekanism:block/bin/advanced", "textures": { "front": "mekanism:block/bin/advanced_front_on", "west": "mekanism:block/bin/advanced_side_on", "east": "mekanism:block/bin/advanced_side_on", "south": "mekanism:block/bin/advanced_side_on", "up": "mekanism:block/bin/advanced_top_on" } }
145
848
<reponame>bluetiger9/Vitis-AI<gh_stars>100-1000 # Copyright 2019 Xilinx 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. # ============================================================================== """Fast finetune for quantized tf.keras models.""" import tensorflow as tf import numpy as np from tensorflow.python.keras.engine import data_adapter from tensorflow_model_optimization.python.core.quantization.keras.vitis.common import vitis_quantize_wrapper from tensorflow_model_optimization.python.core.quantization.keras.vitis.common import vitis_quantize_aware_activation from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import model_utils keras = tf.keras logger = common_utils.VAILogger class SubModel(keras.Model): """A custom keras.Model class to support multi-optimizer.""" def __init__(self, layer, act): super(SubModel, self).__init__() new_input = keras.Input(layer.get_input_shape_at(0)[1:], name='new_input') new_output = layer(new_input) if act.name != layer.name: new_output = act(new_output) self.sub_model = keras.Model( inputs=new_input, outputs=new_output, name='sub_model') self.w = self.sub_model.trainable_weights[0] if hasattr(layer.layer, 'use_bias') and layer.layer.use_bias: self.use_bias = True self.b = self.sub_model.trainable_weights[1] else: self.use_bias = False self.b = None self.loss_tracker = keras.metrics.Mean(name="loss") def call(self, x, training): return self.sub_model(x, training) def compile(self, loss, w_opt, b_opt=None): super(SubModel, self).compile() self.loss = loss self.w_opt = w_opt if self.use_bias: self.b_opt = b_opt @property def metrics(self): return [self.loss_tracker] def test_step(self, data): data = data_adapter.expand_1d(data) x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data) y_pred = self.call(x, training=False) loss_value = self.loss(y, y_pred, sample_weight) self.loss_tracker.update_state(loss_value) return {'loss': self.loss_tracker.result()} def train_step(self, data): data = data_adapter.expand_1d(data) x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data) with tf.GradientTape(persistent=True) as tape: y_pred = self.call(x, training=True) loss_value = self.loss(y, y_pred, sample_weight) # Get gradients of loss wrt the weights. w_gradients = tape.gradient(loss_value, self.w) self.w_opt.apply_gradients(zip([w_gradients], [self.w])) if self.use_bias: b_gradients = tape.gradient(loss_value, self.b) self.b_opt.apply_gradients(zip([b_gradients], [self.b])) del tape self.loss_tracker.update_state(loss_value) return {'loss': self.loss_tracker.result()} def _get_layer_input(model, layer_name, input_data, batch_size, steps): """Get the predict result of layer's input.""" target_layer = model.get_layer(layer_name) layer_model = tf.keras.Model(inputs=model.input, outputs=target_layer.input) return layer_model.predict( input_data, batch_size=batch_size, steps=steps, verbose=logger.debug_enabled()) def _get_layer_output(model, layer_name, input_data, batch_size, steps): """Get the predict result of layer's ouput.""" target_layer = model.get_layer(layer_name) layer_model = tf.keras.Model(inputs=model.input, outputs=target_layer.output) return layer_model.predict( input_data, batch_size=batch_size, steps=steps, verbose=logger.debug_enabled()) def _get_module_io(model, input_name, output_name, input_data, batch_size, steps): """Get the predict result of module's input and ouput.""" input_layer = model.get_layer(input_name) output_layer = model.get_layer(output_name) layer_model = tf.keras.Model( inputs=model.input, outputs=[input_layer.input, output_layer.output]) inputs, outputs = layer_model.predict( input_data, batch_size=batch_size, steps=steps, verbose=logger.debug_enabled()) return inputs, outputs def _eval_model_loss(quant_model, float_outputs, layer, dataset, batch_size, steps): """Evaluate the mse loss of the float model and quant model for given layer.""" quant_outputs = _get_layer_output(quant_model, layer.name, dataset, batch_size, steps) return tf.keras.losses.mean_squared_error(float_outputs, quant_outputs).numpy().mean() def fast_finetune(quant_model, float_model, calib_dataset, calib_batch_size, calib_steps, ft_epochs): """Do Ada-Quant Fast Finetuning.""" target_modules = [] for layer in quant_model.layers: if isinstance( layer, vitis_quantize_wrapper.QuantizeWrapper) and layer.trainable_weights: activation = layer.layer.activation.activation if isinstance(activation, vitis_quantize_aware_activation.NoQuantizeActivation): act = layer.outbound_nodes[0].outbound_layer else: act = layer target_modules.append({'layer': layer, 'act': act}) # Main loop for i, module in enumerate(target_modules): layer = module['layer'] act = module['act'] logger.info("Fast Finetuning({}/{}): {} -> {}".format( i + 1, len(target_modules), layer.layer.name, act.layer.name)) logger.debug("Cache float inputs and outputs of layer: {} -> {}".format( layer.layer.name, act.layer.name)) float_inputs, float_outputs = _get_module_io( model=float_model, input_name=layer.layer.name, output_name=act.layer.name, input_data=calib_dataset, batch_size=calib_batch_size, steps=calib_steps) sub_model = SubModel(layer, act) sub_model.compile( loss=tf.keras.losses.MeanSquaredError( reduction=tf.keras.losses.Reduction.NONE), w_opt=keras.optimizers.Adam(learning_rate=1e-5), b_opt=keras.optimizers.Adam(learning_rate=1e-3)) logger.debug("Get initial loss...") best_loss = 0 loss_type = 'layer' if loss_type == 'layer': best_loss = sub_model.evaluate( float_inputs, float_outputs, batch_size=calib_batch_size, steps=calib_steps, verbose=logger.debug_enabled()) else: best_loss = _eval_model_loss(quant_model, float_outputs, layer, calib_dataset, calib_batch_size, calib_steps) best_params = sub_model.get_weights() for e in range(ft_epochs): logger.debug("Epoch {}/{}".format(e + 1, ft_epochs)) sub_model.fit( float_inputs, float_outputs, batch_size=calib_batch_size, steps_per_epoch=calib_steps, epochs=1, verbose=logger.debug_enabled()) logger.debug("Get new loss...") new_loss = 0 if loss_type == 'layer': new_loss = sub_model.evaluate( float_inputs, float_outputs, batch_size=calib_batch_size, steps=calib_steps, verbose=logger.debug_enabled()) else: new_loss = _eval_model_loss(quant_model, float_outputs, layer, calib_dataset, calib_batch_size, calib_steps) logger.debug("Best Loss: {:.2e}, new Loss: {:.2e}".format( best_loss, new_loss)) if new_loss < best_loss: logger.debug("Update best loss: {:.2e} -> {:.2e}".format( best_loss, new_loss)) best_loss = new_loss best_params = sub_model.get_weights() else: logger.debug("Revert best loss: {:.2e} -> {:.2e}".format( new_loss, best_loss)) sub_model.set_weights(best_params) break if logger.debug_enabled(): model_utils.save_model(quant_model, 'fast_ft_{}.h5'.format(i + 1), './debug/') return
3,643
585
/** * Copyright (c) 2016-present, Facebook, 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 "caffe2/core/blob.h" #include "caffe2/core/blob_serialization.h" #include "caffe2/core/context_gpu.h" namespace caffe2 { template <> void TensorSerializer<CUDAContext>::StoreDeviceDetail( const Tensor<CUDAContext>& input, TensorProto* proto) { auto* device_detail = proto->mutable_device_detail(); device_detail->set_device_type(CUDA); device_detail->set_cuda_gpu_id( GetGPUIDForPointer(input.raw_data())); } namespace { REGISTER_BLOB_SERIALIZER( (TypeMeta::Id<TensorCUDA>()), TensorSerializer<CUDAContext>); REGISTER_BLOB_DESERIALIZER(TensorCUDA, TensorDeserializer<CUDAContext>); } } // namespace caffe2
425
373
<reponame>linkingtd/UniAuth package com.dianrong.common.uniauth.client.custom.jwt; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.OrderComparator; /** * JWTQuery的适配实现,负责查找Spring环境中所有的JWTQuery实现,<br> * 并依次调用获取JWT,直到获取到JWT或者返回null. * * @author wanglin * */ @Slf4j public class CompositeJWTQuery implements JWTQuery, ApplicationContextAware, InitializingBean { /** * JWTQuery实现集合. */ private Set<JWTQuery> jwtQuerySets = Sets.newHashSet(); private ApplicationContext applicationContext; @Override public String getJWT(HttpServletRequest request) { for (JWTQuery jwtQuery : jwtQuerySets) { String jwt = jwtQuery.getJWT(request); if (jwt != null) { return jwt; } } return null; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void afterPropertiesSet() throws Exception { String[] names = this.applicationContext.getBeanNamesForType(JWTQuery.class, false, false); List<JWTQuery> jwtQuerys = Lists.newArrayList(); for (String name : names) { Object object = this.applicationContext.getBean(name); if (object instanceof CompositeJWTQuery) { log.debug("Ignore CompositeJWTQuery type JWTQuery :" + object); continue; } jwtQuerys.add((JWTQuery) object); } Comparator<Object> comparator = OrderComparator.INSTANCE; Collections.sort(jwtQuerys, comparator); this.jwtQuerySets = Collections.unmodifiableSet(new LinkedHashSet<>(jwtQuerys)); } }
814
1,510
/* * 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.drill.exec.planner; import java.util.List; import java.util.Map; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rex.RexInputRef; import org.apache.calcite.rex.RexNode; import org.apache.drill.common.expression.SchemaPath; public class StarColumnHelper { public final static String PREFIX_DELIMITER = "\u00a6\u00a6"; public final static String PREFIXED_STAR_COLUMN = PREFIX_DELIMITER + SchemaPath.DYNAMIC_STAR; public static boolean containsStarColumn(RelDataType type) { if (! type.isStruct()) { return false; } List<String> fieldNames = type.getFieldNames(); for (String fieldName : fieldNames) { if (SchemaPath.DYNAMIC_STAR.equals(fieldName)) { return true; } } return false; } public static boolean containsStarColumnInProject(RelDataType inputRowType, List<RexNode> projExprs) { if (!inputRowType.isStruct()) { return false; } for (RexNode expr : projExprs) { if (expr instanceof RexInputRef) { String name = inputRowType.getFieldNames().get(((RexInputRef) expr).getIndex()); if (SchemaPath.DYNAMIC_STAR.equals(name)) { return true; } } } return false; } public static boolean isPrefixedStarColumn(String fieldName) { return fieldName.indexOf(PREFIXED_STAR_COLUMN) > 0; // the delimiter * starts at none-zero position. } public static boolean isNonPrefixedStarColumn(String fieldName) { return SchemaPath.DYNAMIC_STAR.equals(fieldName); } public static boolean isStarColumn(String fieldName) { return isPrefixedStarColumn(fieldName) || isNonPrefixedStarColumn(fieldName); } // Expression in some sense is similar to regular columns. Expression (i.e. C1 + C2 + 10) is not // associated with an alias, the project will have (C1 + C2 + 10) --> f1, column "f1" could be // viewed as a regular column, and does not require prefix. If user put an alias, then, // the project will have (C1 + C2 + 10) -> alias. public static boolean isRegularColumnOrExp(String fieldName) { return ! isStarColumn(fieldName); } public static String extractStarColumnPrefix(String fieldName) { assert (isPrefixedStarColumn(fieldName)); return fieldName.substring(0, fieldName.indexOf(PREFIXED_STAR_COLUMN)); } public static String extractColumnPrefix(String fieldName) { if (fieldName.indexOf(PREFIX_DELIMITER) >=0) { return fieldName.substring(0, fieldName.indexOf(PREFIX_DELIMITER)); } else { return ""; } } // Given a set of prefixes, check if a regular column is subsumed by any of the prefixed star column in the set. public static boolean subsumeColumn(Map<String, String> prefixMap, String fieldName) { String prefix = extractColumnPrefix(fieldName); if (isRegularColumnOrExp(fieldName)) { return false; // regular column or expression is not subsumed by any star column. } else { return prefixMap.containsKey(prefix) && ! fieldName.equals(prefixMap.get(prefix)); // t1*0 is subsumed by t1*. } } }
1,286
10,225
package io.quarkus.it.spring.web; import io.quarkus.test.junit.NativeImageTest; @NativeImageTest public class SecurityIT extends SecurityTest { }
49
324
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.ultradns.ws.binders; import static org.testng.Assert.assertEquals; import org.jclouds.ultradns.ws.domain.ResourceRecord; import org.testng.annotations.Test; @Test(groups = "unit", testName = "ZoneAndResourceRecordToXMLTest") public class ZoneAndResourceRecordToXMLTest { private static final String A = "<v01:createResourceRecord><transactionID /><resourceRecord ZoneName=\"jclouds.org.\" Type=\"1\" DName=\"www.jclouds.org.\" TTL=\"3600\"><InfoValues Info1Value=\"1.1.1.1\" /></resourceRecord></v01:createResourceRecord>"; public void testA() { assertEquals(ZoneAndResourceRecordToXML.toXML("jclouds.org.", ResourceRecord.rrBuilder() .name("www.jclouds.org.") .type(1) .ttl(3600) .rdata("1.1.1.1").build()), A); } private static final String MX = "<v01:createResourceRecord><transactionID /><resourceRecord ZoneName=\"jclouds.org.\" Type=\"15\" DName=\"mail.jclouds.org.\" TTL=\"1800\"><InfoValues Info1Value=\"10\" Info2Value=\"maileast.jclouds.org.\" /></resourceRecord></v01:createResourceRecord>"; public void testMX() { assertEquals(ZoneAndResourceRecordToXML.toXML("jclouds.org.", ResourceRecord.rrBuilder() .name("mail.jclouds.org.") .type(15) .ttl(1800) .infoValue(10) .infoValue("maileast.jclouds.org.").build()), MX); } private static final String A_UPDATE = "<v01:updateResourceRecord><transactionID /><resourceRecord Guid=\"ABCDEF\" ZoneName=\"jclouds.org.\" Type=\"1\" DName=\"www.jclouds.org.\" TTL=\"3600\"><InfoValues Info1Value=\"1.1.1.1\" /></resourceRecord></v01:updateResourceRecord>"; public void testUpdate() { assertEquals(ZoneAndResourceRecordToXML.update("ABCDEF", A), A_UPDATE); } }
1,520
892
{ "schema_version": "1.2.0", "id": "GHSA-jr56-p22g-v622", "modified": "2022-05-13T01:47:59Z", "published": "2022-05-13T01:47:59Z", "aliases": [ "CVE-2017-9481" ], "details": "The Comcast firmware on Cisco DPC3939 (firmware version dpc3939-P20-18-v303r20421746-170221a-CMCST) devices allows remote attackers to obtain unintended access to the Network Processor (NP) 169.254/16 IP network by adding a routing-table entry that specifies the LAN IP address as the router for that network.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2017-9481" }, { "type": "WEB", "url": "https://github.com/BastilleResearch/CableTap/blob/master/doc/advisories/bastille-24.atom-ip-routing.txt" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
473
417
/*************************************************************************** file : PlibSoundInterface.cpp created : Thu Apr 7 04:21 CEST 2005 copyright : (C) 2005 <NAME> email : <EMAIL> version : $Id: PlibSoundInterface.cpp,v 1.8 2005/11/18 00:20:32 olethros Exp $ ***************************************************************************/ /*************************************************************************** * * * 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 * * (at your option) any later version. * * * ***************************************************************************/ #include "SoundInterface.h" #include "TorcsSound.h" #include "CarSoundData.h" PlibSoundInterface::PlibSoundInterface(float sampling_rate, int n_channels) : SoundInterface (sampling_rate, n_channels) { sched = new slScheduler ((int) sampling_rate); sched->setSafetyMargin (0.128f); sched->setMaxConcurrent (n_channels); engpri = NULL; car_src = NULL; global_gain = 1.0f; // initialise mappings grass.schar = &CarSoundData::grass; grass_skid.schar = &CarSoundData::grass_skid; road.schar = &CarSoundData::road; metal_skid.schar = &CarSoundData::drag_collision; backfire_loop.schar = &CarSoundData::engine_backfire; turbo.schar = &CarSoundData::turbo; axle.schar = &CarSoundData::axle; } PlibSoundInterface::~PlibSoundInterface() { for (unsigned int i=0; i<sound_list.size(); i++) { delete sound_list[i]; } delete [] engpri; delete sched; if (car_src) { delete [] car_src; } } void PlibSoundInterface::setNCars(int n_cars) { engpri = new SoundPri[n_cars]; car_src = new SoundSource[n_cars]; } slScheduler* PlibSoundInterface::getScheduler() { return sched; } TorcsSound* PlibSoundInterface::addSample (const char* filename, int flags, bool loop, bool static_pool) { PlibTorcsSound* sound = new PlibTorcsSound (sched, filename, flags, loop); sound->setVolume (2.0*global_gain); sound_list.push_back ((TorcsSound*) sound); return sound; } void PlibSoundInterface::update(CarSoundData** car_sound_data, int n_cars, sgVec3 p_obs, sgVec3 u_obs, sgVec3 c_obs, sgVec3 a_obs) { // Copy car ID basically. int i; for (i = 0; i<n_cars; i++) { car_sound_data[i]->copyEngPri(engpri[i]); } for (i = 0; i<n_cars; i++) { int id = engpri[i].id; sgVec3 p; sgVec3 u; car_sound_data[id]->getCarPosition(p); car_sound_data[id]->getCarSpeed(u); car_src[id].setSource (p, u); car_src[id].setListener (p_obs, u_obs); car_src[id].update(); engpri[id].a = car_src[id].a; } qsort ((void*) engpri, n_cars, sizeof(SoundPri), &sortSndPriority); for (i = 0; i<n_cars; i++) { int id = engpri[i].id; TorcsSound* engine = car_sound_data[id]->getEngineSound(); if (i>=NB_ENGINE_SOUND) { engine->setVolume (0.0f); engine->pause(); //printf ("Pausing %d (%d)\n", id, i); } else { engine->resume(); engine->setLPFilter(car_src[id].lp*car_sound_data[id]->engine.lp); engine->setPitch(car_src[id].f*car_sound_data[id]->engine.f); engine->setVolume(global_gain*car_src[id].a*car_sound_data[id]->engine.a); engine->update(); } } float max_skid_vol[4] = {0.0f, 0.0f, 0.0f, 0.0f}; int max_skid_id[4] = {0,0,0,0}; int id; for (id = 0; id<n_cars; id++) { CarSoundData* sound_data = car_sound_data[id]; for (int j=0; j<4; j++) { float skvol=sound_data->attenuation*sound_data->wheel[j].skid.a; if (skvol > max_skid_vol[j]) { max_skid_vol[j] = skvol; max_skid_id[j] = id; } } } for (i = 0; i<4; i++) { int id = max_skid_id[i]; WheelSoundData* sound_data = car_sound_data[id]->wheel; float mod_a = car_src[id].a; float mod_f = car_src[id].f; skid_sound[i]->setVolume (global_gain*sound_data[i].skid.a * mod_a); skid_sound[i]->setPitch (sound_data[i].skid.f * mod_f); skid_sound[i]->update(); #if 0 if (sound_data[i].skid.a > VOLUME_CUTOFF) { skid_sound[i]->start(); } else { skid_sound[i]->stop(); } #endif } // other looping sounds road.snd = road_ride_sound; SortSingleQueue (car_sound_data, &road, n_cars); SetMaxSoundCar (car_sound_data, &road); grass.snd = grass_ride_sound; SortSingleQueue (car_sound_data, &grass, n_cars); SetMaxSoundCar (car_sound_data, &grass); grass_skid.snd = grass_skid_sound; SortSingleQueue (car_sound_data, &grass_skid, n_cars); SetMaxSoundCar (car_sound_data, &grass_skid); metal_skid.snd = metal_skid_sound; SortSingleQueue (car_sound_data, &metal_skid, n_cars); SetMaxSoundCar (car_sound_data, &metal_skid); backfire_loop.snd = backfire_loop_sound; SortSingleQueue (car_sound_data, &backfire_loop, n_cars); SetMaxSoundCar (car_sound_data, &backfire_loop); turbo.snd = turbo_sound; SortSingleQueue (car_sound_data, &turbo, n_cars); SetMaxSoundCar (car_sound_data, &turbo); axle.snd = axle_sound; SortSingleQueue (car_sound_data, &axle, n_cars); SetMaxSoundCar (car_sound_data, &axle); // One-off sounds for (id = 0; id<n_cars; id++) { float crash_threshold = 0.5f; float gear_threshold = 0.75; CarSoundData* sound_data = car_sound_data[id]; if (sound_data->crash) { if (++curCrashSnd>=NB_CRASH_SOUND) { curCrashSnd = 0; } if (car_src[id].a > crash_threshold) { crash_sound[curCrashSnd]->start(); } } if (sound_data->bang) { if (car_src[id].a > crash_threshold) { bang_sound->start(); } } if (sound_data->bottom_crash) { if (car_src[id].a > crash_threshold) { bottom_crash_sound->start(); } } if (sound_data->gear_changing) { if (car_src[id].a > gear_threshold) { gear_change_sound->start(); } } } sched->update(); } int sortSndPriority(const void* a, const void* b) { SoundPri* A = (SoundPri*) a; SoundPri* B = (SoundPri*) b; if (A->a > B->a) { return -1; } else { return 1; } } void PlibSoundInterface::SetMaxSoundCar(CarSoundData** car_sound_data, QueueSoundMap* smap) { int id = smap->id; //float max_vol = smap->max_vol; QSoundChar CarSoundData::*p2schar = smap->schar; QSoundChar* schar = &(car_sound_data[id]->*p2schar); TorcsSound* snd = smap->snd; snd->setVolume (global_gain * schar->a * car_src[id].a); snd->setPitch (schar->f * car_src[id].f); snd->update(); #if 0 f (max_vol > VOLUME_CUTOFF) { snd->start(); } else { snd->stop(); } #endif }
2,987
1,742
<reponame>sim-wangyan/x7<gh_stars>1000+ package x7.demo.repository; import io.xream.sqli.api.BaseRepository; import io.xream.sqli.api.ResultMapRepository; import org.springframework.stereotype.Repository; import x7.demo.entity.OrderLog; @Repository public interface OrderLogRepository extends BaseRepository<OrderLog>, ResultMapRepository { }
130
1,420
<gh_stars>1000+ /* * * Copyright 2019 Netflix, 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 com.netflix.genie.web.agent.inspectors.impl; import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.InspectionReport; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * Abstract base class for {@link AgentMetadataInspector} based on regex matching. * Can be configure to accept or reject in case of match and do the opposite in case of no match. * If a valid regex is not provided, this inspector accepts. * * @author mprimi * @since 4.0.0 */ @Slf4j abstract class BaseRegexAgentMetadataInspector implements AgentMetadataInspector { private final AtomicReference<Pattern> patternReference = new AtomicReference<>(); private final InspectionReport.Decision decisionIfMatch; private String lastCompiledPattern; BaseRegexAgentMetadataInspector( final InspectionReport.Decision decisionIfMatch ) { this.decisionIfMatch = decisionIfMatch; } InspectionReport inspectWithPattern( @Nullable final String currentPatternString, @Nullable final String metadataAttribute ) { final Pattern currentPattern = maybeReloadPattern(currentPatternString); if (currentPattern == null) { return InspectionReport.newAcceptance("Pattern not not set"); } else if (StringUtils.isBlank(metadataAttribute)) { return InspectionReport.newRejection("Metadata attribute not set"); } else if (currentPattern.matcher(metadataAttribute).matches()) { return new InspectionReport( decisionIfMatch, "Attribute: " + metadataAttribute + " matches: " + currentPattern.pattern() ); } else { return new InspectionReport( InspectionReport.Decision.flip(decisionIfMatch), "Attribute: " + metadataAttribute + " does not match: " + currentPattern.pattern() ); } } private Pattern maybeReloadPattern(@Nullable final String currentPatternString) { synchronized (this) { if (StringUtils.isBlank(currentPatternString)) { patternReference.set(null); lastCompiledPattern = null; } else if (!currentPatternString.equals(lastCompiledPattern)) { try { final Pattern newPattern = Pattern.compile(currentPatternString); patternReference.set(newPattern); } catch (final PatternSyntaxException e) { patternReference.set(null); log.error("Failed to load pattern: {}", currentPatternString, e); } lastCompiledPattern = currentPatternString; } } return patternReference.get(); } }
1,355
390
import rdkit import torch from dgllife.data import JTVAEZINC, JTVAEDataset, JTVAECollator from dgllife.utils import JTVAEVocab from dgllife.model import JTNNVAE, load_pretrained from torch.utils.data import DataLoader def main(args): lg = rdkit.RDLogger.logger() lg.setLevel(rdkit.RDLogger.CRITICAL) if args.use_cpu or not torch.cuda.is_available(): device = torch.device('cpu') else: device = torch.device('cuda:0') vocab = JTVAEVocab(file_path=args.train_path) if args.test_path is None: dataset = JTVAEZINC('test', vocab) else: dataset = JTVAEDataset(args.test_path, vocab, training=False) dataloader = DataLoader(dataset, batch_size=1, collate_fn=JTVAECollator(training=False)) if args.model_path is None: model = load_pretrained('JTVAE_ZINC_no_kl') else: model = JTNNVAE(vocab, args.hidden_size, args.latent_size, args.depth) model.load_state_dict(torch.load(args.model_path, map_location='cpu')) model = model.to(device) acc = 0.0 for it, (tree, tree_graph, mol_graph) in enumerate(dataloader): tot = it + 1 smiles = tree.smiles tree_graph = tree_graph.to(device) mol_graph = mol_graph.to(device) dec_smiles = model.reconstruct(tree_graph, mol_graph) if dec_smiles == smiles: acc += 1 if tot % args.print_iter == 0: print('Iter {:d}/{:d} | Acc {:.4f}'.format( tot // args.print_iter, len(dataloader) // args.print_iter, acc / tot)) print('Final acc: {:.4f}'.format(acc / tot)) if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-tr', '--train-path', type=str, help='Path to the training molecules, with one SMILES string a line') parser.add_argument('-te', '--test-path', type=str, help='Path to the test molecules, with one SMILES string a line') parser.add_argument('-m', '--model-path', type=str, help='Path to pre-trained model checkpoint') parser.add_argument('-w', '--hidden-size', type=int, default=450, help='Hidden size') parser.add_argument('-l', '--latent-size', type=int, default=56, help='Latent size') parser.add_argument('-d', '--depth', type=int, default=3, help='Number of GNN layers') parser.add_argument('-pi', '--print-iter', type=int, default=20, help='Frequency for printing evaluation metrics') parser.add_argument('-cpu', '--use-cpu', action='store_true', help='By default, the script uses GPU whenever available. ' 'This flag enforces the use of CPU.') args = parser.parse_args() main(args)
1,350
3,282
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.ntp; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.LevelListDrawable; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; import org.chromium.chrome.browser.ntp.ForeignSessionHelper.ForeignSession; import org.chromium.chrome.browser.widget.TintedDrawable; import org.chromium.ui.base.DeviceFormFactor; /** * Header view shown above each group of items on the Recent Tabs page. Shows the name of the * group (e.g. "Recently closed" or "Jim's Laptop"), an icon, last synced time, and a button to * expand or collapse the group. */ public class RecentTabsGroupView extends RelativeLayout { /** Drawable levels for the device type icon and the expand/collapse arrow. */ private static final int DRAWABLE_LEVEL_COLLAPSED = 0; private static final int DRAWABLE_LEVEL_EXPANDED = 1; private ImageView mDeviceIcon; private ImageView mExpandCollapseIcon; private TextView mDeviceLabel; private TextView mTimeLabel; private int mDeviceLabelExpandedColor; private int mDeviceLabelCollapsedColor; private int mTimeLabelExpandedColor; private int mTimeLabelCollapsedColor; /** * Constructor for inflating from XML. * * @param context The context this view will work in. * @param attrs The attribute set for this view. */ public RecentTabsGroupView(Context context, AttributeSet attrs) { super(context, attrs); Resources res = getResources(); mDeviceLabelExpandedColor = ApiCompatibilityUtils.getColor(res, R.color.light_active_color); mDeviceLabelCollapsedColor = ApiCompatibilityUtils.getColor(res, R.color.ntp_list_header_text); mTimeLabelExpandedColor = ApiCompatibilityUtils.getColor(res, R.color.ntp_list_header_subtext_active); mTimeLabelCollapsedColor = ApiCompatibilityUtils.getColor(res, R.color.ntp_list_header_subtext); } @Override public void onFinishInflate() { super.onFinishInflate(); mDeviceIcon = (ImageView) findViewById(R.id.device_icon); mTimeLabel = (TextView) findViewById(R.id.time_label); mDeviceLabel = (TextView) findViewById(R.id.device_label); mExpandCollapseIcon = (ImageView) findViewById(R.id.expand_collapse_icon); // Create drawable for expand/collapse arrow. LevelListDrawable collapseIcon = new LevelListDrawable(); collapseIcon.addLevel(DRAWABLE_LEVEL_COLLAPSED, DRAWABLE_LEVEL_COLLAPSED, TintedDrawable.constructTintedDrawable(getResources(), R.drawable.ic_expanded)); TintedDrawable collapse = TintedDrawable.constructTintedDrawable(getResources(), R.drawable.ic_collapsed); collapse.setTint( ApiCompatibilityUtils.getColorStateList(getResources(), R.color.blue_mode_tint)); collapseIcon.addLevel(DRAWABLE_LEVEL_EXPANDED, DRAWABLE_LEVEL_EXPANDED, collapse); mExpandCollapseIcon.setImageDrawable(collapseIcon); } /** * Configures the view for currently open tabs. * * @param isExpanded Whether the view is expanded or collapsed. */ public void configureForCurrentlyOpenTabs(boolean isExpanded) { mDeviceIcon.setVisibility(View.VISIBLE); mDeviceIcon.setImageResource(DeviceFormFactor.isTablet(getContext()) ? R.drawable.recent_tablet : R.drawable.recent_phone); String title = getResources().getString(R.string.recent_tabs_this_device); mDeviceLabel.setText(title); setTimeLabelVisibility(View.GONE); configureExpandedCollapsed(isExpanded); } /** * Configures the view for a foreign session. * * @param session The session to configure the view for. * @param isExpanded Whether the view is expanded or collapsed. */ public void configureForForeignSession(ForeignSession session, boolean isExpanded) { mDeviceIcon.setVisibility(View.VISIBLE); mDeviceLabel.setText(session.name); setTimeLabelVisibility(View.VISIBLE); mTimeLabel.setText(getTimeString(session)); switch (session.deviceType) { case ForeignSession.DEVICE_TYPE_PHONE: mDeviceIcon.setImageResource(R.drawable.recent_phone); break; case ForeignSession.DEVICE_TYPE_TABLET: mDeviceIcon.setImageResource(R.drawable.recent_tablet); break; default: mDeviceIcon.setImageResource(R.drawable.recent_laptop); break; } configureExpandedCollapsed(isExpanded); } /** * Configures the view for the recently closed tabs group. * * @param isExpanded Whether the view is expanded or collapsed. */ public void configureForRecentlyClosedTabs(boolean isExpanded) { mDeviceIcon.setVisibility(View.VISIBLE); mDeviceIcon.setImageResource(R.drawable.recent_recently_closed); mDeviceLabel.setText(R.string.recently_closed); setTimeLabelVisibility(View.GONE); configureExpandedCollapsed(isExpanded); } /** * Configures the view for the sync promo. * * @param isExpanded Whether the view is expanded or collapsed. */ public void configureForSyncPromo(boolean isExpanded) { mDeviceIcon.setVisibility(View.VISIBLE); mDeviceIcon.setImageResource(R.drawable.recent_laptop); mDeviceLabel.setText(R.string.ntp_recent_tabs_sync_promo_title); setTimeLabelVisibility(View.GONE); configureExpandedCollapsed(isExpanded); } private void configureExpandedCollapsed(boolean isExpanded) { String description = getResources().getString(isExpanded ? R.string.ntp_recent_tabs_accessibility_expanded_group : R.string.ntp_recent_tabs_accessibility_collapsed_group); mExpandCollapseIcon.setContentDescription(description); int level = isExpanded ? DRAWABLE_LEVEL_EXPANDED : DRAWABLE_LEVEL_COLLAPSED; mExpandCollapseIcon.getDrawable().setLevel(level); mDeviceIcon.setActivated(isExpanded); mDeviceLabel.setTextColor(isExpanded ? mDeviceLabelExpandedColor : mDeviceLabelCollapsedColor); mTimeLabel.setTextColor(isExpanded ? mTimeLabelExpandedColor : mTimeLabelCollapsedColor); } private CharSequence getTimeString(ForeignSession session) { long timeDeltaMs = System.currentTimeMillis() - session.modifiedTime; if (timeDeltaMs < 0) timeDeltaMs = 0; int daysElapsed = (int) (timeDeltaMs / (24L * 60L * 60L * 1000L)); int hoursElapsed = (int) (timeDeltaMs / (60L * 60L * 1000L)); int minutesElapsed = (int) (timeDeltaMs / (60L * 1000L)); Resources res = getResources(); String relativeTime; if (daysElapsed > 0L) { relativeTime = res.getQuantityString(R.plurals.n_days_ago, daysElapsed, daysElapsed); } else if (hoursElapsed > 0L) { relativeTime = res.getQuantityString(R.plurals.n_hours_ago, hoursElapsed, hoursElapsed); } else if (minutesElapsed > 0L) { relativeTime = res.getQuantityString(R.plurals.n_minutes_ago, minutesElapsed, minutesElapsed); } else { relativeTime = res.getString(R.string.just_now); } return getResources().getString(R.string.ntp_recent_tabs_last_synced, relativeTime); } /** * Shows or hides the time label (e.g. "Last synced: just now") and adjusts the positions of the * icon and device label. In particular, the icon and device label are top-aligned when the time * is visible, but are vertically centered when the time is gone. */ private void setTimeLabelVisibility(int visibility) { if (mTimeLabel.getVisibility() == visibility) return; mTimeLabel.setVisibility(visibility); if (visibility == View.GONE) { replaceRule(mDeviceIcon, ALIGN_PARENT_TOP, CENTER_VERTICAL); replaceRule(mDeviceLabel, ALIGN_PARENT_TOP, CENTER_VERTICAL); } else { replaceRule(mDeviceIcon, CENTER_VERTICAL, ALIGN_PARENT_TOP); replaceRule(mDeviceLabel, CENTER_VERTICAL, ALIGN_PARENT_TOP); } } private static void replaceRule(View view, int oldRule, int newRule) { RelativeLayout.LayoutParams lp = ((RelativeLayout.LayoutParams) view.getLayoutParams()); lp.addRule(oldRule, 0); lp.addRule(newRule); } }
3,515
546
#ifndef MSNHEXVECTOR_H #define MSNHEXVECTOR_H #include <iostream> #include <algorithm> #include <vector> #include <iterator> #include <set> #include "Msnhnet/utils/MsnhExport.h" namespace Msnhnet { class MsnhNet_API ExVector { public: template<typename T> static inline bool contains(const std::vector<T>&vec, const T &val) { auto result = std::find(vec.begin(),vec.end(),val); if(result != vec.end()) { return true; } else { return false; } } template<typename T> static inline long long maxIndex(const std::vector<T>&vec) { auto biggest = std::max_element(vec.begin(), vec.end()); return std::distance(vec.begin(), biggest); } template<typename T> static inline int minIndex(const std::vector<T>&vec) { auto smallest = std::min_element(vec.begin(), vec.end()); return std::distance(vec.begin(), smallest); } template<typename T> static inline T max(const std::vector<T>&vec) { auto biggest = std::max_element(vec.begin(), vec.end()); return *biggest; } template<typename T> static inline T min(const std::vector<T>&vec) { auto smallest = std::min_element(vec.begin(), vec.end()); return *smallest ; } template<typename T> static inline std::vector<int> argsort(const std::vector<T>& a, const bool &descending = false) { int Len = a.size(); std::vector<int> idx(static_cast<size_t>(Len), 0); for(int i = 0; i < Len; i++) { idx[static_cast<size_t>(i)] = i; } if(!descending) std::sort(idx.begin(), idx.end(), [&a](int i1, int i2){return a[i1] < a[i2];}); else std::sort(idx.begin(), idx.end(), [&a](int i1, int i2){return a[i1] > a[i2];}); return idx; } template<typename T> inline static void removeRepeat(std::vector<T>& v){ std::set<T> st(v.begin(), v.end()); v.assign(st.begin(), st.end()); } }; } #endif
1,179
836
<reponame>severinsimmler/Mallet package cc.mallet.pipe.iterator; import java.util.Iterator; import cc.mallet.types.Instance; public class EmptyInstanceIterator implements Iterator<Instance> { public boolean hasNext() { return false; } public Instance next () { throw new IllegalStateException ("This iterator never has any instances."); } public void remove () { throw new IllegalStateException ("This iterator does not support remove()."); } }
121
526
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.accessservices.governanceprogram.metadataelements; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import org.odpi.openmetadata.accessservices.governanceprogram.properties.PersonalProfileProperties; import java.io.Serializable; import java.util.*; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * The PersonalProfileElement describes an individual who has (or will be) appointed to one of the * governance roles defined in the governance program. Information about the personal profile is stored * as an Person entity. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public class PersonalProfileElement implements Serializable, MetadataElement { private static final long serialVersionUID = 1L; private ElementHeader elementHeader = null; private PersonalProfileProperties profileProperties = null; /** * Default Constructor */ public PersonalProfileElement() { } /** * Copy/clone Constructor - the resulting object. * * @param template object being copied */ public PersonalProfileElement(PersonalProfileElement template) { if (template != null) { elementHeader = template.getElementHeader(); profileProperties = template.getProfileProperties(); } } /** * Return the element header associated with the properties. * * @return element header object */ public ElementHeader getElementHeader() { return elementHeader; } /** * Set up the element header associated with the properties. * * @param elementHeader element header object */ public void setElementHeader(ElementHeader elementHeader) { this.elementHeader = elementHeader; } /** * Return the properties of the profile. * * @return properties */ public PersonalProfileProperties getProfileProperties() { return profileProperties; } /** * Set up the profile properties. * * @param profileProperties properties */ public void setProfileProperties(PersonalProfileProperties profileProperties) { this.profileProperties = profileProperties; } /** * JSON-style toString * * @return return string containing the property names and values */ @Override public String toString() { return "PersonalProfileElement{" + "elementHeader=" + elementHeader + ", profileProperties=" + profileProperties + '}'; } /** * Return comparison result based on the content of the properties. * * @param objectToCompare test object * @return result of comparison */ @Override public boolean equals(Object objectToCompare) { if (this == objectToCompare) { return true; } if (objectToCompare == null || getClass() != objectToCompare.getClass()) { return false; } PersonalProfileElement that = (PersonalProfileElement) objectToCompare; return Objects.equals(elementHeader, that.elementHeader) && Objects.equals(profileProperties, that.profileProperties); } /** * Return hash code for this object * * @return int hash code */ @Override public int hashCode() { return Objects.hash(elementHeader, profileProperties); } }
1,477
733
package com.douban.rexxar.example.widget; import android.app.Activity; import android.content.DialogInterface; import android.net.Uri; import android.support.annotation.Keep; import android.text.TextUtils; import android.webkit.WebView; import com.douban.rexxar.utils.GsonHelper; import com.douban.rexxar.view.RexxarWidget; import java.util.ArrayList; import java.util.List; /** * Created by luanqian on 16/4/28. */ public class AlertDialogWidget implements RexxarWidget { static final String KEY = "data"; static boolean sShowing = false; @Override public String getPath() { return "/widget/alert_dialog"; } @Override public boolean handle(WebView view, String url) { if (TextUtils.isEmpty(url)) { return false; } Uri uri = Uri.parse(url); String path = uri.getPath(); if (TextUtils.equals(path, getPath())) { String data = uri.getQueryParameter(KEY); Data alertDialogData = null; if (!TextUtils.isEmpty(data)) { alertDialogData = GsonHelper.getInstance().fromJson(data, Data.class); } if (null == alertDialogData || !alertDialogData.valid()) { return false; } return renderDialog((Activity) view.getContext(), view, alertDialogData); } return false; } /** * 根据dialog数据显示dialog * * @param data * @return */ private static boolean renderDialog(Activity activity, final WebView webView, Data data) { if (null == data) { return false; } // 正在显示dialog,则不再显示 if (sShowing) { return false; } if (activity.isFinishing()) { return false; } android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity) .setTitle(data.title) .setMessage(data.message) // 不可消失 .setCancelable(false) // dialog消失后,sShowing设置为false .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { sShowing = false; } }); switch (data.buttons.size()) { // 一个button case 1: { final Button positive = data.buttons.get(0); builder.setPositiveButton(positive.text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { webView.loadUrl("javascript:" + positive.action); } }); break; } // 两个button case 2: { final Button positive = data.buttons.get(1); final Button negative = data.buttons.get(0); builder.setPositiveButton(positive.text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { webView.loadUrl("javascript:" + positive.action); } }); builder.setNegativeButton(negative.text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { webView.loadUrl("javascript:" + negative.action); } }); break; } // 3个button case 3: { final Button positive = data.buttons.get(2); final Button negative = data.buttons.get(0); final Button neutral = data.buttons.get(1); builder.setPositiveButton(positive.text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { webView.loadUrl("javascript:" + positive.action); } }); builder.setNegativeButton(negative.text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { webView.loadUrl("javascript:" + negative.action); } }); builder.setNeutralButton(neutral.text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { webView.loadUrl("javascript:" + neutral.action); } }); break; } default:{ return false; } } builder.create().show(); sShowing = true; return true; } @Keep static class Button { String text; String action; public Button() {} } @Keep static class Data { String title; String message; List<Button> buttons = new ArrayList<>(); public Data(){} public boolean valid() { if (TextUtils.isEmpty(message)) { return false; } if (null == buttons || buttons.size() == 0) { return false; } return true; } } }
2,919
498
<gh_stars>100-1000 package com.yheriatovych.reductor.example.reductor.filter; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.example.model.NotesFilter; @ActionCreator public interface FilterActions { String SET_FILTER = "SET_FILTER"; @ActionCreator.Action(SET_FILTER) Action setFilter(NotesFilter filter); }
140
4,238
<reponame>khanhgithead/grr #!/usr/bin/env python from absl import app # pylint: disable=unused-import from grr_response_client.vfs_handlers.ntfs_test_lib import NTFSNativeWindowsTest from grr_response_client.vfs_handlers.ntfs_test_lib import NTFSTest # pylint: enable=unused-import from grr.test_lib import test_lib def main(argv): test_lib.main(argv) if __name__ == "__main__": app.run(main)
159
1,324
<reponame>ahanmal/EKAlgorithms<filename>EKAlgorithms/iOS/NSObject+EKComparisonForIOS.h<gh_stars>1000+ // // Created by ASPCartman on 26/08/14. // #if TARGET_OS_IPHONE @interface NSObject (EKComparisonForIOS) - (BOOL)isEqualTo:(id)obj; @end #endif
113
326
<filename>scala/unstable/defs.bzl<gh_stars>100-1000 """ Starlark rules for building Scala projects. These are the core rules under active development. Their APIs are not guaranteed stable and we anticipate some breaking changes. We do not recommend using these APIs for production codebases. Instead, use the stable rules exported by scala.bzl: ``` load( "@io_bazel_rules_scala//scala:scala.bzl", "scala_library", "scala_binary", "scala_test" ) ``` """ load( "@io_bazel_rules_scala//scala/private:rules/scala_binary.bzl", _make_scala_binary = "make_scala_binary", ) load( "@io_bazel_rules_scala//scala/private:rules/scala_library.bzl", _make_scala_library = "make_scala_library", ) load( "@io_bazel_rules_scala//scala/private:rules/scala_test.bzl", _make_scala_test = "make_scala_test", ) make_scala_library = _make_scala_library make_scala_binary = _make_scala_binary make_scala_test = _make_scala_test scala_library = _make_scala_library() scala_binary = _make_scala_binary() scala_test = _make_scala_test()
414
713
package org.infinispan.commands.irac; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.concurrent.CompletionStage; import org.infinispan.commands.remote.BaseRpcCommand; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSetsExternalization; import org.infinispan.factories.ComponentRegistry; import org.infinispan.util.ByteString; import org.infinispan.util.concurrent.CompletableFutures; /** * Requests the state for a given segments. * * @author <NAME> * @since 11.0 */ public class IracRequestStateCommand extends BaseRpcCommand { public static final byte COMMAND_ID = 121; private IntSet segments; @SuppressWarnings("unused") public IracRequestStateCommand() { super(null); } public IracRequestStateCommand(ByteString cacheName) { super(cacheName); } public IracRequestStateCommand(ByteString cacheName, IntSet segments) { super(cacheName); this.segments = segments; } @Override public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable { registry.getIracManager().wired().requestState(getOrigin(), segments); return CompletableFutures.completedNull(); } @Override public byte getCommandId() { return COMMAND_ID; } @Override public boolean isReturnValueExpected() { return false; } @Override public void writeTo(ObjectOutput output) throws IOException { IntSetsExternalization.writeTo(output, segments); } @Override public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { this.segments = IntSetsExternalization.readFrom(input); } @Override public String toString() { return "IracRequestStateCommand{" + "segments=" + segments + ", cacheName=" + cacheName + '}'; } }
659
2,443
// Copyright (c) 2015-2019 The HomeKit ADK Contributors // // Licensed under the Apache License, Version 2.0 (the “License”); // you may not use this file except in compliance with the License. // See [CONTRIBUTORS.md] for the list of HomeKit ADK project authors. #ifndef HAP_LEGACY_IMPORT_H #define HAP_LEGACY_IMPORT_H #ifdef __cplusplus extern "C" { #endif #include "HAP.h" #if __has_feature(nullability) #pragma clang assume_nonnull begin #endif /** * Device ID of an accessory server. */ typedef struct HAP_ATTRIBUTE_GCC(packed) { /** * Device ID. */ uint8_t bytes[6]; } HAPAccessoryServerDeviceID; /** * Imports a device ID into an un-provisioned key-value store. * This is useful to import legacy settings from a different HomeKit SDK. * * - This function must no longer be called after the initial HAPAccessoryServerCreate call. * * @param keyValueStore Un-provisioned key-value store. * @param deviceID DeviceID of the accessory server. * * @return kHAPError_None If successful. * @return kHAPError_Unknown If an error occurred while accessing the key-value store. */ HAP_ATTRIBUTE_GCC(warn_unused_result) HAPError HAPLegacyImportDeviceID(HAPPlatformKeyValueStore* keyValueStore, const HAPAccessoryServerDeviceID* deviceID); /** * Imports a configuration number into an un-provisioned key-value store. * This is useful to import legacy settings from a different HomeKit SDK. * * - This function must no longer be called after the initial HAPAccessoryServerCreate call. * * @param keyValueStore Un-provisioned key-value store. * @param configurationNumber Configuration number. * * @return kHAPError_None If successful. * @return kHAPError_Unknown If an error occurred while accessing the key-value store. */ HAP_ATTRIBUTE_GCC(warn_unused_result) HAPError HAPLegacyImportConfigurationNumber(HAPPlatformKeyValueStore* keyValueStore, uint32_t configurationNumber); /** * Ed25519 long-term secret key of an accessory server. */ typedef struct HAP_ATTRIBUTE_GCC(packed) { /** * Ed25519 long-term secret key. */ uint8_t bytes[32]; } HAPAccessoryServerLongTermSecretKey; /** * Imports a Ed25519 long-term secret key into an un-provisioned key-value store. * This is useful to import legacy settings from a different HomeKit SDK. * * - This function must no longer be called after the initial HAPAccessoryServerCreate call. * * @param keyValueStore Un-provisioned key-value store. * @param longTermSecretKey Long-term secret key of the accessory server. * * @return kHAPError_None If successful. * @return kHAPError_Unknown If an error occurred while accessing the key-value store. */ HAP_ATTRIBUTE_GCC(warn_unused_result) HAPError HAPLegacyImportLongTermSecretKey( HAPPlatformKeyValueStore* keyValueStore, const HAPAccessoryServerLongTermSecretKey* longTermSecretKey); /** * Imports an unsuccessful authentication attempts counter into an un-provisioned key-value store. * This is useful to import legacy settings from a different HomeKit SDK. * * - This function must no longer be called after the initial HAPAccessoryServerCreate call. * * @param keyValueStore Un-provisioned key-value store. * @param numAuthAttempts Unsuccessful authentication attempts counter. * * @return kHAPError_None If successful. * @return kHAPError_Unknown If an error occurred while accessing the key-value store. */ HAP_ATTRIBUTE_GCC(warn_unused_result) HAPError HAPLegacyImportUnsuccessfulAuthenticationAttemptsCounter( HAPPlatformKeyValueStore* keyValueStore, uint8_t numAuthAttempts); /** * Pairing identifier of a paired controller. */ typedef struct HAP_ATTRIBUTE_GCC(packed) { /** * Buffer containing pairing identifier. */ uint8_t bytes[36]; /** * Number of used bytes in buffer. */ size_t numBytes; } HAPControllerPairingIdentifier; /** * Public key of a paired controller. */ typedef struct HAP_ATTRIBUTE_GCC(packed) { /** * Public key. */ uint8_t bytes[32]; } HAPControllerPublicKey; /** * Imports a controller pairing into an un-provisioned key-value store. * This is useful to import legacy settings from a different HomeKit SDK. * * - This function must no longer be called after the initial HAPAccessoryServerCreate call. * * @param keyValueStore Un-provisioned key-value store. * @param pairingIndex Key-value store pairing index. 0 ..< Max number of pairings that will be supported. * @param pairingIdentifier HomeKit pairing identifier. * @param publicKey Ed25519 long-term public key of the paired controller. * @param isAdmin Whether or not the added controller has admin permissions. * * @return kHAPError_None If successful. * @return kHAPError_Unknown If an error occurred while accessing the key-value store. */ HAP_ATTRIBUTE_GCC(warn_unused_result) HAPError HAPLegacyImportControllerPairing( HAPPlatformKeyValueStore* keyValueStore, HAPPlatformKeyValueStoreKey pairingIndex, const HAPControllerPairingIdentifier* pairingIdentifier, const HAPControllerPublicKey* publicKey, bool isAdmin); #if __has_feature(nullability) #pragma clang assume_nonnull end #endif #ifdef __cplusplus } #endif #endif
1,890
322
/* portfwd.c * * Copyright (C) 2014-2020 wolfSSL Inc. * * This file is part of wolfSSH. * * wolfSSH 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. * * wolfSSH 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 wolfSSH. If not, see <http://www.gnu.org/licenses/>. */ #define WOLFSSH_TEST_CLIENT #define WOLFSSH_TEST_SERVER #include <stdio.h> #ifdef HAVE_TERMIOS_H #include <termios.h> #endif #include <errno.h> #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #include <wolfssh/ssh.h> #include <wolfssh/test.h> #include <wolfssh/port.h> #include <wolfssl/wolfcrypt/ecc.h> #include "examples/portfwd/wolfssh_portfwd.h" /* The portfwd tool will be a client or server in the port forwarding * interaction. * * The portfwd client will connect to an SSH server and request a tunnel. * The client acts like a server for the local user application. It forwards * the packets received to the SSH server who will then forward the packet * to its local application server. * * The portfwd server will listen for SSH connections, and when it receives * one will only accept forward requests from the connection. All data for * the forwarding channel are sent to the local application server and * data from the server is forwarded to the client. */ #define INVALID_FWD_PORT 0 static const char defaultFwdFromHost[] = "0.0.0.0"; static inline int max(int a, int b) { return (a > b) ? a : b; } static void ShowUsage(void) { printf("portfwd %s\n" " -? display this help and exit\n" " -h <host> host to connect to, default %s\n" " -p <num> port to connect on, default %u\n" " -u <username> username to authenticate as (REQUIRED)\n" " -P <password> password for username, prompted if omitted\n" " -F <host> host to forward from, default %s\n" " -f <num> host port to forward from (REQUIRED)\n" " -T <host> host to forward to, default to host\n" " -t <num> port to forward to (REQUIRED)\n", LIBWOLFSSH_VERSION_STRING, wolfSshIp, wolfSshPort, defaultFwdFromHost); } static int SetEcho(int on) { #ifndef USE_WINDOWS_API static int echoInit = 0; static struct termios originalTerm; if (!echoInit) { if (tcgetattr(STDIN_FILENO, &originalTerm) != 0) { printf("Couldn't get the original terminal settings.\n"); return -1; } echoInit = 1; } if (on) { if (tcsetattr(STDIN_FILENO, TCSANOW, &originalTerm) != 0) { printf("Couldn't restore the terminal settings.\n"); return -1; } } else { struct termios newTerm; memcpy(&newTerm, &originalTerm, sizeof(struct termios)); newTerm.c_lflag &= ~ECHO; newTerm.c_lflag |= (ICANON | ECHONL); if (tcsetattr(STDIN_FILENO, TCSANOW, &newTerm) != 0) { printf("Couldn't turn off echo.\n"); return -1; } } #else static int echoInit = 0; static DWORD originalTerm; HANDLE stdinHandle = GetStdHandle(STD_INPUT_HANDLE); if (!echoInit) { if (GetConsoleMode(stdinHandle, &originalTerm) == 0) { printf("Couldn't get the original terminal settings.\n"); return -1; } echoInit = 1; } if (on) { if (SetConsoleMode(stdinHandle, originalTerm) == 0) { printf("Couldn't restore the terminal settings.\n"); return -1; } } else { DWORD newTerm = originalTerm; newTerm &= ~ENABLE_ECHO_INPUT; if (SetConsoleMode(stdinHandle, newTerm) == 0) { printf("Couldn't turn off echo.\n"); return -1; } } #endif return 0; } byte userPassword[256]; static int wsUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) { const char* defaultPassword = (const char*)ctx; word32 passwordSz; int ret = WOLFSSH_USERAUTH_SUCCESS; (void)authType; if (defaultPassword != NULL) { passwordSz = (word32)strlen(defaultPassword); memcpy(userPassword, defaultPassword, passwordSz); } else { printf("Password: "); SetEcho(0); if (WFGETS((char*)userPassword, sizeof(userPassword), stdin) == NULL) { printf("Getting password failed.\n"); ret = WOLFSSH_USERAUTH_FAILURE; } else { char* c = strpbrk((char*)userPassword, "\r\n");; if (c != NULL) *c = '\0'; passwordSz = (word32)strlen((const char*)userPassword); } SetEcho(1); #ifdef USE_WINDOWS_API printf("\r\n"); #endif } if (ret == WOLFSSH_USERAUTH_SUCCESS) { authData->sf.password.password = <PASSWORD>; authData->sf.password.passwordSz = <PASSWORD>; } return ret; } static int wsPublicKeyCheck(const byte* pubKey, word32 pubKeySz, void* ctx) { printf("Sample public key check callback\n" " public key = %p\n" " public key size = %u\n" " ctx = %s\n", pubKey, pubKeySz, (const char*)ctx); return 0; } /* * fwdFromHost - address to bind the local listener socket to (default: any) * fwdFromHostPort - port number to bind the local listener socket to * fwdToHost - address to tell the remote peer to connect to on behalf of the * client (actual server address) * fwdToHostPort - port number to tell the remote peer to connect to on behalf * of the client (actual server port) * host - peer SSH server address to connect to * hostPort - peer SSH server port number to connect to */ THREAD_RETURN WOLFSSH_THREAD portfwd_worker(void* args) { WOLFSSH* ssh; WOLFSSH_CTX* ctx; char* host = (char*)wolfSshIp; word16 port = wolfSshPort; word16 fwdFromPort = INVALID_FWD_PORT; word16 fwdToPort = INVALID_FWD_PORT; const char* fwdFromHost = defaultFwdFromHost; const char* fwdToHost = NULL; const char* username = NULL; const char* password = NULL; SOCKADDR_IN_T hostAddr; socklen_t hostAddrSz = sizeof(hostAddr); SOCKET_T sshFd; SOCKADDR_IN_T fwdFromHostAddr; socklen_t fwdFromHostAddrSz = sizeof(fwdFromHostAddr); SOCKET_T listenFd; SOCKET_T appFd = -1; int argc = ((func_args*)args)->argc; char** argv = ((func_args*)args)->argv; fd_set templateFds; fd_set rxFds; fd_set errFds; int nFds; int ret; int ch; int appFdSet = 0; struct timeval to; WOLFSSH_CHANNEL* fwdChannel = NULL; byte buffer[4096]; word32 bufferSz = sizeof(buffer); word32 bufferUsed = 0; ((func_args*)args)->return_code = 0; while ((ch = mygetopt(argc, argv, "?f:h:p:t:u:F:P:T:")) != -1) { switch (ch) { case 'h': host = myoptarg; break; case 'f': fwdFromPort = (word16)atoi(myoptarg); break; case 'p': port = (word16)atoi(myoptarg); #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API) if (port == 0) err_sys("port number cannot be 0"); #endif break; case 't': fwdToPort = (word16)atoi(myoptarg); break; case 'u': username = myoptarg; break; case 'F': fwdFromHost = myoptarg; break; case 'P': password = <PASSWORD>; break; case 'T': fwdToHost = myoptarg; break; case '?': ShowUsage(); exit(EXIT_SUCCESS); default: ShowUsage(); exit(MY_EX_USAGE); } } myoptind = 0; if (username == NULL) err_sys("client requires a username parameter."); if (fwdToPort == INVALID_FWD_PORT) err_sys("requires a port to forward to"); if (fwdFromPort == INVALID_FWD_PORT) err_sys("requires a port to forward from"); if (fwdToHost == NULL) fwdToHost = host; printf("portfwd options\n" " * ssh host: %s:%u\n" " * username: %s\n" " * password: <PASSWORD>" " * forward from: %s:%u\n" " * forward to: %s:%u\n", host, port, username, password, fwdFromHost, fwdFromPort, fwdToHost, fwdToPort); ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL); if (ctx == NULL) err_sys("couldn't create the ssh client"); if (((func_args*)args)->user_auth == NULL) wolfSSH_SetUserAuth(ctx, wsUserAuth); else wolfSSH_SetUserAuth(ctx, ((func_args*)args)->user_auth); ssh = wolfSSH_new(ctx); if (ssh == NULL) err_sys("Couldn't create wolfSSH session."); if (password != NULL) wolfSSH_SetUserAuthCtx(ssh, (void*)password); wolfSSH_CTX_SetPublicKeyCheck(ctx, wsPublicKeyCheck); wolfSSH_SetPublicKeyCheckCtx(ssh, (void*)"You've been sampled."); ret = wolfSSH_SetUsername(ssh, username); if (ret != WS_SUCCESS) err_sys("Couldn't set the username."); build_addr(&hostAddr, host, port); build_addr(&fwdFromHostAddr, fwdFromHost, fwdFromPort); tcp_socket(&sshFd); /* Socket to SSH peer. */ tcp_socket(&listenFd); /* Either receive from client application or connect to server application. */ tcp_listen(&listenFd, &fwdFromPort, 1); printf("Connecting to the SSH server...\n"); ret = connect(sshFd, (const struct sockaddr *)&hostAddr, hostAddrSz); if (ret != 0) err_sys("Couldn't connect to server."); ret = wolfSSH_set_fd(ssh, (int)sshFd); if (ret != WS_SUCCESS) err_sys("Couldn't set the session's socket."); ret = wolfSSH_connect(ssh); if (ret != WS_SUCCESS) err_sys("Couldn't connect SFTP"); FD_ZERO(&templateFds); FD_SET(sshFd, &templateFds); FD_SET(listenFd, &templateFds); nFds = max(sshFd, listenFd) + 1; for (;;) { rxFds = templateFds; errFds = templateFds; to.tv_sec = 1; to.tv_usec = 0; ret = select(nFds, &rxFds, NULL, &errFds, &to); if (ret == 0) { ret = wolfSSH_SendIgnore(ssh, NULL, 0); if (ret != WS_SUCCESS) err_sys("Couldn't send an ignore message."); continue; } else if (ret < 0) err_sys("select failed\n"); if ((appFdSet && FD_ISSET(appFd, &errFds)) || FD_ISSET(sshFd, &errFds) || FD_ISSET(listenFd, &errFds)) { err_sys("some socket had an error"); } if (appFdSet && FD_ISSET(appFd, &rxFds)) { int rxd; rxd = (int)recv(appFd, buffer + bufferUsed, bufferSz - bufferUsed, 0); if (rxd > 0) bufferUsed += rxd; else break; } if (FD_ISSET(sshFd, &rxFds)) { word32 channelId = 0; ret = wolfSSH_worker(ssh, &channelId); if (ret == WS_CHAN_RXD) { WOLFSSH_CHANNEL* readChannel; bufferSz = sizeof(buffer); readChannel = wolfSSH_ChannelFind(ssh, channelId, WS_CHANNEL_ID_SELF); ret = (readChannel == NULL) ? WS_INVALID_CHANID : WS_SUCCESS; if (ret == WS_SUCCESS) ret = wolfSSH_ChannelRead(readChannel, buffer, bufferSz); if (ret > 0) { bufferSz = (word32)ret; if (appFd != -1) { ret = (int)send(appFd, buffer, bufferSz, 0); if (ret != (int)bufferSz) break; } } } } if (!appFdSet && FD_ISSET(listenFd, &rxFds)) { appFd = accept(listenFd, (struct sockaddr*)&fwdFromHostAddr, &fwdFromHostAddrSz); if (appFd < 0) break; FD_SET(appFd, &templateFds); nFds = appFd + 1; appFdSet = 1; fwdChannel = wolfSSH_ChannelFwdNew(ssh, fwdToHost, fwdToPort, fwdFromHost, fwdFromPort); } if (bufferUsed > 0) { ret = wolfSSH_ChannelSend(fwdChannel, buffer, bufferUsed); if (ret > 0) bufferUsed -= ret; } } ret = wolfSSH_shutdown(ssh); if (ret != WS_SUCCESS) err_sys("Closing port forward stream failed."); WCLOSESOCKET(sshFd); WCLOSESOCKET(listenFd); WCLOSESOCKET(appFd); wolfSSH_free(ssh); wolfSSH_CTX_free(ctx); #if defined(HAVE_ECC) && defined(FP_ECC) && defined(HAVE_THREAD_LS) wc_ecc_fp_free(); /* free per thread cache */ #endif return 0; } #ifndef NO_MAIN_DRIVER int main(int argc, char** argv) { func_args args; args.argc = argc; args.argv = argv; args.return_code = 0; args.user_auth = NULL; WSTARTTCP(); #ifdef DEBUG_WOLFSSH wolfSSH_Debugging_ON(); #endif wolfSSH_Init(); ChangeToWolfSshRoot(); portfwd_worker(&args); wolfSSH_Cleanup(); return args.return_code; } int myoptind = 0; char* myoptarg = NULL; #endif /* NO_MAIN_DRIVER */
6,837
994
// // system_executor.hpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2019 <NAME> (chris at kohlhoff dot com) // // 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) // #ifndef NET_TS_SYSTEM_EXECUTOR_HPP #define NET_TS_SYSTEM_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <experimental/__net_ts/detail/config.hpp> #include <experimental/__net_ts/detail/push_options.hpp> namespace std { namespace experimental { namespace net { inline namespace v1 { class system_context; /// An executor that uses arbitrary threads. /** * The system executor represents an execution context where functions are * permitted to run on arbitrary threads. The post() and defer() functions * schedule the function to run on an unspecified system thread pool, and * dispatch() invokes the function immediately. */ class system_executor { public: /// Obtain the underlying execution context. system_context& context() const NET_TS_NOEXCEPT; /// Inform the executor that it has some outstanding work to do. /** * For the system executor, this is a no-op. */ void on_work_started() const NET_TS_NOEXCEPT { } /// Inform the executor that some work is no longer outstanding. /** * For the system executor, this is a no-op. */ void on_work_finished() const NET_TS_NOEXCEPT { } /// Request the system executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object will always be executed inside this function. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void dispatch(NET_TS_MOVE_ARG(Function) f, const Allocator& a) const; /// Request the system executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object will never be executed inside this function. * Instead, it will be scheduled to run on an unspecified system thread pool. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void post(NET_TS_MOVE_ARG(Function) f, const Allocator& a) const; /// Request the system executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object will never be executed inside this function. * Instead, it will be scheduled to run on an unspecified system thread pool. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void defer(NET_TS_MOVE_ARG(Function) f, const Allocator& a) const; /// Compare two executors for equality. /** * System executors always compare equal. */ friend bool operator==(const system_executor&, const system_executor&) NET_TS_NOEXCEPT { return true; } /// Compare two executors for inequality. /** * System executors always compare equal. */ friend bool operator!=(const system_executor&, const system_executor&) NET_TS_NOEXCEPT { return false; } }; } // inline namespace v1 } // namespace net } // namespace experimental } // namespace std #include <experimental/__net_ts/detail/pop_options.hpp> #include <experimental/__net_ts/impl/system_executor.hpp> #endif // NET_TS_SYSTEM_EXECUTOR_HPP
1,339
1,564
package org.modelmapper.functional.merge; import static org.testng.Assert.assertEquals; import org.modelmapper.AbstractTest; import org.modelmapper.Converter; import org.modelmapper.PropertyMap; import org.modelmapper.spi.MappingContext; import org.testng.annotations.Test; @Test public class MergeSourcePropertiesTest extends AbstractTest { static class Source { private int year; private int month; private int day; public Source(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } } static class Destination { private String date; public String getDate() { return date; } public void setDate(String date) { this.date = date; } } public void shouldMergeSourceProperties() { final Converter<Source, String> converter = new Converter<Source, String>() { public String convert(MappingContext<Source, String> context) { return String.format("%04d/%02d/%02d", context.getSource().getYear(), context.getSource().getMonth(), context.getSource().getDay()); } }; modelMapper.addMappings(new PropertyMap<Source, Destination>() { protected void configure() { using(converter).map(source).setDate(null); } }); Destination destination = modelMapper.map(new Source(2000, 1, 1), Destination.class); assertEquals(destination.getDate(), "2000/01/01"); } }
669
328
<gh_stars>100-1000 String GetShapeName(Shape s) { if (s instanceof Square) { return "Square"; } else if (s instanceof Circle) { return "Circle"; } else { return "Other"; } }
76
820
<gh_stars>100-1000 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """Process Entity class.""" from datetime import datetime from typing import Any, Mapping, Optional from ..._version import VERSION from ...common.utility import export from .entity import Entity from .account import Account from .entity_enums import ElevationToken from .file import File from .host import Host from .host_logon_session import HostLogonSession __version__ = VERSION __author__ = "<NAME>" # pylint: disable=invalid-name, too-many-instance-attributes @export class Process(Entity): """ Process Entity class. Attributes ---------- ProcessId : str Process ProcessId CommandLine : str Process CommandLine ElevationToken : str Process ElevationToken CreationTimeUtc : datetime Process CreationTimeUtc ImageFile : File Process ImageFile Account : Account Process Account ParentProcess : Process Process ParentProcess Host : Host Process Host LogonSession : HostLogonSession Process LogonSession """ ID_PROPERTIES = ["ProcessId", "ImageFile", "CreationTimeUtc", "CommandLine"] def __init__( self, src_entity: Mapping[str, Any] = None, src_event: Mapping[str, Any] = None, role="new", **kwargs, ): """ Create a new instance of the entity type. Parameters ---------- src_entity : Mapping[str, Any], optional Create entity from existing entity or other mapping object that implements entity properties. (the default is None) src_event : Mapping[str, Any], optional Create entity from event properties (the default is None) role : str, optional 'new' or 'parent' - only relevant if the entity is being constructed from an event. (the default is 'new') Other Parameters ---------------- kwargs : Dict[str, Any] Supply the entity properties as a set of kw arguments. """ self.ProcessId: Optional[str] = None self.CommandLine: Optional[str] = None self.ElevationToken: Optional[ElevationToken] = None self.CreationTimeUtc: datetime = datetime.min self.ImageFile: Optional[File] = None self.Account: Optional[Account] = None self.ParentProcess: Optional[Process] = None self.Host: Optional[Host] = None self.LogonSession: Optional[HostLogonSession] = None super().__init__(src_entity=src_entity, **kwargs) # pylint: disable=locally-disabled, line-too-long if src_event is not None: self._create_from_event(src_event, role) def _create_from_event(self, src_event, role): if role == "new": self.ProcessId = src_event.get("NewProcessId") self.CommandLine = src_event.get("CommandLine") if "TimeCreatedUtc" in src_event: self.CreationTimeUtc = src_event["TimeCreatedUtc"] elif "TimeGenerated" in src_event: self.CreationTimeUtc = src_event["TimeGenerated"] self.ImageFile = File(src_event=src_event, role="new") self.Account = Account(src_event=src_event, role="subject") if "ParentProcessName" in src_event or "ProcessName" in src_event: parent = Process(src_event=src_event, role="parent") self.ParentProcess = parent # Linux properties self.success = src_event.get("success") self.audit_user = src_event.get("audit_user") self.auid = src_event.get("auid") self.group = src_event.get("group") self.gid = src_event.get("gid") self.effective_user = src_event.get("effective_user") self.euid = src_event.get("euid") self.effective_group = src_event.get("effective_group") self.egid = src_event.get("effective_group") self.cwd = src_event.get("cwd") self.name = src_event.get("cwd") else: self.ProcessId = src_event.get("ProcessId") self.ImageFile = File(src_event=src_event, role="parent") @property def ProcessName(self) -> Optional[str]: # noqa: N802 """Return the name of the process file.""" file = self["ImageFile"] return file.Name if file else None @property def ProcessFilePath(self) -> Optional[str]: # noqa: N802 """Return the name of the process file path.""" file = self.ImageFile return file.FullPath if file else None @property def description_str(self) -> str: """Return Entity Description.""" if self.ProcessFilePath: return f"{self.ProcessFilePath}: {self.CommandLine}" return self.__class__.__name__ @property def name_str(self) -> str: """Return Entity Name.""" if self.ImageFile: return f"{self.ImageFile.name_str}[pid:{self.ProcessId}]" return self.ImageFile.name_str if self.ImageFile else super().name_str _entity_schema = { # ProcessId (type System.String) "ProcessId": None, # CommandLine (type System.String) "CommandLine": None, # ElevationToken (type System.Nullable`1 # [Microsoft.Azure.Security.Detection # .AlertContracts.V3.Entities.ElevationToken]) "ElevationToken": None, # CreationTimeUtc (type System.Nullable`1[System.DateTime]) "CreationTimeUtc": None, # ImageFile (type Microsoft.Azure.Security.Detection # .AlertContracts.V3.Entities.File) "ImageFile": "File", # Account (type Microsoft.Azure.Security.Detection # .AlertContracts.V3.Entities.Account) "Account": "Account", # ParentProcess (type Microsoft.Azure.Security.Detection.AlertContracts # .V3.Entities.Process) "ParentProcess": "Process", # Host (type Microsoft.Azure.Security.Detection # .AlertContracts.V3.Entities.Host) "Host": "Host", # Host (type Microsoft.Azure.Security.Detection # .AlertContracts.V3.Entities.HostLogonSession) "LogonSession": "HostLogonSession", "TimeGenerated": None, "StartTime": None, "EndTime": None, }
2,753
1,592
/*************************************************************************** * Copyright (c) <NAME>, <NAME> and <NAME> * * Copyright (c) QuantStack * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include "test_common.hpp" #include "test_common_macros.hpp" #include <cstddef> #include "xtensor/xarray.hpp" #include "xtensor/xtensor.hpp" #include "xtensor/xoptional_assembly.hpp" namespace xt { template <class C, std::size_t> struct redim_container { using type = C; }; template <class T, std::size_t N, layout_type L, std::size_t NN> struct redim_container<xtensor<T, N, L>, NN> { using type = xtensor<T, NN, L>; }; template <class C, std::size_t N> using redim_container_t = typename redim_container<C, N>::type; namespace xop_test { template <class C, class T> struct rebind_container; template <class T, class NT> struct rebind_container<xarray<T>, NT> { using type = xarray<NT>; }; template <class T, std::size_t N, class NT> struct rebind_container<xtensor<T, N>, NT> { using type = xtensor<NT, N>; }; template <class C, class T> using rebind_container_t = typename rebind_container<C, T>::type; } class my_double { public: my_double(double d = 0.) : m_value(d) {} double& operator+=(double rhs) { m_value += rhs; return m_value; } private: double m_value; }; double operator+(double rhs, my_double lhs) { my_double tmp(lhs); return tmp += rhs; } template <class C> class operation : public ::testing::Test { public: using storage_type = C; }; template <class T> struct int_rebind; template <> struct int_rebind<xarray<double>> { using type = xarray<int>; }; template <> struct int_rebind<xtensor<double, 2>> { using type = xtensor<int, 2>; }; template <class T> using int_rebind_t = typename int_rebind<T>::type; struct vtype { double a = 0; size_t b = 0; explicit operator double() const { return a; } }; using xarray_type = xarray<double>; using xtensor_2_type = xtensor<double, 2>; #define XOPERATION_TEST_TYPES xarray_type, xtensor_2_type TEST_SUITE("operation") { TEST_CASE_TEMPLATE("plus", TypeParam, XOPERATION_TEST_TYPES) { using shape_type = typename TypeParam::shape_type; shape_type shape = {3, 2}; TypeParam a(shape, 4.5); double ref = +(a(0, 0)); double actual = (+a)(0, 0); EXPECT_EQ(ref, actual); } TEST_CASE_TEMPLATE("minus", TypeParam, XOPERATION_TEST_TYPES) { using shape_type = typename TypeParam::shape_type; shape_type shape = {3, 2}; TypeParam a(shape, 4.5); double ref = -(a(0, 0)); double actual = (-a)(0, 0); EXPECT_EQ(ref, actual); } TEST_CASE_TEMPLATE("add", TypeParam, XOPERATION_TEST_TYPES) { using shape_type = typename TypeParam::shape_type; shape_type shape = {3, 2}; TypeParam a(shape, 4.5); TypeParam b(shape, 1.3); EXPECT_EQ((a + b)(0, 0), a(0, 0) + b(0, 0)); double sb = 1.2; EXPECT_EQ((a + sb)(0, 0), a(0, 0) + sb); double sa = 4.6; EXPECT_EQ((sa + b)(0, 0), sa + b(0, 0)); } TEST_CASE_TEMPLATE("subtract", TypeParam, XOPERATION_TEST_TYPES) { using shape_type = typename TypeParam::shape_type; shape_type shape = {3, 2}; TypeParam a(shape, 4.5); TypeParam b(shape, 1.3); EXPECT_EQ((a - b)(0, 0), a(0, 0) - b(0, 0)); double sb = 1.2; EXPECT_EQ((a - sb)(0, 0), a(0, 0) - sb); double sa = 4.6; EXPECT_EQ((sa - b)(0, 0), sa - b(0, 0)); } TEST_CASE_TEMPLATE("multiply", TypeParam, XOPERATION_TEST_TYPES) { using shape_type = typename TypeParam::shape_type; shape_type shape = {3, 2}; TypeParam a(shape, 4.5); TypeParam b(shape, 1.3); EXPECT_EQ((a * b)(0, 0), a(0, 0) * b(0, 0)); double sb = 1.2; EXPECT_EQ((a * sb)(0, 0), a(0, 0) * sb); double sa = 4.6; EXPECT_EQ((sa * b)(0, 0), sa * b(0, 0)); } TEST_CASE_TEMPLATE("divide", TypeParam, XOPERATION_TEST_TYPES) { using shape_type = typename TypeParam::shape_type; shape_type shape = {3, 2}; TypeParam a(shape, 4.5); TypeParam b(shape, 1.3); EXPECT_EQ((a / b)(0, 0), a(0, 0) / b(0, 0)); double sb = 1.2; EXPECT_EQ((a / sb)(0, 0), a(0, 0) / sb); double sa = 4.6; EXPECT_EQ((sa / b)(0, 0), sa / b(0, 0)); } TEST_CASE_TEMPLATE("modulus", TypeParam, XOPERATION_TEST_TYPES) { using int_container = xop_test::rebind_container_t<TypeParam, int>; using shape_type = typename int_container::shape_type; shape_type shape = {3, 2}; int_container a(shape, 11); int_container b(shape, 3); EXPECT_EQ((a % b)(0, 0), a(0, 0) % b(0, 0)); int sb = 3; EXPECT_EQ((a % sb)(0, 0), a(0, 0) % sb); int sa = 11; EXPECT_EQ((sa % b)(0, 0), sa % b(0, 0)); } TEST_CASE_TEMPLATE("bitwise_and", TypeParam, XOPERATION_TEST_TYPES) { using int_tensor = int_rebind_t<TypeParam>; using shape_type = typename int_tensor::shape_type; shape_type shape = {3, 2}; int_tensor a(shape, 14); int_tensor b(shape, 15); EXPECT_EQ((a & b)(0, 0), a(0, 0) & b(0, 0)); int sb = 48; EXPECT_EQ((a & sb)(0, 0), a(0, 0) & sb); int sa = 24; EXPECT_EQ((sa & b)(0, 0), sa & b(0, 0)); } TEST_CASE_TEMPLATE("bitwise_or", TypeParam, XOPERATION_TEST_TYPES) { using int_tensor = int_rebind_t<TypeParam>; using shape_type = typename int_tensor::shape_type; shape_type shape = {3, 2}; int_tensor a(shape, 14); int_tensor b(shape, 15); EXPECT_EQ((a | b)(0, 0), a(0, 0) | b(0, 0)); int sb = 48; EXPECT_EQ((a | sb)(0, 0), a(0, 0) | sb); int sa = 24; EXPECT_EQ((sa | b)(0, 0), sa | b(0, 0)); } TEST_CASE_TEMPLATE("bitwise_xor", TypeParam, XOPERATION_TEST_TYPES) { using int_tensor = int_rebind_t<TypeParam>; using shape_type = typename int_tensor::shape_type; shape_type shape = {3, 2}; int_tensor a(shape, 14); int_tensor b(shape, 15); EXPECT_EQ((a ^ b)(0, 0), a(0, 0) ^ b(0, 0)); int sb = 48; EXPECT_EQ((a ^ sb)(0, 0), a(0, 0) ^ sb); int sa = 24; EXPECT_EQ((sa ^ b)(0, 0), sa ^ b(0, 0)); } TEST_CASE_TEMPLATE("bitwise_not", TypeParam, XOPERATION_TEST_TYPES) { using int_tensor = int_rebind_t<TypeParam>; using shape_type = typename int_tensor::shape_type; shape_type shape = {3, 2}; int_tensor a(shape, 15); EXPECT_EQ((~a)(0, 0), ~(a(0, 0))); } TEST_CASE_TEMPLATE("less", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using bool_container = xop_test::rebind_container_t<container_1d, bool>; container_1d a = {1, 2, 3, 4, 5}; bool_container expected = {1, 1, 1, 0, 0}; bool_container b = a < 4; EXPECT_EQ(expected, b); bool_container b2 = less(a, 4); EXPECT_EQ(expected, b2); } TEST_CASE_TEMPLATE("less_equal", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using bool_container = xop_test::rebind_container_t<container_1d, bool>; container_1d a = {1, 2, 3, 4, 5}; bool_container expected = {1, 1, 1, 1, 0}; bool_container b = a <= 4; EXPECT_EQ(expected, b); bool_container b2 = less_equal(a, 4); EXPECT_EQ(expected, b2); } TEST_CASE_TEMPLATE("greater", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using bool_container = xop_test::rebind_container_t<container_1d, bool>; container_1d a = {1, 2, 3, 4, 5}; bool_container expected = {0, 0, 0, 0, 1}; bool_container b = a > 4; EXPECT_EQ(expected, b); bool_container b2 = greater(a, 4); EXPECT_EQ(expected, b2); } TEST_CASE_TEMPLATE("greater_equal", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using bool_container = xop_test::rebind_container_t<container_1d, bool>; container_1d a = {1, 2, 3, 4, 5}; bool_container expected = {0, 0, 0, 1, 1}; bool_container b = a >= 4; EXPECT_EQ(expected, b); bool_container b2 = greater_equal(a, 4); EXPECT_EQ(expected, b2); } TEST_CASE_TEMPLATE("negate", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using bool_container = xop_test::rebind_container_t<container_1d, bool>; container_1d a = {1, 2, 3, 4, 5}; bool_container expected = {1, 1, 1, 0, 0}; bool_container b = !(a >= 4); EXPECT_EQ(expected, b); } TEST_CASE_TEMPLATE("equal", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using bool_container = xop_test::rebind_container_t<container_1d, bool>; container_1d a = {1, 2, 3, 4, 5}; bool_container expected = {0, 0, 0, 1, 0}; bool_container b = equal(a, 4); EXPECT_EQ(expected, b); container_1d other = {1, 2, 3, 0, 0}; bool_container b_2 = equal(a, other); bool_container expected_2 = {1, 1, 1, 0, 0}; EXPECT_EQ(expected_2, b_2); } TEST_CASE_TEMPLATE("not_equal", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using bool_container = xop_test::rebind_container_t<container_1d, bool>; container_1d a = {1, 2, 3, 4, 5}; bool_container expected = {1, 1, 1, 0, 1}; bool_container b = not_equal(a, 4); EXPECT_EQ(expected, b); container_1d other = {1, 2, 3, 0, 0}; bool_container b_2 = not_equal(a, other); bool_container expected_2 = {0, 0, 0, 1, 1}; EXPECT_EQ(expected_2, b_2); } TEST_CASE_TEMPLATE("logical_and", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using bool_container = xop_test::rebind_container_t<container_1d, bool>; bool_container a = {0, 0, 0, 1, 0}; bool_container expected = {0, 0, 0, 0, 0}; bool_container b = a && false; bool_container c = a && a; EXPECT_EQ(expected, b); EXPECT_EQ(c, a); } TEST_CASE_TEMPLATE("logical_or", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using bool_container = xop_test::rebind_container_t<container_1d, bool>; bool_container a = {0, 0, 0, 1, 0}; bool_container other = {0, 0, 0, 0, 0}; bool_container b = a || other; bool_container c = a || false; bool_container d = a || true; EXPECT_EQ(b, a); EXPECT_EQ(c, a); bool_container expected = {1, 1, 1, 1, 1}; EXPECT_EQ(expected, d); } TEST_CASE_TEMPLATE("any", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using int_container = xop_test::rebind_container_t<container_1d, int>; using int_container_2d = xop_test::rebind_container_t<TypeParam, int>; int_container a = {0, 0, 3}; EXPECT_EQ(true, any(a)); int_container_2d b = {{0, 0, 0}, {0, 0, 0}}; EXPECT_EQ(false, any(b)); } TEST_CASE_TEMPLATE("minimum", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using int_container = xop_test::rebind_container_t<container_1d, int>; int_container a = {0, 0, 3}; int_container b = {-1, 0, 10}; int_container expected = {-1, 0, 3}; EXPECT_TRUE(all(equal(minimum(a, b), expected))); } TEST_CASE_TEMPLATE("maximum", TypeParam, XOPERATION_TEST_TYPES) { using container_1d = redim_container_t<TypeParam, 1>; using int_container = xop_test::rebind_container_t<container_1d, int>; int_container a = {0, 0, 3}; int_container b = {-1, 0, 10}; int_container expected = {0, 0, 10}; int_container expected_2 = {0, 1, 10}; EXPECT_TRUE(all(equal(maximum(a, b), expected))); EXPECT_TRUE(all(equal(maximum(arange(0, 3), b), expected_2))); } TEST_CASE_TEMPLATE("amax", TypeParam, XOPERATION_TEST_TYPES) { using int_container_2d = xop_test::rebind_container_t<TypeParam, int>; using container_1d = redim_container_t<TypeParam, 1>; using int_container_1d = xop_test::rebind_container_t<container_1d, int>; int_container_2d a = {{0, 0, 3}, {1, 2, 10}}; EXPECT_EQ(10, amax(a)()); int_container_1d e1 = {1, 2, 10}; EXPECT_EQ(e1, amax(a, {0})); int_container_1d e2 = {3, 10}; EXPECT_EQ(e2, amax(a, {1})); } TEST_CASE_TEMPLATE("amin", TypeParam, XOPERATION_TEST_TYPES) { using int_container_2d = xop_test::rebind_container_t<TypeParam, int>; using container_1d = redim_container_t<TypeParam, 1>; using int_container_1d = xop_test::rebind_container_t<container_1d, int>; int_container_2d a = {{0, 0, 3}, {1, 2, 10}}; EXPECT_EQ(0, amin(a)()); int_container_1d e1 = {0, 0, 3}; EXPECT_EQ(e1, amin(a, {0})); int_container_1d e2 = {0, 1}; EXPECT_EQ(e2, amin(a, {1})); } TEST_CASE_TEMPLATE("all", TypeParam, XOPERATION_TEST_TYPES) { using int_container_2d = xop_test::rebind_container_t<TypeParam, int>; using container_1d = redim_container_t<TypeParam, 1>; using int_container_1d = xop_test::rebind_container_t<container_1d, int>; int_container_1d a = {1, 1, 3}; EXPECT_EQ(true, all(a)); int_container_2d b = {{0, 2, 1}, {2, 1, 0}}; EXPECT_EQ(false, all(b)); } TEST_CASE_TEMPLATE("all_layout", TypeParam, XOPERATION_TEST_TYPES) { xarray<int, layout_type::row_major> a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; xarray<int, layout_type::column_major> b = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; EXPECT_EQ(a(0, 1), b(0, 1)); EXPECT_TRUE(all(equal(a, b))); } TEST_CASE_TEMPLATE("nonzero", TypeParam, XOPERATION_TEST_TYPES) { using int_container_2d = xop_test::rebind_container_t<TypeParam, int>; using container_1d = redim_container_t<TypeParam, 1>; using int_container_1d = xop_test::rebind_container_t<container_1d, int>; using container_3d = redim_container_t<TypeParam, 3>; using bool_container = xop_test::rebind_container_t<container_3d, bool>; using shape_type = typename container_3d::shape_type; int_container_1d a = {1, 0, 3}; std::vector<std::vector<std::size_t>> expected = {{0, 2}}; EXPECT_EQ(expected, nonzero(a)); int_container_2d b = {{0, 2, 1}, {2, 1, 0}}; std::vector<std::vector<std::size_t>> expected_b = {{0, 0, 1, 1}, {1, 2, 0, 1}}; EXPECT_EQ(expected_b, nonzero(b)); auto c = equal(b, 0); std::vector<std::vector<std::size_t>> expected_c = {{0, 1}, {0, 2}}; EXPECT_EQ(expected_c, nonzero(c)); shape_type s = {3, 3, 3}; bool_container d(s); std::fill(d.begin(), d.end(), true); auto d_nz = nonzero(d); EXPECT_EQ(size_t(3), d_nz.size()); EXPECT_EQ(size_t(27 * 27 * 27), d_nz[0].size() * d_nz[1].size() * d_nz[2].size()); } TEST_CASE_TEMPLATE("where_only_condition", TypeParam, XOPERATION_TEST_TYPES) { using int_container_2d = xop_test::rebind_container_t<TypeParam, int>; int_container_2d a = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; std::vector<std::vector<std::size_t>> expected = {{0, 1, 2}, {0, 1, 2}}; EXPECT_EQ(expected, where(a)); } TEST_CASE_TEMPLATE("where", TypeParam, XOPERATION_TEST_TYPES) { TypeParam a = { { 1, 2, 3 },{ 0, 1, 0 },{ 0, 4, 1 } }; double b = 1.0; TypeParam res = where(a > b, b, a); TypeParam expected = { { 1, 1, 1 },{ 0, 1, 0 },{ 0, 1, 1 } }; EXPECT_EQ(expected, res); #ifdef XTENSOR_USE_XSIMD // This will fail to compile if simd is broken for conditional_ternary auto func = where(a > b, b, a); auto s = func.template load_simd<xsimd::aligned_mode>(0); (void)s; using assign_traits = xassign_traits<TypeParam, decltype(func)>; EXPECT_TRUE(assign_traits::simd_linear_assign()); #endif } TEST_CASE_TEMPLATE("where_optional", TypeParam, XOPERATION_TEST_TYPES) { using opt_type = xoptional_assembly<TypeParam, xtensor<bool, 2>>; auto missing = xtl::missing<double>(); opt_type a = { { 1, missing, 3 },{ 0, 1, 0 },{ missing, 4, 1 } }; double b = 1.0; opt_type res = where(a > b, b, a); opt_type expected = { { 1, missing, 1 },{ 0, 1, 0 },{ missing, 1, 1 } }; EXPECT_EQ(expected, res); opt_type res1 = where(true, a + 3, a); opt_type expected1 = { { 4, missing, 6 },{ 3, 4, 3 },{ missing, 7, 4 } }; EXPECT_EQ(expected1, res1); } TEST_CASE_TEMPLATE("where_cast", TypeParam, XOPERATION_TEST_TYPES) { using int_container_2d = xop_test::rebind_container_t<TypeParam, int>; int_container_2d a = {{0, 1, 0}, {3, 0, 5}}; double res1 = 1.2; TypeParam b = where(equal(a, 0.0), res1, 0.0); TypeParam expected = { {1.2, 0., 1.2}, {0., 1.2, 0.} }; EXPECT_EQ(b, expected); } TEST_CASE_TEMPLATE("argwhere", TypeParam, XOPERATION_TEST_TYPES) { using int_container_2d = xop_test::rebind_container_t<TypeParam, int>; using container_1d = redim_container_t<TypeParam, 1>; using int_container_1d = xop_test::rebind_container_t<container_1d, int>; using container_3d = redim_container_t<TypeParam, 3>; using bool_container = xop_test::rebind_container_t<container_3d, bool>; using shape_type = typename container_3d::shape_type; int_container_1d a = {1, 0, 3}; std::vector<xindex_type_t<typename int_container_1d::shape_type>> expected = {{0}, {2}}; EXPECT_EQ(expected, argwhere(a)); int_container_2d b = {{0, 2, 1}, {2, 1, 0}}; std::vector<xindex_type_t<typename int_container_2d::shape_type>> expected_b = {{0, 1}, {0, 2}, {1, 0}, {1, 1}}; EXPECT_EQ(expected_b, argwhere(b)); auto c = equal(b, 0); std::vector<xindex_type_t<typename int_container_2d::shape_type>> expected_c = {{0, 0}, {1, 2}}; EXPECT_EQ(expected_c, argwhere(c)); shape_type s = {3, 3, 3}; bool_container d(s); std::fill(d.begin(), d.end(), true); auto d_nz = argwhere(d); EXPECT_EQ(size_t(3 * 3 * 3), d_nz.size()); xindex_type_t<typename container_3d::shape_type> last_idx = {2, 2, 2}; EXPECT_EQ(last_idx, d_nz.back()); } TEST_CASE_TEMPLATE("cast", TypeParam, XOPERATION_TEST_TYPES) { using int_container_t = xop_test::rebind_container_t<TypeParam, int>; using shape_type = typename int_container_t::shape_type; shape_type shape = {3, 2}; int_container_t a(shape, 5); auto ref = static_cast<double>(a(0, 0)) / 2; auto actual = (cast<double>(a) / 2)(0, 0); EXPECT_EQ(ref, actual); } TEST_CASE_TEMPLATE("cast_custom_type", TypeParam, XOPERATION_TEST_TYPES) { using vtype_container_t = xop_test::rebind_container_t<TypeParam, vtype>; using shape_type = typename vtype_container_t::shape_type; shape_type shape = { 3, 2 }; vtype_container_t a(shape); auto ref = static_cast<double>(a(0, 0)); auto actual = (cast<double>(a))(0, 0); EXPECT_EQ(ref, actual); } TEST_CASE_TEMPLATE("mixed_arithmetic", TypeParam, XOPERATION_TEST_TYPES) { using int_container_t = xop_test::rebind_container_t<TypeParam, int>; TypeParam a = {{0., 1., 2.}, {3., 4., 5.}}; int_container_t b = {{0, 1, 2}, {3, 4, 5}}; int_container_t c = b; TypeParam res = a + (b + c); TypeParam expected = {{0., 3., 6.}, {9., 12., 15.}}; EXPECT_EQ(res, expected); } TEST_CASE_TEMPLATE("assign_traits", TypeParam, XOPERATION_TEST_TYPES) { TypeParam a = { { 0., 1., 2. },{ 3., 4., 5. } }; TypeParam b = { { 0., 1., 2. },{ 3., 4., 5. } }; SUBCASE("xarray<double> + xarray<double>") { auto fd = a + b; using assign_traits_double = xassign_traits<TypeParam, decltype(fd)>; #if XTENSOR_USE_XSIMD EXPECT_TRUE(assign_traits_double::simd_linear_assign()); #else // SFINAE on load_simd is broken on mingw when xsimd is disabled. This using // triggers the same error as the one caught by mingw. using return_type = decltype(fd.template load_simd<aligned_mode>(std::size_t(0))); EXPECT_FALSE(assign_traits_double::simd_linear_assign()); EXPECT_TRUE((std::is_same<return_type, double>::value)); #endif } SUBCASE("double * xarray<double>") { xscalar<double> sd = 2.; auto fsd = sd * a; using assign_traits_scalar_double = xassign_traits<TypeParam, decltype(fsd)>; #if XTENSOR_USE_XSIMD auto batch = fsd.template load_simd<double>(0); (void)batch; EXPECT_TRUE(assign_traits_scalar_double::simd_linear_assign()); #else using return_type = decltype(fsd.template load_simd<aligned_mode>(std::size_t(0))); EXPECT_FALSE(assign_traits_scalar_double::simd_linear_assign()); EXPECT_TRUE((std::is_same<return_type, double>::value)); #endif } SUBCASE("xarray<double> + xarray<int>") { using int_container_t = xop_test::rebind_container_t<TypeParam, int>; int_container_t c = { { 0, 1, 2 },{ 3, 4, 5 } }; auto fm = a + c; using assign_traits_mixed = xassign_traits<TypeParam, decltype(fm)>; #if XTENSOR_USE_XSIMD EXPECT_TRUE(assign_traits_mixed::simd_linear_assign()); #else using return_type = decltype(fm.template load_simd<aligned_mode>(std::size_t(0))); EXPECT_FALSE(assign_traits_mixed::simd_linear_assign()); EXPECT_TRUE((std::is_same<return_type, double>::value)); #endif } SUBCASE("int * xarray<double>") { xscalar<int> si = 2; auto fsm = si * a; using assign_traits_scalar_mixed = xassign_traits<TypeParam, decltype(fsm)>; #if XTENSOR_USE_XSIMD EXPECT_TRUE(assign_traits_scalar_mixed::simd_linear_assign()); #else using return_type = decltype(fsm.template load_simd<aligned_mode>(std::size_t(0))); EXPECT_FALSE(assign_traits_scalar_mixed::simd_linear_assign()); EXPECT_TRUE((std::is_same<return_type, double>::value)); #endif } SUBCASE("xarray<double> + xarray<char>") { using char_container_t = xop_test::rebind_container_t<TypeParam, char>; char_container_t d = { { 0, 1, 2 },{ 3, 4, 5 } }; auto fdc = a + d; using assign_traits_char_double = xassign_traits<TypeParam, decltype(fdc)>; #if XTENSOR_USE_XSIMD EXPECT_TRUE(assign_traits_char_double::simd_linear_assign()); #else using return_type = decltype(fdc.template load_simd<aligned_mode>(std::size_t(0))); EXPECT_FALSE(assign_traits_char_double::simd_linear_assign()); EXPECT_TRUE((std::is_same<return_type, double>::value)); #endif } SUBCASE("xarray<double> + xarray<my_double>") { using md_container_t = xop_test::rebind_container_t<TypeParam, my_double>; md_container_t d = { { 0, 1, 2 },{ 3, 4, 5 } }; auto fdm = a + d; using assign_traits_md_double = xassign_traits<TypeParam, decltype(fdm)>; #if XTENSOR_USE_XSIMD EXPECT_FALSE(assign_traits_md_double::simd_linear_assign()); #else using return_type = decltype(fdm.template load_simd<aligned_mode>(std::size_t(0))); EXPECT_FALSE(assign_traits_md_double::simd_linear_assign()); EXPECT_TRUE((std::is_same<return_type, double>::value)); #endif } SUBCASE("xarray<double> > xarray<double>") { auto fgt = a > b; using bool_container_t = xop_test::rebind_container_t<TypeParam, bool>; using assign_traits_gt = xassign_traits<bool_container_t, decltype(fgt)>; #if XTENSOR_USE_XSIMD EXPECT_TRUE(assign_traits_gt::simd_linear_assign()); #else using return_type = decltype(fgt.template load_simd<aligned_mode>(std::size_t(0))); EXPECT_FALSE(assign_traits_gt::simd_linear_assign()); EXPECT_TRUE((std::is_same<return_type, bool>::value)); #endif } SUBCASE("xarray<bool> || xarray<bool>") { using bool_container_t = xop_test::rebind_container_t<TypeParam, bool>; bool_container_t b0 = {{true, false, true}, {false, false, true}}; bool_container_t b1 = {{true, true, false}, {false, true, true}}; auto fb = b0 || b1; using assign_traits_bool_bool = xassign_traits<bool_container_t, decltype(fb)>; #if XTENSOR_USE_XSIMD EXPECT_TRUE(assign_traits_bool_bool::simd_linear_assign()); #else using return_type = decltype(fb.template load_simd<aligned_mode>(std::size_t(0))); EXPECT_FALSE(assign_traits_bool_bool::simd_linear_assign()); EXPECT_TRUE((std::is_same<return_type, bool>::value)); #endif } } TEST(operation, mixed_assign) { xt::xarray<double> asrc = { 1., 2. }; xt::xarray<std::size_t> bsrc = { std::size_t(3), std::size_t(4) }; xt::xarray<double> a(asrc); xt::xarray<double> aexp = { 3., 4. }; a = bsrc; xt::xarray<std::size_t> b(bsrc); xt::xarray<std::size_t> bexp = { std::size_t(1), std::size_t(2) }; b = asrc; EXPECT_EQ(b, bexp); } TEST(operation, mixed_bool_assign) { xt::xarray<double> a = { 1., 6. }; xt::xarray<double> b = { 2., 3. }; using uchar = unsigned char; xt::xarray<uchar> res = a > b; xt::xarray<uchar> exp = { uchar(0), uchar(1) }; EXPECT_EQ(res, exp); } TEST(operation, dynamic_simd_assign) { using array_type = xt::xarray<double, layout_type::dynamic>; array_type a({2, 3}, layout_type::row_major); array_type b({2, 3}, layout_type::column_major); auto frr = a + a; auto frc = a + b; auto fcc = b + b; using frr_traits = xassign_traits<array_type, decltype(frr)>; using frc_traits = xassign_traits<array_type, decltype(frc)>; using fcc_traits = xassign_traits<array_type, decltype(fcc)>; EXPECT_FALSE(frr_traits::simd_linear_assign()); EXPECT_FALSE(frc_traits::simd_linear_assign()); EXPECT_FALSE(fcc_traits::simd_linear_assign()); SUBCASE("row_major + row_major") { #if XTENSOR_USE_XSIMD EXPECT_TRUE(frr_traits::simd_linear_assign(a, frr)); #else EXPECT_FALSE(frr_traits::simd_linear_assign(a, frr)); #endif EXPECT_FALSE(frr_traits::simd_linear_assign(b, frr)); } SUBCASE("row_major + column_major") { EXPECT_FALSE(frc_traits::simd_linear_assign(a, frc)); EXPECT_FALSE(frc_traits::simd_linear_assign(b, frc)); } SUBCASE("row_major + column_major") { EXPECT_FALSE(fcc_traits::simd_linear_assign(a, fcc)); #if XTENSOR_USE_XSIMD EXPECT_TRUE(fcc_traits::simd_linear_assign(b, fcc)); #else EXPECT_FALSE(fcc_traits::simd_linear_assign(b, fcc)); #endif } } TEST_CASE("left_shift") { xarray<int> arr({5,1, 1000}); xarray<int> arr2({2,1, 3}); xarray<int> res1 = left_shift(arr, 4); xarray<int> res2 = left_shift(arr, arr2); EXPECT_EQ(left_shift(arr, 4)(1), 16); xarray<int> expected1 = {80, 16, 16000}; xarray<int> expected2 = {20, 2, 8000}; EXPECT_EQ(expected1, res1); EXPECT_EQ(expected2, res2); xarray<int> res3 = arr << 4; xarray<int> res4 = arr << arr2; EXPECT_EQ(expected1, res3); EXPECT_EQ(expected2, res4); } TEST_CASE("right_shift") { xarray<int> arr({5,1, 1000}); xarray<int> arr2({2,1, 3}); xarray<int> res1 = right_shift(arr, 4); xarray<int> res2 = right_shift(arr, arr2); EXPECT_EQ(right_shift(arr, 4)(1), 0); xarray<int> expected1 = {0, 0, 62}; xarray<int> expected2 = {1, 0, 125}; EXPECT_EQ(expected1, res1); EXPECT_EQ(expected2, res2); xarray<int> res3 = arr >> 4; xarray<int> res4 = arr >> arr2; EXPECT_EQ(expected1, res3); EXPECT_EQ(expected2, res4); } } #undef XOPERATION_TEST_TYPES }
17,726
1,700
// Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include "common/common_tests.cpp" #include "geometry/geometry_tests.cpp"
51
487
/* * Copyright 2012-2014 <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.intellij.erlang.resolve; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.testFramework.LightProjectDescriptor; import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor; import org.intellij.erlang.psi.ErlangModuleRef; import org.intellij.erlang.psi.ErlangQAtom; import org.intellij.erlang.sdk.ErlangSdkRelease; import org.intellij.erlang.sdk.ErlangSdkType; import org.intellij.erlang.utils.ErlangLightPlatformCodeInsightFixtureTestCase; import org.jetbrains.annotations.NotNull; public class ErlangModuleResolutionTest extends ErlangLightPlatformCodeInsightFixtureTestCase { @Override protected LightProjectDescriptor getProjectDescriptor() { return new DefaultLightProjectDescriptor() { @Override public Sdk getSdk() { return ErlangSdkType.createMockSdk("testData/mockSdk-R15B02/", ErlangSdkRelease.V_R15B02); } }; } @Override protected void setUp() throws Exception { super.setUp(); setUpProjectSdk(); } @Override protected String getTestDataPath() { return "testData/resolve/module/" + getTestName(true) + "/"; } public void testKernelModulesAppearFirst() { doModuleRefTest("kernel-2.15.2/src/file.erl", "test.erl", "file.erl"); } public void testStdlibModulesAppearFirst() { doModuleRefTest("stdlib-1.18.2/src/io.erl", "test.erl", "io.erl"); } public void testUserModulesAppearFirst() { doModuleRefTest("eunit.erl", "test.erl", "eunit.erl"); } public void testModuleVariableInSpec() { doParameterTest("variableInArguments.erl", "variableInArguments.erl"); } public void testModuleTypeInSpec() { doParameterTest("typeInArguments.erl", "typeInArguments.erl"); } private void doModuleRefTest(String expectedPath, String ... filePaths) { doTest(ErlangModuleRef.class, expectedPath, filePaths); } private void doParameterTest(String expectedPath, String ... filePaths) { doTest(ErlangQAtom.class, expectedPath, filePaths); } private void doTest(@NotNull Class<? extends PsiElement> clazz, String expectedPath, String... filePaths) { myFixture.configureByFiles(filePaths); PsiElement focusedElement = getElementAtCaret(clazz); PsiReference reference = focusedElement.getReference(); PsiElement module = reference != null ? reference.resolve() : null; PsiFile containingFile = module != null ? module.getContainingFile() : null; VirtualFile virtualFile = containingFile != null ? containingFile.getVirtualFile() : null; assertNotNull(virtualFile); String actualModulePath = virtualFile.getPath(); assertTrue("Expected path: *" + expectedPath + ", Actual: " + actualModulePath, actualModulePath.endsWith(expectedPath)); } //TODO add small IDE tests //TODO test source roots are preferred to plain directories //TODO test plain directories are preferred to hidden directories }
1,189
386
<reponame>beru/libonnx #include <onnx.h> static int Reshape_init(struct onnx_node_t * n) { struct onnx_tensor_t * x; struct onnx_tensor_t * s; if((n->ninput == 2) && (n->noutput == 1)) { x = n->inputs[0]; s = n->inputs[1]; if((x->ndim == 0) || (x->type == ONNX_TENSOR_TYPE_UNDEFINED)) return 0; if((s->ndim == 0) || (s->type != ONNX_TENSOR_TYPE_INT64)) return 0; return 1; } return 0; } static int Reshape_exit(struct onnx_node_t * n) { return 1; } static int Reshape_reshape(struct onnx_node_t * n) { struct onnx_tensor_t * y = n->outputs[0]; struct onnx_tensor_t * x = n->inputs[0]; struct onnx_tensor_t * s = n->inputs[1]; int64_t * ps = s->datas; int total_dim = 1; int total_shape = 1; int ndim = s->ndata; int dims[ndim]; for(int i = 0; i < ndim; i++) { if(ps[i] == 0) dims[i] = x->dims[i]; else if(ps[i] > 0) dims[i] = ps[i]; else { for(int j = 0; j < x->ndim; j++) total_dim *= x->dims[j]; for(int j = 0; j < ndim; j++) { if(ps[j] > 0) total_shape *= ps[j]; else if(ps[j] == 0) total_shape *= x->dims[j]; } dims[i] = total_dim / total_shape; } } return onnx_tensor_reshape(y, dims, ndim, x->type); } static void Reshape_operator(struct onnx_node_t * n) { struct onnx_tensor_t * y = n->outputs[0]; struct onnx_tensor_t * x = n->inputs[0]; char ** py = (char **)y->datas; char ** px = (char **)x->datas; if(x->type == ONNX_TENSOR_TYPE_STRING) { for(size_t i = 0, l = y->ndata; i < l; i++) { if(py[i]) free(py[i]); py[i] = strdup(px[i]); } } else { memcpy(y->datas, x->datas, x->ndata * onnx_tensor_type_sizeof(x->type)); } } void resolver_default_op_Reshape(struct onnx_node_t * n) { if(n->opset >= 14) { switch(n->inputs[0]->type) { case ONNX_TENSOR_TYPE_BOOL: case ONNX_TENSOR_TYPE_INT8: case ONNX_TENSOR_TYPE_INT16: case ONNX_TENSOR_TYPE_INT32: case ONNX_TENSOR_TYPE_INT64: case ONNX_TENSOR_TYPE_UINT8: case ONNX_TENSOR_TYPE_UINT16: case ONNX_TENSOR_TYPE_UINT32: case ONNX_TENSOR_TYPE_UINT64: case ONNX_TENSOR_TYPE_BFLOAT16: case ONNX_TENSOR_TYPE_FLOAT16: case ONNX_TENSOR_TYPE_FLOAT32: case ONNX_TENSOR_TYPE_FLOAT64: case ONNX_TENSOR_TYPE_COMPLEX64: case ONNX_TENSOR_TYPE_COMPLEX128: case ONNX_TENSOR_TYPE_STRING: n->init = Reshape_init; n->exit = Reshape_exit; n->reshape = Reshape_reshape; n->operator = Reshape_operator; break; default: break; } } else if(n->opset >= 13) { switch(n->inputs[0]->type) { case ONNX_TENSOR_TYPE_BOOL: case ONNX_TENSOR_TYPE_INT8: case ONNX_TENSOR_TYPE_INT16: case ONNX_TENSOR_TYPE_INT32: case ONNX_TENSOR_TYPE_INT64: case ONNX_TENSOR_TYPE_UINT8: case ONNX_TENSOR_TYPE_UINT16: case ONNX_TENSOR_TYPE_UINT32: case ONNX_TENSOR_TYPE_UINT64: case ONNX_TENSOR_TYPE_BFLOAT16: case ONNX_TENSOR_TYPE_FLOAT16: case ONNX_TENSOR_TYPE_FLOAT32: case ONNX_TENSOR_TYPE_FLOAT64: case ONNX_TENSOR_TYPE_COMPLEX64: case ONNX_TENSOR_TYPE_COMPLEX128: case ONNX_TENSOR_TYPE_STRING: n->init = Reshape_init; n->exit = Reshape_exit; n->reshape = Reshape_reshape; n->operator = Reshape_operator; break; default: break; } } else if(n->opset >= 5) { switch(n->inputs[0]->type) { case ONNX_TENSOR_TYPE_BOOL: case ONNX_TENSOR_TYPE_INT8: case ONNX_TENSOR_TYPE_INT16: case ONNX_TENSOR_TYPE_INT32: case ONNX_TENSOR_TYPE_INT64: case ONNX_TENSOR_TYPE_UINT8: case ONNX_TENSOR_TYPE_UINT16: case ONNX_TENSOR_TYPE_UINT32: case ONNX_TENSOR_TYPE_UINT64: case ONNX_TENSOR_TYPE_FLOAT16: case ONNX_TENSOR_TYPE_FLOAT32: case ONNX_TENSOR_TYPE_FLOAT64: case ONNX_TENSOR_TYPE_COMPLEX64: case ONNX_TENSOR_TYPE_COMPLEX128: case ONNX_TENSOR_TYPE_STRING: n->init = Reshape_init; n->exit = Reshape_exit; n->reshape = Reshape_reshape; n->operator = Reshape_operator; break; default: break; } } else if(n->opset >= 1) { } }
2,124
578
<reponame>dlabaj/syndesis-react-poc<filename>app/server/jsondb/src/main/java/io/syndesis/server/jsondb/impl/expr/LiteralSqlExpressionBuilder.java /* * Copyright (C) 2016 Red Hat, 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.syndesis.server.jsondb.impl.expr; import static io.syndesis.server.jsondb.impl.JsonRecordSupport.FALSE_VALUE_PREFIX; import static io.syndesis.server.jsondb.impl.JsonRecordSupport.NULL_VALUE_PREFIX; import static io.syndesis.server.jsondb.impl.JsonRecordSupport.STRING_VALUE_PREFIX; import static io.syndesis.server.jsondb.impl.JsonRecordSupport.TRUE_VALUE_PREFIX; import static io.syndesis.server.jsondb.impl.JsonRecordSupport.toLexSortableString; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import org.skife.jdbi.v2.Query; class LiteralSqlExpressionBuilder extends SqlExpressionBuilder { private final Object value; public LiteralSqlExpressionBuilder(Object value) { this.value = value; } @Override public void build(StringBuilder sql, ArrayList<Consumer<Query<Map<String, Object>>>> binds, AtomicInteger bindCounter) { int b1 = bindCounter.incrementAndGet(); sql.append(":f").append(b1); binds.add(query -> { if( value == null ) { query.bind("f" + b1, String.valueOf(NULL_VALUE_PREFIX)); } else if( Boolean.FALSE.equals(value) ) { query.bind("f" + b1, String.valueOf(FALSE_VALUE_PREFIX)); } else if( Boolean.TRUE.equals(value) ) { query.bind("f" + b1, String.valueOf(TRUE_VALUE_PREFIX)); } else if( value.getClass() == String.class ) { query.bind("f" + b1, STRING_VALUE_PREFIX+value.toString()); } else if( value instanceof Number ) { query.bind("f" + b1, toLexSortableString(value.toString())); } else { query.bind("f" + b1, STRING_VALUE_PREFIX+value.toString()); } }); } }
1,011
674
<gh_stars>100-1000 # -*- coding: utf-8 -*- """Bottle request argument parsing module. Example: :: from bottle import route, run from marshmallow import fields from webargs.bottleparser import use_args hello_args = { 'name': fields.Str(missing='World') } @route('/', method='GET') @use_args(hello_args) def index(args): return 'Hello ' + args['name'] if __name__ == '__main__': run(debug=True) """ import bottle from webargs import core class BottleParser(core.Parser): """Bottle.py request argument parser.""" def parse_querystring(self, req, name, field): """Pull a querystring value from the request.""" return core.get_value(req.query, name, field) def parse_form(self, req, name, field): """Pull a form value from the request.""" return core.get_value(req.forms, name, field) def parse_json(self, req, name, field): """Pull a json value from the request.""" json_body = self._cache.get('json') if json_body is None: try: self._cache['json'] = json_body = req.json except (AttributeError, ValueError): return core.missing if json_body is not None: return core.get_value(req.json, name, field) else: return core.missing def parse_headers(self, req, name, field): """Pull a value from the header data.""" return core.get_value(req.headers, name, field) def parse_cookies(self, req, name, field): """Pull a value from the cookiejar.""" return req.get_cookie(name) def parse_files(self, req, name, field): """Pull a file from the request.""" return core.get_value(req.files, name, field) def handle_error(self, error): """Handles errors during parsing. Aborts the current request with a 400 error. """ status_code = getattr(error, 'status_code', self.DEFAULT_VALIDATION_STATUS) headers = getattr(error, 'headers', {}) raise bottle.HTTPError(status=status_code, body=error.messages, headers=headers, exception=error) def get_default_request(self): """Override to use bottle's thread-local request object by default.""" return bottle.request parser = BottleParser() use_args = parser.use_args use_kwargs = parser.use_kwargs
974
751
<gh_stars>100-1000 #pragma once #include <cstdint> #include <cstdlib> namespace xoroshiro { namespace detail { template<typename STATE, typename RESULT, STATE A, STATE B, STATE C> class XorOshiro { private: static constexpr unsigned STATE_BITS = 8 * sizeof(STATE); static constexpr unsigned RESULT_BITS = 8 * sizeof(RESULT); static_assert( STATE_BITS >= RESULT_BITS, "STATE must have at least as many bits as RESULT"); STATE x; STATE y; static inline STATE rotl(STATE x, STATE k) { return (x << k) | (x >> (STATE_BITS - k)); } public: XorOshiro(STATE x_ = 5489, STATE y_ = 0) : x(x_), y(y_) { // If both zero, then this does not work if (x_ == 0 && y_ == 0) abort(); next(); } void set_state(STATE x_, STATE y_ = 0) { // If both zero, then this does not work if (x_ == 0 && y_ == 0) abort(); x = x_; y = y_; next(); } RESULT next() { STATE r = x + y; y ^= x; x = rotl(x, A) ^ y ^ (y << B); y = rotl(y, C); // If both zero, then this does not work if (x == 0 && y == 0) abort(); return r >> (STATE_BITS - RESULT_BITS); } }; } using p128r64 = detail::XorOshiro<uint64_t, uint64_t, 55, 14, 36>; using p128r32 = detail::XorOshiro<uint64_t, uint32_t, 55, 14, 36>; using p64r32 = detail::XorOshiro<uint32_t, uint32_t, 27, 7, 20>; using p64r16 = detail::XorOshiro<uint32_t, uint16_t, 27, 7, 20>; using p32r16 = detail::XorOshiro<uint16_t, uint16_t, 13, 5, 10>; using p32r8 = detail::XorOshiro<uint16_t, uint8_t, 13, 5, 10>; using p16r8 = detail::XorOshiro<uint8_t, uint8_t, 4, 7, 3>; }
908
1,350
<reponame>ppartarr/azure-sdk-for-java /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.knowledge.qnamaker.models; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * Active learning feedback records. */ public class FeedbackRecordsDTO { /** * List of feedback records. */ @JsonProperty(value = "feedbackRecords") private List<FeedbackRecordDTO> feedbackRecords; /** * Get the feedbackRecords value. * * @return the feedbackRecords value */ public List<FeedbackRecordDTO> feedbackRecords() { return this.feedbackRecords; } /** * Set the feedbackRecords value. * * @param feedbackRecords the feedbackRecords value to set * @return the FeedbackRecordsDTO object itself. */ public FeedbackRecordsDTO withFeedbackRecords(List<FeedbackRecordDTO> feedbackRecords) { this.feedbackRecords = feedbackRecords; return this; } }
416
4,036
// header.h #ifndef HEADER_H #define HEADER_H DLLEXPORT void myFunction1(int a, int b, int c); DLLEXPORT void myFunction2(int a, int b, int c); DLLEXPORT void myFunction3(int a, int b, int c); DLLEXPORT void myFunction5(int a, int b, int c); void myFunction5(int a, int b, int c); #endif // HEADER_H
129
953
/*! @file */ /* Copyright (C) 2018-2021, Sakura Editor Organization This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "StdAfx.h" #include "io/CFile.h" #include "window/CEditWnd.h" // 変更予定 #include <io.h> #include "CSelectLang.h" #include "String_define.h" // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // // コンストラクタ・デストラクタ // // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // CFile::CFile(LPCWSTR pszPath) : m_hLockedFile( INVALID_HANDLE_VALUE ) , m_nFileShareModeOld( SHAREMODE_NOT_EXCLUSIVE ) { if(pszPath){ SetFilePath(pszPath); } } CFile::~CFile() { FileUnlock(); } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // // 各種判定 // // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // bool CFile::IsFileExist() const { return fexist(GetFilePath()); } bool CFile::HasWritablePermission() const { return -1 != _waccess( GetFilePath(), 2 ); } bool CFile::IsFileWritable() const { //書き込めるか検査 // Note. 他のプロセスが明示的に書き込み禁止しているかどうか // ⇒ GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE でチェックする // 実際のファイル保存もこれと等価な _wfopen の L"wb" を使用している HANDLE hFile = CreateFile( this->GetFilePath(), //ファイル名 GENERIC_WRITE, //書きモード FILE_SHARE_READ | FILE_SHARE_WRITE, //読み書き共有 NULL, //既定のセキュリティ記述子 OPEN_EXISTING, //ファイルが存在しなければ失敗 FILE_ATTRIBUTE_NORMAL, //特に属性は指定しない NULL //テンプレート無し ); if(hFile==INVALID_HANDLE_VALUE){ return false; } CloseHandle(hFile); return true; } bool CFile::IsFileReadable() const { HANDLE hTest = CreateFile( this->GetFilePath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL ); if(hTest==INVALID_HANDLE_VALUE){ // 読み込みアクセス権がない return false; } CloseHandle( hTest ); return true; } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // // ロック // // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // //! ファイルの排他ロック解除 void CFile::FileUnlock() { //クローズ if( m_hLockedFile != INVALID_HANDLE_VALUE ){ ::CloseHandle( m_hLockedFile ); m_hLockedFile = INVALID_HANDLE_VALUE; } } //! ファイルの排他ロック bool CFile::FileLock( EShareMode eShareMode, bool bMsg ) { // ロック解除 FileUnlock(); // ファイルの存在チェック if( !this->IsFileExist() ){ return false; } // モード設定 if(eShareMode==SHAREMODE_NOT_EXCLUSIVE)return true; //フラグ DWORD dwShareMode=0; switch(eShareMode){ case SHAREMODE_NOT_EXCLUSIVE: return true; break; //排他制御無し case SHAREMODE_DENY_READWRITE: dwShareMode = 0; break; //読み書き禁止→共有無し case SHAREMODE_DENY_WRITE: dwShareMode = FILE_SHARE_READ; break; //書き込み禁止→読み込みのみ認める default: dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; break; //禁止事項なし→読み書き共に認める } //オープン m_hLockedFile = CreateFile( this->GetFilePath(), //ファイル名 GENERIC_READ, //読み書きタイプ dwShareMode, //共有モード NULL, //既定のセキュリティ記述子 OPEN_EXISTING, //ファイルが存在しなければ失敗 FILE_ATTRIBUTE_NORMAL, //特に属性は指定しない NULL //テンプレート無し ); //結果 if( INVALID_HANDLE_VALUE == m_hLockedFile && bMsg ){ const WCHAR* pszMode; switch( eShareMode ){ case SHAREMODE_DENY_READWRITE: pszMode = LS(STR_EXCLU_DENY_READWRITE); break; case SHAREMODE_DENY_WRITE: pszMode = LS(STR_EXCLU_DENY_WRITE); break; default: pszMode = LS(STR_EXCLU_UNDEFINED); break; } TopWarningMessage( CEditWnd::getInstance()->GetHwnd(), LS(STR_FILE_LOCK_ERR), GetFilePathClass().IsValidPath() ? GetFilePath() : LS(STR_NO_TITLE1), pszMode ); return false; } return true; }
2,308
679
<reponame>Grosskopf/openoffice<filename>main/xmloff/source/text/XMLIndexSourceBaseContext.cxx<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include "XMLIndexSourceBaseContext.hxx" #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/container/XIndexReplace.hpp> #include "XMLIndexTemplateContext.hxx" #include "XMLIndexTitleTemplateContext.hxx" #include "XMLIndexTOCStylesContext.hxx" #include <xmloff/xmlictxt.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/txtimp.hxx> #include "xmloff/xmlnmspe.hxx" #include <xmloff/nmspmap.hxx> #include <xmloff/xmltoken.hxx> #include <xmloff/xmluconv.hxx> #include <tools/debug.hxx> #include <rtl/ustring.hxx> using namespace ::xmloff::token; using ::rtl::OUString; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; const sal_Char sAPI_CreateFromChapter[] = "CreateFromChapter"; const sal_Char sAPI_IsRelativeTabstops[] = "IsRelativeTabstops"; static __FAR_DATA SvXMLTokenMapEntry aIndexSourceTokenMap[] = { { XML_NAMESPACE_TEXT, XML_OUTLINE_LEVEL, XML_TOK_INDEXSOURCE_OUTLINE_LEVEL}, { XML_NAMESPACE_TEXT, XML_USE_INDEX_MARKS, XML_TOK_INDEXSOURCE_USE_INDEX_MARKS }, { XML_NAMESPACE_TEXT, XML_INDEX_SCOPE, XML_TOK_INDEXSOURCE_INDEX_SCOPE }, { XML_NAMESPACE_TEXT, XML_RELATIVE_TAB_STOP_POSITION, XML_TOK_INDEXSOURCE_RELATIVE_TABS } , { XML_NAMESPACE_TEXT, XML_USE_OTHER_OBJECTS, XML_TOK_INDEXSOURCE_USE_OTHER_OBJECTS }, { XML_NAMESPACE_TEXT, XML_USE_SPREADSHEET_OBJECTS, XML_TOK_INDEXSOURCE_USE_SHEET }, { XML_NAMESPACE_TEXT, XML_USE_CHART_OBJECTS, XML_TOK_INDEXSOURCE_USE_CHART }, { XML_NAMESPACE_TEXT, XML_USE_DRAW_OBJECTS, XML_TOK_INDEXSOURCE_USE_DRAW }, { XML_NAMESPACE_TEXT, XML_USE_IMAGE_OBJECTS, XML_TOK_INDEXSOURCE_USE_IMAGE }, { XML_NAMESPACE_TEXT, XML_USE_MATH_OBJECTS, XML_TOK_INDEXSOURCE_USE_MATH }, { XML_NAMESPACE_TEXT, XML_MAIN_ENTRY_STYLE_NAME, XML_TOK_INDEXSOURCE_MAIN_ENTRY_STYLE }, { XML_NAMESPACE_TEXT, XML_IGNORE_CASE, XML_TOK_INDEXSOURCE_IGNORE_CASE }, { XML_NAMESPACE_TEXT, XML_ALPHABETICAL_SEPARATORS, XML_TOK_INDEXSOURCE_SEPARATORS }, { XML_NAMESPACE_TEXT, XML_COMBINE_ENTRIES, XML_TOK_INDEXSOURCE_COMBINE_ENTRIES }, { XML_NAMESPACE_TEXT, XML_COMBINE_ENTRIES_WITH_DASH, XML_TOK_INDEXSOURCE_COMBINE_WITH_DASH }, { XML_NAMESPACE_TEXT, XML_USE_KEYS_AS_ENTRIES, XML_TOK_INDEXSOURCE_KEYS_AS_ENTRIES }, { XML_NAMESPACE_TEXT, XML_COMBINE_ENTRIES_WITH_PP, XML_TOK_INDEXSOURCE_COMBINE_WITH_PP }, { XML_NAMESPACE_TEXT, XML_CAPITALIZE_ENTRIES, XML_TOK_INDEXSOURCE_CAPITALIZE }, { XML_NAMESPACE_TEXT, XML_USE_OBJECTS, XML_TOK_INDEXSOURCE_USE_OBJECTS }, { XML_NAMESPACE_TEXT, XML_USE_GRAPHICS, XML_TOK_INDEXSOURCE_USE_GRAPHICS }, { XML_NAMESPACE_TEXT, XML_USE_TABLES, XML_TOK_INDEXSOURCE_USE_TABLES }, { XML_NAMESPACE_TEXT, XML_USE_FLOATING_FRAMES, XML_TOK_INDEXSOURCE_USE_FRAMES }, { XML_NAMESPACE_TEXT, XML_COPY_OUTLINE_LEVELS, XML_TOK_INDEXSOURCE_COPY_OUTLINE_LEVELS }, { XML_NAMESPACE_TEXT, XML_USE_CAPTION, XML_TOK_INDEXSOURCE_USE_CAPTION }, { XML_NAMESPACE_TEXT, XML_CAPTION_SEQUENCE_NAME, XML_TOK_INDEXSOURCE_SEQUENCE_NAME }, { XML_NAMESPACE_TEXT, XML_CAPTION_SEQUENCE_FORMAT, XML_TOK_INDEXSOURCE_SEQUENCE_FORMAT }, { XML_NAMESPACE_TEXT, XML_COMMA_SEPARATED, XML_TOK_INDEXSOURCE_COMMA_SEPARATED }, { XML_NAMESPACE_TEXT, XML_USE_INDEX_SOURCE_STYLES, XML_TOK_INDEXSOURCE_USE_INDEX_SOURCE_STYLES }, { XML_NAMESPACE_TEXT, XML_SORT_ALGORITHM, XML_TOK_INDEXSOURCE_SORT_ALGORITHM }, { XML_NAMESPACE_FO, XML_LANGUAGE, XML_TOK_INDEXSOURCE_LANGUAGE }, { XML_NAMESPACE_FO, XML_COUNTRY, XML_TOK_INDEXSOURCE_COUNTRY }, { XML_NAMESPACE_TEXT, XML_INDEX_NAME, XML_TOK_INDEXSOURCE_USER_INDEX_NAME }, { XML_NAMESPACE_TEXT, XML_USE_OUTLINE_LEVEL, XML_TOK_INDEXSOURCE_USE_OUTLINE_LEVEL}, XML_TOKEN_MAP_END }; TYPEINIT1( XMLIndexSourceBaseContext, SvXMLImportContext ); XMLIndexSourceBaseContext::XMLIndexSourceBaseContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, Reference<XPropertySet> & rPropSet, sal_Bool bLevelFormats) : SvXMLImportContext(rImport, nPrfx, rLocalName) , sCreateFromChapter(RTL_CONSTASCII_USTRINGPARAM(sAPI_CreateFromChapter)) , sIsRelativeTabstops(RTL_CONSTASCII_USTRINGPARAM(sAPI_IsRelativeTabstops)) , bUseLevelFormats(bLevelFormats) , bChapterIndex(sal_False) , bRelativeTabs(sal_True) , rIndexPropertySet(rPropSet) { } XMLIndexSourceBaseContext::~XMLIndexSourceBaseContext() { } void XMLIndexSourceBaseContext::StartElement( const Reference<XAttributeList> & xAttrList) { SvXMLTokenMap aTokenMap(aIndexSourceTokenMap); // process attributes sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 i=0; i<nLength; i++) { // map to IndexSourceParamEnum OUString sLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(i), &sLocalName ); sal_uInt16 nToken = aTokenMap.Get(nPrefix, sLocalName); // process attribute ProcessAttribute((enum IndexSourceParamEnum)nToken, xAttrList->getValueByIndex(i)); } } void XMLIndexSourceBaseContext::ProcessAttribute( enum IndexSourceParamEnum eParam, const OUString& rValue) { switch (eParam) { case XML_TOK_INDEXSOURCE_INDEX_SCOPE: if ( IsXMLToken( rValue, XML_CHAPTER ) ) { bChapterIndex = sal_True; } break; case XML_TOK_INDEXSOURCE_RELATIVE_TABS: { sal_Bool bTmp; if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bRelativeTabs = bTmp; } break; } default: // unknown attribute -> ignore break; } } void XMLIndexSourceBaseContext::EndElement() { Any aAny; aAny.setValue(&bRelativeTabs, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sIsRelativeTabstops, aAny); aAny.setValue(&bChapterIndex, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromChapter, aAny); } SvXMLImportContext* XMLIndexSourceBaseContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { SvXMLImportContext* pContext = NULL; if (XML_NAMESPACE_TEXT == nPrefix) { if ( IsXMLToken( rLocalName, XML_INDEX_TITLE_TEMPLATE ) ) { pContext = new XMLIndexTitleTemplateContext(GetImport(), rIndexPropertySet, nPrefix, rLocalName); } else if ( bUseLevelFormats && IsXMLToken( rLocalName, XML_INDEX_SOURCE_STYLES ) ) { pContext = new XMLIndexTOCStylesContext(GetImport(), rIndexPropertySet, nPrefix, rLocalName); } // else: unknown element in text namespace -> ignore } // else: unknown namespace -> ignore // use default context if (pContext == NULL) { pContext = SvXMLImportContext::CreateChildContext(nPrefix, rLocalName, xAttrList); } return pContext; }
3,449
3,200
<filename>mindspore/core/ops/broadcast.cc<gh_stars>1000+ /** * Copyright 2020 Huawei Technologies Co., Ltd * * 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 <set> #include <vector> #include <memory> #include "ops/broadcast.h" #include "ops/op_utils.h" #include "utils/check_convert_utils.h" namespace mindspore { namespace ops { void Broadcast::Init(const int64_t root_rank, const std::string &group) { this->set_root_rank(root_rank); this->set_group(group); } void Broadcast::set_root_rank(const int64_t root_rank) { (void)this->AddAttr(kKeepProb, MakeValue(root_rank)); } void Broadcast::set_group(const std::string &group) { CheckAndConvertUtils::CheckString(kGroup, group, {"hccl_world_group", "hccl_world_group"}, this->name()); (void)this->AddAttr(kGroup, MakeValue(group)); } int64_t Broadcast::get_root_rank() const { auto value_ptr = this->GetAttr(kRootRank); return GetValue<int64_t>(value_ptr); } std::string Broadcast::get_group() const { auto value_ptr = this->GetAttr(kGroup); return GetValue<std::string>(value_ptr); } AbstractBasePtr BroadcastInfer(const abstract::AnalysisEnginePtr &, const PrimitivePtr &primitive, const std::vector<AbstractBasePtr> &input_args) { MS_EXCEPTION_IF_NULL(primitive); auto prim_name = primitive->name(); for (const auto &item : input_args) { MS_EXCEPTION_IF_NULL(item); } // infer shape auto in_shape = CheckAndConvertUtils::ConvertShapePtrToShapeMap(input_args[0]->BuildShape())[kShape]; // infer type auto x_type = input_args[0]->BuildType()->cast<TensorTypePtr>()->element(); std::vector<TypePtr> output_types; const std::set<TypePtr> valid_types = {kInt8, kInt32, kFloat16, kFloat32}; for (size_t i = 0; i < input_args.size(); i++) { auto out_type = input_args[i]->BuildType()->cast<TensorTypePtr>()->element(); output_types.push_back(out_type); (void)CheckAndConvertUtils::CheckTensorTypeValid("index_type", out_type, valid_types, prim_name); } return std::make_shared<abstract::AbstractTensor>(x_type, in_shape); } REGISTER_PRIMITIVE_C(kNameBroadcast, Broadcast); } // namespace ops } // namespace mindspore
920
892
{ "schema_version": "1.2.0", "id": "GHSA-f9mp-88cg-ffch", "modified": "2022-02-18T00:00:51Z", "published": "2022-02-12T00:00:51Z", "aliases": [ "CVE-2021-42000" ], "details": "When a password reset or password change flow with an authentication policy is configured and the adapter in the reset or change policy supports multiple parallel reset flows, an existing user can reset another existing users password.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-42000" }, { "type": "WEB", "url": "https://docs.pingidentity.com/bundle/pingfederate-103/page/hhm1634833631515.html" }, { "type": "WEB", "url": "https://www.pingidentity.com/en/resources/downloads/pingfederate.html" } ], "database_specific": { "cwe_ids": [ "CWE-863" ], "severity": "MODERATE", "github_reviewed": false } }
419
3,266
<filename>java/java2py/antlr-3.1.3/runtime/ObjC/Xcode plugin/GrammarFilterLexer.h // $ANTLR 3.0b5 /Users/kroepke/Projects/antlr3/code/antlr/main/lib/ObjC/Xcode plugin/GrammarFilter.g 2006-11-12 20:15:18 #import <Cocoa/Cocoa.h> #import <ANTLR/ANTLR.h> #pragma mark Cyclic DFA start @interface GrammarFilterLexerDFA13 : ANTLRDFA {} @end #pragma mark Cyclic DFA end #pragma mark Rule return scopes start #pragma mark Rule return scopes end #pragma mark Tokens #define GrammarFilterLexer_GRAMMAR_TYPE 4 #define GrammarFilterLexer_EOF -1 #define GrammarFilterLexer_WS 5 #define GrammarFilterLexer_STRING 13 #define GrammarFilterLexer_Tokens 14 #define GrammarFilterLexer_LEXER_RULE 11 #define GrammarFilterLexer_OPTIONS 10 #define GrammarFilterLexer_ACTION 12 #define GrammarFilterLexer_COMMENT 9 #define GrammarFilterLexer_GRAMMAR 7 #define GrammarFilterLexer_SL_COMMENT 8 #define GrammarFilterLexer_ID 6 @interface GrammarFilterLexer : ANTLRLexer { GrammarFilterLexerDFA13 *dfa13; SEL synpred7SyntacticPredicate; SEL synpred3SyntacticPredicate; SEL synpred8SyntacticPredicate; id delegate; } - (void) setDelegate:(id)theDelegate; - (void) mGRAMMAR; - (void) mGRAMMAR_TYPE; - (void) mOPTIONS; - (void) mLEXER_RULE; - (void) mCOMMENT; - (void) mSL_COMMENT; - (void) mACTION; - (void) mSTRING; - (void) mID; - (void) mWS; - (void) mTokens; - (void) synpred3; - (void) synpred7; - (void) synpred8; @end
592
345
import os import os.path import re import unittest import shutil from programy.mappings.properties import RegexTemplatesCollection from programy.storage.stores.file.config import FileStorageConfiguration from programy.storage.stores.file.config import FileStoreConfiguration from programy.storage.stores.file.engine import FileStorageEngine from programy.storage.stores.file.store.properties import FileRegexStore class FileRegexStoreTests(unittest.TestCase): def test_initialise(self): config = FileStorageConfiguration() engine = FileStorageEngine(config) engine.initialise() store = FileRegexStore(engine) self.assertEqual(store.storage_engine, engine) def test_storage_path(self): config = FileStorageConfiguration() engine = FileStorageEngine(config) engine.initialise() store = FileRegexStore(engine) self.assertEquals('/tmp/regex/regex-templates.txt', store._get_storage_path()) self.assertIsInstance(store.get_storage(), FileStoreConfiguration) def test_load_regex(self): config = FileStorageConfiguration() config._regex_storage = FileStoreConfiguration(file=os.path.dirname(__file__) + os.sep + "data" + os.sep + "lookups" + os.sep + "text" + os.sep + "regex-templates.txt", fileformat="text", encoding="utf-8", delete_on_start=False) engine = FileStorageEngine(config) engine.initialise() store = FileRegexStore(engine) collection = RegexTemplatesCollection() store.load(collection) self.assertIsNotNone(store.get_regular_expressions()) self.assertTrue(collection.has_regex("anything")) self.assertEqual(re.compile('^.*$', re.IGNORECASE), collection.regex("anything")) self.assertTrue(collection.has_regex("legion")) self.assertFalse(collection.has_regex("XXXXX"))
674
5,383
from typing import Optional from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.orm import column_property from sqlalchemy.orm import deferred from sqlalchemy.orm import registry from sqlalchemy.orm import Session from sqlalchemy.orm import synonym from sqlalchemy.sql.functions import func from sqlalchemy.sql.sqltypes import Text reg: registry = registry() @reg.mapped class User: __tablename__ = "user" id = Column(Integer(), primary_key=True) name = Column(String) # this gets inferred big_col = deferred(Column(Text)) # this gets inferred explicit_col = column_property(Column(Integer)) # EXPECTED: Can't infer type from ORM mapped expression assigned to attribute 'lower_name'; # noqa lower_name = column_property(func.lower(name)) # EXPECTED: Can't infer type from ORM mapped expression assigned to attribute 'syn_name'; # noqa syn_name = synonym("name") # this uses our type lower_name_exp: str = column_property(func.lower(name)) # this uses our type syn_name_exp: Optional[str] = synonym("name") s = Session() u1: Optional[User] = s.get(User, 5) assert u1 q1: Optional[str] = u1.big_col q2: Optional[int] = u1.explicit_col # EXPECTED_MYPY: Incompatible types in assignment (expression has type "str", variable has type "int") # noqa x: int = u1.lower_name_exp # EXPECTED_MYPY: Incompatible types in assignment (expression has type "Optional[str]", variable has type "int") # noqa y: int = u1.syn_name_exp
506
43,319
{ "name": "pkg-both", "main": "./does-not-exist.js", "jsnext:main": "./jsnext.module.js", "module": "./es6.module.js" }
67
347
<filename>frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/editor/EnterIgnoringFocusHandler.java package org.ovirt.engine.ui.common.widget.editor; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Event; /** * If this handler is registered to focus and blur events of a widget, the enter key will be ignored while * this widget has focus. The "enter will be ignored" means that any listener listening to enter will not be * notifyed so the dialog will not get submitted. * * It is useful for widgets like textarea where the user should be able to press enter without submitting the dialog. */ public class EnterIgnoringFocusHandler implements FocusHandler, BlurHandler { private HandlerRegistration eventHandler; @Override public void onFocus(FocusEvent event) { eventHandler = Event.addNativePreviewHandler(e -> { NativeEvent nativeEvent = e.getNativeEvent(); if (nativeEvent.getKeyCode() == KeyCodes.KEY_ENTER && (e.getTypeInt() == Event.ONKEYPRESS || e.getTypeInt() == Event.ONKEYDOWN) && !e.isCanceled()) { // swallow the enter key otherwise the whole dialog would get submitted nativeEvent.preventDefault(); nativeEvent.stopPropagation(); e.cancel(); if (e.getTypeInt() == Event.ONKEYDOWN) { enterPressed(); } } }); } @Override public void onBlur(BlurEvent event) { if (eventHandler != null) { eventHandler.removeHandler(); } } protected void enterPressed() { // any custom operation } }
787
12,278
/*! @file Forward declares `boost::hana::is_empty`. @copyright <NAME> 2013-2017 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_IS_EMPTY_HPP #define BOOST_HANA_FWD_IS_EMPTY_HPP #include <boost/hana/config.hpp> #include <boost/hana/core/when.hpp> BOOST_HANA_NAMESPACE_BEGIN //! Returns whether the iterable is empty. //! @ingroup group-Iterable //! //! Given an `Iterable` `xs`, `is_empty` returns whether `xs` contains //! no more elements. In other words, it returns whether trying to //! extract the tail of `xs` would be an error. In the current version //! of the library, `is_empty` must return an `IntegralConstant` holding //! a value convertible to `bool`. This is because only compile-time //! `Iterable`s are supported right now. //! //! //! Example //! ------- //! @include example/is_empty.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto is_empty = [](auto const& xs) { return tag-dispatched; }; #else template <typename It, typename = void> struct is_empty_impl : is_empty_impl<It, when<true>> { }; struct is_empty_t { template <typename Xs> constexpr auto operator()(Xs const& xs) const; }; constexpr is_empty_t is_empty{}; #endif BOOST_HANA_NAMESPACE_END #endif // !BOOST_HANA_FWD_IS_EMPTY_HPP
580
3,428
{"id":"00491","group":"easy-ham-1","checksum":{"type":"MD5","value":"c0d9405bdda12781f96bc37c00a382d9"},"text":"From <EMAIL> Sat Sep 7 21:54:10 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 8ECCB16F03\n\tfor <jm@localhost>; Sat, 7 Sep 2002 21:52:47 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Sat, 07 Sep 2002 21:52:47 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g87KAIC31918 for <<EMAIL>>;\n Sat, 7 Sep 2002 21:10:21 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id 820932940D3; Sat, 7 Sep 2002 13:07:03 -0700 (PDT)\nDelivered-To: <EMAIL>.<EMAIL>\nReceived: from relay.pair.com (relay1.pair.com [209.68.1.20]) by xent.com\n (Postfix) with SMTP id 394F429409E for <<EMAIL>>; Sat,\n 7 Sep 2002 13:06:04 -0700 (PDT)\nReceived: (qmail 19746 invoked from network); 7 Sep 2002 20:08:45 -0000\nReceived: from adsl-67-119-24-60.dsl.snfc21.pacbell.net (HELO golden)\n (172.16.31.10) by relay1.pair.com with SMTP; 7 Sep 2002 20:08:45 -0000\nX-Pair-Authenticated: 172.16.31.10\nMessage-Id: <005701c256aa$5d12d6e0$640a000a@golden>\nFrom: \"<NAME>\" <<EMAIL>>\nTo: <<EMAIL>>\nReferences: <<EMAIL>>\nSubject: Re: Selling Wedded Bliss (was Re: Ouch...)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"Windows-1252\"\nContent-Transfer-Encoding: 7bit\nX-Priority: 3\nX-Msmail-Priority: Normal\nX-Mailer: Microsoft Outlook Express 6.00.2600.0000\nX-Mimeole: Produced By Microsoft MimeOLE V6.00.2600.0000\nSender: [email protected]\nErrors-To: [email protected]\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of <NAME> <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Sat, 7 Sep 2002 13:08:41 -0700\n\nDefinitional nit to pick:\n\n<NAME> writes:\n> It is perfectly obvious that (heterosexual) promiscuity is exactly,\n> precisely identical between males and females.\n> \n> Of course the shapes of the distributions may differ.\n\nYou've redefined \"promiscuity\" above as \"total\" or \"average\" \nactivity, which seems to rob it of its common meaning: \nactivity above some specific threshold (usually \"one\") or \nnorm, or involving extra or indiscriminate variety. \n\"Promiscuity\" is thus inherently a description of \ndistributions rather than averages.\n\nConsider a population of 3 males and 3 females. Let\nthere be three pairings which result in each person\nhaving sex once. Then, let one of the males also have \nsex with the other two females. \n\nSure, the average number of sex acts and sex partners\nis equal between the sexes, tautologically. \n\nBut here more women than men are:\n - above the single partner threshold\n - above the overall average 1.67 acts/partners threshold\n - above the overall median 1.5 acts/partners\n - above the overall mode 1 acts/partners\n\nAnd here women have a higher mode (2) and median (2) \nnumber of partners.\n\nSo in this contrived population, females are more \n\"promiscuous\" than males, unless \"promiscuity\" is \ndefined uselessly.\n\n- Gordon\n\n\n"}
1,343
1,127
<reponame>ryanloney/openvino-1 // Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "batch_to_space_kernel_selector.h" #include "batch_to_space_kernel_ref.h" namespace kernel_selector { batch_to_space_kernel_selector::batch_to_space_kernel_selector() { Attach<BatchToSpaceKernelRef>(); } KernelsData batch_to_space_kernel_selector::GetBestKernels(const Params& params, const optional_params& options) const { return GetNaiveBestKernel(params, options, KernelType::BATCH_TO_SPACE); } } // namespace kernel_selector
204
416
<reponame>khauser/SimpleFlatMapper package org.simpleflatmapper.jdbc.test; import org.junit.Test; import org.simpleflatmapper.jdbc.DynamicJdbcMapper; import org.simpleflatmapper.jdbc.JdbcMapper; import org.simpleflatmapper.jdbc.JdbcMapperBuilder; import org.simpleflatmapper.jdbc.JdbcMapperFactory; import org.simpleflatmapper.test.beans.DbArrayObject; import org.simpleflatmapper.test.beans.DbArrayOfString; import org.simpleflatmapper.test.beans.DbObject; import org.simpleflatmapper.test.jdbc.DbHelper; import org.simpleflatmapper.test.jdbc.TestRowHandler; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Arrays; import java.util.Iterator; import java.util.List; import static org.junit.Assert.*; public class JdbcMapperArrayTest { private static final class TestDbArrayObject implements TestRowHandler<PreparedStatement> { private final boolean asm ; public TestDbArrayObject(boolean asm) { this.asm = asm; } @Override public void handle(PreparedStatement t) throws Exception { ResultSet rs = t.executeQuery(); final JdbcMapper<DbArrayObject> mapper = JdbcMapperFactoryHelper.asm().useAsm(asm).newBuilder(DbArrayObject.class) .addMapping(rs.getMetaData()) .mapper(); rs.next(); DbArrayObject object = mapper.map(rs); assertEquals(12, object.getId()); assertEquals(3, object.getObjects().length); assertNull(object.getObjects()[0]); DbHelper.assertDbObjectMapping(object.getObjects()[1]); DbHelper.assertDbObjectMapping(object.getObjects()[2]); } } private static final class TestArrayObject implements TestRowHandler<PreparedStatement> { private final boolean asm ; public TestArrayObject(boolean asm) { this.asm = asm; } @Override public void handle(PreparedStatement t) throws Exception { ResultSet rs = t.executeQuery(); final JdbcMapper<DbObject[]> mapper = JdbcMapperFactoryHelper.asm().useAsm(asm).newBuilder(DbObject[].class) .addMapping(rs.getMetaData()) .mapper(); rs.next(); DbObject[] list = mapper.map(rs); assertEquals(3, list.length); assertNull(list[0]); DbHelper.assertDbObjectMapping(list[1]); DbHelper.assertDbObjectMapping(list[2]); } } private static final class TestDbArrayString implements TestRowHandler<PreparedStatement> { private final boolean asm; public TestDbArrayString(boolean asm) { this.asm = asm; } @Override public void handle(PreparedStatement t) throws Exception { ResultSet rs = t.executeQuery(); JdbcMapperBuilder<DbArrayOfString> builder = JdbcMapperFactoryHelper.asm().useAsm(asm).newBuilder(DbArrayOfString.class).addMapping(rs.getMetaData()); final JdbcMapper<DbArrayOfString> mapper = builder.mapper(); rs.next(); DbArrayOfString object = mapper.map(rs); assertEquals(12, object.getId()); assertEquals(3, object.getObjects().length); assertNull(object.getObjects()[0]); assertEquals("value1", object.getObjects()[1]); assertEquals("value2", object.getObjects()[2]); } } private static final String QUERY = "select 12 as id, " + " 1 as objects_1_id, 'name 1' as objects_1_name, '<EMAIL>' as objects_1_email, TIMESTAMP'2014-03-04 11:10:03' as objects_1_creation_time, 2 as objects_1_type_ordinal, 'type4' as objects_1_type_name, " + " 1 as objects_2_id, 'name 1' as objects_2_name, '<EMAIL>' as objects_2_email, TIMESTAMP'2014-03-04 11:10:03' as objects_2_creation_time, 2 as objects_2_type_ordinal, 'type4' as objects_2_type_name " + " from TEST_DB_OBJECT "; private static final String QUERY_LIST = "select " + " 1 as objects_1_id, 'name 1' as objects_1_name, '<EMAIL>' as objects_1_email, TIMESTAMP'2014-03-04 11:10:03' as objects_1_creation_time, 2 as objects_1_type_ordinal, 'type4' as objects_1_type_name, " + " 1 as objects_2_id, 'name 1' as objects_2_name, '<EMAIL>' as objects_2_email, TIMESTAMP'2014-03-04 11:10:03' as objects_2_creation_time, 2 as objects_2_type_ordinal, 'type4' as objects_2_type_name " + " from TEST_DB_OBJECT "; private static final String QUERY_STRING_LIST = "select 12 as id, " + " 'value1' as objects_1, 'value2' as objects_2 from TEST_DB_OBJECT "; @Test public void testMapInnerObjectWithStaticMapperNoAsm() throws Exception { DbHelper.testQuery(new TestDbArrayObject(false), QUERY); } @Test public void testMapInnerObjectWithStaticMapperAsm() throws Exception { DbHelper.testQuery(new TestDbArrayObject(true), QUERY); } @Test public void testMapDbArrayOfStringNoAsm() throws Exception { DbHelper.testQuery(new TestDbArrayString(false), QUERY_STRING_LIST); } @Test public void testMapArrayOfStringAsm() throws Exception { DbHelper.testQuery(new TestDbArrayString(true), QUERY_STRING_LIST); } @Test public void testMapTestArrayObjectNoAsm() throws Exception { DbHelper.testQuery(new TestArrayObject(false), QUERY_LIST); } @Test public void testMapTestArrayObjectAsm() throws Exception { DbHelper.testQuery(new TestArrayObject(true), QUERY_LIST); } @Test public void testPlurals() throws Exception { DynamicJdbcMapper<Plural> mapper = JdbcMapperFactory.newInstance().addKeys("id").newMapper(Plural.class); Connection dbConnection = DbHelper.getDbConnection(DbHelper.TargetDB.POSTGRESQL); if (dbConnection == null) return; try { Statement statement = dbConnection.createStatement(); try { ResultSet rs = statement.executeQuery("WITH vals (id, label) AS (VALUES (1,'l1'), (1, 'l2'), (2, 'l3')) SELECT * FROM vals"); Iterator<Plural> iterator = mapper.iterator(rs); assertTrue(iterator.hasNext()); assertEquals(new Plural(1, Arrays.asList("l1", "l2")), iterator.next()); assertTrue(iterator.hasNext()); assertEquals(new Plural(2, Arrays.asList("l3")), iterator.next()); assertFalse(iterator.hasNext()); } finally { statement.close(); } } finally { dbConnection.close(); } } public static class Plural { public final long id; public final List<String> labels; public Plural(long id, List<String> labels) { this.id = id; this.labels = labels; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Plural plural = (Plural) o; if (id != plural.id) return false; return labels != null ? labels.equals(plural.labels) : plural.labels == null; } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (labels != null ? labels.hashCode() : 0); return result; } @Override public String toString() { return "Plural{" + "id=" + id + ", labels=" + labels + '}'; } } }
2,633
17,006
/** * 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. */ // -*- c++ -*- #pragma once #include <vector> #include <faiss/IndexFlat.h> #include <faiss/impl/NNDescent.h> #include <faiss/utils/utils.h> namespace faiss { /** The NNDescent index is a normal random-access index with an NNDescent * link structure built on top */ struct IndexNNDescent : Index { // internal storage of vectors (32 bits) using storage_idx_t = NNDescent::storage_idx_t; /// Faiss results are 64-bit using idx_t = Index::idx_t; // the link strcuture NNDescent nndescent; // the sequential storage bool own_fields; Index* storage; explicit IndexNNDescent( int d = 0, int K = 32, MetricType metric = METRIC_L2); explicit IndexNNDescent(Index* storage, int K = 32); ~IndexNNDescent() override; void add(idx_t n, const float* x) override; /// Trains the storage if needed void train(idx_t n, const float* x) override; /// entry point for search void search( idx_t n, const float* x, idx_t k, float* distances, idx_t* labels) const override; void reconstruct(idx_t key, float* recons) const override; void reset() override; }; /** Flat index topped with with a NNDescent structure to access elements * more efficiently. */ struct IndexNNDescentFlat : IndexNNDescent { IndexNNDescentFlat(); IndexNNDescentFlat(int d, int K, MetricType metric = METRIC_L2); }; } // namespace faiss
650
711
<reponame>jingetiema2100/MicroCommunity package com.java110.front.components.app; import com.java110.core.context.IPageData; import com.java110.front.smo.app.IAddAppSMO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; /** * 添加应用组件 */ @Component("addApp") public class AddAppComponent { @Autowired private IAddAppSMO addAppSMOImpl; /** * 添加应用数据 * @param pd 页面数据封装 * @return ResponseEntity 对象 */ public ResponseEntity<String> save(IPageData pd){ return addAppSMOImpl.saveApp(pd); } public IAddAppSMO getAddAppSMOImpl() { return addAppSMOImpl; } public void setAddAppSMOImpl(IAddAppSMO addAppSMOImpl) { this.addAppSMOImpl = addAppSMOImpl; } }
374
1,772
from django.test import TestCase from dojo.tools.h1.parser import H1Parser from dojo.models import Test class TestHackerOneParser(TestCase): def test_parse_file_with_no_vuln_has_no_finding(self): testfile = open("dojo/unittests/scans/h1/data_empty.json") parser = H1Parser() findings = parser.get_findings(testfile, Test()) self.assertEqual(0, len(findings)) def test_parse_file_with_one_vuln_has_one_finding(self): testfile = open("dojo/unittests/scans/h1/data_one.json") parser = H1Parser() findings = parser.get_findings(testfile, Test()) self.assertEqual(1, len(findings)) def test_parse_file_with_multiple_vuln_has_multiple_finding(self): testfile = open("dojo/unittests/scans/h1/data_many.json") parser = H1Parser() findings = parser.get_findings(testfile, Test()) self.assertEqual(2, len(findings))
392
4,612
<gh_stars>1000+ import io import sys from twisted.logger import eventsFromJSONLogFile, textFileLogObserver output = textFileLogObserver(sys.stdout) for event in eventsFromJSONLogFile(open("log.json")): output(event)
74
835
package ai.verta.modeldb; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class ModelDBTestUtils { private static final Logger LOGGER = LogManager.getLogger(ModelDBTestUtils.class); public static String readFile(String filePath) throws IOException { LOGGER.info("Start reading file : " + filePath); StringBuilder contentBuilder = new StringBuilder(); try (Stream<String> stream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) { stream.forEach(s -> contentBuilder.append(s).append("\n")); } catch (IOException e) { LOGGER.warn(e.getMessage(), e); throw e; } LOGGER.info("Stop reading file"); return contentBuilder.toString(); } }
318
431
#include "mtcnn.h" #include "mropencv.h" #if _WIN32 #pragma comment(lib,"ncnn.lib") #endif cv::Mat drawDetection(const cv::Mat &img, std::vector<Bbox> &box) { cv::Mat show = img.clone(); const int num_box = box.size(); std::vector<cv::Rect> bbox; bbox.resize(num_box); for (int i = 0; i < num_box; i++) { bbox[i] = cv::Rect(box[i].x1, box[i].y1, box[i].x2 - box[i].x1 + 1, box[i].y2 - box[i].y1 + 1); for (int j = 0; j < 5; j = j + 1) { cv::circle(show, cv::Point(box[i].ppoint[j], box[i].ppoint[j + 5]), 2, CV_RGB(0, 255, 0)); } } for (vector<cv::Rect>::iterator it = bbox.begin(); it != bbox.end(); it++) { rectangle(show, (*it), Scalar(0, 0, 255), 2, 8, 0); } return show; } void test_camera(MTCNN &mtcnn) { cv::VideoCapture mVideoCapture(0); cv::Mat frame; mVideoCapture >> frame; while (!frame.empty()) { mVideoCapture >> frame; if (frame.empty()) { break; } clock_t start_time = clock(); ncnn::Mat ncnn_img = ncnn::Mat::from_pixels(frame.data, ncnn::Mat::PIXEL_BGR2RGB, frame.cols, frame.rows); std::vector<Bbox> finalBbox; //mtcnn.detectMaxFace(ncnn_img, finalBbox); mtcnn.detect(ncnn_img, finalBbox); cv::Mat show = drawDetection(frame, finalBbox); clock_t finish_time = clock(); double total_time = (double)(finish_time - start_time) / CLOCKS_PER_SEC; std::cout << total_time * 1000 << "ms" << std::endl; cv::imshow("img", show); cv::waitKey(1); } return; } int main(int argc, char** argv){ MTCNN mtcnn; mtcnn.init("../model/ncnn"); mtcnn.SetMinFace(160); test_camera(mtcnn); return 0; }
875
679
<reponame>Grosskopf/openoffice /************************************************************** * * 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. * *************************************************************/ #ifndef DBGMACROS_HXX_INCLUDED #define DBGMACROS_HXX_INCLUDED void DbgAssert(bool condition, const char* message); #if OSL_DEBUG_LEVEL > 0 #define PRE_CONDITION(x, msg) DbgAssert(x, msg) #define POST_CONDITION(x, msg) DbgAssert(x, msg) #define ENSURE(x ,msg) DbgAssert(x, msg) #else // OSL_DEBUG_LEVEL == 0 #define PRE_CONDITION(x, msg) ((void)0) #define POST_CONDITION(x, msg) ((void)0) #define ENSURE(x, msg) ((void)0) #endif #endif
433
338
<reponame>XmobiTea-Family/ezyfox-server package com.tvd12.ezyfoxserver.ssl; import java.nio.file.Paths; import com.tvd12.ezyfox.mapping.properties.EzyPropertiesFileReader; import com.tvd12.ezyfox.mapping.properties.EzySimplePropertiesFileMapper; public class EzySimpleSslConfigLoader implements EzySslConfigLoader { @Override public EzySslConfig load(String filePath) { EzySimpleSslConfig answer = readConfig(filePath); String parent = getParentFolder(filePath); answer.setKeyStoreFile(getPath(parent, answer.getKeyStoreFile())); answer.setKeyStorePasswordFile(getPath(parent, answer.getKeyStorePasswordFile())); answer.setCertificatePasswordFile(getPath(parent, answer.getCertificatePasswordFile())); return answer; } protected EzySimpleSslConfig readConfig(String filePath) { return newPropertiesReader().read(filePath, EzySimpleSslConfig.class); } protected EzyPropertiesFileReader newPropertiesReader() { return EzySimplePropertiesFileMapper.builder() .context(getClass()) .build(); } protected String getParentFolder(String filePath) { return Paths.get(filePath).getParent().toString(); } protected String getPath(String first, String... more) { return Paths.get(first, more).toString(); } }
515
1,641
<gh_stars>1000+ from eth.vm.forks.petersburg.headers import ( compute_difficulty, ) from eth.vm.forks.istanbul.headers import ( configure_header, create_header_from_parent, ) compute_muir_glacier_difficulty = compute_difficulty(9000000) create_muir_glacier_header_from_parent = create_header_from_parent( compute_muir_glacier_difficulty ) configure_muir_glacier_header = configure_header(compute_muir_glacier_difficulty)
167
537
<filename>cpp/turbodbc_numpy/Library/turbodbc_numpy/ndarrayobject.h #pragma once /** * Include this file instead of the original Numpy header so common * problems with the API can be solved at a central position. */ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // compare http://docs.scipy.org/doc/numpy/reference/c-api.array.html#importing-the-api // as to why these defines are necessary #define PY_ARRAY_UNIQUE_SYMBOL turbodbc_numpy_API #define NO_IMPORT_ARRAY #include <Python.h> #include <numpy/ndarrayobject.h>
190
684
<reponame>MirageEarl/activiti /* 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.activiti.explorer.ui.content; import org.activiti.engine.task.Attachment; import com.vaadin.data.Validator.InvalidValueException; import com.vaadin.ui.Component; /** * Component that is capable of rendering an editable piece of related content. * * @see AttachmentRendererManager * * @author <NAME> */ public interface AttachmentEditorComponent extends Component { /** * Get the edited or created attachment based on the values filled in. <b>The * editor should save the attachment when this method is called.</b> * * @throws InvalidValueException * when validation of the values failed. Editor should show * error-message in component. */ Attachment getAttachment() throws InvalidValueException; }
389
1,273
<filename>src/main/java/org/broadinstitute/hellbender/utils/runtime/StreamingToolConstants.java<gh_stars>1000+ package org.broadinstitute.hellbender.utils.runtime; /** * Various constants used by StreamingProcessController that require synchronized equivalents in * the companion process, i.e., if the streaming process is written in Python, there must be * equivalent Python constants for use by the Python code. * * See the equivalents for Python in toolcontants.py. */ public class StreamingToolConstants { /** * Command acknowledgement messages used to signal positive acknowledgement ('ack'), * negative acknowledgement ('nck'), and negative acknowledgement with an accompanying * message ('nkm'). */ public static String STREAMING_ACK_MESSAGE = "ack"; public static String STREAMING_NCK_MESSAGE = "nck"; public static String STREAMING_NCK_WITH_MESSAGE_MESSAGE = "nkm"; // This is only used by Java, but is kept here since it represents the length of the constant // strings defined above. protected static int STREAMING_ACK_MESSAGE_SIZE = 3; // "ack", "nck", or "nkm" /** * Number of characters used to represent the length of the serialized message, fixed at a constant * 4 characters to ensure we can deterministically know how much input to wait for when looking for * a message length in the incoming stream. */ public static int STREAMING_NCK_WITH_MESSAGE_MESSAGE_LEN_SIZE = 4; public static int STREAMING_NCK_WITH_MESSAGE_MAX_MESSAGE_LENGTH = 9999; }
474
311
<reponame>MatthewMartinFD/dd-trace-java<gh_stars>100-1000 package datadog.trace.agent.tooling.context; import java.util.Collections; import java.util.HashMap; import java.util.Map; import net.bytebuddy.agent.builder.AgentBuilder; import net.bytebuddy.asm.AsmVisitorWrapper; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.matcher.ElementMatcher; import net.bytebuddy.utility.JavaModule; final class ContextStoreUtils { static AgentBuilder.Transformer wrapVisitor(final AsmVisitorWrapper visitor) { return new AgentBuilder.Transformer() { @Override public DynamicType.Builder<?> transform( final DynamicType.Builder<?> builder, final TypeDescription typeDescription, final ClassLoader classLoader, final JavaModule module) { return builder.visit(visitor); } }; } static Map<String, String> unpackContextStore( Map<ElementMatcher<ClassLoader>, Map<String, String>> matchedContextStores) { if (matchedContextStores.isEmpty()) { return Collections.emptyMap(); } else if (matchedContextStores.size() == 1) { return matchedContextStores.entrySet().iterator().next().getValue(); } else { Map<String, String> contextStore = new HashMap<>(); for (Map.Entry<ElementMatcher<ClassLoader>, Map<String, String>> matcherAndStores : matchedContextStores.entrySet()) { contextStore.putAll(matcherAndStores.getValue()); } return contextStore; } } }
558
695
<gh_stars>100-1000 /* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */ #ifndef ATOMIC_QUEUE_BENCHMARKS_H_INCLUDED #define ATOMIC_QUEUE_BENCHMARKS_H_INCLUDED #include <utility> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace atomic_queue { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct Context { unsigned producers; unsigned consumers; }; struct NoContext { template<class... Args> constexpr NoContext(Args&&...) noexcept {} }; template<class T> typename T::ContextType context_of_(int); template<class T> NoContext context_of_(long); template<class T> using ContextOf = decltype(context_of_<T>(0)); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct NoToken { template<class... Args> constexpr NoToken(Args&&...) noexcept {} template<class Queue, class T> static void push(Queue& q, T&& element) noexcept { q.push(std::forward<T>(element)); } template<class Queue> static auto pop(Queue& q) noexcept { return q.pop(); } }; template<class T> typename T::Producer producer_of_(int); template<class T> NoToken producer_of_(long); template<class T> using ProducerOf = decltype(producer_of_<T>(1)); template<class T> typename T::Consumer consumer_of_(int); template<class T> NoToken consumer_of_(long); template<class T> using ConsumerOf = decltype(consumer_of_<T>(1)); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } // atomic_queue //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif // ATOMIC_QUEUE_BENCHMARKS_H_INCLUDED
524
1,347
// Subclass of EJCanvasContextWebGL that renders to the screne (a UIView) #import "EJCanvasContextWebGL.h" #import "EAGLView.h" #import "EJPresentable.h" @interface EJCanvasContextWebGLScreen : EJCanvasContextWebGL <EJPresentable> { EAGLView *glview; CGRect style; } - (void)present; - (void)finish; @end
127
523
package com.fenchtose.nocropper; import android.graphics.Bitmap; import android.util.Log; public class Cropper { public final CropInfo cropInfo; public final Bitmap originalBitmap; private static final String TAG = "Cropper"; public Cropper(CropInfo cropInfo, Bitmap originalBitmap) { this.cropInfo = cropInfo; this.originalBitmap = originalBitmap; } public CropState crop(CropperCallback callback) { CropperTask task = new CropperTask(callback); task.execute(this); return CropState.STARTED; } public Bitmap cropBitmap() throws IllegalArgumentException { Log.i(TAG, "cropinfo: " + cropInfo + ", bitmap: " + originalBitmap.getWidth() + ", " + originalBitmap.getHeight()); return BitmapUtils.getCroppedBitmap(originalBitmap, cropInfo); } }
307
3,102
<filename>clang/test/Driver/arm-multilibs.c // RUN: %clang -target armv7-linux-gnueabi --sysroot=%S/Inputs/multilib_arm_linux_tree -### -c %s -o /dev/null 2>&1 | FileCheck -check-prefix CHECK-ARM %s // RUN: %clang -target thumbv7-linux-gnueabi --sysroot=%S/Inputs/multilib_arm_linux_tree -### -c %s -o /dev/null 2>&1 | FileCheck -check-prefix CHECK-ARM %s // RUN: %clang -target armv7-linux-gnueabihf --sysroot=%S/Inputs/multilib_armhf_linux_tree -### -c %s -o /dev/null 2>&1 | FileCheck -check-prefix CHECK-ARMHF %s // RUN: %clang -target thumbv7-linux-gnueabihf --sysroot=%S/Inputs/multilib_armhf_linux_tree -### -c %s -o /dev/null 2>&1 | FileCheck -check-prefix CHECK-ARMHF %s // RUN: %clang -target armv7eb-linux-gnueabi --sysroot=%S/Inputs/multilib_armeb_linux_tree -### -c %s -o /dev/null 2>&1 | FileCheck -check-prefix CHECK-ARMEB %s // RUN: %clang -target thumbv7eb-linux-gnueabi --sysroot=%S/Inputs/multilib_armeb_linux_tree -### -c %s -o /dev/null 2>&1 | FileCheck -check-prefix CHECK-ARMEB %s // RUN: %clang -target armv7eb-linux-gnueabihf --sysroot=%S/Inputs/multilib_armebhf_linux_tree -### -c %s -o /dev/null 2>&1 | FileCheck -check-prefix CHECK-ARMEBHF %s // RUN: %clang -target thumbv7eb-linux-gnueabihf --sysroot=%S/Inputs/multilib_armebhf_linux_tree -### -c %s -o /dev/null 2>&1 | FileCheck -check-prefix CHECK-ARMEBHF %s // CHECK-ARM: "-internal-externc-isystem" "{{.*}}/usr/include/arm-linux-gnueabi" // CHECK-ARMHF: "-internal-externc-isystem" "{{.*}}/usr/include/arm-linux-gnueabihf" // CHECK-ARMEB: "-internal-externc-isystem" "{{.*}}/usr/include/armeb-linux-gnueabi" // CHECK-ARMEBHF: "-internal-externc-isystem" "{{.*}}/usr/include/armeb-linux-gnueabihf"
730
4,253
package com.mashibing.mult; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import javax.sql.DataSource; import java.util.Map; public class DynamicDataSource extends AbstractRoutingDataSource { public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) { super.setDefaultTargetDataSource(defaultTargetDataSource); super.setTargetDataSources(targetDataSources); // afterPropertiesSet()方法调用时用来将targetDataSources的属性写入resolvedDataSources中的 super.afterPropertiesSet(); } /** * 根据Key获取数据源的信息 * * @return */ @Override protected Object determineCurrentLookupKey() { return DynamicDataSourceContextHolder.getDataSourceType(); } }
308
1,816
from src.masonite.providers import ( RouteProvider, FrameworkProvider, ViewProvider, WhitenoiseProvider, ExceptionProvider, MailProvider, SessionProvider, QueueProvider, CacheProvider, EventProvider, StorageProvider, HelpersProvider, BroadcastProvider, AuthenticationProvider, AuthorizationProvider, HashServiceProvider, ORMProvider, ) from src.masonite.scheduling.providers import ScheduleProvider from src.masonite.notification.providers import NotificationProvider from src.masonite.validation.providers.ValidationProvider import ValidationProvider from src.masonite.api.providers import ApiProvider from ..test_package import MyTestPackageProvider from tests.integrations.providers import AppProvider PROVIDERS = [ FrameworkProvider, HelpersProvider, RouteProvider, ViewProvider, WhitenoiseProvider, ExceptionProvider, MailProvider, NotificationProvider, SessionProvider, CacheProvider, QueueProvider, ScheduleProvider, EventProvider, StorageProvider, BroadcastProvider, HashServiceProvider, AuthenticationProvider, AuthorizationProvider, ValidationProvider, MyTestPackageProvider, AppProvider, ORMProvider, ApiProvider, ]
414
28,899
<reponame>RakhithJK/pandas<filename>pandas/tests/io/parser/common/test_float.py """ Tests that work on both the Python and C engines but do not have a specific classification into the other test modules. """ from io import StringIO import numpy as np import pytest from pandas.compat import is_platform_linux from pandas import DataFrame import pandas._testing as tm pytestmark = pytest.mark.usefixtures("pyarrow_skip") def test_float_parser(all_parsers): # see gh-9565 parser = all_parsers data = "45e-1,4.5,45.,inf,-inf" result = parser.read_csv(StringIO(data), header=None) expected = DataFrame([[float(s) for s in data.split(",")]]) tm.assert_frame_equal(result, expected) def test_scientific_no_exponent(all_parsers_all_precisions): # see gh-12215 df = DataFrame.from_dict({"w": ["2e"], "x": ["3E"], "y": ["42e"], "z": ["632E"]}) data = df.to_csv(index=False) parser, precision = all_parsers_all_precisions if parser == "pyarrow": pytest.skip() df_roundtrip = parser.read_csv(StringIO(data), float_precision=precision) tm.assert_frame_equal(df_roundtrip, df) @pytest.mark.parametrize("neg_exp", [-617, -100000, -99999999999999999]) def test_very_negative_exponent(all_parsers_all_precisions, neg_exp): # GH#38753 parser, precision = all_parsers_all_precisions if parser == "pyarrow": pytest.skip() data = f"data\n10E{neg_exp}" result = parser.read_csv(StringIO(data), float_precision=precision) expected = DataFrame({"data": [0.0]}) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("exp", [999999999999999999, -999999999999999999]) def test_too_many_exponent_digits(all_parsers_all_precisions, exp, request): # GH#38753 parser, precision = all_parsers_all_precisions data = f"data\n10E{exp}" result = parser.read_csv(StringIO(data), float_precision=precision) if precision == "round_trip": if exp == 999999999999999999 and is_platform_linux(): mark = pytest.mark.xfail(reason="GH38794, on Linux gives object result") request.node.add_marker(mark) value = np.inf if exp > 0 else 0.0 expected = DataFrame({"data": [value]}) else: expected = DataFrame({"data": [f"10E{exp}"]}) tm.assert_frame_equal(result, expected)
937
5,169
<gh_stars>1000+ { "name": "image-sequence-streaming", "version": "0.4.1", "summary": "Interactive image sequences with small memory footprint, nearly unlimited length, and lighting fast playback.", "description": "Interactive image sequences with small memory footprint, nearly unlimited length, and lighting fast playback.\nThis project aims to overcome these limitations by streaming individual frames, as fast as possible, from an optimized sequence file.", "homepage": "https://github.com/aceontech/image-sequence-streaming", "license": { "type": "MIT", "file": "source/LICENSE" }, "authors": "<NAME>", "platforms": { "ios": null }, "source": { "git": "https://github.com/aceontech/image-sequence-streaming.git", "tag": "0.4.1" }, "source_files": [ "source", "source/**/*.{h,m}" ], "requires_arc": false }
284
575
<gh_stars>100-1000 // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_OZONE_PLATFORM_WAYLAND_HOST_WAYLAND_DATA_DEVICE_H_ #define UI_OZONE_PLATFORM_WAYLAND_HOST_WAYLAND_DATA_DEVICE_H_ #include <cstdint> #include <memory> #include <string> #include "base/callback.h" #include "base/files/scoped_file.h" #include "base/gtest_prod_util.h" #include "ui/ozone/platform/wayland/common/wayland_object.h" #include "ui/ozone/platform/wayland/host/wayland_data_device_base.h" #include "ui/ozone/platform/wayland/host/wayland_data_source.h" #include "ui/ozone/public/platform_clipboard.h" namespace gfx { class PointF; } // namespace gfx namespace ui { class WaylandDataOffer; class WaylandConnection; class WaylandWindow; // This class provides access to inter-client data transfer mechanisms // such as copy-and-paste and drag-and-drop mechanisms. class WaylandDataDevice : public WaylandDataDeviceBase { public: using RequestDataCallback = base::OnceCallback<void(PlatformClipboard::Data)>; // DragDelegate is responsible for handling drag and drop sessions. class DragDelegate { public: virtual bool IsDragSource() const = 0; virtual void DrawIcon() = 0; virtual void OnDragOffer(std::unique_ptr<WaylandDataOffer> offer) = 0; virtual void OnDragEnter(WaylandWindow* window, const gfx::PointF& location, uint32_t serial) = 0; virtual void OnDragMotion(const gfx::PointF& location) = 0; virtual void OnDragLeave() = 0; virtual void OnDragDrop() = 0; protected: virtual ~DragDelegate() = default; }; WaylandDataDevice(WaylandConnection* connection, wl_data_device* data_device); WaylandDataDevice(const WaylandDataDevice&) = delete; WaylandDataDevice& operator=(const WaylandDataDevice&) = delete; ~WaylandDataDevice() override; // Starts a wayland drag and drop session, controlled by |delegate|. void StartDrag(const WaylandDataSource& data_source, const WaylandWindow& origin_window, wl_surface* icon_surface, DragDelegate* delegate); // Reset the drag delegate, assuming there is one set. Any wl_data_device // event received after this will be ignored until a new delegate is set. void ResetDragDelegate(); // Requests data for an |offer| in a format specified by |mime_type|. The // transfer happens asynchronously and |callback| is called when it is done. void RequestData(WaylandDataOffer* offer, const std::string& mime_type, RequestDataCallback callback); // Returns the underlying wl_data_device singleton object. wl_data_device* data_device() const { return data_device_.get(); } // wl_data_device::set_selection makes the corresponding wl_data_source the // target of future wl_data_device::data_offer events. In non-Wayland terms, // this is equivalent to "writing" to the clipboard or DnD, although the // actual transfer of data happens asynchronously, on-demand-only. // // The API relies on the assumption that the Wayland client is responding to a // keyboard or mouse event with a serial number. This is cached in // WaylandConnection. However, this may not exist or be set properly in tests, // resulting in the Wayland server ignoring the set_selection() request. void SetSelectionSource(WaylandDataSource* source); private: FRIEND_TEST_ALL_PREFIXES(WaylandDataDragControllerTest, StartDrag); void ReadDragDataFromFD(base::ScopedFD fd, RequestDataCallback callback); // wl_data_device_listener callbacks static void OnOffer(void* data, wl_data_device* data_device, wl_data_offer* id); static void OnEnter(void* data, wl_data_device* data_device, uint32_t serial, wl_surface* surface, wl_fixed_t x, wl_fixed_t y, wl_data_offer* offer); static void OnMotion(void* data, struct wl_data_device* data_device, uint32_t time, wl_fixed_t x, wl_fixed_t y); static void OnDrop(void* data, struct wl_data_device* data_device); static void OnLeave(void* data, struct wl_data_device* data_device); // Called by the compositor when the window gets pointer or keyboard focus, // or clipboard content changes behind the scenes. // // https://wayland.freedesktop.org/docs/html/apa.html#protocol-spec-wl_data_device static void OnSelection(void* data, wl_data_device* data_device, wl_data_offer* id); // The wl_data_device wrapped by this WaylandDataDevice. wl::Object<wl_data_device> data_device_; DragDelegate* drag_delegate_ = nullptr; // There are two separate data offers at a time, the drag offer and the // selection offer, each with independent lifetimes. When we receive a new // offer, it is not immediately possible to know whether the new offer is // the drag offer or the selection offer. This variable is used to store // new data offers temporarily until it is possible to determine which kind // session it belongs to. std::unique_ptr<WaylandDataOffer> new_offer_; }; } // namespace ui #endif // UI_OZONE_PLATFORM_WAYLAND_HOST_WAYLAND_DATA_DEVICE_H_
2,044
391
#include <esp_log.h> #include <wolfssl/wolfcrypt/hmac.h> #include "hkdf.h" #define TAG "HKDF" struct hkdf_salt_info { char* salt; char* info; }; static struct hkdf_salt_info _hkdf_salt_info[] = { { /* HKDF_KEY_TYPE_PAIR_SETUP_ENCRYPT */ .salt = "Pair-Setup-Encrypt-Salt", .info = "Pair-Setup-Encrypt-Info", }, { /* HKDF_KEY_TYPE_PAIR_SETUP_CONTROLLER */ .salt = "Pair-Setup-Controller-Sign-Salt", .info = "Pair-Setup-Controller-Sign-Info", }, { /* HKDF_KEY_TYPE_PAIR_SETUP_ACCESSORY */ .salt = "Pair-Setup-Accessory-Sign-Salt", .info = "Pair-Setup-Accessory-Sign-Info", }, { /* HKDF_KEY_TYPE_PAIR_VERIFY_ENCRYPT */ .salt = "Pair-Verify-Encrypt-Salt", .info = "Pair-Verify-Encrypt-Info", }, { /* HKDF_KEY_TYPE_CONTROL_READ */ .salt = "Control-Salt", .info = "Control-Read-Encryption-Key", }, { /* HKDF_KEY_TYPE_CONTROL_WRITE */ .salt = "Control-Salt", .info = "Control-Write-Encryption-Key", } }; static struct hkdf_salt_info* _salt_info_get(enum hkdf_key_type type) { return &_hkdf_salt_info[type]; } int hkdf_key_get(enum hkdf_key_type type, uint8_t* inkey, int inkey_len, uint8_t* outkey) { uint8_t key[CHACHA20_POLY1305_AEAD_KEYSIZE]; struct hkdf_salt_info* salt_info = _salt_info_get(type); int err = wc_HKDF(SHA512, inkey, inkey_len, (uint8_t*)salt_info->salt, strlen(salt_info->salt), (uint8_t*)salt_info->info, strlen(salt_info->info), key, CHACHA20_POLY1305_AEAD_KEYSIZE); if (err < 0) { ESP_LOGE(TAG, "wc_HKDF failed. %d\n", err); return err; } memcpy(outkey, key, CHACHA20_POLY1305_AEAD_KEYSIZE); return 0; }
916
3,172
{"kty": "EC", "kid": "<EMAIL>", "use": "sig", "crv": "P-521", "x": "<KEY>", "y": "<KEY>", "d": "<KEY>"}
54
547
<gh_stars>100-1000 // xlsxconditionalformatting.h #ifndef QXLSX_XLSXCONDITIONALFORMATTING_H #define QXLSX_XLSXCONDITIONALFORMATTING_H #include <QtGlobal> #include <QString> #include <QList> #include <QColor> #include <QXmlStreamReader> #include <QXmlStreamWriter> #include <QSharedDataPointer> #include "xlsxglobal.h" #include "xlsxcellrange.h" #include "xlsxcellreference.h" class ConditionalFormattingTest; QT_BEGIN_NAMESPACE_XLSX class Format; class Worksheet; class Styles; class ConditionalFormattingPrivate; class ConditionalFormatting { public: enum HighlightRuleType { Highlight_LessThan, Highlight_LessThanOrEqual, Highlight_Equal, Highlight_NotEqual, Highlight_GreaterThanOrEqual, Highlight_GreaterThan, Highlight_Between, Highlight_NotBetween, Highlight_ContainsText, Highlight_NotContainsText, Highlight_BeginsWith, Highlight_EndsWith, Highlight_TimePeriod, Highlight_Duplicate, Highlight_Unique, Highlight_Blanks, Highlight_NoBlanks, Highlight_Errors, Highlight_NoErrors, Highlight_Top, Highlight_TopPercent, Highlight_Bottom, Highlight_BottomPercent, Highlight_AboveAverage, Highlight_AboveOrEqualAverage, Highlight_AboveStdDev1, Highlight_AboveStdDev2, Highlight_AboveStdDev3, Highlight_BelowAverage, Highlight_BelowOrEqualAverage, Highlight_BelowStdDev1, Highlight_BelowStdDev2, Highlight_BelowStdDev3, Highlight_Expression }; enum ValueObjectType { VOT_Formula, VOT_Max, VOT_Min, VOT_Num, VOT_Percent, VOT_Percentile }; public: ConditionalFormatting(); ConditionalFormatting(const ConditionalFormatting &other); ~ConditionalFormatting(); public: bool addHighlightCellsRule(HighlightRuleType type, const Format &format, bool stopIfTrue=false); bool addHighlightCellsRule(HighlightRuleType type, const QString &formula1, const Format &format, bool stopIfTrue=false); bool addHighlightCellsRule(HighlightRuleType type, const QString &formula1, const QString &formula2, const Format &format, bool stopIfTrue=false); bool addDataBarRule(const QColor &color, bool showData=true, bool stopIfTrue=false); bool addDataBarRule(const QColor &color, ValueObjectType type1, const QString &val1, ValueObjectType type2, const QString &val2, bool showData=true, bool stopIfTrue=false); bool add2ColorScaleRule(const QColor &minColor, const QColor &maxColor, bool stopIfTrue=false); bool add3ColorScaleRule(const QColor &minColor, const QColor &midColor, const QColor &maxColor, bool stopIfTrue=false); QList<CellRange> ranges() const; void addCell(const CellReference &cell); void addCell(int row, int col); void addRange(int firstRow, int firstCol, int lastRow, int lastCol); void addRange(const CellRange &range); //needed by QSharedDataPointer!! ConditionalFormatting &operator=(const ConditionalFormatting &other); private: friend class Worksheet; friend class ::ConditionalFormattingTest; private: bool saveToXml(QXmlStreamWriter &writer) const; bool loadFromXml(QXmlStreamReader &reader, Styles* styles = NULL); QSharedDataPointer<ConditionalFormattingPrivate> d; }; QT_END_NAMESPACE_XLSX #endif // QXLSX_XLSXCONDITIONALFORMATTING_H
1,407
933
/* * Copyright (C) 2018 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. */ #include "src/traced/probes/ftrace/atrace_wrapper.h" #include <fcntl.h> #include <poll.h> #include <stdint.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "perfetto/base/build_config.h" #include "perfetto/base/logging.h" #include "perfetto/base/time.h" #include "perfetto/ext/base/optional.h" #include "perfetto/ext/base/pipe.h" #include "perfetto/ext/base/string_utils.h" #include "perfetto/ext/base/utils.h" #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #include <sys/system_properties.h> #endif // PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) namespace perfetto { namespace { RunAtraceFunction g_run_atrace_for_testing = nullptr; base::Optional<bool> g_is_old_atrace_for_testing{}; #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // Args should include "atrace" for argv[0]. bool ExecvAtrace(const std::vector<std::string>& args) { int status = 1; std::vector<char*> argv; // args, and then a null. argv.reserve(1 + args.size()); for (const auto& arg : args) argv.push_back(const_cast<char*>(arg.c_str())); argv.push_back(nullptr); // Create the pipe for the child process to return stderr. base::Pipe err_pipe = base::Pipe::Create(base::Pipe::kRdNonBlock); pid_t pid = fork(); PERFETTO_CHECK(pid >= 0); if (pid == 0) { // Duplicate the write end of the pipe into stderr. if ((dup2(*err_pipe.wr, STDERR_FILENO) == -1)) { const char kError[] = "Unable to duplicate stderr fd"; base::ignore_result(write(*err_pipe.wr, kError, sizeof(kError))); _exit(1); } int null_fd = open("/dev/null", O_RDWR); if (null_fd == -1) { const char kError[] = "Unable to open dev null"; base::ignore_result(write(*err_pipe.wr, kError, sizeof(kError))); _exit(1); } if ((dup2(null_fd, STDOUT_FILENO) == -1)) { const char kError[] = "Unable to duplicate stdout fd"; base::ignore_result(write(*err_pipe.wr, kError, sizeof(kError))); _exit(1); } if ((dup2(null_fd, STDIN_FILENO) == -1)) { const char kError[] = "Unable to duplicate stdin fd"; base::ignore_result(write(*err_pipe.wr, kError, sizeof(kError))); _exit(1); } // Close stdin/out + any file descriptor that we might have mistakenly // not marked as FD_CLOEXEC. |err_pipe| is FD_CLOEXEC and will be // automatically closed on exec. for (int i = 0; i < 128; i++) { if (i != STDIN_FILENO && i != STDERR_FILENO && i != STDOUT_FILENO) close(i); } execv("/system/bin/atrace", &argv[0]); // Reached only if execv fails. _exit(1); } // Close the write end of the pipe. err_pipe.wr.reset(); // Collect the output from child process. char buffer[4096]; std::string error; // Get the read end of the pipe. constexpr uint8_t kFdCount = 1; struct pollfd fds[kFdCount]{}; fds[0].fd = *err_pipe.rd; fds[0].events = POLLIN; // Store the start time of atrace and setup the timeout. constexpr auto timeout = base::TimeMillis(20000); auto start = base::GetWallTimeMs(); for (;;) { // Check if we are below the timeout and update the select timeout to // the time remaining. auto now = base::GetWallTimeMs(); auto remaining = timeout - (now - start); auto timeout_ms = static_cast<int>(remaining.count()); if (timeout_ms <= 0) { // Kill atrace. kill(pid, SIGKILL); std::string cmdline = "/system/bin/atrace"; for (const auto& arg : args) { cmdline += " " + arg; } error.append("Timed out waiting for atrace (cmdline: " + cmdline + ")"); break; } // Wait for the value of the timeout. auto ret = poll(fds, kFdCount, timeout_ms); if (ret == 0 || (ret < 0 && errno == EINTR)) { // Either timeout occurred in poll (in which case continue so that this // will be picked up by our own timeout logic) or we received an EINTR and // we should try again. continue; } else if (ret < 0) { error.append("Error while polling atrace stderr"); break; } // Data is available to be read from the fd. int64_t count = PERFETTO_EINTR(read(*err_pipe.rd, buffer, sizeof(buffer))); if (ret < 0 && errno == EAGAIN) { continue; } else if (count < 0) { error.append("Error while reading atrace stderr"); break; } else if (count == 0) { // EOF so we can exit this loop. break; } error.append(buffer, static_cast<size_t>(count)); } // Wait until the child process exits fully. PERFETTO_EINTR(waitpid(pid, &status, 0)); bool ok = WIFEXITED(status) && WEXITSTATUS(status) == 0; if (!ok) { // TODO(lalitm): use the stderr result from atrace. PERFETTO_ELOG("%s", error.c_str()); } return ok; } #endif } // namespace bool RunAtrace(const std::vector<std::string>& args) { if (g_run_atrace_for_testing) return g_run_atrace_for_testing(args); #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) return ExecvAtrace(args); #else PERFETTO_LOG("Atrace only supported on Android."); return false; #endif } void SetRunAtraceForTesting(RunAtraceFunction f) { g_run_atrace_for_testing = f; } bool IsOldAtrace() { if (g_is_old_atrace_for_testing.has_value()) return *g_is_old_atrace_for_testing; #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) && \ !PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD) // Sideloaded case. We could be sideloaded on a modern device or an older one. char str_value[PROP_VALUE_MAX]; if (!__system_property_get("ro.build.version.sdk", str_value)) return false; auto opt_value = base::CStringToUInt32(str_value); return opt_value.has_value() && *opt_value < 28; // 28 == Android P. #else // In in-tree builds we know that atrace is current, no runtime checks needed. return false; #endif } void SetIsOldAtraceForTesting(bool value) { g_is_old_atrace_for_testing = value; } void ClearIsOldAtraceForTesting() { g_is_old_atrace_for_testing.reset(); } } // namespace perfetto
2,610
4,812
<filename>llvm/lib/MC/MCDisassembler/MCSymbolizer.cpp //===-- llvm/MC/MCSymbolizer.cpp - MCSymbolizer class ---------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/MC/MCDisassembler/MCSymbolizer.h" using namespace llvm; MCSymbolizer::~MCSymbolizer() = default;
172
440
/*========================== begin_copyright_notice ============================ Copyright (C) 2017-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ #ifndef __LATENCY_TABLE_H #define __LATENCY_TABLE_H #include "../BuildIR.h" namespace vISA { enum LegacyLatencies : uint16_t { // // General instruction latencies // // To be comptabile with send cycles, don't normalized them to 1 UNCOMPR_LATENCY = 2, // Latency of an uncompressed instruction COMPR_LATENCY = 4, // Latency of a compressed instruction ACC_BUBBLE = 4, // Accumulator back-to-back stall IVB_PIPELINE_LENGTH = 14, EDGE_LATENCY_MATH = 22, EDGE_LATENCY_MATH_TYPE2 = 30, EDGE_LATENCY_SEND_WAR = 36 }; // // Message latencies // static const uint16_t LegacyFFLatency[] = { 2, // 0: SFID_NULL 2, // 1: Useless 300, // 2: SFID_SAMPLER 200, // 3: SFID_GATEWAY 400, // 4: SFID_DP_READ, SFID_DP_DC2 200, // 5: SFID_DP_WRITE 50, // 6: SFID_URB 50, // 7: SFID_SPAWNER 50, // 8: SFID_VME 60, // 9: SFID_DP_CC 400, //10: SFID_DP_DC 50, //11: SFID_DP_PI 400, //12: SFID_DP_DC1 200, //13: SFID_CRE 200 //14: unknown, SFID_NUM }; enum LatenciesXe : uint16_t { // // General instruction latencies // FPU_ACC = 6, // SIMD8 latency if dst is acc. FPU = 10, // SIMD8 latency for general FPU ops. MATH = 17, // Math latency. BRANCH = 23, // Latency for SIMD16 branch. BARRIER = 30, // Latency for barrier. DELTA = 1, // Extra cycles for wider SIMD sizes, compute only. DELTA_MATH = 4, ARF = 16, // latency for ARF dependencies (flag, address, etc.) // Latency for dpas 8x1 // Latency for dpas 8x8 is 21 + 7 = 28 DPAS = 21, // // Message latencies // // Latency for SIMD16 SLM messages. If accessing // the same location, it takes 28 cycles. For the // sequential access pattern, it takes 26 cycles. SLM = 28, SEND_OTHERS = 50, // Latency for other messages. DP_L3 = 146, // Dataport L3 hit SAMPLER_L3 = 214, // Sampler L3 hit SLM_FENCE = 23, // Fence SLM }; class LatencyTable { public: explicit LatencyTable(const IR_Builder* builder) : m_builder(builder) { } // Functions to get latencies/occupancy based on platforms uint16_t getOccupancy(G4_INST* Inst) const; uint16_t getLatency(G4_INST* Inst) const; uint16_t getDPAS8x8Latency() const; private: uint16_t getLatencyLegacy(G4_INST* Inst) const; uint16_t getOccupancyLegacy(G4_INST* Inst) const; uint16_t getLatencyG12(const G4_INST* Inst) const; uint16_t getOccupancyG12(G4_INST* Inst) const; const IR_Builder* m_builder; }; } // namespace vISA #endif
1,756
462
{ "appDesc": { "description": "App description.", "message": "Buat dan edit spreadsheet" }, "appName": { "description": "App name.", "message": "Google Spreadsheets" } }
84
4,065
<filename>richtext/src/main/java/com/zzhoujay/richtext/ext/TextKit.java package com.zzhoujay.richtext.ext; import android.text.TextUtils; /** * Created by zhou on 2017/2/21. * TextKit */ public class TextKit { private static final String ASSETS_PREFIX = "file:///android_asset/"; private static final String LOCAL_FILE_PREFIX = "/"; public static boolean isLocalPath(String path) { return !TextUtils.isEmpty(path) && path.startsWith(LOCAL_FILE_PREFIX); } public static boolean isAssetPath(String path) { return !TextUtils.isEmpty(path) && path.startsWith(ASSETS_PREFIX); } }
235
3,055
/* Fontname: -FreeType-Samim FD-Medium-R-Normal--10-100-72-72-P-52-ISO10646-1 Copyright: Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. DejaVu changes are in public domain Copyright (c) 2015 by <NAME>. All Rights Reserved. Non-Arabic(Latin) glyphs and data are imported from Open Sans font under the Apache License, Version 2.0. Glyphs: 486/489 BBX Build Mode: 0 */ const uint8_t u8g2_font_samim_fd_10_t_all[5714] U8G2_FONT_SECTION("u8g2_font_samim_fd_10_t_all") = "\346\0\3\2\4\4\4\5\5\23\17\373\374\10\375\7\376\1S\2\303\5G \5\0\10'!\7\201\11" "'.\1\42\7\42Y)\206\0#\21\206\10\255\222,\211\6)\211*\303RK\42\0$\15\224\371\254" "\242!i\322\244AK\0%\23\207\10o\242J)\321\22%J\224()%m\11\0&\17\206\10m" "\266$K\302P\222\22-Z\2'\6!Y%\4(\11\222\350f\22\245\247\0)\12\222\351&\222(" "\351\242\0*\13U\70\255\302h\220\244$\1+\12U\30\253\302h\220\302\10,\7\62\370d\224\4-" "\6\23('\6.\6\21\11'\2/\12\203\10\251Z\242J\24\1\60\10\63\31)\224d\1\61\11\202" "\11)\222R\322\1\62\13\204\11-\262(\221\262N\0\63\14\205\11/\242$R\224b\67\0\64\13\204" "\11-\222!\313\226\254\11\65\16\206\10\255R-\221*\241)\31\206\0\66\13t\11k\224,\134\262(" "\3\67\12t\31-\42K\344\24\1\70\12t\11m\62\311\322$\5\71\12t\10k\224HJ\266\6:" "\7Q\11'\262\0;\7q\371&\262\1<\12e\31-#)S\325\0=\10\64)-\206p\10>" "\12T)-D-Q\62\0\77\13\204\10)\306,\252\345@\4@\26\230\371\264\206,L\242E\211\22" "%J\224(\221\224(G\206\10A\15\206\10\355Bc\22\225\206$\24\3B\16\205\11-\206$\323\6" "%\263\15\12\0C\12\205\11\257\226,lM\7D\15\206\11\61\206(KBo\311\20\1E\13\204\11" "-\6-\33\264\332\20F\13\204\11+\6\255\66h\65\0G\16\206\11\261\206$Lkc\222EC\0" "H\13\206\11\61B\343\60\210\216\1I\7\201\11'\16\2J\10\243\347\246\372\323\2K\16\205\11-\62" "))iIT\211\222,L\11\204\11+\262\276\15\1M\20\207\11\63\304m\310\226\212RQ*&\251" "\0N\17\206\11\61\302M\211\224HJ\244D\33\3O\14\207\11\263\266J\352\232d\331\4P\14\205\11" "-\206$\263\15JX\4Q\17\247\351\262\266J\352\232d\331\234\3\11\0R\16\205\11/\206$\263\15" "J\224dZ\0S\13\205\11m\6\61U\213\203\2T\12\205\10+\6)\354\23\0U\12\206\11\61B" "\77&C\2V\13\206\10-B-\352\233h\2W\22\211\10\63\262L\253\64%\235\222\246$\262i%" "\0X\16\205\10-\262$\212\64S\22EZ\0Y\14\205\10+\62-)%Y\330\4Z\14\205\11/" "\6M+fa\66\10[\10\242\351(\226~\21\134\12\203\10)\242,\252E\5]\10\242\351(\224~" "\31^\13U\70\253\262$J\242\244\26_\7\25\350(\6\1`\7\42z-\242\0a\12d\10k\266" "d\210\244Ab\14\205\11-\302pH\62\267A\1c\10d\10i\206\254qd\13\205\10-+\203\346" "\226\14\1e\13e\10k\226l\30\302t\10f\12\204\10g\226h\312:\1g\16\225\330j\6MK" "\246p\311\264d\1h\13\205\11/\302pH\62o\1i\7\201\11'\222aj\11\262\330f\262\244/" "\3k\14\204\11-\262\222\222HI\247\0l\7\201\11'\16\2m\16g\11\63\26%\212\244H\212\244" "H*n\11e\11/\206$\363\26o\12e\10k\226\314-Y\0p\14\225\331,\206$s\33\224\260" "\10q\13\225\330l\6\315-\31\302\6r\11c\11)\206\250\23\0s\12d\10i\206L\324\206\4t" "\12\204\10i\262h\312\332\6u\11e\11/\62o\311\20v\15e\10+\62-)%Q\222E\0w" "\17h\10\61\242LR\242D\211\224\222S\4x\13e\10k\242\244\26fI-y\16\225\330*\62-" ")%Q\222\205%\15z\12d\11-\206,j\33\2{\13\243\350\246\222\250\222Em\1|\7\261\332" "*\36\4}\14\243\350&\262\250\244D-\21\0~\7%\71/V\1\240\5\0\10'\241\7\201\351&" "\222a\242\13\204\11\255\242!k\234\22\0\243\14\205\10\255\226\260\66Da\66\10\244\11T\31-\6\311" "\64\10\245\16\205\10+\62\251\22%\321\226m\21\0\246\10\261\332*\206l\10\247\15\204\11-\6Q\211" "\244D\34\22\0\250\6\21{-\2\251\22\210\10\261\206,Q\32\225P\11%)\11\263!\2\252\10C" "\70'\226C\0\253\10S\11+\22/\1\254\10\65\30+\6\261\0\255\6\23('\6\256\23\210\10\261" "\206lH:)\232RRJI\230\15\21\0\257\7\25\210+\6\1\260\10CIk*J\5\261\13e" "\10\253\302h\220\302h\20\262\10C\71+\246$\31\263\10C\70)\6m\10\264\7\42zm\24\0\265" "\13\225\331.\62o\303\20\26\1\266\11\245\350l\206\177\332<\267\6\21\71'\2\270\6\42\350d\6\271" "\7B\71)\224\6\272\11C\70'\206D\251\0\273\13T\10+\222(\351\242$\0\274\23\207\11\61\244" ",\312\222\60))\232\22%C\222%\0\275\20\207\10\61\244,\312\222\60\231\264$\213\312\3\276\24\210" "\10\61v \212\244\64\251(\211\226\324\222!\11\23\0\277\13\204\350\250r \213j\341\0\0\0\0\14" "\6\363\4Y\373\222\4\213\377\377\2\274\10\62Xe\224\4\2\306\10#ym\226\0\2\307\10#y-" "\222D\2\311\7\23y-\6\2\330\10#y-\222!\2\331\7\21y'\2\2\332\7\62j-\16\2" "\333\10\42\350$\22\1\2\334\11$ym\22%\1\2\335\10#ym\226\0\2\363\7\62\331(\16\3" "\11\10\42d!\224\0\3\17\10#s!\22%\3#\7\21\345 \2\3\204\10\42jm\24\0\6\14" "\7!\31'\4\6\25\10\62z!\222!\6\33\11R\11g\224,\1\6\37\14t\10i\206,\254\3" "\11\0\6!\11C\30'\206l\2\6\42\12\203\10'\306\250\27\0\6#\10\221\11'\224a\6$\14" "\243\331j\214\213\62D\321\2\6%\10\241\331&\36\2\6&\17\206\350nT\35\320\222\250\66&C\2" "\6'\10q\11'\16\1\6(\14h\350\62bs\62\354p\6\6)\14t\10itL\211\244D\1" "\6*\14X\30\363\222(\66'\303\2\6+\15h\10\63\343$\212\315\311\260\0\6,\16\205\330l\244" "H\312\212Q\222\16\1\6-\14\205\330l\244H\312\212\325!\6.\14\205\370l\244H\312\212\325!\6" "/\12D\31\253\302lH\0\6\60\13t\11+t\64\314\206\4\6\61\11T\330\350\232\206\10\6\62\14" "\204\330\250r\64+\15\21\0\6\63\23{\330\370\261\34\210\304(\21\207!L\303x\210\1\6\64\24\213" "\370\370\201\35\314\201H\214\22q\30\302\64\214\207\30\6\65\24|\330\370\221\35\211\306$J\302a\11\343" "\60\7\206\34\6\66\26\234\330\370\241\234eG\242\61\211\222pX\302\70\314\201!\7\6\67\17w\10q" "\342&)\211\22m\30\22\0\6\70\21w\10q\342(\213#)\211\22m\30\22\0\6\71\16\225\330\254" "\244\60]\262\60\24\207\0\6:\16\245\350\254B)L\227,\14\305!\6@\7\22\10#\4\6A\17" "y\30\263s\232\22&\305A\216\206\11\6B\21\226\330\354\222\34\22\23%\222\206P\213\206\4\6C\20" "x\11\365\201\60\312\212\221\224\311\311\260\0\6D\14\246\350n\273\212\216\311\220\0\6E\14u\330j\206" "$J\6\261\21\6F\14f\350\354\242\320\61\31\22\0\6G\13D\30i\224HJ\24\0\6H\13s" "\331j\26e\210\242\5\6I\15f\350n\265$\252\215\311\220\0\6J\17\206\310n\265$\252\215\311\220" "CI\2\6K\10\42j!\206\0\6L\11\63ja\242!\1\6M\10\62\332 \24\5\6N\7\22" "z#\4\6O\10\62j!\24\5\6P\10#\352\242\26\0\6Q\10#z\243\206\0\6R\10\42j" "!\206\0\6S\7\22i!\4\6T\10\42z!\206\0\6U\7!\352 \4\6W\10\63y\241\246" "\4\6Z\10#y-\62\1\6`\11\63\31)\224d\1\6a\12r\11)\222(\351\0\6b\14t" "\11-\262(\221\262&\0\6c\15u\11/\242$R\224b\33\0\6d\14t\11-\222![\262&" "\0\6e\17v\10\255R-J\262$T\242a\10\6f\14t\11k\224,J\244Z\6\6g\14t" "\11-\42S\42\231\42\0\6h\13t\11m\62\311\22\231\2\6i\13t\10k\224HJ\266\6\6j" "\14t\11-\242Z\224EY\24\6k\10\62\10i\22\5\6l\7!\351&\4\6n\13H\10\63b" "s\62,\0\6o\17v\330\354\304D\211\244!\324\242!\1\6p\7!{#\4\6t\10\62y'" "\226\4\6~\15x\330\62bs\62\354\350\234\1\6\206\16\205\330l\244H\312JS\222\16\1\6\230\14" "\224\330\250\242\35\314JC\4\6\241\16Y\10\263\225\60)\16r\64L\0\6\251\21y\10\365\1U\7" "\262\64\212\223\70\32&\0\6\257\23\231\11\367\221XNT\35\310\21)\215\342h\230\0\6\272\13V\350" ",B\307dH\0\6\300\14\204\10\251j\262bJ\24\0\6\312\15\223\331j\224hQ\206(Z\0\6" "\314\15f\350n\265$\252\215\311\220\0\6\325\13D\30i\224HJ\24\0\6\360\11\63\31)\224d\1" "\6\361\12r\11)\222(\351\0\6\362\14t\11-\262(\221\262&\0\6\363\15u\11/\242$R\224" "b\33\0\6\364\14t\11-\222![\262&\0\6\365\17v\10\255R-J\262$T\242a\10\6\366" "\14t\11k\224,J\244Z\6\6\367\14t\11-\42S\42\231\42\0\6\370\13t\11m\62\311\22\231" "\2\6\371\13t\10k\224HJ\266\6 \0\6\0\10+ \1\6\0\10\65 \2\6\0\10+ \3" "\6\0\10\65 \4\6\0\10' \5\6\0\10' \6\6\0\10% \7\6\0\10- \10\6\0" "\10' \11\6\0\10% \12\6\0\10# \13\6\0\10! \14\6\0\10! \15\6\0\10!" " \23\10\25(+\6\1 \24\10\32(\65\36\2 \25\10\32(\65\36\2 \27\11\64\330(\206p" "\10 \30\7\61X%\6 \31\7\61X%\6 \32\10\62\370d\224\4 \33\10\62X%\222( " "\34\11\63X)\22K\0 \35\11\63X)\22K\0 \36\10\63\370h\26% \14\204\11k\262" "hH\262N\0 !\16\204\11k\262hH\262hH\262\10 \42\7\62\71)\16 &\10\27\11\63" "\242\2 /\6\0\10# \60\30\213\10w\262\64)'\345\304T\221\224(\211\224(\211\224\232\224\0" " \62\7!Y%\4 \63\10\42Y)\206\0 \71\10B\30g\224( :\11B\31'\242D\1" " <\12\203\11+\22_\262$ D\15\205\6#\263\60\13\263\60\13\1 p\12C\70'\206D\31" "\2 t\11C\70\251\206!\12 u\11C\70'\6m\10 v\12C\70g\22%\31\2 w\12" "C\70'\246$J\0 x\12C\70)\206d\30\2 y\13C\70'\206$Q\22\0 \177\11\63" "H'\206D\11 \243\16\205\10k\206$,\16I\266e\0 \244\16\205\10\253\226\60\33\242l\210\262" "A \247\22\207\11\61\306(\213\222\322\60DI\230\204I( \253\24\246\350\254\206\60\32\222,\311\222" ",\311\242!\7\6\5 \254\17\206\10\255\206(\14\207h\310\342t\1!\5\21\207\11q\223%\312\242" "!N\262\244\224\64\15!\23\13s\11+\206DY\242L!\26\22y\11\65\262P\12\245D\251H\322" "dJ\262d! \16G\70\61\206H\32\222aP\242\0!\42\17G\70\61\206(I\206$\31\222R" "\0!&\15w\11q\6%\134\255I\226\34!.\14e\11\255\42\245\66\14\351\2![\21\207\11\61" "\244,\312\222\60))\245.\332\0!\134\21\207\10/\246,\211\244PI\226R\227\322\0!]\21\207" "\10/\246$\213\206TI\226R\227\322\0!^\20\207\10/\346$K\302\244\226\224\272\224\6\42\2\14" "u\10m\326d\320L\221\4\42\6\16u\10\255\262$J\242\244\246\15\3\42\17\12\246\331.\16\241\177" "\14\42\21\15\246\330,.q\265X\15\207\1\42\22\10\25\70-\6\1\42\32\17\226\10k\213i\42U" "\262$\24\63\0\42\36\13\66(o\224EI\6\1\42+\13\263\330\250\222\250\277D\0\42H\11\65(" "-\6u\20\42`\14U\30\355\222A\212\6%\3\42d\13e\10-#E\134\207\1\42e\13e\10" "-T\65R\264A$\0\6\0\10!%\312\14t\11m$%\62%R\4\373\0\22\207\10m\224%" "\212\206\251\26eQ\26eQ\4\373\1\21\205\10m\206$[JI\224DI\224D\1\373\2\22\205\10" "m\206$\32\222R\22%Q\22%Q\0\373\3\27\211\10u$-\12\207!)eI\224%Q\226D" "Y\22e\1\373\4\27\211\10u$\245\224\15\203R\312\222(K\242,\211\262$\312\2\373V\15x\330" "\62bs\62\354\350\234\1\373W\22z\330\64r(\7\222X\32\246\34Nr$\5\373X\13s\330\250" "JC\226T\0\373Y\14d\330\250\262D\11\223(\2\373z\16\205\330l\244H\312JS\222\16\1\373" "{\20w\330nv@\32\242p\11\243pP\0\373|\14v\330n\344M\331\301\61\2\373}\16w\330" "nt`\224&\35Z\63\0\373\212\14\224\350\250\242\35\314JC\4\373\213\14\225\330\252\262\235\20j%" "\15\373\216\21y\10\365\1U\7\262\64\212\223\70\32&\0\373\217\21z\10\365\1YG\302\64\213\243X" "\32\246\0\373\220\14u\10\355\24--&\23\0\373\221\14v\10\355$\61\256*S\0\373\222\23\231\11" "\367\221XNT\35\310\21)\215\342h\230\0\373\223\24\232\11\367\221\34\320\201D\326\221\34\322R)\226" "\206)\373\224\16\225\10-#)\61\211b\232L\0\373\225\16\226\10-\63-\221\64\271\252L\1\373\236" "\13V\350,B\307dH\0\373\237\16W\350.\302$\34\223\60\32\42\0\373\245\15\206\11\255\304\64\316" "\246\322\20\13\373\254\15V\10\255\302!J\226\312\60\4\373\255\15e\330\252\244$J\222\245-\2\373\350" "\11C\10\247JC\0\373\351\11\64\10\251\262D\11\373\374\15f\350n\265$\252\215\311\220\0\373\375\15" "G\350.\262!\33\322dP\0\373\376\12c\350\250JC\226\4\373\377\13T\350\250\262D\11\223\4\375" "\362\31\275\10\275s\64GsT\307\306\70\252E-SIj\32\244\306A\13\375\374!\256\330~\223\34" "Lr\60\311\301$\313\201$\213\302$\213\302hH\304\34H\206,\251\203\22\0\376p\10\42i)\206" "\0\376q\13\204\10i\264('\16\1\376r\11\63ig\242!\1\376s\10\42\11'\22\1\376t\10" "\62\331(\24\5\376v\7\22y)\4\376w\11\204\11)t\326!\376x\10\62i'\24\5\376y\14" "\244\10g\62-\312Y\206\0\376z\10#\351\250\26\0\376{\12\64\350(\206,Q\0\376|\10#y" "\251\206\0\376}\12\224\11\251\222\235q\10\376~\10\42i'\206\0\376\177\13\224\10g\224\222\316\60\4" "\376\200\11C\30'\206l\2\376\201\12\203\10'\306\250\27\0\376\202\11\223\10g:\365\26\376\203\10\221" "\11'\224a\376\204\12\242\11'\222,\351)\376\205\14\243\331j\214\213\62D\321\2\376\206\17\245\330j" "\304\34\321\222R\64d%\15\376\207\10\241\331&\36\2\376\210\12\242\331&\222\236\22\3\376\211\17\206\350" "nT\35\320\222\250\66&C\2\376\212\17w\330\256T\35\313\206lH\223A\1\376\213\13c\30g\242" ",\212\206\0\376\214\13d\10i$\35\310\22%\376\215\10q\11'\16\1\376\216\11r\11'\222\236\2" "\376\217\14h\350\62bs\62\354p\6\376\220\20j\350\64r(\7\222X\32\246\234\220\2\376\221\12c" "\350\246JC\230\0\376\222\13T\350\250\262D\11%\0\376\223\14t\10itL\211\244D\1\376\224\16" "u\10\255\222\34\211\226(\31\322\0\376\225\14X\30\363\222(\66'\303\2\376\226\16Z\10\365\306\34\312" "\201$\226\206)\376\227\13c\10'\222\64\212\206\0\376\230\13T\10)\222\34\310\22%\376\231\15h\10" "\63\343$\212\315\311\260\0\376\232\20j\10\65s\244\230C\71\220\304\322\60\5\376\233\12s\10gZ\243" "h\10\376\234\15t\10i\262(\311\201,Q\2\376\235\16\205\330l\244H\312\212Q\222\16\1\376\236\20" "w\330nv@\32\242p\312r`P\0\376\237\13f\350n\344M\331\321\10\376\240\15g\350nt`" "\224&\35\313\0\376\241\14\205\330l\244H\312\212\325!\376\242\17w\330nv@\32\242p\316\201A\1" "\376\243\12F\10o\344M\331\0\376\244\13G\10ot`\224&\1\376\245\14\205\370l\244H\312\212\325" "!\376\246\17w\10ov@\32\242p\316\201A\1\376\247\13f\10\257rL\336\224\15\376\250\14g\10" "\257rT\7Fi\22\376\251\12D\31\253\302lH\0\376\252\13U\10\255\302\64L\6\1\376\253\13t" "\11+t\64\314\206\4\376\254\14u\10\255r(L\303d\20\376\255\11T\330\350\232\206\10\376\256\12U" "\350\352B\255\244\1\376\257\14\204\330\250r\64+\15\21\0\376\260\14\205\330\252rJ\250\225\64\0\376\261" "\23{\330\370\261\34\210\304(\21\207!L\303x\210\1\376\262\24l\330\370\201(\11\223(\11\7E\214" "\303\34\30r\0\376\263\15H\7\361\201(\211Z\16\11\0\376\264\15\71\10s\242$\213*C\62\4\376" "\265\24\213\370\370\201\35\314\201H\214\22q\30\302\64\214\207\30\376\266\25\214\370\370\201\235!J\302$J" "\302A\21\343\60\7\206\34\376\267\17h\27q\343$G\242$j\71$\0\376\270\21i\30\63s \311" "\341(\311\242\312\220\14\1\376\271\24|\330\370\221\35\211\306$J\302a\11\343\60\7\206\34\376\272\26}" "\330\372\221\35\212\224\60\211\224p\70\346@\230#C\216\0\376\273\15H\10q\245\226R\222\14\12\0\376" "\274\15I\10s\265\250%K\222a\10\376\275\26\234\330\370\241\234eG\242\61\211\222pX\302\70\314\201" "!\7\376\276\30\235\330\372\241\234m\207\42%L\42%\34\216\71\20\346\310\220#\0\376\277\16h\10q" "s\212\324RJ\222A\1\376\300\17i\10ss\232\26\265dI\62\14\1\376\301\17w\10q\342&)" "\211\22m\30\22\0\376\302\22x\10qr \7r \322\222(\322\222a\20\376\303\17w\10q\342&" ")\211\22m\30\22\0\376\304\22x\10qr \7r \322\222(\322\222a\20\376\305\21w\10q\342" "(\213#)\211\22m\30\22\0\376\306\22x\10qr \12s \322\222(\322\222a\20\376\307\21w" "\10q\342(\213#)\211\22m\30\22\0\376\310\22x\10qr \12s \322\222(\322\222a\20\376" "\311\16\225\330\256\244\60]\262\60\24\207\0\376\312\20\206\330j\246,J\62-\32\322xH\0\376\313\12" "E\10\253\244\60\33\4\376\314\13F\10m\206\250\266,\2\376\315\16\245\350\254B)L\227,\14\305!" "\376\316\21\246\330\252rl\312\242$\323\242!\215\207\4\376\317\14u\10\253\302\34\222\302l\20\376\320\14" "f\10\255rl\210j\313\42\376\321\17y\30\263s\232\22&\305A\216\206\11\376\322\17j\30\363\201\234" "(\205Q\22\16\321p\376\323\14t\30\253r`H\222m\20\376\324\15f\30\255rP\213\242!\31\6" "\376\325\21\226\330\354\222\34\22\23%\222\206P\213\206\4\376\326\22\227\330\356\222\70T\223\246$\32\304$" "\223\206\10\376\327\14t\30kt`H\222m\20\376\330\15f\30m\352\230\26EC\62\14\376\331\20x" "\11\365\201\60\312\212\221\224\311\311\260\0\376\332\22y\11\365\201\64\12\263\64J\242,\211\243a\20\376\333" "\14u\10\355\24--&\23\0\376\334\14v\10\355$\61\256*S\0\376\335\14\246\350n\273\212\216\311" "\220\0\376\336\16\227\350n\343.a\22\216\321\20\1\376\337\11s\7\247zZ\0\376\340\12t\7\247\262" "^\206\0\376\341\14u\330j\206$J\6\261\21\376\342\14v\310\254L\211\264Hi\25\376\343\12E\7" "\353*Q\62\14\376\344\11\65\30k\246\244\62\376\345\14f\350\354\242\320\61\31\22\0\376\346\16g\350\356" "\212I\70&a\64D\0\376\347\12c\10g\342(\32\2\376\350\13T\10ir$K\224\0\376\351\13" "D\30i\224HJ\24\0\376\352\13U\10\355\242%J\206\64\376\353\15V\10\255\302!J\226\312\60\4" "\376\354\15e\330\252\244$J\222\245-\2\376\355\13s\331j\26e\210\242\5\376\356\15u\330j\264\244" "\24\15YI\3\376\357\15f\350n\265$\252\215\311\220\0\376\360\15G\350.\262!\33\322dP\0\376" "\361\17\206\310n\265$\252\215\311\220CI\2\376\362\17g\310.\262!\33\322d\320\261$\2\376\363\12" "c\350\250JC\226\4\376\364\13T\350\250\262D\11\223\4\376\365\16\206\7-v\244\26\365-\211\26\0" "\376\366\16\206\10-t\244\26\365-\211\226\0\376\367\22\225\10-\64\35H\242$J\242J\224$\13\0" "\376\370\16\226\10-D\35\211\372[\22-\1\376\371\21\245\330,\265$J\242$\252$S\26\206\0\376" "\372\17\246\330,\223,\352[\22-\305\64\5\376\373\17u\10-\265$J\242$\252$\13\0\376\374\15" "v\10-\223,\352[\22-\1\376\377\6\0\10!\0";
10,099
13,648
<reponame>sebastien-riou/micropython # test passing arguments @micropython.asm_thumb def arg0(): mov(r0, 1) print(arg0()) @micropython.asm_thumb def arg1(r0): add(r0, r0, 1) print(arg1(1)) @micropython.asm_thumb def arg2(r0, r1): add(r0, r0, r1) print(arg2(1, 2)) @micropython.asm_thumb def arg3(r0, r1, r2): add(r0, r0, r1) add(r0, r0, r2) print(arg3(1, 2, 3)) @micropython.asm_thumb def arg4(r0, r1, r2, r3): add(r0, r0, r1) add(r0, r0, r2) add(r0, r0, r3) print(arg4(1, 2, 3, 4))
302
1,561
/* * Description: Widget displaying a webots robot device */ #ifndef DEVICE_WIDGET_HPP #define DEVICE_WIDGET_HPP class QLabel; class QVBoxLayout; class QHBoxLayout; #include <QtWidgets/QWidget> namespace webotsQtUtils { class Device; class DeviceWidget : public QWidget { public: explicit DeviceWidget(Device *device, QWidget *parent = NULL); virtual ~DeviceWidget() {} virtual void readSensors() {} virtual void writeActuators() {} protected: void setTitleSuffix(const QString &suffix); Device *mDevice; QVBoxLayout *mVBoxLayout; QHBoxLayout *mTitleLayout; QWidget *mMainWidget; QWidget *mTitleWidget; QLabel *mTitleLabel; }; } // namespace webotsQtUtils #endif
270
539
from __future__ import print_function import python_compatibility_test as test import sys, getopt def schema(input_, output): obj = test.SchemaDef() schema = test.GetRuntimeSchema(test.Compat()) test.Unmarshal(input_.read(), obj) assert(obj == schema) output.write(test.Marshal(schema)) def compat(input_, output, test_case): obj = test.Compat() protocol = test.ProtocolType.COMPACT_PROTOCOL if (test_case == "json"): protocol = test.ProtocolType.SIMPLE_JSON_PROTOCOL test.Deserialize(input_.read(), obj, protocol) output.write(test.Serialize(obj, protocol)) def usage(): print('') print('compat.py -d INPUT_FILE -s OUTPUT_FILE TEST') print('') print(' -? --help show this help text') print(' TEST compact | json | schema') print(' -d --deserialize=INPUT_FILE deserialize object from specified file') print(' -s --serialize=OUTPUT_FILE serialize object to specified file') def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"?s:d:",["help","serialize=","deserialize="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ("-?", "--help"): usage() sys.exit() elif opt in ("-s", "--serialize"): outputfile = arg elif opt in ("-d", "--deserialize"): inputfile = arg if (len(args) != 1 \ or args[0] not in ("compact", "json", "schema")\ or inputfile == "" or outputfile == ""): usage() sys.exit(2) input_ = open(inputfile, "rb") output = open(outputfile, "wb+") if (args[0] == "schema"): schema(input_, output) else: compat(input_, output, args[0]) if __name__ == "__main__": main(sys.argv[1:])
838
1,144
/* * netlink/netlink-compat.h Netlink Compatability * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * Copyright (c) 2003-2006 <NAME> <<EMAIL>> */ #ifndef NETLINK_COMPAT_H_ #define NETLINK_COMPAT_H_ #if !defined _LINUX_SOCKET_H && !defined _BITS_SOCKADDR_H typedef unsigned short sa_family_t; #endif #ifndef IFNAMSIZ /** Maximum length of a interface name */ #define IFNAMSIZ 16 #endif /* patch 2.4.x if_arp */ #ifndef ARPHRD_INFINIBAND #define ARPHRD_INFINIBAND 32 #endif /* patch 2.4.x eth header file */ #ifndef ETH_P_MPLS_UC #define ETH_P_MPLS_UC 0x8847 #endif #ifndef ETH_P_MPLS_MC #define ETH_P_MPLS_MC 0x8848 #endif #ifndef ETH_P_EDP2 #define ETH_P_EDP2 0x88A2 #endif #ifndef ETH_P_HDLC #define ETH_P_HDLC 0x0019 #endif #ifndef AF_LLC #define AF_LLC 26 #endif #endif
426
1,338
/* EndpointInfo.cpp * ---------------- * Implements the EndpointInfo object. * * Copyright 2013, Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Revisions by <NAME> * * Copyright 1999, Be Incorporated. All Rights Reserved. * This file may be used under the terms of the Be Sample Code License. */ #include "EndpointInfo.h" #include <Bitmap.h> #include <Debug.h> #include <IconUtils.h> #include <Message.h> #include <MidiRoster.h> #include <MidiEndpoint.h> const char* LARGE_ICON_NAME = "be:large_icon"; const char* MINI_ICON_NAME = "be:mini_icon"; const char* VECTOR_ICON_NAME = "icon"; const uint32 LARGE_ICON_TYPE = 'ICON'; const uint32 MINI_ICON_TYPE = 'MICN'; const uint32 VECTOR_ICON_TYPE = 'VICN'; extern const uint8 LARGE_ICON_SIZE = 32; extern const uint8 MINI_ICON_SIZE = 16; extern const icon_size DISPLAY_ICON_SIZE = B_LARGE_ICON; extern const color_space ICON_COLOR_SPACE = B_CMAP8; static BBitmap* CreateIcon(const BMessage* msg, icon_size which); EndpointInfo::EndpointInfo() : fId(-1), fIcon(NULL) {} EndpointInfo::EndpointInfo(int32 id) : fId(id), fIcon(NULL) { BMidiRoster* roster = BMidiRoster::MidiRoster(); if (roster != NULL) { BMidiEndpoint* endpoint = roster->FindEndpoint(id); if (endpoint != NULL) { printf("endpoint %" B_PRId32 " = %p\n", id, endpoint); BMessage msg; if (endpoint->GetProperties(&msg) == B_OK) { fIcon = CreateIcon(&msg, DISPLAY_ICON_SIZE); } endpoint->Release(); } } } EndpointInfo::EndpointInfo(const EndpointInfo& info) : fId(info.fId) { fIcon = (info.fIcon) ? new BBitmap(info.fIcon) : NULL; } EndpointInfo& EndpointInfo::operator=(const EndpointInfo& info) { if (&info != this) { fId = info.fId; delete fIcon; fIcon = (info.fIcon) ? new BBitmap(info.fIcon) : NULL; } return *this; } EndpointInfo::~EndpointInfo() { delete fIcon; } void EndpointInfo::UpdateProperties(const BMessage* props) { delete fIcon; fIcon = CreateIcon(props, DISPLAY_ICON_SIZE); } static BBitmap* CreateIcon(const BMessage* msg, icon_size which) { const void* data; ssize_t size; BBitmap* bitmap = NULL; // See if a Haiku Vector Icon available if (msg->FindData(VECTOR_ICON_NAME, VECTOR_ICON_TYPE, &data, &size) == B_OK) { BRect r(0, 0, LARGE_ICON_SIZE - 1, LARGE_ICON_SIZE - 1); bitmap = new BBitmap(r, B_RGBA32); if (BIconUtils::GetVectorIcon((const uint8*)data, size, bitmap) == B_OK) { printf("Created vector icon bitmap\n"); return bitmap; } else { delete bitmap; bitmap = NULL; } } // If not, look for BeOS style icon float bmapSize; uint32 iconType; const char* iconName; if (which == B_LARGE_ICON) { bmapSize = LARGE_ICON_SIZE - 1; iconType = LARGE_ICON_TYPE; iconName = LARGE_ICON_NAME; } else if (which == B_MINI_ICON) { bmapSize = MINI_ICON_SIZE - 1; iconType = MINI_ICON_TYPE; iconName = MINI_ICON_NAME; } else return NULL; if (msg->FindData(iconName, iconType, &data, &size) == B_OK) { bitmap = new BBitmap(BRect(0, 0, bmapSize, bmapSize), ICON_COLOR_SPACE); ASSERT((bitmap->BitsLength() == size)); memcpy(bitmap->Bits(), data, size); } return bitmap; }
1,316
1,163
/* * Copyright 2020 The IREE Authors * * Licensed under the Apache License v2.0 with LLVM Exceptions. * See https://llvm.org/LICENSE.txt for license information. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ package com.google.iree; import java.util.concurrent.CancellationException; import java.util.concurrent.TimeoutException; /** Well-known status codes matching iree_status_code_t values. */ public enum Status { OK, CANCELLED, UNKNOWN, INVALID_ARGUMENT, DEADLINE_EXCEEDED, NOT_FOUND, ALREADY_EXISTS, PERMISSION_DENIED, UNAUTHENTICATED, RESOURCE_EXHAUSTED, FAILED_PRECONDITION, ABORTED, OUT_OF_RANGE, UNIMPLEMENTED, INTERNAL, UNAVAILABLE, DATA_LOSS; public boolean isOk() { return this == Status.OK; } public Exception toException(String message) { String messageWithStatus = this + ": " + message; switch (this) { case CANCELLED: return new CancellationException(messageWithStatus); case UNKNOWN: return new RuntimeException(messageWithStatus); case INVALID_ARGUMENT: return new IllegalArgumentException(messageWithStatus); case DEADLINE_EXCEEDED: return new TimeoutException(messageWithStatus); case NOT_FOUND: return new RuntimeException(messageWithStatus); case ALREADY_EXISTS: return new IllegalStateException(messageWithStatus); case PERMISSION_DENIED: return new IllegalAccessException(messageWithStatus); case RESOURCE_EXHAUSTED: return new RuntimeException(messageWithStatus); case FAILED_PRECONDITION: return new IllegalStateException(messageWithStatus); case ABORTED: return new InterruptedException(messageWithStatus); case OUT_OF_RANGE: return new IndexOutOfBoundsException(messageWithStatus); case UNIMPLEMENTED: return new UnsupportedOperationException(messageWithStatus); case INTERNAL: return new RuntimeException(messageWithStatus); case UNAVAILABLE: return new IllegalStateException(messageWithStatus); case DATA_LOSS: return new RuntimeException(messageWithStatus); case UNAUTHENTICATED: return new IllegalStateException(messageWithStatus); default: return new RuntimeException(messageWithStatus); } } public static Status fromCode(int code) { return Status.values()[code]; } }
894
9,402
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _ICorJitCompilerImpl #define _ICorJitCompilerImpl // ICorJitCompilerImpl: declare for implementation all the members of the ICorJitCompiler interface (which are // specified as pure virtual methods). This is done once, here, and all implementations share it, // to avoid duplicated declarations. This file is #include'd within all the ICorJitCompiler implementation // classes. // // NOTE: this file is in exactly the same order, with exactly the same whitespace, as the ICorJitCompiler // interface declaration (with the "virtual" and "= 0" syntax removed). This is to make it easy to compare // against the interface declaration. public: // compileMethod is the main routine to ask the JIT Compiler to create native code for a method. The // method to be compiled is passed in the 'info' parameter, and the code:ICorJitInfo is used to allow the // JIT to resolve tokens, and make any other callbacks needed to create the code. nativeEntry, and // nativeSizeOfCode are just for convenience because the JIT asks the EE for the memory to emit code into // (see code:ICorJitInfo.allocMem), so really the EE already knows where the method starts and how big // it is (in fact, it could be in more than one chunk). // // * In the 32 bit jit this is implemented by code:CILJit.compileMethod // * For the 64 bit jit this is implemented by code:PreJit.compileMethod // // Note: setTargetOS must be called before this api is used. CorJitResult compileMethod(ICorJitInfo* comp, /* IN */ struct CORINFO_METHOD_INFO* info, /* IN */ unsigned /* code:CorJitFlag */ flags, /* IN */ uint8_t** nativeEntry, /* OUT */ uint32_t* nativeSizeOfCode /* OUT */ ); // Do any appropriate work at process shutdown. Default impl is to do nothing. void ProcessShutdownWork(ICorStaticInfo* info); /* {}; */ // The EE asks the JIT for a "version identifier". This represents the version of the JIT/EE interface. // If the JIT doesn't implement the same JIT/EE interface expected by the EE (because the JIT doesn't // return the version identifier that the EE expects), then the EE fails to load the JIT. // void getVersionIdentifier(GUID* versionIdentifier /* OUT */ ); // When the EE loads the System.Numerics.Vectors assembly, it asks the JIT what length (in bytes) of // SIMD vector it supports as an intrinsic type. Zero means that the JIT does not support SIMD // intrinsics, so the EE should use the default size (i.e. the size of the IL implementation). unsigned getMaxIntrinsicSIMDVectorLength(CORJIT_FLAGS cpuCompileFlags); /* { return 0; } */ // Some JIT's may support multiple OSs. This api provides a means to specify to the JIT what OS it should // be trying to compile. This api does not produce any errors, any errors are to be generated by the // the compileMethod call, which will call back into the VM to ensure bits are correctly setup. // // Note: this api MUST be called before the compileMethod is called for the first time in the process. void setTargetOS(CORINFO_OS os); #endif
1,045
1,275
# # Copyright 2015-2016 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. # # Python bindings for mgmt library # -*- coding: utf-8 -*- # # WORD_SIZE is: 8 # POINTER_SIZE is: 8 # LONGDOUBLE_SIZE is: 16 # import ctypes _libraries = {} _libraries['libfpga_mgmt.so'] = ctypes.CDLL('libfpga_mgmt.so') # if local wordsize is same as target, keep ctypes pointer function. if ctypes.sizeof(ctypes.c_void_p) == 8: POINTER_T = ctypes.POINTER else: # required to access _ctypes import _ctypes # Emulate a pointer class using the approriate c_int32/c_int64 type # The new class should have : # ['__module__', 'from_param', '_type_', '__dict__', '__weakref__', '__doc__'] # but the class should be submitted to a unique instance for each base type # to that if A == B, POINTER_T(A) == POINTER_T(B) ctypes._pointer_t_type_cache = {} def POINTER_T(pointee): # a pointer should have the same length as LONG fake_ptr_base_type = ctypes.c_uint64 # specific case for c_void_p if pointee is None: # VOID pointer type. c_void_p. pointee = type(None) # ctypes.c_void_p # ctypes.c_ulong clsname = 'c_void' else: clsname = pointee.__name__ if clsname in ctypes._pointer_t_type_cache: return ctypes._pointer_t_type_cache[clsname] # make template class _T(_ctypes._SimpleCData,): _type_ = 'L' _subtype_ = pointee def _sub_addr_(self): return self.value def __repr__(self): return '%s(%d)'%(clsname, self.value) def contents(self): raise TypeError('This is not a ctypes pointer.') def __init__(self, **args): raise TypeError('This is not a ctypes pointer. It is not instanciable.') _class = type('LP_%d_%s'%(8, clsname), (_T,),{}) ctypes._pointer_t_type_cache[clsname] = _class return _class c_int128 = ctypes.c_ubyte*16 c_uint128 = c_int128 void = None if ctypes.sizeof(ctypes.c_longdouble) == 16: c_long_double_t = ctypes.c_longdouble else: c_long_double_t = ctypes.c_ubyte*16 fpga_mgmt_init = _libraries['libfpga_mgmt.so'].fpga_mgmt_init fpga_mgmt_init.restype = ctypes.c_int32 fpga_mgmt_init.argtypes = [] fpga_mgmt_close = _libraries['libfpga_mgmt.so'].fpga_mgmt_close fpga_mgmt_close.restype = ctypes.c_int32 fpga_mgmt_close.argtypes = [] fpga_mgmt_strerror = _libraries['libfpga_mgmt.so'].fpga_mgmt_strerror fpga_mgmt_strerror.restype = POINTER_T(ctypes.c_char) fpga_mgmt_strerror.argtypes = [ctypes.c_int32] fpga_mgmt_strerror_long = _libraries['libfpga_mgmt.so'].fpga_mgmt_strerror_long fpga_mgmt_strerror_long.restype = POINTER_T(ctypes.c_char) fpga_mgmt_strerror_long.argtypes = [ctypes.c_int32] uint32_t = ctypes.c_uint32 fpga_mgmt_set_cmd_timeout = _libraries['libfpga_mgmt.so'].fpga_mgmt_set_cmd_timeout fpga_mgmt_set_cmd_timeout.restype = None fpga_mgmt_set_cmd_timeout.argtypes = [uint32_t] fpga_mgmt_set_cmd_delay_msec = _libraries['libfpga_mgmt.so'].fpga_mgmt_set_cmd_delay_msec fpga_mgmt_set_cmd_delay_msec.restype = None fpga_mgmt_set_cmd_delay_msec.argtypes = [uint32_t] class struct_fpga_mgmt_image_info(ctypes.Structure): pass class struct_fpga_meta_ids(ctypes.Structure): pass class struct_afi_device_ids(ctypes.Structure): _pack_ = True # source:True _fields_ = [ ('vendor_id', ctypes.c_uint16), ('device_id', ctypes.c_uint16), ('svid', ctypes.c_uint16), ('ssid', ctypes.c_uint16), ] struct_fpga_meta_ids._pack_ = True # source:True struct_fpga_meta_ids._fields_ = [ ('afi_id', ctypes.c_char * 64), ('afi_device_ids', struct_afi_device_ids), ] class struct_fpga_slot_spec(ctypes.Structure): pass class struct_fpga_pci_resource_map(ctypes.Structure): _pack_ = True # source:True _fields_ = [ ('vendor_id', ctypes.c_uint16), ('device_id', ctypes.c_uint16), ('subsystem_device_id', ctypes.c_uint16), ('subsystem_vendor_id', ctypes.c_uint16), ('domain', ctypes.c_uint16), ('bus', ctypes.c_ubyte), ('dev', ctypes.c_ubyte), ('func', ctypes.c_ubyte), ('resource_burstable', ctypes.c_bool * 5), ('resource_size', ctypes.c_uint64 * 5), ] struct_fpga_slot_spec._pack_ = True # source:True struct_fpga_slot_spec._fields_ = [ ('map', struct_fpga_pci_resource_map * 2), ] class struct_fpga_metrics_common(ctypes.Structure): pass class struct_fpga_ddr_if_metrics_common(ctypes.Structure): _pack_ = True # source:True _fields_ = [ ('write_count', ctypes.c_uint64), ('read_count', ctypes.c_uint64), ] class struct_fpga_clocks_common(ctypes.Structure): _pack_ = True # source:True _fields_ = [ ('frequency', ctypes.c_uint64 * 7), ] struct_fpga_metrics_common._pack_ = True # source:True struct_fpga_metrics_common._fields_ = [ ('int_status', ctypes.c_uint32), ('pcim_axi_protocol_error_status', ctypes.c_uint32), ('dma_pcis_timeout_addr', ctypes.c_uint64), ('dma_pcis_timeout_count', ctypes.c_uint32), ('pcim_range_error_addr', ctypes.c_uint64), ('pcim_range_error_count', ctypes.c_uint32), ('pcim_axi_protocol_error_addr', ctypes.c_uint64), ('pcim_axi_protocol_error_count', ctypes.c_uint32), ('reserved2', ctypes.c_ubyte * 12), ('ocl_slave_timeout_addr', ctypes.c_uint64), ('ocl_slave_timeout_count', ctypes.c_uint32), ('bar1_slave_timeout_addr', ctypes.c_uint64), ('bar1_slave_timeout_count', ctypes.c_uint32), ('sdacl_slave_timeout_addr', ctypes.c_uint32), ('sdacl_slave_timeout_count', ctypes.c_uint32), ('virtual_jtag_slave_timeout_addr', ctypes.c_uint32), ('virtual_jtag_slave_timeout_count', ctypes.c_uint32), ('pcim_write_count', ctypes.c_uint64), ('pcim_read_count', ctypes.c_uint64), ('ddr_ifs', struct_fpga_ddr_if_metrics_common * 4), ('clocks', struct_fpga_clocks_common * 3), ('power_mean', ctypes.c_uint64), ('power_max', ctypes.c_uint64), ('power', ctypes.c_uint64), ('cached_agfis', ctypes.c_uint64 * 16), ('flags', ctypes.c_uint64), ] struct_fpga_mgmt_image_info._pack_ = True # source:False struct_fpga_mgmt_image_info._fields_ = [ ('status', ctypes.c_int32), ('status_q', ctypes.c_int32), ('slot_id', ctypes.c_int32), ('ids', struct_fpga_meta_ids), ('spec', struct_fpga_slot_spec), ('sh_version', ctypes.c_uint32), ('metrics', struct_fpga_metrics_common), ] fpga_mgmt_describe_local_image = _libraries['libfpga_mgmt.so'].fpga_mgmt_describe_local_image fpga_mgmt_describe_local_image.restype = ctypes.c_int32 fpga_mgmt_describe_local_image.argtypes = [ctypes.c_int32, POINTER_T(struct_fpga_mgmt_image_info), uint32_t] fpga_mgmt_get_status = _libraries['libfpga_mgmt.so'].fpga_mgmt_get_status fpga_mgmt_get_status.restype = ctypes.c_int32 fpga_mgmt_get_status.argtypes = [ctypes.c_int32, POINTER_T(ctypes.c_int32), POINTER_T(ctypes.c_int32)] fpga_mgmt_get_status_name = _libraries['libfpga_mgmt.so'].fpga_mgmt_get_status_name fpga_mgmt_get_status_name.restype = POINTER_T(ctypes.c_char) fpga_mgmt_get_status_name.argtypes = [ctypes.c_int32] fpga_mgmt_clear_local_image = _libraries['libfpga_mgmt.so'].fpga_mgmt_clear_local_image fpga_mgmt_clear_local_image.restype = ctypes.c_int32 fpga_mgmt_clear_local_image.argtypes = [ctypes.c_int32] fpga_mgmt_clear_local_image_sync = _libraries['libfpga_mgmt.so'].fpga_mgmt_clear_local_image_sync fpga_mgmt_clear_local_image_sync.restype = ctypes.c_int32 fpga_mgmt_clear_local_image_sync.argtypes = [ctypes.c_int32, uint32_t, uint32_t, POINTER_T(struct_fpga_mgmt_image_info)] fpga_mgmt_load_local_image = _libraries['libfpga_mgmt.so'].fpga_mgmt_load_local_image fpga_mgmt_load_local_image.restype = ctypes.c_int32 fpga_mgmt_load_local_image.argtypes = [ctypes.c_int32, POINTER_T(ctypes.c_char)] fpga_mgmt_load_local_image_flags = _libraries['libfpga_mgmt.so'].fpga_mgmt_load_local_image_flags fpga_mgmt_load_local_image_flags.restype = ctypes.c_int32 fpga_mgmt_load_local_image_flags.argtypes = [ctypes.c_int32, POINTER_T(ctypes.c_char), uint32_t] class union_fpga_mgmt_load_local_image_options(ctypes.Union): pass class struct_fpga_mgmt_load_local_image_options_0(ctypes.Structure): _pack_ = True # source:False _fields_ = [ ('slot_id', ctypes.c_int32), ('PADDING_0', ctypes.c_ubyte * 4), ('afi_id', POINTER_T(ctypes.c_char)), ('flags', ctypes.c_uint32), ('clock_mains', ctypes.c_uint32 * 3), ] union_fpga_mgmt_load_local_image_options._pack_ = True # source:False union_fpga_mgmt_load_local_image_options._fields_ = [ ('reserved', ctypes.c_ubyte * 1024), ('_1', struct_fpga_mgmt_load_local_image_options_0), ('PADDING_0', ctypes.c_ubyte * 992), ] fpga_mgmt_init_load_local_image_options = _libraries['libfpga_mgmt.so'].fpga_mgmt_init_load_local_image_options fpga_mgmt_init_load_local_image_options.restype = ctypes.c_int32 fpga_mgmt_init_load_local_image_options.argtypes = [POINTER_T(union_fpga_mgmt_load_local_image_options)] fpga_mgmt_load_local_image_with_options = _libraries['libfpga_mgmt.so'].fpga_mgmt_load_local_image_with_options fpga_mgmt_load_local_image_with_options.restype = ctypes.c_int32 fpga_mgmt_load_local_image_with_options.argtypes = [POINTER_T(union_fpga_mgmt_load_local_image_options)] fpga_mgmt_load_local_image_sync = _libraries['libfpga_mgmt.so'].fpga_mgmt_load_local_image_sync fpga_mgmt_load_local_image_sync.restype = ctypes.c_int32 fpga_mgmt_load_local_image_sync.argtypes = [ctypes.c_int32, POINTER_T(ctypes.c_char), uint32_t, uint32_t, POINTER_T(struct_fpga_mgmt_image_info)] fpga_mgmt_load_local_image_sync_flags = _libraries['libfpga_mgmt.so'].fpga_mgmt_load_local_image_sync_flags fpga_mgmt_load_local_image_sync_flags.restype = ctypes.c_int32 fpga_mgmt_load_local_image_sync_flags.argtypes = [ctypes.c_int32, POINTER_T(ctypes.c_char), uint32_t, uint32_t, uint32_t, POINTER_T(struct_fpga_mgmt_image_info)] fpga_mgmt_load_local_image_sync_with_options = _libraries['libfpga_mgmt.so'].fpga_mgmt_load_local_image_sync_with_options fpga_mgmt_load_local_image_sync_with_options.restype = ctypes.c_int32 fpga_mgmt_load_local_image_sync_with_options.argtypes = [POINTER_T(union_fpga_mgmt_load_local_image_options), uint32_t, uint32_t, POINTER_T(struct_fpga_mgmt_image_info)] fpga_mgmt_get_vLED_status = _libraries['libfpga_mgmt.so'].fpga_mgmt_get_vLED_status fpga_mgmt_get_vLED_status.restype = ctypes.c_int32 fpga_mgmt_get_vLED_status.argtypes = [ctypes.c_int32, POINTER_T(ctypes.c_uint16)] uint16_t = ctypes.c_uint16 fpga_mgmt_set_vDIP = _libraries['libfpga_mgmt.so'].fpga_mgmt_set_vDIP fpga_mgmt_set_vDIP.restype = ctypes.c_int32 fpga_mgmt_set_vDIP.argtypes = [ctypes.c_int32, uint16_t] fpga_mgmt_get_vDIP_status = _libraries['libfpga_mgmt.so'].fpga_mgmt_get_vDIP_status fpga_mgmt_get_vDIP_status.restype = ctypes.c_int32 fpga_mgmt_get_vDIP_status.argtypes = [ctypes.c_int32, POINTER_T(ctypes.c_uint16)] # values for enumeration 'c__Ea_FPGA_CMD_RSVD' c__Ea_FPGA_CMD_RSVD__enumvalues = { 1: 'FPGA_CMD_RSVD', 2: 'FPGA_CMD_GET_HW_METRICS', 4: 'FPGA_CMD_CLEAR_HW_METRICS', 8: 'FPGA_CMD_FORCE_SHELL_RELOAD', 16: 'FPGA_CMD_DRAM_DATA_RETENTION', 64: 'FPGA_CMD_EXTENDED_METRICS_SIZE', 128: 'FPGA_CMD_PREFETCH', 222: 'FPGA_CMD_ALL_FLAGS', } FPGA_CMD_RSVD = 1 FPGA_CMD_GET_HW_METRICS = 2 FPGA_CMD_CLEAR_HW_METRICS = 4 FPGA_CMD_FORCE_SHELL_RELOAD = 8 FPGA_CMD_DRAM_DATA_RETENTION = 16 FPGA_CMD_EXTENDED_METRICS_SIZE = 64 FPGA_CMD_PREFETCH = 128 FPGA_CMD_ALL_FLAGS = 222 c__Ea_FPGA_CMD_RSVD = ctypes.c_int # enum # values for enumeration 'c__Ea_FPGA_ERR_OK' c__Ea_FPGA_ERR_OK__enumvalues = { 0: 'FPGA_ERR_OK', 3: 'FPGA_ERR_AFI_CMD_BUSY', 5: 'FPGA_ERR_AFI_ID_INVALID', 11: 'FPGA_ERR_AFI_CMD_API_VERSION_INVALID', 12: 'FPGA_ERR_CL_ID_MISMATCH', 13: 'FPGA_ERR_CL_DDR_CALIB_FAILED', 14: 'FPGA_ERR_FAIL', 16: 'FPGA_ERR_SHELL_MISMATCH', 17: 'FPGA_ERR_POWER_VIOLATION', 18: 'FPGA_ERR_DRAM_DATA_RETENTION_NOT_POSSIBLE', 19: 'FPGA_ERR_HARDWARE_BUSY', 20: 'FPGA_ERR_PCI_MISSING', 21: 'FPGA_ERR_AFI_CMD_MALFORMED', 22: 'FPGA_ERR_DRAM_DATA_RETENTION_FAILED', 23: 'FPGA_ERR_DRAM_DATA_RETENTION_SETUP_FAILED', 24: 'FPGA_ERR_SOFTWARE_PROBLEM', 25: 'FPGA_ERR_UNRESPONSIVE', 26: 'FPGA_ERR_END', } FPGA_ERR_OK = 0 FPGA_ERR_AFI_CMD_BUSY = 3 FPGA_ERR_AFI_ID_INVALID = 5 FPGA_ERR_AFI_CMD_API_VERSION_INVALID = 11 FPGA_ERR_CL_ID_MISMATCH = 12 FPGA_ERR_CL_DDR_CALIB_FAILED = 13 FPGA_ERR_FAIL = 14 FPGA_ERR_SHELL_MISMATCH = 16 FPGA_ERR_POWER_VIOLATION = 17 FPGA_ERR_DRAM_DATA_RETENTION_NOT_POSSIBLE = 18 FPGA_ERR_HARDWARE_BUSY = 19 FPGA_ERR_PCI_MISSING = 20 FPGA_ERR_AFI_CMD_MALFORMED = 21 FPGA_ERR_DRAM_DATA_RETENTION_FAILED = 22 FPGA_ERR_DRAM_DATA_RETENTION_SETUP_FAILED = 23 FPGA_ERR_SOFTWARE_PROBLEM = 24 FPGA_ERR_UNRESPONSIVE = 25 FPGA_ERR_END = 26 c__Ea_FPGA_ERR_OK = ctypes.c_int # enum # values for enumeration 'c__Ea_FPGA_STATUS_LOADED' c__Ea_FPGA_STATUS_LOADED__enumvalues = { 0: 'FPGA_STATUS_LOADED', 1: 'FPGA_STATUS_CLEARED', 2: 'FPGA_STATUS_BUSY', 3: 'FPGA_STATUS_NOT_PROGRAMMED', 7: 'FPGA_STATUS_LOAD_FAILED', 8: 'FPGA_STATUS_END', } FPGA_STATUS_LOADED = 0 FPGA_STATUS_CLEARED = 1 FPGA_STATUS_BUSY = 2 FPGA_STATUS_NOT_PROGRAMMED = 3 FPGA_STATUS_LOAD_FAILED = 7 FPGA_STATUS_END = 8 c__Ea_FPGA_STATUS_LOADED = ctypes.c_int # enum class struct_fpga_common_cfg(ctypes.Structure): _pack_ = True # source:False _fields_ = [ ('reserved', ctypes.c_uint32), ] # values for enumeration 'c__Ea_FPGA_APP_PF' c__Ea_FPGA_APP_PF__enumvalues = { 0: 'FPGA_APP_PF', 1: 'FPGA_MGMT_PF', 2: 'FPGA_PF_MAX', } FPGA_APP_PF = 0 FPGA_MGMT_PF = 1 FPGA_PF_MAX = 2 c__Ea_FPGA_APP_PF = ctypes.c_int # enum # values for enumeration 'c__Ea_APP_PF_BAR0' c__Ea_APP_PF_BAR0__enumvalues = { 0: 'APP_PF_BAR0', 1: 'APP_PF_BAR1', 4: 'APP_PF_BAR4', 5: 'APP_PF_BAR_MAX', } APP_PF_BAR0 = 0 APP_PF_BAR1 = 1 APP_PF_BAR4 = 4 APP_PF_BAR_MAX = 5 c__Ea_APP_PF_BAR0 = ctypes.c_int # enum # values for enumeration 'c__Ea_MGMT_PF_BAR0' c__Ea_MGMT_PF_BAR0__enumvalues = { 0: 'MGMT_PF_BAR0', 2: 'MGMT_PF_BAR2', 4: 'MGMT_PF_BAR4', 5: 'MGMT_PF_BAR_MAX', } MGMT_PF_BAR0 = 0 MGMT_PF_BAR2 = 2 MGMT_PF_BAR4 = 4 MGMT_PF_BAR_MAX = 5 c__Ea_MGMT_PF_BAR0 = ctypes.c_int # enum # values for enumeration 'c__Ea_FPGA_INT_STATUS_SDACL_SLAVE_TIMEOUT' c__Ea_FPGA_INT_STATUS_SDACL_SLAVE_TIMEOUT__enumvalues = { 1: 'FPGA_INT_STATUS_SDACL_SLAVE_TIMEOUT', 2: 'FPGA_INT_STATUS_VIRTUAL_JTAG_SLAVE_TIMEOUT', 131072: 'FPGA_INT_STATUS_DMA_PCI_SLAVE_TIMEOUT', 262144: 'FPGA_INT_STATUS_PCI_MASTER_RANGE_ERROR', 524288: 'FPGA_INT_STATUS_PCI_MASTER_AXI_PROTOCOL_ERROR', 268435456: 'FPGA_INT_STATUS_OCL_SLAVE_TIMEOUT', 536870912: 'FPGA_INT_STATUS_BAR1_SLAVE_TIMEOUT', 806223875: 'FPGA_INT_STATUS_ALL', } FPGA_INT_STATUS_SDACL_SLAVE_TIMEOUT = 1 FPGA_INT_STATUS_VIRTUAL_JTAG_SLAVE_TIMEOUT = 2 FPGA_INT_STATUS_DMA_PCI_SLAVE_TIMEOUT = 131072 FPGA_INT_STATUS_PCI_MASTER_RANGE_ERROR = 262144 FPGA_INT_STATUS_PCI_MASTER_AXI_PROTOCOL_ERROR = 524288 FPGA_INT_STATUS_OCL_SLAVE_TIMEOUT = 268435456 FPGA_INT_STATUS_BAR1_SLAVE_TIMEOUT = 536870912 FPGA_INT_STATUS_ALL = 806223875 c__Ea_FPGA_INT_STATUS_SDACL_SLAVE_TIMEOUT = ctypes.c_int # enum # values for enumeration 'c__Ea_FPGA_PAP_4K_CROSS_ERROR' c__Ea_FPGA_PAP_4K_CROSS_ERROR__enumvalues = { 2: 'FPGA_PAP_4K_CROSS_ERROR', 4: 'FPGA_PAP_BM_EN_ERROR', 8: 'FPGA_PAP_REQ_SIZE_ERROR', 16: 'FPGA_PAP_WR_INCOMPLETE_ERROR', 32: 'FPGA_PAP_FIRST_BYTE_EN_ERROR', 64: 'FPGA_PAP_LAST_BYTE_EN_ERROR', 256: 'FPGA_PAP_BREADY_TIMEOUT_ERROR', 512: 'FPGA_PAP_RREADY_TIMEOUT_ERROR', 1024: 'FPGA_PAP_WCHANNEL_TIMEOUT_ERROR', 1918: 'FPGA_PAP_ERROR_STATUS_ALL', } FPGA_PAP_4K_CROSS_ERROR = 2 FPGA_PAP_BM_EN_ERROR = 4 FPGA_PAP_REQ_SIZE_ERROR = 8 FPGA_PAP_WR_INCOMPLETE_ERROR = 16 FPGA_PAP_FIRST_BYTE_EN_ERROR = 32 FPGA_PAP_LAST_BYTE_EN_ERROR = 64 FPGA_PAP_BREADY_TIMEOUT_ERROR = 256 FPGA_PAP_RREADY_TIMEOUT_ERROR = 512 FPGA_PAP_WCHANNEL_TIMEOUT_ERROR = 1024 FPGA_PAP_ERROR_STATUS_ALL = 1918 c__Ea_FPGA_PAP_4K_CROSS_ERROR = ctypes.c_int # enum __all__ = \ ['APP_PF_BAR0', 'APP_PF_BAR1', 'APP_PF_BAR4', 'APP_PF_BAR_MAX', 'FPGA_APP_PF', 'FPGA_CMD_ALL_FLAGS', 'FPGA_CMD_CLEAR_HW_METRICS', 'FPGA_CMD_DRAM_DATA_RETENTION', 'FPGA_CMD_EXTENDED_METRICS_SIZE', 'FPGA_CMD_FORCE_SHELL_RELOAD', 'FPGA_CMD_GET_HW_METRICS', 'FPGA_CMD_PREFETCH', 'FPGA_CMD_RSVD', 'FPGA_ERR_AFI_CMD_API_VERSION_INVALID', 'FPGA_ERR_AFI_CMD_BUSY', 'FPGA_ERR_AFI_CMD_MALFORMED', 'FPGA_ERR_AFI_ID_INVALID', 'FPGA_ERR_CL_DDR_CALIB_FAILED', 'FPGA_ERR_CL_ID_MISMATCH', 'FPGA_ERR_DRAM_DATA_RETENTION_FAILED', 'FPGA_ERR_DRAM_DATA_RETENTION_NOT_POSSIBLE', 'FPGA_ERR_DRAM_DATA_RETENTION_SETUP_FAILED', 'FPGA_ERR_END', 'FPGA_ERR_FAIL', 'FPGA_ERR_HARDWARE_BUSY', 'FPGA_ERR_OK', 'FPGA_ERR_PCI_MISSING', 'FPGA_ERR_POWER_VIOLATION', 'FPGA_ERR_SHELL_MISMATCH', 'FPGA_ERR_SOFTWARE_PROBLEM', 'FPGA_ERR_UNRESPONSIVE', 'FPGA_INT_STATUS_ALL', 'FPGA_INT_STATUS_BAR1_SLAVE_TIMEOUT', 'FPGA_INT_STATUS_DMA_PCI_SLAVE_TIMEOUT', 'FPGA_INT_STATUS_OCL_SLAVE_TIMEOUT', 'FPGA_INT_STATUS_PCI_MASTER_AXI_PROTOCOL_ERROR', 'FPGA_INT_STATUS_PCI_MASTER_RANGE_ERROR', 'FPGA_INT_STATUS_SDACL_SLAVE_TIMEOUT', 'FPGA_INT_STATUS_VIRTUAL_JTAG_SLAVE_TIMEOUT', 'FPGA_MGMT_PF', 'FPGA_PAP_4K_CROSS_ERROR', 'FPGA_PAP_BM_EN_ERROR', 'FPGA_PAP_BREADY_TIMEOUT_ERROR', 'FPGA_PAP_ERROR_STATUS_ALL', 'FPGA_PAP_FIRST_BYTE_EN_ERROR', 'FPGA_PAP_LAST_BYTE_EN_ERROR', 'FPGA_PAP_REQ_SIZE_ERROR', 'FPGA_PAP_RREADY_TIMEOUT_ERROR', 'FPGA_PAP_WCHANNEL_TIMEOUT_ERROR', 'FPGA_PAP_WR_INCOMPLETE_ERROR', 'FPGA_PF_MAX', 'FPGA_STATUS_BUSY', 'FPGA_STATUS_CLEARED', 'FPGA_STATUS_END', 'FPGA_STATUS_LOADED', 'FPGA_STATUS_LOAD_FAILED', 'FPGA_STATUS_NOT_PROGRAMMED', 'MGMT_PF_BAR0', 'MGMT_PF_BAR2', 'MGMT_PF_BAR4', 'MGMT_PF_BAR_MAX', 'c__Ea_APP_PF_BAR0', 'c__Ea_FPGA_APP_PF', 'c__Ea_FPGA_CMD_RSVD', 'c__Ea_FPGA_ERR_OK', 'c__Ea_FPGA_INT_STATUS_SDACL_SLAVE_TIMEOUT', 'c__Ea_FPGA_PAP_4K_CROSS_ERROR', 'c__Ea_FPGA_STATUS_LOADED', 'c__Ea_MGMT_PF_BAR0', 'fpga_mgmt_clear_local_image', 'fpga_mgmt_clear_local_image_sync', 'fpga_mgmt_close', 'fpga_mgmt_describe_local_image', 'fpga_mgmt_get_status', 'fpga_mgmt_get_status_name', 'fpga_mgmt_get_vDIP_status', 'fpga_mgmt_get_vLED_status', 'fpga_mgmt_init', 'fpga_mgmt_init_load_local_image_options', 'fpga_mgmt_load_local_image', 'fpga_mgmt_load_local_image_flags', 'fpga_mgmt_load_local_image_sync', 'fpga_mgmt_load_local_image_sync_flags', 'fpga_mgmt_load_local_image_sync_with_options', 'fpga_mgmt_load_local_image_with_options', 'fpga_mgmt_set_cmd_delay_msec', 'fpga_mgmt_set_cmd_timeout', 'fpga_mgmt_set_vDIP', 'fpga_mgmt_strerror', 'fpga_mgmt_strerror_long', 'struct_afi_device_ids', 'struct_fpga_clocks_common', 'struct_fpga_common_cfg', 'struct_fpga_ddr_if_metrics_common', 'struct_fpga_meta_ids', 'struct_fpga_metrics_common', 'struct_fpga_mgmt_image_info', 'struct_fpga_mgmt_load_local_image_options_0', 'struct_fpga_pci_resource_map', 'struct_fpga_slot_spec', 'uint16_t', 'uint32_t', 'union_fpga_mgmt_load_local_image_options']
9,576
383
<reponame>Microsoft/Windows-Machine-Learning #pragma once #include "pch.h" #include <appmodel.h> #include <mutex> #include <filesystem> #ifndef PIXREDIST #define PIXREDIST typedef HRESULT(WINAPI* BeginCapture)(DWORD captureFlags, _In_ PPIXCaptureParameters captureParameters); typedef HRESULT(WINAPI* EndCapture)(BOOL discard); typedef HRESULT(WINAPI* BeginEventOnCommandQueue)(ID3D12CommandQueue* commandQueue, UINT64 color, _In_ PCSTR formatString); typedef HRESULT(WINAPI* EndEventOnCommandQueue)(ID3D12CommandQueue* commandQueue); typedef HRESULT(WINAPI* SetMarkerOnCommandQueue)(ID3D12CommandQueue* commandQueue, UINT64 color, _In_ PCSTR formatString); static BeginCapture g_beginCaptureSingleton = nullptr; static EndCapture g_endCaptureSingleton = nullptr; static BeginEventOnCommandQueue g_beginEventSingleton = nullptr; static EndEventOnCommandQueue g_endEventSingleton = nullptr; static SetMarkerOnCommandQueue g_setMarkerSingleton = nullptr; static bool g_pixLoadAttempted = false; static std::mutex g_mutex; void TryEnsurePIXFunctions(); void GetSubdirs(std::vector<std::wstring>& output, const std::wstring& path); void LoadPIXGpuCapturer(); void PIXBeginEvent(ID3D12CommandQueue* commandQueue, UINT64 color, _In_ PCSTR string); void PIXEndEvent(ID3D12CommandQueue* commandQueue); void PIXSetMarker(ID3D12CommandQueue* commandQueue, UINT64 color, _In_ PCSTR string); void PIXBeginCaptureRedist(DWORD captureFlags, _In_ PPIXCaptureParameters captureParameters); void PIXEndCaptureRedist(BOOL discard); #endif
540
478
{ "name": "sweet-scroll", "version": "4.0.0", "description": "Modern and the sweet smooth scroll library.", "main": "sweet-scroll.js", "types": "sweet-scroll.d.ts", "scripts": { "start": "npm-run-all -p build:watch docs", "build": "npm-run-all build:bundle build:minify build:decls", "build:bundle": "rollup -c", "build:minify": "uglifyjs -c -m --comments -o sweet-scroll.min.js -- sweet-scroll.js", "build:decls": "dts-bundle --baseDir ./ --name sweet-scroll --main decls/index.d.ts", "build:watch": "yarn build:bundle --watch", "prebuild": "yarn clean", "clean": "rm -rf decls .rpt2_cache", "test": "npm-run-all lint test:unit", "test:unit": "npm-run-all test:browser test:node", "test:browser": "jest --setupTestFrameworkScriptFile=./jest/setup-for-browser.js --testPathPattern \"browser.spec.ts\"", "test:browser:watch": "yarn test:browser --watch", "test:node": "jest --env=node --testPathPattern \"node.spec.ts\"", "test:node:watch": "yarn test:node --watch", "lint": "tslint -c tslint.json \"src/**/*.ts\"", "docs": "npm-run-all -p docs:server docs:watch", "docs:server": "browser-sync start -s docs -f \"docs/**/*\" --no-notify --no-ghost-mode --no-open", "docs:build": "cpx sweet-scroll.js docs", "docs:watch": "yarn docs:build --watch", "docs:deploy": "gh-pages -t -d docs", "format": "npm-run-all format:tslint format:prettier", "format:tslint": "yarn lint --fix", "format:prettier": "prettier --write \"src/**/*\" \"*.md\"", "predocs:deploy": "yarn docs:build", "prepublishOnly": "yarn build" }, "files": [ "decls", "sweet-scroll.js", "sweet-scroll.min.js", "sweet-scroll.d.ts" ], "keywords": [ "smooth scroll", "sweet scroll", "sweet", "scroll", "animation" ], "repository": { "type": "git", "url": "https://github.com/tsuyoshiwada/sweet-scroll.git" }, "author": "tsuyoshiwada", "license": "MIT", "bugs": { "url": "https://github.com/tsuyoshiwada/sweet-scroll/issues" }, "homepage": "https://github.com/tsuyoshiwada/sweet-scroll", "devDependencies": { "@types/jest": "24.0.9", "browser-sync": "2.26.3", "cpx": "1.5.0", "dts-bundle": "0.7.3", "gh-pages": "2.0.1", "jest": "24.3.1", "npm-run-all": "4.1.5", "prettier": "1.16.4", "rollup": "1.4.1", "rollup-plugin-typescript2": "0.19.3", "rollup-watch": "4.3.1", "ts-jest": "24.0.0", "tslint": "5.13.1", "typescript": "3.3.3333", "uglify-es": "3.3.9" }, "jest": { "preset": "ts-jest" }, "prettier": { "trailingComma": "all", "printWidth": 100, "tabWidth": 2, "useTabs": false, "semi": true, "singleQuote": true, "bracketSpacing": true, "arrowParens": "always" } }
1,287
50,961
import pytest from numpy.testing import assert_allclose from sklearn.utils import check_random_state from sklearn.utils._arpack import _init_arpack_v0 @pytest.mark.parametrize("seed", range(100)) def test_init_arpack_v0(seed): # check that the initialization a sampling from an uniform distribution # where we can fix the random state size = 1000 v0 = _init_arpack_v0(size, seed) rng = check_random_state(seed) assert_allclose(v0, rng.uniform(-1, 1, size=size))
174
310
{ "name": "Project", "description": "Project management software.", "url": "https://products.office.com/project" }
37