text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengles;
public interface AMD_compressed_ATC_texture {
/**
* Accepted by the <internalformat> parameter of CompressedTexImage2D and
* CompressedTexImage3DOES.
*/
int GL_ATC_RGB_AMD = 0x8C92,
GL_ATC_RGBA_EXPLICIT_ALPHA_AMD = 0x8C93,
GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD = 0x87EE;
}
| {
"pile_set_name": "Github"
} |
# export-to-postgresql.py: export perf data to a postgresql database
# Copyright (c) 2014, Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU General Public License,
# version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope 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.
import os
import sys
import struct
import datetime
# To use this script you will need to have installed package python-pyside which
# provides LGPL-licensed Python bindings for Qt. You will also need the package
# libqt4-sql-psql for Qt postgresql support.
#
# The script assumes postgresql is running on the local machine and that the
# user has postgresql permissions to create databases. Examples of installing
# postgresql and adding such a user are:
#
# fedora:
#
# $ sudo yum install postgresql postgresql-server python-pyside qt-postgresql
# $ sudo su - postgres -c initdb
# $ sudo service postgresql start
# $ sudo su - postgres
# $ createuser <your user id here>
# Shall the new role be a superuser? (y/n) y
#
# ubuntu:
#
# $ sudo apt-get install postgresql
# $ sudo su - postgres
# $ createuser <your user id here>
# Shall the new role be a superuser? (y/n) y
#
# An example of using this script with Intel PT:
#
# $ perf record -e intel_pt//u ls
# $ perf script -s ~/libexec/perf-core/scripts/python/export-to-postgresql.py pt_example branches calls
# 2015-05-29 12:49:23.464364 Creating database...
# 2015-05-29 12:49:26.281717 Writing to intermediate files...
# 2015-05-29 12:49:27.190383 Copying to database...
# 2015-05-29 12:49:28.140451 Removing intermediate files...
# 2015-05-29 12:49:28.147451 Adding primary keys
# 2015-05-29 12:49:28.655683 Adding foreign keys
# 2015-05-29 12:49:29.365350 Done
#
# To browse the database, psql can be used e.g.
#
# $ psql pt_example
# pt_example=# select * from samples_view where id < 100;
# pt_example=# \d+
# pt_example=# \d+ samples_view
# pt_example=# \q
#
# An example of using the database is provided by the script
# call-graph-from-postgresql.py. Refer to that script for details.
#
# Tables:
#
# The tables largely correspond to perf tools' data structures. They are largely self-explanatory.
#
# samples
#
# 'samples' is the main table. It represents what instruction was executing at a point in time
# when something (a selected event) happened. The memory address is the instruction pointer or 'ip'.
#
# calls
#
# 'calls' represents function calls and is related to 'samples' by 'call_id' and 'return_id'.
# 'calls' is only created when the 'calls' option to this script is specified.
#
# call_paths
#
# 'call_paths' represents all the call stacks. Each 'call' has an associated record in 'call_paths'.
# 'calls_paths' is only created when the 'calls' option to this script is specified.
#
# branch_types
#
# 'branch_types' provides descriptions for each type of branch.
#
# comm_threads
#
# 'comm_threads' shows how 'comms' relates to 'threads'.
#
# comms
#
# 'comms' contains a record for each 'comm' - the name given to the executable that is running.
#
# dsos
#
# 'dsos' contains a record for each executable file or library.
#
# machines
#
# 'machines' can be used to distinguish virtual machines if virtualization is supported.
#
# selected_events
#
# 'selected_events' contains a record for each kind of event that has been sampled.
#
# symbols
#
# 'symbols' contains a record for each symbol. Only symbols that have samples are present.
#
# threads
#
# 'threads' contains a record for each thread.
#
# Views:
#
# Most of the tables have views for more friendly display. The views are:
#
# calls_view
# call_paths_view
# comm_threads_view
# dsos_view
# machines_view
# samples_view
# symbols_view
# threads_view
#
# More examples of browsing the database with psql:
# Note that some of the examples are not the most optimal SQL query.
# Note that call information is only available if the script's 'calls' option has been used.
#
# Top 10 function calls (not aggregated by symbol):
#
# SELECT * FROM calls_view ORDER BY elapsed_time DESC LIMIT 10;
#
# Top 10 function calls (aggregated by symbol):
#
# SELECT symbol_id,(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,
# SUM(elapsed_time) AS tot_elapsed_time,SUM(branch_count) AS tot_branch_count
# FROM calls_view GROUP BY symbol_id ORDER BY tot_elapsed_time DESC LIMIT 10;
#
# Note that the branch count gives a rough estimation of cpu usage, so functions
# that took a long time but have a relatively low branch count must have spent time
# waiting.
#
# Find symbols by pattern matching on part of the name (e.g. names containing 'alloc'):
#
# SELECT * FROM symbols_view WHERE name LIKE '%alloc%';
#
# Top 10 function calls for a specific symbol (e.g. whose symbol_id is 187):
#
# SELECT * FROM calls_view WHERE symbol_id = 187 ORDER BY elapsed_time DESC LIMIT 10;
#
# Show function calls made by function in the same context (i.e. same call path) (e.g. one with call_path_id 254):
#
# SELECT * FROM calls_view WHERE parent_call_path_id = 254;
#
# Show branches made during a function call (e.g. where call_id is 29357 and return_id is 29370 and tid is 29670)
#
# SELECT * FROM samples_view WHERE id >= 29357 AND id <= 29370 AND tid = 29670 AND event LIKE 'branches%';
#
# Show transactions:
#
# SELECT * FROM samples_view WHERE event = 'transactions';
#
# Note transaction start has 'in_tx' true whereas, transaction end has 'in_tx' false.
# Transaction aborts have branch_type_name 'transaction abort'
#
# Show transaction aborts:
#
# SELECT * FROM samples_view WHERE event = 'transactions' AND branch_type_name = 'transaction abort';
#
# To print a call stack requires walking the call_paths table. For example this python script:
# #!/usr/bin/python2
#
# import sys
# from PySide.QtSql import *
#
# if __name__ == '__main__':
# if (len(sys.argv) < 3):
# print >> sys.stderr, "Usage is: printcallstack.py <database name> <call_path_id>"
# raise Exception("Too few arguments")
# dbname = sys.argv[1]
# call_path_id = sys.argv[2]
# db = QSqlDatabase.addDatabase('QPSQL')
# db.setDatabaseName(dbname)
# if not db.open():
# raise Exception("Failed to open database " + dbname + " error: " + db.lastError().text())
# query = QSqlQuery(db)
# print " id ip symbol_id symbol dso_id dso_short_name"
# while call_path_id != 0 and call_path_id != 1:
# ret = query.exec_('SELECT * FROM call_paths_view WHERE id = ' + str(call_path_id))
# if not ret:
# raise Exception("Query failed: " + query.lastError().text())
# if not query.next():
# raise Exception("Query failed")
# print "{0:>6} {1:>10} {2:>9} {3:<30} {4:>6} {5:<30}".format(query.value(0), query.value(1), query.value(2), query.value(3), query.value(4), query.value(5))
# call_path_id = query.value(6)
from PySide.QtSql import *
# Need to access PostgreSQL C library directly to use COPY FROM STDIN
from ctypes import *
libpq = CDLL("libpq.so.5")
PQconnectdb = libpq.PQconnectdb
PQconnectdb.restype = c_void_p
PQconnectdb.argtypes = [ c_char_p ]
PQfinish = libpq.PQfinish
PQfinish.argtypes = [ c_void_p ]
PQstatus = libpq.PQstatus
PQstatus.restype = c_int
PQstatus.argtypes = [ c_void_p ]
PQexec = libpq.PQexec
PQexec.restype = c_void_p
PQexec.argtypes = [ c_void_p, c_char_p ]
PQresultStatus = libpq.PQresultStatus
PQresultStatus.restype = c_int
PQresultStatus.argtypes = [ c_void_p ]
PQputCopyData = libpq.PQputCopyData
PQputCopyData.restype = c_int
PQputCopyData.argtypes = [ c_void_p, c_void_p, c_int ]
PQputCopyEnd = libpq.PQputCopyEnd
PQputCopyEnd.restype = c_int
PQputCopyEnd.argtypes = [ c_void_p, c_void_p ]
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
# These perf imports are not used at present
#from perf_trace_context import *
#from Core import *
perf_db_export_mode = True
perf_db_export_calls = False
def usage():
print >> sys.stderr, "Usage is: export-to-postgresql.py <database name> [<columns>] [<calls>]"
print >> sys.stderr, "where: columns 'all' or 'branches'"
print >> sys.stderr, " calls 'calls' => create calls table"
raise Exception("Too few arguments")
if (len(sys.argv) < 2):
usage()
dbname = sys.argv[1]
if (len(sys.argv) >= 3):
columns = sys.argv[2]
else:
columns = "all"
if columns not in ("all", "branches"):
usage()
branches = (columns == "branches")
if (len(sys.argv) >= 4):
if (sys.argv[3] == "calls"):
perf_db_export_calls = True
else:
usage()
output_dir_name = os.getcwd() + "/" + dbname + "-perf-data"
os.mkdir(output_dir_name)
def do_query(q, s):
if (q.exec_(s)):
return
raise Exception("Query failed: " + q.lastError().text())
print datetime.datetime.today(), "Creating database..."
db = QSqlDatabase.addDatabase('QPSQL')
query = QSqlQuery(db)
db.setDatabaseName('postgres')
db.open()
try:
do_query(query, 'CREATE DATABASE ' + dbname)
except:
os.rmdir(output_dir_name)
raise
query.finish()
query.clear()
db.close()
db.setDatabaseName(dbname)
db.open()
query = QSqlQuery(db)
do_query(query, 'SET client_min_messages TO WARNING')
do_query(query, 'CREATE TABLE selected_events ('
'id bigint NOT NULL,'
'name varchar(80))')
do_query(query, 'CREATE TABLE machines ('
'id bigint NOT NULL,'
'pid integer,'
'root_dir varchar(4096))')
do_query(query, 'CREATE TABLE threads ('
'id bigint NOT NULL,'
'machine_id bigint,'
'process_id bigint,'
'pid integer,'
'tid integer)')
do_query(query, 'CREATE TABLE comms ('
'id bigint NOT NULL,'
'comm varchar(16))')
do_query(query, 'CREATE TABLE comm_threads ('
'id bigint NOT NULL,'
'comm_id bigint,'
'thread_id bigint)')
do_query(query, 'CREATE TABLE dsos ('
'id bigint NOT NULL,'
'machine_id bigint,'
'short_name varchar(256),'
'long_name varchar(4096),'
'build_id varchar(64))')
do_query(query, 'CREATE TABLE symbols ('
'id bigint NOT NULL,'
'dso_id bigint,'
'sym_start bigint,'
'sym_end bigint,'
'binding integer,'
'name varchar(2048))')
do_query(query, 'CREATE TABLE branch_types ('
'id integer NOT NULL,'
'name varchar(80))')
if branches:
do_query(query, 'CREATE TABLE samples ('
'id bigint NOT NULL,'
'evsel_id bigint,'
'machine_id bigint,'
'thread_id bigint,'
'comm_id bigint,'
'dso_id bigint,'
'symbol_id bigint,'
'sym_offset bigint,'
'ip bigint,'
'time bigint,'
'cpu integer,'
'to_dso_id bigint,'
'to_symbol_id bigint,'
'to_sym_offset bigint,'
'to_ip bigint,'
'branch_type integer,'
'in_tx boolean)')
else:
do_query(query, 'CREATE TABLE samples ('
'id bigint NOT NULL,'
'evsel_id bigint,'
'machine_id bigint,'
'thread_id bigint,'
'comm_id bigint,'
'dso_id bigint,'
'symbol_id bigint,'
'sym_offset bigint,'
'ip bigint,'
'time bigint,'
'cpu integer,'
'to_dso_id bigint,'
'to_symbol_id bigint,'
'to_sym_offset bigint,'
'to_ip bigint,'
'period bigint,'
'weight bigint,'
'transaction bigint,'
'data_src bigint,'
'branch_type integer,'
'in_tx boolean)')
if perf_db_export_calls:
do_query(query, 'CREATE TABLE call_paths ('
'id bigint NOT NULL,'
'parent_id bigint,'
'symbol_id bigint,'
'ip bigint)')
do_query(query, 'CREATE TABLE calls ('
'id bigint NOT NULL,'
'thread_id bigint,'
'comm_id bigint,'
'call_path_id bigint,'
'call_time bigint,'
'return_time bigint,'
'branch_count bigint,'
'call_id bigint,'
'return_id bigint,'
'parent_call_path_id bigint,'
'flags integer)')
do_query(query, 'CREATE VIEW machines_view AS '
'SELECT '
'id,'
'pid,'
'root_dir,'
'CASE WHEN id=0 THEN \'unknown\' WHEN pid=-1 THEN \'host\' ELSE \'guest\' END AS host_or_guest'
' FROM machines')
do_query(query, 'CREATE VIEW dsos_view AS '
'SELECT '
'id,'
'machine_id,'
'(SELECT host_or_guest FROM machines_view WHERE id = machine_id) AS host_or_guest,'
'short_name,'
'long_name,'
'build_id'
' FROM dsos')
do_query(query, 'CREATE VIEW symbols_view AS '
'SELECT '
'id,'
'name,'
'(SELECT short_name FROM dsos WHERE id=dso_id) AS dso,'
'dso_id,'
'sym_start,'
'sym_end,'
'CASE WHEN binding=0 THEN \'local\' WHEN binding=1 THEN \'global\' ELSE \'weak\' END AS binding'
' FROM symbols')
do_query(query, 'CREATE VIEW threads_view AS '
'SELECT '
'id,'
'machine_id,'
'(SELECT host_or_guest FROM machines_view WHERE id = machine_id) AS host_or_guest,'
'process_id,'
'pid,'
'tid'
' FROM threads')
do_query(query, 'CREATE VIEW comm_threads_view AS '
'SELECT '
'comm_id,'
'(SELECT comm FROM comms WHERE id = comm_id) AS command,'
'thread_id,'
'(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
'(SELECT tid FROM threads WHERE id = thread_id) AS tid'
' FROM comm_threads')
if perf_db_export_calls:
do_query(query, 'CREATE VIEW call_paths_view AS '
'SELECT '
'c.id,'
'to_hex(c.ip) AS ip,'
'c.symbol_id,'
'(SELECT name FROM symbols WHERE id = c.symbol_id) AS symbol,'
'(SELECT dso_id FROM symbols WHERE id = c.symbol_id) AS dso_id,'
'(SELECT dso FROM symbols_view WHERE id = c.symbol_id) AS dso_short_name,'
'c.parent_id,'
'to_hex(p.ip) AS parent_ip,'
'p.symbol_id AS parent_symbol_id,'
'(SELECT name FROM symbols WHERE id = p.symbol_id) AS parent_symbol,'
'(SELECT dso_id FROM symbols WHERE id = p.symbol_id) AS parent_dso_id,'
'(SELECT dso FROM symbols_view WHERE id = p.symbol_id) AS parent_dso_short_name'
' FROM call_paths c INNER JOIN call_paths p ON p.id = c.parent_id')
do_query(query, 'CREATE VIEW calls_view AS '
'SELECT '
'calls.id,'
'thread_id,'
'(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
'(SELECT tid FROM threads WHERE id = thread_id) AS tid,'
'(SELECT comm FROM comms WHERE id = comm_id) AS command,'
'call_path_id,'
'to_hex(ip) AS ip,'
'symbol_id,'
'(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,'
'call_time,'
'return_time,'
'return_time - call_time AS elapsed_time,'
'branch_count,'
'call_id,'
'return_id,'
'CASE WHEN flags=1 THEN \'no call\' WHEN flags=2 THEN \'no return\' WHEN flags=3 THEN \'no call/return\' ELSE \'\' END AS flags,'
'parent_call_path_id'
' FROM calls INNER JOIN call_paths ON call_paths.id = call_path_id')
do_query(query, 'CREATE VIEW samples_view AS '
'SELECT '
'id,'
'time,'
'cpu,'
'(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
'(SELECT tid FROM threads WHERE id = thread_id) AS tid,'
'(SELECT comm FROM comms WHERE id = comm_id) AS command,'
'(SELECT name FROM selected_events WHERE id = evsel_id) AS event,'
'to_hex(ip) AS ip_hex,'
'(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,'
'sym_offset,'
'(SELECT short_name FROM dsos WHERE id = dso_id) AS dso_short_name,'
'to_hex(to_ip) AS to_ip_hex,'
'(SELECT name FROM symbols WHERE id = to_symbol_id) AS to_symbol,'
'to_sym_offset,'
'(SELECT short_name FROM dsos WHERE id = to_dso_id) AS to_dso_short_name,'
'(SELECT name FROM branch_types WHERE id = branch_type) AS branch_type_name,'
'in_tx'
' FROM samples')
file_header = struct.pack("!11sii", "PGCOPY\n\377\r\n\0", 0, 0)
file_trailer = "\377\377"
def open_output_file(file_name):
path_name = output_dir_name + "/" + file_name
file = open(path_name, "w+")
file.write(file_header)
return file
def close_output_file(file):
file.write(file_trailer)
file.close()
def copy_output_file_direct(file, table_name):
close_output_file(file)
sql = "COPY " + table_name + " FROM '" + file.name + "' (FORMAT 'binary')"
do_query(query, sql)
# Use COPY FROM STDIN because security may prevent postgres from accessing the files directly
def copy_output_file(file, table_name):
conn = PQconnectdb("dbname = " + dbname)
if (PQstatus(conn)):
raise Exception("COPY FROM STDIN PQconnectdb failed")
file.write(file_trailer)
file.seek(0)
sql = "COPY " + table_name + " FROM STDIN (FORMAT 'binary')"
res = PQexec(conn, sql)
if (PQresultStatus(res) != 4):
raise Exception("COPY FROM STDIN PQexec failed")
data = file.read(65536)
while (len(data)):
ret = PQputCopyData(conn, data, len(data))
if (ret != 1):
raise Exception("COPY FROM STDIN PQputCopyData failed, error " + str(ret))
data = file.read(65536)
ret = PQputCopyEnd(conn, None)
if (ret != 1):
raise Exception("COPY FROM STDIN PQputCopyEnd failed, error " + str(ret))
PQfinish(conn)
def remove_output_file(file):
name = file.name
file.close()
os.unlink(name)
evsel_file = open_output_file("evsel_table.bin")
machine_file = open_output_file("machine_table.bin")
thread_file = open_output_file("thread_table.bin")
comm_file = open_output_file("comm_table.bin")
comm_thread_file = open_output_file("comm_thread_table.bin")
dso_file = open_output_file("dso_table.bin")
symbol_file = open_output_file("symbol_table.bin")
branch_type_file = open_output_file("branch_type_table.bin")
sample_file = open_output_file("sample_table.bin")
if perf_db_export_calls:
call_path_file = open_output_file("call_path_table.bin")
call_file = open_output_file("call_table.bin")
def trace_begin():
print datetime.datetime.today(), "Writing to intermediate files..."
# id == 0 means unknown. It is easier to create records for them than replace the zeroes with NULLs
evsel_table(0, "unknown")
machine_table(0, 0, "unknown")
thread_table(0, 0, 0, -1, -1)
comm_table(0, "unknown")
dso_table(0, 0, "unknown", "unknown", "")
symbol_table(0, 0, 0, 0, 0, "unknown")
sample_table(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
if perf_db_export_calls:
call_path_table(0, 0, 0, 0)
unhandled_count = 0
def trace_end():
print datetime.datetime.today(), "Copying to database..."
copy_output_file(evsel_file, "selected_events")
copy_output_file(machine_file, "machines")
copy_output_file(thread_file, "threads")
copy_output_file(comm_file, "comms")
copy_output_file(comm_thread_file, "comm_threads")
copy_output_file(dso_file, "dsos")
copy_output_file(symbol_file, "symbols")
copy_output_file(branch_type_file, "branch_types")
copy_output_file(sample_file, "samples")
if perf_db_export_calls:
copy_output_file(call_path_file, "call_paths")
copy_output_file(call_file, "calls")
print datetime.datetime.today(), "Removing intermediate files..."
remove_output_file(evsel_file)
remove_output_file(machine_file)
remove_output_file(thread_file)
remove_output_file(comm_file)
remove_output_file(comm_thread_file)
remove_output_file(dso_file)
remove_output_file(symbol_file)
remove_output_file(branch_type_file)
remove_output_file(sample_file)
if perf_db_export_calls:
remove_output_file(call_path_file)
remove_output_file(call_file)
os.rmdir(output_dir_name)
print datetime.datetime.today(), "Adding primary keys"
do_query(query, 'ALTER TABLE selected_events ADD PRIMARY KEY (id)')
do_query(query, 'ALTER TABLE machines ADD PRIMARY KEY (id)')
do_query(query, 'ALTER TABLE threads ADD PRIMARY KEY (id)')
do_query(query, 'ALTER TABLE comms ADD PRIMARY KEY (id)')
do_query(query, 'ALTER TABLE comm_threads ADD PRIMARY KEY (id)')
do_query(query, 'ALTER TABLE dsos ADD PRIMARY KEY (id)')
do_query(query, 'ALTER TABLE symbols ADD PRIMARY KEY (id)')
do_query(query, 'ALTER TABLE branch_types ADD PRIMARY KEY (id)')
do_query(query, 'ALTER TABLE samples ADD PRIMARY KEY (id)')
if perf_db_export_calls:
do_query(query, 'ALTER TABLE call_paths ADD PRIMARY KEY (id)')
do_query(query, 'ALTER TABLE calls ADD PRIMARY KEY (id)')
print datetime.datetime.today(), "Adding foreign keys"
do_query(query, 'ALTER TABLE threads '
'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id),'
'ADD CONSTRAINT processfk FOREIGN KEY (process_id) REFERENCES threads (id)')
do_query(query, 'ALTER TABLE comm_threads '
'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),'
'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id)')
do_query(query, 'ALTER TABLE dsos '
'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id)')
do_query(query, 'ALTER TABLE symbols '
'ADD CONSTRAINT dsofk FOREIGN KEY (dso_id) REFERENCES dsos (id)')
do_query(query, 'ALTER TABLE samples '
'ADD CONSTRAINT evselfk FOREIGN KEY (evsel_id) REFERENCES selected_events (id),'
'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id),'
'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id),'
'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),'
'ADD CONSTRAINT dsofk FOREIGN KEY (dso_id) REFERENCES dsos (id),'
'ADD CONSTRAINT symbolfk FOREIGN KEY (symbol_id) REFERENCES symbols (id),'
'ADD CONSTRAINT todsofk FOREIGN KEY (to_dso_id) REFERENCES dsos (id),'
'ADD CONSTRAINT tosymbolfk FOREIGN KEY (to_symbol_id) REFERENCES symbols (id)')
if perf_db_export_calls:
do_query(query, 'ALTER TABLE call_paths '
'ADD CONSTRAINT parentfk FOREIGN KEY (parent_id) REFERENCES call_paths (id),'
'ADD CONSTRAINT symbolfk FOREIGN KEY (symbol_id) REFERENCES symbols (id)')
do_query(query, 'ALTER TABLE calls '
'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id),'
'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),'
'ADD CONSTRAINT call_pathfk FOREIGN KEY (call_path_id) REFERENCES call_paths (id),'
'ADD CONSTRAINT callfk FOREIGN KEY (call_id) REFERENCES samples (id),'
'ADD CONSTRAINT returnfk FOREIGN KEY (return_id) REFERENCES samples (id),'
'ADD CONSTRAINT parent_call_pathfk FOREIGN KEY (parent_call_path_id) REFERENCES call_paths (id)')
do_query(query, 'CREATE INDEX pcpid_idx ON calls (parent_call_path_id)')
if (unhandled_count):
print datetime.datetime.today(), "Warning: ", unhandled_count, " unhandled events"
print datetime.datetime.today(), "Done"
def trace_unhandled(event_name, context, event_fields_dict):
global unhandled_count
unhandled_count += 1
def sched__sched_switch(*x):
pass
def evsel_table(evsel_id, evsel_name, *x):
n = len(evsel_name)
fmt = "!hiqi" + str(n) + "s"
value = struct.pack(fmt, 2, 8, evsel_id, n, evsel_name)
evsel_file.write(value)
def machine_table(machine_id, pid, root_dir, *x):
n = len(root_dir)
fmt = "!hiqiii" + str(n) + "s"
value = struct.pack(fmt, 3, 8, machine_id, 4, pid, n, root_dir)
machine_file.write(value)
def thread_table(thread_id, machine_id, process_id, pid, tid, *x):
value = struct.pack("!hiqiqiqiiii", 5, 8, thread_id, 8, machine_id, 8, process_id, 4, pid, 4, tid)
thread_file.write(value)
def comm_table(comm_id, comm_str, *x):
n = len(comm_str)
fmt = "!hiqi" + str(n) + "s"
value = struct.pack(fmt, 2, 8, comm_id, n, comm_str)
comm_file.write(value)
def comm_thread_table(comm_thread_id, comm_id, thread_id, *x):
fmt = "!hiqiqiq"
value = struct.pack(fmt, 3, 8, comm_thread_id, 8, comm_id, 8, thread_id)
comm_thread_file.write(value)
def dso_table(dso_id, machine_id, short_name, long_name, build_id, *x):
n1 = len(short_name)
n2 = len(long_name)
n3 = len(build_id)
fmt = "!hiqiqi" + str(n1) + "si" + str(n2) + "si" + str(n3) + "s"
value = struct.pack(fmt, 5, 8, dso_id, 8, machine_id, n1, short_name, n2, long_name, n3, build_id)
dso_file.write(value)
def symbol_table(symbol_id, dso_id, sym_start, sym_end, binding, symbol_name, *x):
n = len(symbol_name)
fmt = "!hiqiqiqiqiii" + str(n) + "s"
value = struct.pack(fmt, 6, 8, symbol_id, 8, dso_id, 8, sym_start, 8, sym_end, 4, binding, n, symbol_name)
symbol_file.write(value)
def branch_type_table(branch_type, name, *x):
n = len(name)
fmt = "!hiii" + str(n) + "s"
value = struct.pack(fmt, 2, 4, branch_type, n, name)
branch_type_file.write(value)
def sample_table(sample_id, evsel_id, machine_id, thread_id, comm_id, dso_id, symbol_id, sym_offset, ip, time, cpu, to_dso_id, to_symbol_id, to_sym_offset, to_ip, period, weight, transaction, data_src, branch_type, in_tx, *x):
if branches:
value = struct.pack("!hiqiqiqiqiqiqiqiqiqiqiiiqiqiqiqiiiB", 17, 8, sample_id, 8, evsel_id, 8, machine_id, 8, thread_id, 8, comm_id, 8, dso_id, 8, symbol_id, 8, sym_offset, 8, ip, 8, time, 4, cpu, 8, to_dso_id, 8, to_symbol_id, 8, to_sym_offset, 8, to_ip, 4, branch_type, 1, in_tx)
else:
value = struct.pack("!hiqiqiqiqiqiqiqiqiqiqiiiqiqiqiqiqiqiqiqiiiB", 21, 8, sample_id, 8, evsel_id, 8, machine_id, 8, thread_id, 8, comm_id, 8, dso_id, 8, symbol_id, 8, sym_offset, 8, ip, 8, time, 4, cpu, 8, to_dso_id, 8, to_symbol_id, 8, to_sym_offset, 8, to_ip, 8, period, 8, weight, 8, transaction, 8, data_src, 4, branch_type, 1, in_tx)
sample_file.write(value)
def call_path_table(cp_id, parent_id, symbol_id, ip, *x):
fmt = "!hiqiqiqiq"
value = struct.pack(fmt, 4, 8, cp_id, 8, parent_id, 8, symbol_id, 8, ip)
call_path_file.write(value)
def call_return_table(cr_id, thread_id, comm_id, call_path_id, call_time, return_time, branch_count, call_id, return_id, parent_call_path_id, flags, *x):
fmt = "!hiqiqiqiqiqiqiqiqiqiqii"
value = struct.pack(fmt, 11, 8, cr_id, 8, thread_id, 8, comm_id, 8, call_path_id, 8, call_time, 8, return_time, 8, branch_count, 8, call_id, 8, return_id, 8, parent_call_path_id, 4, flags)
call_file.write(value)
| {
"pile_set_name": "Github"
} |
# Default values for kubeinvaders.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
rbac:
# Specifies whether RBAC resources should be created
create: true
serviceAccount:
# Specifies whether a service account should be created
create: true
# The name of the service account to use.
# If not set and create is true, a name is generated using the fullname template
name:
clusterRole:
create: true
# The name of a cluster role to bind to; if not set and create is
# true, a name based on fullname is generated
name:
# If clusterRole "false" specifies which namespaces
# kubeinvaders should have access to
allowedNamespaces: []
replicaCount: 1
image:
repository: luckysideburn/kubeinvaders
tag: latest
pullPolicy: IfNotPresent
nameOverride: ""
fullnameOverride: ""
service:
type: ClusterIP
port: 8080
ingress:
enabled: true
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
hostName: kubeinvaders.local
tls:
# secretName: kubeinvaders.local
resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi
nodeSelector: {}
tolerations: []
route_host: kubernetes.default.svc
target_namespace: "foobar"
hitslimit: 1
alienproximity: 15
updatetime: 1
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
import pandas as pd
import pytest
import numpy as np
import sys
from pandas import Series, DataFrame
import pandas.util.testing as tm
from pandas.util.testing import (assert_almost_equal, raise_with_traceback,
assert_index_equal, assert_series_equal,
assert_frame_equal, assert_numpy_array_equal,
RNGContext)
from pandas.compat import is_platform_windows
class TestAssertAlmostEqual(object):
def _assert_almost_equal_both(self, a, b, **kwargs):
assert_almost_equal(a, b, **kwargs)
assert_almost_equal(b, a, **kwargs)
def _assert_not_almost_equal_both(self, a, b, **kwargs):
pytest.raises(AssertionError, assert_almost_equal, a, b, **kwargs)
pytest.raises(AssertionError, assert_almost_equal, b, a, **kwargs)
def test_assert_almost_equal_numbers(self):
self._assert_almost_equal_both(1.1, 1.1)
self._assert_almost_equal_both(1.1, 1.100001)
self._assert_almost_equal_both(np.int16(1), 1.000001)
self._assert_almost_equal_both(np.float64(1.1), 1.1)
self._assert_almost_equal_both(np.uint32(5), 5)
self._assert_not_almost_equal_both(1.1, 1)
self._assert_not_almost_equal_both(1.1, True)
self._assert_not_almost_equal_both(1, 2)
self._assert_not_almost_equal_both(1.0001, np.int16(1))
def test_assert_almost_equal_numbers_with_zeros(self):
self._assert_almost_equal_both(0, 0)
self._assert_almost_equal_both(0, 0.0)
self._assert_almost_equal_both(0, np.float64(0))
self._assert_almost_equal_both(0.000001, 0)
self._assert_not_almost_equal_both(0.001, 0)
self._assert_not_almost_equal_both(1, 0)
def test_assert_almost_equal_numbers_with_mixed(self):
self._assert_not_almost_equal_both(1, 'abc')
self._assert_not_almost_equal_both(1, [1, ])
self._assert_not_almost_equal_both(1, object())
def test_assert_almost_equal_edge_case_ndarrays(self):
self._assert_almost_equal_both(np.array([], dtype='M8[ns]'),
np.array([], dtype='float64'),
check_dtype=False)
self._assert_almost_equal_both(np.array([], dtype=str),
np.array([], dtype='int64'),
check_dtype=False)
def test_assert_almost_equal_dicts(self):
self._assert_almost_equal_both({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
self._assert_not_almost_equal_both({'a': 1, 'b': 2}, {'a': 1, 'b': 3})
self._assert_not_almost_equal_both({'a': 1, 'b': 2},
{'a': 1, 'b': 2, 'c': 3})
self._assert_not_almost_equal_both({'a': 1}, 1)
self._assert_not_almost_equal_both({'a': 1}, 'abc')
self._assert_not_almost_equal_both({'a': 1}, [1, ])
def test_assert_almost_equal_dict_like_object(self):
class DictLikeObj(object):
def keys(self):
return ('a', )
def __getitem__(self, item):
if item == 'a':
return 1
self._assert_almost_equal_both({'a': 1}, DictLikeObj(),
check_dtype=False)
self._assert_not_almost_equal_both({'a': 2}, DictLikeObj(),
check_dtype=False)
def test_assert_almost_equal_strings(self):
self._assert_almost_equal_both('abc', 'abc')
self._assert_not_almost_equal_both('abc', 'abcd')
self._assert_not_almost_equal_both('abc', 'abd')
self._assert_not_almost_equal_both('abc', 1)
self._assert_not_almost_equal_both('abc', [1, ])
def test_assert_almost_equal_iterables(self):
self._assert_almost_equal_both([1, 2, 3], [1, 2, 3])
self._assert_almost_equal_both(np.array([1, 2, 3]),
np.array([1, 2, 3]))
# class / dtype are different
self._assert_not_almost_equal_both(np.array([1, 2, 3]), [1, 2, 3])
self._assert_not_almost_equal_both(np.array([1, 2, 3]),
np.array([1., 2., 3.]))
# Can't compare generators
self._assert_not_almost_equal_both(iter([1, 2, 3]), [1, 2, 3])
self._assert_not_almost_equal_both([1, 2, 3], [1, 2, 4])
self._assert_not_almost_equal_both([1, 2, 3], [1, 2, 3, 4])
self._assert_not_almost_equal_both([1, 2, 3], 1)
def test_assert_almost_equal_null(self):
self._assert_almost_equal_both(None, None)
self._assert_not_almost_equal_both(None, np.NaN)
self._assert_not_almost_equal_both(None, 0)
self._assert_not_almost_equal_both(np.NaN, 0)
def test_assert_almost_equal_inf(self):
self._assert_almost_equal_both(np.inf, np.inf)
self._assert_almost_equal_both(np.inf, float("inf"))
self._assert_not_almost_equal_both(np.inf, 0)
self._assert_almost_equal_both(np.array([np.inf, np.nan, -np.inf]),
np.array([np.inf, np.nan, -np.inf]))
self._assert_almost_equal_both(np.array([np.inf, None, -np.inf],
dtype=np.object_),
np.array([np.inf, np.nan, -np.inf],
dtype=np.object_))
def test_assert_almost_equal_pandas(self):
tm.assert_almost_equal(pd.Index([1., 1.1]),
pd.Index([1., 1.100001]))
tm.assert_almost_equal(pd.Series([1., 1.1]),
pd.Series([1., 1.100001]))
tm.assert_almost_equal(pd.DataFrame({'a': [1., 1.1]}),
pd.DataFrame({'a': [1., 1.100001]}))
def test_assert_almost_equal_object(self):
a = [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-01')]
b = [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-01')]
self._assert_almost_equal_both(a, b)
class TestUtilTesting(object):
def test_raise_with_traceback(self):
with tm.assert_raises_regex(LookupError, "error_text"):
try:
raise ValueError("THIS IS AN ERROR")
except ValueError as e:
e = LookupError("error_text")
raise_with_traceback(e)
with tm.assert_raises_regex(LookupError, "error_text"):
try:
raise ValueError("This is another error")
except ValueError:
e = LookupError("error_text")
_, _, traceback = sys.exc_info()
raise_with_traceback(e, traceback)
class TestAssertNumpyArrayEqual(object):
def test_numpy_array_equal_message(self):
if is_platform_windows():
pytest.skip("windows has incomparable line-endings "
"and uses L on the shape")
expected = """numpy array are different
numpy array shapes are different
\\[left\\]: \\(2,\\)
\\[right\\]: \\(3,\\)"""
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(np.array([1, 2]), np.array([3, 4, 5]))
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(np.array([1, 2]), np.array([3, 4, 5]))
# scalar comparison
expected = """Expected type """
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(1, 2)
expected = """expected 2\\.00000 but got 1\\.00000, with decimal 5"""
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(1, 2)
# array / scalar array comparison
expected = """numpy array are different
numpy array classes are different
\\[left\\]: ndarray
\\[right\\]: int"""
with tm.assert_raises_regex(AssertionError, expected):
# numpy_array_equal only accepts np.ndarray
assert_numpy_array_equal(np.array([1]), 1)
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(np.array([1]), 1)
# scalar / array comparison
expected = """numpy array are different
numpy array classes are different
\\[left\\]: int
\\[right\\]: ndarray"""
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(1, np.array([1]))
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(1, np.array([1]))
expected = """numpy array are different
numpy array values are different \\(66\\.66667 %\\)
\\[left\\]: \\[nan, 2\\.0, 3\\.0\\]
\\[right\\]: \\[1\\.0, nan, 3\\.0\\]"""
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(np.array([np.nan, 2, 3]),
np.array([1, np.nan, 3]))
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(np.array([np.nan, 2, 3]),
np.array([1, np.nan, 3]))
expected = """numpy array are different
numpy array values are different \\(50\\.0 %\\)
\\[left\\]: \\[1, 2\\]
\\[right\\]: \\[1, 3\\]"""
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(np.array([1, 2]), np.array([1, 3]))
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(np.array([1, 2]), np.array([1, 3]))
expected = """numpy array are different
numpy array values are different \\(50\\.0 %\\)
\\[left\\]: \\[1\\.1, 2\\.000001\\]
\\[right\\]: \\[1\\.1, 2.0\\]"""
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(
np.array([1.1, 2.000001]), np.array([1.1, 2.0]))
# must pass
assert_almost_equal(np.array([1.1, 2.000001]), np.array([1.1, 2.0]))
expected = """numpy array are different
numpy array values are different \\(16\\.66667 %\\)
\\[left\\]: \\[\\[1, 2\\], \\[3, 4\\], \\[5, 6\\]\\]
\\[right\\]: \\[\\[1, 3\\], \\[3, 4\\], \\[5, 6\\]\\]"""
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(np.array([[1, 2], [3, 4], [5, 6]]),
np.array([[1, 3], [3, 4], [5, 6]]))
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(np.array([[1, 2], [3, 4], [5, 6]]),
np.array([[1, 3], [3, 4], [5, 6]]))
expected = """numpy array are different
numpy array values are different \\(25\\.0 %\\)
\\[left\\]: \\[\\[1, 2\\], \\[3, 4\\]\\]
\\[right\\]: \\[\\[1, 3\\], \\[3, 4\\]\\]"""
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(np.array([[1, 2], [3, 4]]),
np.array([[1, 3], [3, 4]]))
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(np.array([[1, 2], [3, 4]]),
np.array([[1, 3], [3, 4]]))
# allow to overwrite message
expected = """Index are different
Index shapes are different
\\[left\\]: \\(2,\\)
\\[right\\]: \\(3,\\)"""
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(np.array([1, 2]), np.array([3, 4, 5]),
obj='Index')
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(np.array([1, 2]), np.array([3, 4, 5]),
obj='Index')
def test_numpy_array_equal_object_message(self):
if is_platform_windows():
pytest.skip("windows has incomparable line-endings "
"and uses L on the shape")
a = np.array([pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-01')])
b = np.array([pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02')])
expected = """numpy array are different
numpy array values are different \\(50\\.0 %\\)
\\[left\\]: \\[2011-01-01 00:00:00, 2011-01-01 00:00:00\\]
\\[right\\]: \\[2011-01-01 00:00:00, 2011-01-02 00:00:00\\]"""
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(a, b)
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(a, b)
def test_numpy_array_equal_copy_flag(self):
a = np.array([1, 2, 3])
b = a.copy()
c = a.view()
expected = r'array\(\[1, 2, 3\]\) is not array\(\[1, 2, 3\]\)'
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(a, b, check_same='same')
expected = r'array\(\[1, 2, 3\]\) is array\(\[1, 2, 3\]\)'
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(a, c, check_same='copy')
def test_assert_almost_equal_iterable_message(self):
expected = """Iterable are different
Iterable length are different
\\[left\\]: 2
\\[right\\]: 3"""
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal([1, 2], [3, 4, 5])
expected = """Iterable are different
Iterable values are different \\(50\\.0 %\\)
\\[left\\]: \\[1, 2\\]
\\[right\\]: \\[1, 3\\]"""
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal([1, 2], [1, 3])
class TestAssertIndexEqual(object):
def test_index_equal_message(self):
expected = """Index are different
Index levels are different
\\[left\\]: 1, Int64Index\\(\\[1, 2, 3\\], dtype='int64'\\)
\\[right\\]: 2, MultiIndex\\(levels=\\[\\[u?'A', u?'B'\\], \\[1, 2, 3, 4\\]\\],
labels=\\[\\[0, 0, 1, 1\\], \\[0, 1, 2, 3\\]\\]\\)"""
idx1 = pd.Index([1, 2, 3])
idx2 = pd.MultiIndex.from_tuples([('A', 1), ('A', 2),
('B', 3), ('B', 4)])
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2, exact=False)
expected = """MultiIndex level \\[1\\] are different
MultiIndex level \\[1\\] values are different \\(25\\.0 %\\)
\\[left\\]: Int64Index\\(\\[2, 2, 3, 4\\], dtype='int64'\\)
\\[right\\]: Int64Index\\(\\[1, 2, 3, 4\\], dtype='int64'\\)"""
idx1 = pd.MultiIndex.from_tuples([('A', 2), ('A', 2),
('B', 3), ('B', 4)])
idx2 = pd.MultiIndex.from_tuples([('A', 1), ('A', 2),
('B', 3), ('B', 4)])
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2)
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2, check_exact=False)
expected = """Index are different
Index length are different
\\[left\\]: 3, Int64Index\\(\\[1, 2, 3\\], dtype='int64'\\)
\\[right\\]: 4, Int64Index\\(\\[1, 2, 3, 4\\], dtype='int64'\\)"""
idx1 = pd.Index([1, 2, 3])
idx2 = pd.Index([1, 2, 3, 4])
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2)
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2, check_exact=False)
expected = """Index are different
Index classes are different
\\[left\\]: Int64Index\\(\\[1, 2, 3\\], dtype='int64'\\)
\\[right\\]: Float64Index\\(\\[1\\.0, 2\\.0, 3\\.0\\], dtype='float64'\\)"""
idx1 = pd.Index([1, 2, 3])
idx2 = pd.Index([1, 2, 3.0])
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2, exact=True)
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2, exact=True, check_exact=False)
expected = """Index are different
Index values are different \\(33\\.33333 %\\)
\\[left\\]: Float64Index\\(\\[1.0, 2.0, 3.0], dtype='float64'\\)
\\[right\\]: Float64Index\\(\\[1.0, 2.0, 3.0000000001\\], dtype='float64'\\)"""
idx1 = pd.Index([1, 2, 3.])
idx2 = pd.Index([1, 2, 3.0000000001])
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2)
# must success
assert_index_equal(idx1, idx2, check_exact=False)
expected = """Index are different
Index values are different \\(33\\.33333 %\\)
\\[left\\]: Float64Index\\(\\[1.0, 2.0, 3.0], dtype='float64'\\)
\\[right\\]: Float64Index\\(\\[1.0, 2.0, 3.0001\\], dtype='float64'\\)"""
idx1 = pd.Index([1, 2, 3.])
idx2 = pd.Index([1, 2, 3.0001])
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2)
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2, check_exact=False)
# must success
assert_index_equal(idx1, idx2, check_exact=False,
check_less_precise=True)
expected = """Index are different
Index values are different \\(33\\.33333 %\\)
\\[left\\]: Int64Index\\(\\[1, 2, 3\\], dtype='int64'\\)
\\[right\\]: Int64Index\\(\\[1, 2, 4\\], dtype='int64'\\)"""
idx1 = pd.Index([1, 2, 3])
idx2 = pd.Index([1, 2, 4])
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2)
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2, check_less_precise=True)
expected = """MultiIndex level \\[1\\] are different
MultiIndex level \\[1\\] values are different \\(25\\.0 %\\)
\\[left\\]: Int64Index\\(\\[2, 2, 3, 4\\], dtype='int64'\\)
\\[right\\]: Int64Index\\(\\[1, 2, 3, 4\\], dtype='int64'\\)"""
idx1 = pd.MultiIndex.from_tuples([('A', 2), ('A', 2),
('B', 3), ('B', 4)])
idx2 = pd.MultiIndex.from_tuples([('A', 1), ('A', 2),
('B', 3), ('B', 4)])
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2)
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2, check_exact=False)
def test_index_equal_metadata_message(self):
expected = """Index are different
Attribute "names" are different
\\[left\\]: \\[None\\]
\\[right\\]: \\[u?'x'\\]"""
idx1 = pd.Index([1, 2, 3])
idx2 = pd.Index([1, 2, 3], name='x')
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2)
# same name, should pass
assert_index_equal(pd.Index([1, 2, 3], name=np.nan),
pd.Index([1, 2, 3], name=np.nan))
assert_index_equal(pd.Index([1, 2, 3], name=pd.NaT),
pd.Index([1, 2, 3], name=pd.NaT))
expected = """Index are different
Attribute "names" are different
\\[left\\]: \\[nan\\]
\\[right\\]: \\[NaT\\]"""
idx1 = pd.Index([1, 2, 3], name=np.nan)
idx2 = pd.Index([1, 2, 3], name=pd.NaT)
with tm.assert_raises_regex(AssertionError, expected):
assert_index_equal(idx1, idx2)
class TestAssertSeriesEqual(object):
def _assert_equal(self, x, y, **kwargs):
assert_series_equal(x, y, **kwargs)
assert_series_equal(y, x, **kwargs)
def _assert_not_equal(self, a, b, **kwargs):
pytest.raises(AssertionError, assert_series_equal, a, b, **kwargs)
pytest.raises(AssertionError, assert_series_equal, b, a, **kwargs)
def test_equal(self):
self._assert_equal(Series(range(3)), Series(range(3)))
self._assert_equal(Series(list('abc')), Series(list('abc')))
def test_not_equal(self):
self._assert_not_equal(Series(range(3)), Series(range(3)) + 1)
self._assert_not_equal(Series(list('abc')), Series(list('xyz')))
self._assert_not_equal(Series(range(3)), Series(range(4)))
self._assert_not_equal(
Series(range(3)), Series(
range(3), dtype='float64'))
self._assert_not_equal(
Series(range(3)), Series(
range(3), index=[1, 2, 4]))
# ATM meta data is not checked in assert_series_equal
# self._assert_not_equal(Series(range(3)),Series(range(3),name='foo'),check_names=True)
def test_less_precise(self):
s1 = Series([0.12345], dtype='float64')
s2 = Series([0.12346], dtype='float64')
pytest.raises(AssertionError, assert_series_equal, s1, s2)
self._assert_equal(s1, s2, check_less_precise=True)
for i in range(4):
self._assert_equal(s1, s2, check_less_precise=i)
pytest.raises(AssertionError, assert_series_equal, s1, s2, 10)
s1 = Series([0.12345], dtype='float32')
s2 = Series([0.12346], dtype='float32')
pytest.raises(AssertionError, assert_series_equal, s1, s2)
self._assert_equal(s1, s2, check_less_precise=True)
for i in range(4):
self._assert_equal(s1, s2, check_less_precise=i)
pytest.raises(AssertionError, assert_series_equal, s1, s2, 10)
# even less than less precise
s1 = Series([0.1235], dtype='float32')
s2 = Series([0.1236], dtype='float32')
pytest.raises(AssertionError, assert_series_equal, s1, s2)
pytest.raises(AssertionError, assert_series_equal, s1, s2, True)
def test_index_dtype(self):
df1 = DataFrame.from_records(
{'a': [1, 2], 'c': ['l1', 'l2']}, index=['a'])
df2 = DataFrame.from_records(
{'a': [1.0, 2.0], 'c': ['l1', 'l2']}, index=['a'])
self._assert_not_equal(df1.c, df2.c, check_index_type=True)
def test_multiindex_dtype(self):
df1 = DataFrame.from_records(
{'a': [1, 2], 'b': [2.1, 1.5],
'c': ['l1', 'l2']}, index=['a', 'b'])
df2 = DataFrame.from_records(
{'a': [1.0, 2.0], 'b': [2.1, 1.5],
'c': ['l1', 'l2']}, index=['a', 'b'])
self._assert_not_equal(df1.c, df2.c, check_index_type=True)
def test_series_equal_message(self):
expected = """Series are different
Series length are different
\\[left\\]: 3, RangeIndex\\(start=0, stop=3, step=1\\)
\\[right\\]: 4, RangeIndex\\(start=0, stop=4, step=1\\)"""
with tm.assert_raises_regex(AssertionError, expected):
assert_series_equal(pd.Series([1, 2, 3]), pd.Series([1, 2, 3, 4]))
expected = """Series are different
Series values are different \\(33\\.33333 %\\)
\\[left\\]: \\[1, 2, 3\\]
\\[right\\]: \\[1, 2, 4\\]"""
with tm.assert_raises_regex(AssertionError, expected):
assert_series_equal(pd.Series([1, 2, 3]), pd.Series([1, 2, 4]))
with tm.assert_raises_regex(AssertionError, expected):
assert_series_equal(pd.Series([1, 2, 3]), pd.Series([1, 2, 4]),
check_less_precise=True)
class TestAssertFrameEqual(object):
def _assert_equal(self, x, y, **kwargs):
assert_frame_equal(x, y, **kwargs)
assert_frame_equal(y, x, **kwargs)
def _assert_not_equal(self, a, b, **kwargs):
pytest.raises(AssertionError, assert_frame_equal, a, b, **kwargs)
pytest.raises(AssertionError, assert_frame_equal, b, a, **kwargs)
def test_equal_with_different_row_order(self):
# check_like=True ignores row-column orderings
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
index=['a', 'b', 'c'])
df2 = pd.DataFrame({'A': [3, 2, 1], 'B': [6, 5, 4]},
index=['c', 'b', 'a'])
self._assert_equal(df1, df2, check_like=True)
self._assert_not_equal(df1, df2)
def test_not_equal_with_different_shape(self):
self._assert_not_equal(pd.DataFrame({'A': [1, 2, 3]}),
pd.DataFrame({'A': [1, 2, 3, 4]}))
def test_index_dtype(self):
df1 = DataFrame.from_records(
{'a': [1, 2], 'c': ['l1', 'l2']}, index=['a'])
df2 = DataFrame.from_records(
{'a': [1.0, 2.0], 'c': ['l1', 'l2']}, index=['a'])
self._assert_not_equal(df1, df2, check_index_type=True)
def test_multiindex_dtype(self):
df1 = DataFrame.from_records(
{'a': [1, 2], 'b': [2.1, 1.5],
'c': ['l1', 'l2']}, index=['a', 'b'])
df2 = DataFrame.from_records(
{'a': [1.0, 2.0], 'b': [2.1, 1.5],
'c': ['l1', 'l2']}, index=['a', 'b'])
self._assert_not_equal(df1, df2, check_index_type=True)
def test_empty_dtypes(self):
df1 = pd.DataFrame(columns=["col1", "col2"])
df1["col1"] = df1["col1"].astype('int64')
df2 = pd.DataFrame(columns=["col1", "col2"])
self._assert_equal(df1, df2, check_dtype=False)
self._assert_not_equal(df1, df2, check_dtype=True)
def test_frame_equal_message(self):
expected = """DataFrame are different
DataFrame shape mismatch
\\[left\\]: \\(3, 2\\)
\\[right\\]: \\(3, 1\\)"""
with tm.assert_raises_regex(AssertionError, expected):
assert_frame_equal(pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}),
pd.DataFrame({'A': [1, 2, 3]}))
expected = """DataFrame\\.index are different
DataFrame\\.index values are different \\(33\\.33333 %\\)
\\[left\\]: Index\\(\\[u?'a', u?'b', u?'c'\\], dtype='object'\\)
\\[right\\]: Index\\(\\[u?'a', u?'b', u?'d'\\], dtype='object'\\)"""
with tm.assert_raises_regex(AssertionError, expected):
assert_frame_equal(pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
index=['a', 'b', 'c']),
pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
index=['a', 'b', 'd']))
expected = """DataFrame\\.columns are different
DataFrame\\.columns values are different \\(50\\.0 %\\)
\\[left\\]: Index\\(\\[u?'A', u?'B'\\], dtype='object'\\)
\\[right\\]: Index\\(\\[u?'A', u?'b'\\], dtype='object'\\)"""
with tm.assert_raises_regex(AssertionError, expected):
assert_frame_equal(pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
index=['a', 'b', 'c']),
pd.DataFrame({'A': [1, 2, 3], 'b': [4, 5, 6]},
index=['a', 'b', 'c']))
expected = """DataFrame\\.iloc\\[:, 1\\] are different
DataFrame\\.iloc\\[:, 1\\] values are different \\(33\\.33333 %\\)
\\[left\\]: \\[4, 5, 6\\]
\\[right\\]: \\[4, 5, 7\\]"""
with tm.assert_raises_regex(AssertionError, expected):
assert_frame_equal(pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}),
pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 7]}))
with tm.assert_raises_regex(AssertionError, expected):
assert_frame_equal(pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}),
pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 7]}),
by_blocks=True)
class TestAssertCategoricalEqual(object):
def test_categorical_equal_message(self):
expected = """Categorical\\.categories are different
Categorical\\.categories values are different \\(25\\.0 %\\)
\\[left\\]: Int64Index\\(\\[1, 2, 3, 4\\], dtype='int64'\\)
\\[right\\]: Int64Index\\(\\[1, 2, 3, 5\\], dtype='int64'\\)"""
a = pd.Categorical([1, 2, 3, 4])
b = pd.Categorical([1, 2, 3, 5])
with tm.assert_raises_regex(AssertionError, expected):
tm.assert_categorical_equal(a, b)
expected = """Categorical\\.codes are different
Categorical\\.codes values are different \\(50\\.0 %\\)
\\[left\\]: \\[0, 1, 3, 2\\]
\\[right\\]: \\[0, 1, 2, 3\\]"""
a = pd.Categorical([1, 2, 4, 3], categories=[1, 2, 3, 4])
b = pd.Categorical([1, 2, 3, 4], categories=[1, 2, 3, 4])
with tm.assert_raises_regex(AssertionError, expected):
tm.assert_categorical_equal(a, b)
expected = """Categorical are different
Attribute "ordered" are different
\\[left\\]: False
\\[right\\]: True"""
a = pd.Categorical([1, 2, 3, 4], ordered=False)
b = pd.Categorical([1, 2, 3, 4], ordered=True)
with tm.assert_raises_regex(AssertionError, expected):
tm.assert_categorical_equal(a, b)
class TestRNGContext(object):
def test_RNGContext(self):
expected0 = 1.764052345967664
expected1 = 1.6243453636632417
with RNGContext(0):
with RNGContext(1):
assert np.random.randn() == expected1
assert np.random.randn() == expected0
class TestLocale(object):
def test_locale(self):
if sys.platform == 'win32':
pytest.skip(
"skipping on win platforms as locale not available")
# GH9744
locales = tm.get_locales()
assert len(locales) >= 1
| {
"pile_set_name": "Github"
} |
/**
* spaint: PropagationComponent.cpp
* Copyright (c) Torr Vision Group, University of Oxford, 2016. All rights reserved.
*/
#include "pipelinecomponents/PropagationComponent.h"
#include "propagation/LabelPropagatorFactory.h"
namespace spaint {
//#################### CONSTRUCTORS ####################
PropagationComponent::PropagationComponent(const PropagationContext_Ptr& context, const std::string& sceneID)
: m_context(context), m_sceneID(sceneID)
{
const Vector2i& depthImageSize = context->get_slam_state(sceneID)->get_depth_image_size();
const int raycastResultSize = depthImageSize.width * depthImageSize.height;
reset_label_propagator(raycastResultSize);
}
//#################### PUBLIC MEMBER FUNCTIONS ####################
void PropagationComponent::reset_label_propagator(int raycastResultSize)
{
m_labelPropagator = LabelPropagatorFactory::make_label_propagator(raycastResultSize, m_context->get_settings()->deviceType);
}
void PropagationComponent::run(const VoxelRenderState_CPtr& renderState)
{
m_labelPropagator->propagate_label(m_context->get_semantic_label(), renderState->raycastResult, m_context->get_slam_state(m_sceneID)->get_voxel_scene().get());
}
}
| {
"pile_set_name": "Github"
} |
module.exports = function(hljs) {
var KEYWORDS = {
keyword:
'module use_module import_module include_module end_module initialise ' +
'mutable initialize finalize finalise interface implementation pred ' +
'mode func type inst solver any_pred any_func is semidet det nondet ' +
'multi erroneous failure cc_nondet cc_multi typeclass instance where ' +
'pragma promise external trace atomic or_else require_complete_switch ' +
'require_det require_semidet require_multi require_nondet ' +
'require_cc_multi require_cc_nondet require_erroneous require_failure',
meta:
// pragma
'inline no_inline type_spec source_file fact_table obsolete memo ' +
'loop_check minimal_model terminates does_not_terminate ' +
'check_termination promise_equivalent_clauses ' +
// preprocessor
'foreign_proc foreign_decl foreign_code foreign_type ' +
'foreign_import_module foreign_export_enum foreign_export ' +
'foreign_enum may_call_mercury will_not_call_mercury thread_safe ' +
'not_thread_safe maybe_thread_safe promise_pure promise_semipure ' +
'tabled_for_io local untrailed trailed attach_to_io_state ' +
'can_pass_as_mercury_type stable will_not_throw_exception ' +
'may_modify_trail will_not_modify_trail may_duplicate ' +
'may_not_duplicate affects_liveness does_not_affect_liveness ' +
'doesnt_affect_liveness no_sharing unknown_sharing sharing',
built_in:
'some all not if then else true fail false try catch catch_any ' +
'semidet_true semidet_false semidet_fail impure_true impure semipure'
};
var COMMENT = hljs.COMMENT('%', '$');
var NUMCODE = {
className: 'number',
begin: "0'.\\|0[box][0-9a-fA-F]*"
};
var ATOM = hljs.inherit(hljs.APOS_STRING_MODE, {relevance: 0});
var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {relevance: 0});
var STRING_FMT = {
className: 'subst',
begin: '\\\\[abfnrtv]\\|\\\\x[0-9a-fA-F]*\\\\\\|%[-+# *.0-9]*[dioxXucsfeEgGp]',
relevance: 0
};
STRING.contains.push(STRING_FMT);
var IMPLICATION = {
className: 'built_in',
variants: [
{begin: '<=>'},
{begin: '<=', relevance: 0},
{begin: '=>', relevance: 0},
{begin: '/\\\\'},
{begin: '\\\\/'}
]
};
var HEAD_BODY_CONJUNCTION = {
className: 'built_in',
variants: [
{begin: ':-\\|-->'},
{begin: '=', relevance: 0}
]
};
return {
aliases: ['m', 'moo'],
keywords: KEYWORDS,
contains: [
IMPLICATION,
HEAD_BODY_CONJUNCTION,
COMMENT,
hljs.C_BLOCK_COMMENT_MODE,
NUMCODE,
hljs.NUMBER_MODE,
ATOM,
STRING,
{begin: /:-/} // relevance booster
]
};
}; | {
"pile_set_name": "Github"
} |
package com.anychart.core.ui;
import com.anychart.APIlib;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.JsObject;
import com.anychart.core.VisualBaseWithBounds;
import java.util.Locale;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import android.text.TextUtils;
// class
/**
* Background element class.<br/>
Background can be a part of another complex element (chart, legend, title and so on),
or used separately.<br/>
Background has a fill, a border and corner shape settings.<br/>
<b>Note:</b> Always specify display bounds if you use Background separately.
*/
public class Background extends VisualBaseWithBounds {
protected Background() {
}
public static Background instantiate() {
return new Background("new anychart.core.ui.background()");
}
public Background(String jsChart) {
jsBase = "background" + ++variableIndex;
APIlib.getInstance().addJSLine(jsBase + " = " + jsChart + ";");
}
public String getJsBase() {
return jsBase;
}
/**
* Getter for element bottom bound settings.
*/
public void bottom() {
APIlib.getInstance().addJSLine(jsBase + ".bottom();");
}
/**
* Setter for element bottom bound settings.
*/
public com.anychart.core.ui.Background bottom(Number bottom) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottom(%s);", bottom));
return this;
}
/**
* Setter for element bottom bound settings.
*/
public com.anychart.core.ui.Background bottom(String bottom) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottom(%s);", wrapQuotes(bottom)));
return this;
}
/**
* Getter for the bottom stroke.
*/
public void bottomStroke() {
APIlib.getInstance().addJSLine(jsBase + ".bottomStroke();");
}
/**
* Setter for bottom stroke settings using one parameter.
*/
public com.anychart.core.ui.Background bottomStroke(com.anychart.graphics.vector.Stroke color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for bottom stroke settings using one parameter.
*/
public com.anychart.core.ui.Background bottomStroke(com.anychart.graphics.vector.ColoredFill color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for bottom stroke settings using one parameter.
*/
public com.anychart.core.ui.Background bottomStroke(String color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s);", wrapQuotes(color)));
return this;
}
/**
* Setter for bottom stroke settings.
*/
public com.anychart.core.ui.Background bottomStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, String lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), wrapQuotes(lineCap)));
return this;
}
/**
* Setter for bottom stroke settings.
*/
public com.anychart.core.ui.Background bottomStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, String lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for bottom stroke settings.
*/
public com.anychart.core.ui.Background bottomStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, wrapQuotes(lineCap)));
return this;
}
/**
* Setter for bottom stroke settings.
*/
public com.anychart.core.ui.Background bottomStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for bottom stroke settings.
*/
public com.anychart.core.ui.Background bottomStroke(String value, Number thickness, String dashpattern, String lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), wrapQuotes(lineCap)));
return this;
}
/**
* Setter for bottom stroke settings.
*/
public com.anychart.core.ui.Background bottomStroke(String value, Number thickness, String dashpattern, String lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for bottom stroke settings.
*/
public com.anychart.core.ui.Background bottomStroke(String value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, wrapQuotes(lineCap)));
return this;
}
/**
* Setter for bottom stroke settings.
*/
public com.anychart.core.ui.Background bottomStroke(String value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bottomStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Getter for element bounds settings.
*/
public com.anychart.core.utils.Bounds bounds() {
return new com.anychart.core.utils.Bounds(jsBase + ".bounds()");
}
/**
* Setter for bounds of the element using one parameter.
*/
public com.anychart.core.ui.Background bounds(com.anychart.utils.RectObj bounds) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s);", (bounds != null) ? bounds.getJsBase() : null));
return this;
}
/**
* Setter for bounds of the element using one parameter.
*/
public com.anychart.core.ui.Background bounds(com.anychart.math.Rect bounds) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s);", (bounds != null) ? bounds.getJsBase() : null));
return this;
}
/**
* Setter for bounds of the element using one parameter.
*/
public com.anychart.core.ui.Background bounds(com.anychart.core.utils.Bounds bounds) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s);", (bounds != null) ? bounds.getJsBase() : null));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(Number x, Number y, Number width, Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", x, y, width, height));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(Number x, Number y, Number width, String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", x, y, width, wrapQuotes(height)));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(Number x, Number y, String width, Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", x, y, wrapQuotes(width), height));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(Number x, Number y, String width, String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", x, y, wrapQuotes(width), wrapQuotes(height)));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(Number x, String y, Number width, Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", x, wrapQuotes(y), width, height));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(Number x, String y, Number width, String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", x, wrapQuotes(y), width, wrapQuotes(height)));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(Number x, String y, String width, Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", x, wrapQuotes(y), wrapQuotes(width), height));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(Number x, String y, String width, String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", x, wrapQuotes(y), wrapQuotes(width), wrapQuotes(height)));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(String x, Number y, Number width, Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", wrapQuotes(x), y, width, height));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(String x, Number y, Number width, String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", wrapQuotes(x), y, width, wrapQuotes(height)));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(String x, Number y, String width, Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", wrapQuotes(x), y, wrapQuotes(width), height));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(String x, Number y, String width, String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", wrapQuotes(x), y, wrapQuotes(width), wrapQuotes(height)));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(String x, String y, Number width, Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", wrapQuotes(x), wrapQuotes(y), width, height));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(String x, String y, Number width, String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", wrapQuotes(x), wrapQuotes(y), width, wrapQuotes(height)));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(String x, String y, String width, Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", wrapQuotes(x), wrapQuotes(y), wrapQuotes(width), height));
return this;
}
/**
* Setter for element bounds settings.
*/
public com.anychart.core.ui.Background bounds(String x, String y, String width, String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".bounds(%s, %s, %s, %s);", wrapQuotes(x), wrapQuotes(y), wrapQuotes(width), wrapQuotes(height)));
return this;
}
/**
* Getter for the corner type.
*/
public void cornerType() {
APIlib.getInstance().addJSLine(jsBase + ".cornerType();");
}
/**
* Setter for the corner type.
*/
public com.anychart.core.ui.Background cornerType(com.anychart.enums.BackgroundCornersType type) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".cornerType(%s);", (type != null) ? type.getJsBase() : null));
return this;
}
/**
* Setter for the corner type.
*/
public com.anychart.core.ui.Background cornerType(String type) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".cornerType(%s);", wrapQuotes(type)));
return this;
}
/**
* Getter for the corner radius.
*/
public void corners() {
APIlib.getInstance().addJSLine(jsBase + ".corners();");
}
/**
* Setter for the corner radius by one value.
*/
public com.anychart.core.ui.Background corners(Number corners) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s);", corners));
return this;
}
/**
* Setter for the corner radius by one value.
*/
public com.anychart.core.ui.Background corners(String corners) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s);", wrapQuotes(corners)));
return this;
}
/**
* Setter for the corner radius by one value.
*/
public com.anychart.core.ui.Background corners(Number[] corners) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s);", Arrays.toString(corners)));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(Number topLeft, Number topRight, Number bottomRight, Number bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", topLeft, topRight, bottomRight, bottomLeft));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(Number topLeft, Number topRight, Number bottomRight, String bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", topLeft, topRight, bottomRight, wrapQuotes(bottomLeft)));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(Number topLeft, Number topRight, String bottomRight, Number bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", topLeft, topRight, wrapQuotes(bottomRight), bottomLeft));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(Number topLeft, Number topRight, String bottomRight, String bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", topLeft, topRight, wrapQuotes(bottomRight), wrapQuotes(bottomLeft)));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(Number topLeft, String topRight, Number bottomRight, Number bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", topLeft, wrapQuotes(topRight), bottomRight, bottomLeft));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(Number topLeft, String topRight, Number bottomRight, String bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", topLeft, wrapQuotes(topRight), bottomRight, wrapQuotes(bottomLeft)));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(Number topLeft, String topRight, String bottomRight, Number bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", topLeft, wrapQuotes(topRight), wrapQuotes(bottomRight), bottomLeft));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(Number topLeft, String topRight, String bottomRight, String bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", topLeft, wrapQuotes(topRight), wrapQuotes(bottomRight), wrapQuotes(bottomLeft)));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(String topLeft, Number topRight, Number bottomRight, Number bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", wrapQuotes(topLeft), topRight, bottomRight, bottomLeft));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(String topLeft, Number topRight, Number bottomRight, String bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", wrapQuotes(topLeft), topRight, bottomRight, wrapQuotes(bottomLeft)));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(String topLeft, Number topRight, String bottomRight, Number bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", wrapQuotes(topLeft), topRight, wrapQuotes(bottomRight), bottomLeft));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(String topLeft, Number topRight, String bottomRight, String bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", wrapQuotes(topLeft), topRight, wrapQuotes(bottomRight), wrapQuotes(bottomLeft)));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(String topLeft, String topRight, Number bottomRight, Number bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", wrapQuotes(topLeft), wrapQuotes(topRight), bottomRight, bottomLeft));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(String topLeft, String topRight, Number bottomRight, String bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", wrapQuotes(topLeft), wrapQuotes(topRight), bottomRight, wrapQuotes(bottomLeft)));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(String topLeft, String topRight, String bottomRight, Number bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", wrapQuotes(topLeft), wrapQuotes(topRight), wrapQuotes(bottomRight), bottomLeft));
return this;
}
/**
* Setter for the corner radius by each value.
*/
public com.anychart.core.ui.Background corners(String topLeft, String topRight, String bottomRight, String bottomLeft) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".corners(%s, %s, %s, %s);", wrapQuotes(topLeft), wrapQuotes(topRight), wrapQuotes(bottomRight), wrapQuotes(bottomLeft)));
return this;
}
/**
* Getter for the element state (enabled or disabled).
*/
public void enabled() {
APIlib.getInstance().addJSLine(jsBase + ".enabled();");
}
/**
* Setter for the element enabled state.
*/
public com.anychart.core.ui.Background enabled(Boolean enabled) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".enabled(%s);", enabled));
return this;
}
/**
* Getter for the background fill.
*/
public void fill() {
APIlib.getInstance().addJSLine(jsBase + ".fill();");
}
/**
* Setter for fill settings using an object, an array or a string.<br/>
Accepts:
<ul>
<li>{@link anychart.graphics.vector.LinearGradientFill}</li>
<li>{@link anychart.graphics.vector.RadialGradientFill}</li>
<li>{@link anychart.graphics.vector.Fill}</li>
<li>{@link anychart.graphics.vector.ImageFill}</li>
</ul>
or a color as a string, along with opacity, if needed, format is "<b>Color Opacity</b>",
e.g. "red 0.5".
*/
public com.anychart.core.ui.Background fill(com.anychart.graphics.vector.Fill color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for fill settings using an object, an array or a string.<br/>
Accepts:
<ul>
<li>{@link anychart.graphics.vector.LinearGradientFill}</li>
<li>{@link anychart.graphics.vector.RadialGradientFill}</li>
<li>{@link anychart.graphics.vector.Fill}</li>
<li>{@link anychart.graphics.vector.ImageFill}</li>
</ul>
or a color as a string, along with opacity, if needed, format is "<b>Color Opacity</b>",
e.g. "red 0.5".
*/
public com.anychart.core.ui.Background fill(com.anychart.graphics.vector.GradientKey color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for fill settings using an object, an array or a string.<br/>
Accepts:
<ul>
<li>{@link anychart.graphics.vector.LinearGradientFill}</li>
<li>{@link anychart.graphics.vector.RadialGradientFill}</li>
<li>{@link anychart.graphics.vector.Fill}</li>
<li>{@link anychart.graphics.vector.ImageFill}</li>
</ul>
or a color as a string, along with opacity, if needed, format is "<b>Color Opacity</b>",
e.g. "red 0.5".
*/
public com.anychart.core.ui.Background fill(String[] color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s);", arrayToStringWrapQuotes(color)));
return this;
}
/**
* Fill as a color with opacity.
*/
public com.anychart.core.ui.Background fill(String color, Number opacity) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s, %s);", wrapQuotes(color), opacity));
return this;
}
/**
* Linear gradient fill.
*/
public com.anychart.core.ui.Background fill(com.anychart.graphics.vector.GradientKey keys, Number angle, Boolean mode, Number opacity) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s, %s, %s, %s);", (keys != null) ? keys.getJsBase() : null, angle, mode, opacity));
return this;
}
/**
* Linear gradient fill.
*/
public com.anychart.core.ui.Background fill(com.anychart.graphics.vector.GradientKey keys, Number angle, com.anychart.graphics.vector.Rect mode, Number opacity) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s, %s, %s, %s);", (keys != null) ? keys.getJsBase() : null, angle, (mode != null) ? mode.getJsBase() : null, opacity));
return this;
}
/**
* Linear gradient fill.
*/
public com.anychart.core.ui.Background fill(com.anychart.graphics.vector.GradientKey keys, Number angle, String mode, Number opacity) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s, %s, %s, %s);", (keys != null) ? keys.getJsBase() : null, angle, wrapQuotes(mode), opacity));
return this;
}
/**
* Linear gradient fill.
*/
public com.anychart.core.ui.Background fill(String[] keys, Number angle, Boolean mode, Number opacity) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s, %s, %s, %s);", arrayToStringWrapQuotes(keys), angle, mode, opacity));
return this;
}
/**
* Linear gradient fill.
*/
public com.anychart.core.ui.Background fill(String[] keys, Number angle, com.anychart.graphics.vector.Rect mode, Number opacity) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s, %s, %s, %s);", arrayToStringWrapQuotes(keys), angle, (mode != null) ? mode.getJsBase() : null, opacity));
return this;
}
/**
* Linear gradient fill.
*/
public com.anychart.core.ui.Background fill(String[] keys, Number angle, String mode, Number opacity) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s, %s, %s, %s);", arrayToStringWrapQuotes(keys), angle, wrapQuotes(mode), opacity));
return this;
}
/**
* Radial gradient fill.
*/
public com.anychart.core.ui.Background fill(com.anychart.graphics.vector.GradientKey keys, Number cx, Number cy, com.anychart.graphics.math.Rect mode, Number opacity, Number fx, Number fy) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s, %s, %s, %s, %s, %s, %s);", (keys != null) ? keys.getJsBase() : null, cx, cy, (mode != null) ? mode.getJsBase() : null, opacity, fx, fy));
return this;
}
/**
* Radial gradient fill.
*/
public com.anychart.core.ui.Background fill(String[] keys, Number cx, Number cy, com.anychart.graphics.math.Rect mode, Number opacity, Number fx, Number fy) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s, %s, %s, %s, %s, %s, %s);", arrayToStringWrapQuotes(keys), cx, cy, (mode != null) ? mode.getJsBase() : null, opacity, fx, fy));
return this;
}
/**
* Returns pixel bounds of the element due to parent bounds and self bounds settings.
*/
public com.anychart.math.Rect getPixelBounds() {
return new com.anychart.math.Rect(jsBase + ".getPixelBounds()");
}
/**
* Getter for element height settings.
*/
public void height() {
APIlib.getInstance().addJSLine(jsBase + ".height();");
}
/**
* Setter for element height setting.
*/
public com.anychart.core.ui.Background height(Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".height(%s);", height));
return this;
}
/**
* Setter for element height setting.
*/
public com.anychart.core.ui.Background height(String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".height(%s);", wrapQuotes(height)));
return this;
}
/**
* Getter for element left bound settings.
*/
public void left() {
APIlib.getInstance().addJSLine(jsBase + ".left();");
}
/**
* Setter for element left bound settings.
*/
public com.anychart.core.ui.Background left(Number left) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".left(%s);", left));
return this;
}
/**
* Setter for element left bound settings.
*/
public com.anychart.core.ui.Background left(String left) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".left(%s);", wrapQuotes(left)));
return this;
}
/**
* Getter for the left stroke.
*/
public void leftStroke() {
APIlib.getInstance().addJSLine(jsBase + ".leftStroke();");
}
/**
* Setter for left stroke settings using one parameter.
*/
public com.anychart.core.ui.Background leftStroke(com.anychart.graphics.vector.Stroke color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".leftStroke(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for left stroke settings using one parameter.
*/
public com.anychart.core.ui.Background leftStroke(String color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".leftStroke(%s);", wrapQuotes(color)));
return this;
}
/**
* Setter for left stroke settings.
*/
public com.anychart.core.ui.Background leftStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, String lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".leftStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), wrapQuotes(lineCap)));
return this;
}
/**
* Setter for left stroke settings.
*/
public com.anychart.core.ui.Background leftStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, String lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".leftStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for left stroke settings.
*/
public com.anychart.core.ui.Background leftStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".leftStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, wrapQuotes(lineCap)));
return this;
}
/**
* Setter for left stroke settings.
*/
public com.anychart.core.ui.Background leftStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".leftStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for left stroke settings.
*/
public com.anychart.core.ui.Background leftStroke(String value, Number thickness, String dashpattern, String lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".leftStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), wrapQuotes(lineCap)));
return this;
}
/**
* Setter for left stroke settings.
*/
public com.anychart.core.ui.Background leftStroke(String value, Number thickness, String dashpattern, String lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".leftStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for left stroke settings.
*/
public com.anychart.core.ui.Background leftStroke(String value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".leftStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, wrapQuotes(lineCap)));
return this;
}
/**
* Setter for left stroke settings.
*/
public com.anychart.core.ui.Background leftStroke(String value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".leftStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Getter for the maximum height.
*/
public void maxHeight() {
APIlib.getInstance().addJSLine(jsBase + ".maxHeight();");
}
/**
* Setter for the maximum height.
*/
public com.anychart.core.ui.Background maxHeight(Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".maxHeight(%s);", height));
return this;
}
/**
* Setter for the maximum height.
*/
public com.anychart.core.ui.Background maxHeight(String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".maxHeight(%s);", wrapQuotes(height)));
return this;
}
/**
* Getter for the maximum width.
*/
public void maxWidth() {
APIlib.getInstance().addJSLine(jsBase + ".maxWidth();");
}
/**
* Setter for the maximum width.
*/
public com.anychart.core.ui.Background maxWidth(Number width) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".maxWidth(%s);", width));
return this;
}
/**
* Setter for the maximum width.
*/
public com.anychart.core.ui.Background maxWidth(String width) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".maxWidth(%s);", wrapQuotes(width)));
return this;
}
/**
* Getter for the minimum height.
*/
public void minHeight() {
APIlib.getInstance().addJSLine(jsBase + ".minHeight();");
}
/**
* Setter for the minimum height.
*/
public com.anychart.core.ui.Background minHeight(Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".minHeight(%s);", height));
return this;
}
/**
* Setter for the minimum height.
*/
public com.anychart.core.ui.Background minHeight(String height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".minHeight(%s);", wrapQuotes(height)));
return this;
}
/**
* Getter for the minimum width.
*/
public void minWidth() {
APIlib.getInstance().addJSLine(jsBase + ".minWidth();");
}
/**
* Setter for the minimum width.
*/
public com.anychart.core.ui.Background minWidth(Number width) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".minWidth(%s);", width));
return this;
}
/**
* Setter for the minimum width.
*/
public com.anychart.core.ui.Background minWidth(String width) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".minWidth(%s);", wrapQuotes(width)));
return this;
}
/**
* Prints all elements on related stage.
*/
public void print(com.anychart.graphics.vector.PaperSize paperSizeOrOptions, Boolean landscape) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".print(%s, %s);", (paperSizeOrOptions != null) ? paperSizeOrOptions.getJsBase() : null, landscape));
}
/**
* Prints all elements on related stage.
*/
public void print(String paperSizeOrOptions, Boolean landscape) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".print(%s, %s);", wrapQuotes(paperSizeOrOptions), landscape));
}
/**
* Removes all listeners from an object. You can also optionally remove listeners of some particular type.
*/
public void removeAllListeners(String type) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".removeAllListeners(%s);", wrapQuotes(type)));
}
/**
* Getter for element right bound settings.
*/
public void right() {
APIlib.getInstance().addJSLine(jsBase + ".right();");
}
/**
* Setter for element right bound setting.
*/
public com.anychart.core.ui.Background right(Number right) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".right(%s);", right));
return this;
}
/**
* Setter for element right bound setting.
*/
public com.anychart.core.ui.Background right(String right) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".right(%s);", wrapQuotes(right)));
return this;
}
/**
* Getter for the right stroke.
*/
public void rightStroke() {
APIlib.getInstance().addJSLine(jsBase + ".rightStroke();");
}
/**
* Setter for right stroke settings using one parameter.
*/
public com.anychart.core.ui.Background rightStroke(com.anychart.graphics.vector.Stroke color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for right stroke settings using one parameter.
*/
public com.anychart.core.ui.Background rightStroke(com.anychart.graphics.vector.ColoredFill color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for right stroke settings using one parameter.
*/
public com.anychart.core.ui.Background rightStroke(String color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s);", wrapQuotes(color)));
return this;
}
/**
* Setter for right stroke settings.
*/
public com.anychart.core.ui.Background rightStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, String lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), wrapQuotes(lineCap)));
return this;
}
/**
* Setter for right stroke settings.
*/
public com.anychart.core.ui.Background rightStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, String lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for right stroke settings.
*/
public com.anychart.core.ui.Background rightStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, wrapQuotes(lineCap)));
return this;
}
/**
* Setter for right stroke settings.
*/
public com.anychart.core.ui.Background rightStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for right stroke settings.
*/
public com.anychart.core.ui.Background rightStroke(String value, Number thickness, String dashpattern, String lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), wrapQuotes(lineCap)));
return this;
}
/**
* Setter for right stroke settings.
*/
public com.anychart.core.ui.Background rightStroke(String value, Number thickness, String dashpattern, String lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for right stroke settings.
*/
public com.anychart.core.ui.Background rightStroke(String value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, wrapQuotes(lineCap)));
return this;
}
/**
* Setter for right stroke settings.
*/
public com.anychart.core.ui.Background rightStroke(String value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".rightStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Getter for the background stroke.
*/
public void stroke() {
APIlib.getInstance().addJSLine(jsBase + ".stroke();");
}
/**
* Setter for stroke settings using one parameter.
*/
public com.anychart.core.ui.Background stroke(com.anychart.graphics.vector.Stroke color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for stroke settings using one parameter.
*/
public com.anychart.core.ui.Background stroke(com.anychart.graphics.vector.ColoredFill color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for stroke settings using one parameter.
*/
public com.anychart.core.ui.Background stroke(String color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s);", wrapQuotes(color)));
return this;
}
/**
* Setter for stroke settings.
*/
public com.anychart.core.ui.Background stroke(com.anychart.graphics.vector.Stroke color, Number thickness, String dashpattern, String lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s, %s, %s, %s, %s);", (color != null) ? color.getJsBase() : null, thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), wrapQuotes(lineCap)));
return this;
}
/**
* Setter for stroke settings.
*/
public com.anychart.core.ui.Background stroke(com.anychart.graphics.vector.Stroke color, Number thickness, String dashpattern, String lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s, %s, %s, %s, %s);", (color != null) ? color.getJsBase() : null, thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for stroke settings.
*/
public com.anychart.core.ui.Background stroke(com.anychart.graphics.vector.Stroke color, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s, %s, %s, %s, %s);", (color != null) ? color.getJsBase() : null, thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, wrapQuotes(lineCap)));
return this;
}
/**
* Setter for stroke settings.
*/
public com.anychart.core.ui.Background stroke(com.anychart.graphics.vector.Stroke color, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s, %s, %s, %s, %s);", (color != null) ? color.getJsBase() : null, thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for stroke settings.
*/
public com.anychart.core.ui.Background stroke(String color, Number thickness, String dashpattern, String lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s, %s, %s, %s, %s);", wrapQuotes(color), thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), wrapQuotes(lineCap)));
return this;
}
/**
* Setter for stroke settings.
*/
public com.anychart.core.ui.Background stroke(String color, Number thickness, String dashpattern, String lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s, %s, %s, %s, %s);", wrapQuotes(color), thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for stroke settings.
*/
public com.anychart.core.ui.Background stroke(String color, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s, %s, %s, %s, %s);", wrapQuotes(color), thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, wrapQuotes(lineCap)));
return this;
}
/**
* Setter for stroke settings.
*/
public com.anychart.core.ui.Background stroke(String color, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".stroke(%s, %s, %s, %s, %s);", wrapQuotes(color), thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Getter for element top bound settings.
*/
public void top() {
APIlib.getInstance().addJSLine(jsBase + ".top();");
}
/**
* Setter for element top bound settings.
*/
public com.anychart.core.ui.Background top(Number top) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".top(%s);", top));
return this;
}
/**
* Setter for element top bound settings.
*/
public com.anychart.core.ui.Background top(String top) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".top(%s);", wrapQuotes(top)));
return this;
}
/**
* Getter for the top stroke.
*/
public void topStroke() {
APIlib.getInstance().addJSLine(jsBase + ".topStroke();");
}
/**
* Setter for top stroke settings using one parameter.
*/
public com.anychart.core.ui.Background topStroke(com.anychart.graphics.vector.Stroke color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for top stroke settings using one parameter.
*/
public com.anychart.core.ui.Background topStroke(com.anychart.graphics.vector.ColoredFill color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s);", (color != null) ? color.getJsBase() : null));
return this;
}
/**
* Setter for top stroke settings using one parameter.
*/
public com.anychart.core.ui.Background topStroke(String color) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s);", wrapQuotes(color)));
return this;
}
/**
* Setter for top stroke settings.
*/
public com.anychart.core.ui.Background topStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, String lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), wrapQuotes(lineCap)));
return this;
}
/**
* Setter for top stroke settings.
*/
public com.anychart.core.ui.Background topStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, String lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for top stroke settings.
*/
public com.anychart.core.ui.Background topStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, wrapQuotes(lineCap)));
return this;
}
/**
* Setter for top stroke settings.
*/
public com.anychart.core.ui.Background topStroke(com.anychart.graphics.vector.Stroke value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s, %s, %s, %s, %s);", (value != null) ? value.getJsBase() : null, thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for top stroke settings.
*/
public com.anychart.core.ui.Background topStroke(String value, Number thickness, String dashpattern, String lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), wrapQuotes(lineCap)));
return this;
}
/**
* Setter for top stroke settings.
*/
public com.anychart.core.ui.Background topStroke(String value, Number thickness, String dashpattern, String lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), wrapQuotes(lineJoin), (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
/**
* Setter for top stroke settings.
*/
public com.anychart.core.ui.Background topStroke(String value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, String lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, wrapQuotes(lineCap)));
return this;
}
/**
* Setter for top stroke settings.
*/
public com.anychart.core.ui.Background topStroke(String value, Number thickness, String dashpattern, com.anychart.graphics.vector.StrokeLineJoin lineJoin, com.anychart.graphics.vector.StrokeLineCap lineCap) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".topStroke(%s, %s, %s, %s, %s);", wrapQuotes(value), thickness, wrapQuotes(dashpattern), (lineJoin != null) ? lineJoin.getJsBase() : null, (lineCap != null) ? lineCap.getJsBase() : null));
return this;
}
public void setOnClickListener(com.anychart.chart.common.listener.ListenersInterface.OnClickListener listener) {
StringBuilder js = new StringBuilder();
js.append(jsBase).append(".listen('pointClick', function(e) {");
if (listener.getFields() != null) {
js.append("var result = ");
for (String field : listener.getFields()) {
js.append(String.format(Locale.US, "'%1$s' + ':' + e.point.get('%1$s') + ',' +", field));
}
js.setLength(js.length() - 8);
js.append(";");
js.append("android.onClick(result);");
} else {
js.append("android.onClick(null);");
}
js.append("});");
com.anychart.chart.common.listener.ListenersInterface.getInstance().setOnClickListener(listener);
APIlib.getInstance().addJSLine(js.toString());
}
public void setOnClickListener(com.anychart.chart.common.listener.ListenersInterface.OnClickListener listener, String type, String ePath) {
StringBuilder js = new StringBuilder();
js.append(jsBase).append(String.format(Locale.US, ".listen('%1$s', function(e) {", type));
if (listener.getFields() != null) {
ePath = (ePath != null) ? ePath + "." : "";
js.append("var result = ");
for (String field : listener.getFields()) {
js.append(String.format(Locale.US, "'%1$s' + ':' + e.%2$s%1$s + ',' +", field, ePath));
}
js.setLength(js.length() - 8);
js.append(";");
js.append("android.onClick(result);");
} else {
js.append("android.onClick(null);");
}
js.append("});");
com.anychart.chart.common.listener.ListenersInterface.getInstance().setOnClickListener(listener);
APIlib.getInstance().addJSLine(js.toString());
}
/**
* Removes an event listener which was added with listen() by the key returned by listen() or listenOnce().
*/
public void unlistenByKey(String key) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".unlistenByKey(%s);", wrapQuotes(key)));
}
/**
* Getter for element width settings.
*/
public void width() {
APIlib.getInstance().addJSLine(jsBase + ".width();");
}
/**
* Setter for element width setting.
*/
public com.anychart.core.ui.Background width(Number width) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".width(%s);", width));
return this;
}
/**
* Setter for element width setting.
*/
public com.anychart.core.ui.Background width(String width) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".width(%s);", wrapQuotes(width)));
return this;
}
/**
* Getter for the Z-index of the element.
*/
public void zIndex() {
APIlib.getInstance().addJSLine(jsBase + ".zIndex();");
}
/**
* Setter for the Z-index of the element.
*/
public com.anychart.core.ui.Background zIndex(Number zIndex) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".zIndex(%s);", zIndex));
return this;
}
/**
* Getter for the container.
*/
public com.anychart.graphics.vector.Layer container() {
return new com.anychart.graphics.vector.Layer(jsBase + ".container()");
}
/**
* Setter for the container.
*/
public com.anychart.core.ui.Background container(com.anychart.graphics.vector.Layer element) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".container(%s);", (element != null) ? element.getJsBase() : null));
return this;
}
/**
* Setter for the container.
*/
public com.anychart.core.ui.Background container(com.anychart.graphics.vector.Stage element) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".container(%s);", (element != null) ? element.getJsBase() : null));
return this;
}
/**
* Setter for the container.
*/
public com.anychart.core.ui.Background container(String element) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".container(%s);", wrapQuotes(element)));
return this;
}
/**
* Getter for the parent bounds.<br>
Bounds that would be used in case of percent size calculations. Expects pixel values only.
*/
public com.anychart.math.Rect parentBounds() {
return new com.anychart.math.Rect(jsBase + ".parentBounds()");
}
/**
* Setter for the parent bounds using single value.<br>
Bounds that would be used in case of percent size calculations. Expects pixel values only.
*/
public com.anychart.core.ui.Background parentBounds(com.anychart.math.Rect bounds) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".parentBounds(%s);", (bounds != null) ? bounds.getJsBase() : null));
return this;
}
/**
* Setter for the parent bounds using single value.<br>
Bounds that would be used in case of percent size calculations. Expects pixel values only.
*/
public com.anychart.core.ui.Background parentBounds(String bounds) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".parentBounds(%s);", wrapQuotes(bounds)));
return this;
}
/**
* Setter for the parent bounds using single value.<br>
Bounds that would be used in case of percent size calculations. Expects pixel values only.
*/
public com.anychart.core.ui.Background parentBounds(Number bounds) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".parentBounds(%s);", bounds));
return this;
}
/**
* Setter for the parent bounds using several values.<br>
Bounds that would be used in case of percent size calculations. Expects pixel values only.
*/
public com.anychart.core.ui.Background parentBounds(Number left, Number top, Number width, Number height) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".parentBounds(%s, %s, %s, %s);", left, top, width, height));
return this;
}
/**
*
*/
public com.anychart.core.ui.Background fill(String value) {
APIlib.getInstance().addJSLine(String.format(Locale.US, jsBase + ".fill(%s);", wrapQuotes(value)));
return this;
}
} | {
"pile_set_name": "Github"
} |
/*
* PLUGIN HISTORY
*
* Swedish language file.
*
* Author: Magnus Holm ([email protected])
*/
theUILang.historyAddition = "Tillägg";
theUILang.historyDeletion = "Radering";
theUILang.historyFinish = "Slutföring";
theUILang.historyLog = "Logg";
theUILang.history = "Historia";
theUILang.historyLimit = "Högst antal uppgifter";
theUILang.seedingTime = "Slutförd";
theUILang.addTime = "Tillagd";
theUILang.hstDeletePrompt = "Vill du verkligen ta bort markerad(e) uppgift(er)?";
theUILang.hstDelete = "Ta bort uppgift(er)";
theUILang.Added = "Tillagd";
theUILang.Finished = "Slutförd";
theUILang.Deleted = "Borttagen";
theUILang.Time = "Tid";
theUILang.Tracker = "Tracker";
theUILang.enableNotifications = "Aktivera skrivbordsnotiser";
theUILang.historyNotification = "Skrivbordsnotiser";
theUILang.notifAutoClose = "Stäng skrivbordsnotiser automatiskt efter";
theUILang.notifTip = {
false: "Din webbläsare stöder inte skrivbordsnotiser. Försök med en annan webbläsare. T.ex. Google Chrome.",
"granted": "",
"default": "Din webbläsare stöder skrivbordsnotiser. Tryck på knappen nedan för att aktivera.",
"denied": "Din webbläsare stöder skrivbordsnotiser men de är inaktiverade för denna webbplats. Stäng denna dialog och aktivera skrivbordsnotiser i dina webbläsarinställningar.",
};
theUILang.pushbulletNotification = "PushBullet notifications";
theUILang.pushbulletKey = "PushBullet Access Token";
theUILang.turnNotifyOn = "Turn notifications on";
theUILang.turnNotifyOff = "Turn notifications off";
thePlugins.get("history").langLoaded(); | {
"pile_set_name": "Github"
} |
'use strict';
module.exports = function generate_contains(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $idx = 'i' + $lvl,
$dataNxt = $it.dataLevel = it.dataLevel + 1,
$nextData = 'data' + $dataNxt,
$currentBaseId = it.baseId,
$nonEmptySchema = it.util.schemaHasRules($schema, it.RULES.all);
out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
if ($nonEmptySchema) {
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
var $passData = $data + '[' + $idx + ']';
$it.dataPathArr[$dataNxt] = $idx;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
} else {
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
}
out += ' if (' + ($nextValid) + ') break; } ';
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
} else {
out += ' if (' + ($data) + '.length == 0) {';
}
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'should contain a valid item\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } else { ';
if ($nonEmptySchema) {
out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
}
if (it.opts.allErrors) {
out += ' } ';
}
out = it.util.cleanUpCode(out);
return out;
}
| {
"pile_set_name": "Github"
} |
{
"assignee": null,
"assignees": [],
"author_association": "MEMBER",
"body": "插件安装即将破百之际, 作一先期调研,由于源代码中的命名往往是驼峰或下划线格式, 而双击选中文本往往选中整个命名, 考虑翻译整个命名. 演示如下\r\n\r\n\r\n\r\n- 在状态栏中显示直译信息 (会与一马的翻译效果相同)\r\n- 在弹窗中, 显示所有词的详细释义和词形.\r\n - 是否需要原词? 比如 \"show n. 显示, 表现....\"\r\n - 词形是否需要?\r\n - 由于没找到好的分隔方法, 暂时用🐶代替.\r\n\r\n[v2调研帖](https://www.v2ex.com/t/505953)",
"closed_at": "2018-11-10T12:21:06Z",
"comment_data": [
{
"author_association": "MEMBER",
"body": "已在0.0.4实现: https://github.com/program-in-chinese/vscode_english_chinese_dictionary/commit/82f2f32ce8bc6164bb919bdea3f38e521b1accde",
"created_at": "2018-11-10T12:21:06Z",
"html_url": "https://github.com/program-in-chinese/vscode_english_chinese_dictionary/issues/2#issuecomment-437580128",
"id": 437580128,
"issue_url": "https://api.github.com/repos/program-in-chinese/vscode_english_chinese_dictionary/issues/2",
"node_id": "MDEyOklzc3VlQ29tbWVudDQzNzU4MDEyOA==",
"updated_at": "2018-11-10T12:21:06Z",
"url": "https://api.github.com/repos/program-in-chinese/vscode_english_chinese_dictionary/issues/comments/437580128",
"user": {
"avatar_url": "https://avatars1.githubusercontent.com/u/392497?v=4",
"events_url": "https://api.github.com/users/nobodxbodon/events{/privacy}",
"followers_url": "https://api.github.com/users/nobodxbodon/followers",
"following_url": "https://api.github.com/users/nobodxbodon/following{/other_user}",
"gists_url": "https://api.github.com/users/nobodxbodon/gists{/gist_id}",
"gravatar_id": "",
"html_url": "https://github.com/nobodxbodon",
"id": 392497,
"login": "nobodxbodon",
"node_id": "MDQ6VXNlcjM5MjQ5Nw==",
"organizations_url": "https://api.github.com/users/nobodxbodon/orgs",
"received_events_url": "https://api.github.com/users/nobodxbodon/received_events",
"repos_url": "https://api.github.com/users/nobodxbodon/repos",
"site_admin": false,
"starred_url": "https://api.github.com/users/nobodxbodon/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/nobodxbodon/subscriptions",
"type": "User",
"url": "https://api.github.com/users/nobodxbodon"
}
}
],
"comments": 1,
"comments_url": "https://api.github.com/repos/program-in-chinese/vscode_english_chinese_dictionary/issues/2/comments",
"created_at": "2018-11-08T18:22:32Z",
"event_data": [
{
"actor": {
"avatar_url": "https://avatars1.githubusercontent.com/u/392497?v=4",
"events_url": "https://api.github.com/users/nobodxbodon/events{/privacy}",
"followers_url": "https://api.github.com/users/nobodxbodon/followers",
"following_url": "https://api.github.com/users/nobodxbodon/following{/other_user}",
"gists_url": "https://api.github.com/users/nobodxbodon/gists{/gist_id}",
"gravatar_id": "",
"html_url": "https://github.com/nobodxbodon",
"id": 392497,
"login": "nobodxbodon",
"node_id": "MDQ6VXNlcjM5MjQ5Nw==",
"organizations_url": "https://api.github.com/users/nobodxbodon/orgs",
"received_events_url": "https://api.github.com/users/nobodxbodon/received_events",
"repos_url": "https://api.github.com/users/nobodxbodon/repos",
"site_admin": false,
"starred_url": "https://api.github.com/users/nobodxbodon/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/nobodxbodon/subscriptions",
"type": "User",
"url": "https://api.github.com/users/nobodxbodon"
},
"commit_id": null,
"commit_url": null,
"created_at": "2018-11-10T12:21:06Z",
"event": "closed",
"id": 1958379990,
"node_id": "MDExOkNsb3NlZEV2ZW50MTk1ODM3OTk5MA==",
"url": "https://api.github.com/repos/program-in-chinese/vscode_english_chinese_dictionary/issues/events/1958379990"
}
],
"events_url": "https://api.github.com/repos/program-in-chinese/vscode_english_chinese_dictionary/issues/2/events",
"html_url": "https://github.com/program-in-chinese/vscode_english_chinese_dictionary/issues/2",
"id": 378858970,
"labels": [],
"labels_url": "https://api.github.com/repos/program-in-chinese/vscode_english_chinese_dictionary/issues/2/labels{/name}",
"locked": false,
"milestone": null,
"node_id": "MDU6SXNzdWUzNzg4NTg5NzA=",
"number": 2,
"repository_url": "https://api.github.com/repos/program-in-chinese/vscode_english_chinese_dictionary",
"state": "closed",
"title": "翻译整个命名字段",
"updated_at": "2018-11-10T12:21:06Z",
"url": "https://api.github.com/repos/program-in-chinese/vscode_english_chinese_dictionary/issues/2",
"user": {
"avatar_url": "https://avatars1.githubusercontent.com/u/392497?v=4",
"events_url": "https://api.github.com/users/nobodxbodon/events{/privacy}",
"followers_url": "https://api.github.com/users/nobodxbodon/followers",
"following_url": "https://api.github.com/users/nobodxbodon/following{/other_user}",
"gists_url": "https://api.github.com/users/nobodxbodon/gists{/gist_id}",
"gravatar_id": "",
"html_url": "https://github.com/nobodxbodon",
"id": 392497,
"login": "nobodxbodon",
"node_id": "MDQ6VXNlcjM5MjQ5Nw==",
"organizations_url": "https://api.github.com/users/nobodxbodon/orgs",
"received_events_url": "https://api.github.com/users/nobodxbodon/received_events",
"repos_url": "https://api.github.com/users/nobodxbodon/repos",
"site_admin": false,
"starred_url": "https://api.github.com/users/nobodxbodon/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/nobodxbodon/subscriptions",
"type": "User",
"url": "https://api.github.com/users/nobodxbodon"
}
} | {
"pile_set_name": "Github"
} |
.panel {
overflow: hidden;
text-align: left;
margin: 0;
border: 0;
-moz-border-radius: 0 0 0 0;
-webkit-border-radius: 0 0 0 0;
border-radius: 0 0 0 0;
}
.panel-header,
.panel-body {
border-width: 1px;
border-style: solid;
}
.panel-header {
padding: 5px;
position: relative;
}
.panel-title {
background: url('images/blank.gif') no-repeat;
}
.panel-header-noborder {
border-width: 0 0 1px 0;
}
.panel-body {
overflow: auto;
border-top-width: 0;
padding: 0;
}
.panel-body-noheader {
border-top-width: 1px;
}
.panel-body-noborder {
border-width: 0px;
}
.panel-body-nobottom {
border-bottom-width: 0;
}
.panel-with-icon {
padding-left: 18px;
}
.panel-icon,
.panel-tool {
position: absolute;
top: 50%;
margin-top: -8px;
height: 16px;
overflow: hidden;
}
.panel-icon {
left: 5px;
width: 16px;
}
.panel-tool {
right: 5px;
width: auto;
}
.panel-tool a {
display: inline-block;
width: 16px;
height: 16px;
opacity: 0.6;
filter: alpha(opacity=60);
margin: 0 0 0 2px;
vertical-align: top;
}
.panel-tool a:hover {
opacity: 1;
filter: alpha(opacity=100);
background-color: #E6E6E6;
-moz-border-radius: -2px -2px -2px -2px;
-webkit-border-radius: -2px -2px -2px -2px;
border-radius: -2px -2px -2px -2px;
}
.panel-loading {
padding: 11px 0px 10px 30px;
}
.panel-noscroll {
overflow: hidden;
}
.panel-fit,
.panel-fit body {
height: 100%;
margin: 0;
padding: 0;
border: 0;
overflow: hidden;
}
.panel-loading {
background: url('images/loading.gif') no-repeat 10px 10px;
}
.panel-tool-close {
background: url('images/panel_tools.png') no-repeat -16px 0px;
}
.panel-tool-min {
background: url('images/panel_tools.png') no-repeat 0px 0px;
}
.panel-tool-max {
background: url('images/panel_tools.png') no-repeat 0px -16px;
}
.panel-tool-restore {
background: url('images/panel_tools.png') no-repeat -16px -16px;
}
.panel-tool-collapse {
background: url('images/panel_tools.png') no-repeat -32px 0;
}
.panel-tool-expand {
background: url('images/panel_tools.png') no-repeat -32px -16px;
}
.panel-header,
.panel-body {
border-color: #abafb8;
}
.panel-header {
background-color: #c7ccd1;
}
.panel-body {
background-color: #fafafa;
color: #404040;
font-size: 12px;
}
.panel-title {
font-size: 12px;
font-weight: bold;
color: #404040;
height: 16px;
line-height: 16px;
}
.panel-footer {
border: 1px solid #abafb8;
overflow: hidden;
background: #f5f5f5;
}
.panel-footer-noborder {
border-width: 1px 0 0 0;
}
| {
"pile_set_name": "Github"
} |
<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/autoload.php';
ini_set('precision', 14);
ini_set('serialize_precision', 14);
| {
"pile_set_name": "Github"
} |
package org.stagemonitor.alerting.alerter;
import java.io.StringWriter;
import java.util.Collections;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.stagemonitor.alerting.AlertingPlugin;
import org.stagemonitor.alerting.incident.Incident;
public class AlertTemplateProcessor {
private final AlertingPlugin alertingPlugin;
private final Configuration cfg;
public AlertTemplateProcessor(AlertingPlugin alertingPlugin) {
this.alertingPlugin = alertingPlugin;
cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
public String processHtmlTemplate(Incident incident) {
return processTemplate("alertsHtml.ftl", alertingPlugin.getHtmlAlertTemplate(), incident);
}
public String processPlainTextTemplate(Incident incident) {
return processTemplate("alertsPlainText.ftl", alertingPlugin.getPlainTextAlertTemplate(), incident);
}
public String processShortDescriptionTemplate(Incident incident) {
return processTemplate("alertsShortDescription.ftl", alertingPlugin.getShortDescriptionAlertTemplate(), incident);
}
private String processTemplate(String templateName, String templateString, Incident incident) {
try {
Template template = new Template(templateName, templateString, cfg);
StringWriter out = new StringWriter(templateString.length());
template.process(Collections.singletonMap("incident", incident), out);
return out.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| {
"pile_set_name": "Github"
} |
RPLIDAR Public SDK v1.12.0 Release Note
======================================
- [new feature] support to set spin speed for S1 in rplidar_driver and framegrabber
- [improvement] use grabScanDataHq instead of grabScanData in ultra_simple | {
"pile_set_name": "Github"
} |
/*
* Copyright 2015 The FireNio Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.firenio.common;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class DateUtil {
private static final ThreadLocal<DateUtil> dateUtils = new ThreadLocal<>();
private static final String[] MONTHS = new String[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
private static final byte[][] MONTHS_BYTES = new byte[][]{"Jan".getBytes(), "Feb".getBytes(), "Mar".getBytes(), "Apr".getBytes(), "May".getBytes(), "Jun".getBytes(), "Jul".getBytes(), "Aug".getBytes(), "Sep".getBytes(), "Oct".getBytes(), "Nov".getBytes(), "Dec".getBytes()};
private static final byte[] NS = new byte[10];
private static final TimeZone TZ = TimeZone.getDefault();
private static final byte TZ_0;
private static final byte TZ_1;
private static final byte TZ_2;
private static final String TZ_NAME;
private static final String[] WEEK_DAYS = new String[]{"", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
private static final byte[][] WEEK_DAYS_BYTES = new byte[][]{"".getBytes(), "Sun".getBytes(), "Mon".getBytes(), "Tue".getBytes(), "Wed".getBytes(), "Thu".getBytes(), "Fri".getBytes(), "Sat".getBytes()};
static {
boolean daylight = (Calendar.getInstance().get(Calendar.DST_OFFSET) != 0);
TZ_NAME = TZ.getDisplayName(daylight, TimeZone.SHORT, Locale.getDefault());
TZ_0 = (byte) TZ_NAME.charAt(0);
TZ_1 = (byte) TZ_NAME.charAt(1);
TZ_2 = (byte) TZ_NAME.charAt(2);
for (int i = 0; i < NS.length; i++) {
NS[i] = (byte) String.valueOf(i).charAt(0);
}
}
private final DateFormat HH_mm_ss = new SimpleDateFormat("HH:mm:ss");
private final DateFormat yyMMdd = new SimpleDateFormat("yyMMdd");
private final DateFormat yyyy_MM_dd = new SimpleDateFormat("yyyy-MM-dd");
private final DateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final DateFormat yyyy_MM_dd_HH_mm_ss_SSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private final DateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
private final DateFormat yyyyMMdd_HH_mm_ss = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
private final DateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
private Calendar calendar = Calendar.getInstance(TZ);
public static DateUtil get() {
DateUtil d = dateUtils.get();
if (d == null) {
d = new DateUtil();
dateUtils.set(d);
}
return d;
}
public static void main(String[] args) {
Date d = new Date();
System.out.println(DateUtil.get().formatYyyy_MM_dd_HH_mm_ss(d));
String str = get().formatHttp(d.getTime());
System.out.println(str);
d = get().parseHttp(str);
System.out.println(DateUtil.get().formatYyyy_MM_dd_HH_mm_ss(d));
System.out.println(new String(get().formatHttpBytes()));
System.out.println(get().formatYyyy_MM_dd_HH_mm_ss(d));
System.out.println(TZ);
}
public String formatHH_mm_ss() {
return formatHH_mm_ss(new Date());
}
public String formatHH_mm_ss(Date date) {
return HH_mm_ss.format(date);
}
public String formatHttp() {
return formatHttp(Util.now());
}
public String formatHttp(long time) {
calendar.setTimeInMillis(time);
calendar.setTimeZone(TZ);
int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int year = calendar.get(Calendar.YEAR);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
StringBuilder b = new StringBuilder(26);
b.append(WEEK_DAYS[weekDay]);
b.append(',');
b.append(' ');
if (day < 10) {
b.append('0');
}
b.append(day);
b.append(' ');
b.append(MONTHS[month]);
b.append(' ');
b.append(year);
b.append(' ');
if (hour < 10) {
b.append('0');
}
b.append(hour);
b.append(':');
if (minute < 10) {
b.append('0');
}
b.append(minute);
b.append(':');
if (second < 10) {
b.append('0');
}
b.append(second);
b.append(" ");
b.append(TZ_NAME);
return b.toString();
}
public byte[] formatHttpBytes() {
byte[] b = new byte[29];
formatHttpBytes(b, 0, Util.now());
return b;
}
public byte[] formatHttpBytes(long time) {
byte[] b = new byte[29];
formatHttpBytes(b, 0, time);
return b;
}
public void formatHttpBytes(byte[] b) {
formatHttpBytes(b, 0, Util.now());
}
//b.len = 29
public void formatHttpBytes(byte[] b, int off, long time) {
calendar.setTimeInMillis(time);
int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int year = calendar.get(Calendar.YEAR);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
byte[] days = WEEK_DAYS_BYTES[weekDay];
byte[] months = MONTHS_BYTES[month];
b[off + 0] = days[0];
b[off + 1] = days[1];
b[off + 2] = days[2];
b[off + 3] = ',';
b[off + 4] = ' ';
b[off + 5] = NS[day / 10];
b[off + 6] = NS[day % 10];
b[off + 7] = ' ';
b[off + 8] = months[0];
b[off + 9] = months[1];
b[off + 10] = months[2];
b[off + 11] = ' ';
b[off + 12] = NS[year / 1000];
b[off + 13] = NS[(year / 100) % 10];
b[off + 14] = NS[(year / 10) % 10];
b[off + 15] = NS[year % 10];
b[off + 16] = ' ';
b[off + 17] = NS[hour / 10];
b[off + 18] = NS[hour % 10];
b[off + 19] = ':';
b[off + 20] = NS[minute / 10];
b[off + 21] = NS[minute % 10];
b[off + 22] = ':';
b[off + 23] = NS[second / 10];
b[off + 24] = NS[second % 10];
b[off + 25] = ' ';
b[off + 26] = TZ_0;
b[off + 27] = TZ_1;
b[off + 28] = TZ_2;
}
public String formatYyMMdd() {
return formatYyMMdd(new Date());
}
public String formatYyMMdd(Date date) {
return yyMMdd.format(date);
}
// --------------------------------------------------------------------------------
public String formatYyyy_MM_dd() {
return formatYyyy_MM_dd(new Date());
}
public String formatYyyy_MM_dd(Date date) {
return yyyy_MM_dd.format(date);
}
public String formatYyyy_MM_dd_HH_mm_ss() {
return formatYyyy_MM_dd_HH_mm_ss(new Date());
}
public String formatYyyy_MM_dd_HH_mm_ss(Date date) {
return yyyy_MM_dd_HH_mm_ss.format(date);
}
public String formatYyyy_MM_dd_HH_mm_ss_SSS() {
return formatYyyy_MM_dd_HH_mm_ss_SSS(new Date());
}
public String formatYyyy_MM_dd_HH_mm_ss_SSS(Date date) {
return yyyy_MM_dd_HH_mm_ss_SSS.format(date);
}
public String formatYyyyMMdd() {
return formatYyyyMMdd(new Date());
}
public String formatYyyyMMdd(Date date) {
return yyyyMMdd.format(date);
}
// --------------------------------------------------------------------------------
public String formatYyyyMMdd_HH_mm_ss() {
return formatYyyyMMdd_HH_mm_ss(new Date());
}
public String formatYyyyMMdd_HH_mm_ss(Date date) {
return yyyyMMdd_HH_mm_ss.format(date);
}
public String formatYyyyMMddHHmmss() {
return formatYyyyMMddHHmmss(new Date());
}
public String formatYyyyMMddHHmmss(Date date) {
return yyyyMMddHHmmss.format(date);
}
private int getMonth(String month, int begin, int end) {
char c1 = month.charAt(begin);
char c2 = month.charAt(begin + 1);
char c3 = month.charAt(begin + 2);
int c = (c1 << 16) | (c2 << 8) | c3;
switch (c) {
case ('J' << 16) | ('a' << 8) | ('n'):
return 0;
case ('F' << 16) | ('e' << 8) | ('b'):
return 1;
case ('M' << 16) | ('a' << 8) | ('r'):
return 2;
case ('A' << 16) | ('p' << 8) | ('r'):
return 3;
case ('M' << 16) | ('a' << 8) | ('y'):
return 4;
case ('J' << 16) | ('u' << 8) | ('n'):
return 5;
case ('J' << 16) | ('u' << 8) | ('l'):
return 6;
case ('A' << 16) | ('u' << 8) | ('g'):
return 7;
case ('S' << 16) | ('e' << 8) | ('p'):
return 8;
case ('O' << 16) | ('c' << 8) | ('t'):
return 9;
case ('N' << 16) | ('o' << 8) | ('v'):
return 10;
case ('D' << 16) | ('e' << 8) | ('v'):
return 11;
default:
return -1;
}
}
public Date parseHH_mm_ss(String source) {
try {
return HH_mm_ss.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public Date parseHttp(String source) {
int day = parseInt(source, 5, 7);
int year = parseInt(source, 12, 16);
int hour = parseInt(source, 17, 19);
int minute = parseInt(source, 20, 22);
int second = parseInt(source, 23, 25);
int month = getMonth(source, 8, 11);
Calendar calendar = Calendar.getInstance(TZ);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
private int parseInt(String cs, int begin, int end) {
int sum = 0;
for (int i = begin; i < end; i++) {
sum = sum * 10 + (cs.charAt(i) - 48);
}
return sum;
}
public Date parseYyMMdd(String source) {
try {
return yyMMdd.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public Date parseYyyy_MM_dd(String source) {
try {
return yyyy_MM_dd.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public Date parseYyyy_MM_dd_HH_mm_ss(String source) {
try {
return yyyy_MM_dd_HH_mm_ss.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public Date parseYyyy_MM_dd_HH_mm_ss_SSS(String source) {
try {
return yyyy_MM_dd_HH_mm_ss_SSS.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public Date parseYyyyMMdd(String source) {
try {
return yyyyMMdd.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public Date parseYyyyMMdd_HH_mm_ss(String source) {
try {
return yyyyMMdd_HH_mm_ss.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public Date parseYyyyMMddHHmmss(String source) {
try {
return yyyyMMddHHmmss.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
| {
"pile_set_name": "Github"
} |
#
# utils.py
#
# Auxiliary functions for the `docmaker' tool (library file).
#
# Copyright 2002, 2004, 2007, 2008, 2014 by
# David Turner.
#
# This file is part of the FreeType project, and may only be used,
# modified, and distributed under the terms of the FreeType project
# license, LICENSE.TXT. By continuing to use, modify, or distribute
# this file you indicate that you have read the license and
# understand and accept it fully.
import string, sys, os, glob, itertools
# current output directory
#
output_dir = None
# A function that generates a sorting key. We want lexicographical order
# (primary key) except that capital letters are sorted before lowercase
# ones (secondary key).
#
# The primary key is implemented by lowercasing the input. The secondary
# key is simply the original data appended, character by character. For
# example, the sort key for `FT_x' is `fFtT__xx', while the sort key for
# `ft_X' is `fftt__xX'. Since ASCII codes of uppercase letters are
# numerically smaller than the codes of lowercase letters, `fFtT__xx' gets
# sorted before `fftt__xX'.
#
def index_key( s ):
return string.join( itertools.chain( *zip( s.lower(), s ) ) )
# Sort `input_list', placing the elements of `order_list' in front.
#
def sort_order_list( input_list, order_list ):
new_list = order_list[:]
for id in input_list:
if not id in order_list:
new_list.append( id )
return new_list
# Divert standard output to a given project documentation file. Use
# `output_dir' to determine the filename location if necessary and save the
# old stdout handle in a tuple that is returned by this function.
#
def open_output( filename ):
global output_dir
if output_dir and output_dir != "":
filename = output_dir + os.sep + filename
old_stdout = sys.stdout
new_file = open( filename, "w" )
sys.stdout = new_file
return ( new_file, old_stdout )
# Close the output that was returned by `open_output'.
#
def close_output( output ):
output[0].close()
sys.stdout = output[1]
# Check output directory.
#
def check_output():
global output_dir
if output_dir:
if output_dir != "":
if not os.path.isdir( output_dir ):
sys.stderr.write( "argument"
+ " '" + output_dir + "' "
+ "is not a valid directory" )
sys.exit( 2 )
else:
output_dir = None
def file_exists( pathname ):
"""Check that a given file exists."""
result = 1
try:
file = open( pathname, "r" )
file.close()
except:
result = None
sys.stderr.write( pathname + " couldn't be accessed\n" )
return result
def make_file_list( args = None ):
"""Build a list of input files from command-line arguments."""
file_list = []
# sys.stderr.write( repr( sys.argv[1 :] ) + '\n' )
if not args:
args = sys.argv[1:]
for pathname in args:
if string.find( pathname, '*' ) >= 0:
newpath = glob.glob( pathname )
newpath.sort() # sort files -- this is important because
# of the order of files
else:
newpath = [pathname]
file_list.extend( newpath )
if len( file_list ) == 0:
file_list = None
else:
# now filter the file list to remove non-existing ones
file_list = filter( file_exists, file_list )
return file_list
# eof
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1997-2003 by The XFree86 Project, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Except as contained in this notice, the name of the copyright holder(s)
* and author(s) shall not be used in advertising or otherwise to promote
* the sale, use or other dealings in this Software without prior written
* authorization from the copyright holder(s) and author(s).
*/
/*
* This file contains declarations for public XFree86 functions and variables,
* and definitions of public macros.
*
* "public" means available to video drivers.
*/
#ifndef _XF86_H
#define _XF86_H
#if HAVE_XORG_CONFIG_H
#include <xorg-config.h>
#elif HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif
#include <pciaccess.h>
#include "xf86str.h"
#include "xf86Opt.h"
#include <X11/Xfuncproto.h>
#include <stdarg.h>
#ifdef RANDR
#include <X11/extensions/randr.h>
#endif
#include "propertyst.h"
/* General parameters */
extern int xf86DoConfigure;
extern Bool xf86DoModalias;
extern Bool xf86DoConfigurePass1;
extern DevPrivateKey xf86ScreenKey;
extern DevPrivateKey xf86CreateRootWindowKey;
extern DevPrivateKey xf86PixmapKey;
extern ScrnInfoPtr *xf86Screens; /* List of pointers to ScrnInfoRecs */
extern const unsigned char byte_reversed[256];
extern ScrnInfoPtr xf86CurrentScreen;
extern Bool pciSlotClaimed;
extern Bool isaSlotClaimed;
extern Bool fbSlotClaimed;
#if defined(__sparc__) || defined(__sparc)
extern Bool sbusSlotClaimed;
#endif
extern confDRIRec xf86ConfigDRI;
extern Bool xf86inSuspend;
extern Bool xf86DRI2Enabled(void);
#define XF86SCRNINFO(p) ((ScrnInfoPtr)dixLookupPrivate(&(p)->devPrivates, \
xf86ScreenKey))
#define XF86FLIP_PIXELS() \
do { \
if (xf86GetFlipPixels()) { \
pScreen->whitePixel = (pScreen->whitePixel) ? 0 : 1; \
pScreen->blackPixel = (pScreen->blackPixel) ? 0 : 1; \
} \
while (0)
#define BOOLTOSTRING(b) ((b) ? "TRUE" : "FALSE")
#define PIX24TOBPP(p) (((p) == Pix24Use24) ? 24 : \
(((p) == Pix24Use32) ? 32 : 0))
/* Function Prototypes */
#ifndef _NO_XF86_PROTOTYPES
/* xf86Bus.c */
Bool xf86CheckPciSlot( const struct pci_device * );
int xf86ClaimPciSlot( struct pci_device *, DriverPtr drvp,
int chipset, GDevPtr dev, Bool active);
Bool xf86ParsePciBusString(const char *busID, int *bus, int *device,
int *func);
Bool xf86ComparePciBusString(const char *busID, int bus, int device, int func);
void xf86FormatPciBusNumber(int busnum, char *buffer);
void xf86PrintResList(int verb, resPtr list);
resPtr xf86AddRangesToList(resPtr list, resRange *pRange, int entityIndex);
int xf86ClaimIsaSlot(DriverPtr drvp, int chipset, GDevPtr dev, Bool active);
int xf86GetIsaInfoForScreen(int scrnIndex);
int xf86GetFbInfoForScreen(int scrnIndex);
Bool xf86ParseIsaBusString(const char *busID);
int xf86ClaimFbSlot(DriverPtr drvp, int chipset, GDevPtr dev, Bool active);
int xf86ClaimNoSlot(DriverPtr drvp, int chipset, GDevPtr dev, Bool active);
void xf86EnableAccess(ScrnInfoPtr pScrn);
void xf86SetCurrentAccess(Bool Enable, ScrnInfoPtr pScrn);
Bool xf86IsPrimaryPci(struct pci_device * pPci);
Bool xf86IsPrimaryIsa(void);
/* new RAC */
resPtr xf86AddResToList(resPtr rlist, resRange *Range, int entityIndex);
resPtr xf86JoinResLists(resPtr rlist1, resPtr rlist2);
resPtr xf86DupResList(const resPtr rlist);
void xf86FreeResList(resPtr rlist);
void xf86ClaimFixedResources(resList list, int entityIndex);
Bool xf86DriverHasEntities(DriverPtr drvp);
void xf86AddEntityToScreen(ScrnInfoPtr pScrn, int entityIndex);
void xf86SetEntityInstanceForScreen(ScrnInfoPtr pScrn, int entityIndex,
int instance);
int xf86GetNumEntityInstances(int entityIndex);
GDevPtr xf86GetDevFromEntity(int entityIndex, int instance);
void xf86RemoveEntityFromScreen(ScrnInfoPtr pScrn, int entityIndex);
EntityInfoPtr xf86GetEntityInfo(int entityIndex);
struct pci_device * xf86GetPciInfoForEntity(int entityIndex);
Bool xf86SetEntityFuncs(int entityIndex, EntityProc init,
EntityProc enter, EntityProc leave, pointer);
void xf86DeallocateResourcesForEntity(int entityIndex, unsigned long type);
resPtr xf86RegisterResources(int entityIndex, resList list,
unsigned long Access);
Bool xf86CheckPciMemBase(struct pci_device * pPci, memType base);
void xf86SetAccessFuncs(EntityInfoPtr pEnt, xf86SetAccessFuncPtr funcs,
xf86SetAccessFuncPtr oldFuncs);
Bool xf86IsEntityPrimary(int entityIndex);
resPtr xf86ReallocatePciResources(int entityIndex, resPtr pRes);
resPtr xf86SetOperatingState(resList list, int entityIndex, int mask);
void xf86EnterServerState(xf86State state);
memType xf86ChkConflict(resRange *rgp, int entityIndex);
ScrnInfoPtr xf86FindScreenForEntity(int entityIndex);
Bool xf86NoSharedResources(int screenIndex, resType res);
resPtr xf86FindIntersectOfLists(resPtr l1, resPtr l2);
void xf86RegisterStateChangeNotificationCallback(xf86StateChangeNotificationCallbackFunc func, pointer arg);
Bool xf86DeregisterStateChangeNotificationCallback(xf86StateChangeNotificationCallbackFunc func);
int xf86GetLastScrnFlag(int entityIndex);
void xf86SetLastScrnFlag(int entityIndex, int scrnIndex);
Bool xf86IsEntityShared(int entityIndex);
void xf86SetEntityShared(int entityIndex);
Bool xf86IsEntitySharable(int entityIndex);
void xf86SetEntitySharable(int entityIndex);
Bool xf86IsPrimInitDone(int entityIndex);
void xf86SetPrimInitDone(int entityIndex);
void xf86ClearPrimInitDone(int entityIndex);
int xf86AllocateEntityPrivateIndex(void);
DevUnion *xf86GetEntityPrivate(int entityIndex, int privIndex);
/* xf86Configure.c */
GDevPtr xf86AddBusDeviceToConfigure(const char *driver, BusType bus,
void *busData, int chipset);
GDevPtr xf86AddDeviceToConfigure( const char *driver,
struct pci_device * pVideo, int chipset );
/* xf86Cursor.c */
void xf86LockZoom(ScreenPtr pScreen, int lock);
void xf86InitViewport(ScrnInfoPtr pScr);
void xf86SetViewport(ScreenPtr pScreen, int x, int y);
void xf86ZoomViewport(ScreenPtr pScreen, int zoom);
Bool xf86SwitchMode(ScreenPtr pScreen, DisplayModePtr mode);
void *xf86GetPointerScreenFuncs(void);
void xf86InitOrigins(void);
void xf86ReconfigureLayout(void);
/* xf86cvt.c */
DisplayModePtr xf86CVTMode(int HDisplay, int VDisplay, float VRefresh,
Bool Reduced, Bool Interlaced);
/* xf86DPMS.c */
Bool xf86DPMSInit(ScreenPtr pScreen, DPMSSetProcPtr set, int flags);
/* xf86DGA.c */
Bool DGAInit(ScreenPtr pScreen, DGAFunctionPtr funcs, DGAModePtr modes,
int num);
Bool DGAReInitModes(ScreenPtr pScreen, DGAModePtr modes, int num);
xf86SetDGAModeProc xf86SetDGAMode;
/* xf86Events.c */
void SetTimeSinceLastInputEvent(void);
pointer xf86AddInputHandler(int fd, InputHandlerProc proc, pointer data);
int xf86RemoveInputHandler(pointer handler);
void xf86DisableInputHandler(pointer handler);
void xf86EnableInputHandler(pointer handler);
pointer xf86AddGeneralHandler(int fd, InputHandlerProc proc, pointer data);
int xf86RemoveGeneralHandler(pointer handler);
void xf86DisableGeneralHandler(pointer handler);
void xf86EnableGeneralHandler(pointer handler);
void xf86InterceptSignals(int *signo);
void xf86InterceptSigIll(void (*sigillhandler)(void));
Bool xf86EnableVTSwitch(Bool new);
Bool xf86CommonSpecialKey(int key, Bool down, int modifiers);
void xf86ProcessActionEvent(ActionEvent action, void *arg);
/* xf86Helper.c */
void xf86AddDriver(DriverPtr driver, pointer module, int flags);
void xf86DeleteDriver(int drvIndex);
ScrnInfoPtr xf86AllocateScreen(DriverPtr drv, int flags);
void xf86DeleteScreen(int scrnIndex, int flags);
int xf86AllocateScrnInfoPrivateIndex(void);
Bool xf86AddPixFormat(ScrnInfoPtr pScrn, int depth, int bpp, int pad);
Bool xf86SetDepthBpp(ScrnInfoPtr scrp, int depth, int bpp, int fbbpp,
int depth24flags);
void xf86PrintDepthBpp(ScrnInfoPtr scrp);
Bool xf86SetWeight(ScrnInfoPtr scrp, rgb weight, rgb mask);
Bool xf86SetDefaultVisual(ScrnInfoPtr scrp, int visual);
Bool xf86SetGamma(ScrnInfoPtr scrp, Gamma newGamma);
void xf86SetDpi(ScrnInfoPtr pScrn, int x, int y);
void xf86SetBlackWhitePixels(ScreenPtr pScreen);
void xf86EnableDisableFBAccess(int scrnIndex, Bool enable);
void xf86VDrvMsgVerb(int scrnIndex, MessageType type, int verb,
const char *format, va_list args);
void xf86DrvMsgVerb(int scrnIndex, MessageType type, int verb,
const char *format, ...) _printf_attribute(4,5);
void xf86DrvMsg(int scrnIndex, MessageType type, const char *format, ...)
_printf_attribute(3,4);
void xf86MsgVerb(MessageType type, int verb, const char *format, ...)
_printf_attribute(3,4);
void xf86Msg(MessageType type, const char *format, ...) _printf_attribute(2,3);
void xf86ErrorFVerb(int verb, const char *format, ...) _printf_attribute(2,3);
void xf86ErrorF(const char *format, ...) _printf_attribute(1,2);
const char *xf86TokenToString(SymTabPtr table, int token);
int xf86StringToToken(SymTabPtr table, const char *string);
void xf86ShowClocks(ScrnInfoPtr scrp, MessageType from);
void xf86PrintChipsets(const char *drvname, const char *drvmsg,
SymTabPtr chips);
int xf86MatchDevice(const char *drivername, GDevPtr **driversectlist);
int xf86MatchPciInstances(const char *driverName, int vendorID,
SymTabPtr chipsets, PciChipsets *PCIchipsets,
GDevPtr *devList, int numDevs, DriverPtr drvp,
int **foundEntities);
int xf86MatchIsaInstances(const char *driverName, SymTabPtr chipsets,
IsaChipsets *ISAchipsets, DriverPtr drvp,
FindIsaDevProc FindIsaDevice, GDevPtr *devList,
int numDevs, int **foundEntities);
void xf86GetClocks(ScrnInfoPtr pScrn, int num,
Bool (*ClockFunc)(ScrnInfoPtr, int),
void (*ProtectRegs)(ScrnInfoPtr, Bool),
void (*BlankScreen)(ScrnInfoPtr, Bool),
IOADDRESS vertsyncreg, int maskval,
int knownclkindex, int knownclkvalue);
void xf86SetPriority(Bool up);
const char *xf86GetVisualName(int visual);
int xf86GetVerbosity(void);
Pix24Flags xf86GetPix24(void);
int xf86GetDepth(void);
rgb xf86GetWeight(void);
Gamma xf86GetGamma(void);
Bool xf86GetFlipPixels(void);
const char *xf86GetServerName(void);
Bool xf86ServerIsExiting(void);
Bool xf86ServerIsResetting(void);
Bool xf86ServerIsInitialising(void);
Bool xf86ServerIsOnlyDetecting(void);
Bool xf86ServerIsOnlyProbing(void);
Bool xf86CaughtSignal(void);
Bool xf86GetVidModeAllowNonLocal(void);
Bool xf86GetVidModeEnabled(void);
Bool xf86GetModInDevAllowNonLocal(void);
Bool xf86GetModInDevEnabled(void);
Bool xf86GetAllowMouseOpenFail(void);
Bool xf86IsPc98(void);
void xf86DisableRandR(void);
CARD32 xf86GetVersion(void);
CARD32 xorgGetVersion(void);
CARD32 xf86GetModuleVersion(pointer module);
pointer xf86LoadDrvSubModule(DriverPtr drv, const char *name);
pointer xf86LoadSubModule(ScrnInfoPtr pScrn, const char *name);
pointer xf86LoadOneModule(char *name, pointer optlist);
void xf86UnloadSubModule(pointer mod);
Bool xf86LoaderCheckSymbol(const char *name);
void xf86LoaderReqSymLists(const char **, ...);
void xf86LoaderReqSymbols(const char *, ...);
void xf86LoaderRefSymLists(const char **, ...);
void xf86LoaderRefSymbols(const char *, ...);
void xf86SetBackingStore(ScreenPtr pScreen);
void xf86SetSilkenMouse(ScreenPtr pScreen);
int xf86NewSerialNumber(WindowPtr p, pointer unused);
pointer xf86FindXvOptions(int scrnIndex, int adapt_index, char *port_name,
char **adaptor_name, pointer *adaptor_options);
void xf86GetOS(const char **name, int *major, int *minor, int *teeny);
ScrnInfoPtr xf86ConfigPciEntity(ScrnInfoPtr pScrn, int scrnFlag,
int entityIndex,PciChipsets *p_chip,
resList res, EntityProc init,
EntityProc enter, EntityProc leave,
pointer private);
ScrnInfoPtr xf86ConfigIsaEntity(ScrnInfoPtr pScrn, int scrnFlag,
int entityIndex, IsaChipsets *i_chip,
resList res, EntityProc init,
EntityProc enter, EntityProc leave,
pointer private);
ScrnInfoPtr xf86ConfigFbEntity(ScrnInfoPtr pScrn, int scrnFlag,
int entityIndex, EntityProc init,
EntityProc enter, EntityProc leave,
pointer private);
/* Obsolete! don't use */
Bool xf86ConfigActivePciEntity(ScrnInfoPtr pScrn,
int entityIndex,PciChipsets *p_chip,
resList res, EntityProc init,
EntityProc enter, EntityProc leave,
pointer private);
/* Obsolete! don't use */
Bool xf86ConfigActiveIsaEntity(ScrnInfoPtr pScrn,
int entityIndex, IsaChipsets *i_chip,
resList res, EntityProc init,
EntityProc enter, EntityProc leave,
pointer private);
void xf86ConfigPciEntityInactive(EntityInfoPtr pEnt, PciChipsets *p_chip,
resList res, EntityProc init,
EntityProc enter, EntityProc leave,
pointer private);
void xf86ConfigIsaEntityInactive(EntityInfoPtr pEnt, IsaChipsets *i_chip,
resList res, EntityProc init,
EntityProc enter, EntityProc leave,
pointer private);
void xf86ConfigFbEntityInactive(EntityInfoPtr pEnt, EntityProc init,
EntityProc enter, EntityProc leave,
pointer private);
Bool xf86IsScreenPrimary(int scrnIndex);
int xf86RegisterRootWindowProperty(int ScrnIndex, Atom property, Atom type,
int format, unsigned long len,
pointer value);
Bool xf86IsUnblank(int mode);
_X_DEPRECATED void xf86AddModuleInfo(pointer info, pointer module);
_X_DEPRECATED void xf86DeleteModuleInfo(int idx);
void xf86getsecs(long *, long *);
/* xf86Debug.c */
#ifdef BUILDDEBUG
CARD8 xf86PeekFb8(CARD8 *p);
CARD16 xf86PeekFb16(CARD16 *p);
CARD32 xf86PeekFb32(CARD32 *p);
void xf86PokeFb8(CARD8 *p, CARD8 v);
void xf86PokeFb16(CARD16 *p, CARD16 v);
void xf86PokeFb32(CARD16 *p, CARD32 v);
CARD8 xf86PeekMmio8(pointer Base, unsigned long Offset);
CARD16 xf86PeekMmio16(pointer Base, unsigned long Offset);
CARD32 xf86PeekMmio32(pointer Base, unsigned long Offset);
void xf86PokeMmio8(pointer Base, unsigned long Offset, CARD8 v);
void xf86PokeMmio16(pointer Base, unsigned long Offset, CARD16 v);
void xf86PokeMmio32(pointer Base, unsigned long Offset, CARD32 v);
#endif
/* xf86Init.c */
PixmapFormatPtr xf86GetPixFormat(ScrnInfoPtr pScrn, int depth);
int xf86GetBppFromDepth(ScrnInfoPtr pScrn, int depth);
/* xf86Mode.c */
int xf86GetNearestClock(ScrnInfoPtr scrp, int freq, Bool allowDiv2,
int DivFactor, int MulFactor, int *divider);
const char *xf86ModeStatusToString(ModeStatus status);
ModeStatus xf86LookupMode(ScrnInfoPtr scrp, DisplayModePtr modep,
ClockRangePtr clockRanges, LookupModeFlags strategy);
ModeStatus xf86CheckModeForMonitor(DisplayModePtr mode, MonPtr monitor);
ModeStatus xf86InitialCheckModeForDriver(ScrnInfoPtr scrp, DisplayModePtr mode,
ClockRangePtr clockRanges,
LookupModeFlags strategy,
int maxPitch, int virtualX,
int virtualY);
ModeStatus xf86CheckModeForDriver(ScrnInfoPtr scrp, DisplayModePtr mode,
int flags);
int xf86ValidateModes(ScrnInfoPtr scrp, DisplayModePtr availModes,
char **modeNames, ClockRangePtr clockRanges,
int *linePitches, int minPitch, int maxPitch,
int minHeight, int maxHeight, int pitchInc,
int virtualX, int virtualY, int apertureSize,
LookupModeFlags strategy);
void xf86DeleteMode(DisplayModePtr *modeList, DisplayModePtr mode);
void xf86PruneDriverModes(ScrnInfoPtr scrp);
void xf86SetCrtcForModes(ScrnInfoPtr scrp, int adjustFlags);
void xf86PrintModes(ScrnInfoPtr scrp);
void xf86ShowClockRanges(ScrnInfoPtr scrp, ClockRangePtr clockRanges);
double xf86ModeHSync(DisplayModePtr mode);
double xf86ModeVRefresh(DisplayModePtr mode);
void xf86SetModeDefaultName(DisplayModePtr mode);
void xf86SetModeCrtc(DisplayModePtr p, int adjustFlags);
DisplayModePtr xf86DuplicateMode(DisplayModePtr pMode);
DisplayModePtr xf86DuplicateModes(ScrnInfoPtr pScrn, DisplayModePtr modeList);
Bool xf86ModesEqual(DisplayModePtr pMode1, DisplayModePtr pMode2);
void xf86PrintModeline(int scrnIndex,DisplayModePtr mode);
DisplayModePtr xf86ModesAdd(DisplayModePtr modes, DisplayModePtr new);
/* xf86Option.c */
void xf86CollectOptions(ScrnInfoPtr pScrn, pointer extraOpts);
/* xf86RandR.c */
#ifdef RANDR
Bool xf86RandRInit (ScreenPtr pScreen);
void xf86RandRSetInitialMode (ScreenPtr pScreen);
Rotation xf86GetRotation(ScreenPtr pScreen);
Bool xf86RandRSetNewVirtualAndDimensions(ScreenPtr pScreen,
int newvirtX, int newvirtY,
int newmmWidth, int newmmHeight, Bool resetMode);
#endif
/* xf86VidModeExtentionInit.c */
Bool VidModeExtensionInit(ScreenPtr pScreen);
/* xf86Versions.c */
CARD32 xf86GetBuiltinInterfaceVersion(BuiltinInterface iface, int flag);
Bool xf86RegisterBuiltinInterfaceVersion(BuiltinInterface iface,
CARD32 version, int flags);
#endif /* _NO_XF86_PROTOTYPES */
#endif /* _XF86_H */
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The Go 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 bpf implements marshaling and unmarshaling of programs for the
Berkeley Packet Filter virtual machine, and provides a Go implementation
of the virtual machine.
BPF's main use is to specify a packet filter for network taps, so that
the kernel doesn't have to expensively copy every packet it sees to
userspace. However, it's been repurposed to other areas where running
user code in-kernel is needed. For example, Linux's seccomp uses BPF
to apply security policies to system calls. For simplicity, this
documentation refers only to packets, but other uses of BPF have their
own data payloads.
BPF programs run in a restricted virtual machine. It has almost no
access to kernel functions, and while conditional branches are
allowed, they can only jump forwards, to guarantee that there are no
infinite loops.
The virtual machine
The BPF VM is an accumulator machine. Its main register, called
register A, is an implicit source and destination in all arithmetic
and logic operations. The machine also has 16 scratch registers for
temporary storage, and an indirection register (register X) for
indirect memory access. All registers are 32 bits wide.
Each run of a BPF program is given one packet, which is placed in the
VM's read-only "main memory". LoadAbsolute and LoadIndirect
instructions can fetch up to 32 bits at a time into register A for
examination.
The goal of a BPF program is to produce and return a verdict (uint32),
which tells the kernel what to do with the packet. In the context of
packet filtering, the returned value is the number of bytes of the
packet to forward to userspace, or 0 to ignore the packet. Other
contexts like seccomp define their own return values.
In order to simplify programs, attempts to read past the end of the
packet terminate the program execution with a verdict of 0 (ignore
packet). This means that the vast majority of BPF programs don't need
to do any explicit bounds checking.
In addition to the bytes of the packet, some BPF programs have access
to extensions, which are essentially calls to kernel utility
functions. Currently, the only extensions supported by this package
are the Linux packet filter extensions.
Examples
This packet filter selects all ARP packets.
bpf.Assemble([]bpf.Instruction{
// Load "EtherType" field from the ethernet header.
bpf.LoadAbsolute{Off: 12, Size: 2},
// Skip over the next instruction if EtherType is not ARP.
bpf.JumpIf{Cond: bpf.JumpNotEqual, Val: 0x0806, SkipTrue: 1},
// Verdict is "send up to 4k of the packet to userspace."
bpf.RetConstant{Val: 4096},
// Verdict is "ignore packet."
bpf.RetConstant{Val: 0},
})
This packet filter captures a random 1% sample of traffic.
bpf.Assemble([]bpf.Instruction{
// Get a 32-bit random number from the Linux kernel.
bpf.LoadExtension{Num: bpf.ExtRand},
// 1% dice roll?
bpf.JumpIf{Cond: bpf.JumpLessThan, Val: 2^32/100, SkipFalse: 1},
// Capture.
bpf.RetConstant{Val: 4096},
// Ignore.
bpf.RetConstant{Val: 0},
})
*/
package bpf // import "golang.org/x/net/bpf"
| {
"pile_set_name": "Github"
} |
package com.alibaba.excel.analysis.v03.handlers;
import org.apache.poi.hssf.record.NoteRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.metadata.CellExtra;
/**
* Record handler
*
* @author Dan Zheng
*/
public class NoteRecordHandler extends AbstractXlsRecordHandler implements IgnorableXlsRecordHandler {
@Override
public boolean support(XlsReadContext xlsReadContext, Record record) {
return xlsReadContext.readWorkbookHolder().getExtraReadSet().contains(CellExtraTypeEnum.COMMENT);
}
@Override
public void processRecord(XlsReadContext xlsReadContext, Record record) {
NoteRecord nr = (NoteRecord)record;
String text = xlsReadContext.xlsReadSheetHolder().getObjectCacheMap().get(nr.getShapeId());
CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.COMMENT, text, nr.getRow(), nr.getColumn());
xlsReadContext.xlsReadSheetHolder().setCellExtra(cellExtra);
xlsReadContext.analysisEventProcessor().extra(xlsReadContext);
}
}
| {
"pile_set_name": "Github"
} |
/*!
* jQuery UI Progressbar 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/progressbar/#theming
*/
.ui-progressbar {
height: 2em;
text-align: left;
overflow: hidden;
}
.ui-progressbar .ui-progressbar-value {
margin: -1px;
height: 100%;
}
.ui-progressbar .ui-progressbar-overlay {
background: url("data:image/gif;base64,R0lGODlhKAAoAIABAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJAQABACwAAAAAKAAoAAACkYwNqXrdC52DS06a7MFZI+4FHBCKoDeWKXqymPqGqxvJrXZbMx7Ttc+w9XgU2FB3lOyQRWET2IFGiU9m1frDVpxZZc6bfHwv4c1YXP6k1Vdy292Fb6UkuvFtXpvWSzA+HycXJHUXiGYIiMg2R6W459gnWGfHNdjIqDWVqemH2ekpObkpOlppWUqZiqr6edqqWQAAIfkECQEAAQAsAAAAACgAKAAAApSMgZnGfaqcg1E2uuzDmmHUBR8Qil95hiPKqWn3aqtLsS18y7G1SzNeowWBENtQd+T1JktP05nzPTdJZlR6vUxNWWjV+vUWhWNkWFwxl9VpZRedYcflIOLafaa28XdsH/ynlcc1uPVDZxQIR0K25+cICCmoqCe5mGhZOfeYSUh5yJcJyrkZWWpaR8doJ2o4NYq62lAAACH5BAkBAAEALAAAAAAoACgAAAKVDI4Yy22ZnINRNqosw0Bv7i1gyHUkFj7oSaWlu3ovC8GxNso5fluz3qLVhBVeT/Lz7ZTHyxL5dDalQWPVOsQWtRnuwXaFTj9jVVh8pma9JjZ4zYSj5ZOyma7uuolffh+IR5aW97cHuBUXKGKXlKjn+DiHWMcYJah4N0lYCMlJOXipGRr5qdgoSTrqWSq6WFl2ypoaUAAAIfkECQEAAQAsAAAAACgAKAAAApaEb6HLgd/iO7FNWtcFWe+ufODGjRfoiJ2akShbueb0wtI50zm02pbvwfWEMWBQ1zKGlLIhskiEPm9R6vRXxV4ZzWT2yHOGpWMyorblKlNp8HmHEb/lCXjcW7bmtXP8Xt229OVWR1fod2eWqNfHuMjXCPkIGNileOiImVmCOEmoSfn3yXlJWmoHGhqp6ilYuWYpmTqKUgAAIfkECQEAAQAsAAAAACgAKAAAApiEH6kb58biQ3FNWtMFWW3eNVcojuFGfqnZqSebuS06w5V80/X02pKe8zFwP6EFWOT1lDFk8rGERh1TTNOocQ61Hm4Xm2VexUHpzjymViHrFbiELsefVrn6XKfnt2Q9G/+Xdie499XHd2g4h7ioOGhXGJboGAnXSBnoBwKYyfioubZJ2Hn0RuRZaflZOil56Zp6iioKSXpUAAAh+QQJAQABACwAAAAAKAAoAAACkoQRqRvnxuI7kU1a1UU5bd5tnSeOZXhmn5lWK3qNTWvRdQxP8qvaC+/yaYQzXO7BMvaUEmJRd3TsiMAgswmNYrSgZdYrTX6tSHGZO73ezuAw2uxuQ+BbeZfMxsexY35+/Qe4J1inV0g4x3WHuMhIl2jXOKT2Q+VU5fgoSUI52VfZyfkJGkha6jmY+aaYdirq+lQAACH5BAkBAAEALAAAAAAoACgAAAKWBIKpYe0L3YNKToqswUlvznigd4wiR4KhZrKt9Upqip61i9E3vMvxRdHlbEFiEXfk9YARYxOZZD6VQ2pUunBmtRXo1Lf8hMVVcNl8JafV38aM2/Fu5V16Bn63r6xt97j09+MXSFi4BniGFae3hzbH9+hYBzkpuUh5aZmHuanZOZgIuvbGiNeomCnaxxap2upaCZsq+1kAACH5BAkBAAEALAAAAAAoACgAAAKXjI8By5zf4kOxTVrXNVlv1X0d8IGZGKLnNpYtm8Lr9cqVeuOSvfOW79D9aDHizNhDJidFZhNydEahOaDH6nomtJjp1tutKoNWkvA6JqfRVLHU/QUfau9l2x7G54d1fl995xcIGAdXqMfBNadoYrhH+Mg2KBlpVpbluCiXmMnZ2Sh4GBqJ+ckIOqqJ6LmKSllZmsoq6wpQAAAh+QQJAQABACwAAAAAKAAoAAAClYx/oLvoxuJDkU1a1YUZbJ59nSd2ZXhWqbRa2/gF8Gu2DY3iqs7yrq+xBYEkYvFSM8aSSObE+ZgRl1BHFZNr7pRCavZ5BW2142hY3AN/zWtsmf12p9XxxFl2lpLn1rseztfXZjdIWIf2s5dItwjYKBgo9yg5pHgzJXTEeGlZuenpyPmpGQoKOWkYmSpaSnqKileI2FAAACH5BAkBAAEALAAAAAAoACgAAAKVjB+gu+jG4kORTVrVhRlsnn2dJ3ZleFaptFrb+CXmO9OozeL5VfP99HvAWhpiUdcwkpBH3825AwYdU8xTqlLGhtCosArKMpvfa1mMRae9VvWZfeB2XfPkeLmm18lUcBj+p5dnN8jXZ3YIGEhYuOUn45aoCDkp16hl5IjYJvjWKcnoGQpqyPlpOhr3aElaqrq56Bq7VAAAOw==");
height: 100%;
filter: alpha(opacity=25); /* support: IE8 */
opacity: 0.25;
}
.ui-progressbar-indeterminate .ui-progressbar-value {
background-image: none;
}
| {
"pile_set_name": "Github"
} |
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 80);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports) {
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file.
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
module.exports = function normalizeComponent (
rawScriptExports,
compiledTemplate,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier /* server only */
) {
var esModule
var scriptExports = rawScriptExports = rawScriptExports || {}
// ES6 modules interop
var type = typeof rawScriptExports.default
if (type === 'object' || type === 'function') {
esModule = rawScriptExports
scriptExports = rawScriptExports.default
}
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (compiledTemplate) {
options.render = compiledTemplate.render
options.staticRenderFns = compiledTemplate.staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = injectStyles
}
if (hook) {
var functional = options.functional
var existing = functional
? options.render
: options.beforeCreate
if (!functional) {
// inject component registration as beforeCreate hook
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
} else {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functioal component in vue file
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return existing(h, context)
}
}
}
return {
esModule: esModule,
exports: scriptExports,
options: options
}
}
/***/ }),
/***/ 1:
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/mixins/emitter");
/***/ }),
/***/ 80:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _dropdownItem = __webpack_require__(81);
var _dropdownItem2 = _interopRequireDefault(_dropdownItem);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* istanbul ignore next */
_dropdownItem2.default.install = function (Vue) {
Vue.component(_dropdownItem2.default.name, _dropdownItem2.default);
};
exports.default = _dropdownItem2.default;
/***/ }),
/***/ 81:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_dropdown_item_vue__ = __webpack_require__(82);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_dropdown_item_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_dropdown_item_vue__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_a3065bd2_hasScoped_false_preserveWhitespace_false_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_dropdown_item_vue__ = __webpack_require__(83);
var normalizeComponent = __webpack_require__(0)
/* script */
/* template */
/* template functional */
var __vue_template_functional__ = false
/* styles */
var __vue_styles__ = null
/* scopeId */
var __vue_scopeId__ = null
/* moduleIdentifier (server only) */
var __vue_module_identifier__ = null
var Component = normalizeComponent(
__WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_dropdown_item_vue___default.a,
__WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_a3065bd2_hasScoped_false_preserveWhitespace_false_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_dropdown_item_vue__["a" /* default */],
__vue_template_functional__,
__vue_styles__,
__vue_scopeId__,
__vue_module_identifier__
)
/* harmony default export */ __webpack_exports__["default"] = (Component.exports);
/***/ }),
/***/ 82:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _emitter = __webpack_require__(1);
var _emitter2 = _interopRequireDefault(_emitter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
name: 'ElDropdownItem',
mixins: [_emitter2.default],
props: {
command: {},
disabled: Boolean,
divided: Boolean
},
methods: {
handleClick: function handleClick(e) {
this.dispatch('ElDropdown', 'menu-item-click', [this.command, this]);
}
}
}; //
//
//
//
//
//
//
//
//
//
//
//
//
//
/***/ }),
/***/ 83:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('li',{staticClass:"el-dropdown-menu__item",class:{
'is-disabled': _vm.disabled,
'el-dropdown-menu__item--divided': _vm.divided
},attrs:{"aria-disabled":_vm.disabled,"tabindex":_vm.disabled ? null : -1},on:{"click":_vm.handleClick}},[_vm._t("default")],2)}
var staticRenderFns = []
var esExports = { render: render, staticRenderFns: staticRenderFns }
/* harmony default export */ __webpack_exports__["a"] = (esExports);
/***/ })
/******/ }); | {
"pile_set_name": "Github"
} |
//
// Dropdown menus
// --------------------------------------------------
// Dropdown arrow/caret
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: @caret-width-base solid;
border-right: @caret-width-base solid transparent;
border-left: @caret-width-base solid transparent;
}
// The dropdown wrapper (div)
.dropdown {
position: relative;
}
// Prevent the focus on the dropdown toggle when closing dropdowns
.dropdown-toggle:focus {
outline: 0;
}
// The dropdown menu (ul)
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: @zindex-dropdown;
display: none; // none by default, but block on "open" of the menu
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0; // override default ul
list-style: none;
font-size: @font-size-base;
text-align: left; // Ensures proper alignment if parent has it changed (e.g., modal footer)
background-color: @dropdown-bg;
border: 1px solid @dropdown-fallback-border; // IE8 fallback
border: 1px solid @dropdown-border;
border-radius: @border-radius-base;
.box-shadow(0 6px 12px rgba(0,0,0,.175));
background-clip: padding-box;
// Aligns the dropdown menu to right
//
// Deprecated as of 3.1.0 in favor of `.dropdown-menu-[dir]`
&.pull-right {
right: 0;
left: auto;
}
// Dividers (basically an hr) within the dropdown
.divider {
.nav-divider(@dropdown-divider-bg);
}
// Links within the dropdown menu
> li > a {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: @line-height-base;
color: @dropdown-link-color;
white-space: nowrap; // prevent links from randomly breaking onto new lines
}
}
// Hover/Focus state
.dropdown-menu > li > a {
&:hover,
&:focus {
text-decoration: none;
color: @dropdown-link-hover-color;
background-color: @dropdown-link-hover-bg;
}
}
// Active state
.dropdown-menu > .active > a {
&,
&:hover,
&:focus {
color: @dropdown-link-active-color;
text-decoration: none;
outline: 0;
background-color: @dropdown-link-active-bg;
}
}
// Disabled state
//
// Gray out text and ensure the hover/focus state remains gray
.dropdown-menu > .disabled > a {
&,
&:hover,
&:focus {
color: @dropdown-link-disabled-color;
}
// Nuke hover/focus effects
&:hover,
&:focus {
text-decoration: none;
background-color: transparent;
background-image: none; // Remove CSS gradient
.reset-filter();
cursor: @cursor-disabled;
}
}
// Open state for the dropdown
.open {
// Show the menu
> .dropdown-menu {
display: block;
}
// Remove the outline when :focus is triggered
> a {
outline: 0;
}
}
// Menu positioning
//
// Add extra class to `.dropdown-menu` to flip the alignment of the dropdown
// menu with the parent.
.dropdown-menu-right {
left: auto; // Reset the default from `.dropdown-menu`
right: 0;
}
// With v3, we enabled auto-flipping if you have a dropdown within a right
// aligned nav component. To enable the undoing of that, we provide an override
// to restore the default dropdown menu alignment.
//
// This is only for left-aligning a dropdown menu within a `.navbar-right` or
// `.pull-right` nav component.
.dropdown-menu-left {
left: 0;
right: auto;
}
// Dropdown section headers
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: @font-size-small;
line-height: @line-height-base;
color: @dropdown-header-color;
white-space: nowrap; // as with > li > a
}
// Backdrop to catch body clicks on mobile, etc.
.dropdown-backdrop {
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
z-index: (@zindex-dropdown - 10);
}
// Right aligned dropdowns
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
// Allow for dropdowns to go bottom up (aka, dropup-menu)
//
// Just add .dropup after the standard .dropdown class and you're set, bro.
// TODO: abstract this so that the navbar fixed styles are not placed here?
.dropup,
.navbar-fixed-bottom .dropdown {
// Reverse the caret
.caret {
border-top: 0;
border-bottom: @caret-width-base solid;
content: "";
}
// Different positioning for bottom up menu
.dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 1px;
}
}
// Component alignment
//
// Reiterate per navbar.less and the modified component alignment there.
@media (min-width: @grid-float-breakpoint) {
.navbar-right {
.dropdown-menu {
.dropdown-menu-right();
}
// Necessary for overrides of the default right aligned menu.
// Will remove come v4 in all likelihood.
.dropdown-menu-left {
.dropdown-menu-left();
}
}
}
| {
"pile_set_name": "Github"
} |
{
"fluentMethods": true,
"relationships": [
{
"relationshipName": "user",
"otherEntityName": "user",
"relationshipType": "one-to-one",
"otherEntityField": "login",
"ownerSide": true,
"otherEntityRelationshipName": "preferences"
}
],
"fields": [
{
"fieldName": "weeklyGoal",
"fieldType": "Integer",
"fieldValidateRules": [
"required",
"min",
"max"
],
"fieldValidateRulesMin": "10",
"fieldValidateRulesMax": "21"
},
{
"fieldName": "weightUnits",
"fieldType": "Units",
"fieldValues": "kg,lb",
"fieldValidateRules": [
"required"
]
}
],
"changelogDate": "20170725033721",
"dto": "no",
"service": "no",
"entityTableName": "preferences",
"pagination": "no"
}
| {
"pile_set_name": "Github"
} |
:- dynamic query/5.
:- import query/5 from usermod.
:- import str_cat/3 from machine.
:- import numbervars/1 from num_vars.
:- import member/2 from basics.
?- load_dyn('wfsexs.P').
gen(P) :-
telling(X), str_cat(P, '.P', File), tell(File), gen1(P), told, tell(X).
gen1(P) :-
query(P, Q, Subgoals, Trues, Undefineds),
write_query(query(P, Q, Subgoals, Trues, Undefineds)),
write_table_decls(Subgoals), write_clauses(P),
fail.
gen1(_).
write_query(Query) :-
write(Query), writeln('.'),
writeln('%-----------------------------------------------------------'),
nl, fail. % undo numbervars.
write_query(_).
write_table_decls(Subgoals) :-
findall(P/A, (member(S, Subgoals), functor(S, P, A)), PredList),
sort(PredList, PredSet), member(Pred, PredSet),
write(':- table '), write(Pred), writeln('.'), fail.
write_table_decls(_) :- nl.
write_clauses(P) :-
pgm(P, Rule), numbervars(Rule),
Rule = rule(Head, BodyLiterals),
write(Head), write_body(BodyLiterals), writeln('.'),
fail.
write_clauses(_).
write_body([]).
write_body([L|Ls]) :-
write(' :- '), write_literal(L), write_body1(Ls).
write_body1([]).
write_body1([L|Ls]) :-
write(', '), write_literal(L), write_body1(Ls).
write_literal(L) :-
( L = (\+ A) -> write(tnot(A)) ; write(L) ).
| {
"pile_set_name": "Github"
} |
<HTML>
<HEAD>
<META NAME="GENERATOR" CONTENT="Adobe PageMill 2.0 Mac">
<TITLE>Credits</TITLE>
</HEAD>
<BODY>
<H1>Java L&F Credits</H1>
<P>The Java L&F Engineering team:</P>
<UL>
<LI>Mike Albers
<LI>Tom Santos
<LI>Jeff Shapiro
<LI>Steve Wilson
</UL>
<P>Management: </P>
<UL>
<LI>Harry Vertelney
</UL>
<P>The Java L&F Designer:</P>
<UL>
<LI>Chris Ryan
</UL>
<P><A HREF="toc.html"><IMG alt="Back" SRC="back.gif" WIDTH="42" HEIGHT="22" ALIGN="BOTTOM" BORDER="0">Back</A>
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/securityhub/SecurityHub_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/securityhub/model/StandardsSubscription.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace SecurityHub
{
namespace Model
{
class AWS_SECURITYHUB_API BatchDisableStandardsResult
{
public:
BatchDisableStandardsResult();
BatchDisableStandardsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
BatchDisableStandardsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The details of the standards subscriptions that were disabled.</p>
*/
inline const Aws::Vector<StandardsSubscription>& GetStandardsSubscriptions() const{ return m_standardsSubscriptions; }
/**
* <p>The details of the standards subscriptions that were disabled.</p>
*/
inline void SetStandardsSubscriptions(const Aws::Vector<StandardsSubscription>& value) { m_standardsSubscriptions = value; }
/**
* <p>The details of the standards subscriptions that were disabled.</p>
*/
inline void SetStandardsSubscriptions(Aws::Vector<StandardsSubscription>&& value) { m_standardsSubscriptions = std::move(value); }
/**
* <p>The details of the standards subscriptions that were disabled.</p>
*/
inline BatchDisableStandardsResult& WithStandardsSubscriptions(const Aws::Vector<StandardsSubscription>& value) { SetStandardsSubscriptions(value); return *this;}
/**
* <p>The details of the standards subscriptions that were disabled.</p>
*/
inline BatchDisableStandardsResult& WithStandardsSubscriptions(Aws::Vector<StandardsSubscription>&& value) { SetStandardsSubscriptions(std::move(value)); return *this;}
/**
* <p>The details of the standards subscriptions that were disabled.</p>
*/
inline BatchDisableStandardsResult& AddStandardsSubscriptions(const StandardsSubscription& value) { m_standardsSubscriptions.push_back(value); return *this; }
/**
* <p>The details of the standards subscriptions that were disabled.</p>
*/
inline BatchDisableStandardsResult& AddStandardsSubscriptions(StandardsSubscription&& value) { m_standardsSubscriptions.push_back(std::move(value)); return *this; }
private:
Aws::Vector<StandardsSubscription> m_standardsSubscriptions;
};
} // namespace Model
} // namespace SecurityHub
} // namespace Aws
| {
"pile_set_name": "Github"
} |
<?php
/**
* Functions to transmit a CCD as a Direct Protocol Message
*
* Copyright (C) 2013 EMR Direct <http://www.emrdirect.com/>
*
* Use of these functions requires an active phiMail Direct messaging
* account with EMR Direct. For information regarding this service,
* please visit http://www.emrdirect.com or email [email protected]
*
* LICENSE: This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
*
* @package OpenEMR
* @author EMR Direct <http://www.emrdirect.com/>
* @link http://www.open-emr.org
*/
require_once(dirname(__FILE__) . "/../library/patient.inc");
require_once(dirname(__FILE__) . "/../library/direct_message_check.inc");
use OpenEMR\Common\Crypto\CryptoGen;
use OpenEMR\Common\Logging\EventAuditLogger;
/*
* Connect to a phiMail Direct Messaging server and transmit
* a CCD document to the specified recipient. If the message is accepted by the
* server, the script will return "SUCCESS", otherwise it will return an error msg.
* @param DOMDocument ccd the xml data to transmit, a CCDA document is assumed
* @param string recipient the Direct Address of the recipient
* @param string requested_by user | patient
* @return string result of operation
*/
function transmitCCD($ccd, $recipient, $requested_by, $xml_type = "CCD")
{
global $pid;
//get patient name in Last_First format (used for CCDA filename) and
//First Last for the message text.
$patientData = getPatientPID(array("pid" => $pid));
if (empty($patientData[0]['lname'])) {
$att_filename = "";
$patientName2 = "";
} else {
//spaces are the argument delimiter for the phiMail API calls and must be removed
$att_filename = " " .
str_replace(" ", "_", $xml_type . "_" . $patientData[0]['lname']
. "_" . $patientData[0]['fname']) . ".xml";
$patientName2 = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
}
$config_err = xl("Direct messaging is currently unavailable.") . " EC:";
if ($GLOBALS['phimail_enable'] == false) {
return("$config_err 1");
}
$fp = phimail_connect($err);
if ($fp === false) {
return("$config_err $err");
}
$phimail_username = $GLOBALS['phimail_username'];
$cryptoGen = new CryptoGen();
$phimail_password = $cryptoGen->decryptStandard($GLOBALS['phimail_password']);
$ret = phimail_write_expect_OK($fp, "AUTH $phimail_username $phimail_password\n");
if ($ret !== true) {
return("$config_err 4");
}
$ret = phimail_write_expect_OK($fp, "TO $recipient\n");
if ($ret !== true) {
return( xl("Delivery is not allowed to the specified Direct Address.") );
}
$ret = fgets($fp, 1024); //ignore extra server data
if ($requested_by == "patient") {
$text_out = xl("Delivery of the attached clinical document was requested by the patient") .
($patientName2 == "" ? "." : ", " . $patientName2 . ".");
} else {
$text_out = xl("A clinical document is attached") .
($patientName2 == "" ? "." : " " . xl("for patient") . " " . $patientName2 . ".");
}
$text_len = strlen($text_out);
phimail_write($fp, "TEXT $text_len\n");
$ret = @fgets($fp, 256);
if ($ret != "BEGIN\n") {
phimail_close($fp);
return("$config_err 5");
}
$ret = phimail_write_expect_OK($fp, $text_out);
if ($ret !== true) {
return("$config_err 6");
}
$ccd_out = $ccd->saveXml();
$ccd_len = strlen($ccd_out);
phimail_write($fp, "ADD " . ($xml_type == "CCR" ? "CCR " : "CDA ") . $ccd_len . $att_filename . "\n");
$ret = fgets($fp, 256);
if ($ret != "BEGIN\n") {
phimail_close($fp);
return("$config_err 7");
}
$ret = phimail_write_expect_OK($fp, $ccd_out);
if ($ret !== true) {
return("$config_err 8");
}
phimail_write($fp, "SEND\n");
$ret = fgets($fp, 256);
phimail_close($fp);
if ($requested_by == "patient") {
$reqBy = "portal-user";
$sql = "SELECT id FROM users WHERE username='portal-user'";
if (
($r = sqlStatementNoLog($sql)) === false ||
($u = sqlFetchArray($r)) === false
) {
$reqID = 1; //default if we don't have a service user
} else {
$reqID = $u['id'];
}
} else {
$reqBy = $_SESSION['authUser'];
$reqID = $_SESSION['authUserID'];
}
if (substr($ret, 5) == "ERROR") {
//log the failure
EventAuditLogger::instance()->newEvent("transmit-ccd", $reqBy, $_SESSION['authProvider'], 0, $ret, $pid);
return( xl("The message could not be sent at this time."));
}
/**
* If we get here, the message was successfully sent and the return
* value $ret is of the form "QUEUED recipient message-id" which
* is suitable for logging.
*/
$msg_id = explode(" ", trim($ret), 4);
if ($msg_id[0] != "QUEUED" || !isset($msg_id[2])) { //unexpected response
$ret = "UNEXPECTED RESPONSE: " . $ret;
EventAuditLogger::instance()->newEvent("transmit-ccd", $reqBy, $_SESSION['authProvider'], 0, $ret, $pid);
return( xl("There was a problem sending the message."));
}
EventAuditLogger::instance()->newEvent("transmit-" . $xml_type, $reqBy, $_SESSION['authProvider'], 1, $ret, $pid);
$adodb = $GLOBALS['adodb']['db'];
$sql = "INSERT INTO direct_message_log (msg_type,msg_id,sender,recipient,status,status_ts,patient_id,user_id) " .
"VALUES ('S', ?, ?, ?, 'S', NOW(), ?, ?)";
$res = @sqlStatementNoLog($sql, array($msg_id[2],$phimail_username,$recipient,$pid,$reqID));
return("SUCCESS");
}
| {
"pile_set_name": "Github"
} |
#!/bin/sh
service tomcat7 stop
exit 0 | {
"pile_set_name": "Github"
} |
layer at (0,0) size 800x600
RenderView at (0,0) size 800x600
layer at (0,0) size 800x186
RenderBlock {html} at (0,0) size 800x186
RenderBody {body} at (8,16) size 784x154
RenderBlock {div} at (0,0) size 784x154
RenderBlock {p} at (0,0) size 784x18
RenderText {#text} at (0,0) size 221x18
text run at (0,0) width 221: "This paragraph should be unstyled."
RenderBlock {address} at (0,34) size 784x18 [bgcolor=#00FF00]
RenderText {#text} at (0,0) size 296x18
text run at (0,0) width 296: "This address should have a green background."
RenderBlock {address} at (0,68) size 784x18 [bgcolor=#00FF00]
RenderText {#text} at (0,0) size 296x18
text run at (0,0) width 296: "This address should have a green background."
RenderBlock {q} at (0,102) size 784x18
RenderText {#text} at (0,0) size 221x18
text run at (0,0) width 221: "This paragraph should be unstyled."
RenderBlock {r} at (0,136) size 784x18 [bgcolor=#00FF00]
RenderText {#text} at (0,0) size 308x18
text run at (0,0) width 308: "This paragraph should have a green background."
| {
"pile_set_name": "Github"
} |
/*
* RHQ Management Platform
* Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* 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 version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.rhq.enterprise.server.naming.util;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Given as set of decorators extending given type, this class can pick
* the most appropriate set of decorators for a class or a method call.
* <p>
* To configure the decorator, one has to provide a {@link DecoratorSetContext} that
* is then used to obtain the list of
* {@link DecoratorSetContext#getSupportedInterfaces() supported interfaces}, which are
* all the interfaces that should be used for decorator resolution (i.e. all other interfaces
* that a class might implement are ignored during decorator resolution), the list of
* {@link DecoratorSetContext#getDecoratorClasses() decorator classes}, which is a list
* of decorators the picker can choose from and is also used to instantiate and initialize
* the decorators.
*
* @author Lukas Krejci
*/
public class DecoratorPicker<Type, Decorator extends Type> {
private DecoratorSetContext<Type, Decorator> context;
public DecoratorSetContext<Type, Decorator> getContext() {
return context;
}
public void setContext(DecoratorSetContext<Type, Decorator> decoratorSetContext) {
this.context = decoratorSetContext;
}
/**
* Returns a set of decorators applicable for given method. The set is established based
* on the declaring class of the method.
*
* @param method the method to inspect
* @return the set of decorators that can be used to wrap a method call
* @throws Exception
*/
public Set<Decorator> getDecoratorsForMethod(Method method) throws Exception {
return getDecoratorsForClass_Private(method.getDeclaringClass());
}
/**
* Returns a set of decorators that can be used on instances of given class.
* @param cls the class to inspect
* @return
* @throws Exception
*/
public Set<Decorator> getDecoratorsForClass(Class<? extends Type> cls) throws Exception {
return getDecoratorsForClass_Private(cls);
}
/**
* This method first establishes the set of decorators to use based on the class of the supplied
* object and then chains the decorators (in arbitrary order) with the supplied object at the
* "root" of the chain.
* <p>
* If a method is then called on the returned object, the methods of all the decorators are called
* in chain (each supposedly calling the next) and finally, at the end of the chain, the method on
* the original object (the one supplied to this method) is called.
* <p>
* Note that the above is only an intended behavior and actually depends on the implementation of
* the decorators that are resposinble for the chaining. Each decorator is initialized
* (@{link {@link DecoratorSetContext#init(Object, Object)} which should set it up for such chaining.
*
* @param object
* @return
* @throws Exception
*/
public Type decorate(Type object) throws Exception {
Set<Decorator> decs = getDecoratorsForClass_Private(object.getClass());
Type ret = object;
for(Decorator d : decs) {
context.init(d, ret);
ret = d;
}
return ret;
}
/**
* Similar to {@link #decorate(Object)} but instead of the class of the object itself,
* uses the significantSuperClass as the basis for the decorator resolution.
* <p>
* This is important, because if the object implements two mutually incompatible sub-interfaces of <code>Type</code>,
* the chained decorators might fail to execute a method later on if the decorator depends on the upper part
* of the chain to implement certain sub-interface of <code>Type</code>.
*
* @param object the object to wrap in decorators
* @param significantSuperClass the class to base the decorator resolution on
* @return
* @throws Exception
*/
public Type decorate(Type object, Class<?> significantSuperClass) throws Exception {
Set<Decorator> decs = getDecoratorsForClass_Private(significantSuperClass);
Type ret = object;
for(Decorator d : decs) {
context.init(d, ret);
ret = d;
}
return ret;
}
private Set<Decorator> getDecoratorsForClass_Private(Class<?> cls) throws Exception {
Set<Class<? extends Type>> ifaces = getNearestApplicableInterfaces(cls);
HashSet<Decorator> ret = new HashSet<Decorator>();
for (Class<? extends Type> iface : ifaces) {
for (Class<? extends Decorator> decClass : getMatch(iface)) {
ret.add(context.instantiate(decClass));
}
}
return ret;
}
private Set<Class<? extends Type>> getNearestApplicableInterfaces(Class<?> cls) {
List<Class<? extends Type>> ifaces = new ArrayList<Class<? extends Type>>(getAllApplicableInterfaces(cls));
//now compact the set to only contain the most concrete interfaces
Iterator<Class<? extends Type>> it = ifaces.iterator();
while (it.hasNext()) {
Class<? extends Type> c = it.next();
for (int i = 0; i < ifaces.size(); ++i) {
Class<? extends Type> nextC = ifaces.get(i);
if (!c.equals(nextC) && c.isAssignableFrom(nextC)) {
it.remove();
break;
}
}
}
return new HashSet<Class<? extends Type>>(ifaces);
}
private Set<Class<? extends Type>> getAllApplicableInterfaces(Class<?> cls) {
Set<Class<? extends Type>> ifaces = new HashSet<Class<? extends Type>>();
for (Class<? extends Type> iface : context.getSupportedInterfaces()) {
if (iface.isAssignableFrom(cls)) {
ifaces.add(iface);
}
}
if (ifaces.isEmpty()) {
throw new IllegalArgumentException("Class " + cls
+ " doesn't implement any of the applicable interfaces. Cannot find decorators for it.");
}
return ifaces;
}
private Set<Class<? extends Decorator>> getMatch(Class<?> targetIface) {
Set<Class<? extends Decorator>> ret = new HashSet<Class<? extends Decorator>>();
for (Class<? extends Decorator> cls : context.getDecoratorClasses()) {
if (Arrays.asList(cls.getInterfaces()).contains(targetIface)) {
ret.add(cls);
}
}
return ret;
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Barcode
* @subpackage Object
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** @see Zend_Barcode_Object_Code25interleaved */
require_once 'Zend/Barcode/Object/Code25interleaved.php';
/** @see Zend_Validate_Barcode */
require_once 'Zend/Validate/Barcode.php';
/**
* Class for generate Itf14 barcode
*
* @category Zend
* @package Zend_Barcode
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Barcode_Object_Itf14 extends Zend_Barcode_Object_Code25interleaved
{
/**
* Default options for Identcode barcode
* @return void
*/
protected function _getDefaultOptions()
{
$this->_barcodeLength = 14;
$this->_mandatoryChecksum = true;
}
}
| {
"pile_set_name": "Github"
} |
# Vietnamese Translation for Gettext Examples.
# Copyright © 2010 Yoyodyne, Inc. (msgids)
# Copyright © 2010 Free Software Foundation, Inc.
# This file is distributed under the same license as the gettext package.
# Clytie Siddall <[email protected]>, 2005-2010.
#
msgid ""
msgstr ""
"Project-Id-Version: hello-c++-qt 0.18\n"
"Report-Msgid-Bugs-To: [email protected]\n"
"PO-Revision-Date: 2010-05-13 17:32+0930\n"
"Last-Translator: Clytie Siddall <[email protected]>\n"
"Language-Team: Vietnamese <[email protected]>\n"
"Language: vi\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Generator: LocFactoryEditor 1.8\n"
#: hello.cc:45
msgid "Hello, world!"
msgstr "Chào thế giới !"
#: hello.cc:52
#, qt-format
msgid "This program is running as process number %1."
msgstr "Chương trình này đang chạy với số hiệu tiến trình %1."
| {
"pile_set_name": "Github"
} |
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* 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 com.sun.org.apache.xml.internal.serializer;
/**
* This class defines the constants which are the names of the four default
* output methods.
* <p>
* Three default output methods are defined: XML, HTML, and TEXT.
* These constants can be used as an argument to the
* OutputPropertiesFactory.getDefaultMethodProperties() method to get
* the properties to create a serializer.
*
* This class is a public API.
*
* @see OutputPropertiesFactory
* @see Serializer
*
* @xsl.usage general
*/
public final class Method
{
/**
* A private constructor to prevent the creation of such a class.
*/
private Method() {
}
/**
* The output method type for XML documents: <tt>xml</tt>.
*/
public static final String XML = "xml";
/**
* The output method type for HTML documents: <tt>html</tt>.
*/
public static final String HTML = "html";
/**
* The output method for XHTML documents,
* this method type is not currently supported: <tt>xhtml</tt>.
*/
public static final String XHTML = "xhtml";
/**
* The output method type for text documents: <tt>text</tt>.
*/
public static final String TEXT = "text";
/**
* The "internal" method, just used when no method is
* specified in the style sheet, and a serializer of this type wraps either an
* XML or HTML type (depending on the first tag in the output being html or
* not)
*/
public static final String UNKNOWN = "";
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2017 The Wallaroo Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*/
use "assert"
use "buffered"
use "collections"
use "net"
use "promises"
use "serialise"
use "time"
use "wallaroo_labs/guid"
use "wallaroo_labs/time"
use "wallaroo/core/barrier"
use "wallaroo/core/boundary"
use "wallaroo/core/checkpoint"
use "wallaroo/core/common"
use "wallaroo/core/data_receiver"
use "wallaroo/core/initialization"
use "wallaroo/core/invariant"
use "wallaroo/core/metrics"
use "wallaroo/core/network"
use "wallaroo/core/rebalancing"
use "wallaroo/core/recovery"
use "wallaroo/core/routing"
use "wallaroo/core/sink/tcp_sink"
use "wallaroo/core/state"
use "wallaroo/core/topology"
use "wallaroo/core/windows"
use "wallaroo_labs/collection_helpers"
use "wallaroo_labs/logging"
use "wallaroo_labs/mort"
use @l[I32](severity: LogSeverity, category: LogCategory, fmt: Pointer[U8] tag, ...)
actor Step is (Producer & Consumer & BarrierProcessor)
let _auth: AmbientAuth
let _worker_name: WorkerName
var _id: U128
let _runner: Runner
var _router: Router = EmptyRouter
let _metrics_reporter: MetricsReporter
let _event_log: EventLog
var _seq_id_generator: StepSeqIdGenerator = StepSeqIdGenerator
var _phase: StepPhase = _InitialStepPhase
var _consumer_sender: TestableConsumerSender
// _routes contains one route per Consumer
let _routes: SetIs[Consumer] = _routes.create()
// _outputs keeps track of all output targets by step id. There might be
// duplicate consumers in this map (unlike _routes) since there might be
// multiple target step ids over a boundary
let _outputs: Map[RoutingId, Consumer] = _outputs.create()
// _routes contains one upstream per producer
var _upstreams: SetIs[Producer] = _upstreams.create()
// _inputs keeps track of all inputs by step id. There might be
// duplicate producers in this map (unlike upstreams) since there might be
// multiple upstream step ids over a boundary
let _inputs: Map[RoutingId, Producer] = _inputs.create()
// Lifecycle
var _initializer: (LocalTopologyInitializer | None) = None
var _initialized: Bool = false
var _seq_id_initialized_on_recovery: Bool = false
let _recovery_replayer: RecoveryReconnecter
let _outgoing_boundaries: Map[String, OutgoingBoundary] =
_outgoing_boundaries.create()
// Watermarks
var _watermarks: StageWatermarks = _watermarks.create()
let _timers: Timers = Timers
new create(auth: AmbientAuth, worker_name: WorkerName, runner: Runner iso,
metrics_reporter: MetricsReporter iso,
id: U128, event_log: EventLog,
recovery_replayer: RecoveryReconnecter,
outgoing_boundaries: Map[String, OutgoingBoundary] val,
router': Router = EmptyRouter, is_recovering: Bool = false)
=>
_auth = auth
_worker_name = worker_name
_runner = consume runner
_metrics_reporter = consume metrics_reporter
_event_log = event_log
_recovery_replayer = recovery_replayer
_id = id
// We must set this up first so we can pass a ref to ConsumerSender
_consumer_sender = FailingConsumerSender(_id)
_consumer_sender = ConsumerSender(_id, this, _metrics_reporter.clone())
match _runner
| let r: RollbackableRunner => r.set_step_id(id)
end
_recovery_replayer.register_step(this)
for (worker, boundary) in outgoing_boundaries.pairs() do
_outgoing_boundaries(worker) = boundary
end
_event_log.register_resilient(id, this)
_update_router(router')
for (c_id, consumer) in _router.routes().pairs() do
_register_output(c_id, consumer)
end
_phase =
if is_recovering then
_RecoveringStepPhase(this)
else
_NormalStepPhase(this)
end
match _runner
| let tr: TimeoutTriggeringRunner =>
tr.set_triggers(StepTimeoutTrigger(this), _watermarks)
end
ifdef "identify_routing_ids" then
@l(Log.info(), Log.step(), "===Step %s created===".cstring(),
_id.string().cstring())
let timer = Timer(_StepWaitingReportTimer(this), 500_000_000, 500_000_000)
_timers(consume timer)
end
be step_waiting_report() =>
ifdef "checkpoint_trace" then
@l(Log.debug(), Log.step(), "step_waiting_report: id %s: %s".cstring(), _id.string().cstring(), _phase.step_waiting_report(_inputs).cstring())
end
//
// Application startup lifecycle event
//
be application_begin_reporting(initializer: LocalTopologyInitializer) =>
initializer.report_created(this)
be application_created(initializer: LocalTopologyInitializer) =>
_initialized = true
initializer.report_initialized(this)
be application_initialized(initializer: LocalTopologyInitializer) =>
_prepare_ready_to_work(initializer)
be quick_initialize(initializer: LocalTopologyInitializer) =>
_prepare_ready_to_work(initializer)
fun ref _prepare_ready_to_work(initializer: LocalTopologyInitializer) =>
_initializer = initializer
_report_ready_to_work()
fun ref _report_ready_to_work() =>
match _initializer
| let rrtw: LocalTopologyInitializer =>
rrtw.report_ready_to_work(this)
else
Fail()
end
be application_ready_to_work(initializer: LocalTopologyInitializer) =>
None
be cluster_ready_to_work(initializer: LocalTopologyInitializer) =>
None
fun routing_id(): RoutingId =>
_id
be update_router(router': Router) =>
_update_router(router')
fun ref _update_router(router': Router) =>
let old_router = _router
_router = router'
for (old_id, outdated_consumer) in
old_router.routes_not_in(_router).pairs()
do
if _outputs.contains(old_id) then
_unregister_output(old_id, outdated_consumer)
end
end
for (c_id, consumer) in _router.routes().pairs() do
_register_output(c_id, consumer)
end
_phase.check_completion(inputs())
fun ref _register_output(id: RoutingId, c: Consumer) =>
if _outputs.contains(id) then
try
let old_c = _outputs(id)?
if old_c is c then
// We already know about this output.
return
end
_unregister_output(id, old_c)
else
Unreachable()
end
end
_outputs(id) = c
_routes.set(c)
_consumer_sender.register_producer(id, c)
fun ref _unregister_output(id: RoutingId, c: Consumer) =>
try
_consumer_sender.unregister_producer(id, c)
_outputs.remove(id)?
_remove_route_if_no_output(c)
else
Fail()
end
fun ref _unregister_all_outputs() =>
"""
This method should only be called if we are removing this step from the
active graph (or on dispose())
"""
let outputs_to_remove = Map[RoutingId, Consumer]
for (id, consumer) in _outputs.pairs() do
outputs_to_remove(id) = consumer
end
for (id, consumer) in outputs_to_remove.pairs() do
_unregister_output(id, consumer)
end
be register_downstream() =>
_reregister_as_producer()
fun ref _reregister_as_producer() =>
for (id, c) in _outputs.pairs() do
match c
| let ob: OutgoingBoundary =>
ob.forward_register_producer(_id, id, this)
else
c.register_producer(_id, this)
end
end
be remove_route_to_consumer(id: RoutingId, c: Consumer) =>
if _outputs.contains(id) then
ifdef debug then
Invariant(_routes.contains(c))
end
_unregister_output(id, c)
end
fun ref _remove_route_if_no_output(c: Consumer) =>
var have_output = false
for consumer in _outputs.values() do
if consumer is c then have_output = true end
end
if not have_output then
_remove_route(c)
end
fun ref _remove_route(c: Consumer) =>
_routes.unset(c)
be add_boundaries(boundaries: Map[String, OutgoingBoundary] val) =>
_add_boundaries(boundaries)
fun ref _add_boundaries(boundaries: Map[String, OutgoingBoundary] val) =>
for (worker, boundary) in boundaries.pairs() do
if not _outgoing_boundaries.contains(worker) then
_outgoing_boundaries(worker) = boundary
_routes.set(boundary)
end
end
be remove_boundary(worker: String) =>
_remove_boundary(worker)
fun ref _remove_boundary(worker: String) =>
None
be run[D: Any val](metric_name: String, pipeline_time_spent: U64, data: D,
key: Key, event_ts: U64, watermark_ts: U64, i_producer_id: RoutingId,
i_producer: Producer, msg_uid: MsgId, frac_ids: FractionalMessageId,
i_seq_id: SeqId, latest_ts: U64, metrics_id: U16, worker_ingress_ts: U64)
=>
ifdef "trace" then
@l(Log.debug(), Log.step(), "Received msg at Step".cstring())
end
_phase.run[D](metric_name, pipeline_time_spent, data, key,
event_ts, watermark_ts, i_producer_id, i_producer, msg_uid, frac_ids,
i_seq_id, latest_ts, metrics_id, worker_ingress_ts)
fun ref process_message[D: Any val](metric_name: String,
pipeline_time_spent: U64, data: D, key: Key, event_ts: U64,
watermark_ts: U64, i_producer_id: RoutingId, i_producer: Producer,
msg_uid: MsgId, frac_ids: FractionalMessageId, i_seq_id: SeqId,
latest_ts: U64, metrics_id: U16, worker_ingress_ts: U64)
=>
_seq_id_generator.new_id()
let process_ts = WallClock.nanoseconds()
let input_watermark_ts =
_watermarks.receive_watermark(i_producer_id, watermark_ts, process_ts)
let my_latest_ts = ifdef "detailed-metrics" then
process_ts
else
latest_ts
end
let my_metrics_id = ifdef "detailed-metrics" then
_metrics_reporter.step_metric(metric_name,
"Before receive at step behavior", metrics_id, latest_ts,
my_latest_ts)
metrics_id + 1
else
metrics_id
end
ifdef "trace" then
@l(Log.debug(), Log.step(), ("Rcvd msg at " + _runner.name() + " step\n").cstring())
end
(let is_finished, let last_ts) = _runner.run[D](metric_name,
pipeline_time_spent, data, key, event_ts, input_watermark_ts,
_consumer_sender, _router, msg_uid, frac_ids, my_latest_ts,
my_metrics_id, worker_ingress_ts)
if is_finished then
ifdef "trace" then
@l(Log.debug(), Log.step(), "Filtering".cstring())
end
let end_ts = WallClock.nanoseconds()
let time_spent = end_ts - worker_ingress_ts
ifdef "detailed-metrics" then
_metrics_reporter.step_metric(metric_name, "Before end at Step", 9999,
last_ts, end_ts)
end
_metrics_reporter.pipeline_metric(metric_name,
time_spent + pipeline_time_spent)
_metrics_reporter.worker_metric(metric_name, time_spent)
end
fun inputs(): Map[RoutingId, Producer] box =>
_inputs
fun outputs(): Map[RoutingId, Consumer] box =>
_outputs
fun ref next_sequence_id(): SeqId =>
_seq_id_generator.new_id()
fun ref current_sequence_id(): SeqId =>
_seq_id_generator.current_seq_id()
fun has_route_to(c: Consumer): Bool =>
_routes.contains(c)
be register_producer(id: RoutingId, producer: Producer) =>
_inputs(id) = producer
_upstreams.set(producer)
be unregister_producer(id: RoutingId, producer: Producer) =>
if _inputs.contains(id) then
try
_inputs.remove(id)?
else Fail() end
_phase.remove_input(id)
var have_input = false
for i in _inputs.values() do
if i is producer then have_input = true end
end
if not have_input then
_upstreams.unset(producer)
end
end
be report_status(code: ReportStatusCode) =>
match code
| BoundaryCountStatus =>
var b_count: USize = 0
for c in _routes.values() do
match c
| let ob: OutgoingBoundary => b_count = b_count + 1
end
end
@l(Log.info(), Log.step(), "Step %s has %s boundaries.".cstring(), _id.string().cstring(), b_count.string().cstring())
end
be mute(c: Consumer) =>
for u in _upstreams.values() do
u.mute(c)
end
be unmute(c: Consumer) =>
for u in _upstreams.values() do
u.unmute(c)
end
be dispose_with_promise(promise: Promise[None]) =>
_phase.dispose(this)
promise(None)
be dispose() =>
_phase.dispose(this)
fun ref finish_disposing() =>
@l(Log.info(), Log.step(), "Disposing Step %s".cstring(), _id.string().cstring())
_event_log.unregister_resilient(_id, this)
_unregister_all_outputs()
_timers.dispose()
_phase = _DisposedStepPhase
///////////////
// GROW-TO-FIT
be receive_key_state(step_group: RoutingId, key: Key,
state_bytes: ByteSeq val)
=>
ifdef "autoscale" then
StepStateMigrator.receive_state(this, _runner, step_group, key,
state_bytes)
@l(Log.info(), Log.step(), "Received state for step %s".cstring(),
_id.string().cstring())
end
be send_state(boundary: OutgoingBoundary, step_group: RoutingId, key: Key,
checkpoint_id: CheckpointId)
=>
ifdef "autoscale" then
_phase.send_state(this, _runner, _id, boundary, step_group,
key, checkpoint_id, _auth)
end
//////////////
// BARRIER
//////////////
be receive_barrier(step_id: RoutingId, producer: Producer,
barrier_token: BarrierToken)
=>
ifdef "checkpoint_trace" then
@l(Log.debug(), Log.step(), "Step %s received barrier %s from %s".cstring(),
_id.string().cstring(), barrier_token.string().cstring(),
step_id.string().cstring())
end
process_barrier(step_id, producer, barrier_token)
fun ref process_barrier(step_id: RoutingId, producer: Producer,
barrier_token: BarrierToken)
=>
if _inputs.contains(step_id) then
ifdef "checkpoint_trace" then
@l(Log.debug(), Log.step(), "Process Barrier %s at Step %s from %s".cstring(),
barrier_token.string().cstring(), _id.string().cstring(),
step_id.string().cstring())
end
// TODO: We can find a way to handle this behavior by
// the StepPhase itself.
match barrier_token
| let srt: CheckpointRollbackBarrierToken =>
_phase.prepare_for_rollback(srt)
| let abt: AutoscaleBarrierToken =>
if ArrayHelpers[WorkerName].contains[WorkerName](abt.leaving_workers(),
_worker_name)
then
// We're leaving, so we need to flush any remaining worker local
// state (which won't be migrated).
_runner.flush_local_state(_consumer_sender, _router, _watermarks)
end
end
_phase.receive_barrier(step_id, producer,
barrier_token)
else
@l(Log.info(), Log.step(), ("Received barrier from unregistered input %s at step " +
"%s. \n").cstring(), step_id.string().cstring(),
_id.string().cstring())
end
fun ref receive_new_barrier(input_id: RoutingId, producer: Producer,
barrier_token: BarrierToken)
=>
ifdef "checkpoint_trace" then
@l(Log.debug(), Log.step(), "Receive New Barrier %s at Step %s from %s".cstring(),
barrier_token.string().cstring(), _id.string().cstring(),
input_id.string().cstring())
end
_phase = _BarrierStepPhase(this, _id, barrier_token)
_phase.receive_barrier(input_id, producer, barrier_token)
fun ref barrier_complete(barrier_token: BarrierToken) =>
ifdef "checkpoint_trace" then
@l(Log.debug(), Log.step(), "Barrier %s complete at Step %s".cstring(),
barrier_token.string().cstring(), _id.string().cstring())
end
match barrier_token
| let cbt: CheckpointBarrierToken =>
checkpoint_state(cbt.id)
end
var queued = Array[_Queued]
match barrier_token
| let crbt: CheckpointRollbackBarrierToken =>
_phase = _RecoveringStepPhase(this, crbt)
else
queued = _phase.queued()
_phase = _NormalStepPhase(this)
end
for q in queued.values() do
match q
| let qm: QueuedMessage =>
qm.process_message(this)
| let qb: QueuedBarrier =>
qb.inject_barrier(this)
end
end
//////////////
// CHECKPOINTS
//////////////
fun ref checkpoint_state(checkpoint_id: CheckpointId) =>
ifdef "resilience" then
StepStateCheckpointer(_runner, _id, checkpoint_id, _event_log,
_watermarks, _auth)
end
be prepare_for_rollback() =>
finish_preparing_for_rollback(None, _phase)
fun ref finish_preparing_for_rollback(token: (BarrierToken | None),
new_phase: StepPhase)
=>
@l(Log.debug(), Log.step(), "StepPhase Id %s change line %lu current _phase type %s new_phase type %s".cstring(), _id.string().cstring(), __loc.line(), _phase.name().cstring(), new_phase.name().cstring())
_phase = new_phase
be rollback(payload: ByteSeq val, event_log: EventLog,
checkpoint_id: CheckpointId)
=>
_phase.rollback(_id, this, payload, event_log, _runner)
fun ref finish_rolling_back() =>
_phase = _NormalStepPhase(this)
fun ref rollback_watermarks(bs: ByteSeq val) =>
try
_watermarks = StageWatermarksDeserializer(bs as Array[U8] val, _auth)?
else
Fail()
end
///////////////
// WATERMARKS
///////////////
fun ref check_effective_input_watermark(current_ts: U64): U64 =>
_watermarks.check_effective_input_watermark(current_ts)
fun ref update_output_watermark(w: U64): (U64, U64) =>
_watermarks.update_output_watermark(w)
fun input_watermark(): U64 =>
_watermarks.input_watermark()
fun output_watermark(): U64 =>
_watermarks.output_watermark()
/////////////
// TIMEOUTS
/////////////
fun ref set_timeout(t: U64) =>
_timers(Timer(StepTimeoutNotify(this), t))
be trigger_timeout() =>
_phase.trigger_timeout(this)
fun ref finish_triggering_timeout() =>
match _runner
| let tr: TimeoutTriggeringRunner =>
tr.on_timeout(_consumer_sender, _router, _watermarks)
else
Fail()
end
class _StepWaitingReportTimer is TimerNotify
let _step: Step
new iso create(step: Step) =>
_step = step
fun ref apply(timer: Timer, count: U64): Bool =>
_step.step_waiting_report()
true
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">
<chapter>
<header>
<copyright>
<year>2003</year><year>2016</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
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.
</legalnotice>
<title>Records</title>
<prepared></prepared>
<docno></docno>
<date></date>
<rev></rev>
<file>records.xml</file>
</header>
<section>
<title>Records and Tuples</title>
<p>The main advantage of using records rather than tuples is that
fields in a record are accessed by name, whereas fields in a
tuple are accessed by position. To illustrate these differences,
suppose that you want to represent a person with the tuple
<c>{Name, Address, Phone}</c>.</p>
<p>To write functions that manipulate this data, remember the following:</p>
<list type="bulleted">
<item>The <c>Name</c> field is the first element of the tuple.</item>
<item>The <c>Address</c> field is the second element.</item>
<item>The <c>Phone</c> field is the third element.</item>
</list>
<p>For example, to extract data from a variable <c>P</c>
that contains such a tuple, you can write the following code
and then use pattern matching to extract the relevant fields:</p>
<code type="none">
Name = element(1, P),
Address = element(2, P),
...</code>
<p>Such code is difficult to read and understand, and errors
occur if the numbering of the elements in the tuple is wrong.
If the data representation of the fields is changed, by re-ordering,
adding, or removing fields, all references to
the person tuple must be checked and possibly modified.</p>
<p>Records allow references to the fields by name, instead of by
position. In the following example, a record instead of a tuple
is used to store the data:</p>
<code type="none">
-record(person, {name, phone, address}).</code>
<p>This enables references to the fields of the record by name.
For example, if <c>P</c> is a variable whose value is a
<c>person</c> record, the following code access
the name and address fields of the records:</p>
<code type="none">
Name = P#person.name,
Address = P#person.address,
...</code>
<p>Internally, records are represented using tagged tuples:</p>
<code type="none">
{person, Name, Phone, Address}</code>
</section>
<section>
<title>Defining a Record</title>
<p>This following definition of a <c>person</c> is used in several
examples in this section. Three fields are included, <c>name</c>,
<c>phone</c>, and <c>address</c>. The default values for
<c>name</c> and <c>phone</c> is "" and [], respectively.
The default value for <c>address</c> is the atom
<c>undefined</c>, since no default value is supplied for this
field:</p>
<pre>
-record(person, {name = "", phone = [], address}).</pre>
<p>The record must be defined in the shell to enable
use of the record syntax in the examples:</p>
<pre>
> <input>rd(person, {name = "", phone = [], address}).</input>
person</pre>
<p>This is because record definitions are only available
at compile time, not at runtime. For details on records
in the shell, see the
<seeerl marker="stdlib:shell">shell(3)</seeerl>
manual page in STDLIB.</p>
</section>
<section>
<title>Creating a Record</title>
<p>A new <c>person</c> record is created as follows:</p>
<pre>
> <input>#person{phone=[0,8,2,3,4,3,1,2], name="Robert"}.</input>
#person{name = "Robert",phone = [0,8,2,3,4,3,1,2],address = undefined}</pre>
<p>As the <c>address</c> field was omitted, its default value
is used.</p>
<p>From Erlang 5.1/OTP R8B, a value to all
fields in a record can be set with the special field <c>_</c>.
<c>_</c> means "all fields not explicitly specified".</p>
<p><em>Example:</em></p>
<pre>
> <input>#person{name = "Jakob", _ = '_'}.</input>
#person{name = "Jakob",phone = '_',address = '_'}</pre>
<p>It is primarily intended to be used in <c>ets:match/2</c> and
<c>mnesia:match_object/3</c>, to set record fields to the atom
<c>'_'</c>. (This is a wildcard in <c>ets:match/2</c>.)</p>
</section>
<section>
<title>Accessing a Record Field</title>
<p>The following example shows how to access a record field:</p>
<pre>
> <input>P = #person{name = "Joe", phone = [0,8,2,3,4,3,1,2]}.</input>
#person{name = "Joe",phone = [0,8,2,3,4,3,1,2],address = undefined}
> <input>P#person.name.</input>
"Joe"</pre>
</section>
<section>
<title>Updating a Record</title>
<p>The following example shows how to update a record:</p>
<pre>
> <input>P1 = #person{name="Joe", phone=[1,2,3], address="A street"}.</input>
#person{name = "Joe",phone = [1,2,3],address = "A street"}
> <input>P2 = P1#person{name="Robert"}.</input>
#person{name = "Robert",phone = [1,2,3],address = "A street"}</pre>
</section>
<section>
<title>Type Testing</title>
<p>The following example shows that the guard succeeds if
<c>P</c> is record of type <c>person</c>:</p>
<pre>
foo(P) when is_record(P, person) -> a_person;
foo(_) -> not_a_person.</pre>
</section>
<section>
<title>Pattern Matching</title>
<p>Matching can be used in combination with records, as shown in
the following example:</p>
<pre>
> <input>P3 = #person{name="Joe", phone=[0,0,7], address="A street"}.</input>
#person{name = "Joe",phone = [0,0,7],address = "A street"}
> <input>#person{name = Name} = P3, Name.</input>
"Joe"</pre>
<p>The following function takes a list of <c>person</c> records
and searches for the phone number of a person with a particular
name:</p>
<code type="none">
find_phone([#person{name=Name, phone=Phone} | _], Name) ->
{found, Phone};
find_phone([_| T], Name) ->
find_phone(T, Name);
find_phone([], Name) ->
not_found.</code>
<p>The fields referred to in the pattern can be given in any order.</p>
</section>
<section>
<title>Nested Records</title>
<p>The value of a field in a record can be an instance of a
record. Retrieval of nested data can be done stepwise, or in a
single step, as shown in the following example:</p>
<pre>
-record(name, {first = "Robert", last = "Ericsson"}).
-record(person, {name = #name{}, phone}).
demo() ->
P = #person{name= #name{first="Robert",last="Virding"}, phone=123},
First = (P#person.name)#name.first.</pre>
<p>Here, <c>demo()</c> evaluates to <c>"Robert"</c>.</p>
</section>
<section>
<title>A Longer Example</title>
<p>Comments are embedded in the following example:</p>
<pre>
%% File: person.hrl
%%-----------------------------------------------------------
%% Data Type: person
%% where:
%% name: A string (default is undefined).
%% age: An integer (default is undefined).
%% phone: A list of integers (default is []).
%% dict: A dictionary containing various information
%% about the person.
%% A {Key, Value} list (default is the empty list).
%%------------------------------------------------------------
-record(person, {name, age, phone = [], dict = []}).</pre>
<pre>
-module(person).
-include("person.hrl").
-compile(export_all). % For test purposes only.
%% This creates an instance of a person.
%% Note: The phone number is not supplied so the
%% default value [] will be used.
make_hacker_without_phone(Name, Age) ->
#person{name = Name, age = Age,
dict = [{computer_knowledge, excellent},
{drinks, coke}]}.
%% This demonstrates matching in arguments
print(#person{name = Name, age = Age,
phone = Phone, dict = Dict}) ->
io:format("Name: ~s, Age: ~w, Phone: ~w ~n"
"Dictionary: ~w.~n", [Name, Age, Phone, Dict]).
%% Demonstrates type testing, selector, updating.
birthday(P) when record(P, person) ->
P#person{age = P#person.age + 1}.
register_two_hackers() ->
Hacker1 = make_hacker_without_phone("Joe", 29),
OldHacker = birthday(Hacker1),
% The central_register_server should have
% an interface function for this.
central_register_server ! {register_person, Hacker1},
central_register_server ! {register_person,
OldHacker#person{name = "Robert",
phone = [0,8,3,2,4,5,3,1]}}.</pre>
</section>
</chapter>
| {
"pile_set_name": "Github"
} |
package org.bimserver.database.query.conditions;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import java.util.Set;
import org.bimserver.emf.IdEObject;
import org.eclipse.emf.ecore.EClass;
public class AndCondition extends Condition {
private final Condition conditionB;
private final Condition conditionA;
public AndCondition(Condition conditionA, Condition conditionB) {
this.conditionA = conditionA;
this.conditionB = conditionB;
}
@Override
public void getEClassRequirements(Set<EClass> classRequirements) {
conditionA.getEClassRequirements(classRequirements);
conditionB.getEClassRequirements(classRequirements);
}
@Override
public boolean matches(IdEObject object) {
return conditionA.matches(object) && conditionB.matches(object);
}
} | {
"pile_set_name": "Github"
} |
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://[email protected]
class: javax.crypto.spec.DESedeKeySpec
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVAX_CRYPTO_SPEC_DESEDEKEYSPEC_HPP_DECL
#define J2CPP_JAVAX_CRYPTO_SPEC_DESEDEKEYSPEC_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace security { namespace spec { class KeySpec; } } } }
#include <java/lang/Object.hpp>
#include <java/security/spec/KeySpec.hpp>
namespace j2cpp {
namespace javax { namespace crypto { namespace spec {
class DESedeKeySpec;
class DESedeKeySpec
: public object<DESedeKeySpec>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_FIELD(0)
explicit DESedeKeySpec(jobject jobj)
: object<DESedeKeySpec>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
operator local_ref<java::security::spec::KeySpec>() const;
DESedeKeySpec(local_ref< array<jbyte,1> > const&);
DESedeKeySpec(local_ref< array<jbyte,1> > const&, jint);
local_ref< array<jbyte,1> > getKey();
static jboolean isParityAdjusted(local_ref< array<jbyte,1> > const&, jint);
static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > DES_EDE_KEY_LEN;
}; //class DESedeKeySpec
} //namespace spec
} //namespace crypto
} //namespace javax
} //namespace j2cpp
#endif //J2CPP_JAVAX_CRYPTO_SPEC_DESEDEKEYSPEC_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVAX_CRYPTO_SPEC_DESEDEKEYSPEC_HPP_IMPL
#define J2CPP_JAVAX_CRYPTO_SPEC_DESEDEKEYSPEC_HPP_IMPL
namespace j2cpp {
javax::crypto::spec::DESedeKeySpec::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
javax::crypto::spec::DESedeKeySpec::operator local_ref<java::security::spec::KeySpec>() const
{
return local_ref<java::security::spec::KeySpec>(get_jobject());
}
javax::crypto::spec::DESedeKeySpec::DESedeKeySpec(local_ref< array<jbyte,1> > const &a0)
: object<javax::crypto::spec::DESedeKeySpec>(
call_new_object<
javax::crypto::spec::DESedeKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESedeKeySpec::J2CPP_METHOD_NAME(0),
javax::crypto::spec::DESedeKeySpec::J2CPP_METHOD_SIGNATURE(0)
>(a0)
)
{
}
javax::crypto::spec::DESedeKeySpec::DESedeKeySpec(local_ref< array<jbyte,1> > const &a0, jint a1)
: object<javax::crypto::spec::DESedeKeySpec>(
call_new_object<
javax::crypto::spec::DESedeKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESedeKeySpec::J2CPP_METHOD_NAME(1),
javax::crypto::spec::DESedeKeySpec::J2CPP_METHOD_SIGNATURE(1)
>(a0, a1)
)
{
}
local_ref< array<jbyte,1> > javax::crypto::spec::DESedeKeySpec::getKey()
{
return call_method<
javax::crypto::spec::DESedeKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESedeKeySpec::J2CPP_METHOD_NAME(2),
javax::crypto::spec::DESedeKeySpec::J2CPP_METHOD_SIGNATURE(2),
local_ref< array<jbyte,1> >
>(get_jobject());
}
jboolean javax::crypto::spec::DESedeKeySpec::isParityAdjusted(local_ref< array<jbyte,1> > const &a0, jint a1)
{
return call_static_method<
javax::crypto::spec::DESedeKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESedeKeySpec::J2CPP_METHOD_NAME(3),
javax::crypto::spec::DESedeKeySpec::J2CPP_METHOD_SIGNATURE(3),
jboolean
>(a0, a1);
}
static_field<
javax::crypto::spec::DESedeKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESedeKeySpec::J2CPP_FIELD_NAME(0),
javax::crypto::spec::DESedeKeySpec::J2CPP_FIELD_SIGNATURE(0),
jint
> javax::crypto::spec::DESedeKeySpec::DES_EDE_KEY_LEN;
J2CPP_DEFINE_CLASS(javax::crypto::spec::DESedeKeySpec,"javax/crypto/spec/DESedeKeySpec")
J2CPP_DEFINE_METHOD(javax::crypto::spec::DESedeKeySpec,0,"<init>","([B)V")
J2CPP_DEFINE_METHOD(javax::crypto::spec::DESedeKeySpec,1,"<init>","([BI)V")
J2CPP_DEFINE_METHOD(javax::crypto::spec::DESedeKeySpec,2,"getKey","()[B")
J2CPP_DEFINE_METHOD(javax::crypto::spec::DESedeKeySpec,3,"isParityAdjusted","([BI)Z")
J2CPP_DEFINE_FIELD(javax::crypto::spec::DESedeKeySpec,0,"DES_EDE_KEY_LEN","I")
} //namespace j2cpp
#endif //J2CPP_JAVAX_CRYPTO_SPEC_DESEDEKEYSPEC_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| {
"pile_set_name": "Github"
} |
/**
* @file cryptoConfig.h
* @version $Format:%h%d$
*
* Configuration file for crypto features.
*/
/*
* Copyright (c) 2013-2017 INSIDE Secure Corporation
* Copyright (c) PeerSec Networks, 2002-2011
* All Rights Reserved
*
* The latest version of this code is available at http://www.matrixssl.org
*
* This software is open source; 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.
*
* This General Public License does NOT permit incorporating this software
* into proprietary programs. If you are unable to comply with the GPL, a
* commercial license for this software may be purchased from INSIDE at
* http://www.insidesecure.com/
*
* This program is distributed in WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* http://www.gnu.org/copyleft/gpl.html
*/
/******************************************************************************/
#ifndef _h_PS_CRYPTOCONFIG
# define _h_PS_CRYPTOCONFIG
/******************************************************************************/
/* Configurable features */
/******************************************************************************/
/**
Define to enable psTrace*Crypto APIs for debugging the crypto module.
*/
/* #define USE_CRYPTO_TRACE */
# ifdef DEBUG
/* #define CRYPTO_ASSERT *//**< Extra sanity asserts */
# endif
/******************************************************************************/
/*
Use built-in cryptographic library delivered with MatrixSSL
*/
# define USE_NATIVE_RSA /* Default built-in software support */
/******************************************************************************/
/**
Security related settings.
@security MIN_*_BITS is the minimum supported key sizes in bits, weaker
keys will be rejected.
*/
# define MIN_ECC_BITS 192/**< @security Affects ECC curves below */
# define MIN_RSA_BITS 1024
/* The configuration can define set minimum for RSA public exponent.
For CL crypto, the default is 65537 (according to FIPS 186-4 standard).
It can be overridden on line below:
*/
/* #define MIN_RSA_PUBLIC_EXPONENT 65537 *//* Valid values 3, 5, 17, 65537. */
# define MIN_DH_BITS 1024
/* #define USE_BURN_STACK *//**< @security Zero sensitive data from the stack. */
/* Allow extraction of the master key via the API */
/* #define ENABLE_MASTER_SECRET_EXPORT */
/******************************************************************************/
/**
Public-Key Algorithm Support.
*/
/* #define USE_RSA */
/* #define USE_ECC */
/* #define USE_DH */
/**< @note Enable verification of DSA signatures in certificate validation.
Works only when using the CL/SL library. @pre USE_CERT_PARSE. */
/* #define USE_DSA_VERIFY */
# ifdef USE_DH
/**< @note Enable this if you intent to support Diffie-Hellman groups larger
than 4096. Usually such large groups are not used. */
/* #define USE_LARGE_DH_GROUPS */
# endif /* USE_DH */
/**< @note Enable ECDHE with Curve25519. */
/* #define USE_X25519 */
/**< @note Enable Pure EdDSA Curve25519 (Ed25519) signatures.
@pre USE_ECC, USE_SHA512. */
/* #define USE_ED25519 */
/******************************************************************************/
/**
Build the PKCS and ASN1 extra CL sublibraries.
These are needed by the CL_PKCS API.
*/
/******************************************************************************/
/**
Define to enable the individual NIST Prime curves.
@see http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf
*/
# ifdef USE_ECC
/* #define USE_SECP192R1 *//**< @security FIPS allowed for sig ver only. */
/* #define USE_SECP224R1 */
/* #define USE_SECP256R1 *//**< @security NIST_SHALL */
/* #define USE_SECP384R1 *//**< @security NIST_SHALL */
/* #define USE_SECP521R1 */
# endif
/**
Define to enable the individual Brainpool curves.
@see https://tools.ietf.org/html/rfc5639
@security WARNING: Public points on Brainpool curves are not validated
*/
# ifdef USE_ECC
/* #define USE_BRAIN224R1 */
/* #define USE_BRAIN256R1 */
/* #define USE_BRAIN384R1 */
/* #define USE_BRAIN512R1 */
# endif
/******************************************************************************/
/**
Symmetric and AEAD ciphers.
@security Deprecated ciphers must be enabled in cryptolib.h
*/
/* #define USE_AES *//* Enable/Disable AES */
# define USE_AES_CBC
/* #define USE_AES_GCM */
/** If you want new ciphersuites specified in RFC 7539 enable this.
Currently CHACHA20-based cipher suites are only supported by the newest
TLS clients and servers. These cipher suites are not allowed in FIPS
mode of operation.
*/
/* #define USE_CHACHA20_POLY1305_IETF */
/** @security 3DES is still relatively secure, however is deprecated for TLS */
/* #define USE_3DES */
/******************************************************************************/
/**
Legacy ciphers.
These ciphers have been deprecated, but may be occasionally required
for legacy compatibility. Usage of these cipher suites should be avoided
as these may represent small or moderate risk.
Note: The RC4 cipher below need to disabled according to RFC 7465.
*/
/* #define USE_ARC4 */
/******************************************************************************/
/**
Digest algorithms.
@note SHA256 and above are used with TLS 1.2, and also used for
certificate signatures on some certificates regardless of TLS version.
@security MD5 is deprecated, but still required in combination with SHA-1
for TLS handshakes before TLS 1.2, meaning that the strength is at least
that of SHA-1 in this usage. The define USE_MD5SHA1 can be used to enable
MD5 only for this purpose. The only other usage of MD5 by TLS is for
certificate signatures and MD5 based cipher suites. Both of which are
disabled at compile time by default.
@security SHA1 will be deprecated in the future, but is still required in
combination with MD5 for versions prior to TLS 1.2. In addition, SHA1
certificates are still commonly used, so SHA1 support may be needed
to validate older certificates. It is possible to completely disable
SHA1 using TLS 1.2 and SHA2 based ciphersuites, and interacting
only with newer certificates.
*/
/* #define USE_SHA224 *//**< @note Used only for cert signature */
# define USE_SHA256/**< @note Required for TLS 1.2 and above */
# define USE_HMAC_SHA256
/* #define USE_SHA384 *//**< @pre USE_SHA512 */
/* #define USE_HMAC_SHA384 */
/* #define USE_SHA512 */
/**
@security SHA-1 based hashes are deprecated but enabled by default
@note ENABLE_SHA1_SIGNED_CERTS can additionally be configured below.
*/
/* #define USE_SHA1 */
/* #define USE_HMAC_SHA1 */
/**
@security MD5 is considered insecure, but required by TLS < 1.2
@note ENABLE_MD5_SIGNED_CERTS can additionally be configured below.
*/
/* #define USE_MD5 */
/* #define USE_MD5SHA1 *//* Required for < TLS 1.2 Handshake */
/* #define USE_HMAC_MD5 */
/**
@security MD2 is considered insecure, but is sometimes used for
verification of legacy root certificate signatures.
@note MD2 signature verification also requires
ENABLE_MD5_SIGNED_CERTS and USE_MD5.
*/
/* #define USE_MD2 */
/* Please enable, unless using no HMAC algorithms. */
# define USE_HMAC
/**
HMAC-based Extract-and-Expand Key Derivation Function (HKDF) (RFC 5869).
Needed in TLS 1.3 key derivation.
*/
# if defined(USE_HMAC_SHA256) || defined(USE_HMAC_SHA384)
/* #define USE_HKDF */
# endif
/******************************************************************************/
/**
X.509 Certificates/PKI
*/
/* #define USE_BASE64_DECODE */
/* #define USE_X509 *//**< Enable minimal X.509 support. */
/* #define USE_CERT_PARSE *//**< Enable TBSCertificate parsing. Usually required. @pre USE_X509 */
/* #define USE_FULL_CERT_PARSE *//**< @pre USE_CERT_PARSE */
/**< Support the certificatePolicy, policyMappings and policyContrainsts X.509 extensions. */
/* #define USE_CERT_POLICY_EXTENSIONS */
/**< Support extra distinguished name attributes that SHOULD be supported according to RFC 5280. */
/* #define USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD */
/**< Support extra distinguished name attributes not mentioned in RFC 5280. */
/* #define USE_EXTRA_DN_ATTRIBUTES */
/**< Allow ASN.1 BMPString string type in DN Attributes. */
/* #define USE_ASN_BMPSTRING_DN_ATTRIBS */
/* #define ENABLE_CA_CERT_HASH *//**< Used only for TLS trusted CA ind ext. */
/* #define ENABLE_MD5_SIGNED_CERTS *//** @security Accept MD5 signed certs? */
/**
@security SHA-1 based signatures are insecure, as SHA-1 can no longer
be considered collision resistant (https://shattered.it/static/shattered.pdf).
Enable if compatibility with old certificates is required.
*/
/* #define ENABLE_SHA1_SIGNED_CERTS */
/**< @security Allow parsing of locally trusted v1 root certs? */
/* #define ALLOW_VERSION_1_ROOT_CERT_PARSE */
/**
When parsing certificates, always also retain the unparsed DER data.
Enabling this has the same effect as setting the
CERT_STORE_UNPARSED_BUFFER flag in each psX509ParseCert call.
*/
/* #define ALWAYS_KEEP_CERT_DER */
/**
Always attempt to match expectedName with the subject CN, even if
a supported, but non-matching subjectAltName was presented.
The default behaviour is to check the CN only when no supported SAN
was presented, in accordance with Section 6.4.4 of RFC 6125.
*/
/* #define ALWAYS_CHECK_SUBJECT_CN_IN_HOSTNAME_VALIDATION */
/* #define USE_CRL *//***< @pre USE_FULL_CERT_PARSE */
# ifdef USE_CRL
/**
Allow CRL authentication to succeed even when signer CA's cert does not
have the keyUsage extension and thus no cRLSign bit.
Note that RFC 5280 requires CRL issuer certs to have the keyUsage extension
and the cRLSign bit.
*/
/* #define ALLOW_CRL_ISSUERS_WITHOUT_KEYUSAGE */
# endif
/**
Enable OCSP response and request handling.
*/
/* #define USE_OCSP *//**< @pre USE_SHA1 */
# ifdef USE_OCSP
# define USE_OCSP_RESPONSE
# elif defined(USE_X509) && defined(USE_SHA1) && defined(USE_CERT_PARSE)
/**
Enable parsing and writing of OCSP responses. This is enough
to support OCSP stapling.
*/
/* #define USE_OCSP_RESPONSE *//**< @pre USE_SHA1 */
#endif /* USE_OCSP */
/******************************************************************************/
/**
Various PKCS standards support
*/
/* #define USE_PRIVATE_KEY_PARSING */
/* #define USE_PKCS5 *//**< v2.0 PBKDF encrypted priv keys. @pre USE_3DES */
/**< Enable PBKDF1 in priv key PEM encryption. @pre USE_PKCS5 and @pre USE_MD5. @security Not recommended. */
/* #define USE_PBKDF1 */
/* #define USE_PKCS8 *//* Alternative private key storage format */
/* #define USE_PKCS12 *//**< @pre USE_PKCS8 */
/* #define USE_PKCS1_OAEP *//* OAEP padding algorithm */
/* #define USE_PKCS1_PSS *//* PSS padding algorithm */
# ifdef USE_PRIVATE_KEY_PARSING
/* USE_PRIVATE_KEY_PARSING enables decoding of DER-encoded keys and certs. For PEM there is a separate define. */
/* #define USE_BASE64_DECODE *//* Allow decoding Base64-encoded data. */
/* #define USE_PEM_DECODE *//* Allow decoding PEM-encoded data. @pre USE_BASE64_DECODE. */
# endif
#endif /* _h_PS_CRYPTOCONFIG */
/******************************************************************************/
| {
"pile_set_name": "Github"
} |
// Copyright 2017-2019 Espressif Systems (Shanghai) PTE 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 "bt_hidh.h"
#if CONFIG_BT_HID_HOST_ENABLED
#include "esp_hidh_private.h"
#include <string.h>
#include <stdbool.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_bt_hh_api.h"
static const char *TAG = "BT_HIDH";
static esp_event_loop_handle_t event_loop_handle;
static const char *s_bta_hh_evt_names[] = {"ENABLE", "DISABLE", "OPEN", "CLOSE", "GET_RPT", "SET_RPT", "GET_PROTO", "SET_PROTO", "GET_IDLE", "SET_IDLE", "GET_DSCP", "ADD_DEV", "RMV_DEV", "VC_UNPLUG", "DATA", "API_ERR", "UPDATE_SCPP"};
static const char *s_bta_hh_status_names[] = {"OK", "HS_HID_NOT_READY", "HS_INVALID_RPT_ID", "HS_TRANS_NOT_SPT", "HS_INVALID_PARAM", "HS_ERROR", "ERR", "ERR_SDP", "ERR_PROTO", "ERR_DB_FULL", "ERR_TOD_UNSPT", "ERR_NO_RES", "ERR_AUTH_FAILED", "ERR_HDL", "ERR_SEC"};
static inline void WAIT_DEV(esp_hidh_dev_t *dev)
{
xSemaphoreTake(dev->semaphore, portMAX_DELAY);
}
static inline void SEND_DEV(esp_hidh_dev_t *dev)
{
xSemaphoreGive(dev->semaphore);
}
static void bta_hh_cb(tBTA_HH_EVT event, tBTA_HH *p_data)
{
static esp_hidh_dev_t *descr_dev = NULL;
esp_hidh_dev_t *dev = NULL;
switch (event) {
case BTA_HH_ENABLE_EVT: {
if (p_data->status) {
ESP_LOGE(TAG, "ENABLE ERROR: %s", s_bta_hh_status_names[p_data->status]);
}
} break;
case BTA_HH_OPEN_EVT: {
dev = esp_hidh_dev_get_by_handle(p_data->conn.handle);
if (dev == NULL) {
ESP_LOGE(TAG, "OPEN ERROR: Device Not Found");
return;
}
dev->status = p_data->conn.status;
memcpy(dev->bda, p_data->conn.bda, sizeof(esp_bd_addr_t));
if (dev->status == BTA_HH_OK) {
descr_dev = dev;
BTA_HhGetDscpInfo(dev->bt.handle);
} else {
ESP_LOGE(TAG, "OPEN ERROR: %s", s_bta_hh_status_names[dev->status]);
if (dev->opened) {
SEND_DEV(dev);
} else {
esp_hidh_dev_free(dev);
}
}
} break;
case BTA_HH_GET_DSCP_EVT: {
ESP_LOGV(TAG, "DESCRIPTOR: PID: 0x%04x, VID: 0x%04x, VERSION: 0x%04x, REPORT_LEN: %u", p_data->dscp_info.product_id, p_data->dscp_info.vendor_id, p_data->dscp_info.version, p_data->dscp_info.descriptor.dl_len);
if (descr_dev == NULL) {
ESP_LOGE(TAG, "Device Not Found");
return;
}
dev = descr_dev;
dev->config.product_id = p_data->dscp_info.product_id;
dev->config.vendor_id = p_data->dscp_info.vendor_id;
dev->config.version = p_data->dscp_info.version;
dev->config.report_maps_len = 1;
dev->config.report_maps = (esp_hid_raw_report_map_t *)malloc(dev->config.report_maps_len * sizeof(esp_hid_raw_report_map_t));
if (dev->config.report_maps == NULL) {
ESP_LOGE(TAG, "malloc report maps failed");
return;
}
dev->config.report_maps[0].data = (uint8_t *)malloc(p_data->dscp_info.descriptor.dl_len);
if (dev->config.report_maps[0].data == NULL) {
ESP_LOGE(TAG, "Malloc Report Map Failed");
dev->status = BTA_HH_ERR_NO_RES;
} else {
dev->config.report_maps[0].len = p_data->dscp_info.descriptor.dl_len;
memcpy((uint8_t *)dev->config.report_maps[0].data, p_data->dscp_info.descriptor.dsc_list, dev->config.report_maps[0].len);
//generate reports
if (dev->config.report_maps[0].len && dev->config.report_maps[0].data) {
esp_hid_report_map_t *map;
esp_hidh_dev_report_t *report;
esp_hid_report_item_t *r;
map = esp_hid_parse_report_map(dev->config.report_maps[0].data, dev->config.report_maps[0].len);
if (map) {
if (dev->usage == 0) {
dev->usage = map->usage;
}
dev->connected = true;
dev->reports = NULL;
for (uint8_t i = 0; i < map->reports_len; i++) {
r = &map->reports[i];
report = (esp_hidh_dev_report_t *)malloc(sizeof(esp_hidh_dev_report_t));
if (report == NULL) {
ESP_LOGE(TAG, "Malloc Report Failed");
dev->status = BTA_HH_ERR_NO_RES;
dev->connected = false;
break;
}
report->map_index = 0;
report->protocol_mode = r->protocol_mode;
report->report_type = r->report_type;
report->report_id = r->report_id;
report->value_len = r->value_len;
report->usage = r->usage;
report->next = dev->reports;
dev->reports = report;
}
dev->reports_len = map->reports_len;
free(map->reports);
free(map);
map = NULL;
} else {
ESP_LOGE(TAG, "Parse Report Map Failed");
dev->status = BTA_HH_ERR;
}
}
}
descr_dev = NULL;
if (dev->status == BTA_HH_OK) {
BTA_HhAddDev(dev->bda, dev->bt.attr_mask, dev->bt.sub_class, dev->bt.app_id, p_data->dscp_info);
} else {
ESP_LOGE(TAG, "Read Report Map Failed, status: %s", s_bta_hh_status_names[dev->status]);
if (dev->opened) {
SEND_DEV(dev);
} else {
esp_hidh_dev_free(dev);
}
}
} break;
case BTA_HH_ADD_DEV_EVT: {
ESP_LOGV(TAG, "ADD_DEV: BDA: " ESP_BD_ADDR_STR ", handle: %d, status: %s", ESP_BD_ADDR_HEX(p_data->dev_info.bda), p_data->dev_info.handle, s_bta_hh_status_names[p_data->dev_info.status]);
dev = esp_hidh_dev_get_by_handle(p_data->conn.handle);
if (dev == NULL) {
ESP_LOGE(TAG, "Device Not Found");
return;
}
dev->status = p_data->conn.status;
if (dev->status == BTA_HH_OK) {
esp_hidh_event_data_t p;
p.open.dev = dev;
esp_event_post_to(event_loop_handle, ESP_HIDH_EVENTS, ESP_HIDH_OPEN_EVENT, &p, sizeof(esp_hidh_event_data_t), portMAX_DELAY);
} else {
ESP_LOGE(TAG, "Device Add Failed, status: %s", s_bta_hh_status_names[dev->status]);
}
if (dev->opened) {
SEND_DEV(dev);
} else if (dev->status != BTA_HH_OK) {
esp_hidh_dev_free(dev);
}
} break;
case BTA_HH_CLOSE_EVT: {
ESP_LOGV(TAG, "CLOSE: handle: %d, status: %s", p_data->dev_status.handle, s_bta_hh_status_names[p_data->dev_status.status]);
dev = esp_hidh_dev_get_by_handle(p_data->dev_status.handle);
if (dev == NULL) {
ESP_LOGE(TAG, "Device Not Found");
return;
}
dev->status = p_data->dev_status.status;
esp_hidh_event_data_t p;
p.close.dev = dev;
p.close.reason = 0;
esp_event_post_to(event_loop_handle, ESP_HIDH_EVENTS, ESP_HIDH_CLOSE_EVENT, &p, sizeof(esp_hidh_event_data_t), portMAX_DELAY);
} break;
case BTA_HH_SET_RPT_EVT: {
dev = esp_hidh_dev_get_by_handle(p_data->dev_status.handle);
if (dev == NULL) {
ESP_LOGE(TAG, "SET_RPT ERROR: hDevice Not Found");
return;
}
if (p_data->dev_status.status) {
ESP_LOGE(TAG, "SET_RPT ERROR: handle: %d, status: %s", p_data->dev_status.handle, s_bta_hh_status_names[p_data->dev_status.status]);
}
dev->status = p_data->dev_status.status;
SEND_DEV(dev);
} break;
case BTA_HH_GET_RPT_EVT: {
dev = esp_hidh_dev_get_by_handle(p_data->hs_data.handle);
if (dev == NULL) {
ESP_LOGE(TAG, "Device Not Found");
return;
}
if (p_data->hs_data.status) {
ESP_LOGE(TAG, "GET_RPT ERROR: handle: %d, status: %s", p_data->hs_data.handle, s_bta_hh_status_names[p_data->hs_data.status]);
}
dev->status = p_data->hs_data.status;
BT_HDR *rpt = p_data->hs_data.rsp_data.p_rpt_data;
dev->tmp = rpt->data + rpt->offset;
dev->tmp_len = rpt->len;
SEND_DEV(dev);
} break;
default:
ESP_LOGV(TAG, "BTA_HH EVENT: %s", s_bta_hh_evt_names[event]);
break;
}
}
/*
* Public Functions
* */
static esp_err_t esp_bt_hidh_dev_close(esp_hidh_dev_t *dev)
{
BTA_HhClose(dev->bt.handle);
return ESP_OK;
}
static esp_err_t esp_bt_hidh_dev_report_write(esp_hidh_dev_t *dev, size_t map_index, size_t report_id, int report_type, uint8_t *data, size_t len)
{
esp_hidh_dev_report_t *report = esp_hidh_dev_get_report_by_id_and_type(dev, map_index, report_id, report_type);
if (!report) {
ESP_LOGE(TAG, "%s report %d not found", esp_hid_report_type_str(report_type), report_id);
return ESP_FAIL;
}
if (len > report->value_len) {
ESP_LOGE(TAG, "%s report %d takes maximum %d bytes. you have provided %d", esp_hid_report_type_str(report_type), report_id, report->value_len, len);
return ESP_FAIL;
}
uint8_t *pbuf_data;
BT_HDR *p_buf = (BT_HDR *)malloc((uint16_t) (len + 14 + sizeof(BT_HDR)));
if (p_buf != NULL) {
p_buf->len = len + 1;
p_buf->offset = 14;
pbuf_data = (uint8_t *) (p_buf + 1) + p_buf->offset;
pbuf_data[0] = report_id;
memcpy(pbuf_data + 1, data, len);
if (report_type == ESP_HID_REPORT_TYPE_OUTPUT) {
p_buf->layer_specific = BTA_HH_RPTT_OUTPUT;
BTA_HhSendData(dev->bt.handle, dev->bda, p_buf);
} else {
BTA_HhSetReport(dev->bt.handle, report_type, p_buf);
WAIT_DEV(dev);
}
if (dev->status) {
ESP_LOGE(TAG, "Write %s: %s", esp_hid_report_type_str(report_type), s_bta_hh_status_names[dev->status]);
return ESP_FAIL;
}
}
return ESP_OK;
}
static esp_err_t esp_bt_hidh_dev_report_read(esp_hidh_dev_t *dev, size_t map_index, size_t report_id, int report_type, size_t max_length, uint8_t *value, size_t *value_len)
{
esp_hidh_dev_report_t *report = esp_hidh_dev_get_report_by_id_and_type(dev, map_index, report_id, report_type);
if (!report) {
ESP_LOGE(TAG, "%s report %d not found", esp_hid_report_type_str(report_type), report_id);
return ESP_FAIL;
}
BTA_HhGetReport(dev->bt.handle, report_type, report_id, max_length);
if (xSemaphoreTake(dev->semaphore, 500 / portTICK_PERIOD_MS) != pdTRUE) {
ESP_LOGE(TAG, "Read Timeout %s", esp_hid_report_type_str(report_type));
return ESP_FAIL;
}
if (dev->status) {
ESP_LOGE(TAG, "Read %s: %s", esp_hid_report_type_str(report_type), s_bta_hh_status_names[dev->status]);
return ESP_FAIL;
}
if (report_id) {
dev->tmp++;
dev->tmp_len--;
}
if (dev->tmp_len > max_length) {
dev->tmp_len = max_length;
}
*value_len = dev->tmp_len;
memcpy(value, dev->tmp, dev->tmp_len);
return ESP_OK;
}
static void esp_bt_hidh_dev_dump(esp_hidh_dev_t *dev, FILE *fp)
{
fprintf(fp, "BDA:" ESP_BD_ADDR_STR ", Status: %s, Connected: %s, Handle: %d, Usage: %s\n", ESP_BD_ADDR_HEX(dev->bda), s_bta_hh_status_names[dev->status], dev->connected ? "YES" : "NO", dev->bt.handle, esp_hid_usage_str(dev->usage));
fprintf(fp, "Name: %s, Manufacturer: %s, Serial Number: %s\n", dev->config.device_name ? dev->config.device_name : "", dev->config.manufacturer_name ? dev->config.manufacturer_name : "", dev->config.serial_number ? dev->config.serial_number : "");
fprintf(fp, "PID: 0x%04x, VID: 0x%04x, VERSION: 0x%04x\n", dev->config.product_id, dev->config.vendor_id, dev->config.version);
fprintf(fp, "Report Map Length: %d\n", dev->config.report_maps[0].len);
esp_hidh_dev_report_t *report = dev->reports;
while (report) {
fprintf(fp, " %8s %7s %6s, ID: %3u, Length: %3u\n",
esp_hid_usage_str(report->usage), esp_hid_report_type_str(report->report_type), esp_hid_protocol_mode_str(report->protocol_mode),
report->report_id, report->value_len);
report = report->next;
}
}
esp_err_t esp_bt_hidh_init(const esp_hidh_config_t *config)
{
if (config == NULL) {
ESP_LOGE(TAG, "Config is NULL");
return ESP_FAIL;
}
esp_event_loop_args_t event_task_args = {
.queue_size = 5,
.task_name = "esp_bt_hidh_events",
.task_priority = uxTaskPriorityGet(NULL),
.task_stack_size = 2048,
.task_core_id = tskNO_AFFINITY
};
esp_err_t ret = esp_event_loop_create(&event_task_args, &event_loop_handle);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "esp_event_loop_create failed!");
return ret;
}
esp_event_handler_register_with(event_loop_handle, ESP_HIDH_EVENTS, ESP_EVENT_ANY_ID, config->callback, NULL);
BTA_HhEnable(0, bta_hh_cb);
return ESP_OK;
}
esp_err_t esp_bt_hidh_deinit(void)
{
if (event_loop_handle) {
esp_event_loop_delete(event_loop_handle);
}
BTA_HhDisable();
return ESP_OK;
}
esp_hidh_dev_t *esp_bt_hidh_dev_open(esp_bd_addr_t bda)
{
esp_hidh_dev_t *dev = esp_hidh_dev_malloc();
if (dev == NULL) {
ESP_LOGE(TAG, "malloc esp_hidh_dev_t failed");
return NULL;
}
dev->transport = ESP_HID_TRANSPORT_BT;
memcpy(dev->bda, bda, sizeof(esp_bd_addr_t));
dev->bt.handle = -1;
dev->opened = true;
BTA_HhOpen(dev->bda, 0, BTA_HH_PROTO_RPT_MODE, (BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT));
WAIT_DEV(dev);
if (dev->status != BTA_HH_OK) {
esp_hidh_dev_free(dev);
return NULL;
}
dev->close = esp_bt_hidh_dev_close;
dev->report_write = esp_bt_hidh_dev_report_write;
dev->report_read = esp_bt_hidh_dev_report_read;
dev->dump = esp_bt_hidh_dev_dump;
return dev;
}
/*
* BlueDroid BT HIDH Stack Callbacks
* */
/* This callback function is executed by BTA_HH when data is received on an interrupt channel. */
void bta_hh_co_data(uint8_t handle, uint8_t *p_rpt, uint16_t len, tBTA_HH_PROTO_MODE mode, uint8_t sub_class, uint8_t country_code, esp_bd_addr_t bda, uint8_t app_id)
{
if (len < 2) {
ESP_LOGE(TAG, "Not Enough Data");
return;
}
esp_hidh_dev_t *dev = NULL;
esp_hidh_dev_report_t *report = NULL;
dev = esp_hidh_dev_get_by_handle(handle);
if (dev == NULL) {
ESP_LOGE(TAG, "Device Not Found: handle %u", handle);
return;
}
report = esp_hidh_dev_get_input_report_by_id_and_proto(dev, p_rpt[0], mode ? ESP_HID_PROTOCOL_MODE_BOOT : ESP_HID_PROTOCOL_MODE_REPORT);
if (report == NULL) {
ESP_LOGE(TAG, "Report Not Found: %d mode: %s", p_rpt[0], mode ? "BOOT" : "REPORT");
return;
}
if (len != (report->value_len + 1)) {
ESP_LOGW(TAG, "Wrong Data Len: %u != %u", len, (report->value_len + 1));
}
if (event_loop_handle) {
esp_hidh_event_data_t p = {0};
if (report->report_type == ESP_HID_REPORT_TYPE_FEATURE) {
p.feature.dev = dev;
p.feature.report_id = report->report_id;
p.feature.usage = report->usage;
p.feature.data = p_rpt + 1;
p.feature.length = len - 1;
esp_event_post_to(event_loop_handle, ESP_HIDH_EVENTS, ESP_HIDH_FEATURE_EVENT, &p, sizeof(esp_hidh_event_data_t), portMAX_DELAY);
} else {
p.input.dev = dev;
p.input.report_id = report->report_id;
p.input.usage = report->usage;
p.input.data = p_rpt + 1;
p.input.length = len - 1;
esp_event_post_to(event_loop_handle, ESP_HIDH_EVENTS, ESP_HIDH_INPUT_EVENT, &p, sizeof(esp_hidh_event_data_t), portMAX_DELAY);
}
}
}
/* This callback function is executed by BTA_HH when connection is opened, and application may do some device specific initialization. */
void bta_hh_co_open(uint8_t handle, uint8_t sub_class, uint16_t attr_mask, uint8_t app_id)
{
esp_hidh_dev_t *dev = NULL;
dev = esp_hidh_dev_get_by_handle(-1);
if (dev == NULL) {
ESP_LOGI(TAG, "Device Not Found? It's probably a reconnect.");
dev = esp_hidh_dev_malloc();
if (dev == NULL) {
ESP_LOGE(TAG, "DEV Malloc Failed");
return;
}
dev->transport = ESP_HID_TRANSPORT_BT;
dev->close = esp_bt_hidh_dev_close;
dev->report_write = esp_bt_hidh_dev_report_write;
dev->report_read = esp_bt_hidh_dev_report_read;
dev->dump = esp_bt_hidh_dev_dump;
}
dev->bt.attr_mask = attr_mask;
dev->bt.app_id = app_id;
dev->bt.sub_class = sub_class;
dev->bt.handle = handle;
}
/* This callback function is executed by BTA_HH when connection is closed, and device specific finalization may be needed. */
void bta_hh_co_close(uint8_t dev_handle, uint8_t app_id) {}
#endif /* CONFIG_BT_HID_HOST_ENABLED */
| {
"pile_set_name": "Github"
} |
/*
*
* 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.
*
*/
var self,
exception = ripple('exception'),
_HtmlElements = ['header', 'footer', 'section', 'aside', 'nav', 'article'];
self = module.exports = {
validateNumberOfArguments: function (lowerBound, upperBound, numberOfArguments, customExceptionType, customExceptionMessage, customExceptionObject) {
customExceptionMessage = customExceptionMessage || "";
if (arguments.length < 3 || arguments.length > 6) {
exception.raise(exception.types.Argument, "Wrong number of arguments when calling: validateNumberOfArguments()");
}
if (isNaN(lowerBound) && isNaN(upperBound) && isNaN(numberOfArguments)) {
exception.raise(exception.types.ArgumentType, "(validateNumberOfArguments) Arguments are not numbers");
}
lowerBound = parseInt(lowerBound, 10);
upperBound = parseInt(upperBound, 10);
numberOfArguments = parseInt(numberOfArguments, 10);
if (numberOfArguments < lowerBound || numberOfArguments > upperBound) {
exception.raise((customExceptionType || exception.types.ArgumentLength), (customExceptionMessage + "\n\nWrong number of arguments"), customExceptionObject);
}
},
validateArgumentType: function (arg, argType, customExceptionType, customExceptionMessage, customExceptionObject) {
var invalidArg = false,
msg;
switch (argType) {
case "array":
if (!(arg instanceof Array)) {
invalidArg = true;
}
break;
case "date":
if (!(arg instanceof Date)) {
invalidArg = true;
}
break;
case "integer":
if (typeof arg === "number") {
if (arg !== Math.floor(arg)) {
invalidArg = true;
}
}
else {
invalidArg = true;
}
break;
default:
if (typeof arg !== argType) {
invalidArg = true;
}
break;
}
if (invalidArg) {
msg = customExceptionMessage + ("\n\nInvalid Argument type. argument: " + arg + " ==> was expected to be of type: " + argType);
exception.raise((customExceptionType || exception.types.ArgumentType), msg, customExceptionObject);
}
},
validateMultipleArgumentTypes: function (argArray, argTypeArray, customExceptionType, customExceptionMessage, customExceptionObject) {
for (var i = 0; i < argArray.length; i++) {
this.validateArgumentType(argArray[i], argTypeArray[i], customExceptionType, customExceptionMessage, customExceptionObject);
}
},
createElement: function (elementType, attributes) {
var d = document.createElement(elementType);
if (attributes) {
this.forEach(attributes, function (attributeValue, attributeName) {
switch (attributeName.toLowerCase()) {
case "innerhtml":
d.innerHTML = attributeValue;
break;
case "innertext":
d.innerText = attributeValue;
break;
default:
d.setAttribute(attributeName, attributeValue);
}
});
}
return d;
},
loadHTMLElements: function () {
for (var i = 0; i < _HtmlElements.length; i += 1) {
document.createElement(_HtmlElements[i]);
}
},
getAllStylesheetRules: function getAllStylesheetRules(title) {
this.validateNumberOfArguments(1, 1, arguments.length);
var i, x, sheet, rules, styles_array = [];
// get style sheet according to title
for (i = 0; i < document.styleSheets.length; i += 1) {
sheet = document.styleSheets[i];
rules = sheet.cssRules;
if (rules) {
for (x = 0; x < rules.length; x += 1) {
if (rules[x].selectorText && rules[x].selectorText === (title.toString())) {
styles_array.push(rules[x]);
}
}
}
}
return (styles_array);
},
location: function () {
return window.location;
},
queryString: function () {
// trim the leading ? and split each name=value
var args = this.location().search.replace(/^\?/, '').split('&');
return args.reduce(function (obj, value) {
if (value) {
value = value.toLowerCase().split("=");
obj[value[0]] = value[1];
}
return obj;
}, {});
},
extensionUrl: function () {
return document.getElementById("extension-url").innerHTML;
},
appLocation: function () {
var loc = self.location(),
parts = loc.pathname.split("/"),
base = "",
port = loc.port ? ":" + loc.port : "";
if (parts[parts.length - 1].match(/\.\w*$/)) {
parts = parts.splice(0, parts.length - 1);
}
base = parts.join("/").replace(/\/$/, '');
return loc.protocol + "//" + loc.hostname + port + base + "/";
},
arrayContains: function (array, obj) {
var i = array.length;
while (i--) {
if (array[i] === obj) {
return true;
}
}
return false;
},
some: function (obj, predicate, scope) {
if (obj instanceof Array) {
return obj.some(predicate, scope);
}
else {
var values = self.map(obj, predicate, scope);
return self.reduce(values, function (some, value) {
return value ? value : some;
}, false);
}
},
count: function (obj) {
return self.sum(obj, function () {
return 1;
});
},
sum: function (obj, selector, scope) {
var values = self.map(obj, selector, scope);
return self.reduce(values, function (total, value) {
return total + value;
});
},
max: function (obj, selector, scope) {
var values = self.map(obj, selector, scope);
return self.reduce(values, function (max, value) {
return max < value ? value : max;
}, Number.MIN_VALUE);
},
min: function (obj, selector, scope) {
var values = self.map(obj, selector, scope);
return self.reduce(values, function (min, value) {
return min > value ? value : min;
}, Number.MAX_VALUE);
},
forEach: function (obj, action, scope) {
if (obj instanceof Array) {
return obj.forEach(action, scope);
}
else {
self.map(obj, action, scope);
}
},
filter: function (obj, predicate, scope) {
if (obj instanceof Array) {
return obj.filter(predicate, scope);
}
else {
var result = [];
self.forEach(obj, function (value, index) {
if (predicate.apply(scope, [value, index])) {
result.push(value);
}
}, scope);
return result;
}
},
reduce: function (obj, func, init, scope) {
var i,
initial = init === undefined ? 0 : init,
result = initial;
//MozHack for NamedNodeMap
/* jshint ignore:start */
if(window.MozNamedAttrMap) NamedNodeMap = window.MozNamedAttrMap;
/* jshint ignore:end */
if (obj instanceof Array) {
return obj.reduce(func, initial);
}
else if (obj instanceof NamedNodeMap) {
for (i = 0; i < obj.length; i++) {
result = func.apply(scope, [result, obj[i], i]);
}
}
else {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
result = func.apply(scope, [result, obj[i], i]);
}
}
}
return result;
},
map: function (obj, func, scope) {
var i,
returnVal = null,
result = [];
//MozHack for NamedNodeMap
/* jshint ignore:start */
if(window.MozNamedAttrMap) NamedNodeMap = window.MozNamedAttrMap;
/* jshint ignore:end */
if (obj instanceof Array) {
return obj.map(func, scope);
}
else if (obj instanceof NamedNodeMap) {
for (i = 0; i < obj.length; i++) {
returnVal = func.apply(scope, [obj[i], i]);
result.push(returnVal);
}
}
else {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
returnVal = func.apply(scope, [obj[i], i]);
result.push(returnVal);
}
}
}
return result;
},
regexSanitize: function (regexString) {
return regexString.replace("^", "\\^")
.replace("$", "\\$")
.replace("(", "\\(")
.replace(")", "\\)")
.replace("<", "\\<")
.replace("[", "\\[")
.replace("{", "\\{")
.replace(/\\/, "\\\\")
.replace("|", "\\|")
.replace(">", "\\>")
.replace(".", "\\.")
.replace("*", "\\*")
.replace("+", "\\+")
.replace("?", "\\?");
},
bindAutoSaveEvent: function (node, saveCallback) {
var oldSetTimeoutId,
jNode = jQuery(node);
jNode.bind("keyup", function (event) {
if (event.keyCode !== 9) {
clearTimeout(oldSetTimeoutId);
oldSetTimeoutId = window.setTimeout(function () {
saveCallback();
}, 500);
}
});
},
find: function (comparison, collection, startInx, endInx, callback) {
var results = [],
compare = function (s, pattern) {
if (typeof(s) !== "string" || pattern === null) {
return s === pattern;
}
var regex = pattern.replace(/\./g, "\\.")
.replace(/\^/g, "\\^")
.replace(/\*/g, ".*")
.replace(/\\\.\*/g, "\\*");
regex = "^".concat(regex, "$");
return !!s.match(new RegExp(regex, "i"));
};
self.forEach(collection, function (c) {
var match,
fail = false;
self.forEach(comparison, function (value, key) {
if (!fail && value !== undefined) {
if (compare(c[key], value)) {
match = c;
}
else {
fail = true;
match = null;
}
}
});
if (match) {
results.push(match);
}
});
if (callback) {
if (startInx === undefined) {
startInx = 0;
}
if (endInx === undefined) {
endInx = results.length;
}
if (startInx === endInx) {
endInx = startInx + 1;
}
callback.apply(null, [results.slice(startInx, endInx)]);
}
},
mixin: function (mixin, to) {
for (var prop in mixin) {
if (Object.hasOwnProperty.call(mixin, prop)) {
to[prop] = mixin[prop];
}
}
return to;
},
copy: function (obj) {
var i,
newObj = jQuery.isArray(obj) ? [] : {};
if (typeof obj === 'number' ||
typeof obj === 'string' ||
typeof obj === 'boolean' ||
obj === null ||
obj === undefined) {
return obj;
}
if (obj instanceof Date) {
return new Date(obj);
}
if (obj instanceof RegExp) {
return new RegExp(obj);
}
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (obj[i] && typeof obj[i] === "object") {
if (obj[i] instanceof Date) {
newObj[i] = obj[i];
}
else {
newObj[i] = self.copy(obj[i]);
}
}
else {
newObj[i] = obj[i];
}
}
}
return newObj;
},
navHelper: function () {
return {
getHeading: function (lat1, lon1, lat2, lon2) {
var dLon = this.rad(lon2 - lon1),
llat1 = this.rad(lat1),
llat2 = this.rad(lat2),
y = Math.sin(dLon) * Math.cos(llat2),
x = Math.cos(llat1) * Math.sin(llat2) - Math.sin(llat1) * Math.cos(llat2) * Math.cos(dLon);
return (this.deg(Math.atan2(y, x)) + 360) % 360;
},
getDistance: function (lat1, lon1, lat2, lon2) {
var dLat = this.rad(lat2 - lat1),
dLon = this.rad(lon2 - lon1),
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.rad(lat1)) * Math.cos(this.rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2),
c = 2 * Math.asin(Math.sqrt(a)),
d = 6378100 * c;
return d;
},
simulateTravel: function (lat, lon, hdg, dist) {
var lat1 = this.rad(lat),
lon1 = this.rad(lon),
brng = this.rad(hdg),
angularDistance = dist / 6378100,
lat2 = Math.asin(Math.sin(lat1) * Math.cos(angularDistance) + Math.cos(lat1) * Math.sin(angularDistance) * Math.cos(brng)),
lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angularDistance) * Math.cos(lat1), Math.cos(angularDistance) - Math.sin(lat1) * Math.sin(lat2));
lon2 = (lon2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // Normalize to -180..+180
return {
latitude: this.deg(lat2),
longitude: this.deg(lon2)
};
},
deg: function (num) {
return num * 180 / Math.PI;
},
rad: function (num) {
return num * Math.PI / 180;
}
};
},
defineReadOnlyField: function (obj, field, value) {
Object.defineProperty(obj, field, {"value": value, "writable": false});
},
parseUrl: function (url) {
var a = document.createElement("a");
a.href = url;
return {
href: a.href,
host: a.host,
origin: a.origin,
port: a.port,
protocol: a.protocol,
search: a.search
};
}
};
| {
"pile_set_name": "Github"
} |
#!/bin/sh
DIR=`pwd`
cd ../src/python
./test-python2.sh
RESULT=$?
cd $DIR
exit $RESULT
| {
"pile_set_name": "Github"
} |
var searchData=
[
['d3dcolor',['D3DCOLOR',['../namespacepvrvk.html#a9d61c6a587c92b4666875184f283d48fa67cb8b94254acbfda2cdf7a916421298',1,'pvrvk']]]
];
| {
"pile_set_name": "Github"
} |
import {bar as baz} from "foo";
| {
"pile_set_name": "Github"
} |
import Mixin from "@ember/object/mixin";
import { isNone } from "@ember/utils";
import { makeArray } from "discourse-common/lib/helpers";
let _appendContentCallbacks = {};
function appendContent(pluginApiIdentifiers, contentFunction) {
if (isNone(_appendContentCallbacks[pluginApiIdentifiers])) {
_appendContentCallbacks[pluginApiIdentifiers] = [];
}
_appendContentCallbacks[pluginApiIdentifiers].push(contentFunction);
}
let _prependContentCallbacks = {};
function prependContent(targetedIdentifier, contentFunction) {
if (isNone(_prependContentCallbacks[targetedIdentifier])) {
_prependContentCallbacks[targetedIdentifier] = [];
}
_prependContentCallbacks[targetedIdentifier].push(contentFunction);
}
let _onChangeCallbacks = {};
function onChange(pluginApiIdentifiers, mutationFunction) {
if (isNone(_onChangeCallbacks[pluginApiIdentifiers])) {
_onChangeCallbacks[pluginApiIdentifiers] = [];
}
_onChangeCallbacks[pluginApiIdentifiers].push(mutationFunction);
}
export function applyContentPluginApiCallbacks(content, component) {
makeArray(component.pluginApiIdentifiers).forEach((key) => {
(_prependContentCallbacks[key] || []).forEach((c) => {
const prependedContent = c(component, content);
if (prependedContent) {
content = makeArray(prependedContent).concat(content);
}
});
(_appendContentCallbacks[key] || []).forEach((c) => {
const appendedContent = c(component, content);
if (appendedContent) {
content = content.concat(makeArray(appendedContent));
}
});
});
return content;
}
export function applyOnChangePluginApiCallbacks(value, items, component) {
makeArray(component.pluginApiIdentifiers).forEach((key) => {
(_onChangeCallbacks[key] || []).forEach((c) => c(component, value, items));
});
}
export function modifySelectKit(targetedIdentifier) {
return {
appendContent: (callback) => {
appendContent(targetedIdentifier, callback);
return modifySelectKit(targetedIdentifier);
},
prependContent: (callback) => {
prependContent(targetedIdentifier, callback);
return modifySelectKit(targetedIdentifier);
},
onChange: (callback) => {
onChange(targetedIdentifier, callback);
return modifySelectKit(targetedIdentifier);
},
};
}
export function clearCallbacks() {
_appendContentCallbacks = {};
_prependContentCallbacks = {};
_onChangeCallbacks = {};
}
const EMPTY_ARRAY = Object.freeze([]);
export default Mixin.create({
concatenatedProperties: ["pluginApiIdentifiers"],
pluginApiIdentifiers: EMPTY_ARRAY,
});
| {
"pile_set_name": "Github"
} |
-----BEGIN CERTIFICATE-----
MIIB1zCCAX2gAwIBAgIBATAKBggqhkjOPQQDAjAvMQswCQYDVQQGEwJVSzERMA8G
A1UECgwIbWJlZCBUTFMxDTALBgNVBAMMBENBMDkwHhcNMTcwNjIyMTE1MDMzWhcN
MjcwNjIzMTE1MDMzWjAvMQswCQYDVQQGEwJVSzERMA8GA1UECgwIbWJlZCBUTFMx
DTALBgNVBAMMBENBMTAwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR6jlGKbJd5
hiDxN789gkOcwpyHI9wRwCrADAOwOkMePBPRlwGdm7mw7Z/EAmu26zRm/hcyrs4M
qk2LabDjPI9Xo4GJMIGGMB0GA1UdDgQWBBQtxZSLJAkEz+2RKMQexM6EtsfgcjBX
BgNVHSMEUDBOgBT6gyXHzPIPYc1Vr1aGiLLeMh4HpqEzpDEwLzELMAkGA1UEBhMC
VUsxETAPBgNVBAoMCG1iZWQgVExTMQ0wCwYDVQQDDARDQTA4ggEBMAwGA1UdEwQF
MAMBAf8wCgYIKoZIzj0EAwIDSAAwRQIgP7S8vFstfUBdNe6ym5GYG5Q+aBVEKqRs
fVW7HNUktSYCIQDo6Jua6o/DJbrpq4qYWq5gv4yGyzPTN+3IaKrEICdaaw==
-----END CERTIFICATE-----
| {
"pile_set_name": "Github"
} |
class PrivacyEthereumRpcModePresenter {
weak var view: IPrivacyEthereumRpcModeView?
weak var delegate: IPrivacyEthereumRpcModeDelegate?
private let router: IPrivacyEthereumRpcModeRouter
private var currentMode: EthereumRpcMode
private let modes = EthereumRpcMode.allCases
init(currentMode: EthereumRpcMode, router: IPrivacyEthereumRpcModeRouter) {
self.currentMode = currentMode
self.router = router
}
private func syncViewItems() {
let viewItems = modes.map { mode in
PrivacyEthereumRpcModeModule.ViewItem(
title: mode.title,
subtitle: mode.address,
selected: mode == currentMode
)
}
view?.set(viewItems: viewItems)
}
}
extension PrivacyEthereumRpcModePresenter: IPrivacyEthereumRpcModeViewDelegate {
func onLoad() {
syncViewItems()
}
func onTapViewItem(index: Int) {
currentMode = modes[index]
syncViewItems()
}
func onTapDone() {
delegate?.onSelect(mode: currentMode)
router.close()
}
}
| {
"pile_set_name": "Github"
} |
// Simple multi-thread/multi-core TCP server.
package main
import (
"flag"
"fmt"
"net"
"os"
)
const maxRead = 25
func main() {
flag.Parse()
if flag.NArg() != 2 {
panic("usage: host port")
}
hostAndPort := fmt.Sprintf("%s:%s", flag.Arg(0), flag.Arg(1))
listener := initServer(hostAndPort)
for {
conn, err := listener.Accept()
checkError(err, "Accept: ")
go connectionHandler(conn)
}
}
func initServer(hostAndPort string) *net.TCPListener {
serverAddr, err := net.ResolveTCPAddr("tcp", hostAndPort)
checkError(err, "Resolving address:port failed: '"+hostAndPort+"'")
listener, err := net.Listen("tcp", serverAddr)
checkError(err, "ListenTCP: ")
println("Listening to: ", listener.Addr().String())
return listener
}
func connectionHandler(conn net.Conn) {
connFrom := conn.RemoteAddr().String()
println("Connection from: ", connFrom)
sayHello(conn)
for {
var ibuf []byte = make([]byte, maxRead+1)
length, err := conn.Read(ibuf[0:maxRead])
ibuf[maxRead] = 0 // to prevent overflow
switch err {
case nil:
handleMsg(length, err, ibuf)
case os.EAGAIN: // try again
continue
default:
goto DISCONNECT
}
}
DISCONNECT:
err := conn.Close()
println("Closed connection: ", connFrom)
checkError(err, "Close: ")
}
func sayHello(to net.Conn) {
obuf := []byte{'L', 'e', 't', '\'', 's', ' ', 'G', 'O', '!', '\n'}
wrote, err := to.Write(obuf)
checkError(err, "Write: wrote "+string(wrote)+" bytes.")
}
func handleMsg(length int, err error, msg []byte) {
if length > 0 {
print("<", length, ":")
for i := 0; ; i++ {
if msg[i] == 0 {
break
}
fmt.Printf("%c", msg[i])
}
print(">")
}
}
func checkError(error error, info string) {
if error != nil {
panic("ERROR: " + info + " " + error.Error()) // terminate program
}
}
| {
"pile_set_name": "Github"
} |
// (C) Copyright John Maddock 2007.
// Use, modification and distribution are subject to 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)
//
// This file is machine generated, do not edit by hand
// Polynomial evaluation using second order Horners rule
#ifndef BOOST_MATH_TOOLS_RAT_EVAL_11_HPP
#define BOOST_MATH_TOOLS_RAT_EVAL_11_HPP
namespace boost{ namespace math{ namespace tools{ namespace detail{
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V&, const mpl::int_<0>*)
{
return static_cast<V>(0);
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V&, const mpl::int_<1>*)
{
return static_cast<V>(a[0]) / static_cast<V>(b[0]);
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<2>*)
{
return static_cast<V>((a[1] * x + a[0]) / (b[1] * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<3>*)
{
return static_cast<V>(((a[2] * x + a[1]) * x + a[0]) / ((b[2] * x + b[1]) * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<4>*)
{
return static_cast<V>((((a[3] * x + a[2]) * x + a[1]) * x + a[0]) / (((b[3] * x + b[2]) * x + b[1]) * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<5>*)
{
if(x <= 1)
{
V x2 = x * x;
return static_cast<V>(((a[4] * x2 + a[2]) * x2 + a[0] + (a[3] * x2 + a[1]) * x) / ((b[4] * x2 + b[2]) * x2 + b[0] + (b[3] * x2 + b[1]) * x));
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
return static_cast<V>(((a[0] * z2 + a[2]) * z2 + a[4] + (a[1] * z2 + a[3]) * z) / ((b[0] * z2 + b[2]) * z2 + b[4] + (b[1] * z2 + b[3]) * z));
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<6>*)
{
if(x <= 1)
{
V x2 = x * x;
return static_cast<V>((((a[5] * x2 + a[3]) * x2 + a[1]) * x + (a[4] * x2 + a[2]) * x2 + a[0]) / (((b[5] * x2 + b[3]) * x2 + b[1]) * x + (b[4] * x2 + b[2]) * x2 + b[0]));
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
return static_cast<V>((((a[0] * z2 + a[2]) * z2 + a[4]) * z + (a[1] * z2 + a[3]) * z2 + a[5]) / (((b[0] * z2 + b[2]) * z2 + b[4]) * z + (b[1] * z2 + b[3]) * z2 + b[5]));
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<7>*)
{
if(x <= 1)
{
V x2 = x * x;
return static_cast<V>((((a[6] * x2 + a[4]) * x2 + a[2]) * x2 + a[0] + ((a[5] * x2 + a[3]) * x2 + a[1]) * x) / (((b[6] * x2 + b[4]) * x2 + b[2]) * x2 + b[0] + ((b[5] * x2 + b[3]) * x2 + b[1]) * x));
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
return static_cast<V>((((a[0] * z2 + a[2]) * z2 + a[4]) * z2 + a[6] + ((a[1] * z2 + a[3]) * z2 + a[5]) * z) / (((b[0] * z2 + b[2]) * z2 + b[4]) * z2 + b[6] + ((b[1] * z2 + b[3]) * z2 + b[5]) * z));
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<8>*)
{
if(x <= 1)
{
V x2 = x * x;
return static_cast<V>(((((a[7] * x2 + a[5]) * x2 + a[3]) * x2 + a[1]) * x + ((a[6] * x2 + a[4]) * x2 + a[2]) * x2 + a[0]) / ((((b[7] * x2 + b[5]) * x2 + b[3]) * x2 + b[1]) * x + ((b[6] * x2 + b[4]) * x2 + b[2]) * x2 + b[0]));
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
return static_cast<V>(((((a[0] * z2 + a[2]) * z2 + a[4]) * z2 + a[6]) * z + ((a[1] * z2 + a[3]) * z2 + a[5]) * z2 + a[7]) / ((((b[0] * z2 + b[2]) * z2 + b[4]) * z2 + b[6]) * z + ((b[1] * z2 + b[3]) * z2 + b[5]) * z2 + b[7]));
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<9>*)
{
if(x <= 1)
{
V x2 = x * x;
return static_cast<V>(((((a[8] * x2 + a[6]) * x2 + a[4]) * x2 + a[2]) * x2 + a[0] + (((a[7] * x2 + a[5]) * x2 + a[3]) * x2 + a[1]) * x) / ((((b[8] * x2 + b[6]) * x2 + b[4]) * x2 + b[2]) * x2 + b[0] + (((b[7] * x2 + b[5]) * x2 + b[3]) * x2 + b[1]) * x));
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
return static_cast<V>(((((a[0] * z2 + a[2]) * z2 + a[4]) * z2 + a[6]) * z2 + a[8] + (((a[1] * z2 + a[3]) * z2 + a[5]) * z2 + a[7]) * z) / ((((b[0] * z2 + b[2]) * z2 + b[4]) * z2 + b[6]) * z2 + b[8] + (((b[1] * z2 + b[3]) * z2 + b[5]) * z2 + b[7]) * z));
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<10>*)
{
if(x <= 1)
{
V x2 = x * x;
return static_cast<V>((((((a[9] * x2 + a[7]) * x2 + a[5]) * x2 + a[3]) * x2 + a[1]) * x + (((a[8] * x2 + a[6]) * x2 + a[4]) * x2 + a[2]) * x2 + a[0]) / (((((b[9] * x2 + b[7]) * x2 + b[5]) * x2 + b[3]) * x2 + b[1]) * x + (((b[8] * x2 + b[6]) * x2 + b[4]) * x2 + b[2]) * x2 + b[0]));
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
return static_cast<V>((((((a[0] * z2 + a[2]) * z2 + a[4]) * z2 + a[6]) * z2 + a[8]) * z + (((a[1] * z2 + a[3]) * z2 + a[5]) * z2 + a[7]) * z2 + a[9]) / (((((b[0] * z2 + b[2]) * z2 + b[4]) * z2 + b[6]) * z2 + b[8]) * z + (((b[1] * z2 + b[3]) * z2 + b[5]) * z2 + b[7]) * z2 + b[9]));
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<11>*)
{
if(x <= 1)
{
V x2 = x * x;
return static_cast<V>((((((a[10] * x2 + a[8]) * x2 + a[6]) * x2 + a[4]) * x2 + a[2]) * x2 + a[0] + ((((a[9] * x2 + a[7]) * x2 + a[5]) * x2 + a[3]) * x2 + a[1]) * x) / (((((b[10] * x2 + b[8]) * x2 + b[6]) * x2 + b[4]) * x2 + b[2]) * x2 + b[0] + ((((b[9] * x2 + b[7]) * x2 + b[5]) * x2 + b[3]) * x2 + b[1]) * x));
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
return static_cast<V>((((((a[0] * z2 + a[2]) * z2 + a[4]) * z2 + a[6]) * z2 + a[8]) * z2 + a[10] + ((((a[1] * z2 + a[3]) * z2 + a[5]) * z2 + a[7]) * z2 + a[9]) * z) / (((((b[0] * z2 + b[2]) * z2 + b[4]) * z2 + b[6]) * z2 + b[8]) * z2 + b[10] + ((((b[1] * z2 + b[3]) * z2 + b[5]) * z2 + b[7]) * z2 + b[9]) * z));
}
}
}}}} // namespaces
#endif // include guard
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<doc>
<assembly>
<name>Microsoft.Practices.ServiceLocation</name>
</assembly>
<members>
<member name="T:Microsoft.Practices.ServiceLocation.ActivationException">
<summary>
The standard exception thrown when a ServiceLocator has an error in resolving an object.
</summary>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ActivationException.#ctor">
<summary>
Initializes a new instance of the <see cref="T:System.Exception" /> class.
</summary>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ActivationException.#ctor(System.String)">
<summary>
Initializes a new instance of the <see cref="T:System.Exception" /> class with a specified error message.
</summary>
<param name="message">
The message that describes the error.
</param>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ActivationException.#ctor(System.String,System.Exception)">
<summary>
Initializes a new instance of the <see cref="T:System.Exception" /> class with a specified error message and a reference to the inner exception that is the cause of this exception.
</summary>
<param name="message">
The error message that explains the reason for the exception.
</param>
<param name="innerException">
The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.
</param>
</member>
<member name="T:Microsoft.Practices.ServiceLocation.IServiceLocator">
<summary>
The generic Service Locator interface. This interface is used
to retrieve services (instances identified by type and optional
name) from a container.
</summary>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetInstance(System.Type)">
<summary>
Get an instance of the given <paramref name="serviceType"/>.
</summary>
<param name="serviceType">Type of object requested.</param>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is an error resolving
the service instance.</exception>
<returns>The requested service instance.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetInstance(System.Type,System.String)">
<summary>
Get an instance of the given named <paramref name="serviceType"/>.
</summary>
<param name="serviceType">Type of object requested.</param>
<param name="key">Name the object was registered with.</param>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is an error resolving
the service instance.</exception>
<returns>The requested service instance.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetAllInstances(System.Type)">
<summary>
Get all instances of the given <paramref name="serviceType"/> currently
registered in the container.
</summary>
<param name="serviceType">Type of object requested.</param>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
the service instance.</exception>
<returns>A sequence of instances of the requested <paramref name="serviceType"/>.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetInstance``1">
<summary>
Get an instance of the given <typeparamref name="TService"/>.
</summary>
<typeparam name="TService">Type of object requested.</typeparam>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
the service instance.</exception>
<returns>The requested service instance.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetInstance``1(System.String)">
<summary>
Get an instance of the given named <typeparamref name="TService"/>.
</summary>
<typeparam name="TService">Type of object requested.</typeparam>
<param name="key">Name the object was registered with.</param>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
the service instance.</exception>
<returns>The requested service instance.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetAllInstances``1">
<summary>
Get all instances of the given <typeparamref name="TService"/> currently
registered in the container.
</summary>
<typeparam name="TService">Type of object requested.</typeparam>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
the service instance.</exception>
<returns>A sequence of instances of the requested <typeparamref name="TService"/>.</returns>
</member>
<member name="T:Microsoft.Practices.ServiceLocation.Properties.Resources">
<summary>
A strongly-typed resource class, for looking up localized strings, etc.
</summary>
</member>
<member name="P:Microsoft.Practices.ServiceLocation.Properties.Resources.ResourceManager">
<summary>
Returns the cached ResourceManager instance used by this class.
</summary>
</member>
<member name="P:Microsoft.Practices.ServiceLocation.Properties.Resources.Culture">
<summary>
Overrides the current thread's CurrentUICulture property for all
resource lookups using this strongly typed resource class.
</summary>
</member>
<member name="P:Microsoft.Practices.ServiceLocation.Properties.Resources.ActivateAllExceptionMessage">
<summary>
Looks up a localized string similar to Activation error occured while trying to get all instances of type {0}.
</summary>
</member>
<member name="P:Microsoft.Practices.ServiceLocation.Properties.Resources.ActivationExceptionMessage">
<summary>
Looks up a localized string similar to Activation error occured while trying to get instance of type {0}, key "{1}".
</summary>
</member>
<member name="T:Microsoft.Practices.ServiceLocation.ServiceLocator">
<summary>
This class provides the ambient container for this application. If your
framework defines such an ambient container, use ServiceLocator.Current
to get it.
</summary>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocator.SetLocatorProvider(Microsoft.Practices.ServiceLocation.ServiceLocatorProvider)">
<summary>
Set the delegate that is used to retrieve the current container.
</summary>
<param name="newProvider">Delegate that, when called, will return
the current ambient container.</param>
</member>
<member name="P:Microsoft.Practices.ServiceLocation.ServiceLocator.Current">
<summary>
The current ambient container.
</summary>
</member>
<member name="T:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase">
<summary>
This class is a helper that provides a default implementation
for most of the methods of <see cref="T:Microsoft.Practices.ServiceLocation.IServiceLocator"/>.
</summary>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetService(System.Type)">
<summary>
Implementation of <see cref="M:System.IServiceProvider.GetService(System.Type)"/>.
</summary>
<param name="serviceType">The requested service.</param>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is an error in resolving the service instance.</exception>
<returns>The requested object.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(System.Type)">
<summary>
Get an instance of the given <paramref name="serviceType"/>.
</summary>
<param name="serviceType">Type of object requested.</param>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is an error resolving
the service instance.</exception>
<returns>The requested service instance.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(System.Type,System.String)">
<summary>
Get an instance of the given named <paramref name="serviceType"/>.
</summary>
<param name="serviceType">Type of object requested.</param>
<param name="key">Name the object was registered with.</param>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is an error resolving
the service instance.</exception>
<returns>The requested service instance.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetAllInstances(System.Type)">
<summary>
Get all instances of the given <paramref name="serviceType"/> currently
registered in the container.
</summary>
<param name="serviceType">Type of object requested.</param>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
the service instance.</exception>
<returns>A sequence of instances of the requested <paramref name="serviceType"/>.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance``1">
<summary>
Get an instance of the given <typeparamref name="TService"/>.
</summary>
<typeparam name="TService">Type of object requested.</typeparam>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
the service instance.</exception>
<returns>The requested service instance.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance``1(System.String)">
<summary>
Get an instance of the given named <typeparamref name="TService"/>.
</summary>
<typeparam name="TService">Type of object requested.</typeparam>
<param name="key">Name the object was registered with.</param>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
the service instance.</exception>
<returns>The requested service instance.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetAllInstances``1">
<summary>
Get all instances of the given <typeparamref name="TService"/> currently
registered in the container.
</summary>
<typeparam name="TService">Type of object requested.</typeparam>
<exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
the service instance.</exception>
<returns>A sequence of instances of the requested <typeparamref name="TService"/>.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.DoGetInstance(System.Type,System.String)">
<summary>
When implemented by inheriting classes, this method will do the actual work of resolving
the requested service instance.
</summary>
<param name="serviceType">Type of instance requested.</param>
<param name="key">Name of registered service you want. May be null.</param>
<returns>The requested service instance.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.DoGetAllInstances(System.Type)">
<summary>
When implemented by inheriting classes, this method will do the actual work of
resolving all the requested service instances.
</summary>
<param name="serviceType">Type of service requested.</param>
<returns>Sequence of service instance objects.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.FormatActivationExceptionMessage(System.Exception,System.Type,System.String)">
<summary>
Format the exception message for use in an <see cref="T:Microsoft.Practices.ServiceLocation.ActivationException"/>
that occurs while resolving a single service.
</summary>
<param name="actualException">The actual exception thrown by the implementation.</param>
<param name="serviceType">Type of service requested.</param>
<param name="key">Name requested.</param>
<returns>The formatted exception message string.</returns>
</member>
<member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.FormatActivateAllExceptionMessage(System.Exception,System.Type)">
<summary>
Format the exception message for use in an <see cref="T:Microsoft.Practices.ServiceLocation.ActivationException"/>
that occurs while resolving multiple service instances.
</summary>
<param name="actualException">The actual exception thrown by the implementation.</param>
<param name="serviceType">Type of service requested.</param>
<returns>The formatted exception message string.</returns>
</member>
<member name="T:Microsoft.Practices.ServiceLocation.ServiceLocatorProvider">
<summary>
This delegate type is used to provide a method that will
return the current container. Used with the <see cref="T:Microsoft.Practices.ServiceLocation.ServiceLocator"/>
static accessor class.
</summary>
<returns>An <see cref="T:Microsoft.Practices.ServiceLocation.IServiceLocator"/>.</returns>
</member>
</members>
</doc>
| {
"pile_set_name": "Github"
} |
using Exercism.CSharp.Output;
namespace Exercism.CSharp.Exercises.Generators
{
public class DifferenceOfSquares : GeneratorExercise
{
protected override void UpdateTestMethod(TestMethod testMethod)
{
testMethod.TestedMethod = $"Calculate{testMethod.TestedMethod}";
}
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include "gtest/gtest.h"
GTEST_API_ int main(int argc, char **argv) {
std::cout << "Running main() from gtest_main.cc\n";
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>DataTables example - DOM positioning</title>
<link rel="stylesheet" type="text/css" href="../../media/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="../resources/syntax/shCore.css">
<link rel="stylesheet" type="text/css" href="../resources/demo.css">
<style type="text/css" class="init">
</style>
<script type="text/javascript" language="javascript" src="../../media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="../../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" src="../resources/syntax/shCore.js"></script>
<script type="text/javascript" language="javascript" src="../resources/demo.js"></script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example').dataTable( {
"dom": '<"top"i>rt<"bottom"flp><"clear">'
} );
} );
</script>
</head>
<body class="dt-example">
<div class="container">
<section>
<h1>DataTables example <span>DOM positioning</span></h1>
<div class="info">
<p>When customising DataTables for your own usage, you might find that the default position of the
feature elements (filter input etc) is not quite to your liking. To address this issue DataTables takes
inspiration from the CSS 3 Advanced Layout Module and provides the <a href=
"//datatables.net/reference/option/dom"><code class="option" title=
"DataTables initialisation option">dom<span>DT</span></code></a> initialisation parameter which can be
set to indicate where you which particular features to appear in the DOM. You can also specify
<code>div</code> wrapping containers (with an id and / or class) to provide complete layout
flexibility.</p>
<p>Each HTML control element presented by DataTables is denoted by a single character in the <a href=
"//datatables.net/reference/option/dom"><code class="option" title=
"DataTables initialisation option">dom<span>DT</span></code></a> option. For example the <code>l</code>
option is used for the <code>L</code>ength changing input option.</p>
<p>The built-in options available are:</p>
<ul class="markdown">
<li><code>l</code> - <code>L</code>ength changing</li>
<li><code>f</code> - <code>F</code>iltering input</li>
<li><code>t</code> - The <code>T</code>able!</li>
<li><code>i</code> - <code>I</code>nformation</li>
<li><code>p</code> - <code>P</code>agination</li>
<li><code>r</code> - p<code>R</code>ocessing</li>
<li><code><</code> and <code>></code> - div elements</li>
<li><code><"#id"</code> and <code>></code> - div with an id</li>
<li><code><"class"</code> and <code>></code> - div with a class</li>
<li><code><"#id.class"</code> and <code>></code> - div with an id and class</li>
</ul>
<p>Example 1:</p>
<pre>
<code class="multiline"><"wrapper"flipt>
</code>
</pre>
<p>This results in the following DOM structure:</p>
<pre>
<code class="multiline"><div class="wrapper">
{ filter }
{ length }
{ info }
{ paging }
{ table }
</div>
</code>
</pre>
<p>Example 2:</p>
<pre>
<code class="multiline"><lf<t>ip>
</code>
</pre>
<p>This results in the following DOM structure:</p>
<pre>
<code class="multiline"><div>
{ length }
{ filter }
<div>
{ table }
</div>
{ info }
{ paging }
</div>
</code>
</pre>
<p>All options (with the exception of the <code>t</code> (table) option can be specified multiple
times, for if you want to show the same control multiple times (pagination at the top and bottom of the
table for example).</p>
<p>Furthermore, note that additional <a href="//datatables.net/reference/option/dom"><code class=
"option" title="DataTables initialisation option">dom<span>DT</span></code></a> options can be added to
DataTables through the use of plug-ins.</p>
<p>In the example below, the table information is moved to the top of the table, and all the
interaction elements to the bottom, each wrapper in a container <code>div</code>.</p>
</div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>2012/12/02</td>
<td>$372,000</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>2012/08/06</td>
<td>$137,500</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>2010/10/14</td>
<td>$327,900</td>
</tr>
<tr>
<td>Colleen Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>2009/09/15</td>
<td>$205,500</td>
</tr>
<tr>
<td>Sonya Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>2008/12/13</td>
<td>$103,600</td>
</tr>
<tr>
<td>Jena Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>2008/12/19</td>
<td>$90,560</td>
</tr>
<tr>
<td>Quinn Flynn</td>
<td>Support Lead</td>
<td>Edinburgh</td>
<td>22</td>
<td>2013/03/03</td>
<td>$342,000</td>
</tr>
<tr>
<td>Charde Marshall</td>
<td>Regional Director</td>
<td>San Francisco</td>
<td>36</td>
<td>2008/10/16</td>
<td>$470,600</td>
</tr>
<tr>
<td>Haley Kennedy</td>
<td>Senior Marketing Designer</td>
<td>London</td>
<td>43</td>
<td>2012/12/18</td>
<td>$313,500</td>
</tr>
<tr>
<td>Tatyana Fitzpatrick</td>
<td>Regional Director</td>
<td>London</td>
<td>19</td>
<td>2010/03/17</td>
<td>$385,750</td>
</tr>
<tr>
<td>Michael Silva</td>
<td>Marketing Designer</td>
<td>London</td>
<td>66</td>
<td>2012/11/27</td>
<td>$198,500</td>
</tr>
<tr>
<td>Paul Byrd</td>
<td>Chief Financial Officer (CFO)</td>
<td>New York</td>
<td>64</td>
<td>2010/06/09</td>
<td>$725,000</td>
</tr>
<tr>
<td>Gloria Little</td>
<td>Systems Administrator</td>
<td>New York</td>
<td>59</td>
<td>2009/04/10</td>
<td>$237,500</td>
</tr>
<tr>
<td>Bradley Greer</td>
<td>Software Engineer</td>
<td>London</td>
<td>41</td>
<td>2012/10/13</td>
<td>$132,000</td>
</tr>
<tr>
<td>Dai Rios</td>
<td>Personnel Lead</td>
<td>Edinburgh</td>
<td>35</td>
<td>2012/09/26</td>
<td>$217,500</td>
</tr>
<tr>
<td>Jenette Caldwell</td>
<td>Development Lead</td>
<td>New York</td>
<td>30</td>
<td>2011/09/03</td>
<td>$345,000</td>
</tr>
<tr>
<td>Yuri Berry</td>
<td>Chief Marketing Officer (CMO)</td>
<td>New York</td>
<td>40</td>
<td>2009/06/25</td>
<td>$675,000</td>
</tr>
<tr>
<td>Caesar Vance</td>
<td>Pre-Sales Support</td>
<td>New York</td>
<td>21</td>
<td>2011/12/12</td>
<td>$106,450</td>
</tr>
<tr>
<td>Doris Wilder</td>
<td>Sales Assistant</td>
<td>Sidney</td>
<td>23</td>
<td>2010/09/20</td>
<td>$85,600</td>
</tr>
<tr>
<td>Angelica Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009/10/09</td>
<td>$1,200,000</td>
</tr>
<tr>
<td>Gavin Joyce</td>
<td>Developer</td>
<td>Edinburgh</td>
<td>42</td>
<td>2010/12/22</td>
<td>$92,575</td>
</tr>
<tr>
<td>Jennifer Chang</td>
<td>Regional Director</td>
<td>Singapore</td>
<td>28</td>
<td>2010/11/14</td>
<td>$357,650</td>
</tr>
<tr>
<td>Brenden Wagner</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>28</td>
<td>2011/06/07</td>
<td>$206,850</td>
</tr>
<tr>
<td>Fiona Green</td>
<td>Chief Operating Officer (COO)</td>
<td>San Francisco</td>
<td>48</td>
<td>2010/03/11</td>
<td>$850,000</td>
</tr>
<tr>
<td>Shou Itou</td>
<td>Regional Marketing</td>
<td>Tokyo</td>
<td>20</td>
<td>2011/08/14</td>
<td>$163,000</td>
</tr>
<tr>
<td>Michelle House</td>
<td>Integration Specialist</td>
<td>Sidney</td>
<td>37</td>
<td>2011/06/02</td>
<td>$95,400</td>
</tr>
<tr>
<td>Suki Burks</td>
<td>Developer</td>
<td>London</td>
<td>53</td>
<td>2009/10/22</td>
<td>$114,500</td>
</tr>
<tr>
<td>Prescott Bartlett</td>
<td>Technical Author</td>
<td>London</td>
<td>27</td>
<td>2011/05/07</td>
<td>$145,000</td>
</tr>
<tr>
<td>Gavin Cortez</td>
<td>Team Leader</td>
<td>San Francisco</td>
<td>22</td>
<td>2008/10/26</td>
<td>$235,500</td>
</tr>
<tr>
<td>Martena Mccray</td>
<td>Post-Sales support</td>
<td>Edinburgh</td>
<td>46</td>
<td>2011/03/09</td>
<td>$324,050</td>
</tr>
<tr>
<td>Unity Butler</td>
<td>Marketing Designer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/12/09</td>
<td>$85,675</td>
</tr>
<tr>
<td>Howard Hatfield</td>
<td>Office Manager</td>
<td>San Francisco</td>
<td>51</td>
<td>2008/12/16</td>
<td>$164,500</td>
</tr>
<tr>
<td>Hope Fuentes</td>
<td>Secretary</td>
<td>San Francisco</td>
<td>41</td>
<td>2010/02/12</td>
<td>$109,850</td>
</tr>
<tr>
<td>Vivian Harrell</td>
<td>Financial Controller</td>
<td>San Francisco</td>
<td>62</td>
<td>2009/02/14</td>
<td>$452,500</td>
</tr>
<tr>
<td>Timothy Mooney</td>
<td>Office Manager</td>
<td>London</td>
<td>37</td>
<td>2008/12/11</td>
<td>$136,200</td>
</tr>
<tr>
<td>Jackson Bradshaw</td>
<td>Director</td>
<td>New York</td>
<td>65</td>
<td>2008/09/26</td>
<td>$645,750</td>
</tr>
<tr>
<td>Olivia Liang</td>
<td>Support Engineer</td>
<td>Singapore</td>
<td>64</td>
<td>2011/02/03</td>
<td>$234,500</td>
</tr>
<tr>
<td>Bruno Nash</td>
<td>Software Engineer</td>
<td>London</td>
<td>38</td>
<td>2011/05/03</td>
<td>$163,500</td>
</tr>
<tr>
<td>Sakura Yamamoto</td>
<td>Support Engineer</td>
<td>Tokyo</td>
<td>37</td>
<td>2009/08/19</td>
<td>$139,575</td>
</tr>
<tr>
<td>Thor Walton</td>
<td>Developer</td>
<td>New York</td>
<td>61</td>
<td>2013/08/11</td>
<td>$98,540</td>
</tr>
<tr>
<td>Finn Camacho</td>
<td>Support Engineer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/07/07</td>
<td>$87,500</td>
</tr>
<tr>
<td>Serge Baldwin</td>
<td>Data Coordinator</td>
<td>Singapore</td>
<td>64</td>
<td>2012/04/09</td>
<td>$138,575</td>
</tr>
<tr>
<td>Zenaida Frank</td>
<td>Software Engineer</td>
<td>New York</td>
<td>63</td>
<td>2010/01/04</td>
<td>$125,250</td>
</tr>
<tr>
<td>Zorita Serrano</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>56</td>
<td>2012/06/01</td>
<td>$115,000</td>
</tr>
<tr>
<td>Jennifer Acosta</td>
<td>Junior Javascript Developer</td>
<td>Edinburgh</td>
<td>43</td>
<td>2013/02/01</td>
<td>$75,650</td>
</tr>
<tr>
<td>Cara Stevens</td>
<td>Sales Assistant</td>
<td>New York</td>
<td>46</td>
<td>2011/12/06</td>
<td>$145,600</td>
</tr>
<tr>
<td>Hermione Butler</td>
<td>Regional Director</td>
<td>London</td>
<td>47</td>
<td>2011/03/21</td>
<td>$356,250</td>
</tr>
<tr>
<td>Lael Greer</td>
<td>Systems Administrator</td>
<td>London</td>
<td>21</td>
<td>2009/02/27</td>
<td>$103,500</td>
</tr>
<tr>
<td>Jonas Alexander</td>
<td>Developer</td>
<td>San Francisco</td>
<td>30</td>
<td>2010/07/14</td>
<td>$86,500</td>
</tr>
<tr>
<td>Shad Decker</td>
<td>Regional Director</td>
<td>Edinburgh</td>
<td>51</td>
<td>2008/11/13</td>
<td>$183,000</td>
</tr>
<tr>
<td>Michael Bruce</td>
<td>Javascript Developer</td>
<td>Singapore</td>
<td>29</td>
<td>2011/06/27</td>
<td>$183,000</td>
</tr>
<tr>
<td>Donna Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
</tr>
</tbody>
</table>
<ul class="tabs">
<li class="active">Javascript</li>
<li>HTML</li>
<li>CSS</li>
<li>Ajax</li>
<li>Server-side script</li>
</ul>
<div class="tabs">
<div class="js">
<p>The Javascript shown below is used to initialise the table shown in this
example:</p><code class="multiline brush: js;">$(document).ready(function() {
$('#example').dataTable( {
"dom": '<"top"i>rt<"bottom"flp><"clear">'
} );
} );</code>
<p>In addition to the above code, the following Javascript library files are loaded for use in this
example:</p>
<ul>
<li><a href="../../media/js/jquery.js">../../media/js/jquery.js</a></li>
<li><a href="../../media/js/jquery.dataTables.js">../../media/js/jquery.dataTables.js</a></li>
</ul>
</div>
<div class="table">
<p>The HTML shown below is the raw HTML table element, before it has been enhanced by
DataTables:</p>
</div>
<div class="css">
<div>
<p>This example uses a little bit of additional CSS beyond what is loaded from the library
files (below), in order to correctly display the table. The additional CSS used is shown
below:</p><code class="multiline brush: js;"></code>
</div>
<p>The following CSS library files are loaded for use in this example to provide the styling of the
table:</p>
<ul>
<li><a href=
"../../media/css/jquery.dataTables.css">../../media/css/jquery.dataTables.css</a></li>
</ul>
</div>
<div class="ajax">
<p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data
will update automatically as any additional data is loaded.</p>
</div>
<div class="php">
<p>The script used to perform the server-side processing for this table is shown below. Please note
that this is just an example script using PHP. Server-side processing scripts can be written in any
language, using <a href="//datatables.net/manual/server-side">the protocol described in the
DataTables documentation</a>.</p>
</div>
</div>
</section>
</div>
<section>
<div class="footer">
<div class="gradient"></div>
<div class="liner">
<h2>Other examples</h2>
<div class="toc">
<div class="toc-group">
<h3><a href="./index.html">Basic initialisation</a></h3>
<ul class="toc active">
<li><a href="./zero_configuration.html">Zero configuration</a></li>
<li><a href="./filter_only.html">Feature enable / disable</a></li>
<li><a href="./table_sorting.html">Default ordering (sorting)</a></li>
<li><a href="./multi_col_sort.html">Multi-column ordering</a></li>
<li><a href="./multiple_tables.html">Multiple tables</a></li>
<li><a href="./hidden_columns.html">Hidden columns</a></li>
<li><a href="./complex_header.html">Complex headers (rowspan and colspan)</a></li>
<li class="active"><a href="./dom.html">DOM positioning</a></li>
<li><a href="./flexible_width.html">Flexible table width</a></li>
<li><a href="./state_save.html">State saving</a></li>
<li><a href="./alt_pagination.html">Alternative pagination</a></li>
<li><a href="./scroll_y.html">Scroll - vertical</a></li>
<li><a href="./scroll_x.html">Scroll - horizontal</a></li>
<li><a href="./scroll_xy.html">Scroll - horizontal and vertical</a></li>
<li><a href="./scroll_y_theme.html">Scroll - vertical with jQuery UI ThemeRoller</a></li>
<li><a href="./comma-decimal.html">Language - Comma decimal place</a></li>
<li><a href="./language.html">Language options</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../advanced_init/index.html">Advanced initialisation</a></h3>
<ul class="toc">
<li><a href="../advanced_init/events_live.html">DOM / jQuery events</a></li>
<li><a href="../advanced_init/dt_events.html">DataTables events</a></li>
<li><a href="../advanced_init/column_render.html">Column rendering</a></li>
<li><a href="../advanced_init/length_menu.html">Page length options</a></li>
<li><a href="../advanced_init/dom_multiple_elements.html">Multiple table control
elements</a></li>
<li><a href="../advanced_init/complex_header.html">Complex headers (rowspan /
colspan)</a></li>
<li><a href="../advanced_init/html5-data-attributes.html">HTML5 data-* attributes</a></li>
<li><a href="../advanced_init/language_file.html">Language file</a></li>
<li><a href="../advanced_init/defaults.html">Setting defaults</a></li>
<li><a href="../advanced_init/row_callback.html">Row created callback</a></li>
<li><a href="../advanced_init/row_grouping.html">Row grouping</a></li>
<li><a href="../advanced_init/footer_callback.html">Footer callback</a></li>
<li><a href="../advanced_init/dom_toolbar.html">Custom toolbar elements</a></li>
<li><a href="../advanced_init/sort_direction_control.html">Order direction sequence
control</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../styling/index.html">Styling</a></h3>
<ul class="toc">
<li><a href="../styling/display.html">Base style</a></li>
<li><a href="../styling/no-classes.html">Base style - no styling classes</a></li>
<li><a href="../styling/cell-border.html">Base style - cell borders</a></li>
<li><a href="../styling/compact.html">Base style - compact</a></li>
<li><a href="../styling/hover.html">Base style - hover</a></li>
<li><a href="../styling/order-column.html">Base style - order-column</a></li>
<li><a href="../styling/row-border.html">Base style - row borders</a></li>
<li><a href="../styling/stripe.html">Base style - stripe</a></li>
<li><a href="../styling/bootstrap.html">Bootstrap</a></li>
<li><a href="../styling/foundation.html">Foundation</a></li>
<li><a href="../styling/jqueryUI.html">jQuery UI ThemeRoller</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../data_sources/index.html">Data sources</a></h3>
<ul class="toc">
<li><a href="../data_sources/dom.html">HTML (DOM) sourced data</a></li>
<li><a href="../data_sources/ajax.html">Ajax sourced data</a></li>
<li><a href="../data_sources/js_array.html">Javascript sourced data</a></li>
<li><a href="../data_sources/server_side.html">Server-side processing</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../api/index.html">API</a></h3>
<ul class="toc">
<li><a href="../api/add_row.html">Add rows</a></li>
<li><a href="../api/multi_filter.html">Individual column searching (text inputs)</a></li>
<li><a href="../api/multi_filter_select.html">Individual column searching (select
inputs)</a></li>
<li><a href="../api/highlight.html">Highlighting rows and columns</a></li>
<li><a href="../api/row_details.html">Child rows (show extra / detailed
information)</a></li>
<li><a href="../api/select_row.html">Row selection (multiple rows)</a></li>
<li><a href="../api/select_single_row.html">Row selection and deletion (single
row)</a></li>
<li><a href="../api/form.html">Form inputs</a></li>
<li><a href="../api/counter_columns.html">Index column</a></li>
<li><a href="../api/show_hide.html">Show / hide columns dynamically</a></li>
<li><a href="../api/api_in_init.html">Using API in callbacks</a></li>
<li><a href="../api/tabs_and_scrolling.html">Scrolling and jQuery UI tabs</a></li>
<li><a href="../api/regex.html">Search API (regular expressions)</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../ajax/index.html">Ajax</a></h3>
<ul class="toc">
<li><a href="../ajax/simple.html">Ajax data source (arrays)</a></li>
<li><a href="../ajax/objects.html">Ajax data source (objects)</a></li>
<li><a href="../ajax/deep.html">Nested object data (objects)</a></li>
<li><a href="../ajax/objects_subarrays.html">Nested object data (arrays)</a></li>
<li><a href="../ajax/orthogonal-data.html">Orthogonal data</a></li>
<li><a href="../ajax/null_data_source.html">Generated content for a column</a></li>
<li><a href="../ajax/custom_data_property.html">Custom data source property</a></li>
<li><a href="../ajax/custom_data_flat.html">Flat array data source</a></li>
<li><a href="../ajax/defer_render.html">Deferred rendering for speed</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../server_side/index.html">Server-side</a></h3>
<ul class="toc">
<li><a href="../server_side/simple.html">Server-side processing</a></li>
<li><a href="../server_side/custom_vars.html">Custom HTTP variables</a></li>
<li><a href="../server_side/post.html">POST data</a></li>
<li><a href="../server_side/ids.html">Automatic addition of row ID attributes</a></li>
<li><a href="../server_side/object_data.html">Object data source</a></li>
<li><a href="../server_side/row_details.html">Row details</a></li>
<li><a href="../server_side/select_rows.html">Row selection</a></li>
<li><a href="../server_side/jsonp.html">JSONP data source for remote domains</a></li>
<li><a href="../server_side/defer_loading.html">Deferred loading of data</a></li>
<li><a href="../server_side/pipeline.html">Pipelining data to reduce Ajax calls for
paging</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../plug-ins/index.html">Plug-ins</a></h3>
<ul class="toc">
<li><a href="../plug-ins/api.html">API plug-in methods</a></li>
<li><a href="../plug-ins/sorting_auto.html">Ordering plug-ins (with type
detection)</a></li>
<li><a href="../plug-ins/sorting_manual.html">Ordering plug-ins (no type
detection)</a></li>
<li><a href="../plug-ins/range_filtering.html">Custom filtering - range search</a></li>
<li><a href="../plug-ins/dom_sort.html">Live DOM ordering</a></li>
</ul>
</div>
</div>
<div class="epilogue">
<p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full
information about its API properties and methods.<br>
Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and
<a href="http://www.datatables.net/plug-ins">plug-ins</a> which extend the capabilities of
DataTables.</p>
<p class="copyright">DataTables designed and created by <a href=
"http://www.sprymedia.co.uk">SpryMedia Ltd</a> © 2007-2014<br>
DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p>
</div>
</div>
</div>
</section>
</body>
</html> | {
"pile_set_name": "Github"
} |
---
fixes:
- |
Fix prometheus-openstack-exporter to use CA certificate.
| {
"pile_set_name": "Github"
} |
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
//----------------------------------------------------------------------
/*!\file
*
* \author Lars Pfotzer <[email protected]>
* \date 2010-02-08
*
* \brief Contains icl_core::thread::RWLockImplWin32
*
* \b icl_core::thread::RWLockImplWin32
*/
//----------------------------------------------------------------------
#ifndef ICL_CORE_THREAD_RWLOCK_IMPL_WIN32_H_INCLUDED
#define ICL_CORE_THREAD_RWLOCK_IMPL_WIN32_H_INCLUDED
#include <vector>
#include <Windows.h>
#include "icl_core_thread/RWLockImpl.h"
#include "icl_core_thread/Mutex.h"
namespace icl_core {
namespace thread {
class RWLockImplWin32 : public RWLockImpl, protected virtual icl_core::Noncopyable
{
public:
RWLockImplWin32();
virtual ~RWLockImplWin32();
virtual bool readLock();
virtual bool readLock(const TimeStamp& timeout);
virtual bool readLock(const TimeSpan& timeout);
virtual bool tryReadLock();
virtual bool writeLock();
virtual bool writeLock(const TimeStamp& timeout);
virtual bool writeLock(const TimeSpan& timeout);
virtual bool tryWriteLock();
virtual void unlock();
private:
bool readLock(DWORD timeout);
bool writeLock(DWORD timeout);
Mutex m_reader_access_lock;
HANDLE m_reader_mutex_event;
HANDLE m_writer_mutex;
int m_number_of_writer;
int m_number_of_reader;
int m_writer_pid;
std::vector<int> m_reader_pid;
};
}
}
#endif
| {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
namespace Tailspin.Surveys.Data.DTOs
{
public class UserSurveysDTO
{
public ICollection<SurveySummaryDTO> Published { get; set; }
public ICollection<SurveySummaryDTO> Own { get; set; }
public ICollection<SurveySummaryDTO> Contribute { get; set; }
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2012 Igalia S.L
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
// FFTFrame implementation using the GStreamer FFT library.
#include "config.h"
#if USE(WEBAUDIO_GSTREAMER)
#include "FFTFrame.h"
#include "VectorMath.h"
#include <wtf/FastMalloc.h>
#include <wtf/StdLibExtras.h>
namespace {
size_t unpackedFFTDataSize(unsigned fftSize)
{
return fftSize / 2 + 1;
}
} // anonymous namespace
namespace WebCore {
// Normal constructor: allocates for a given fftSize.
FFTFrame::FFTFrame(unsigned fftSize)
: m_FFTSize(fftSize)
, m_log2FFTSize(static_cast<unsigned>(log2(fftSize)))
, m_complexData(std::make_unique<GstFFTF32Complex[]>(unpackedFFTDataSize(m_FFTSize)))
, m_realData(unpackedFFTDataSize(m_FFTSize))
, m_imagData(unpackedFFTDataSize(m_FFTSize))
{
int fftLength = gst_fft_next_fast_length(m_FFTSize);
m_fft = gst_fft_f32_new(fftLength, FALSE);
m_inverseFft = gst_fft_f32_new(fftLength, TRUE);
}
// Creates a blank/empty frame (interpolate() must later be called).
FFTFrame::FFTFrame()
: m_FFTSize(0)
, m_log2FFTSize(0)
{
int fftLength = gst_fft_next_fast_length(m_FFTSize);
m_fft = gst_fft_f32_new(fftLength, FALSE);
m_inverseFft = gst_fft_f32_new(fftLength, TRUE);
}
// Copy constructor.
FFTFrame::FFTFrame(const FFTFrame& frame)
: m_FFTSize(frame.m_FFTSize)
, m_log2FFTSize(frame.m_log2FFTSize)
, m_complexData(std::make_unique<GstFFTF32Complex[]>(unpackedFFTDataSize(m_FFTSize)))
, m_realData(unpackedFFTDataSize(frame.m_FFTSize))
, m_imagData(unpackedFFTDataSize(frame.m_FFTSize))
{
int fftLength = gst_fft_next_fast_length(m_FFTSize);
m_fft = gst_fft_f32_new(fftLength, FALSE);
m_inverseFft = gst_fft_f32_new(fftLength, TRUE);
// Copy/setup frame data.
memcpy(realData(), frame.realData(), sizeof(float) * unpackedFFTDataSize(m_FFTSize));
memcpy(imagData(), frame.imagData(), sizeof(float) * unpackedFFTDataSize(m_FFTSize));
}
void FFTFrame::initialize()
{
}
void FFTFrame::cleanup()
{
}
FFTFrame::~FFTFrame()
{
if (!m_fft)
return;
gst_fft_f32_free(m_fft);
m_fft = 0;
gst_fft_f32_free(m_inverseFft);
m_inverseFft = 0;
}
void FFTFrame::multiply(const FFTFrame& frame)
{
FFTFrame& frame1 = *this;
FFTFrame& frame2 = const_cast<FFTFrame&>(frame);
float* realP1 = frame1.realData();
float* imagP1 = frame1.imagData();
const float* realP2 = frame2.realData();
const float* imagP2 = frame2.imagData();
size_t size = unpackedFFTDataSize(m_FFTSize);
VectorMath::zvmul(realP1, imagP1, realP2, imagP2, realP1, imagP1, size);
// Scale accounts the peculiar scaling of vecLib on the Mac.
// This ensures the right scaling all the way back to inverse FFT.
// FIXME: if we change the scaling on the Mac then this scale
// factor will need to change too.
float scale = 0.5f;
VectorMath::vsmul(realP1, 1, &scale, realP1, 1, size);
VectorMath::vsmul(imagP1, 1, &scale, imagP1, 1, size);
}
void FFTFrame::doFFT(const float* data)
{
gst_fft_f32_fft(m_fft, data, m_complexData.get());
// Scale the frequency domain data to match vecLib's scale factor
// on the Mac. FIXME: if we change the definition of FFTFrame to
// eliminate this scale factor then this code will need to change.
// Also, if this loop turns out to be hot then we should use SSE
// or other intrinsics to accelerate it.
float scaleFactor = 2;
float* imagData = m_imagData.data();
float* realData = m_realData.data();
for (unsigned i = 0; i < unpackedFFTDataSize(m_FFTSize); ++i) {
imagData[i] = m_complexData[i].i * scaleFactor;
realData[i] = m_complexData[i].r * scaleFactor;
}
}
void FFTFrame::doInverseFFT(float* data)
{
// Merge the real and imaginary vectors to complex vector.
float* realData = m_realData.data();
float* imagData = m_imagData.data();
for (size_t i = 0; i < unpackedFFTDataSize(m_FFTSize); ++i) {
m_complexData[i].i = imagData[i];
m_complexData[i].r = realData[i];
}
gst_fft_f32_inverse_fft(m_inverseFft, m_complexData.get(), data);
// Scale so that a forward then inverse FFT yields exactly the original data.
const float scaleFactor = 1.0 / (2 * m_FFTSize);
VectorMath::vsmul(data, 1, &scaleFactor, data, 1, m_FFTSize);
}
float* FFTFrame::realData() const
{
return const_cast<float*>(m_realData.data());
}
float* FFTFrame::imagData() const
{
return const_cast<float*>(m_imagData.data());
}
} // namespace WebCore
#endif // USE(WEBAUDIO_GSTREAMER)
| {
"pile_set_name": "Github"
} |
#tb 0: 1/25
#media_type 0: video
#codec_id 0: rawvideo
#dimensions 0: 832x480
#sar 0: 0/1
0, 0, 0, 1, 599040, 0x8087662a
0, 1, 1, 1, 599040, 0x5278d8db
0, 2, 2, 1, 599040, 0x73c74090
0, 3, 3, 1, 599040, 0xde0d8317
0, 4, 4, 1, 599040, 0xd9d4c26c
0, 5, 5, 1, 599040, 0x603a10bd
0, 6, 6, 1, 599040, 0xa91e9b91
0, 7, 7, 1, 599040, 0x73567e6a
0, 8, 8, 1, 599040, 0x67912cc6
0, 9, 9, 1, 599040, 0x98d3fb2c
0, 10, 10, 1, 599040, 0x50c6d7fc
0, 11, 11, 1, 599040, 0x8ae23020
0, 12, 12, 1, 599040, 0x9eaa976f
0, 13, 13, 1, 599040, 0x3cadf6c0
0, 14, 14, 1, 599040, 0x7d498902
0, 15, 15, 1, 599040, 0x525decac
0, 16, 16, 1, 599040, 0x081485cc
0, 17, 17, 1, 599040, 0x3fd6ba7a
0, 18, 18, 1, 599040, 0x8bbbaa4c
0, 19, 19, 1, 599040, 0x9e60a407
0, 20, 20, 1, 599040, 0x394becb9
0, 21, 21, 1, 599040, 0x068dffb5
0, 22, 22, 1, 599040, 0x531fd221
0, 23, 23, 1, 599040, 0x3aa6922e
0, 24, 24, 1, 599040, 0x089d2456
0, 25, 25, 1, 599040, 0x7c432995
0, 26, 26, 1, 599040, 0x3693613d
0, 27, 27, 1, 599040, 0x8b6d902f
0, 28, 28, 1, 599040, 0x7c9a947b
0, 29, 29, 1, 599040, 0x51d9e4c6
0, 30, 30, 1, 599040, 0xdc7f62f3
0, 31, 31, 1, 599040, 0x9da6cba0
0, 32, 32, 1, 599040, 0x1bef8581
0, 33, 33, 1, 599040, 0xc19c4211
0, 34, 34, 1, 599040, 0x7824188e
0, 35, 35, 1, 599040, 0xd0511050
0, 36, 36, 1, 599040, 0x39d93e78
0, 37, 37, 1, 599040, 0x1e0dc88e
0, 38, 38, 1, 599040, 0x2cd7522e
0, 39, 39, 1, 599040, 0x538928a5
0, 40, 40, 1, 599040, 0x95549fb2
0, 41, 41, 1, 599040, 0x1f57d5c1
0, 42, 42, 1, 599040, 0xc99fa8c6
0, 43, 43, 1, 599040, 0x567f4e7e
0, 44, 44, 1, 599040, 0x23d3d54f
0, 45, 45, 1, 599040, 0xe8f74d97
0, 46, 46, 1, 599040, 0xd2b03a4d
0, 47, 47, 1, 599040, 0xe59c4faf
0, 48, 48, 1, 599040, 0x46da921d
0, 49, 49, 1, 599040, 0x7a344fa3
0, 50, 50, 1, 599040, 0xbc736fd4
0, 51, 51, 1, 599040, 0xfe5c362c
0, 52, 52, 1, 599040, 0x115ed271
0, 53, 53, 1, 599040, 0x3c4913fc
0, 54, 54, 1, 599040, 0x1e1f8114
0, 55, 55, 1, 599040, 0x08c06e58
0, 56, 56, 1, 599040, 0x599f07f6
0, 57, 57, 1, 599040, 0xc922a0c9
0, 58, 58, 1, 599040, 0xc77b5201
0, 59, 59, 1, 599040, 0x4c2cde6d
| {
"pile_set_name": "Github"
} |
# Codeception Test Suite Configuration
# suite for functional (integration) tests.
# emulate web requests and make application process them.
# Include one of framework modules (Symfony2, Yii2, Laravel4) to use it.
class_name: FunctionalTester
modules:
enabled: [Filesystem, FunctionalHelper]
| {
"pile_set_name": "Github"
} |
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* checkParam.js
*
* The files given as arguments on the command line are assumed to be
* Java source code files. This program checks to see that the @param
* tags in the documentation comments match with the parameters for
* the associated Java methods.
* <p>
* Any errors found are reported.
*
*/
defineClass("File")
// Return true if "str" ends with "suffix".
function stringEndsWith(str, suffix) {
return str.substring(str.length - suffix.length) == suffix;
}
/**
* Perform processing once the end of a documentation comment is seen.
*
* Look for a parameter list following the end of the comment and
* collect the parameters and compare to the @param entries.
* Report any discrepancies.
* @param f the current file
* @param a an array of parameters from @param comments
* @param line the string containing the comment end (in case the
* parameters are on the same line)
*/
function processCommentEnd(f, a, line) {
while (line != null && !line.match(/\(/))
line = f.readLine();
while (line != null && !line.match(/\)/))
line += f.readLine();
if (line === null)
return;
var m = line.match(/\(([^\)]+)\)/);
var args = m ? m[1].split(",") : [];
if (a.length != args.length) {
print('"' + f.name +
'"; line ' + f.lineNumber +
' mismatch: had a different number' +
' of @param entries and parameters.');
} else {
for (var i=0; i < a.length; i++) {
if (!stringEndsWith(args[i], a[i])) {
print('"' + f.name +
'"; line ' + f.lineNumber +
' mismatch: had "' + a[i] +
'" and "' + args[i] + '".');
break;
}
}
}
}
/**
* Process the given file, looking for mismatched @param lists and
* parameter lists.
* @param f the file to process
*/
function processFile(f) {
var line;
var m;
var i = 0;
var a = [];
outer:
while ((line = f.readLine()) != null) {
if (line.match(/@param/)) {
while (m = line.match(/@param[ ]+([^ ]+)/)) {
a[i++] = m[1];
line = f.readLine();
if (line == null)
break outer;
}
}
if (i != 0 && line.match(/\*\//)) {
processCommentEnd(f, a, line);
i = 0;
a = [];
}
}
if (i != 0) {
print('"' + f.name +
'"; line ' + f.lineNumber +
' missing parameters at end of file.');
}
}
// main script: process each file in arguments list
for (var i=0; i < arguments.length; i++) {
var filename = String(arguments[i]);
print("Checking " + filename + "...");
var f = new File(filename);
processFile(f);
}
print("done.");
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Character View -->
<declare-styleable name="CharacterView">
<attr name="character" format="string"/>
<attr name="characterTextColor" format="color"/>
<attr name="backgroundRoundAsCircle" format="boolean"/>
<attr name="backgroundColor" format="color"/>
<attr name="backgroundRadius" format="dimension"/>
<attr name="characterPadding" format="dimension"/>
</declare-styleable>
</resources> | {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function (format) {};
if (__DEV__) {
validateFormat = function (format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant; | {
"pile_set_name": "Github"
} |
package im.actor.sdk.util.images.sources;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import im.actor.sdk.util.images.common.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by ex3ndr on 20.09.14.
*/
public class UriSource extends ImageSource {
private Uri uri;
private Context context;
public UriSource(Uri uri, Context context) {
this.uri = uri;
this.context = context;
}
@Override
protected ImageMetadata loadMetadata() throws ImageLoadException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inTempStorage = WorkCache.BITMAP_TMP.get();
InputStream is = null;
try {
is = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(is, null, o);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new ImageLoadException("Unable to load image from stream");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
if (o.outWidth == 0 || o.outHeight == 0) {
throw new ImageLoadException("BitmapFactory.decodeFile: unable to load file");
}
ImageFormat format = ImageFormat.UNKNOWN;
if ("image/jpeg".equals(o.outMimeType) || "image/jpg".equals(o.outMimeType)) {
format = ImageFormat.JPEG;
} else if ("image/gif".equals(o.outMimeType)) {
format = ImageFormat.GIF;
} else if ("image/bmp".equals(o.outMimeType)) {
format = ImageFormat.BMP;
} else if ("image/webp".equals(o.outMimeType)) {
format = ImageFormat.WEBP;
}
int w = o.outWidth;
int h = o.outHeight;
return new ImageMetadata(w, h, 0, format);
}
@Override
public Bitmap loadBitmap() throws ImageLoadException {
return loadBitmap(1);
}
@Override
public Bitmap loadBitmap(int scale) throws ImageLoadException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inScaled = false;
o.inTempStorage = WorkCache.BITMAP_TMP.get();
o.inSampleSize = scale;
o.inPreferredConfig = Bitmap.Config.ARGB_8888;
if (Build.VERSION.SDK_INT >= 10) {
o.inPreferQualityOverSpeed = true;
}
if (Build.VERSION.SDK_INT >= 11) {
o.inMutable = true;
}
InputStream is = null;
Bitmap res;
try {
is = context.getContentResolver().openInputStream(uri);
res = BitmapFactory.decodeStream(is, null, o);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new ImageLoadException("Unable to load image from stream");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
if (res == null) {
throw new ImageLoadException("BitmapFactory.decodeFile return null");
}
return res;
}
@Override
public ReuseResult loadBitmap(Bitmap reuse) throws ImageLoadException {
if (Build.VERSION.SDK_INT < 11) {
throw new ImageLoadException("Bitmap reuse not available before HONEYCOMB");
}
BitmapFactory.Options o = new BitmapFactory.Options();
o.inScaled = false;
o.inTempStorage = WorkCache.BITMAP_TMP.get();
o.inPreferQualityOverSpeed = true;
o.inBitmap = reuse;
o.inMutable = true;
o.inPreferredConfig = Bitmap.Config.ARGB_8888;
o.inSampleSize = 1;
InputStream is = null;
Bitmap res;
try {
is = context.getContentResolver().openInputStream(uri);
res = BitmapFactory.decodeStream(is, null, o);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new ImageLoadException("Unable to load image from stream");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
if (res == null) {
throw new ImageLoadException("BitmapFactory.decodeFile return null");
}
return new ReuseResult(res, true);
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2010 The Go 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 cmplx
import "math"
// The original C code, the long comment, and the constants
// below are from http://netlib.sandia.gov/cephes/c9x-complex/clog.c.
// The go code is a simplified version of the original C.
//
// Cephes Math Library Release 2.8: June, 2000
// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
//
// The readme file at http://netlib.sandia.gov/cephes/ says:
// Some software in this archive may be from the book _Methods and
// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster
// International, 1989) or from the Cephes Mathematical Library, a
// commercial product. In either event, it is copyrighted by the author.
// What you see here may be used freely but it comes with no support or
// guarantee.
//
// The two known misprints in the book are repaired here in the
// source listings for the gamma function and the incomplete beta
// integral.
//
// Stephen L. Moshier
// [email protected]
// Complex circular arc sine
//
// DESCRIPTION:
//
// Inverse complex sine:
// 2
// w = -i clog( iz + csqrt( 1 - z ) ).
//
// casin(z) = -i casinh(iz)
//
// ACCURACY:
//
// Relative error:
// arithmetic domain # trials peak rms
// DEC -10,+10 10100 2.1e-15 3.4e-16
// IEEE -10,+10 30000 2.2e-14 2.7e-15
// Larger relative error can be observed for z near zero.
// Also tested by csin(casin(z)) = z.
// Asin returns the inverse sine of x.
func Asin(x complex128) complex128 {
switch re, im := real(x), imag(x); {
case im == 0 && math.Abs(re) <= 1:
return complex(math.Asin(re), im)
case re == 0 && math.Abs(im) <= 1:
return complex(re, math.Asinh(im))
case math.IsNaN(im):
switch {
case re == 0:
return complex(re, math.NaN())
case math.IsInf(re, 0):
return complex(math.NaN(), re)
default:
return NaN()
}
case math.IsInf(im, 0):
switch {
case math.IsNaN(re):
return x
case math.IsInf(re, 0):
return complex(math.Copysign(math.Pi/4, re), im)
default:
return complex(math.Copysign(0, re), im)
}
case math.IsInf(re, 0):
return complex(math.Copysign(math.Pi/2, re), math.Copysign(re, im))
}
ct := complex(-imag(x), real(x)) // i * x
xx := x * x
x1 := complex(1-real(xx), -imag(xx)) // 1 - x*x
x2 := Sqrt(x1) // x2 = sqrt(1 - x*x)
w := Log(ct + x2)
return complex(imag(w), -real(w)) // -i * w
}
// Asinh returns the inverse hyperbolic sine of x.
func Asinh(x complex128) complex128 {
switch re, im := real(x), imag(x); {
case im == 0 && math.Abs(re) <= 1:
return complex(math.Asinh(re), im)
case re == 0 && math.Abs(im) <= 1:
return complex(re, math.Asin(im))
case math.IsInf(re, 0):
switch {
case math.IsInf(im, 0):
return complex(re, math.Copysign(math.Pi/4, im))
case math.IsNaN(im):
return x
default:
return complex(re, math.Copysign(0.0, im))
}
case math.IsNaN(re):
switch {
case im == 0:
return x
case math.IsInf(im, 0):
return complex(im, re)
default:
return NaN()
}
case math.IsInf(im, 0):
return complex(math.Copysign(im, re), math.Copysign(math.Pi/2, im))
}
xx := x * x
x1 := complex(1+real(xx), imag(xx)) // 1 + x*x
return Log(x + Sqrt(x1)) // log(x + sqrt(1 + x*x))
}
// Complex circular arc cosine
//
// DESCRIPTION:
//
// w = arccos z = PI/2 - arcsin z.
//
// ACCURACY:
//
// Relative error:
// arithmetic domain # trials peak rms
// DEC -10,+10 5200 1.6e-15 2.8e-16
// IEEE -10,+10 30000 1.8e-14 2.2e-15
// Acos returns the inverse cosine of x.
func Acos(x complex128) complex128 {
w := Asin(x)
return complex(math.Pi/2-real(w), -imag(w))
}
// Acosh returns the inverse hyperbolic cosine of x.
func Acosh(x complex128) complex128 {
if x == 0 {
return complex(0, math.Copysign(math.Pi/2, imag(x)))
}
w := Acos(x)
if imag(w) <= 0 {
return complex(-imag(w), real(w)) // i * w
}
return complex(imag(w), -real(w)) // -i * w
}
// Complex circular arc tangent
//
// DESCRIPTION:
//
// If
// z = x + iy,
//
// then
// 1 ( 2x )
// Re w = - arctan(-----------) + k PI
// 2 ( 2 2)
// (1 - x - y )
//
// ( 2 2)
// 1 (x + (y+1) )
// Im w = - log(------------)
// 4 ( 2 2)
// (x + (y-1) )
//
// Where k is an arbitrary integer.
//
// catan(z) = -i catanh(iz).
//
// ACCURACY:
//
// Relative error:
// arithmetic domain # trials peak rms
// DEC -10,+10 5900 1.3e-16 7.8e-18
// IEEE -10,+10 30000 2.3e-15 8.5e-17
// The check catan( ctan(z) ) = z, with |x| and |y| < PI/2,
// had peak relative error 1.5e-16, rms relative error
// 2.9e-17. See also clog().
// Atan returns the inverse tangent of x.
func Atan(x complex128) complex128 {
switch re, im := real(x), imag(x); {
case im == 0:
return complex(math.Atan(re), im)
case re == 0 && math.Abs(im) <= 1:
return complex(re, math.Atanh(im))
case math.IsInf(im, 0) || math.IsInf(re, 0):
if math.IsNaN(re) {
return complex(math.NaN(), math.Copysign(0, im))
}
return complex(math.Copysign(math.Pi/2, re), math.Copysign(0, im))
case math.IsNaN(re) || math.IsNaN(im):
return NaN()
}
x2 := real(x) * real(x)
a := 1 - x2 - imag(x)*imag(x)
if a == 0 {
return NaN()
}
t := 0.5 * math.Atan2(2*real(x), a)
w := reducePi(t)
t = imag(x) - 1
b := x2 + t*t
if b == 0 {
return NaN()
}
t = imag(x) + 1
c := (x2 + t*t) / b
return complex(w, 0.25*math.Log(c))
}
// Atanh returns the inverse hyperbolic tangent of x.
func Atanh(x complex128) complex128 {
z := complex(-imag(x), real(x)) // z = i * x
z = Atan(z)
return complex(imag(z), -real(z)) // z = -i * z
}
| {
"pile_set_name": "Github"
} |
var dep = require('../src/dep');
describe("app", function() {
it("dep can be called", function() {
var result = dep("nothing");
expect(result).toBe("doSomething with nothing");
});
});
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* "Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
* Reserved. This file contains Original Code and/or Modifications of
* Original Code as defined in and that are subject to the Apple Public
* Source License Version 1.0 (the 'License'). You may not use this file
* except in compliance with the License. Please obtain a copy of the
* License at http://www.apple.com/publicsource and read it before using
* this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License."
*
* @APPLE_LICENSE_HEADER_END@
*/
/* $OpenBSD: yplog.h,v 1.3 1996/05/30 09:53:04 deraadt Exp $ */
/*
* Copyright (c) 1994 Mats O Jansson <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _YPLOG_H_
#define _YPLOG_H_
#include <stdarg.h>
__BEGIN_DECLS
void yplog __P((const char *, ...));
void vyplog __P((const char *, va_list));
void ypopenlog __P((void));
void ypcloselog __P((void));
__END_DECLS
#endif /* !_YPLOG_H_ */
| {
"pile_set_name": "Github"
} |
i18n - french resources
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="github.nisrulz.recyclerview.MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_fruits"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
| {
"pile_set_name": "Github"
} |
/*!
* content-type
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
*
* parameter = token "=" ( token / quoted-string )
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
* / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
* / DIGIT / ALPHA
* ; any VCHAR, except delimiters
* quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
* qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
* obs-text = %x80-FF
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
*/
var paramRegExp = /; *([!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) */g
var textRegExp = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/
var tokenRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/
/**
* RegExp to match quoted-pair in RFC 7230 sec 3.2.6
*
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
* obs-text = %x80-FF
*/
var qescRegExp = /\\([\u000b\u0020-\u00ff])/g
/**
* RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6
*/
var quoteRegExp = /([\\"])/g
/**
* RegExp to match type in RFC 6838
*
* media-type = type "/" subtype
* type = token
* subtype = token
*/
var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+\/[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/
/**
* Module exports.
* @public
*/
exports.format = format
exports.parse = parse
/**
* Format object to media type.
*
* @param {object} obj
* @return {string}
* @public
*/
function format(obj) {
if (!obj || typeof obj !== 'object') {
throw new TypeError('argument obj is required')
}
var parameters = obj.parameters
var type = obj.type
if (!type || !typeRegExp.test(type)) {
throw new TypeError('invalid type')
}
var string = type
// append parameters
if (parameters && typeof parameters === 'object') {
var param
var params = Object.keys(parameters).sort()
for (var i = 0; i < params.length; i++) {
param = params[i]
if (!tokenRegExp.test(param)) {
throw new TypeError('invalid parameter name')
}
string += '; ' + param + '=' + qstring(parameters[param])
}
}
return string
}
/**
* Parse media type to object.
*
* @param {string|object} string
* @return {Object}
* @public
*/
function parse(string) {
if (!string) {
throw new TypeError('argument string is required')
}
if (typeof string === 'object') {
// support req/res-like objects as argument
string = getcontenttype(string)
if (typeof string !== 'string') {
throw new TypeError('content-type header is missing from object');
}
}
if (typeof string !== 'string') {
throw new TypeError('argument string is required to be a string')
}
var index = string.indexOf(';')
var type = index !== -1
? string.substr(0, index).trim()
: string.trim()
if (!typeRegExp.test(type)) {
throw new TypeError('invalid media type')
}
var key
var match
var obj = new ContentType(type.toLowerCase())
var value
paramRegExp.lastIndex = index
while (match = paramRegExp.exec(string)) {
if (match.index !== index) {
throw new TypeError('invalid parameter format')
}
index += match[0].length
key = match[1].toLowerCase()
value = match[2]
if (value[0] === '"') {
// remove quotes and escapes
value = value
.substr(1, value.length - 2)
.replace(qescRegExp, '$1')
}
obj.parameters[key] = value
}
if (index !== -1 && index !== string.length) {
throw new TypeError('invalid parameter format')
}
return obj
}
/**
* Get content-type from req/res objects.
*
* @param {object}
* @return {Object}
* @private
*/
function getcontenttype(obj) {
if (typeof obj.getHeader === 'function') {
// res-like
return obj.getHeader('content-type')
}
if (typeof obj.headers === 'object') {
// req-like
return obj.headers && obj.headers['content-type']
}
}
/**
* Quote a string if necessary.
*
* @param {string} val
* @return {string}
* @private
*/
function qstring(val) {
var str = String(val)
// no need to quote tokens
if (tokenRegExp.test(str)) {
return str
}
if (str.length > 0 && !textRegExp.test(str)) {
throw new TypeError('invalid parameter value')
}
return '"' + str.replace(quoteRegExp, '\\$1') + '"'
}
/**
* Class to represent a content type.
* @private
*/
function ContentType(type) {
this.parameters = Object.create(null)
this.type = type
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<title>The page you were looking for doesn't exist (404)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/404.html -->
<div class="dialog">
<h1>The page you were looking for doesn't exist.</h1>
<p>You may have mistyped the address or the page may have moved.</p>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
package com.sk89q.craftbook.mechanics.dispenser;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.Directional;
import org.bukkit.block.data.type.Dispenser;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
public class Cannon extends Recipe {
public Cannon(Material[] recipe) {
super(recipe);
}
public Cannon() {
super(new Material[] {
Material.FIRE_CHARGE, Material.GUNPOWDER, Material.FIRE_CHARGE,
Material.GUNPOWDER, Material.TNT, Material.GUNPOWDER,
Material.FIRE_CHARGE, Material.GUNPOWDER, Material.FIRE_CHARGE
});
}
@Override
public boolean doAction(Block block, ItemStack item, Vector velocity, BlockDispenseEvent event) {
Directional disp = (Directional) block.getBlockData();
BlockFace face = disp.getFacing();
Location location = block.getRelative(face).getLocation().add(0.5, 0.5, 0.5);
TNTPrimed a = (TNTPrimed) block.getWorld().spawnEntity(location, EntityType.PRIMED_TNT);
a.setVelocity(velocity.normalize().multiply(2));
return true;
}
} | {
"pile_set_name": "Github"
} |
var $export = require('./$.export');
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: require('./$.string-repeat')
}); | {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example oAuth Flow</title>
</head>
<body>
<a href="/do-auth"><img src="http://xerodev.wpengine.com/wp-content/uploads/2011/09/connect_xero_button_blue1.png"></a>
</body>
</html>
| {
"pile_set_name": "Github"
} |
dataset:
observation_fieldnames:
- index
- sentence
- lemma_sentence
- upos_sentence
- xpos_sentence
- morph
- head_indices
- governance_relations
- secondary_relations
- extra_info
- embeddings
corpus:
root: /u/scr/nlp/johnhew/data/lstm-word-order/ptb-wsj-sd/
train_path: ptb3-wsj-train.conllx
dev_path: ptb3-wsj-dev.conllx
test_path: ptb3-wsj-test.conllx
embeddings:
type: subword #{token,subword}
root: /u/scr/nlp/johnhew/data/lstm-word-order/ptb-wsj-sd/
train_path: raw.train.bertlarge-layers.hdf5
dev_path: raw.dev.bertlarge-layers.hdf5
test_path: raw.test.bertlarge-layers.hdf5
batch_size: 20
model:
hidden_dim: 1024 # ELMo hidden dim
#embedding_dim: 1024 # ELMo word embedding dim
model_type: BERT-disk # BERT-disk, ELMo-disk,
use_disk: True
model_layer: 19 # BERT-base: {1,...,12}; ELMo: {1,2,3}
probe:
task_signature: word_pair # word, word_pair
task_name: parse-distance
maximum_rank: 1024
psd_parameters: True
diagonal: False
params_path: predictor.params
probe_training:
epochs: 40
loss: L1
reporting:
root: /u/scr/nlp/johnhew/results/naacl19/
observation_paths:
train_path: train.observations
dev_path: dev.observations
test_path: test.observations
prediction_paths:
train_path: train.predictions
dev_path: dev.predictions
test_path: test.predictions
reporting_methods:
- spearmanr
- image_examples
- uuas
| {
"pile_set_name": "Github"
} |
//
// detail/reactive_socket_accept_op.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (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 ASIO_DETAIL_REACTIVE_SOCKET_ACCEPT_OP_HPP
#define ASIO_DETAIL_REACTIVE_SOCKET_ACCEPT_OP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/buffer_sequence_adapter.hpp"
#include "asio/detail/fenced_block.hpp"
#include "asio/detail/memory.hpp"
#include "asio/detail/reactor_op.hpp"
#include "asio/detail/socket_holder.hpp"
#include "asio/detail/socket_ops.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename Socket, typename Protocol>
class reactive_socket_accept_op_base : public reactor_op
{
public:
reactive_socket_accept_op_base(socket_type socket,
socket_ops::state_type state, Socket& peer, const Protocol& protocol,
typename Protocol::endpoint* peer_endpoint, func_type complete_func)
: reactor_op(&reactive_socket_accept_op_base::do_perform, complete_func),
socket_(socket),
state_(state),
peer_(peer),
protocol_(protocol),
peer_endpoint_(peer_endpoint),
addrlen_(peer_endpoint ? peer_endpoint->capacity() : 0)
{
}
static status do_perform(reactor_op* base)
{
reactive_socket_accept_op_base* o(
static_cast<reactive_socket_accept_op_base*>(base));
socket_type new_socket = invalid_socket;
status result = socket_ops::non_blocking_accept(o->socket_,
o->state_, o->peer_endpoint_ ? o->peer_endpoint_->data() : 0,
o->peer_endpoint_ ? &o->addrlen_ : 0, o->ec_, new_socket)
? done : not_done;
o->new_socket_.reset(new_socket);
ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_accept", o->ec_));
return result;
}
void do_assign()
{
if (new_socket_.get() != invalid_socket)
{
if (peer_endpoint_)
peer_endpoint_->resize(addrlen_);
peer_.assign(protocol_, new_socket_.get(), ec_);
if (!ec_)
new_socket_.release();
}
}
private:
socket_type socket_;
socket_ops::state_type state_;
socket_holder new_socket_;
Socket& peer_;
Protocol protocol_;
typename Protocol::endpoint* peer_endpoint_;
std::size_t addrlen_;
};
template <typename Socket, typename Protocol, typename Handler>
class reactive_socket_accept_op :
public reactive_socket_accept_op_base<Socket, Protocol>
{
public:
ASIO_DEFINE_HANDLER_PTR(reactive_socket_accept_op);
reactive_socket_accept_op(socket_type socket,
socket_ops::state_type state, Socket& peer, const Protocol& protocol,
typename Protocol::endpoint* peer_endpoint, Handler& handler)
: reactive_socket_accept_op_base<Socket, Protocol>(socket, state, peer,
protocol, peer_endpoint, &reactive_socket_accept_op::do_complete),
handler_(ASIO_MOVE_CAST(Handler)(handler))
{
handler_work<Handler>::start(handler_);
}
static void do_complete(void* owner, operation* base,
const asio::error_code& /*ec*/,
std::size_t /*bytes_transferred*/)
{
// Take ownership of the handler object.
reactive_socket_accept_op* o(static_cast<reactive_socket_accept_op*>(base));
ptr p = { asio::detail::addressof(o->handler_), o, o };
handler_work<Handler> w(o->handler_);
// On success, assign new connection to peer socket object.
if (owner)
o->do_assign();
ASIO_HANDLER_COMPLETION((*o));
// Make a copy of the handler so that the memory can be deallocated before
// the upcall is made. Even if we're not about to make an upcall, a
// sub-object of the handler may be the true owner of the memory associated
// with the handler. Consequently, a local copy of the handler is required
// to ensure that any owning sub-object remains valid until after we have
// deallocated the memory here.
detail::binder1<Handler, asio::error_code>
handler(o->handler_, o->ec_);
p.h = asio::detail::addressof(handler.handler_);
p.reset();
// Make the upcall if required.
if (owner)
{
fenced_block b(fenced_block::half);
ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_));
w.complete(handler, handler.handler_);
ASIO_HANDLER_INVOCATION_END;
}
}
private:
Handler handler_;
};
#if defined(ASIO_HAS_MOVE)
template <typename Protocol, typename Handler>
class reactive_socket_move_accept_op :
private Protocol::socket,
public reactive_socket_accept_op_base<typename Protocol::socket, Protocol>
{
public:
ASIO_DEFINE_HANDLER_PTR(reactive_socket_move_accept_op);
reactive_socket_move_accept_op(io_context& ioc, socket_type socket,
socket_ops::state_type state, const Protocol& protocol,
typename Protocol::endpoint* peer_endpoint, Handler& handler)
: Protocol::socket(ioc),
reactive_socket_accept_op_base<typename Protocol::socket, Protocol>(
socket, state, *this, protocol, peer_endpoint,
&reactive_socket_move_accept_op::do_complete),
handler_(ASIO_MOVE_CAST(Handler)(handler))
{
handler_work<Handler>::start(handler_);
}
static void do_complete(void* owner, operation* base,
const asio::error_code& /*ec*/,
std::size_t /*bytes_transferred*/)
{
// Take ownership of the handler object.
reactive_socket_move_accept_op* o(
static_cast<reactive_socket_move_accept_op*>(base));
ptr p = { asio::detail::addressof(o->handler_), o, o };
handler_work<Handler> w(o->handler_);
// On success, assign new connection to peer socket object.
if (owner)
o->do_assign();
ASIO_HANDLER_COMPLETION((*o));
// Make a copy of the handler so that the memory can be deallocated before
// the upcall is made. Even if we're not about to make an upcall, a
// sub-object of the handler may be the true owner of the memory associated
// with the handler. Consequently, a local copy of the handler is required
// to ensure that any owning sub-object remains valid until after we have
// deallocated the memory here.
detail::move_binder2<Handler,
asio::error_code, typename Protocol::socket>
handler(0, ASIO_MOVE_CAST(Handler)(o->handler_), o->ec_,
ASIO_MOVE_CAST(typename Protocol::socket)(*o));
p.h = asio::detail::addressof(handler.handler_);
p.reset();
// Make the upcall if required.
if (owner)
{
fenced_block b(fenced_block::half);
ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, "..."));
w.complete(handler, handler.handler_);
ASIO_HANDLER_INVOCATION_END;
}
}
private:
Handler handler_;
};
#endif // defined(ASIO_HAS_MOVE)
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_DETAIL_REACTIVE_SOCKET_ACCEPT_OP_HPP
| {
"pile_set_name": "Github"
} |
#ifndef MULTIVERSO_TIMER_H_
#define MULTIVERSO_TIMER_H_
#include <chrono>
#include <string>
namespace multiverso {
class Timer {
public:
Timer();
// Restart the timer
void Start();
// Get elapsed milliseconds since last Timer::Start
double elapse();
private:
using Clock = std::chrono::high_resolution_clock;
using TimePoint = Clock::time_point;
TimePoint start_point_;
};
} // namespace multiverso
#endif // MULTIVERSO_TIMER_H_
| {
"pile_set_name": "Github"
} |
package mutate
import (
"encoding/json"
"reflect"
"strings"
"testing"
"gotest.tools/assert"
"sigs.k8s.io/controller-runtime/pkg/log"
)
func TestMeetConditions_NoAnchor(t *testing.T) {
overlayRaw := []byte(`
{
"subsets":[
{
"ports":[
{
"name":"secure-connection",
"port":444,
"protocol":"UDP"
}
]
}
]
}`)
var overlay interface{}
err := json.Unmarshal(overlayRaw, &overlay)
assert.Assert(t, reflect.DeepEqual(err, nil))
_, err = meetConditions(log.Log, nil, overlay)
assert.Assert(t, reflect.DeepEqual(err, overlayError{}))
}
func TestMeetConditions_conditionalAnchorOnMap(t *testing.T) {
resourceRaw := []byte(`
{
"apiVersion":"v1",
"kind":"Endpoints",
"metadata":{
"name":"test-endpoint",
"labels":{
"label":"test"
}
},
"subsets":[
{
"addresses":[
{
"ip":"192.168.10.171"
}
],
"ports":[
{
"name":"secure-connection",
"port":443,
"protocol":"TCP"
}
]
}
]
}`)
overlayRaw := []byte(`
{
"subsets":[
{
"(ports)":[
{
"name":"secure-connection",
"port":444,
"protocol":"UDP"
}
]
}
]
}`)
var resource, overlay interface{}
err := json.Unmarshal(resourceRaw, &resource)
assert.NilError(t, err)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Assert(t, !reflect.DeepEqual(err, overlayError{}))
overlayRaw = []byte(`
{
"(subsets)":[
{
"ports":[
{
"name":"secure-connection",
"port":443,
"(protocol)":"TCP"
}
]
}
]
}`)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, overlayerr := meetConditions(log.Log, resource, overlay)
assert.Assert(t, reflect.DeepEqual(overlayerr, overlayError{}))
}
func TestMeetConditions_DifferentTypes(t *testing.T) {
resourceRaw := []byte(`
{
"apiVersion": "v1",
"kind": "Endpoints",
"metadata": {
"name": "test-endpoint"
},
"subsets": {
"addresses": {
"ip": "192.168.10.171"
}
}
}`)
overlayRaw := []byte(`
{
"subsets":[
{
"ports":[
{
"(name)":"secure-connection",
"port":444,
"protocol":"UDP"
}
]
}
]
}`)
var resource, overlay interface{}
err := json.Unmarshal(resourceRaw, &resource)
assert.NilError(t, err)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
// anchor exist
_, err = meetConditions(log.Log, resource, overlay)
assert.Assert(t, strings.Contains(err.Error(), "element type mismatch at path /subsets/"))
}
func TestMeetConditions_anchosInSameObject(t *testing.T) {
resourceRaw := []byte(`
{
"apiVersion":"v1",
"kind":"Endpoints",
"metadata":{
"name":"test-endpoint",
"labels":{
"label":"test"
}
},
"subsets":[
{
"addresses":[
{
"ip":"192.168.10.171"
}
],
"ports":[
{
"name":"secure-connection",
"port":443,
"protocol":"TCP"
}
]
}
]
}`)
overlayRaw := []byte(`
{
"subsets":[
{
"ports":[
{
"(name)":"secure-connection",
"(port)":444,
"protocol":"UDP"
}
]
}
]
}`)
var resource, overlay interface{}
err := json.Unmarshal(resourceRaw, &resource)
assert.NilError(t, err)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Error(t, err, "[overlayError:0] Failed validating value 443 with overlay 444")
}
func TestMeetConditions_anchorOnPeer(t *testing.T) {
resourceRaw := []byte(`
{
"apiVersion":"v1",
"kind":"Endpoints",
"metadata":{
"name":"test-endpoint",
"labels":{
"label":"test"
}
},
"subsets":[
{
"addresses":[
{
"ip":"192.168.10.171"
}
],
"ports":[
{
"name":"secure-connection",
"port":443,
"protocol":"TCP"
}
]
}
]
}`)
overlayRaw := []byte(`
{
"subsets":[
{
"addresses":[
{
"(ip)":"192.168.10.171"
}
],
"ports":[
{
"(name)":"secure-connection",
"port":444,
"protocol":"UDP"
}
]
}
]
}`)
var resource, overlay interface{}
err := json.Unmarshal(resourceRaw, &resource)
assert.NilError(t, err)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Assert(t, reflect.DeepEqual(err, overlayError{}))
}
func TestMeetConditions_anchorsOnMetaAndSpec(t *testing.T) {
overlayRaw := []byte(`{
"spec": {
"template": {
"metadata": {
"labels": {
"(app)": "nginx"
}
},
"spec": {
"containers": [
{
"(image)": "*:latest",
"imagePullPolicy": "IfNotPresent",
"ports": [
{
"containerPort": 8080
}
]
}
]
}
}
}
}`)
resourceRaw := []byte(`{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"name": "nginx-deployment",
"labels": {
"app": "nginx"
}
},
"spec": {
"replicas": 1,
"selector": {
"matchLabels": {
"app": "nginx"
}
},
"template": {
"metadata": {
"labels": {
"app": "nginx"
}
},
"spec": {
"containers": [
{
"name": "nginx",
"image": "nginx:latest",
"ports": [
{
"containerPort": 80
}
]
},
{
"name": "ghost",
"image": "ghost:latest"
}
]
}
}
}
}`)
var resource, overlay interface{}
err := json.Unmarshal(resourceRaw, &resource)
assert.NilError(t, err)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Assert(t, reflect.DeepEqual(err, overlayError{}))
}
var resourceRawAnchorOnPeers = []byte(`{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"name": "psp-demo-unprivileged",
"labels": {
"app.type": "prod"
}
},
"spec": {
"replicas": 1,
"selector": {
"matchLabels": {
"app": "psp"
}
},
"template": {
"metadata": {
"labels": {
"app": "psp"
}
},
"spec": {
"securityContext": {
"runAsNonRoot": true
},
"containers": [
{
"name": "sec-ctx-unprivileged",
"image": "nginxinc/nginx-unprivileged",
"securityContext": {
"runAsNonRoot": true,
"allowPrivilegeEscalation": false
},
"env": [
{
"name": "ENV_KEY",
"value": "ENV_VALUE"
}
]
}
]
}
}
}
}`)
func TestMeetConditions_anchorsOnPeer_single(t *testing.T) {
overlayRaw := []byte(`{
"spec": {
"template": {
"spec": {
"containers": [
{
"(image)": "*/nginx-unprivileged",
"securityContext": {
"runAsNonRoot": true,
"allowPrivilegeEscalation": false
},
"env": [
{
"name": "ENV_KEY",
"value": "ENV_VALUE"
}
]
}
]
}
}
}
}`)
var resource, overlay interface{}
err := json.Unmarshal(resourceRawAnchorOnPeers, &resource)
assert.NilError(t, err)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Assert(t, reflect.DeepEqual(err, overlayError{}))
}
func TestMeetConditions_anchorsOnPeer_two(t *testing.T) {
overlayRaw := []byte(`{
"spec": {
"template": {
"spec": {
"containers": [
{
"(image)": "*/nginx-unprivileged",
"securityContext": {
"(runAsNonRoot)": false,
"allowPrivilegeEscalation": false
},
"env": [
{
"name": "ENV_KEY",
"value": "ENV_VALUE"
}
]
}
]
}
}
}
}`)
var resource, overlay interface{}
err := json.Unmarshal(resourceRawAnchorOnPeers, &resource)
assert.NilError(t, err)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Error(t, err, "[overlayError:0] Failed validating value true with overlay false")
overlayRaw = []byte(`{
"spec": {
"template": {
"spec": {
"containers": [
{
"(image)": "*/nginx-unprivileged",
"securityContext": {
"runAsNonRoot": true,
"allowPrivilegeEscalation": false
},
"env": [
{
"(name)": "ENV_KEY",
"value": "ENV_VALUE"
}
]
}
]
}
}
}
}`)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Assert(t, reflect.DeepEqual(err, overlayError{}))
overlayRaw = []byte(`{
"spec": {
"template": {
"spec": {
"containers": [
{
"image": "*/nginx-unprivileged",
"securityContext": {
"runAsNonRoot": true,
"(allowPrivilegeEscalation)": false
},
"env": [
{
"(name)": "ENV_KEY",
"value": "ENV_VALUE"
}
]
}
]
}
}
}
}`)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Assert(t, reflect.DeepEqual(err, overlayError{}))
}
func TestMeetConditions_anchorsOnPeer_multiple(t *testing.T) {
overlayRaw := []byte(`{
"spec": {
"template": {
"spec": {
"containers": [
{
"(image)": "*/nginx-unprivileged",
"securityContext": {
"(runAsNonRoot)": true,
"allowPrivilegeEscalation": false
},
"env": [
{
"(name)": "ENV_KEY",
"value": "ENV_VALUE"
}
]
}
]
}
}
}
}`)
var resource, overlay interface{}
err := json.Unmarshal(resourceRawAnchorOnPeers, &resource)
assert.NilError(t, err)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Assert(t, reflect.DeepEqual(err, overlayError{}))
overlayRaw = []byte(`{
"spec": {
"template": {
"spec": {
"containers": [
{
"(image)": "*/nginx-unprivileged",
"securityContext": {
"runAsNonRoot": true,
"(allowPrivilegeEscalation)": false
},
"env": [
{
"(name)": "ENV_KEY",
"value": "ENV_VALUE"
}
]
}
]
}
}
}
}`)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Assert(t, reflect.DeepEqual(err, overlayError{}))
overlayRaw = []byte(`{
"spec": {
"template": {
"spec": {
"containers": [
{
"(image)": "*/nginx-unprivileged",
"securityContext": {
"runAsNonRoot": true,
"(allowPrivilegeEscalation)": false
},
"(env)": [
{
"name": "ENV_KEY",
"value": "ENV_VALUE1"
}
]
}
]
}
}
}
}`)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
_, err = meetConditions(log.Log, resource, overlay)
assert.Error(t, err, "[overlayError:0] Failed validating value ENV_VALUE with overlay ENV_VALUE1")
}
func TestMeetConditions_AtleastOneExist(t *testing.T) {
overlayRaw := []byte(`
{
"metadata": {
"annotations": {
"+(cluster-autoscaler.kubernetes.io/safe-to-evict)": true
}
},
"spec": {
"volumes": [
{
"(emptyDir)": {}
}
]
}
}`)
// validate when resource has multiple same blocks
resourceRaw := []byte(`
{
"spec": {
"containers": [
{
"image": "k8s.gcr.io/test-webserver",
"name": "test-container",
"volumeMounts": [
{
"mountPath": "/cache",
"name": "cache-volume"
}
]
}
],
"volumes": [
{
"name": "cache-volume1",
"emptyDir": 1
},
{
"name": "cache-volume2",
"emptyDir": 2
},
{
"name": "cache-volume3",
"emptyDir": {}
}
]
}
}`)
var resource, overlay interface{}
err := json.Unmarshal(resourceRaw, &resource)
assert.NilError(t, err)
err = json.Unmarshal(overlayRaw, &overlay)
assert.NilError(t, err)
path, err := meetConditions(log.Log, resource, overlay)
assert.Assert(t, reflect.DeepEqual(err, overlayError{}))
assert.Assert(t, len(path) == 0)
}
| {
"pile_set_name": "Github"
} |
package com.github.czyzby.tests.reflected.widgets;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.util.highlight.BaseHighlighter;
import com.kotcrab.vis.ui.util.highlight.Highlight;
import com.kotcrab.vis.ui.widget.HighlightTextArea;
/**
* Mock-up {@link BaseHighlighter} implementation that does not color the text.
* @author MJ
*/
public class MockHighlighter extends BaseHighlighter {
@Override
public void process(HighlightTextArea textArea, Array<Highlight> highlights) {
// Does nothing.
}
}
| {
"pile_set_name": "Github"
} |
module.exports = {
"default": require("core-js/library"),
__esModule: true
};
| {
"pile_set_name": "Github"
} |
-- Quest: C:\QUESTS\WORKING\C0B10Y06.Qbn.
-- StartsBy: NPC
-- Questee: member
-- Questor: temple
-- Repute: 10
-- QuestId: 6
Messages: 12
Quest: C0B10Y06
DisplayName: The Expiatory Sacrifice
-- Message panels
QRC:
QuestorOffer: [1000]
<ce> They tell me that you quite loyal to
<ce> the temple. I need you perform a vital
<ce> task for us. %god has become angry
<ce> with us. You need not concern yourself
<ce> with why. Our only hope is to hold a
<ce> rite of atonement. We need _ingredient_
<ce> for the ceremony. My sources tell me
<ce> that some can be found in ___dungeon_.
<ce> Will you bring it to us?
RefuseQuest: [1001]
<ce> Your loyalty to the temple
<ce> is not what I thought it
<ce> was, %pcn.
AcceptQuest: [1002]
<ce> The ceremony must be held
<ce> within =traveltime_ days. The
<ce> temple will reward you
<ce> with _gold_ gold for this.
<ce> Only untainted _ingredient_
<ce> will do. %god's blessing
<ce> is upon you so that you
<ce> will know it when you
<ce> find it.
QuestComplete: [1004]
<ce> You have it? _ingredient_!
<ce> %god will be pacified.
<ce> You have done well. Here is
<ce> your reward.
RumorsDuringQuest: [1005]
Things have been rather ... tense around __qgiver_ lately.
<--->
There was supposedly an unauthorized orgy in __qgiver_.
<--->
Someone spoke %god's name backwards in a ceremony at __qgiver_.
RumorsPostfailure: [1006]
__qgiver_ is still out of favor with their god.
RumorsPostsuccess: [1007]
__qgiver_ is back in favor with their god.
QuestorPostsuccess: [1008]
You have pacified %god, %pct. Of course, how can I help you?
QuestorPostfailure: [1009]
While %god hates __qgiver_, I shall hate thee, %pct.
QuestLogEntry: [1010]
%qdt:
_qgiver_ of __qgiver_,
in ___qgiver_, told me that %g3 god was
angered. %g needs untainted
_ingredient_ from ___dungeon_
for a rite of atonement. It
must be in _qgiver_'s
hands at __qgiver_
within =traveltime_ days.
Message: 1011
<ce> This is it! I can feel the
<ce> purity of the _ingredient_.
<ce> Now to get it back to
<ce> _qgiver_.
-- Symbols used in the QRC file:
--
-- %g occurs 1 time.
-- %g3 occurs 1 time.
-- %god occurs 6 times.
-- %pcn occurs 2 times.
-- %pct occurs 18 times.
-- %qdt occurs 1 time.
-- =traveltime_ occurs 3 times.
-- ___dungeon_ occurs 4 times.
-- ___qgiver_ occurs 12 times.
-- _gold_ occurs 1 time.
-- _ingredient_ occurs 5 times.
-- _qgiver_ occurs 3 times.
QBN:
Item _ingredient_ organs
Item _gold_ gold
Person _qgiver_ group Questor male
Place _dungeon_ remote dungeon
Clock _traveltime_ 00:00 0 flag 17 range 0 2
-- Quest start-up:
place item _ingredient_ at _dungeon_
start timer _traveltime_
reveal _dungeon_
log 1010 step 0
_traveltime_ task:
end quest
_questdone_ task:
toting _ingredient_ and _qgiver_ clicked
give pc _gold_
end quest
_S.02_ task:
clicked item _ingredient_
say 1011
--illegal argument
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.config.annotation;
import java.util.Arrays;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.accept.FixedContentNegotiationStrategy;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.testfixture.servlet.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test fixture for {@link ContentNegotiationConfigurer} tests.
* @author Rossen Stoyanchev
*/
public class ContentNegotiationConfigurerTests {
private ContentNegotiationConfigurer configurer;
private NativeWebRequest webRequest;
private MockHttpServletRequest servletRequest;
@BeforeEach
public void setup() {
this.servletRequest = new MockHttpServletRequest();
this.webRequest = new ServletWebRequest(this.servletRequest);
this.configurer = new ContentNegotiationConfigurer(this.servletRequest.getServletContext());
}
@Test
public void defaultSettings() throws Exception {
ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
this.servletRequest.setRequestURI("/flower.gif");
assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).as("Should be able to resolve file extensions by default").isEqualTo(MediaType.IMAGE_GIF);
this.servletRequest.setRequestURI("/flower?format=gif");
this.servletRequest.addParameter("format", "gif");
assertThat(manager.resolveMediaTypes(this.webRequest)).as("Should not resolve request parameters by default").isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST);
this.servletRequest.setRequestURI("/flower");
this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE);
assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).as("Should resolve Accept header by default").isEqualTo(MediaType.IMAGE_GIF);
}
@Test
public void addMediaTypes() throws Exception {
this.configurer.mediaTypes(Collections.singletonMap("json", MediaType.APPLICATION_JSON));
ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
this.servletRequest.setRequestURI("/flower.json");
assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).isEqualTo(MediaType.APPLICATION_JSON);
}
@Test
public void favorParameter() throws Exception {
this.configurer.favorParameter(true);
this.configurer.parameterName("f");
this.configurer.mediaTypes(Collections.singletonMap("json", MediaType.APPLICATION_JSON));
ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
this.servletRequest.setRequestURI("/flower");
this.servletRequest.addParameter("f", "json");
assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).isEqualTo(MediaType.APPLICATION_JSON);
}
@Test
public void ignoreAcceptHeader() throws Exception {
this.configurer.ignoreAcceptHeader(true);
ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
this.servletRequest.setRequestURI("/flower");
this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE);
assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST);
}
@Test
public void setDefaultContentType() throws Exception {
this.configurer.defaultContentType(MediaType.APPLICATION_JSON);
ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).isEqualTo(MediaType.APPLICATION_JSON);
}
@Test
public void setMultipleDefaultContentTypes() throws Exception {
this.configurer.defaultContentType(MediaType.APPLICATION_JSON, MediaType.ALL);
ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.ALL));
}
@Test
public void setDefaultContentTypeStrategy() throws Exception {
this.configurer.defaultContentTypeStrategy(new FixedContentNegotiationStrategy(MediaType.APPLICATION_JSON));
ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).isEqualTo(MediaType.APPLICATION_JSON);
}
}
| {
"pile_set_name": "Github"
} |
package cors
import "strings"
const toLower = 'a' - 'A'
type converter func(string) string
type wildcard struct {
prefix string
suffix string
}
func (w wildcard) match(s string) bool {
return len(s) >= len(w.prefix+w.suffix) && strings.HasPrefix(s, w.prefix) && strings.HasSuffix(s, w.suffix)
}
// convert converts a list of string using the passed converter function
func convert(s []string, c converter) []string {
out := []string{}
for _, i := range s {
out = append(out, c(i))
}
return out
}
// parseHeaderList tokenize + normalize a string containing a list of headers
func parseHeaderList(headerList string) []string {
l := len(headerList)
h := make([]byte, 0, l)
upper := true
// Estimate the number headers in order to allocate the right splice size
t := 0
for i := 0; i < l; i++ {
if headerList[i] == ',' {
t++
}
}
headers := make([]string, 0, t)
for i := 0; i < l; i++ {
b := headerList[i]
switch {
case b >= 'a' && b <= 'z':
if upper {
h = append(h, b-toLower)
} else {
h = append(h, b)
}
case b >= 'A' && b <= 'Z':
if !upper {
h = append(h, b+toLower)
} else {
h = append(h, b)
}
case b == '-' || b == '_' || (b >= '0' && b <= '9'):
h = append(h, b)
}
if b == ' ' || b == ',' || i == l-1 {
if len(h) > 0 {
// Flush the found header
headers = append(headers, string(h))
h = h[:0]
upper = true
}
} else {
upper = b == '-' || b == '_'
}
}
return headers
}
| {
"pile_set_name": "Github"
} |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2013 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "meshStructure.H"
// * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * * //
bool Foam::meshStructure::structured() const
{
return structured_;
}
const Foam::labelList& Foam::meshStructure::cellToPatchFaceAddressing() const
{
return cellToPatchFaceAddressing_;
}
Foam::labelList& Foam::meshStructure::cellToPatchFaceAddressing()
{
return cellToPatchFaceAddressing_;
}
const Foam::labelList& Foam::meshStructure::cellLayer() const
{
return cellLayer_;
}
Foam::labelList& Foam::meshStructure::cellLayer()
{
return cellLayer_;
}
const Foam::labelList& Foam::meshStructure::faceToPatchFaceAddressing() const
{
return faceToPatchFaceAddressing_;
}
Foam::labelList& Foam::meshStructure::faceToPatchFaceAddressing()
{
return faceToPatchFaceAddressing_;
}
const Foam::labelList& Foam::meshStructure::faceToPatchEdgeAddressing() const
{
return faceToPatchEdgeAddressing_;
}
Foam::labelList& Foam::meshStructure::faceToPatchEdgeAddressing()
{
return faceToPatchEdgeAddressing_;
}
const Foam::labelList& Foam::meshStructure::faceLayer() const
{
return faceLayer_;
}
Foam::labelList& Foam::meshStructure::faceLayer()
{
return faceLayer_;
}
const Foam::labelList& Foam::meshStructure::pointToPatchPointAddressing() const
{
return pointToPatchPointAddressing_;
}
Foam::labelList& Foam::meshStructure::pointToPatchPointAddressing()
{
return pointToPatchPointAddressing_;
}
const Foam::labelList& Foam::meshStructure::pointLayer() const
{
return pointLayer_;
}
Foam::labelList& Foam::meshStructure::pointLayer()
{
return pointLayer_;
}
// ************************************************************************* //
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2013 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs <[email protected]>
*/
#include "gf100.h"
#include "gk104.h"
#include "ctxgf100.h"
#include <nvif/class.h>
/*******************************************************************************
* PGRAPH register lists
******************************************************************************/
const struct gf100_gr_init
gk104_gr_init_main_0[] = {
{ 0x400080, 1, 0x04, 0x003083c2 },
{ 0x400088, 1, 0x04, 0x0001ffe7 },
{ 0x40008c, 1, 0x04, 0x00000000 },
{ 0x400090, 1, 0x04, 0x00000030 },
{ 0x40013c, 1, 0x04, 0x003901f7 },
{ 0x400140, 1, 0x04, 0x00000100 },
{ 0x400144, 1, 0x04, 0x00000000 },
{ 0x400148, 1, 0x04, 0x00000110 },
{ 0x400138, 1, 0x04, 0x00000000 },
{ 0x400130, 2, 0x04, 0x00000000 },
{ 0x400124, 1, 0x04, 0x00000002 },
{}
};
static const struct gf100_gr_init
gk104_gr_init_ds_0[] = {
{ 0x405844, 1, 0x04, 0x00ffffff },
{ 0x405850, 1, 0x04, 0x00000000 },
{ 0x405900, 1, 0x04, 0x0000ff34 },
{ 0x405908, 1, 0x04, 0x00000000 },
{ 0x405928, 2, 0x04, 0x00000000 },
{}
};
static const struct gf100_gr_init
gk104_gr_init_sked_0[] = {
{ 0x407010, 1, 0x04, 0x00000000 },
{}
};
static const struct gf100_gr_init
gk104_gr_init_cwd_0[] = {
{ 0x405b50, 1, 0x04, 0x00000000 },
{}
};
static const struct gf100_gr_init
gk104_gr_init_gpc_unk_1[] = {
{ 0x418d00, 1, 0x04, 0x00000000 },
{ 0x418d28, 2, 0x04, 0x00000000 },
{ 0x418f00, 1, 0x04, 0x00000000 },
{ 0x418f08, 1, 0x04, 0x00000000 },
{ 0x418f20, 2, 0x04, 0x00000000 },
{ 0x418e00, 1, 0x04, 0x00000060 },
{ 0x418e08, 1, 0x04, 0x00000000 },
{ 0x418e1c, 2, 0x04, 0x00000000 },
{}
};
const struct gf100_gr_init
gk104_gr_init_gpc_unk_2[] = {
{ 0x418884, 1, 0x04, 0x00000000 },
{}
};
const struct gf100_gr_init
gk104_gr_init_tpccs_0[] = {
{ 0x419d0c, 1, 0x04, 0x00000000 },
{ 0x419d10, 1, 0x04, 0x00000014 },
{}
};
const struct gf100_gr_init
gk104_gr_init_pe_0[] = {
{ 0x41980c, 1, 0x04, 0x00000010 },
{ 0x419844, 1, 0x04, 0x00000000 },
{ 0x419850, 1, 0x04, 0x00000004 },
{ 0x419854, 2, 0x04, 0x00000000 },
{}
};
static const struct gf100_gr_init
gk104_gr_init_l1c_0[] = {
{ 0x419c98, 1, 0x04, 0x00000000 },
{ 0x419ca8, 1, 0x04, 0x00000000 },
{ 0x419cb0, 1, 0x04, 0x01000000 },
{ 0x419cb4, 1, 0x04, 0x00000000 },
{ 0x419cb8, 1, 0x04, 0x00b08bea },
{ 0x419c84, 1, 0x04, 0x00010384 },
{ 0x419cbc, 1, 0x04, 0x28137646 },
{ 0x419cc0, 2, 0x04, 0x00000000 },
{ 0x419c80, 1, 0x04, 0x00020232 },
{}
};
static const struct gf100_gr_init
gk104_gr_init_sm_0[] = {
{ 0x419e00, 1, 0x04, 0x00000000 },
{ 0x419ea0, 1, 0x04, 0x00000000 },
{ 0x419ee4, 1, 0x04, 0x00000000 },
{ 0x419ea4, 1, 0x04, 0x00000100 },
{ 0x419ea8, 1, 0x04, 0x00000000 },
{ 0x419eb4, 4, 0x04, 0x00000000 },
{ 0x419edc, 1, 0x04, 0x00000000 },
{ 0x419f00, 1, 0x04, 0x00000000 },
{ 0x419f74, 1, 0x04, 0x00000555 },
{}
};
const struct gf100_gr_init
gk104_gr_init_be_0[] = {
{ 0x40880c, 1, 0x04, 0x00000000 },
{ 0x408850, 1, 0x04, 0x00000004 },
{ 0x408910, 9, 0x04, 0x00000000 },
{ 0x408950, 1, 0x04, 0x00000000 },
{ 0x408954, 1, 0x04, 0x0000ffff },
{ 0x408958, 1, 0x04, 0x00000034 },
{ 0x408984, 1, 0x04, 0x00000000 },
{ 0x408988, 1, 0x04, 0x08040201 },
{ 0x40898c, 1, 0x04, 0x80402010 },
{}
};
const struct gf100_gr_pack
gk104_gr_pack_mmio[] = {
{ gk104_gr_init_main_0 },
{ gf100_gr_init_fe_0 },
{ gf100_gr_init_pri_0 },
{ gf100_gr_init_rstr2d_0 },
{ gf119_gr_init_pd_0 },
{ gk104_gr_init_ds_0 },
{ gf100_gr_init_scc_0 },
{ gk104_gr_init_sked_0 },
{ gk104_gr_init_cwd_0 },
{ gf119_gr_init_prop_0 },
{ gf108_gr_init_gpc_unk_0 },
{ gf100_gr_init_setup_0 },
{ gf100_gr_init_crstr_0 },
{ gf108_gr_init_setup_1 },
{ gf100_gr_init_zcull_0 },
{ gf119_gr_init_gpm_0 },
{ gk104_gr_init_gpc_unk_1 },
{ gf100_gr_init_gcc_0 },
{ gk104_gr_init_gpc_unk_2 },
{ gk104_gr_init_tpccs_0 },
{ gf119_gr_init_tex_0 },
{ gk104_gr_init_pe_0 },
{ gk104_gr_init_l1c_0 },
{ gf100_gr_init_mpc_0 },
{ gk104_gr_init_sm_0 },
{ gf117_gr_init_pes_0 },
{ gf117_gr_init_wwdx_0 },
{ gf117_gr_init_cbm_0 },
{ gk104_gr_init_be_0 },
{ gf100_gr_init_fe_1 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_main_0[] = {
{ 0x4041f0, 1, 0x00004046 },
{ 0x409890, 1, 0x00000045 },
{ 0x4098b0, 1, 0x0000007f },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_rstr2d_0[] = {
{ 0x4078c0, 1, 0x00000042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_unk_0[] = {
{ 0x406000, 1, 0x00004044 },
{ 0x405860, 1, 0x00004042 },
{ 0x40590c, 1, 0x00004042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gcc_0[] = {
{ 0x408040, 1, 0x00004044 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_sked_0[] = {
{ 0x407000, 1, 0x00004044 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_unk_1[] = {
{ 0x405bf0, 1, 0x00004044 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_ctxctl_0[] = {
{ 0x41a890, 1, 0x00000042 },
{ 0x41a8b0, 1, 0x0000007f },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_unk_0[] = {
{ 0x418500, 1, 0x00004042 },
{ 0x418608, 1, 0x00004042 },
{ 0x418688, 1, 0x00004042 },
{ 0x418718, 1, 0x00000042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_esetup_0[] = {
{ 0x418828, 1, 0x00000044 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_tpbus_0[] = {
{ 0x418bbc, 1, 0x00004042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_zcull_0[] = {
{ 0x418970, 1, 0x00004042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_tpconf_0[] = {
{ 0x418c70, 1, 0x00004042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_unk_1[] = {
{ 0x418cf0, 1, 0x00004042 },
{ 0x418d70, 1, 0x00004042 },
{ 0x418f0c, 1, 0x00004042 },
{ 0x418e0c, 1, 0x00004042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_gcc_0[] = {
{ 0x419020, 1, 0x00004042 },
{ 0x419038, 1, 0x00000042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_ffb_0[] = {
{ 0x418898, 1, 0x00000042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_tex_0[] = {
{ 0x419a40, 9, 0x00004042 },
{ 0x419acc, 1, 0x00004047 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_poly_0[] = {
{ 0x419868, 1, 0x00000042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_l1c_0[] = {
{ 0x419ccc, 3, 0x00000042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_unk_2[] = {
{ 0x419c70, 1, 0x00004045 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_mp_0[] = {
{ 0x419fd0, 1, 0x00004043 },
{ 0x419fd8, 1, 0x00004049 },
{ 0x419fe0, 2, 0x00004042 },
{ 0x419ff0, 1, 0x00004046 },
{ 0x419ff8, 1, 0x00004042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_gpc_ppc_0[] = {
{ 0x41be28, 1, 0x00000042 },
{ 0x41bfe8, 1, 0x00004042 },
{ 0x41bed0, 1, 0x00004042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_rop_zrop_0[] = {
{ 0x408810, 2, 0x00004042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_rop_0[] = {
{ 0x408a80, 6, 0x00004042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_rop_crop_0[] = {
{ 0x4089a8, 1, 0x00004042 },
{ 0x4089b0, 1, 0x00000042 },
{ 0x4089b8, 1, 0x00004042 },
{}
};
const struct nvkm_therm_clkgate_init
gk104_clkgate_blcg_init_pxbar_0[] = {
{ 0x13c820, 1, 0x0001007f },
{ 0x13cbe0, 1, 0x00000042 },
{}
};
static const struct nvkm_therm_clkgate_pack
gk104_clkgate_pack[] = {
{ gk104_clkgate_blcg_init_main_0 },
{ gk104_clkgate_blcg_init_rstr2d_0 },
{ gk104_clkgate_blcg_init_unk_0 },
{ gk104_clkgate_blcg_init_gcc_0 },
{ gk104_clkgate_blcg_init_sked_0 },
{ gk104_clkgate_blcg_init_unk_1 },
{ gk104_clkgate_blcg_init_gpc_ctxctl_0 },
{ gk104_clkgate_blcg_init_gpc_unk_0 },
{ gk104_clkgate_blcg_init_gpc_esetup_0 },
{ gk104_clkgate_blcg_init_gpc_tpbus_0 },
{ gk104_clkgate_blcg_init_gpc_zcull_0 },
{ gk104_clkgate_blcg_init_gpc_tpconf_0 },
{ gk104_clkgate_blcg_init_gpc_unk_1 },
{ gk104_clkgate_blcg_init_gpc_gcc_0 },
{ gk104_clkgate_blcg_init_gpc_ffb_0 },
{ gk104_clkgate_blcg_init_gpc_tex_0 },
{ gk104_clkgate_blcg_init_gpc_poly_0 },
{ gk104_clkgate_blcg_init_gpc_l1c_0 },
{ gk104_clkgate_blcg_init_gpc_unk_2 },
{ gk104_clkgate_blcg_init_gpc_mp_0 },
{ gk104_clkgate_blcg_init_gpc_ppc_0 },
{ gk104_clkgate_blcg_init_rop_zrop_0 },
{ gk104_clkgate_blcg_init_rop_0 },
{ gk104_clkgate_blcg_init_rop_crop_0 },
{ gk104_clkgate_blcg_init_pxbar_0 },
{}
};
/*******************************************************************************
* PGRAPH engine/subdev functions
******************************************************************************/
void
gk104_gr_init_sked_hww_esr(struct gf100_gr *gr)
{
nvkm_wr32(gr->base.engine.subdev.device, 0x407020, 0x40000000);
}
static void
gk104_gr_init_fecs_exceptions(struct gf100_gr *gr)
{
struct nvkm_device *device = gr->base.engine.subdev.device;
nvkm_wr32(device, 0x409ffc, 0x00000000);
nvkm_wr32(device, 0x409c14, 0x00003e3e);
nvkm_wr32(device, 0x409c24, 0x000f0001);
}
void
gk104_gr_init_rop_active_fbps(struct gf100_gr *gr)
{
struct nvkm_device *device = gr->base.engine.subdev.device;
const u32 fbp_count = nvkm_rd32(device, 0x120074);
nvkm_mask(device, 0x408850, 0x0000000f, fbp_count); /* zrop */
nvkm_mask(device, 0x408958, 0x0000000f, fbp_count); /* crop */
}
void
gk104_gr_init_ppc_exceptions(struct gf100_gr *gr)
{
struct nvkm_device *device = gr->base.engine.subdev.device;
int gpc, ppc;
for (gpc = 0; gpc < gr->gpc_nr; gpc++) {
for (ppc = 0; ppc < gr->ppc_nr[gpc]; ppc++) {
if (!(gr->ppc_mask[gpc] & (1 << ppc)))
continue;
nvkm_wr32(device, PPC_UNIT(gpc, ppc, 0x038), 0xc0000000);
}
}
}
void
gk104_gr_init_vsc_stream_master(struct gf100_gr *gr)
{
struct nvkm_device *device = gr->base.engine.subdev.device;
nvkm_wr32(device, GPC_UNIT(0, 0x3018), 0x00000001);
}
#include "fuc/hubgk104.fuc3.h"
static struct gf100_gr_ucode
gk104_gr_fecs_ucode = {
.code.data = gk104_grhub_code,
.code.size = sizeof(gk104_grhub_code),
.data.data = gk104_grhub_data,
.data.size = sizeof(gk104_grhub_data),
};
#include "fuc/gpcgk104.fuc3.h"
static struct gf100_gr_ucode
gk104_gr_gpccs_ucode = {
.code.data = gk104_grgpc_code,
.code.size = sizeof(gk104_grgpc_code),
.data.data = gk104_grgpc_data,
.data.size = sizeof(gk104_grgpc_data),
};
static const struct gf100_gr_func
gk104_gr = {
.oneinit_tiles = gf100_gr_oneinit_tiles,
.oneinit_sm_id = gf100_gr_oneinit_sm_id,
.init = gf100_gr_init,
.init_gpc_mmu = gf100_gr_init_gpc_mmu,
.init_vsc_stream_master = gk104_gr_init_vsc_stream_master,
.init_zcull = gf117_gr_init_zcull,
.init_num_active_ltcs = gf100_gr_init_num_active_ltcs,
.init_rop_active_fbps = gk104_gr_init_rop_active_fbps,
.init_fecs_exceptions = gk104_gr_init_fecs_exceptions,
.init_sked_hww_esr = gk104_gr_init_sked_hww_esr,
.init_419cc0 = gf100_gr_init_419cc0,
.init_419eb4 = gf100_gr_init_419eb4,
.init_ppc_exceptions = gk104_gr_init_ppc_exceptions,
.init_tex_hww_esr = gf100_gr_init_tex_hww_esr,
.init_shader_exceptions = gf100_gr_init_shader_exceptions,
.init_400054 = gf100_gr_init_400054,
.trap_mp = gf100_gr_trap_mp,
.mmio = gk104_gr_pack_mmio,
.fecs.ucode = &gk104_gr_fecs_ucode,
.gpccs.ucode = &gk104_gr_gpccs_ucode,
.rops = gf100_gr_rops,
.ppc_nr = 1,
.grctx = &gk104_grctx,
.clkgate_pack = gk104_clkgate_pack,
.zbc = &gf100_gr_zbc,
.sclass = {
{ -1, -1, FERMI_TWOD_A },
{ -1, -1, KEPLER_INLINE_TO_MEMORY_A },
{ -1, -1, KEPLER_A, &gf100_fermi },
{ -1, -1, KEPLER_COMPUTE_A },
{}
}
};
static const struct gf100_gr_fwif
gk104_gr_fwif[] = {
{ -1, gf100_gr_load, &gk104_gr },
{ -1, gf100_gr_nofw, &gk104_gr },
{}
};
int
gk104_gr_new(struct nvkm_device *device, int index, struct nvkm_gr **pgr)
{
return gf100_gr_new_(gk104_gr_fwif, device, index, pgr);
}
| {
"pile_set_name": "Github"
} |
class Galib < Formula
homepage "http://lancet.mit.edu/ga/"
url "http://lancet.mit.edu/ga/dist/galib247.tgz"
sha256 "ea76b66ce4db4db2ed86e20d6d3ff144abaf73e33620104246639d9b2a465329"
def install
# https://github.com/B0RJA/GAlib-mpi/issues/1
inreplace %W[ga/GA1DArrayGenome.C ga/GA2DArrayGenome.C ga/GA3DArrayGenome.C] do |s|
s.gsub! "initializer(GA", "this->initializer(GA"
s.gsub! "mutator(GA", "this->mutator(GA"
s.gsub! "comparator(GA", "this->comparator(GA"
s.gsub! "crossover(GA", "this->crossover(GA"
end
# To avoid that 'libga.a' will be install as 'lib' and not *into* lib:
lib.mkpath
# Sometime builds fail. It's fast anyway, so lets deparallelize
ENV.deparallelize
system "make"
system "make", "test"
system "make", "DESTDIR=#{prefix}", "install"
end
end
| {
"pile_set_name": "Github"
} |
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# TestCategory.py
# Copyright (C) 2011 Simon Newton
__author__ = '[email protected] (Simon Newton)'
class TestCategory(object):
"""The category a test is part of."""
SYMBOLS_TO_VALUES = {
# These correspond to categories in the E1.20 document
'NETWORK_MANAGEMENT': 'Network Management',
'STATUS_COLLECTION': 'Status Collection',
'RDM_INFORMATION': 'RDM Information',
'PRODUCT_INFORMATION': 'Product Information',
'DMX_SETUP': 'DMX512 Setup',
'DIMMER_SETTINGS': 'Dimmer Settings',
'IP_DNS_CONFIGURATION': 'IP and DNS Configuration',
'SENSORS': 'Sensors',
'POWER_LAMP_SETTINGS': 'Power / Lamp Settings',
'DISPLAY_SETTINGS': 'Display Settings',
'CONFIGURATION': 'Configuration',
'CONTROL': 'Control',
# And others for things that don't quite fit
'CORE': 'Core Functionality',
'ERROR_CONDITIONS': 'Error Conditions',
'SUB_DEVICES': 'Sub Devices',
'UNCLASSIFIED': 'Unclassified',
}
CATEGORIES_ = []
def __init__(self, category):
self._category = category
def __str__(self):
return self._category
def __hash__(self):
return hash(self._category)
@staticmethod
def Categories():
"""Return a list of all TestCategories."""
return TestCategory.CATEGORIES_
# Make the symbols accessible, i.e. TestCategory.STATUS_COLLECTION
for symbol, description in TestCategory.SYMBOLS_TO_VALUES.items():
obj = TestCategory(description)
setattr(TestCategory, symbol, obj)
TestCategory.CATEGORIES_.append(obj)
| {
"pile_set_name": "Github"
} |
# CVS $Revision: $ $Author: $ -- Sun Dec 8 22:17:49 2013 -- reformated by prettylst.pl v1.50 (build 22352)
###Block: Masterwork
# Modifier Name Unique Key Naming Format Naming Option Type Cost Visible Type granted Source Page Required Type Prohibited Type Bonus Armor Modifiers Modify the item cost Weapon prop. bonus Apply to both heads
Masterwork KEY:MWORKW FORMATCAT:FRONT NAMEOPT:NORMAL TYPE:MasterworkQuality.Ammunition.Weapon COST:0 VISIBLE:QUALIFY ITYPE:Masterwork SOURCEPAGE:RSRD Equipment.rtf PRETYPE:1,Weapon,Ammunition !PRETYPE:1,Masterwork,Mithral,Adamantine,Darkwood BONUS:ITEMCOST|TYPE=Ammunition|6 BONUS:ITEMCOST|TYPE=Weapon|300 BONUS:WEAPON|TOHIT|1|TYPE=Enhancement ASSIGNTOALL:YES
Masterwork KEY:MWORKA FORMATCAT:FRONT NAMEOPT:NORMAL TYPE:MasterworkQuality.Armor.Shield COST:150 VISIBLE:QUALIFY ITYPE:Masterwork SOURCEPAGE:RSRD Equipment.rtf PRETYPE:1,Armor,Shield !PRETYPE:1,Masterwork,Mithral,Adamantine,Darkwood BONUS:EQMARMOR|ACCHECK|1|TYPE=Enhancement ASSIGNTOALL:YES
Masterwork KEY:MWORKI FORMATCAT:FRONT NAMEOPT:NORMAL TYPE:MasterworkQuality.Instrument COST:95 VISIBLE:QUALIFY ITYPE:Masterwork SOURCEPAGE:RSRD Equipment.rtf PRETYPE:1,Instrument !PRETYPE:1,Masterwork,Mithral,Adamantine,Darkwood ASSIGNTOALL:YES
Masterwork KEY:MWORKT FORMATCAT:FRONT NAMEOPT:NORMAL TYPE:MasterworkQuality.Tools COST:50 VISIBLE:QUALIFY ITYPE:Masterwork SOURCEPAGE:RSRD Equipment.rtf PRETYPE:1,Tools !PRETYPE:1,Masterwork,Mithral,Adamantine,Darkwood BONUS:ITEMCOST|TYPE=Thief|20 ASSIGNTOALL:YES
###Block: Base Materials
###Block: Strength Bow
# Modifier Name Unique Key Naming Option Type Cost Visible Source Page Required Type Modify the item cost Weapon prop. bonus Special Property Choose Apply to both heads
Bow_STR KEY:BOWSTR NAMEOPT:NONAME TYPE:Bow.Composite COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD Equipment.rtf PRETYPE:1,Composite BONUS:ITEMCOST|TYPE.Shortbow|75*%CHOICE|PREVARGT:%CHOICE,0 BONUS:ITEMCOST|TYPE.Longbow|100*%CHOICE|PREVARGT:%CHOICE,0 BONUS:WEAPON|TOHIT|-2|PREVARGT:%CHOICE,STR BONUS:WEAPON|DAMAGE|min(%CHOICE,STR) SPROP:STR bonus to damage CHOOSE:NUMBER|MIN=-5|MAX=100|TITLE=STR mod CHOOSE:NUMBER|MIN=-5|MAX=100|TITLE=STR mod ASSIGNTOALL:YES
###Block: Armor Accesories
# Modifier Name Unique Key Type Cost Visible Type granted Source Page Required Type Bonus Equipment Modifiers Bonus Weapon Modifiers Special Property Automatically Added to Inventory
Armor Spikes KEY:SPIKE_A TYPE:Armor COST:50 VISIBLE:QUALIFY ITYPE:Spiked.Piercing SOURCEPAGE:RSRD Equipment.rtf PRETYPE:1,Shield,Armor SPROP:Spiked AUTO:EQUIP|Armor Spikes
Shield Spikes KEY:SPIKE_S TYPE:Shield COST:10 VISIBLE:QUALIFY ITYPE:Spiked.Piercing SOURCEPAGE:RSRD Equipment.rtf PRETYPE:1,Shield,Armor BONUS:EQM|WEIGHTADD|5 BONUS:EQMWEAPON|DAMAGESIZE|1 SPROP:Spiked
Shield Spikes KEY:SPIKE_SB TYPE:Shieldbash COST:0 VISIBLE:QUALIFY ITYPE:Spiked.Piercing SOURCEPAGE:RSRD Equipment.rtf BONUS:EQMWEAPON|DAMAGESIZE|1 SPROP:Spiked
Locked Gauntlets KEY:Lock_G TYPE:Gauntlet COST:8 VISIBLE:QUALIFY ITYPE:GauntletLock SOURCEPAGE:RSRD Equipment.rtf BONUS:EQM|WEIGHTADD|5 SPROP:Locked
Nonhumanoid KEY:NONHUMANOID TYPE:Armor COST:BASECOST*(((SIZE<=2)*.5)+(SIZE==3)+(SIZE==4)+((SIZE>=5)*(2^(SIZE-4)))) VISIBLE:QUALIFY SOURCEPAGE:RSRD Equipment.rtf
###Block: Base Materials
# Modifier Name Unique Key Naming Option Type Cost Visible Type granted Source Page Prohibited Type Apply to both heads
Wood KEY:WOOD NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY ITYPE:Wooden SOURCEPAGE:RSRD Equipment.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal ASSIGNTOALL:YES
Steel KEY:STEEL NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY ITYPE:Metal SOURCEPAGE:RSRD Equipment.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Wooden
Clay KEY:CLAY NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Cloth KEY:CLOTH NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Glass KEY:GLASS NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Hide KEY:HIDE NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Ice KEY:ICE NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Iron KEY:IRON NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY ITYPE:Metal SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Wooden
Leather KEY:LEATHER NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Paper KEY:PAPER NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Parchment KEY:PARCHMENT NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Rope KEY:ROPE NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Stone KEY:STONE NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Wax KEY:WAX NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD CarryingandExploration.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
#The following are not explicitely mentioned in the SRD but are derived from existing equipment like a ring or a gong
Bone KEY:BONE NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD Equipment.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Wooden,Metal
Brass KEY:BRASS NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY ITYPE:Metal SOURCEPAGE:RSRD Equipment.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Wooden
Bronze KEY:BRONZE NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY ITYPE:Metal SOURCEPAGE:RSRD Equipment.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Wooden
Gold KEY:GOLD NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY ITYPE:Metal SOURCEPAGE:RSRD Equipment.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Wooden
Silk KEY:SILK NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY SOURCEPAGE:RSRD Equipment.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Metal,Wooden
Silver KEY:SILVER NAMEOPT:NORMAL TYPE:BaseMaterial.Mundane.Ammunition.Armor.Shield.Weapon.Instruments.Tools.Goods COST:0 VISIBLE:QUALIFY ITYPE:Metal SOURCEPAGE:RSRD Equipment.rtf !PRETYPE:1,EQMODTYPE=Mundane !PRETYPE:1,Wooden
#I didn't include mention of hp and hardness since I wouldn't want to see that printed as property for every normal equipmment,
#leaving that until we have equipment variables -- Frank
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <AppKit/NSButtonCell.h>
@interface TButtonCell : NSButtonCell
{
BOOL _acceptsFirstMouse;
}
@property BOOL acceptsFirstMouse; // @synthesize acceptsFirstMouse=_acceptsFirstMouse;
- (_Bool)acceptsFirstMouseFE:(id)arg1 inRect:(struct CGRect)arg2 ofView:(id)arg3;
- (long long)nextState;
- (void)initCommon;
- (id)initImageCell:(id)arg1;
- (id)initTextCell:(id)arg1;
- (id)initWithCoder:(id)arg1;
@end
| {
"pile_set_name": "Github"
} |
/*
* 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.
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'echarts'], factory);
} else if (
typeof exports === 'object' &&
typeof exports.nodeName !== 'string'
) {
// CommonJS
factory(exports, require('echarts'));
} else {
// Browser globals
factory({}, root.echarts);
}
})(this, function(exports, echarts) {
var log = function(msg) {
if (typeof console !== 'undefined') {
console && console.error && console.error(msg);
}
};
if (!echarts) {
log('ECharts is not Loaded');
return;
}
var colorPalette = [
'#e52c3c',
'#f7b1ab',
'#fa506c',
'#f59288',
'#f8c4d8',
'#e54f5c',
'#f06d5c',
'#e54f80',
'#f29c9f',
'#eeb5b7'
];
var theme = {
color: colorPalette,
title: {
textStyle: {
fontWeight: 'normal',
color: '#e52c3c'
}
},
visualMap: {
color: ['#e52c3c', '#f7b1ab']
},
dataRange: {
color: ['#e52c3c', '#f7b1ab']
},
candlestick: {
itemStyle: {
color: '#e52c3c',
color0: '#f59288'
},
lineStyle: {
width: 1,
color: '#e52c3c',
color0: '#f59288'
},
areaStyle: {
color: '#fa506c',
color0: '#f8c4d8'
}
},
map: {
itemStyle: {
color: '#e52c3c',
borderColor: '#fff',
borderWidth: 1
},
areaStyle: {
color: '#ccc'
},
label: {
color: 'rgba(139,69,19,1)',
show: false
}
},
graph: {
itemStyle: {
color: '#f2385a'
},
nodeStyle: {
brushType: 'both',
strokeColor: '#e54f5c'
},
linkStyle: {
color: '#f2385a',
strokeColor: '#e54f5c'
},
label: {
color: '#f2385a',
show: false
}
},
gauge: {
axisLine: {
lineStyle: {
color: [
[0.2, '#e52c3c'],
[0.8, '#f7b1ab'],
[1, '#fa506c']
],
width: 8
}
}
}
};
echarts.registerTheme('sakura', theme);
});
| {
"pile_set_name": "Github"
} |
<a href="http://promises-aplus.github.com/promises-spec"><img src="http://promises-aplus.github.com/promises-spec/assets/logo-small.png" align="right" /></a>
# is-promise
Test whether an object looks like a promises-a+ promise
[](https://travis-ci.org/then/is-promise)
[](https://gemnasium.com/then/is-promise)
[](https://www.npmjs.org/package/is-promise)
## Installation
$ npm install is-promise
You can also use it client side via npm.
## API
```javascript
var isPromise = require('is-promise');
isPromise({then:function () {...}});//=>true
isPromise(null);//=>false
isPromise({});//=>false
isPromise({then: true})//=>false
```
## License
MIT
| {
"pile_set_name": "Github"
} |
from octopus.core.utils import bytecode_to_bytes
class BytecodeEmptyException(Exception):
"""Exception raised when bytecode is None"""
pass
class Disassembler(object):
""" Generic Disassembler class """
def __init__(self, asm, bytecode=None):
self.bytecode = bytecode
self.instructions = list()
self.reverse_instructions = dict()
self.asm = asm
def attributes_reset(self):
"""Reset instructions class attributes """
self.instructions = list()
self.reverse_instructions = dict()
def disassemble_opcode(self, bytecode, offset=0):
""" Generic method to disassemble one instruction """
raise NotImplementedError
def disassemble(self, bytecode=None, offset=0, r_format='list'):
"""Generic method to disassemble bytecode
:param bytecode: bytecode sequence
:param offset: start offset
:param r_format: output format ('list'/'text'/'reverse')
:type bytecode: bytes, str
:type offset: int
:type r_format: list, str, dict
:return: dissassembly result depending of r_format
:rtype: list, str, dict
"""
# reinitialize class variable
self.attributes_reset()
self.bytecode = bytecode if bytecode else self.bytecode
if not self.bytecode:
raise BytecodeEmptyException()
self.bytecode = bytecode_to_bytes(self.bytecode)
while offset < len(self.bytecode):
instr = self.disassemble_opcode(self.bytecode[offset:], offset)
offset += instr.size
self.instructions.append(instr)
# fill reverse instructions
self.reverse_instructions = {k: v for k, v in
enumerate(self.instructions)}
# return instructions
if r_format == 'list':
return self.instructions
elif r_format == 'text':
return '\n'.join(map(str, self.instructions))
elif r_format == 'reverse':
return self.reverse_instructions
def disassemble_contract(self, contract):
""" Generic method to disassemble a Contract """
# reinitialize class variable
self.attributes_reset()
# update class bytecode
self.bytecode = contract.bytecode
self.disassemble(self.bytecode)
| {
"pile_set_name": "Github"
} |
# This source code was written by the Go contributors.
# The master list of contributors is in the main Go distribution,
# visible at http://tip.golang.org/CONTRIBUTORS.
| {
"pile_set_name": "Github"
} |
=pod
=head1 NAME
DSA_set_default_method, DSA_get_default_method,
DSA_set_method, DSA_new_method, DSA_OpenSSL - select DSA method
=head1 SYNOPSIS
#include <openssl/dsa.h>
#include <openssl/engine.h>
void DSA_set_default_method(const DSA_METHOD *meth);
const DSA_METHOD *DSA_get_default_method(void);
int DSA_set_method(DSA *dsa, const DSA_METHOD *meth);
DSA *DSA_new_method(ENGINE *engine);
DSA_METHOD *DSA_OpenSSL(void);
=head1 DESCRIPTION
A B<DSA_METHOD> specifies the functions that OpenSSL uses for DSA
operations. By modifying the method, alternative implementations
such as hardware accelerators may be used. IMPORTANT: See the NOTES section for
important information about how these DSA API functions are affected by the use
of B<ENGINE> API calls.
Initially, the default DSA_METHOD is the OpenSSL internal implementation,
as returned by DSA_OpenSSL().
DSA_set_default_method() makes B<meth> the default method for all DSA
structures created later. B<NB>: This is true only whilst no ENGINE has
been set as a default for DSA, so this function is no longer recommended.
DSA_get_default_method() returns a pointer to the current default
DSA_METHOD. However, the meaningfulness of this result is dependent on
whether the ENGINE API is being used, so this function is no longer
recommended.
DSA_set_method() selects B<meth> to perform all operations using the key
B<rsa>. This will replace the DSA_METHOD used by the DSA key and if the
previous method was supplied by an ENGINE, the handle to that ENGINE will
be released during the change. It is possible to have DSA keys that only
work with certain DSA_METHOD implementations (eg. from an ENGINE module
that supports embedded hardware-protected keys), and in such cases
attempting to change the DSA_METHOD for the key can have unexpected
results.
DSA_new_method() allocates and initializes a DSA structure so that B<engine>
will be used for the DSA operations. If B<engine> is NULL, the default engine
for DSA operations is used, and if no default ENGINE is set, the DSA_METHOD
controlled by DSA_set_default_method() is used.
=head1 THE DSA_METHOD STRUCTURE
struct
{
/* name of the implementation */
const char *name;
/* sign */
DSA_SIG *(*dsa_do_sign)(const unsigned char *dgst, int dlen,
DSA *dsa);
/* pre-compute k^-1 and r */
int (*dsa_sign_setup)(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp);
/* verify */
int (*dsa_do_verify)(const unsigned char *dgst, int dgst_len,
DSA_SIG *sig, DSA *dsa);
/* compute rr = a1^p1 * a2^p2 mod m (May be NULL for some
implementations) */
int (*dsa_mod_exp)(DSA *dsa, BIGNUM *rr, BIGNUM *a1, BIGNUM *p1,
BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *in_mont);
/* compute r = a ^ p mod m (May be NULL for some implementations) */
int (*bn_mod_exp)(DSA *dsa, BIGNUM *r, BIGNUM *a,
const BIGNUM *p, const BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *m_ctx);
/* called at DSA_new */
int (*init)(DSA *DSA);
/* called at DSA_free */
int (*finish)(DSA *DSA);
int flags;
char *app_data; /* ?? */
} DSA_METHOD;
=head1 RETURN VALUES
DSA_OpenSSL() and DSA_get_default_method() return pointers to the respective
B<DSA_METHOD>s.
DSA_set_default_method() returns no value.
DSA_set_method() returns non-zero if the provided B<meth> was successfully set as
the method for B<dsa> (including unloading the ENGINE handle if the previous
method was supplied by an ENGINE).
DSA_new_method() returns NULL and sets an error code that can be
obtained by L<ERR_get_error(3)|ERR_get_error(3)> if the allocation
fails. Otherwise it returns a pointer to the newly allocated structure.
=head1 NOTES
As of version 0.9.7, DSA_METHOD implementations are grouped together with other
algorithmic APIs (eg. RSA_METHOD, EVP_CIPHER, etc) in B<ENGINE> modules. If a
default ENGINE is specified for DSA functionality using an ENGINE API function,
that will override any DSA defaults set using the DSA API (ie.
DSA_set_default_method()). For this reason, the ENGINE API is the recommended way
to control default implementations for use in DSA and other cryptographic
algorithms.
=head1 SEE ALSO
L<dsa(3)|dsa(3)>, L<DSA_new(3)|DSA_new(3)>
=head1 HISTORY
DSA_set_default_method(), DSA_get_default_method(), DSA_set_method(),
DSA_new_method() and DSA_OpenSSL() were added in OpenSSL 0.9.4.
DSA_set_default_openssl_method() and DSA_get_default_openssl_method() replaced
DSA_set_default_method() and DSA_get_default_method() respectively, and
DSA_set_method() and DSA_new_method() were altered to use B<ENGINE>s rather than
B<DSA_METHOD>s during development of the engine version of OpenSSL 0.9.6. For
0.9.7, the handling of defaults in the ENGINE API was restructured so that this
change was reversed, and behaviour of the other functions resembled more closely
the previous behaviour. The behaviour of defaults in the ENGINE API now
transparently overrides the behaviour of defaults in the DSA API without
requiring changing these function prototypes.
=cut
| {
"pile_set_name": "Github"
} |
#-*-Mode:perl;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*-
# ex: set ft=perl fenc=utf-8 sts=4 ts=4 sw=4 et nomod:
#
# MIT License
#
# Copyright (c) 2014-2017 Michael Truog <mjtruog at protonmail dot com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
package CloudI::ReturnSyncException;
use strict;
use warnings;
use parent 'Erlang::Exception';
sub new
{
my $class = shift;
return $class->SUPER::new('Synchronous Call Return Invalid');
}
1;
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !appengine
// +build gc
// +build !noasm
#include "textflag.h"
// The asm code generally follows the pure Go code in decode_other.go, except
// where marked with a "!!!".
// func decode(dst, src []byte) int
//
// All local variables fit into registers. The non-zero stack size is only to
// spill registers and push args when issuing a CALL. The register allocation:
// - AX scratch
// - BX scratch
// - CX length or x
// - DX offset
// - SI &src[s]
// - DI &dst[d]
// + R8 dst_base
// + R9 dst_len
// + R10 dst_base + dst_len
// + R11 src_base
// + R12 src_len
// + R13 src_base + src_len
// - R14 used by doCopy
// - R15 used by doCopy
//
// The registers R8-R13 (marked with a "+") are set at the start of the
// function, and after a CALL returns, and are not otherwise modified.
//
// The d variable is implicitly DI - R8, and len(dst)-d is R10 - DI.
// The s variable is implicitly SI - R11, and len(src)-s is R13 - SI.
TEXT ·decode(SB), NOSPLIT, $48-56
// Initialize SI, DI and R8-R13.
MOVQ dst_base+0(FP), R8
MOVQ dst_len+8(FP), R9
MOVQ R8, DI
MOVQ R8, R10
ADDQ R9, R10
MOVQ src_base+24(FP), R11
MOVQ src_len+32(FP), R12
MOVQ R11, SI
MOVQ R11, R13
ADDQ R12, R13
loop:
// for s < len(src)
CMPQ SI, R13
JEQ end
// CX = uint32(src[s])
//
// switch src[s] & 0x03
MOVBLZX (SI), CX
MOVL CX, BX
ANDL $3, BX
CMPL BX, $1
JAE tagCopy
// ----------------------------------------
// The code below handles literal tags.
// case tagLiteral:
// x := uint32(src[s] >> 2)
// switch
SHRL $2, CX
CMPL CX, $60
JAE tagLit60Plus
// case x < 60:
// s++
INCQ SI
doLit:
// This is the end of the inner "switch", when we have a literal tag.
//
// We assume that CX == x and x fits in a uint32, where x is the variable
// used in the pure Go decode_other.go code.
// length = int(x) + 1
//
// Unlike the pure Go code, we don't need to check if length <= 0 because
// CX can hold 64 bits, so the increment cannot overflow.
INCQ CX
// Prepare to check if copying length bytes will run past the end of dst or
// src.
//
// AX = len(dst) - d
// BX = len(src) - s
MOVQ R10, AX
SUBQ DI, AX
MOVQ R13, BX
SUBQ SI, BX
// !!! Try a faster technique for short (16 or fewer bytes) copies.
//
// if length > 16 || len(dst)-d < 16 || len(src)-s < 16 {
// goto callMemmove // Fall back on calling runtime·memmove.
// }
//
// The C++ snappy code calls this TryFastAppend. It also checks len(src)-s
// against 21 instead of 16, because it cannot assume that all of its input
// is contiguous in memory and so it needs to leave enough source bytes to
// read the next tag without refilling buffers, but Go's Decode assumes
// contiguousness (the src argument is a []byte).
CMPQ CX, $16
JGT callMemmove
CMPQ AX, $16
JLT callMemmove
CMPQ BX, $16
JLT callMemmove
// !!! Implement the copy from src to dst as a 16-byte load and store.
// (Decode's documentation says that dst and src must not overlap.)
//
// This always copies 16 bytes, instead of only length bytes, but that's
// OK. If the input is a valid Snappy encoding then subsequent iterations
// will fix up the overrun. Otherwise, Decode returns a nil []byte (and a
// non-nil error), so the overrun will be ignored.
//
// Note that on amd64, it is legal and cheap to issue unaligned 8-byte or
// 16-byte loads and stores. This technique probably wouldn't be as
// effective on architectures that are fussier about alignment.
MOVOU 0(SI), X0
MOVOU X0, 0(DI)
// d += length
// s += length
ADDQ CX, DI
ADDQ CX, SI
JMP loop
callMemmove:
// if length > len(dst)-d || length > len(src)-s { etc }
CMPQ CX, AX
JGT errCorrupt
CMPQ CX, BX
JGT errCorrupt
// copy(dst[d:], src[s:s+length])
//
// This means calling runtime·memmove(&dst[d], &src[s], length), so we push
// DI, SI and CX as arguments. Coincidentally, we also need to spill those
// three registers to the stack, to save local variables across the CALL.
MOVQ DI, 0(SP)
MOVQ SI, 8(SP)
MOVQ CX, 16(SP)
MOVQ DI, 24(SP)
MOVQ SI, 32(SP)
MOVQ CX, 40(SP)
CALL runtime·memmove(SB)
// Restore local variables: unspill registers from the stack and
// re-calculate R8-R13.
MOVQ 24(SP), DI
MOVQ 32(SP), SI
MOVQ 40(SP), CX
MOVQ dst_base+0(FP), R8
MOVQ dst_len+8(FP), R9
MOVQ R8, R10
ADDQ R9, R10
MOVQ src_base+24(FP), R11
MOVQ src_len+32(FP), R12
MOVQ R11, R13
ADDQ R12, R13
// d += length
// s += length
ADDQ CX, DI
ADDQ CX, SI
JMP loop
tagLit60Plus:
// !!! This fragment does the
//
// s += x - 58; if uint(s) > uint(len(src)) { etc }
//
// checks. In the asm version, we code it once instead of once per switch case.
ADDQ CX, SI
SUBQ $58, SI
MOVQ SI, BX
SUBQ R11, BX
CMPQ BX, R12
JA errCorrupt
// case x == 60:
CMPL CX, $61
JEQ tagLit61
JA tagLit62Plus
// x = uint32(src[s-1])
MOVBLZX -1(SI), CX
JMP doLit
tagLit61:
// case x == 61:
// x = uint32(src[s-2]) | uint32(src[s-1])<<8
MOVWLZX -2(SI), CX
JMP doLit
tagLit62Plus:
CMPL CX, $62
JA tagLit63
// case x == 62:
// x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16
MOVWLZX -3(SI), CX
MOVBLZX -1(SI), BX
SHLL $16, BX
ORL BX, CX
JMP doLit
tagLit63:
// case x == 63:
// x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24
MOVL -4(SI), CX
JMP doLit
// The code above handles literal tags.
// ----------------------------------------
// The code below handles copy tags.
tagCopy4:
// case tagCopy4:
// s += 5
ADDQ $5, SI
// if uint(s) > uint(len(src)) { etc }
MOVQ SI, BX
SUBQ R11, BX
CMPQ BX, R12
JA errCorrupt
// length = 1 + int(src[s-5])>>2
SHRQ $2, CX
INCQ CX
// offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24)
MOVLQZX -4(SI), DX
JMP doCopy
tagCopy2:
// case tagCopy2:
// s += 3
ADDQ $3, SI
// if uint(s) > uint(len(src)) { etc }
MOVQ SI, BX
SUBQ R11, BX
CMPQ BX, R12
JA errCorrupt
// length = 1 + int(src[s-3])>>2
SHRQ $2, CX
INCQ CX
// offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8)
MOVWQZX -2(SI), DX
JMP doCopy
tagCopy:
// We have a copy tag. We assume that:
// - BX == src[s] & 0x03
// - CX == src[s]
CMPQ BX, $2
JEQ tagCopy2
JA tagCopy4
// case tagCopy1:
// s += 2
ADDQ $2, SI
// if uint(s) > uint(len(src)) { etc }
MOVQ SI, BX
SUBQ R11, BX
CMPQ BX, R12
JA errCorrupt
// offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1]))
MOVQ CX, DX
ANDQ $0xe0, DX
SHLQ $3, DX
MOVBQZX -1(SI), BX
ORQ BX, DX
// length = 4 + int(src[s-2])>>2&0x7
SHRQ $2, CX
ANDQ $7, CX
ADDQ $4, CX
doCopy:
// This is the end of the outer "switch", when we have a copy tag.
//
// We assume that:
// - CX == length && CX > 0
// - DX == offset
// if offset <= 0 { etc }
CMPQ DX, $0
JLE errCorrupt
// if d < offset { etc }
MOVQ DI, BX
SUBQ R8, BX
CMPQ BX, DX
JLT errCorrupt
// if length > len(dst)-d { etc }
MOVQ R10, BX
SUBQ DI, BX
CMPQ CX, BX
JGT errCorrupt
// forwardCopy(dst[d:d+length], dst[d-offset:]); d += length
//
// Set:
// - R14 = len(dst)-d
// - R15 = &dst[d-offset]
MOVQ R10, R14
SUBQ DI, R14
MOVQ DI, R15
SUBQ DX, R15
// !!! Try a faster technique for short (16 or fewer bytes) forward copies.
//
// First, try using two 8-byte load/stores, similar to the doLit technique
// above. Even if dst[d:d+length] and dst[d-offset:] can overlap, this is
// still OK if offset >= 8. Note that this has to be two 8-byte load/stores
// and not one 16-byte load/store, and the first store has to be before the
// second load, due to the overlap if offset is in the range [8, 16).
//
// if length > 16 || offset < 8 || len(dst)-d < 16 {
// goto slowForwardCopy
// }
// copy 16 bytes
// d += length
CMPQ CX, $16
JGT slowForwardCopy
CMPQ DX, $8
JLT slowForwardCopy
CMPQ R14, $16
JLT slowForwardCopy
MOVQ 0(R15), AX
MOVQ AX, 0(DI)
MOVQ 8(R15), BX
MOVQ BX, 8(DI)
ADDQ CX, DI
JMP loop
slowForwardCopy:
// !!! If the forward copy is longer than 16 bytes, or if offset < 8, we
// can still try 8-byte load stores, provided we can overrun up to 10 extra
// bytes. As above, the overrun will be fixed up by subsequent iterations
// of the outermost loop.
//
// The C++ snappy code calls this technique IncrementalCopyFastPath. Its
// commentary says:
//
// ----
//
// The main part of this loop is a simple copy of eight bytes at a time
// until we've copied (at least) the requested amount of bytes. However,
// if d and d-offset are less than eight bytes apart (indicating a
// repeating pattern of length < 8), we first need to expand the pattern in
// order to get the correct results. For instance, if the buffer looks like
// this, with the eight-byte <d-offset> and <d> patterns marked as
// intervals:
//
// abxxxxxxxxxxxx
// [------] d-offset
// [------] d
//
// a single eight-byte copy from <d-offset> to <d> will repeat the pattern
// once, after which we can move <d> two bytes without moving <d-offset>:
//
// ababxxxxxxxxxx
// [------] d-offset
// [------] d
//
// and repeat the exercise until the two no longer overlap.
//
// This allows us to do very well in the special case of one single byte
// repeated many times, without taking a big hit for more general cases.
//
// The worst case of extra writing past the end of the match occurs when
// offset == 1 and length == 1; the last copy will read from byte positions
// [0..7] and write to [4..11], whereas it was only supposed to write to
// position 1. Thus, ten excess bytes.
//
// ----
//
// That "10 byte overrun" worst case is confirmed by Go's
// TestSlowForwardCopyOverrun, which also tests the fixUpSlowForwardCopy
// and finishSlowForwardCopy algorithm.
//
// if length > len(dst)-d-10 {
// goto verySlowForwardCopy
// }
SUBQ $10, R14
CMPQ CX, R14
JGT verySlowForwardCopy
makeOffsetAtLeast8:
// !!! As above, expand the pattern so that offset >= 8 and we can use
// 8-byte load/stores.
//
// for offset < 8 {
// copy 8 bytes from dst[d-offset:] to dst[d:]
// length -= offset
// d += offset
// offset += offset
// // The two previous lines together means that d-offset, and therefore
// // R15, is unchanged.
// }
CMPQ DX, $8
JGE fixUpSlowForwardCopy
MOVQ (R15), BX
MOVQ BX, (DI)
SUBQ DX, CX
ADDQ DX, DI
ADDQ DX, DX
JMP makeOffsetAtLeast8
fixUpSlowForwardCopy:
// !!! Add length (which might be negative now) to d (implied by DI being
// &dst[d]) so that d ends up at the right place when we jump back to the
// top of the loop. Before we do that, though, we save DI to AX so that, if
// length is positive, copying the remaining length bytes will write to the
// right place.
MOVQ DI, AX
ADDQ CX, DI
finishSlowForwardCopy:
// !!! Repeat 8-byte load/stores until length <= 0. Ending with a negative
// length means that we overrun, but as above, that will be fixed up by
// subsequent iterations of the outermost loop.
CMPQ CX, $0
JLE loop
MOVQ (R15), BX
MOVQ BX, (AX)
ADDQ $8, R15
ADDQ $8, AX
SUBQ $8, CX
JMP finishSlowForwardCopy
verySlowForwardCopy:
// verySlowForwardCopy is a simple implementation of forward copy. In C
// parlance, this is a do/while loop instead of a while loop, since we know
// that length > 0. In Go syntax:
//
// for {
// dst[d] = dst[d - offset]
// d++
// length--
// if length == 0 {
// break
// }
// }
MOVB (R15), BX
MOVB BX, (DI)
INCQ R15
INCQ DI
DECQ CX
JNZ verySlowForwardCopy
JMP loop
// The code above handles copy tags.
// ----------------------------------------
end:
// This is the end of the "for s < len(src)".
//
// if d != len(dst) { etc }
CMPQ DI, R10
JNE errCorrupt
// return 0
MOVQ $0, ret+48(FP)
RET
errCorrupt:
// return decodeErrCodeCorrupt
MOVQ $1, ret+48(FP)
RET
| {
"pile_set_name": "Github"
} |
/*
Author: Annie Kim, [email protected] : King, [email protected]
Date: Nov 9, 2013
Update: Oct 5, 2014
Problem: Linked List Cycle
Difficulty: Easy
Source: http://oj.leetcode.com/problems/linked-list-cycle/
Notes:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution: two pointers.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow) return true;
}
return false;
}
};
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x",
"filename" : "[email protected]"
},
{
"idiom" : "universal",
"scale" : "3x",
"filename" : "[email protected]"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
from rsf.proj import *
Fetch('marmvel.hh','marm')
Flow('marm','marmvel.hh','dd form=native')
Plot('marm','window j1=2 j2=2 | grey allpos=y screenratio=.327 screenht=4.7 wanttitle=n')
for order in (1,2):
eiko = 'eiko%d' % order
Flow(eiko,'marm','eikonal order=%d yshot=5000 b1=5 b2=5' % order)
Plot(eiko,
'''
window j1=2 j2=2 |
contour screenratio=.327 screenht=4.7 wanttitle=n wantaxis=n dash=%d nc=200
''' % (0,3)[order-1])
Result('marmousi','marm eiko1 eiko2','Overlay')
End()
| {
"pile_set_name": "Github"
} |
今野さおり最新番号
【CJW-010】痴女ワーキングガール 2</a>2008-04-16h.m.p$$$Cream88分钟 | {
"pile_set_name": "Github"
} |
// Copyright (C) 2014 Yasuhiro Matsumoto <[email protected]>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build go1.8
package sqlite3
import (
"database/sql/driver"
"errors"
"context"
)
// Ping implement Pinger.
func (c *SQLiteConn) Ping(ctx context.Context) error {
if c.db == nil {
return errors.New("Connection was closed")
}
return nil
}
// QueryContext implement QueryerContext.
func (c *SQLiteConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return c.query(ctx, query, list)
}
// ExecContext implement ExecerContext.
func (c *SQLiteConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return c.exec(ctx, query, list)
}
// PrepareContext implement ConnPrepareContext.
func (c *SQLiteConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
return c.prepare(ctx, query)
}
// BeginTx implement ConnBeginTx.
func (c *SQLiteConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
return c.begin(ctx)
}
// QueryContext implement QueryerContext.
func (s *SQLiteStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return s.query(ctx, list)
}
// ExecContext implement ExecerContext.
func (s *SQLiteStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return s.exec(ctx, list)
}
| {
"pile_set_name": "Github"
} |
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
require "spec_helper"
require "power/analyzer/entry"
require "support/fake_points"
describe Power::Analyzer::Entry do
include FakePoints
let(:datacenter) { Power::Datacenter.add(99, "PRN", "Prineville") }
let(:points) { fake_points("1000") }
let(:entry) { Power::Analyzer::Entry.new(datacenter, points) }
describe "#computed_pue" do
context "with both 'util_kwh' and 'it_kwh' present" do
let(:points) { extra_points(1.0, 2.0) }
it "returns the calculated coeficient" do
entry.computed_pue.must_equal 0.5
end
end
context "without 'util_kwh' present" do
let(:points) { extra_points(nil, 2.0) }
it "returns nothing" do
entry.computed_pue.must_be_nil
end
end
context "without 'it_kwh' present" do
let(:points) { extra_points(1.0, nil) }
it "returns nothing" do
entry.computed_pue.must_be_nil
end
end
end
describe "#computed_wue" do
context "with both 'twu' and 'it_kwh' present" do
let(:points) { extra_points(nil, 5.0, 1.0) }
it "returns the calculated coeficient" do
entry.computed_wue.must_equal 0.2
end
end
context "without 'twu' present" do
let(:points) { extra_points(nil, 2.0, nil) }
it "returns nothing" do
entry.computed_wue.must_be_nil
end
end
context "without 'it_kwh' present" do
let(:points) { extra_points(nil, nil, 1.0) }
it "returns nothing" do
entry.computed_wue.must_be_nil
end
end
end
describe "#id" do
it "uses datacenter identification as part of the ID" do
entry.id.must_include "99"
end
it "uses timestamp as part of the ID" do
entry.id.must_include "1000"
end
end
describe "#util_kwh" do
context "with 'it_kwh' pair present" do
let(:points) { extra_points(100.0, 100) }
it "returns the provided value" do
entry.util_kwh.must_equal 100.0
end
end
context "without 'it_kwh' pair present" do
let(:points) { extra_points(100.0) }
it "returns nothing" do
entry.util_kwh.must_be_nil
end
end
end
describe "#twu" do
context "with 'it_kwh' pair present" do
let(:points) { extra_points(nil, 100, 300) }
it "returns the provided value" do
entry.twu.must_equal 300
end
end
context "without 'it_kwh' pair present" do
let(:points) { extra_points(nil, nil, 300) }
it "returns nothing" do
entry.twu.must_be_nil
end
end
end
describe "#it_kwh_a" do
context "with 'util_kwh' pair present" do
let(:points) { extra_points(100, 500) }
it "returns the provided value" do
entry.it_kwh_a.must_equal 500
end
end
context "without 'util_kwh' pair present" do
let(:points) { extra_points(nil, 500) }
it "returns nothing" do
entry.it_kwh_a.must_be_nil
end
end
end
describe "#it_kwh_b" do
context "with 'twu' pair present" do
let(:points) { extra_points(nil, 500, 100) }
it "returns the provided value" do
entry.it_kwh_b.must_equal 500
end
end
context "without 'twu' pair present" do
let(:points) { extra_points(nil, 500) }
it "returns nothing" do
entry.it_kwh_b.must_be_nil
end
end
end
describe "#to_hash" do
let(:to_hash) { entry.to_hash }
it "includes the id" do
to_hash.must_include :id
end
it "includes the datacenter ID" do
to_hash.must_include :datacenter_id
end
describe "given missing points" do
let(:points) {
fake_points("1000", 1.08, 0.88, 45)
}
it "includes only the present ones" do
to_hash.must_include :pue
to_hash.must_include :wue
to_hash.must_include :temperature
to_hash.wont_include :humidity
end
end
describe "given denormalized missing points" do
context "for PUE" do
let(:points) { extra_points(100, 200) }
it "includes matching pairs" do
to_hash.must_include :util_kwh
to_hash.must_include :it_kwh_a
end
it "includes computed_pue" do
to_hash.must_include :computed_pue
end
it "does not include missing pairs" do
to_hash.wont_include :twu
to_hash.wont_include :it_kwh_b
end
end
context "for WUE" do
let(:points) { extra_points(nil, 200, 500) }
it "includes matching pairs" do
to_hash.must_include :twu
to_hash.must_include :it_kwh_b
end
it "includes computed_wue" do
to_hash.must_include :computed_wue
end
it "does not include missing pairs" do
to_hash.wont_include :util_kwh
to_hash.wont_include :it_kwh_a
end
end
end
end
describe "#to_indexed_json" do
let(:to_indexed_json) { entry.to_indexed_json }
it "serializes the attributes" do
to_indexed_json.must_be_instance_of String
to_indexed_json.must_include "timestamp"
to_indexed_json.must_include "1000"
end
end
end
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.