max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
661
#define OWL_PARSER_IMPLEMENTATION #include "1-parse.h"
23
665
<reponame>apache/isis /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.commons.internal.exceptions; import java.io.PrintStream; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.lang.Nullable; import org.apache.isis.commons.collections.Can; import org.apache.isis.commons.internal.base._NullSafe; import org.apache.isis.commons.internal.base._Strings; import org.apache.isis.commons.internal.collections._Lists; import lombok.NonNull; import lombok.val; /** * <h1>- internal use only -</h1> * <p> * A collection of framework internal exceptions and exception related idioms. * </p> * <p> * <b>WARNING</b>: Do <b>NOT</b> use any of the classes provided by this package! <br/> * These may be changed or removed without notice! * </p> * * @since 2.0 */ public final class _Exceptions { private _Exceptions(){} // -- FRAMEWORK INTERNAL ERRORS /** * Most likely to be used in switch statements to handle the default case. * @param _case the unmatched case to be reported * @return new IllegalArgumentException */ public static final IllegalArgumentException unmatchedCase(final @Nullable Object _case) { return new IllegalArgumentException("internal error: unmatched case in switch statement: "+_case); } // -- ILLEGAL ARGUMENT /** * @param format like in {@link java.lang.String#format(String, Object...)} * @param args * @return new IllegalArgumentException */ public static final IllegalArgumentException illegalArgument( final @NonNull String format, final @Nullable Object ... args) { return new IllegalArgumentException(String.format(format, args)); } // -- ILLEGAL STATE public static IllegalStateException illegalState( final @NonNull String format, final @Nullable Object ... args) { return new IllegalStateException(String.format(format, args)); } public static IllegalStateException illegalState( final @NonNull Throwable cause, final @NonNull String format, final @Nullable Object ... args) { return new IllegalStateException(String.format(format, args), cause); } // -- ILLEGAL ACCESS public static IllegalAccessException illegalAccess( final @NonNull String format, final @Nullable Object ... args) { return new IllegalAccessException(String.format(format, args)); } // -- NO SUCH ELEMENT public static final NoSuchElementException noSuchElement() { return new NoSuchElementException(); } public static final NoSuchElementException noSuchElement(final String msg) { return new NoSuchElementException(msg); } public static final NoSuchElementException noSuchElement( final @NonNull String format, final @Nullable Object ...args) { return noSuchElement(String.format(format, args)); } // -- UNEXPECTED CODE REACH public static final IllegalStateException unexpectedCodeReach() { return new IllegalStateException("internal error: code was reached, that is expected unreachable"); } // -- NOT IMPLEMENTED public static IllegalStateException notImplemented() { return new IllegalStateException("internal error: code was reached, that is not implemented yet"); } // -- UNRECOVERABLE public static RuntimeException unrecoverable(final Throwable cause) { return new RuntimeException("unrecoverable error: with cause ...", cause); } public static RuntimeException unrecoverable(final String msg) { return new RuntimeException(String.format("unrecoverable error: '%s'", msg)); } public static RuntimeException unrecoverable(final String msg, final Throwable cause) { return new RuntimeException(String.format("unrecoverable error: '%s' with cause ...", msg), cause); } public static RuntimeException unrecoverableFormatted(final String format, final Object ...args) { return new RuntimeException(String.format("unrecoverable error: '%s'", String.format(format, args))); } // -- UNSUPPORTED public static UnsupportedOperationException unsupportedOperation() { return new UnsupportedOperationException("unrecoverable error: method call not allowed/supported"); } public static UnsupportedOperationException unsupportedOperation(final String msg) { return new UnsupportedOperationException(msg); } public static UnsupportedOperationException unsupportedOperation(final String format, final Object ...args) { return new UnsupportedOperationException(String.format(format, args)); } // -- ASSERT public static AssertionError assertionError(final String msg) { return new AssertionError(msg); } // -- MESSAGE public static String getMessage(final Exception ex) { if(ex==null) { return "no exception present"; } if(_Strings.isNotEmpty(ex.getMessage())) { return ex.getMessage(); } val sb = new StringBuilder(); val nestedMsg = streamCausalChain(ex) .peek(throwable->{ sb.append(throwable.getClass().getSimpleName()).append("/"); }) .map(Throwable::getMessage) .filter(_NullSafe::isPresent) .findFirst(); if(nestedMsg.isPresent()) { sb.append(nestedMsg.get()); } else { Can.ofArray(ex.getStackTrace()) .stream() .limit(20) .forEach(trace->sb.append("\n").append(trace)); } return sb.toString(); } // -- THROWING /** * Used to hide from the compiler the fact, that this call always throws. * * <pre>{ * throw unexpectedCodeReach(); * return 0; // won't compile: unreachable code *}</pre> * * hence ... * * <pre>{ * throwUnexpectedCodeReach(); * return 0; *}</pre> * */ public static void throwUnexpectedCodeReach() { throw unexpectedCodeReach(); } /** * Used to hide from the compiler the fact, that this call always throws. * * <pre>{ * throw notImplemented(); * return 0; // won't compile: unreachable code *}</pre> * * hence ... * * <pre>{ * throwNotImplemented(); * return 0; *}</pre> * */ public static void throwNotImplemented() { dumpStackTrace(); throw notImplemented(); } // -- SELECTIVE ERROR SUPPRESSION // /** // * Allows to selectively ignore unchecked exceptions. Most likely used framework internally // * for workarounds, not properly dealing with the root cause. This way at least we know, where // * we placed such workarounds. // * // * @param runnable that might throw an unchecked exception // * @param suppress predicate that decides whether to suppress an exception // */ // public static void catchSilently( // Runnable runnable, // Predicate<RuntimeException> suppress) { // // try { // runnable.run(); // } catch (RuntimeException cause) { // if(suppress.test(cause)) { // return; // } // throw cause; // } // } // -- SELECTIVE THROW public static <E extends Exception> void throwWhenTrue(final E cause, final Predicate<E> test) throws E { if(test.test(cause)) { throw cause; } } // -- STACKTRACE UTILITITIES public static final Stream<String> streamStacktraceLines(final @Nullable Throwable ex, final int maxLines) { if(ex==null) { return Stream.empty(); } return _NullSafe.stream(ex.getStackTrace()) .map(StackTraceElement::toString) .limit(maxLines); } public static final String asStacktrace(final @Nullable Throwable ex, final int maxLines, final String delimiter) { return _Exceptions.streamStacktraceLines(ex, maxLines) .collect(Collectors.joining(delimiter)); } public static final String asStacktrace(final @Nullable Throwable ex, final int maxLines) { return asStacktrace(ex, maxLines, "\n"); } public static final String asStacktrace(final @Nullable Throwable ex) { return asStacktrace(ex, 1000); } /** * Dumps the current thread's stack-trace onto the given {@code writer}. * @param writer * @param skipLines * @param maxLines */ public static void dumpStackTrace(final PrintStream writer, final int skipLines, final int maxLines) { _NullSafe.stream(Thread.currentThread().getStackTrace()) .map(StackTraceElement::toString) .skip(skipLines) .limit(maxLines) .forEach(writer::println); } public static void dumpStackTrace() { dumpStackTrace(System.err, 0, 1000); } // -- CAUSAL CHAIN public static List<Throwable> getCausalChain(final @Nullable Throwable ex) { if(ex==null) { return Collections.emptyList(); } final List<Throwable> chain = _Lists.newArrayList(); Throwable t = ex; while(t!=null) { chain.add(t); t = t.getCause(); } return chain; } public static Stream<Throwable> streamCausalChain(final @Nullable Throwable ex) { if(ex==null) { return Stream.empty(); } val chain = getCausalChain(ex); return chain.stream(); } public static Throwable getRootCause(final @Nullable Throwable ex) { return _Lists.lastElementIfAny(getCausalChain(ex)); } // -- SWALLOW public static void silence(final Runnable runnable) { val currentThread = Thread.currentThread(); val silencedHandler = currentThread.getUncaughtExceptionHandler(); currentThread.setUncaughtExceptionHandler((final Thread t, final Throwable e)->{/*noop*/}); try { runnable.run(); } finally { currentThread.setUncaughtExceptionHandler(silencedHandler); } } // -- PREDICATES public static boolean containsAnyOfTheseMessages( final @Nullable Throwable throwable, final @Nullable String ... messages) { if(throwable==null) { return false; } val throwableMessage = throwable.getMessage(); if(throwableMessage == null || _NullSafe.isEmpty(messages)) { return false; } for (String message : messages) { if(_Strings.isNotEmpty(message) && throwableMessage.contains(message)) { return true; } } return false; } // -- FLUENT EXCEPTION /** * [ahuber] Experimental, remove if it adds no value. Otherwise expand. */ public static class FluentException<E extends Exception> { public static <E extends Exception> FluentException<E> of(final E cause) { return new FluentException<>(cause); } private final E cause; private FluentException(final @NonNull E cause) { this.cause = cause; } public E getCause() { return cause; } public Optional<String> getMessage() { return Optional.ofNullable(cause.getMessage()); } // -- RE-THROW IDIOMS public void rethrow() throws E { throw cause; } public void rethrowIf(final @NonNull Predicate<E> condition) throws E { if(condition.test(cause)) { throw cause; } } public void suppressIf(final @NonNull Predicate<E> condition) throws E { if(!condition.test(cause)) { throw cause; } } public void rethrowIfMessageContains(final @NonNull String string) throws E { final boolean containsMessage = getMessage().map(msg->msg.contains(string)).orElse(false); if(containsMessage) { throw cause; } } public void suppressIfMessageContains(final @NonNull String string) throws E { final boolean containsMessage = getMessage().map(msg->msg.contains(string)).orElse(false); if(!containsMessage) { throw cause; } } } }
5,289
617
<gh_stars>100-1000 #!/usr/bin/env python from __future__ import absolute_import import base64 import json import logging import os import requests import thriftrw from kazoo.client import KazooClient api = thriftrw.install( os.path.join( os.path.dirname(os.path.realpath(__file__)), "../../pkg/aurorabridge/thrift/api.thrift", ) ) AuroraSchedulerManager = api.AuroraSchedulerManager ReadOnlyScheduler = api.ReadOnlyScheduler log = logging.getLogger(__name__) MEMBER_PREFIX = "member_" ZK_PATH = "peloton/aurora/scheduler" class ResponseError(Exception): """ Raised whenever there is a non-OK response code. """ def __init__(self, response): self.code = response.responseCode self.msg = ",".join(map(lambda d: d.message, response.details)) def __str__(self): return "bad response: {code} {msg}".format( code=api.ResponseCode.name_of(self.code), msg=self.msg ) class Client(object): def __init__(self, zookeeper): self.zookeeper = eval('[\'' + zookeeper + '\']') def get_job_update_summaries(self, *args): res = self._send( ReadOnlyScheduler, ReadOnlyScheduler.getJobUpdateSummaries, *args ) return res.result.getJobUpdateSummariesResult def get_job_update_details(self, *args): res = self._send( ReadOnlyScheduler, ReadOnlyScheduler.getJobUpdateDetails, *args ) return res.result.getJobUpdateDetailsResult def get_job_summary(self, *args): res = self._send( ReadOnlyScheduler, ReadOnlyScheduler.getJobSummary, *args ) return res.result.jobSummaryResult def get_jobs(self, *args): res = self._send(ReadOnlyScheduler, ReadOnlyScheduler.getJobs, *args) return res.result.getJobsResult def get_tasks_without_configs(self, *args): res = self._send( ReadOnlyScheduler, ReadOnlyScheduler.getTasksWithoutConfigs, *args ) return res.result.scheduleStatusResult def get_config_summary(self, *args): res = self._send( ReadOnlyScheduler, ReadOnlyScheduler.getConfigSummary, *args ) return res.result.configSummaryResult def kill_tasks(self, *args): self._send( AuroraSchedulerManager, AuroraSchedulerManager.killTasks, *args ) # killTasks has no result. def pulse_job_update(self, *args): res = self._send( AuroraSchedulerManager, AuroraSchedulerManager.pulseJobUpdate, *args ) return res.result.pulseJobUpdateResult def start_job_update(self, *args): res = self._send( AuroraSchedulerManager, AuroraSchedulerManager.startJobUpdate, *args ) return res.result.startJobUpdateResult def abort_job_update(self, *args): self._send( AuroraSchedulerManager, AuroraSchedulerManager.abortJobUpdate, *args ) # abortJobUpdate has no result def pause_job_update(self, *args): self._send( AuroraSchedulerManager, AuroraSchedulerManager.pauseJobUpdate, *args ) # pauseJobUpdate has no result def rollback_job_update(self, *args): self._send( AuroraSchedulerManager, AuroraSchedulerManager.rollbackJobUpdate, *args ) # rollbackJobUpdate has no result def _send(self, service, method, *args): zk_client = KazooClient(",".join(self.zookeeper)) leader_node_name = None try: zk_client.start() for znode_name in zk_client.get_children(ZK_PATH): if znode_name.startswith(MEMBER_PREFIX): leader_node_name = znode_name if not leader_node_name: raise Exception( "leader name is not defined %s" % self.zookeeper ) leader_node_info = zk_client.get( "%s/%s" % (ZK_PATH, leader_node_name) ) instance = json.loads(leader_node_info[0]) additional_endpoints = instance.get("additionalEndpoints", []) for proto in ["https", "http"]: if proto in additional_endpoints: endpoint = additional_endpoints[proto] host = endpoint.get("host", None) port = endpoint.get("port", None) req = method.request(*args) res = requests.post( "http://%s:%s/api" % (host, port), headers={ "Rpc-Caller": "aurorabridge-test-client", "Rpc-Encoding": "thrift", "Rpc-Service": "peloton-aurorabridge", "Rpc-Procedure": "%s::%s" % (service.__name__, method.name), "Context-TTL-MS": "30000", }, data=api.dumps(req), ) if res.status_code != 200: raise Exception( "{url} {method}: {code} {reason}: {body}".format( url=res.url, method=method.name, code=res.status_code, reason=res.reason, body=res.text, ) ) response = api.loads(method.response, res.content).success if response.responseCode != api.ResponseCode.OK: raise ResponseError(response) return response except Exception as e: print e finally: zk_client.stop()
3,054
4,332
<reponame>HollowMan6/vowpal_wabbit #include "vw/config/cli_help_formatter.h" #include "vw/config/option_builder.h" #include "vw/config/option_group_definition.h" #include "vw/config/options_cli.h" #include "vw/core/crossplat_compat.h" #include "vw/core/vw.h" #include <unistd.h> #include <algorithm> #include <cassert> #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <queue> #include <utility> #include <vector> int pairs = 0; int users = 0; int items = 0; int recs = 0; int skipped = 0; int banned = 0; int show = 1; int bits = 16; int topk = 10; int verbose = 0; std::string blacklistfilename; std::string itemfilename; std::string userfilename; std::string vwparams; void progress() { fprintf(stderr, "%12d %8d %8d %8d %12d %s %s\n", pairs, users, items, recs, skipped, userfilename.c_str(), itemfilename.c_str()); } #define MASK(u, b) (u & ((1UL << b) - 1)) #define NUM_HASHES 2 void get_hashv(char* in, size_t len, unsigned* out) { assert(NUM_HASHES == 2); out[0] = MASK(VW::uniform_hash(in, len, 1), bits); out[1] = MASK(VW::uniform_hash(in, len, 2), bits); } #define BIT_TEST(c, i) (c[i / 8] & (1 << (i % 8))) #define BIT_SET(c, i) (c[i / 8] |= (1 << (i % 8))) #define byte_len(b) (((1UL << b) / 8) + (((1UL << b) % 8) ? 1 : 0)) #define num_bits(b) (1UL << b) char* bf_new(unsigned b) { char* bf = (char* )calloc(1, byte_len(b)); return bf; } void bf_add(char* bf, char* line) { unsigned i, hashv[NUM_HASHES]; get_hashv(line, strlen(line), hashv); for (i = 0; i < NUM_HASHES; i++) { BIT_SET(bf, hashv[i]); } } void bf_info(char* bf, FILE* f) { unsigned i, on = 0; for (i = 0; i < num_bits(bits); i++) { if (BIT_TEST(bf, i)) { on++; } } fprintf(f, "%.2f%% saturation\n%lu bf bit size\n", on * 100.0 / num_bits(bits), num_bits(bits)); } int bf_hit(char* bf, char* line) { unsigned i, hashv[NUM_HASHES]; get_hashv(line, strlen(line), hashv); for (i = 0; i < NUM_HASHES; i++) { if (BIT_TEST(bf, hashv[i]) == 0) { return 0; } } return 1; } using scored_example = std::pair<float, std::string>; std::vector<scored_example> scored_examples; struct compare_scored_examples { bool operator()(scored_example const &lhs, scored_example const &rhs) const { return lhs.first > rhs.first; } }; std::priority_queue<scored_example, std::vector<scored_example>, compare_scored_examples> pr_queue; int main(int argc, char* argv[]) { using std::cerr; using std::cout; using std::endl; bool help; VW::config::options_cli opts(std::vector<std::string>(argv + 1, argv + argc)); VW::config::option_group_definition desc("Recommend"); desc.add(VW::config::make_option("help", help).short_name("h").help("Produce help message")) .add(VW::config::make_option("topk", topk).default_value(10).help("Number of items to recommend per user")) .add(VW::config::make_option("verbose", verbose).short_name("v").help("Increase verbosity (can be repeated)")) .add(VW::config::make_option("bf_bits", bits) .default_value(16) .short_name("b") .help("Number of items to recommend")) .add(VW::config::make_option("blacklist", blacklistfilename) .short_name("B") .help("User item pairs (in vw format) that we should not recommend (have been seen before)")) .add(VW::config::make_option("users", userfilename) .short_name("U") .help("Users portion in vw format to make recs for")) .add( VW::config::make_option("items", itemfilename).short_name("I").help("Items (in vw format) to recommend from")) .add(VW::config::make_option("vwparams", vwparams).help("vw parameters for model instantiation (-i model ...)")); opts.add_and_parse(desc); // Return value is ignored as option reachability is not relevant here. auto warnings = opts.check_unregistered(); _UNUSED(warnings); VW::config::cli_help_formatter help_formatter; const auto help_message = help_formatter.format_help(opts.get_all_option_group_definitions()); if (help) { VW::config::cli_help_formatter help_formatter; std::cout << help_message << std::endl; return 1; } if (blacklistfilename.empty() || userfilename.empty() || itemfilename.empty() || vwparams.empty()) { VW::config::cli_help_formatter help_formatter; std::cout << help_message << std::endl; exit(2); } FILE* fB; FILE* fU; FILE* fI; if (VW::file_open(&fB, blacklistfilename.c_str(), "r") != 0) { fprintf(stderr, "can't open %s: %s\n", blacklistfilename.c_str(), VW::strerror_to_string(errno).c_str()); cerr << help_message << endl; exit(2); } if (VW::file_open(&fU, userfilename.c_str(), "r") != 0) { fprintf(stderr, "can't open %s: %s\n", userfilename.c_str(), VW::strerror_to_string(errno).c_str()); cerr << help_message << endl; exit(2); } if (VW::file_open(&fI, itemfilename.c_str(), "r") != 0) { fprintf(stderr, "can't open %s: %s\n", itemfilename.c_str(), VW::strerror_to_string(errno).c_str()); cerr << help_message << endl; exit(2); } char* buf = NULL; char* u = NULL; char* i = NULL; size_t len = 0; ssize_t read; /* make the bloom filter */ if (verbose > 0) { fprintf(stderr, "loading blacklist into bloom filter...\n"); } char* bf = bf_new(bits); /* loop over the source file */ while ((read = getline(&buf, &len, fB)) != -1) { bf_add(bf, buf); banned++; } /* print saturation etc */ if (verbose) { bf_info(bf, stderr); fprintf(stderr, "%d banned pairs\n", banned); } // INITIALIZE WITH WHATEVER YOU WOULD PUT ON THE VW COMMAND LINE if (verbose > 0) { fprintf(stderr, "initializing vw...\n"); } VW::workspace* model = VW::initialize(vwparams); char* estr = NULL; if (verbose > 0) { fprintf(stderr, "predicting...\n"); fprintf(stderr, "%12s %8s %8s %8s %12s %s %s\n", "pair", "user", "item", "rec", "skipped", "userfile", "itemfile"); } while ((read = getline(&u, &len, fU)) != -1) { users++; u[strlen(u) - 1] = 0; // chop rewind(fI); items = 0; while ((read = getline(&i, &len, fI)) != -1) { items++; pairs++; if ((verbose > 0) & (pairs % show == 0)) { progress(); show *= 2; } free(estr); estr = strdup((std::string(u) + std::string(i)).c_str()); if (!bf_hit(bf, estr)) { VW::example* ex = VW::read_example(*model, estr); model->learn(*ex); const std::string str(estr); if (pr_queue.size() < (size_t)topk) { pr_queue.push(std::make_pair(ex->pred.scalar, str)); } else if (pr_queue.top().first < ex->pred.scalar) { pr_queue.pop(); pr_queue.push(std::make_pair(ex->pred.scalar, str)); } VW::finish_example(*model, *ex); } else { skipped++; if (verbose >= 2) { fprintf(stderr, "skipping:#%s#\n", estr); } } } while (!pr_queue.empty()) { cout << pr_queue.top().first << "\t" << pr_queue.top().second; pr_queue.pop(); recs++; } } if (verbose > 0) { progress(); } VW::finish(*model); fclose(fI); fclose(fU); return 0; }
3,221
1,443
<reponame>cssence/mit-license<filename>users/neutroncreations.json { "copyright": "Neutron Creations, http://neutroncreations.com", "url": "http://neutroncreations.com" }
67
316
<reponame>burgerdev/vigra<filename>test/classifier/data/SPECTF_labels.hxx #ifndef SPECTF_LABELS #define SPECTF_LABELS int SPECTF_labels[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int SPECTF_Classes[] = {0,1}; int SPECTF_size = 2; #endif
334
3,372
<gh_stars>1000+ /* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.auditmanager; import javax.annotation.Generated; import com.amazonaws.services.auditmanager.model.*; /** * Interface for accessing AWS Audit Manager asynchronously. Each asynchronous method will return a Java Future object * representing the asynchronous operation; overloads which accept an {@code AsyncHandler} can be used to receive * notification when an asynchronous operation completes. * <p> * <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from * {@link com.amazonaws.services.auditmanager.AbstractAWSAuditManagerAsync} instead. * </p> * <p> * <p> * Welcome to the Audit Manager API reference. This guide is for developers who need detailed information about the * Audit Manager API operations, data types, and errors. * </p> * <p> * Audit Manager is a service that provides automated evidence collection so that you can continuously audit your Amazon * Web Services usage, and assess the effectiveness of your controls to better manage risk and simplify compliance. * </p> * <p> * Audit Manager provides pre-built frameworks that structure and automate assessments for a given compliance standard. * Frameworks include a pre-built collection of controls with descriptions and testing procedures, which are grouped * according to the requirements of the specified compliance standard or regulation. You can also customize frameworks * and controls to support internal audits with unique requirements. * </p> * <p> * Use the following links to get started with the Audit Manager API: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/API_Operations.html">Actions</a>: An * alphabetical list of all Audit Manager API operations. * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/API_Types.html">Data types</a>: An * alphabetical list of all Audit Manager data types. * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/CommonParameters.html">Common parameters</a>: * Parameters that all Query operations can use. * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/CommonErrors.html">Common errors</a>: Client * and server errors that all operations can return. * </p> * </li> * </ul> * <p> * If you're new to Audit Manager, we recommend that you review the <a * href="https://docs.aws.amazon.com/audit-manager/latest/userguide/what-is.html"> Audit Manager User Guide</a>. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public interface AWSAuditManagerAsync extends AWSAuditManager { /** * <p> * Associates an evidence folder to the specified assessment report in Audit Manager. * </p> * * @param associateAssessmentReportEvidenceFolderRequest * @return A Java Future containing the result of the AssociateAssessmentReportEvidenceFolder operation returned by * the service. * @sample AWSAuditManagerAsync.AssociateAssessmentReportEvidenceFolder * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/AssociateAssessmentReportEvidenceFolder" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<AssociateAssessmentReportEvidenceFolderResult> associateAssessmentReportEvidenceFolderAsync( AssociateAssessmentReportEvidenceFolderRequest associateAssessmentReportEvidenceFolderRequest); /** * <p> * Associates an evidence folder to the specified assessment report in Audit Manager. * </p> * * @param associateAssessmentReportEvidenceFolderRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the AssociateAssessmentReportEvidenceFolder operation returned by * the service. * @sample AWSAuditManagerAsyncHandler.AssociateAssessmentReportEvidenceFolder * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/AssociateAssessmentReportEvidenceFolder" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<AssociateAssessmentReportEvidenceFolderResult> associateAssessmentReportEvidenceFolderAsync( AssociateAssessmentReportEvidenceFolderRequest associateAssessmentReportEvidenceFolderRequest, com.amazonaws.handlers.AsyncHandler<AssociateAssessmentReportEvidenceFolderRequest, AssociateAssessmentReportEvidenceFolderResult> asyncHandler); /** * <p> * Associates a list of evidence to an assessment report in an Audit Manager assessment. * </p> * * @param batchAssociateAssessmentReportEvidenceRequest * @return A Java Future containing the result of the BatchAssociateAssessmentReportEvidence operation returned by * the service. * @sample AWSAuditManagerAsync.BatchAssociateAssessmentReportEvidence * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchAssociateAssessmentReportEvidence" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<BatchAssociateAssessmentReportEvidenceResult> batchAssociateAssessmentReportEvidenceAsync( BatchAssociateAssessmentReportEvidenceRequest batchAssociateAssessmentReportEvidenceRequest); /** * <p> * Associates a list of evidence to an assessment report in an Audit Manager assessment. * </p> * * @param batchAssociateAssessmentReportEvidenceRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the BatchAssociateAssessmentReportEvidence operation returned by * the service. * @sample AWSAuditManagerAsyncHandler.BatchAssociateAssessmentReportEvidence * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchAssociateAssessmentReportEvidence" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<BatchAssociateAssessmentReportEvidenceResult> batchAssociateAssessmentReportEvidenceAsync( BatchAssociateAssessmentReportEvidenceRequest batchAssociateAssessmentReportEvidenceRequest, com.amazonaws.handlers.AsyncHandler<BatchAssociateAssessmentReportEvidenceRequest, BatchAssociateAssessmentReportEvidenceResult> asyncHandler); /** * <p> * Create a batch of delegations for a specified assessment in Audit Manager. * </p> * * @param batchCreateDelegationByAssessmentRequest * @return A Java Future containing the result of the BatchCreateDelegationByAssessment operation returned by the * service. * @sample AWSAuditManagerAsync.BatchCreateDelegationByAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchCreateDelegationByAssessment" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<BatchCreateDelegationByAssessmentResult> batchCreateDelegationByAssessmentAsync( BatchCreateDelegationByAssessmentRequest batchCreateDelegationByAssessmentRequest); /** * <p> * Create a batch of delegations for a specified assessment in Audit Manager. * </p> * * @param batchCreateDelegationByAssessmentRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the BatchCreateDelegationByAssessment operation returned by the * service. * @sample AWSAuditManagerAsyncHandler.BatchCreateDelegationByAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchCreateDelegationByAssessment" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<BatchCreateDelegationByAssessmentResult> batchCreateDelegationByAssessmentAsync( BatchCreateDelegationByAssessmentRequest batchCreateDelegationByAssessmentRequest, com.amazonaws.handlers.AsyncHandler<BatchCreateDelegationByAssessmentRequest, BatchCreateDelegationByAssessmentResult> asyncHandler); /** * <p> * Deletes the delegations in the specified Audit Manager assessment. * </p> * * @param batchDeleteDelegationByAssessmentRequest * @return A Java Future containing the result of the BatchDeleteDelegationByAssessment operation returned by the * service. * @sample AWSAuditManagerAsync.BatchDeleteDelegationByAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDeleteDelegationByAssessment" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<BatchDeleteDelegationByAssessmentResult> batchDeleteDelegationByAssessmentAsync( BatchDeleteDelegationByAssessmentRequest batchDeleteDelegationByAssessmentRequest); /** * <p> * Deletes the delegations in the specified Audit Manager assessment. * </p> * * @param batchDeleteDelegationByAssessmentRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the BatchDeleteDelegationByAssessment operation returned by the * service. * @sample AWSAuditManagerAsyncHandler.BatchDeleteDelegationByAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDeleteDelegationByAssessment" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<BatchDeleteDelegationByAssessmentResult> batchDeleteDelegationByAssessmentAsync( BatchDeleteDelegationByAssessmentRequest batchDeleteDelegationByAssessmentRequest, com.amazonaws.handlers.AsyncHandler<BatchDeleteDelegationByAssessmentRequest, BatchDeleteDelegationByAssessmentResult> asyncHandler); /** * <p> * Disassociates a list of evidence from the specified assessment report in Audit Manager. * </p> * * @param batchDisassociateAssessmentReportEvidenceRequest * @return A Java Future containing the result of the BatchDisassociateAssessmentReportEvidence operation returned * by the service. * @sample AWSAuditManagerAsync.BatchDisassociateAssessmentReportEvidence * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDisassociateAssessmentReportEvidence" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<BatchDisassociateAssessmentReportEvidenceResult> batchDisassociateAssessmentReportEvidenceAsync( BatchDisassociateAssessmentReportEvidenceRequest batchDisassociateAssessmentReportEvidenceRequest); /** * <p> * Disassociates a list of evidence from the specified assessment report in Audit Manager. * </p> * * @param batchDisassociateAssessmentReportEvidenceRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the BatchDisassociateAssessmentReportEvidence operation returned * by the service. * @sample AWSAuditManagerAsyncHandler.BatchDisassociateAssessmentReportEvidence * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDisassociateAssessmentReportEvidence" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<BatchDisassociateAssessmentReportEvidenceResult> batchDisassociateAssessmentReportEvidenceAsync( BatchDisassociateAssessmentReportEvidenceRequest batchDisassociateAssessmentReportEvidenceRequest, com.amazonaws.handlers.AsyncHandler<BatchDisassociateAssessmentReportEvidenceRequest, BatchDisassociateAssessmentReportEvidenceResult> asyncHandler); /** * <p> * Uploads one or more pieces of evidence to the specified control in the assessment in Audit Manager. * </p> * * @param batchImportEvidenceToAssessmentControlRequest * @return A Java Future containing the result of the BatchImportEvidenceToAssessmentControl operation returned by * the service. * @sample AWSAuditManagerAsync.BatchImportEvidenceToAssessmentControl * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchImportEvidenceToAssessmentControl" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<BatchImportEvidenceToAssessmentControlResult> batchImportEvidenceToAssessmentControlAsync( BatchImportEvidenceToAssessmentControlRequest batchImportEvidenceToAssessmentControlRequest); /** * <p> * Uploads one or more pieces of evidence to the specified control in the assessment in Audit Manager. * </p> * * @param batchImportEvidenceToAssessmentControlRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the BatchImportEvidenceToAssessmentControl operation returned by * the service. * @sample AWSAuditManagerAsyncHandler.BatchImportEvidenceToAssessmentControl * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchImportEvidenceToAssessmentControl" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<BatchImportEvidenceToAssessmentControlResult> batchImportEvidenceToAssessmentControlAsync( BatchImportEvidenceToAssessmentControlRequest batchImportEvidenceToAssessmentControlRequest, com.amazonaws.handlers.AsyncHandler<BatchImportEvidenceToAssessmentControlRequest, BatchImportEvidenceToAssessmentControlResult> asyncHandler); /** * <p> * Creates an assessment in Audit Manager. * </p> * * @param createAssessmentRequest * @return A Java Future containing the result of the CreateAssessment operation returned by the service. * @sample AWSAuditManagerAsync.CreateAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessment" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<CreateAssessmentResult> createAssessmentAsync(CreateAssessmentRequest createAssessmentRequest); /** * <p> * Creates an assessment in Audit Manager. * </p> * * @param createAssessmentRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the CreateAssessment operation returned by the service. * @sample AWSAuditManagerAsyncHandler.CreateAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessment" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<CreateAssessmentResult> createAssessmentAsync(CreateAssessmentRequest createAssessmentRequest, com.amazonaws.handlers.AsyncHandler<CreateAssessmentRequest, CreateAssessmentResult> asyncHandler); /** * <p> * Creates a custom framework in Audit Manager. * </p> * * @param createAssessmentFrameworkRequest * @return A Java Future containing the result of the CreateAssessmentFramework operation returned by the service. * @sample AWSAuditManagerAsync.CreateAssessmentFramework * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentFramework" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<CreateAssessmentFrameworkResult> createAssessmentFrameworkAsync( CreateAssessmentFrameworkRequest createAssessmentFrameworkRequest); /** * <p> * Creates a custom framework in Audit Manager. * </p> * * @param createAssessmentFrameworkRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the CreateAssessmentFramework operation returned by the service. * @sample AWSAuditManagerAsyncHandler.CreateAssessmentFramework * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentFramework" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<CreateAssessmentFrameworkResult> createAssessmentFrameworkAsync( CreateAssessmentFrameworkRequest createAssessmentFrameworkRequest, com.amazonaws.handlers.AsyncHandler<CreateAssessmentFrameworkRequest, CreateAssessmentFrameworkResult> asyncHandler); /** * <p> * Creates an assessment report for the specified assessment. * </p> * * @param createAssessmentReportRequest * @return A Java Future containing the result of the CreateAssessmentReport operation returned by the service. * @sample AWSAuditManagerAsync.CreateAssessmentReport * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentReport" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<CreateAssessmentReportResult> createAssessmentReportAsync(CreateAssessmentReportRequest createAssessmentReportRequest); /** * <p> * Creates an assessment report for the specified assessment. * </p> * * @param createAssessmentReportRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the CreateAssessmentReport operation returned by the service. * @sample AWSAuditManagerAsyncHandler.CreateAssessmentReport * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentReport" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<CreateAssessmentReportResult> createAssessmentReportAsync(CreateAssessmentReportRequest createAssessmentReportRequest, com.amazonaws.handlers.AsyncHandler<CreateAssessmentReportRequest, CreateAssessmentReportResult> asyncHandler); /** * <p> * Creates a new custom control in Audit Manager. * </p> * * @param createControlRequest * @return A Java Future containing the result of the CreateControl operation returned by the service. * @sample AWSAuditManagerAsync.CreateControl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateControl" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<CreateControlResult> createControlAsync(CreateControlRequest createControlRequest); /** * <p> * Creates a new custom control in Audit Manager. * </p> * * @param createControlRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the CreateControl operation returned by the service. * @sample AWSAuditManagerAsyncHandler.CreateControl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateControl" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<CreateControlResult> createControlAsync(CreateControlRequest createControlRequest, com.amazonaws.handlers.AsyncHandler<CreateControlRequest, CreateControlResult> asyncHandler); /** * <p> * Deletes an assessment in Audit Manager. * </p> * * @param deleteAssessmentRequest * @return A Java Future containing the result of the DeleteAssessment operation returned by the service. * @sample AWSAuditManagerAsync.DeleteAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessment" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<DeleteAssessmentResult> deleteAssessmentAsync(DeleteAssessmentRequest deleteAssessmentRequest); /** * <p> * Deletes an assessment in Audit Manager. * </p> * * @param deleteAssessmentRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the DeleteAssessment operation returned by the service. * @sample AWSAuditManagerAsyncHandler.DeleteAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessment" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<DeleteAssessmentResult> deleteAssessmentAsync(DeleteAssessmentRequest deleteAssessmentRequest, com.amazonaws.handlers.AsyncHandler<DeleteAssessmentRequest, DeleteAssessmentResult> asyncHandler); /** * <p> * Deletes a custom framework in Audit Manager. * </p> * * @param deleteAssessmentFrameworkRequest * @return A Java Future containing the result of the DeleteAssessmentFramework operation returned by the service. * @sample AWSAuditManagerAsync.DeleteAssessmentFramework * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentFramework" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<DeleteAssessmentFrameworkResult> deleteAssessmentFrameworkAsync( DeleteAssessmentFrameworkRequest deleteAssessmentFrameworkRequest); /** * <p> * Deletes a custom framework in Audit Manager. * </p> * * @param deleteAssessmentFrameworkRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the DeleteAssessmentFramework operation returned by the service. * @sample AWSAuditManagerAsyncHandler.DeleteAssessmentFramework * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentFramework" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<DeleteAssessmentFrameworkResult> deleteAssessmentFrameworkAsync( DeleteAssessmentFrameworkRequest deleteAssessmentFrameworkRequest, com.amazonaws.handlers.AsyncHandler<DeleteAssessmentFrameworkRequest, DeleteAssessmentFrameworkResult> asyncHandler); /** * <p> * Deletes an assessment report from an assessment in Audit Manager. * </p> * * @param deleteAssessmentReportRequest * @return A Java Future containing the result of the DeleteAssessmentReport operation returned by the service. * @sample AWSAuditManagerAsync.DeleteAssessmentReport * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentReport" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<DeleteAssessmentReportResult> deleteAssessmentReportAsync(DeleteAssessmentReportRequest deleteAssessmentReportRequest); /** * <p> * Deletes an assessment report from an assessment in Audit Manager. * </p> * * @param deleteAssessmentReportRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the DeleteAssessmentReport operation returned by the service. * @sample AWSAuditManagerAsyncHandler.DeleteAssessmentReport * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentReport" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<DeleteAssessmentReportResult> deleteAssessmentReportAsync(DeleteAssessmentReportRequest deleteAssessmentReportRequest, com.amazonaws.handlers.AsyncHandler<DeleteAssessmentReportRequest, DeleteAssessmentReportResult> asyncHandler); /** * <p> * Deletes a custom control in Audit Manager. * </p> * * @param deleteControlRequest * @return A Java Future containing the result of the DeleteControl operation returned by the service. * @sample AWSAuditManagerAsync.DeleteControl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteControl" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<DeleteControlResult> deleteControlAsync(DeleteControlRequest deleteControlRequest); /** * <p> * Deletes a custom control in Audit Manager. * </p> * * @param deleteControlRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the DeleteControl operation returned by the service. * @sample AWSAuditManagerAsyncHandler.DeleteControl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteControl" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<DeleteControlResult> deleteControlAsync(DeleteControlRequest deleteControlRequest, com.amazonaws.handlers.AsyncHandler<DeleteControlRequest, DeleteControlResult> asyncHandler); /** * <p> * Deregisters an account in Audit Manager. * </p> * * @param deregisterAccountRequest * @return A Java Future containing the result of the DeregisterAccount operation returned by the service. * @sample AWSAuditManagerAsync.DeregisterAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterAccount" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<DeregisterAccountResult> deregisterAccountAsync(DeregisterAccountRequest deregisterAccountRequest); /** * <p> * Deregisters an account in Audit Manager. * </p> * * @param deregisterAccountRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the DeregisterAccount operation returned by the service. * @sample AWSAuditManagerAsyncHandler.DeregisterAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterAccount" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<DeregisterAccountResult> deregisterAccountAsync(DeregisterAccountRequest deregisterAccountRequest, com.amazonaws.handlers.AsyncHandler<DeregisterAccountRequest, DeregisterAccountResult> asyncHandler); /** * <p> * Removes the specified member account as a delegated administrator for Audit Manager. * </p> * <important> * <p> * When you remove a delegated administrator from your Audit Manager settings, or when you deregister a delegated * administrator from Organizations, you continue to have access to the evidence that you previously collected under * that account. However, Audit Manager will stop collecting and attaching evidence to that delegated administrator * account moving forward. * </p> * </important> * * @param deregisterOrganizationAdminAccountRequest * @return A Java Future containing the result of the DeregisterOrganizationAdminAccount operation returned by the * service. * @sample AWSAuditManagerAsync.DeregisterOrganizationAdminAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterOrganizationAdminAccount" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<DeregisterOrganizationAdminAccountResult> deregisterOrganizationAdminAccountAsync( DeregisterOrganizationAdminAccountRequest deregisterOrganizationAdminAccountRequest); /** * <p> * Removes the specified member account as a delegated administrator for Audit Manager. * </p> * <important> * <p> * When you remove a delegated administrator from your Audit Manager settings, or when you deregister a delegated * administrator from Organizations, you continue to have access to the evidence that you previously collected under * that account. However, Audit Manager will stop collecting and attaching evidence to that delegated administrator * account moving forward. * </p> * </important> * * @param deregisterOrganizationAdminAccountRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the DeregisterOrganizationAdminAccount operation returned by the * service. * @sample AWSAuditManagerAsyncHandler.DeregisterOrganizationAdminAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterOrganizationAdminAccount" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<DeregisterOrganizationAdminAccountResult> deregisterOrganizationAdminAccountAsync( DeregisterOrganizationAdminAccountRequest deregisterOrganizationAdminAccountRequest, com.amazonaws.handlers.AsyncHandler<DeregisterOrganizationAdminAccountRequest, DeregisterOrganizationAdminAccountResult> asyncHandler); /** * <p> * Disassociates an evidence folder from the specified assessment report in Audit Manager. * </p> * * @param disassociateAssessmentReportEvidenceFolderRequest * @return A Java Future containing the result of the DisassociateAssessmentReportEvidenceFolder operation returned * by the service. * @sample AWSAuditManagerAsync.DisassociateAssessmentReportEvidenceFolder * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DisassociateAssessmentReportEvidenceFolder" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<DisassociateAssessmentReportEvidenceFolderResult> disassociateAssessmentReportEvidenceFolderAsync( DisassociateAssessmentReportEvidenceFolderRequest disassociateAssessmentReportEvidenceFolderRequest); /** * <p> * Disassociates an evidence folder from the specified assessment report in Audit Manager. * </p> * * @param disassociateAssessmentReportEvidenceFolderRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the DisassociateAssessmentReportEvidenceFolder operation returned * by the service. * @sample AWSAuditManagerAsyncHandler.DisassociateAssessmentReportEvidenceFolder * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DisassociateAssessmentReportEvidenceFolder" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<DisassociateAssessmentReportEvidenceFolderResult> disassociateAssessmentReportEvidenceFolderAsync( DisassociateAssessmentReportEvidenceFolderRequest disassociateAssessmentReportEvidenceFolderRequest, com.amazonaws.handlers.AsyncHandler<DisassociateAssessmentReportEvidenceFolderRequest, DisassociateAssessmentReportEvidenceFolderResult> asyncHandler); /** * <p> * Returns the registration status of an account in Audit Manager. * </p> * * @param getAccountStatusRequest * @return A Java Future containing the result of the GetAccountStatus operation returned by the service. * @sample AWSAuditManagerAsync.GetAccountStatus * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAccountStatus" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<GetAccountStatusResult> getAccountStatusAsync(GetAccountStatusRequest getAccountStatusRequest); /** * <p> * Returns the registration status of an account in Audit Manager. * </p> * * @param getAccountStatusRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetAccountStatus operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetAccountStatus * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAccountStatus" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<GetAccountStatusResult> getAccountStatusAsync(GetAccountStatusRequest getAccountStatusRequest, com.amazonaws.handlers.AsyncHandler<GetAccountStatusRequest, GetAccountStatusResult> asyncHandler); /** * <p> * Returns an assessment from Audit Manager. * </p> * * @param getAssessmentRequest * @return A Java Future containing the result of the GetAssessment operation returned by the service. * @sample AWSAuditManagerAsync.GetAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessment" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<GetAssessmentResult> getAssessmentAsync(GetAssessmentRequest getAssessmentRequest); /** * <p> * Returns an assessment from Audit Manager. * </p> * * @param getAssessmentRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetAssessment operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessment" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<GetAssessmentResult> getAssessmentAsync(GetAssessmentRequest getAssessmentRequest, com.amazonaws.handlers.AsyncHandler<GetAssessmentRequest, GetAssessmentResult> asyncHandler); /** * <p> * Returns a framework from Audit Manager. * </p> * * @param getAssessmentFrameworkRequest * @return A Java Future containing the result of the GetAssessmentFramework operation returned by the service. * @sample AWSAuditManagerAsync.GetAssessmentFramework * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentFramework" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetAssessmentFrameworkResult> getAssessmentFrameworkAsync(GetAssessmentFrameworkRequest getAssessmentFrameworkRequest); /** * <p> * Returns a framework from Audit Manager. * </p> * * @param getAssessmentFrameworkRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetAssessmentFramework operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetAssessmentFramework * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentFramework" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetAssessmentFrameworkResult> getAssessmentFrameworkAsync(GetAssessmentFrameworkRequest getAssessmentFrameworkRequest, com.amazonaws.handlers.AsyncHandler<GetAssessmentFrameworkRequest, GetAssessmentFrameworkResult> asyncHandler); /** * <p> * Returns the URL of a specified assessment report in Audit Manager. * </p> * * @param getAssessmentReportUrlRequest * @return A Java Future containing the result of the GetAssessmentReportUrl operation returned by the service. * @sample AWSAuditManagerAsync.GetAssessmentReportUrl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentReportUrl" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetAssessmentReportUrlResult> getAssessmentReportUrlAsync(GetAssessmentReportUrlRequest getAssessmentReportUrlRequest); /** * <p> * Returns the URL of a specified assessment report in Audit Manager. * </p> * * @param getAssessmentReportUrlRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetAssessmentReportUrl operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetAssessmentReportUrl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentReportUrl" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetAssessmentReportUrlResult> getAssessmentReportUrlAsync(GetAssessmentReportUrlRequest getAssessmentReportUrlRequest, com.amazonaws.handlers.AsyncHandler<GetAssessmentReportUrlRequest, GetAssessmentReportUrlResult> asyncHandler); /** * <p> * Returns a list of changelogs from Audit Manager. * </p> * * @param getChangeLogsRequest * @return A Java Future containing the result of the GetChangeLogs operation returned by the service. * @sample AWSAuditManagerAsync.GetChangeLogs * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetChangeLogs" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<GetChangeLogsResult> getChangeLogsAsync(GetChangeLogsRequest getChangeLogsRequest); /** * <p> * Returns a list of changelogs from Audit Manager. * </p> * * @param getChangeLogsRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetChangeLogs operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetChangeLogs * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetChangeLogs" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<GetChangeLogsResult> getChangeLogsAsync(GetChangeLogsRequest getChangeLogsRequest, com.amazonaws.handlers.AsyncHandler<GetChangeLogsRequest, GetChangeLogsResult> asyncHandler); /** * <p> * Returns a control from Audit Manager. * </p> * * @param getControlRequest * @return A Java Future containing the result of the GetControl operation returned by the service. * @sample AWSAuditManagerAsync.GetControl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetControl" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<GetControlResult> getControlAsync(GetControlRequest getControlRequest); /** * <p> * Returns a control from Audit Manager. * </p> * * @param getControlRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetControl operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetControl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetControl" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<GetControlResult> getControlAsync(GetControlRequest getControlRequest, com.amazonaws.handlers.AsyncHandler<GetControlRequest, GetControlResult> asyncHandler); /** * <p> * Returns a list of delegations from an audit owner to a delegate. * </p> * * @param getDelegationsRequest * @return A Java Future containing the result of the GetDelegations operation returned by the service. * @sample AWSAuditManagerAsync.GetDelegations * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetDelegations" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<GetDelegationsResult> getDelegationsAsync(GetDelegationsRequest getDelegationsRequest); /** * <p> * Returns a list of delegations from an audit owner to a delegate. * </p> * * @param getDelegationsRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetDelegations operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetDelegations * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetDelegations" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<GetDelegationsResult> getDelegationsAsync(GetDelegationsRequest getDelegationsRequest, com.amazonaws.handlers.AsyncHandler<GetDelegationsRequest, GetDelegationsResult> asyncHandler); /** * <p> * Returns evidence from Audit Manager. * </p> * * @param getEvidenceRequest * @return A Java Future containing the result of the GetEvidence operation returned by the service. * @sample AWSAuditManagerAsync.GetEvidence * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidence" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<GetEvidenceResult> getEvidenceAsync(GetEvidenceRequest getEvidenceRequest); /** * <p> * Returns evidence from Audit Manager. * </p> * * @param getEvidenceRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetEvidence operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetEvidence * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidence" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<GetEvidenceResult> getEvidenceAsync(GetEvidenceRequest getEvidenceRequest, com.amazonaws.handlers.AsyncHandler<GetEvidenceRequest, GetEvidenceResult> asyncHandler); /** * <p> * Returns all evidence from a specified evidence folder in Audit Manager. * </p> * * @param getEvidenceByEvidenceFolderRequest * @return A Java Future containing the result of the GetEvidenceByEvidenceFolder operation returned by the service. * @sample AWSAuditManagerAsync.GetEvidenceByEvidenceFolder * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceByEvidenceFolder" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetEvidenceByEvidenceFolderResult> getEvidenceByEvidenceFolderAsync( GetEvidenceByEvidenceFolderRequest getEvidenceByEvidenceFolderRequest); /** * <p> * Returns all evidence from a specified evidence folder in Audit Manager. * </p> * * @param getEvidenceByEvidenceFolderRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetEvidenceByEvidenceFolder operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetEvidenceByEvidenceFolder * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceByEvidenceFolder" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetEvidenceByEvidenceFolderResult> getEvidenceByEvidenceFolderAsync( GetEvidenceByEvidenceFolderRequest getEvidenceByEvidenceFolderRequest, com.amazonaws.handlers.AsyncHandler<GetEvidenceByEvidenceFolderRequest, GetEvidenceByEvidenceFolderResult> asyncHandler); /** * <p> * Returns an evidence folder from the specified assessment in Audit Manager. * </p> * * @param getEvidenceFolderRequest * @return A Java Future containing the result of the GetEvidenceFolder operation returned by the service. * @sample AWSAuditManagerAsync.GetEvidenceFolder * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFolder" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<GetEvidenceFolderResult> getEvidenceFolderAsync(GetEvidenceFolderRequest getEvidenceFolderRequest); /** * <p> * Returns an evidence folder from the specified assessment in Audit Manager. * </p> * * @param getEvidenceFolderRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetEvidenceFolder operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetEvidenceFolder * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFolder" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<GetEvidenceFolderResult> getEvidenceFolderAsync(GetEvidenceFolderRequest getEvidenceFolderRequest, com.amazonaws.handlers.AsyncHandler<GetEvidenceFolderRequest, GetEvidenceFolderResult> asyncHandler); /** * <p> * Returns the evidence folders from a specified assessment in Audit Manager. * </p> * * @param getEvidenceFoldersByAssessmentRequest * @return A Java Future containing the result of the GetEvidenceFoldersByAssessment operation returned by the * service. * @sample AWSAuditManagerAsync.GetEvidenceFoldersByAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessment" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetEvidenceFoldersByAssessmentResult> getEvidenceFoldersByAssessmentAsync( GetEvidenceFoldersByAssessmentRequest getEvidenceFoldersByAssessmentRequest); /** * <p> * Returns the evidence folders from a specified assessment in Audit Manager. * </p> * * @param getEvidenceFoldersByAssessmentRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetEvidenceFoldersByAssessment operation returned by the * service. * @sample AWSAuditManagerAsyncHandler.GetEvidenceFoldersByAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessment" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetEvidenceFoldersByAssessmentResult> getEvidenceFoldersByAssessmentAsync( GetEvidenceFoldersByAssessmentRequest getEvidenceFoldersByAssessmentRequest, com.amazonaws.handlers.AsyncHandler<GetEvidenceFoldersByAssessmentRequest, GetEvidenceFoldersByAssessmentResult> asyncHandler); /** * <p> * Returns a list of evidence folders associated with a specified control of an assessment in Audit Manager. * </p> * * @param getEvidenceFoldersByAssessmentControlRequest * @return A Java Future containing the result of the GetEvidenceFoldersByAssessmentControl operation returned by * the service. * @sample AWSAuditManagerAsync.GetEvidenceFoldersByAssessmentControl * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessmentControl" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetEvidenceFoldersByAssessmentControlResult> getEvidenceFoldersByAssessmentControlAsync( GetEvidenceFoldersByAssessmentControlRequest getEvidenceFoldersByAssessmentControlRequest); /** * <p> * Returns a list of evidence folders associated with a specified control of an assessment in Audit Manager. * </p> * * @param getEvidenceFoldersByAssessmentControlRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetEvidenceFoldersByAssessmentControl operation returned by * the service. * @sample AWSAuditManagerAsyncHandler.GetEvidenceFoldersByAssessmentControl * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessmentControl" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetEvidenceFoldersByAssessmentControlResult> getEvidenceFoldersByAssessmentControlAsync( GetEvidenceFoldersByAssessmentControlRequest getEvidenceFoldersByAssessmentControlRequest, com.amazonaws.handlers.AsyncHandler<GetEvidenceFoldersByAssessmentControlRequest, GetEvidenceFoldersByAssessmentControlResult> asyncHandler); /** * <p> * Returns the name of the delegated Amazon Web Services administrator account for the organization. * </p> * * @param getOrganizationAdminAccountRequest * @return A Java Future containing the result of the GetOrganizationAdminAccount operation returned by the service. * @sample AWSAuditManagerAsync.GetOrganizationAdminAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetOrganizationAdminAccount" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetOrganizationAdminAccountResult> getOrganizationAdminAccountAsync( GetOrganizationAdminAccountRequest getOrganizationAdminAccountRequest); /** * <p> * Returns the name of the delegated Amazon Web Services administrator account for the organization. * </p> * * @param getOrganizationAdminAccountRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetOrganizationAdminAccount operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetOrganizationAdminAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetOrganizationAdminAccount" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetOrganizationAdminAccountResult> getOrganizationAdminAccountAsync( GetOrganizationAdminAccountRequest getOrganizationAdminAccountRequest, com.amazonaws.handlers.AsyncHandler<GetOrganizationAdminAccountRequest, GetOrganizationAdminAccountResult> asyncHandler); /** * <p> * Returns a list of the in-scope Amazon Web Services services for the specified assessment. * </p> * * @param getServicesInScopeRequest * @return A Java Future containing the result of the GetServicesInScope operation returned by the service. * @sample AWSAuditManagerAsync.GetServicesInScope * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetServicesInScope" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetServicesInScopeResult> getServicesInScopeAsync(GetServicesInScopeRequest getServicesInScopeRequest); /** * <p> * Returns a list of the in-scope Amazon Web Services services for the specified assessment. * </p> * * @param getServicesInScopeRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetServicesInScope operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetServicesInScope * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetServicesInScope" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<GetServicesInScopeResult> getServicesInScopeAsync(GetServicesInScopeRequest getServicesInScopeRequest, com.amazonaws.handlers.AsyncHandler<GetServicesInScopeRequest, GetServicesInScopeResult> asyncHandler); /** * <p> * Returns the settings for the specified account. * </p> * * @param getSettingsRequest * @return A Java Future containing the result of the GetSettings operation returned by the service. * @sample AWSAuditManagerAsync.GetSettings * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetSettings" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<GetSettingsResult> getSettingsAsync(GetSettingsRequest getSettingsRequest); /** * <p> * Returns the settings for the specified account. * </p> * * @param getSettingsRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the GetSettings operation returned by the service. * @sample AWSAuditManagerAsyncHandler.GetSettings * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetSettings" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<GetSettingsResult> getSettingsAsync(GetSettingsRequest getSettingsRequest, com.amazonaws.handlers.AsyncHandler<GetSettingsRequest, GetSettingsResult> asyncHandler); /** * <p> * Returns a list of the frameworks available in the Audit Manager framework library. * </p> * * @param listAssessmentFrameworksRequest * @return A Java Future containing the result of the ListAssessmentFrameworks operation returned by the service. * @sample AWSAuditManagerAsync.ListAssessmentFrameworks * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentFrameworks" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<ListAssessmentFrameworksResult> listAssessmentFrameworksAsync(ListAssessmentFrameworksRequest listAssessmentFrameworksRequest); /** * <p> * Returns a list of the frameworks available in the Audit Manager framework library. * </p> * * @param listAssessmentFrameworksRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the ListAssessmentFrameworks operation returned by the service. * @sample AWSAuditManagerAsyncHandler.ListAssessmentFrameworks * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentFrameworks" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<ListAssessmentFrameworksResult> listAssessmentFrameworksAsync(ListAssessmentFrameworksRequest listAssessmentFrameworksRequest, com.amazonaws.handlers.AsyncHandler<ListAssessmentFrameworksRequest, ListAssessmentFrameworksResult> asyncHandler); /** * <p> * Returns a list of assessment reports created in Audit Manager. * </p> * * @param listAssessmentReportsRequest * @return A Java Future containing the result of the ListAssessmentReports operation returned by the service. * @sample AWSAuditManagerAsync.ListAssessmentReports * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentReports" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<ListAssessmentReportsResult> listAssessmentReportsAsync(ListAssessmentReportsRequest listAssessmentReportsRequest); /** * <p> * Returns a list of assessment reports created in Audit Manager. * </p> * * @param listAssessmentReportsRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the ListAssessmentReports operation returned by the service. * @sample AWSAuditManagerAsyncHandler.ListAssessmentReports * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentReports" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<ListAssessmentReportsResult> listAssessmentReportsAsync(ListAssessmentReportsRequest listAssessmentReportsRequest, com.amazonaws.handlers.AsyncHandler<ListAssessmentReportsRequest, ListAssessmentReportsResult> asyncHandler); /** * <p> * Returns a list of current and past assessments from Audit Manager. * </p> * * @param listAssessmentsRequest * @return A Java Future containing the result of the ListAssessments operation returned by the service. * @sample AWSAuditManagerAsync.ListAssessments * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessments" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<ListAssessmentsResult> listAssessmentsAsync(ListAssessmentsRequest listAssessmentsRequest); /** * <p> * Returns a list of current and past assessments from Audit Manager. * </p> * * @param listAssessmentsRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the ListAssessments operation returned by the service. * @sample AWSAuditManagerAsyncHandler.ListAssessments * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessments" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<ListAssessmentsResult> listAssessmentsAsync(ListAssessmentsRequest listAssessmentsRequest, com.amazonaws.handlers.AsyncHandler<ListAssessmentsRequest, ListAssessmentsResult> asyncHandler); /** * <p> * Returns a list of controls from Audit Manager. * </p> * * @param listControlsRequest * @return A Java Future containing the result of the ListControls operation returned by the service. * @sample AWSAuditManagerAsync.ListControls * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListControls" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<ListControlsResult> listControlsAsync(ListControlsRequest listControlsRequest); /** * <p> * Returns a list of controls from Audit Manager. * </p> * * @param listControlsRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the ListControls operation returned by the service. * @sample AWSAuditManagerAsyncHandler.ListControls * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListControls" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<ListControlsResult> listControlsAsync(ListControlsRequest listControlsRequest, com.amazonaws.handlers.AsyncHandler<ListControlsRequest, ListControlsResult> asyncHandler); /** * <p> * Returns a list of keywords that pre-mapped to the specified control data source. * </p> * * @param listKeywordsForDataSourceRequest * @return A Java Future containing the result of the ListKeywordsForDataSource operation returned by the service. * @sample AWSAuditManagerAsync.ListKeywordsForDataSource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListKeywordsForDataSource" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<ListKeywordsForDataSourceResult> listKeywordsForDataSourceAsync( ListKeywordsForDataSourceRequest listKeywordsForDataSourceRequest); /** * <p> * Returns a list of keywords that pre-mapped to the specified control data source. * </p> * * @param listKeywordsForDataSourceRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the ListKeywordsForDataSource operation returned by the service. * @sample AWSAuditManagerAsyncHandler.ListKeywordsForDataSource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListKeywordsForDataSource" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<ListKeywordsForDataSourceResult> listKeywordsForDataSourceAsync( ListKeywordsForDataSourceRequest listKeywordsForDataSourceRequest, com.amazonaws.handlers.AsyncHandler<ListKeywordsForDataSourceRequest, ListKeywordsForDataSourceResult> asyncHandler); /** * <p> * Returns a list of all Audit Manager notifications. * </p> * * @param listNotificationsRequest * @return A Java Future containing the result of the ListNotifications operation returned by the service. * @sample AWSAuditManagerAsync.ListNotifications * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListNotifications" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<ListNotificationsResult> listNotificationsAsync(ListNotificationsRequest listNotificationsRequest); /** * <p> * Returns a list of all Audit Manager notifications. * </p> * * @param listNotificationsRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the ListNotifications operation returned by the service. * @sample AWSAuditManagerAsyncHandler.ListNotifications * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListNotifications" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<ListNotificationsResult> listNotificationsAsync(ListNotificationsRequest listNotificationsRequest, com.amazonaws.handlers.AsyncHandler<ListNotificationsRequest, ListNotificationsResult> asyncHandler); /** * <p> * Returns a list of tags for the specified resource in Audit Manager. * </p> * * @param listTagsForResourceRequest * @return A Java Future containing the result of the ListTagsForResource operation returned by the service. * @sample AWSAuditManagerAsync.ListTagsForResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListTagsForResource" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest listTagsForResourceRequest); /** * <p> * Returns a list of tags for the specified resource in Audit Manager. * </p> * * @param listTagsForResourceRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the ListTagsForResource operation returned by the service. * @sample AWSAuditManagerAsyncHandler.ListTagsForResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListTagsForResource" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest listTagsForResourceRequest, com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler); /** * <p> * Enables Audit Manager for the specified account. * </p> * * @param registerAccountRequest * @return A Java Future containing the result of the RegisterAccount operation returned by the service. * @sample AWSAuditManagerAsync.RegisterAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterAccount" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<RegisterAccountResult> registerAccountAsync(RegisterAccountRequest registerAccountRequest); /** * <p> * Enables Audit Manager for the specified account. * </p> * * @param registerAccountRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the RegisterAccount operation returned by the service. * @sample AWSAuditManagerAsyncHandler.RegisterAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterAccount" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<RegisterAccountResult> registerAccountAsync(RegisterAccountRequest registerAccountRequest, com.amazonaws.handlers.AsyncHandler<RegisterAccountRequest, RegisterAccountResult> asyncHandler); /** * <p> * Enables an account within the organization as the delegated administrator for Audit Manager. * </p> * * @param registerOrganizationAdminAccountRequest * @return A Java Future containing the result of the RegisterOrganizationAdminAccount operation returned by the * service. * @sample AWSAuditManagerAsync.RegisterOrganizationAdminAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterOrganizationAdminAccount" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<RegisterOrganizationAdminAccountResult> registerOrganizationAdminAccountAsync( RegisterOrganizationAdminAccountRequest registerOrganizationAdminAccountRequest); /** * <p> * Enables an account within the organization as the delegated administrator for Audit Manager. * </p> * * @param registerOrganizationAdminAccountRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the RegisterOrganizationAdminAccount operation returned by the * service. * @sample AWSAuditManagerAsyncHandler.RegisterOrganizationAdminAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterOrganizationAdminAccount" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<RegisterOrganizationAdminAccountResult> registerOrganizationAdminAccountAsync( RegisterOrganizationAdminAccountRequest registerOrganizationAdminAccountRequest, com.amazonaws.handlers.AsyncHandler<RegisterOrganizationAdminAccountRequest, RegisterOrganizationAdminAccountResult> asyncHandler); /** * <p> * Tags the specified resource in Audit Manager. * </p> * * @param tagResourceRequest * @return A Java Future containing the result of the TagResource operation returned by the service. * @sample AWSAuditManagerAsync.TagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/TagResource" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest tagResourceRequest); /** * <p> * Tags the specified resource in Audit Manager. * </p> * * @param tagResourceRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the TagResource operation returned by the service. * @sample AWSAuditManagerAsyncHandler.TagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/TagResource" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest tagResourceRequest, com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler); /** * <p> * Removes a tag from a resource in Audit Manager. * </p> * * @param untagResourceRequest * @return A Java Future containing the result of the UntagResource operation returned by the service. * @sample AWSAuditManagerAsync.UntagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UntagResource" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest untagResourceRequest); /** * <p> * Removes a tag from a resource in Audit Manager. * </p> * * @param untagResourceRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the UntagResource operation returned by the service. * @sample AWSAuditManagerAsyncHandler.UntagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UntagResource" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest untagResourceRequest, com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler); /** * <p> * Edits an Audit Manager assessment. * </p> * * @param updateAssessmentRequest * @return A Java Future containing the result of the UpdateAssessment operation returned by the service. * @sample AWSAuditManagerAsync.UpdateAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessment" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<UpdateAssessmentResult> updateAssessmentAsync(UpdateAssessmentRequest updateAssessmentRequest); /** * <p> * Edits an Audit Manager assessment. * </p> * * @param updateAssessmentRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the UpdateAssessment operation returned by the service. * @sample AWSAuditManagerAsyncHandler.UpdateAssessment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessment" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<UpdateAssessmentResult> updateAssessmentAsync(UpdateAssessmentRequest updateAssessmentRequest, com.amazonaws.handlers.AsyncHandler<UpdateAssessmentRequest, UpdateAssessmentResult> asyncHandler); /** * <p> * Updates a control within an assessment in Audit Manager. * </p> * * @param updateAssessmentControlRequest * @return A Java Future containing the result of the UpdateAssessmentControl operation returned by the service. * @sample AWSAuditManagerAsync.UpdateAssessmentControl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControl" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<UpdateAssessmentControlResult> updateAssessmentControlAsync(UpdateAssessmentControlRequest updateAssessmentControlRequest); /** * <p> * Updates a control within an assessment in Audit Manager. * </p> * * @param updateAssessmentControlRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the UpdateAssessmentControl operation returned by the service. * @sample AWSAuditManagerAsyncHandler.UpdateAssessmentControl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControl" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<UpdateAssessmentControlResult> updateAssessmentControlAsync(UpdateAssessmentControlRequest updateAssessmentControlRequest, com.amazonaws.handlers.AsyncHandler<UpdateAssessmentControlRequest, UpdateAssessmentControlResult> asyncHandler); /** * <p> * Updates the status of a control set in an Audit Manager assessment. * </p> * * @param updateAssessmentControlSetStatusRequest * @return A Java Future containing the result of the UpdateAssessmentControlSetStatus operation returned by the * service. * @sample AWSAuditManagerAsync.UpdateAssessmentControlSetStatus * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControlSetStatus" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<UpdateAssessmentControlSetStatusResult> updateAssessmentControlSetStatusAsync( UpdateAssessmentControlSetStatusRequest updateAssessmentControlSetStatusRequest); /** * <p> * Updates the status of a control set in an Audit Manager assessment. * </p> * * @param updateAssessmentControlSetStatusRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the UpdateAssessmentControlSetStatus operation returned by the * service. * @sample AWSAuditManagerAsyncHandler.UpdateAssessmentControlSetStatus * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControlSetStatus" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<UpdateAssessmentControlSetStatusResult> updateAssessmentControlSetStatusAsync( UpdateAssessmentControlSetStatusRequest updateAssessmentControlSetStatusRequest, com.amazonaws.handlers.AsyncHandler<UpdateAssessmentControlSetStatusRequest, UpdateAssessmentControlSetStatusResult> asyncHandler); /** * <p> * Updates a custom framework in Audit Manager. * </p> * * @param updateAssessmentFrameworkRequest * @return A Java Future containing the result of the UpdateAssessmentFramework operation returned by the service. * @sample AWSAuditManagerAsync.UpdateAssessmentFramework * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentFramework" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<UpdateAssessmentFrameworkResult> updateAssessmentFrameworkAsync( UpdateAssessmentFrameworkRequest updateAssessmentFrameworkRequest); /** * <p> * Updates a custom framework in Audit Manager. * </p> * * @param updateAssessmentFrameworkRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the UpdateAssessmentFramework operation returned by the service. * @sample AWSAuditManagerAsyncHandler.UpdateAssessmentFramework * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentFramework" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<UpdateAssessmentFrameworkResult> updateAssessmentFrameworkAsync( UpdateAssessmentFrameworkRequest updateAssessmentFrameworkRequest, com.amazonaws.handlers.AsyncHandler<UpdateAssessmentFrameworkRequest, UpdateAssessmentFrameworkResult> asyncHandler); /** * <p> * Updates the status of an assessment in Audit Manager. * </p> * * @param updateAssessmentStatusRequest * @return A Java Future containing the result of the UpdateAssessmentStatus operation returned by the service. * @sample AWSAuditManagerAsync.UpdateAssessmentStatus * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentStatus" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<UpdateAssessmentStatusResult> updateAssessmentStatusAsync(UpdateAssessmentStatusRequest updateAssessmentStatusRequest); /** * <p> * Updates the status of an assessment in Audit Manager. * </p> * * @param updateAssessmentStatusRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the UpdateAssessmentStatus operation returned by the service. * @sample AWSAuditManagerAsyncHandler.UpdateAssessmentStatus * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentStatus" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<UpdateAssessmentStatusResult> updateAssessmentStatusAsync(UpdateAssessmentStatusRequest updateAssessmentStatusRequest, com.amazonaws.handlers.AsyncHandler<UpdateAssessmentStatusRequest, UpdateAssessmentStatusResult> asyncHandler); /** * <p> * Updates a custom control in Audit Manager. * </p> * * @param updateControlRequest * @return A Java Future containing the result of the UpdateControl operation returned by the service. * @sample AWSAuditManagerAsync.UpdateControl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateControl" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<UpdateControlResult> updateControlAsync(UpdateControlRequest updateControlRequest); /** * <p> * Updates a custom control in Audit Manager. * </p> * * @param updateControlRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the UpdateControl operation returned by the service. * @sample AWSAuditManagerAsyncHandler.UpdateControl * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateControl" target="_top">AWS API * Documentation</a> */ java.util.concurrent.Future<UpdateControlResult> updateControlAsync(UpdateControlRequest updateControlRequest, com.amazonaws.handlers.AsyncHandler<UpdateControlRequest, UpdateControlResult> asyncHandler); /** * <p> * Updates Audit Manager settings for the current user account. * </p> * * @param updateSettingsRequest * @return A Java Future containing the result of the UpdateSettings operation returned by the service. * @sample AWSAuditManagerAsync.UpdateSettings * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateSettings" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<UpdateSettingsResult> updateSettingsAsync(UpdateSettingsRequest updateSettingsRequest); /** * <p> * Updates Audit Manager settings for the current user account. * </p> * * @param updateSettingsRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the UpdateSettings operation returned by the service. * @sample AWSAuditManagerAsyncHandler.UpdateSettings * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateSettings" target="_top">AWS * API Documentation</a> */ java.util.concurrent.Future<UpdateSettingsResult> updateSettingsAsync(UpdateSettingsRequest updateSettingsRequest, com.amazonaws.handlers.AsyncHandler<UpdateSettingsRequest, UpdateSettingsResult> asyncHandler); /** * <p> * Validates the integrity of an assessment report in Audit Manager. * </p> * * @param validateAssessmentReportIntegrityRequest * @return A Java Future containing the result of the ValidateAssessmentReportIntegrity operation returned by the * service. * @sample AWSAuditManagerAsync.ValidateAssessmentReportIntegrity * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ValidateAssessmentReportIntegrity" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<ValidateAssessmentReportIntegrityResult> validateAssessmentReportIntegrityAsync( ValidateAssessmentReportIntegrityRequest validateAssessmentReportIntegrityRequest); /** * <p> * Validates the integrity of an assessment report in Audit Manager. * </p> * * @param validateAssessmentReportIntegrityRequest * @param asyncHandler * Asynchronous callback handler for events in the lifecycle of the request. Users can provide an * implementation of the callback methods in this interface to receive notification of successful or * unsuccessful completion of the operation. * @return A Java Future containing the result of the ValidateAssessmentReportIntegrity operation returned by the * service. * @sample AWSAuditManagerAsyncHandler.ValidateAssessmentReportIntegrity * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ValidateAssessmentReportIntegrity" * target="_top">AWS API Documentation</a> */ java.util.concurrent.Future<ValidateAssessmentReportIntegrityResult> validateAssessmentReportIntegrityAsync( ValidateAssessmentReportIntegrityRequest validateAssessmentReportIntegrityRequest, com.amazonaws.handlers.AsyncHandler<ValidateAssessmentReportIntegrityRequest, ValidateAssessmentReportIntegrityResult> asyncHandler); }
30,811
3,428
<gh_stars>1000+ {"id":"00547","group":"easy-ham-1","checksum":{"type":"MD5","value":"59bf01e07cf08c7e3a778b747e020989"},"text":"From <EMAIL> Wed Sep 11 13:49:23 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.<EMAIL>\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 13ECF16F03\n\tfor <jm@localhost>; Wed, 11 Sep 2002 13:49:23 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 11 Sep 2002 13:49:23 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g8AIcYC11645 for <<EMAIL>>;\n Tue, 10 Sep 2002 19:38:38 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id 5ADDE2940A0; Tue, 10 Sep 2002 11:35:04 -0700 (PDT)\nDelivered-To: <EMAIL>\nReceived: from localhost.localdomain (pm1-15.sba1.netlojix.net\n [207.71.218.63]) by xent.com (Postfix) with ESMTP id CA94C29409A for\n <<EMAIL>>; Tue, 10 Sep 2002 11:34:34 -0700 (PDT)\nReceived: (from dave@localhost) by maltesecat (8.8.7/8.8.7a) id LAA10179;\n Tue, 10 Sep 2002 11:21:56 -0700\nMessage-Id: <<EMAIL>>\nTo: <EMAIL>int.org\nSubject: Re: Tech's Major Decline\nIn-Reply-To: Message from <EMAIL> of\n \"Sun, 01 Sep 2002 20:24:01 PDT.\"\n <<EMAIL>>\nFrom: <NAME> <<EMAIL>>\nSender: [email protected]\nErrors-To: [email protected]\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of Rohit Khare <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Tue, 10 Sep 2002 11:21:56 -0700\n\n\nI'm not sure which way to make\nthe old bits call on this:\n\n[A] <http://www.xent.com/pipermail/fork/2002-September/014448.html>\nwas posted well after\n[B] <http://www.xent.com/pipermail/fork/2002-August/014351.html>\nwas in the archives, but then\nagain, [B] didn't bother with\nany commentary (new bits).\n\nIf you two can agree upon who\nwas at fault, penance will be\nto explain how feedback phase\nis affected by time lags, and\ntie that in to the spontaneous\ngeneration of \"business cycles\"\nin the Beer Game. *\n\n-Dave\n\n* <http://web.mit.edu/jsterman/www/SDG/beergame.html>\n\nsee also:\n\nExplaining Capacity Overshoot and Price War: Misperceptions\n of Feedback in Competitive Growth Markets \n<http://web.mit.edu/jsterman/www/B&B_Rev.html>\n\nin which the scenario 4 (margin\noriented tit for tat) seems close\nto the strategy described in:\n\n\"game theoretical gandhi / more laptops\"\n<http://www.xent.com/aug00/0200.html>\n\n\n\n"}
1,189
445
<filename>include/multiverso/worker.h<gh_stars>100-1000 #ifndef MULTIVERSO_WORKER_H_ #define MULTIVERSO_WORKER_H_ #include <vector> #include "multiverso/actor.h" namespace multiverso { class WorkerTable; class Worker : public Actor { public: Worker(); int RegisterTable(WorkerTable* worker_table); private: void ProcessGet(MessagePtr& msg); void ProcessAdd(MessagePtr& msg); void ProcessReplyGet(MessagePtr& msg); void ProcessReplyAdd(MessagePtr& msg); std::vector<WorkerTable*> cache_; }; } // namespace multiverso #endif // MULTIVERSO_WORKER_H_
203
6,663
<reponame>johannes-mueller/cython /////////////// CppExceptionConversion.proto /////////////// #ifndef __Pyx_CppExn2PyErr #include <new> #include <typeinfo> #include <stdexcept> #include <ios> static void __Pyx_CppExn2PyErr() { // Catch a handful of different errors here and turn them into the // equivalent Python errors. try { if (PyErr_Occurred()) ; // let the latest Python exn pass through and ignore the current one else throw; } catch (const std::bad_alloc& exn) { PyErr_SetString(PyExc_MemoryError, exn.what()); } catch (const std::bad_cast& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::bad_typeid& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::domain_error& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::invalid_argument& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::ios_base::failure& exn) { // Unfortunately, in standard C++ we have no way of distinguishing EOF // from other errors here; be careful with the exception mask PyErr_SetString(PyExc_IOError, exn.what()); } catch (const std::out_of_range& exn) { // Change out_of_range to IndexError PyErr_SetString(PyExc_IndexError, exn.what()); } catch (const std::overflow_error& exn) { PyErr_SetString(PyExc_OverflowError, exn.what()); } catch (const std::range_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::underflow_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::exception& exn) { PyErr_SetString(PyExc_RuntimeError, exn.what()); } catch (...) { PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); } } #endif /////////////// PythranConversion.proto /////////////// template <class T> auto __Pyx_pythran_to_python(T &&value) -> decltype(to_python( typename pythonic::returnable<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::type{std::forward<T>(value)})) { using returnable_type = typename pythonic::returnable<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::type; return to_python(returnable_type{std::forward<T>(value)}); } #define __Pyx_PythranShapeAccessor(x) (pythonic::builtins::getattr(pythonic::types::attr::SHAPE{}, x)) ////////////// MoveIfSupported.proto ////////////////// #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600) // move should be defined for these versions of MSVC, but __cplusplus isn't set usefully #include <utility> #define __PYX_STD_MOVE_IF_SUPPORTED(x) std::move(x) #else #define __PYX_STD_MOVE_IF_SUPPORTED(x) x #endif ////////////// EnumClassDecl.proto ////////////////// #if defined (_MSC_VER) #if _MSC_VER >= 1910 #define __PYX_ENUM_CLASS_DECL enum #else #define __PYX_ENUM_CLASS_DECL #endif #else #define __PYX_ENUM_CLASS_DECL enum #endif ////////////// OptionalLocals.proto //////////////// //@proto_block: utility_code_proto_before_types #if defined(CYTHON_USE_BOOST_OPTIONAL) // fallback mode - std::optional is preferred but this gives // people with a less up-to-date compiler a chance #include <boost/optional.hpp> #define __Pyx_Optional_Type boost::optional #else #include <optional> // since std::optional is a C++17 features, a templated using declaration should be safe // (although it could be replaced with a define) template <typename T> using __Pyx_Optional_Type = std::optional<T>; #endif
1,337
432
[ { "slug": "ReleaseIQ", "name": "ReleaseIQ", "description": "ReleaseIQ helps companies accelerate software product release cycles while improving quality and efficiency with an Enterprise DevOps Platform that leverages existing CI/CD tools", "url": "https://www.releaseiq.io", "tags": [ "linux", "free", "commercial", "ci", "cd", "orchestration" ] } ]
156
418
<reponame>NewLeafG/esplay-retro-emulation /* ** Nofrendo (c) 1998-2000 <NAME> (<EMAIL>) ** ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of version 2 of the GNU Library General ** Public License as published by the Free Software Foundation. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Library General Public License for more details. To obtain a ** copy of the GNU Library General Public License, write to the Free ** Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ** ** Any permitted reproduction of these routines, in whole or in part, ** must bear this legend. ** ** ** dis6502.h ** ** 6502 disassembler header ** $Id: dis6502.h,v 1.1 2001/04/27 12:54:39 neil Exp $ */ #ifndef _DIS6502_H_ #define _DIS6502_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ extern char *nes6502_disasm(uint32 PC, uint8 P, uint8 A, uint8 X, uint8 Y, uint8 S); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* !_DIS6502_H_ */ /* ** $Log: dis6502.h,v $ ** Revision 1.1 2001/04/27 12:54:39 neil ** blah ** ** Revision 1.1.1.1 2001/04/27 07:03:54 neil ** initial ** ** Revision 1.6 2000/07/17 01:52:28 matt ** made sure last line of all source files is a newline ** ** Revision 1.5 2000/07/11 04:26:23 matt ** rewrote to fill up a static buffer, rather than use log_printf ** ** Revision 1.4 2000/06/09 15:12:25 matt ** initial revision ** */
559
411
<reponame>tonyyang924/MyDiary package com.kiminonawa.mydiary.shared; import android.content.Context; import org.apache.commons.io.FileUtils; import java.io.File; /** * Created by daxia on 2016/12/12. */ public class OldVersionHelper { public static boolean Version17MoveTheDiaryIntoNewDir(Context context) throws Exception { FileManager rootFileManager = new FileManager(context, FileManager.ROOT_DIR); File[] dataFiles = rootFileManager.getDir().listFiles(); boolean moveIntoNewDir = false; //router all dir first for (int i = 0; i < dataFiles.length; i++) { if (FileManager.isNumeric(dataFiles[i].getName()) && dataFiles[i].listFiles().length > 0) { moveIntoNewDir = true; break; } } //If the numeric dir is exist , move it if (moveIntoNewDir) { FileManager diaryFM = new FileManager(context, FileManager.DIARY_ROOT_DIR); File destDir = diaryFM.getDir(); FileUtils.deleteDirectory(destDir); for (int i = 0; i < dataFiles.length; i++) { if (FileManager.isNumeric(dataFiles[i].getName())) { FileUtils.moveDirectoryToDirectory(dataFiles[i], new FileManager(context, FileManager.DIARY_ROOT_DIR).getDir() , true); } } //Remove the diary/temp/ FileUtils.deleteDirectory(new File(diaryFM.getDirAbsolutePath() + "/temp")); } return moveIntoNewDir; } }
738
530
package org.carlspring.strongbox.dependency.snippet; import org.carlspring.strongbox.artifact.coordinates.ArtifactCoordinates; import org.carlspring.strongbox.artifact.coordinates.NugetArtifactCoordinates; import org.carlspring.strongbox.providers.layout.AbstractLayoutProvider; import org.carlspring.strongbox.providers.layout.NugetLayoutProvider; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * @author carlspring */ @Component public class NugetDependencyFormatter implements DependencySynonymFormatter { private static final Logger logger = LoggerFactory.getLogger(AbstractLayoutProvider.class); public static final String ALIAS = "NuGet"; @Inject private CompatibleDependencyFormatRegistry compatibleDependencyFormatRegistry; @PostConstruct @Override public void register() { compatibleDependencyFormatRegistry.addProviderImplementation(getLayout(), getFormatAlias(), this); logger.debug("Initialized the NuGet dependency formatter."); } @Override public String getLayout() { return NugetLayoutProvider.ALIAS; } @Override public String getFormatAlias() { return ALIAS; } @Override public String getDependencySnippet(ArtifactCoordinates artifactCoordinates) { NugetArtifactCoordinates coordinates = (NugetArtifactCoordinates) artifactCoordinates; String sb = "<dependency id=\"" + coordinates.getId() + "\"" + " version=\"" + coordinates.getVersion() + "\" />\n"; return sb; } }
601
11,024
<gh_stars>1000+ #!/bin/env python2 import argparse parser = argparse.ArgumentParser("Run multithreaded client tests") parser.add_argument("cluster_file", nargs='+', help='List of fdb.cluster files to connect to') parser.add_argument("--skip-so-files", default=False, action='store_true', help='Do not load .so files') parser.add_argument("--threads", metavar="N", type=int, default=3, help='Number of threads to use. Zero implies local client') parser.add_argument("--build-dir", metavar="DIR", default='.', help='Path to root directory of FDB build output') parser.add_argument("--client-log-dir", metavar="DIR", default="client-logs", help="Path to write client logs to. The directory will be created if it does not exist.") args = parser.parse_args() import sys ### sample usage (from inside your FDB build output directory): ## These should pass: # ../tests/loopback_cluster/run_cluster.sh . 3 '../tests/python_tests/multithreaded_client.py loopback-cluster-*/fdb.cluster' # ../tests/loopback_cluster/run_cluster.sh . 3 '../tests/python_tests/multithreaded_client.py loopback-cluster-*/fdb.cluster --threads 1' # ../tests/loopback_cluster/run_cluster.sh . 3 '../tests/python_tests/multithreaded_client.py loopback-cluster-*/fdb.cluster --threads 1 --skip-so-files' # ../tests/loopback_cluster/run_cluster.sh . 3 '../tests/python_tests/multithreaded_client.py loopback-cluster-*/fdb.cluster --threads 0' # ../tests/loopback_cluster/run_cluster.sh . 3 '../tests/python_tests/multithreaded_client.py loopback-cluster-*/fdb.cluster --threads 0 --skip-so-files' ## This fails (unsupported configuration): # ../tests/loopback_cluster/run_cluster.sh . 3 '../tests/python_tests/multithreaded_client.py loopback-cluster-*/fdb.cluster --threads 2 --skip-so-files' sys.path.append(args.build_dir + '/bindings/python') import fdb import os import random import time fdb.api_version(630) if not os.path.exists(args.client_log_dir): os.mkdir(args.client_log_dir) fdb.options.set_trace_enable(args.client_log_dir) fdb.options.set_knob("min_trace_severity=5") if not args.skip_so_files: print("Loading .so files") fdb.options.set_external_client_directory(args.build_dir + '/lib') if args.threads > 0: fdb.options.set_client_threads_per_version(args.threads) dbs = [] for v in args.cluster_file: dbs.append(fdb.open(cluster_file=v)) counter = 0 for i in range(100): key = b"test_%d" % random.randrange(0, 100000000) val = b"value_%d" % random.randrange(0, 10000000) db = dbs[i % len(dbs)] print ("Writing: ", key, val, db) db[key] = val assert (val == db[key])
960
563
package com.gentics.mesh.core.graphql; import static com.gentics.mesh.assertj.MeshAssertions.assertThat; import static com.gentics.mesh.core.rest.common.Permission.READ; import static com.gentics.mesh.core.rest.role.RolePermissionRequest.withPermissions; import static com.gentics.mesh.test.TestDataProvider.PROJECT_NAME; import static com.gentics.mesh.test.util.TestUtils.getResourceAsString; import static java.util.Collections.singletonMap; import static java.util.Objects.hash; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.Map; import org.junit.Before; import org.junit.Test; import com.gentics.mesh.core.rest.graphql.GraphQLRequest; import com.gentics.mesh.core.rest.graphql.GraphQLResponse; import com.gentics.mesh.core.rest.microschema.impl.MicroschemaCreateRequest; import com.gentics.mesh.core.rest.node.NodeCreateRequest; import com.gentics.mesh.core.rest.node.NodeResponse; import com.gentics.mesh.core.rest.schema.impl.SchemaCreateRequest; import com.gentics.mesh.core.rest.schema.impl.SchemaResponse; import com.gentics.mesh.json.JsonUtil; import com.gentics.mesh.test.TestSize; import com.gentics.mesh.test.context.AbstractMeshTest; import com.gentics.mesh.test.context.MeshTestSetting; import com.gentics.mesh.test.context.Rug; import io.reactivex.Single; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; @MeshTestSetting(testSize = TestSize.FULL, startServer = true) public class GraphQLReferencedByTest extends AbstractMeshTest { private NodeResponse sourceNode; private NodeResponse targetNode; @Before public void setUp() throws Exception { createSchema(); targetNode = readNode(projectName(), tx(() -> folder("2015").getUuid())); sourceNode = createReferenceNode(targetNode.getUuid()); } @Test public void testAllReferences() throws IOException { JsonArray responseData = query("basic-query"); String sourceUuid = sourceNode.getUuid(); assertThat(responseData).containsJsonObjectHashesInAnyOrder( obj -> hash( obj.getString("fieldName"), obj.getString("micronodeFieldName"), obj.getJsonObject("node").getString("uuid") ), hash("simpleNodeRef", null, sourceUuid), hash("listNodeRef", null, sourceUuid), hash("simpleMicronode", "microSimpleNodeRef", sourceUuid), hash("simpleMicronode", "microListNodeRef", sourceUuid), hash("listMicronode", "microSimpleNodeRef", sourceUuid), hash("listMicronode", "microListNodeRef", sourceUuid) ); } @Test public void testPagedReferences() throws IOException { JsonArray responseData = query("paged-query"); assertEquals("The array should only contain two elements.", 2, responseData.size()); } @Test public void testPermissions() throws IOException { Rug tester = createUserGroupRole("tester"); client().updateRolePermissions( tester.getRole().getUuid(), String.format("/projects/%s/nodes/%s", projectUuid(), targetNode.getUuid()), withPermissions(READ) ).blockingAwait(); client().setLogin(tester.getUser().getUsername(), "test1234"); client().login().blockingGet(); JsonArray resultData = query("basic-query"); assertThat(resultData.getList()).isEmpty(); } private JsonArray query(String queryCaseName) throws IOException { String queryName = "referencedBy/" + queryCaseName; GraphQLResponse response = graphQl( getGraphQLQuery(queryName), singletonMap("uuid", targetNode.getUuid()) ); assertThat(new JsonObject(response.toJson())).compliesToAssertions(queryName); return response.getData() .getJsonObject("node") .getJsonObject("referencedBy") .getJsonArray("elements"); } private GraphQLResponse graphQl(String query, Map<String, Object> variables) { GraphQLRequest request = new GraphQLRequest(); request.setQuery(query); request.setVariables(new JsonObject(variables)); return client().graphql(PROJECT_NAME, request).blockingGet(); } /** * Creates a schema which contains all possible node reference fields. * @return */ private SchemaResponse createSchema() { String projectName = projectName(); SchemaCreateRequest schemaRequest = JsonUtil.readValue(getResourceAsString("/graphql/referencedBy/schema.json"), SchemaCreateRequest.class); MicroschemaCreateRequest microschemaRequest = JsonUtil.readValue(getResourceAsString("/graphql/referencedBy/microschema.json"), MicroschemaCreateRequest.class); return Single.zip( client().createSchema(schemaRequest).toSingle() .flatMap(schemaResponse -> client().assignSchemaToProject(projectName, schemaResponse.getUuid()).toSingle()), client().createMicroschema(microschemaRequest).toSingle() .flatMap(microschemaResponse -> client().assignMicroschemaToProject(projectName, microschemaResponse.getUuid()).toSingle()), (schema, ignore) -> schema ).blockingGet(); } private NodeResponse createReferenceNode(String uuid) { NodeCreateRequest request = JsonUtil.readValue( getResourceAsString("/graphql/referencedBy/refNode.json").replaceAll("%UUID%", uuid), NodeCreateRequest.class ); return client().createNode(projectName(), request).blockingGet(); } }
1,749
493
package com.martinrgb.animer.core.interpolator.AndroidNative; import com.martinrgb.animer.core.interpolator.AnInterpolator; public class DecelerateInterpolator extends AnInterpolator { private float mFactor = 1.0f; public DecelerateInterpolator() { initArgData(0,1,"factor",0,10); } public DecelerateInterpolator(float factor) { mFactor = factor; initArgData(0,factor,"factor",0,10); } public float getInterpolation(float input) { float result; if (mFactor == 1.0f) { result = (float)(1.0f - (1.0f - input) * (1.0f - input)); } else { result = (float)(1.0f - Math.pow((1.0f - input), 2 * mFactor)); } return result; } @Override public void resetArgValue(int i, float value){ setArgValue(i,value); if(i == 0){ mFactor = value; } } }
418
539
<reponame>glenfe/microsoft.bond<filename>java/core/src/main/java/org/bondlib/UInt16BondType.java // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package org.bondlib; import java.io.IOException; /** * Implements the {@link BondType} contract for the Bond "uint16" data type. */ public final class UInt16BondType extends PrimitiveBondType<Short> { /** * The default of primitive values of this type. */ public static final short DEFAULT_VALUE_AS_PRIMITIVE = (short) 0; /** * The default of object values of this type. */ public static final Short DEFAULT_VALUE_AS_OBJECT = DEFAULT_VALUE_AS_PRIMITIVE; /** * The name of the type as it appears in Bond schemas. */ public static final String TYPE_NAME = "uint16"; /** * Singleton, public access is via constants in the BondTypes class. */ static final UInt16BondType INSTANCE = new UInt16BondType(); private UInt16BondType() { } @Override public final String getName() { return TYPE_NAME; } @Override public final String getQualifiedName() { return TYPE_NAME; } @Override public final BondDataType getBondDataType() { return BondDataType.BT_UINT16; } @Override public final Class<Short> getValueClass() { return Short.class; } @Override public final Class<Short> getPrimitiveValueClass() { return Short.TYPE; } @Override protected final Short newDefaultValue() { return DEFAULT_VALUE_AS_OBJECT; } @Override protected final void serializeValue(SerializationContext context, Short value) throws IOException { this.verifyNonNullableValueIsNotSetToNull(value); serializePrimitiveValue(context, value); } @Override protected final Short deserializeValue(TaggedDeserializationContext context) throws IOException { return deserializePrimitiveValue(context); } @Override protected final Short deserializeValue( UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return deserializePrimitiveValue(context); } @Override protected final void serializeField( SerializationContext context, Short value, StructBondType.StructField<Short> field) throws IOException { this.verifySerializedNonNullableFieldIsNotSetToNull(value, field); serializePrimitiveField(context, value, field); } @Override protected final Short deserializeField( TaggedDeserializationContext context, StructBondType.StructField<Short> field) throws IOException { return deserializePrimitiveField(context, field); } /** * Implements the behavior of the {@link BondType#serializeValue(SerializationContext, Object)} method * for primitive values. * * @param context contains the runtime context of the serialization * @param value the value to serialize * @throws IOException if an I/O error occurred */ protected static void serializePrimitiveValue(SerializationContext context, short value) throws IOException { context.writer.writeUInt16(value); } /** * Implements the behavior of the {@link BondType#deserializeValue(TaggedDeserializationContext)} method * for primitive values. * * @param context contains the runtime context of the deserialization * @return the deserialized value * @throws IOException if an I/O error occurred */ protected static short deserializePrimitiveValue(TaggedDeserializationContext context) throws IOException { return context.reader.readUInt16(); } /** * Implements the behavior of the {@link BondType#deserializeValue(UntaggedDeserializationContext, TypeDef)} * method for primitive values. * * @param context contains the runtime context of the deserialization * @return the deserialized value * @throws IOException if an I/O error occurred */ protected static short deserializePrimitiveValue(UntaggedDeserializationContext context) throws IOException { return context.reader.readUInt16(); } /** * Implements the behavior of the * {@link BondType#serializeField(SerializationContext, Object, StructBondType.StructField)} * for primitive values. * * @param context contains the runtime context of the serialization * @param value the value to serialize * @param field descriptor of the field * @throws IOException if an I/O error occurred */ protected static void serializePrimitiveField( SerializationContext context, short value, StructBondType.StructField<Short> field) throws IOException { if (!field.isDefaultNothing() && field.isOptional() && (value == field.getDefaultValue())) { context.writer.writeFieldOmitted(BondDataType.BT_UINT16, field.getId(), field.getFieldDef().metadata); } else { context.writer.writeFieldBegin(BondDataType.BT_UINT16, field.getId(), field.getFieldDef().metadata); context.writer.writeUInt16(value); context.writer.writeFieldEnd(); } } /** * Implements the behavior of the * {@link BondType#serializeSomethingField(SerializationContext, SomethingObject, StructBondType.StructField)} * for primitive values. * * @param context contains the runtime context of the serialization * @param value the value to serialize * @param field descriptor of the field * @throws IOException if an I/O error occurred */ protected static void serializePrimitiveSomethingField( SerializationContext context, SomethingShort value, StructBondType.StructField<Short> field) throws IOException { if (value != null) { serializePrimitiveField(context, value.value, field); } else if (!field.isOptional()) { // throws Throw.raiseNonOptionalFieldValueSetToNothingError(field); } } /** * Implements the behavior of the * {@link BondType#deserializeField(TaggedDeserializationContext, StructBondType.StructField)} * for primitive values. * * @param context contains the runtime context of the deserialization * @param field descriptor of the field * @return the deserialized value * @throws IOException if an I/O error occurred */ protected static short deserializePrimitiveField( TaggedDeserializationContext context, StructBondType.StructField<Short> field) throws IOException { // an uint16 value may be deserialized from BT_UINT16 or BT_UINT8 if (context.readFieldResult.type.value != BondDataType.BT_UINT16.value) { if (context.readFieldResult.type.value == BondDataType.BT_UINT8.value) { return context.reader.readInt8(); } // throws Throw.raiseFieldTypeIsNotCompatibleDeserializationError(context.readFieldResult.type, field); } return context.reader.readUInt16(); } /** * Implements the behavior of the * {@link BondType#deserializeSomethingField(TaggedDeserializationContext, StructBondType.StructField)} * for primitive values. * * @param context contains the runtime context of the deserialization * @param field descriptor of the field * @return the deserialized value * @throws IOException if an I/O error occurred */ protected static SomethingShort deserializePrimitiveSomethingField( TaggedDeserializationContext context, StructBondType.StructField<Short> field) throws IOException { return Something.wrap(deserializePrimitiveField(context, field)); } }
2,880
783
/* * The MIT License (MIT) * * Copyright (c) 2014 Zillow * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.yalantis.cameramodule.control; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.RectF; import android.hardware.Camera; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.ImageView; import com.yalantis.cameramodule.interfaces.FocusCallback; import com.yalantis.cameramodule.interfaces.KeyEventsListener; import com.yalantis.cameramodule.model.FocusMode; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import timber.log.Timber; public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback, Camera.AutoFocusCallback { private static final int DISPLAY_ORIENTATION = 90; private static final float FOCUS_AREA_SIZE = 75f; private static final float STROKE_WIDTH = 5f; private static final float FOCUS_AREA_FULL_SIZE = 2000f; private static final int ACCURACY = 3; private Activity activity; private Camera camera; private ImageView canvasFrame; private Canvas canvas; private Paint paint; private FocusMode focusMode = FocusMode.AUTO; private boolean hasAutoFocus; private boolean focusing; private boolean focused; private float focusKoefW; private float focusKoefH; private float prevScaleFactor; private FocusCallback focusCallback; private Rect tapArea; private KeyEventsListener keyEventsListener; public CameraPreview(Activity activity, Camera camera, ImageView canvasFrame, FocusCallback focusCallback, KeyEventsListener keyEventsListener) { super(activity); this.activity = activity; this.camera = camera; this.canvasFrame = canvasFrame; this.focusCallback = focusCallback; this.keyEventsListener = keyEventsListener; List<String> supportedFocusModes = camera.getParameters().getSupportedFocusModes(); hasAutoFocus = supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO); initHolder(); } private void initHolder() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. SurfaceHolder holder = getHolder(); if (holder != null) { holder.addCallback(this); holder.setKeepScreenOn(true); } } private void initFocusDrawingTools(int width, int height) { Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444); canvas = new Canvas(bitmap); paint = new Paint(); paint.setColor(Color.GREEN); paint.setStrokeWidth(STROKE_WIDTH); canvasFrame.setImageBitmap(bitmap); } public void surfaceCreated(SurfaceHolder holder) { Timber.d("surfaceCreated"); // The Surface has been created, now tell the camera where to draw the preview. startPreview(holder); } public void surfaceDestroyed(SurfaceHolder holder) { Timber.d("surfaceDestroyed"); stopPreview(); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Timber.d("surfaceChanged(%1d, %2d)", width, height); // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. initFocusDrawingTools(width, height); initFocusKoefs(width, height); if (holder.getSurface() == null) { // preview surface does not exist return; } stopPreview(); startPreview(holder); setOnTouchListener(new CameraTouchListener()); } private void initFocusKoefs(float width, float height) { focusKoefW = width / FOCUS_AREA_FULL_SIZE; focusKoefH = height / FOCUS_AREA_FULL_SIZE; } public void setFocusMode(FocusMode focusMode) { clearCameraFocus(); this.focusMode = focusMode; focusing = false; setOnTouchListener(new CameraTouchListener()); } private void startFocusing() { if (!focusing) { focused = false; focusing = true; if (focusMode == FocusMode.AUTO || (focusMode == FocusMode.TOUCH && tapArea == null)) { drawFocusFrame(createAutoFocusRect()); } camera.autoFocus(this); } } public void takePicture() { if (hasAutoFocus) { if (focusMode == FocusMode.AUTO) { startFocusing(); } if (focusMode == FocusMode.TOUCH) { if (focused && tapArea != null) { focused(); } else { startFocusing(); } } } else { focused(); } } private Rect createAutoFocusRect() { int left = (int) (getWidth() / 2 - FOCUS_AREA_SIZE); int right = (int) (getWidth() / 2 + FOCUS_AREA_SIZE); int top = (int) (getHeight() / 2 - FOCUS_AREA_SIZE); int bottom = (int) (getHeight() / 2 + FOCUS_AREA_SIZE); return new Rect(left, top, right, bottom); } private void startPreview(SurfaceHolder holder) { Timber.d("startPreview"); try { camera.setPreviewDisplay(holder); camera.setDisplayOrientation(DISPLAY_ORIENTATION); Camera.Parameters parameters = camera.getParameters(); parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); camera.setParameters(parameters); camera.startPreview(); } catch (Exception e) { Timber.e(e, "Error starting camera preview: " + e.getMessage()); } } private void stopPreview() { Timber.d("stopPreview"); try { camera.stopPreview(); } catch (Exception e) { Timber.e(e, "Error stopping camera preview: " + e.getMessage()); } } private void drawFocusFrame(Rect rect) { canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); canvas.drawLine(rect.left, rect.top, rect.right, rect.top, paint); canvas.drawLine(rect.right, rect.top, rect.right, rect.bottom, paint); canvas.drawLine(rect.right, rect.bottom, rect.left, rect.bottom, paint); canvas.drawLine(rect.left, rect.bottom, rect.left, rect.top, paint); canvasFrame.draw(canvas); canvasFrame.invalidate(); } private void clearCameraFocus() { if (hasAutoFocus) { focused = false; camera.cancelAutoFocus(); if (canvas != null) { tapArea = null; try { Camera.Parameters parameters = camera.getParameters(); parameters.setFocusAreas(null); parameters.setMeteringAreas(null); camera.setParameters(parameters); } catch (Exception e) { Timber.e(e, "clearCameraFocus"); } finally { canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); canvasFrame.draw(canvas); canvasFrame.invalidate(); } } } } @Override public void onAutoFocus(boolean success, Camera camera) { focusing = false; focused = true; if (focusMode == FocusMode.AUTO) { focused(); } if (focusMode == FocusMode.TOUCH && tapArea == null) { focused(); } } private void focused() { focusing = false; if (focusCallback != null) { focusCallback.onFocused(camera); } } public void onPictureTaken() { clearCameraFocus(); } protected void focusOnTouch(MotionEvent event) { tapArea = calculateTapArea(event.getX(), event.getY(), 1f); Camera.Parameters parameters = camera.getParameters(); int maxFocusAreas = parameters.getMaxNumFocusAreas(); if (maxFocusAreas > 0) { Camera.Area area = new Camera.Area(convert(tapArea), 100); parameters.setFocusAreas(Arrays.asList(area)); } maxFocusAreas = parameters.getMaxNumMeteringAreas(); if (maxFocusAreas > 0) { Rect rectMetering = calculateTapArea(event.getX(), event.getY(), 1.5f); Camera.Area area = new Camera.Area(convert(rectMetering), 100); parameters.setMeteringAreas(Arrays.asList(area)); } camera.setParameters(parameters); drawFocusFrame(tapArea); startFocusing(); } /** * Convert touch position x:y to {@link android.hardware.Camera.Area} position -1000:-1000 to 1000:1000. */ private Rect calculateTapArea(float x, float y, float coefficient) { int areaSize = Float.valueOf(FOCUS_AREA_SIZE * coefficient).intValue(); int left = clamp((int) x - areaSize / 2, 0, getWidth() - areaSize); int top = clamp((int) y - areaSize / 2, 0, getHeight() - areaSize); RectF rect = new RectF(left, top, left + areaSize, top + areaSize); Timber.d("tap: " + rect.toShortString()); return round(rect); } private Rect round(RectF rect) { return new Rect(Math.round(rect.left), Math.round(rect.top), Math.round(rect.right), Math.round(rect.bottom)); } private Rect convert(Rect rect) { Rect result = new Rect(); result.top = normalize(rect.top / focusKoefH - 1000); result.left = normalize(rect.left / focusKoefW - 1000); result.right = normalize(rect.right / focusKoefW - 1000); result.bottom = normalize(rect.bottom / focusKoefH - 1000); Timber.d("convert: " + result.toShortString()); return result; } private int normalize(float value) { if (value > 1000) { return 1000; } if (value < -1000) { return -1000; } return Math.round(value); } private int clamp(int x, int min, int max) { if (x > max) { return max; } if (x < min) { return min; } return x; } private void scale(float scaleFactor) { scaleFactor = BigDecimal.valueOf(scaleFactor).setScale(ACCURACY, BigDecimal.ROUND_HALF_UP).floatValue(); if (Float.compare(scaleFactor, 1.0f) == 0 || Float.compare(scaleFactor, prevScaleFactor) == 0) { return; } if (scaleFactor > 1f) { keyEventsListener.zoomIn(); } if (scaleFactor < 1f) { keyEventsListener.zoomOut(); } prevScaleFactor = scaleFactor; } private class CameraTouchListener implements OnTouchListener { private ScaleGestureDetector mScaleDetector = new ScaleGestureDetector(activity, new ScaleListener()); private GestureDetector mTapDetector = new GestureDetector(activity, new TapListener()); @Override public boolean onTouch(View v, MotionEvent event) { clearCameraFocus(); if (event.getPointerCount() > 1) { mScaleDetector.onTouchEvent(event); return true; } if (hasAutoFocus && focusMode == FocusMode.TOUCH) { mTapDetector.onTouchEvent(event); return true; } return true; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { scale(detector.getScaleFactor()); return true; } } private class TapListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapConfirmed(MotionEvent event) { focusOnTouch(event); return true; } } } }
5,562
1,858
/* * Tencent is pleased to support the open source community by making TENCENT SOTER available. * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * https://opensource.org/licenses/BSD-3-Clause * 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.tencent.soter.core.model; import org.json.JSONException; import org.json.JSONObject; /** * The signature model generated in TEE after authenticated by user's enrolled fingerprint. */ @SuppressWarnings({"unused", "WeakerAccess"}) public class SoterSignatureResult { private static final String TAG = "Soter.SoterSignatureResult"; private static final String SIGNATURE_KEY_RAW = "raw"; private static final String SIGNATURE_KEY_FID = "fid"; private static final String SIGNATURE_KEY_COUNTER = "counter"; private static final String SIGNATURE_KEY_TEE_NAME = "tee_n"; private static final String SIGNATURE_KEY_TEE_VERSION = "tee_v"; private static final String SIGNATURE_KEY_FP_NAME = "fp_n"; private static final String SIGNATURE_KEY_FP_VERSION = "fp_v"; private static final String SIGNATURE_KEY_CPU_ID = "cpu_id"; private static final String SIGNATURE_KEY_SALTLEN = "rsa_pss_saltlen"; private static final int DEFAULT_SALT_LEN = 20; private String rawValue = null; private String fid = null; private long counter = -1; private String TEEName = ""; private String TEEVersion = ""; private String FpName = ""; private String FpVersion = ""; private String cpuId = ""; private int saltLen = DEFAULT_SALT_LEN; public String getJsonValue() { return jsonValue; } private void setJsonValue(String jsonValue) { this.jsonValue = jsonValue; } private String jsonValue = ""; //real signature public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } private String signature = ""; public void setCpuId(String cpuId) { this.cpuId = cpuId; } public SoterSignatureResult(String rawValue, String fid, long counter, String TEEName, String TEEVersion, String fpName, String fpVersion, String cpuId, String signature, int saltLen) { this.rawValue = rawValue; this.fid = fid; this.counter = counter; this.TEEName = TEEName; this.TEEVersion = TEEVersion; FpName = fpName; FpVersion = fpVersion; this.cpuId = cpuId; this.signature = signature; this.saltLen = saltLen; } @Override public String toString() { return "SoterSignatureResult{" + "rawValue='" + rawValue + '\'' + ", fid='" + fid + '\'' + ", counter=" + counter + ", TEEName='" + TEEName + '\'' + ", TEEVersion='" + TEEVersion + '\'' + ", FpName='" + FpName + '\'' + ", FpVersion='" + FpVersion + '\'' + ", cpuId='" + cpuId + '\'' + ", saltLen=" + saltLen + ", jsonValue='" + jsonValue + '\'' + ", signature='" + signature + '\'' + '}'; } public SoterSignatureResult() { } public static SoterSignatureResult convertFromJson(String jsonStr) { // this.jsonValue = jsonStr; try { JSONObject jsonObj = new JSONObject(jsonStr); SoterSignatureResult result = new SoterSignatureResult(); result.setJsonValue(jsonStr); result.setRawValue(jsonObj.optString(SIGNATURE_KEY_RAW)); result.setFid(jsonObj.optString(SIGNATURE_KEY_FID)); result.setCounter(jsonObj.optLong(SIGNATURE_KEY_COUNTER)); result.setTEEName(jsonObj.optString(SIGNATURE_KEY_TEE_NAME)); result.setTEEVersion(jsonObj.optString(SIGNATURE_KEY_TEE_VERSION)); result.setFpName(jsonObj.optString(SIGNATURE_KEY_FP_NAME)); result.setFpVersion(jsonObj.optString(SIGNATURE_KEY_FP_VERSION)); result.setCpuId(jsonObj.optString(SIGNATURE_KEY_CPU_ID)); result.setSaltLen(jsonObj.optInt(SIGNATURE_KEY_SALTLEN, DEFAULT_SALT_LEN)); return result; } catch (JSONException e) { SLogger.e(TAG, "soter: convert from json failed." + e.toString()); return null; } } private void setRawValue(String rawValue) { this.rawValue = rawValue; } private void setFid(String fid) { this.fid = fid; } private void setCounter(long counter) { this.counter = counter; } private void setTEEName(String TEEName) { this.TEEName = TEEName; } private void setTEEVersion(String TEEVersion) { this.TEEVersion = TEEVersion; } private void setFpName(String fpName) { FpName = fpName; } private void setFpVersion(String fpVersion) { FpVersion = fpVersion; } private void setSaltLen(int saltLen) { this.saltLen = saltLen; } public String getRawValue() { return rawValue; } public String getFid() { return fid; } public long getCounter() { return counter; } public String getTEEName() { return TEEName; } public String getTEEVersion() { return TEEVersion; } public String getFpName() { return FpName; } public String getFpVersion() { return FpVersion; } public String getCpuId() { return cpuId; } public int getSaltLen() { return saltLen; } }
2,478
663
<reponame>mchelen-gov/integrations-core # (C) Datadog, Inc. 2010-present # All rights reserved # Licensed under Simplified BSD License (see LICENSE)
49
1,608
<filename>cakechat/dialog_model/inference/__init__.py from cakechat.dialog_model.inference.utils import get_sequence_log_probs, get_sequence_score_by_thought_vector, \ get_sequence_score from cakechat.dialog_model.inference.predict import get_nn_response_ids, get_nn_responses, warmup_predictor from cakechat.dialog_model.inference.service_tokens import ServiceTokensIDs
125
1,850
<filename>repeater-plugin-api/src/main/java/com/alibaba/jvm/sandbox/repeater/plugin/domain/RepeatContext.java package com.alibaba.jvm.sandbox.repeater.plugin.domain; /** * <p> * * @author zhaoyb1990 */ public class RepeatContext { private RepeatMeta meta; private RecordModel recordModel; private String traceId; public RepeatContext(RepeatMeta meta, RecordModel recordModel, String traceId) { this.meta = meta; this.recordModel = recordModel; this.traceId = traceId; } public RepeatMeta getMeta() { return meta; } public void setMeta(RepeatMeta meta) { this.meta = meta; } public RecordModel getRecordModel() { return recordModel; } public void setRecordModel(RecordModel recordModel) { this.recordModel = recordModel; } public String getTraceId() { return traceId; } public void setTraceId(String traceId) { this.traceId = traceId; } }
381
1,118
{"deu":{"common":"Libyen","official":"Staat Libyen"},"fin":{"common":"Libya","official":"Libyan valtio"},"fra":{"common":"Libye","official":"Grande République arabe libyenne populaire et socialiste"},"hrv":{"common":"Libija","official":"Država Libiji"},"ita":{"common":"Libia","official":"Stato della Libia"},"jpn":{"common":"リビア","official":"リビアの国家"},"nld":{"common":"Libië","official":"Staat van Libië"},"por":{"common":"Líbia","official":"Estado da Líbia"},"rus":{"common":"Ливия","official":"Государство Ливии"},"spa":{"common":"Libia","official":"Estado de Libia"}}
200
11,356
<filename>deps/src/boost_1_65_1/boost/graph/sequential_vertex_coloring.hpp //======================================================================= // Copyright 1997, 1998, 1999, 2000 University of Notre Dame. // Copyright 2004 The Trustees of Indiana University // Authors: <NAME>, <NAME>, <NAME> // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef BOOST_GRAPH_SEQUENTIAL_VERTEX_COLORING_HPP #define BOOST_GRAPH_SEQUENTIAL_VERTEX_COLORING_HPP #include <vector> #include <boost/graph/graph_traits.hpp> #include <boost/tuple/tuple.hpp> #include <boost/property_map/property_map.hpp> #include <boost/limits.hpp> #ifdef BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS # include <iterator> #endif /* This algorithm is to find coloring of a graph Algorithm: Let G = (V,E) be a graph with vertices (somehow) ordered v_1, v_2, ..., v_n. For k = 1, 2, ..., n the sequential algorithm assigns v_k to the smallest possible color. Reference: <NAME> and <NAME>, Estimation of sparse Jacobian matrices and graph coloring problems. J. Numer. Anal. V20, P187-209, 1983 v_k is stored as o[k] here. The color of the vertex v will be stored in color[v]. i.e., vertex v belongs to coloring color[v] */ namespace boost { template <class VertexListGraph, class OrderPA, class ColorMap> typename property_traits<ColorMap>::value_type sequential_vertex_coloring(const VertexListGraph& G, OrderPA order, ColorMap color) { typedef graph_traits<VertexListGraph> GraphTraits; typedef typename GraphTraits::vertex_descriptor Vertex; typedef typename property_traits<ColorMap>::value_type size_type; size_type max_color = 0; const size_type V = num_vertices(G); // We need to keep track of which colors are used by // adjacent vertices. We do this by marking the colors // that are used. The mark array contains the mark // for each color. The length of mark is the // number of vertices since the maximum possible number of colors // is the number of vertices. std::vector<size_type> mark(V, std::numeric_limits<size_type>::max BOOST_PREVENT_MACRO_SUBSTITUTION()); //Initialize colors typename GraphTraits::vertex_iterator v, vend; for (boost::tie(v, vend) = vertices(G); v != vend; ++v) put(color, *v, V-1); //Determine the color for every vertex one by one for ( size_type i = 0; i < V; i++) { Vertex current = get(order,i); typename GraphTraits::adjacency_iterator v, vend; //Mark the colors of vertices adjacent to current. //i can be the value for marking since i increases successively for (boost::tie(v,vend) = adjacent_vertices(current, G); v != vend; ++v) mark[get(color,*v)] = i; //Next step is to assign the smallest un-marked color //to the current vertex. size_type j = 0; //Scan through all useable colors, find the smallest possible //color that is not used by neighbors. Note that if mark[j] //is equal to i, color j is used by one of the current vertex's //neighbors. while ( j < max_color && mark[j] == i ) ++j; if ( j == max_color ) //All colors are used up. Add one more color ++max_color; //At this point, j is the smallest possible color put(color, current, j); //Save the color of vertex current } return max_color; } template<class VertexListGraph, class ColorMap> typename property_traits<ColorMap>::value_type sequential_vertex_coloring(const VertexListGraph& G, ColorMap color) { typedef typename graph_traits<VertexListGraph>::vertex_descriptor vertex_descriptor; typedef typename graph_traits<VertexListGraph>::vertex_iterator vertex_iterator; std::pair<vertex_iterator, vertex_iterator> v = vertices(G); #ifndef BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS std::vector<vertex_descriptor> order(v.first, v.second); #else std::vector<vertex_descriptor> order; order.reserve(std::distance(v.first, v.second)); while (v.first != v.second) order.push_back(*v.first++); #endif return sequential_vertex_coloring (G, make_iterator_property_map (order.begin(), identity_property_map(), graph_traits<VertexListGraph>::null_vertex()), color); } } #endif
1,697
30,023
<reponame>liangleslie/core { "options": { "step": { "init": { "data": { "timestep": "Minuteid NowCasti prognooside vahel" }, "description": "Kui otsustad lubada \"nowcast\" prognoosi\u00fcksuse, saad seadistada minutite arvu iga prognoosi vahel. Esitatavate prognooside arv s\u00f5ltub prognooside vahel valitud minutite arvust.", "title": "V\u00e4rskenda [%key:component::climacell::title%] suvandeid" } } } }
296
416
package org.springframework.roo.addon.web.mvc.controller.addon.test; import static org.springframework.roo.model.RooJavaType.ROO_JSON_CONTROLLER_INTEGRATION_TEST; import org.apache.commons.lang3.Validate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; import org.osgi.service.component.ComponentContext; import org.springframework.roo.addon.jpa.addon.entity.factories.JpaEntityFactoryLocator; import org.springframework.roo.addon.layers.service.addon.ServiceLocator; import org.springframework.roo.classpath.PhysicalTypeIdentifier; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.classpath.details.ItdTypeDetails; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.classpath.itd.AbstractMemberDiscoveringItdMetadataProvider; import org.springframework.roo.classpath.itd.ItdTypeDetailsProvidingMetadataItem; import org.springframework.roo.metadata.MetadataDependencyRegistry; import org.springframework.roo.metadata.internal.MetadataDependencyRegistryTracker; import org.springframework.roo.model.JavaType; import org.springframework.roo.model.RooJavaType; import org.springframework.roo.project.LogicalPath; /** * Implementation of {@link JsonControllerIntegrationTestMetadataProvider}. * * @author <NAME> * @since 2.0 */ @Component @Service public class JsonControllerIntegrationTestMetadataProviderImpl extends AbstractMemberDiscoveringItdMetadataProvider implements JsonControllerIntegrationTestMetadataProvider { protected MetadataDependencyRegistryTracker registryTracker = null; /** * This service is being activated so setup it: * <ul> * <li>Create and open the {@link MetadataDependencyRegistryTracker}.</li> * <li>Registers {@link RooJavaType#ROO_JSON_CONTROLLER_INTEGRATION_TEST} as * additional JavaType that will trigger metadata registration.</li> * </ul> */ @Override protected void activate(final ComponentContext cContext) { super.activate(cContext); this.registryTracker = new MetadataDependencyRegistryTracker(cContext.getBundleContext(), this, PhysicalTypeIdentifier.getMetadataIdentiferType(), getProvidesType()); this.registryTracker.open(); addMetadataTrigger(ROO_JSON_CONTROLLER_INTEGRATION_TEST); } /** * This service is being deactivated so unregister upstream-downstream * dependencies, triggers, matchers and listeners. * * @param context */ protected void deactivate(final ComponentContext context) { MetadataDependencyRegistry registry = this.registryTracker.getService(); registry.removeNotificationListener(this); registry.deregisterDependency(PhysicalTypeIdentifier.getMetadataIdentiferType(), getProvidesType()); this.registryTracker.close(); removeMetadataTrigger(ROO_JSON_CONTROLLER_INTEGRATION_TEST); } @Override protected String createLocalIdentifier(final JavaType javaType, final LogicalPath path) { return JsonControllerIntegrationTestMetadata.createIdentifier(javaType, path); } @Override protected String getGovernorPhysicalTypeIdentifier(final String metadataIdentificationString) { final JavaType javaType = JsonControllerIntegrationTestMetadata.getJavaType(metadataIdentificationString); final LogicalPath path = JsonControllerIntegrationTestMetadata.getPath(metadataIdentificationString); return PhysicalTypeIdentifier.createIdentifier(javaType, path); } @Override protected String getLocalMidToRequest(final ItdTypeDetails itdTypeDetails) { return getLocalMid(itdTypeDetails); } @Override public String getItdUniquenessFilenameSuffix() { return "JsonControllerIntegrationTest"; } @Override protected ItdTypeDetailsProvidingMetadataItem getMetadata( final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) { final JsonControllerIntegrationTestAnnotationValues annotationValues = new JsonControllerIntegrationTestAnnotationValues(governorPhysicalTypeMetadata); // Get JSON controller target class final JavaType jsonController = annotationValues.getTargetClass(); // Get the controller managed entity ClassOrInterfaceTypeDetails controllerCid = getTypeLocationService().getTypeDetails(jsonController); AnnotationMetadata rooControllerAnnotation = controllerCid.getAnnotation(RooJavaType.ROO_CONTROLLER); Validate.notNull(rooControllerAnnotation, "The target class must be annotated with @RooController."); Validate.notNull(rooControllerAnnotation.getAttribute("entity"), "The @RooController must have an 'entity' attribute, targeting managed entity."); final JavaType managedEntity = (JavaType) rooControllerAnnotation.getAttribute("entity").getValue(); // Get the entity factory of managed entity final JavaType entityFactory = getJpaEntityFactoryLocator().getFirstJpaEntityFactoryForEntity(managedEntity); // Get the service related to managed entity final JavaType entityService = getServiceLocator().getFirstService(managedEntity).getType(); return new JsonControllerIntegrationTestMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, annotationValues, jsonController, managedEntity, entityFactory, entityService); } public String getProvidesType() { return JsonControllerIntegrationTestMetadata.getMetadataIdentiferType(); } protected JpaEntityFactoryLocator getJpaEntityFactoryLocator() { return this.serviceManager.getServiceInstance(this, JpaEntityFactoryLocator.class); } protected ServiceLocator getServiceLocator() { return this.serviceManager.getServiceInstance(this, ServiceLocator.class); } }
1,797
1,056
<filename>groovy/groovy.editor/test/unit/src/org/netbeans/modules/groovy/editor/api/GroovyLexerIncTest.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 org.netbeans.modules.groovy.editor.api; import java.util.ConcurrentModificationException; import java.util.logging.Level; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import org.netbeans.api.lexer.Language; import org.netbeans.api.lexer.TokenHierarchy; import org.netbeans.api.lexer.TokenSequence; import org.netbeans.junit.NbTestCase; import org.netbeans.lib.lexer.test.LexerTestUtilities; import org.netbeans.lib.lexer.test.ModificationTextDocument; import org.netbeans.modules.groovy.editor.api.lexer.GroovyTokenId; /** * * @author <NAME> */ public class GroovyLexerIncTest extends NbTestCase { public GroovyLexerIncTest(String testName) { super(testName); } @Override protected void setUp() throws java.lang.Exception { // uncomment to enable logging from GroovyLexer // Logger.getLogger("org.netbeans.modules.groovy.editor.lexer.GroovyLexer").setLevel(Level.FINEST); } protected Level logLevel() { // enabling logging return Level.INFO; // we are only interested in a single logger, so we set its level in setUp(), // as returning Level.FINEST here would log from all loggers } public void test1() throws Exception { Document doc = new ModificationTextDocument(); // Assign a language to the document doc.putProperty(Language.class,GroovyTokenId.language()); TokenHierarchy<?> hi = TokenHierarchy.get(doc); assertNotNull("Null token hierarchy for document", hi); TokenSequence<?> ts = hi.tokenSequence(); // contains \n assertTrue(ts.moveNext()); assertEquals(GroovyTokenId.NLS, ts.token().id()); assertFalse(ts.moveNext()); // Insert text into document String text = "println \"Hello $name\""; doc.insertString(0, text, null); // Logger.getLogger(org.netbeans.lib.lexer.inc.TokenListUpdater.class.getName()).setLevel(Level.FINE); // Extra logging // Logger.getLogger(org.netbeans.lib.lexer.inc.TokenHierarchyUpdate.class.getName()).setLevel(Level.FINE); // Extra logging // Last token sequence should throw exception - new must be obtained try { ts.moveNext(); fail("TokenSequence.moveNext() did not throw exception as expected."); } catch (ConcurrentModificationException e) { // Expected exception } ts = hi.tokenSequence(); next(ts, GroovyTokenId.IDENTIFIER, "println", 0); assertEquals(1, LexerTestUtilities.lookahead(ts)); next(ts, GroovyTokenId.WHITESPACE, " ", 7); next(ts, GroovyTokenId.STRING_LITERAL, "\"Hello $", 8); next(ts, GroovyTokenId.IDENTIFIER, "name", 16); next(ts, GroovyTokenId.STRING_LITERAL, "\"", 20); // contains \n assertTrue(ts.moveNext()); assertEquals(GroovyTokenId.NLS, ts.token().id()); assertFalse(ts.moveNext()); LexerTestUtilities.incCheck(doc, false); int offset = text.length() - 1; // Check TokenSequence.move() int relOffset = ts.move(50); // past the end of all tokens assertEquals(relOffset, 50 - (offset + 2)); assertTrue(ts.movePrevious()); LexerTestUtilities.assertTokenEquals(ts, GroovyTokenId.NLS, "\n", offset + 1); assertTrue(ts.movePrevious()); LexerTestUtilities.assertTokenEquals(ts, GroovyTokenId.STRING_LITERAL, "\"", offset); relOffset = ts.move(8); // right at begining of gstring assertEquals(relOffset, 0); assertTrue(ts.moveNext()); LexerTestUtilities.assertTokenEquals(ts, GroovyTokenId.STRING_LITERAL, "\"Hello $", 8); relOffset = ts.move(-5); // to first token "println" assertEquals(relOffset, -5); assertTrue(ts.moveNext()); LexerTestUtilities.assertTokenEquals(ts, GroovyTokenId.IDENTIFIER, "println", 0); relOffset = ts.move(10); assertEquals(relOffset, 2); assertTrue(ts.moveNext()); LexerTestUtilities.assertTokenEquals(ts, GroovyTokenId.STRING_LITERAL, "\"Hello $", 8); doc.insertString(5, "x", null); // should be "printxln" // Last token sequence should throw exception - new must be obtained try { ts.moveNext(); fail("TokenSequence.moveNext() did not throw exception as expected."); } catch (ConcurrentModificationException e) { // Expected exception } ts = hi.tokenSequence(); assertTrue(ts.moveNext()); LexerTestUtilities.assertTokenEquals(ts, GroovyTokenId.IDENTIFIER, "printxln", 0); LexerTestUtilities.incCheck(doc, false); // Remove added 'x' to become "println" again doc.remove(5, 1); // should be "println" again ts = hi.tokenSequence(); assertTrue(ts.moveNext()); LexerTestUtilities.assertTokenEquals(ts, GroovyTokenId.IDENTIFIER, "println", 0); LexerTestUtilities.incCheck(doc, false); // Now insert right at the end of first token - identifier with lookahead 1 doc.insertString(7, "x", null); // should become "printlnx" ts = hi.tokenSequence(); assertTrue(ts.moveNext()); LexerTestUtilities.assertTokenEquals(ts, GroovyTokenId.IDENTIFIER, "printlnx", 0); LexerTestUtilities.incCheck(doc, false); doc.remove(7, 1); // return back to "println" ts = hi.tokenSequence(); assertTrue(ts.moveNext()); LexerTestUtilities.assertTokenEquals(ts, GroovyTokenId.IDENTIFIER, "println", 0); LexerTestUtilities.incCheck(doc, false); doc.insertString(offset, " ", null); ts = hi.tokenSequence(); next(ts, GroovyTokenId.IDENTIFIER, "println", 0); next(ts, GroovyTokenId.WHITESPACE, " ", 7); next(ts, GroovyTokenId.STRING_LITERAL, "\"Hello $", 8); next(ts, GroovyTokenId.IDENTIFIER, "name", 16); next(ts, GroovyTokenId.STRING_LITERAL, " \"", 20); assertTrue(ts.moveNext()); assertEquals(GroovyTokenId.NLS, ts.token().id()); assertFalse(ts.moveNext()); LexerTestUtilities.incCheck(doc, false); } public void test2() throws Exception { Document doc = new ModificationTextDocument(); // Assign a language to the document doc.putProperty(Language.class,GroovyTokenId.language()); TokenHierarchy<?> hi = TokenHierarchy.get(doc); assertNotNull("Null token hierarchy for document", hi); TokenSequence<?> ts = hi.tokenSequence(); // contains \n assertTrue(ts.moveNext()); assertEquals(GroovyTokenId.NLS, ts.token().id()); assertFalse(ts.moveNext()); // Insert text into document String text = "println \"Hello ${name} !\""; doc.insertString(0, text, null); // Last token sequence should throw exception - new must be obtained try { ts.moveNext(); fail("TokenSequence.moveNext() did not throw exception as expected."); } catch (ConcurrentModificationException e) { // Expected exception } ts = hi.tokenSequence(); next(ts, GroovyTokenId.IDENTIFIER, "println", 0); next(ts, GroovyTokenId.WHITESPACE, " ", 7); next(ts, GroovyTokenId.STRING_LITERAL, "\"Hello $", 8); next(ts, GroovyTokenId.LBRACE, "{", 16); next(ts, GroovyTokenId.IDENTIFIER, "name", 17); next(ts, GroovyTokenId.RBRACE, "}", 21); next(ts, GroovyTokenId.STRING_LITERAL, " !\"", 22); // contains \n assertTrue(ts.moveNext()); assertEquals(GroovyTokenId.NLS, ts.token().id()); assertFalse(ts.moveNext()); LexerTestUtilities.incCheck(doc, false); int offset = text.length() - 3; doc.insertString(offset, " ", null); ts = hi.tokenSequence(); next(ts, GroovyTokenId.IDENTIFIER, "println", 0); next(ts, GroovyTokenId.WHITESPACE, " ", 7); next(ts, GroovyTokenId.STRING_LITERAL, "\"Hello $", 8); next(ts, GroovyTokenId.LBRACE, "{", 16); next(ts, GroovyTokenId.IDENTIFIER, "name", 17); next(ts, GroovyTokenId.RBRACE, "}", 21); next(ts, GroovyTokenId.STRING_LITERAL, " !\"", 22); // contains \n assertTrue(ts.moveNext()); assertEquals(GroovyTokenId.NLS, ts.token().id()); assertFalse(ts.moveNext()); LexerTestUtilities.incCheck(doc, false); offset = text.length() - 3; doc.insertString(offset, " ", null); ts = hi.tokenSequence(); next(ts, GroovyTokenId.IDENTIFIER, "println", 0); next(ts, GroovyTokenId.WHITESPACE, " ", 7); next(ts, GroovyTokenId.STRING_LITERAL, "\"Hello $", 8); next(ts, GroovyTokenId.LBRACE, "{", 16); next(ts, GroovyTokenId.IDENTIFIER, "name", 17); next(ts, GroovyTokenId.RBRACE, "}", 21); next(ts, GroovyTokenId.STRING_LITERAL, " !\"", 22); // contains \n assertTrue(ts.moveNext()); assertEquals(GroovyTokenId.NLS, ts.token().id()); assertFalse(ts.moveNext()); LexerTestUtilities.incCheck(doc, false); } public void test3() throws BadLocationException { Document doc = new ModificationTextDocument(); // Assign a language to the document doc.putProperty(Language.class,GroovyTokenId.language()); TokenHierarchy<?> hi = TokenHierarchy.get(doc); assertNotNull("Null token hierarchy for document", hi); TokenSequence<?> ts = hi.tokenSequence(); // contains \n assertTrue(ts.moveNext()); assertEquals(GroovyTokenId.NLS, ts.token().id()); assertFalse(ts.moveNext()); // Insert text into document String text = "class Foo { }"; doc.insertString(0, text, null); // Last token sequence should throw exception - new must be obtained try { ts.moveNext(); fail("TokenSequence.moveNext() did not throw exception as expected."); } catch (ConcurrentModificationException e) { // Expected exception } ts = hi.tokenSequence(); next(ts, GroovyTokenId.LITERAL_class, "class", 0); next(ts, GroovyTokenId.WHITESPACE, " ", 5); next(ts, GroovyTokenId.IDENTIFIER, "Foo", 6); next(ts, GroovyTokenId.WHITESPACE, " ", 9); next(ts, GroovyTokenId.LBRACE, "{", 10); next(ts, GroovyTokenId.WHITESPACE, " ", 11); next(ts, GroovyTokenId.RBRACE, "}", 13); // contains \n assertTrue(ts.moveNext()); assertEquals(GroovyTokenId.NLS, ts.token().id()); assertFalse(ts.moveNext()); LexerTestUtilities.incCheck(doc, false); int offset = text.length() - 2; doc.insertString(offset, "d", null); doc.insertString(offset + 1, "e", null); doc.insertString(offset + 2, "f", null); ts = hi.tokenSequence(); next(ts, GroovyTokenId.LITERAL_class, "class", 0); next(ts, GroovyTokenId.WHITESPACE, " ", 5); next(ts, GroovyTokenId.IDENTIFIER, "Foo", 6); next(ts, GroovyTokenId.WHITESPACE, " ", 9); next(ts, GroovyTokenId.LBRACE, "{", 10); next(ts, GroovyTokenId.WHITESPACE, " ", 11); next(ts, GroovyTokenId.LITERAL_def, "def", 12); next(ts, GroovyTokenId.WHITESPACE, " ", 15); next(ts, GroovyTokenId.RBRACE, "}", 16); // contains \n assertTrue(ts.moveNext()); assertEquals(GroovyTokenId.NLS, ts.token().id()); assertFalse(ts.moveNext()); LexerTestUtilities.incCheck(doc, false); } void next(TokenSequence<?> ts, GroovyTokenId id, String fixedText, int offset){ assertTrue(ts.moveNext()); LexerTestUtilities.assertTokenEquals(ts, id, fixedText, offset); } }
5,321
12,706
# -*- coding: utf-8 -*- import time import base import v2_swagger_client class Replication(base.Base, object): def __init__(self): super(Replication,self).__init__(api_type = "replication") def wait_until_jobs_finish(self, rule_id, retry=10, interval=5, **kwargs): Succeed = False for i in range(retry): Succeed = False jobs = self.get_replication_executions(rule_id, **kwargs) for job in jobs: if job.status == "Succeed": return if not Succeed: time.sleep(interval) if not Succeed: raise Exception("The jobs not Succeed") def trigger_replication_executions(self, rule_id, expect_status_code = 201, **kwargs): _, status_code, _ = self._get_client(**kwargs).start_replication_with_http_info({"policy_id":rule_id}) base._assert_status_code(expect_status_code, status_code) def get_replication_executions(self, rule_id, expect_status_code = 200, **kwargs): data, status_code, _ = self._get_client(**kwargs).list_replication_executions_with_http_info(policy_id=rule_id) base._assert_status_code(expect_status_code, status_code) return data def create_replication_policy(self, dest_registry=None, src_registry=None, name=None, description="", dest_namespace = "", filters=None, trigger=v2_swagger_client.ReplicationTrigger(type="manual",trigger_settings=v2_swagger_client.ReplicationTriggerSettings(cron="")), deletion=False, override=True, enabled=True, expect_status_code = 201, **kwargs): if name is None: name = base._random_name("rule") if filters is None: filters = [] policy = v2_swagger_client.ReplicationPolicy(name=name, description=description,dest_namespace=dest_namespace, dest_registry=dest_registry, src_registry=src_registry,filters=filters, trigger=trigger, deletion=deletion, override=override, enabled=enabled) _, status_code, header = self._get_client(**kwargs).create_replication_policy_with_http_info(policy) base._assert_status_code(expect_status_code, status_code) return base._get_id_from_header(header), name def get_replication_rule(self, param = None, rule_id = None, expect_status_code = 200, **kwargs): if rule_id is None: if param is None: param = dict() data, status_code, _ = self._get_client(**kwargs).get_replication_policy_with_http_info(param) else: data, status_code, _ = self._get_client(**kwargs).get_replication_policy_with_http_info(rule_id) base._assert_status_code(expect_status_code, status_code) return data def check_replication_rule_should_exist(self, check_rule_id, expect_rule_name, expect_trigger = None, **kwargs): rule_data = self.get_replication_rule(rule_id = check_rule_id, **kwargs) if str(rule_data.name) != str(expect_rule_name): raise Exception(r"Check replication rule failed, expect <{}> actual <{}>.".format(expect_rule_name, str(rule_data.name))) else: print(r"Check Replication rule passed, rule name <{}>.".format(str(rule_data.name))) #get_trigger = str(rule_data.trigger.kind) #if expect_trigger is not None and get_trigger == str(expect_trigger): # print r"Check Replication rule trigger passed, trigger name <{}>.".format(get_trigger) #else: # raise Exception(r"Check replication rule trigger failed, expect <{}> actual <{}>.".format(expect_trigger, get_trigger)) def delete_replication_rule(self, rule_id, expect_status_code = 200, **kwargs): _, status_code, _ = self._get_client(**kwargs).delete_replication_policy_with_http_info(rule_id) base._assert_status_code(expect_status_code, status_code)
1,758
383
#!/usr/bin/python3 import argparse from collections import defaultdict, OrderedDict parser = argparse.ArgumentParser() parser.add_argument('source_file') parser.add_argument('target_file') parser.add_argument('align_file') args = parser.parse_args() src_vocab = OrderedDict() trg_vocab = OrderedDict() counts = defaultdict(dict) with open(args.source_file) as src_file, open(args.target_file) as trg_file, open(args.align_file) as align_file: for src, trg, align in zip(src_file, trg_file, align_file): src = src.split() trg = trg.split() align = align.split() for i, j in map(lambda p: map(int, p.split('-')), align): src_ = src[i] trg_ = trg[j] src_id = src_vocab.setdefault(src_, len(src_vocab)) trg_id = trg_vocab.setdefault(trg_, len(trg_vocab)) #src_counts[src_id] = src_counts.get(src_id, 0) + 1 #trg_counts[trg_id] = trg_counts.get(trg_id, 0) + 1 #pair_counts((src_id, trg_id)) = pair_counts.get((src_id, trg_id), 0) + 1 counts[src_id][trg_id] = counts[src_id].get(trg_id, 0) + 1 src_vocab = list(src_vocab.keys()) trg_vocab = list(trg_vocab.keys()) for source, counts_ in counts.items(): target = max(counts_.keys(), key=lambda word: counts_[word]) source = src_vocab[source] target = trg_vocab[target] print(source, target)
657
650
# Copyright 2017, OpenCensus 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. import unittest class TestPrintExporter(unittest.TestCase): @staticmethod def _get_target_class(): from opencensus.trace.print_exporter import PrintExporter return PrintExporter def _make_one(self, *args, **kw): return self._get_target_class()(*args, **kw) def test_emit(self): traces = {} exporter = self._make_one() exporter.emit(traces) def test_export(self): exporter = self._make_one(transport=MockTransport) exporter.export({}) self.assertTrue(exporter.transport.export_called) class MockTransport(object): def __init__(self, exporter=None): self.export_called = False self.exporter = exporter def export(self, trace): self.export_called = True
478
3,212
<reponame>westdart/nifi /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.runtime.manifest; import org.apache.nifi.c2.protocol.component.api.BuildInfo; import org.apache.nifi.c2.protocol.component.api.Bundle; import org.apache.nifi.c2.protocol.component.api.RuntimeManifest; import org.apache.nifi.c2.protocol.component.api.SchedulingDefaults; import org.apache.nifi.extension.manifest.ExtensionManifest; /** * Builder for creating a RuntimeManifest. */ public interface RuntimeManifestBuilder { /** * @param identifier the identifier for the manifest * @return the builder */ RuntimeManifestBuilder identifier(String identifier); /** * @param version the version for the manifest * @return the builder */ RuntimeManifestBuilder version(String version); /** * @param runtimeType the runtime type (i.e. nifi, nifi-stateless, minifi-cpp, etc) * @return the builder */ RuntimeManifestBuilder runtimeType(String runtimeType); /** * @param buildInfo the build info for the manifest * @return the builder */ RuntimeManifestBuilder buildInfo(BuildInfo buildInfo); /** * Adds a Bundle from the given ExtensionManifest. * * @param extensionManifest the extension manifest to add * @return the builder */ RuntimeManifestBuilder addBundle(ExtensionManifest extensionManifest); /** * Adds a Bundle for each of the given ExtensionManifests. * * @param extensionManifests the extension manifests to add * @return the builder */ RuntimeManifestBuilder addBundles(Iterable<ExtensionManifest> extensionManifests); /** * Adds the given Bundle. * * @param bundle the bundle to add * @return the builder */ RuntimeManifestBuilder addBundle(Bundle bundle); /** * @param schedulingDefaults the scheduling defaults * @return the builder */ RuntimeManifestBuilder schedulingDefaults(SchedulingDefaults schedulingDefaults); /** * @return a RuntimeManifest containing the added bundles */ RuntimeManifest build(); }
903
1,508
<reponame>bpmbank/XChange package org.knowm.xchange.ascendex; import org.knowm.xchange.BaseExchange; import org.knowm.xchange.Exchange; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.ascendex.service.AscendexAccountService; import org.knowm.xchange.ascendex.service.AscendexMarketDataService; import org.knowm.xchange.ascendex.service.AscendexMarketDataServiceRaw; import org.knowm.xchange.ascendex.service.AscendexTradeService; import org.knowm.xchange.exceptions.ExchangeException; import java.io.IOException; /** * @author makarid */ public class AscendexExchange extends BaseExchange implements Exchange { @Override protected void initServices() { this.marketDataService = new AscendexMarketDataService(this); this.accountService = new AscendexAccountService(this); this.tradeService = new AscendexTradeService(this); } @Override public ExchangeSpecification getDefaultExchangeSpecification() { ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass()); exchangeSpecification.setSslUri("https://ascendex.com/"); exchangeSpecification.setExchangeName("Ascendex"); exchangeSpecification.setExchangeDescription( "Ascendex is a Bitcoin exchange with spot and future markets."); return exchangeSpecification; } @Override public void remoteInit() throws IOException, ExchangeException { AscendexMarketDataServiceRaw raw = ((AscendexMarketDataServiceRaw) getMarketDataService()); exchangeMetaData = AscendexAdapters.adaptExchangeMetaData(raw.getAllAssets(), raw.getAllProducts()); } }
506
347
<filename>backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/HostNetworkTopologyPersister.java package org.ovirt.engine.core.vdsbroker.vdsbroker; import org.ovirt.engine.core.common.businessentities.NonOperationalReason; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.vdscommands.UserConfiguredNetworkData; public interface HostNetworkTopologyPersister { /** * Persist this host network topology to DB. Set the host to non-operational in case its networks don't comply with * the cluster rules: * <ul> * <li>All mandatory networks(optional=false) should be implemented by the host.</li> * <li>All VM networks must be implemented with bridges.</li> * </ul> * * @param skipManagementNetwork * if <code>true</code> skip validations for the management network (existence on the host or configured * properly) * @param userConfiguredNetworkData * The network configuration as provided by the user, for which engine managed data will be preserved. * @return The reason for non-operability of the host or <code>NonOperationalReason.NONE</code> */ NonOperationalReason persistAndEnforceNetworkCompliance(VDS host, boolean skipManagementNetwork, UserConfiguredNetworkData userConfiguredNetworkData); NonOperationalReason persistAndEnforceNetworkCompliance(VDS host); }
503
3,336
{ "Get-AzContainerInstanceUsage+[NoContext]+List+$GET+https://management.azure.com/subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/providers/Microsoft.ContainerInstance/locations/eastus/usages?api-version=2021-09-01+1": { "Request": { "Method": "GET", "RequestUri": "https://management.azure.com/subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/providers/Microsoft.ContainerInstance/locations/eastus/usages?api-version=2021-09-01", "Content": null, "isContentBase64": false, "Headers": { "x-ms-unique-id": [ "21" ], "x-ms-client-request-id": [ "6f860017-b50b-433b-be99-8d6067bb5c56" ], "CommandName": [ "Get-AzContainerInstanceUsage" ], "FullCommandName": [ "Get-AzContainerInstanceUsage_List" ], "ParameterSetName": [ "__AllParameterSets" ], "User-Agent": [ "AzurePowershell/v0.0.0" ], "Authorization": [ "[Filtered]" ] }, "ContentHeaders": { } }, "Response": { "StatusCode": 200, "Headers": { "Cache-Control": [ "no-cache" ], "Pragma": [ "no-cache" ], "Vary": [ "Accept-Encoding" ], "x-ms-request-id": [ "eastus:7225ff88-caaf-4d67-b1fa-c07a2bbc4bab" ], "x-ms-ratelimit-remaining-subscription-reads": [ "11985" ], "x-ms-correlation-request-id": [ "68aa65b1-89ec-495b-9e11-51855ce22c08" ], "x-ms-routing-request-id": [ "SOUTHEASTASIA:20211109T085616Z:68aa65b1-89ec-495b-9e11-51855ce22c08" ], "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], "X-Content-Type-Options": [ "nosniff" ], "Date": [ "Tue, 09 Nov 2021 08:56:16 GMT" ] }, "ContentHeaders": { "Content-Length": [ "1807" ], "Content-Type": [ "application/json; charset=utf-8" ], "Expires": [ "-1" ] }, "Content": "{\"value\":[{\"id\":\"/subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/providers/Microsoft.ContainerInstance/locations/eastus/usages/ContainerGroups\",\"unit\":\"Count\",\"currentValue\":4,\"limit\":100,\"name\":{\"value\":\"ContainerGroups\",\"localizedValue\":\"Container Groups\"}},{\"id\":\"/subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/providers/Microsoft.ContainerInstance/locations/eastus/usages/standardCores\",\"unit\":\"Count\",\"currentValue\":4,\"limit\":400,\"name\":{\"value\":\"StandardCores\",\"localizedValue\":\"Container Groups\"}},{\"id\":\"/subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/providers/Microsoft.ContainerInstance/locations/eastus/usages/standardK80Cores\",\"unit\":\"Count\",\"currentValue\":0,\"limit\":400,\"name\":{\"value\":\"StandardK80Cores\",\"localizedValue\":\"Container Groups\"}},{\"id\":\"/subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/providers/Microsoft.ContainerInstance/locations/eastus/usages/standardP100Cores\",\"unit\":\"Count\",\"currentValue\":0,\"limit\":400,\"name\":{\"value\":\"StandardP100Cores\",\"localizedValue\":\"Container Groups\"}},{\"id\":\"/subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/providers/Microsoft.ContainerInstance/locations/eastus/usages/standardV100Cores\",\"unit\":\"Count\",\"currentValue\":0,\"limit\":400,\"name\":{\"value\":\"StandardV100Cores\",\"localizedValue\":\"Container Groups\"}},{\"id\":\"/subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/providers/Microsoft.ContainerInstance/locations/eastus/usages/DedicatedContainerGroups\",\"unit\":\"Count\",\"currentValue\":0,\"limit\":0,\"name\":{\"value\":\"DedicatedContainerGroups\",\"localizedValue\":\"Container Groups\"}},{\"id\":\"/subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/providers/Microsoft.ContainerInstance/locations/eastus/usages/dedicatedCores\",\"unit\":\"Count\",\"currentValue\":0,\"limit\":0,\"name\":{\"value\":\"DedicatedCores\",\"localizedValue\":\"Container Groups\"}}]}", "isContentBase64": false } } }
1,629
1,141
/* * predixy - A high performance and full features proxy for redis. * Copyright (C) 2017 Joyield, Inc. <<EMAIL>> * All rights reserved. */ #ifndef _PREDIXY_EPOLL_MULTIPLEXOR_H_ #define _PREDIXY_EPOLL_MULTIPLEXOR_H_ #include <unistd.h> #include <sys/epoll.h> #include "Multiplexor.h" #include "Exception.h" #include "Util.h" class EpollMultiplexor : public MultiplexorBase { public: DefException(EpollCreateFail); DefException(EpollWaitFail); public: EpollMultiplexor(); ~EpollMultiplexor(); bool addSocket(Socket* s, int evts = ReadEvent); void delSocket(Socket* s); bool addEvent(Socket* s, int evts); bool delEvent(Socket* s, int evts); template<class T> int wait(long usec, T* handler); private: int mFd; static const int MaxEvents = 1024; epoll_event mEvents[MaxEvents]; }; template<class T> int EpollMultiplexor::wait(long usec, T* handler) { int timeout = usec < 0 ? usec : usec / 1000; logVerb("epoll wait with timeout %ld usec", usec); int num = epoll_wait(mFd, mEvents, MaxEvents, timeout); logVerb("epoll wait return with event count:%d", num); if (num == -1) { if (errno == EINTR) { return 0; } Throw(EpollWaitFail, "handler %d epoll wait fail %s", handler->id(), StrError()); } for (int i = 0; i < num; ++i) { Socket* s = static_cast<Socket*>(mEvents[i].data.ptr); int evts = 0; evts |= (mEvents[i].events & EPOLLIN) ? ReadEvent : 0; evts |= (mEvents[i].events & EPOLLOUT) ? WriteEvent : 0; evts |= (mEvents[i].events & (EPOLLERR|EPOLLHUP)) ? ErrorEvent : 0; handler->handleEvent(s, evts); } return num; } typedef EpollMultiplexor Multiplexor; #define _MULTIPLEXOR_ASYNC_ASSIGN_ #endif
767
14,668
<reponame>zealoussnow/chromium<filename>chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabLaunchCauseMetrics.java<gh_stars>1000+ // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.customtabs; import org.chromium.chrome.browser.app.metrics.LaunchCauseMetrics; import org.chromium.chrome.browser.flags.ActivityType; /** * LaunchCauseMetrics for CustomTabActivity. */ public class CustomTabLaunchCauseMetrics extends LaunchCauseMetrics { private final CustomTabActivity mActivity; public CustomTabLaunchCauseMetrics(CustomTabActivity activity) { super(activity); mActivity = activity; } @Override public @LaunchCause int computeIntentLaunchCause() { if (mActivity.getActivityType() == ActivityType.TRUSTED_WEB_ACTIVITY) { return LaunchCause.TWA; } assert mActivity.getActivityType() == ActivityType.CUSTOM_TAB; return LaunchCause.CUSTOM_TAB; } }
374
1,136
<reponame>bradebarrows/Github.swift { "login": "octokit-testing-user", "id": 1, "url": "https://api.github.com/users/octokit-testing-user", "html_url": "https://github.com/octokit-testing-user", "followers_url": "https://api.github.com/users/octokit-testing-user/followers", "following_url": "https://api.github.com/users/octokit-testing-user/following{/other_user}", "gists_url": "https://api.github.com/users/octokit-testing-user/gists{/gist_id}", "starred_url": "https://api.github.com/users/octokit-testing-user/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octokit-testing-user/subscriptions", "organizations_url": "https://api.github.com/users/octokit-testing-user/orgs", "repos_url": "https://api.github.com/users/octokit-testing-user/repos", "events_url": "https://api.github.com/users/octokit-testing-user/events{/privacy}", "received_events_url": "https://api.github.com/users/octokit-testing-user/received_events", "type": "User", "name": "<NAME>", "bio": "" }
409
12,278
<filename>3rdParty/V8/v7.9.317/third_party/icu/fuzzers/icu_number_format_fuzzer.cc<gh_stars>1000+ // Copyright 2016 The Chromium Authors. All rights reserved. // Fuzzer for NumberFormat::parse. #include <stddef.h> #include <stdint.h> #include <memory> #include "third_party/icu/fuzzers/fuzzer_utils.h" #include "third_party/icu/source/i18n/unicode/numfmt.h" IcuEnvironment* env = new IcuEnvironment(); // Entry point for LibFuzzer. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { UErrorCode status = U_ZERO_ERROR; auto rng = CreateRng(data, size); const icu::Locale& locale = GetRandomLocale(&rng); std::unique_ptr<icu::NumberFormat> fmt( icu::NumberFormat::createInstance(locale, status)); if (U_FAILURE(status)) return 0; icu::UnicodeString str(UnicodeStringFromUtf8(data, size)); icu::Formattable result; fmt->parse(str, result, status); return 0; }
353
14,668
<gh_stars>1000+ // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_FRAGMENT_DATA_ITERATOR_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_FRAGMENT_DATA_ITERATOR_H_ #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.h" namespace blink { class LayoutBox; class LayoutObject; class NGPhysicalBoxFragment; // FragmentData iterator, accompanied by "corresponding" NG layout structures. // For LayoutBox, this means NGPhysicalBoxFragment. For non-atomic inlines, it // means NGInlineCursor. class FragmentDataIterator { STACK_ALLOCATED(); public: explicit FragmentDataIterator(const LayoutObject&); const NGInlineCursor* Cursor() { return cursor_ ? &(*cursor_) : nullptr; } const FragmentData* GetFragmentData() const { return fragment_data_; } const NGPhysicalBoxFragment* GetPhysicalBoxFragment() const; // Advance the iterator. For LayoutBox fragments this also means that we're // going to advance to the next fragmentainer, and thereby the next // FragmentData entry. For non-atomic inlines, though, there may be multiple // fragment items (because there are multiple lines inside the same // fragmentainer, for instance). bool Advance(); bool IsDone() const { return !fragment_data_; } private: absl::optional<NGInlineCursor> cursor_; const LayoutBox* ng_layout_box_ = nullptr; const FragmentData* fragment_data_; wtf_size_t box_fragment_index_ = 0u; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_FRAGMENT_DATA_ITERATOR_H_
564
348
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2021. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: <NAME> $ // $Authors: <NAME>, <NAME> $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/IONMOBILITY/IMDataConverter.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/MzMLFile.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(IMDataConverter, "$Id$") ///////////////////////////////////////////////////////////// IMDataConverter* e_ptr = nullptr; IMDataConverter* e_nullPointer = nullptr; START_SECTION((IMDataConverter())) e_ptr = new IMDataConverter; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION((~IMDataConverter())) delete e_ptr; END_SECTION START_SECTION((std::vector<PeakMap> splitByFAIMSCV(PeakMap& exp))) MzMLFile IM_file; PeakMap exp; IM_file.load(OPENMS_GET_TEST_DATA_PATH("IM_FAIMS_test.mzML"), exp); TEST_EQUAL(exp.getSpectra().size(), 19) vector<PeakMap> splitPeakMap = IMDataConverter::splitByFAIMSCV(std::move(exp)); TEST_EQUAL(splitPeakMap.size(), 3) TEST_EQUAL(splitPeakMap[0].size(), 4) TEST_EQUAL(splitPeakMap[1].size(), 9) TEST_EQUAL(splitPeakMap[2].size(), 6) for (PeakMap::Iterator it = splitPeakMap[0].begin(); it != splitPeakMap[0].end(); ++it) { TEST_EQUAL(it->getDriftTime(), -65.0) } for (PeakMap::Iterator it = splitPeakMap[1].begin(); it != splitPeakMap[1].end(); ++it) { TEST_EQUAL(it->getDriftTime(), -55.0) } for (PeakMap::Iterator it = splitPeakMap[2].begin(); it != splitPeakMap[2].end(); ++it) { TEST_EQUAL(it->getDriftTime(), -45.0) } TEST_EQUAL(splitPeakMap[1].getExperimentalSettings().getDateTime().toString(), "2019-09-07T09:40:04") END_SECTION START_SECTION(static void setIMUnit(DataArrays::FloatDataArray& fda, const DriftTimeUnit unit)) MSSpectrum::FloatDataArray fda; TEST_EXCEPTION(Exception::InvalidValue, IMDataConverter::setIMUnit(fda, DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE)) TEST_EXCEPTION(Exception::InvalidValue, IMDataConverter::setIMUnit(fda, DriftTimeUnit::NONE)) DriftTimeUnit unit; IMDataConverter::setIMUnit(fda, DriftTimeUnit::MILLISECOND); TEST_EQUAL(IMDataConverter::getIMUnit(fda, unit), true) TEST_EQUAL(DriftTimeUnit::MILLISECOND == unit, true) IMDataConverter::setIMUnit(fda, DriftTimeUnit::VSSC); TEST_EQUAL(IMDataConverter::getIMUnit(fda, unit), true) TEST_EQUAL(DriftTimeUnit::VSSC == unit, true) END_SECTION START_SECTION(static bool getIMUnit(const DataArrays::FloatDataArray& fda, DriftTimeUnit& unit)) NOT_TESTABLE // tested above END_SECTION MSSpectrum frame; frame.push_back({1.0, 29.0f}); frame.push_back({2.0, 60.0f}); frame.push_back({3.0, 34.0f}); frame.push_back({4.0, 29.0f}); frame.push_back({5.0, 37.0f}); frame.push_back({6.0, 31.0f}); frame.setRT(1); MSSpectrum::FloatDataArray& afa = frame.getFloatDataArrays().emplace_back(); afa.assign({1.1, 2.2, 3.3, 3.3, 5.5, 6.6}); IMDataConverter::setIMUnit(afa, DriftTimeUnit::MILLISECOND); MSSpectrum spec; spec.push_back({111.0, -1.0f}); spec.push_back({222.0, -2.0f}); spec.push_back({333.0, -3.0f}); spec.setRT(2); // just a spectrum with RT = 2 START_SECTION(static MSExperiment splitByIonMobility(MSSpectrum im_frame, UInt number_of_bins = -1)) TEST_EXCEPTION(Exception::MissingInformation, IMDataConverter::splitByIonMobility(spec)) { auto exp = IMDataConverter::splitByIonMobility(frame); TEST_EQUAL(exp.size(), 5); TEST_EQUAL(exp[0].size(), 1); TEST_EQUAL(exp[2].size(), 2); TEST_EQUAL(exp[0][0].getIntensity(), 29.0f); TEST_EQUAL(exp[0].getDriftTime(), 1.1f); TEST_EQUAL(exp[0].getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true); TEST_EQUAL(exp[0].getRT(), 1); auto frame_reconstruct = IMDataConverter::collapseFramesToSingle(exp); TEST_EQUAL(frame_reconstruct.size(), 1) TEST_EQUAL(frame_reconstruct[0], frame); } { auto exp_binned = IMDataConverter::splitByIonMobility(frame, 1); TEST_EQUAL(exp_binned.size(), 1); TEST_EQUAL(exp_binned[0].size(), frame.size()); TEST_EQUAL(exp_binned[0][0].getIntensity(), 29.0f); TEST_REAL_SIMILAR(exp_binned[0].getDriftTime(), (6.6-1.1)/2 + 1.1); TEST_EQUAL(exp_binned[0].getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true); TEST_EQUAL(exp_binned[0].getRT(), 1); } END_SECTION START_SECTION(static MSExperiment splitByIonMobility(MSExperiment&& in, UInt number_of_bins = -1)) MSExperiment e_in; e_in.addSpectrum(frame); e_in.addSpectrum(spec); // just copy it... auto frame3 = frame; frame3.setRT(3); e_in.addSpectrum(frame3); auto exp = IMDataConverter::splitByIonMobility(std::move(e_in)); TEST_EQUAL(exp.size(), 5+1+5); TEST_EQUAL(exp[0].size(), 1); TEST_EQUAL(exp[2].size(), 2); TEST_EQUAL(exp[0][0].getIntensity(), 29.0f); TEST_EQUAL(exp[0].getDriftTime(), 1.1f); TEST_EQUAL(exp[0].getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true); TEST_EQUAL(exp[0].getRT(), 1); TEST_EQUAL(exp[5], spec); // copied TEST_EQUAL(exp[6].getRT(), 3); auto frame_reconstruct = IMDataConverter::collapseFramesToSingle(exp); TEST_EQUAL(frame_reconstruct.size(), 3) TEST_EQUAL(frame_reconstruct[0] == frame, true); TEST_EQUAL(frame_reconstruct[1] == spec, true); TEST_EQUAL(frame_reconstruct[2] == frame3, true); END_SECTION START_SECTION(static MSExperiment collapseFramesToSingle(const MSExperiment& in)) NOT_TESTABLE // tested_above END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
2,805
1,297
/* * Copyright 2016 - 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package de.mrapp.android.tabswitcher.model; /** * Contains all possible states of a tab, while the switcher is shown. * * @author <NAME> * @since 0.1.0 */ public enum State { /** * When the tab is part of the stack, which is located at the start of the switcher. */ STACKED_START, /** * When the tab is displayed atop of the stack, which is located at the start of the switcher. */ STACKED_START_ATOP, /** * When the tab is floating and freely movable. */ FLOATING, /** * When the tab is part of the stack, which is located at the end of the switcher. */ STACKED_END, /** * When the tab is currently not visible, i.e. if no view is inflated to visualize it. */ HIDDEN }
437
1,825
package com.github.unidbg.linux.android.dvm; import com.github.unidbg.Emulator; import java.nio.ByteBuffer; import java.nio.ByteOrder; class ArmVarArg32 extends ArmVarArg { ArmVarArg32(Emulator<?> emulator, BaseVM vm, DvmMethod method) { super(emulator, vm, method); int offset = 0; for (Shorty shorty : shorties) { switch (shorty.getType()) { case 'L': case 'B': case 'C': case 'I': case 'S': case 'Z': { args.add(getInt(offset++)); break; } case 'D': { if (offset % 2 == 0) { offset++; } ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(getInt(offset++)); buffer.putInt(getInt(offset++)); buffer.flip(); args.add(buffer.getDouble()); break; } case 'F': { if (offset % 2 == 0) { offset++; } ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(getInt(offset++)); buffer.putInt(getInt(offset++)); buffer.flip(); args.add((float) buffer.getDouble()); break; } case 'J': { if (offset % 2 == 0) { offset++; } ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(getInt(offset++)); buffer.putInt(getInt(offset++)); buffer.flip(); args.add(buffer.getLong()); break; } default: throw new IllegalStateException("c=" + shorty.getType()); } } } }
1,388
306
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QFAppDispatcher> #include <QuickFlux> int main(int argc, char *argv[]) { qputenv("QML_DISABLE_DISK_CACHE", "true"); QGuiApplication app(argc, argv); registerQuickFluxQmlTypes(); // It is not necessary to call this function if the QuickFlux library is installed via qpm QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); QFAppDispatcher* dispatcher = QFAppDispatcher::instance(&engine); dispatcher->dispatch("startApp"); return app.exec(); }
211
14,668
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/css/media_feature_overrides.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { TEST(MediaFeatureOverrides, GetOverrideInitial) { MediaFeatureOverrides overrides; EXPECT_FALSE(overrides.GetOverride("unknown").IsValid()); EXPECT_FALSE(overrides.GetOverride("prefers-color-scheme").IsValid()); EXPECT_FALSE(overrides.GetOverride("display-mode").IsValid()); } TEST(MediaFeatureOverrides, SetOverrideInvalid) { MediaFeatureOverrides overrides; overrides.SetOverride("prefers-color-scheme", "1px"); EXPECT_FALSE(overrides.GetOverride("prefers-color-scheme").IsValid()); overrides.SetOverride("prefers-color-scheme", "orange"); EXPECT_FALSE(overrides.GetOverride("prefers-color-scheme").IsValid()); } TEST(MediaFeatureOverrides, SetOverrideValid) { MediaFeatureOverrides overrides; overrides.SetOverride("prefers-color-scheme", "light"); auto light_override = overrides.GetOverride("prefers-color-scheme"); EXPECT_TRUE(light_override.IsValid()); ASSERT_TRUE(light_override.IsId()); EXPECT_EQ(CSSValueID::kLight, light_override.Id()); overrides.SetOverride("prefers-color-scheme", "dark"); auto dark_override = overrides.GetOverride("prefers-color-scheme"); ASSERT_TRUE(dark_override.IsValid()); EXPECT_TRUE(dark_override.IsId()); EXPECT_EQ(CSSValueID::kDark, dark_override.Id()); } TEST(MediaFeatureOverrides, ResetOverride) { MediaFeatureOverrides overrides; overrides.SetOverride("prefers-color-scheme", "light"); EXPECT_TRUE(overrides.GetOverride("prefers-color-scheme").IsValid()); overrides.SetOverride("prefers-color-scheme", ""); EXPECT_FALSE(overrides.GetOverride("prefers-color-scheme").IsValid()); overrides.SetOverride("prefers-color-scheme", "light"); EXPECT_TRUE(overrides.GetOverride("prefers-color-scheme").IsValid()); overrides.SetOverride("prefers-color-scheme", "invalid"); EXPECT_FALSE(overrides.GetOverride("prefers-color-scheme").IsValid()); } } // namespace blink
760
14,668
<reponame>zealoussnow/chromium<gh_stars>1000+ // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/allocator/partition_allocator/starscan/stack/stack.h" #include <memory> #include <ostream> #include "base/compiler_specific.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #if !defined(MEMORY_TOOL_REPLACES_ALLOCATOR) #if defined(OS_LINUX) && (defined(ARCH_CPU_X86) || defined(ARCH_CPU_X86_64)) #include <xmmintrin.h> #endif namespace base { namespace internal { namespace { class PartitionAllocStackTest : public ::testing::Test { protected: PartitionAllocStackTest() : stack_(std::make_unique<Stack>(GetStackTop())) {} Stack* GetStack() const { return stack_.get(); } private: std::unique_ptr<Stack> stack_; }; class StackScanner final : public StackVisitor { public: struct Container { std::unique_ptr<int> value; }; StackScanner() : container_(std::make_unique<Container>()) { container_->value = std::make_unique<int>(); } void VisitStack(uintptr_t* stack_ptr, uintptr_t* stack_top) final { for (; stack_ptr != stack_top; ++stack_ptr) { if (*stack_ptr == reinterpret_cast<uintptr_t>(container_->value.get())) found_ = true; } } void Reset() { found_ = false; } bool found() const { return found_; } int* needle() const { return container_->value.get(); } private: std::unique_ptr<Container> container_; bool found_ = false; }; } // namespace TEST_F(PartitionAllocStackTest, IteratePointersFindsOnStackValue) { auto scanner = std::make_unique<StackScanner>(); // No check that the needle is initially not found as on some platforms it // may be part of temporaries after setting it up through StackScanner. { int* volatile tmp = scanner->needle(); ALLOW_UNUSED_LOCAL(tmp); GetStack()->IteratePointers(scanner.get()); EXPECT_TRUE(scanner->found()); } } TEST_F(PartitionAllocStackTest, IteratePointersFindsOnStackValuePotentiallyUnaligned) { auto scanner = std::make_unique<StackScanner>(); // No check that the needle is initially not found as on some platforms it // may be part of temporaries after setting it up through StackScanner. { char a = 'c'; ALLOW_UNUSED_LOCAL(a); int* volatile tmp = scanner->needle(); ALLOW_UNUSED_LOCAL(tmp); GetStack()->IteratePointers(scanner.get()); EXPECT_TRUE(scanner->found()); } } namespace { // Prevent inlining as that would allow the compiler to prove that the parameter // must not actually be materialized. // // Parameter positiosn are explicit to test various calling conventions. NOINLINE void* RecursivelyPassOnParameterImpl(void* p1, void* p2, void* p3, void* p4, void* p5, void* p6, void* p7, void* p8, Stack* stack, StackVisitor* visitor) { if (p1) { return RecursivelyPassOnParameterImpl(nullptr, p1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, stack, visitor); } else if (p2) { return RecursivelyPassOnParameterImpl(nullptr, nullptr, p2, nullptr, nullptr, nullptr, nullptr, nullptr, stack, visitor); } else if (p3) { return RecursivelyPassOnParameterImpl(nullptr, nullptr, nullptr, p3, nullptr, nullptr, nullptr, nullptr, stack, visitor); } else if (p4) { return RecursivelyPassOnParameterImpl(nullptr, nullptr, nullptr, nullptr, p4, nullptr, nullptr, nullptr, stack, visitor); } else if (p5) { return RecursivelyPassOnParameterImpl(nullptr, nullptr, nullptr, nullptr, nullptr, p5, nullptr, nullptr, stack, visitor); } else if (p6) { return RecursivelyPassOnParameterImpl(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, p6, nullptr, stack, visitor); } else if (p7) { return RecursivelyPassOnParameterImpl(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, p7, stack, visitor); } else if (p8) { stack->IteratePointers(visitor); return p8; } return nullptr; } NOINLINE void* RecursivelyPassOnParameter(size_t num, void* parameter, Stack* stack, StackVisitor* visitor) { switch (num) { case 0: stack->IteratePointers(visitor); return parameter; case 1: return RecursivelyPassOnParameterImpl(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, parameter, stack, visitor); case 2: return RecursivelyPassOnParameterImpl(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, parameter, nullptr, stack, visitor); case 3: return RecursivelyPassOnParameterImpl(nullptr, nullptr, nullptr, nullptr, nullptr, parameter, nullptr, nullptr, stack, visitor); case 4: return RecursivelyPassOnParameterImpl(nullptr, nullptr, nullptr, nullptr, parameter, nullptr, nullptr, nullptr, stack, visitor); case 5: return RecursivelyPassOnParameterImpl(nullptr, nullptr, nullptr, parameter, nullptr, nullptr, nullptr, nullptr, stack, visitor); case 6: return RecursivelyPassOnParameterImpl(nullptr, nullptr, parameter, nullptr, nullptr, nullptr, nullptr, nullptr, stack, visitor); case 7: return RecursivelyPassOnParameterImpl(nullptr, parameter, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, stack, visitor); case 8: return RecursivelyPassOnParameterImpl(parameter, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, stack, visitor); default: __builtin_unreachable(); } __builtin_unreachable(); } } // namespace TEST_F(PartitionAllocStackTest, IteratePointersFindsParameterNesting0) { auto scanner = std::make_unique<StackScanner>(); void* needle = RecursivelyPassOnParameter(0, scanner->needle(), GetStack(), scanner.get()); EXPECT_EQ(scanner->needle(), needle); EXPECT_TRUE(scanner->found()); } TEST_F(PartitionAllocStackTest, IteratePointersFindsParameterNesting1) { auto scanner = std::make_unique<StackScanner>(); void* needle = RecursivelyPassOnParameter(1, scanner->needle(), GetStack(), scanner.get()); EXPECT_EQ(scanner->needle(), needle); EXPECT_TRUE(scanner->found()); } TEST_F(PartitionAllocStackTest, IteratePointersFindsParameterNesting2) { auto scanner = std::make_unique<StackScanner>(); void* needle = RecursivelyPassOnParameter(2, scanner->needle(), GetStack(), scanner.get()); EXPECT_EQ(scanner->needle(), needle); EXPECT_TRUE(scanner->found()); } TEST_F(PartitionAllocStackTest, IteratePointersFindsParameterNesting3) { auto scanner = std::make_unique<StackScanner>(); void* needle = RecursivelyPassOnParameter(3, scanner->needle(), GetStack(), scanner.get()); EXPECT_EQ(scanner->needle(), needle); EXPECT_TRUE(scanner->found()); } TEST_F(PartitionAllocStackTest, IteratePointersFindsParameterNesting4) { auto scanner = std::make_unique<StackScanner>(); void* needle = RecursivelyPassOnParameter(4, scanner->needle(), GetStack(), scanner.get()); EXPECT_EQ(scanner->needle(), needle); EXPECT_TRUE(scanner->found()); } TEST_F(PartitionAllocStackTest, IteratePointersFindsParameterNesting5) { auto scanner = std::make_unique<StackScanner>(); void* needle = RecursivelyPassOnParameter(5, scanner->needle(), GetStack(), scanner.get()); EXPECT_EQ(scanner->needle(), needle); EXPECT_TRUE(scanner->found()); } TEST_F(PartitionAllocStackTest, IteratePointersFindsParameterNesting6) { auto scanner = std::make_unique<StackScanner>(); void* needle = RecursivelyPassOnParameter(6, scanner->needle(), GetStack(), scanner.get()); EXPECT_EQ(scanner->needle(), needle); EXPECT_TRUE(scanner->found()); } TEST_F(PartitionAllocStackTest, IteratePointersFindsParameterNesting7) { auto scanner = std::make_unique<StackScanner>(); void* needle = RecursivelyPassOnParameter(7, scanner->needle(), GetStack(), scanner.get()); EXPECT_EQ(scanner->needle(), needle); EXPECT_TRUE(scanner->found()); } TEST_F(PartitionAllocStackTest, IteratePointersFindsParameterNesting8) { auto scanner = std::make_unique<StackScanner>(); void* needle = RecursivelyPassOnParameter(8, scanner->needle(), GetStack(), scanner.get()); EXPECT_EQ(scanner->needle(), needle); EXPECT_TRUE(scanner->found()); } // The following test uses inline assembly and has been checked to work on clang // to verify that the stack-scanning trampoline pushes callee-saved registers. // // The test uses a macro loop as asm() can only be passed string literals. #if defined(__clang__) && defined(ARCH_CPU_X86_64) && !defined(OS_WIN) // Excluded from test: rbp #define FOR_ALL_CALLEE_SAVED_REGS(V) \ V("rbx") \ V("r12") \ V("r13") \ V("r14") \ V("r15") namespace { extern "C" void IteratePointersNoMangling(Stack* stack, StackVisitor* visitor) { stack->IteratePointers(visitor); } } // namespace TEST_F(PartitionAllocStackTest, IteratePointersFindsCalleeSavedRegisters) { auto scanner = std::make_unique<StackScanner>(); // No check that the needle is initially not found as on some platforms it // may be part of temporaries after setting it up through StackScanner. // First, clear all callee-saved registers. #define CLEAR_REGISTER(reg) asm("mov $0, %%" reg : : : reg); FOR_ALL_CALLEE_SAVED_REGS(CLEAR_REGISTER) #undef CLEAR_REGISTER // Keep local raw pointers to keep instruction sequences small below. auto* local_stack = GetStack(); auto* local_scanner = scanner.get(); // Moves |local_scanner->needle()| into a callee-saved register, leaving the // callee-saved register as the only register referencing the needle. // (Ignoring implementation-dependent dirty registers/stack.) #define KEEP_ALIVE_FROM_CALLEE_SAVED(reg) \ local_scanner->Reset(); \ [local_stack, local_scanner]() NOINLINE { \ asm volatile(" mov %0, %%" reg \ "\n mov %1, %%rdi" \ "\n mov %2, %%rsi" \ "\n call %P3" \ "\n mov $0, %%" reg \ : \ : "r"(local_scanner->needle()), "r"(local_stack), \ "r"(local_scanner), "i"(IteratePointersNoMangling) \ : "memory", reg, "rdi", "rsi", "cc"); \ }(); \ EXPECT_TRUE(local_scanner->found()) \ << "pointer in callee-saved register not found. register: " << reg \ << std::endl; FOR_ALL_CALLEE_SAVED_REGS(KEEP_ALIVE_FROM_CALLEE_SAVED) #undef KEEP_ALIVE_FROM_CALLEE_SAVED #undef FOR_ALL_CALLEE_SAVED_REGS } #endif // defined(__clang__) && defined(ARCH_CPU_X86_64) && !defined(OS_WIN) #if defined(OS_LINUX) && (defined(ARCH_CPU_X86) || defined(ARCH_CPU_X86_64)) class CheckStackAlignmentVisitor final : public StackVisitor { public: void VisitStack(uintptr_t*, uintptr_t*) final { // Check that the stack doesn't get misaligned by asm trampolines. float f[4] = {0.}; volatile auto xmm = ::_mm_load_ps(f); ALLOW_UNUSED_LOCAL(xmm); } }; TEST_F(PartitionAllocStackTest, StackAlignment) { auto checker = std::make_unique<CheckStackAlignmentVisitor>(); GetStack()->IteratePointers(checker.get()); } #endif // defined(OS_LINUX) && (defined(ARCH_CPU_X86) || // defined(ARCH_CPU_X86_64)) } // namespace internal } // namespace base #endif // !defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
6,842
1,428
<reponame>kennethsequeira/Hello-world<filename>Python/OptimalBST.py<gh_stars>1000+ ###### O(N^3) ###### from itertools import accumulate def dp(a,acc,n): cost = [[float('inf')]*n for i in range(n)] st = [[0]*n for i in range(n)] for i in range(n): cost[i][i] = a[i][1] for l in range(2,n+1): for i in range(n-l+1): j = i+l-1 for r in range(i,j+1): if i!=0: c = (lambda r:cost[i][r-1] if r>i else 0)(r) + (lambda r:cost[r+1][j] if r<j else 0)(r) + acc[j] - acc[i-1] else: c = (lambda r: cost[i][r - 1] if r > i else 0)(r) + (lambda r: cost[r + 1][j] if r < j else 0)(r) + acc[j] if c<cost[i][j]: cost[i][j]=c st[i][j]=r ans = [] prStruct(a,0,n-1,st,ans) return ans #return cost[0][n-1] def prStruct(a,i,j,st,ans): if j<i: return elif i==j: ans.append(a[i][0]) return else: ans.append(a[st[i][j]][0]) prStruct(a,i,st[i][j]-1,st,ans) prStruct(a,st[i][j]+1,j,st,ans) keys = [12, 20, 10, 22] wt = [34, 30, 50, 5] n=4 a = list(sorted(zip(keys,wt),key=lambda x:x[0])) acc = list(accumulate([i[1] for i in a])) ans = dp(a,acc,4) print(*ans)
777
14,668
<filename>third_party/blink/renderer/core/mathml/mathml_radical_element.h // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_MATHML_MATHML_RADICAL_ELEMENT_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_MATHML_MATHML_RADICAL_ELEMENT_H_ #include "third_party/blink/renderer/core/mathml/mathml_row_element.h" namespace blink { class Document; class CORE_EXPORT MathMLRadicalElement : public MathMLRowElement { public: MathMLRadicalElement(const QualifiedName&, Document&); bool HasIndex() const; private: LayoutObject* CreateLayoutObject(const ComputedStyle&, LegacyLayout legacy) override; bool IsGroupingElement() const final { return false; } }; template <> inline bool IsElementOfType<const MathMLRadicalElement>(const Node& node) { return IsA<MathMLRadicalElement>(node); } template <> struct DowncastTraits<MathMLRadicalElement> { static bool AllowFrom(const Node& node) { auto* mathml_element = DynamicTo<MathMLElement>(node); return mathml_element && AllowFrom(*mathml_element); } static bool AllowFrom(const MathMLElement& mathml_element) { return mathml_element.HasTagName(mathml_names::kMsqrtTag) || mathml_element.HasTagName(mathml_names::kMrootTag); } }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_MATHML_MATHML_RADICAL_ELEMENT_H_
554
2,372
<filename>physx/source/physx/src/device/windows/PhysXIndicatorWindows.cpp<gh_stars>1000+ // // 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 NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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. // // Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "PhysXIndicator.h" #include "nvPhysXtoDrv.h" #pragma warning (push) #pragma warning (disable : 4668) //'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives' #include <windows.h> #pragma warning (pop) #include <stdio.h> #if _MSC_VER >= 1800 #include <VersionHelpers.h> #endif // Scope-based to indicate to NV driver that CPU PhysX is happening physx::PhysXIndicator::PhysXIndicator(bool isGpu) : mPhysXDataPtr(0), mFileHandle(0), mIsGpu(isGpu) { // Get the windows version (we can only create Global\\ namespace objects in XP) /** Operating system Version number ---------------- -------------- Windows 7 6.1 Windows Server 2008 R2 6.1 Windows Server 2008 6.0 Windows Vista 6.0 Windows Server 2003 R2 5.2 Windows Server 2003 5.2 Windows XP 5.1 Windows 2000 5.0 **/ char configName[128]; #if _MSC_VER >= 1800 if (!IsWindowsVistaOrGreater()) #else OSVERSIONINFOEX windowsVersionInfo; windowsVersionInfo.dwOSVersionInfoSize = sizeof (windowsVersionInfo); GetVersionEx((LPOSVERSIONINFO)&windowsVersionInfo); if (windowsVersionInfo.dwMajorVersion < 6) #endif NvPhysXToDrv_Build_SectionNameXP(GetCurrentProcessId(), configName); else NvPhysXToDrv_Build_SectionName(GetCurrentProcessId(), configName); mFileHandle = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(NvPhysXToDrv_Data_V1), configName); if (!mFileHandle || mFileHandle == INVALID_HANDLE_VALUE) return; bool alreadyExists = ERROR_ALREADY_EXISTS == GetLastError(); mPhysXDataPtr = (physx::NvPhysXToDrv_Data_V1*)MapViewOfFile(mFileHandle, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(NvPhysXToDrv_Data_V1)); if(!mPhysXDataPtr) return; if (!alreadyExists) { mPhysXDataPtr->bCpuPhysicsPresent = 0; mPhysXDataPtr->bGpuPhysicsPresent = 0; } updateCounter(1); // init header last to prevent race conditions // this must be done because the driver may have already created the shared memory block, // thus alreadyExists may be true, even if PhysX hasn't been initialized NvPhysXToDrv_Header_Init(mPhysXDataPtr->header); } physx::PhysXIndicator::~PhysXIndicator() { if(mPhysXDataPtr) { updateCounter(-1); UnmapViewOfFile(mPhysXDataPtr); } if(mFileHandle && mFileHandle != INVALID_HANDLE_VALUE) CloseHandle(mFileHandle); } void physx::PhysXIndicator::setIsGpu(bool isGpu) { if(!mPhysXDataPtr) return; updateCounter(-1); mIsGpu = isGpu; updateCounter(1); } PX_INLINE void physx::PhysXIndicator::updateCounter(int delta) { (mIsGpu ? mPhysXDataPtr->bGpuPhysicsPresent : mPhysXDataPtr->bCpuPhysicsPresent) += delta; }
1,521
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.iot.deviceupdate; import com.azure.core.credential.TokenCredential; import com.azure.core.exception.HttpResponseException; import com.azure.core.http.*; import com.azure.core.http.policy.AddHeadersPolicy; import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.http.rest.PagedFlux; import com.azure.core.test.TestBase; import com.azure.core.test.TestMode; import com.azure.identity.ClientSecretCredentialBuilder; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.iot.deviceupdate.models.*; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.*; public class DevicesClientTests extends TestBase { private static final String DEFAULT_SCOPE = "6ee392c4-d339-4083-b04d-6b7947c6cf78/.default"; private DevicesAsyncClient createClient() { TokenCredential credentials; HttpClient httpClient; HttpPipelinePolicy recordingPolicy = null; HttpPipeline httpPipeline; HttpHeaders headers = new HttpHeaders().put("Accept", ContentType.APPLICATION_JSON); AddHeadersPolicy addHeadersPolicy = new AddHeadersPolicy(headers); if (getTestMode() != TestMode.PLAYBACK) { // Record & Live credentials = new ClientSecretCredentialBuilder() .tenantId(TestData.TENANT_ID) .clientId(TestData.CLIENT_ID) .clientSecret(System.getenv("AZURE_CLIENT_SECRET")) .build(); httpClient = HttpClient.createDefault(); if (getTestMode() == TestMode.RECORD) { recordingPolicy = interceptorManager.getRecordPolicy(); } BearerTokenAuthenticationPolicy bearerTokenAuthenticationPolicy = new BearerTokenAuthenticationPolicy(credentials, DEFAULT_SCOPE); // Record & Live httpPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(bearerTokenAuthenticationPolicy, addHeadersPolicy, recordingPolicy) .build(); } else { // Playback credentials = new DefaultAzureCredentialBuilder().build(); httpClient = interceptorManager.getPlaybackClient(); httpPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(addHeadersPolicy) .build(); } return new DeviceUpdateClientBuilder() .accountEndpoint(TestData.ACCOUNT_ENDPOINT) .instanceId(TestData.INSTANCE_ID) .pipeline(httpPipeline) .buildDevicesAsyncClient(); } @Test public void testGetAllDeviceClasses() { DevicesAsyncClient client = createClient(); PagedFlux<DeviceClass> response = client.getAllDeviceClasses(); assertNotNull(response); List<DeviceClass> deviceClasses = new ArrayList<>(); response.byPage().map(page -> deviceClasses.addAll(page.getValue())).blockLast(); assertTrue(deviceClasses.size() > 0); } @Test public void testGetDeviceClass() { DevicesAsyncClient client = createClient(); DeviceClass deviceClass = client.getDeviceClass(TestData.DEVICE_CLASS_ID) .block(); assertNotNull(deviceClass); assertEquals(TestData.PROVIDER, deviceClass.getManufacturer()); assertEquals(TestData.NAME, deviceClass.getModel()); } @Test public void testDeviceClassNotFound() { DevicesAsyncClient client = createClient(); try { client.getDeviceClassWithResponse("foo") .block(); fail("Expected NotFound response"); } catch (HttpResponseException e) { assertEquals(404, e.getResponse().getStatusCode()); } } @Test public void testGetAllDeviceClassIds() { DevicesAsyncClient client = createClient(); PagedFlux<String> response = client.getDeviceClassDeviceIds(TestData.DEVICE_CLASS_ID); assertNotNull(response); List<String> deviceIds = new ArrayList<>(); response.byPage().map(page -> deviceIds.addAll(page.getValue())).blockLast(); assertTrue(deviceIds.size() > 0); } @Test public void testGetAllDeviceClassIdsNotFound() { DevicesAsyncClient client = createClient(); try { PagedFlux<String> response = client.getDeviceClassDeviceIds("foo"); List<String> deviceIds = new ArrayList<>(); response.byPage().map(page -> deviceIds.addAll(page.getValue())).blockLast(); fail("Expected NotFound response"); } catch (HttpResponseException e) { assertEquals(404, e.getResponse().getStatusCode()); } } @Test public void testGetAllDeviceClassInstallableUpdates() { DevicesAsyncClient client = createClient(); PagedFlux<UpdateId> response = client.getDeviceClassInstallableUpdates(TestData.DEVICE_CLASS_ID); assertNotNull(response); List<UpdateId> updateIds = new ArrayList<>(); response.byPage().map(page -> updateIds.addAll(page.getValue())).blockLast(); assertTrue(updateIds.size() > 0); boolean found = false; for (UpdateId updateId : updateIds) { if (updateId.getProvider().equals(TestData.PROVIDER) && updateId.getName().equals(TestData.NAME) && updateId.getVersion().equals(TestData.VERSION)) { found = true; } } assertTrue(found); } @Test public void testGetAllDeviceClassInstallableUpdatesNotFound() { DevicesAsyncClient client = createClient(); try { PagedFlux<UpdateId> response = client.getDeviceClassInstallableUpdates("foo"); List<UpdateId> updateIds = new ArrayList<>(); response.byPage().map(page -> updateIds.addAll(page.getValue())).blockLast(); fail("Expected NotFound response"); } catch (HttpResponseException e) { assertEquals(404, e.getResponse().getStatusCode()); } } @Test public void testGetAllDevices() { DevicesAsyncClient client = createClient(); PagedFlux<Device> response = client.getAllDevices(null); assertNotNull(response); List<Device> devices = new ArrayList<>(); response.byPage().map(page -> devices.addAll(page.getValue())).blockLast(); assertTrue(devices.size() > 0); } @Test public void testGetDevice() { DevicesAsyncClient client = createClient(); Device device = client.getDevice(TestData.DEVICE_ID) .block(); assertNotNull(device); assertEquals(TestData.PROVIDER, device.getManufacturer()); assertEquals(TestData.NAME, device.getModel()); } @Test public void testGetDeviceNotFound() { DevicesAsyncClient client = createClient(); try { client.getDevice("foo") .block(); fail("Expected NotFound response"); } catch (HttpResponseException e) { assertEquals(404, e.getResponse().getStatusCode()); } } @Test public void testGetUpdateCompliance() { DevicesAsyncClient client = createClient(); UpdateCompliance updateCompliance = client.getUpdateCompliance() .block(); assertNotNull(updateCompliance); assertTrue(updateCompliance.getTotalDeviceCount() > 0); } @Test public void testGetAllDeviceTags() { DevicesAsyncClient client = createClient(); PagedFlux<DeviceTag> response = client.getAllDeviceTags(); assertNotNull(response); List<DeviceTag> deviceTags = new ArrayList<>(); response.byPage().map(page -> deviceTags.addAll(page.getValue())).blockLast(); assertTrue(deviceTags.size() > 0); } @Test public void testGetDeviceTag() { DevicesAsyncClient client = createClient(); String tag_name = "functionaltests-groupname1"; DeviceTag deviceTag = client.getDeviceTag(tag_name) .block(); assertNotNull(deviceTag); assertEquals(tag_name, deviceTag.getTagName()); } @Test public void testGetDeviceTagNotFound() { DevicesAsyncClient client = createClient(); try { client.getDevice("foo") .block(); fail("Expected NotFound response"); } catch (HttpResponseException e) { assertEquals(404, e.getResponse().getStatusCode()); } } @Test public void testGetAllGroups() { DevicesAsyncClient client = createClient(); PagedFlux<Group> response = client.getAllGroups(); assertNotNull(response); List<Group> groups = new ArrayList<>(); response.byPage().map(page -> groups.addAll(page.getValue())).blockLast(); assertTrue(groups.size() > 0); } @Test public void testGetGroup() { DevicesAsyncClient client = createClient(); String group_id = "Uncategorized"; Group group = client.getGroup(group_id) .block(); assertNotNull(group); assertEquals(group_id, group.getGroupId()); } @Test public void testGetGroupNotFound() { DevicesAsyncClient client = createClient(); try { client.getGroup("foo") .block(); fail("Expected NotFound response"); } catch (HttpResponseException e) { assertEquals(404, e.getResponse().getStatusCode()); } } @Test public void testGetGroupUpdateCompliance() { DevicesAsyncClient client = createClient(); String group_id = "Uncategorized"; UpdateCompliance compliance = client.getGroupUpdateCompliance(group_id) .block(); assertNotNull(compliance); assertTrue(compliance.getTotalDeviceCount() > 0); } @Test public void testGetGroupUpdateComplianceNotFound() { DevicesAsyncClient client = createClient(); try { client.getGroupUpdateCompliance("foo") .block(); fail("Expected NotFound response"); } catch (HttpResponseException e) { assertEquals(404, e.getResponse().getStatusCode()); } } @Test public void testGetGroupBestUpdates() { DevicesAsyncClient client = createClient(); String group_id = TestData.DEVICE_ID; PagedFlux<UpdatableDevices> response = client.getGroupBestUpdates(group_id, null); assertNotNull(response); List<UpdatableDevices> updates = new ArrayList<>(); response.byPage().map(page -> updates.addAll(page.getValue())).blockLast(); assertTrue(updates.size() > 0); } @Test public void testGetGroupBestUpdatesNotFound() { DevicesAsyncClient client = createClient(); try { PagedFlux<UpdatableDevices> response = client.getGroupBestUpdates("foo", null); List<UpdatableDevices> updates = new ArrayList<>(); response.byPage().map(page -> updates.addAll(page.getValue())).blockLast(); fail("Expected NotFound response"); } catch (HttpResponseException e) { assertEquals(404, e.getResponse().getStatusCode()); } } }
4,806
4,391
# This sample tests the special-case handling of the __self__ # attribute for a function when it is bound to a class or object. # pyright: reportFunctionMemberAccess=error from typing import Literal def func1(a: int) -> str: ... # This should generate an error because func1 isn't # bound to a "self". s1 = func1.__self__ class A: def method1(self) -> None: ... @classmethod def method2(cls) -> None: ... @staticmethod def method3() -> None: ... s2 = A().method1.__self__ t_s2: Literal["A"] = reveal_type(s2) s3 = A.method2.__self__ t_s3: Literal["Type[A]"] = reveal_type(s3) s3 = A.method2.__self__ t_s3: Literal["Type[A]"] = reveal_type(s3) s4 = A().method2.__self__ t_s4: Literal["Type[A]"] = reveal_type(s4) # This should generate an error because method3 is static. s5 = A().method3.__self__ # This should generate an error because method3 is static. s6 = A.method3.__self__
372
1,590
<reponame>libc16/azure-rest-api-specs { "id":"451675de-a67d-4929-876c-5c2bf0b2c000", "topic":"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Maps/accounts/{accountName}", "subject":"/spatial/geofence/udid/{udid}/id/{eventId}", "data":{ "geometries":[ { "deviceId":"device_1", "udId":"1a13b444-4acf-32ab-ce4e-9ca4af20b169", "geometryId":"1", "distance":999.0, "nearestLat":47.609833, "nearestLon":-122.148274 }, { "deviceId":"device_1", "udId":"1a13b444-4acf-32ab-ce4e-9ca4af20b169", "geometryId":"2", "distance":999.0, "nearestLat":47.621954, "nearestLon":-122.131841 } ], "expiredGeofenceGeometryId":[ ], "invalidPeriodGeofenceGeometryId":[ ] }, "eventType":"Microsoft.Maps.GeofenceResult", "eventTime":"2018-11-08T00:52:08.0954283Z", "metadataVersion":"1", "dataVersion":"1.0" }
408
320
#ifndef BREAKPOINT_HH #define BREAKPOINT_HH #include "BreakPointBase.hh" #include "openmsx.hh" namespace openmsx { /** Base class for CPU breakpoints. * For performance reasons every bp is associated with exactly one * (immutable) address. */ class BreakPoint final : public BreakPointBase { public: BreakPoint(word address_, TclObject command_, TclObject condition_, bool once_) : BreakPointBase(std::move(command_), std::move(condition_), once_) , id(++lastId) , address(address_) {} [[nodiscard]] word getAddress() const { return address; } [[nodiscard]] unsigned getId() const { return id; } private: unsigned id; word address; static inline unsigned lastId = 0; }; } // namespace openmsx #endif
243
348
<gh_stars>100-1000 {"nom":"Bosroger","circ":"1ère circonscription","dpt":"Creuse","inscrits":81,"abs":31,"votants":50,"blancs":8,"nuls":1,"exp":41,"res":[{"nuance":"LR","nom":"<NAME>","voix":21},{"nuance":"REM","nom":"<NAME>","voix":20}]}
97
1,240
<filename>app/src/main/java/com/eventyay/organizer/data/sponsor/SponsorRepositoryImpl.java package com.eventyay.organizer.data.sponsor; import androidx.annotation.NonNull; import com.eventyay.organizer.common.Constants; import com.eventyay.organizer.data.RateLimiter; import com.eventyay.organizer.data.Repository; import org.threeten.bp.Duration; import javax.inject.Inject; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class SponsorRepositoryImpl implements SponsorRepository { private final Repository repository; private final SponsorApi sponsorApi; private final RateLimiter<String> rateLimiter = new RateLimiter<>(Duration.ofMinutes(10)); @Inject public SponsorRepositoryImpl(Repository repository, SponsorApi sponsorApi) { this.repository = repository; this.sponsorApi = sponsorApi; } @NonNull @Override public Observable<Sponsor> getSponsors(long eventId, boolean reload) { Observable<Sponsor> diskObservable = Observable.defer(() -> repository.getItems(Sponsor.class, Sponsor_Table.event_id.eq(eventId)) ); Observable<Sponsor> networkObservable = Observable.defer(() -> sponsorApi.getSponsors(eventId) .doOnNext(sponsors -> repository .syncSave(Sponsor.class, sponsors, Sponsor::getId, Sponsor_Table.id) .subscribe()) .flatMapIterable(sponsors -> sponsors)); return repository.observableOf(Sponsor.class) .reload(reload) .withRateLimiterConfig("Sponsors", rateLimiter) .withDiskObservable(diskObservable) .withNetworkObservable(networkObservable) .build(); } @NonNull @Override public Observable<Sponsor> getSponsor(long sponsorId, boolean reload) { Observable<Sponsor> diskObservable = Observable.defer(() -> repository .getItems(Sponsor.class, Sponsor_Table.id.eq(sponsorId)).take(1) ); Observable<Sponsor> networkObservable = Observable.defer(() -> sponsorApi.getSponsor(sponsorId) .doOnNext(sponsor -> repository .save(Sponsor.class, sponsor) .subscribe())); return repository .observableOf(Sponsor.class) .reload(reload) .withDiskObservable(diskObservable) .withNetworkObservable(networkObservable) .build(); } @Override public Observable<Sponsor> createSponsor(Sponsor sponsor) { if (!repository.isConnected()) { return Observable.error(new Throwable(Constants.NO_NETWORK)); } return sponsorApi .postSponsor(sponsor) .doOnNext(created -> { created.setEvent(sponsor.getEvent()); repository .save(Sponsor.class, created) .subscribe(); }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } @NonNull @Override public Observable<Sponsor> updateSponsor(Sponsor sponsor) { if (!repository.isConnected()) { return Observable.error(new Throwable(Constants.NO_NETWORK)); } return sponsorApi .updateSponsor(sponsor.getId(), sponsor) .doOnNext(updatedSponsor -> repository .update(Sponsor.class, updatedSponsor) .subscribe()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } @Override public Completable deleteSponsor(long id) { if (!repository.isConnected()) { return Completable.error(new Throwable(Constants.NO_NETWORK)); } return sponsorApi.deleteSponsor(id) .doOnComplete(() -> repository .delete(Sponsor.class, Sponsor_Table.id.eq(id)) .subscribe()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }
1,911
574
//////////////////////////////////////////////////////////////////////////////// // // Visual Leak Detector - Import Library Header // Copyright (c) 2005-2014 VLD Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // See COPYING.txt for the full terms of the GNU Lesser General Public License. // //////////////////////////////////////////////////////////////////////////////// #pragma once #ifndef _WCHAR_T_DEFINED # include <wchar.h> #endif #define VLD_OPT_AGGREGATE_DUPLICATES 0x0001 // If set, aggregate duplicate leaks in the leak report. #define VLD_OPT_MODULE_LIST_INCLUDE 0x0002 // If set, modules in the module list are included, all others are excluded. #define VLD_OPT_REPORT_TO_DEBUGGER 0x0004 // If set, the memory leak report is sent to the debugger. #define VLD_OPT_REPORT_TO_FILE 0x0008 // If set, the memory leak report is sent to a file. #define VLD_OPT_SAFE_STACK_WALK 0x0010 // If set, the stack is walked using the "safe" method (StackWalk64). #define VLD_OPT_SELF_TEST 0x0020 // If set, perform a self-test to verify memory leak self-checking. #define VLD_OPT_SLOW_DEBUGGER_DUMP 0x0040 // If set, inserts a slight delay between sending output to the debugger. #define VLD_OPT_START_DISABLED 0x0080 // If set, memory leak detection will initially disabled. #define VLD_OPT_TRACE_INTERNAL_FRAMES 0x0100 // If set, include useless frames (e.g. internal to VLD) in call stacks. #define VLD_OPT_UNICODE_REPORT 0x0200 // If set, the leak report will be encoded UTF-16 instead of ASCII. #define VLD_OPT_VLDOFF 0x0400 // If set, VLD will be completely deactivated. It will not attach to any modules. #define VLD_OPT_REPORT_TO_STDOUT 0x0800 // If set, the memory leak report is sent to stdout. #define VLD_OPT_SKIP_HEAPFREE_LEAKS 0x1000 // If set, VLD skip HeapFree memory leaks. #define VLD_OPT_VALIDATE_HEAPFREE 0x2000 // If set, VLD verifies and reports heap consistency for HeapFree calls. #define VLD_OPT_SKIP_CRTSTARTUP_LEAKS 0x4000 // If set, VLD skip crt srtartup memory leaks. #define VLD_RPTHOOK_INSTALL 0 #define VLD_RPTHOOK_REMOVE 1 typedef int (__cdecl * VLD_REPORT_HOOK)(int reportType, wchar_t *message, int *returnValue);
1,031
440
<filename>src/main/java/yanagishima/model/dto/PublishDto.java package yanagishima.model.dto; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; @Getter @Setter public class PublishDto { @JsonProperty("publish_id") private String publishId; private String error; }
121
1,260
<gh_stars>1000+ /*! @file Defines `boost::hana::detail::variadic::reverse_apply`. @copyright <NAME> 2013-2017 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_DETAIL_VARIADIC_REVERSE_APPLY_HPP #define BOOST_HANA_DETAIL_VARIADIC_REVERSE_APPLY_HPP #include <boost/hana/config.hpp> #include <boost/hana/detail/variadic/reverse_apply/unrolled.hpp> BOOST_HANA_NAMESPACE_BEGIN namespace detail { namespace variadic { BOOST_HANA_INLINE_VARIABLE BOOST_HANA_CONSTEXPR_LAMBDA auto reverse_apply = [](auto&& f, auto&& ...x) -> decltype(auto) { return detail::variadic::reverse_apply_unrolled( static_cast<decltype(f)>(f), static_cast<decltype(x)>(x)... ); }; }} BOOST_HANA_NAMESPACE_END #endif // !BOOST_HANA_DETAIL_VARIADIC_REVERSE_APPLY_HPP
425
10,225
package io.quarkus.restclient.configuration; import java.util.Collections; import java.util.HashMap; import java.util.Set; import org.eclipse.microprofile.config.ConfigProvider; import org.eclipse.microprofile.config.spi.ConfigSource; import io.quarkus.runtime.annotations.StaticInitSafe; import io.smallrye.config.common.MapBackedConfigSource; @StaticInitSafe public class RestClientRunTimeConfigSource extends MapBackedConfigSource { public RestClientRunTimeConfigSource() { super(RestClientRunTimeConfigSource.class.getName(), new HashMap<>()); } @Override public String getValue(final String propertyName) { if (!propertyName.equals("io.quarkus.restclient.configuration.EchoClient/mp-rest/url")) { return null; } if (isRuntime()) { return "http://localhost:${quarkus.http.test-port:8081}"; } return null; } @Override public Set<String> getPropertyNames() { return Collections.singleton("io.quarkus.restclient.configuration.EchoClient/mp-rest/url"); } @Override public int getOrdinal() { return Integer.MAX_VALUE; } private static boolean isRuntime() { for (ConfigSource configSource : ConfigProvider.getConfig().getConfigSources()) { if (configSource.getName().equals("PropertiesConfigSource[source=Specified default values]")) { return true; } } return false; } }
566
1,144
<gh_stars>1000+ import sqlparse skip_token_type = [ sqlparse.tokens.Comment.Single, sqlparse.tokens.Comment.Multi, sqlparse.tokens.Whitespace, sqlparse.tokens.Newline, ] def get_statement_ranges(query): statements = sqlparse.parse(query) statement_ranges = [] start_index = 0 for statement in statements: statement_str = statement.value statement_len = len(statement_str) if get_sanitized_statement(statement_str) != "": statement_start = start_index statement_end = start_index found_start = False for token in statement.flatten(): token_type = getattr(token, "ttype") if not found_start: # Skipping for start if token_type in skip_token_type: statement_start += len(token.value) else: found_start = True statement_end = statement_start # Don't change this to else:, since token from not found start # might be used here if found_start: # Looking for end ; if token_type != sqlparse.tokens.Punctuation or token.value != ";": statement_end += len(token.value) else: break statement_range = (statement_start, statement_end) statement_ranges.append(statement_range) start_index += statement_len return statement_ranges def get_statements(query): statement_ranges = get_statement_ranges(query) return [ get_sanitized_statement(query[start:end]) for start, end in statement_ranges ] def get_sanitized_statement(statement): return sqlparse.format(statement, strip_comments=True).strip(" \n\r\t;")
853
586
# -*- coding: utf-8 -*- import pytest from validators import slug, ValidationFailure @pytest.mark.parametrize('value', [ '123-12312-asdasda', '123____123', 'dsadasd-dsadas', ]) def test_returns_true_on_valid_slug(value): assert slug(value) @pytest.mark.parametrize('value', [ 'some.slug', '1231321%', ' 21312', '123asda&', ]) def test_returns_failed_validation_on_invalid_slug(value): assert isinstance(slug(value), ValidationFailure)
207
506
<filename>atcoder/abc089/c.py #!/usr/bin/env python3 # https://abc089.contest.atcoder.jp/tasks/abc089_c import itertools n = int(input()) a = [0] * 26 for _ in range(n): a[ord(input()[0]) - ord('A')] += 1 c = [] for x in 'MARCH': c.append(a[ord(x) - ord('A')]) s = 0 for x in itertools.combinations(c, 3): k = 1 for i in x: k *= i s += k print(s)
179
335
{ "word": "Exception", "definitions": [ "A person or thing that is excluded from a general statement or does not follow a rule." ], "parts-of-speech": "Noun" }
69
363
<filename>src/test/java/com/github/ferstl/depgraph/dependency/MavenGraphAdapterTest.java /* * Copyright (c) 2014 - 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.github.ferstl.depgraph.dependency; import java.util.EnumSet; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.project.DependencyResolutionException; import org.apache.maven.project.DependencyResolutionRequest; import org.apache.maven.project.DependencyResolutionResult; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.project.ProjectDependenciesResolver; import org.eclipse.aether.RepositorySystemSession; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.github.ferstl.depgraph.ToStringNodeIdRenderer; import com.github.ferstl.depgraph.graph.GraphBuilder; import static com.github.ferstl.depgraph.dependency.NodeResolution.INCLUDED; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * JUnit tests for {@link MavenGraphAdapter}. */ class MavenGraphAdapterTest { private ProjectDependenciesResolver dependenciesResolver; private MavenProject mavenProject; private GraphBuilder<DependencyNode> graphBuilder; private ArtifactFilter globalFilter; private MavenGraphAdapter graphAdapter; @BeforeEach void before() throws Exception { Artifact projectArtifact = mock(Artifact.class); this.mavenProject = new MavenProject(); this.mavenProject.setArtifact(projectArtifact); ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class); when(projectBuildingRequest.getRepositorySession()).thenReturn(mock(RepositorySystemSession.class)); //noinspection deprecation this.mavenProject.setProjectBuildingRequest(projectBuildingRequest); this.globalFilter = mock(ArtifactFilter.class); ArtifactFilter transitiveIncludeExcludeFilter = mock(ArtifactFilter.class); ArtifactFilter targetFilter = mock(ArtifactFilter.class); this.graphBuilder = GraphBuilder.create(ToStringNodeIdRenderer.INSTANCE); this.dependenciesResolver = mock(ProjectDependenciesResolver.class); DependencyResolutionResult dependencyResolutionResult = mock(DependencyResolutionResult.class); when(dependencyResolutionResult.getDependencyGraph()).thenReturn(mock(org.eclipse.aether.graph.DependencyNode.class)); when(this.dependenciesResolver.resolve(any(DependencyResolutionRequest.class))).thenReturn(dependencyResolutionResult); this.graphAdapter = new MavenGraphAdapter(this.dependenciesResolver, transitiveIncludeExcludeFilter, targetFilter, EnumSet.of(INCLUDED)); } @Test void dependencyGraph() throws Exception { this.graphAdapter.buildDependencyGraph(this.mavenProject, this.globalFilter, this.graphBuilder); verify(this.dependenciesResolver).resolve(any(DependencyResolutionRequest.class)); } @Test void dependencyGraphWithException() throws Exception { DependencyResolutionException exception = new DependencyResolutionException(mock(DependencyResolutionResult.class), "boom", new Exception()); when(this.dependenciesResolver.resolve(any(DependencyResolutionRequest.class))).thenThrow(exception); try { this.graphAdapter.buildDependencyGraph(this.mavenProject, this.globalFilter, this.graphBuilder); fail("Expect exception"); } catch (DependencyGraphException e) { assertEquals(exception, e.getCause()); } } }
1,298
1,060
{ "name": "react-selecto", "version": "1.12.0", "description": "A React Selecto Component that allows you to select elements in the drag area using the mouse or touch.", "main": "./dist/selecto.cjs.js", "module": "./dist/selecto.esm.js", "sideEffects": false, "types": "declaration/index.d.ts", "scripts": { "lint": "tslint -c tslint.json 'src/react-selecto/**/*.ts' 'src/react-selecto/**/*.tsx'", "start": "react-scripts start", "build": "rollup -c && npm run declaration && print-sizes ./dist ", "declaration": "rm -rf declaration && tsc -p tsconfig.declaration.json", "packages": "npm run packages:update && npm run packages:build && npm run packages:publish", "packages:update": "pvu --path=../ --update=preact-selecto", "packages:build": "pvu --path=../ --build=preact-selecto", "packages:publish": "pvu --path=../ --publish=preact-selecto" }, "keywords": [ "select", "selecto", "selection", "selectable", "moveable", "react" ], "repository": { "type": "git", "url": "https://github.com/daybrush/selecto/blob/master/packages/react-selecto" }, "author": "Daybrush", "license": "MIT", "bugs": { "url": "https://github.com/daybrush/selecto/issues" }, "homepage": "https://daybrush.com/selecto", "devDependencies": { "@daybrush/builder": "^0.1.2", "@types/react-dom": "^16.9.4", "print-sizes": "0.0.4", "pvu": "^0.5.1", "react": "^16.8.6", "react-dom": "^16.8.6", "react-scripts": "^3.0.1", "tslint": "^5.16.0", "typescript": "^3.4.5" }, "dependencies": { "selecto": "~1.12.1" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
808
4,487
<gh_stars>1000+ /******************************************************************************* * * (C) COPYRIGHT AUTHORS, 2017 - 2021 * * TITLE: UTIL.H * * VERSION: 3.56 * * DATE: 19 July 2021 * * Global support routines header file shared between payload dlls. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. * *******************************************************************************/ #pragma once typedef struct _UACME_PARAM_BLOCK { ULONG Crc32; ULONG SessionId; ULONG AkagiFlag; WCHAR szParameter[MAX_PATH + 1]; WCHAR szDesktop[MAX_PATH + 1]; WCHAR szWinstation[MAX_PATH + 1]; WCHAR szSignalObject[MAX_PATH + 1]; } UACME_PARAM_BLOCK, *PUACME_PARAM_BLOCK; typedef BOOL(WINAPI* PFNCREATEPROCESSW)( LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); typedef BOOL(WINAPI *PFNCREATEPROCESSASUSERW)( _In_opt_ HANDLE hToken, _In_opt_ LPCWSTR lpApplicationName, _Inout_opt_ LPWSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCWSTR lpCurrentDirectory, _In_ LPSTARTUPINFOW lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation); typedef struct _OBJSCANPARAM { PWSTR Buffer; SIZE_T BufferSize; } OBJSCANPARAM, *POBJSCANPARAM; VOID ucmBinTextEncode( _In_ unsigned __int64 x, _Inout_ wchar_t* s); VOID ucmGenerateSharedObjectName( _In_ WORD ObjectId, _Inout_ LPWSTR lpBuffer); BOOLEAN ucmPrivilegeEnabled( _In_ HANDLE hToken, _In_ ULONG Privilege); NTSTATUS ucmCreateSyncMutant( _Out_ PHANDLE phMutant); BOOLEAN ucmIsProcess32bit( _In_ HANDLE hProcess); DWORD ucmGetHashForString( _In_ char* s); LPVOID ucmGetProcedureAddressByHash( _In_ PVOID ImageBase, _In_ DWORD ProcedureHash); VOID ucmGetStartupInfo( _In_ LPSTARTUPINFOW lpStartupInfo); DWORD ucmExpandEnvironmentStrings( _In_ LPCWSTR lpSrc, _Out_writes_to_opt_(nSize, return) LPWSTR lpDst, _In_ DWORD nSize); PVOID ucmGetSystemInfo( _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass); BOOL ucmLaunchPayload( _In_opt_ LPWSTR pszPayload, _In_opt_ DWORD cbPayload); BOOL ucmLaunchPayloadEx( _In_ PFNCREATEPROCESSW pCreateProcess, _In_opt_ LPWSTR pszPayload, _In_opt_ DWORD cbPayload); BOOL ucmLaunchPayload2( _In_ PFNCREATEPROCESSASUSERW pCreateProcessAsUser, _In_ BOOL bIsLocalSystem, _In_ ULONG SessionId, _In_opt_ LPWSTR pszPayload, _In_opt_ DWORD cbPayload); LPWSTR ucmQueryRuntimeInfo( _In_ BOOL ReturnData); BOOLEAN ucmDestroyRuntimeInfo( _In_ LPWSTR RuntimeInfo); BOOL ucmIsUserWinstaInteractive( VOID); NTSTATUS ucmIsUserHasInteractiveSid( _In_ HANDLE hToken, _Out_ PBOOL pbInteractiveSid); NTSTATUS ucmIsLocalSystem( _Out_ PBOOL pbResult); HANDLE ucmOpenAkagiNamespace( VOID); _Success_(return == TRUE) BOOL ucmReadSharedParameters( _Out_ UACME_PARAM_BLOCK *SharedParameters); VOID ucmSetCompletion( _In_ LPWSTR lpEvent); BOOL ucmGetProcessElevationType( _In_opt_ HANDLE ProcessHandle, _Out_ TOKEN_ELEVATION_TYPE *lpType); NTSTATUS ucmIsProcessElevated( _In_ ULONG ProcessId, _Out_ PBOOL Elevated); PLARGE_INTEGER ucmFormatTimeOut( _Out_ PLARGE_INTEGER TimeOut, _In_ DWORD Milliseconds); VOID ucmSleep( _In_ DWORD Miliseconds); BOOL ucmSetEnvironmentVariable( _In_ LPCWSTR lpName, _In_ LPCWSTR lpValue); #ifdef _DEBUG #define ucmDbgMsg(Message) OutputDebugString(Message) #else #define ucmDbgMsg(Message) #endif
1,778
663
<reponame>doctorpangloss/gogradle /* * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.github.blindpirate.gogradle.util; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.apache.tools.tar.TarEntry; import org.apache.tools.tar.TarInputStream; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.util.zip.GZIPInputStream; public class CompressUtils { private static final Logger LOGGER = Logging.getLogger(CompressUtils.class); public static void decompressZip(File zipFile, File destDir) { try { ZipFile zF = new ZipFile(zipFile); zF.extractAll(destDir.toString()); } catch (ZipException e) { throw ExceptionHandler.uncheckException(e); } } public static void decompressTarGz(File tarGzFile, File destDir) { try { IOUtils.forceMkdir(destDir); TarInputStream tin = new TarInputStream(new GZIPInputStream(new FileInputStream(tarGzFile))); TarEntry tarEntry = tin.getNextEntry(); while (tarEntry != null) { File destPath = new File(destDir, tarEntry.getName()); if (tarEntry.isDirectory()) { IOUtils.forceMkdir(destPath); } else { FileOutputStream fout = new FileOutputStream(destPath); tin.copyEntryContents(fout); fout.close(); } tarEntry = tin.getNextEntry(); } tin.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public static void decompressZipOrTarGz(File compressedFile, File destDir) { LOGGER.quiet("Extracting {} to {}", compressedFile.getAbsolutePath(), destDir.getAbsolutePath()); if (compressedFile.getName().endsWith("tar.gz")) { decompressTarGz(compressedFile, destDir); } else if (compressedFile.getName().endsWith("zip")) { decompressZip(compressedFile, destDir); } else { throw new IllegalArgumentException("Only zip and tar.gz are supported!"); } } }
1,194
371
<gh_stars>100-1000 /* * Copyright (C) 2018 xuexiangjys(<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xuexiang.xhttp2demo.fragment; import com.xuexiang.xhttp2.XHttp; import com.xuexiang.xhttp2demo.entity.User; import com.xuexiang.xhttp2demo.http.callback.TipRequestCallBack; import com.xuexiang.xpage.annotation.Page; import com.xuexiang.xpage.base.XPageSimpleListFragment; import com.xuexiang.xrouter.launcher.XRouter; import com.xuexiang.xutil.net.JsonUtil; import com.xuexiang.xutil.tip.ToastUtils; import java.util.List; /** * @author xuexiang * @since 2018/8/7 上午12:01 */ @Page(name = "高阶使用 -- 身份校验") public class TokenFragment extends XPageSimpleListFragment { @Override protected List<String> initSimpleData(List<String> lists) { lists.add("跳转至登陆获取token"); lists.add("验证token"); lists.add("频繁进行网络请求的校验(30秒内请求不能超过3次)"); lists.add("频繁进行网络请求的校验(10秒钟之内只能请求一次)"); return lists; } @Override protected void onItemClick(int position) { switch (position) { case 0: XRouter.getInstance().build("/xhttp/login").navigation(); break; case 1: XHttp.get("/authorization/getCurrentUser") .accessToken(true) .execute(new TipRequestCallBack<User>() { @Override public void onSuccess(User user) throws Throwable { ToastUtils.toast("当前登录的用户:" + JsonUtil.toJson(user)); } }); break; case 2: XHttp.get("/authorization/testLimitedRequest") .execute(new TipRequestCallBack<Boolean>() { @Override public void onSuccess(Boolean aBoolean) throws Throwable { ToastUtils.toast("请求成功!"); } }); break; case 3: XHttp.get("/authorization/testQuickRequest") .timeStamp(true) .execute(new TipRequestCallBack<Boolean>() { @Override public void onSuccess(Boolean aBoolean) throws Throwable { ToastUtils.toast("请求成功!"); } }); break; default: break; } } }
1,718
480
// // TagListContainerView.h // ESTCollectionViewDropDownList // // Created by Aufree on 12/3/15. // Copyright © 2015 The EST Group. All rights reserved. // #import <UIKit/UIKit.h> @protocol TagListContainerViewDelegate <NSObject> - (void)didSelectedTags:(NSMutableArray *)tags; @end @interface TagListContainerView : UIView @property (nonatomic, copy) NSArray *tagsEntities; @property (nonatomic, weak) id<TagListContainerViewDelegate> delegate; @end
152
1,602
#include <string.h> static void get_string(const char** string_out) { *string_out = strdup("Hello"); printf("get_string returns %s\n", *string_out); } static void modify_string(const char** string_out, const char* string_in) { char* tmp; printf("modify_string got %s\n", string_in); tmp = strdup(string_in); tmp[0] = 'A'; *string_out = tmp; printf("modify_string returns %s\n", *string_out); }
162
1,319
# -*- coding: utf-8 -*- import urwid DIV = urwid.Divider() HR = urwid.AttrMap(urwid.Divider('_'), 'hr') def pad(widget, left=2, right=2): return urwid.Padding(widget, left=left, right=right) class TextButton(urwid.Button): """ Args: label (str): label for the text button on_press (function): callback user_data(): user_data for on_press align (str): (default right) """ def __init__(self, label, on_press=None, user_data=None, align='right'): super(TextButton, self).__init__( label, on_press=on_press, user_data=user_data) self._label.align = align cols = urwid.Columns([self._label]) super(urwid.Button, self).__init__(cols) class Card(urwid.WidgetWrap): """ Args: content (urwid.Widget): header (urwid.Widget): footer (urwid.Widget): """ def __init__(self, content, header=None, footer=None): wlist = [] if header: wlist.append(header) wlist.extend([DIV, pad(content)]) if footer: wlist.extend([HR, DIV, pad(footer)]) wlist.append(DIV) card = urwid.AttrMap(urwid.Pile(wlist), 'card') urwid.WidgetWrap.__init__(self, card) class ObjectButton(urwid.Button): def __init__(self, content, on_press=None, user_data=None): self.__super.__init__('', on_press=on_press, user_data=user_data) super(urwid.Button, self).__init__(content) @staticmethod def get_content(text): return urwid.Pile([urwid.SelectableIcon( s, 0) if i == 0 else urwid.Text(s) for i, s in enumerate(text)]) class LineButton(ObjectButton): """ Creates a LineBox button with an image on the left column and text on the right Args: text ((palette_class, str)[]): array of string tuples """ def __init__(self, text, vertical_padding=True): content = [urwid.Padding(self.get_content(text), left=3, right=3)] if vertical_padding: content = [DIV] + content + [DIV] lbox = urwid.LineBox(urwid.Pile(content)) self.__super.__init__(urwid.AttrMap(urwid.Pile( [lbox]), 'image button', 'image button focus')) class ImageButton(ObjectButton): """ Creates a LineBox button with an image on the left column and text on the right Args: pic (urwid.Pile): object created with picRead text ((palette_class, str)[]): array of string tuples """ def __init__(self, pic, text): content = self.get_content(text) lbox = urwid.LineBox(urwid.Pile([DIV, urwid.Padding( urwid.Columns([(8, pic), content], 4), left=3, right=3), DIV])) self.__super.__init__(urwid.AttrMap(urwid.Pile( [lbox]), 'image button', 'image button focus')) class InputField(urwid.WidgetWrap): """ Creates an input field with underline and a label Args: label (str): label for the input label_width (int): label width (default 15 characters) """ def __init__(self, label="", label_width=15, next_callback=False): self.label, self.next_callback = label, next_callback self.edit = urwid.Padding(urwid.Edit(), left=1, right=1) label = urwid.LineBox( urwid.Text(label), tlcorner=' ', tline=' ', lline=' ', trcorner=' ', blcorner=' ', rline=' ', brcorner=' ', bline=' ') lbox = urwid.AttrMap( urwid.LineBox( self.edit, tlcorner=' ', tline=' ', lline=' ', trcorner=' ', blcorner=' ', rline=' ', brcorner=' '), 'input', 'input focus') cols = urwid.Columns([(label_width, label), lbox]) urwid.WidgetWrap.__init__(self, cols) def get_text(self): """ Returns: str: value of the input field """ return self.edit.original_widget.get_text()[0] def get_label(self): """ Returns: str: label for the input field """ return self.label def keypress(self, size, key): if key is 'enter' and self.next_callback: self.next_callback() else: return self.__super.keypress(size, key) class FormCard(urwid.WidgetWrap): """ Args: content (urwid.Widget): any widget that can be piled field_labels (str[]): labels for the input_fields btn_label (str): label for the button callbacks Dict(function, function): callbacks for next and back button app (App): main app Note: callbacks['next'] must take the same amount of arguments as labels were passed and each parameter in the callback must be named as the label but in snake case and lower case e.g. 'Field Name' => field_name """ def __init__(self, data, field_labels, btn_label, callbacks): self.app = data["app"] self.error = False self.fields, self.callbacks = [], callbacks for label in field_labels: self.fields.append(InputField(label, next_callback=self.next)) input_fields = urwid.Pile(self.fields) self.message_field = urwid.Text('') error_row = urwid.Columns([(17, urwid.Text('')), self.message_field]) buttons = [TextButton(btn_label, on_press=self.next)] if callbacks['back']: buttons.insert(0, TextButton('< Back', align='left', on_press=callbacks['back'])) footer = urwid.AttrMap(urwid.Columns(buttons), 'button') card = Card(urwid.Pile( [data["content"], input_fields, error_row]), footer=footer) urwid.WidgetWrap.__init__(self, card) def next(self, *_): self.callbacks['next'](form=self, **(self.get_field_values())) def get_field_values(self): """ Returns: dict: the keys are the labels of the fields in snake_case """ values = dict() for field in self.fields: values[field.get_label().lower().replace(" ", "_")] = field.get_text() return values def set_message(self, msg, error=False): """ Shows a message message at the bottom of the form Args: msg (str): message error (bool): if message type is error """ self.error = error self.message_field.set_text(('error' if error else 'info', msg)) self.app.loop.draw_screen() def unset_error(self): """ Removes the error message """ self.message_field.set_text('') self.app.loop.draw_screen() def keypress(self, size, key): if self.error: self.unset_error() self.error = False return self.__super.keypress(size, key) class TestRunner(urwid.WidgetWrap): """ Run the test while displaying the progress Args: title (str): title to pass to the callback cred (dict(str: str)): credentials tests (Test[]): tests to run callback (function): to call when the tests finish running """ def __init__(self, title, cred, tests, data): self.app = None self.tester = data["tester"] urn = cred["nodelist"][0][0] + ":" + str(cred["nodelist"][0][1]) + ( "/" + (cred["database"]) if bool(cred["database"]) else "") self.data = {"title": title, "callback": data["callback"], "urn": urn, "num_tests": len(tests)} self.progress_text = urwid.Text( ('progress', '0/' + str(self.data["num_tests"]))) running_display = urwid.Columns( [(14, urwid.Text(('text', 'Running test'))), self.progress_text]) self.progress_bar = CustomProgressBar( 'progress', 'remaining', 0, self.data["num_tests"]) self.text_running = urwid.Text(('text', '')) box = urwid.BoxAdapter(urwid.Filler( self.text_running, valign='top'), 2) pile = urwid.Pile([running_display, self.progress_bar, DIV, box]) urwid.WidgetWrap.__init__(self, pile) def each(self, test): """ Update the description of the test currently running """ current = self.progress_bar.get_current() + 1 self.progress_text.set_text( ('progress', '%s/%s' % (str(current), str(self.data["num_tests"])))) self.progress_bar.set_completion(current) self.text_running.set_text('Checking if %s...' % test.title) self.app.loop.draw_screen() def run(self, app): """ run tests """ self.app = app self.tester.run(self.each, self.end) def end(self, res): self.data["callback"](res, self.data["title"], self.data["urn"]) class CustomProgressBar(urwid.ProgressBar): """ ProgressBar that displays a semigraph instead of a percentage """ semi = u'\u2582' def get_text(self): """ Return the progress bar percentage. """ return min(100, max(0, int(self.current * 100 / self.done))) def get_current(self): """ Return the current value of the ProgressBar """ return self.current def get_done(self): """ Return the end value of the ProgressBar """ return self.done def render(self, size, **_): """ Render the progress bar. """ (maxcol,) = size ccol = int(self.current * maxcol / self.done) txt = urwid.Text([(self.normal, self.semi * ccol), (self.complete, self.semi * (maxcol - ccol))]) return txt.render(size) class DisplayTest(urwid.WidgetWrap): """ Display test result """ currently_displayed = 0 top_columns = urwid.Columns([]) test_result = urwid.Pile([]) def __init__(self, result): self.result = result self.total = len(result) self.update_view('next_callback') walker = urwid.SimpleListWalker([urwid.Padding(self.top_columns, left=3, right=3), self.test_result]) adapter = urwid.BoxAdapter(urwid.ListBox(walker), height=14) urwid.WidgetWrap.__init__(self, adapter) @staticmethod def test_display(test, options): """ Compose the element that will display the test Returns: [urwid.Widget]: """ empty_line = (DIV, options('weight', 1)) title = (urwid.Text( ('text bold', test['title'][0].upper() + test['title'][1:])), options('weight', 1)) caption = (urwid.Text( ('text', test['caption'])), options('weight', 1)) severity = (urwid.Text([ ('input', 'Severity: '), ('text', ['HIGH', 'Medium', 'Low'][test['severity']]) ]), options('weight', 1)) result = (urwid.Text([ ('input', 'Result: '), ( ['failed', 'passed', 'warning', 'info'][test['result']], ['✘ FAILED', '✔ PASSED', '! WARNING', '* OMITTED'][test['result']] ) ]), options('weight', 1)) if isinstance(test['message'], list): message_string = test['message'][0] + \ test['extra_data'] + test['message'][1] else: message_string = test['message'] message = (urwid.Text( ('text', message_string)), options('weight', 1)) return [empty_line, title, empty_line, severity, caption, result, message] def get_top_text(self): """ Returns: tuple(str,str): PALETTE , Test n/total """ return 'header red', 'Test ' + \ str(self.currently_displayed) + '/' + str(self.total) def get_top_row(self, current, options): def get_button(sign, text): return urwid.AttrMap(TextButton(sign, on_press=( lambda _: self.update_view(text))), 'button') next_btn = get_button('>', 'next_callback') prev_btn = get_button('<', 'prev') top_row = [] if current > 1: top_row.append((prev_btn, options('weight', 0))) top_row.append((urwid.Padding(urwid.Text(self.get_top_text()), left=25), options('weight', 1))) if current < len(self.result): top_row.append((next_btn, options('weight', 0.2))) return top_row def update_currently_displayed(self, btn): self.currently_displayed += 1 if btn is 'next_callback' else -1 def set_focus_position(self, current, btn): focus = 0 # moving to the left if current <= 1: focus = 1 # first element elif btn is 'next_callback' and current < self.total: focus = 2 # moving to the right self.top_columns.focus_position = focus def update_view(self, btn): self.update_currently_displayed(btn) self.top_columns.contents = self.get_top_row( self.currently_displayed, self.top_columns.options) self.set_focus_position(self.currently_displayed, btn) self.test_result.contents = self.test_display( self.result[self.currently_displayed - 1], self.test_result.options)
6,143
507
# terrascript/data/mildred/systemd.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:28:13 UTC) __all__ = []
48
2,494
<reponame>ktrzeciaknubisa/jxcore-binary-packaging /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* JS reflection package. */ #include "jsreflect.h" #include "mozilla/ArrayUtils.h" #include "mozilla/DebugOnly.h" #include <stdlib.h> #include "jsarray.h" #include "jsatom.h" #include "jsobj.h" #include "jspubtd.h" #include "frontend/Parser.h" #include "frontend/TokenStream.h" #include "js/CharacterEncoding.h" #include "vm/RegExpObject.h" #include "jsobjinlines.h" #include "frontend/ParseNode-inl.h" using namespace js; using namespace js::frontend; using JS::AutoValueArray; using mozilla::ArrayLength; using mozilla::DebugOnly; char const * const js::aopNames[] = { "=", /* AOP_ASSIGN */ "+=", /* AOP_PLUS */ "-=", /* AOP_MINUS */ "*=", /* AOP_STAR */ "/=", /* AOP_DIV */ "%=", /* AOP_MOD */ "<<=", /* AOP_LSH */ ">>=", /* AOP_RSH */ ">>>=", /* AOP_URSH */ "|=", /* AOP_BITOR */ "^=", /* AOP_BITXOR */ "&=" /* AOP_BITAND */ }; char const * const js::binopNames[] = { "==", /* BINOP_EQ */ "!=", /* BINOP_NE */ "===", /* BINOP_STRICTEQ */ "!==", /* BINOP_STRICTNE */ "<", /* BINOP_LT */ "<=", /* BINOP_LE */ ">", /* BINOP_GT */ ">=", /* BINOP_GE */ "<<", /* BINOP_LSH */ ">>", /* BINOP_RSH */ ">>>", /* BINOP_URSH */ "+", /* BINOP_PLUS */ "-", /* BINOP_MINUS */ "*", /* BINOP_STAR */ "/", /* BINOP_DIV */ "%", /* BINOP_MOD */ "|", /* BINOP_BITOR */ "^", /* BINOP_BITXOR */ "&", /* BINOP_BITAND */ "in", /* BINOP_IN */ "instanceof", /* BINOP_INSTANCEOF */ }; char const * const js::unopNames[] = { "delete", /* UNOP_DELETE */ "-", /* UNOP_NEG */ "+", /* UNOP_POS */ "!", /* UNOP_NOT */ "~", /* UNOP_BITNOT */ "typeof", /* UNOP_TYPEOF */ "void" /* UNOP_VOID */ }; char const * const js::nodeTypeNames[] = { #define ASTDEF(ast, str, method) str, #include "jsast.tbl" #undef ASTDEF nullptr }; static char const * const callbackNames[] = { #define ASTDEF(ast, str, method) method, #include "jsast.tbl" #undef ASTDEF nullptr }; enum YieldKind { Delegating, NotDelegating }; typedef AutoValueVector NodeVector; /* * ParseNode is a somewhat intricate data structure, and its invariants have * evolved, making it more likely that there could be a disconnect between the * parser and the AST serializer. We use these macros to check invariants on a * parse node and raise a dynamic error on failure. */ #define LOCAL_ASSERT(expr) \ JS_BEGIN_MACRO \ JS_ASSERT(expr); \ if (!(expr)) { \ JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_PARSE_NODE); \ return false; \ } \ JS_END_MACRO #define LOCAL_NOT_REACHED(expr) \ JS_BEGIN_MACRO \ MOZ_ASSERT(false); \ JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_PARSE_NODE); \ return false; \ JS_END_MACRO namespace { /* Set 'result' to obj[id] if any such property exists, else defaultValue. */ static bool GetPropertyDefault(JSContext *cx, HandleObject obj, HandleId id, HandleValue defaultValue, MutableHandleValue result) { bool found; if (!JSObject::hasProperty(cx, obj, id, &found)) return false; if (!found) { result.set(defaultValue); return true; } return JSObject::getGeneric(cx, obj, obj, id, result); } /* * Builder class that constructs JavaScript AST node objects. See: * * https://developer.mozilla.org/en/SpiderMonkey/Parser_API * * Bug 569487: generalize builder interface */ class NodeBuilder { typedef AutoValueArray<AST_LIMIT> CallbackArray; JSContext *cx; TokenStream *tokenStream; bool saveLoc; /* save source location information? */ char const *src; /* source filename or null */ RootedValue srcval; /* source filename JS value or null */ CallbackArray callbacks; /* user-specified callbacks */ RootedValue userv; /* user-specified builder object or null */ public: NodeBuilder(JSContext *c, bool l, char const *s) : cx(c), tokenStream(nullptr), saveLoc(l), src(s), srcval(c), callbacks(cx), userv(c) {} bool init(HandleObject userobj = js::NullPtr()) { if (src) { if (!atomValue(src, &srcval)) return false; } else { srcval.setNull(); } if (!userobj) { userv.setNull(); for (unsigned i = 0; i < AST_LIMIT; i++) { callbacks[i].setNull(); } return true; } userv.setObject(*userobj); RootedValue nullVal(cx, NullValue()); RootedValue funv(cx); for (unsigned i = 0; i < AST_LIMIT; i++) { const char *name = callbackNames[i]; RootedAtom atom(cx, Atomize(cx, name, strlen(name))); if (!atom) return false; RootedId id(cx, AtomToId(atom)); if (!GetPropertyDefault(cx, userobj, id, nullVal, &funv)) return false; if (funv.isNullOrUndefined()) { callbacks[i].setNull(); continue; } if (!funv.isObject() || !funv.toObject().is<JSFunction>()) { js_ReportValueErrorFlags(cx, JSREPORT_ERROR, JSMSG_NOT_FUNCTION, JSDVG_SEARCH_STACK, funv, js::NullPtr(), nullptr, nullptr); return false; } callbacks[i].set(funv); } return true; } void setTokenStream(TokenStream *ts) { tokenStream = ts; } private: bool callback(HandleValue fun, TokenPos *pos, MutableHandleValue dst) { if (saveLoc) { RootedValue loc(cx); if (!newNodeLoc(pos, &loc)) return false; AutoValueArray<1> argv(cx); argv[0].set(loc); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } AutoValueArray<1> argv(cx); argv[0].setNull(); /* no zero-length arrays allowed! */ return Invoke(cx, userv, fun, 0, argv.begin(), dst); } bool callback(HandleValue fun, HandleValue v1, TokenPos *pos, MutableHandleValue dst) { if (saveLoc) { RootedValue loc(cx); if (!newNodeLoc(pos, &loc)) return false; AutoValueArray<2> argv(cx); argv[0].set(v1); argv[1].set(loc); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } AutoValueArray<1> argv(cx); argv[0].set(v1); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } bool callback(HandleValue fun, HandleValue v1, HandleValue v2, TokenPos *pos, MutableHandleValue dst) { if (saveLoc) { RootedValue loc(cx); if (!newNodeLoc(pos, &loc)) return false; AutoValueArray<3> argv(cx); argv[0].set(v1); argv[1].set(v2); argv[2].set(loc); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } AutoValueArray<2> argv(cx); argv[0].set(v1); argv[1].set(v2); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } bool callback(HandleValue fun, HandleValue v1, HandleValue v2, HandleValue v3, TokenPos *pos, MutableHandleValue dst) { if (saveLoc) { RootedValue loc(cx); if (!newNodeLoc(pos, &loc)) return false; AutoValueArray<4> argv(cx); argv[0].set(v1); argv[1].set(v2); argv[2].set(v3); argv[3].set(loc); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } AutoValueArray<3> argv(cx); argv[0].set(v1); argv[1].set(v2); argv[2].set(v3); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } bool callback(HandleValue fun, HandleValue v1, HandleValue v2, HandleValue v3, HandleValue v4, TokenPos *pos, MutableHandleValue dst) { if (saveLoc) { RootedValue loc(cx); if (!newNodeLoc(pos, &loc)) return false; AutoValueArray<5> argv(cx); argv[0].set(v1); argv[1].set(v2); argv[2].set(v3); argv[3].set(v4); argv[4].set(loc); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } AutoValueArray<4> argv(cx); argv[0].set(v1); argv[1].set(v2); argv[2].set(v3); argv[3].set(v4); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } bool callback(HandleValue fun, HandleValue v1, HandleValue v2, HandleValue v3, HandleValue v4, HandleValue v5, TokenPos *pos, MutableHandleValue dst) { if (saveLoc) { RootedValue loc(cx); if (!newNodeLoc(pos, &loc)) return false; AutoValueArray<6> argv(cx); argv[0].set(v1); argv[1].set(v2); argv[2].set(v3); argv[3].set(v4); argv[4].set(v5); argv[5].set(loc); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } AutoValueArray<5> argv(cx); argv[0].set(v1); argv[1].set(v2); argv[2].set(v3); argv[3].set(v4); argv[4].set(v5); return Invoke(cx, userv, fun, argv.length(), argv.begin(), dst); } // WARNING: Returning a Handle is non-standard, but it works in this case // because both |v| and |UndefinedHandleValue| are definitely rooted on a // previous stack frame (i.e. we're just choosing between two // already-rooted values). HandleValue opt(HandleValue v) { JS_ASSERT_IF(v.isMagic(), v.whyMagic() == JS_SERIALIZE_NO_NODE); return v.isMagic(JS_SERIALIZE_NO_NODE) ? JS::UndefinedHandleValue : v; } bool atomValue(const char *s, MutableHandleValue dst) { /* * Bug 575416: instead of Atomize, lookup constant atoms in tbl file */ RootedAtom atom(cx, Atomize(cx, s, strlen(s))); if (!atom) return false; dst.setString(atom); return true; } bool newObject(MutableHandleObject dst) { RootedObject nobj(cx, NewBuiltinClassInstance(cx, &JSObject::class_)); if (!nobj) return false; dst.set(nobj); return true; } bool newArray(NodeVector &elts, MutableHandleValue dst); bool newNode(ASTType type, TokenPos *pos, MutableHandleObject dst); bool newNode(ASTType type, TokenPos *pos, MutableHandleValue dst) { RootedObject node(cx); return newNode(type, pos, &node) && setResult(node, dst); } bool newNode(ASTType type, TokenPos *pos, const char *childName, HandleValue child, MutableHandleValue dst) { RootedObject node(cx); return newNode(type, pos, &node) && setProperty(node, childName, child) && setResult(node, dst); } bool newNode(ASTType type, TokenPos *pos, const char *childName1, HandleValue child1, const char *childName2, HandleValue child2, MutableHandleValue dst) { RootedObject node(cx); return newNode(type, pos, &node) && setProperty(node, childName1, child1) && setProperty(node, childName2, child2) && setResult(node, dst); } bool newNode(ASTType type, TokenPos *pos, const char *childName1, HandleValue child1, const char *childName2, HandleValue child2, const char *childName3, HandleValue child3, MutableHandleValue dst) { RootedObject node(cx); return newNode(type, pos, &node) && setProperty(node, childName1, child1) && setProperty(node, childName2, child2) && setProperty(node, childName3, child3) && setResult(node, dst); } bool newNode(ASTType type, TokenPos *pos, const char *childName1, HandleValue child1, const char *childName2, HandleValue child2, const char *childName3, HandleValue child3, const char *childName4, HandleValue child4, MutableHandleValue dst) { RootedObject node(cx); return newNode(type, pos, &node) && setProperty(node, childName1, child1) && setProperty(node, childName2, child2) && setProperty(node, childName3, child3) && setProperty(node, childName4, child4) && setResult(node, dst); } bool newNode(ASTType type, TokenPos *pos, const char *childName1, HandleValue child1, const char *childName2, HandleValue child2, const char *childName3, HandleValue child3, const char *childName4, HandleValue child4, const char *childName5, HandleValue child5, MutableHandleValue dst) { RootedObject node(cx); return newNode(type, pos, &node) && setProperty(node, childName1, child1) && setProperty(node, childName2, child2) && setProperty(node, childName3, child3) && setProperty(node, childName4, child4) && setProperty(node, childName5, child5) && setResult(node, dst); } bool newNode(ASTType type, TokenPos *pos, const char *childName1, HandleValue child1, const char *childName2, HandleValue child2, const char *childName3, HandleValue child3, const char *childName4, HandleValue child4, const char *childName5, HandleValue child5, const char *childName6, HandleValue child6, MutableHandleValue dst) { RootedObject node(cx); return newNode(type, pos, &node) && setProperty(node, childName1, child1) && setProperty(node, childName2, child2) && setProperty(node, childName3, child3) && setProperty(node, childName4, child4) && setProperty(node, childName5, child5) && setProperty(node, childName6, child6) && setResult(node, dst); } bool newNode(ASTType type, TokenPos *pos, const char *childName1, HandleValue child1, const char *childName2, HandleValue child2, const char *childName3, HandleValue child3, const char *childName4, HandleValue child4, const char *childName5, HandleValue child5, const char *childName6, HandleValue child6, const char *childName7, HandleValue child7, MutableHandleValue dst) { RootedObject node(cx); return newNode(type, pos, &node) && setProperty(node, childName1, child1) && setProperty(node, childName2, child2) && setProperty(node, childName3, child3) && setProperty(node, childName4, child4) && setProperty(node, childName5, child5) && setProperty(node, childName6, child6) && setProperty(node, childName7, child7) && setResult(node, dst); } bool listNode(ASTType type, const char *propName, NodeVector &elts, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(elts, &array)) return false; RootedValue cb(cx, callbacks[type]); if (!cb.isNull()) return callback(cb, array, pos, dst); return newNode(type, pos, propName, array, dst); } bool setProperty(HandleObject obj, const char *name, HandleValue val) { JS_ASSERT_IF(val.isMagic(), val.whyMagic() == JS_SERIALIZE_NO_NODE); /* * Bug 575416: instead of Atomize, lookup constant atoms in tbl file */ RootedAtom atom(cx, Atomize(cx, name, strlen(name))); if (!atom) return false; /* Represent "no node" as null and ensure users are not exposed to magic values. */ RootedValue optVal(cx, val.isMagic(JS_SERIALIZE_NO_NODE) ? NullValue() : val); return JSObject::defineProperty(cx, obj, atom->asPropertyName(), optVal); } bool newNodeLoc(TokenPos *pos, MutableHandleValue dst); bool setNodeLoc(HandleObject node, TokenPos *pos); bool setResult(HandleObject obj, MutableHandleValue dst) { JS_ASSERT(obj); dst.setObject(*obj); return true; } public: /* * All of the public builder methods take as their last two * arguments a nullable token position and a non-nullable, rooted * outparam. * * Any Value arguments representing optional subnodes may be a * JS_SERIALIZE_NO_NODE magic value. */ /* * misc nodes */ bool program(NodeVector &elts, TokenPos *pos, MutableHandleValue dst); bool literal(HandleValue val, TokenPos *pos, MutableHandleValue dst); bool identifier(HandleValue name, TokenPos *pos, MutableHandleValue dst); bool function(ASTType type, TokenPos *pos, HandleValue id, NodeVector &args, NodeVector &defaults, HandleValue body, HandleValue rest, bool isGenerator, bool isExpression, MutableHandleValue dst); bool variableDeclarator(HandleValue id, HandleValue init, TokenPos *pos, MutableHandleValue dst); bool switchCase(HandleValue expr, NodeVector &elts, TokenPos *pos, MutableHandleValue dst); bool catchClause(HandleValue var, HandleValue guard, HandleValue body, TokenPos *pos, MutableHandleValue dst); bool propertyInitializer(HandleValue key, HandleValue val, PropKind kind, bool isShorthand, bool isMethod, TokenPos *pos, MutableHandleValue dst); /* * statements */ bool blockStatement(NodeVector &elts, TokenPos *pos, MutableHandleValue dst); bool expressionStatement(HandleValue expr, TokenPos *pos, MutableHandleValue dst); bool emptyStatement(TokenPos *pos, MutableHandleValue dst); bool ifStatement(HandleValue test, HandleValue cons, HandleValue alt, TokenPos *pos, MutableHandleValue dst); bool breakStatement(HandleValue label, TokenPos *pos, MutableHandleValue dst); bool continueStatement(HandleValue label, TokenPos *pos, MutableHandleValue dst); bool labeledStatement(HandleValue label, HandleValue stmt, TokenPos *pos, MutableHandleValue dst); bool throwStatement(HandleValue arg, TokenPos *pos, MutableHandleValue dst); bool returnStatement(HandleValue arg, TokenPos *pos, MutableHandleValue dst); bool forStatement(HandleValue init, HandleValue test, HandleValue update, HandleValue stmt, TokenPos *pos, MutableHandleValue dst); bool forInStatement(HandleValue var, HandleValue expr, HandleValue stmt, bool isForEach, TokenPos *pos, MutableHandleValue dst); bool forOfStatement(HandleValue var, HandleValue expr, HandleValue stmt, TokenPos *pos, MutableHandleValue dst); bool withStatement(HandleValue expr, HandleValue stmt, TokenPos *pos, MutableHandleValue dst); bool whileStatement(HandleValue test, HandleValue stmt, TokenPos *pos, MutableHandleValue dst); bool doWhileStatement(HandleValue stmt, HandleValue test, TokenPos *pos, MutableHandleValue dst); bool switchStatement(HandleValue disc, NodeVector &elts, bool lexical, TokenPos *pos, MutableHandleValue dst); bool tryStatement(HandleValue body, NodeVector &guarded, HandleValue unguarded, HandleValue finally, TokenPos *pos, MutableHandleValue dst); bool debuggerStatement(TokenPos *pos, MutableHandleValue dst); bool letStatement(NodeVector &head, HandleValue stmt, TokenPos *pos, MutableHandleValue dst); bool importDeclaration(NodeVector &elts, HandleValue moduleSpec, TokenPos *pos, MutableHandleValue dst); bool importSpecifier(HandleValue importName, HandleValue bindingName, TokenPos *pos, MutableHandleValue dst); bool exportDeclaration(HandleValue decl, NodeVector &elts, HandleValue moduleSpec, TokenPos *pos, MutableHandleValue dst); bool exportSpecifier(HandleValue bindingName, HandleValue exportName, TokenPos *pos, MutableHandleValue dst); bool exportBatchSpecifier(TokenPos *pos, MutableHandleValue dst); /* * expressions */ bool binaryExpression(BinaryOperator op, HandleValue left, HandleValue right, TokenPos *pos, MutableHandleValue dst); bool unaryExpression(UnaryOperator op, HandleValue expr, TokenPos *pos, MutableHandleValue dst); bool assignmentExpression(AssignmentOperator op, HandleValue lhs, HandleValue rhs, TokenPos *pos, MutableHandleValue dst); bool updateExpression(HandleValue expr, bool incr, bool prefix, TokenPos *pos, MutableHandleValue dst); bool logicalExpression(bool lor, HandleValue left, HandleValue right, TokenPos *pos, MutableHandleValue dst); bool conditionalExpression(HandleValue test, HandleValue cons, HandleValue alt, TokenPos *pos, MutableHandleValue dst); bool sequenceExpression(NodeVector &elts, TokenPos *pos, MutableHandleValue dst); bool newExpression(HandleValue callee, NodeVector &args, TokenPos *pos, MutableHandleValue dst); bool callExpression(HandleValue callee, NodeVector &args, TokenPos *pos, MutableHandleValue dst); bool memberExpression(bool computed, HandleValue expr, HandleValue member, TokenPos *pos, MutableHandleValue dst); bool arrayExpression(NodeVector &elts, TokenPos *pos, MutableHandleValue dst); bool templateLiteral(NodeVector &elts, TokenPos *pos, MutableHandleValue dst); bool taggedTemplate(HandleValue callee, NodeVector &args, TokenPos *pos, MutableHandleValue dst); bool callSiteObj(NodeVector &raw, NodeVector &cooked, TokenPos *pos, MutableHandleValue dst); bool spreadExpression(HandleValue expr, TokenPos *pos, MutableHandleValue dst); bool computedName(HandleValue name, TokenPos *pos, MutableHandleValue dst); bool objectExpression(NodeVector &elts, TokenPos *pos, MutableHandleValue dst); bool thisExpression(TokenPos *pos, MutableHandleValue dst); bool yieldExpression(HandleValue arg, YieldKind kind, TokenPos *pos, MutableHandleValue dst); bool comprehensionBlock(HandleValue patt, HandleValue src, bool isForEach, bool isForOf, TokenPos *pos, MutableHandleValue dst); bool comprehensionExpression(HandleValue body, NodeVector &blocks, HandleValue filter, TokenPos *pos, MutableHandleValue dst); bool generatorExpression(HandleValue body, NodeVector &blocks, HandleValue filter, TokenPos *pos, MutableHandleValue dst); bool letExpression(NodeVector &head, HandleValue expr, TokenPos *pos, MutableHandleValue dst); /* * declarations */ bool variableDeclaration(NodeVector &elts, VarDeclKind kind, TokenPos *pos, MutableHandleValue dst); /* * patterns */ bool arrayPattern(NodeVector &elts, TokenPos *pos, MutableHandleValue dst); bool objectPattern(NodeVector &elts, TokenPos *pos, MutableHandleValue dst); bool propertyPattern(HandleValue key, HandleValue patt, bool isShorthand, TokenPos *pos, MutableHandleValue dst); }; } /* anonymous namespace */ bool NodeBuilder::newNode(ASTType type, TokenPos *pos, MutableHandleObject dst) { JS_ASSERT(type > AST_ERROR && type < AST_LIMIT); RootedValue tv(cx); RootedObject node(cx, NewBuiltinClassInstance(cx, &JSObject::class_)); if (!node || !setNodeLoc(node, pos) || !atomValue(nodeTypeNames[type], &tv) || !setProperty(node, "type", tv)) { return false; } dst.set(node); return true; } bool NodeBuilder::newArray(NodeVector &elts, MutableHandleValue dst) { const size_t len = elts.length(); if (len > UINT32_MAX) { js_ReportAllocationOverflow(cx); return false; } RootedObject array(cx, NewDenseAllocatedArray(cx, uint32_t(len))); if (!array) return false; for (size_t i = 0; i < len; i++) { RootedValue val(cx, elts[i]); JS_ASSERT_IF(val.isMagic(), val.whyMagic() == JS_SERIALIZE_NO_NODE); /* Represent "no node" as an array hole by not adding the value. */ if (val.isMagic(JS_SERIALIZE_NO_NODE)) continue; if (!JSObject::setElement(cx, array, array, i, &val, false)) return false; } dst.setObject(*array); return true; } bool NodeBuilder::newNodeLoc(TokenPos *pos, MutableHandleValue dst) { if (!pos) { dst.setNull(); return true; } RootedObject loc(cx); RootedObject to(cx); RootedValue val(cx); if (!newObject(&loc)) return false; dst.setObject(*loc); uint32_t startLineNum, startColumnIndex; uint32_t endLineNum, endColumnIndex; tokenStream->srcCoords.lineNumAndColumnIndex(pos->begin, &startLineNum, &startColumnIndex); tokenStream->srcCoords.lineNumAndColumnIndex(pos->end, &endLineNum, &endColumnIndex); if (!newObject(&to)) return false; val.setObject(*to); if (!setProperty(loc, "start", val)) return false; val.setNumber(startLineNum); if (!setProperty(to, "line", val)) return false; val.setNumber(startColumnIndex); if (!setProperty(to, "column", val)) return false; if (!newObject(&to)) return false; val.setObject(*to); if (!setProperty(loc, "end", val)) return false; val.setNumber(endLineNum); if (!setProperty(to, "line", val)) return false; val.setNumber(endColumnIndex); if (!setProperty(to, "column", val)) return false; if (!setProperty(loc, "source", srcval)) return false; return true; } bool NodeBuilder::setNodeLoc(HandleObject node, TokenPos *pos) { if (!saveLoc) { RootedValue nullVal(cx, NullValue()); setProperty(node, "loc", nullVal); return true; } RootedValue loc(cx); return newNodeLoc(pos, &loc) && setProperty(node, "loc", loc); } bool NodeBuilder::program(NodeVector &elts, TokenPos *pos, MutableHandleValue dst) { return listNode(AST_PROGRAM, "body", elts, pos, dst); } bool NodeBuilder::blockStatement(NodeVector &elts, TokenPos *pos, MutableHandleValue dst) { return listNode(AST_BLOCK_STMT, "body", elts, pos, dst); } bool NodeBuilder::expressionStatement(HandleValue expr, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_EXPR_STMT]); if (!cb.isNull()) return callback(cb, expr, pos, dst); return newNode(AST_EXPR_STMT, pos, "expression", expr, dst); } bool NodeBuilder::emptyStatement(TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_EMPTY_STMT]); if (!cb.isNull()) return callback(cb, pos, dst); return newNode(AST_EMPTY_STMT, pos, dst); } bool NodeBuilder::ifStatement(HandleValue test, HandleValue cons, HandleValue alt, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_IF_STMT]); if (!cb.isNull()) return callback(cb, test, cons, opt(alt), pos, dst); return newNode(AST_IF_STMT, pos, "test", test, "consequent", cons, "alternate", alt, dst); } bool NodeBuilder::breakStatement(HandleValue label, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_BREAK_STMT]); if (!cb.isNull()) return callback(cb, opt(label), pos, dst); return newNode(AST_BREAK_STMT, pos, "label", label, dst); } bool NodeBuilder::continueStatement(HandleValue label, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_CONTINUE_STMT]); if (!cb.isNull()) return callback(cb, opt(label), pos, dst); return newNode(AST_CONTINUE_STMT, pos, "label", label, dst); } bool NodeBuilder::labeledStatement(HandleValue label, HandleValue stmt, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_LAB_STMT]); if (!cb.isNull()) return callback(cb, label, stmt, pos, dst); return newNode(AST_LAB_STMT, pos, "label", label, "body", stmt, dst); } bool NodeBuilder::throwStatement(HandleValue arg, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_THROW_STMT]); if (!cb.isNull()) return callback(cb, arg, pos, dst); return newNode(AST_THROW_STMT, pos, "argument", arg, dst); } bool NodeBuilder::returnStatement(HandleValue arg, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_RETURN_STMT]); if (!cb.isNull()) return callback(cb, opt(arg), pos, dst); return newNode(AST_RETURN_STMT, pos, "argument", arg, dst); } bool NodeBuilder::forStatement(HandleValue init, HandleValue test, HandleValue update, HandleValue stmt, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_FOR_STMT]); if (!cb.isNull()) return callback(cb, opt(init), opt(test), opt(update), stmt, pos, dst); return newNode(AST_FOR_STMT, pos, "init", init, "test", test, "update", update, "body", stmt, dst); } bool NodeBuilder::forInStatement(HandleValue var, HandleValue expr, HandleValue stmt, bool isForEach, TokenPos *pos, MutableHandleValue dst) { RootedValue isForEachVal(cx, BooleanValue(isForEach)); RootedValue cb(cx, callbacks[AST_FOR_IN_STMT]); if (!cb.isNull()) return callback(cb, var, expr, stmt, isForEachVal, pos, dst); return newNode(AST_FOR_IN_STMT, pos, "left", var, "right", expr, "body", stmt, "each", isForEachVal, dst); } bool NodeBuilder::forOfStatement(HandleValue var, HandleValue expr, HandleValue stmt, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_FOR_OF_STMT]); if (!cb.isNull()) return callback(cb, var, expr, stmt, pos, dst); return newNode(AST_FOR_OF_STMT, pos, "left", var, "right", expr, "body", stmt, dst); } bool NodeBuilder::withStatement(HandleValue expr, HandleValue stmt, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_WITH_STMT]); if (!cb.isNull()) return callback(cb, expr, stmt, pos, dst); return newNode(AST_WITH_STMT, pos, "object", expr, "body", stmt, dst); } bool NodeBuilder::whileStatement(HandleValue test, HandleValue stmt, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_WHILE_STMT]); if (!cb.isNull()) return callback(cb, test, stmt, pos, dst); return newNode(AST_WHILE_STMT, pos, "test", test, "body", stmt, dst); } bool NodeBuilder::doWhileStatement(HandleValue stmt, HandleValue test, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_DO_STMT]); if (!cb.isNull()) return callback(cb, stmt, test, pos, dst); return newNode(AST_DO_STMT, pos, "body", stmt, "test", test, dst); } bool NodeBuilder::switchStatement(HandleValue disc, NodeVector &elts, bool lexical, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(elts, &array)) return false; RootedValue lexicalVal(cx, BooleanValue(lexical)); RootedValue cb(cx, callbacks[AST_SWITCH_STMT]); if (!cb.isNull()) return callback(cb, disc, array, lexicalVal, pos, dst); return newNode(AST_SWITCH_STMT, pos, "discriminant", disc, "cases", array, "lexical", lexicalVal, dst); } bool NodeBuilder::tryStatement(HandleValue body, NodeVector &guarded, HandleValue unguarded, HandleValue finally, TokenPos *pos, MutableHandleValue dst) { RootedValue guardedHandlers(cx); if (!newArray(guarded, &guardedHandlers)) return false; RootedValue cb(cx, callbacks[AST_TRY_STMT]); if (!cb.isNull()) return callback(cb, body, guardedHandlers, unguarded, opt(finally), pos, dst); return newNode(AST_TRY_STMT, pos, "block", body, "guardedHandlers", guardedHandlers, "handler", unguarded, "finalizer", finally, dst); } bool NodeBuilder::debuggerStatement(TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_DEBUGGER_STMT]); if (!cb.isNull()) return callback(cb, pos, dst); return newNode(AST_DEBUGGER_STMT, pos, dst); } bool NodeBuilder::binaryExpression(BinaryOperator op, HandleValue left, HandleValue right, TokenPos *pos, MutableHandleValue dst) { JS_ASSERT(op > BINOP_ERR && op < BINOP_LIMIT); RootedValue opName(cx); if (!atomValue(binopNames[op], &opName)) return false; RootedValue cb(cx, callbacks[AST_BINARY_EXPR]); if (!cb.isNull()) return callback(cb, opName, left, right, pos, dst); return newNode(AST_BINARY_EXPR, pos, "operator", opName, "left", left, "right", right, dst); } bool NodeBuilder::unaryExpression(UnaryOperator unop, HandleValue expr, TokenPos *pos, MutableHandleValue dst) { JS_ASSERT(unop > UNOP_ERR && unop < UNOP_LIMIT); RootedValue opName(cx); if (!atomValue(unopNames[unop], &opName)) return false; RootedValue cb(cx, callbacks[AST_UNARY_EXPR]); if (!cb.isNull()) return callback(cb, opName, expr, pos, dst); RootedValue trueVal(cx, BooleanValue(true)); return newNode(AST_UNARY_EXPR, pos, "operator", opName, "argument", expr, "prefix", trueVal, dst); } bool NodeBuilder::assignmentExpression(AssignmentOperator aop, HandleValue lhs, HandleValue rhs, TokenPos *pos, MutableHandleValue dst) { JS_ASSERT(aop > AOP_ERR && aop < AOP_LIMIT); RootedValue opName(cx); if (!atomValue(aopNames[aop], &opName)) return false; RootedValue cb(cx, callbacks[AST_ASSIGN_EXPR]); if (!cb.isNull()) return callback(cb, opName, lhs, rhs, pos, dst); return newNode(AST_ASSIGN_EXPR, pos, "operator", opName, "left", lhs, "right", rhs, dst); } bool NodeBuilder::updateExpression(HandleValue expr, bool incr, bool prefix, TokenPos *pos, MutableHandleValue dst) { RootedValue opName(cx); if (!atomValue(incr ? "++" : "--", &opName)) return false; RootedValue prefixVal(cx, BooleanValue(prefix)); RootedValue cb(cx, callbacks[AST_UPDATE_EXPR]); if (!cb.isNull()) return callback(cb, expr, opName, prefixVal, pos, dst); return newNode(AST_UPDATE_EXPR, pos, "operator", opName, "argument", expr, "prefix", prefixVal, dst); } bool NodeBuilder::logicalExpression(bool lor, HandleValue left, HandleValue right, TokenPos *pos, MutableHandleValue dst) { RootedValue opName(cx); if (!atomValue(lor ? "||" : "&&", &opName)) return false; RootedValue cb(cx, callbacks[AST_LOGICAL_EXPR]); if (!cb.isNull()) return callback(cb, opName, left, right, pos, dst); return newNode(AST_LOGICAL_EXPR, pos, "operator", opName, "left", left, "right", right, dst); } bool NodeBuilder::conditionalExpression(HandleValue test, HandleValue cons, HandleValue alt, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_COND_EXPR]); if (!cb.isNull()) return callback(cb, test, cons, alt, pos, dst); return newNode(AST_COND_EXPR, pos, "test", test, "consequent", cons, "alternate", alt, dst); } bool NodeBuilder::sequenceExpression(NodeVector &elts, TokenPos *pos, MutableHandleValue dst) { return listNode(AST_LIST_EXPR, "expressions", elts, pos, dst); } bool NodeBuilder::callExpression(HandleValue callee, NodeVector &args, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(args, &array)) return false; RootedValue cb(cx, callbacks[AST_CALL_EXPR]); if (!cb.isNull()) return callback(cb, callee, array, pos, dst); return newNode(AST_CALL_EXPR, pos, "callee", callee, "arguments", array, dst); } bool NodeBuilder::newExpression(HandleValue callee, NodeVector &args, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(args, &array)) return false; RootedValue cb(cx, callbacks[AST_NEW_EXPR]); if (!cb.isNull()) return callback(cb, callee, array, pos, dst); return newNode(AST_NEW_EXPR, pos, "callee", callee, "arguments", array, dst); } bool NodeBuilder::memberExpression(bool computed, HandleValue expr, HandleValue member, TokenPos *pos, MutableHandleValue dst) { RootedValue computedVal(cx, BooleanValue(computed)); RootedValue cb(cx, callbacks[AST_MEMBER_EXPR]); if (!cb.isNull()) return callback(cb, computedVal, expr, member, pos, dst); return newNode(AST_MEMBER_EXPR, pos, "object", expr, "property", member, "computed", computedVal, dst); } bool NodeBuilder::arrayExpression(NodeVector &elts, TokenPos *pos, MutableHandleValue dst) { return listNode(AST_ARRAY_EXPR, "elements", elts, pos, dst); } bool NodeBuilder::callSiteObj(NodeVector &raw, NodeVector &cooked, TokenPos *pos, MutableHandleValue dst) { RootedValue rawVal(cx); if (!newArray(raw, &rawVal)) return false; RootedValue cookedVal(cx); if (!newArray(cooked, &cookedVal)) return false; return newNode(AST_CALL_SITE_OBJ, pos, "raw", rawVal, "cooked", cookedVal, dst); } bool NodeBuilder::taggedTemplate(HandleValue callee, NodeVector &args, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(args, &array)) return false; return newNode(AST_TAGGED_TEMPLATE, pos, "callee", callee, "arguments", array, dst); } bool NodeBuilder::templateLiteral(NodeVector &elts, TokenPos *pos, MutableHandleValue dst) { return listNode(AST_TEMPLATE_LITERAL, "elements", elts, pos, dst); } bool NodeBuilder::computedName(HandleValue name, TokenPos *pos, MutableHandleValue dst) { return newNode(AST_COMPUTED_NAME, pos, "name", name, dst); } bool NodeBuilder::spreadExpression(HandleValue expr, TokenPos *pos, MutableHandleValue dst) { return newNode(AST_SPREAD_EXPR, pos, "expression", expr, dst); } bool NodeBuilder::propertyPattern(HandleValue key, HandleValue patt, bool isShorthand, TokenPos *pos, MutableHandleValue dst) { RootedValue kindName(cx); if (!atomValue("init", &kindName)) return false; RootedValue isShorthandVal(cx, BooleanValue(isShorthand)); RootedValue cb(cx, callbacks[AST_PROP_PATT]); if (!cb.isNull()) return callback(cb, key, patt, pos, dst); return newNode(AST_PROP_PATT, pos, "key", key, "value", patt, "kind", kindName, "shorthand", isShorthandVal, dst); } bool NodeBuilder::propertyInitializer(HandleValue key, HandleValue val, PropKind kind, bool isShorthand, bool isMethod, TokenPos *pos, MutableHandleValue dst) { RootedValue kindName(cx); if (!atomValue(kind == PROP_INIT ? "init" : kind == PROP_GETTER ? "get" : "set", &kindName)) { return false; } RootedValue isShorthandVal(cx, BooleanValue(isShorthand)); RootedValue isMethodVal(cx, BooleanValue(isMethod)); RootedValue cb(cx, callbacks[AST_PROPERTY]); if (!cb.isNull()) return callback(cb, kindName, key, val, pos, dst); return newNode(AST_PROPERTY, pos, "key", key, "value", val, "kind", kindName, "method", isMethodVal, "shorthand", isShorthandVal, dst); } bool NodeBuilder::objectExpression(NodeVector &elts, TokenPos *pos, MutableHandleValue dst) { return listNode(AST_OBJECT_EXPR, "properties", elts, pos, dst); } bool NodeBuilder::thisExpression(TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_THIS_EXPR]); if (!cb.isNull()) return callback(cb, pos, dst); return newNode(AST_THIS_EXPR, pos, dst); } bool NodeBuilder::yieldExpression(HandleValue arg, YieldKind kind, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_YIELD_EXPR]); RootedValue delegateVal(cx); switch (kind) { case Delegating: delegateVal = BooleanValue(true); break; case NotDelegating: delegateVal = BooleanValue(false); break; } if (!cb.isNull()) return callback(cb, opt(arg), delegateVal, pos, dst); return newNode(AST_YIELD_EXPR, pos, "argument", arg, "delegate", delegateVal, dst); } bool NodeBuilder::comprehensionBlock(HandleValue patt, HandleValue src, bool isForEach, bool isForOf, TokenPos *pos, MutableHandleValue dst) { RootedValue isForEachVal(cx, BooleanValue(isForEach)); RootedValue isForOfVal(cx, BooleanValue(isForOf)); RootedValue cb(cx, callbacks[AST_COMP_BLOCK]); if (!cb.isNull()) return callback(cb, patt, src, isForEachVal, isForOfVal, pos, dst); return newNode(AST_COMP_BLOCK, pos, "left", patt, "right", src, "each", isForEachVal, "of", isForOfVal, dst); } bool NodeBuilder::comprehensionExpression(HandleValue body, NodeVector &blocks, HandleValue filter, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(blocks, &array)) return false; RootedValue cb(cx, callbacks[AST_COMP_EXPR]); if (!cb.isNull()) return callback(cb, body, array, opt(filter), pos, dst); return newNode(AST_COMP_EXPR, pos, "body", body, "blocks", array, "filter", filter, dst); } bool NodeBuilder::generatorExpression(HandleValue body, NodeVector &blocks, HandleValue filter, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(blocks, &array)) return false; RootedValue cb(cx, callbacks[AST_GENERATOR_EXPR]); if (!cb.isNull()) return callback(cb, body, array, opt(filter), pos, dst); return newNode(AST_GENERATOR_EXPR, pos, "body", body, "blocks", array, "filter", filter, dst); } bool NodeBuilder::letExpression(NodeVector &head, HandleValue expr, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(head, &array)) return false; RootedValue cb(cx, callbacks[AST_LET_EXPR]); if (!cb.isNull()) return callback(cb, array, expr, pos, dst); return newNode(AST_LET_EXPR, pos, "head", array, "body", expr, dst); } bool NodeBuilder::letStatement(NodeVector &head, HandleValue stmt, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(head, &array)) return false; RootedValue cb(cx, callbacks[AST_LET_STMT]); if (!cb.isNull()) return callback(cb, array, stmt, pos, dst); return newNode(AST_LET_STMT, pos, "head", array, "body", stmt, dst); } bool NodeBuilder::importDeclaration(NodeVector &elts, HandleValue moduleSpec, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(elts, &array)) return false; RootedValue cb(cx, callbacks[AST_IMPORT_DECL]); if (!cb.isNull()) return callback(cb, array, moduleSpec, pos, dst); return newNode(AST_IMPORT_DECL, pos, "specifiers", array, "source", moduleSpec, dst); } bool NodeBuilder::importSpecifier(HandleValue importName, HandleValue bindingName, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_IMPORT_SPEC]); if (!cb.isNull()) return callback(cb, importName, bindingName, pos, dst); return newNode(AST_IMPORT_SPEC, pos, "id", importName, "name", bindingName, dst); } bool NodeBuilder::exportDeclaration(HandleValue decl, NodeVector &elts, HandleValue moduleSpec, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx, NullValue()); if (decl.isNull() && !newArray(elts, &array)) return false; RootedValue cb(cx, callbacks[AST_IMPORT_DECL]); if (!cb.isNull()) return callback(cb, decl, array, moduleSpec, pos, dst); return newNode(AST_EXPORT_DECL, pos, "declaration", decl, "specifiers", array, "source", moduleSpec, dst); } bool NodeBuilder::exportSpecifier(HandleValue bindingName, HandleValue exportName, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_EXPORT_SPEC]); if (!cb.isNull()) return callback(cb, bindingName, exportName, pos, dst); return newNode(AST_EXPORT_SPEC, pos, "id", bindingName, "name", exportName, dst); } bool NodeBuilder::exportBatchSpecifier(TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_EXPORT_BATCH_SPEC]); if (!cb.isNull()) return callback(cb, pos, dst); return newNode(AST_EXPORT_BATCH_SPEC, pos, dst); } bool NodeBuilder::variableDeclaration(NodeVector &elts, VarDeclKind kind, TokenPos *pos, MutableHandleValue dst) { JS_ASSERT(kind > VARDECL_ERR && kind < VARDECL_LIMIT); RootedValue array(cx), kindName(cx); if (!newArray(elts, &array) || !atomValue(kind == VARDECL_CONST ? "const" : kind == VARDECL_LET ? "let" : "var", &kindName)) { return false; } RootedValue cb(cx, callbacks[AST_VAR_DECL]); if (!cb.isNull()) return callback(cb, kindName, array, pos, dst); return newNode(AST_VAR_DECL, pos, "kind", kindName, "declarations", array, dst); } bool NodeBuilder::variableDeclarator(HandleValue id, HandleValue init, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_VAR_DTOR]); if (!cb.isNull()) return callback(cb, id, opt(init), pos, dst); return newNode(AST_VAR_DTOR, pos, "id", id, "init", init, dst); } bool NodeBuilder::switchCase(HandleValue expr, NodeVector &elts, TokenPos *pos, MutableHandleValue dst) { RootedValue array(cx); if (!newArray(elts, &array)) return false; RootedValue cb(cx, callbacks[AST_CASE]); if (!cb.isNull()) return callback(cb, opt(expr), array, pos, dst); return newNode(AST_CASE, pos, "test", expr, "consequent", array, dst); } bool NodeBuilder::catchClause(HandleValue var, HandleValue guard, HandleValue body, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_CATCH]); if (!cb.isNull()) return callback(cb, var, opt(guard), body, pos, dst); return newNode(AST_CATCH, pos, "param", var, "guard", guard, "body", body, dst); } bool NodeBuilder::literal(HandleValue val, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_LITERAL]); if (!cb.isNull()) return callback(cb, val, pos, dst); return newNode(AST_LITERAL, pos, "value", val, dst); } bool NodeBuilder::identifier(HandleValue name, TokenPos *pos, MutableHandleValue dst) { RootedValue cb(cx, callbacks[AST_IDENTIFIER]); if (!cb.isNull()) return callback(cb, name, pos, dst); return newNode(AST_IDENTIFIER, pos, "name", name, dst); } bool NodeBuilder::objectPattern(NodeVector &elts, TokenPos *pos, MutableHandleValue dst) { return listNode(AST_OBJECT_PATT, "properties", elts, pos, dst); } bool NodeBuilder::arrayPattern(NodeVector &elts, TokenPos *pos, MutableHandleValue dst) { return listNode(AST_ARRAY_PATT, "elements", elts, pos, dst); } bool NodeBuilder::function(ASTType type, TokenPos *pos, HandleValue id, NodeVector &args, NodeVector &defaults, HandleValue body, HandleValue rest, bool isGenerator, bool isExpression, MutableHandleValue dst) { RootedValue array(cx), defarray(cx); if (!newArray(args, &array)) return false; if (!newArray(defaults, &defarray)) return false; RootedValue isGeneratorVal(cx, BooleanValue(isGenerator)); RootedValue isExpressionVal(cx, BooleanValue(isExpression)); RootedValue cb(cx, callbacks[type]); if (!cb.isNull()) { return callback(cb, opt(id), array, body, isGeneratorVal, isExpressionVal, pos, dst); } return newNode(type, pos, "id", id, "params", array, "defaults", defarray, "body", body, "rest", rest, "generator", isGeneratorVal, "expression", isExpressionVal, dst); } namespace { /* * Serialization of parse nodes to JavaScript objects. * * All serialization methods take a non-nullable ParseNode pointer. */ class ASTSerializer { JSContext *cx; Parser<FullParseHandler> *parser; NodeBuilder builder; DebugOnly<uint32_t> lineno; Value unrootedAtomContents(JSAtom *atom) { return StringValue(atom ? atom : cx->names().empty); } BinaryOperator binop(ParseNodeKind kind, JSOp op); UnaryOperator unop(ParseNodeKind kind, JSOp op); AssignmentOperator aop(JSOp op); bool statements(ParseNode *pn, NodeVector &elts); bool expressions(ParseNode *pn, NodeVector &elts); bool leftAssociate(ParseNode *pn, MutableHandleValue dst); bool functionArgs(ParseNode *pn, ParseNode *pnargs, ParseNode *pndestruct, ParseNode *pnbody, NodeVector &args, NodeVector &defaults, MutableHandleValue rest); bool sourceElement(ParseNode *pn, MutableHandleValue dst); bool declaration(ParseNode *pn, MutableHandleValue dst); bool variableDeclaration(ParseNode *pn, bool let, MutableHandleValue dst); bool variableDeclarator(ParseNode *pn, VarDeclKind *pkind, MutableHandleValue dst); bool let(ParseNode *pn, bool expr, MutableHandleValue dst); bool importDeclaration(ParseNode *pn, MutableHandleValue dst); bool importSpecifier(ParseNode *pn, MutableHandleValue dst); bool exportDeclaration(ParseNode *pn, MutableHandleValue dst); bool exportSpecifier(ParseNode *pn, MutableHandleValue dst); bool optStatement(ParseNode *pn, MutableHandleValue dst) { if (!pn) { dst.setMagic(JS_SERIALIZE_NO_NODE); return true; } return statement(pn, dst); } bool forInit(ParseNode *pn, MutableHandleValue dst); bool forIn(ParseNode *loop, ParseNode *head, HandleValue var, HandleValue stmt, MutableHandleValue dst); bool forOf(ParseNode *loop, ParseNode *head, HandleValue var, HandleValue stmt, MutableHandleValue dst); bool statement(ParseNode *pn, MutableHandleValue dst); bool blockStatement(ParseNode *pn, MutableHandleValue dst); bool switchStatement(ParseNode *pn, MutableHandleValue dst); bool switchCase(ParseNode *pn, MutableHandleValue dst); bool tryStatement(ParseNode *pn, MutableHandleValue dst); bool catchClause(ParseNode *pn, bool *isGuarded, MutableHandleValue dst); bool optExpression(ParseNode *pn, MutableHandleValue dst) { if (!pn) { dst.setMagic(JS_SERIALIZE_NO_NODE); return true; } return expression(pn, dst); } bool expression(ParseNode *pn, MutableHandleValue dst); bool propertyName(ParseNode *pn, MutableHandleValue dst); bool property(ParseNode *pn, MutableHandleValue dst); bool optIdentifier(HandleAtom atom, TokenPos *pos, MutableHandleValue dst) { if (!atom) { dst.setMagic(JS_SERIALIZE_NO_NODE); return true; } return identifier(atom, pos, dst); } bool identifier(HandleAtom atom, TokenPos *pos, MutableHandleValue dst); bool identifier(ParseNode *pn, MutableHandleValue dst); bool literal(ParseNode *pn, MutableHandleValue dst); bool pattern(ParseNode *pn, VarDeclKind *pkind, MutableHandleValue dst); bool arrayPattern(ParseNode *pn, VarDeclKind *pkind, MutableHandleValue dst); bool objectPattern(ParseNode *pn, VarDeclKind *pkind, MutableHandleValue dst); bool function(ParseNode *pn, ASTType type, MutableHandleValue dst); bool functionArgsAndBody(ParseNode *pn, NodeVector &args, NodeVector &defaults, MutableHandleValue body, MutableHandleValue rest); bool functionBody(ParseNode *pn, TokenPos *pos, MutableHandleValue dst); bool comprehensionBlock(ParseNode *pn, MutableHandleValue dst); bool comprehension(ParseNode *pn, MutableHandleValue dst); bool generatorExpression(ParseNode *pn, MutableHandleValue dst); public: ASTSerializer(JSContext *c, bool l, char const *src, uint32_t ln) : cx(c) , builder(c, l, src) #ifdef DEBUG , lineno(ln) #endif {} bool init(HandleObject userobj) { return builder.init(userobj); } void setParser(Parser<FullParseHandler> *p) { parser = p; builder.setTokenStream(&p->tokenStream); } bool program(ParseNode *pn, MutableHandleValue dst); }; } /* anonymous namespace */ AssignmentOperator ASTSerializer::aop(JSOp op) { switch (op) { case JSOP_NOP: return AOP_ASSIGN; case JSOP_ADD: return AOP_PLUS; case JSOP_SUB: return AOP_MINUS; case JSOP_MUL: return AOP_STAR; case JSOP_DIV: return AOP_DIV; case JSOP_MOD: return AOP_MOD; case JSOP_LSH: return AOP_LSH; case JSOP_RSH: return AOP_RSH; case JSOP_URSH: return AOP_URSH; case JSOP_BITOR: return AOP_BITOR; case JSOP_BITXOR: return AOP_BITXOR; case JSOP_BITAND: return AOP_BITAND; default: return AOP_ERR; } } UnaryOperator ASTSerializer::unop(ParseNodeKind kind, JSOp op) { if (kind == PNK_DELETE) return UNOP_DELETE; switch (op) { case JSOP_NEG: return UNOP_NEG; case JSOP_POS: return UNOP_POS; case JSOP_NOT: return UNOP_NOT; case JSOP_BITNOT: return UNOP_BITNOT; case JSOP_TYPEOF: case JSOP_TYPEOFEXPR: return UNOP_TYPEOF; case JSOP_VOID: return UNOP_VOID; default: return UNOP_ERR; } } BinaryOperator ASTSerializer::binop(ParseNodeKind kind, JSOp op) { switch (kind) { case PNK_LSH: return BINOP_LSH; case PNK_RSH: return BINOP_RSH; case PNK_URSH: return BINOP_URSH; case PNK_LT: return BINOP_LT; case PNK_LE: return BINOP_LE; case PNK_GT: return BINOP_GT; case PNK_GE: return BINOP_GE; case PNK_EQ: return BINOP_EQ; case PNK_NE: return BINOP_NE; case PNK_STRICTEQ: return BINOP_STRICTEQ; case PNK_STRICTNE: return BINOP_STRICTNE; case PNK_ADD: return BINOP_ADD; case PNK_SUB: return BINOP_SUB; case PNK_STAR: return BINOP_STAR; case PNK_DIV: return BINOP_DIV; case PNK_MOD: return BINOP_MOD; case PNK_BITOR: return BINOP_BITOR; case PNK_BITXOR: return BINOP_BITXOR; case PNK_BITAND: return BINOP_BITAND; case PNK_IN: return BINOP_IN; case PNK_INSTANCEOF: return BINOP_INSTANCEOF; default: return BINOP_ERR; } } bool ASTSerializer::statements(ParseNode *pn, NodeVector &elts) { JS_ASSERT(pn->isKind(PNK_STATEMENTLIST)); JS_ASSERT(pn->isArity(PN_LIST)); if (!elts.reserve(pn->pn_count)) return false; for (ParseNode *next = pn->pn_head; next; next = next->pn_next) { JS_ASSERT(pn->pn_pos.encloses(next->pn_pos)); RootedValue elt(cx); if (!sourceElement(next, &elt)) return false; elts.infallibleAppend(elt); } return true; } bool ASTSerializer::expressions(ParseNode *pn, NodeVector &elts) { if (!elts.reserve(pn->pn_count)) return false; for (ParseNode *next = pn->pn_head; next; next = next->pn_next) { JS_ASSERT(pn->pn_pos.encloses(next->pn_pos)); RootedValue elt(cx); if (!expression(next, &elt)) return false; elts.infallibleAppend(elt); } return true; } bool ASTSerializer::blockStatement(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT(pn->isKind(PNK_STATEMENTLIST)); NodeVector stmts(cx); return statements(pn, stmts) && builder.blockStatement(stmts, &pn->pn_pos, dst); } bool ASTSerializer::program(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT(parser->tokenStream.srcCoords.lineNum(pn->pn_pos.begin) == lineno); NodeVector stmts(cx); return statements(pn, stmts) && builder.program(stmts, &pn->pn_pos, dst); } bool ASTSerializer::sourceElement(ParseNode *pn, MutableHandleValue dst) { /* SpiderMonkey allows declarations even in pure statement contexts. */ return statement(pn, dst); } bool ASTSerializer::declaration(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT(pn->isKind(PNK_FUNCTION) || pn->isKind(PNK_VAR) || pn->isKind(PNK_LET) || pn->isKind(PNK_CONST)); switch (pn->getKind()) { case PNK_FUNCTION: return function(pn, AST_FUNC_DECL, dst); case PNK_VAR: case PNK_CONST: return variableDeclaration(pn, false, dst); default: JS_ASSERT(pn->isKind(PNK_LET)); return variableDeclaration(pn, true, dst); } } bool ASTSerializer::variableDeclaration(ParseNode *pn, bool let, MutableHandleValue dst) { JS_ASSERT(let ? pn->isKind(PNK_LET) : (pn->isKind(PNK_VAR) || pn->isKind(PNK_CONST))); /* Later updated to VARDECL_CONST if we find a PND_CONST declarator. */ VarDeclKind kind = let ? VARDECL_LET : VARDECL_VAR; NodeVector dtors(cx); if (!dtors.reserve(pn->pn_count)) return false; for (ParseNode *next = pn->pn_head; next; next = next->pn_next) { RootedValue child(cx); if (!variableDeclarator(next, &kind, &child)) return false; dtors.infallibleAppend(child); } return builder.variableDeclaration(dtors, kind, &pn->pn_pos, dst); } bool ASTSerializer::variableDeclarator(ParseNode *pn, VarDeclKind *pkind, MutableHandleValue dst) { ParseNode *pnleft; ParseNode *pnright; if (pn->isKind(PNK_NAME)) { pnleft = pn; pnright = pn->isUsed() ? nullptr : pn->pn_expr; JS_ASSERT_IF(pnright, pn->pn_pos.encloses(pnright->pn_pos)); } else if (pn->isKind(PNK_ASSIGN)) { pnleft = pn->pn_left; pnright = pn->pn_right; JS_ASSERT(pn->pn_pos.encloses(pnleft->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pnright->pn_pos)); } else { /* This happens for a destructuring declarator in a for-in/of loop. */ pnleft = pn; pnright = nullptr; } RootedValue left(cx), right(cx); return pattern(pnleft, pkind, &left) && optExpression(pnright, &right) && builder.variableDeclarator(left, right, &pn->pn_pos, dst); } bool ASTSerializer::let(ParseNode *pn, bool expr, MutableHandleValue dst) { JS_ASSERT(pn->pn_pos.encloses(pn->pn_left->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_right->pn_pos)); ParseNode *letHead = pn->pn_left; LOCAL_ASSERT(letHead->isArity(PN_LIST)); ParseNode *letBody = pn->pn_right; LOCAL_ASSERT(letBody->isKind(PNK_LEXICALSCOPE)); NodeVector dtors(cx); if (!dtors.reserve(letHead->pn_count)) return false; VarDeclKind kind = VARDECL_LET_HEAD; for (ParseNode *next = letHead->pn_head; next; next = next->pn_next) { RootedValue child(cx); /* * Unlike in |variableDeclaration|, this does not update |kind|; since let-heads do * not contain const declarations, declarators should never have PND_CONST set. */ if (!variableDeclarator(next, &kind, &child)) return false; dtors.infallibleAppend(child); } RootedValue v(cx); return expr ? expression(letBody->pn_expr, &v) && builder.letExpression(dtors, v, &pn->pn_pos, dst) : statement(letBody->pn_expr, &v) && builder.letStatement(dtors, v, &pn->pn_pos, dst); } bool ASTSerializer::importDeclaration(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT(pn->isKind(PNK_IMPORT)); JS_ASSERT(pn->pn_left->isKind(PNK_IMPORT_SPEC_LIST)); JS_ASSERT(pn->pn_right->isKind(PNK_STRING)); NodeVector elts(cx); if (!elts.reserve(pn->pn_count)) return false; for (ParseNode *next = pn->pn_left->pn_head; next; next = next->pn_next) { RootedValue elt(cx); if (!importSpecifier(next, &elt)) return false; elts.infallibleAppend(elt); } RootedValue moduleSpec(cx); return literal(pn->pn_right, &moduleSpec) && builder.importDeclaration(elts, moduleSpec, &pn->pn_pos, dst); } bool ASTSerializer::importSpecifier(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT(pn->isKind(PNK_IMPORT_SPEC)); RootedValue importName(cx); RootedValue bindingName(cx); return identifier(pn->pn_left, &importName) && identifier(pn->pn_right, &bindingName) && builder.importSpecifier(importName, bindingName, &pn->pn_pos, dst); } bool ASTSerializer::exportDeclaration(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT(pn->isKind(PNK_EXPORT) || pn->isKind(PNK_EXPORT_FROM)); JS_ASSERT_IF(pn->isKind(PNK_EXPORT_FROM), pn->pn_right->isKind(PNK_STRING)); RootedValue decl(cx, NullValue()); NodeVector elts(cx); ParseNode *kid = pn->isKind(PNK_EXPORT) ? pn->pn_kid : pn->pn_left; switch (ParseNodeKind kind = kid->getKind()) { case PNK_EXPORT_SPEC_LIST: if (!elts.reserve(pn->pn_count)) return false; for (ParseNode *next = pn->pn_left->pn_head; next; next = next->pn_next) { RootedValue elt(cx); if (next->isKind(PNK_EXPORT_SPEC)) { if (!exportSpecifier(next, &elt)) return false; } else { if (!builder.exportBatchSpecifier(&pn->pn_pos, &elt)) return false; } elts.infallibleAppend(elt); } break; case PNK_FUNCTION: if (!function(kid, AST_FUNC_DECL, &decl)) return false; break; case PNK_VAR: case PNK_CONST: case PNK_LET: if (!variableDeclaration(kid, kind == PNK_LET, &decl)) return false; break; default: LOCAL_NOT_REACHED("unexpected statement type"); } RootedValue moduleSpec(cx, NullValue()); if (pn->isKind(PNK_EXPORT_FROM) && !literal(pn->pn_right, &moduleSpec)) return false; return builder.exportDeclaration(decl, elts, moduleSpec, &pn->pn_pos, dst); } bool ASTSerializer::exportSpecifier(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT(pn->isKind(PNK_EXPORT_SPEC)); RootedValue bindingName(cx); RootedValue exportName(cx); return identifier(pn->pn_left, &bindingName) && identifier(pn->pn_right, &exportName) && builder.exportSpecifier(bindingName, exportName, &pn->pn_pos, dst); } bool ASTSerializer::switchCase(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT_IF(pn->pn_left, pn->pn_pos.encloses(pn->pn_left->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_right->pn_pos)); NodeVector stmts(cx); RootedValue expr(cx); return optExpression(pn->pn_left, &expr) && statements(pn->pn_right, stmts) && builder.switchCase(expr, stmts, &pn->pn_pos, dst); } bool ASTSerializer::switchStatement(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT(pn->pn_pos.encloses(pn->pn_left->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_right->pn_pos)); RootedValue disc(cx); if (!expression(pn->pn_left, &disc)) return false; ParseNode *listNode; bool lexical; if (pn->pn_right->isKind(PNK_LEXICALSCOPE)) { listNode = pn->pn_right->pn_expr; lexical = true; } else { listNode = pn->pn_right; lexical = false; } NodeVector cases(cx); if (!cases.reserve(listNode->pn_count)) return false; for (ParseNode *next = listNode->pn_head; next; next = next->pn_next) { RootedValue child(cx); if (!switchCase(next, &child)) return false; cases.infallibleAppend(child); } return builder.switchStatement(disc, cases, lexical, &pn->pn_pos, dst); } bool ASTSerializer::catchClause(ParseNode *pn, bool *isGuarded, MutableHandleValue dst) { JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid1->pn_pos)); JS_ASSERT_IF(pn->pn_kid2, pn->pn_pos.encloses(pn->pn_kid2->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid3->pn_pos)); RootedValue var(cx), guard(cx), body(cx); if (!pattern(pn->pn_kid1, nullptr, &var) || !optExpression(pn->pn_kid2, &guard)) { return false; } *isGuarded = !guard.isMagic(JS_SERIALIZE_NO_NODE); return statement(pn->pn_kid3, &body) && builder.catchClause(var, guard, body, &pn->pn_pos, dst); } bool ASTSerializer::tryStatement(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid1->pn_pos)); JS_ASSERT_IF(pn->pn_kid2, pn->pn_pos.encloses(pn->pn_kid2->pn_pos)); JS_ASSERT_IF(pn->pn_kid3, pn->pn_pos.encloses(pn->pn_kid3->pn_pos)); RootedValue body(cx); if (!statement(pn->pn_kid1, &body)) return false; NodeVector guarded(cx); RootedValue unguarded(cx, NullValue()); if (pn->pn_kid2) { if (!guarded.reserve(pn->pn_kid2->pn_count)) return false; for (ParseNode *next = pn->pn_kid2->pn_head; next; next = next->pn_next) { RootedValue clause(cx); bool isGuarded; if (!catchClause(next->pn_expr, &isGuarded, &clause)) return false; if (isGuarded) guarded.infallibleAppend(clause); else unguarded = clause; } } RootedValue finally(cx); return optStatement(pn->pn_kid3, &finally) && builder.tryStatement(body, guarded, unguarded, finally, &pn->pn_pos, dst); } bool ASTSerializer::forInit(ParseNode *pn, MutableHandleValue dst) { if (!pn) { dst.setMagic(JS_SERIALIZE_NO_NODE); return true; } return (pn->isKind(PNK_VAR) || pn->isKind(PNK_CONST)) ? variableDeclaration(pn, false, dst) : expression(pn, dst); } bool ASTSerializer::forOf(ParseNode *loop, ParseNode *head, HandleValue var, HandleValue stmt, MutableHandleValue dst) { RootedValue expr(cx); return expression(head->pn_kid3, &expr) && builder.forOfStatement(var, expr, stmt, &loop->pn_pos, dst); } bool ASTSerializer::forIn(ParseNode *loop, ParseNode *head, HandleValue var, HandleValue stmt, MutableHandleValue dst) { RootedValue expr(cx); bool isForEach = loop->pn_iflags & JSITER_FOREACH; return expression(head->pn_kid3, &expr) && builder.forInStatement(var, expr, stmt, isForEach, &loop->pn_pos, dst); } bool ASTSerializer::statement(ParseNode *pn, MutableHandleValue dst) { JS_CHECK_RECURSION(cx, return false); switch (pn->getKind()) { case PNK_FUNCTION: case PNK_VAR: case PNK_CONST: return declaration(pn, dst); case PNK_LET: return pn->isArity(PN_BINARY) ? let(pn, false, dst) : declaration(pn, dst); case PNK_IMPORT: return importDeclaration(pn, dst); case PNK_EXPORT: case PNK_EXPORT_FROM: return exportDeclaration(pn, dst); case PNK_NAME: LOCAL_ASSERT(pn->isUsed()); return statement(pn->pn_lexdef, dst); case PNK_SEMI: if (pn->pn_kid) { RootedValue expr(cx); return expression(pn->pn_kid, &expr) && builder.expressionStatement(expr, &pn->pn_pos, dst); } return builder.emptyStatement(&pn->pn_pos, dst); case PNK_LEXICALSCOPE: pn = pn->pn_expr; if (!pn->isKind(PNK_STATEMENTLIST)) return statement(pn, dst); /* FALL THROUGH */ case PNK_STATEMENTLIST: return blockStatement(pn, dst); case PNK_IF: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid1->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid2->pn_pos)); JS_ASSERT_IF(pn->pn_kid3, pn->pn_pos.encloses(pn->pn_kid3->pn_pos)); RootedValue test(cx), cons(cx), alt(cx); return expression(pn->pn_kid1, &test) && statement(pn->pn_kid2, &cons) && optStatement(pn->pn_kid3, &alt) && builder.ifStatement(test, cons, alt, &pn->pn_pos, dst); } case PNK_SWITCH: return switchStatement(pn, dst); case PNK_TRY: return tryStatement(pn, dst); case PNK_WITH: case PNK_WHILE: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_left->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_right->pn_pos)); RootedValue expr(cx), stmt(cx); return expression(pn->pn_left, &expr) && statement(pn->pn_right, &stmt) && (pn->isKind(PNK_WITH) ? builder.withStatement(expr, stmt, &pn->pn_pos, dst) : builder.whileStatement(expr, stmt, &pn->pn_pos, dst)); } case PNK_DOWHILE: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_left->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_right->pn_pos)); RootedValue stmt(cx), test(cx); return statement(pn->pn_left, &stmt) && expression(pn->pn_right, &test) && builder.doWhileStatement(stmt, test, &pn->pn_pos, dst); } case PNK_FOR: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_left->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_right->pn_pos)); ParseNode *head = pn->pn_left; JS_ASSERT_IF(head->pn_kid1, head->pn_pos.encloses(head->pn_kid1->pn_pos)); JS_ASSERT_IF(head->pn_kid2, head->pn_pos.encloses(head->pn_kid2->pn_pos)); JS_ASSERT_IF(head->pn_kid3, head->pn_pos.encloses(head->pn_kid3->pn_pos)); RootedValue stmt(cx); if (!statement(pn->pn_right, &stmt)) return false; if (head->isKind(PNK_FORIN)) { RootedValue var(cx); return (!head->pn_kid1 ? pattern(head->pn_kid2, nullptr, &var) : head->pn_kid1->isKind(PNK_LEXICALSCOPE) ? variableDeclaration(head->pn_kid1->pn_expr, true, &var) : variableDeclaration(head->pn_kid1, false, &var)) && forIn(pn, head, var, stmt, dst); } if (head->isKind(PNK_FOROF)) { RootedValue var(cx); return (!head->pn_kid1 ? pattern(head->pn_kid2, nullptr, &var) : head->pn_kid1->isKind(PNK_LEXICALSCOPE) ? variableDeclaration(head->pn_kid1->pn_expr, true, &var) : variableDeclaration(head->pn_kid1, false, &var)) && forOf(pn, head, var, stmt, dst); } RootedValue init(cx), test(cx), update(cx); return forInit(head->pn_kid1, &init) && optExpression(head->pn_kid2, &test) && optExpression(head->pn_kid3, &update) && builder.forStatement(init, test, update, stmt, &pn->pn_pos, dst); } /* Synthesized by the parser when a for-in loop contains a variable initializer. */ case PNK_SEQ: { LOCAL_ASSERT(pn->pn_count == 2); ParseNode *prelude = pn->pn_head; ParseNode *loop = prelude->pn_next; LOCAL_ASSERT(prelude->isKind(PNK_VAR) && loop->isKind(PNK_FOR)); RootedValue var(cx); if (!variableDeclaration(prelude, false, &var)) return false; ParseNode *head = loop->pn_left; JS_ASSERT(head->isKind(PNK_FORIN)); RootedValue stmt(cx); return statement(loop->pn_right, &stmt) && forIn(loop, head, var, stmt, dst); } case PNK_BREAK: case PNK_CONTINUE: { RootedValue label(cx); RootedAtom pnAtom(cx, pn->pn_atom); return optIdentifier(pnAtom, nullptr, &label) && (pn->isKind(PNK_BREAK) ? builder.breakStatement(label, &pn->pn_pos, dst) : builder.continueStatement(label, &pn->pn_pos, dst)); } case PNK_LABEL: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_expr->pn_pos)); RootedValue label(cx), stmt(cx); RootedAtom pnAtom(cx, pn->as<LabeledStatement>().label()); return identifier(pnAtom, nullptr, &label) && statement(pn->pn_expr, &stmt) && builder.labeledStatement(label, stmt, &pn->pn_pos, dst); } case PNK_THROW: case PNK_RETURN: { JS_ASSERT_IF(pn->pn_kid, pn->pn_pos.encloses(pn->pn_kid->pn_pos)); RootedValue arg(cx); return optExpression(pn->pn_kid, &arg) && (pn->isKind(PNK_THROW) ? builder.throwStatement(arg, &pn->pn_pos, dst) : builder.returnStatement(arg, &pn->pn_pos, dst)); } case PNK_DEBUGGER: return builder.debuggerStatement(&pn->pn_pos, dst); case PNK_NOP: return builder.emptyStatement(&pn->pn_pos, dst); default: LOCAL_NOT_REACHED("unexpected statement type"); } } bool ASTSerializer::leftAssociate(ParseNode *pn, MutableHandleValue dst) { JS_ASSERT(pn->isArity(PN_LIST)); JS_ASSERT(pn->pn_count >= 1); ParseNodeKind kind = pn->getKind(); bool lor = kind == PNK_OR; bool logop = lor || (kind == PNK_AND); ParseNode *head = pn->pn_head; RootedValue left(cx); if (!expression(head, &left)) return false; for (ParseNode *next = head->pn_next; next; next = next->pn_next) { RootedValue right(cx); if (!expression(next, &right)) return false; TokenPos subpos(pn->pn_pos.begin, next->pn_pos.end); if (logop) { if (!builder.logicalExpression(lor, left, right, &subpos, &left)) return false; } else { BinaryOperator op = binop(pn->getKind(), pn->getOp()); LOCAL_ASSERT(op > BINOP_ERR && op < BINOP_LIMIT); if (!builder.binaryExpression(op, left, right, &subpos, &left)) return false; } } dst.set(left); return true; } bool ASTSerializer::comprehensionBlock(ParseNode *pn, MutableHandleValue dst) { LOCAL_ASSERT(pn->isArity(PN_BINARY)); ParseNode *in = pn->pn_left; LOCAL_ASSERT(in && (in->isKind(PNK_FORIN) || in->isKind(PNK_FOROF))); bool isForEach = pn->pn_iflags & JSITER_FOREACH; bool isForOf = in->isKind(PNK_FOROF); RootedValue patt(cx), src(cx); return pattern(in->pn_kid2, nullptr, &patt) && expression(in->pn_kid3, &src) && builder.comprehensionBlock(patt, src, isForEach, isForOf, &in->pn_pos, dst); } bool ASTSerializer::comprehension(ParseNode *pn, MutableHandleValue dst) { LOCAL_ASSERT(pn->isKind(PNK_FOR)); NodeVector blocks(cx); ParseNode *next = pn; while (next->isKind(PNK_FOR)) { RootedValue block(cx); if (!comprehensionBlock(next, &block) || !blocks.append(block)) return false; next = next->pn_right; } RootedValue filter(cx, MagicValue(JS_SERIALIZE_NO_NODE)); if (next->isKind(PNK_IF)) { if (!optExpression(next->pn_kid1, &filter)) return false; next = next->pn_kid2; } else if (next->isKind(PNK_STATEMENTLIST) && next->pn_count == 0) { /* FoldConstants optimized away the push. */ NodeVector empty(cx); return builder.arrayExpression(empty, &pn->pn_pos, dst); } LOCAL_ASSERT(next->isKind(PNK_ARRAYPUSH)); RootedValue body(cx); return expression(next->pn_kid, &body) && builder.comprehensionExpression(body, blocks, filter, &pn->pn_pos, dst); } bool ASTSerializer::generatorExpression(ParseNode *pn, MutableHandleValue dst) { LOCAL_ASSERT(pn->isKind(PNK_FOR)); NodeVector blocks(cx); ParseNode *next = pn; while (next->isKind(PNK_FOR)) { RootedValue block(cx); if (!comprehensionBlock(next, &block) || !blocks.append(block)) return false; next = next->pn_right; } RootedValue filter(cx, MagicValue(JS_SERIALIZE_NO_NODE)); if (next->isKind(PNK_IF)) { if (!optExpression(next->pn_kid1, &filter)) return false; next = next->pn_kid2; } LOCAL_ASSERT(next->isKind(PNK_SEMI) && next->pn_kid->isKind(PNK_YIELD) && next->pn_kid->pn_kid); RootedValue body(cx); return expression(next->pn_kid->pn_kid, &body) && builder.generatorExpression(body, blocks, filter, &pn->pn_pos, dst); } bool ASTSerializer::expression(ParseNode *pn, MutableHandleValue dst) { JS_CHECK_RECURSION(cx, return false); switch (pn->getKind()) { case PNK_FUNCTION: { ASTType type = pn->pn_funbox->function()->isArrow() ? AST_ARROW_EXPR : AST_FUNC_EXPR; return function(pn, type, dst); } case PNK_COMMA: { NodeVector exprs(cx); return expressions(pn, exprs) && builder.sequenceExpression(exprs, &pn->pn_pos, dst); } case PNK_CONDITIONAL: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid1->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid2->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid3->pn_pos)); RootedValue test(cx), cons(cx), alt(cx); return expression(pn->pn_kid1, &test) && expression(pn->pn_kid2, &cons) && expression(pn->pn_kid3, &alt) && builder.conditionalExpression(test, cons, alt, &pn->pn_pos, dst); } case PNK_OR: case PNK_AND: { if (pn->isArity(PN_BINARY)) { JS_ASSERT(pn->pn_pos.encloses(pn->pn_left->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_right->pn_pos)); RootedValue left(cx), right(cx); return expression(pn->pn_left, &left) && expression(pn->pn_right, &right) && builder.logicalExpression(pn->isKind(PNK_OR), left, right, &pn->pn_pos, dst); } return leftAssociate(pn, dst); } case PNK_PREINCREMENT: case PNK_PREDECREMENT: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid->pn_pos)); bool inc = pn->isKind(PNK_PREINCREMENT); RootedValue expr(cx); return expression(pn->pn_kid, &expr) && builder.updateExpression(expr, inc, true, &pn->pn_pos, dst); } case PNK_POSTINCREMENT: case PNK_POSTDECREMENT: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid->pn_pos)); bool inc = pn->isKind(PNK_POSTINCREMENT); RootedValue expr(cx); return expression(pn->pn_kid, &expr) && builder.updateExpression(expr, inc, false, &pn->pn_pos, dst); } case PNK_ASSIGN: case PNK_ADDASSIGN: case PNK_SUBASSIGN: case PNK_BITORASSIGN: case PNK_BITXORASSIGN: case PNK_BITANDASSIGN: case PNK_LSHASSIGN: case PNK_RSHASSIGN: case PNK_URSHASSIGN: case PNK_MULASSIGN: case PNK_DIVASSIGN: case PNK_MODASSIGN: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_left->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_right->pn_pos)); AssignmentOperator op = aop(pn->getOp()); LOCAL_ASSERT(op > AOP_ERR && op < AOP_LIMIT); RootedValue lhs(cx), rhs(cx); return pattern(pn->pn_left, nullptr, &lhs) && expression(pn->pn_right, &rhs) && builder.assignmentExpression(op, lhs, rhs, &pn->pn_pos, dst); } case PNK_ADD: case PNK_SUB: case PNK_STRICTEQ: case PNK_EQ: case PNK_STRICTNE: case PNK_NE: case PNK_LT: case PNK_LE: case PNK_GT: case PNK_GE: case PNK_LSH: case PNK_RSH: case PNK_URSH: case PNK_STAR: case PNK_DIV: case PNK_MOD: case PNK_BITOR: case PNK_BITXOR: case PNK_BITAND: case PNK_IN: case PNK_INSTANCEOF: if (pn->isArity(PN_BINARY)) { JS_ASSERT(pn->pn_pos.encloses(pn->pn_left->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_right->pn_pos)); BinaryOperator op = binop(pn->getKind(), pn->getOp()); LOCAL_ASSERT(op > BINOP_ERR && op < BINOP_LIMIT); RootedValue left(cx), right(cx); return expression(pn->pn_left, &left) && expression(pn->pn_right, &right) && builder.binaryExpression(op, left, right, &pn->pn_pos, dst); } return leftAssociate(pn, dst); case PNK_DELETE: case PNK_TYPEOF: case PNK_VOID: case PNK_NOT: case PNK_BITNOT: case PNK_POS: case PNK_NEG: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid->pn_pos)); UnaryOperator op = unop(pn->getKind(), pn->getOp()); LOCAL_ASSERT(op > UNOP_ERR && op < UNOP_LIMIT); RootedValue expr(cx); return expression(pn->pn_kid, &expr) && builder.unaryExpression(op, expr, &pn->pn_pos, dst); } #if JS_HAS_GENERATOR_EXPRS case PNK_GENEXP: return generatorExpression(pn->generatorExpr(), dst); #endif case PNK_NEW: case PNK_TAGGED_TEMPLATE: case PNK_CALL: { ParseNode *next = pn->pn_head; JS_ASSERT(pn->pn_pos.encloses(next->pn_pos)); RootedValue callee(cx); if (!expression(next, &callee)) return false; NodeVector args(cx); if (!args.reserve(pn->pn_count - 1)) return false; for (next = next->pn_next; next; next = next->pn_next) { JS_ASSERT(pn->pn_pos.encloses(next->pn_pos)); RootedValue arg(cx); if (!expression(next, &arg)) return false; args.infallibleAppend(arg); } if (pn->getKind() == PNK_TAGGED_TEMPLATE) return builder.taggedTemplate(callee, args, &pn->pn_pos, dst); return pn->isKind(PNK_NEW) ? builder.newExpression(callee, args, &pn->pn_pos, dst) : builder.callExpression(callee, args, &pn->pn_pos, dst); } case PNK_DOT: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_expr->pn_pos)); RootedValue expr(cx), id(cx); RootedAtom pnAtom(cx, pn->pn_atom); return expression(pn->pn_expr, &expr) && identifier(pnAtom, nullptr, &id) && builder.memberExpression(false, expr, id, &pn->pn_pos, dst); } case PNK_ELEM: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_left->pn_pos)); JS_ASSERT(pn->pn_pos.encloses(pn->pn_right->pn_pos)); RootedValue left(cx), right(cx); return expression(pn->pn_left, &left) && expression(pn->pn_right, &right) && builder.memberExpression(true, left, right, &pn->pn_pos, dst); } case PNK_CALLSITEOBJ: { NodeVector raw(cx); if (!raw.reserve(pn->pn_head->pn_count)) return false; for (ParseNode *next = pn->pn_head->pn_head; next; next = next->pn_next) { JS_ASSERT(pn->pn_pos.encloses(next->pn_pos)); RootedValue expr(cx); expr.setString(next->pn_atom); raw.infallibleAppend(expr); } NodeVector cooked(cx); if (!cooked.reserve(pn->pn_count - 1)) return false; for (ParseNode *next = pn->pn_head->pn_next; next; next = next->pn_next) { JS_ASSERT(pn->pn_pos.encloses(next->pn_pos)); RootedValue expr(cx); expr.setString(next->pn_atom); cooked.infallibleAppend(expr); } return builder.callSiteObj(raw, cooked, &pn->pn_pos, dst); } case PNK_ARRAY: { NodeVector elts(cx); if (!elts.reserve(pn->pn_count)) return false; for (ParseNode *next = pn->pn_head; next; next = next->pn_next) { JS_ASSERT(pn->pn_pos.encloses(next->pn_pos)); if (next->isKind(PNK_ELISION)) { elts.infallibleAppend(NullValue()); } else { RootedValue expr(cx); if (!expression(next, &expr)) return false; elts.infallibleAppend(expr); } } return builder.arrayExpression(elts, &pn->pn_pos, dst); } case PNK_SPREAD: { RootedValue expr(cx); return expression(pn->pn_kid, &expr) && builder.spreadExpression(expr, &pn->pn_pos, dst); } case PNK_COMPUTED_NAME: { RootedValue name(cx); return expression(pn->pn_kid, &name) && builder.computedName(name, &pn->pn_pos, dst); } case PNK_OBJECT: { NodeVector elts(cx); if (!elts.reserve(pn->pn_count)) return false; for (ParseNode *next = pn->pn_head; next; next = next->pn_next) { JS_ASSERT(pn->pn_pos.encloses(next->pn_pos)); RootedValue prop(cx); if (!property(next, &prop)) return false; elts.infallibleAppend(prop); } return builder.objectExpression(elts, &pn->pn_pos, dst); } case PNK_NAME: return identifier(pn, dst); case PNK_THIS: return builder.thisExpression(&pn->pn_pos, dst); case PNK_TEMPLATE_STRING_LIST: { NodeVector elts(cx); if (!elts.reserve(pn->pn_count)) return false; for (ParseNode *next = pn->pn_head; next; next = next->pn_next) { JS_ASSERT(pn->pn_pos.encloses(next->pn_pos)); RootedValue expr(cx); if (!expression(next, &expr)) return false; elts.infallibleAppend(expr); } return builder.templateLiteral(elts, &pn->pn_pos, dst); } case PNK_TEMPLATE_STRING: case PNK_STRING: case PNK_REGEXP: case PNK_NUMBER: case PNK_TRUE: case PNK_FALSE: case PNK_NULL: return literal(pn, dst); case PNK_YIELD_STAR: { JS_ASSERT(pn->pn_pos.encloses(pn->pn_kid->pn_pos)); RootedValue arg(cx); return expression(pn->pn_kid, &arg) && builder.yieldExpression(arg, Delegating, &pn->pn_pos, dst); } case PNK_YIELD: { JS_ASSERT_IF(pn->pn_kid, pn->pn_pos.encloses(pn->pn_kid->pn_pos)); RootedValue arg(cx); return optExpression(pn->pn_kid, &arg) && builder.yieldExpression(arg, NotDelegating, &pn->pn_pos, dst); } case PNK_ARRAYCOMP: JS_ASSERT(pn->pn_pos.encloses(pn->pn_head->pn_pos)); /* NB: it's no longer the case that pn_count could be 2. */ LOCAL_ASSERT(pn->pn_count == 1); LOCAL_ASSERT(pn->pn_head->isKind(PNK_LEXICALSCOPE)); return comprehension(pn->pn_head->pn_expr, dst); case PNK_LET: return let(pn, true, dst); default: LOCAL_NOT_REACHED("unexpected expression type"); } } bool ASTSerializer::propertyName(ParseNode *pn, MutableHandleValue dst) { if (pn->isKind(PNK_COMPUTED_NAME)) return expression(pn, dst); if (pn->isKind(PNK_NAME)) return identifier(pn, dst); LOCAL_ASSERT(pn->isKind(PNK_STRING) || pn->isKind(PNK_NUMBER)); return literal(pn, dst); } bool ASTSerializer::property(ParseNode *pn, MutableHandleValue dst) { PropKind kind; switch (pn->getOp()) { case JSOP_INITPROP: kind = PROP_INIT; break; case JSOP_INITPROP_GETTER: kind = PROP_GETTER; break; case JSOP_INITPROP_SETTER: kind = PROP_SETTER; break; default: LOCAL_NOT_REACHED("unexpected object-literal property"); } bool isShorthand = pn->isKind(PNK_SHORTHAND); bool isMethod = pn->pn_right->isKind(PNK_FUNCTION) && kind == PROP_INIT; RootedValue key(cx), val(cx); return propertyName(pn->pn_left, &key) && expression(pn->pn_right, &val) && builder.propertyInitializer(key, val, kind, isShorthand, isMethod, &pn->pn_pos, dst); } bool ASTSerializer::literal(ParseNode *pn, MutableHandleValue dst) { RootedValue val(cx); switch (pn->getKind()) { case PNK_TEMPLATE_STRING: case PNK_STRING: val.setString(pn->pn_atom); break; case PNK_REGEXP: { RootedObject re1(cx, pn->as<RegExpLiteral>().objbox()->object); LOCAL_ASSERT(re1 && re1->is<RegExpObject>()); RootedObject re2(cx, CloneRegExpObject(cx, re1)); if (!re2) return false; val.setObject(*re2); break; } case PNK_NUMBER: val.setNumber(pn->pn_dval); break; case PNK_NULL: val.setNull(); break; case PNK_TRUE: val.setBoolean(true); break; case PNK_FALSE: val.setBoolean(false); break; default: LOCAL_NOT_REACHED("unexpected literal type"); } return builder.literal(val, &pn->pn_pos, dst); } bool ASTSerializer::arrayPattern(ParseNode *pn, VarDeclKind *pkind, MutableHandleValue dst) { JS_ASSERT(pn->isKind(PNK_ARRAY)); NodeVector elts(cx); if (!elts.reserve(pn->pn_count)) return false; for (ParseNode *next = pn->pn_head; next; next = next->pn_next) { if (next->isKind(PNK_ELISION)) { elts.infallibleAppend(NullValue()); } else if (next->isKind(PNK_SPREAD)) { RootedValue target(cx); RootedValue spread(cx); if (!pattern(next->pn_kid, pkind, &target)) return false; if(!builder.spreadExpression(target, &next->pn_pos, &spread)) return false; elts.infallibleAppend(spread); } else { RootedValue patt(cx); if (!pattern(next, pkind, &patt)) return false; elts.infallibleAppend(patt); } } return builder.arrayPattern(elts, &pn->pn_pos, dst); } bool ASTSerializer::objectPattern(ParseNode *pn, VarDeclKind *pkind, MutableHandleValue dst) { JS_ASSERT(pn->isKind(PNK_OBJECT)); NodeVector elts(cx); if (!elts.reserve(pn->pn_count)) return false; for (ParseNode *next = pn->pn_head; next; next = next->pn_next) { LOCAL_ASSERT(next->isOp(JSOP_INITPROP)); RootedValue key(cx), patt(cx), prop(cx); if (!propertyName(next->pn_left, &key) || !pattern(next->pn_right, pkind, &patt) || !builder.propertyPattern(key, patt, next->isKind(PNK_SHORTHAND), &next->pn_pos, &prop)) { return false; } elts.infallibleAppend(prop); } return builder.objectPattern(elts, &pn->pn_pos, dst); } bool ASTSerializer::pattern(ParseNode *pn, VarDeclKind *pkind, MutableHandleValue dst) { JS_CHECK_RECURSION(cx, return false); switch (pn->getKind()) { case PNK_OBJECT: return objectPattern(pn, pkind, dst); case PNK_ARRAY: return arrayPattern(pn, pkind, dst); case PNK_NAME: if (pkind && (pn->pn_dflags & PND_CONST)) *pkind = VARDECL_CONST; /* FALL THROUGH */ default: return expression(pn, dst); } } bool ASTSerializer::identifier(HandleAtom atom, TokenPos *pos, MutableHandleValue dst) { RootedValue atomContentsVal(cx, unrootedAtomContents(atom)); return builder.identifier(atomContentsVal, pos, dst); } bool ASTSerializer::identifier(ParseNode *pn, MutableHandleValue dst) { LOCAL_ASSERT(pn->isArity(PN_NAME) || pn->isArity(PN_NULLARY)); LOCAL_ASSERT(pn->pn_atom); RootedAtom pnAtom(cx, pn->pn_atom); return identifier(pnAtom, &pn->pn_pos, dst); } bool ASTSerializer::function(ParseNode *pn, ASTType type, MutableHandleValue dst) { RootedFunction func(cx, pn->pn_funbox->function()); // FIXME: Provide more information (legacy generator vs star generator). bool isGenerator = pn->pn_funbox->isGenerator(); bool isExpression = #if JS_HAS_EXPR_CLOSURES func->isExprClosure(); #else false; #endif RootedValue id(cx); RootedAtom funcAtom(cx, func->atom()); if (!optIdentifier(funcAtom, nullptr, &id)) return false; NodeVector args(cx); NodeVector defaults(cx); RootedValue body(cx), rest(cx); if (func->hasRest()) rest.setUndefined(); else rest.setNull(); return functionArgsAndBody(pn->pn_body, args, defaults, &body, &rest) && builder.function(type, &pn->pn_pos, id, args, defaults, body, rest, isGenerator, isExpression, dst); } bool ASTSerializer::functionArgsAndBody(ParseNode *pn, NodeVector &args, NodeVector &defaults, MutableHandleValue body, MutableHandleValue rest) { ParseNode *pnargs; ParseNode *pnbody; /* Extract the args and body separately. */ if (pn->isKind(PNK_ARGSBODY)) { pnargs = pn; pnbody = pn->last(); } else { pnargs = nullptr; pnbody = pn; } ParseNode *pndestruct; /* Extract the destructuring assignments. */ if (pnbody->isArity(PN_LIST) && (pnbody->pn_xflags & PNX_DESTRUCT)) { ParseNode *head = pnbody->pn_head; LOCAL_ASSERT(head && head->isKind(PNK_SEMI)); pndestruct = head->pn_kid; LOCAL_ASSERT(pndestruct); LOCAL_ASSERT(pndestruct->isKind(PNK_VAR)); } else { pndestruct = nullptr; } /* Serialize the arguments and body. */ switch (pnbody->getKind()) { case PNK_RETURN: /* expression closure, no destructured args */ return functionArgs(pn, pnargs, nullptr, pnbody, args, defaults, rest) && expression(pnbody->pn_kid, body); case PNK_SEQ: /* expression closure with destructured args */ { ParseNode *pnstart = pnbody->pn_head->pn_next; LOCAL_ASSERT(pnstart && pnstart->isKind(PNK_RETURN)); return functionArgs(pn, pnargs, pndestruct, pnbody, args, defaults, rest) && expression(pnstart->pn_kid, body); } case PNK_STATEMENTLIST: /* statement closure */ { ParseNode *pnstart = (pnbody->pn_xflags & PNX_DESTRUCT) ? pnbody->pn_head->pn_next : pnbody->pn_head; return functionArgs(pn, pnargs, pndestruct, pnbody, args, defaults, rest) && functionBody(pnstart, &pnbody->pn_pos, body); } default: LOCAL_NOT_REACHED("unexpected function contents"); } } bool ASTSerializer::functionArgs(ParseNode *pn, ParseNode *pnargs, ParseNode *pndestruct, ParseNode *pnbody, NodeVector &args, NodeVector &defaults, MutableHandleValue rest) { uint32_t i = 0; ParseNode *arg = pnargs ? pnargs->pn_head : nullptr; ParseNode *destruct = pndestruct ? pndestruct->pn_head : nullptr; RootedValue node(cx); /* * Arguments are found in potentially two different places: 1) the * argsbody sequence (which ends with the body node), or 2) a * destructuring initialization at the beginning of the body. Loop * |arg| through the argsbody and |destruct| through the initial * destructuring assignments, stopping only when we've exhausted * both. */ while ((arg && arg != pnbody) || destruct) { if (destruct && destruct->pn_right->frameSlot() == i) { if (!pattern(destruct->pn_left, nullptr, &node) || !args.append(node)) return false; destruct = destruct->pn_next; } else if (arg && arg != pnbody) { /* * We don't check that arg->frameSlot() == i since we * can't call that method if the arg def has been turned * into a use, e.g.: * * function(a) { function a() { } } * * There's no other way to ask a non-destructuring arg its * index in the formals list, so we rely on the ability to * ask destructuring args their index above. */ JS_ASSERT(arg->isKind(PNK_NAME) || arg->isKind(PNK_ASSIGN)); ParseNode *argName = arg->isKind(PNK_NAME) ? arg : arg->pn_left; if (!identifier(argName, &node)) return false; if (rest.isUndefined() && arg->pn_next == pnbody) rest.setObject(node.toObject()); else if (!args.append(node)) return false; if (arg->pn_dflags & PND_DEFAULT) { ParseNode *expr = arg->expr(); RootedValue def(cx); if (!expression(expr, &def) || !defaults.append(def)) return false; } arg = arg->pn_next; } else { LOCAL_NOT_REACHED("missing function argument"); } ++i; } JS_ASSERT(!rest.isUndefined()); return true; } bool ASTSerializer::functionBody(ParseNode *pn, TokenPos *pos, MutableHandleValue dst) { NodeVector elts(cx); /* We aren't sure how many elements there are up front, so we'll check each append. */ for (ParseNode *next = pn; next; next = next->pn_next) { RootedValue child(cx); if (!sourceElement(next, &child) || !elts.append(child)) return false; } return builder.blockStatement(elts, pos, dst); } static bool reflect_parse(JSContext *cx, uint32_t argc, jsval *vp) { CallArgs args = CallArgsFromVp(argc, vp); if (args.length() < 1) { JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "Reflect.parse", "0", "s"); return false; } RootedString src(cx, ToString<CanGC>(cx, args[0])); if (!src) return false; ScopedJSFreePtr<char> filename; uint32_t lineno = 1; bool loc = true; RootedObject builder(cx); RootedValue arg(cx, args.get(1)); if (!arg.isNullOrUndefined()) { if (!arg.isObject()) { js_ReportValueErrorFlags(cx, JSREPORT_ERROR, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, arg, js::NullPtr(), "not an object", nullptr); return false; } RootedObject config(cx, &arg.toObject()); RootedValue prop(cx); /* config.loc */ RootedId locId(cx, NameToId(cx->names().loc)); RootedValue trueVal(cx, BooleanValue(true)); if (!GetPropertyDefault(cx, config, locId, trueVal, &prop)) return false; loc = ToBoolean(prop); if (loc) { /* config.source */ RootedId sourceId(cx, NameToId(cx->names().source)); RootedValue nullVal(cx, NullValue()); if (!GetPropertyDefault(cx, config, sourceId, nullVal, &prop)) return false; if (!prop.isNullOrUndefined()) { RootedString str(cx, ToString<CanGC>(cx, prop)); if (!str) return false; filename = JS_EncodeString(cx, str); if (!filename) return false; } /* config.line */ RootedId lineId(cx, NameToId(cx->names().line)); RootedValue oneValue(cx, Int32Value(1)); if (!GetPropertyDefault(cx, config, lineId, oneValue, &prop) || !ToUint32(cx, prop, &lineno)) { return false; } } /* config.builder */ RootedId builderId(cx, NameToId(cx->names().builder)); RootedValue nullVal(cx, NullValue()); if (!GetPropertyDefault(cx, config, builderId, nullVal, &prop)) return false; if (!prop.isNullOrUndefined()) { if (!prop.isObject()) { js_ReportValueErrorFlags(cx, JSREPORT_ERROR, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, prop, js::NullPtr(), "not an object", nullptr); return false; } builder = &prop.toObject(); } } /* Extract the builder methods first to report errors before parsing. */ ASTSerializer serialize(cx, loc, filename, lineno); if (!serialize.init(builder)) return false; JSFlatString *flat = src->ensureFlat(cx); if (!flat) return false; AutoStableStringChars flatChars(cx); if (!flatChars.initTwoByte(cx, flat)) return false; CompileOptions options(cx); options.setFileAndLine(filename, lineno); options.setCanLazilyParse(false); mozilla::Range<const jschar> chars = flatChars.twoByteRange(); Parser<FullParseHandler> parser(cx, &cx->tempLifoAlloc(), options, chars.start().get(), chars.length(), /* foldConstants = */ false, nullptr, nullptr); serialize.setParser(&parser); ParseNode *pn = parser.parse(nullptr); if (!pn) return false; RootedValue val(cx); if (!serialize.program(pn, &val)) { args.rval().setNull(); return false; } args.rval().set(val); return true; } JS_PUBLIC_API(JSObject *) JS_InitReflect(JSContext *cx, HandleObject obj) { static const JSFunctionSpec static_methods[] = { JS_FN("parse", reflect_parse, 1, 0), JS_FS_END }; RootedObject proto(cx, obj->as<GlobalObject>().getOrCreateObjectPrototype(cx)); if (!proto) return nullptr; RootedObject Reflect(cx, NewObjectWithGivenProto(cx, &JSObject::class_, proto, obj, SingletonObject)); if (!Reflect) return nullptr; if (!JS_DefineProperty(cx, obj, "Reflect", Reflect, 0, JS_PropertyStub, JS_StrictPropertyStub)) { return nullptr; } if (!JS_DefineFunctions(cx, Reflect, static_methods)) return nullptr; return Reflect; }
51,913
17,703
<filename>tools/testdata/check_format/clang_format_on.cc namespace Envoy { // clang-format off // Some ignored content. // clang-format on // Over enthusiastic spaces should be fixed after clang-format is turned on // Too many spaces. Here. } // namespace Envoy
80
494
<gh_stars>100-1000 # BSD 3-Clause License # # Copyright (C) 2021 THL A29 Limited, a Tencent company. 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 psutil authors 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. import logging import unittest import torch from transformers import BertConfig, BertForSequenceClassification from common import distributed_test from examples.data_loader import get_bert_data_loader from patrickstar.runtime import initialize_engine from patrickstar.utils import logger logger.setLevel(logging.WARNING) def bert_model( batch_size=32, hidden_dim=768, sequence_length=512, num_layer=12, num_head=12, ): # Avoid gpu0 use more memory. # https://discuss.pytorch.org/t/extra-10gb-memory-on-gpu-0-in-ddp-tutorial/118113 rank = torch.distributed.get_rank() torch.cuda.empty_cache() device = torch.device(f"cuda:{torch.cuda.current_device()}") cfg = BertConfig( hidden_size=hidden_dim, intermediate_size=hidden_dim * 4, max_position_embeddings=sequence_length, num_attention_heads=num_head, num_hidden_layers=num_layer, # Set dropout rate to 0 to prevent randomness in training. hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, ) hf_model = BertForSequenceClassification(cfg) hf_model.eval() hf_model.to(device) def model_func(): return BertForSequenceClassification(cfg) config = { # The same format as optimizer config of DeepSpeed # https://www.deepspeed.ai/docs/config-json/#optimizer-parameters "optimizer": { "type": "Adam", "params": { "lr": 0.001, "betas": (0.9, 0.999), "eps": 1e-6, "weight_decay": 0, "use_hybrid_adam": True, }, }, "fp16": { "enabled": True, "loss_scale": 0, "initial_scale_power": 10, "loss_scale_window": 1000, "hysteresis": 2, "min_loss_scale": 1, }, "default_chunk_size": 32 * 1024 * 1024, "release_after_init": True, "use_cpu_embedding": True, } model, _ = initialize_engine(model_func=model_func, local_rank=rank, config=config) model.eval() data_loader = get_bert_data_loader( batch_size=batch_size, total_samples=10000, sequence_length=sequence_length, device=device, is_distrbuted=True, ) batch0 = next(iter(data_loader)) output = hf_model(input_ids=batch0[0], labels=batch0[1]) loss0 = output[0].item() print("loss of huggingface:", loss0) output = model(input_ids=batch0[0], labels=batch0[1]) loss1 = output[0].item() print("loss of patrickstar:", loss1) assert abs(loss1 - loss0) > 1e-3, f"{loss1} vs {loss0}" model.load_state_dict(hf_model.state_dict()) output = model(input_ids=batch0[0], labels=batch0[1]) loss2 = output[0].item() print("loss of patrickstar after load:", loss2) # PatrickStar uses fp16, so there will be some difference. assert abs(loss2 - loss0) < 1e-3, f"{loss2} vs {loss0}, diff: {abs(loss2 - loss0)}" hf_model.load_state_dict(model.state_dict()) output = hf_model(input_ids=batch0[0], labels=batch0[1]) loss3 = output[0].item() print("loss of huggingface after load:", loss3) assert loss3 == loss0, f"{loss3} vs {loss0}" class TestHfCheckpointContext(unittest.TestCase): def setUp(self): pass @distributed_test(world_size=[1], backend="gloo", use_fake_dist=False) def test_hf_checkpoint(self): # 0.11B hidden_dim = 768 sequence_length = 512 num_layer = 6 num_head = 12 batch_size = 2 assert hidden_dim % num_head == 0 bert_model( hidden_dim=hidden_dim, batch_size=batch_size, sequence_length=sequence_length, num_layer=num_layer, num_head=num_head, ) if __name__ == "__main__": unittest.main()
2,250
4,403
package cn.hutool.core.lang; import cn.hutool.core.collection.ConcurrentHashSet; import cn.hutool.core.exceptions.UtilException; import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.StrUtil; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.util.HashSet; import java.util.Set; /** * Snowflake单元测试 * @author Looly * */ public class SnowflakeTest { @Test public void snowflakeTest1(){ //构建Snowflake,提供终端ID和数据中心ID Snowflake idWorker = new Snowflake(0, 0); long nextId = idWorker.nextId(); Assert.assertTrue(nextId > 0); } @Test public void snowflakeTest(){ HashSet<Long> hashSet = new HashSet<>(); //构建Snowflake,提供终端ID和数据中心ID Snowflake idWorker = new Snowflake(0, 0); for (int i = 0; i < 1000; i++) { long id = idWorker.nextId(); hashSet.add(id); } Assert.assertEquals(1000L, hashSet.size()); } @Test public void snowflakeGetTest(){ //构建Snowflake,提供终端ID和数据中心ID Snowflake idWorker = new Snowflake(1, 2); long nextId = idWorker.nextId(); Assert.assertEquals(1, idWorker.getWorkerId(nextId)); Assert.assertEquals(2, idWorker.getDataCenterId(nextId)); Assert.assertTrue(idWorker.getGenerateDateTime(nextId) - System.currentTimeMillis() < 10); } @Test @Ignore public void uniqueTest(){ // 测试并发环境下生成ID是否重复 Snowflake snowflake = IdUtil.getSnowflake(0, 0); Set<Long> ids = new ConcurrentHashSet<>(); ThreadUtil.concurrencyTest(100, () -> { for (int i = 0; i < 5000; i++) { if(false == ids.add(snowflake.nextId())){ throw new UtilException("重复ID!"); } } }); } @Test public void getSnowflakeLengthTest(){ for (int i = 0; i < 1000; i++) { final long l = IdUtil.getSnowflake(0, 0).nextId(); Assert.assertEquals(19, StrUtil.toString(l).length()); } } }
869
4,047
#include <gpgme.h> int main() { printf("gpgme-v%s", gpgme_check_version(NULL)); return 0; }
51
1,467
<gh_stars>1000+ { "version": "2.13.27", "date": "2020-06-01", "entries": [ { "type": "feature", "category": "AWS Key Management Service", "description": "AWS Key Management Service (AWS KMS): If the GenerateDataKeyPair or GenerateDataKeyPairWithoutPlaintext APIs are called on a CMK in a custom key store (origin == AWS_CLOUDHSM), they return an UnsupportedOperationException. If a call to UpdateAlias causes a customer to exceed the Alias resource quota, the UpdateAlias API returns a LimitExceededException." }, { "type": "feature", "category": "Amazon Athena", "description": "This release adds support for connecting Athena to your own Apache Hive Metastores in addition to the AWS Glue Data Catalog. For more information, please see https://docs.aws.amazon.com/athena/latest/ug/connect-to-data-source-hive.html" }, { "type": "feature", "category": "AWS SDK for Java v2", "description": "Updated service endpoint metadata." }, { "type": "feature", "category": "Amazon Elastic MapReduce", "description": "Amazon EMR now supports encrypting log files with AWS Key Management Service (KMS) customer managed keys." }, { "type": "feature", "category": "AWS Maven Lambda Archetype", "description": "Updated the `archetype-lambda` to generate SDK client that uses region from environment variable." }, { "type": "feature", "category": "Amazon WorkLink", "description": "Amazon WorkLink now supports resource tagging for fleets." }, { "type": "feature", "category": "Amazon SageMaker Service", "description": "We are releasing HumanTaskUiArn as a new parameter in CreateLabelingJob and RenderUiTemplate which can take an ARN for a system managed UI to render a task." }, { "type": "feature", "category": "Amazon FSx", "description": "New capabilities to update storage capacity and throughput capacity of your file systems, providing the flexibility to grow file storage and to scale up or down the available performance as needed to meet evolving storage needs over time." } ] }
930
598
<reponame>yangboz/maro<gh_stars>100-1000 # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # native lib import json import os import signal import sys import time import uuid from collections import defaultdict, deque, namedtuple from enum import Enum from typing import Dict, List, Tuple, Union # third party lib import redis # private lib from maro.utils import DummyLogger, InternalLogger from maro.utils.exception.communication_exception import InformationUncompletedError, PeersMissError, PendingToSend from maro.utils.exit_code import KILL_ALL_EXIT_CODE, NON_RESTART_EXIT_CODE from .driver import DriverType, ZmqDriver from .message import Message, NotificationSessionStage, SessionMessage, SessionType, TaskSessionStage from .utils import default_parameters _PEER_INFO = namedtuple("PEER_INFO", ["hash_table_name", "expected_number"]) HOST = default_parameters.proxy.redis.host PORT = default_parameters.proxy.redis.port MAX_RETRIES = default_parameters.proxy.redis.max_retries BASE_RETRY_INTERVAL = default_parameters.proxy.redis.base_retry_interval DELAY_FOR_SLOW_JOINER = default_parameters.proxy.delay_for_slow_joiner ENABLE_REJOIN = default_parameters.proxy.peer_rejoin.enable # Only enable at real k8s cluster or grass cluster PEERS_CATCH_LIFETIME = default_parameters.proxy.peer_rejoin.peers_catch_lifetime ENABLE_MESSAGE_CACHE_FOR_REJOIN = default_parameters.proxy.peer_rejoin.enable_message_cache TIMEOUT_FOR_MINIMAL_PEER_NUMBER = default_parameters.proxy.peer_rejoin.timeout_for_minimal_peer_number MINIMAL_PEERS = default_parameters.proxy.peer_rejoin.minimal_peers IS_REMOVE_FAILED_CONTAINER = default_parameters.proxy.peer_rejoin.is_remove_failed_container MAX_REJOIN_TIMES = default_parameters.proxy.peer_rejoin.max_rejoin_times MAX_LENGTH_FOR_MESSAGE_CACHE = default_parameters.proxy.peer_rejoin.max_length_for_message_cache class Proxy: """The communication module is responsible for receiving and sending messages. There are three ways of sending messages: ``send``, ``scatter``, and ``broadcast``. Also, there are two ways to receive messages from other peers: ``receive`` and ``receive_by_id``. Args: group_name (str): Identifier for the group of all distributed components. component_type (str): Component's type in the current group. expected_peers (Dict): Dict of peers' information which contains peer type and expected number. E.g. Dict['learner': 1, 'actor': 2] driver_type (Enum): A type of communication driver class uses to communicate with other components. Defaults to ``DriverType.ZMQ``. driver_parameters (Dict): The arguments for communication driver class initial. Defaults to None. redis_address (Tuple): Hostname and port of the Redis server. Defaults to ("localhost", 6379). max_retries (int): Maximum number of retries before raising an exception. Defaults to 5. retry_interval_base_value (float): The time interval between attempts. Defaults to 0.1. log_enable (bool): Open internal logger or not. Defaults to True. enable_rejoin (bool): Allow peers rejoin or not. Defaults to False, and must use with maro cli. minimal_peers Union[int, dict]: The minimal number of peers for each peer type. peers_catch_lifetime (int): The lifetime for onboard peers' information. enable_message_cache_for_rejoin (bool): Enable message cache for failed peers or not. Default to False. max_length_for_message_cache (int): The maximal number of cached messages. timeout_for_minimal_peer_number (int): The timeout of waiting enough alive peers. is_remove_failed_container (bool): Enable remove failed containers automatically or not. Default to False. max_rejoin_times (int): The maximal retry times for one peer rejoins. """ def __init__( self, group_name: str, component_type: str, expected_peers: dict, driver_type: DriverType = DriverType.ZMQ, driver_parameters: dict = None, redis_address: Tuple = (HOST, PORT), max_retries: int = MAX_RETRIES, retry_interval_base_value: float = BASE_RETRY_INTERVAL, log_enable: bool = True, enable_rejoin: bool = ENABLE_REJOIN, minimal_peers: Union[int, dict] = MINIMAL_PEERS, peers_catch_lifetime: int = PEERS_CATCH_LIFETIME, enable_message_cache_for_rejoin: bool = ENABLE_MESSAGE_CACHE_FOR_REJOIN, max_length_for_message_cache: int = MAX_LENGTH_FOR_MESSAGE_CACHE, timeout_for_minimal_peer_number: int = TIMEOUT_FOR_MINIMAL_PEER_NUMBER, is_remove_failed_container: bool = IS_REMOVE_FAILED_CONTAINER, max_rejoin_times: int = MAX_REJOIN_TIMES ): self._group_name = group_name self._component_type = component_type self._redis_hash_name = f"{self._group_name}:{self._component_type}" if "COMPONENT_NAME" in os.environ: self._name = os.getenv("COMPONENT_NAME") else: unique_id = str(uuid.uuid1()).replace("-", "") self._name = f"{self._component_type}_proxy_{unique_id}" self._max_retries = max_retries self._retry_interval_base_value = retry_interval_base_value self._log_enable = log_enable self._logger = InternalLogger(component_name=self._name) if self._log_enable else DummyLogger() # TODO:In multiprocess with spawn start method, the driver must be initiated before the Redis. # Otherwise it will cause Error 9: Bad File Descriptor in proxy.__del__(). Root cause not found. # Initialize the driver. if driver_type == DriverType.ZMQ: self._driver = ZmqDriver( component_type=self._component_type, **driver_parameters, logger=self._logger ) if driver_parameters else ZmqDriver(component_type=self._component_type, logger=self._logger) else: self._logger.error(f"Unsupported driver type {driver_type}, please use DriverType class.") sys.exit(NON_RESTART_EXIT_CODE) # Initialize the Redis. self._redis_connection = redis.Redis(host=redis_address[0], port=redis_address[1], socket_keepalive=True) try: self._redis_connection.ping() except Exception as e: self._logger.error(f"{self._name} failure to connect to redis server due to {e}") sys.exit(NON_RESTART_EXIT_CODE) # Record the peer's redis information. self._peers_info_dict = {} for peer_type, number in expected_peers.items(): self._peers_info_dict[peer_type] = _PEER_INFO( hash_table_name=f"{self._group_name}:{peer_type}", expected_number=number ) self._onboard_peer_dict = defaultdict(dict) # Temporary store the message. self._message_cache = defaultdict(list) # Parameters for dynamic peers. self._enable_rejoin = enable_rejoin self._is_remove_failed_container = is_remove_failed_container self._max_rejoin_times = max_rejoin_times if self._enable_rejoin: self._peers_catch_lifetime = peers_catch_lifetime self._timeout_for_minimal_peer_number = timeout_for_minimal_peer_number self._enable_message_cache = enable_message_cache_for_rejoin if self._enable_message_cache: self._message_cache_for_exited_peers = defaultdict( lambda: deque([], maxlen=max_length_for_message_cache) ) if isinstance(minimal_peers, int): self._minimal_peers = { peer_type: max(minimal_peers, 1) for peer_type, peer_info in self._peers_info_dict.items() } elif isinstance(minimal_peers, dict): self._minimal_peers = { peer_type: max(minimal_peers[peer_type], 1) for peer_type, peer_info in self._peers_info_dict.items() } else: self._logger.error("Unsupported minimal peers type, please use integer or dict.") sys.exit(NON_RESTART_EXIT_CODE) self._join() def _signal_handler(self, signum, frame): self._redis_connection.hdel(self._redis_hash_name, self._name) self._logger.critical(f"{self._name} received Signal: {signum} at frame: {frame}") sys.exit(signum) def _join(self): """Join the communication network for the experiment given by experiment_name with ID given by name. Specifically, it gets sockets' address for receiving (pulling) messages from its driver and uploads the receiving address to the Redis server. It then attempts to collect remote peers' receiving address by querying the Redis server. Finally, ask its driver to connect remote peers using those receiving address. """ self._register_redis() self._get_peers_list() self._build_connection() # TODO: Handle slow joiner for PUB/SUB. time.sleep(DELAY_FOR_SLOW_JOINER) # Build component-container-mapping for dynamic component in k8s/grass cluster. if "JOB_ID" in os.environ and "CONTAINER_NAME" in os.environ: container_name = os.getenv("CONTAINER_NAME") job_id = os.getenv("JOB_ID") rejoin_config = { "rejoin:enable": int(self._enable_rejoin), "rejoin:max_restart_times": self._max_rejoin_times, "is_remove_failed_container": int(self._is_remove_failed_container) } self._redis_connection.hmset(f"job:{job_id}:runtime_details", rejoin_config) if self._enable_rejoin: self._redis_connection.hset( f"job:{job_id}:rejoin_component_name_to_container_name", self._name, container_name ) def __del__(self): self._redis_connection.hdel(self._redis_hash_name, self._name) self._driver.close() def _register_redis(self): """Self-registration on Redis and driver initialization. Redis store structure: Hash Table: name: group name + peer's type, table (Dict[]): The key of table is the peer's name, the value of table is the peer's socket address. """ self._redis_connection.hset(self._redis_hash_name, self._name, json.dumps(self._driver.address)) # Handle interrupt signal for clearing Redis record. try: signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGTERM, self._signal_handler) except Exception as e: self._logger.error( "Signal detector disable. This may cause dirty data to be left in the Redis! " "To avoid this, please use multiprocess or make sure it can exit successfully." f"Due to {str(e)}." ) def _get_peers_list(self): """To collect all peers' name in the same group (group name) from Redis.""" if not self._peers_info_dict: raise PeersMissError(f"Cannot get {self._name}\'s peers.") for peer_type in self._peers_info_dict.keys(): peer_hash_name, peer_number = self._peers_info_dict[peer_type] retry_number = 0 expected_peers_name = [] while retry_number < self._max_retries: if self._redis_connection.hlen(peer_hash_name) >= peer_number: expected_peers_name = self._redis_connection.hkeys(peer_hash_name) expected_peers_name = [peer.decode() for peer in expected_peers_name] if len(expected_peers_name) > peer_number: expected_peers_name = expected_peers_name[:peer_number] self._logger.info(f"{self._name} successfully get all {peer_type}\'s name.") break else: self._logger.warn( f"{self._name} failed to get {peer_type}\'s name. Retrying in " f"{self._retry_interval_base_value * (2 ** retry_number)} seconds." ) time.sleep(self._retry_interval_base_value * (2 ** retry_number)) retry_number += 1 if not expected_peers_name: raise InformationUncompletedError( f"{self._name} failure to get enough number of {peer_type} from redis." ) self._onboard_peer_dict[peer_type] = {peer_name: None for peer_name in expected_peers_name} self._onboard_peers_start_time = time.time() def _build_connection(self): """Grabbing all peers' address from Redis, and connect all peers in driver.""" for peer_type in self._peers_info_dict.keys(): name_list = list(self._onboard_peer_dict[peer_type].keys()) try: peers_socket_value = self._redis_connection.hmget( self._peers_info_dict[peer_type].hash_table_name, name_list ) for idx, peer_name in enumerate(name_list): self._onboard_peer_dict[peer_type][peer_name] = json.loads(peers_socket_value[idx]) self._logger.info(f"{self._name} successfully get {peer_name}\'s socket address") except Exception as e: raise InformationUncompletedError(f"{self._name} failed to get {name_list}\'s address. Due to {str(e)}") self._driver.connect(self._onboard_peer_dict[peer_type]) @property def group_name(self) -> str: """str: Identifier for the group of all communication components.""" return self._group_name @property def name(self) -> str: """str: Unique identifier in the current group.""" return self._name @property def component_type(self) -> str: """str: Component's type in the current group.""" return self._component_type @property def peers_name(self) -> Dict: """Dict: The ``Dict`` of all connected peers' names, stored by peer type.""" return { peer_type: list(self._onboard_peer_dict[peer_type].keys()) for peer_type in self._peers_info_dict.keys() } def receive(self, is_continuous: bool = True, timeout: int = None): """Receive messages from communication driver. Args: is_continuous (bool): Continuously receive message or not. Defaults to True. """ return self._driver.receive(is_continuous, timeout=timeout) def receive_by_id(self, targets: List[str], timeout: int = None) -> List[Message]: """Receive target messages from communication driver. Args: targets List[str]: List of ``session_id``. E.g. ['0_learner0_actor0', '1_learner1_actor1', ...]. Returns: List[Message]: List of received messages. """ if not isinstance(targets, list) and not isinstance(targets, str): # The input may be None, if enable peer rejoin. self._logger.warn(f"Unrecognized target {targets}.") return # Pre-process targets. if isinstance(targets, str): targets = [targets] pending_targets, received_messages = targets[:], [] # Check message cache for saved messages. for session_id in targets: if session_id in self._message_cache: pending_targets.remove(session_id) received_messages.append(self._message_cache[session_id].pop(0)) if not self._message_cache[session_id]: del self._message_cache[session_id] if not pending_targets: return received_messages # Wait for incoming messages. for msg in self._driver.receive(is_continuous=True, timeout=timeout): if not msg: return received_messages if msg.session_id in pending_targets: pending_targets.remove(msg.session_id) received_messages.append(msg) else: self._message_cache[msg.session_id].append(msg) if not pending_targets: break return received_messages def _scatter( self, tag: Union[str, Enum], session_type: SessionType, destination_payload_list: list ) -> List[str]: """Scatters a list of data to peers, and return list of session id.""" session_id_list = [] for destination, payload in destination_payload_list: message = SessionMessage( tag=tag, source=self._name, destination=destination, payload=payload, session_type=session_type ) send_result = self.isend(message) if isinstance(send_result, list): session_id_list += send_result return session_id_list def scatter( self, tag: Union[str, Enum], session_type: SessionType, destination_payload_list: list, timeout: int = -1 ) -> List[Message]: """Scatters a list of data to peers, and return replied messages. Args: tag (str|Enum): Message's tag. session_type (Enum): Message's session type. destination_payload_list ([Tuple(str, object)]): The destination-payload list. The first item of the tuple in list is the message destination, and the second item of the tuple in list is the message payload. Returns: List[Message]: List of replied message. """ return self.receive_by_id( targets=self._scatter(tag, session_type, destination_payload_list), timeout=timeout ) def iscatter( self, tag: Union[str, Enum], session_type: SessionType, destination_payload_list: list ) -> List[str]: """Scatters a list of data to peers, and return list of message id. Args: tag (str|Enum): Message's tag. session_type (Enum): Message's session type. destination_payload_list ([Tuple(str, object)]): The destination-payload list. The first item of the tuple in list is the message's destination, and the second item of the tuple in list is the message's payload. Returns: List[str]: List of message's session id. """ return self._scatter(tag, session_type, destination_payload_list) def _broadcast( self, component_type: str, tag: Union[str, Enum], session_type: SessionType, payload=None ) -> List[str]: """Broadcast message to all peers, and return list of session id.""" if component_type not in list(self._onboard_peer_dict.keys()): self._logger.error( f"peer_type: {component_type} cannot be recognized. Please check the input of proxy.broadcast." ) sys.exit(NON_RESTART_EXIT_CODE) if self._enable_rejoin: self._rejoin(component_type) message = SessionMessage( tag=tag, source=self._name, destination=component_type, payload=payload, session_type=session_type ) self._driver.broadcast(component_type, message) return [message.session_id for _ in range(len(self._onboard_peer_dict[component_type]))] def broadcast( self, component_type: str, tag: Union[str, Enum], session_type: SessionType, payload=None, timeout: int = None ) -> List[Message]: """Broadcast message to all peers, and return all replied messages. Args: component_type (str): Broadcast to all peers in this type. tag (str|Enum): Message's tag. session_type (Enum): Message's session type. payload (object): The true data. Defaults to None. Returns: List[Message]: List of replied messages. """ return self.receive_by_id( targets=self._broadcast(component_type, tag, session_type, payload), timeout=timeout ) def ibroadcast( self, component_type: str, tag: Union[str, Enum], session_type: SessionType, payload=None ) -> List[str]: """Broadcast message to all subscribers, and return list of message's session id. Args: component_type (str): Broadcast to all peers in this type. tag (str|Enum): Message's tag. session_type (Enum): Message's session type. payload (object): The true data. Defaults to None. Returns: List[str]: List of message's session id which related to the replied message. """ return self._broadcast(component_type, tag, session_type, payload) def _send(self, message: Message) -> Union[List[str], None]: """Send a message to a remote peer. Args: message: Message to be sent. Returns: Union[List[str], None]: The list of message's session id; If enable rejoin, it will return None when sending message to the failed peers; If enable rejoin and message cache, it may return list of session id which from the pending messages in message cache. """ session_id_list = [] if self._enable_rejoin: peer_type = self.get_peer_type(message.destination) self._rejoin(peer_type) # Check message cache. if ( self._enable_message_cache and message.destination in list(self._onboard_peer_dict[peer_type].keys()) and message.destination in list(self._message_cache_for_exited_peers.keys()) ): self._logger.info(f"Sending pending message to {message.destination}.") for pending_message in self._message_cache_for_exited_peers[message.destination]: self._driver.send(pending_message) session_id_list.append(pending_message.session_id) del self._message_cache_for_exited_peers[message.destination] try: self._driver.send(message) session_id_list.append(message.session_id) return session_id_list except PendingToSend as e: self._logger.warn(f"{e} Peer {message.destination} exited, but still have enough peers.") if self._enable_message_cache: self._push_message_to_message_cache(message) def isend(self, message: Message) -> Union[List[str], None]: """Send a message to a remote peer. Args: message: Message to be sent. Returns: Union[List[str], None]: The list of message's session id; If enable rejoin, it will return None when sending message to the failed peers. If enable rejoin and message cache, it may return list of session id which from the pending messages. """ return self._send(message) def send( self, message: Message, timeout: int = None ) -> Union[List[Message], None]: """Send a message to a remote peer. Args: message: Message to be sent. Returns: Union[List[Message], None]: The list of received message; If enable rejoin, it will return None when sending message to the failed peers. If enable rejoin and message cache, it may return list of messages which from the pending messages. """ return self.receive_by_id(self._send(message), timeout) def reply( self, message: Union[SessionMessage, Message], tag: Union[str, Enum] = None, payload=None, ack_reply: bool = False ) -> List[str]: """Reply a received message. Args: message (Message): The message need to reply. tag (str|Enum): New message tag, if None, keeps the original message's tag. Defaults to None. payload (object): New message payload, if None, keeps the original message's payload. Defaults to None. ack_reply (bool): If True, it is acknowledge reply. Defaults to False. Returns: List[str]: Message belonged session id. """ message.reply(tag=tag, payload=payload) if isinstance(message, SessionMessage): if message.session_type == SessionType.TASK: session_stage = TaskSessionStage.RECEIVE if ack_reply else TaskSessionStage.COMPLETE else: session_stage = NotificationSessionStage.RECEIVE message.session_stage = session_stage return self.isend(message) def forward( self, message: Union[SessionMessage, Message], destination: str, tag: Union[str, Enum] = None, payload=None ) -> List[str]: """Forward a received message. Args: message (Message): The message need to forward. destination (str): The receiver of message. tag (str|Enum): New message tag, if None, keeps the original message's tag. Defaults to None. payload (object): Message payload, if None, keeps the original message's payload. Defaults to None. Returns: List[str]: Message belonged session id. """ message.forward(destination=destination, tag=tag, payload=payload) return self.isend(message) def _check_peers_update(self): """Compare the peers' information on local with the peers' information on Redis. For the different between two peers information dict's key (peer_name): If some peers only appear on Redis, the proxy will connect with those peers; If some peers only appear on local, the proxy will disconnect with those peers; For the different between two peers information dict's value (peers_socket_address): If some peers' information is different between Redis and local, the proxy will update those peers (driver disconnect with the local information and connect with the peer's information on Redis). """ for peer_type in self._peers_info_dict.keys(): # onboard_peers_dict_on_redis is the newest peers' information from the Redis. onboard_peers_dict_on_redis = self._redis_connection.hgetall( self._peers_info_dict[peer_type].hash_table_name ) onboard_peers_dict_on_redis = { key.decode(): json.loads(value) for key, value in onboard_peers_dict_on_redis.items() } # Mappings (instances of dict) compare equal if and only if they have equal (key, value) pairs. # Equality comparison of the keys and values enforces reflexivity. if self._onboard_peer_dict[peer_type] != onboard_peers_dict_on_redis: union_peer_name = list(self._onboard_peer_dict[peer_type].keys()) + \ list(onboard_peers_dict_on_redis.keys()) for peer_name in union_peer_name: # Add new peers (new key added on redis). if peer_name not in list(self._onboard_peer_dict[peer_type].keys()): self._logger.info(f"PEER_REJOIN: New peer {peer_name} join.") self._driver.connect({peer_name: onboard_peers_dict_on_redis[peer_name]}) self._onboard_peer_dict[peer_type][peer_name] = onboard_peers_dict_on_redis[peer_name] # Delete out of date peers (old key deleted on local) elif peer_name not in onboard_peers_dict_on_redis.keys(): self._logger.info(f"PEER_REJOIN: Peer {peer_name} exited.") self._driver.disconnect({peer_name: self._onboard_peer_dict[peer_type][peer_name]}) del self._onboard_peer_dict[peer_type][peer_name] else: # Peer's ip/port updated, re-connect (value update on redis). if onboard_peers_dict_on_redis[peer_name] != self._onboard_peer_dict[peer_type][peer_name]: self._logger.info(f"PEER_REJOIN: Peer {peer_name} rejoin.") self._driver.disconnect({peer_name: self._onboard_peer_dict[peer_type][peer_name]}) self._driver.connect({peer_name: onboard_peers_dict_on_redis[peer_name]}) self._onboard_peer_dict[peer_type][peer_name] = onboard_peers_dict_on_redis[peer_name] def _rejoin(self, peer_type=None): """The logic about proxy rejoin. Update onboard peers with the peers on Redis, if onboard peers expired. If there are not enough peers for the given peer type, block until peers rejoin or timeout. """ current_time = time.time() if current_time - self._onboard_peers_start_time > self._peers_catch_lifetime: self._check_peers_update() self._onboard_peers_start_time = current_time if len(self._onboard_peer_dict[peer_type].keys()) < self._minimal_peers[peer_type]: self._wait_for_minimal_peer_number(peer_type) def _wait_for_minimal_peer_number(self, peer_type): """Blocking until there are enough peers for the given peer type.""" start_time = time.time() while time.time() - start_time < self._timeout_for_minimal_peer_number: self._logger.warn( f"No enough peers in {peer_type}! Wait for some peer restart. Remaining time: " f"{start_time + self._timeout_for_minimal_peer_number - time.time()}" ) self._check_peers_update() if len(self._onboard_peer_dict[peer_type]) >= self._minimal_peers[peer_type]: return time.sleep(self._peers_catch_lifetime) self._logger.error(f"Failure to get enough peers for {peer_type}. All components will exited.") sys.exit(KILL_ALL_EXIT_CODE) def get_peer_type(self, peer_name: str) -> str: """Get peer type from given peer name. Args: peer_name (str): The component name of a peer, which form by peer_type and UUID. Returns: str: The component type of a peer in current group. """ # peer_name is consist by peer_type + '_proxy_' + UUID where UUID is only compose by digits and letters. # So the peer_type must be the part before last '_proxy_'. peer_type = peer_name[:peer_name.rfind("_proxy_")] if peer_type not in list(self._onboard_peer_dict.keys()): self._logger.error( f"The message's destination {peer_name} does not belong to any recognized peer type. " f"Please check the input of message." ) sys.exit(NON_RESTART_EXIT_CODE) return peer_type def _push_message_to_message_cache(self, message: Message): peer_name = message.destination for pending_message in self._message_cache_for_exited_peers[peer_name]: if pending_message.message_id == message.message_id: self._logger.warn(f"{message.message_id} has been added in the message cache.") return self._message_cache_for_exited_peers[peer_name].append(message) self._logger.info(f"Temporarily save message {message.session_id} to message cache.") def close(self): self._redis_connection.hdel(self._redis_hash_name, self._name) self._driver.close()
14,003
570
<gh_stars>100-1000 /* * Souffle - A Datalog Compiler * Copyright (c) 2020, The Souffle Developers. All rights reserved * Licensed under the Universal Permissive License v 1.0 as shown at: * - https://opensource.org/licenses/UPL * - <souffle root>/licenses/SOUFFLE-UPL.txt */ /************************************************************************ * * @file TypeChecker.cpp * * Implementation of the type checker pass. * ***********************************************************************/ #include "ast/transform/TypeChecker.h" #include "Global.h" #include "ast/Aggregator.h" #include "ast/AlgebraicDataType.h" #include "ast/Argument.h" #include "ast/Atom.h" #include "ast/Attribute.h" #include "ast/BinaryConstraint.h" #include "ast/BranchInit.h" #include "ast/BranchType.h" #include "ast/Clause.h" #include "ast/Constant.h" #include "ast/Counter.h" #include "ast/Functor.h" #include "ast/IntrinsicFunctor.h" #include "ast/QualifiedName.h" #include "ast/analysis/Functor.h" #include "ast/analysis/typesystem/PolymorphicObjects.h" #include "ast/analysis/typesystem/SumTypeBranches.h" #include "ast/analysis/typesystem/Type.h" #include "ast/analysis/typesystem/TypeEnvironment.h" #include "ast/analysis/typesystem/TypeSystem.h" #include "ast/utility/Utils.h" #include "ast/utility/Visitor.h" #include "reports/ErrorReport.h" #include "souffle/utility/StringUtil.h" #include <algorithm> #include <map> #include <sstream> #include <string> #include <unordered_set> #include <utility> #include <vector> namespace souffle::ast::transform { using namespace analysis; class TypeDeclarationChecker { public: TypeDeclarationChecker(TranslationUnit& tu) : tu(tu){}; void run(); private: TranslationUnit& tu; ErrorReport& report = tu.getErrorReport(); const Program& program = tu.getProgram(); const TypeEnvironmentAnalysis& typeEnvAnalysis = tu.getAnalysis<TypeEnvironmentAnalysis>(); const TypeEnvironment& typeEnv = typeEnvAnalysis.getTypeEnvironment(); void checkRecordType(const ast::RecordType& type); void checkSubsetType(const ast::SubsetType& type); void checkAliasType(const ast::AliasType& type); void checkUnionType(const ast::UnionType& type); void checkADT(const ast::AlgebraicDataType& type); }; class TypeCheckerImpl : public Visitor<void> { public: TypeCheckerImpl(TranslationUnit& tu) : tu(tu){}; /** Analyse types, clause by clause */ void run() { for (auto const* clause : program.getClauses()) { visit(*clause, *this); } for (auto const* decl : program.getFunctorDeclarations()) { if (!typeAnalysis.hasValidTypeInfo(*decl)) { // This could happen if the types mentioned int the functor declaration // are not valid continue; } // Only stateful functors can use UDTs auto goodFunctor = [this, stateful = decl->isStateful()](QualifiedName const& tName) { auto attr = getTypeAttribute(typeEnv.getType(tName)); return stateful || (attr != TypeAttribute::ADT && attr != TypeAttribute::Record); }; if (!goodFunctor(decl->getReturnType().getTypeName())) { report.addError( "Functors which are not stateful cannot use UDTs", decl->getReturnType().getSrcLoc()); } for (auto const& param : decl->getParams()) { if (!goodFunctor(param->getTypeName())) { report.addError("Functors which are not stateful cannot use UDTs", param->getSrcLoc()); } } } } private: TranslationUnit& tu; ErrorReport& report = tu.getErrorReport(); const TypeAnalysis& typeAnalysis = tu.getAnalysis<TypeAnalysis>(); const TypeEnvironment& typeEnv = tu.getAnalysis<TypeEnvironmentAnalysis>().getTypeEnvironment(); const PolymorphicObjectsAnalysis& polyAnalysis = tu.getAnalysis<PolymorphicObjectsAnalysis>(); const SumTypeBranchesAnalysis& sumTypesBranches = tu.getAnalysis<SumTypeBranchesAnalysis>(); const Program& program = tu.getProgram(); std::unordered_set<const Atom*> negatedAtoms; /** Collect negated atoms */ void visit_(type_identity<Negation>, const Negation& neg) override; /* Type checks */ /** Check if declared types of the relation match deduced types. */ void visit_(type_identity<Atom>, const Atom& atom) override; void visit_(type_identity<Variable>, const Variable& var) override; void visit_(type_identity<StringConstant>, const StringConstant& constant) override; void visit_(type_identity<NumericConstant>, const NumericConstant& constant) override; void visit_(type_identity<NilConstant>, const NilConstant& constant) override; void visit_(type_identity<RecordInit>, const RecordInit& rec) override; void visit_(type_identity<BranchInit>, const BranchInit& adt) override; void visit_(type_identity<TypeCast>, const ast::TypeCast& cast) override; void visit_(type_identity<IntrinsicFunctor>, const IntrinsicFunctor& fun) override; void visit_(type_identity<UserDefinedFunctor>, const UserDefinedFunctor& fun) override; void visit_(type_identity<BinaryConstraint>, const BinaryConstraint& constraint) override; void visit_(type_identity<Aggregator>, const Aggregator& aggregator) override; }; // namespace souffle::ast::transform void TypeChecker::verify(TranslationUnit& tu) { auto& report = tu.getErrorReport(); auto errorsBeforeDeclarationsCheck = report.getNumErrors(); TypeDeclarationChecker{tu}.run(); // Run type checker only if type declarations are valid. if (report.getNumErrors() == errorsBeforeDeclarationsCheck) { TypeCheckerImpl{tu}.run(); } } void TypeDeclarationChecker::checkUnionType(const ast::UnionType& type) { // check presence of all the element types and that all element types are based off a primitive for (const QualifiedName& sub : type.getTypes()) { if (typeEnv.isPrimitiveType(sub)) { continue; } const ast::Type* subtype = getIf( program.getTypes(), [&](const ast::Type* type) { return type->getQualifiedName() == sub; }); if (subtype == nullptr) { report.addError(tfm::format("Undefined type %s in definition of union type %s", sub, type.getQualifiedName()), type.getSrcLoc()); } else if (!isA<ast::UnionType>(subtype) && !isA<ast::SubsetType>(subtype) && !isA<ast::AliasType>(subtype)) { report.addError(tfm::format("Union type %s contains the non-primitive type %s", type.getQualifiedName(), sub), type.getSrcLoc()); } } // Check if the union is recursive. if (typeEnvAnalysis.isCyclic(type.getQualifiedName())) { report.addError("Infinite descent in the definition of type " + toString(type.getQualifiedName()), type.getSrcLoc()); } /* check that union types do not mix different primitive types */ for (const auto* type : program.getTypes()) { // We are only interested in unions here. if (!isA<ast::UnionType>(type)) { continue; } const auto& name = type->getQualifiedName(); const auto& predefinedTypesInUnion = typeEnvAnalysis.getPrimitiveTypesInUnion(name); // Report error (if size == 0, then the union is cyclic) if (predefinedTypesInUnion.size() > 1) { report.addError( tfm::format("Union type %s is defined over {%s} (multiple primitive types in union)", name, join(predefinedTypesInUnion, ", ")), type->getSrcLoc()); } } } void TypeDeclarationChecker::checkRecordType(const ast::RecordType& type) { auto&& fields = type.getFields(); // check proper definition of all field types for (auto&& field : fields) { if (!typeEnv.isType(field->getTypeName())) { report.addError(tfm::format("Undefined type %s in definition of field %s", field->getTypeName(), field->getName()), field->getSrcLoc()); } } // check that field names are unique for (std::size_t i = 0; i < fields.size(); i++) { auto&& cur_name = fields[i]->getName(); for (std::size_t j = 0; j < i; j++) { if (fields[j]->getName() == cur_name) { report.addError(tfm::format("Doubly defined field name %s in definition of type %s", cur_name, type.getQualifiedName()), fields[i]->getSrcLoc()); } } } } void TypeDeclarationChecker::checkADT(const ast::AlgebraicDataType& type) { // check if all branches contain properly defined types. for (auto* branch : type.getBranches()) { for (auto* field : branch->getFields()) { if (!typeEnv.isType(field->getTypeName())) { report.addError(tfm::format("Undefined type %s in definition of branch %s", field->getTypeName(), branch->getBranchName()), field->getSrcLoc()); } } } } void TypeDeclarationChecker::checkAliasType(const ast::AliasType& astType) { if (typeEnvAnalysis.isCyclic(astType.getQualifiedName())) { report.addError( tfm::format("Infinite descent in the definition of type %s", astType.getQualifiedName()), astType.getSrcLoc()); return; } if (!typeEnv.isType(astType.getAliasType())) { report.addError(tfm::format("Undefined alias type %s in definition of type %s", astType.getAliasType(), astType.getQualifiedName()), astType.getSrcLoc()); return; } } void TypeDeclarationChecker::checkSubsetType(const ast::SubsetType& astType) { if (typeEnvAnalysis.isCyclic(astType.getQualifiedName())) { report.addError( tfm::format("Infinite descent in the definition of type %s", astType.getQualifiedName()), astType.getSrcLoc()); return; } if (!typeEnv.isType(astType.getBaseType())) { report.addError(tfm::format("Undefined base type %s in definition of type %s", astType.getBaseType(), astType.getQualifiedName()), astType.getSrcLoc()); return; } auto& rootType = typeEnv.getType(astType.getBaseType()); if (isA<analysis::UnionType>(rootType)) { report.addError(tfm::format("Subset type %s can't be derived from union %s", astType.getQualifiedName(), rootType.getName()), astType.getSrcLoc()); } if (isA<analysis::RecordType>(rootType)) { report.addError(tfm::format("Subset type %s can't be derived from record type %s", astType.getQualifiedName(), rootType.getName()), astType.getSrcLoc()); } } void TypeDeclarationChecker::run() { // The redefinitions of types is checked by checkNamespaces in SemanticChecker for (auto* type : program.getTypes()) { if (typeEnv.isPrimitiveType(type->getQualifiedName())) { report.addError("Redefinition of the predefined type", type->getSrcLoc()); continue; } if (isA<ast::UnionType>(type)) { checkUnionType(*as<ast::UnionType>(type)); } else if (isA<ast::RecordType>(type)) { checkRecordType(*as<ast::RecordType>(type)); } else if (isA<ast::SubsetType>(type)) { checkSubsetType(*as<ast::SubsetType>(type)); } else if (isA<ast::AliasType>(type)) { checkAliasType(*as<ast::AliasType>(type)); } else if (isA<ast::AlgebraicDataType>(type)) { checkADT(*as<ast::AlgebraicDataType>(type)); } else { fatal("unsupported type construct: %s", typeid(type).name()); } } // Check if all the branch names are unique in sum types. std::map<QualifiedName, std::vector<SrcLocation>> branchToLocation; visit(program.getTypes(), [&](const ast::AlgebraicDataType& type) { for (auto* branch : type.getBranches()) { branchToLocation[branch->getBranchName()].push_back(branch->getSrcLoc()); } }); for (auto& branchLocs : branchToLocation) { auto& branch = branchLocs.first; auto& locs = branchLocs.second; // If a branch is used only once, then everything is fine. if (locs.size() == 1) continue; auto primaryDiagnostic = DiagnosticMessage(tfm::format("Branch %s is defined multiple times", branch)); std::vector<DiagnosticMessage> branchDeclarations; for (auto& loc : locs) { branchDeclarations.push_back(DiagnosticMessage(tfm::format("Branch %s defined", branch), loc)); } report.addDiagnostic(Diagnostic( Diagnostic::Type::ERROR, std::move(primaryDiagnostic), std::move(branchDeclarations))); } } void TypeCheckerImpl::visit_(type_identity<Atom>, const Atom& atom) { auto relation = program.getRelation(atom); if (relation == nullptr) { return; // error unrelated to types. } auto attributes = relation->getAttributes(); auto arguments = atom.getArguments(); if (attributes.size() != arguments.size()) { return; // error in input program } for (std::size_t i = 0; i < attributes.size(); ++i) { auto& typeName = attributes[i]->getTypeName(); if (!typeEnv.isType(typeName)) { continue; } auto argTypes = typeAnalysis.getTypes(arguments[i]); auto& attributeType = typeEnv.getType(typeName); if (argTypes.isAll() || argTypes.empty()) { continue; // This will be reported later. } // We consider two cases: negated and not negated atoms. // Negated atom have to agree in kind, non-negated atom need to follow source/sink rules. if (negatedAtoms.count(&atom) == 0) { // Attribute and argument type agree if, argument type is a subtype of declared type // or is of the appropriate constant type or the (constant) record type. bool validAttribute = all_of(argTypes, [&attributeType](const analysis::Type& type) { if (isSubtypeOf(type, attributeType)) return true; if (!isSubtypeOf(attributeType, type)) return false; if (isA<ConstantType>(type)) return true; return isA<analysis::RecordType>(type) && !isA<analysis::SubsetType>(type); }); if (!validAttribute && !Global::config().has("legacy")) { auto primaryDiagnostic = DiagnosticMessage("Atom's argument type is not a subtype of its declared type", arguments[i]->getSrcLoc()); auto declaredTypeInfo = DiagnosticMessage(tfm::format("The argument's declared type is %s", typeName), attributes[i]->getSrcLoc()); report.addDiagnostic(Diagnostic(Diagnostic::Type::ERROR, std::move(primaryDiagnostic), {std::move(declaredTypeInfo)})); } } else { // negation case. // Declared attribute and deduced type agree if: // They are the same type, or // They are derived from the same constant type. bool validAttribute = all_of(argTypes, [&](const analysis::Type& type) { return type == attributeType || any_of(typeEnv.getConstantTypes(), [&](auto& constantType) { return isSubtypeOf(attributeType, constantType) && isSubtypeOf(type, constantType); }); }); if (!validAttribute) { auto primaryDiagnostic = DiagnosticMessage("The kind of atom's argument doesn't match the declared type kind", arguments[i]->getSrcLoc()); auto declaredTypeInfo = DiagnosticMessage(tfm::format("The argument's declared type is %s", typeName), attributes[i]->getSrcLoc()); report.addDiagnostic(Diagnostic(Diagnostic::Type::ERROR, std::move(primaryDiagnostic), {std::move(declaredTypeInfo)})); } } } } void TypeCheckerImpl::visit_(type_identity<Variable>, const ast::Variable& var) { if (typeAnalysis.getTypes(&var).empty()) { report.addError("Unable to deduce type for variable " + var.getName(), var.getSrcLoc()); } } void TypeCheckerImpl::visit_(type_identity<StringConstant>, const StringConstant& constant) { TypeSet types = typeAnalysis.getTypes(&constant); if (!isOfKind(types, TypeAttribute::Symbol)) { report.addError("Symbol constant (type mismatch)", constant.getSrcLoc()); } } void TypeCheckerImpl::visit_(type_identity<NumericConstant>, const NumericConstant& constant) { TypeSet types = typeAnalysis.getTypes(&constant); // No type could be assigned. if (polyAnalysis.hasInvalidType(constant)) { report.addError("Ambiguous constant (unable to deduce type)", constant.getSrcLoc()); return; } switch (polyAnalysis.getInferredType(constant)) { case NumericConstant::Type::Int: if (!isOfKind(types, TypeAttribute::Signed) || !canBeParsedAsRamSigned(constant.getConstant())) { report.addError("Number constant (type mismatch)", constant.getSrcLoc()); } break; case NumericConstant::Type::Uint: if (!isOfKind(types, TypeAttribute::Unsigned) || !canBeParsedAsRamUnsigned(constant.getConstant())) { report.addError("Unsigned constant (type mismatch)", constant.getSrcLoc()); } break; case NumericConstant::Type::Float: if (!isOfKind(types, TypeAttribute::Float) || !canBeParsedAsRamFloat(constant.getConstant())) { report.addError("Float constant (type mismatch)", constant.getSrcLoc()); } break; } } void TypeCheckerImpl::visit_(type_identity<NilConstant>, const NilConstant& constant) { TypeSet types = typeAnalysis.getTypes(&constant); if (!isOfKind(types, TypeAttribute::Record)) { report.addError("Nil constant used as a non-record", constant.getSrcLoc()); return; } } void TypeCheckerImpl::visit_(type_identity<RecordInit>, const RecordInit& rec) { TypeSet types = typeAnalysis.getTypes(&rec); if (!isOfKind(types, TypeAttribute::Record) || types.size() != 1) { report.addError("Ambiguous record", rec.getSrcLoc()); return; } // At this point we know that there is exactly one type in set, so we can take it. auto& recordType = *as<analysis::RecordType>(*types.begin()); if (recordType.getFields().size() != rec.getArguments().size()) { report.addError("Wrong number of arguments given to record", rec.getSrcLoc()); return; } } void TypeCheckerImpl::visit_(type_identity<BranchInit>, const BranchInit& adt) { TypeSet types = typeAnalysis.getTypes(&adt); if (sumTypesBranches.getType(adt.getBranchName()) == nullptr) { report.addError("Undeclared branch", adt.getSrcLoc()); return; } if (!isOfKind(types, TypeAttribute::ADT) || types.isAll() || types.size() != 1) { report.addError("Ambiguous branch", adt.getSrcLoc()); return; } // We know now that the set "types" is a singleton auto& sumType = *as<analysis::AlgebraicDataType>(*types.begin()); auto& argsDeclaredTypes = sumType.getBranchTypes(adt.getBranchName()); auto args = adt.getArguments(); if (argsDeclaredTypes.size() != args.size()) { report.addError(tfm::format("Invalid arity, the declared arity of %s is %s", adt.getBranchName(), argsDeclaredTypes.size()), adt.getSrcLoc()); return; } for (std::size_t i = 0; i < args.size(); ++i) { auto argTypes = typeAnalysis.getTypes(args[i]); bool correctType = all_of( argTypes, [&](const analysis::Type& t) { return isSubtypeOf(t, *argsDeclaredTypes[i]); }); if (!correctType) { // TODO (darth_tytus): Give better error report.addError("Branch argument's type doesn't match its declared type", args[i]->getSrcLoc()); } } } void TypeCheckerImpl::visit_(type_identity<TypeCast>, const ast::TypeCast& cast) { if (!typeEnv.isType(cast.getType())) { report.addError( tfm::format("Type cast to the undeclared type \"%s\"", cast.getType()), cast.getSrcLoc()); return; } auto& castTypes = typeAnalysis.getTypes(&cast); auto& argTypes = typeAnalysis.getTypes(cast.getValue()); if (castTypes.isAll() || castTypes.size() != 1) { report.addError("Unable to deduce type of the argument (cast)", cast.getSrcLoc()); return; } // This should be reported elsewhere if (argTypes.isAll() || castTypes.size() != 1 || argTypes.isAll() || argTypes.size() != 1) { return; } } void TypeCheckerImpl::visit_(type_identity<IntrinsicFunctor>, const IntrinsicFunctor& fun) { if (!typeAnalysis.hasValidTypeInfo(fun)) { auto args = fun.getArguments(); if (!isValidFunctorOpArity(fun.getBaseFunctionOp(), args.size())) { report.addError("invalid overload (arity mismatch)", fun.getSrcLoc()); return; } assert(typeAnalysis.getValidIntrinsicFunctorOverloads(fun).empty() && "unexpected type analysis result"); report.addError("no valid overloads", fun.getSrcLoc()); } } void TypeCheckerImpl::visit_(type_identity<UserDefinedFunctor>, const UserDefinedFunctor& fun) { // check type of result const TypeSet& resultTypes = typeAnalysis.getTypes(&fun); using Type = analysis::Type; auto const* udfd = getFunctorDeclaration(program, fun.getName()); if (udfd == nullptr || !typeAnalysis.hasValidTypeInfo(*udfd)) { // I found this very confusing, hopefully this comment helps someone else. // I assumed that this branch cannot be taken, because the Semantic checker // verifies that every functor has a declaration! However, it turns out that // the SemanticChecker is *not* the first Transformer which gets run and so // it's not really clear that those invariants hold yet. // I don't particularly like that but am not at a place where I can change the // order of the passes/transformers. So, for now, here's a comment for the next // person going doing this rabbit hole. return; } Type const& returnType = typeAnalysis.getFunctorReturnType(fun); if (resultTypes.isAll() || resultTypes.size() != 1) { std::ostringstream out; out << "Invalid use of functor returning " << returnType; report.addError(out.str(), fun.getSrcLoc()); } else { Type const& resultType = *resultTypes.begin(); if (!isSubtypeOf(returnType, resultType)) { std::ostringstream out; out << "Invalid conversion of return type " << returnType << " to " << resultType; report.addError(out.str(), fun.getSrcLoc()); } } auto const& params = udfd->getParams(); auto const arity = params.size(); auto const& args = fun.getArguments(); auto const toCheck = std::min(args.size(), arity); if (args.size() != arity) { std::ostringstream out; out << "Functor arity mismatch: Got " << args.size() << " arguments, expecting " << arity; report.addError(out.str(), fun.getSrcLoc()); } auto getName = [&params](std::size_t idx) { auto const& name = params[idx]->getName(); std::ostringstream out; out << "positional parameter " << idx; if (!name.empty()) { out << " ('" << name << "')"; } return out.str(); }; for (std::size_t ii = 0; ii < toCheck; ++ii) { auto const& arg = args[ii]; Type const& paramType = typeAnalysis.getFunctorParamType(fun, ii); TypeSet const& argTypes = typeAnalysis.getTypes(arg); if (argTypes.isAll() || argTypes.size() != 1) { report.addError("Unable to determine type for " + getName(ii), arg->getSrcLoc()); } else { Type const& argType = *argTypes.begin(); if (!isSubtypeOf(argType, paramType)) { std::ostringstream out; out << "Invalid conversion of value of type " << argType << " to " << getName(ii) << " with type " << paramType; report.addError(out.str(), arg->getSrcLoc()); } } } } void TypeCheckerImpl::visit_(type_identity<BinaryConstraint>, const BinaryConstraint& constraint) { auto op = polyAnalysis.getOverloadedOperator(constraint); auto left = constraint.getLHS(); auto right = constraint.getRHS(); auto opTypesAttrs = getBinaryConstraintTypes(op); auto leftTypes = typeAnalysis.getTypes(left); auto rightTypes = typeAnalysis.getTypes(right); // Skip checks if either side could not be fully deduced // The unable-to-deduce-type checker will point out the issue. if (leftTypes.isAll() || leftTypes.size() != 1) return; if (rightTypes.isAll() || rightTypes.size() != 1) return; // Extract types from singleton sets. auto& leftType = *typeAnalysis.getTypes(left).begin(); auto& rightType = *typeAnalysis.getTypes(right).begin(); // give them a slightly nicer error if (isOrderedBinaryConstraintOp(op) && !areEquivalentTypes(leftType, rightType)) { report.addError("Cannot compare different types", constraint.getSrcLoc()); } else { auto checkTyAttr = [&](Argument const& side) { auto opMatchesType = any_of(opTypesAttrs, [&](auto& typeAttr) { return isOfKind(typeAnalysis.getTypes(&side), typeAttr); }); if (!opMatchesType) { std::stringstream ss; ss << "Constraint requires an operand of type " << join(opTypesAttrs, " or ", [&](auto& out, auto& typeAttr) { switch (typeAttr) { case TypeAttribute::Signed: out << "`number`"; break; case TypeAttribute::Symbol: out << "`symbol`"; break; case TypeAttribute::Unsigned: out << "`unsigned`"; break; case TypeAttribute::Float: out << "`float`"; break; case TypeAttribute::Record: out << "a record"; break; case TypeAttribute::ADT: out << "a sum"; break; } }); report.addError(ss.str(), side.getSrcLoc()); } }; checkTyAttr(*left); checkTyAttr(*right); } } void TypeCheckerImpl::visit_(type_identity<Aggregator>, const Aggregator& aggregator) { auto op = polyAnalysis.getOverloadedOperator(aggregator); auto aggregatorType = typeAnalysis.getTypes(&aggregator); TypeAttribute opType = getTypeAttributeAggregate(op); // Check if operation type and return type agree. if (!isOfKind(aggregatorType, opType)) { report.addError("Couldn't assign types to the aggregator", aggregator.getSrcLoc()); } } void TypeCheckerImpl::visit_(type_identity<Negation>, const Negation& neg) { negatedAtoms.insert(neg.getAtom()); } } // namespace souffle::ast::transform
11,654
32,544
package com.baeldung.boot.configurationproperties; import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix = "server") public class ServerConfig { private Address address; private Map<String, String> resourcesPath; public static class Address { private String ip; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Map<String, String> getResourcesPath() { return resourcesPath; } public void setResourcesPath(Map<String, String> resourcesPath) { this.resourcesPath = resourcesPath; } }
343
2,360
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyFuzzywuzzy(PythonPackage): """Fuzzy string matching in python.""" homepage = "https://github.com/seatgeek/fuzzywuzzy" pypi = "fuzzywuzzy/fuzzywuzzy-0.18.0.tar.gz" version('0.18.0', sha256='45016e92264780e58972dca1b3d939ac864b78437422beecebb3095f8efd00e8') variant('speedup', default=False, description='Provide a 4-10x speedup') depends_on('[email protected]:2.8,3.4:', type=('build', 'run')) depends_on('py-setuptools', type='build') depends_on('[email protected]:', when='+speedup', type=('build', 'run'))
318
1,056
<filename>ide/editor.fold/src/org/netbeans/modules/editor/fold/ApiPackageAccessor.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 org.netbeans.modules.editor.fold; import java.util.Collection; import javax.swing.event.DocumentEvent; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import org.netbeans.api.editor.fold.Fold; import org.netbeans.api.editor.fold.FoldHierarchy; import org.netbeans.api.editor.fold.FoldHierarchyEvent; import org.netbeans.api.editor.fold.FoldStateChange; import org.netbeans.api.editor.fold.FoldType; import org.netbeans.api.editor.mimelookup.MimeLookup; import org.netbeans.api.editor.mimelookup.MimePath; import org.netbeans.spi.editor.fold.FoldHierarchyMonitor; import org.openide.util.Lookup; /** * Accessor for the package-private functionality in org.netbeans.api.editor.fold. * * @author <NAME> * @version 1.00 */ public abstract class ApiPackageAccessor { private static ApiPackageAccessor INSTANCE; public static ApiPackageAccessor get() { return INSTANCE; } /** * Register the accessor. The method can only be called once * - othewise it throws IllegalStateException. * * @param accessor instance. */ public static void register(ApiPackageAccessor accessor) { if (INSTANCE != null) { throw new IllegalStateException("Already registered"); // NOI18N } INSTANCE = accessor; // this is a HACK; forces registration of the view. MimeLookup.getLookup(MimePath.EMPTY).lookup(FoldHierarchyMonitor.class); } public abstract FoldHierarchy createFoldHierarchy(FoldHierarchyExecution execution); public abstract Fold createFold(FoldOperationImpl operation, FoldType type, String description, boolean collapsed, Document doc, int startOffset, int endOffset, int startGuardedLength, int endGuardedLength, Object extraInfo) throws BadLocationException; public abstract FoldHierarchyEvent createFoldHierarchyEvent(FoldHierarchy source, Fold[] removedFolds, Fold[] addedFolds, FoldStateChange[] foldStateChanges, int affectedStartOffset, int affectedEndOffset); public abstract FoldStateChange createFoldStateChange(Fold fold); public abstract void foldSetCollapsed(Fold fold, boolean collapsed); public abstract void foldSetParent(Fold fold, Fold parent); public abstract void foldTearOut(Fold f, Collection c); public abstract void foldExtractToChildren(Fold fold, int index, int length, Fold targetFold); public abstract Fold foldReplaceByChildren(Fold fold, int index); public abstract void foldSetDescription(Fold fold, String description); public abstract void foldSetStartOffset(Fold fold, Document doc, int startOffset) throws BadLocationException; public abstract void foldSetEndOffset(Fold fold, Document doc, int endOffset) throws BadLocationException; public abstract boolean foldIsStartDamaged(Fold fold); public abstract boolean foldIsEndDamaged(Fold fold); // public abstract boolean foldIsExpandNecessary(Fold fold); public abstract void foldInsertUpdate(Fold fold, DocumentEvent evt); public abstract void foldRemoveUpdate(Fold fold, DocumentEvent evt); public abstract FoldOperationImpl foldGetOperation(Fold fold); public abstract int foldGetRawIndex(Fold fold); public abstract void foldSetRawIndex(Fold fold, int rawIndex); public abstract void foldUpdateRawIndex(Fold fold, int rawIndexDelta); public abstract Object foldGetExtraInfo(Fold fold); public abstract void foldSetExtraInfo(Fold fold, Object info); public abstract void foldStateChangeCollapsedChanged(FoldStateChange fsc); public abstract void foldStateChangeDescriptionChanged(FoldStateChange fsc); public abstract void foldStateChangeStartOffsetChanged(FoldStateChange fsc, int originalStartOffset); public abstract void foldStateChangeEndOffsetChanged(FoldStateChange fsc, int originalEndOffset); public abstract FoldHierarchyExecution foldGetExecution(FoldHierarchy fh); public abstract void foldMarkDamaged(Fold f, int dmgBits); public abstract int foldStartGuardedLength(Fold f); public abstract int foldEndGuardedLength(Fold f); }
1,610
664
<filename>src/gui/LIIIstyle.h #pragma once #include <QProxyStyle> class LIIIStyle : public QProxyStyle { Q_OBJECT public: void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const override; void drawPrimitive(PrimitiveElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const override; int styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const override; QSize sizeFromContents(ContentsType ct, const QStyleOption* opt, const QSize & csz, const QWidget* widget = 0) const override; };
219
460
<gh_stars>100-1000 // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef _BT_PROFILER_ #define _BT_PROFILER_ #include "BT_Singleton.h" #include "BT_Stopwatch.h" class Profiler { Stopwatch _timer; bool _isProfiling; uint _numFrames; StrList _code_block_names; QHash<QString, uint> _code_blocks; StrList _repeated_code_names; QHash<QString, uint> _repeated_code_blocks; public: Profiler(); ~Profiler(); bool isProfiling(); void incrementTime(QString code_block_name, uint ms); void incrementRepeated(QString code_block_name, uint ms); void start(); void stop(bool ignoreNumFrames = false); void onFrame(); }; #define profiler Singleton<Profiler>::getInstance() #endif
439
457
<gh_stars>100-1000 package denominator.model.rdata; import java.util.LinkedHashMap; import static denominator.common.Preconditions.checkArgument; import static denominator.common.Preconditions.checkNotNull; /** * Corresponds to the binary representation of the {@code A} (Address) RData * * <br> <br> <b>Example</b><br> * * <pre> * AData rdata = AData.create(&quot;192.0.2.1&quot;); * </pre> * * See <a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a> */ public final class AData extends LinkedHashMap<String, Object> { private static final long serialVersionUID = 1L; AData(String address) { checkNotNull(address, "address"); checkArgument(address.indexOf('.') != -1, "%s should be a ipv4 address", address); put("address", address); } /** * @param ipv4address valid ipv4 address. ex. {@code 192.0.2.1} * @throws IllegalArgumentException if the address is malformed or not ipv4 */ public static AData create(String ipv4address) throws IllegalArgumentException { return new AData(ipv4address); } /** * a 32-bit internet address * * @since 1.3 */ public String address() { return get("address").toString(); } }
426
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Chépy","circ":"3ème circonscription","dpt":"Somme","inscrits":898,"abs":495,"votants":403,"blancs":31,"nuls":17,"exp":355,"res":[{"nuance":"LR","nom":"<NAME>","voix":225},{"nuance":"REM","nom":"M. <NAME>","voix":130}]}
111
2,074
<filename>examples/CorePlotGallery/src/plots/ControlChart.h #import "PlotItem.h" @interface ControlChart : PlotItem<CPTPlotDataSource> @end
49
21,382
import pytest from ray.serve.utils import get_random_letters from ray.serve.common import ReplicaName def test_replica_tag_formatting(): deployment_tag = "DeploymentA" replica_suffix = get_random_letters() replica_name = ReplicaName(deployment_tag, replica_suffix) assert replica_name.replica_tag == f"{deployment_tag}#{replica_suffix}" assert str(replica_name) == f"{deployment_tag}#{replica_suffix}" def test_replica_name_from_str(): replica_suffix = get_random_letters() replica_tag = f"DeploymentA#{replica_suffix}" replica_name = ReplicaName.from_str(replica_tag) assert replica_name.replica_tag == replica_tag assert str(replica_tag) == replica_tag def test_invalid_name_from_str(): replica_suffix = get_random_letters() replica_tag = f"DeploymentA##{replica_suffix}" with pytest.raises(AssertionError): ReplicaName.from_str(replica_tag) if __name__ == "__main__": import sys sys.exit(pytest.main(["-v", "-s", __file__]))
390
451
#!/usr/bin/env python # # usage: extcode_mach.py input_filename output_filename # # Evaluates the output and residual for the implicit relationship # between the area ratio and mach number. # # Read the value of `area_ratio` from input file # and writes the values or residuals of `mach` to output file depending on what is requested. # What is requested is given by the first line in the file read. It can be either 'residuals' or # 'outputs'. def area_ratio_explicit(mach): """Explicit isentropic relationship between area ratio and Mach number""" gamma = 1.4 gamma_p_1 = gamma + 1 gamma_m_1 = gamma - 1 exponent = gamma_p_1 / (2 * gamma_m_1) return (gamma_p_1 / 2.) ** -exponent * ( (1 + gamma_m_1 / 2. * mach ** 2) ** exponent) / mach def mach_residual(mach, area_ratio_target): """If area_ratio is known, then finding Mach is an implicit relationship""" return area_ratio_target - area_ratio_explicit(mach) def mach_solve(area_ratio, super_sonic=False): """Solve for mach, given area ratio""" if super_sonic: initial_guess = 4 else: initial_guess = .1 mach = fsolve(func=mach_residual, x0=initial_guess, args=(area_ratio,))[0] return mach if __name__ == '__main__': import sys from scipy.optimize import fsolve input_filename = sys.argv[1] output_filename = sys.argv[2] with open(input_filename, 'r') as input_file: output_or_resids = input_file.readline().strip() area_ratio = float(input_file.readline()) if output_or_resids == 'residuals': mach = float(input_file.readline()) else: # outputs super_sonic = (input_file.readline().strip() == "True") if output_or_resids == 'outputs': mach_output = mach_solve(area_ratio, super_sonic=super_sonic) with open(output_filename, 'w') as output_file: output_file.write('%.16f\n' % mach_output) elif output_or_resids == 'residuals': mach_resid = mach_residual(mach, area_ratio) with open(output_filename, 'w') as output_file: output_file.write('%.16f\n' % mach_resid)
871
774
// // NetPeer.h // // Lunar Unity Mobile Console // https://github.com/SpaceMadness/lunar-unity-console // // Copyright 2015-2021 <NAME>, SpaceMadness. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> @class NetPeer; @interface NetPeerMessage : NSObject @property (nonatomic, readonly) NSString *name; @property (nonatomic, readonly) NSDictionary *payload; - (instancetype)initWithName:(NSString *)name; - (instancetype)initWithData:(NSData *)data; - (id)objectForKeyedSubscript:(NSString *)key; - (void)setObject:(id)obj forKeyedSubscript:(NSString *)key; - (NSData *)toJsonData; @end @protocol NetPeerDelegate <NSObject> @optional - (void)clientDidConnect; - (void)serverDidConnect; - (void)peer:(NetPeer *)peer didReceiveMessage:(NetPeerMessage *)message; - (void)peerDidReceiveAck:(NetPeer *)peer; @end @interface NetPeer : NSObject @property (nonatomic, weak) id<NetPeerDelegate> delegate; - (void)startListeningOnPort:(uint16_t)port; - (void)connectToHost:(NSString *)host port:(uint16_t)port; - (void)sendMessage:(NetPeerMessage *)message; - (void)shutdown; @end
546
1,681
# -*- coding: utf-8 -*- """ ============================= Labeling your datapoints ============================= This is an example of how to use the `label(s)` kwarg, which must be a list the length of the number of datapoints (rows) you have in the matrix. Here, we are simply labeling the first datapoint for each matrix in the list. """ # Code source: <NAME> # License: MIT # import import hypertools as hyp import numpy as np # load example data geo = hyp.load('weights_sample') data = geo.get_data() # simulate labels labels=[] for idx,i in enumerate(data): tmp=[] for iidx,ii in enumerate(i): if iidx==0: tmp.append('Subject ' + str(idx)) else: tmp.append(None) labels.append(tmp) # plot geo.plot(fmt='.', labels=labels)
299
1,253
<filename>greedy/fractional_knapsack/c++/fractional_knapsack.cpp #include <bits/stdc++.h> using namespace std; int main() { int num_items, capacity; printf("Enter number of items and capacity of sack:"); scanf("%d%d", &num_items, &capacity); vector <pair <float, pair<int, int> > > vec; printf("Enter value and weight of each item:"); for(int i = 0; i < num_items; i++) { int v, w; scanf("%d%d", &v, &w); vec.push_back(make_pair((float)v / w, make_pair(v, w))); } int item = 0; float max = 0; sort(vec.rbegin(), vec.rend()); while(capacity) { if(vec[item].second.second <= capacity) { capacity -= vec[item].second.second; max += vec[item].second.first; item++; } else { float frac = (float) capacity / vec[item].second.second; max += ((float) vec[item].second.first * frac); item++; break; } } cout << max; }
372
4,013
import unittest from checkov.terraform.checks.provider.aws.credentials import check from checkov.common.models.enums import CheckResult class TestCredentials(unittest.TestCase): def test_success(self): provider_conf = {'region': ['us-west-2']} scan_result = check.scan_provider_conf(conf=provider_conf) self.assertEqual(CheckResult.PASSED, scan_result) provider_conf = {} scan_result = check.scan_provider_conf(conf=provider_conf) self.assertEqual(CheckResult.PASSED, scan_result) def test_failure(self): provider_conf = {'region': ['us-west-2'], 'access_key': ['AKIAIOSFODNN7EXAMPLE'], 'secret_key': ['<KEY>']} scan_result = check.scan_provider_conf(conf=provider_conf) self.assertEqual(CheckResult.FAILED, scan_result) provider_conf = {'region': ['us-west-2'], 'secret_key': ['<KEY>']} scan_result = check.scan_provider_conf(conf=provider_conf) self.assertEqual(CheckResult.FAILED, scan_result) provider_conf = {'region': ['us-west-2'], 'access_key': ['AKIAIOSFODNN7EXAMPLE']} scan_result = check.scan_provider_conf(conf=provider_conf) self.assertEqual(CheckResult.FAILED, scan_result) if __name__ == '__main__': unittest.main()
533
475
/* Vector-pool aggregation based local feature aggregation for point cloud. PV-RCNN++: Point-Voxel Feature Set Abstraction With Local Vector Representation for 3D Object Detection https://arxiv.org/abs/2102.00463 Written by <NAME> All Rights Reserved 2020. */ #ifndef _STACK_VECTOR_POOL_GPU_H #define _STACK_VECTOR_POOL_GPU_H #include <torch/serialize/tensor.h> #include <vector> #include <cuda.h> #include <cuda_runtime_api.h> int query_stacked_local_neighbor_idxs_kernel_launcher_stack( const float *support_xyz, const int *xyz_batch_cnt, const float *new_xyz, const int *new_xyz_batch_cnt, int *stack_neighbor_idxs, int *start_len, int *cumsum, int avg_length_of_neighbor_idxs, float max_neighbour_distance, int batch_size, int M, int nsample, int neighbor_type); int query_stacked_local_neighbor_idxs_wrapper_stack(at::Tensor support_xyz_tensor, at::Tensor xyz_batch_cnt_tensor, at::Tensor new_xyz_tensor, at::Tensor new_xyz_batch_cnt_tensor, at::Tensor stack_neighbor_idxs_tensor, at::Tensor start_len_tensor, at::Tensor cumsum_tensor, int avg_length_of_neighbor_idxs, float max_neighbour_distance, int nsample, int neighbor_type); int query_three_nn_by_stacked_local_idxs_kernel_launcher_stack( const float *support_xyz, const float *new_xyz, const float *new_xyz_grid_centers, int *new_xyz_grid_idxs, float *new_xyz_grid_dist2, const int *stack_neighbor_idxs, const int *start_len, int M, int num_total_grids); int query_three_nn_by_stacked_local_idxs_wrapper_stack(at::Tensor support_xyz_tensor, at::Tensor new_xyz_tensor, at::Tensor new_xyz_grid_centers_tensor, at::Tensor new_xyz_grid_idxs_tensor, at::Tensor new_xyz_grid_dist2_tensor, at::Tensor stack_neighbor_idxs_tensor, at::Tensor start_len_tensor, int M, int num_total_grids); int vector_pool_wrapper_stack(at::Tensor support_xyz_tensor, at::Tensor xyz_batch_cnt_tensor, at::Tensor support_features_tensor, at::Tensor new_xyz_tensor, at::Tensor new_xyz_batch_cnt_tensor, at::Tensor new_features_tensor, at::Tensor new_local_xyz, at::Tensor point_cnt_of_grid_tensor, at::Tensor grouped_idxs_tensor, int num_grid_x, int num_grid_y, int num_grid_z, float max_neighbour_distance, int use_xyz, int num_max_sum_points, int nsample, int neighbor_type, int pooling_type); int vector_pool_kernel_launcher_stack( const float *support_xyz, const float *support_features, const int *xyz_batch_cnt, const float *new_xyz, float *new_features, float * new_local_xyz, const int *new_xyz_batch_cnt, int *point_cnt_of_grid, int *grouped_idxs, int num_grid_x, int num_grid_y, int num_grid_z, float max_neighbour_distance, int batch_size, int N, int M, int num_c_in, int num_c_out, int num_total_grids, int use_xyz, int num_max_sum_points, int nsample, int neighbor_type, int pooling_type); int vector_pool_grad_wrapper_stack(at::Tensor grad_new_features_tensor, at::Tensor point_cnt_of_grid_tensor, at::Tensor grouped_idxs_tensor, at::Tensor grad_support_features_tensor); void vector_pool_grad_kernel_launcher_stack( const float *grad_new_features, const int *point_cnt_of_grid, const int *grouped_idxs, float *grad_support_features, int N, int M, int num_c_out, int num_c_in, int num_total_grids, int num_max_sum_points); #endif
1,332
12,278
// Boost.Geometry // Copyright (c) 2016, 2018 Oracle and/or its affiliates. // Contributed and/or modified by <NAME>, on behalf of Oracle // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_FORMULAS_ECCENCRICITY_SQR_HPP #define BOOST_GEOMETRY_FORMULAS_ECCENCRICITY_SQR_HPP #include <boost/geometry/algorithms/not_implemented.hpp> #include <boost/geometry/core/radius.hpp> #include <boost/geometry/core/tag.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/util/math.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DISPATCH namespace formula_dispatch { template <typename ResultType, typename Geometry, typename Tag = typename tag<Geometry>::type> struct eccentricity_sqr : not_implemented<Tag> {}; template <typename ResultType, typename Geometry> struct eccentricity_sqr<ResultType, Geometry, srs_sphere_tag> { static inline ResultType apply(Geometry const& /*geometry*/) { return ResultType(0); } }; template <typename ResultType, typename Geometry> struct eccentricity_sqr<ResultType, Geometry, srs_spheroid_tag> { static inline ResultType apply(Geometry const& geometry) { // 1 - (b / a)^2 return ResultType(1) - math::sqr(ResultType(get_radius<2>(geometry)) / ResultType(get_radius<0>(geometry))); } }; } // namespace formula_dispatch #endif // DOXYGEN_NO_DISPATCH #ifndef DOXYGEN_NO_DETAIL namespace formula { template <typename ResultType, typename Geometry> ResultType eccentricity_sqr(Geometry const& geometry) { return formula_dispatch::eccentricity_sqr<ResultType, Geometry>::apply(geometry); } } // namespace formula #endif // DOXYGEN_NO_DETAIL }} // namespace boost::geometry #endif // BOOST_GEOMETRY_FORMULAS_ECCENCRICITY_SQR_HPP
755
335
<gh_stars>100-1000 { "word": "Carol", "definitions": [ "Sing or say (something) happily.", "The activity of singing Christmas carols." ], "parts-of-speech": "Verb" }
86
852
<filename>PhysicsTools/HeppyCore/python/statistics/counter.py<gh_stars>100-1000 # Copyright (C) 2014 <NAME> # https://github.com/cbernet/heppy/blob/master/LICENSE from builtins import range import pickle from PhysicsTools.HeppyCore.utils.diclist import diclist class Counter(diclist): def __init__(self, name): self.name = name super(Counter, self).__init__() def register(self, level): self.add( level, [level, 0] ) def inc(self, level, nentries=1): '''increment an existing level ''' if level not in self.dico: raise ValueError('level', level, 'has not been registered') else: self[level][1] += nentries def __add__(self, other): '''Add two counters (+).''' size = max( len(self), len(other)) for i in range(0, size): if i>=len(other): # this line exists only in this counter, leave it as is continue elif i>=len(self): self.register( other[i][0]) self.inc( other[i][0], other[i][1] ) else: if self[i][0] != other[i][0]: err = ['cannot add these counters:', str(self), str(other)] raise ValueError('\n'.join(err)) else: self.inc( other[i][0], other[i][1] ) return self def __iadd__(self, other): '''Add two counters (+=).''' return self.__add__(other) def write(self, dirname): '''Dump the counter to a pickle file and to a text file in dirname.''' pckfname = '{d}/{f}.pck'.format(d=dirname, f=self.name) pckfname = pckfname.replace('*','STAR') pckfile = open( pckfname, 'w' ) pickle.dump(self, pckfile) txtfile = open( pckfname.replace('.pck', '.txt'), 'w') txtfile.write( str(self) ) txtfile.write( '\n' ) txtfile.close() def __str__(self): retstr = 'Counter %s :\n' % self.name prev = None init = None for level, count in self: if prev == None: prev = count init = count if prev == 0: eff1 = -1. else: eff1 = float(count)/prev if init == 0: eff2 = -1. else: eff2 = float(count)/init retstr += '\t {level:<40} {count:>9} \t {eff1:4.2f} \t {eff2:6.4f}\n'.format( level=level, count=count, eff1=eff1, eff2=eff2 ) prev = count return retstr class Counters(object): ''' TODO: could be a diclist? ''' def __init__( self ): self.counters = [] self.ranks = {} def addCounter(self, name): self.ranks[ name ] = len( self.counters ) self.counters.append( Counter(name) ) def counter(self, name): return self.counters[ self.ranks[name] ] def write(self, dirname): map( lambda x: x.write(dirname), self.counters) def __str__(self): prints = map( str, self.counters ) return '\n'.join(prints) def __getitem__(self, name): return self.counter(name)
1,726
372
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.container.model; /** * AutoUpgradeOptions defines the set of options for the user to control how the Auto Upgrades will * proceed. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Kubernetes Engine API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class AutoUpgradeOptions extends com.google.api.client.json.GenericJson { /** * [Output only] This field is set when upgrades are about to commence with the approximate start * time for the upgrades, in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String autoUpgradeStartTime; /** * [Output only] This field is set when upgrades are about to commence with the description of the * upgrade. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * [Output only] This field is set when upgrades are about to commence with the approximate start * time for the upgrades, in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) text format. * @return value or {@code null} for none */ public java.lang.String getAutoUpgradeStartTime() { return autoUpgradeStartTime; } /** * [Output only] This field is set when upgrades are about to commence with the approximate start * time for the upgrades, in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) text format. * @param autoUpgradeStartTime autoUpgradeStartTime or {@code null} for none */ public AutoUpgradeOptions setAutoUpgradeStartTime(java.lang.String autoUpgradeStartTime) { this.autoUpgradeStartTime = autoUpgradeStartTime; return this; } /** * [Output only] This field is set when upgrades are about to commence with the description of the * upgrade. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * [Output only] This field is set when upgrades are about to commence with the description of the * upgrade. * @param description description or {@code null} for none */ public AutoUpgradeOptions setDescription(java.lang.String description) { this.description = description; return this; } @Override public AutoUpgradeOptions set(String fieldName, Object value) { return (AutoUpgradeOptions) super.set(fieldName, value); } @Override public AutoUpgradeOptions clone() { return (AutoUpgradeOptions) super.clone(); } }
1,046
407
// MIT License // // Copyright (c) 2019 <NAME>, Chair for Embedded Security. All Rights reserved. // Copyright (c) 2021 Max Planck Institute for Security and Privacy. All Rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include "gui/validator/validator.h" #include <QList> namespace hal { /** * @ingroup gui * @brief Combines different validators into one. * * The StackedValidator is a Validator that combines multiple other Validators. Its validate function returns * <b>true</b> if all added Validators accept the string. <br> * The fail text will be chosen from the firstly added validator which validation fails. */ class StackedValidator : public Validator { public: /** * Constructor. * At this point the StackedValidator will accept any string. * Therefore one should add validators by calling addValidator. */ StackedValidator(); /** * Adds a Validator to the StackedValidator. * * @param v - The Validator to add */ void addValidator(Validator* v); /** * Removes a Validator from the StackedValidator. * * @param v - The Validator to remove */ void removeValidator(Validator* v); /** * Removes all Validators from the StackedValidator. */ void clearValidators(); /** * Given any string this function returns <b>true</b> iff the string is accepted by all registered Validators * (added by StackedValidator:addValidator). * * If no Validator is registered this function always returns true. * If one or more Validators reject the string, the fail text of the failing Validator that was added the * earliest will be chosen. * * @param input - The input string * @returns <b>true</b> iff the string is considered valid (accepted by all validators) */ bool validate(const QString &input); private: QList<Validator*> mValidators; }; }
1,247