max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
16,503 | /* Copyright 2021 Google LLC. 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.
* ===========================================================================*/
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#include <cstddef>
#include <cstring>
#include <vector>
#include "tfjs-backend-wasm/src/cc/backend.h"
#include "tfjs-backend-wasm/src/cc/util.h"
// Must match enum in MirrorPad.ts
enum MirrorPaddingMode {
REFLECT = 0,
SYMMETRIC = 1,
};
namespace {
using tfjs::util::compute_strides;
using tfjs::util::size_from_shape;
template <typename T>
void mirror_pad_recursion(const T* x_data, const std::vector<size_t>& x_shape,
const std::vector<size_t>& pre_paddings,
const std::vector<size_t>& post_paddings,
const int32_t offset,
const std::vector<size_t>& in_strides,
const std::vector<size_t>& out_strides, T* out_data,
const size_t dim, size_t in_offset,
size_t out_offset) {
const size_t depth = x_shape[dim];
const size_t rank = x_shape.size();
const size_t in_stride = dim == rank - 1 ? 1 : in_strides[dim];
const size_t out_stride = dim == rank - 1 ? 1 : out_strides[dim];
out_offset += pre_paddings[dim] * out_stride;
if (dim == rank - 1) {
memcpy(out_data + out_offset, x_data + in_offset, sizeof(T) * depth);
} else {
for (size_t i = 0; i < depth; ++i) {
mirror_pad_recursion(x_data, x_shape, pre_paddings, post_paddings, offset,
in_strides, out_strides, out_data, dim + 1,
in_offset + in_stride * i,
out_offset + out_stride * i);
}
}
const T* src = out_data + out_offset + offset * out_stride;
T* dist = out_data + out_offset - out_stride;
for (size_t i = 0; i < pre_paddings[dim]; ++i) {
memcpy(dist, src, out_stride * sizeof(T));
src += out_stride;
dist -= out_stride;
}
out_offset += (depth - 1) * out_stride;
src = out_data + out_offset - offset * out_stride;
dist = out_data + out_offset + out_stride;
for (size_t i = 0; i < post_paddings[dim]; ++i) {
memcpy(dist, src, out_stride * sizeof(T));
src -= out_stride;
dist += out_stride;
}
}
template <typename T>
void mirror_pad(const T* x_data, const std::vector<size_t>& x_shape,
const std::vector<size_t>& pre_paddings,
const std::vector<size_t>& post_paddings,
const MirrorPaddingMode mode, T* out_data) {
const size_t rank = x_shape.size();
std::vector<size_t> out_shape(rank);
for (size_t i = 0; i < rank; ++i) {
const size_t pad_left = pre_paddings[i];
const size_t pad_right = post_paddings[i];
out_shape[i] = x_shape[i] + pad_left + pad_right;
}
const int32_t offset = mode == MirrorPaddingMode::REFLECT ? 1 : 0;
std::vector<size_t> in_strides = compute_strides(x_shape);
std::vector<size_t> out_strides = compute_strides(out_shape);
mirror_pad_recursion(x_data, x_shape, pre_paddings, post_paddings, offset,
in_strides, out_strides, out_data, 0, 0, 0);
}
} // namespace
namespace tfjs {
namespace wasm {
// We use C-style API to interface with Javascript.
extern "C" {
#ifdef __EMSCRIPTEN__
EMSCRIPTEN_KEEPALIVE
#endif
void MirrorPad(const size_t x_id, const size_t* x_shape_ptr,
const size_t x_shape_length, const DType dtype,
const size_t* pre_paddings_ptr, const size_t* post_paddings_ptr,
const MirrorPaddingMode mode, const size_t out_id) {
auto x_shape = std::vector<size_t>(x_shape_ptr, x_shape_ptr + x_shape_length);
auto pre_paddings =
std::vector<size_t>(pre_paddings_ptr, pre_paddings_ptr + x_shape_length);
auto post_paddings = std::vector<size_t>(post_paddings_ptr,
post_paddings_ptr + x_shape_length);
auto& x_info = backend::get_tensor_info(x_id);
auto& out_info = backend::get_tensor_info_out(out_id);
switch (dtype) {
case DType::float32:
mirror_pad<float>(x_info.f32(), x_shape, pre_paddings, post_paddings,
mode, out_info.f32_write());
break;
case DType::int32:
mirror_pad<int32_t>(x_info.i32(), x_shape, pre_paddings, post_paddings,
mode, out_info.i32_write());
break;
case DType::boolean:
mirror_pad<bool>(x_info.b(), x_shape, pre_paddings, post_paddings, mode,
out_info.b_write());
break;
default:
util::warn("MirrorPad for tensor id %d failed. Unknown dtype % d ", x_id,
dtype);
}
}
} // extern "C"
} // namespace wasm
} // namespace tfjs
| 2,352 |
1,664 | <filename>ambari-server/src/main/java/org/apache/ambari/server/controller/ivory/Cluster.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.apache.ambari.server.controller.ivory;
import java.util.Map;
import java.util.Set;
/**
* Ivory cluster.
*/
public class Cluster {
private final String name;
private final String colo;
private final Set<Interface> interfaces;
private final Set<Location> locations;
private final Map<String, String> properties;
/**
* Construct a cluster.
*
* @param name the cluster name
* @param colo the colo
* @param interfaces the interfaces
* @param locations the locations
* @param properties the properties
*/
public Cluster(String name, String colo, Set<Interface> interfaces, Set<Location> locations, Map<String, String> properties) {
this.name = name;
this.colo = colo;
this.interfaces = interfaces;
this.locations = locations;
this.properties = properties;
}
/**
* Get the cluster name.
*
* @return the cluster name
*/
public String getName() {
return name;
}
/**
* Get the colo.
*
* @return the colo
*/
public String getColo() {
return colo;
}
/**
* Get the interfaces.
*
* @return the interfaces
*/
public Set<Interface> getInterfaces() {
return interfaces;
}
/**
* Get the locations.
*
* @return the locations
*/
public Set<Location> getLocations() {
return locations;
}
/**
* Get the properties.
*
* @return the properties
*/
public Map<String, String> getProperties() {
return properties;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cluster cluster = (Cluster) o;
return !(colo != null ? !colo.equals(cluster.colo) : cluster.colo != null) &&
!(interfaces != null ? !interfaces.equals(cluster.interfaces) : cluster.interfaces != null) &&
!(locations != null ? !locations.equals(cluster.locations) : cluster.locations != null) &&
!(name != null ? !name.equals(cluster.name) : cluster.name != null) &&
!(properties != null ? !properties.equals(cluster.properties) : cluster.properties != null);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (colo != null ? colo.hashCode() : 0);
result = 31 * result + (interfaces != null ? interfaces.hashCode() : 0);
result = 31 * result + (locations != null ? locations.hashCode() : 0);
result = 31 * result + (properties != null ? properties.hashCode() : 0);
return result;
}
// ----- inner classes -----------------------------------------------------
/**
* Cluster interface.
*/
public static class Interface {
private final String type;
private final String endpoint;
private final String version;
/**
* Construct an interface.
*
* @param type the type
* @param endpoint the endpoint
* @param version the version
*/
public Interface(String type, String endpoint, String version) {
this.type = type;
this.endpoint = endpoint;
this.version = version;
}
/**
* Get the type.
*
* @return the type
*/
public String getType() {
return type;
}
/**
* Get the endpoint.
*
* @return the endpoint
*/
public String getEndpoint() {
return endpoint;
}
/**
* Get the version.
*
* @return the version
*/
public String getVersion() {
return version;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Interface that = (Interface) o;
return !(endpoint != null ? !endpoint.equals(that.endpoint) : that.endpoint != null) &&
!(type != null ? !type.equals(that.type) : that.type != null) &&
!(version != null ? !version.equals(that.version) : that.version != null);
}
@Override
public int hashCode() {
int result = type != null ? type.hashCode() : 0;
result = 31 * result + (endpoint != null ? endpoint.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
/**
* Cluster location
*/
public static class Location {
private final String name;
private final String path;
/**
* Construct a location.
*
* @param name the name
* @param path the path
*/
public Location(String name, String path) {
this.name = name;
this.path = path;
}
/**
* Get the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Get the path.
*
* @return the path
*/
public String getPath() {
return path;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Location location = (Location) o;
return !(name != null ? !name.equals(location.name) : location.name != null) &&
!(path != null ? !path.equals(location.path) : location.path != null);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (path != null ? path.hashCode() : 0);
return result;
}
}
}
| 2,313 |
611 | <filename>torchdata/datapipes/map/util/unzipper.py
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional, Sequence, TypeVar
from torchdata.datapipes import functional_datapipe
from torchdata.datapipes.map import MapDataPipe
T = TypeVar("T")
@functional_datapipe("unzip")
class UnZipperMapDataPipe(MapDataPipe):
"""
Takes in a DataPipe of Sequences, unpacks each Sequence, and return the elements in separate DataPipes
based on their position in the Sequence (functional name: ``unzip``). The number of instances produced
equals to the ``sequence_legnth`` minus the number of columns to skip.
Note:
Each sequence within the DataPipe should have the same length, specified by
the input argument `sequence_length`.
Args:
source_datapipe: Iterable DataPipe with sequences of data
sequence_length: Length of the sequence within the source_datapipe. All elements should have the same length.
columns_to_skip: optional indices of columns that the DataPipe should skip (each index should be
an integer from 0 to sequence_length - 1)
Example:
>>> from torchdata.datapipes.iter import SequenceWrapper
>>> source_dp = SequenceWrapper([(i, i + 10, i + 20) for i in range(3)])
>>> dp1, dp2, dp3 = source_dp.unzip(sequence_length=3)
>>> list(dp1)
[0, 1, 2]
>>> list(dp2)
[10, 11, 12]
>>> list(dp3)
[20, 21, 22]
"""
def __new__(
cls,
source_datapipe: MapDataPipe[Sequence[T]],
sequence_length: int,
columns_to_skip: Optional[Sequence[int]] = None,
):
if sequence_length < 1:
raise ValueError(f"Expected `sequence_length` larger than 0, but {sequence_length} is found")
if columns_to_skip is None:
instance_ids = list(range(sequence_length))
else:
skips = set(columns_to_skip)
instance_ids = [i for i in range(sequence_length) if i not in skips]
if len(instance_ids) == 0:
raise RuntimeError(
f"All instances are being filtered out in {cls.__name__}. Please check"
"the input `sequence_length` and `columns_to_skip`."
)
return [_UnZipperMapDataPipe(source_datapipe, i) for i in instance_ids]
class _UnZipperMapDataPipe(MapDataPipe[T]):
def __init__(self, main_datapipe: MapDataPipe[Sequence[T]], instance_id: int):
self.main_datapipe = main_datapipe
self.instance_id = instance_id
def __getitem__(self, index) -> T:
return self.main_datapipe[index][self.instance_id]
def __len__(self) -> int:
return len(self.main_datapipe)
| 1,150 |
723 | package net.dongliu.apk.parser.struct.resource;
import net.dongliu.apk.parser.struct.ResourceValue;
import javax.annotation.Nullable;
import java.util.Locale;
/**
* A Resource entry specifies the key (name) of the Resource.
* It is immediately followed by the value of that Resource.
*
* @author dongliu
*/
public class ResourceEntry {
// Number of bytes in this structure. uint16_t
private int size;
// If set, this is a complex entry, holding a set of name/value
// mappings. It is followed by an array of ResTable_map structures.
public static final int FLAG_COMPLEX = 0x0001;
// If set, this resource has been declared public, so libraries
// are allowed to reference it.
public static final int FLAG_PUBLIC = 0x0002;
// uint16_t
private int flags;
// Reference into ResTable_package::keyStrings identifying this entry.
//public long keyRef;
private String key;
// the resvalue following this resource entry.
private ResourceValue value;
/**
* get value as string
*
* @return
*/
public String toStringValue(ResourceTable resourceTable, Locale locale) {
if (value != null) {
return value.toStringValue(resourceTable, locale);
} else {
return "null";
}
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getFlags() {
return flags;
}
public void setFlags(int flags) {
this.flags = flags;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Nullable
public ResourceValue getValue() {
return value;
}
@Nullable
public void setValue(@Nullable ResourceValue value) {
this.value = value;
}
@Override
public String toString() {
return "ResourceEntry{" +
"size=" + size +
", flags=" + flags +
", key='" + key + '\'' +
", value=" + value +
'}';
}
}
| 851 |
1,405 | package android.support.v4.os;
import android.os.Trace;
class TraceJellybeanMR2 {
TraceJellybeanMR2() {
}
public static void beginSection(String section) {
Trace.beginSection(section);
}
public static void endSection() {
Trace.endSection();
}
}
| 113 |
575 | <gh_stars>100-1000
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SSL_INSECURE_SENSITIVE_INPUT_DRIVER_H_
#define CHROME_BROWSER_SSL_INSECURE_SENSITIVE_INPUT_DRIVER_H_
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "third_party/blink/public/mojom/insecure_input/insecure_input_service.mojom.h"
namespace content {
class RenderFrameHost;
}
// The InsecureSensitiveInputDriver watches for calls from renderers and
// instructs the parent |InsecureSensitiveInputDriverFactory| monitoring the
// WebContents to update the SSLStatusInputEventData.
//
// There is one InsecureSensitiveInputDriver per RenderFrameHost.
// The lifetime is managed by the InsecureSensitiveInputDriverFactory.
class InsecureSensitiveInputDriver : public blink::mojom::InsecureInputService {
public:
explicit InsecureSensitiveInputDriver(
content::RenderFrameHost* render_frame_host);
~InsecureSensitiveInputDriver() override;
void BindInsecureInputServiceReceiver(
mojo::PendingReceiver<blink::mojom::InsecureInputService> receiver);
// blink::mojom::InsecureInputService:
void DidEditFieldInInsecureContext() override;
private:
content::RenderFrameHost* render_frame_host_;
mojo::ReceiverSet<blink::mojom::InsecureInputService>
insecure_input_receivers_;
DISALLOW_COPY_AND_ASSIGN(InsecureSensitiveInputDriver);
};
#endif // CHROME_BROWSER_SSL_INSECURE_SENSITIVE_INPUT_DRIVER_H_
| 525 |
1,056 | <reponame>timfel/netbeans
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.web.monitor.data;
import java.beans.PropertyChangeListener;
import java.util.Vector;
import javax.servlet.http.Cookie;
import org.netbeans.modules.schema2beans.BaseBean;
import org.netbeans.modules.schema2beans.BeanComparator;
import org.netbeans.modules.schema2beans.BeanProp;
import org.netbeans.modules.schema2beans.Common;
import org.netbeans.modules.schema2beans.Version;
public class CookieIn extends BaseBean {
static Vector<BeanComparator> comparators = new Vector<>();
public CookieIn() {
this(Common.USE_DEFAULT_VALUES);
}
public CookieIn(Cookie cookie) {
super(comparators, new Version(1, 0, 5));
this.setAttributeValue("name", cookie.getName());//NOI18N
this.setAttributeValue("value", cookie.getValue());//NOI18N
}
public CookieIn(String name, String value) {
super(comparators, new Version(1, 0, 5));
this.setAttributeValue("name", name);//NOI18N
this.setAttributeValue("value", value);//NOI18N
}
public CookieIn(int options) {
super(comparators, new Version(1, 0, 6));
// Properties (see root bean comments for the bean graph)
this.initialize(options);
}
// Setting the default values of the properties
void initialize(int options)
{
}
// This method verifies that the mandatory properties are set
public boolean verify()
{
return true;
}
/**
* Get the value of name.
* @return Value of name.
*/
public String getName() {return this.getAttributeValue("name");} //NOI18N
/**
* Set the value of Name.
* @param v Value to assign to name.
*/
public void setName(String v) {this.setAttributeValue("name", v);} //NOI18N
/**
* Get the value of value.
* @return Value of value.
*/
public String getValue() {return this.getAttributeValue("value");} //NOI18N
/**
* Set the value of value.
* @param v Value to assign to value.
*/
public void setValue(String v) {this.setAttributeValue("value", v);} //NOI18N
//
static public void addComparator(BeanComparator c)
{
CookieIn.comparators.add(c);
}
//
static public void removeComparator(BeanComparator c)
{
CookieIn.comparators.remove(c);
}
//
public void addPropertyChangeListener(PropertyChangeListener l)
{
BeanProp p = this.beanProp();
if (p != null)
p.addPCListener(l);
}
//
public void removePropertyChangeListener(PropertyChangeListener l)
{
BeanProp p = this.beanProp();
if (p != null)
p.removePCListener(l);
}
//
public void addPropertyChangeListener(String n, PropertyChangeListener l)
{
BeanProp p = this.beanProp(n);
if (p != null)
p.addPCListener(l);
}
//
public void removePropertyChangeListener(String n, PropertyChangeListener l)
{
BeanProp p = this.beanProp(n);
if (p != null)
p.removePCListener(l);
}
// Dump the content of this bean returning it as a String
public void dump(StringBuffer str, String indent)
{
String s;
BaseBean n;
}
public String dumpBeanNode()
{
StringBuffer str = new StringBuffer();
str.append("CookieIn\n");//NOI18N
this.dump(str, "\n ");//NOI18N
return str.toString();
}
}
| 1,485 |
1,602 | /* $Source: bitbucket.org:berkeleylab/gasnet.git/gasnet.h $
* Description: GASNet -> GASNet-EX transitional header
* Copyright 2016, The Regents of the University of California
* Terms of use are as specified in license.txt
*/
#ifndef _GASNET_H
#define _GASNET_H
#define _INCLUDED_GASNET_H
#include <gasnetex.h>
#include <gasnet_tools.h>
GASNETT_BEGIN_EXTERNC
GASNETI_BEGIN_NOWARN
/* ------------------------------------------------------------------------------------ */
/*
Globals
=====================
*/
extern gex_Client_t gasneti_thunk_client;
extern gex_EP_t gasneti_thunk_endpoint;
extern gex_TM_t gasneti_thunk_tm;
extern gex_Segment_t gasneti_thunk_segment;
/* ------------------------------------------------------------------------------------ */
/*
Compile-time constants
=====================
*/
#define SIZEOF_GASNET_REGISTER_VALUE_T SIZEOF_GEX_RMA_VALUE_T
/* public spec version numbers */
#define GASNET_SPEC_VERSION_MAJOR GASNETI_SPEC_VERSION_MAJOR
#define GASNET_SPEC_VERSION_MINOR GASNETI_SPEC_VERSION_MINOR
/* legacy name for major spec version number */
#define GASNET_VERSION GASNET_SPEC_VERSION_MAJOR
/* ------------------------------------------------------------------------------------ */
/*
Base types
==========
*/
typedef gex_Rank_t gasnet_node_t;
typedef gex_Token_t gasnet_token_t;
typedef gex_AM_Index_t gasnet_handler_t;
typedef gex_AM_Arg_t gasnet_handlerarg_t;
typedef gex_RMA_Value_t gasnet_register_value_t;
typedef gex_Event_t gasnet_handle_t;
#define GASNET_INVALID_HANDLE GEX_EVENT_INVALID
typedef struct {
void *addr;
size_t len;
} gasnet_memvec_t;
/* ------------------------------------------------------------------------------------ */
/*
Initialization
==============
*/
GASNETT_INLINE(gasnet_init)
int gasnet_init(int *_argc, char ***_argv) {
gex_Client_t _g2ex_client;
gex_EP_t _g2ex_ep;
gex_TM_t _g2ex_tm;
return gex_Client_Init (&_g2ex_client,
&_g2ex_ep,
&_g2ex_tm,
"LEGACY", _argc, _argv,
GASNETI_FLAG_INIT_LEGACY | GEX_FLAG_USES_GASNET1);
}
extern int gasneti_attach( gex_TM_t _tm,
gasnet_handlerentry_t *_table,
int _numentries,
uintptr_t _segsize);
extern void gasneti_legacy_attach_checks(int _checksegment);
GASNETT_INLINE(gasnet_attach)
int gasnet_attach( gasnet_handlerentry_t *_table, int _numentries,
uintptr_t _segsize, uintptr_t _minheapoffset ) {
gasneti_legacy_attach_checks(0);
if (! _segsize) _segsize = GASNET_PAGESIZE;
int _result = gasneti_attach( gasneti_thunk_tm, _table, _numentries, _segsize);
#if GASNET_SEGMENT_EVERYTHING
gasneti_legacy_attach_checks(0);
#else
gasneti_legacy_attach_checks(1);
#endif
return _result;
}
GASNETT_INLINE(gasnet_QueryGexObjects)
void gasnet_QueryGexObjects( gex_Client_t *_client_p,
gex_EP_t *_endpoint_p,
gex_TM_t *_tm_p,
gex_Segment_t *_segment_p) {
GASNETI_CHECKATTACH();
if (_client_p) *_client_p = gasneti_thunk_client;
if (_endpoint_p) *_endpoint_p = gasneti_thunk_endpoint;
if (_tm_p) *_tm_p = gasneti_thunk_tm;
if (_segment_p) *_segment_p = gasneti_thunk_segment;
}
#define gasnet_mynode() (GASNETI_CHECKINIT(), gex_System_QueryJobRank())
#define gasnet_nodes() (GASNETI_CHECKINIT(), gex_System_QueryJobSize())
/* ------------------------------------------------------------------------------------ */
/*
Active Message Query Functions
==============================
*/
#define gasnet_AMMaxMedium() MIN(gex_AM_LUBRequestMedium(),\
gex_AM_LUBReplyMedium())
#define gasnet_AMMaxLongRequest() gex_AM_LUBRequestLong()
#define gasnet_AMMaxLongReply() gex_AM_LUBReplyLong()
#define gasnet_AMMaxArgs() ((size_t)gex_AM_MaxArgs())
GASNETT_INLINE(gasnet_AMGetMsgSource)
int gasnet_AMGetMsgSource(gasnet_token_t _token, gasnet_node_t *_srcrank) {
gex_Token_Info_t _info;
gex_TI_t _rc = gex_Token_Info(_token, &_info, GEX_TI_SRCRANK);
gasneti_assert(_rc & GEX_TI_SRCRANK);
*_srcrank = _info.gex_srcrank;
return 0;
}
/* ------------------------------------------------------------------------------------ */
/*
Active Message Request/Reply Functions
======================================
These all return 0 in EX for non-immediate, which matches the GASNET_OK success return code in GASNet-1
*/
#define gasnet_AMRequestShort0(dest, handler) \
gex_AM_RequestShort0(gasneti_thunk_tm, dest, handler, 0)
#define gasnet_AMRequestShort1(dest, handler, a0) \
gex_AM_RequestShort1(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0)
#define gasnet_AMRequestShort2(dest, handler, a0, a1) \
gex_AM_RequestShort2(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1)
#define gasnet_AMRequestShort3(dest, handler, a0, a1, a2) \
gex_AM_RequestShort3(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2)
#define gasnet_AMRequestShort4(dest, handler, a0, a1, a2, a3) \
gex_AM_RequestShort4(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3)
#define gasnet_AMRequestShort5(dest, handler, a0, a1, a2, a3, a4) \
gex_AM_RequestShort5(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4)
#define gasnet_AMRequestShort6(dest, handler, a0, a1, a2, a3, a4, a5) \
gex_AM_RequestShort6(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5)
#define gasnet_AMRequestShort7(dest, handler, a0, a1, a2, a3, a4, a5, a6) \
gex_AM_RequestShort7(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6)
#define gasnet_AMRequestShort8(dest, handler, a0, a1, a2, a3, a4, a5, a6, a7) \
gex_AM_RequestShort8(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7)
#define gasnet_AMRequestShort9( dest, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8 ) \
gex_AM_RequestShort9(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8)
#define gasnet_AMRequestShort10(dest, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) \
gex_AM_RequestShort10(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9)
#define gasnet_AMRequestShort11(dest, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) \
gex_AM_RequestShort11(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10)
#define gasnet_AMRequestShort12(dest, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) \
gex_AM_RequestShort12(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11)
#define gasnet_AMRequestShort13(dest, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) \
gex_AM_RequestShort13(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12)
#define gasnet_AMRequestShort14(dest, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) \
gex_AM_RequestShort14(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13)
#define gasnet_AMRequestShort15(dest, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) \
gex_AM_RequestShort15(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14)
#define gasnet_AMRequestShort16(dest, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) \
gex_AM_RequestShort16(gasneti_thunk_tm, dest, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14, (gex_AM_Arg_t)a15)
/* ------------------------------------------------------------------------------------ */
#define gasnet_AMRequestMedium0(dest, handler, source_addr, nbytes) \
gex_AM_RequestMedium0(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0)
#define gasnet_AMRequestMedium1(dest, handler, source_addr, nbytes, a0) \
gex_AM_RequestMedium1(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0)
#define gasnet_AMRequestMedium2(dest, handler, source_addr, nbytes, a0, a1) \
gex_AM_RequestMedium2(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1)
#define gasnet_AMRequestMedium3(dest, handler, source_addr, nbytes, a0, a1, a2) \
gex_AM_RequestMedium3(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2)
#define gasnet_AMRequestMedium4(dest, handler, source_addr, nbytes, a0, a1, a2, a3) \
gex_AM_RequestMedium4(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3)
#define gasnet_AMRequestMedium5(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4) \
gex_AM_RequestMedium5(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4)
#define gasnet_AMRequestMedium6(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5) \
gex_AM_RequestMedium6(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5)
#define gasnet_AMRequestMedium7(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6) \
gex_AM_RequestMedium7(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6)
#define gasnet_AMRequestMedium8(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7) \
gex_AM_RequestMedium8(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7)
#define gasnet_AMRequestMedium9( dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8 ) \
gex_AM_RequestMedium9(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8)
#define gasnet_AMRequestMedium10(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) \
gex_AM_RequestMedium10(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9)
#define gasnet_AMRequestMedium11(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) \
gex_AM_RequestMedium11(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10)
#define gasnet_AMRequestMedium12(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) \
gex_AM_RequestMedium12(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11)
#define gasnet_AMRequestMedium13(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) \
gex_AM_RequestMedium13(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12)
#define gasnet_AMRequestMedium14(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) \
gex_AM_RequestMedium14(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13)
#define gasnet_AMRequestMedium15(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) \
gex_AM_RequestMedium15(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14)
#define gasnet_AMRequestMedium16(dest, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) \
gex_AM_RequestMedium16(gasneti_thunk_tm, dest, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14, (gex_AM_Arg_t)a15)
/* ------------------------------------------------------------------------------------ */
#define gasnet_AMRequestLong0(dest, handler, source_addr, nbytes, dest_addr) \
gex_AM_RequestLong0(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0)
#define gasnet_AMRequestLong1(dest, handler, source_addr, nbytes, dest_addr, a0) \
gex_AM_RequestLong1(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0)
#define gasnet_AMRequestLong2(dest, handler, source_addr, nbytes, dest_addr, a0, a1) \
gex_AM_RequestLong2(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1)
#define gasnet_AMRequestLong3(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2) \
gex_AM_RequestLong3(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2)
#define gasnet_AMRequestLong4(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3) \
gex_AM_RequestLong4(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3)
#define gasnet_AMRequestLong5(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4) \
gex_AM_RequestLong5(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4)
#define gasnet_AMRequestLong6(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5) \
gex_AM_RequestLong6(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5)
#define gasnet_AMRequestLong7(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6) \
gex_AM_RequestLong7(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6)
#define gasnet_AMRequestLong8(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7) \
gex_AM_RequestLong8(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7)
#define gasnet_AMRequestLong9( dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8 ) \
gex_AM_RequestLong9(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8)
#define gasnet_AMRequestLong10(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) \
gex_AM_RequestLong10(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9)
#define gasnet_AMRequestLong11(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) \
gex_AM_RequestLong11(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10)
#define gasnet_AMRequestLong12(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) \
gex_AM_RequestLong12(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11)
#define gasnet_AMRequestLong13(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) \
gex_AM_RequestLong13(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12)
#define gasnet_AMRequestLong14(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) \
gex_AM_RequestLong14(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13)
#define gasnet_AMRequestLong15(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) \
gex_AM_RequestLong15(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14)
#define gasnet_AMRequestLong16(dest, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) \
gex_AM_RequestLong16(gasneti_thunk_tm, dest, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14, (gex_AM_Arg_t)a15)
/* ------------------------------------------------------------------------------------ */
#define gasnet_AMRequestLongAsync0 gasnet_AMRequestLong0
#define gasnet_AMRequestLongAsync1 gasnet_AMRequestLong1
#define gasnet_AMRequestLongAsync2 gasnet_AMRequestLong2
#define gasnet_AMRequestLongAsync3 gasnet_AMRequestLong3
#define gasnet_AMRequestLongAsync4 gasnet_AMRequestLong4
#define gasnet_AMRequestLongAsync5 gasnet_AMRequestLong5
#define gasnet_AMRequestLongAsync6 gasnet_AMRequestLong6
#define gasnet_AMRequestLongAsync7 gasnet_AMRequestLong7
#define gasnet_AMRequestLongAsync8 gasnet_AMRequestLong8
#define gasnet_AMRequestLongAsync9 gasnet_AMRequestLong9
#define gasnet_AMRequestLongAsync10 gasnet_AMRequestLong10
#define gasnet_AMRequestLongAsync11 gasnet_AMRequestLong11
#define gasnet_AMRequestLongAsync12 gasnet_AMRequestLong12
#define gasnet_AMRequestLongAsync13 gasnet_AMRequestLong13
#define gasnet_AMRequestLongAsync14 gasnet_AMRequestLong14
#define gasnet_AMRequestLongAsync15 gasnet_AMRequestLong15
#define gasnet_AMRequestLongAsync16 gasnet_AMRequestLong16
/* ------------------------------------------------------------------------------------ */
#define gasnet_AMReplyShort0(token, handler) \
gex_AM_ReplyShort0(token, handler, 0)
#define gasnet_AMReplyShort1(token, handler, a0) \
gex_AM_ReplyShort1(token, handler, 0, (gex_AM_Arg_t)a0)
#define gasnet_AMReplyShort2(token, handler, a0, a1) \
gex_AM_ReplyShort2(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1)
#define gasnet_AMReplyShort3(token, handler, a0, a1, a2) \
gex_AM_ReplyShort3(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2)
#define gasnet_AMReplyShort4(token, handler, a0, a1, a2, a3) \
gex_AM_ReplyShort4(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3)
#define gasnet_AMReplyShort5(token, handler, a0, a1, a2, a3, a4) \
gex_AM_ReplyShort5(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4)
#define gasnet_AMReplyShort6(token, handler, a0, a1, a2, a3, a4, a5) \
gex_AM_ReplyShort6(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5)
#define gasnet_AMReplyShort7(token, handler, a0, a1, a2, a3, a4, a5, a6) \
gex_AM_ReplyShort7(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6)
#define gasnet_AMReplyShort8(token, handler, a0, a1, a2, a3, a4, a5, a6, a7) \
gex_AM_ReplyShort8(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7)
#define gasnet_AMReplyShort9( token, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8 ) \
gex_AM_ReplyShort9(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8)
#define gasnet_AMReplyShort10(token, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) \
gex_AM_ReplyShort10(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9)
#define gasnet_AMReplyShort11(token, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) \
gex_AM_ReplyShort11(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10)
#define gasnet_AMReplyShort12(token, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) \
gex_AM_ReplyShort12(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11)
#define gasnet_AMReplyShort13(token, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) \
gex_AM_ReplyShort13(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12)
#define gasnet_AMReplyShort14(token, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) \
gex_AM_ReplyShort14(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13)
#define gasnet_AMReplyShort15(token, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) \
gex_AM_ReplyShort15(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14)
#define gasnet_AMReplyShort16(token, handler, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) \
gex_AM_ReplyShort16(token, handler, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14, (gex_AM_Arg_t)a15)
/* ------------------------------------------------------------------------------------ */
#define gasnet_AMReplyMedium0(token, handler, source_addr, nbytes) \
gex_AM_ReplyMedium0(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0)
#define gasnet_AMReplyMedium1(token, handler, source_addr, nbytes, a0) \
gex_AM_ReplyMedium1(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0)
#define gasnet_AMReplyMedium2(token, handler, source_addr, nbytes, a0, a1) \
gex_AM_ReplyMedium2(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1)
#define gasnet_AMReplyMedium3(token, handler, source_addr, nbytes, a0, a1, a2) \
gex_AM_ReplyMedium3(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2)
#define gasnet_AMReplyMedium4(token, handler, source_addr, nbytes, a0, a1, a2, a3) \
gex_AM_ReplyMedium4(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3)
#define gasnet_AMReplyMedium5(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4) \
gex_AM_ReplyMedium5(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4)
#define gasnet_AMReplyMedium6(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5) \
gex_AM_ReplyMedium6(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5)
#define gasnet_AMReplyMedium7(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6) \
gex_AM_ReplyMedium7(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6)
#define gasnet_AMReplyMedium8(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7) \
gex_AM_ReplyMedium8(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7)
#define gasnet_AMReplyMedium9( token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8 ) \
gex_AM_ReplyMedium9(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8)
#define gasnet_AMReplyMedium10(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) \
gex_AM_ReplyMedium10(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9)
#define gasnet_AMReplyMedium11(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) \
gex_AM_ReplyMedium11(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10)
#define gasnet_AMReplyMedium12(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) \
gex_AM_ReplyMedium12(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11)
#define gasnet_AMReplyMedium13(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) \
gex_AM_ReplyMedium13(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12)
#define gasnet_AMReplyMedium14(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) \
gex_AM_ReplyMedium14(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13)
#define gasnet_AMReplyMedium15(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) \
gex_AM_ReplyMedium15(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14)
#define gasnet_AMReplyMedium16(token, handler, source_addr, nbytes, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) \
gex_AM_ReplyMedium16(token, handler, source_addr, nbytes, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14, (gex_AM_Arg_t)a15)
/* ------------------------------------------------------------------------------------ */
#define gasnet_AMReplyLong0(token, handler, source_addr, nbytes, dest_addr) \
gex_AM_ReplyLong0(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0)
#define gasnet_AMReplyLong1(token, handler, source_addr, nbytes, dest_addr, a0) \
gex_AM_ReplyLong1(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0)
#define gasnet_AMReplyLong2(token, handler, source_addr, nbytes, dest_addr, a0, a1) \
gex_AM_ReplyLong2(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1)
#define gasnet_AMReplyLong3(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2) \
gex_AM_ReplyLong3(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2)
#define gasnet_AMReplyLong4(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3) \
gex_AM_ReplyLong4(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3)
#define gasnet_AMReplyLong5(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4) \
gex_AM_ReplyLong5(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4)
#define gasnet_AMReplyLong6(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5) \
gex_AM_ReplyLong6(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5)
#define gasnet_AMReplyLong7(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6) \
gex_AM_ReplyLong7(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6)
#define gasnet_AMReplyLong8(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7) \
gex_AM_ReplyLong8(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7)
#define gasnet_AMReplyLong9( token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8 ) \
gex_AM_ReplyLong9(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8)
#define gasnet_AMReplyLong10(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) \
gex_AM_ReplyLong10(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9)
#define gasnet_AMReplyLong11(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) \
gex_AM_ReplyLong11(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10)
#define gasnet_AMReplyLong12(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) \
gex_AM_ReplyLong12(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11)
#define gasnet_AMReplyLong13(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) \
gex_AM_ReplyLong13(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12)
#define gasnet_AMReplyLong14(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) \
gex_AM_ReplyLong14(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13)
#define gasnet_AMReplyLong15(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) \
gex_AM_ReplyLong15(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14)
#define gasnet_AMReplyLong16(token, handler, source_addr, nbytes, dest_addr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) \
gex_AM_ReplyLong16(token, handler, source_addr, nbytes, dest_addr, GEX_EVENT_NOW, 0, (gex_AM_Arg_t)a0, (gex_AM_Arg_t)a1, (gex_AM_Arg_t)a2, (gex_AM_Arg_t)a3, (gex_AM_Arg_t)a4, (gex_AM_Arg_t)a5, (gex_AM_Arg_t)a6, (gex_AM_Arg_t)a7, (gex_AM_Arg_t)a8, (gex_AM_Arg_t)a9, (gex_AM_Arg_t)a10, (gex_AM_Arg_t)a11, (gex_AM_Arg_t)a12, (gex_AM_Arg_t)a13, (gex_AM_Arg_t)a14, (gex_AM_Arg_t)a15)
/* ------------------------------------------------------------------------------------ */
/*
Variable-Argument Active Message Request/Reply Functions
========================================================
These were never a normative feature of GASNet-1, but are provided as best-effort for
backwards compatibility of clients who may rely upon them.
They will only be available for compilers supporting C99-style vararg macros - this is
guaranteed by std C99 and C++11, but can otherwise be forced with -DGASNETI_FORCE_VA_ARG
Note these differed in signature from the similar feature in EX in that they require the
client to explicitly pass the argument count before the argument list
*/
#if GASNETI_USING_VA_ARG
#define _GASNETI_ARGCOUNT_VAL(_stem, ...) _stem
#define GASNETI_ARGCOUNT_VAL(...) _GASNETI_ARGCOUNT_VAL(__VA_ARGS__,gasneti_dummy)
// First element of VA_ARGS below is the (possibly computed) argument count,
// which is checked against the actual argument count and then discarded by folding into the flags arg
#define gasnet_AMRequestShort(node,hidx,...) ( \
gasneti_assert_reason_always(GASNETI_ARGCOUNT_VAL(__VA_ARGS__) == GASNETI_AMNUMARGS(__VA_ARGS__), \
"Argument count mismatch to gasnet_AMRequestShort()"), \
GASNETI_AMVA(RequestShort,__VA_ARGS__)(gasneti_thunk_tm,node,hidx,0&&__VA_ARGS__) )
#define gasnet_AMRequestMedium(node,hidx,src_addr,nbytes,...) ( \
gasneti_assert_reason_always(GASNETI_ARGCOUNT_VAL(__VA_ARGS__) == GASNETI_AMNUMARGS(__VA_ARGS__), \
"Argument count mismatch to gasnet_AMRequestMedium()"), \
GASNETI_AMVA(RequestMedium,__VA_ARGS__)(gasneti_thunk_tm,node,hidx,src_addr,nbytes,GEX_EVENT_NOW,0&&__VA_ARGS__) )
#define gasnet_AMRequestLong(node,hidx,src_addr,nbytes,dst_addr,...) ( \
gasneti_assert_reason_always(GASNETI_ARGCOUNT_VAL(__VA_ARGS__) == GASNETI_AMNUMARGS(__VA_ARGS__), \
"Argument count mismatch to gasnet_AMRequestLong()"), \
GASNETI_AMVA(RequestLong,__VA_ARGS__)(gasneti_thunk_tm,node,hidx,src_addr,nbytes,dst_addr,GEX_EVENT_NOW,0&&__VA_ARGS__) )
#define gasnet_AMRequestLongAsync(node,hidx,src_addr,nbytes,dst_addr,...) ( \
gasneti_assert_reason_always(GASNETI_ARGCOUNT_VAL(__VA_ARGS__) == GASNETI_AMNUMARGS(__VA_ARGS__), \
"Argument count mismatch to gasnet_AMRequestLongAsync()"), \
GASNETI_AMVA(RequestLong,__VA_ARGS__)(gasneti_thunk_tm,node,hidx,src_addr,nbytes,dst_addr,GEX_EVENT_NOW,0&&__VA_ARGS__) )
#define gasnet_AMReplyShort(token,hidx,...) ( \
gasneti_assert_reason_always(GASNETI_ARGCOUNT_VAL(__VA_ARGS__) == GASNETI_AMNUMARGS(__VA_ARGS__), \
"Argument count mismatch to gasnet_AMReplyShort()"), \
GASNETI_AMVA(ReplyShort,__VA_ARGS__)(token,hidx,0&&__VA_ARGS__) )
#define gasnet_AMReplyMedium(token,hidx,src_addr,nbytes,...) ( \
gasneti_assert_reason_always(GASNETI_ARGCOUNT_VAL(__VA_ARGS__) == GASNETI_AMNUMARGS(__VA_ARGS__), \
"Argument count mismatch to gasnet_AMReplyMedium()"), \
GASNETI_AMVA(ReplyMedium,__VA_ARGS__)(token,hidx,src_addr,nbytes,GEX_EVENT_NOW,0&&__VA_ARGS__) )
#define gasnet_AMReplyLong(token,hidx,src_addr,nbytes,dst_addr,...) ( \
gasneti_assert_reason_always(GASNETI_ARGCOUNT_VAL(__VA_ARGS__) == GASNETI_AMNUMARGS(__VA_ARGS__), \
"Argument count mismatch to gasnet_AMReplyLong()"), \
GASNETI_AMVA(ReplyLong,__VA_ARGS__)(token,hidx,src_addr,nbytes,dst_addr,GEX_EVENT_NOW,0&&__VA_ARGS__) )
#endif
/* ------------------------------------------------------------------------------------ */
/* Handler-safe locks */
#define gasnet_hsl_t gex_HSL_t
#define gasnet_hsl_init gex_HSL_Init
#define gasnet_hsl_destroy gex_HSL_Destroy
#define gasnet_hsl_lock gex_HSL_Lock
#define gasnet_hsl_unlock gex_HSL_Unlock
#define gasnet_hsl_trylock gex_HSL_Trylock
#define GASNET_HSL_INITIALIZER GEX_HSL_INITIALIZER
/* ------------------------------------------------------------------------------------ */
/* Blocking Put and Get */
#define gasnet_put(node,dest,src,nbytes) \
((void)gex_RMA_PutBlocking(gasneti_thunk_tm,node,dest,src,nbytes,0))
#define gasnet_get(dest,node,src,nbytes) \
((void)gex_RMA_GetBlocking(gasneti_thunk_tm,dest,node,src,nbytes,0))
#define gasnet_put_bulk gasnet_put
#define gasnet_get_bulk gasnet_get
/* ------------------------------------------------------------------------------------ */
/* Implicit-handle non-blocking Put and Get */
#define gasnet_put_nbi(node,dest,src,nbytes) \
((void)gex_RMA_PutNBI(gasneti_thunk_tm,node,dest,src,nbytes,GEX_EVENT_NOW,0))
#define gasnet_put_nbi_bulk(node,dest,src,nbytes) \
((void)gex_RMA_PutNBI(gasneti_thunk_tm,node,dest,src,nbytes,GEX_EVENT_DEFER,0))
#define gasnet_get_nbi(dest,node,src,nbytes) \
((void)gex_RMA_GetNBI(gasneti_thunk_tm,dest,node,src,nbytes,0))
#define gasnet_get_nbi_bulk gasnet_get_nbi
/* ------------------------------------------------------------------------------------ */
/* Explicit-handle non-blocking Put and Get */
#define gasnet_put_nb(node,dest,src,nbytes) \
gex_RMA_PutNB(gasneti_thunk_tm,node,dest,src,nbytes,GEX_EVENT_NOW,0)
#define gasnet_put_nb_bulk(node,dest,src,nbytes) \
gex_RMA_PutNB(gasneti_thunk_tm,node,dest,src,nbytes,GEX_EVENT_DEFER,0)
#define gasnet_get_nb(dest,node,src,nbytes) \
gex_RMA_GetNB(gasneti_thunk_tm,dest,node,src,nbytes,0)
#define gasnet_get_nb_bulk gasnet_get_nb
/* ------------------------------------------------------------------------------------ */
/* Value Gets - blocking and explicit-handle non-blocking */
#define gasnet_get_val(node,src,nbytes) \
gex_RMA_GetBlockingVal(gasneti_thunk_tm,node,src,nbytes,0)
typedef struct {
gex_RMA_Value_t gasneti_valget_value;
gex_Event_t gasneti_valget_event;
} *gasnet_valget_handle_t;
GASNETT_INLINE(gasnet_get_nb_val)
gasnet_valget_handle_t gasnet_get_nb_val(gasnet_node_t _node, void *_src, size_t _nbytes)
{
gasnet_valget_handle_t _result = (gasnet_valget_handle_t)gasneti_extern_malloc(sizeof(*_result));
#ifdef PLATFORM_ARCH_BIG_ENDIAN
void *_dest = (void*)((uintptr_t)&(_result->gasneti_valget_value) + sizeof(gex_RMA_Value_t) - _nbytes);
#else /* little-endian */
void *_dest = &_result->gasneti_valget_value;
#endif
_result->gasneti_valget_value = 0;
//assert(_nbytes > 0 && _nbytes <= sizeof(gex_RMA_Value_t));
_result->gasneti_valget_event = gex_RMA_GetNB(gasneti_thunk_tm, _dest, _node, _src, _nbytes, 0);
return _result;
}
GASNETT_INLINE(gasnet_wait_syncnb_valget)
gasnet_register_value_t gasnet_wait_syncnb_valget(gasnet_valget_handle_t _handle)
{
gex_RMA_Value_t _result;
gex_Event_Wait(_handle->gasneti_valget_event);
_result = _handle->gasneti_valget_value;
gasneti_extern_free(_handle);
return _result;
}
/* ------------------------------------------------------------------------------------ */
/* Value Puts - blocking, and explicit- and implicit-handle non-blocking */
#define gasnet_put_val(node,dest,value,nbytes) \
((void)gex_RMA_PutBlockingVal(gasneti_thunk_tm,node,dest,value,nbytes,0))
#define gasnet_put_nb_val(node,dest,value,nbytes) \
gex_RMA_PutNBVal(gasneti_thunk_tm,node,dest,value,nbytes,0)
#define gasnet_put_nbi_val(node,dest,value,nbytes) \
((void)gex_RMA_PutNBIVal(gasneti_thunk_tm,node,dest,value,nbytes,0))
/* ------------------------------------------------------------------------------------ */
/* Memset */
extern gex_Event_t gasneti_legacy_memset_nb (gex_Rank_t _node, void *_dest, int _val, size_t _nbytes GASNETI_THREAD_FARG) GASNETI_WARN_UNUSED_RESULT;
extern int gasneti_legacy_memset_nbi(gex_Rank_t _node, void *_dest, int _val, size_t _nbytes GASNETI_THREAD_FARG);
#define gasnet_memset(node,dest,val,nbytes) gasnet_wait_syncnb(gasneti_legacy_memset_nb(node,dest,val,nbytes GASNETI_THREAD_GET))
#define gasnet_memset_nb(node,dest,val,nbytes) gasneti_legacy_memset_nb(node,dest,val,nbytes GASNETI_THREAD_GET)
#define gasnet_memset_nbi(node,dest,val,nbytes) ((void)gasneti_legacy_memset_nbi(node,dest,val,nbytes GASNETI_THREAD_GET))
/* ------------------------------------------------------------------------------------ */
/* Explicit-handle sync operations */
#define gasnet_try_syncnb_nopoll(h) gex_Event_Test(h)
#define gasnet_try_syncnb_some_nopoll(ph,sz) gex_Event_TestSome(ph,sz,0)
#define gasnet_try_syncnb_all_nopoll(ph,sz) gex_Event_TestAll(ph,sz,0)
#define gasnet_try_syncnb(h) (gasnet_AMPoll(),gex_Event_Test(h))
#define gasnet_try_syncnb_some(ph,sz) (gasnet_AMPoll(),gex_Event_TestSome(ph,sz,0))
#define gasnet_try_syncnb_all(ph,sz) (gasnet_AMPoll(),gex_Event_TestAll(ph,sz,0))
#define gasnet_wait_syncnb(h) gex_Event_Wait(h)
#define gasnet_wait_syncnb_some(ph,sz) gex_Event_WaitSome(ph,sz,0)
#define gasnet_wait_syncnb_all(ph,sz) gex_Event_WaitAll(ph,sz,0)
/* ------------------------------------------------------------------------------------ */
/* Implicit-handle sync operations */
#define gasnet_try_syncnbi_gets() (gasnet_AMPoll(),gex_NBI_Test(GEX_EC_GET,0))
#define gasnet_try_syncnbi_puts() (gasnet_AMPoll(),gex_NBI_Test(GEX_EC_PUT,0))
#define gasnet_try_syncnbi_all() (gasnet_AMPoll(),gex_NBI_Test(GEX_EC_ALL,0))
#define gasnet_wait_syncnbi_gets() gex_NBI_Wait(GEX_EC_GET,0)
#define gasnet_wait_syncnbi_puts() gex_NBI_Wait(GEX_EC_PUT,0)
#define gasnet_wait_syncnbi_all() gex_NBI_Wait(GEX_EC_ALL,0)
/* ------------------------------------------------------------------------------------ */
/* Implicit-handle access regions */
#define gasnet_begin_nbi_accessregion() gex_NBI_BeginAccessRegion(0)
#define gasnet_end_nbi_accessregion() gex_NBI_EndAccessRegion(0)
/* ------------------------------------------------------------------------------------ */
/* No-interrupt sections - GASNet-1 compliant empty implementation */
#define gasnet_hold_interrupts() ((void)0)
#define gasnet_resume_interrupts() ((void)0)
/* ------------------------------------------------------------------------------------ */
/* VIS */
#define gasnet_putv_bulk(dstrank,dstcount,dstlist,srccount,srclist) \
((void)gex_VIS_VectorPutBlocking(gasneti_thunk_tm,dstrank,dstcount,(gex_Memvec_t*)(dstlist),srccount,(gex_Memvec_t*)(srclist),0))
#define gasnet_getv_bulk(dstcount,dstlist,srcrank,srccount,srclist) \
((void)gex_VIS_VectorGetBlocking(gasneti_thunk_tm,dstcount,(gex_Memvec_t*)(dstlist),srcrank,srccount,(gex_Memvec_t*)(srclist),0))
#define gasnet_putv_nb_bulk(dstrank,dstcount,dstlist,srccount,srclist) \
gex_VIS_VectorPutNB(gasneti_thunk_tm,dstrank,dstcount,(gex_Memvec_t*)(dstlist),srccount,(gex_Memvec_t*)(srclist),0)
#define gasnet_getv_nb_bulk(dstcount,dstlist,srcrank,srccount,srclist) \
gex_VIS_VectorGetNB(gasneti_thunk_tm,dstcount,(gex_Memvec_t*)(dstlist),srcrank,srccount,(gex_Memvec_t*)(srclist),0)
#define gasnet_putv_nbi_bulk(dstrank,dstcount,dstlist,srccount,srclist) \
((void)gex_VIS_VectorPutNBI(gasneti_thunk_tm,dstrank,dstcount,(gex_Memvec_t*)(dstlist),srccount,(gex_Memvec_t*)(srclist),0))
#define gasnet_getv_nbi_bulk(dstcount,dstlist,srcrank,srccount,srclist) \
((void)gex_VIS_VectorGetNBI(gasneti_thunk_tm,dstcount,(gex_Memvec_t*)(dstlist),srcrank,srccount,(gex_Memvec_t*)(srclist),0))
#define gasnet_puti_bulk(dstrank,dstcount,dstlist,dstlen,srccount,srclist,srclen) \
((void)gex_VIS_IndexedPutBlocking(gasneti_thunk_tm,dstrank,dstcount,dstlist,dstlen,srccount,srclist,srclen,0))
#define gasnet_geti_bulk(dstcount,dstlist,dstlen,srcrank,srccount,srclist,srclen) \
((void)gex_VIS_IndexedGetBlocking(gasneti_thunk_tm,dstcount,dstlist,dstlen,srcrank,srccount,srclist,srclen,0))
#define gasnet_puti_nb_bulk(dstrank,dstcount,dstlist,dstlen,srccount,srclist,srclen) \
gex_VIS_IndexedPutNB(gasneti_thunk_tm,dstrank,dstcount,dstlist,dstlen,srccount,srclist,srclen,0)
#define gasnet_geti_nb_bulk(dstcount,dstlist,dstlen,srcrank,srccount,srclist,srclen) \
gex_VIS_IndexedGetNB(gasneti_thunk_tm,dstcount,dstlist,dstlen,srcrank,srccount,srclist,srclen,0)
#define gasnet_puti_nbi_bulk(dstrank,dstcount,dstlist,dstlen,srccount,srclist,srclen) \
((void)gex_VIS_IndexedPutNBI(gasneti_thunk_tm,dstrank,dstcount,dstlist,dstlen,srccount,srclist,srclen,0))
#define gasnet_geti_nbi_bulk(dstcount,dstlist,dstlen,srcrank,srccount,srclist,srclen) \
((void)gex_VIS_IndexedGetNBI(gasneti_thunk_tm,dstcount,dstlist,dstlen,srcrank,srccount,srclist,srclen,0))
// dedicated g2ex wrappers translate the Strided metadata from legacy to EX format
#define gasnet_puts_bulk(dstrank,dstaddr,dststrides,srcaddr,srcstrides,count,stridelevels) \
_gasnet_puts_bulk(gasneti_thunk_tm,dstrank,dstaddr,dststrides,srcaddr,srcstrides,count,stridelevels GASNETI_THREAD_GET)
#define gasnet_gets_bulk(dstaddr,dststrides,srcrank,srcaddr,srcstrides,count,stridelevels) \
_gasnet_gets_bulk(gasneti_thunk_tm,dstaddr,dststrides,srcrank,srcaddr,srcstrides,count,stridelevels GASNETI_THREAD_GET)
#define gasnet_puts_nb_bulk(dstrank,dstaddr,dststrides,srcaddr,srcstrides,count,stridelevels) \
_gasnet_puts_nb_bulk(gasneti_thunk_tm,dstrank,dstaddr,dststrides,srcaddr,srcstrides,count,stridelevels GASNETI_THREAD_GET)
#define gasnet_gets_nb_bulk(dstaddr,dststrides,srcrank,srcaddr,srcstrides,count,stridelevels) \
_gasnet_gets_nb_bulk(gasneti_thunk_tm,dstaddr,dststrides,srcrank,srcaddr,srcstrides,count,stridelevels GASNETI_THREAD_GET)
#define gasnet_puts_nbi_bulk(dstrank,dstaddr,dststrides,srcaddr,srcstrides,count,stridelevels) \
_gasnet_puts_nbi_bulk(gasneti_thunk_tm,dstrank,dstaddr,dststrides,srcaddr,srcstrides,count,stridelevels GASNETI_THREAD_GET)
#define gasnet_gets_nbi_bulk(dstaddr,dststrides,srcrank,srcaddr,srcstrides,count,stridelevels) \
_gasnet_gets_nbi_bulk(gasneti_thunk_tm,dstaddr,dststrides,srcrank,srcaddr,srcstrides,count,stridelevels GASNETI_THREAD_GET)
/* ------------------------------------------------------------------------------------ */
GASNETI_END_NOWARN
GASNETT_END_EXTERNC
#endif
| 26,936 |
382 | <gh_stars>100-1000
package com.youku.player.plugin;
/**
* Class MediaPlayerObserver
*/
public interface MediaPlayerObserver {
//
// Methods
//
//
// Accessor methods
//
//
// Other methods
//
/**
* 缓冲的通知
*
* @param percent
* 目前缓存的百分比
*/
public void onBufferingUpdateListener(int percent);
/**
* 播放完成的通知
*/
public void onCompletionListener();
/**
* 出现错误的通知
*
* @param extra
* 错误携带的参数
* @param what
* 错误代码
* @return
*/
public boolean onErrorListener(int what, int extra);
/**
* 准备完成的通知
*/
public void OnPreparedListener();
/**
* seek完成的通知
*/
public void OnSeekCompleteListener();
/**
* 视频的宽高比发生变化的通知
*
* @param height
* 高度
* @param width
* 宽度
*/
public void OnVideoSizeChangedListener(int width, int height);
/**
* 超时通知
*/
public void OnTimeoutListener();
/**
* 播放时间点变化通知
*
* @param currentPosition
* 当前的时间点,单位毫秒
*/
public void OnCurrentPositionChangeListener(int currentPosition);
/**
* 已经加载完成的通知
*/
public void onLoadedListener();
/**
* 正在加载的通知
*
*/
public void onLoadingListener();
/**
* 改变清晰度的通知
*/
public void onNotifyChangeVideoQuality();
/**
* 正片开始播放
*/
public void onRealVideoStarted();
}
| 738 |
535 | <filename>bazel/serf.bzl
serf_build_rule = """
cc_library(
name = "serf",
srcs = [
"auth/auth.c",
"auth/auth_basic.c",
"auth/auth_digest.c",
"auth/auth_spnego.c",
"auth/auth_spnego_gss.c",
"auth/auth_spnego_sspi.c",
"buckets/aggregate_buckets.c",
# XXX(oschaaf): the gyp has this, but wouldn't it violate the ODR?
#"buckets/allocator.c",
"buckets/barrier_buckets.c",
"buckets/chunk_buckets.c",
"buckets/dechunk_buckets.c",
"buckets/deflate_buckets.c",
"buckets/file_buckets.c",
"buckets/headers_buckets.c",
"buckets/iovec_buckets.c",
"buckets/limit_buckets.c",
"buckets/mmap_buckets.c",
"buckets/request_buckets.c",
"buckets/response_body_buckets.c",
"buckets/simple_buckets.c",
"buckets/socket_buckets.c",
"context.c",
"incoming.c",
"ssltunnel.c",
"@mod_pagespeed//third_party/serf:serf_pagespeed",
],
hdrs = [
"serf.h",
"serf_private.h",
"serf_bucket_types.h",
"serf_bucket_util.h",
"auth/auth.h",
"auth/auth_spnego.h",
],
copts = [
"-Iexternal/aprutil/include/",
"-Iexternal/aprutil/include/private/",
"-Iexternal/aprutil/include/arch/unix/",
"-Iexternal/aprutil/",
"-Ithird_party/aprutil/gen/arch/linux/x64/include/",
"-Ithird_party/apr/gen/arch/linux/x64/include/",
"-Iexternal/apr/include/",
"-Iexternal/apr/include/arch/unix/",
"-Iexternal/apr/",
"-Iexternal/serf/include/",
"-Iexternal/serf/",
],
visibility = ["//visibility:public"],
deps = [
"@apr",
"@aprutil",
"@boringssl//:ssl"
],
)
"""
| 990 |
310 | <reponame>dreeves/usesthis
{
"name": "5big Thunderbolt",
"description": "A large hard drive bay.",
"url": "https://www.amazon.com/MODEL-LaCie-Thunderbolt-External-9000378U/dp/B00AX9ZA6W/"
} | 79 |
692 | <reponame>Hammy927/zt-exec<filename>src/main/java/org/zeroturnaround/exec/ProcessAttributes.java
/*
* Copyright (C) 2014 ZeroTurnaround <<EMAIL>>
* Contains fragments of code from Apache Commons Exec, rights owned
* by Apache Software Foundation (ASF).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zeroturnaround.exec;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Immutable set of attributes used to start a process.
*/
class ProcessAttributes {
/**
* The external program and its arguments.
*/
private final List<String> command;
/**
* Working directory, <code>null</code> in case of current working directory.
*/
private final File directory;
/**
* Environment variables which are added (removed in case of <code>null</code> values) to the started process.
*/
private final Map<String,String> environment;
/**
* Set of accepted exit codes or <code>null</code> if all exit codes are allowed.
*/
private final Set<Integer> allowedExitValues;
public ProcessAttributes(List<String> command, File directory, Map<String, String> environment, Set<Integer> allowedExitValues) {
this.command = command;
this.directory = directory;
this.environment = environment;
this.allowedExitValues = allowedExitValues;
}
public List<String> getCommand() {
return command;
}
public File getDirectory() {
return directory;
}
public Map<String, String> getEnvironment() {
return environment;
}
public Set<Integer> getAllowedExitValues() {
return allowedExitValues;
}
}
| 611 |
462 | <filename>mq-biz/src/main/java/com/ppdai/infrastructure/mq/biz/ui/vo/ConnectionsVo.java
package com.ppdai.infrastructure.mq.biz.ui.vo;
/**
* @Author:wanghe02
* @Date:2019/4/16 16:19
*/
public class ConnectionsVo {
private String ip;
private String maxConnection;
private String curConnection;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getMaxConnection() {
return maxConnection;
}
public void setMaxConnection(String maxConnection) {
this.maxConnection = maxConnection;
}
public String getCurConnection() {
return curConnection;
}
public void setCurConnection(String curConnection) {
this.curConnection = curConnection;
}
}
| 311 |
1,627 | <filename>src/main/java/net/querz/mcaselector/filter/NumberFilter.java
package net.querz.mcaselector.filter;
import net.querz.mcaselector.io.mca.ChunkData;
public abstract class NumberFilter<T extends Number> extends Filter<T> {
private static final Comparator[] comparators = new Comparator[] {
Comparator.EQUAL,
Comparator.NOT_EQUAL,
Comparator.LARGER,
Comparator.SMALLER,
Comparator.LARGER_EQUAL,
Comparator.SMALLER_EQUAL
};
private Comparator comparator;
public NumberFilter(FilterType type, Operator operator, Comparator comparator) {
super(type, operator);
this.comparator = comparator;
}
@Override
public T getFilterValue() {
return getFilterNumber();
}
@Override
public Comparator[] getComparators() {
return comparators;
}
@Override
public Comparator getComparator() {
return comparator;
}
public void setComparator(Comparator comparator) {
this.comparator = comparator;
}
public boolean matches(T value, T data) {
switch (comparator) {
case EQUAL:
return isEqual(data, value);
case NOT_EQUAL:
return isNotEqual(data, value);
case LARGER:
return isLargerThan(data, value);
case SMALLER:
return isSmallerThan(data, value);
case LARGER_EQUAL:
return isLargerEqual(data, value);
case SMALLER_EQUAL:
return isSmallerEqual(data, value);
}
return false;
}
@Override
public boolean matches(ChunkData data) {
return matches(getFilterNumber(), getNumber(data));
}
@Override
public String toString() {
return getType() + " " + comparator.getQueryString() + " " + getFilterValue();
}
public abstract String getFormatText();
abstract T getFilterNumber();
abstract void setFilterNumber(T value);
abstract T getNumber(ChunkData data);
abstract boolean isEqual(T a, T b);
abstract boolean isNotEqual(T a, T b);
abstract boolean isLargerThan(T a, T b);
abstract boolean isSmallerThan(T a, T b);
abstract boolean isLargerEqual(T a, T b);
abstract boolean isSmallerEqual(T a, T b);
}
| 730 |
1,831 | /**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/server/rebuilding/RebuildingReadStorageTask.h"
#include <gtest/gtest.h>
#include "logdevice/common/settings/SettingsUpdater.h"
#include "logdevice/common/test/NodeSetTestUtil.h"
#include "logdevice/common/test/NodesConfigurationTestUtil.h"
#include "logdevice/server/locallogstore/test/TemporaryLogStore.h"
using namespace facebook::logdevice;
static const std::chrono::milliseconds MINUTE = std::chrono::minutes(1);
static const std::chrono::milliseconds PARTITION_DURATION = MINUTE * 15;
static const RecordTimestamp BASE_TIME{
TemporaryPartitionedStore::baseTime().toMilliseconds()};
static const std::string BIG_PAYLOAD(10000, '.');
static const ShardID N0{0, 0};
static const ShardID N1{1, 0};
static const ShardID N2{2, 0};
static const ShardID N3{3, 0};
static const ShardID N4{4, 0};
static const ShardID N5{5, 0};
static const ShardID N6{6, 0};
static const ShardID N7{7, 0};
static const ShardID N8{8, 0};
static const ShardID N9{9, 0};
// Ain't nobody got time to spell "compose_lsn(epoch_t(1), esn_t(1))".
lsn_t mklsn(epoch_t::raw_type epoch, esn_t::raw_type esn) {
return compose_lsn(epoch_t(epoch), esn_t(esn));
}
class RebuildingReadStorageTaskTest : public ::testing::TestWithParam<bool> {
public:
class MockRebuildingReadStorageTask : public RebuildingReadStorageTask {
public:
MockRebuildingReadStorageTask(RebuildingReadStorageTaskTest* test,
std::weak_ptr<Context> context)
: RebuildingReadStorageTask(context), test(test) {}
RebuildingReadStorageTaskTest* test;
protected:
UpdateableSettings<Settings> getSettings() override {
return test->settings;
}
std::shared_ptr<UpdateableConfig> getConfig() override {
return test->config;
}
folly::Optional<NodeID> getMyNodeID() override {
return folly::none;
}
std::unique_ptr<LocalLogStore::AllLogsIterator> createIterator(
const LocalLogStore::ReadOptions& opts,
const std::unordered_map<logid_t, std::pair<lsn_t, lsn_t>>& logs)
override {
return test->store->readAllLogs(opts, logs);
}
void updateTrimPoint(logid_t log,
Context* context,
Context::LogState* log_state) override {}
StatsHolder* getStats() override {
return &test->stats;
}
};
RebuildingReadStorageTaskTest() {
// Create nodes and logs config. This part is super boilerplaty, just skip
// the code and read comments.
auto nodes = std::make_shared<const NodesConfiguration>();
// Nodes 0..9.
NodeSetTestUtil::addNodes(nodes, /* nodes */ 10, /* shards */ 2, "....");
// Metadata logs, nodeset 5..9, replication factor 3.
nodes = nodes->applyUpdate(
NodesConfigurationTestUtil::setStorageMembershipUpdate(
*nodes,
{ShardID(5, -1),
ShardID(6, -1),
ShardID(7, -1),
ShardID(8, -1),
ShardID(9, -1)},
folly::none,
membership::MetaDataStorageState::METADATA));
nodes = nodes->applyUpdate(
NodesConfigurationTestUtil::setMetadataReplicationPropertyUpdate(
*nodes, ReplicationProperty{{NodeLocationScope::NODE, 3}}));
auto logs_config = std::make_shared<configuration::LocalLogsConfig>();
// Logs 1..10, replication factor 3.
auto log_attrs =
logsconfig::LogAttributes()
.with_backlogDuration(std::chrono::seconds(3600 * 24 * 1))
.with_replicationFactor(3);
logs_config->insert(
boost::icl::right_open_interval<logid_t::raw_type>(1, 10),
"lg1",
log_attrs);
// Event log, replication factor 3.
log_attrs =
log_attrs.with_backlogDuration(folly::none).with_replicationFactor(3);
configuration::InternalLogs internal_logs;
ld_check(internal_logs.insert("event_log_deltas", log_attrs));
logs_config->setInternalLogsConfig(internal_logs);
logs_config->markAsFullyLoaded();
auto server_config = std::shared_ptr<ServerConfig>(
ServerConfig::fromDataTest("RebuildingReadStorageTaskTest"));
auto cfg = std::make_shared<Configuration>(
server_config, logs_config, std::move(nodes));
config = std::make_shared<UpdateableConfig>(cfg);
// Create local log store (logsdb) and 6 partitions, 15 minutes apart.
store = std::make_unique<TemporaryPartitionedStore>();
for (size_t i = 0; i < 6; ++i) {
RecordTimestamp t = BASE_TIME + PARTITION_DURATION * i;
store->setTime(SystemTimestamp(t.toMilliseconds()));
store->createPartition();
partition_start.push_back(t);
}
setRebuildingSettings(
{{"rebuilding-new-to-old", GetParam() ? "true" : "false"}});
}
void
setRebuildingSettings(std::unordered_map<std::string, std::string> settings) {
settings["rebuilding-new-to-old"] = GetParam() ? "true" : "false";
SettingsUpdater u;
u.registerSettings(rebuildingSettings);
u.setFromConfig(settings);
}
// The caller needs to assign `onDone` and `logs` afterwards.
std::shared_ptr<RebuildingReadStorageTask::Context>
createContext(std::shared_ptr<const RebuildingSet> rebuilding_set,
ShardID my_shard_id = ShardID(1, 0)) {
auto c = std::make_shared<RebuildingReadStorageTask::Context>();
c->rebuildingSet = rebuilding_set;
c->rebuildingSettings = rebuildingSettings;
c->myShardID = my_shard_id;
c->onDone = [&](std::vector<std::unique_ptr<ChunkData>> c) {
chunks = std::move(c);
};
return c;
}
UpdateableSettings<Settings> settings;
UpdateableSettings<RebuildingSettings> rebuildingSettings;
std::shared_ptr<UpdateableConfig> config;
StatsHolder stats{StatsParams().setIsServer(true)};
std::unique_ptr<TemporaryPartitionedStore> store;
std::vector<RecordTimestamp> partition_start;
std::vector<std::unique_ptr<ChunkData>> chunks;
};
struct ChunkDescription {
logid_t log;
lsn_t min_lsn;
size_t num_records = 1;
bool big_payload = false;
bool operator==(const ChunkDescription& rhs) const {
return std::tie(log, min_lsn, num_records, big_payload) ==
std::tie(rhs.log, rhs.min_lsn, rhs.num_records, rhs.big_payload);
}
};
static std::vector<ChunkDescription>
convertChunks(const std::vector<std::unique_ptr<ChunkData>>& chunks) {
std::vector<ChunkDescription> res;
for (auto& c : chunks) {
EXPECT_EQ(c->numRecords(), c->address.max_lsn - c->address.min_lsn + 1);
// Expect payload to be either BIG_PAYLOAD or log_id concatenated with lsn.
bool big = c->totalBytes() > BIG_PAYLOAD.size();
if (big) {
EXPECT_EQ(1, c->numRecords());
}
// Verify payloads.
for (size_t i = 0; i < c->numRecords(); ++i) {
EXPECT_EQ(c->address.min_lsn + i, c->getLSN(i));
Payload payload;
folly::IOBuf blob = c->getRecordBlob(i);
int rv =
LocalLogStoreRecordFormat::parse(Slice(blob.data(), blob.length()),
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
0,
nullptr,
nullptr,
&payload,
shard_index_t(0));
EXPECT_EQ(0, rv);
std::string expected_payload;
if (big) {
expected_payload = BIG_PAYLOAD;
} else {
expected_payload =
toString(c->address.log.val()) + lsn_to_string(c->getLSN(i));
}
EXPECT_EQ(expected_payload, payload.toString());
}
res.push_back(ChunkDescription{c->address.log,
c->address.min_lsn,
c->address.max_lsn - c->address.min_lsn + 1,
big});
}
return res;
}
std::ostream& operator<<(std::ostream& out, const ChunkDescription& c) {
out << c.log.val() << lsn_to_string(c.min_lsn);
if (c.num_records != 1) {
out << ":" << c.num_records;
}
if (c.big_payload) {
out << ":big";
}
return out;
}
TEST_P(RebuildingReadStorageTaskTest, Basic) {
logid_t L1(1), L2(2), L3(3), L4(4);
logid_t M1 = MetaDataLog::metaDataLogID(L1);
logid_t I1 = configuration::InternalLogs::EVENT_LOG_DELTAS;
auto& P = partition_start;
ReplicationProperty R({{NodeLocationScope::NODE, 3}});
StorageSet all_nodes{N0, N1, N2, N3, N4, N5, N6, N7, N8, N9};
Slice big_payload = Slice::fromString(BIG_PAYLOAD);
// Read 10 KB per storage task.
setRebuildingSettings({{"rebuilding-max-batch-bytes", "10000"}});
// Rebuilding set is {N2}.
auto rebuilding_set = std::make_shared<RebuildingSet>();
rebuilding_set->shards.emplace(
ShardID(2, 0), RebuildingNodeInfo(RebuildingMode::RESTORE));
auto c = createContext(rebuilding_set);
// Fill out rebuilding plan.
// For internal and metadata log read all epochs.
c->logs[I1].plan.untilLSN = LSN_MAX;
c->logs[I1].plan.addEpochRange(
EPOCH_INVALID, EPOCH_MAX, std::make_shared<EpochMetaData>(all_nodes, R));
c->logs[M1].plan.untilLSN = LSN_MAX;
c->logs[M1].plan.addEpochRange(
EPOCH_INVALID, EPOCH_MAX, std::make_shared<EpochMetaData>(all_nodes, R));
// For log 1 read epochs 3-4 and 7-8, and stop at e8n50.
c->logs[L1].plan.untilLSN = mklsn(8, 50);
c->logs[L1].plan.addEpochRange(
epoch_t(3), epoch_t(4), std::make_shared<EpochMetaData>(all_nodes, R));
c->logs[L1].plan.addEpochRange(
epoch_t(7), epoch_t(8), std::make_shared<EpochMetaData>(all_nodes, R));
// For log 2 read all epochs and stop at e10n50.
c->logs[L2].plan.untilLSN = mklsn(10, 50);
c->logs[L2].plan.addEpochRange(
EPOCH_INVALID, EPOCH_MAX, std::make_shared<EpochMetaData>(all_nodes, R));
// Don't read log 3.
// For log 4 read only epoch 1.
c->logs[L4].plan.untilLSN = LSN_MAX;
c->logs[L4].plan.addEpochRange(
epoch_t(1), epoch_t(1), std::make_shared<EpochMetaData>(all_nodes, R));
// Write some records. Commment '-' means the record will be filtered out.
// Remember that we're N1, and rebuilding set is {N2}.
// Internal log.
store->putRecord(I1, mklsn(1, 10), BASE_TIME, {N1, N0, N2}); // +
// Metadata log.
store->putRecord(M1, mklsn(2, 1), BASE_TIME - MINUTE, {N2, N1, N0}); // +
store->putRecord(M1, mklsn(2, 2), BASE_TIME - MINUTE, {N2, N1, N0}); // +
store->putRecord(M1, mklsn(3, 1), BASE_TIME - MINUTE, {N1, N3, N4}); // -
store->putRecord(M1, mklsn(3, 2), BASE_TIME - MINUTE, {N1, N2, N3}); // +
// Data logs in partition 0.
store->putRecord(L1, mklsn(1, 10), P[0] + MINUTE, {N2, N1, N3}); // -
store->putRecord(L1, mklsn(2, 10), P[0] + MINUTE, {N2, N1, N3}); // -
store->putRecord(L1, mklsn(3, 10), P[0] + MINUTE, {N3, N1, N2}); // -
store->putRecord(L1, mklsn(3, 11), P[0] + MINUTE, {N1, N3, N2}); // +
store->putRecord(L1, mklsn(3, 12), P[0] + MINUTE * 2, {N1, N3, N2}); // +
store->putRecord(
L1, mklsn(4, 1), P[0] + MINUTE * 2, {N1, N3, N2}, 0, big_payload); // +
store->putRecord(L2, mklsn(1, 1), P[0] + MINUTE, {N3, N1, N2}); // -
store->putRecord(L3, mklsn(1, 1), P[0] + MINUTE, {N2, N1, N3}); // -
store->putRecord(
L4, mklsn(1, 1), P[0] + MINUTE, {N2, N1, N5}, 0, big_payload); // +
// Data logs in partition 1.
store->putRecord(L4,
mklsn(1, 2),
P[1] + MINUTE,
{N2, N1, N5},
LocalLogStoreRecordFormat::FLAG_DRAINED); // -
// Keep partition 2 empty.
// Data logs in partition 3.
store->putRecord(L1, mklsn(4, 2), P[3] + MINUTE, {N1, N3, N2}); // +
store->putRecord(L1, mklsn(5, 1), P[3] + MINUTE, {N1, N3, N2}); // -
store->putRecord(L1, mklsn(8, 50), P[3] + MINUTE, {N1, N3, N2}); // +
store->putRecord(L1, mklsn(8, 51), P[3] + MINUTE, {N1, N3, N2}); // -
store->putRecord(L2, mklsn(10, 40), P[3] + MINUTE * 2, {N1, N3, N2}); // +
store->putRecord(L2, mklsn(10, 60), P[3] + MINUTE * 2, {N1, N3, N2}); // -
store->putRecord(L3, mklsn(10, 10), P[3] + MINUTE, {N2, N1, N3}); // -
store->putRecord(L4, mklsn(1, 3), P[3] + MINUTE * 2, {N1, N3, N2}); // +
// Write lots of CSI entries that'll be filtered out. This should get iterator
// into LIMIT_REACHED state.
for (size_t i = 0; i < 2000; ++i) {
store->putRecord(L4, mklsn(1, i + 4), P[3] + MINUTE * 2, {N1, N3, N4}); // -
}
store->putRecord(L4, mklsn(1, 100000), P[3] + MINUTE * 2, {N1, N3, N2}); // +
store->putRecord(L4, mklsn(2, 1), P[3] + MINUTE * 2, {N1, N3, N2}); // -
// Sanity check that the records didn't end up in totally wrong partitions.
EXPECT_EQ(std::vector<size_t>({4, 1, 0, 4}), store->getNumLogsPerPartition());
if (GetParam()) { // new-to-old
// Metadata and partition 3.
// Read up to the long range of filtered out records.
{
MockRebuildingReadStorageTask task(this, c);
task.execute();
task.onDone();
EXPECT_FALSE(c->reachedEnd);
EXPECT_FALSE(c->persistentError);
EXPECT_EQ(std::vector<ChunkDescription>({{I1, mklsn(1, 10)},
{M1, mklsn(2, 1), 2},
{M1, mklsn(3, 2)},
{L1, mklsn(4, 2)},
{L1, mklsn(8, 50)},
{L2, mklsn(10, 40)},
{L4, mklsn(1, 3)}}),
convertChunks(chunks));
}
// Partition 3, 2, 1, 0.
// Read through a long sequence of CSI that doesn't pass filter.
// The next nonempty batch will stop at the big record in partition 0.
int empty_batches = 0;
while (true) {
MockRebuildingReadStorageTask task(this, c);
task.execute();
task.onDone();
EXPECT_FALSE(c->persistentError);
if (!chunks.empty()) {
break;
}
EXPECT_EQ(false, c->reachedEnd);
++empty_batches;
// Invalidate iterator after first batch.
if (empty_batches == 1) {
c->iterator->invalidate();
}
}
EXPECT_GE(empty_batches, 2);
EXPECT_EQ(std::vector<ChunkDescription>(
{{L4, mklsn(1, 100000)}, {L1, mklsn(3, 11), 2}}),
convertChunks(chunks));
// Partition 0.
// Read up to the next big record. Note that the first big record doesn't
// count towards the limit for this batch because it was counted by the
// previous batch.
{
MockRebuildingReadStorageTask task(this, c);
task.execute();
task.onDone();
EXPECT_FALSE(c->reachedEnd);
EXPECT_FALSE(c->persistentError);
EXPECT_EQ(
std::vector<ChunkDescription>({{L1, mklsn(4, 1), 1, /* big */ true}}),
convertChunks(chunks));
}
// Partition 0. Read the second big record, and we're done.
{
MockRebuildingReadStorageTask task(this, c);
task.execute();
task.onDone();
EXPECT_TRUE(c->reachedEnd);
EXPECT_FALSE(c->persistentError);
EXPECT_EQ(
std::vector<ChunkDescription>({{L4, mklsn(1, 1), 1, /* big */ true}}),
convertChunks(chunks));
}
} else {
{
// Read up to the big record that exceeds the byte limit.
MockRebuildingReadStorageTask task(this, c);
task.execute();
task.onDone();
EXPECT_FALSE(c->reachedEnd);
EXPECT_FALSE(c->persistentError);
EXPECT_EQ(std::vector<ChunkDescription>({{I1, mklsn(1, 10)},
{M1, mklsn(2, 1), 2},
{M1, mklsn(3, 2)},
{L1, mklsn(3, 11), 2}}),
convertChunks(chunks));
}
size_t block_id;
{
// Read up to the next big record. Note that the first big record doesn't
// count towards the limit for this batch because it was counted by the
// previous batch.
MockRebuildingReadStorageTask task(this, c);
task.execute();
task.onDone();
EXPECT_FALSE(c->reachedEnd);
EXPECT_FALSE(c->persistentError);
EXPECT_EQ(
std::vector<ChunkDescription>({{L1, mklsn(4, 1), 1, /* big */ true}}),
convertChunks(chunks));
block_id = chunks.at(0)->blockID;
}
{
MockRebuildingReadStorageTask task(this, c);
task.execute();
task.onDone();
EXPECT_FALSE(c->reachedEnd);
EXPECT_FALSE(c->persistentError);
EXPECT_EQ(
std::vector<ChunkDescription>({{L4, mklsn(1, 1), 1, /* big */ true},
{L1, mklsn(4, 2)},
{L1, mklsn(8, 50)},
{L2, mklsn(10, 40)},
{L4, mklsn(1, 3)}}),
convertChunks(chunks));
// Check that chunk e4n2 from this batch has the same block ID as chunk
// e4n1 from previous batch.
EXPECT_EQ(block_id, chunks.at(1)->blockID);
// Check that next chunk for same log has next block ID.
EXPECT_EQ(block_id + 1, chunks.at(2)->blockID);
}
// Read through a long sequence of CSI that doesn't pass filter.
int empty_batches = 0;
while (true) {
MockRebuildingReadStorageTask task(this, c);
task.execute();
task.onDone();
EXPECT_FALSE(c->persistentError);
if (c->reachedEnd) {
break;
}
EXPECT_EQ(0, chunks.size());
++empty_batches;
// Invalidate iterator after first batch.
if (empty_batches == 1) {
c->iterator->invalidate();
}
}
EXPECT_GE(empty_batches, 2);
EXPECT_EQ(std::vector<ChunkDescription>({{L4, mklsn(1, 100000)}}),
convertChunks(chunks));
}
// Run a task after Context is destroyed. Check that callback is not called.
{
chunks.clear();
chunks.push_back(std::make_unique<ChunkData>());
chunks.back()->address.min_lsn = 42;
MockRebuildingReadStorageTask task(this, c);
c.reset();
task.execute();
task.onDone();
ASSERT_EQ(1, chunks.size());
EXPECT_EQ(42, chunks.at(0)->address.min_lsn);
}
}
TEST_P(RebuildingReadStorageTaskTest, TimeRanges) {
// N1 is us.
// N2 needs to be rebuilt for partitions 0-2.
// N3 needs to be rebuilt for partitions 1 and 4.
// N4 needs to be rebuilt for partition 5.
// Log 1 epoch 3 has nodeset {N1, N2, N3, N5, N6}.
// Log 1 epoch 4 has nodeset {N1, N3, N5, N6}.
// Log 2 epoch 2 has nodeset {N1, N4, N5, N6}.
logid_t L1(1), L2(2);
auto& P = partition_start;
ReplicationProperty R({{NodeLocationScope::NODE, 3}});
// Fill out rebuilding set according to comment above.
auto rebuilding_set = std::make_shared<RebuildingSet>();
RecordTimeIntervals n2_dirty_ranges;
n2_dirty_ranges.insert(
RecordTimeInterval(P[0] + MINUTE * 2, P[3] - MINUTE * 2));
rebuilding_set->shards.emplace(
N2,
RebuildingNodeInfo(
{{DataClass::APPEND, n2_dirty_ranges}}, RebuildingMode::RESTORE));
RecordTimeIntervals n3_dirty_ranges;
n3_dirty_ranges.insert(
RecordTimeInterval(P[1] + MINUTE * 2, P[2] - MINUTE * 2));
n3_dirty_ranges.insert(
RecordTimeInterval(P[4] + MINUTE * 2, P[5] - MINUTE * 2));
rebuilding_set->shards.emplace(
N3,
RebuildingNodeInfo(
{{DataClass::APPEND, n3_dirty_ranges}}, RebuildingMode::RESTORE));
RecordTimeIntervals n4_dirty_ranges;
n4_dirty_ranges.insert(RecordTimeInterval(
P[5] + MINUTE * 2, P[5] + PARTITION_DURATION - MINUTE * 2));
rebuilding_set->shards.emplace(
N4,
RebuildingNodeInfo(
{{DataClass::APPEND, n4_dirty_ranges}}, RebuildingMode::RESTORE));
auto c = createContext(rebuilding_set);
// Fill out rebuilding plan according to comment above.
c->logs[L1].plan.untilLSN = LSN_MAX;
c->logs[L1].plan.addEpochRange(
epoch_t(3),
epoch_t(3),
std::make_shared<EpochMetaData>(StorageSet{N1, N2, N3, N5, N6}, R));
c->logs[L1].plan.addEpochRange(
epoch_t(4),
epoch_t(4),
std::make_shared<EpochMetaData>(StorageSet{N1, N3, N5, N6}, R));
c->logs[L2].plan.untilLSN = LSN_MAX;
c->logs[L2].plan.addEpochRange(
epoch_t(2),
epoch_t(2),
std::make_shared<EpochMetaData>(StorageSet{N1, N4, N5, N6}, R));
// Write some records, trying to hit as many different cases as possible.
// Partition 0.
store->putRecord(L1, mklsn(2, 1), P[0] + MINUTE * 3, {N1, N2, N3}); // -
store->putRecord(L1, mklsn(3, 1), P[0] + MINUTE * 1, {N1, N2, N3}); // -
store->putRecord(L1, mklsn(3, 2), P[0] + MINUTE * 3, {N1, N2, N3}); // +
store->putRecord(L1, mklsn(3, 3), P[0] + MINUTE * 3, {N1, N3, N5}); // -
store->putRecord(L1, mklsn(3, 4), P[0] + MINUTE * 3, {N1, N5, N6}); // -
store->putRecord(L1, mklsn(3, 5), P[0] + MINUTE * 3, {N1, N2, N6}); // +
store->putRecord(L1, mklsn(3, 6), P[1] - MINUTE * 1, {N1, N2, N6}); // +
store->putRecord(L2, mklsn(1, 1), P[0] + MINUTE * 3, {N1, N7, N8}); // -
store->putRecord(L2, mklsn(2, 1), P[0] + MINUTE * 3, {N1, N4, N5}); // -
// Partition 1.
store->putRecord(L1, mklsn(3, 7), P[1] + MINUTE * 1, {N1, N2, N5}); // +
store->putRecord(L1, mklsn(3, 8), P[1] + MINUTE * 1, {N1, N3, N5}); // -
store->putRecord(L1, mklsn(3, 9), P[1] + MINUTE * 3, {N1, N3, N5}); // +
store->putRecord(L1, mklsn(3, 10), P[1] + MINUTE * 3, {N1, N2, N3}); // +
store->putRecord(L1, mklsn(4, 1), P[1] + MINUTE * 4, {N1, N3, N5}); // +
// Partition 2.
store->putRecord(L1, mklsn(4, 2), P[2] + MINUTE * 4, {N1, N3, N5}); // -
store->putRecord(L1, mklsn(4, 3), P[2] + MINUTE * 4, {N1, N5, N6}); // -
// Partition 3.
store->putRecord(L1, mklsn(4, 4), P[3] + MINUTE * 4, {N1, N3, N4}); // -
store->putRecord(L2, mklsn(2, 2), P[3] + MINUTE * 4, {N1, N4, N5}); // -
// Partition 4.
store->putRecord(L1, mklsn(4, 5), P[4] + MINUTE * 4, {N1, N3, N5}); // +
store->putRecord(L1, mklsn(4, 6), P[4] + MINUTE * 4, {N1, N5, N6}); // -
store->putRecord(L1, mklsn(5, 1), P[4] + MINUTE * 4, {N1, N5, N6}); // -
store->putRecord(
L1, mklsn(2000000000, 1), P[4] + MINUTE * 4, {N1, N5, N6}); // -
// Partition 5.
store->putRecord(
L1, mklsn(2000000000, 2), P[5] + MINUTE * 4, {N1, N5, N6}); // -
store->putRecord(L2, mklsn(2, 3), P[5] + MINUTE * 4, {N1, N4, N5}); // +
EXPECT_EQ(
std::vector<size_t>({2, 1, 1, 2, 1, 2}), store->getNumLogsPerPartition());
{
MockRebuildingReadStorageTask task(this, c);
task.execute();
task.onDone();
EXPECT_TRUE(c->reachedEnd);
EXPECT_FALSE(c->persistentError);
if (GetParam()) { // new-to-old
EXPECT_EQ(std::vector<ChunkDescription>({
{L2, mklsn(2, 3)}, // p5
{L1, mklsn(4, 5)}, // p4
{L1, mklsn(3, 7)}, // p1
{L1, mklsn(3, 9)}, // p1
{L1, mklsn(3, 10)}, // p1
{L1, mklsn(4, 1)}, // p1
{L1, mklsn(3, 2)}, // p0
{L1, mklsn(3, 5), 2} // p0
}),
convertChunks(chunks));
} else {
EXPECT_EQ(std::vector<ChunkDescription>({{L1, mklsn(3, 2)},
{L1, mklsn(3, 5), 2},
{L1, mklsn(3, 7)},
{L1, mklsn(3, 9)},
{L1, mklsn(3, 10)},
{L1, mklsn(4, 1)},
{L1, mklsn(4, 5)},
{L2, mklsn(2, 3)}}),
convertChunks(chunks));
}
}
}
INSTANTIATE_TEST_CASE_P(P,
RebuildingReadStorageTaskTest,
::testing::Values(false, true));
| 11,773 |
3,843 | <gh_stars>1000+
package cn.finalteam.galleryfinal.sample.listener;
import com.bumptech.glide.Glide;
import cn.finalteam.galleryfinal.PauseOnScrollListener;
/**
* Desction:
* Author:pengjianbo
* Date:2016/1/9 0009 18:18
*/
public class GlidePauseOnScrollListener extends PauseOnScrollListener {
public GlidePauseOnScrollListener(boolean pauseOnScroll, boolean pauseOnFling) {
super(pauseOnScroll, pauseOnFling);
}
@Override
public void resume() {
Glide.with(getActivity()).resumeRequests();
}
@Override
public void pause() {
Glide.with(getActivity()).pauseRequests();
}
}
| 239 |
645 | <gh_stars>100-1000
# coding: utf-8
import os
import sys
import logging
from importlib import import_module
def pytest_sessionstart(session):
logging.basicConfig(
stream=sys.stdout,
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s",
)
proj_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
sys.path.insert(0, proj_dir)
jqdatasdk = import_module("jqdatasdk")
client = jqdatasdk.JQDataClient.instance()
client.ensure_auth()
assert jqdatasdk.is_auth()
def pytest_sessionfinish(session, exitstatus):
import_module("jqdatasdk").logout()
logging.info("test session finish, exit status: %s", exitstatus)
| 325 |
2,305 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from collections import OrderedDict
from copy import Error
import logging
from typing import Dict, List
import numpy as np
from torch import Tensor
from torch.nn import Module
from nni.algorithms.compression.v2.pytorch.utils import config_list_canonical
from nni.compression.pytorch.utils import count_flops_params
_logger = logging.getLogger(__name__)
class AMCEnv:
def __init__(self, model: Module, config_list: List[Dict], dummy_input: Tensor, total_sparsity: float, max_sparsity_per_layer: Dict[str, float], target: str = 'flops'):
pruning_op_names = []
[pruning_op_names.extend(config['op_names']) for config in config_list_canonical(model, config_list)]
self.pruning_ops = OrderedDict()
self.pruning_types = []
for i, (name, layer) in enumerate(model.named_modules()):
if name in pruning_op_names:
op_type = type(layer).__name__
stride = np.power(np.prod(layer.stride), 1 / len(layer.stride)) if hasattr(layer, 'stride') else 0 # type: ignore
kernel_size = np.power(np.prod(layer.kernel_size), 1 / len(layer.kernel_size)) if hasattr(layer, 'kernel_size') else 1 # type: ignore
self.pruning_ops[name] = (i, op_type, stride, kernel_size)
self.pruning_types.append(op_type)
self.pruning_types = list(set(self.pruning_types))
self.pruning_op_names = list(self.pruning_ops.keys())
self.dummy_input = dummy_input
self.total_sparsity = total_sparsity
self.max_sparsity_per_layer = max_sparsity_per_layer
assert target in ['flops', 'params']
self.target = target
self.origin_target, self.origin_params_num, origin_statistics = count_flops_params(model, dummy_input, verbose=False)
self.origin_statistics = {result['name']: result for result in origin_statistics}
self.under_pruning_target = sum([self.origin_statistics[name][self.target] for name in self.pruning_op_names])
self.excepted_pruning_target = self.total_sparsity * self.under_pruning_target
def reset(self):
self.ops_iter = iter(self.pruning_ops)
# build embedding (static part)
self._build_state_embedding(self.origin_statistics)
observation = self.layer_embedding[0].copy()
return observation
def correct_action(self, action: float, model: Module):
try:
op_name = next(self.ops_iter)
index = self.pruning_op_names.index(op_name)
_, _, current_statistics = count_flops_params(model, self.dummy_input, verbose=False)
current_statistics = {result['name']: result for result in current_statistics}
total_current_target = sum([current_statistics[name][self.target] for name in self.pruning_op_names])
previous_pruning_target = self.under_pruning_target - total_current_target
max_rest_pruning_target = sum([current_statistics[name][self.target] * self.max_sparsity_per_layer[name] for name in self.pruning_op_names[index + 1:]])
min_current_pruning_target = self.excepted_pruning_target - previous_pruning_target - max_rest_pruning_target
max_current_pruning_target_1 = self.origin_statistics[op_name][self.target] * self.max_sparsity_per_layer[op_name] - (self.origin_statistics[op_name][self.target] - current_statistics[op_name][self.target])
max_current_pruning_target_2 = self.excepted_pruning_target - previous_pruning_target
max_current_pruning_target = min(max_current_pruning_target_1, max_current_pruning_target_2)
min_action = min_current_pruning_target / current_statistics[op_name][self.target]
max_action = max_current_pruning_target / current_statistics[op_name][self.target]
if min_action > self.max_sparsity_per_layer[op_name]:
_logger.warning('[%s] min action > max sparsity per layer: %f > %f', op_name, min_action, self.max_sparsity_per_layer[op_name])
action = max(0., min(max_action, max(min_action, action)))
self.current_op_name = op_name
self.current_op_target = current_statistics[op_name][self.target]
except StopIteration:
raise Error('Something goes wrong, this should not happen.')
return action
def step(self, action: float, model: Module):
_, _, current_statistics = count_flops_params(model, self.dummy_input, verbose=False)
current_statistics = {result['name']: result for result in current_statistics}
index = self.pruning_op_names.index(self.current_op_name)
action = 1 - current_statistics[self.current_op_name][self.target] / self.current_op_target
total_current_target = sum([current_statistics[name][self.target] for name in self.pruning_op_names])
previous_pruning_target = self.under_pruning_target - total_current_target
rest_target = sum([current_statistics[name][self.target] for name in self.pruning_op_names[index + 1:]])
self.layer_embedding[index][-3] = previous_pruning_target / self.under_pruning_target # reduced
self.layer_embedding[index][-2] = rest_target / self.under_pruning_target # rest
self.layer_embedding[index][-1] = action # last action
observation = self.layer_embedding[index, :].copy()
return action, 0, observation, self.is_final_layer()
def is_first_layer(self):
return self.pruning_op_names.index(self.current_op_name) == 0
def is_final_layer(self):
return self.pruning_op_names.index(self.current_op_name) == len(self.pruning_op_names) - 1
@property
def state_feature(self):
return ['index', 'layer_type', 'input_size', 'output_size', 'stride', 'kernel_size', 'params_size', 'reduced', 'rest', 'a_{t-1}']
def _build_state_embedding(self, statistics: Dict[str, Dict]):
_logger.info('Building state embedding...')
layer_embedding = []
for name, (idx, op_type, stride, kernel_size) in self.pruning_ops.items():
state = []
state.append(idx) # index
state.append(self.pruning_types.index(op_type)) # layer type
state.append(np.prod(statistics[name]['input_size'])) # input size
state.append(np.prod(statistics[name]['output_size'])) # output size
state.append(stride) # stride
state.append(kernel_size) # kernel size
state.append(statistics[name]['params']) # params size
state.append(0.) # reduced
state.append(1.) # rest
state.append(0.) # a_{t-1}
layer_embedding.append(np.array(state))
layer_embedding = np.array(layer_embedding, 'float')
_logger.info('=> shape of embedding (n_layer * n_dim): %s', layer_embedding.shape)
assert len(layer_embedding.shape) == 2, layer_embedding.shape
# normalize the state
for i in range(layer_embedding.shape[1]):
fmin = min(layer_embedding[:, i])
fmax = max(layer_embedding[:, i])
if fmax - fmin > 0:
layer_embedding[:, i] = (layer_embedding[:, i] - fmin) / (fmax - fmin)
self.layer_embedding = layer_embedding
| 3,025 |
1,724 | /*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb.internal.operation;
import com.mongodb.MongoNamespace;
import com.mongodb.WriteConcern;
import com.mongodb.internal.bulk.UpdateRequest;
import com.mongodb.internal.bulk.WriteRequest;
import java.util.List;
import static com.mongodb.assertions.Assertions.isTrueArgument;
import static com.mongodb.assertions.Assertions.notNull;
/**
* An operation that updates a document in a collection.
*
* @since 3.0
*/
public class UpdateOperation extends BaseWriteOperation {
private final List<UpdateRequest> updates;
/**
* Construct an instance.
*
* @param namespace the database and collection namespace for the operation.
* @param ordered whether the updates are ordered.
* @param writeConcern the write concern for the operation.
* @param updates the update requests.
*/
public UpdateOperation(final MongoNamespace namespace, final boolean ordered, final WriteConcern writeConcern,
final List<UpdateRequest> updates) {
this(namespace, ordered, writeConcern, false, updates);
}
/**
* Construct an instance.
*
* @param namespace the database and collection namespace for the operation.
* @param ordered whether the updates are ordered.
* @param writeConcern the write concern for the operation.
* @param retryWrites if writes should be retried if they fail due to a network error.
* @param updates the update requests.
* @since 3.6
*/
public UpdateOperation(final MongoNamespace namespace, final boolean ordered, final WriteConcern writeConcern,
final boolean retryWrites, final List<UpdateRequest> updates) {
super(namespace, ordered, writeConcern, retryWrites);
this.updates = notNull("update", updates);
isTrueArgument("updateRequests not empty", !updates.isEmpty());
}
/**
* Gets the list of update requests.
*
* @return the update requests
*/
public List<UpdateRequest> getUpdateRequests() {
return updates;
}
@Override
protected List<? extends WriteRequest> getWriteRequests() {
return getUpdateRequests();
}
@Override
protected WriteRequest.Type getType() {
return WriteRequest.Type.UPDATE;
}
}
| 956 |
2,056 | <reponame>wbaweto/QConf
package net.qihoo.qconf;
public class QconfException extends Exception
{
public QconfException()
{}
public QconfException(String msg)
{
super(msg);
}
}
| 83 |
410 | {
"dId": "83683fda4a2c395c9d9952015b7d45be12d6862fe698153438ff6d89",
"title": "Cabinet anger at Brown cash raid",
"text": "Ministers are unhappy about plans to use Whitehall cash to keep council tax bills down, local government minister <NAME> has acknowledged.\n\n<NAME> reallocated \u00a3512m from central to local government budgets in his pre-Budget report on Thursday. <NAME> said he had held some \"pretty frank discussions\" with fellow ministers over the plans. But he said local governments had to deliver good services without big council tax rises.\n\nThe central government cash is part of a \u00a31bn package to help local authorities in England keep next year's council tax rises below 5%, in what is likely to be a general election year.\n\n<NAME> said nearly all central government departments had an interest in well run local authorities. And he confirmed rows over the issue with ministerial colleagues. \"Obviously we had some pretty frank discussions about this,\" he told BBC Radio 4's The World at One. But he said there was a recognition that \"a good settlement for local government\" was important to health, education and \"other government departments\". Ministers had to be sure local government could deliver without \"unreasonable council tax increases\", he added. Mr Raynsford dismissed a suggestion the move was designed to keep council taxes down ahead of an expected general election.\n\n\"This is a response to the concerns that have been voiced by local government about the pressures they face.\" <NAME> also plans to make savings of \u00a3100m by making changes to local government pensions schemes. These would raise the age from which retiring workers could claim their pensions and limit how much they received if they retired early. He insisted the changes were \"very modest\" and designed to tackle the problem of workers retiring \"very early\". But general secretary of the public services union Unison <NAME> criticised the plans. \"If you want world class public services you don't get that by hitting people as they approach retirement.\"",
"description": "",
"category": "politics",
"filename": "357.txt",
"date_publish": "2004-12-03T00:00:00"
} | 519 |
460 | <reponame>dyzmapl/BumpTop
#include "../../../src/xmlpatterns/schema/qxsdidcache_p.h"
| 40 |
3,702 | <filename>discovery-server/src/main/java/app/metatron/discovery/domain/mdm/source/MetaSourceService.java<gh_stars>1000+
/*
* 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 app.metatron.discovery.domain.mdm.source;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import app.metatron.discovery.domain.dataconnection.DataConnectionRepository;
import app.metatron.discovery.domain.datasource.DataSource;
import app.metatron.discovery.domain.datasource.DataSourceProjections;
import app.metatron.discovery.domain.datasource.DataSourceRepository;
import app.metatron.discovery.domain.mdm.Metadata;
import app.metatron.discovery.domain.mdm.MetadataController;
import app.metatron.discovery.domain.workbook.DashboardRepository;
import app.metatron.discovery.util.ProjectionUtils;
@Component
@Transactional(readOnly = true)
public class MetaSourceService {
private static Logger LOGGER = LoggerFactory.getLogger(MetadataController.class);
@Autowired
MetadataSourceRepository metadataSourceRepository;
@Autowired
DataSourceRepository dataSourceRepository;
@Autowired
DataConnectionRepository dataConnectionRepository;
@Autowired
DashboardRepository dashboardRepository;
@Autowired
ProjectionFactory projectionFactory;
public List<MetadataSource> findMetadataSourcesBySourceId(String type, String sourceId) {
return null;
}
/**
* Get Metadata source by source id
*
* @param type
* @param sourceId
* @return
*/
public Object getSourcesBySourceId(Metadata.SourceType type, String sourceId) {
switch (type) {
case ENGINE:
return dataSourceRepository.findOne(sourceId);
case JDBC:
return dataConnectionRepository.findOne(sourceId);
}
return null;
}
/**
* Gets sources by source id with projection.
*
* @param type the type
* @param sourceId the source id
* @return the sources by source id with projection
*/
public Object getSourcesBySourceIdWithProjection(Metadata.SourceType type, String sourceId) {
Object source = null;
switch (type) {
case ENGINE:
DataSource dataSource = dataSourceRepository.findOne(sourceId);
return ProjectionUtils.toResource(projectionFactory, DataSourceProjections.ForDetailProjection.class, dataSource);
case JDBC:
source = dataConnectionRepository.findOne(sourceId);
break;
}
return source;
}
}
| 1,006 |
458 | // Copyright (C) 2014 - 2015 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package net.osrg.namazu;
import com.google.protobuf.InvalidProtocolBufferException;
import sun.misc.Signal;
import sun.misc.SignalHandler;
import java.io.*;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.SynchronousQueue;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class PBInspector implements Inspector {
private boolean Direct = false;
private boolean Disabled = false;
private boolean NoInitiation = false;
private boolean Dryrun = false;
private String EntityID;
private int GATCPPort = 10000;
private Logger LOGGER;
private Socket GASock;
private DataOutputStream GAOutstream;
private DataInputStream GAInstream;
private Map<Integer, SynchronousQueue<Object>> waitingMap;
private int SendReq(InspectorMessage.InspectorMsgReq req) {
return SendReq(GAOutstream, req);
}
private int SendReq(DataOutputStream outstream, InspectorMessage.InspectorMsgReq req) {
byte[] serialized = req.toByteArray();
byte[] lengthBuf = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(serialized.length).array();
try {
outstream.write(lengthBuf);
outstream.write(serialized);
} catch (IOException e) {
return 1;
}
return 0;
}
private InspectorMessage.InspectorMsgRsp RecvRsp() {
return RecvRsp(GAInstream);
}
private InspectorMessage.InspectorMsgRsp RecvRsp(DataInputStream instream) {
byte[] lengthBuf = new byte[4];
try {
instream.read(lengthBuf, 0, 4);
} catch (IOException e) {
LOGGER.severe("failed to read header of response: " + e);
return null;
}
int length = ByteBuffer.wrap(lengthBuf).order(ByteOrder.LITTLE_ENDIAN).getInt();
byte[] rspBuf = new byte[length];
try {
instream.read(rspBuf, 0, length);
} catch (IOException e) {
LOGGER.severe("failed to read body of response: " + e);
return null;
}
InspectorMessage.InspectorMsgRsp rsp;
try {
rsp = InspectorMessage.InspectorMsgRsp.parseFrom(rspBuf);
} catch (InvalidProtocolBufferException e) {
LOGGER.severe("failed to parse response: " + e);
return null;
}
return rsp;
}
private InspectorMessage.InspectorMsgRsp ExecReq(InspectorMessage.InspectorMsgReq req) {
int ret = SendReq(req);
if (ret != 0) {
LOGGER.severe("failed to send request");
System.exit(1);
}
InspectorMessage.InspectorMsgRsp rsp = RecvRsp();
if (rsp == null) {
LOGGER.severe("failed to receive response");
System.exit(1);
}
return rsp;
}
public PBInspector() {
LOGGER = Logger.getLogger(this.getClass().getName());
LOGGER.setLevel(Level.INFO);
Signal signal = new Signal("TERM");
Signal.handle(signal, new SignalHandler() {
public void handle(Signal signal) {
LOGGER.info("singal: " + signal + " catched");
if (reader != null) {
reader.kill();
}
System.exit(0);
}
});
try {
FileHandler logFileHandler = new FileHandler("/tmp/namazu-inspection-java.log");
logFileHandler.setFormatter(new SimpleFormatter());
LOGGER.addHandler(logFileHandler);
} catch (IOException e) {
System.err.println("failed to initialize file hander for logging: " + e);
System.exit(1);
}
String _Disabled = System.getenv("NMZ_DISABLE");
if (_Disabled != null) {
LOGGER.info("inspection is disabled");
Disabled = true;
return;
}
String _Dryrun = System.getenv("NMZ_DRYRUN");
if (_Dryrun != null) {
LOGGER.info("inspection in dryrun");
Dryrun = true;
}
String _NoInitiation = System.getenv("NMZ_NO_INITIATION");
if (_NoInitiation != null) {
LOGGER.info("no initiation, connection per thread model");
NoInitiation = true;
}
String _Direct = System.getenv("NMZ_MODE_DIRECT");
if (_Direct != null) {
LOGGER.info("run in direct mode");
Direct = true;
} else {
LOGGER.info("run in non direct mode");
}
EntityID = System.getenv("NMZ_ENV_ENTITY_ID");
if (EntityID == null) {
LOGGER.severe("entity id required but not given (NMZ_ENV_ENTITY_ID");
System.exit(1);
}
LOGGER.info("Entity ID: " + EntityID);
String _GATCPPort = System.getenv("NMZ_GA_TCP_PORT");
if (_GATCPPort != null) {
GATCPPort = Integer.parseInt(_GATCPPort);
LOGGER.info("given TCP port of guest agent: " + GATCPPort);
}
waitingMap = new HashMap<Integer, SynchronousQueue<Object>>();
}
private boolean running = true;
private class ReaderThread extends Thread {
public void kill() {
InspectorMessage.InspectorMsgReq_Event_Exit.Builder evExitBuilder = InspectorMessage.InspectorMsgReq_Event_Exit.newBuilder();
InspectorMessage.InspectorMsgReq_Event_Exit evExit = evExitBuilder.setExitCode(0).build(); // TODO: exit code
InspectorMessage.InspectorMsgReq_Event.Builder evBuilder = InspectorMessage.InspectorMsgReq_Event.newBuilder();
InspectorMessage.InspectorMsgReq_Event ev = evBuilder
.setType(InspectorMessage.InspectorMsgReq_Event.Type.EXIT)
.setExit(evExit).build();
running = false;
sendEvent(ev, false, null, null);
try {
GAInstream.close();
} catch (IOException e) {
LOGGER.severe("closing GAInstream failed: " + e);
}
}
public void run() {
LOGGER.info("reader thread starts");
while (running) {
LOGGER.fine("reader thread loop");
InspectorMessage.InspectorMsgRsp rsp = RecvRsp();
if (rsp == null) {
// TODO: need to determine orchestrator is broken or kill() is called
if (!running) {
LOGGER.info("exiting reader thread");
return;
}
}
if (rsp.getRes() == InspectorMessage.InspectorMsgRsp.Result.END) {
LOGGER.info("inspection end");
Disabled = true;
break;
}
if (rsp.getRes() != InspectorMessage.InspectorMsgRsp.Result.ACK) {
LOGGER.severe("invalid response: " + rsp.getRes());
System.exit(1);
}
int msgID = rsp.getMsgId();
LOGGER.info("recieved response, message ID: " + Integer.toString(msgID));
synchronized (waitingMap) {
SynchronousQueue<Object> q = waitingMap.get(msgID);
Object token = new Object();
q.offer(token);
waitingMap.remove(q);
}
}
}
}
private ReaderThread reader;
public void Initiation() {
if (Disabled) {
return;
}
if (NoInitiation) {
LOGGER.info("no initiation mode");
return;
}
if (!Dryrun) {
try {
GASock = new Socket("localhost", GATCPPort);
OutputStream out = GASock.getOutputStream();
GAOutstream = new DataOutputStream(out);
InputStream in = GASock.getInputStream();
GAInstream = new DataInputStream(in);
} catch (IOException e) {
LOGGER.severe("failed to connect to guest agent: " + e);
System.exit(1);
}
}
InspectorMessage.InspectorMsgReq_Initiation.Builder initiationReqBuilder = InspectorMessage.InspectorMsgReq_Initiation.newBuilder();
InspectorMessage.InspectorMsgReq_Initiation initiationReq = initiationReqBuilder.setEntityId(EntityID).build();
InspectorMessage.InspectorMsgReq.Builder reqBuilder = InspectorMessage.InspectorMsgReq.newBuilder();
InspectorMessage.InspectorMsgReq req = reqBuilder.setPid(0 /* FIXME */)
.setTid((int) Thread.currentThread().getId())
.setType(InspectorMessage.InspectorMsgReq.Type.INITIATION)
.setMsgId(0)
.setEntityId(EntityID)
.setInitiation(initiationReq).build();
if (Dryrun) {
// TODO: dump initiation message
System.out.println("initiation message: " + req.toString());
return;
}
LOGGER.info("executing request for initiation");
InspectorMessage.InspectorMsgRsp rsp = ExecReq(req);
if (rsp.getRes() != InspectorMessage.InspectorMsgRsp.Result.ACK) {
LOGGER.severe("initiation failed, result: " + rsp.getRes());
System.exit(1);
}
LOGGER.info("initiation succeed");
reader = new ReaderThread();
reader.start();
}
private int MsgID = 1;
private synchronized int nextMsgID() {
int ret;
ret = MsgID;
MsgID++;
return ret;
}
private void sendEvent(InspectorMessage.InspectorMsgReq_Event ev, boolean needRsp,
InspectorMessage.InspectorMsgReq_JavaSpecificFields_StackTraceElement traces[],
InspectorMessage.InspectorMsgReq_JavaSpecificFields_Params[] params) {
int msgID = nextMsgID();
InspectorMessage.InspectorMsgReq_JavaSpecificFields.Builder javaSpecificFieldBuilder =
InspectorMessage.InspectorMsgReq_JavaSpecificFields.newBuilder();
javaSpecificFieldBuilder.setThreadName(Thread.currentThread().getName());
if (traces == null) {
javaSpecificFieldBuilder.setNrStackTraceElements(0);
} else {
javaSpecificFieldBuilder.setNrStackTraceElements(traces.length);
for (int i = 0; i < traces.length; i++) {
javaSpecificFieldBuilder.addStackTraceElements(traces[i]);
}
}
if (params == null) {
javaSpecificFieldBuilder.setNrParams(0);
} else {
javaSpecificFieldBuilder.setNrParams(params.length);
for (int i = 0; i < params.length; i++) {
javaSpecificFieldBuilder.addParams(params[i]);
}
}
InspectorMessage.InspectorMsgReq_JavaSpecificFields javaSpecificField = javaSpecificFieldBuilder.build();
InspectorMessage.InspectorMsgReq.Builder reqBuilder = InspectorMessage.InspectorMsgReq.newBuilder();
InspectorMessage.InspectorMsgReq req = reqBuilder.setPid(0 /*FIXME*/)
.setTid((int) Thread.currentThread().getId())
.setType(InspectorMessage.InspectorMsgReq.Type.EVENT)
.setMsgId(msgID)
.setEntityId(EntityID)
.setHasJavaSpecificFields(1)
.setJavaSpecificFields(javaSpecificField)
.setEvent(ev).build();
if (Dryrun) {
// TODO: dump message
System.out.println("dryrun mode, do nothing");
System.out.println("event message: " + req.toString());
return;
}
if (NoInitiation) {
final ThreadLocal<Socket> tlsSocket = new ThreadLocal<Socket>() {
protected Socket initialValue() {
Socket sock = null;
try {
sock = new Socket("localhost", GATCPPort);
sock.setSoTimeout(0);
} catch (IOException e) {
LOGGER.severe("failed to connect to guest agent: " + e);
return null;
}
return sock;
}
};
ThreadLocal<DataOutputStream> tlsOutputStream = new ThreadLocal<DataOutputStream>() {
protected DataOutputStream initialValue() {
DataOutputStream stream = null;
if (tlsSocket == null) {
LOGGER.severe("tlsSocket is null");
return null;
}
Socket sock = tlsSocket.get();
if (sock == null) {
LOGGER.severe("sock is null");
return null;
}
try {
OutputStream out = sock.getOutputStream();
stream = new DataOutputStream(out);
} catch (IOException e) {
LOGGER.severe("failed to get DataOutputStream: " + e);
return null;
}
return stream;
}
};
ThreadLocal<DataInputStream> tlsInputStream = new ThreadLocal<DataInputStream>() {
protected DataInputStream initialValue() {
DataInputStream stream = null;
if (tlsSocket == null) {
LOGGER.severe("tlsSocket is null");
return null;
}
Socket sock = tlsSocket.get();
if (sock == null) {
LOGGER.severe("sock is null");
return null;
}
try {
InputStream in = sock.getInputStream();
stream = new DataInputStream(in);
} catch (IOException e) {
LOGGER.severe("failed to get DataOutputStream: " + e);
return null;
}
return stream;
}
};
if (tlsInputStream != null && tlsOutputStream.get() != null) {
SendReq(tlsOutputStream.get(), req);
InspectorMessage.InspectorMsgRsp rsp = RecvRsp(tlsInputStream.get());
if (rsp != null) {
LOGGER.fine("response message: " + rsp.toString());
}
} else {
LOGGER.warning("socket ins't ready");
}
} else {
SendReq(req);
SynchronousQueue<Object> q = new SynchronousQueue<Object>();
synchronized (waitingMap) {
waitingMap.put(msgID, q);
}
if (!needRsp) {
return;
}
try {
q.take();
} catch (InterruptedException e) {
LOGGER.severe("interrupted: " + e);
System.exit(1); // TODO: handling
}
}
}
private InspectorMessage.InspectorMsgReq_JavaSpecificFields_StackTraceElement[] makeStackTrace() {
StackTraceElement traces[] = Thread.currentThread().getStackTrace();
/* CAUTION: heuristics */
int maxRuleJavaIdx = -1;
for (int i = 0; i < traces.length; i++) {
StackTraceElement trace = traces[i];
if (trace == null) {
continue;
}
String fileName = trace.getFileName();
if (fileName == null) {
continue;
}
if (fileName.equals("Rule.java")) {
maxRuleJavaIdx = i;
}
}
if (maxRuleJavaIdx == -1) {
LOGGER.severe("unexpected call stack");
System.exit(1);
}
InspectorMessage.InspectorMsgReq_JavaSpecificFields_StackTraceElement[] ret = new InspectorMessage.InspectorMsgReq_JavaSpecificFields_StackTraceElement[traces.length - (maxRuleJavaIdx + 1)];
for (int i = maxRuleJavaIdx + 1, j = 0; i < traces.length; i++, j++) {
StackTraceElement trace = traces[i];
if (trace == null) {
LOGGER.info("stack trace entry %d is null" + i);
continue;
}
InspectorMessage.InspectorMsgReq_JavaSpecificFields_StackTraceElement.Builder traceBuilder = InspectorMessage.InspectorMsgReq_JavaSpecificFields_StackTraceElement.newBuilder();
traceBuilder.setClassName(trace.getClassName() != null ? trace.getClassName() : "<no class name>")
.setFileName(trace.getFileName() != null ? trace.getFileName() : "<no file name>")
.setMethodName(trace.getMethodName() != null ? trace.getMethodName() : "<no method name>")
.setLineNumber(trace.getLineNumber());
InspectorMessage.InspectorMsgReq_JavaSpecificFields_StackTraceElement newElement = traceBuilder.build();
ret[j] = newElement;
}
return ret;
}
public void EventFuncCall(String funcName) {
if (Disabled) {
LOGGER.fine("already disabled");
return;
}
if (!running) {
LOGGER.fine("killed");
return;
}
LOGGER.finest("EventFuncCall: " + funcName);
InspectorMessage.InspectorMsgReq_Event_FuncCall.Builder evFunBuilder = InspectorMessage.InspectorMsgReq_Event_FuncCall.newBuilder();
InspectorMessage.InspectorMsgReq_Event_FuncCall evFun = evFunBuilder.setName(funcName).build();
InspectorMessage.InspectorMsgReq_Event.Builder evBuilder = InspectorMessage.InspectorMsgReq_Event.newBuilder();
InspectorMessage.InspectorMsgReq_Event ev = evBuilder
.setType(InspectorMessage.InspectorMsgReq_Event.Type.FUNC_CALL)
.setFuncCall(evFun).build();
sendEvent(ev, true, makeStackTrace(), null);
}
public void EventFuncReturn(String funcName) {
if (Disabled) {
LOGGER.fine("already disabled");
return;
}
if (!running) {
LOGGER.fine("killed");
return;
}
LOGGER.finest("EventFuncReturn: " + funcName);
InspectorMessage.InspectorMsgReq_Event_FuncReturn.Builder evFunBuilder = InspectorMessage.InspectorMsgReq_Event_FuncReturn.newBuilder();
InspectorMessage.InspectorMsgReq_Event_FuncReturn evFun = evFunBuilder.setName(funcName).build();
InspectorMessage.InspectorMsgReq_Event.Builder evBuilder = InspectorMessage.InspectorMsgReq_Event.newBuilder();
InspectorMessage.InspectorMsgReq_Event ev = evBuilder
.setType(InspectorMessage.InspectorMsgReq_Event.Type.FUNC_RETURN)
.setFuncReturn(evFun).build();
sendEvent(ev, true, makeStackTrace(), null);
}
private InspectorMessage.InspectorMsgReq_JavaSpecificFields_Params[] makeParamsArray(Map<String, Object> paramMap) {
InspectorMessage.InspectorMsgReq_JavaSpecificFields_Params[] ret;
ret = new InspectorMessage.InspectorMsgReq_JavaSpecificFields_Params[paramMap.size()];
int i = 0;
for (Map.Entry<String, Object> e: paramMap.entrySet()) {
InspectorMessage.InspectorMsgReq_JavaSpecificFields_Params.Builder paramBuilder = InspectorMessage.InspectorMsgReq_JavaSpecificFields_Params.newBuilder();
ret[i++] = paramBuilder.setName(e.getKey()).setValue(e.getValue() == null ? "null" : e.getValue().toString()).build();
}
return ret;
}
private boolean classFilterMatch(String className) {
StackTraceElement traces[] = Thread.currentThread().getStackTrace();
for (int i = 0; i < traces.length; i++) {
StackTraceElement trace = traces[i];
String name = trace.getClassName();
if (name == null) {
continue;
}
if (name.equals(className)) {
LOGGER.info("class filter match: " + className);
return true;
}
}
LOGGER.info("class filter dones't match: " + className);
return false;
}
public void EventFuncCall(String funcName, String classFilter) {
if (!classFilterMatch(classFilter)) {
return;
}
EventFuncCall(funcName);
}
public void EventFuncReturn(String funcName, String classFilter) {
if (!classFilterMatch(classFilter)) {
return;
}
EventFuncReturn(funcName);
}
public void EventFuncCall(String funcName, Map<String, Object> paramMap) {
if (Disabled) {
LOGGER.fine("already disabled");
return;
}
if (!running) {
LOGGER.fine("killed");
return;
}
LOGGER.finest("EventFuncCall: " + funcName);
LOGGER.info("paramMap: " + paramMap.toString());
InspectorMessage.InspectorMsgReq_Event_FuncCall.Builder evFunBuilder = InspectorMessage.InspectorMsgReq_Event_FuncCall.newBuilder();
InspectorMessage.InspectorMsgReq_Event_FuncCall evFun = evFunBuilder.setName(funcName).build();
InspectorMessage.InspectorMsgReq_Event.Builder evBuilder = InspectorMessage.InspectorMsgReq_Event.newBuilder();
InspectorMessage.InspectorMsgReq_Event ev = evBuilder
.setType(InspectorMessage.InspectorMsgReq_Event.Type.FUNC_CALL)
.setFuncCall(evFun).build();
sendEvent(ev, true, makeStackTrace(), makeParamsArray(paramMap));
}
public void EventFuncReturn(String funcName, Map<String, Object> paramMap) {
if (Disabled) {
LOGGER.fine("already disabled");
return;
}
if (!running) {
LOGGER.fine("killed");
return;
}
LOGGER.finest("EventFuncReturn: " + funcName);
LOGGER.info("paramMap: " + paramMap.toString());
InspectorMessage.InspectorMsgReq_Event_FuncReturn.Builder evFunBuilder = InspectorMessage.InspectorMsgReq_Event_FuncReturn.newBuilder();
InspectorMessage.InspectorMsgReq_Event_FuncReturn evFun = evFunBuilder.setName(funcName).build();
InspectorMessage.InspectorMsgReq_Event.Builder evBuilder = InspectorMessage.InspectorMsgReq_Event.newBuilder();
InspectorMessage.InspectorMsgReq_Event ev = evBuilder
.setType(InspectorMessage.InspectorMsgReq_Event.Type.FUNC_RETURN)
.setFuncReturn(evFun).build();
sendEvent(ev, true, makeStackTrace(), makeParamsArray(paramMap));
}
public void EventFuncCall(String funcName, Map<String, Object> paramMap, String classFilter) {
if (!classFilterMatch(classFilter)) {
return;
}
EventFuncCall(funcName, paramMap);
}
public void EventFuncReturn(String funcName, Map<String, Object> paramMap, String classFilter) {
if (!classFilterMatch(classFilter)) {
return;
}
EventFuncReturn(funcName, paramMap);
}
public void StopInspection() {
if (Dryrun) {
System.out.println("dryrun mode, do nothing");
return;
}
if (reader != null) {
reader.kill();
}
}
}
| 11,419 |
679 | <reponame>Alan-love/openoffice
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlsecurity.hxx"
#include "xmldocumentwrapper_xmlsecimpl.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <xmloff/attrlist.hxx>
#include "xmlelementwrapper_xmlsecimpl.hxx"
//#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Deleted by AF
#include <memory.h>
*/
#include <sys/types.h>
#include <sys/stat.h>
#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif
#ifdef UNX
#define stricmp strcasecmp
#endif
namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;
namespace cssxcsax = com::sun::star::xml::csax;
namespace cssxs = com::sun::star::xml::sax;
namespace cssxw = com::sun::star::xml::wrapper;
#define SERVICE_NAME "com.sun.star.xml.wrapper.XMLDocumentWrapper"
#define IMPLEMENTATION_NAME "com.sun.star.xml.security.bridge.xmlsec.XMLDocumentWrapper_XmlSecImpl"
#define STRXMLNS "xmlns"
#define RTL_ASCII_USTRINGPARAM( asciiStr ) asciiStr, strlen( asciiStr ), RTL_TEXTENCODING_ASCII_US
#define RTL_UTF8_USTRINGPARAM( asciiStr ) asciiStr, strlen( asciiStr ), RTL_TEXTENCODING_UTF8
/* used by the recursiveDelete method */
#define NODE_REMOVED 0
#define NODE_NOTREMOVED 1
#define NODE_STOPED 2
XMLDocumentWrapper_XmlSecImpl::XMLDocumentWrapper_XmlSecImpl( )
{
saxHelper.startDocument();
m_pDocument = saxHelper.getDocument();
/*
* creates the virtual root element
*/
saxHelper.startElement(rtl::OUString(RTL_UTF8_USTRINGPARAM( "root" )), cssu::Sequence<cssxcsax::XMLAttribute>());
m_pRootElement = saxHelper.getCurrentNode();
m_pCurrentElement = m_pRootElement;
}
XMLDocumentWrapper_XmlSecImpl::~XMLDocumentWrapper_XmlSecImpl()
{
saxHelper.endDocument();
xmlFreeDoc(m_pDocument);
}
void XMLDocumentWrapper_XmlSecImpl::getNextSAXEvent()
/****** XMLDocumentWrapper_XmlSecImpl/getNextSAXEvent *************************
*
* NAME
* getNextSAXEvent -- Prepares the next SAX event to be manipulate
*
* SYNOPSIS
* getNextSAXEvent();
*
* FUNCTION
* When converting the document into SAX events, this method is used to
* decide the next SAX event to be generated.
* Two member variables are checked to make the decision, the
* m_pCurrentElement and the m_nCurrentPosition.
* The m_pCurrentElement represents the node which have been covered, and
* the m_nCurrentPosition represents the event which have been sent.
* For example, suppose that the m_pCurrentElement
* points to element A, and the m_nCurrentPosition equals to
* NODEPOSITION_STARTELEMENT, then the next SAX event should be the
* endElement for element A if A has no child, or startElement for the
* first child element of element A otherwise.
* The m_nCurrentPosition can be one of following values:
* NODEPOSITION_STARTELEMENT for startElement;
* NODEPOSITION_ENDELEMENT for endElement;
* NODEPOSITION_NORMAL for other SAX events;
*
* INPUTS
* empty
*
* RESULT
* empty
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
OSL_ASSERT( m_pCurrentElement != NULL );
/*
* Get the next event through tree order.
*
* if the current event is a startElement, then the next
* event depends on whether or not the current node has
* children.
*/
if (m_nCurrentPosition == NODEPOSITION_STARTELEMENT)
{
/*
* If the current node has children, then its first child
* should be next current node, and the next event will be
* startElement or charaters(PI) based on that child's node
* type. Otherwise, the endElement of current node is the
* next event.
*/
if (m_pCurrentElement->children != NULL)
{
m_pCurrentElement = m_pCurrentElement->children;
m_nCurrentPosition
= (m_pCurrentElement->type == XML_ELEMENT_NODE)?
NODEPOSITION_STARTELEMENT:NODEPOSITION_NORMAL;
}
else
{
m_nCurrentPosition = NODEPOSITION_ENDELEMENT;
}
}
/*
* if the current event is a not startElement, then the next
* event depends on whether or not the current node has
* following sibling.
*/
else if (m_nCurrentPosition == NODEPOSITION_ENDELEMENT || m_nCurrentPosition == NODEPOSITION_NORMAL)
{
xmlNodePtr pNextSibling = m_pCurrentElement->next;
/*
* If the current node has following sibling, that sibling
* should be next current node, and the next event will be
* startElement or charaters(PI) based on that sibling's node
* type. Otherwise, the endElement of current node's parent
* becomes the next event.
*/
if (pNextSibling != NULL)
{
m_pCurrentElement = pNextSibling;
m_nCurrentPosition
= (m_pCurrentElement->type == XML_ELEMENT_NODE)?
NODEPOSITION_STARTELEMENT:NODEPOSITION_NORMAL;
}
else
{
m_pCurrentElement = m_pCurrentElement->parent;
m_nCurrentPosition = NODEPOSITION_ENDELEMENT;
}
}
}
void XMLDocumentWrapper_XmlSecImpl::sendStartElement(
const cssu::Reference< cssxs::XDocumentHandler >& xHandler,
const cssu::Reference< cssxs::XDocumentHandler >& xHandler2,
const xmlNodePtr pNode) const
throw (cssxs::SAXException)
/****** XMLDocumentWrapper_XmlSecImpl/sendStartElement ************************
*
* NAME
* sendStartElement -- Constructs a startElement SAX event
*
* SYNOPSIS
* sendStartElement(xHandler, xHandler2, pNode);
*
* FUNCTION
* Used when converting the document into SAX event stream.
* This method constructs a startElement SAX event for a particular
* element, then calls the startElement methods of the XDocumentHandlers.
*
* INPUTS
* xHandler - the first XDocumentHandler interface to receive the
* startElement SAX event. It can be NULL.
* xHandler2 - the second XDocumentHandler interface to receive the
* startElement SAX event. It can't be NULL.
* pNode - the node on which the startElement should be generated.
* This node must be a element type.
*
* RESULT
* empty
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
SvXMLAttributeList* pAttributeList = new SvXMLAttributeList();
cssu::Reference < cssxs::XAttributeList > xAttrList = cssu::Reference< cssxs::XAttributeList > (pAttributeList);
xmlNsPtr pNsDef = pNode->nsDef;
while (pNsDef != NULL)
{
const xmlChar* pNsPrefix = pNsDef->prefix;
const xmlChar* pNsHref = pNsDef->href;
if (pNsDef->prefix == NULL)
{
pAttributeList->AddAttribute(
rtl::OUString(RTL_UTF8_USTRINGPARAM( STRXMLNS )),
rtl::OUString(RTL_UTF8_USTRINGPARAM( (sal_Char*)pNsHref )));
}
else
{
pAttributeList->AddAttribute(
rtl::OUString(RTL_UTF8_USTRINGPARAM( STRXMLNS ))
+rtl::OUString(RTL_UTF8_USTRINGPARAM( ":" ))
+rtl::OUString(RTL_UTF8_USTRINGPARAM( (sal_Char*)pNsPrefix )),
rtl::OUString(RTL_UTF8_USTRINGPARAM( (sal_Char*)pNsHref )));
}
pNsDef = pNsDef->next;
}
xmlAttrPtr pAttr = pNode->properties;
while (pAttr != NULL)
{
const xmlChar* pAttrName = pAttr->name;
xmlNsPtr pAttrNs = pAttr->ns;
rtl::OUString ouAttrName;
if (pAttrNs == NULL)
{
ouAttrName = rtl::OUString(RTL_UTF8_USTRINGPARAM( (sal_Char*)pAttrName ));
}
else
{
ouAttrName = rtl::OUString(RTL_UTF8_USTRINGPARAM( (sal_Char*)pAttrNs->prefix))
+rtl::OUString(RTL_UTF8_USTRINGPARAM( (sal_Char*)":" ))
+rtl::OUString(RTL_UTF8_USTRINGPARAM( (sal_Char*)pAttrName ));
}
pAttributeList->AddAttribute(
ouAttrName,
rtl::OUString(RTL_UTF8_USTRINGPARAM( (sal_Char*)(pAttr->children->content))));
pAttr = pAttr->next;
}
rtl::OString sNodeName = getNodeQName(pNode);
if (xHandler.is())
{
xHandler->startElement(
rtl::OUString(RTL_UTF8_USTRINGPARAM ( ((sal_Char*)(sNodeName.getStr())) )),
xAttrList);
}
xHandler2->startElement(
rtl::OUString(RTL_UTF8_USTRINGPARAM ( ((sal_Char*)(sNodeName.getStr())) )),
xAttrList);
}
void XMLDocumentWrapper_XmlSecImpl::sendEndElement(
const cssu::Reference< cssxs::XDocumentHandler >& xHandler,
const cssu::Reference< cssxs::XDocumentHandler >& xHandler2,
const xmlNodePtr pNode) const
throw (cssxs::SAXException)
/****** XMLDocumentWrapper_XmlSecImpl/sendEndElement **************************
*
* NAME
* sendEndElement -- Constructs a endElement SAX event
*
* SYNOPSIS
* sendEndElement(xHandler, xHandler2, pNode);
*
* FUNCTION
* Used when converting the document into SAX event stream.
* This method constructs a endElement SAX event for a particular
* element, then calls the endElement methods of the XDocumentHandlers.
*
* INPUTS
* xHandler - the first XDocumentHandler interface to receive the
* endElement SAX event. It can be NULL.
* xHandler2 - the second XDocumentHandler interface to receive the
* endElement SAX event. It can't be NULL.
* pNode - the node on which the endElement should be generated.
* This node must be a element type.
*
* RESULT
* empty
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
rtl::OString sNodeName = getNodeQName(pNode);
if (xHandler.is())
{
xHandler->endElement(rtl::OUString(RTL_UTF8_USTRINGPARAM ( ((sal_Char*)(sNodeName.getStr())) )));
}
xHandler2->endElement(rtl::OUString(RTL_UTF8_USTRINGPARAM ( ((sal_Char*)(sNodeName.getStr())) )));
}
void XMLDocumentWrapper_XmlSecImpl::sendNode(
const cssu::Reference< cssxs::XDocumentHandler >& xHandler,
const cssu::Reference< cssxs::XDocumentHandler >& xHandler2,
const xmlNodePtr pNode) const
throw (cssxs::SAXException)
/****** XMLDocumentWrapper_XmlSecImpl/sendNode ********************************
*
* NAME
* sendNode -- Constructs a characters SAX event or a
* processingInstruction SAX event
*
* SYNOPSIS
* sendNode(xHandler, xHandler2, pNode);
*
* FUNCTION
* Used when converting the document into SAX event stream.
* This method constructs a characters SAX event or a
* processingInstructionfor SAX event based on the type of a particular
* element, then calls the corresponding methods of the XDocumentHandlers.
*
* INPUTS
* xHandler - the first XDocumentHandler interface to receive the
* SAX event. It can be NULL.
* xHandler2 - the second XDocumentHandler interface to receive the
* SAX event. It can't be NULL.
* pNode - the node on which the endElement should be generated.
* If it is a text node, then a characters SAX event is
* generated; if it is a PI node, then a
* processingInstructionfor SAX event is generated.
*
* RESULT
* empty
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
xmlElementType type = pNode->type;
if (type == XML_TEXT_NODE)
{
if (xHandler.is())
{
xHandler->characters(rtl::OUString(RTL_UTF8_USTRINGPARAM ( ((sal_Char*)(pNode->content)) )));
}
xHandler2->characters(rtl::OUString(RTL_UTF8_USTRINGPARAM ( ((sal_Char*)(pNode->content)) )));
}
else if (type == XML_PI_NODE)
{
if (xHandler.is())
{
xHandler->processingInstruction(
rtl::OUString(RTL_UTF8_USTRINGPARAM ( ((sal_Char*)(pNode->name)) )),
rtl::OUString(RTL_UTF8_USTRINGPARAM ( ((sal_Char*)(pNode->content)) )));
}
xHandler2->processingInstruction(
rtl::OUString(RTL_UTF8_USTRINGPARAM ( ((sal_Char*)(pNode->name)) )),
rtl::OUString(RTL_UTF8_USTRINGPARAM ( ((sal_Char*)(pNode->content)) )));
}
}
rtl::OString XMLDocumentWrapper_XmlSecImpl::getNodeQName(const xmlNodePtr pNode) const
/****** XMLDocumentWrapper_XmlSecImpl/getNodeQName ****************************
*
* NAME
* getNodeQName -- Retrieves the qualified name of a node
*
* SYNOPSIS
* name = getNodeQName(pNode);
*
* FUNCTION
* see NAME
*
* INPUTS
* pNode - the node whose name will be retrieved
*
* RESULT
* name - the node's qualified name
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
rtl::OString sNodeName((const sal_Char*)pNode->name);
if (pNode->ns != NULL)
{
xmlNsPtr pNs = pNode->ns;
if (pNs->prefix != NULL)
{
rtl::OString sPrefix((const sal_Char*)pNs->prefix);
sNodeName = sPrefix+rtl::OString(":")+sNodeName;
}
}
return sNodeName;
}
xmlNodePtr XMLDocumentWrapper_XmlSecImpl::checkElement( const cssu::Reference< cssxw::XXMLElementWrapper >& xXMLElement) const
/****** XMLDocumentWrapper_XmlSecImpl/checkElement ****************************
*
* NAME
* checkElement -- Retrieves the node wrapped by an XXMLElementWrapper
* interface
*
* SYNOPSIS
* node = checkElement(xXMLElement);
*
* FUNCTION
* see NAME
*
* INPUTS
* xXMLElement - the XXMLElementWrapper interface wraping a node
*
* RESULT
* node - the node wrapped in the XXMLElementWrapper interface
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
xmlNodePtr rc = NULL;
if (xXMLElement.is())
{
cssu::Reference< cssl::XUnoTunnel > xNodTunnel( xXMLElement, cssu::UNO_QUERY ) ;
if( !xNodTunnel.is() )
{
throw cssu::RuntimeException() ;
}
XMLElementWrapper_XmlSecImpl* pElement
= reinterpret_cast<XMLElementWrapper_XmlSecImpl*>(
sal::static_int_cast<sal_uIntPtr>(
xNodTunnel->getSomething(
XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ))) ;
if( pElement == NULL ) {
throw cssu::RuntimeException() ;
}
rc = pElement->getNativeElement();
}
return rc;
}
sal_Int32 XMLDocumentWrapper_XmlSecImpl::recursiveDelete(
const xmlNodePtr pNode)
/****** XMLDocumentWrapper_XmlSecImpl/recursiveDelete *************************
*
* NAME
* recursiveDelete -- Deletes a paticular node with its branch.
*
* SYNOPSIS
* result = recursiveDelete(pNode);
*
* FUNCTION
* Deletes a paticular node with its branch, while reserving the nodes
* (and their brance) listed in the m_aReservedNodes.
* The deletion process is preformed in the tree order, that is, a node
* is deleted after its previous sibling node is deleted, a parent node
* is deleted after its branch is deleted.
* During the deletion process when the m_pStopAtNode is reached, the
* progress is interrupted at once.
*
* INPUTS
* pNode - the node to be deleted
*
* RESULT
* result - the result of the deletion process, can be one of following
* values:
* NODE_STOPED - the process is interrupted by meeting the
* m_pStopAtNode
* NODE_NOTREMOVED - the pNode is not completely removed
* because there is its descendant in the
* m_aReservedNodes list
* NODE_REMOVED - the pNode and its branch are completely
* removed
*
* NOTES
* The node in the m_aReservedNodes list must be in the tree order, otherwise
* the result is unpredictable.
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
if (pNode == m_pStopAtNode)
{
return NODE_STOPED;
}
if (pNode != m_pCurrentReservedNode)
{
xmlNodePtr pChild = pNode->children;
xmlNodePtr pNextSibling;
bool bIsRemoved = true;
sal_Int32 nResult;
while( pChild != NULL )
{
pNextSibling = pChild->next;
nResult = recursiveDelete(pChild);
switch (nResult)
{
case NODE_STOPED:
return NODE_STOPED;
case NODE_NOTREMOVED:
bIsRemoved = false;
break;
case NODE_REMOVED:
removeNode(pChild);
break;
default:
throw cssu::RuntimeException();
}
pChild = pNextSibling;
}
if (pNode == m_pCurrentElement)
{
bIsRemoved = false;
}
return bIsRemoved?NODE_REMOVED:NODE_NOTREMOVED;
}
else
{
getNextReservedNode();
return NODE_NOTREMOVED;
}
}
void XMLDocumentWrapper_XmlSecImpl::getNextReservedNode()
/****** XMLDocumentWrapper_XmlSecImpl/getNextReservedNode *********************
*
* NAME
* getNextReservedNode -- Highlights the next reserved node in the
* reserved node list
*
* SYNOPSIS
* getNextReservedNode();
*
* FUNCTION
* The m_aReservedNodes array holds a node list, while the
* m_pCurrentReservedNode points to the one currently highlighted.
* This method is used to highlight the next node in the node list.
* This method is called at the time when the current highlighted node
* has been already processed, and the next node should be ready.
*
* INPUTS
* empty
*
* RESULT
* empty
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
if (m_nReservedNodeIndex < m_aReservedNodes.getLength())
{
m_pCurrentReservedNode = checkElement( m_aReservedNodes[m_nReservedNodeIndex] );
m_nReservedNodeIndex ++;
}
else
{
m_pCurrentReservedNode = NULL;
}
}
void XMLDocumentWrapper_XmlSecImpl::removeNode(const xmlNodePtr pNode) const
/****** XMLDocumentWrapper_XmlSecImpl/removeNode ******************************
*
* NAME
* removeNode -- Deletes a node with its branch unconditionaly
*
* SYNOPSIS
* removeNode( pNode );
*
* FUNCTION
* Delete the node along with its branch from the document.
*
* INPUTS
* pNode - the node to be deleted
*
* RESULT
* empty
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
/* you can't remove the current node */
OSL_ASSERT( m_pCurrentElement != pNode );
xmlAttrPtr pAttr = pNode->properties;
while (pAttr != NULL)
{
if (!stricmp((sal_Char*)pAttr->name,"id"))
{
xmlRemoveID(m_pDocument, pAttr);
}
pAttr = pAttr->next;
}
xmlUnlinkNode(pNode);
xmlFreeNode(pNode);
}
void XMLDocumentWrapper_XmlSecImpl::buildIDAttr(xmlNodePtr pNode) const
/****** XMLDocumentWrapper_XmlSecImpl/buildIDAttr *****************************
*
* NAME
* buildIDAttr -- build the ID attribute of a node
*
* SYNOPSIS
* buildIDAttr( pNode );
*
* FUNCTION
* see NAME
*
* INPUTS
* pNode - the node whose id attribute will be built
*
* RESULT
* empty
*
* HISTORY
* 14.06.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
xmlAttrPtr idAttr = xmlHasProp( pNode, (const unsigned char *)"id" );
if (idAttr == NULL)
{
idAttr = xmlHasProp( pNode, (const unsigned char *)"Id" );
}
if (idAttr != NULL)
{
xmlChar* idValue = xmlNodeListGetString( m_pDocument, idAttr->children, 1 ) ;
xmlAddID( NULL, m_pDocument, idValue, idAttr );
}
}
void XMLDocumentWrapper_XmlSecImpl::rebuildIDLink(xmlNodePtr pNode) const
/****** XMLDocumentWrapper_XmlSecImpl/rebuildIDLink ***************************
*
* NAME
* rebuildIDLink -- rebuild the ID link for the branch
*
* SYNOPSIS
* rebuildIDLink( pNode );
*
* FUNCTION
* see NAME
*
* INPUTS
* pNode - the node, from which the branch will be rebuilt
*
* RESULT
* empty
*
* HISTORY
* 14.06.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
if (pNode != NULL && pNode->type == XML_ELEMENT_NODE)
{
buildIDAttr( pNode );
xmlNodePtr child = pNode->children;
while (child != NULL)
{
rebuildIDLink(child);
child = child->next;
}
}
}
/* XXMLDocumentWrapper */
cssu::Reference< cssxw::XXMLElementWrapper > SAL_CALL XMLDocumentWrapper_XmlSecImpl::getCurrentElement( )
throw (cssu::RuntimeException)
{
XMLElementWrapper_XmlSecImpl* pElement = new XMLElementWrapper_XmlSecImpl(m_pCurrentElement);
return (cssu::Reference< cssxw::XXMLElementWrapper >)pElement;
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::setCurrentElement( const cssu::Reference< cssxw::XXMLElementWrapper >& element )
throw (cssu::RuntimeException)
{
m_pCurrentElement = checkElement( element );
saxHelper.setCurrentNode( m_pCurrentElement );
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::removeCurrentElement( )
throw (cssu::RuntimeException)
{
OSL_ASSERT( m_pCurrentElement != NULL );
xmlNodePtr pOldCurrentElement = m_pCurrentElement;
/*
* pop the top node in the parser context's
* nodeTab stack, then the parent of that node will
* automatically become the new stack top, and
* the current node as well.
*/
saxHelper.endElement(
rtl::OUString(
RTL_UTF8_USTRINGPARAM (
(sal_Char*)(pOldCurrentElement->name)
)));
m_pCurrentElement = saxHelper.getCurrentNode();
/*
* remove the node
*/
removeNode(pOldCurrentElement);
}
sal_Bool SAL_CALL XMLDocumentWrapper_XmlSecImpl::isCurrent( const cssu::Reference< cssxw::XXMLElementWrapper >& node )
throw (cssu::RuntimeException)
{
xmlNodePtr pNode = checkElement(node);
return (pNode == m_pCurrentElement);
}
sal_Bool SAL_CALL XMLDocumentWrapper_XmlSecImpl::isCurrentElementEmpty( )
throw (cssu::RuntimeException)
{
sal_Bool rc = sal_False;
if (m_pCurrentElement->children == NULL)
{
rc = sal_True;
}
return rc;
}
rtl::OUString SAL_CALL XMLDocumentWrapper_XmlSecImpl::getNodeName( const cssu::Reference< cssxw::XXMLElementWrapper >& node )
throw (cssu::RuntimeException)
{
xmlNodePtr pNode = checkElement(node);
return rtl::OUString(RTL_UTF8_USTRINGPARAM ( (sal_Char*)pNode->name ));
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::clearUselessData(
const cssu::Reference< cssxw::XXMLElementWrapper >& node,
const cssu::Sequence< cssu::Reference< cssxw::XXMLElementWrapper > >& reservedDescendants,
const cssu::Reference< cssxw::XXMLElementWrapper >& stopAtNode )
throw (cssu::RuntimeException)
{
xmlNodePtr pTargetNode = checkElement(node);
m_pStopAtNode = checkElement(stopAtNode);
m_aReservedNodes = reservedDescendants;
m_nReservedNodeIndex = 0;
getNextReservedNode();
recursiveDelete(pTargetNode);
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::collapse( const cssu::Reference< cssxw::XXMLElementWrapper >& node )
throw (cssu::RuntimeException)
{
xmlNodePtr pTargetNode = checkElement(node);
xmlNodePtr pParent;
while (pTargetNode != NULL)
{
if (pTargetNode->children != NULL || pTargetNode == m_pCurrentElement)
{
break;
}
pParent = pTargetNode->parent;
removeNode(pTargetNode);
pTargetNode = pParent;
}
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::getTree( const cssu::Reference< cssxs::XDocumentHandler >& handler )
throw (cssxs::SAXException, cssu::RuntimeException)
{
if (m_pRootElement != NULL)
{
xmlNodePtr pTempCurrentElement = m_pCurrentElement;
sal_Int32 nTempCurrentPosition = m_nCurrentPosition;
m_pCurrentElement = m_pRootElement;
m_nCurrentPosition = NODEPOSITION_STARTELEMENT;
cssu::Reference< cssxs::XDocumentHandler > xHandler = handler;
while(true)
{
switch (m_nCurrentPosition)
{
case NODEPOSITION_STARTELEMENT:
sendStartElement(NULL, xHandler, m_pCurrentElement);
break;
case NODEPOSITION_ENDELEMENT:
sendEndElement(NULL, xHandler, m_pCurrentElement);
break;
case NODEPOSITION_NORMAL:
sendNode(NULL, xHandler, m_pCurrentElement);
break;
}
if ( (m_pCurrentElement == m_pRootElement) && (m_nCurrentPosition == NODEPOSITION_ENDELEMENT ))
{
break;
}
getNextSAXEvent();
}
m_pCurrentElement = pTempCurrentElement;
m_nCurrentPosition = nTempCurrentPosition;
}
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::generateSAXEvents(
const cssu::Reference< cssxs::XDocumentHandler >& handler,
const cssu::Reference< cssxs::XDocumentHandler >& xEventKeeperHandler,
const cssu::Reference< cssxw::XXMLElementWrapper >& startNode,
const cssu::Reference< cssxw::XXMLElementWrapper >& endNode )
throw (cssxs::SAXException, cssu::RuntimeException)
{
/*
* The first SAX event is the startElement of the startNode
* element.
*/
bool bHasCurrentElementChild = (m_pCurrentElement->children != NULL);
xmlNodePtr pTempCurrentElement = m_pCurrentElement;
m_pCurrentElement = checkElement(startNode);
if (m_pCurrentElement->type == XML_ELEMENT_NODE)
{
m_nCurrentPosition = NODEPOSITION_STARTELEMENT;
}
else
{
m_nCurrentPosition = NODEPOSITION_NORMAL;
}
xmlNodePtr pEndNode = checkElement(endNode);
cssu::Reference < cssxc::sax::XSAXEventKeeper > xSAXEventKeeper( xEventKeeperHandler, cssu::UNO_QUERY );
cssu::Reference< cssxs::XDocumentHandler > xHandler = handler;
while(true)
{
switch (m_nCurrentPosition)
{
case NODEPOSITION_STARTELEMENT:
sendStartElement(xHandler, xEventKeeperHandler, m_pCurrentElement);
break;
case NODEPOSITION_ENDELEMENT:
sendEndElement(xHandler, xEventKeeperHandler, m_pCurrentElement);
break;
case NODEPOSITION_NORMAL:
sendNode(xHandler, xEventKeeperHandler, m_pCurrentElement);
break;
default:
throw cssu::RuntimeException();
}
if (xSAXEventKeeper->isBlocking())
{
xHandler = NULL;
}
if (pEndNode == NULL &&
((bHasCurrentElementChild && m_pCurrentElement == xmlGetLastChild(pTempCurrentElement) && m_nCurrentPosition != NODEPOSITION_STARTELEMENT) ||
(!bHasCurrentElementChild && m_pCurrentElement == pTempCurrentElement && m_nCurrentPosition == NODEPOSITION_STARTELEMENT)))
{
break;
}
getNextSAXEvent();
/*
* If there is an end point specified, then check whether
* the current node equals to the end point. If so, stop
* generating.
*/
if (pEndNode != NULL && m_pCurrentElement == pEndNode)
{
break;
}
}
m_pCurrentElement = pTempCurrentElement;
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::rebuildIDLink(
const com::sun::star::uno::Reference< com::sun::star::xml::wrapper::XXMLElementWrapper >& node )
throw (com::sun::star::uno::RuntimeException)
{
xmlNodePtr pNode = checkElement( node );
rebuildIDLink(pNode);
}
/* cssxs::XDocumentHandler */
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::startDocument( )
throw (cssxs::SAXException, cssu::RuntimeException)
{
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::endDocument( )
throw (cssxs::SAXException, cssu::RuntimeException)
{
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::startElement( const rtl::OUString& aName, const cssu::Reference< cssxs::XAttributeList >& xAttribs )
throw (cssxs::SAXException, cssu::RuntimeException)
{
sal_Int32 nLength = xAttribs->getLength();
cssu::Sequence< cssxcsax::XMLAttribute > aAttributes (nLength);
for (int i = 0; i < nLength; ++i)
{
aAttributes[i].sName = xAttribs->getNameByIndex((short)i);
aAttributes[i].sValue =xAttribs->getValueByIndex((short)i);
}
_startElement(aName, aAttributes);
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::endElement( const rtl::OUString& aName )
throw (cssxs::SAXException, cssu::RuntimeException)
{
saxHelper.endElement(aName);
m_pCurrentElement = saxHelper.getCurrentNode();
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::characters( const rtl::OUString& aChars )
throw (cssxs::SAXException, cssu::RuntimeException)
{
saxHelper.characters(aChars);
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::ignorableWhitespace( const rtl::OUString& aWhitespaces )
throw (cssxs::SAXException, cssu::RuntimeException)
{
saxHelper.ignorableWhitespace(aWhitespaces);
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::processingInstruction( const rtl::OUString& aTarget, const rtl::OUString& aData )
throw (cssxs::SAXException, cssu::RuntimeException)
{
saxHelper.processingInstruction(aTarget, aData);
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::setDocumentLocator( const cssu::Reference< cssxs::XLocator >& xLocator )
throw (cssxs::SAXException, cssu::RuntimeException)
{
saxHelper.setDocumentLocator(xLocator);
}
/* XCompressedDocumentHandler */
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::_startDocument( )
throw (cssxs::SAXException, cssu::RuntimeException)
{
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::_endDocument( )
throw (cssxs::SAXException, cssu::RuntimeException)
{
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::_startElement( const rtl::OUString& aName, const cssu::Sequence< cssxcsax::XMLAttribute >& aAttributes )
throw (cssxs::SAXException, cssu::RuntimeException)
{
saxHelper.startElement(aName, aAttributes);
m_pCurrentElement = saxHelper.getCurrentNode();
buildIDAttr( m_pCurrentElement );
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::_endElement( const rtl::OUString& aName )
throw (cssxs::SAXException, cssu::RuntimeException)
{
endElement( aName );
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::_characters( const rtl::OUString& aChars )
throw (cssxs::SAXException, cssu::RuntimeException)
{
characters( aChars );
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::_ignorableWhitespace( const rtl::OUString& aWhitespaces )
throw (cssxs::SAXException, cssu::RuntimeException)
{
ignorableWhitespace( aWhitespaces );
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::_processingInstruction( const rtl::OUString& aTarget, const rtl::OUString& aData )
throw (cssxs::SAXException, cssu::RuntimeException)
{
processingInstruction( aTarget, aData );
}
void SAL_CALL XMLDocumentWrapper_XmlSecImpl::_setDocumentLocator( sal_Int32 /*columnNumber*/, sal_Int32 /*lineNumber*/, const rtl::OUString& /*publicId*/, const rtl::OUString& /*systemId*/ )
throw (cssxs::SAXException, cssu::RuntimeException)
{
}
rtl::OUString XMLDocumentWrapper_XmlSecImpl_getImplementationName ()
throw (cssu::RuntimeException)
{
return rtl::OUString ( RTL_ASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
}
sal_Bool SAL_CALL XMLDocumentWrapper_XmlSecImpl_supportsService( const rtl::OUString& ServiceName )
throw (cssu::RuntimeException)
{
return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));
}
cssu::Sequence< rtl::OUString > SAL_CALL XMLDocumentWrapper_XmlSecImpl_getSupportedServiceNames( )
throw (cssu::RuntimeException)
{
cssu::Sequence < rtl::OUString > aRet(1);
rtl::OUString* pArray = aRet.getArray();
pArray[0] = rtl::OUString ( RTL_ASCII_USTRINGPARAM ( SERVICE_NAME ) );
return aRet;
}
#undef SERVICE_NAME
cssu::Reference< cssu::XInterface > SAL_CALL XMLDocumentWrapper_XmlSecImpl_createInstance(
const cssu::Reference< cssl::XMultiServiceFactory > &)
throw( cssu::Exception )
{
return (cppu::OWeakObject*) new XMLDocumentWrapper_XmlSecImpl( );
}
/* XServiceInfo */
rtl::OUString SAL_CALL XMLDocumentWrapper_XmlSecImpl::getImplementationName( )
throw (cssu::RuntimeException)
{
return XMLDocumentWrapper_XmlSecImpl_getImplementationName();
}
sal_Bool SAL_CALL XMLDocumentWrapper_XmlSecImpl::supportsService( const rtl::OUString& rServiceName )
throw (cssu::RuntimeException)
{
return XMLDocumentWrapper_XmlSecImpl_supportsService( rServiceName );
}
cssu::Sequence< rtl::OUString > SAL_CALL XMLDocumentWrapper_XmlSecImpl::getSupportedServiceNames( )
throw (cssu::RuntimeException)
{
return XMLDocumentWrapper_XmlSecImpl_getSupportedServiceNames();
}
| 12,126 |
742 | <reponame>ntzxtyz/ormpp<filename>pg_types.h<gh_stars>100-1000
//
// Created by qiyu on 10/30/17.
//
#ifndef ORM_PG_TYPES_H
#define ORM_PG_TYPES_H
#define BOOLOID 16
#define BYTEAOID 17
#define CHAROID 18
#define NAMEOID 19
#define INT8OID 20
#define INT2OID 21
#define INT2VECTOROID 22
#define INT4OID 23
#define REGPROCOID 24
#define TEXTOID 25
#define OIDOID 26
#define TIDOID 27
#define XIDOID 28
#define CIDOID 29
#define OIDVECTOROID 30
#define POINTOID 600
#define LSEGOID 601
#define PATHOID 602
#define BOXOID 603
#define POLYGONOID 604
#define LINEOID 628
#define FLOAT4OID 700
#define FLOAT8OID 701
#define ABSTIMEOID 702
#define RELTIMEOID 703
#define TINTERVALOID 704
#define UNKNOWNOID 705
#define CIRCLEOID 718
#define CASHOID 790
#define INETOID 869
#define CIDROID 650
#define BPCHAROID 1042
#define VARCHAROID 1043
#define DATEOID 1082
#define TIMEOID 1083
#define TIMESTAMPOID 1114
#define TIMESTAMPTZOID 1184
#define INTERVALOID 1186
#define TIMETZOID 1266
#define ZPBITOID 1560
#define VARBITOID 1562
#define NUMERICOID 1700
#endif //ORM_PG_TYPES_H
| 602 |
1,481 | <filename>core/src/test/java/apoc/generate/config/WattsStrogatzConfigTest.java
package apoc.generate.config;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Unit test for {@link WattsStrogatzConfig}.
*/
public class WattsStrogatzConfigTest {
@Test
public void shouldCorrectlyEvaluateValidConfig() {
assertFalse(new WattsStrogatzConfig(-1, 4, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(0, 4, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(1, 4, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(2, 4, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(3, 4, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(4, 4, 0.5).isValid());
assertTrue(new WattsStrogatzConfig(5, 4, 0.5).isValid());
assertTrue(new WattsStrogatzConfig(6, 4, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, 3, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, 2, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, 1, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, 0, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, -1, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, 5, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, 6, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, 7, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, 8, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, 111, 0.5).isValid());
assertFalse(new WattsStrogatzConfig(6, 4, -0.01).isValid());
assertTrue(new WattsStrogatzConfig(6, 4, 0).isValid());
assertTrue(new WattsStrogatzConfig(6, 4, 0.01).isValid());
assertTrue(new WattsStrogatzConfig(6, 4, 0.99).isValid());
assertTrue(new WattsStrogatzConfig(6, 4, 1.00).isValid());
assertFalse(new WattsStrogatzConfig(6, 4, 1.01).isValid());
}
}
| 832 |
1,264 | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.jsprit.core.algorithm.state;
import com.graphhopper.jsprit.core.problem.Capacity;
import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;
import com.graphhopper.jsprit.core.problem.solution.route.activity.ReverseActivityVisitor;
import com.graphhopper.jsprit.core.problem.solution.route.activity.TourActivity;
/**
* A {@link com.graphhopper.jsprit.core.problem.solution.route.activity.ReverseActivityVisitor} that looks forward in the vehicle route and determines
* the maximum capacity utilization (in terms of loads) at subsequent activities.
* <p>
* <p>Assume a vehicle route with the following activity sequence {start,pickup(1,4),delivery(2,3),pickup(3,2),end} where
* pickup(1,2) = pickup(id,cap-demand).<br>
* Future maxLoad for each activity are calculated as follows:<br>
* loadAt(end)=6 (since two pickups need to be delivered to depot)<br>
* pickup(3)=max(loadAt(pickup(3)), futureMaxLoad(end))=max(6,6)=6
* delivery(2)=max(loadAt(delivery(2),futureMaxLoad(pickup(3))=max(4,6)=6
* pickup(1)=max(7,6)=7
* start=max(7,7)=7
* activity (apart from start and end), the maximum capacity is determined when forward looking into the route.
* That is at each activity we know how much capacity is available whithout breaking future capacity constraints.
*
* @author schroeder
*/
class UpdateMaxCapacityUtilisationAtActivitiesByLookingForwardInRoute implements ReverseActivityVisitor, StateUpdater {
private StateManager stateManager;
private Capacity maxLoad;
private Capacity defaultValue;
public UpdateMaxCapacityUtilisationAtActivitiesByLookingForwardInRoute(StateManager stateManager) {
super();
this.stateManager = stateManager;
defaultValue = Capacity.Builder.newInstance().build();
}
@Override
public void begin(VehicleRoute route) {
maxLoad = stateManager.getRouteState(route, InternalStates.LOAD_AT_END, Capacity.class);
if (maxLoad == null) maxLoad = defaultValue;
}
@Override
public void visit(TourActivity act) {
maxLoad = Capacity.max(maxLoad, stateManager.getActivityState(act, InternalStates.LOAD, Capacity.class));
stateManager.putInternalTypedActivityState(act, InternalStates.FUTURE_MAXLOAD, maxLoad);
}
@Override
public void finish() {
}
}
| 953 |
808 | #include <ntddk.h>
#include "PoolManager.h"
#include "Logging.h"
#include "GlobalVariables.h"
#include "PoolManager.h"
#include "Common.h"
BOOLEAN PoolManagerInitialize(){
// Allocate global requesting variable
RequestNewAllocation = ExAllocatePoolWithTag(NonPagedPool, sizeof(REQUEST_NEW_ALLOCATION), POOLTAG);
if (!RequestNewAllocation)
{
LogError("Insufficient memory");
return FALSE;
}
RtlZeroMemory(RequestNewAllocation, sizeof(REQUEST_NEW_ALLOCATION));
ListOfAllocatedPoolsHead = ExAllocatePoolWithTag(NonPagedPool, sizeof(LIST_ENTRY), POOLTAG);
if (!ListOfAllocatedPoolsHead)
{
LogError("Insufficient memory");
return FALSE;
}
RtlZeroMemory(ListOfAllocatedPoolsHead, sizeof(LIST_ENTRY));
// Initialize list head
InitializeListHead(ListOfAllocatedPoolsHead);
// Request pages to be allocated for converting 2MB to 4KB pages
PoolManagerRequestAllocation(sizeof(VMM_EPT_DYNAMIC_SPLIT), 10, SPLIT_2MB_PAGING_TO_4KB_PAGE);
// Request pages to be allocated for paged hook details
PoolManagerRequestAllocation(sizeof(EPT_HOOKED_PAGE_DETAIL), 10, TRACKING_HOOKED_PAGES);
// Request pages to be allocated for Trampoline of Executable hooked pages
PoolManagerRequestAllocation(MAX_EXEC_TRAMPOLINE_SIZE, 10, EXEC_TRAMPOLINE);
// Let's start the allocations
return PoolManagerCheckAndPerformAllocation();
}
VOID PoolManagerUninitialize() {
PLIST_ENTRY ListTemp = 0;
UINT64 Address = 0;
ListTemp = ListOfAllocatedPoolsHead;
while (ListOfAllocatedPoolsHead != ListTemp->Flink)
{
ListTemp = ListTemp->Flink;
// Get the head of the record
PPOOL_TABLE PoolTable = (PPOOL_TABLE)CONTAINING_RECORD(ListTemp, POOL_TABLE, PoolsList);
// Free the alloocated buffer
ExFreePoolWithTag(PoolTable->Address, POOLTAG);
// Free the record itself
ExFreePoolWithTag(PoolTable, POOLTAG);
}
ExFreePoolWithTag(ListOfAllocatedPoolsHead, POOLTAG);
ExFreePoolWithTag(RequestNewAllocation, POOLTAG);
}
/* This function should be called from vmx-root in order to get a pool from the list */
// Returns a pool address or retuns null
/* If RequestNewPool is TRUE then Size is used, otherwise Size is useless */
// Should be executed at vmx root
UINT64 PoolManagerRequestPool(POOL_ALLOCATION_INTENTION Intention, BOOLEAN RequestNewPool , UINT32 Size)
{
PLIST_ENTRY ListTemp = 0;
UINT64 Address = 0;
ListTemp = ListOfAllocatedPoolsHead;
SpinlockLock(&LockForReadingPool);
while (ListOfAllocatedPoolsHead != ListTemp->Flink)
{
ListTemp = ListTemp->Flink;
// Get the head of the record
PPOOL_TABLE PoolTable = (PPOOL_TABLE) CONTAINING_RECORD(ListTemp, POOL_TABLE, PoolsList);
if (PoolTable->Intention == Intention && PoolTable->IsBusy == FALSE)
{
PoolTable->IsBusy = TRUE;
Address = PoolTable->Address;
break;
}
}
SpinlockUnlock(&LockForReadingPool);
// Check if we need additional pools e.g another pool or the pool will be available for the next use blah blah
if (RequestNewPool)
{
PoolManagerRequestAllocation(Size, 1, Intention);
}
// return Address might be null indicating there is no valid pools
return Address;
}
/* Allocate the new pools and add them to pool table */
// Should b ecalled in vmx non-root
// This function doesn't need lock as it just calls once from PASSIVE_LEVEL
BOOLEAN PoolManagerAllocateAndAddToPoolTable(SIZE_T Size, UINT32 Count, POOL_ALLOCATION_INTENTION Intention)
{
/* If we're here then we're in vmx non-root */
for (size_t i = 0; i < Count; i++)
{
POOL_TABLE* SinglePool = ExAllocatePoolWithTag(NonPagedPool, sizeof(POOL_TABLE), POOLTAG);
if (!SinglePool)
{
LogError("Insufficient memory");
return FALSE;
}
RtlZeroMemory(SinglePool, sizeof(POOL_TABLE));
// Allocate the buffer
SinglePool->Address = ExAllocatePoolWithTag(NonPagedPool, Size, POOLTAG);
if (!SinglePool->Address)
{
LogError("Insufficient memory");
return FALSE;
}
RtlZeroMemory(SinglePool->Address, Size);
SinglePool->Intention = Intention;
SinglePool->IsBusy = FALSE;
SinglePool->ShouldBeFreed = FALSE;
SinglePool->Size = Size;
// Add it to the list
InsertHeadList(ListOfAllocatedPoolsHead, &(SinglePool->PoolsList));
}
}
/* This function performs allocations from VMX non-root based on RequestNewAllocation */
BOOLEAN PoolManagerCheckAndPerformAllocation() {
BOOLEAN Result = TRUE;
//let's make sure we're on vmx non-root and also we have new allocation
if (!IsNewRequestForAllocationRecieved || GuestState[KeGetCurrentProcessorNumber()].IsOnVmxRootMode)
{
// allocation's can't be done from vmx root
return FALSE;
}
PAGED_CODE();
if (RequestNewAllocation->Size0 != 0)
{
Result = PoolManagerAllocateAndAddToPoolTable(RequestNewAllocation->Size0, RequestNewAllocation->Count0, RequestNewAllocation->Intention0);
// Free the data for future use
RequestNewAllocation->Count0 = 0;
RequestNewAllocation->Intention0 = 0;
RequestNewAllocation->Size0 = 0;
}
if (RequestNewAllocation->Size1 != 0)
{
Result = PoolManagerAllocateAndAddToPoolTable(RequestNewAllocation->Size1, RequestNewAllocation->Count1, RequestNewAllocation->Intention1);
// Free the data for future use
RequestNewAllocation->Count1 = 0;
RequestNewAllocation->Intention1 = 0;
RequestNewAllocation->Size1 = 0;
}
if (RequestNewAllocation->Size2 != 0)
{
Result = PoolManagerAllocateAndAddToPoolTable(RequestNewAllocation->Size2, RequestNewAllocation->Count2, RequestNewAllocation->Intention2);
// Free the data for future use
RequestNewAllocation->Count2 = 0;
RequestNewAllocation->Intention2 = 0;
RequestNewAllocation->Size2 = 0;
}
if (RequestNewAllocation->Size3 != 0)
{
Result = PoolManagerAllocateAndAddToPoolTable(RequestNewAllocation->Size3, RequestNewAllocation->Count3, RequestNewAllocation->Intention3);
// Free the data for future use
RequestNewAllocation->Count3 = 0;
RequestNewAllocation->Intention3 = 0;
RequestNewAllocation->Size3 = 0;
}
if (RequestNewAllocation->Size4 != 0)
{
Result = PoolManagerAllocateAndAddToPoolTable(RequestNewAllocation->Size4, RequestNewAllocation->Count4, RequestNewAllocation->Intention4);
// Free the data for future use
RequestNewAllocation->Count4 = 0;
RequestNewAllocation->Intention4 = 0;
RequestNewAllocation->Size4 = 0;
}
if (RequestNewAllocation->Size5 != 0)
{
Result = PoolManagerAllocateAndAddToPoolTable(RequestNewAllocation->Size5, RequestNewAllocation->Count5, RequestNewAllocation->Intention5);
// Free the data for future use
RequestNewAllocation->Count5 = 0;
RequestNewAllocation->Intention5 = 0;
RequestNewAllocation->Size5 = 0;
}
if (RequestNewAllocation->Size6 != 0)
{
Result = PoolManagerAllocateAndAddToPoolTable(RequestNewAllocation->Size6, RequestNewAllocation->Count6, RequestNewAllocation->Intention6);
// Free the data for future use
RequestNewAllocation->Count6 = 0;
RequestNewAllocation->Intention6 = 0;
RequestNewAllocation->Size6 = 0;
}
if (RequestNewAllocation->Size7 != 0)
{
Result = PoolManagerAllocateAndAddToPoolTable(RequestNewAllocation->Size7, RequestNewAllocation->Count7, RequestNewAllocation->Intention7);
// Free the data for future use
RequestNewAllocation->Count7 = 0;
RequestNewAllocation->Intention7 = 0;
RequestNewAllocation->Size7 = 0;
}
if (RequestNewAllocation->Size8 != 0)
{
Result = PoolManagerAllocateAndAddToPoolTable(RequestNewAllocation->Size8, RequestNewAllocation->Count8, RequestNewAllocation->Intention8);
// Free the data for future use
RequestNewAllocation->Count8 = 0;
RequestNewAllocation->Intention8 = 0;
RequestNewAllocation->Size8 = 0;
}
if (RequestNewAllocation->Size9 != 0)
{
Result = PoolManagerAllocateAndAddToPoolTable(RequestNewAllocation->Size9, RequestNewAllocation->Count9, RequestNewAllocation->Intention9);
// Free the data for future use
RequestNewAllocation->Count9 = 0;
RequestNewAllocation->Intention9 = 0;
RequestNewAllocation->Size9 = 0;
}
IsNewRequestForAllocationRecieved = FALSE;
return Result;
}
/* Request to allocate new buffers */
BOOLEAN PoolManagerRequestAllocation(SIZE_T Size, UINT32 Count, POOL_ALLOCATION_INTENTION Intention)
{
/* We check to find a free place to store */
SpinlockLock(&LockForRequestAllocation);
if (RequestNewAllocation->Size0 == 0)
{
RequestNewAllocation->Count0 = Count;
RequestNewAllocation->Intention0 = Intention;
RequestNewAllocation->Size0 = Size;
}
else if (RequestNewAllocation->Size1 == 0)
{
RequestNewAllocation->Count1 = Count;
RequestNewAllocation->Intention1 = Intention;
RequestNewAllocation->Size1 = Size;
}
else if (RequestNewAllocation->Size2 == 0)
{
RequestNewAllocation->Count2 = Count;
RequestNewAllocation->Intention2 = Intention;
RequestNewAllocation->Size2 = Size;
}
else if (RequestNewAllocation->Size3 == 0)
{
RequestNewAllocation->Count3 = Count;
RequestNewAllocation->Intention3 = Intention;
RequestNewAllocation->Size3 = Size;
}
else if (RequestNewAllocation->Size4 == 0)
{
RequestNewAllocation->Count4 = Count;
RequestNewAllocation->Intention4 = Intention;
RequestNewAllocation->Size4 = Size;
}
else if (RequestNewAllocation->Size5 == 0)
{
RequestNewAllocation->Count5 = Count;
RequestNewAllocation->Intention5 = Intention;
RequestNewAllocation->Size5 = Size;
}
else if (RequestNewAllocation->Size6 == 0)
{
RequestNewAllocation->Count6 = Count;
RequestNewAllocation->Intention6 = Intention;
RequestNewAllocation->Size6 = Size;
}
else if (RequestNewAllocation->Size7 == 0)
{
RequestNewAllocation->Count7 = Count;
RequestNewAllocation->Intention7 = Intention;
RequestNewAllocation->Size7 = Size;
}
else if (RequestNewAllocation->Size8 == 0)
{
RequestNewAllocation->Count8 = Count;
RequestNewAllocation->Intention8 = Intention;
RequestNewAllocation->Size8 = Size;
}
else if (RequestNewAllocation->Size9 == 0)
{
RequestNewAllocation->Count9 = Count;
RequestNewAllocation->Intention9 = Intention;
RequestNewAllocation->Size9 = Size;
}
else
{
SpinlockUnlock(&LockForRequestAllocation);
return FALSE;
}
// Signals to show that we have new allocations
IsNewRequestForAllocationRecieved = TRUE;
SpinlockUnlock(&LockForRequestAllocation);
return TRUE;
} | 3,861 |
1,208 | ../../../SVProgressHUD/SVProgressHUD/SVRadialGradientLayer.h | 22 |
453 | #include <string.h>
#include <unistd.h>
#include <errno.h>
char *
getwd (char *buf)
{
char tmp[MAXPATHLEN];
if (buf == NULL)
{
errno = EINVAL;
return NULL;
}
if (getcwd (tmp, MAXPATHLEN) == NULL)
return NULL;
return strncpy (buf, tmp, MAXPATHLEN);
}
| 137 |
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.slides.v1.model;
/**
* A TextElement kind that represents auto text.
*
* <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 Google Slides 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 AutoText extends com.google.api.client.json.GenericJson {
/**
* The rendered content of this auto text, if available.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String content;
/**
* The styling applied to this auto text.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TextStyle style;
/**
* The type of this auto text.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* The rendered content of this auto text, if available.
* @return value or {@code null} for none
*/
public java.lang.String getContent() {
return content;
}
/**
* The rendered content of this auto text, if available.
* @param content content or {@code null} for none
*/
public AutoText setContent(java.lang.String content) {
this.content = content;
return this;
}
/**
* The styling applied to this auto text.
* @return value or {@code null} for none
*/
public TextStyle getStyle() {
return style;
}
/**
* The styling applied to this auto text.
* @param style style or {@code null} for none
*/
public AutoText setStyle(TextStyle style) {
this.style = style;
return this;
}
/**
* The type of this auto text.
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* The type of this auto text.
* @param type type or {@code null} for none
*/
public AutoText setType(java.lang.String type) {
this.type = type;
return this;
}
@Override
public AutoText set(String fieldName, Object value) {
return (AutoText) super.set(fieldName, value);
}
@Override
public AutoText clone() {
return (AutoText) super.clone();
}
}
| 986 |
323 | THOST_FTDC_EXP_Normal = '0'
THOST_FTDC_EXP_GenOrderByTrade = '1'
THOST_FTDC_ICT_EID = '0'
THOST_FTDC_ICT_IDCard = '1'
THOST_FTDC_ICT_OfficerIDCard = '2'
THOST_FTDC_ICT_PoliceIDCard = '3'
THOST_FTDC_ICT_SoldierIDCard = '4'
THOST_FTDC_ICT_HouseholdRegister = '5'
THOST_FTDC_ICT_Passport = '6'
THOST_FTDC_ICT_TaiwanCompatriotIDCard = '7'
THOST_FTDC_ICT_HomeComingCard = '8'
THOST_FTDC_ICT_LicenseNo = '9'
THOST_FTDC_ICT_TaxNo = 'A'
THOST_FTDC_ICT_HMMainlandTravelPermit = 'B'
THOST_FTDC_ICT_TwMainlandTravelPermit = 'C'
THOST_FTDC_ICT_DrivingLicense = 'D'
THOST_FTDC_ICT_SocialID = 'F'
THOST_FTDC_ICT_LocalID = 'G'
THOST_FTDC_ICT_BusinessRegistration = 'H'
THOST_FTDC_ICT_HKMCIDCard = 'I'
THOST_FTDC_ICT_AccountsPermits = 'J'
THOST_FTDC_ICT_OtherCard = 'x'
THOST_FTDC_IR_All = '1'
THOST_FTDC_IR_Group = '2'
THOST_FTDC_IR_Single = '3'
THOST_FTDC_DR_All = '1'
THOST_FTDC_DR_Group = '2'
THOST_FTDC_DR_Single = '3'
THOST_FTDC_DS_Asynchronous = '1'
THOST_FTDC_DS_Synchronizing = '2'
THOST_FTDC_DS_Synchronized = '3'
THOST_FTDC_BDS_Synchronized = '1'
THOST_FTDC_BDS_Synchronizing = '2'
THOST_FTDC_ECS_NoConnection = '1'
THOST_FTDC_ECS_QryInstrumentSent = '2'
THOST_FTDC_ECS_GotInformation = '9'
THOST_FTDC_TCS_NotConnected = '1'
THOST_FTDC_TCS_Connected = '2'
THOST_FTDC_TCS_QryInstrumentSent = '3'
THOST_FTDC_TCS_SubPrivateFlow = '4'
THOST_FTDC_FC_DataAsync = '1'
THOST_FTDC_FC_ForceUserLogout = '2'
THOST_FTDC_FC_UserPasswordUpdate = '3'
THOST_FTDC_FC_BrokerPasswordUpdate = '4'
THOST_FTDC_FC_InvestorPasswordUpdate = '5'
THOST_FTDC_FC_OrderInsert = '6'
THOST_FTDC_FC_OrderAction = '7'
THOST_FTDC_FC_SyncSystemData = '8'
THOST_FTDC_FC_SyncBrokerData = '9'
THOST_FTDC_FC_BachSyncBrokerData = 'A'
THOST_FTDC_FC_SuperQuery = 'B'
THOST_FTDC_FC_ParkedOrderInsert = 'C'
THOST_FTDC_FC_ParkedOrderAction = 'D'
THOST_FTDC_FC_SyncOTP = 'E'
THOST_FTDC_FC_DeleteOrder = 'F'
THOST_FTDC_BFC_ForceUserLogout = '1'
THOST_FTDC_BFC_UserPasswordUpdate = '2'
THOST_FTDC_BFC_SyncBrokerData = '3'
THOST_FTDC_BFC_BachSyncBrokerData = '4'
THOST_FTDC_BFC_OrderInsert = '5'
THOST_FTDC_BFC_OrderAction = '6'
THOST_FTDC_BFC_AllQuery = '7'
THOST_FTDC_BFC_log = 'a'
THOST_FTDC_BFC_BaseQry = 'b'
THOST_FTDC_BFC_TradeQry = 'c'
THOST_FTDC_BFC_Trade = 'd'
THOST_FTDC_BFC_Virement = 'e'
THOST_FTDC_BFC_Risk = 'f'
THOST_FTDC_BFC_Session = 'g'
THOST_FTDC_BFC_RiskNoticeCtl = 'h'
THOST_FTDC_BFC_RiskNotice = 'i'
THOST_FTDC_BFC_BrokerDeposit = 'j'
THOST_FTDC_BFC_QueryFund = 'k'
THOST_FTDC_BFC_QueryOrder = 'l'
THOST_FTDC_BFC_QueryTrade = 'm'
THOST_FTDC_BFC_QueryPosition = 'n'
THOST_FTDC_BFC_QueryMarketData = 'o'
THOST_FTDC_BFC_QueryUserEvent = 'p'
THOST_FTDC_BFC_QueryRiskNotify = 'q'
THOST_FTDC_BFC_QueryFundChange = 'r'
THOST_FTDC_BFC_QueryInvestor = 's'
THOST_FTDC_BFC_QueryTradingCode = 't'
THOST_FTDC_BFC_ForceClose = 'u'
THOST_FTDC_BFC_PressTest = 'v'
THOST_FTDC_BFC_RemainCalc = 'w'
THOST_FTDC_BFC_NetPositionInd = 'x'
THOST_FTDC_BFC_RiskPredict = 'y'
THOST_FTDC_BFC_DataExport = 'z'
THOST_FTDC_BFC_RiskTargetSetup = 'A'
THOST_FTDC_BFC_MarketDataWarn = 'B'
THOST_FTDC_BFC_QryBizNotice = 'C'
THOST_FTDC_BFC_CfgBizNotice = 'D'
THOST_FTDC_BFC_SyncOTP = 'E'
THOST_FTDC_BFC_SendBizNotice = 'F'
THOST_FTDC_BFC_CfgRiskLevelStd = 'G'
THOST_FTDC_BFC_TbCommand = 'H'
THOST_FTDC_BFC_DeleteOrder = 'J'
THOST_FTDC_BFC_ParkedOrderInsert = 'K'
THOST_FTDC_BFC_ParkedOrderAction = 'L'
THOST_FTDC_BFC_ExecOrderNoCheck = 'M'
THOST_FTDC_OAS_Submitted = 'a'
THOST_FTDC_OAS_Accepted = 'b'
THOST_FTDC_OAS_Rejected = 'c'
THOST_FTDC_OST_AllTraded = '0'
THOST_FTDC_OST_PartTradedQueueing = '1'
THOST_FTDC_OST_PartTradedNotQueueing = '2'
THOST_FTDC_OST_NoTradeQueueing = '3'
THOST_FTDC_OST_NoTradeNotQueueing = '4'
THOST_FTDC_OST_Canceled = '5'
THOST_FTDC_OST_Unknown = 'a'
THOST_FTDC_OST_NotTouched = 'b'
THOST_FTDC_OST_Touched = 'c'
THOST_FTDC_OSS_InsertSubmitted = '0'
THOST_FTDC_OSS_CancelSubmitted = '1'
THOST_FTDC_OSS_ModifySubmitted = '2'
THOST_FTDC_OSS_Accepted = '3'
THOST_FTDC_OSS_InsertRejected = '4'
THOST_FTDC_OSS_CancelRejected = '5'
THOST_FTDC_OSS_ModifyRejected = '6'
THOST_FTDC_PSD_Today = '1'
THOST_FTDC_PSD_History = '2'
THOST_FTDC_PDT_UseHistory = '1'
THOST_FTDC_PDT_NoUseHistory = '2'
THOST_FTDC_ER_Broker = '1'
THOST_FTDC_ER_Host = '2'
THOST_FTDC_ER_Maker = '3'
THOST_FTDC_PC_Futures = '1'
THOST_FTDC_PC_Options = '2'
THOST_FTDC_PC_Combination = '3'
THOST_FTDC_PC_Spot = '4'
THOST_FTDC_PC_EFP = '5'
THOST_FTDC_PC_SpotOption = '6'
THOST_FTDC_IP_NotStart = '0'
THOST_FTDC_IP_Started = '1'
THOST_FTDC_IP_Pause = '2'
THOST_FTDC_IP_Expired = '3'
THOST_FTDC_D_Buy = '0'
THOST_FTDC_D_Sell = '1'
THOST_FTDC_PT_Net = '1'
THOST_FTDC_PT_Gross = '2'
THOST_FTDC_PD_Net = '1'
THOST_FTDC_PD_Long = '2'
THOST_FTDC_PD_Short = '3'
THOST_FTDC_SS_NonActive = '1'
THOST_FTDC_SS_Startup = '2'
THOST_FTDC_SS_Operating = '3'
THOST_FTDC_SS_Settlement = '4'
THOST_FTDC_SS_SettlementFinished = '5'
THOST_FTDC_RA_Trade = '0'
THOST_FTDC_RA_Settlement = '1'
THOST_FTDC_HF_Speculation = '1'
THOST_FTDC_HF_Arbitrage = '2'
THOST_FTDC_HF_Hedge = '3'
THOST_FTDC_HF_MarketMaker = '5'
THOST_FTDC_BHF_Speculation = '1'
THOST_FTDC_BHF_Arbitrage = '2'
THOST_FTDC_BHF_Hedge = '3'
THOST_FTDC_CIDT_Speculation = '1'
THOST_FTDC_CIDT_Arbitrage = '2'
THOST_FTDC_CIDT_Hedge = '3'
THOST_FTDC_CIDT_MarketMaker = '5'
THOST_FTDC_OPT_AnyPrice = '1'
THOST_FTDC_OPT_LimitPrice = '2'
THOST_FTDC_OPT_BestPrice = '3'
THOST_FTDC_OPT_LastPrice = '4'
THOST_FTDC_OPT_LastPricePlusOneTicks = '5'
THOST_FTDC_OPT_LastPricePlusTwoTicks = '6'
THOST_FTDC_OPT_LastPricePlusThreeTicks = '7'
THOST_FTDC_OPT_AskPrice1 = '8'
THOST_FTDC_OPT_AskPrice1PlusOneTicks = '9'
THOST_FTDC_OPT_AskPrice1PlusTwoTicks = 'A'
THOST_FTDC_OPT_AskPrice1PlusThreeTicks = 'B'
THOST_FTDC_OPT_BidPrice1 = 'C'
THOST_FTDC_OPT_BidPrice1PlusOneTicks = 'D'
THOST_FTDC_OPT_BidPrice1PlusTwoTicks = 'E'
THOST_FTDC_OPT_BidPrice1PlusThreeTicks = 'F'
THOST_FTDC_OPT_FiveLevelPrice = 'G'
THOST_FTDC_OF_Open = '0'
THOST_FTDC_OF_Close = '1'
THOST_FTDC_OF_ForceClose = '2'
THOST_FTDC_OF_CloseToday = '3'
THOST_FTDC_OF_CloseYesterday = '4'
THOST_FTDC_OF_ForceOff = '5'
THOST_FTDC_OF_LocalForceClose = '6'
THOST_FTDC_FCC_NotForceClose = '0'
THOST_FTDC_FCC_LackDeposit = '1'
THOST_FTDC_FCC_ClientOverPositionLimit = '2'
THOST_FTDC_FCC_MemberOverPositionLimit = '3'
THOST_FTDC_FCC_NotMultiple = '4'
THOST_FTDC_FCC_Violation = '5'
THOST_FTDC_FCC_Other = '6'
THOST_FTDC_FCC_PersonDeliv = '7'
THOST_FTDC_ORDT_Normal = '0'
THOST_FTDC_ORDT_DeriveFromQuote = '1'
THOST_FTDC_ORDT_DeriveFromCombination = '2'
THOST_FTDC_ORDT_Combination = '3'
THOST_FTDC_ORDT_ConditionalOrder = '4'
THOST_FTDC_ORDT_Swap = '5'
THOST_FTDC_TC_IOC = '1'
THOST_FTDC_TC_GFS = '2'
THOST_FTDC_TC_GFD = '3'
THOST_FTDC_TC_GTD = '4'
THOST_FTDC_TC_GTC = '5'
THOST_FTDC_TC_GFA = '6'
THOST_FTDC_VC_AV = '1'
THOST_FTDC_VC_MV = '2'
THOST_FTDC_VC_CV = '3'
THOST_FTDC_CC_Immediately = '1'
THOST_FTDC_CC_Touch = '2'
THOST_FTDC_CC_TouchProfit = '3'
THOST_FTDC_CC_ParkedOrder = '4'
THOST_FTDC_CC_LastPriceGreaterThanStopPrice = '5'
THOST_FTDC_CC_LastPriceGreaterEqualStopPrice = '6'
THOST_FTDC_CC_LastPriceLesserThanStopPrice = '7'
THOST_FTDC_CC_LastPriceLesserEqualStopPrice = '8'
THOST_FTDC_CC_AskPriceGreaterThanStopPrice = '9'
THOST_FTDC_CC_AskPriceGreaterEqualStopPrice = 'A'
THOST_FTDC_CC_AskPriceLesserThanStopPrice = 'B'
THOST_FTDC_CC_AskPriceLesserEqualStopPrice = 'C'
THOST_FTDC_CC_BidPriceGreaterThanStopPrice = 'D'
THOST_FTDC_CC_BidPriceGreaterEqualStopPrice = 'E'
THOST_FTDC_CC_BidPriceLesserThanStopPrice = 'F'
THOST_FTDC_CC_BidPriceLesserEqualStopPrice = 'H'
THOST_FTDC_AF_Delete = '0'
THOST_FTDC_AF_Modify = '3'
THOST_FTDC_TR_Allow = '0'
THOST_FTDC_TR_CloseOnly = '1'
THOST_FTDC_TR_Forbidden = '2'
THOST_FTDC_OSRC_Participant = '0'
THOST_FTDC_OSRC_Administrator = '1'
THOST_FTDC_TRDT_SplitCombination = '#'
THOST_FTDC_TRDT_Common = '0'
THOST_FTDC_TRDT_OptionsExecution = '1'
THOST_FTDC_TRDT_OTC = '2'
THOST_FTDC_TRDT_EFPDerived = '3'
THOST_FTDC_TRDT_CombinationDerived = '4'
THOST_FTDC_PSRC_LastPrice = '0'
THOST_FTDC_PSRC_Buy = '1'
THOST_FTDC_PSRC_Sell = '2'
THOST_FTDC_IS_BeforeTrading = '0'
THOST_FTDC_IS_NoTrading = '1'
THOST_FTDC_IS_Continous = '2'
THOST_FTDC_IS_AuctionOrdering = '3'
THOST_FTDC_IS_AuctionBalance = '4'
THOST_FTDC_IS_AuctionMatch = '5'
THOST_FTDC_IS_Closed = '6'
THOST_FTDC_IER_Automatic = '1'
THOST_FTDC_IER_Manual = '2'
THOST_FTDC_IER_Fuse = '3'
THOST_FTDC_BS_NoUpload = '1'
THOST_FTDC_BS_Uploaded = '2'
THOST_FTDC_BS_Failed = '3'
THOST_FTDC_RS_All = '1'
THOST_FTDC_RS_ByProduct = '2'
THOST_FTDC_RP_ByVolume = '1'
THOST_FTDC_RP_ByFeeOnHand = '2'
THOST_FTDC_RL_Level1 = '1'
THOST_FTDC_RL_Level2 = '2'
THOST_FTDC_RL_Level3 = '3'
THOST_FTDC_RL_Level4 = '4'
THOST_FTDC_RL_Level5 = '5'
THOST_FTDC_RL_Level6 = '6'
THOST_FTDC_RL_Level7 = '7'
THOST_FTDC_RL_Level8 = '8'
THOST_FTDC_RL_Level9 = '9'
THOST_FTDC_RSD_ByPeriod = '1'
THOST_FTDC_RSD_ByStandard = '2'
THOST_FTDC_MT_Out = '0'
THOST_FTDC_MT_In = '1'
THOST_FTDC_ISPI_MortgageRatio = '4'
THOST_FTDC_ISPI_MarginWay = '5'
THOST_FTDC_ISPI_BillDeposit = '9'
THOST_FTDC_ESPI_MortgageRatio = '1'
THOST_FTDC_ESPI_OtherFundItem = '2'
THOST_FTDC_ESPI_OtherFundImport = '3'
THOST_FTDC_ESPI_CFFEXMinPrepa = '6'
THOST_FTDC_ESPI_CZCESettlementType = '7'
THOST_FTDC_ESPI_ExchDelivFeeMode = '9'
THOST_FTDC_ESPI_DelivFeeMode = '0'
THOST_FTDC_ESPI_CZCEComMarginType = 'A'
THOST_FTDC_ESPI_DceComMarginType = 'B'
THOST_FTDC_ESPI_OptOutDisCountRate = 'a'
THOST_FTDC_ESPI_OptMiniGuarantee = 'b'
THOST_FTDC_SPI_InvestorIDMinLength = '1'
THOST_FTDC_SPI_AccountIDMinLength = '2'
THOST_FTDC_SPI_UserRightLogon = '3'
THOST_FTDC_SPI_SettlementBillTrade = '4'
THOST_FTDC_SPI_TradingCode = '5'
THOST_FTDC_SPI_CheckFund = '6'
THOST_FTDC_SPI_CommModelRight = '7'
THOST_FTDC_SPI_MarginModelRight = '9'
THOST_FTDC_SPI_IsStandardActive = '8'
THOST_FTDC_SPI_UploadSettlementFile = 'U'
THOST_FTDC_SPI_DownloadCSRCFile = 'D'
THOST_FTDC_SPI_SettlementBillFile = 'S'
THOST_FTDC_SPI_CSRCOthersFile = 'C'
THOST_FTDC_SPI_InvestorPhoto = 'P'
THOST_FTDC_SPI_CSRCData = 'R'
THOST_FTDC_SPI_InvestorPwdModel = 'I'
THOST_FTDC_SPI_CFFEXInvestorSettleFile = 'F'
THOST_FTDC_SPI_InvestorIDType = 'a'
THOST_FTDC_SPI_FreezeMaxReMain = 'r'
THOST_FTDC_SPI_IsSync = 'A'
THOST_FTDC_SPI_RelieveOpenLimit = 'O'
THOST_FTDC_SPI_IsStandardFreeze = 'X'
THOST_FTDC_SPI_CZCENormalProductHedge = 'B'
THOST_FTDC_TPID_EncryptionStandard = 'E'
THOST_FTDC_TPID_RiskMode = 'R'
THOST_FTDC_TPID_RiskModeGlobal = 'G'
THOST_FTDC_TPID_modeEncode = 'P'
THOST_FTDC_TPID_tickMode = 'T'
THOST_FTDC_TPID_SingleUserSessionMaxNum = 'S'
THOST_FTDC_TPID_LoginFailMaxNum = 'L'
THOST_FTDC_TPID_IsAuthForce = 'A'
THOST_FTDC_TPID_IsPosiFreeze = 'F'
THOST_FTDC_TPID_IsPosiLimit = 'M'
THOST_FTDC_TPID_ForQuoteTimeInterval = 'Q'
THOST_FTDC_TPID_IsFuturePosiLimit = 'B'
THOST_FTDC_TPID_IsFutureOrderFreq = 'C'
THOST_FTDC_TPID_IsExecOrderProfit = 'H'
THOST_FTDC_FI_SettlementFund = 'F'
THOST_FTDC_FI_Trade = 'T'
THOST_FTDC_FI_InvestorPosition = 'P'
THOST_FTDC_FI_SubEntryFund = 'O'
THOST_FTDC_FI_CZCECombinationPos = 'C'
THOST_FTDC_FI_CSRCData = 'R'
THOST_FTDC_FI_CZCEClose = 'L'
THOST_FTDC_FI_CZCENoClose = 'N'
THOST_FTDC_FI_PositionDtl = 'D'
THOST_FTDC_FI_OptionStrike = 'S'
THOST_FTDC_FI_SettlementPriceComparison = 'M'
THOST_FTDC_FI_NonTradePosChange = 'B'
THOST_FTDC_FUT_Settlement = '0'
THOST_FTDC_FUT_Check = '1'
THOST_FTDC_FFT_Txt = '0'
THOST_FTDC_FFT_Zip = '1'
THOST_FTDC_FFT_DBF = '2'
THOST_FTDC_FUS_SucceedUpload = '1'
THOST_FTDC_FUS_FailedUpload = '2'
THOST_FTDC_FUS_SucceedLoad = '3'
THOST_FTDC_FUS_PartSucceedLoad = '4'
THOST_FTDC_FUS_FailedLoad = '5'
THOST_FTDC_TD_Out = '0'
THOST_FTDC_TD_In = '1'
THOST_FTDC_SC_NoSpecialRule = '0'
THOST_FTDC_SC_NoSpringFestival = '1'
THOST_FTDC_IPT_LastSettlement = '1'
THOST_FTDC_IPT_LaseClose = '2'
THOST_FTDC_PLP_Active = '1'
THOST_FTDC_PLP_NonActive = '2'
THOST_FTDC_PLP_Canceled = '3'
THOST_FTDC_DM_CashDeliv = '1'
THOST_FTDC_DM_CommodityDeliv = '2'
THOST_FTDC_FIOT_FundIO = '1'
THOST_FTDC_FIOT_Transfer = '2'
THOST_FTDC_FIOT_SwapCurrency = '3'
THOST_FTDC_FT_Deposite = '1'
THOST_FTDC_FT_ItemFund = '2'
THOST_FTDC_FT_Company = '3'
THOST_FTDC_FT_InnerTransfer = '4'
THOST_FTDC_FD_In = '1'
THOST_FTDC_FD_Out = '2'
THOST_FTDC_FS_Record = '1'
THOST_FTDC_FS_Check = '2'
THOST_FTDC_FS_Charge = '3'
THOST_FTDC_PS_None = '1'
THOST_FTDC_PS_Publishing = '2'
THOST_FTDC_PS_Published = '3'
THOST_FTDC_ES_NonActive = '1'
THOST_FTDC_ES_Startup = '2'
THOST_FTDC_ES_Initialize = '3'
THOST_FTDC_ES_Initialized = '4'
THOST_FTDC_ES_Close = '5'
THOST_FTDC_ES_Closed = '6'
THOST_FTDC_ES_Settlement = '7'
THOST_FTDC_STS_Initialize = '0'
THOST_FTDC_STS_Settlementing = '1'
THOST_FTDC_STS_Settlemented = '2'
THOST_FTDC_STS_Finished = '3'
THOST_FTDC_CT_Person = '0'
THOST_FTDC_CT_Company = '1'
THOST_FTDC_CT_Fund = '2'
THOST_FTDC_CT_SpecialOrgan = '3'
THOST_FTDC_CT_Asset = '4'
THOST_FTDC_BT_Trade = '0'
THOST_FTDC_BT_TradeSettle = '1'
THOST_FTDC_FAS_Low = '1'
THOST_FTDC_FAS_Normal = '2'
THOST_FTDC_FAS_Focus = '3'
THOST_FTDC_FAS_Risk = '4'
THOST_FTDC_FAS_ByTrade = '1'
THOST_FTDC_FAS_ByDeliv = '2'
THOST_FTDC_FAS_None = '3'
THOST_FTDC_FAS_FixFee = '4'
THOST_FTDC_PWDT_Trade = '1'
THOST_FTDC_PWDT_Account = '2'
THOST_FTDC_AG_All = '1'
THOST_FTDC_AG_OnlyLost = '2'
THOST_FTDC_AG_OnlyGain = '3'
THOST_FTDC_AG_None = '4'
THOST_FTDC_ICP_Include = '0'
THOST_FTDC_ICP_NotInclude = '2'
THOST_FTDC_AWT_Enable = '0'
THOST_FTDC_AWT_Disable = '2'
THOST_FTDC_AWT_NoHoldEnable = '3'
THOST_FTDC_FPWD_UnCheck = '0'
THOST_FTDC_FPWD_Check = '1'
THOST_FTDC_TT_BankToFuture = '0'
THOST_FTDC_TT_FutureToBank = '1'
THOST_FTDC_TVF_Invalid = '0'
THOST_FTDC_TVF_Valid = '1'
THOST_FTDC_TVF_Reverse = '2'
THOST_FTDC_RN_CD = '0'
THOST_FTDC_RN_ZT = '1'
THOST_FTDC_RN_QT = '2'
THOST_FTDC_SEX_None = '0'
THOST_FTDC_SEX_Man = '1'
THOST_FTDC_SEX_Woman = '2'
THOST_FTDC_UT_Investor = '0'
THOST_FTDC_UT_Operator = '1'
THOST_FTDC_UT_SuperUser = '2'
THOST_FTDC_RATETYPE_MarginRate = '2'
THOST_FTDC_NOTETYPE_TradeSettleBill = '1'
THOST_FTDC_NOTETYPE_TradeSettleMonth = '2'
THOST_FTDC_NOTETYPE_CallMarginNotes = '3'
THOST_FTDC_NOTETYPE_ForceCloseNotes = '4'
THOST_FTDC_NOTETYPE_TradeNotes = '5'
THOST_FTDC_NOTETYPE_DelivNotes = '6'
THOST_FTDC_SBS_Day = '1'
THOST_FTDC_SBS_Volume = '2'
THOST_FTDC_ST_Day = '0'
THOST_FTDC_ST_Month = '1'
THOST_FTDC_URT_Logon = '1'
THOST_FTDC_URT_Transfer = '2'
THOST_FTDC_URT_EMail = '3'
THOST_FTDC_URT_Fax = '4'
THOST_FTDC_URT_ConditionOrder = '5'
THOST_FTDC_MPT_PreSettlementPrice = '1'
THOST_FTDC_MPT_SettlementPrice = '2'
THOST_FTDC_MPT_AveragePrice = '3'
THOST_FTDC_MPT_OpenPrice = '4'
THOST_FTDC_BGS_None = '0'
THOST_FTDC_BGS_NoGenerated = '1'
THOST_FTDC_BGS_Generated = '2'
THOST_FTDC_AT_HandlePositionAlgo = '1'
THOST_FTDC_AT_FindMarginRateAlgo = '2'
THOST_FTDC_HPA_Base = '1'
THOST_FTDC_HPA_DCE = '2'
THOST_FTDC_HPA_CZCE = '3'
THOST_FTDC_FMRA_Base = '1'
THOST_FTDC_FMRA_DCE = '2'
THOST_FTDC_FMRA_CZCE = '3'
THOST_FTDC_HTAA_Base = '1'
THOST_FTDC_HTAA_DCE = '2'
THOST_FTDC_HTAA_CZCE = '3'
THOST_FTDC_PST_Order = '1'
THOST_FTDC_PST_Open = '2'
THOST_FTDC_PST_Fund = '3'
THOST_FTDC_PST_Settlement = '4'
THOST_FTDC_PST_Company = '5'
THOST_FTDC_PST_Corporation = '6'
THOST_FTDC_PST_LinkMan = '7'
THOST_FTDC_PST_Ledger = '8'
THOST_FTDC_PST_Trustee = '9'
THOST_FTDC_PST_TrusteeCorporation = 'A'
THOST_FTDC_PST_TrusteeOpen = 'B'
THOST_FTDC_PST_TrusteeContact = 'C'
THOST_FTDC_PST_ForeignerRefer = 'D'
THOST_FTDC_PST_CorporationRefer = 'E'
THOST_FTDC_QIR_All = '1'
THOST_FTDC_QIR_Group = '2'
THOST_FTDC_QIR_Single = '3'
THOST_FTDC_IRS_Normal = '1'
THOST_FTDC_IRS_Warn = '2'
THOST_FTDC_IRS_Call = '3'
THOST_FTDC_IRS_Force = '4'
THOST_FTDC_IRS_Exception = '5'
THOST_FTDC_UET_Login = '1'
THOST_FTDC_UET_Logout = '2'
THOST_FTDC_UET_Trading = '3'
THOST_FTDC_UET_TradingError = '4'
THOST_FTDC_UET_UpdatePassword = '5'
THOST_FTDC_UET_Authenticate = '6'
THOST_FTDC_UET_Other = '9'
THOST_FTDC_ICS_Close = '0'
THOST_FTDC_ICS_CloseToday = '1'
THOST_FTDC_SM_Non = '0'
THOST_FTDC_SM_Instrument = '1'
THOST_FTDC_SM_Product = '2'
THOST_FTDC_SM_Investor = '3'
THOST_FTDC_PAOS_NotSend = '1'
THOST_FTDC_PAOS_Send = '2'
THOST_FTDC_PAOS_Deleted = '3'
THOST_FTDC_VDS_Dealing = '1'
THOST_FTDC_VDS_DeaclSucceed = '2'
THOST_FTDC_ORGS_Standard = '0'
THOST_FTDC_ORGS_ESunny = '1'
THOST_FTDC_ORGS_KingStarV6 = '2'
THOST_FTDC_VTS_NaturalDeal = '0'
THOST_FTDC_VTS_SucceedEnd = '1'
THOST_FTDC_VTS_FailedEND = '2'
THOST_FTDC_VTS_Exception = '3'
THOST_FTDC_VTS_ManualDeal = '4'
THOST_FTDC_VTS_MesException = '5'
THOST_FTDC_VTS_SysException = '6'
THOST_FTDC_VBAT_BankBook = '1'
THOST_FTDC_VBAT_BankCard = '2'
THOST_FTDC_VBAT_CreditCard = '3'
THOST_FTDC_VMS_Natural = '0'
THOST_FTDC_VMS_Canceled = '9'
THOST_FTDC_VAA_NoAvailAbility = '0'
THOST_FTDC_VAA_AvailAbility = '1'
THOST_FTDC_VAA_Repeal = '2'
THOST_FTDC_VTC_BankBankToFuture = '102001'
THOST_FTDC_VTC_BankFutureToBank = '102002'
THOST_FTDC_VTC_FutureBankToFuture = '202001'
THOST_FTDC_VTC_FutureFutureToBank = '202002'
THOST_FTDC_GEN_Program = '0'
THOST_FTDC_GEN_HandWork = '1'
THOST_FTDC_CFMMCKK_REQUEST = 'R'
THOST_FTDC_CFMMCKK_AUTO = 'A'
THOST_FTDC_CFMMCKK_MANUAL = 'M'
THOST_FTDC_CFT_IDCard = '0'
THOST_FTDC_CFT_Passport = '1'
THOST_FTDC_CFT_OfficerIDCard = '2'
THOST_FTDC_CFT_SoldierIDCard = '3'
THOST_FTDC_CFT_HomeComingCard = '4'
THOST_FTDC_CFT_HouseholdRegister = '5'
THOST_FTDC_CFT_LicenseNo = '6'
THOST_FTDC_CFT_InstitutionCodeCard = '7'
THOST_FTDC_CFT_TempLicenseNo = '8'
THOST_FTDC_CFT_NoEnterpriseLicenseNo = '9'
THOST_FTDC_CFT_OtherCard = 'x'
THOST_FTDC_CFT_SuperDepAgree = 'a'
THOST_FTDC_FBC_Others = '0'
THOST_FTDC_FBC_TransferDetails = '1'
THOST_FTDC_FBC_CustAccStatus = '2'
THOST_FTDC_FBC_AccountTradeDetails = '3'
THOST_FTDC_FBC_FutureAccountChangeInfoDetails = '4'
THOST_FTDC_FBC_CustMoneyDetail = '5'
THOST_FTDC_FBC_CustCancelAccountInfo = '6'
THOST_FTDC_FBC_CustMoneyResult = '7'
THOST_FTDC_FBC_OthersExceptionResult = '8'
THOST_FTDC_FBC_CustInterestNetMoneyDetails = '9'
THOST_FTDC_FBC_CustMoneySendAndReceiveDetails = 'a'
THOST_FTDC_FBC_CorporationMoneyTotal = 'b'
THOST_FTDC_FBC_MainbodyMoneyTotal = 'c'
THOST_FTDC_FBC_MainPartMonitorData = 'd'
THOST_FTDC_FBC_PreparationMoney = 'e'
THOST_FTDC_FBC_BankMoneyMonitorData = 'f'
THOST_FTDC_CEC_Exchange = '1'
THOST_FTDC_CEC_Cash = '2'
THOST_FTDC_YNI_Yes = '0'
THOST_FTDC_YNI_No = '1'
THOST_FTDC_BLT_CurrentMoney = '0'
THOST_FTDC_BLT_UsableMoney = '1'
THOST_FTDC_BLT_FetchableMoney = '2'
THOST_FTDC_BLT_FreezeMoney = '3'
THOST_FTDC_GD_Unknown = '0'
THOST_FTDC_GD_Male = '1'
THOST_FTDC_GD_Female = '2'
THOST_FTDC_FPF_BEN = '0'
THOST_FTDC_FPF_OUR = '1'
THOST_FTDC_FPF_SHA = '2'
THOST_FTDC_PWKT_ExchangeKey = '0'
THOST_FTDC_PWKT_PassWordKey = '1'
THOST_FTDC_PWKT_MACKey = '2'
THOST_FTDC_PWKT_MessageKey = '3'
THOST_FTDC_PWT_Query = '0'
THOST_FTDC_PWT_Fetch = '1'
THOST_FTDC_PWT_Transfer = '2'
THOST_FTDC_PWT_Trade = '3'
THOST_FTDC_EM_NoEncry = '0'
THOST_FTDC_EM_DES = '1'
THOST_FTDC_EM_3DES = '2'
THOST_FTDC_BRF_BankNotNeedRepeal = '0'
THOST_FTDC_BRF_BankWaitingRepeal = '1'
THOST_FTDC_BRF_BankBeenRepealed = '2'
THOST_FTDC_BRORF_BrokerNotNeedRepeal = '0'
THOST_FTDC_BRORF_BrokerWaitingRepeal = '1'
THOST_FTDC_BRORF_BrokerBeenRepealed = '2'
THOST_FTDC_TS_Bank = '0'
THOST_FTDC_TS_Future = '1'
THOST_FTDC_TS_Store = '2'
THOST_FTDC_LF_Yes = '0'
THOST_FTDC_LF_No = '1'
THOST_FTDC_BAS_Normal = '0'
THOST_FTDC_BAS_Freeze = '1'
THOST_FTDC_BAS_ReportLoss = '2'
THOST_FTDC_MAS_Normal = '0'
THOST_FTDC_MAS_Cancel = '1'
THOST_FTDC_MSS_Point = '0'
THOST_FTDC_MSS_PrePoint = '1'
THOST_FTDC_MSS_CancelPoint = '2'
THOST_FTDC_SYT_FutureBankTransfer = '0'
THOST_FTDC_SYT_StockBankTransfer = '1'
THOST_FTDC_SYT_TheThirdPartStore = '2'
THOST_FTDC_TEF_NormalProcessing = '0'
THOST_FTDC_TEF_Success = '1'
THOST_FTDC_TEF_Failed = '2'
THOST_FTDC_TEF_Abnormal = '3'
THOST_FTDC_TEF_ManualProcessedForException = '4'
THOST_FTDC_TEF_CommuFailedNeedManualProcess = '5'
THOST_FTDC_TEF_SysErrorNeedManualProcess = '6'
THOST_FTDC_PSS_NotProcess = '0'
THOST_FTDC_PSS_StartProcess = '1'
THOST_FTDC_PSS_Finished = '2'
THOST_FTDC_CUSTT_Person = '0'
THOST_FTDC_CUSTT_Institution = '1'
THOST_FTDC_FBTTD_FromBankToFuture = '1'
THOST_FTDC_FBTTD_FromFutureToBank = '2'
THOST_FTDC_OOD_Open = '1'
THOST_FTDC_OOD_Destroy = '0'
THOST_FTDC_AVAF_Invalid = '0'
THOST_FTDC_AVAF_Valid = '1'
THOST_FTDC_AVAF_Repeal = '2'
THOST_FTDC_OT_Bank = '1'
THOST_FTDC_OT_Future = '2'
THOST_FTDC_OT_PlateForm = '9'
THOST_FTDC_OL_HeadQuarters = '1'
THOST_FTDC_OL_Branch = '2'
THOST_FTDC_PID_FutureProtocal = '0'
THOST_FTDC_PID_ICBCProtocal = '1'
THOST_FTDC_PID_ABCProtocal = '2'
THOST_FTDC_PID_CBCProtocal = '3'
THOST_FTDC_PID_CCBProtocal = '4'
THOST_FTDC_PID_BOCOMProtocal = '5'
THOST_FTDC_PID_FBTPlateFormProtocal = 'X'
THOST_FTDC_CM_ShortConnect = '0'
THOST_FTDC_CM_LongConnect = '1'
THOST_FTDC_SRM_ASync = '0'
THOST_FTDC_SRM_Sync = '1'
THOST_FTDC_BAT_BankBook = '1'
THOST_FTDC_BAT_SavingCard = '2'
THOST_FTDC_BAT_CreditCard = '3'
THOST_FTDC_FAT_BankBook = '1'
THOST_FTDC_FAT_SavingCard = '2'
THOST_FTDC_FAT_CreditCard = '3'
THOST_FTDC_OS_Ready = '0'
THOST_FTDC_OS_CheckIn = '1'
THOST_FTDC_OS_CheckOut = '2'
THOST_FTDC_OS_CheckFileArrived = '3'
THOST_FTDC_OS_CheckDetail = '4'
THOST_FTDC_OS_DayEndClean = '5'
THOST_FTDC_OS_Invalid = '9'
THOST_FTDC_CCBFM_ByAmount = '1'
THOST_FTDC_CCBFM_ByMonth = '2'
THOST_FTDC_CAPIT_Client = '1'
THOST_FTDC_CAPIT_Server = '2'
THOST_FTDC_CAPIT_UserApi = '3'
THOST_FTDC_LS_Connected = '1'
THOST_FTDC_LS_Disconnected = '2'
THOST_FTDC_BPWDF_NoCheck = '0'
THOST_FTDC_BPWDF_BlankCheck = '1'
THOST_FTDC_BPWDF_EncryptCheck = '2'
THOST_FTDC_SAT_AccountID = '1'
THOST_FTDC_SAT_CardID = '2'
THOST_FTDC_SAT_SHStockholderID = '3'
THOST_FTDC_SAT_SZStockholderID = '4'
THOST_FTDC_TRFS_Normal = '0'
THOST_FTDC_TRFS_Repealed = '1'
THOST_FTDC_SPTYPE_Broker = '0'
THOST_FTDC_SPTYPE_Bank = '1'
THOST_FTDC_REQRSP_Request = '0'
THOST_FTDC_REQRSP_Response = '1'
THOST_FTDC_FBTUET_SignIn = '0'
THOST_FTDC_FBTUET_FromBankToFuture = '1'
THOST_FTDC_FBTUET_FromFutureToBank = '2'
THOST_FTDC_FBTUET_OpenAccount = '3'
THOST_FTDC_FBTUET_CancelAccount = '4'
THOST_FTDC_FBTUET_ChangeAccount = '5'
THOST_FTDC_FBTUET_RepealFromBankToFuture = '6'
THOST_FTDC_FBTUET_RepealFromFutureToBank = '7'
THOST_FTDC_FBTUET_QueryBankAccount = '8'
THOST_FTDC_FBTUET_QueryFutureAccount = '9'
THOST_FTDC_FBTUET_SignOut = 'A'
THOST_FTDC_FBTUET_SyncKey = 'B'
THOST_FTDC_FBTUET_ReserveOpenAccount = 'C'
THOST_FTDC_FBTUET_CancelReserveOpenAccount = 'D'
THOST_FTDC_FBTUET_ReserveOpenAccountConfirm = 'E'
THOST_FTDC_FBTUET_Other = 'Z'
THOST_FTDC_DBOP_Insert = '0'
THOST_FTDC_DBOP_Update = '1'
THOST_FTDC_DBOP_Delete = '2'
THOST_FTDC_SYNF_Yes = '0'
THOST_FTDC_SYNF_No = '1'
THOST_FTDC_SYNT_OneOffSync = '0'
THOST_FTDC_SYNT_TimerSync = '1'
THOST_FTDC_SYNT_TimerFullSync = '2'
THOST_FTDC_FBEDIR_Settlement = '0'
THOST_FTDC_FBEDIR_Sale = '1'
THOST_FTDC_FBERES_Success = '0'
THOST_FTDC_FBERES_InsufficientBalance = '1'
THOST_FTDC_FBERES_UnknownTrading = '8'
THOST_FTDC_FBERES_Fail = 'x'
THOST_FTDC_FBEES_Normal = '0'
THOST_FTDC_FBEES_ReExchange = '1'
THOST_FTDC_FBEFG_DataPackage = '0'
THOST_FTDC_FBEFG_File = '1'
THOST_FTDC_FBEAT_NotTrade = '0'
THOST_FTDC_FBEAT_Trade = '1'
THOST_FTDC_FBEUET_SignIn = '0'
THOST_FTDC_FBEUET_Exchange = '1'
THOST_FTDC_FBEUET_ReExchange = '2'
THOST_FTDC_FBEUET_QueryBankAccount = '3'
THOST_FTDC_FBEUET_QueryExchDetial = '4'
THOST_FTDC_FBEUET_QueryExchSummary = '5'
THOST_FTDC_FBEUET_QueryExchRate = '6'
THOST_FTDC_FBEUET_CheckBankAccount = '7'
THOST_FTDC_FBEUET_SignOut = '8'
THOST_FTDC_FBEUET_Other = 'Z'
THOST_FTDC_FBERF_UnProcessed = '0'
THOST_FTDC_FBERF_WaitSend = '1'
THOST_FTDC_FBERF_SendSuccess = '2'
THOST_FTDC_FBERF_SendFailed = '3'
THOST_FTDC_FBERF_WaitReSend = '4'
THOST_FTDC_NC_NOERROR = '0'
THOST_FTDC_NC_Warn = '1'
THOST_FTDC_NC_Call = '2'
THOST_FTDC_NC_Force = '3'
THOST_FTDC_NC_CHUANCANG = '4'
THOST_FTDC_NC_Exception = '5'
THOST_FTDC_FCT_Manual = '0'
THOST_FTDC_FCT_Single = '1'
THOST_FTDC_FCT_Group = '2'
THOST_FTDC_RNM_System = '0'
THOST_FTDC_RNM_SMS = '1'
THOST_FTDC_RNM_EMail = '2'
THOST_FTDC_RNM_Manual = '3'
THOST_FTDC_RNS_NotGen = '0'
THOST_FTDC_RNS_Generated = '1'
THOST_FTDC_RNS_SendError = '2'
THOST_FTDC_RNS_SendOk = '3'
THOST_FTDC_RNS_Received = '4'
THOST_FTDC_RNS_Confirmed = '5'
THOST_FTDC_RUE_ExportData = '0'
THOST_FTDC_COST_LastPriceAsc = '0'
THOST_FTDC_COST_LastPriceDesc = '1'
THOST_FTDC_COST_AskPriceAsc = '2'
THOST_FTDC_COST_AskPriceDesc = '3'
THOST_FTDC_COST_BidPriceAsc = '4'
THOST_FTDC_COST_BidPriceDesc = '5'
THOST_FTDC_UOAST_NoSend = '0'
THOST_FTDC_UOAST_Sended = '1'
THOST_FTDC_UOAST_Generated = '2'
THOST_FTDC_UOAST_SendFail = '3'
THOST_FTDC_UOAST_Success = '4'
THOST_FTDC_UOAST_Fail = '5'
THOST_FTDC_UOAST_Cancel = '6'
THOST_FTDC_UOACS_NoApply = '1'
THOST_FTDC_UOACS_Submited = '2'
THOST_FTDC_UOACS_Sended = '3'
THOST_FTDC_UOACS_Success = '4'
THOST_FTDC_UOACS_Refuse = '5'
THOST_FTDC_UOACS_Cancel = '6'
THOST_FTDC_QT_Radio = '1'
THOST_FTDC_QT_Option = '2'
THOST_FTDC_QT_Blank = '3'
THOST_FTDC_BT_Request = '1'
THOST_FTDC_BT_Response = '2'
THOST_FTDC_BT_Notice = '3'
THOST_FTDC_CRC_Success = '0'
THOST_FTDC_CRC_Working = '1'
THOST_FTDC_CRC_InfoFail = '2'
THOST_FTDC_CRC_IDCardFail = '3'
THOST_FTDC_CRC_OtherFail = '4'
THOST_FTDC_CfMMCCT_All = '0'
THOST_FTDC_CfMMCCT_Person = '1'
THOST_FTDC_CfMMCCT_Company = '2'
THOST_FTDC_CfMMCCT_Other = '3'
THOST_FTDC_CfMMCCT_SpecialOrgan = '4'
THOST_FTDC_CfMMCCT_Asset = '5'
THOST_FTDC_EIDT_SHFE = 'S'
THOST_FTDC_EIDT_CZCE = 'Z'
THOST_FTDC_EIDT_DCE = 'D'
THOST_FTDC_EIDT_CFFEX = 'J'
THOST_FTDC_EIDT_INE = 'N'
THOST_FTDC_ECIDT_Hedge = '1'
THOST_FTDC_ECIDT_Arbitrage = '2'
THOST_FTDC_ECIDT_Speculation = '3'
THOST_FTDC_UF_NoUpdate = '0'
THOST_FTDC_UF_Success = '1'
THOST_FTDC_UF_Fail = '2'
THOST_FTDC_UF_TCSuccess = '3'
THOST_FTDC_UF_TCFail = '4'
THOST_FTDC_UF_Cancel = '5'
THOST_FTDC_AOID_OpenInvestor = '1'
THOST_FTDC_AOID_ModifyIDCard = '2'
THOST_FTDC_AOID_ModifyNoIDCard = '3'
THOST_FTDC_AOID_ApplyTradingCode = '4'
THOST_FTDC_AOID_CancelTradingCode = '5'
THOST_FTDC_AOID_CancelInvestor = '6'
THOST_FTDC_AOID_FreezeAccount = '8'
THOST_FTDC_AOID_ActiveFreezeAccount = '9'
THOST_FTDC_ASID_NoComplete = '1'
THOST_FTDC_ASID_Submited = '2'
THOST_FTDC_ASID_Checked = '3'
THOST_FTDC_ASID_Refused = '4'
THOST_FTDC_ASID_Deleted = '5'
THOST_FTDC_UOASM_ByAPI = '1'
THOST_FTDC_UOASM_ByFile = '2'
THOST_FTDC_EvM_ADD = '1'
THOST_FTDC_EvM_UPDATE = '2'
THOST_FTDC_EvM_DELETE = '3'
THOST_FTDC_EvM_CHECK = '4'
THOST_FTDC_EvM_COPY = '5'
THOST_FTDC_EvM_CANCEL = '6'
THOST_FTDC_EvM_Reverse = '7'
THOST_FTDC_UOAA_ASR = '1'
THOST_FTDC_UOAA_ASNR = '2'
THOST_FTDC_UOAA_NSAR = '3'
THOST_FTDC_UOAA_NSR = '4'
THOST_FTDC_EvM_InvestorGroupFlow = '1'
THOST_FTDC_EvM_InvestorRate = '2'
THOST_FTDC_EvM_InvestorCommRateModel = '3'
THOST_FTDC_CL_Zero = '0'
THOST_FTDC_CL_One = '1'
THOST_FTDC_CL_Two = '2'
THOST_FTDC_CHS_Init = '0'
THOST_FTDC_CHS_Checking = '1'
THOST_FTDC_CHS_Checked = '2'
THOST_FTDC_CHS_Refuse = '3'
THOST_FTDC_CHS_Cancel = '4'
THOST_FTDC_CHU_Unused = '0'
THOST_FTDC_CHU_Used = '1'
THOST_FTDC_CHU_Fail = '2'
THOST_FTDC_BAO_ByAccProperty = '0'
THOST_FTDC_BAO_ByFBTransfer = '1'
THOST_FTDC_MBTS_ByInstrument = '0'
THOST_FTDC_MBTS_ByDayInsPrc = '1'
THOST_FTDC_MBTS_ByDayIns = '2'
THOST_FTDC_FTC_BankLaunchBankToBroker = '102001'
THOST_FTDC_FTC_BrokerLaunchBankToBroker = '202001'
THOST_FTDC_FTC_BankLaunchBrokerToBank = '102002'
THOST_FTDC_FTC_BrokerLaunchBrokerToBank = '202002'
THOST_FTDC_OTP_NONE = '0'
THOST_FTDC_OTP_TOTP = '1'
THOST_FTDC_OTPS_Unused = '0'
THOST_FTDC_OTPS_Used = '1'
THOST_FTDC_OTPS_Disuse = '2'
THOST_FTDC_BUT_Investor = '1'
THOST_FTDC_BUT_BrokerUser = '2'
THOST_FTDC_FUTT_Commodity = '1'
THOST_FTDC_FUTT_Financial = '2'
THOST_FTDC_FET_Restriction = '0'
THOST_FTDC_FET_TodayRestriction = '1'
THOST_FTDC_FET_Transfer = '2'
THOST_FTDC_FET_Credit = '3'
THOST_FTDC_FET_InvestorWithdrawAlm = '4'
THOST_FTDC_FET_BankRestriction = '5'
THOST_FTDC_FET_Accountregister = '6'
THOST_FTDC_FET_ExchangeFundIO = '7'
THOST_FTDC_FET_InvestorFundIO = '8'
THOST_FTDC_AST_FBTransfer = '0'
THOST_FTDC_AST_ManualEntry = '1'
THOST_FTDC_CST_UnifyAccount = '0'
THOST_FTDC_CST_ManualEntry = '1'
THOST_FTDC_UR_All = '0'
THOST_FTDC_UR_Single = '1'
THOST_FTDC_BG_Investor = '2'
THOST_FTDC_BG_Group = '1'
THOST_FTDC_TSSM_Instrument = '1'
THOST_FTDC_TSSM_Product = '2'
THOST_FTDC_TSSM_Exchange = '3'
THOST_FTDC_ESM_Relative = '1'
THOST_FTDC_ESM_Typical = '2'
THOST_FTDC_RIR_All = '1'
THOST_FTDC_RIR_Model = '2'
THOST_FTDC_RIR_Single = '3'
THOST_FTDC_SDS_Initialize = '0'
THOST_FTDC_SDS_Settlementing = '1'
THOST_FTDC_SDS_Settlemented = '2'
THOST_FTDC_TSRC_NORMAL = '0'
THOST_FTDC_TSRC_QUERY = '1'
THOST_FTDC_FSM_Product = '1'
THOST_FTDC_FSM_Exchange = '2'
THOST_FTDC_FSM_All = '3'
THOST_FTDC_BIR_Property = '1'
THOST_FTDC_BIR_All = '2'
THOST_FTDC_PIR_All = '1'
THOST_FTDC_PIR_Property = '2'
THOST_FTDC_PIR_Single = '3'
THOST_FTDC_FIS_NoCreate = '0'
THOST_FTDC_FIS_Created = '1'
THOST_FTDC_FIS_Failed = '2'
THOST_FTDC_FGS_FileTransmit = '0'
THOST_FTDC_FGS_FileGen = '1'
THOST_FTDC_SoM_Add = '1'
THOST_FTDC_SoM_Update = '2'
THOST_FTDC_SoM_Delete = '3'
THOST_FTDC_SoM_Copy = '4'
THOST_FTDC_SoM_AcTive = '5'
THOST_FTDC_SoM_CanCel = '6'
THOST_FTDC_SoM_ReSet = '7'
THOST_FTDC_SoT_UpdatePassword = '0'
THOST_FTDC_SoT_UserDepartment = '1'
THOST_FTDC_SoT_RoleManager = '2'
THOST_FTDC_SoT_RoleFunction = '3'
THOST_FTDC_SoT_BaseParam = '4'
THOST_FTDC_SoT_SetUserID = '5'
THOST_FTDC_SoT_SetUserRole = '6'
THOST_FTDC_SoT_UserIpRestriction = '7'
THOST_FTDC_SoT_DepartmentManager = '8'
THOST_FTDC_SoT_DepartmentCopy = '9'
THOST_FTDC_SoT_Tradingcode = 'A'
THOST_FTDC_SoT_InvestorStatus = 'B'
THOST_FTDC_SoT_InvestorAuthority = 'C'
THOST_FTDC_SoT_PropertySet = 'D'
THOST_FTDC_SoT_ReSetInvestorPasswd = 'E'
THOST_FTDC_SoT_InvestorPersonalityInfo = 'F'
THOST_FTDC_CSRCQ_Current = '0'
THOST_FTDC_CSRCQ_History = '1'
THOST_FTDC_FRS_Normal = '1'
THOST_FTDC_FRS_Freeze = '0'
THOST_FTDC_STST_Standard = '0'
THOST_FTDC_STST_NonStandard = '1'
THOST_FTDC_RPT_Freeze = '1'
THOST_FTDC_RPT_FreezeActive = '2'
THOST_FTDC_RPT_OpenLimit = '3'
THOST_FTDC_RPT_RelieveOpenLimit = '4'
THOST_FTDC_AMLDS_Normal = '0'
THOST_FTDC_AMLDS_Deleted = '1'
THOST_FTDC_AMLCHS_Init = '0'
THOST_FTDC_AMLCHS_Checking = '1'
THOST_FTDC_AMLCHS_Checked = '2'
THOST_FTDC_AMLCHS_RefuseReport = '3'
THOST_FTDC_AMLDT_DrawDay = '0'
THOST_FTDC_AMLDT_TouchDay = '1'
THOST_FTDC_AMLCL_CheckLevel0 = '0'
THOST_FTDC_AMLCL_CheckLevel1 = '1'
THOST_FTDC_AMLCL_CheckLevel2 = '2'
THOST_FTDC_AMLCL_CheckLevel3 = '3'
THOST_FTDC_EFT_CSV = '0'
THOST_FTDC_EFT_EXCEL = '1'
THOST_FTDC_EFT_DBF = '2'
THOST_FTDC_SMT_Before = '1'
THOST_FTDC_SMT_Settlement = '2'
THOST_FTDC_SMT_After = '3'
THOST_FTDC_SMT_Settlemented = '4'
THOST_FTDC_SML_Must = '1'
THOST_FTDC_SML_Alarm = '2'
THOST_FTDC_SML_Prompt = '3'
THOST_FTDC_SML_Ignore = '4'
THOST_FTDC_SMG_Exhcange = '1'
THOST_FTDC_SMG_ASP = '2'
THOST_FTDC_SMG_CSRC = '3'
THOST_FTDC_LUT_Repeatable = '1'
THOST_FTDC_LUT_Unrepeatable = '2'
THOST_FTDC_DAR_Settle = '1'
THOST_FTDC_DAR_Exchange = '2'
THOST_FTDC_DAR_CSRC = '3'
THOST_FTDC_MGT_ExchMarginRate = '0'
THOST_FTDC_MGT_InstrMarginRate = '1'
THOST_FTDC_MGT_InstrMarginRateTrade = '2'
THOST_FTDC_ACT_Intraday = '1'
THOST_FTDC_ACT_Long = '2'
THOST_FTDC_MRT_Exchange = '1'
THOST_FTDC_MRT_Investor = '2'
THOST_FTDC_MRT_InvestorTrade = '3'
THOST_FTDC_BUS_UnBak = '0'
THOST_FTDC_BUS_BakUp = '1'
THOST_FTDC_BUS_BakUped = '2'
THOST_FTDC_BUS_BakFail = '3'
THOST_FTDC_SIS_UnInitialize = '0'
THOST_FTDC_SIS_Initialize = '1'
THOST_FTDC_SIS_Initialized = '2'
THOST_FTDC_SRS_NoCreate = '0'
THOST_FTDC_SRS_Create = '1'
THOST_FTDC_SRS_Created = '2'
THOST_FTDC_SRS_CreateFail = '3'
THOST_FTDC_SSS_UnSaveData = '0'
THOST_FTDC_SSS_SaveDatad = '1'
THOST_FTDC_SAS_UnArchived = '0'
THOST_FTDC_SAS_Archiving = '1'
THOST_FTDC_SAS_Archived = '2'
THOST_FTDC_SAS_ArchiveFail = '3'
THOST_FTDC_CTPT_Unkown = '0'
THOST_FTDC_CTPT_MainCenter = '1'
THOST_FTDC_CTPT_BackUp = '2'
THOST_FTDC_CDT_Normal = '0'
THOST_FTDC_CDT_SpecFirst = '1'
THOST_FTDC_MFUR_None = '0'
THOST_FTDC_MFUR_Margin = '1'
THOST_FTDC_MFUR_All = '2'
THOST_FTDC_SPT_CzceHedge = '1'
THOST_FTDC_SPT_IneForeignCurrency = '2'
THOST_FTDC_SPT_DceOpenClose = '3'
THOST_FTDC_FMT_Mortgage = '1'
THOST_FTDC_FMT_Redemption = '2'
THOST_FTDC_ASPI_BaseMargin = '1'
THOST_FTDC_ASPI_LowestInterest = '2'
THOST_FTDC_FMD_In = '1'
THOST_FTDC_FMD_Out = '2'
THOST_FTDC_BT_Profit = '0'
THOST_FTDC_BT_Loss = '1'
THOST_FTDC_BT_Other = 'Z'
THOST_FTDC_SST_Manual = '0'
THOST_FTDC_SST_Automatic = '1'
THOST_FTDC_CED_Settlement = '0'
THOST_FTDC_CED_Sale = '1'
THOST_FTDC_CSS_Entry = '1'
THOST_FTDC_CSS_Approve = '2'
THOST_FTDC_CSS_Refuse = '3'
THOST_FTDC_CSS_Revoke = '4'
THOST_FTDC_CSS_Send = '5'
THOST_FTDC_CSS_Success = '6'
THOST_FTDC_CSS_Failure = '7'
THOST_FTDC_REQF_NoSend = '0'
THOST_FTDC_REQF_SendSuccess = '1'
THOST_FTDC_REQF_SendFailed = '2'
THOST_FTDC_REQF_WaitReSend = '3'
THOST_FTDC_RESF_Success = '0'
THOST_FTDC_RESF_InsuffiCient = '1'
THOST_FTDC_RESF_UnKnown = '8'
THOST_FTDC_EXS_Before = '0'
THOST_FTDC_EXS_After = '1'
THOST_FTDC_CR_Domestic = '1'
THOST_FTDC_CR_GMT = '2'
THOST_FTDC_CR_Foreign = '3'
THOST_FTDC_HB_No = '0'
THOST_FTDC_HB_Yes = '1'
THOST_FTDC_SM_Normal = '1'
THOST_FTDC_SM_Emerge = '2'
THOST_FTDC_SM_Restore = '3'
THOST_FTDC_TPT_Full = '1'
THOST_FTDC_TPT_Increment = '2'
THOST_FTDC_TPT_BackUp = '3'
THOST_FTDC_LM_Trade = '0'
THOST_FTDC_LM_Transfer = '1'
THOST_FTDC_CPT_Instrument = '1'
THOST_FTDC_CPT_Margin = '2'
THOST_FTDC_HT_Yes = '1'
THOST_FTDC_HT_No = '0'
THOST_FTDC_AMT_Bank = '1'
THOST_FTDC_AMT_Securities = '2'
THOST_FTDC_AMT_Fund = '3'
THOST_FTDC_AMT_Insurance = '4'
THOST_FTDC_AMT_Trust = '5'
THOST_FTDC_AMT_Other = '9'
THOST_FTDC_CFIOT_FundIO = '0'
THOST_FTDC_CFIOT_SwapCurrency = '1'
THOST_FTDC_CAT_Futures = '1'
THOST_FTDC_CAT_AssetmgrFuture = '2'
THOST_FTDC_CAT_AssetmgrTrustee = '3'
THOST_FTDC_CAT_AssetmgrTransfer = '4'
THOST_FTDC_LT_Chinese = '1'
THOST_FTDC_LT_English = '2'
THOST_FTDC_AMCT_Person = '1'
THOST_FTDC_AMCT_Organ = '2'
THOST_FTDC_AMCT_SpecialOrgan = '4'
THOST_FTDC_ASST_Futures = '3'
THOST_FTDC_ASST_SpecialOrgan = '4'
THOST_FTDC_CIT_HasExch = '0'
THOST_FTDC_CIT_HasATP = '1'
THOST_FTDC_CIT_HasDiff = '2'
THOST_FTDC_DT_HandDeliv = '1'
THOST_FTDC_DT_PersonDeliv = '2'
THOST_FTDC_MMSA_NO = '0'
THOST_FTDC_MMSA_YES = '1'
THOST_FTDC_CACT_Person = '0'
THOST_FTDC_CACT_Company = '1'
THOST_FTDC_CACT_Other = '2'
THOST_FTDC_UOAAT_Futures = '1'
THOST_FTDC_UOAAT_SpecialOrgan = '2'
THOST_FTDC_DEN_Buy = '0'
THOST_FTDC_DEN_Sell = '1'
THOST_FTDC_OFEN_Open = '0'
THOST_FTDC_OFEN_Close = '1'
THOST_FTDC_OFEN_ForceClose = '2'
THOST_FTDC_OFEN_CloseToday = '3'
THOST_FTDC_OFEN_CloseYesterday = '4'
THOST_FTDC_OFEN_ForceOff = '5'
THOST_FTDC_OFEN_LocalForceClose = '6'
THOST_FTDC_HFEN_Speculation = '1'
THOST_FTDC_HFEN_Arbitrage = '2'
THOST_FTDC_HFEN_Hedge = '3'
THOST_FTDC_FIOTEN_FundIO = '1'
THOST_FTDC_FIOTEN_Transfer = '2'
THOST_FTDC_FIOTEN_SwapCurrency = '3'
THOST_FTDC_FTEN_Deposite = '1'
THOST_FTDC_FTEN_ItemFund = '2'
THOST_FTDC_FTEN_Company = '3'
THOST_FTDC_FTEN_InnerTransfer = '4'
THOST_FTDC_FDEN_In = '1'
THOST_FTDC_FDEN_Out = '2'
THOST_FTDC_FMDEN_In = '1'
THOST_FTDC_FMDEN_Out = '2'
THOST_FTDC_CP_CallOptions = '1'
THOST_FTDC_CP_PutOptions = '2'
THOST_FTDC_STM_Continental = '0'
THOST_FTDC_STM_American = '1'
THOST_FTDC_STM_Bermuda = '2'
THOST_FTDC_STT_Hedge = '0'
THOST_FTDC_STT_Match = '1'
THOST_FTDC_APPT_NotStrikeNum = '4'
THOST_FTDC_GUDS_Gen = '0'
THOST_FTDC_GUDS_Hand = '1'
THOST_FTDC_OER_NoExec = 'n'
THOST_FTDC_OER_Canceled = 'c'
THOST_FTDC_OER_OK = '0'
THOST_FTDC_OER_NoPosition = '1'
THOST_FTDC_OER_NoDeposit = '2'
THOST_FTDC_OER_NoParticipant = '3'
THOST_FTDC_OER_NoClient = '4'
THOST_FTDC_OER_NoInstrument = '6'
THOST_FTDC_OER_NoRight = '7'
THOST_FTDC_OER_InvalidVolume = '8'
THOST_FTDC_OER_NoEnoughHistoryTrade = '9'
THOST_FTDC_OER_Unknown = 'a'
THOST_FTDC_COMBT_Future = '0'
THOST_FTDC_COMBT_BUL = '1'
THOST_FTDC_COMBT_BER = '2'
THOST_FTDC_COMBT_STD = '3'
THOST_FTDC_COMBT_STG = '4'
THOST_FTDC_COMBT_PRT = '5'
THOST_FTDC_COMBT_CLD = '6'
THOST_FTDC_ORPT_PreSettlementPrice = '1'
THOST_FTDC_ORPT_OpenPrice = '4'
THOST_FTDC_BLAG_Default = '1'
THOST_FTDC_BLAG_IncludeOptValLost = '2'
THOST_FTDC_ACTP_Exec = '1'
THOST_FTDC_ACTP_Abandon = '2'
THOST_FTDC_FQST_Submitted = 'a'
THOST_FTDC_FQST_Accepted = 'b'
THOST_FTDC_FQST_Rejected = 'c'
THOST_FTDC_VM_Absolute = '0'
THOST_FTDC_VM_Ratio = '1'
THOST_FTDC_EOPF_Reserve = '0'
THOST_FTDC_EOPF_UnReserve = '1'
THOST_FTDC_EOCF_AutoClose = '0'
THOST_FTDC_EOCF_NotToClose = '1'
THOST_FTDC_PTE_Futures = '1'
THOST_FTDC_PTE_Options = '2'
THOST_FTDC_CUFN_CUFN_O = 'O'
THOST_FTDC_CUFN_CUFN_T = 'T'
THOST_FTDC_CUFN_CUFN_P = 'P'
THOST_FTDC_CUFN_CUFN_N = 'N'
THOST_FTDC_CUFN_CUFN_L = 'L'
THOST_FTDC_CUFN_CUFN_F = 'F'
THOST_FTDC_CUFN_CUFN_C = 'C'
THOST_FTDC_CUFN_CUFN_M = 'M'
THOST_FTDC_DUFN_DUFN_O = 'O'
THOST_FTDC_DUFN_DUFN_T = 'T'
THOST_FTDC_DUFN_DUFN_P = 'P'
THOST_FTDC_DUFN_DUFN_F = 'F'
THOST_FTDC_DUFN_DUFN_C = 'C'
THOST_FTDC_DUFN_DUFN_D = 'D'
THOST_FTDC_DUFN_DUFN_M = 'M'
THOST_FTDC_DUFN_DUFN_S = 'S'
THOST_FTDC_SUFN_SUFN_O = 'O'
THOST_FTDC_SUFN_SUFN_T = 'T'
THOST_FTDC_SUFN_SUFN_P = 'P'
THOST_FTDC_SUFN_SUFN_F = 'F'
THOST_FTDC_CFUFN_SUFN_T = 'T'
THOST_FTDC_CFUFN_SUFN_P = 'P'
THOST_FTDC_CFUFN_SUFN_F = 'F'
THOST_FTDC_CFUFN_SUFN_S = 'S'
THOST_FTDC_CMDR_Comb = '0'
THOST_FTDC_CMDR_UnComb = '1'
THOST_FTDC_STOV_RealValue = '1'
THOST_FTDC_STOV_ProfitValue = '2'
THOST_FTDC_STOV_RealRatio = '3'
THOST_FTDC_STOV_ProfitRatio = '4'
THOST_FTDC_ROAST_Processing = '0'
THOST_FTDC_ROAST_Cancelled = '1'
THOST_FTDC_ROAST_Opened = '2'
THOST_FTDC_ROAST_Invalid = '3'
THOST_FTDC_OSCF_CloseSelfOptionPosition = '1'
THOST_FTDC_OSCF_ReserveOptionPosition = '2'
THOST_FTDC_OSCF_SellCloseSelfFuturePosition = '3'
| 19,342 |
3,486 | <reponame>rafaelmotaalves/titan<filename>titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/indexing/IndexInformation.java
package com.thinkaurelius.titan.diskstorage.indexing;
import com.thinkaurelius.titan.graphdb.query.TitanPredicate;
/**
* An IndexInformation gives basic information on what a particular {@link IndexProvider} supports.
*
* @author <NAME> (<EMAIL>)
*/
public interface IndexInformation {
/**
* Whether the index supports executing queries with the given predicate against a key with the given information
* @param information
* @param titanPredicate
* @return
*/
public boolean supports(KeyInformation information, TitanPredicate titanPredicate);
/**
* Whether the index supports indexing a key with the given information
* @param information
* @return
*/
public boolean supports(KeyInformation information);
/**
* Adjusts the name of the key so that it is a valid field name that can be used in the index.
* Titan stores this information and will use the returned name in all interactions with the index.
* <p/>
* Note, that mapped field names (either configured on a per key basis or through a global configuration)
* are not adjusted and handed to the index verbatim.
*
* @param key
* @param information
* @return
*/
public String mapKey2Field(String key, KeyInformation information);
/**
* The features of this index
* @return
*/
public IndexFeatures getFeatures();
}
| 487 |
22,688 | <filename>modules/bridge/udp_bridge_sender_component.cc<gh_stars>1000+
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/bridge/udp_bridge_sender_component.h"
#include "modules/bridge/common/bridge_proto_serialized_buf.h"
#include "modules/bridge/common/macro.h"
#include "modules/bridge/common/util.h"
namespace apollo {
namespace bridge {
#define BRIDGE_IMPL(pb_msg) template class UDPBridgeSenderComponent<pb_msg>
using apollo::bridge::UDPBridgeSenderRemoteInfo;
using apollo::cyber::io::Session;
using apollo::localization::LocalizationEstimate;
template <typename T>
bool UDPBridgeSenderComponent<T>::Init() {
AINFO << "UDP bridge sender init, startin...";
apollo::bridge::UDPBridgeSenderRemoteInfo udp_bridge_remote;
if (!this->GetProtoConfig(&udp_bridge_remote)) {
AINFO << "load udp bridge component proto param failed";
return false;
}
remote_ip_ = udp_bridge_remote.remote_ip();
remote_port_ = udp_bridge_remote.remote_port();
proto_name_ = udp_bridge_remote.proto_name();
ADEBUG << "UDP Bridge remote ip is: " << remote_ip_;
ADEBUG << "UDP Bridge remote port is: " << remote_port_;
ADEBUG << "UDP Bridge for Proto is: " << proto_name_;
return true;
}
template <typename T>
bool UDPBridgeSenderComponent<T>::Proc(const std::shared_ptr<T> &pb_msg) {
if (remote_port_ == 0 || remote_ip_.empty()) {
AERROR << "remote info is invalid!";
return false;
}
if (pb_msg == nullptr) {
AERROR << "proto msg is not ready!";
return false;
}
struct sockaddr_in server_addr;
server_addr.sin_addr.s_addr = inet_addr(remote_ip_.c_str());
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(static_cast<uint16_t>(remote_port_));
int sock_fd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0);
int res =
connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (res < 0) {
close(sock_fd);
return false;
}
BridgeProtoSerializedBuf<T> proto_buf;
proto_buf.Serialize(pb_msg, proto_name_);
for (size_t j = 0; j < proto_buf.GetSerializedBufCount(); j++) {
ssize_t nbytes = send(sock_fd, proto_buf.GetSerializedBuf(j),
proto_buf.GetSerializedBufSize(j), 0);
if (nbytes != static_cast<ssize_t>(proto_buf.GetSerializedBufSize(j))) {
break;
}
}
close(sock_fd);
return true;
}
BRIDGE_IMPL(LocalizationEstimate);
BRIDGE_IMPL(planning::ADCTrajectory);
} // namespace bridge
} // namespace apollo
| 1,106 |
4,163 | <filename>proselint/checks/malapropisms/__init__.py<gh_stars>1000+
"""Malaproprisms."""
| 36 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.web.common.sourcemap;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
/**
* Translator of code locations, based on source maps.
* An instance of this class caches all registered source maps translations in
* both ways. Do not hold a strong reference to an instance of this class after
* it's translations are not needed any more.
*
* @author <NAME>, <NAME>
*/
final class SourceMapsTranslatorImpl implements SourceMapsTranslator {
private static final Logger LOG = Logger.getLogger(SourceMapsTranslatorImpl.class.getName());
private static final Pattern SOURCE_MAPPING_URL_PATTERN = Pattern.compile("^//[#@]\\s*sourceMappingURL\\s*=\\s*(\\S+)\\s*$"); // NOI18N
private static final DirectMapping NO_MAPPING = new DirectMapping();
private final Map<FileObject, DirectMapping> directMappings = new HashMap<>();
private final Map<FileObject, InverseMapping> inverseMappings = new HashMap<>();
public SourceMapsTranslatorImpl() {
}
@Override
public boolean registerTranslation(FileObject source, String sourceMapFileName) {
return registerTranslation(source, sourceMapFileName, null);
}
@Override
public boolean registerTranslation(FileObject source, SourceMap sourceMap) {
return registerTranslation(source, null, sourceMap);
}
boolean registerTranslation(FileObject source, String sourceMapFileName, SourceMap sm) {
DirectMapping dm = getMapping(source, sourceMapFileName, sm);
return dm != NO_MAPPING;
}
@Override
public void unregisterTranslation(FileObject source) {
DirectMapping dm;
synchronized (directMappings) {
dm = directMappings.remove(source);
}
if (dm != null && dm != NO_MAPPING) {
synchronized (inverseMappings) {
for (String src : dm.sourceMap.getSources()) {
FileObject fo = dm.parentFolder.getFileObject(src);
inverseMappings.remove(fo);
}
}
}
}
private DirectMapping getMapping(FileObject source, String sourceMapFileName, SourceMap sm) {
DirectMapping dm;
synchronized (directMappings) {
dm = directMappings.get(source);
if (dm != null) {
if (sourceMapFileName == null && sm == null) {
// return the cached one
return dm;
} else {
// load the source map
dm = null;
}
}
if (sourceMapFileName == null && sm == null) {
String lastLine = null;
try {
List<String> lines = source.asLines();
if (!lines.isEmpty()) {
lastLine = lines.get(lines.size() - 1);
}
Matcher matcher;
if (lastLine != null && (matcher = SOURCE_MAPPING_URL_PATTERN.matcher(lastLine)).matches()) {
sourceMapFileName = matcher.group(1);
} else {
dm = NO_MAPPING;
}
} catch (IOException ioex) {
dm = NO_MAPPING;
}
}
if (dm == null) {
FileObject fo;
if (sm == null) {
File sourceMapFile = new File(sourceMapFileName);
if (sourceMapFile.isAbsolute()) {
fo = FileUtil.toFileObject(FileUtil.normalizeFile(sourceMapFile));
} else {
fo = source.getParent().getFileObject(sourceMapFileName);
}
if (fo == null) {
dm = NO_MAPPING;
} else {
try {
sm = SourceMap.parse(fo.asText("UTF-8"));
} catch (IOException | IllegalArgumentException ex) {
LOG.log(Level.INFO, "Could not read source map "+fo, ex);
dm = NO_MAPPING;
}
}
}
if (sm != null) {
dm = new DirectMapping(source.getParent(), sm);
}
}
directMappings.put(source, dm);
}
if (dm != NO_MAPPING) { // we created new mapping, register the inverse
synchronized (inverseMappings) {
for (String src : dm.sourceMap.getSources()) {
FileObject fo = dm.parentFolder.getFileObject(src);
inverseMappings.put(fo, new InverseMapping(src, source, dm.sourceMap));
}
}
}
return dm;
}
/**
* Translate a location in the compiled file to the location in the source file.
* Translation is based on a source map retrieved from the compiled file.
* @param loc location in the compiled file
* @return corresponding location in the source file, or the original passed
* location if the source map is not found, or does not provide the translation.
*/
@Override
public Location getSourceLocation(Location loc) {
return getSourceLocation(loc, null);
}
/**
* Translate a location in the compiled file to the location in the source file.
* Translation is based on the provided source map.
* @param loc location in the compiled file
* @param sourceMapFileName file name of the source map file
* @return corresponding location in the source file, or the original passed
* location if the source map does not provide the translation.
*/
@Override
public Location getSourceLocation(Location loc, String sourceMapFileName) {
DirectMapping dm = getMapping(loc.getFile(), sourceMapFileName, null);
Location mloc = dm.getMappedLocation(loc.getLine(), loc.getColumn());
if (mloc != null) {
return mloc;
} else {
return loc;
}
}
/**
* Translate a location in the source file to the location in the compiled file.
* Translation is based on an inverse application of source maps already registered.
* @param loc location in the source file
* @return corresponding location in the compiled file, or the original passed
* location if no registered source map provides the appropriate translation.
*/
@Override
public Location getCompiledLocation(Location loc) {
InverseMapping im;
synchronized (inverseMappings) {
im = inverseMappings.get(loc.getFile());
}
if (im == null) {
return loc;
}
Location mloc = im.getMappedLocation(loc.getLine(), loc.getColumn());
if (mloc != null) {
return mloc;
} else {
return loc;
}
}
@Override
public List<FileObject> getSourceFiles(FileObject compiledFile) {
DirectMapping dm = getMapping(compiledFile, null, null);
if (dm.sourceMap == null) {
return null;
}
List<String> sourcePaths = dm.sourceMap.getSources();
List<FileObject> sourceFiles = new ArrayList<>(sourcePaths.size());
for (String sp : sourcePaths) {
FileObject sourceFile = Location.getSourceFile(sp, dm.parentFolder);
if (sourceFile != null) {
sourceFiles.add(sourceFile);
}
}
return sourceFiles;
}
private static class DirectMapping {
private final FileObject parentFolder;
private final SourceMap sourceMap;
DirectMapping() {
this.parentFolder = null;
this.sourceMap = null;
}
DirectMapping(FileObject parentFolder, SourceMap sourceMap) {
this.parentFolder = parentFolder;
this.sourceMap = sourceMap;
}
Location getMappedLocation(int line, int column) {
if (sourceMap == null) {
return null;
}
Mapping mapping = sourceMap.findMapping(line, column);
if (mapping == null) {
return null;
} else {
return new Location(sourceMap, mapping, parentFolder);
}
}
}
private static class InverseMapping {
private final String sourceName;
private final FileObject source;
private final SourceMap sourceMap;
private InverseMapping(String sourceName, FileObject source, SourceMap sourceMap) {
this.sourceName = sourceName;
this.source = source;
this.sourceMap = sourceMap;
}
private Location getMappedLocation(int line, int column) {
Mapping mapping = sourceMap.findInverseMapping(sourceName, line, column);
if (mapping == null) {
return null;
} else {
return new Location(source, mapping.getOriginalLine(), mapping.getOriginalColumn());
}
}
}
}
| 4,589 |
1,863 | <filename>PhysX_3.4/Source/LowLevelCloth/src/SwSolverKernel.h
//
// 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-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#pragma once
#include "IterationState.h"
#include "SwCollision.h"
#include "SwSelfCollision.h"
namespace physx
{
namespace cloth
{
class SwCloth;
struct SwClothData;
template <typename Simd4f>
class SwSolverKernel
{
public:
SwSolverKernel(SwCloth const&, SwClothData&, SwKernelAllocator&, IterationStateFactory&);
void operator()();
// returns a conservative estimate of the
// total memory requirements during a solve
static size_t estimateTemporaryMemory(const SwCloth& c);
private:
void integrateParticles();
void constrainTether();
void solveFabric();
void applyWind();
void constrainMotion();
void constrainSeparation();
void collideParticles();
void selfCollideParticles();
void updateSleepState();
void iterateCloth();
void simulateCloth();
SwCloth const& mCloth;
SwClothData& mClothData;
SwKernelAllocator& mAllocator;
SwCollision<Simd4f> mCollision;
SwSelfCollision<Simd4f> mSelfCollision;
IterationState<Simd4f> mState;
private:
SwSolverKernel<Simd4f>& operator=(const SwSolverKernel<Simd4f>&);
template <typename AccelerationIterator>
void integrateParticles(AccelerationIterator& accelIt, const Simd4f&);
};
#if PX_SUPPORT_EXTERN_TEMPLATE
//explicit template instantiation declaration
#if NV_SIMD_SIMD
extern template class SwSolverKernel<Simd4f>;
#endif
#if NV_SIMD_SCALAR
extern template class SwSolverKernel<Scalar4f>;
#endif
#endif
}
}
| 994 |
5,169 | {
"name": "Ubaguruma",
"version": "0.0.1",
"summary": "Ubaguruma can a photo select picker like LINE.",
"homepage": "https://github.com/nakajijapan/Ubaguruma",
"license": "MIT",
"authors": {
"nakajijapan": "<EMAIL>"
},
"source": {
"git": "https://github.com/nakajijapan/Ubaguruma.git",
"tag": "0.0.1"
},
"platforms": {
"ios": "11.0"
},
"requires_arc": true,
"swift_versions": [
"5.0",
"5.0"
],
"source_files": "Sources/Classes/**/*",
"resource_bundles": {
"Ubaguruma": [
"Sources/Assets/*"
]
},
"swift_version": "5.0"
}
| 283 |
312 | <reponame>patrickwyler/rdf4j<filename>core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/ShaclTestWithoutRdfsReasoner.java
/*******************************************************************************
* Copyright (c) 2021 Eclipse RDF4J contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.sail.shacl;
import org.eclipse.rdf4j.IsolationLevel;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
import org.junit.Test;
import org.junit.jupiter.api.Tag;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* When the RDFS reasoner is disabled it makes ConnectionsGroup.getRdfsSubClassOfReasoner() return null. This could lead
* to null pointer exceptions if some code assumes that it will never be null!
*
* @author <NAME>
*/
@RunWith(Parameterized.class)
@Tag("slow")
public class ShaclTestWithoutRdfsReasoner extends AbstractShaclTest {
public ShaclTestWithoutRdfsReasoner(String testCasePath, String path, ExpectedResult expectedResult,
IsolationLevel isolationLevel) {
super(testCasePath, path, expectedResult, isolationLevel);
}
@Test
public void test() {
if (ignoredTest(testCasePath)) {
return;
}
runWithAutomaticLogging(() -> runTestCase(testCasePath, path, expectedResult, isolationLevel, false));
}
@Test
public void testRevalidation() {
if (ignoredTest(testCasePath)) {
return;
}
runWithAutomaticLogging(() -> runTestCaseRevalidate(testCasePath, path, expectedResult, isolationLevel));
}
// Since we have disabled the RDFS reasoner we can't run the tests that require reasoning
private static boolean ignoredTest(String testCasePath) {
return testCasePath.contains("/subclass");
}
private void runWithAutomaticLogging(Runnable r) {
try {
r.run();
} catch (Throwable t) {
fullLogging = true;
System.out.println("\n##############################################");
System.out.println("###### Re-running test with full logging #####");
System.out.println("##############################################\n");
r.run();
} finally {
fullLogging = false;
}
}
SailRepository getShaclSail() {
ShaclSail shaclSail = new ShaclSail(new MemoryStore());
SailRepository repository = new SailRepository(shaclSail);
shaclSail.setLogValidationPlans(fullLogging);
shaclSail.setCacheSelectNodes(true);
shaclSail.setParallelValidation(false);
shaclSail.setLogValidationViolations(fullLogging);
shaclSail.setGlobalLogValidationExecution(fullLogging);
shaclSail.setEclipseRdf4jShaclExtensions(true);
shaclSail.setDashDataShapes(true);
shaclSail.setRdfsSubClassReasoning(false);
System.setProperty("org.eclipse.rdf4j.sail.shacl.experimentalSparqlValidation", "true");
repository.init();
return repository;
}
}
| 1,019 |
518 | {
"name": "Outlook Calendar",
"category": "Communication & Collaboration",
"start_url": "https://outlook.office365.com/calendar/",
"icons": [
{
"src": "https://cdn.filestackcontent.com/7XA7crEyT5awT59ziTd1",
"platform": "browserx"
}
],
"theme_color": "#0470C7",
"scope": "https://outlook.office365.com/"
}
| 146 |
1,040 | //{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by winmain.rc
//
#define IDI_MAIN_ICON 101
#define IDR_MAIN_ACCEL 113
#define IDD_CHANGEDEVICE 145
#define IDC_DEVICE_COMBO 1010
#define IDC_MODE_COMBO 1011
#define IDM_EXIT 40001
#define IDM_HELP 40012
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_3D_CONTROLS 1
#define _APS_NEXT_RESOURCE_VALUE 147
#define _APS_NEXT_COMMAND_VALUE 40015
#define _APS_NEXT_CONTROL_VALUE 1012
#define _APS_NEXT_SYMED_VALUE 114
#endif
#endif
| 415 |
1,564 | <reponame>nicktar/modelmapper
package org.modelmapper;
/**
* Simple interface for extensions that can be registered with {@link ModelMapper}
* to provide some extensions.
*
* @author <NAME>
*/
public interface Module {
/**
* Setup the ModelMapper for external functionality
*
* @param modelMapper a {@link ModelMapper} instance
*/
void setupModule(ModelMapper modelMapper);
}
| 137 |
610 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import <XCTest/XCTest.h>
NS_ASSUME_NONNULL_BEGIN
@interface FBNotificationsHelper : NSObject
/**
Creates an expectation that is fulfilled when an expected NSNotification is received
@param name The name of the awaited notification
@param timeout The maximum amount of float seconds to wait for the expectation
@return The appropriate waiter result
*/
+ (XCTWaiterResult)waitForNotificationWithName:(NSNotificationName)name
timeout:(NSTimeInterval)timeout;
/**
Creates an expectation that is fulfilled when an expected Darwin notification is received
@param name The name of the awaited notification
@param timeout The maximum amount of float seconds to wait for the expectation
@return The appropriate waiter result
*/
+ (XCTWaiterResult)waitForDarwinNotificationWithName:(NSString *)name
timeout:(NSTimeInterval)timeout;
@end
NS_ASSUME_NONNULL_END
| 386 |
1,231 | <filename>documents/Programmierparadigmen/scripts/mpi/comm-size-example.c
#include "mpi.h"
int size;
MPI_Comm comm;
...
MPI_Comm_size(comm, &size);
... | 72 |
852 | #ifndef IIOV_H
#define IIOV_H
#include <stdexcept>
#include "OnlineDB/EcalCondDB/interface/IUniqueDBObject.h"
/**
* Abstract base class for an IOV object
*/
class IIOV : public IUniqueDBObject {};
#endif
| 79 |
908 | # -*- coding: utf-8 -*-
"""
Tests for the resurrected Py2-like 8-bit string type.
"""
from __future__ import absolute_import, unicode_literals, print_function
from numbers import Integral
from future.tests.base import unittest
from past.builtins import str as oldstr
from past.types.oldstr import unescape
class TestOldStr(unittest.TestCase):
def test_repr(self):
s1 = oldstr(b'abc')
self.assertEqual(repr(s1), "'abc'")
s2 = oldstr(b'abc\ndef')
self.assertEqual(repr(s2), "'abc\\ndef'")
def test_str(self):
s1 = oldstr(b'abc')
self.assertEqual(str(s1), 'abc')
s2 = oldstr(b'abc\ndef')
self.assertEqual(str(s2), 'abc\ndef')
def test_unescape(self):
self.assertEqual(unescape('abc\\ndef'), 'abc\ndef')
s = unescape(r'a\\b\c\\d') # i.e. 'a\\\\b\\c\\\\d'
self.assertEqual(str(s), r'a\b\c\d')
s2 = unescape(r'abc\\ndef') # i.e. 'abc\\\\ndef'
self.assertEqual(str(s2), r'abc\ndef')
def test_getitem(self):
s = oldstr(b'abc')
self.assertNotEqual(s[0], 97)
self.assertEqual(s[0], b'a')
self.assertEqual(s[0], oldstr(b'a'))
self.assertEqual(s[1:], b'bc')
self.assertEqual(s[1:], oldstr(b'bc'))
if __name__ == '__main__':
unittest.main()
| 644 |
456 | <reponame>luckyframework/docsearch-configs
{
"index_name": "capacitorjs",
"start_urls": ["https://capacitorjs.com/docs"],
"stop_urls": [],
"sitemap_urls": ["https://capacitorjs.com/sitemap.xml"],
"selectors": {
"lvl0": "a.sc-docs-header.active",
"lvl1": {
"selector": "//ul[contains(@class, 'menu-list')]//li[contains(@class,'sc-docs-menu')]//a[contains(@class,'-active')]",
"type": "xpath",
"global": true
},
"lvl2": ".doc-content h1",
"lvl3": ".doc-content h2",
"lvl4": ".doc-content h3",
"lvl5": ".doc-content h4",
"lvl6": ".doc-content h5",
"text": ".doc-content p, .doc-content li"
},
"conversation_id": ["1225921234"],
"nb_hits": 1630
}
| 330 |
5,169 | {
"name": "Mattress",
"version": "1.0.2",
"license": "MIT",
"summary": "iOS Offline Caching for Web Content",
"homepage": "https://github.com/buzzfeed/mattress",
"social_media_url": "http://twitter.com/buzzfeed",
"authors": {
"<NAME>": "<EMAIL>",
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/buzzfeed/mattress.git",
"tag": "1.0.2"
},
"platforms": {
"ios": "8.0"
},
"source_files": [
"Source/*.swift",
"Source/Extensions/*.swift"
],
"preserve_paths": "CommonCrypto/*",
"xcconfig": {
"SWIFT_INCLUDE_PATHS[sdk=iphoneos*]": "$(SRCROOT)/Mattress/CommonCrypto/iphoneos",
"SWIFT_INCLUDE_PATHS[sdk=iphonesimulator*]": "$(SRCROOT)/Mattress/CommonCrypto/iphonesimulator",
"SWIFT_INCLUDE_PATHS[sdk=macosx*]": "$(SRCROOT)/Mattress/CommonCrypto/macosx"
},
"requires_arc": true
}
| 396 |
1,948 | <reponame>PyAntony/reactor-netty<gh_stars>1000+
/*
* Copyright (c) 2011-2021 VMware, 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.netty.udp;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import io.netty.channel.ChannelFuture;
import io.netty.channel.socket.DatagramChannel;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import reactor.netty.Connection;
import reactor.netty.ConnectionObserver;
import reactor.netty.FutureMono;
import reactor.netty.channel.ChannelOperations;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import static reactor.netty.ReactorNetty.format;
/**
* @author <NAME>
*/
final class UdpOperations extends ChannelOperations<UdpInbound, UdpOutbound>
implements UdpInbound, UdpOutbound {
UdpOperations(Connection c, ConnectionObserver listener) {
super(c, listener);
}
/**
* Join a multicast group.
*
* @param multicastAddress multicast address of the group to join
*
* @return a {@link Publisher} that will be complete when the group has been joined
*/
@Override
public Mono<Void> join(final InetAddress multicastAddress, @Nullable NetworkInterface iface) {
if (!(connection().channel() instanceof DatagramChannel)) {
throw new UnsupportedOperationException();
}
DatagramChannel datagramChannel = (DatagramChannel) connection().channel();
if (null == iface && null != datagramChannel.config().getNetworkInterface()) {
iface = datagramChannel.config().getNetworkInterface();
}
final ChannelFuture future;
if (null != iface) {
future = datagramChannel.joinGroup(new InetSocketAddress(multicastAddress,
datagramChannel.localAddress()
.getPort()), iface);
}
else {
future = datagramChannel.joinGroup(multicastAddress);
}
return FutureMono.from(future)
.doOnSuccess(v -> {
if (log.isInfoEnabled()) {
log.info(format(future.channel(), "JOIN {}"), multicastAddress);
}
});
}
/**
* Leave a multicast group.
*
* @param multicastAddress multicast address of the group to leave
*
* @return a {@link Publisher} that will be complete when the group has been left
*/
@Override
public Mono<Void> leave(final InetAddress multicastAddress, @Nullable NetworkInterface iface) {
if (!(connection().channel() instanceof DatagramChannel)) {
throw new UnsupportedOperationException();
}
DatagramChannel datagramChannel = (DatagramChannel) connection().channel();
if (null == iface && null != datagramChannel.config().getNetworkInterface()) {
iface = datagramChannel.config().getNetworkInterface();
}
final ChannelFuture future;
if (null != iface) {
future = datagramChannel.leaveGroup(new InetSocketAddress(multicastAddress,
datagramChannel.localAddress()
.getPort()), iface);
}
else {
future = datagramChannel.leaveGroup(multicastAddress);
}
return FutureMono.from(future)
.doOnSuccess(v -> {
if (log.isInfoEnabled()) {
log.info(format(future.channel(), "JOIN {}"), multicastAddress);
}
});
}
static final Logger log = Loggers.getLogger(UdpOperations.class);
}
| 1,399 |
21,684 | #include "rdb_protocol/artificial_table/backend.hpp"
#include <algorithm>
#include "clustering/administration/artificial_reql_cluster_interface.hpp"
#include "rdb_protocol/artificial_table/artificial_table.hpp"
#include "rdb_protocol/datum_stream.hpp"
#include "rdb_protocol/datum_stream/vector.hpp"
const uuid_u artificial_table_backend_t::base_table_id =
str_to_uuid("0eabef01-6deb-4069-9a2d-448db057ab1e");
artificial_table_backend_t::artificial_table_backend_t(
name_string_t const &table_name,
rdb_context_t *rdb_context)
: m_table_name(table_name),
m_table_id(uuid_u::from_hash(base_table_id, table_name.str())),
m_rdb_context(rdb_context) {
}
artificial_table_backend_t::~artificial_table_backend_t() {
}
uuid_u const &artificial_table_backend_t::get_table_id() const {
return m_table_id;
}
bool artificial_table_backend_t::read_all_rows_filtered(
auth::user_context_t const &user_context,
const ql::datumspec_t &datumspec,
sorting_t sorting,
signal_t *interruptor,
std::vector<ql::datum_t> *rows_out,
admin_err_t *error_out) {
/* Fetch the rows from the backend */
std::vector<ql::datum_t> rows;
if (!read_all_rows_as_vector(user_context, interruptor, &rows, error_out)) {
return false;
}
std::string primary_key = get_primary_key_name();
/* Apply range filter */
if (!datumspec.is_universe()) {
std::vector<ql::datum_t> filter_rows;
for (const auto &row : rows) {
ql::datum_t key = row.get_field(primary_key.c_str(), ql::NOTHROW);
guarantee(key.has());
for (size_t i = 0; i < datumspec.copies(key); ++i) {
filter_rows.push_back(row);
}
}
rows = std::move(filter_rows);
}
/* Apply sorting */
if (sorting != sorting_t::UNORDERED) {
/* It's OK to use `std::sort()` instead of `std::stable_sort()` here because
primary keys need to be unique. If we were to support secondary indexes on
artificial tables, we would need to ensure that `read_all_rows_as_vector()`
returns the keys in a deterministic order and then we would need to use a
`std::stable_sort()` here. */
std::sort(rows.begin(), rows.end(),
[&](const ql::datum_t &a, const ql::datum_t &b) {
ql::datum_t a_key = a.get_field(primary_key.c_str(), ql::NOTHROW);
ql::datum_t b_key = b.get_field(primary_key.c_str(), ql::NOTHROW);
guarantee(a_key.has() && b_key.has());
if (sorting == sorting_t::ASCENDING) {
return a_key < b_key;
} else {
return a_key > b_key;
}
});
}
*rows_out = std::move(rows);
return true;
}
bool artificial_table_backend_t::read_all_rows_filtered_as_stream(
auth::user_context_t const &user_context,
ql::backtrace_id_t bt,
const ql::datumspec_t &datumspec,
sorting_t sorting,
signal_t *interruptor,
counted_t<ql::datum_stream_t> *rows_out,
admin_err_t *error_out) {
std::vector<ql::datum_t> rows;
if (!read_all_rows_filtered(user_context, datumspec, sorting, interruptor,
&rows, error_out)) {
return false;
}
ql::changefeed::keyspec_t::range_t range_keyspec = {
std::vector<ql::transform_variant_t>(),
r_nullopt,
sorting,
datumspec,
r_nullopt
};
optional<ql::changefeed::keyspec_t> keyspec(ql::changefeed::keyspec_t(
std::move(range_keyspec),
counted_t<base_table_t>(
new artificial_table_t(
m_rdb_context, artificial_reql_cluster_interface_t::database_id, this)),
m_table_name.str()));
guarantee(keyspec->table.has());
*rows_out = make_counted<ql::vector_datum_stream_t>(
bt, std::move(rows), std::move(keyspec));
return true;
}
| 1,911 |
2,151 | /*
* Copyright (C) 2006, 2007, 2008, 2009, 2013 Apple Inc. All rights reserved.
* Copyright (C) 2007-2009 Torch Mobile, Inc.
* Copyright (C) 2010, 2011 Research In Motion Limited. All rights reserved.
* Copyright (C) 2013 Samsung Electronics. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_CPU_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_CPU_H_
#if defined(arm) || defined(__arm__) || defined(ARM) || defined(_ARM_)
#if !defined(__ARMEB__) && !defined(__ARM_EABI__) && !defined(__EABI__) && \
!defined(__VFP_FP__) && !defined(_WIN32_WCE) && !defined(ANDROID)
#error Chromium does not support middle endian architecture
#endif
// WTF_CPU_ARM_NEON is 0 or 1, and should not use defined(WTF_CPU_ARM_NEON).
#if defined(__ARM_NEON__) && !defined(WTF_CPU_ARM_NEON)
#define WTF_CPU_ARM_NEON 1
#endif
#endif /* ARM */
#if !defined(WTF_CPU_ARM_NEON)
#define WTF_CPU_ARM_NEON 0
#endif
// HAVE_MIPS_MSA_INTRINSICS is 0 or 1, and we should not use
// defined(HAVE_MIPS_MSA_INTRINSICS).
#if defined(__mips_msa) && defined(__mips_isa_rev) && (__mips_isa_rev >= 5)
#define HAVE_MIPS_MSA_INTRINSICS 1
#else
#define HAVE_MIPS_MSA_INTRINSICS 0
#endif
#endif /* WTF_CPU_h */
| 849 |
1,018 | /*
* Copyright 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 org.glowroot.agent;
import java.io.File;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.security.CodeSource;
import java.util.jar.JarFile;
// this class is registered as the Premain-Class in the MANIFEST.MF of glowroot.jar
//
// this class should have minimal dependencies since it will live in the system class loader while
// the rest of glowroot will live in the bootstrap class loader
public class AgentPremain {
private static final boolean PRE_CHECK_LOADED_CLASSES =
Boolean.getBoolean("glowroot.debug.preCheckLoadedClasses");
private AgentPremain() {}
// javaagent entry point
public static void premain(@SuppressWarnings("unused") String agentArgs,
Instrumentation instrumentation) {
try {
Class<?>[] allPriorLoadedClasses;
if (PRE_CHECK_LOADED_CLASSES) {
allPriorLoadedClasses = instrumentation.getAllLoadedClasses();
} else {
allPriorLoadedClasses = new Class<?>[0];
}
CodeSource codeSource = AgentPremain.class.getProtectionDomain().getCodeSource();
// suppress warnings is used instead of annotating this method with @Nullable
// just to avoid dependencies on other classes (in this case the @Nullable annotation)
@SuppressWarnings("argument.type.incompatible")
File glowrootJarFile = getGlowrootJarFile(codeSource);
Class<?> mainEntryPointClass;
if (glowrootJarFile != null) {
instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(glowrootJarFile));
}
mainEntryPointClass = Class.forName("org.glowroot.agent.MainEntryPoint", true,
AgentPremain.class.getClassLoader());
Method premainMethod = mainEntryPointClass.getMethod("premain", Instrumentation.class,
Class[].class, File.class);
premainMethod.invoke(null, instrumentation, allPriorLoadedClasses, glowrootJarFile);
} catch (Throwable t) {
// log error but don't re-throw which would prevent monitored app from starting
System.err.println("Glowroot failed to start: " + t.getMessage());
t.printStackTrace();
}
}
// suppress warnings is used instead of annotating this method with @Nullable
// just to avoid dependencies on other classes (in this case the @Nullable annotation)
@SuppressWarnings("return.type.incompatible")
static File getGlowrootJarFile(CodeSource codeSource) throws Exception {
if (codeSource == null) {
if (System.getProperty("glowroot.test.dir") != null) {
// this is ok, running tests under delegating javaagent
return null;
}
throw new IOException("Could not determine glowroot jar location");
}
File codeSourceFile = new File(codeSource.getLocation().toURI());
if (codeSourceFile.getName().endsWith(".jar")) {
return codeSourceFile;
}
if (System.getProperty("glowroot.test.dir") != null) {
// this is ok, running tests under delegating javaagent
return null;
}
throw new IOException("Could not determine glowroot jar location");
}
}
| 1,454 |
372 | /*-----------------------------------------------------------------------------
* $RCSfile: sec_genrsakey.c,v $
*
* See Copyright for the status of this software.
*
* The OpenSOAP Project
* http://opensoap.jp/
*-----------------------------------------------------------------------------
*/
#include <OpenSOAP/Security.h>
#include <openssl/rsa.h>
#include <openssl/rand.h>
#include <string.h>
#include <openssl/pem.h>
/*****************************************************************************
Function : Generate RSA Keys To Stream
Return : int
************************************************ Yuji Yamawaki 01.07.26 *****/
int
OPENSOAP_API
OpenSOAPSecGenerateRSAKeys
(const unsigned char* szSeedPhrase, /* (i) Seed phrase */
FILE* fpPrivKey, /* (i) RSA Private Key File stream */
FILE* fpPubKey) /* (i) RSA Public Key File stream */
{
int iRet = OPENSOAP_NO_ERROR;
RSA* pRsa = NULL;
/* Check Arguments */
if (!szSeedPhrase || !fpPubKey || !fpPrivKey) {
iRet = OPENSOAP_PARAMETER_BADVALUE;
goto FuncEnd;
}
/* Set Seed */
RAND_seed(szSeedPhrase, strlen(szSeedPhrase));
/* Generate Key */
pRsa = RSA_generate_key(1024, 3, NULL, NULL);
if (pRsa == NULL) {
iRet = OPENSOAP_SEC_KEYGEN_ERROR;
goto FuncEnd;
}
/* Write Public Key */
if (PEM_write_RSAPublicKey(fpPubKey, pRsa) == 0) {
iRet = OPENSOAP_IO_WRITE_ERROR;
goto FuncEnd;
}
/* Write Private Key */
if (PEM_write_RSAPrivateKey(fpPrivKey, pRsa, NULL,
NULL, 0, NULL, NULL) == 0) {
iRet = OPENSOAP_IO_WRITE_ERROR;
goto FuncEnd;
}
FuncEnd:
if (pRsa != NULL)
RSA_free(pRsa);
return iRet;
}
/*****************************************************************************
Function : Generate RSA Keys To File
Return : int
************************************************ <NAME> 01.07.26 *****/
int
OPENSOAP_API
OpenSOAPSecGenerateRSAKeysToFile
(const unsigned char* szSeedPhrase, /* (i) Seed phrase */
const char* szPrivKeyFileName, /* (i) Private Key File Name */
const char* szPubKeyFileName) /* (i) Public Key File Name */
{
int iRet = OPENSOAP_PARAMETER_BADVALUE;
FILE* fpPrivate = NULL;
FILE* fpPublic = NULL;
/* Check arguments */
if (szSeedPhrase == NULL ||
szPubKeyFileName == NULL ||
szPubKeyFileName == NULL) {
return iRet;
}
/* Open Key File */
if ((fpPrivate = fopen(szPrivKeyFileName, "w")) == NULL) {
iRet = OPENSOAP_FILEOPEN_ERROR;
goto FuncEnd;
}
if ((fpPublic = fopen(szPubKeyFileName, "w")) == NULL) {
iRet = OPENSOAP_FILEOPEN_ERROR;
goto FuncEnd;
}
/* Output */
iRet = OpenSOAPSecGenerateRSAKeys(szSeedPhrase,
fpPrivate,
fpPublic);
FuncEnd:
if (fpPrivate != NULL)
fclose(fpPrivate);
if (fpPublic != NULL)
fclose(fpPublic);
return iRet;
}
| 1,354 |
1,744 | package org.embulk.spi.util.dynamic;
import org.embulk.spi.Column;
import org.embulk.spi.PageBuilder;
public class NullDefaultValueSetter implements DefaultValueSetter {
public void setBoolean(PageBuilder pageBuilder, Column c) {
pageBuilder.setNull(c);
}
public void setLong(PageBuilder pageBuilder, Column c) {
pageBuilder.setNull(c);
}
public void setDouble(PageBuilder pageBuilder, Column c) {
pageBuilder.setNull(c);
}
public void setString(PageBuilder pageBuilder, Column c) {
pageBuilder.setNull(c);
}
public void setTimestamp(PageBuilder pageBuilder, Column c) {
pageBuilder.setNull(c);
}
public void setJson(PageBuilder pageBuilder, Column c) {
pageBuilder.setNull(c);
}
}
| 295 |
1,855 | // IFolderArchive.h
#ifndef __IFOLDER_ARCHIVE_H
#define __IFOLDER_ARCHIVE_H
#include "../../../Common/MyString.h"
#include "../../Archive/IArchive.h"
#include "../../UI/Common/LoadCodecs.h"
#include "../../UI/FileManager/IFolder.h"
#include "../Common/ExtractMode.h"
#include "../Common/IFileExtractCallback.h"
#define FOLDER_ARCHIVE_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 0x01, x)
#define FOLDER_ARCHIVE_INTERFACE(i, x) FOLDER_ARCHIVE_INTERFACE_SUB(i, IUnknown, x)
/* ---------- IArchiveFolder ----------
IArchiveFolder is implemented by CAgentFolder (Agent/Agent.h)
IArchiveFolder is used by:
- FileManager/PanelCopy.cpp
CPanel::CopyTo(), if (options->testMode)
- FAR/PluginRead.cpp
CPlugin::ExtractFiles
*/
#define INTERFACE_IArchiveFolder(x) \
STDMETHOD(Extract)(const UInt32 *indices, UInt32 numItems, \
Int32 includeAltStreams, \
Int32 replaceAltStreamCharsMode, \
NExtract::NPathMode::EEnum pathMode, \
NExtract::NOverwriteMode::EEnum overwriteMode, \
const wchar_t *path, Int32 testMode, \
IFolderArchiveExtractCallback *extractCallback2) x; \
FOLDER_ARCHIVE_INTERFACE(IArchiveFolder, 0x0D)
{
INTERFACE_IArchiveFolder(PURE)
};
/* ---------- IInFolderArchive ----------
IInFolderArchive is implemented by CAgent (Agent/Agent.h)
IInFolderArchive Is used by FAR/Plugin
*/
#define INTERFACE_IInFolderArchive(x) \
STDMETHOD(Open)(IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, BSTR *archiveTypeRes, IArchiveOpenCallback *openArchiveCallback) x; \
STDMETHOD(ReOpen)(IArchiveOpenCallback *openArchiveCallback) x; \
STDMETHOD(Close)() x; \
STDMETHOD(GetNumberOfProperties)(UInt32 *numProperties) x; \
STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \
STDMETHOD(BindToRootFolder)(IFolderFolder **resultFolder) x; \
STDMETHOD(Extract)(NExtract::NPathMode::EEnum pathMode, \
NExtract::NOverwriteMode::EEnum overwriteMode, const wchar_t *path, \
Int32 testMode, IFolderArchiveExtractCallback *extractCallback2) x; \
FOLDER_ARCHIVE_INTERFACE(IInFolderArchive, 0x0E)
{
INTERFACE_IInFolderArchive(PURE)
};
#define INTERFACE_IFolderArchiveUpdateCallback(x) \
STDMETHOD(CompressOperation)(const wchar_t *name) x; \
STDMETHOD(DeleteOperation)(const wchar_t *name) x; \
STDMETHOD(OperationResult)(Int32 opRes) x; \
STDMETHOD(UpdateErrorMessage)(const wchar_t *message) x; \
STDMETHOD(SetNumFiles)(UInt64 numFiles) x; \
FOLDER_ARCHIVE_INTERFACE_SUB(IFolderArchiveUpdateCallback, IProgress, 0x0B)
{
INTERFACE_IFolderArchiveUpdateCallback(PURE)
};
#define INTERFACE_IOutFolderArchive(x) \
STDMETHOD(SetFolder)(IFolderFolder *folder) x; \
STDMETHOD(SetFiles)(const wchar_t *folderPrefix, const wchar_t * const *names, UInt32 numNames) x; \
STDMETHOD(DeleteItems)(ISequentialOutStream *outArchiveStream, \
const UInt32 *indices, UInt32 numItems, IFolderArchiveUpdateCallback *updateCallback) x; \
STDMETHOD(DoOperation)( \
FStringVector *requestedPaths, \
FStringVector *processedPaths, \
CCodecs *codecs, int index, \
ISequentialOutStream *outArchiveStream, const Byte *stateActions, const wchar_t *sfxModule, \
IFolderArchiveUpdateCallback *updateCallback) x; \
STDMETHOD(DoOperation2)( \
FStringVector *requestedPaths, \
FStringVector *processedPaths, \
ISequentialOutStream *outArchiveStream, const Byte *stateActions, const wchar_t *sfxModule, \
IFolderArchiveUpdateCallback *updateCallback) x; \
FOLDER_ARCHIVE_INTERFACE(IOutFolderArchive, 0x0F)
{
INTERFACE_IOutFolderArchive(PURE)
};
#define INTERFACE_IFolderArchiveUpdateCallback2(x) \
STDMETHOD(OpenFileError)(const wchar_t *path, HRESULT errorCode) x; \
STDMETHOD(ReadingFileError)(const wchar_t *path, HRESULT errorCode) x; \
STDMETHOD(ReportExtractResult)(Int32 opRes, Int32 isEncrypted, const wchar_t *path) x; \
STDMETHOD(ReportUpdateOperation)(UInt32 notifyOp, const wchar_t *path, Int32 isDir) x; \
FOLDER_ARCHIVE_INTERFACE(IFolderArchiveUpdateCallback2, 0x10)
{
INTERFACE_IFolderArchiveUpdateCallback2(PURE)
};
#define INTERFACE_IFolderScanProgress(x) \
STDMETHOD(ScanError)(const wchar_t *path, HRESULT errorCode) x; \
STDMETHOD(ScanProgress)(UInt64 numFolders, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 isDir) x; \
FOLDER_ARCHIVE_INTERFACE(IFolderScanProgress, 0x11)
{
INTERFACE_IFolderScanProgress(PURE)
};
#endif
| 1,698 |
1,627 | <filename>examples/example_decode.cpp
/*
LodePNG Examples
Copyright (c) 2005-2012 <NAME>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "lodepng.h"
#include <iostream>
/*
3 ways to decode a PNG from a file to RGBA pixel data (and 2 in-memory ways).
*/
//g++ lodepng.cpp example_decode.cpp -ansi -pedantic -Wall -Wextra -O3
//Example 1
//Decode from disk to raw pixels with a single function call
void decodeOneStep(const char* filename) {
std::vector<unsigned char> image; //the raw pixels
unsigned width, height;
//decode
unsigned error = lodepng::decode(image, width, height, filename);
//if there's an error, display it
if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
//the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
}
//Example 2
//Load PNG file from disk to memory first, then decode to raw pixels in memory.
void decodeTwoSteps(const char* filename) {
std::vector<unsigned char> png;
std::vector<unsigned char> image; //the raw pixels
unsigned width, height;
//load and decode
unsigned error = lodepng::load_file(png, filename);
if(!error) error = lodepng::decode(image, width, height, png);
//if there's an error, display it
if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
//the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
}
//Example 3
//Load PNG file from disk using a State, normally needed for more advanced usage.
void decodeWithState(const char* filename) {
std::vector<unsigned char> png;
std::vector<unsigned char> image; //the raw pixels
unsigned width, height;
lodepng::State state; //optionally customize this one
unsigned error = lodepng::load_file(png, filename); //load the image file with given filename
if(!error) error = lodepng::decode(image, width, height, state, png);
//if there's an error, display it
if(error) std::cout << "decoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
//the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
//State state contains extra information about the PNG such as text chunks, ...
}
int main(int argc, char *argv[]) {
const char* filename = argc > 1 ? argv[1] : "test.png";
decodeOneStep(filename);
}
| 972 |
634 | <reponame>halotroop2288/consulo<gh_stars>100-1000
package com.intellij.execution.filters;
import com.intellij.openapi.util.io.FileUtil;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
/**
* from Kotlin
*/
public class ArgumentFileFilter implements Filter {
private volatile String myFilePath;
private volatile String myFileText;
private boolean myTriggred;
public ArgumentFileFilter() {
}
public ArgumentFileFilter(String filePath, String fileText) {
myFilePath = filePath;
myFileText = fileText;
}
public void setPath(String path) throws IOException {
myFilePath = path;
myFileText = FileUtil.loadFile(new File(path));
}
@Nullable
@Override
public Result applyFilter(String line, int entireLength) {
if(!myTriggred) {
String path = myFilePath;
String text = myFileText;
if(path == null || text == null) {
myTriggred = true;
}
else {
int p = line.indexOf(path);
if(p > 0) {
myTriggred = true;
int offset = entireLength - line.length() + p;
return new Result(offset, offset + path.length(), new ShowTextPopupHyperlinkInfo(path, text));
}
}
}
return null;
}
}
| 483 |
423 | <gh_stars>100-1000
import cv2
import torch
import numpy as np
import torch
from math import *
sigma_inp = 20#ref.hmGaussInp
n = sigma_inp * 6 + 1
g_inp = np.zeros((n, n))
for i in range(n):
for j in range(n):
g_inp[i, j] = np.exp(-((i - n / 2) ** 2 + (j - n / 2) ** 2) / (2. * sigma_inp * sigma_inp))
def GetTransform(center, scale, rot, res):
h = scale
t = np.eye(3)
t[0, 0] = res / h
t[1, 1] = res / h
t[0, 2] = res * (- center[0] / h + 0.5)
t[1, 2] = res * (- center[1] / h + 0.5)
if rot != 0:
rot = -rot
r = np.eye(3)
ang = rot * np.math.pi / 180
s = np.math.sin(ang)
c = np.math.cos(ang)
r[0, 0] = c
r[0, 1] = - s
r[1, 0] = s
r[1, 1] = c
t_ = np.eye(3)
t_[0, 2] = - res / 2
t_[1, 2] = - res / 2
t_inv = np.eye(3)
t_inv[0, 2] = res / 2
t_inv[1, 2] = res / 2
t = np.dot(np.dot(np.dot(t_inv, r), t_), t)
return t
def Transform(pt, center, scale, rot, res, invert = False):
pt_ = np.ones(3)
pt_[0], pt_[1] = pt[0], pt[1]
t = GetTransform(center, scale, rot, res)
if invert:
t = np.linalg.inv(t)
new_point = np.dot(t, pt_)[:2]
new_point = new_point.astype(np.int32)
return new_point
def getTransform3D(center, scale, rot, res):
h = 1.0 * scale
t = np.eye(4)
t[0][0] = res / h
t[1][1] = res / h
t[2][2] = res / h
t[0][3] = res * (- center[0] / h + 0.5)
t[1][3] = res * (- center[1] / h + 0.5)
if rot != 0:
raise Exception('Not Implement')
return t
def Transform3D(pt, center, scale, rot, res, invert = False):
pt_ = np.ones(4)
pt_[0], pt_[1], pt_[2] = pt[0], pt[1], pt[2]
t = getTransform3D(center, scale, rot, res)
if invert:
t = np.linalg.inv(t)
new_point = np.dot(t, pt_)[:3]
return new_point
def Crop(img, center, scale, rot, res):
ht, wd = img.shape[0], img.shape[1]
tmpImg, newImg = img.copy(), np.zeros((res, res, 3), dtype = np.uint8)
scaleFactor = scale / res
if scaleFactor < 2:
scaleFactor = 1
else:
newSize = int(np.math.floor(max(ht, wd) / scaleFactor))
newSize_ht = int(np.math.floor(ht / scaleFactor))
newSize_wd = int(np.math.floor(wd / scaleFactor))
if newSize < 2:
return torch.from_numpy(newImg.transpose(2, 0, 1).astype(np.float32) / 256.)
else:
tmpImg = cv2.resize(tmpImg, (newSize_wd, newSize_ht)) #TODO
ht, wd = tmpImg.shape[0], tmpImg.shape[1]
c, s = 1.0 * center / scaleFactor, scale / scaleFactor
c[0], c[1] = c[1], c[0]
ul = Transform((0, 0), c, s, 0, res, invert = True)
br = Transform((res, res), c, s, 0, res, invert = True)
if scaleFactor >= 2:
br = br - (br - ul - res)
pad = int(np.math.ceil((((ul - br) ** 2).sum() ** 0.5) / 2 - (br[0] - ul[0]) / 2))
if rot != 0:
ul = ul - pad
br = br + pad
old_ = [max(0, ul[0]), min(br[0], ht), max(0, ul[1]), min(br[1], wd)]
new_ = [max(0, - ul[0]), min(br[0], ht) - ul[0], max(0, - ul[1]), min(br[1], wd) - ul[1]]
newImg = np.zeros((br[0] - ul[0], br[1] - ul[1], 3), dtype = np.uint8)
#print 'new old newshape tmpshape center', new_[0], new_[1], old_[0], old_[1], newImg.shape, tmpImg.shape, center
try:
newImg[new_[0]:new_[1], new_[2]:new_[3], :] = tmpImg[old_[0]:old_[1], old_[2]:old_[3], :]
except:
#print 'ERROR: new old newshape tmpshape center', new_[0], new_[1], old_[0], old_[1], newImg.shape, tmpImg.shape, center
return np.zeros((3, res, res), np.uint8)
if rot != 0:
M = cv2.getRotationMatrix2D((newImg.shape[0] / 2, newImg.shape[1] / 2), rot, 1)
newImg = cv2.warpAffine(newImg, M, (newImg.shape[0], newImg.shape[1]))
newImg = newImg[pad+1:-pad+1, pad+1:-pad+1, :].copy()
if scaleFactor < 2:
newImg = cv2.resize(newImg, (res, res))
return newImg.transpose(2, 0, 1).astype(np.float32)
def Gaussian(sigma):
if sigma == 7:
return np.array([0.0529, 0.1197, 0.1954, 0.2301, 0.1954, 0.1197, 0.0529,
0.1197, 0.2709, 0.4421, 0.5205, 0.4421, 0.2709, 0.1197,
0.1954, 0.4421, 0.7214, 0.8494, 0.7214, 0.4421, 0.1954,
0.2301, 0.5205, 0.8494, 1.0000, 0.8494, 0.5205, 0.2301,
0.1954, 0.4421, 0.7214, 0.8494, 0.7214, 0.4421, 0.1954,
0.1197, 0.2709, 0.4421, 0.5205, 0.4421, 0.2709, 0.1197,
0.0529, 0.1197, 0.1954, 0.2301, 0.1954, 0.1197, 0.0529]).reshape(7, 7)
elif sigma == n:
return g_inp
else:
raise Exception('Gaussian {} Not Implement'.format(sigma))
def DrawGaussian(img, pt, sigma, truesigma=-1):
img = img.copy()
tmpSize = int(np.math.ceil(3 * sigma))
ul = [int(np.math.floor(pt[0] - tmpSize)), int(np.math.floor(pt[1] - tmpSize))]
br = [int(np.math.floor(pt[0] + tmpSize)), int(np.math.floor(pt[1] + tmpSize))]
if ul[0] > img.shape[1] or ul[1] > img.shape[0] or br[0] < 1 or br[1] < 1:
return img
size = 2 * tmpSize + 1
g = Gaussian(size)
if truesigma==0.5:
g[0,:] *= 0
g[-1,:] *= 0
g[:,0] *= 0
g[:,-1] *= 0
g *= 1.5
g_x = [max(0, -ul[0]), min(br[0], img.shape[1]) - max(0, ul[0]) + max(0, -ul[0])]
g_y = [max(0, -ul[1]), min(br[1], img.shape[0]) - max(0, ul[1]) + max(0, -ul[1])]
img_x = [max(0, ul[0]), min(br[0], img.shape[1])]
img_y = [max(0, ul[1]), min(br[1], img.shape[0])]
img[img_y[0]:img_y[1], img_x[0]:img_x[1]] = g[g_y[0]:g_y[1], g_x[0]:g_x[1]]
return img
def myDrawGaussian(img, pt, sigmaredundant):
pt[0] = floor(pt[0])
pt[1] = floor(pt[1])
if (pt[0] < 1 or pt[1] < 1 or pt[0] > img.shape[0] or pt[1] > img.shape[1]):
return img
img[max(pt[0]-3, 0):min(pt[0]+3, img.shape[0]), max(pt[1]-0, 0):min(pt[1]+0, img.shape[1])] = 1
img[max(pt[0]-2, 0):min(pt[0]+2, img.shape[0]), max(pt[1]-1, 0):min(pt[1]+1, img.shape[1])] = 1
img[max(pt[0]-2, 0):min(pt[0]+2, img.shape[0]), max(pt[1]-2, 0):min(pt[1]+2, img.shape[1])] = 1
img[max(pt[0]-0, 0):min(pt[0]+0, img.shape[0]), max(pt[1]-3, 0):min(pt[1]+3, img.shape[1])] = 1
if (img.sum()==0):
print(pt)
assert(img.sum() != 0)
img = img / img.sum()
return img
def Rnd(x):
wow = torch.randn(1)
return max(-2 * x, min(2 * x, float(wow) * x))
def Flip(img):
return img[:, :, ::-1].copy()
def ShuffleLR(x):
shuffleRef = [[0, 5], [1, 4], [2, 3],
[10, 15], [11, 14], [12, 13]]
for e in shuffleRef:
x[e[0]], x[e[1]] = x[e[1]].copy(), x[e[0]].copy()
return x
| 3,200 |
5,863 | <gh_stars>1000+
import os
import tempfile
class Config:
lineEnd = "\n"
biLineEnd = "\n\n"
triLineEnd = "\n\n\n"
undrln = "_"
blank = " "
tab = "\t"
star = "*"
slash = "/"
comma = ","
delimInFeature = "."
B = "B"
num = "0123456789.几二三四五六七八九十千万亿兆零1234567890%"
letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz/・-"
mark = "*"
model_urls = {
"postag": "https://github.com/lancopku/pkuseg-python/releases/download/v0.0.16/postag.zip",
"medicine": "https://github.com/lancopku/pkuseg-python/releases/download/v0.0.16/medicine.zip",
"tourism": "https://github.com/lancopku/pkuseg-python/releases/download/v0.0.16/tourism.zip",
"news": "https://github.com/lancopku/pkuseg-python/releases/download/v0.0.16/news.zip",
"web": "https://github.com/lancopku/pkuseg-python/releases/download/v0.0.16/web.zip",
}
model_hash = {
"postag": "afdf15f4e39bc47a39be4c37e3761b0c8f6ad1783f3cd3aff52984aebc0a1da9",
"medicine": "773d655713acd27dd1ea9f97d91349cc1b6aa2fc5b158cd742dc924e6f239dfc",
"tourism": "1c84a0366fe6fda73eda93e2f31fd399923b2f5df2818603f426a200b05cbce9",
"news": "18188b68e76b06fc437ec91edf8883a537fe25fa606641534f6f004d2f9a2e42",
"web": "4867f5817f187246889f4db259298c3fcee07c0b03a2d09444155b28c366579e",
}
available_models = ["default", "medicine", "tourism", "web", "news"]
models_with_dict = ["medicine", "tourism"]
def __init__(self):
# main setting
self.pkuseg_home = os.path.expanduser(os.getenv('PKUSEG_HOME', '~/.pkuseg'))
self.trainFile = os.path.join("data", "small_training.utf8")
self.testFile = os.path.join("data", "small_test.utf8")
self._tmp_dir = tempfile.TemporaryDirectory()
self.homepath = self._tmp_dir.name
self.tempFile = os.path.join(self.homepath, ".pkuseg", "temp")
self.readFile = os.path.join("data", "small_test.utf8")
self.outputFile = os.path.join("data", "small_test_output.utf8")
self.modelOptimizer = "crf.adf"
self.rate0 = 0.05 # init value of decay rate in SGD and ADF training
# self.reg = 1
# self.regs = [1]
# self.regList = self.regs.copy()
self.random = (
0
) # 0 for 0-initialization of model weights, 1 for random init of model weights
self.evalMetric = (
"f1"
) # tok.acc (token accuracy), str.acc (string accuracy), f1 (F1-score)
self.trainSizeScale = 1 # for scaling the size of training data
self.ttlIter = 20 # of training iterations
self.nUpdate = 10 # for ADF training
self.outFolder = os.path.join(self.tempFile, "output")
self.save = 1 # save model file
self.rawResWrite = True
self.miniBatch = 1 # mini-batch in stochastic training
self.nThread = 10 # number of processes
# ADF training
self.upper = 0.995 # was tuned for nUpdate = 10
self.lower = 0.6 # was tuned for nUpdate = 10
# global variables
self.metric = None
self.reg = 1
self.outDir = self.outFolder
self.testrawDir = "rawinputs/"
self.testinputDir = "inputs/"
self.tempDir = os.path.join(self.homepath, ".pkuseg", "temp")
self.testoutputDir = "entityoutputs/"
# self.GL_init = True
self.weightRegMode = "L2" # choosing weight regularizer: L2, L1)
self.c_train = os.path.join(self.tempFile, "train.conll.txt")
self.f_train = os.path.join(self.tempFile, "train.feat.txt")
self.c_test = os.path.join(self.tempFile, "test.conll.txt")
self.f_test = os.path.join(self.tempFile, "test.feat.txt")
self.fTune = "tune.txt"
self.fLog = "trainLog.txt"
self.fResSum = "summarizeResult.txt"
self.fResRaw = "rawResult.txt"
self.fOutput = "outputTag-{}.txt"
self.fFeatureTrain = os.path.join(self.tempFile, "ftrain.txt")
self.fGoldTrain = os.path.join(self.tempFile, "gtrain.txt")
self.fFeatureTest = os.path.join(self.tempFile, "ftest.txt")
self.fGoldTest = os.path.join(self.tempFile, "gtest.txt")
self.modelDir = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "models", "ctb8"
)
self.fModel = os.path.join(self.modelDir, "model.txt")
# feature
self.numLetterNorm = True
self.featureTrim = 0
self.wordFeature = True
self.wordMax = 6
self.wordMin = 2
self.nLabel = 5
self.order = 1
def globalCheck(self):
if self.evalMetric == "f1":
self.metric = "f-score"
elif self.evalMetric == "tok.acc":
self.metric = "token-accuracy"
elif self.evalMetric == "str.acc":
self.metric = "string-accuracy"
else:
raise Exception("invalid eval metric")
assert self.rate0 > 0
assert self.trainSizeScale > 0
assert self.ttlIter > 0
assert self.nUpdate > 0
assert self.miniBatch > 0
assert self.reg > 0
config = Config()
| 2,694 |
953 | <gh_stars>100-1000
"""Package for IL commands."""
| 17 |
45,293 | <reponame>Mu-L/kotlin<filename>kotlin-native/backend.native/tests/interop/objc/tests/mangling.h
#import <Foundation/NSObject.h>
// [KT-36067] cinterop tool fails when there is a structure member named Companion
struct EnumFieldMangleStruct {
enum {Companion, Any} smth;
};
struct EnumFieldMangleStruct enumMangledStruct = { Any };
struct MyStruct {
int Companion; // simple clash
int _Companion;
int $_Companion;
int super;
};
struct MyStruct myStruct = {11, 12, 13, 14};
@protocol Proto
@property int Companion; // clash on implementing
@end;
@interface FooMangled : NSObject<Proto>
//- (void) CompanionS; // mangleSimple does not support this: it may clash after mangling
@end;
| 236 |
4,124 | <filename>jstorm-core/src/main/java/com/alibaba/jstorm/daemon/worker/FlusherPool.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 com.alibaba.jstorm.daemon.worker;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author JohnFang (<EMAIL>).
*/
public class FlusherPool {
private final Timer timer = new Timer("flush-trigger", true);
private final ThreadPoolExecutor threadPool;
private final HashMap<Long, ArrayList<Flusher>> pendingFlushMap = new HashMap<>();
private final HashMap<Long, TimerTask> timerTaskMap = new HashMap<>();
public FlusherPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {
this.threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,
new ArrayBlockingQueue<Runnable>(1024), new ThreadPoolExecutor.DiscardPolicy());
}
public synchronized void start(Flusher flusher, final long flushInterval) {
ArrayList<Flusher> pending = pendingFlushMap.get(flushInterval);
if (pending == null) {
pending = new ArrayList<>();
TimerTask t = new TimerTask() {
@Override
public void run() {
invokeAll(flushInterval);
}
};
pendingFlushMap.put(flushInterval, pending);
timer.schedule(t, flushInterval, flushInterval);
timerTaskMap.put(flushInterval, t);
}
pending.add(flusher);
}
private synchronized void invokeAll(long flushInterval) {
ArrayList<Flusher> tasks = pendingFlushMap.get(flushInterval);
if (tasks != null) {
for (Flusher f : tasks) {
threadPool.submit(f);
}
}
}
public synchronized void stop(Flusher flusher, long flushInterval) {
ArrayList<Flusher> pending = pendingFlushMap.get(flushInterval);
pending.remove(flusher);
if (pending.size() == 0) {
pendingFlushMap.remove(flushInterval);
timerTaskMap.remove(flushInterval).cancel();
}
}
public Future<?> submit(Runnable runnable) {
return threadPool.submit(runnable);
}
public void shutdown() {
this.threadPool.shutdown();
this.timer.cancel();
}
public void awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
this.threadPool.awaitTermination(timeout, unit);
}
} | 1,261 |
381 | <filename>tests/general/no_arg_main.cc
#include <stdio.h>
int main() {
puts("hello from C++ no-arg main!");
return 0;
}
| 55 |
875 | <reponame>a-pertsev/sqoop
/**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.sqoop.cloud;
import static org.apache.sqoop.util.AppendUtils.MAPREDUCE_OUTPUT_BASENAME_PROPERTY;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sqoop.cloud.tools.CloudCredentialsRule;
import org.apache.sqoop.testutil.ArgumentArrayBuilder;
import org.apache.sqoop.testutil.AvroTestUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
public abstract class AbstractTestIncrementalAppendAvroImport extends CloudImportJobTestCase {
public static final Log LOG = LogFactory.getLog(AbstractTestIncrementalAppendAvroImport.class.getName());
@Rule
public ExpectedException thrown = ExpectedException.none();
protected AbstractTestIncrementalAppendAvroImport(CloudCredentialsRule credentialsRule) {
super(credentialsRule);
}
@Test
public void testIncrementalAppendAsAvroDataFileWhenNoNewRowIsImported() throws IOException {
String[] args = getArgsWithAsAvroDataFileOption(false);
runImport(args);
args = getIncrementalAppendArgsWithAsAvroDataFileOption(false);
runImport(args);
failIfOutputFilePathContainingPatternExists(fileSystemRule.getCloudFileSystem(), fileSystemRule.getTargetDirPath(), MAP_OUTPUT_FILE_00001);
}
@Test
public void testIncrementalAppendAsAvroDataFile() throws IOException {
String[] args = getArgsWithAsAvroDataFileOption(false);
runImport(args);
insertInputDataIntoTable(getDataSet().getExtraInputData());
args = getIncrementalAppendArgsWithAsAvroDataFileOption(false);
runImport(args);
AvroTestUtils.verify(getDataSet().getExpectedExtraAvroOutput(), fileSystemRule.getCloudFileSystem().getConf(), fileSystemRule.getTargetDirPath(), MAP_OUTPUT_FILE_00001);
}
@Test
public void testIncrementalAppendAsAvroDataFileWithMapreduceOutputBasenameProperty() throws IOException {
String[] args = getArgsWithAsAvroDataFileOption(true);
runImport(args);
insertInputDataIntoTable(getDataSet().getExtraInputData());
args = getIncrementalAppendArgsWithAsAvroDataFileOption(true);
runImport(args);
AvroTestUtils.verify(getDataSet().getExpectedExtraAvroOutput(), fileSystemRule.getCloudFileSystem().getConf(), fileSystemRule.getTargetDirPath(), CUSTOM_MAP_OUTPUT_FILE_00001);
}
private String[] getArgsWithAsAvroDataFileOption(boolean withMapreduceOutputBasenameProperty) {
ArgumentArrayBuilder builder = getArgumentArrayBuilderForUnitTestsWithFileFormatOption(fileSystemRule.getTargetDirPath().toString(), "as-avrodatafile");
if (withMapreduceOutputBasenameProperty) {
builder.withProperty(MAPREDUCE_OUTPUT_BASENAME_PROPERTY, MAPREDUCE_OUTPUT_BASENAME);
}
return builder.build();
}
private String[] getIncrementalAppendArgsWithAsAvroDataFileOption(boolean withMapreduceOutputBasenameProperty) {
ArgumentArrayBuilder builder = getArgumentArrayBuilderForUnitTestsWithFileFormatOption(fileSystemRule.getTargetDirPath().toString(), "as-avrodatafile");
builder = addIncrementalAppendImportArgs(builder, fileSystemRule.getTemporaryRootDirPath().toString());
if (withMapreduceOutputBasenameProperty) {
builder.withProperty(MAPREDUCE_OUTPUT_BASENAME_PROPERTY, MAPREDUCE_OUTPUT_BASENAME);
}
return builder.build();
}
}
| 1,291 |
336 | class Int32:
"""
A signed integer with a 32-bit fixed width.
"""
def __init__(self, value):
if value < -2 ** 31 or value > 2 ** 31 - 1:
raise ValueError('value {} cannot be represented in int32'.format(value))
self._value = value
def get_value(self):
return self._value
def __str__(self):
return str(self._value)
class Int64:
"""
A signed integer with a 64-bit fixed width.
"""
def __init__(self, value):
if value < -2 ** 63 or value > 2 ** 63 - 1:
raise ValueError('value {} cannot be represented in int32'.format(value))
self._value = value
def get_value(self):
return self._value
def __str__(self):
return str(self._value)
class UInt64:
"""
An unsigned integer with a 64-bit fixed width.
"""
def __init__(self, value):
if value < 0 or value > 2 ** 64 - 1:
raise ValueError('value {} cannot be represented in uint32'.format(value))
self._value = value
def get_value(self):
return self._value
def __str__(self):
return str(self._value)
| 474 |
602 | <reponame>CorfuDB/CORFU<gh_stars>100-1000
package org.corfudb.generator.operations;
import org.corfudb.generator.Correctness;
import org.corfudb.generator.State;
import org.corfudb.runtime.exceptions.TransactionAbortedException;
import java.util.List;
/**
* Created by rmichoud on 10/6/17.
*/
public class WriteAfterWriteTxOperation extends Operation {
public WriteAfterWriteTxOperation(State state) {
super(state, "TxWaw");
}
@Override
public void execute() {
Correctness.recordTransactionMarkers(false, shortName, Correctness.TX_START);
long timestamp;
state.startWriteAfterWriteTx();
int numOperations = state.getOperationCount().sample();
List<Operation> operations = state.getOperations().sample(numOperations);
for (Operation operation : operations) {
if (operation instanceof OptimisticTxOperation
|| operation instanceof SnapshotTxOperation
|| operation instanceof NestedTxOperation) {
continue;
}
operation.execute();
}
try {
timestamp = state.stopTx();
Correctness.recordTransactionMarkers(true, shortName, Correctness.TX_END,
Long.toString(timestamp));
} catch (TransactionAbortedException tae) {
Correctness.recordTransactionMarkers(false, shortName, Correctness.TX_ABORTED);
}
}
}
| 587 |
7,018 | <gh_stars>1000+
package com.tencent.mtt.hippy.example.view;
import android.view.View;
import com.tencent.mtt.hippy.annotation.HippyController;
import com.tencent.mtt.hippy.annotation.HippyControllerProps;
import com.tencent.mtt.hippy.utils.LogUtils;
import com.tencent.mtt.hippy.views.custom.HippyCustomPropsController;
@SuppressWarnings({"unused"})
@HippyController(name = HippyCustomPropsController.CLASS_NAME)
public class MyCustomViewController extends HippyCustomPropsController
{
@HippyControllerProps(name = "customString", defaultType = HippyControllerProps.STRING)
public void setCustomString(View view, String text) {
LogUtils.d("MyCustomViewController", "setCustomString: text=" + text);
}
}
| 239 |
2,529 | from datetime import timedelta
import pytest
from .conf import TlsTestConf
class TestProxy:
@pytest.fixture(autouse=True, scope='class')
def _class_scope(self, env):
conf = TlsTestConf(env=env, extras={
'base': "LogLevel proxy:trace1 proxy_http:trace1 ssl:trace1",
env.domain_b: [
"ProxyPreserveHost on",
f'ProxyPass "/proxy/" "http://127.0.0.1:{env.http_port}/"',
f'ProxyPassReverse "/proxy/" "http://{env.domain_b}:{env.http_port}"',
]
})
# add vhosts a+b and a ssl proxy from a to b
conf.add_tls_vhosts(domains=[env.domain_a, env.domain_b])
conf.install()
assert env.apache_restart() == 0
def test_13_proxy_http_get(self, env):
data = env.tls_get_json(env.domain_b, "/proxy/index.json")
assert data == {'domain': env.domain_b}
@pytest.mark.parametrize("name, value", [
("SERVER_NAME", "b.mod-tls.test"),
("SSL_SESSION_RESUMED", ""),
("SSL_SECURE_RENEG", ""),
("SSL_COMPRESS_METHOD", ""),
("SSL_CIPHER_EXPORT", ""),
("SSL_CLIENT_VERIFY", ""),
])
def test_13_proxy_http_vars(self, env, name: str, value: str):
r = env.tls_get(env.domain_b, f"/proxy/vars.py?name={name}")
assert r.exit_code == 0, r.stderr
assert r.json == {name: value}, r.stdout
| 685 |
14,668 | // 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.weblayer_private;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/**
* Helper class to tell native code whether manual JNI registration is required.
*/
@JNINamespace("weblayer")
public final class WebViewCompatibilityHelperImpl {
private static boolean sRequiresManualJniRegistration;
@CalledByNative
private static boolean requiresManualJniRegistration() {
return sRequiresManualJniRegistration;
}
public static void setRequiresManualJniRegistration(boolean isRequired) {
sRequiresManualJniRegistration = isRequired;
}
}
| 244 |
721 | {
"forge_marker": 1,
"defaults": {
"textures": {
"particle": "enderio:blocks/block_concussion_charge_side",
"bottom": "enderio:blocks/block_concussion_charge_bottom",
"top": "enderio:blocks/block_concussion_charge_top",
"side": "enderio:blocks/block_concussion_charge_side"
},
"model": "enderio:sided_cube"
},
"variants": {
"inventory": [{}],
"explode": {
"true": {
},
"false": {
}
}
}
}
| 219 |
1,695 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.spi.ptf;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.trino.spi.expression.ConnectorExpression;
/**
* This class represents the three types of arguments passed to a Table Function:
* scalar arguments, descriptor arguments, and table arguments.
* <p>
* This representation should be considered experimental. Eventually, {@link ConnectorExpression}
* should be extended to include the Table Function arguments.
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "@type")
@JsonSubTypes({
@JsonSubTypes.Type(value = DescriptorArgument.class, name = "descriptor"),
@JsonSubTypes.Type(value = ScalarArgument.class, name = "scalar"),
@JsonSubTypes.Type(value = TableArgument.class, name = "table"),
})
public abstract class Argument
{
}
| 433 |
500 | <reponame>erluxman/flutter_background_geolocation
#import "StreamHandler.h"
@interface MotionChangeStreamHandler : StreamHandler
@end
| 41 |
573 | <gh_stars>100-1000
/*
* This software is licensed under the terms of the MIT License.
* See COPYING for further information.
* ---
* Copyright (c) 2011-2019, <NAME> <<EMAIL>>.
* Copyright (c) 2012-2019, <NAME> <<EMAIL>>.
*/
#include "taisei.h"
#include "spells.h"
#include "../cirno.h"
#include "../misc.h"
#include "common_tasks.h"
#include "global.h"
TASK(move_frozen, { BoxedProjectileArray *parray; }) {
DECLARE_ENT_ARRAY(Projectile, projs, ARGS.parray->size);
ENT_ARRAY_FOREACH(ARGS.parray, Projectile *p, {
ENT_ARRAY_ADD(&projs, p);
});
ENT_ARRAY_FOREACH(&projs, Projectile *p, {
cmplx dir = rng_dir();
p->move = move_asymptotic_halflife(0, 4 * dir, rng_range(60, 80));
p->color = *RGB(0.9, 0.9, 0.9);
stage1_spawn_stain(p->pos, p->angle, 30);
spawn_projectile_highlight_effect(p);
play_sfx_ex("shot2", 0, false);
if(rng_chance(0.4)) {
YIELD;
}
});
}
DEFINE_EXTERN_TASK(stage1_spell_perfect_freeze) {
Boss *boss = INIT_BOSS_ATTACK(&ARGS);
BEGIN_BOSS_ATTACK(&ARGS);
for(int run = 1;;run++) {
boss->move = move_towards(VIEWPORT_W/2.0 + 100.0*I, 0.04);
common_charge(40, &boss->pos, 0, RGBA(1.0, 0.5, 0.0, 0));
int n = global.diff;
int nfrog = n*60;
DECLARE_ENT_ARRAY(Projectile, projs, nfrog);
for(int i = 0; i < nfrog/n; i++) {
play_sfx_loop("shot1_loop");
float r = rng_f32();
float g = rng_f32();
float b = rng_f32();
for(int j = 0; j < n; j++) {
real speed = rng_range(1, difficulty_value(0, 0, 5, 5.5));
ENT_ARRAY_ADD(&projs, PROJECTILE(
.proto = pp_ball,
.pos = boss->pos,
.color = RGB(r, g, b),
.move = move_linear(speed * rng_dir()),
));
}
YIELD;
}
WAIT(20);
ENT_ARRAY_FOREACH(&projs, Projectile *p, {
stage1_spawn_stain(p->pos, p->angle, 30);
stage1_spawn_stain(p->pos, p->angle, 30);
spawn_projectile_highlight_effect(p);
play_sfx("shot_special1");
p->color = *RGB(0.9, 0.9, 0.9);
p->move.retention = 0.8;
if(rng_chance(0.2)) {
YIELD;
}
});
WAIT(60);
real dir = rng_sign();
boss->move = (MoveParams){ .velocity = dir*2.7+I, .retention = 0.99, .acceleration = -dir*0.017 };
int charge_time = difficulty_value(85, 80, 75, 70);
aniplayer_queue(&boss->ani, "(9)", 0);
INVOKE_SUBTASK(common_charge, +60, RGBA(0.3, 0.4, 0.9, 0), charge_time, .anchor = &boss->pos, .sound = COMMON_CHARGE_SOUNDS);
INVOKE_SUBTASK(common_charge, -60, RGBA(0.3, 0.4, 0.9, 0), charge_time, .anchor = &boss->pos);
WAIT(charge_time);
INVOKE_SUBTASK_DELAYED(120, move_frozen, &projs);
int cnt = difficulty_value(0, 0, 30, 50);
for(int i = 0; i < cnt; i++) {
play_sfx_loop("shot1_loop");
real r1 = sin(i/M_PI*5.3) * cos(2*i/M_PI*5.3);
real r2 = cos(i/M_PI*5.3) * sin(2*i/M_PI*5.3);
cmplx aim = cnormalize(global.plr.pos - boss->pos);
real speed = 2 + 0.2 * global.diff;
for(int sign = -1; sign <= 1; sign += 2) {
PROJECTILE(
.proto = pp_rice,
.pos = boss->pos + sign*60,
.color = RGB(0.3, 0.4, 0.9),
.move = move_asymptotic_simple(speed*aim*cdir(0.5*(sign > 0 ? r1 : r2)), 2.5+0.1*sign*I),
);
}
WAIT(difficulty_value(5, 5, 5, 4));
}
aniplayer_queue(&boss->ani,"main",0);
WAIT(difficulty_value(5, 5, 5, 0));
}
}
| 1,596 |
782 | /*
* Copyright (c) 2011-2020, <NAME>. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.alg.disparity.sgm;
import boofcv.abst.filter.FilterImageInterface;
import boofcv.alg.InputSanityCheck;
import boofcv.struct.image.ImageBase;
import boofcv.struct.image.ImageGray;
/**
* Computes Census score for SGM using a straight forward implementation. A census transform is applied
* to the left and right input images. That's then used to compute the census error.
*
* @author <NAME>
*/
public class SgmStereoDisparityCensus<T extends ImageBase<T>, C extends ImageGray<C>>
extends SgmStereoDisparity<T, C> {
FilterImageInterface<T, C> censusTran;
// Storage for census transform of left and right images
C cleft;
C cright;
public SgmStereoDisparityCensus( FilterImageInterface<T, C> censusTran,
SgmDisparityCost<C> sgmCost, SgmDisparitySelector selector ) {
super(sgmCost, selector);
this.censusTran = censusTran;
cleft = censusTran.getOutputType().createImage(1, 1);
cright = censusTran.getOutputType().createImage(1, 1);
}
/**
* Computes disparity
*
* @param left (Input) left rectified stereo image
* @param right (Input) right rectified stereo image
*/
@Override
public void process( T left, T right ) {
InputSanityCheck.checkSameShape(left, right);
// Apply Census Transform to input images
censusTran.process(left, cleft);
censusTran.process(right, cright);
disparity.reshape(left);
helper.configure(left.width, disparityMin, disparityRange);
sgmCost.configure(disparityMin, disparityRange);
aggregation.configure(disparityMin);
// Compute the cost using mutual information
sgmCost.process(cleft, cright, costYXD);
// Aggregate the cost along all the paths
aggregation.process(costYXD);
// Select the best disparity for each pixel given the cost
selector.setDisparityMin(disparityMin);
selector.select(costYXD, aggregation.getAggregated(), disparity);
}
}
| 811 |
1,177 |
#include "stdafx.h"
#include "mLibCore.cpp"
#include "mLibLodePNG.cpp"
//#include "mLibZLib.cpp"
#include "mLibDepthCamera.cpp" | 57 |
562 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module defines a class to represent a compiler environment state."""
import csv
import sys
from typing import Iterable, List, Optional, TextIO
from pydantic import BaseModel, Field, validator
from compiler_gym.datasets.uri import BENCHMARK_URI_PATTERN
from compiler_gym.util.truncate import truncate
class CompilerEnvState(BaseModel):
"""The representation of a compiler environment state.
The state of an environment is defined as a benchmark and a sequence of
actions that has been applied to it. For a given environment, the state
contains the information required to reproduce the result.
"""
benchmark: str = Field(
allow_mutation=False,
regex=BENCHMARK_URI_PATTERN,
examples=[
"benchmark://cbench-v1/crc32",
"generator://csmith-v0/0",
],
)
"""The URI of the benchmark used for this episode."""
commandline: str
"""The list of actions that produced this state, as a commandline."""
walltime: float
"""The walltime of the episode in seconds. Must be non-negative."""
reward: Optional[float] = Field(
required=False,
default=None,
allow_mutation=True,
)
"""The cumulative reward for this episode. Optional."""
@validator("walltime")
def walltime_nonnegative(cls, v):
if v is not None:
assert v >= 0, "Walltime cannot be negative"
return v
@property
def has_reward(self) -> bool:
"""Return whether the state has a reward value."""
return self.reward is not None
def __eq__(self, rhs) -> bool:
if not isinstance(rhs, CompilerEnvState):
return False
epsilon = 1e-5
# Only compare reward if both states have it.
if not (self.has_reward and rhs.has_reward):
reward_equal = True
else:
reward_equal = abs(self.reward - rhs.reward) < epsilon
# Note that walltime is excluded from equivalence checks as two states
# are equivalent if they define the same point in the optimization space
# irrespective of how long it took to get there.
return (
self.benchmark == rhs.benchmark
and reward_equal
and self.commandline == rhs.commandline
)
def __ne__(self, rhs) -> bool:
return not self == rhs
class Config:
validate_assignment = True
class CompilerEnvStateWriter:
"""Serialize compiler environment states to CSV.
Example use:
>>> with CompilerEnvStateWriter(open("results.csv", "wb")) as writer:
... writer.write_state(env.state)
"""
def __init__(self, f: TextIO, header: bool = True):
"""Constructor.
:param f: The file to write to.
:param header: Whether to include a header row.
"""
self.f = f
self.writer = csv.writer(self.f, lineterminator="\n")
self.header = header
def write_state(self, state: CompilerEnvState, flush: bool = False) -> None:
"""Write the state to file.
:param state: A compiler environment state.
:param flush: Write to file immediately.
"""
if self.header:
self.writer.writerow(("benchmark", "reward", "walltime", "commandline"))
self.header = False
self.writer.writerow(
(state.benchmark, state.reward, state.walltime, state.commandline)
)
if flush:
self.f.flush()
def __enter__(self):
"""Support with-statement for the writer."""
return self
def __exit__(self, *args):
"""Support with-statement for the writer."""
self.f.close()
class CompilerEnvStateReader:
"""Read states from a CSV file.
Example usage:
>>> with CompilerEnvStateReader(open("results.csv", "rb")) as reader:
... for state in reader:
... print(state)
"""
def __init__(self, f: TextIO):
"""Constructor.
:param f: The file to read.
"""
self.f = f
self.reader = csv.reader(self.f)
def __iter__(self) -> Iterable[CompilerEnvState]:
"""Read the states from the file."""
columns_in_order = ["benchmark", "reward", "walltime", "commandline"]
# Read the CSV and coerce the columns into the expected order.
for (
benchmark,
reward,
walltime,
commandline,
) in self._iterate_columns_in_order(self.reader, columns_in_order):
yield CompilerEnvState(
benchmark=benchmark,
reward=None if reward == "" else float(reward),
walltime=0 if walltime == "" else float(walltime),
commandline=commandline,
)
@staticmethod
def _iterate_columns_in_order(
reader: csv.reader, columns: List[str]
) -> Iterable[List[str]]:
"""Read the input CSV and return each row in the given column order.
Supports CSVs both with and without a header. If no header, columns are
expected to be in the correct order. Else the header row is used to
determine column order.
Header row detection is case insensitive.
:param reader: The CSV file to read.
:param columns: A list of column names in the order that they are
expected.
:return: An iterator over rows.
"""
try:
row = next(reader)
except StopIteration:
# Empty file.
return
if len(row) != len(columns):
raise ValueError(
f"Expected {len(columns)} columns in the first row of CSV: {truncate(row)}"
)
# Convert the maybe-header columns to lowercase for case-insensitive
# comparison.
maybe_header = [v.lower() for v in row]
if set(maybe_header) == set(columns):
# The first row matches the expected columns names, so use it to
# determine the column order.
column_order = [maybe_header.index(v) for v in columns]
yield from ([row[v] for v in column_order] for row in reader)
else:
# The first row isn't a header, so assume that all rows are in
# expected column order.
yield row
yield from reader
def __enter__(self):
"""Support with-statement for the reader."""
return self
def __exit__(self, *args):
"""Support with-statement for the reader."""
self.f.close()
@staticmethod
def read_paths(paths: Iterable[str]) -> Iterable[CompilerEnvState]:
"""Read a states from a list of file paths.
Read states from stdin using a special path :code:`"-"`.
:param: A list of paths.
:return: A generator of compiler env states.
"""
for path in paths:
if path == "-":
yield from iter(CompilerEnvStateReader(sys.stdin))
else:
with open(path) as f:
yield from iter(CompilerEnvStateReader(f))
| 3,034 |
4,919 | <gh_stars>1000+
/**
* Thread pool wrap/decoration utils.
*
* @author <NAME> (oldratlee at gmail dot com)
* @see com.alibaba.ttl.threadpool.TtlExecutors
* @see com.alibaba.ttl.threadpool.TtlForkJoinPoolHelper
*/
package com.alibaba.ttl.threadpool;
| 97 |
453 | #include "pic.h"
//Some chip-specific PIC defines borrowed from http://wiki.osdev.org/8259_PIC
#define PIC1 0x20 //IO base address for master PIC
#define PIC2 0xA0 //IO base address for slave PIC
#define PIC1_COMMAND PIC1
#define PIC1_DATA (PIC1+1)
#define PIC2_COMMAND PIC2
#define PIC2_DATA (PIC2+1)
#define PIC_EOI 0x20 /* End-of-interrupt command */
#define ICW1_ICW4 0x01 /* ICW4 (not) needed */
#define ICW1_SINGLE 0x02 /* Single (cascade) mode */
#define ICW1_INTERVAL4 0x04 /* Call address interval 4 (8) */
#define ICW1_LEVEL 0x08 /* Level triggered (edge) mode */
#define ICW1_INIT 0x10 /* Initialization - required! */
#define ICW4_8086 0x01 /* 8086/88 (MCS-80/85) mode */
#define ICW4_AUTO 0x02 /* Auto (normal) EOI */
#define ICW4_BUF_SLAVE 0x08 /* Buffered mode/slave */
#define ICW4_BUF_MASTER 0x0C /* Buffered mode/master */
#define ICW4_SFNM 0x10 /* Special fully nested (not) */
void pic_remap(int offset1, int offset2) {
/*
* offset1:
* vector offset for master PIC
* offset2:
* vector offset for slave PIC
*/
//starts PIC initialization process
//in cascade mode
outb(PIC1_COMMAND, ICW1_INIT+ICW1_ICW4);
outb(PIC2_COMMAND, ICW1_INIT+ICW1_ICW4);
//master PIC
outb(PIC1_DATA, offset1); // ICW2: Master PIC vector offset
outb(PIC2_DATA, offset2); // ICW2: Slave PIC vector offset
outb(PIC1_DATA, 4); // ICW3: tell Master PIC that there is a slave PIC at IRQ2 (0000 0100)
outb(PIC2_DATA, 2); // ICW3: tell Slave PIC its cascade identity (0000 0010)
outb(PIC1_DATA, ICW4_8086);
outb(PIC2_DATA, ICW4_8086);
//set interrupt masks here
//we don't want to mask anything, so the mask is 0x00
outb(PIC1_DATA, 0x00);
outb(PIC2_DATA, 0x00);
}
void pic_signal_end_of_interrupt(uint8_t irq_no) {
//if the interrupt comes from the slave PIC, we need to signal EOI to both the master and slave
if (irq_no >= 8) {
outb(PIC2_COMMAND, PIC_EOI);
}
outb(PIC1_COMMAND, PIC_EOI);
}
| 1,085 |
1,204 | /*
* Copyright 2015 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gs.collections.impl.set.sorted.immutable;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import java.util.TreeSet;
import com.gs.collections.api.LazyIterable;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function0;
import com.gs.collections.api.list.ImmutableList;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.sorted.MutableSortedMap;
import com.gs.collections.api.multimap.sortedset.ImmutableSortedSetMultimap;
import com.gs.collections.api.partition.set.sorted.PartitionImmutableSortedSet;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.set.sorted.ImmutableSortedSet;
import com.gs.collections.api.set.sorted.MutableSortedSet;
import com.gs.collections.api.set.sorted.SortedSetIterable;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.impl.block.factory.Comparators;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.factory.Predicates;
import com.gs.collections.impl.block.factory.Predicates2;
import com.gs.collections.impl.block.function.AddFunction;
import com.gs.collections.impl.block.function.NegativeIntervalFunction;
import com.gs.collections.impl.block.function.PassThruFunction0;
import com.gs.collections.impl.block.procedure.CollectionAddProcedure;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.factory.Sets;
import com.gs.collections.impl.factory.SortedSets;
import com.gs.collections.impl.list.Interval;
import com.gs.collections.impl.list.mutable.AddToList;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.map.mutable.UnifiedMap;
import com.gs.collections.impl.multimap.set.sorted.TreeSortedSetMultimap;
import com.gs.collections.impl.set.mutable.UnifiedSet;
import com.gs.collections.impl.set.sorted.mutable.TreeSortedSet;
import com.gs.collections.impl.stack.mutable.ArrayStack;
import com.gs.collections.impl.test.Verify;
import com.gs.collections.impl.tuple.Tuples;
import org.junit.Assert;
import org.junit.Test;
public abstract class AbstractImmutableSortedSetTestCase
{
protected abstract ImmutableSortedSet<Integer> classUnderTest();
protected abstract ImmutableSortedSet<Integer> classUnderTest(Comparator<? super Integer> comparator);
@Test(expected = NullPointerException.class)
public void noSupportForNull()
{
this.classUnderTest().newWith(null);
}
@Test
public void equalsAndHashCode()
{
ImmutableSortedSet<Integer> immutable = this.classUnderTest();
MutableSortedSet<Integer> mutable = TreeSortedSet.newSet(immutable);
Verify.assertEqualsAndHashCode(mutable, immutable);
Verify.assertPostSerializedEqualsAndHashCode(immutable);
Assert.assertNotEquals(FastList.newList(mutable), immutable);
}
@Test
public void newWith()
{
ImmutableSortedSet<Integer> immutable = this.classUnderTest();
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(Interval.fromTo(0, immutable.size())), immutable.newWith(0).castToSortedSet());
Assert.assertSame(immutable, immutable.newWith(immutable.size()));
ImmutableSortedSet<Integer> set = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(Comparators.<Integer>reverseNaturalOrder(), Interval.oneTo(set.size() + 1)),
set.newWith(set.size() + 1).castToSortedSet());
}
@Test
public void newWithout()
{
ImmutableSortedSet<Integer> immutable = this.classUnderTest();
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(Interval.oneTo(immutable.size() - 1)), immutable.newWithout(immutable.size()).castToSortedSet());
Assert.assertSame(immutable, immutable.newWithout(immutable.size() + 1));
ImmutableSortedSet<Integer> set = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(Comparators.<Integer>reverseNaturalOrder(), Interval.oneTo(set.size() - 1)),
set.newWithout(set.size()).castToSortedSet());
}
@Test
public void newWithAll()
{
ImmutableSortedSet<Integer> set = this.classUnderTest(Collections.<Integer>reverseOrder());
ImmutableSortedSet<Integer> withAll = set.newWithAll(UnifiedSet.newSet(Interval.fromTo(1, set.size() + 1)));
Assert.assertNotEquals(set, withAll);
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(Comparators.<Integer>reverseNaturalOrder(), Interval.fromTo(1, set.size() + 1)),
withAll.castToSortedSet());
}
@Test
public void newWithoutAll()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
ImmutableSortedSet<Integer> withoutAll = set.newWithoutAll(set);
Assert.assertEquals(SortedSets.immutable.<Integer>of(), withoutAll);
Assert.assertEquals(Sets.immutable.<Integer>of(), withoutAll);
ImmutableSortedSet<Integer> largeWithoutAll = set.newWithoutAll(Interval.fromTo(101, 150));
Assert.assertEquals(set, largeWithoutAll);
ImmutableSortedSet<Integer> largeWithoutAll2 = set.newWithoutAll(UnifiedSet.newSet(Interval.fromTo(151, 199)));
Assert.assertEquals(set, largeWithoutAll2);
}
@Test
public void contains()
{
ImmutableSortedSet<Integer> set1 = this.classUnderTest();
for (int i = 1; i <= set1.size(); i++)
{
Verify.assertContains(i, set1.castToSortedSet());
}
Verify.assertNotContains(Integer.valueOf(set1.size() + 1), set1.castToSortedSet());
SortedSet<Integer> set2 = new TreeSet<>(set1.castToSortedSet());
Verify.assertThrows(ClassCastException.class, () -> set1.contains(new Object()));
Verify.assertThrows(ClassCastException.class, () -> set2.contains(new Object()));
Verify.assertThrows(ClassCastException.class, () -> set1.contains("1"));
Verify.assertThrows(ClassCastException.class, () -> set2.contains("1"));
Verify.assertThrows(NullPointerException.class, () -> set1.contains(null));
Verify.assertThrows(NullPointerException.class, () -> set2.contains(null));
}
@Test
public void containsAllArray()
{
ImmutableSortedSet<Integer> set1 = this.classUnderTest();
SortedSet<Integer> set2 = new TreeSet<>(set1.castToSortedSet());
Assert.assertTrue(set1.containsAllArguments(set1.toArray()));
Verify.assertThrows(NullPointerException.class, () -> set1.containsAllArguments(null, null));
Verify.assertThrows(NullPointerException.class, () -> set2.containsAll(FastList.newListWith(null, null)));
}
@Test
public void containsAllIterable()
{
ImmutableSortedSet<Integer> set1 = this.classUnderTest();
SortedSet<Integer> set2 = new TreeSet<>(set1.castToSortedSet());
Assert.assertTrue(set1.containsAllIterable(Interval.oneTo(set1.size())));
Verify.assertThrows(NullPointerException.class, () -> set1.containsAllIterable(FastList.newListWith(null, null)));
Verify.assertThrows(NullPointerException.class, () -> set2.containsAll(FastList.newListWith(null, null)));
}
@Test
public void tap()
{
MutableList<Integer> tapResult = Lists.mutable.of();
ImmutableSortedSet<Integer> collection = this.classUnderTest();
Assert.assertSame(collection, collection.tap(tapResult::add));
Assert.assertEquals(collection.toList(), tapResult);
}
@Test
public void forEach()
{
MutableSet<Integer> result = UnifiedSet.newSet();
ImmutableSortedSet<Integer> collection = this.classUnderTest();
collection.forEach(CollectionAddProcedure.on(result));
Assert.assertEquals(collection, result);
}
@Test
public void forEachWith()
{
MutableList<Integer> result = Lists.mutable.of();
ImmutableSortedSet<Integer> set = this.classUnderTest();
set.forEachWith((argument1, argument2) -> result.add(argument1 + argument2), 0);
Verify.assertListsEqual(result, set.toList());
}
@Test
public void forEachWithIndex()
{
MutableList<Integer> result = Lists.mutable.of();
ImmutableSortedSet<Integer> set = this.classUnderTest();
set.forEachWithIndex((object, index) -> result.add(object));
Verify.assertListsEqual(result, set.toList());
}
@Test
public void select()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
Verify.assertIterableEmpty(integers.select(Predicates.greaterThan(integers.size())));
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(Comparators.<Integer>reverseNaturalOrder(), Interval.oneTo(integers.size() - 1)),
integers.select(Predicates.lessThan(integers.size())).castToSortedSet());
}
@Test
public void selectWith()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
Verify.assertIterableEmpty(integers.selectWith(Predicates2.<Integer>greaterThan(), integers.size()));
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(Comparators.<Integer>reverseNaturalOrder(), Interval.oneTo(integers.size() - 1)),
integers.selectWith(Predicates2.<Integer>lessThan(), integers.size()).castToSortedSet());
}
@Test
public void selectToTarget()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Verify.assertListsEqual(integers.toList(),
integers.select(Predicates.lessThan(integers.size() + 1), FastList.<Integer>newList()));
Verify.assertEmpty(
integers.select(Predicates.greaterThan(integers.size()), FastList.<Integer>newList()));
}
@Test
public void reject()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
Verify.assertEmpty(
FastList.newList(integers.reject(Predicates.lessThan(integers.size() + 1))));
Verify.assertSortedSetsEqual(integers.castToSortedSet(),
integers.reject(Predicates.greaterThan(integers.size())).castToSortedSet());
}
@Test
public void rejectWith()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
Verify.assertIterableEmpty(integers.rejectWith(Predicates2.<Integer>lessThanOrEqualTo(), integers.size()));
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(Comparators.<Integer>reverseNaturalOrder(), Interval.oneTo(integers.size() - 1)),
integers.rejectWith(Predicates2.<Integer>greaterThanOrEqualTo(), integers.size()).castToSortedSet());
}
@Test
public void rejectToTarget()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Verify.assertEmpty(
integers.reject(Predicates.lessThan(integers.size() + 1), FastList.<Integer>newList()));
Verify.assertListsEqual(integers.toList(),
integers.reject(Predicates.greaterThan(integers.size()), FastList.<Integer>newList()));
}
@Test
public void selectInstancesOf()
{
ImmutableSortedSet<Integer> set = this.classUnderTest(Collections.<Integer>reverseOrder());
Assert.assertEquals(set, set.selectInstancesOf(Integer.class));
Verify.assertIterableEmpty(set.selectInstancesOf(Double.class));
Assert.assertEquals(Collections.<Integer>reverseOrder(), set.selectInstancesOf(Integer.class).comparator());
Assert.assertEquals(Collections.<Double>reverseOrder(), set.selectInstancesOf(Double.class).comparator());
}
@Test
public void partition()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
PartitionImmutableSortedSet<Integer> partition = integers.partition(Predicates.greaterThan(integers.size()));
Verify.assertIterableEmpty(partition.getSelected());
Assert.assertEquals(integers, partition.getRejected());
Assert.assertEquals(Collections.<Integer>reverseOrder(), partition.getSelected().comparator());
Assert.assertEquals(Collections.<Integer>reverseOrder(), partition.getRejected().comparator());
}
@Test
public void partitionWith()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
PartitionImmutableSortedSet<Integer> partition = integers.partitionWith(Predicates2.<Integer>greaterThan(), integers.size());
Verify.assertIterableEmpty(partition.getSelected());
Assert.assertEquals(integers, partition.getRejected());
Assert.assertEquals(Collections.<Integer>reverseOrder(), partition.getSelected().comparator());
Assert.assertEquals(Collections.<Integer>reverseOrder(), partition.getRejected().comparator());
}
@Test
public void partitionWhile()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
PartitionImmutableSortedSet<Integer> partition1 = integers.partitionWhile(Predicates.greaterThan(integers.size()));
Verify.assertIterableEmpty(partition1.getSelected());
Assert.assertEquals(integers, partition1.getRejected());
Assert.assertEquals(Collections.<Integer>reverseOrder(), partition1.getSelected().comparator());
Assert.assertEquals(Collections.<Integer>reverseOrder(), partition1.getRejected().comparator());
PartitionImmutableSortedSet<Integer> partition2 = integers.partitionWhile(Predicates.lessThanOrEqualTo(integers.size()));
Assert.assertEquals(integers, partition2.getSelected());
Verify.assertIterableEmpty(partition2.getRejected());
}
@Test
public void takeWhile()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
ImmutableSortedSet<Integer> take1 = integers.takeWhile(Predicates.greaterThan(integers.size()));
Verify.assertIterableEmpty(take1);
Assert.assertEquals(Collections.<Integer>reverseOrder(), take1.comparator());
ImmutableSortedSet<Integer> take2 = integers.takeWhile(Predicates.lessThanOrEqualTo(integers.size()));
Assert.assertEquals(integers, take2);
Assert.assertEquals(Collections.<Integer>reverseOrder(), take2.comparator());
}
@Test
public void dropWhile()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
ImmutableSortedSet<Integer> drop1 = integers.dropWhile(Predicates.greaterThan(integers.size()));
Assert.assertEquals(integers, drop1);
Assert.assertEquals(Collections.<Integer>reverseOrder(), drop1.comparator());
ImmutableSortedSet<Integer> drop2 = integers.dropWhile(Predicates.lessThanOrEqualTo(integers.size()));
Verify.assertIterableEmpty(drop2);
Assert.assertEquals(Collections.<Integer>reverseOrder(), drop2.comparator());
}
@Test
public void collect()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
Verify.assertListsEqual(integers.toList(), integers.collect(Functions.getIntegerPassThru()).castToList());
}
@Test
public void collectWith()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
Verify.assertListsEqual(integers.toList(), integers.collectWith((value, parameter) -> value / parameter, 1).castToList());
}
@Test
public void collectToTarget()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Assert.assertEquals(integers, integers.collect(Functions.getIntegerPassThru(), UnifiedSet.<Integer>newSet()));
Verify.assertListsEqual(integers.toList(),
integers.collect(Functions.getIntegerPassThru(), FastList.<Integer>newList()));
}
@Test
public void flatCollect()
{
ImmutableList<String> actual = this.classUnderTest(Collections.<Integer>reverseOrder()).flatCollect(integer -> Lists.fixedSize.of(String.valueOf(integer)));
ImmutableList<String> expected = this.classUnderTest(Collections.<Integer>reverseOrder()).collect(String::valueOf);
Assert.assertEquals(expected, actual);
Verify.assertListsEqual(expected.toList(), actual.toList());
}
@Test
public void flatCollectWithTarget()
{
MutableSet<String> actual = this.classUnderTest().flatCollect(integer -> Lists.fixedSize.of(String.valueOf(integer)), UnifiedSet.<String>newSet());
ImmutableList<String> expected = this.classUnderTest().collect(String::valueOf);
Verify.assertSetsEqual(expected.toSet(), actual);
}
@Test
public void zip()
{
ImmutableSortedSet<Integer> immutableSet = this.classUnderTest(Collections.<Integer>reverseOrder());
List<Object> nulls = Collections.nCopies(immutableSet.size(), null);
List<Object> nullsPlusOne = Collections.nCopies(immutableSet.size() + 1, null);
List<Object> nullsMinusOne = Collections.nCopies(immutableSet.size() - 1, null);
ImmutableList<Pair<Integer, Object>> pairs = immutableSet.zip(nulls);
Assert.assertEquals(immutableSet.toList(), pairs.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne));
Verify.assertListsEqual(FastList.newList(Interval.fromTo(immutableSet.size(), 1)), pairs.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).toList());
Assert.assertEquals(FastList.newList(nulls), pairs.collect((Function<Pair<?, Object>, Object>) Pair::getTwo));
ImmutableList<Pair<Integer, Object>> pairsPlusOne = immutableSet.zip(nullsPlusOne);
Assert.assertEquals(immutableSet.toList(), pairsPlusOne.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne));
Verify.assertListsEqual(FastList.newList(Interval.fromTo(immutableSet.size(), 1)),
pairsPlusOne.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).castToList());
Assert.assertEquals(FastList.newList(nulls), pairsPlusOne.collect((Function<Pair<?, Object>, Object>) Pair::getTwo));
ImmutableList<Pair<Integer, Object>> pairsMinusOne = immutableSet.zip(nullsMinusOne);
Verify.assertListsEqual(FastList.newList(Interval.fromTo(immutableSet.size(), 2)),
pairsMinusOne.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).castToList());
Assert.assertEquals(immutableSet.zip(nulls), immutableSet.zip(nulls, FastList.<Pair<Integer, Object>>newList()));
FastList<Holder> holders = FastList.newListWith(new Holder(1), new Holder(2), new Holder(3));
ImmutableList<Pair<Integer, Holder>> zipped = immutableSet.zip(holders);
Verify.assertSize(3, zipped.castToList());
AbstractImmutableSortedSetTestCase.Holder two = new Holder(-1);
AbstractImmutableSortedSetTestCase.Holder two1 = new Holder(-1);
Assert.assertEquals(Tuples.pair(10, two1), zipped.newWith(Tuples.pair(10, two)).getLast());
Assert.assertEquals(Tuples.pair(1, new Holder(3)), this.classUnderTest().zip(holders.reverseThis()).getFirst());
}
@Test
public void zipWithIndex()
{
ImmutableSortedSet<Integer> immutableSet = this.classUnderTest(Collections.<Integer>reverseOrder());
ImmutableSortedSet<Pair<Integer, Integer>> pairs = immutableSet.zipWithIndex();
Assert.assertEquals(immutableSet.toList(), pairs.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne));
Assert.assertEquals(
Interval.zeroTo(immutableSet.size() - 1).toList(),
pairs.collect((Function<Pair<?, Integer>, Integer>) Pair::getTwo));
Assert.assertEquals(
immutableSet.zipWithIndex(),
immutableSet.zipWithIndex(UnifiedSet.<Pair<Integer, Integer>>newSet()));
Verify.assertListsEqual(TreeSortedSet.newSet(Collections.<Integer>reverseOrder(), Interval.oneTo(immutableSet.size())).toList(),
pairs.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).toList());
}
@Test(expected = IllegalArgumentException.class)
public void chunk_zero_throws()
{
this.classUnderTest().chunk(0);
}
@Test
public void chunk_large_size()
{
Assert.assertEquals(this.classUnderTest(), this.classUnderTest().chunk(10).getFirst());
Verify.assertInstanceOf(ImmutableSortedSet.class, this.classUnderTest().chunk(10).getFirst());
}
@Test
public void detect()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Assert.assertEquals(Integer.valueOf(1), integers.detect(Predicates.equal(1)));
Assert.assertNull(integers.detect(Predicates.equal(integers.size() + 1)));
}
@Test
public void detectWith()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Assert.assertEquals(Integer.valueOf(1), integers.detectWith(Object::equals, Integer.valueOf(1)));
Assert.assertNull(integers.detectWith(Object::equals, Integer.valueOf(integers.size() + 1)));
}
@Test
public void detectWithIfNone()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Function0<Integer> function = new PassThruFunction0<>(integers.size() + 1);
Integer sum = Integer.valueOf(integers.size() + 1);
Assert.assertEquals(Integer.valueOf(1), integers.detectWithIfNone(Object::equals, Integer.valueOf(1), function));
Assert.assertEquals(Integer.valueOf(integers.size() + 1), integers.detectWithIfNone(Object::equals, sum, function));
}
@Test
public void detectIfNone()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Function0<Integer> function = new PassThruFunction0<>(integers.size() + 1);
Assert.assertEquals(Integer.valueOf(1), integers.detectIfNone(Predicates.equal(1), function));
Assert.assertEquals(Integer.valueOf(integers.size() + 1), integers.detectIfNone(Predicates.equal(integers.size() + 1), function));
}
@Test
public void detectIndex()
{
ImmutableSortedSet<Integer> integers1 = this.classUnderTest();
Assert.assertEquals(1, integers1.detectIndex(integer -> integer % 2 == 0));
Assert.assertEquals(0, integers1.detectIndex(integer -> integer % 2 != 0));
Assert.assertEquals(-1, integers1.detectIndex(integer -> integer % 5 == 0));
ImmutableSortedSet<Integer> integers2 = this.classUnderTest(Comparators.reverseNaturalOrder());
Assert.assertEquals(0, integers2.detectIndex(integer -> integer % 2 == 0));
Assert.assertEquals(1, integers2.detectIndex(integer -> integer % 2 != 0));
Assert.assertEquals(-1, integers2.detectIndex(integer -> integer % 5 == 0));
}
@Test
public void corresponds()
{
ImmutableSortedSet<Integer> integers1 = this.classUnderTest();
Assert.assertFalse(integers1.corresponds(this.classUnderTest().newWith(100), Predicates2.alwaysTrue()));
ImmutableList<Integer> integers2 = integers1.collect(integers -> integers + 1);
Assert.assertTrue(integers1.corresponds(integers2, Predicates2.lessThan()));
Assert.assertFalse(integers1.corresponds(integers2, Predicates2.greaterThan()));
ImmutableSortedSet<Integer> integers3 = this.classUnderTest(Comparators.reverseNaturalOrder());
Assert.assertFalse(integers3.corresponds(integers1, Predicates2.equal()));
}
@Test
public void allSatisfy()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Assert.assertTrue(integers.allSatisfy(Integer.class::isInstance));
Assert.assertFalse(integers.allSatisfy(Integer.valueOf(0)::equals));
}
@Test
public void anySatisfy()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Assert.assertFalse(integers.anySatisfy(String.class::isInstance));
Assert.assertTrue(integers.anySatisfy(Integer.class::isInstance));
}
@Test
public void count()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Assert.assertEquals(integers.size(), integers.count(Integer.class::isInstance));
Assert.assertEquals(0, integers.count(String.class::isInstance));
}
@Test
public void collectIf()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
Verify.assertListsEqual(integers.toList(), integers.collectIf(Integer.class::isInstance, Functions.getIntegerPassThru()).toList());
}
@Test
public void collectIfToTarget()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Verify.assertSetsEqual(integers.toSet(), integers.collectIf(Integer.class::isInstance, Functions.getIntegerPassThru(), UnifiedSet.<Integer>newSet()));
}
@Test
public void getFirst()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Assert.assertEquals(Integer.valueOf(1), integers.getFirst());
ImmutableSortedSet<Integer> revInt = this.classUnderTest(Collections.<Integer>reverseOrder());
Assert.assertEquals(Integer.valueOf(revInt.size()), revInt.getFirst());
}
@Test
public void getLast()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Assert.assertEquals(Integer.valueOf(integers.size()), integers.getLast());
ImmutableSortedSet<Integer> revInt = this.classUnderTest(Collections.<Integer>reverseOrder());
Assert.assertEquals(Integer.valueOf(1), revInt.getLast());
}
@Test
public void isEmpty()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
Assert.assertFalse(set.isEmpty());
Assert.assertTrue(set.notEmpty());
}
@Test
public void iterator()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; iterator.hasNext(); i++)
{
Integer integer = iterator.next();
Assert.assertEquals(i + 1, integer.intValue());
}
Verify.assertThrows(NoSuchElementException.class, (Runnable) iterator::next);
Iterator<Integer> intItr = integers.iterator();
intItr.next();
Verify.assertThrows(UnsupportedOperationException.class, intItr::remove);
}
@Test
public void injectInto()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
Integer result = integers.injectInto(0, AddFunction.INTEGER);
Assert.assertEquals(FastList.newList(integers).injectInto(0, AddFunction.INTEGER_TO_INT), result.intValue());
}
@Test
public void toArray()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
MutableList<Integer> copy = FastList.newList(integers);
Assert.assertArrayEquals(integers.toArray(), copy.toArray());
Assert.assertArrayEquals(integers.toArray(new Integer[integers.size()]), copy.toArray(new Integer[integers.size()]));
}
@Test
public void testToString()
{
Assert.assertEquals(FastList.newList(this.classUnderTest()).toString(), this.classUnderTest().toString());
}
@Test
public void makeString()
{
Assert.assertEquals(FastList.newList(this.classUnderTest()).makeString(), this.classUnderTest().makeString());
}
@Test
public void appendString()
{
Appendable builder = new StringBuilder();
this.classUnderTest().appendString(builder);
Assert.assertEquals(FastList.newList(this.classUnderTest()).makeString(), builder.toString());
}
@Test
public void toList()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
MutableList<Integer> list = integers.toList();
Verify.assertEqualsAndHashCode(FastList.newList(integers), list);
}
@Test
public void toSortedList()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
MutableList<Integer> copy = FastList.newList(integers);
MutableList<Integer> list = integers.toSortedList(Collections.<Integer>reverseOrder());
Assert.assertEquals(copy.sortThis(Collections.<Integer>reverseOrder()), list);
MutableList<Integer> list2 = integers.toSortedList();
Verify.assertListsEqual(copy.sortThis(), list2);
}
@Test
public void toSortedListBy()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
MutableList<Integer> list = integers.toSortedListBy(String::valueOf);
Assert.assertEquals(integers.toList(), list);
}
@Test
public void toSortedSet()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
MutableSortedSet<Integer> set = integers.toSortedSet();
Verify.assertSortedSetsEqual(TreeSortedSet.newSetWith(1, 2, 3, 4), set);
}
@Test
public void toSortedSetWithComparator()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
MutableSortedSet<Integer> set = integers.toSortedSet(Collections.<Integer>reverseOrder());
Assert.assertEquals(integers.toSet(), set);
Assert.assertEquals(integers.toSortedList(Comparators.<Integer>reverseNaturalOrder()), set.toList());
}
@Test
public void toSortedSetBy()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
MutableSortedSet<Integer> set = integers.toSortedSetBy(String::valueOf);
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(integers), set);
}
@Test
public void toSortedMap()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
MutableSortedMap<Integer, String> map = integers.toSortedMap(Functions.getIntegerPassThru(), String::valueOf);
Verify.assertMapsEqual(integers.toMap(Functions.getIntegerPassThru(), String::valueOf), map);
Verify.assertListsEqual(Interval.oneTo(integers.size()), map.keySet().toList());
}
@Test
public void toSortedMap_with_comparator()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest();
MutableSortedMap<Integer, String> map = integers.toSortedMap(Comparators.<Integer>reverseNaturalOrder(),
Functions.getIntegerPassThru(), String::valueOf);
Verify.assertMapsEqual(integers.toMap(Functions.getIntegerPassThru(), String::valueOf), map);
Verify.assertListsEqual(Interval.fromTo(integers.size(), 1), map.keySet().toList());
}
@Test
public void forLoop()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
for (Integer each : set)
{
Assert.assertNotNull(each);
}
}
@Test(expected = UnsupportedOperationException.class)
public void iteratorRemove()
{
this.classUnderTest().iterator().remove();
}
@Test(expected = UnsupportedOperationException.class)
public void add()
{
this.classUnderTest().castToSortedSet().add(1);
}
@Test(expected = UnsupportedOperationException.class)
public void remove()
{
this.classUnderTest().castToSortedSet().remove(Integer.valueOf(1));
}
@Test(expected = UnsupportedOperationException.class)
public void clear()
{
this.classUnderTest().castToSortedSet().clear();
}
@Test(expected = UnsupportedOperationException.class)
public void removeAll()
{
this.classUnderTest().castToSortedSet().removeAll(Lists.fixedSize.of());
}
@Test(expected = UnsupportedOperationException.class)
public void retainAll()
{
this.classUnderTest().castToSortedSet().retainAll(Lists.fixedSize.of());
}
@Test(expected = UnsupportedOperationException.class)
public void addAll()
{
this.classUnderTest().castToSortedSet().addAll(Lists.fixedSize.<Integer>of());
}
@Test
public void min()
{
Assert.assertEquals(Integer.valueOf(1), this.classUnderTest().min(Integer::compareTo));
}
@Test
public void max()
{
Assert.assertEquals(Integer.valueOf(1), this.classUnderTest().max(Comparators.reverse(Integer::compareTo)));
}
@Test
public void min_without_comparator()
{
Assert.assertEquals(Integer.valueOf(1), this.classUnderTest().min());
}
@Test
public void max_without_comparator()
{
Assert.assertEquals(Integer.valueOf(this.classUnderTest().size()), this.classUnderTest().max());
}
@Test
public void minBy()
{
Assert.assertEquals(Integer.valueOf(1), this.classUnderTest().minBy(String::valueOf));
}
@Test
public void maxBy()
{
Assert.assertEquals(Integer.valueOf(this.classUnderTest().size()), this.classUnderTest().maxBy(String::valueOf));
}
@Test
public void groupBy()
{
ImmutableSortedSet<Integer> undertest = this.classUnderTest();
ImmutableSortedSetMultimap<Integer, Integer> actual = undertest.groupBy(Functions.<Integer>getPassThru());
ImmutableSortedSetMultimap<Integer, Integer> expected = TreeSortedSet.newSet(undertest).groupBy(Functions.<Integer>getPassThru()).toImmutable();
Assert.assertEquals(expected, actual);
}
@Test
public void groupByEach()
{
ImmutableSortedSet<Integer> undertest = this.classUnderTest(Collections.<Integer>reverseOrder());
NegativeIntervalFunction function = new NegativeIntervalFunction();
ImmutableSortedSetMultimap<Integer, Integer> actual = undertest.groupByEach(function);
ImmutableSortedSetMultimap<Integer, Integer> expected = TreeSortedSet.newSet(undertest).groupByEach(function).toImmutable();
Assert.assertEquals(expected, actual);
}
@Test
public void groupByWithTarget()
{
ImmutableSortedSet<Integer> undertest = this.classUnderTest();
TreeSortedSetMultimap<Integer, Integer> actual = undertest.groupBy(Functions.<Integer>getPassThru(), TreeSortedSetMultimap.<Integer, Integer>newMultimap());
TreeSortedSetMultimap<Integer, Integer> expected = TreeSortedSet.newSet(undertest).groupBy(Functions.<Integer>getPassThru());
Assert.assertEquals(expected, actual);
}
@Test
public void groupByEachWithTarget()
{
ImmutableSortedSet<Integer> undertest = this.classUnderTest();
NegativeIntervalFunction function = new NegativeIntervalFunction();
TreeSortedSetMultimap<Integer, Integer> actual = undertest.groupByEach(function, TreeSortedSetMultimap.<Integer, Integer>newMultimap());
TreeSortedSetMultimap<Integer, Integer> expected = TreeSortedSet.newSet(undertest).groupByEach(function);
Assert.assertEquals(expected, actual);
}
@Test
public void groupByUniqueKey()
{
Assert.assertEquals(
this.classUnderTest().toBag().groupByUniqueKey(id -> id),
this.classUnderTest().groupByUniqueKey(id -> id));
}
@Test(expected = IllegalStateException.class)
public void groupByUniqueKey_throws()
{
this.classUnderTest(Collections.<Integer>reverseOrder()).groupByUniqueKey(Functions.getFixedValue(1));
}
@Test
public void groupByUniqueKey_target()
{
Assert.assertEquals(this.classUnderTest().groupByUniqueKey(id -> id), this.classUnderTest().groupByUniqueKey(id -> id, UnifiedMap.<Integer, Integer>newMap()));
}
@Test(expected = IllegalStateException.class)
public void groupByUniqueKey_target_throws()
{
this.classUnderTest(Collections.<Integer>reverseOrder()).groupByUniqueKey(id -> id, UnifiedMap.newWithKeysValues(2, 2));
}
@Test
public void union()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
ImmutableSortedSet<Integer> union = set.union(UnifiedSet.newSet(Interval.fromTo(set.size(), set.size() + 3)));
Verify.assertSize(set.size() + 3, union.castToSortedSet());
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(Interval.oneTo(set.size() + 3)), union.castToSortedSet());
Assert.assertEquals(set, set.union(UnifiedSet.<Integer>newSet()));
}
@Test
public void unionInto()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
MutableSet<Integer> union = set.unionInto(UnifiedSet.newSet(Interval.fromTo(set.size(), set.size() + 3)), UnifiedSet.<Integer>newSet());
Verify.assertSize(set.size() + 3, union);
Assert.assertTrue(union.containsAllIterable(Interval.oneTo(set.size() + 3)));
Assert.assertEquals(set, set.unionInto(UnifiedSet.<Integer>newSetWith(), UnifiedSet.<Integer>newSet()));
}
@Test
public void intersect()
{
ImmutableSortedSet<Integer> set = this.classUnderTest(Collections.<Integer>reverseOrder());
ImmutableSortedSet<Integer> intersect = set.intersect(UnifiedSet.newSet(Interval.oneTo(set.size() + 2)));
Verify.assertSize(set.size(), intersect.castToSortedSet());
Verify.assertSortedSetsEqual(set.castToSortedSet(), intersect.castToSortedSet());
}
@Test
public void intersectInto()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
MutableSet<Integer> intersect = set.intersectInto(UnifiedSet.newSet(Interval.oneTo(set.size() + 2)), UnifiedSet.<Integer>newSet());
Verify.assertSize(set.size(), intersect);
Assert.assertEquals(set, intersect);
Verify.assertEmpty(set.intersectInto(UnifiedSet.newSet(Interval.fromTo(set.size() + 1, set.size() + 4)), UnifiedSet.<Integer>newSet()));
}
@Test
public void difference()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
ImmutableSortedSet<Integer> difference = set.difference(UnifiedSet.newSet(Interval.fromTo(2, set.size() + 1)));
Verify.assertSortedSetsEqual(TreeSortedSet.newSetWith(1), difference.castToSortedSet());
ImmutableSortedSet<Integer> difference2 = set.difference(UnifiedSet.newSet(Interval.fromTo(2, set.size() + 2)));
Verify.assertSortedSetsEqual(TreeSortedSet.newSetWith(1), difference2.castToSortedSet());
}
@Test
public void differenceInto()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
MutableSet<Integer> difference = set.differenceInto(UnifiedSet.newSet(Interval.fromTo(2, set.size() + 1)), UnifiedSet.<Integer>newSet());
Verify.assertSetsEqual(UnifiedSet.newSetWith(1), difference);
}
@Test
public void symmetricDifference()
{
ImmutableSortedSet<Integer> set = this.classUnderTest(Collections.<Integer>reverseOrder());
ImmutableSortedSet<Integer> difference = set.symmetricDifference(UnifiedSet.newSet(Interval.fromTo(2, set.size() + 1)));
Verify.assertSortedSetsEqual(TreeSortedSet.newSetWith(Comparators.<Integer>reverseNaturalOrder(), 1, set.size() + 1),
difference.castToSortedSet());
}
@Test
public void symmetricDifferenceInto()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
MutableSet<Integer> difference = set.symmetricDifferenceInto(UnifiedSet.newSet(Interval.fromTo(2, set.size() + 1)), UnifiedSet.<Integer>newSet());
Verify.assertSetsEqual(UnifiedSet.newSetWith(1, set.size() + 1), difference);
}
@Test
public void isSubsetOf()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
Assert.assertTrue(set.isSubsetOf(set));
}
@Test
public void isProperSubsetOf()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
Assert.assertTrue(set.isProperSubsetOf(Interval.oneTo(set.size() + 1).toSet()));
Assert.assertFalse(set.isProperSubsetOf(set));
}
@Test
public void powerSet()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
ImmutableSortedSet<SortedSetIterable<Integer>> powerSet = set.powerSet();
Verify.assertSize((int) StrictMath.pow(2, set.size()), powerSet.castToSortedSet());
Verify.assertContains(UnifiedSet.<String>newSet(), powerSet.toSet());
Verify.assertContains(set, powerSet.toSet());
Verify.assertInstanceOf(ImmutableSortedSet.class, powerSet);
Verify.assertInstanceOf(ImmutableSortedSet.class, powerSet.getLast());
}
@Test
public void cartesianProduct()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
LazyIterable<Pair<Integer, Integer>> cartesianProduct = set.cartesianProduct(UnifiedSet.newSet(Interval.oneTo(set.size())));
Assert.assertEquals(set.size() * set.size(), cartesianProduct.size());
Assert.assertEquals(set, cartesianProduct
.select(Predicates.attributeEqual((Function<Pair<?, Integer>, Integer>) Pair::getTwo, 1))
.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).toSet());
}
@Test
public void distinct()
{
ImmutableSortedSet<Integer> set1 = this.classUnderTest();
Assert.assertSame(set1, set1.distinct());
ImmutableSortedSet<Integer> set2 = this.classUnderTest(Comparators.reverseNaturalOrder());
Assert.assertSame(set2, set2.distinct());
}
@Test
public void indexOf()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
Assert.assertEquals(0, integers.indexOf(4));
Assert.assertEquals(1, integers.indexOf(3));
Assert.assertEquals(2, integers.indexOf(2));
Assert.assertEquals(3, integers.indexOf(1));
Assert.assertEquals(-1, integers.indexOf(0));
Assert.assertEquals(-1, integers.indexOf(5));
}
@Test
public void forEachFromTo()
{
MutableList<Integer> result = FastList.newList();
ImmutableSortedSet<Integer> integers = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
integers.forEach(1, 2, result::add);
Assert.assertEquals(Lists.immutable.with(3, 2), result);
MutableList<Integer> result2 = FastList.newList();
integers.forEach(0, 3, result2::add);
Assert.assertEquals(Lists.immutable.with(4, 3, 2, 1), result2);
Verify.assertThrows(IndexOutOfBoundsException.class, () -> integers.forEach(-1, 0, result::add));
Verify.assertThrows(IndexOutOfBoundsException.class, () -> integers.forEach(0, -1, result::add));
Verify.assertThrows(IllegalArgumentException.class, () -> integers.forEach(2, 1, result::add));
}
@Test
public void forEachWithIndexWithFromTo()
{
ImmutableSortedSet<Integer> integers = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
StringBuilder builder = new StringBuilder();
integers.forEachWithIndex(1, 2, (each, index) -> builder.append(each).append(index));
Assert.assertEquals("3122", builder.toString());
MutableList<Integer> result2 = Lists.mutable.of();
integers.forEachWithIndex(0, 3, new AddToList(result2));
Assert.assertEquals(Lists.immutable.with(4, 3, 2, 1), result2);
Verify.assertThrows(IndexOutOfBoundsException.class, () -> integers.forEachWithIndex(-1, 0, new AddToList(result2)));
Verify.assertThrows(IndexOutOfBoundsException.class, () -> integers.forEachWithIndex(0, -1, new AddToList(result2)));
Verify.assertThrows(IllegalArgumentException.class, () -> integers.forEachWithIndex(2, 1, new AddToList(result2)));
}
@Test
public void toStack()
{
ImmutableSortedSet<Integer> set = this.classUnderTest(Comparators.reverseNaturalOrder());
Assert.assertEquals(ArrayStack.newStackWith(4, 3, 2, 1), set.toStack());
}
@Test
public void toImmutable()
{
ImmutableSortedSet<Integer> set = this.classUnderTest();
ImmutableSortedSet<Integer> actual = set.toImmutable();
Assert.assertEquals(set, actual);
Assert.assertSame(set, actual);
}
@Test
public void take()
{
ImmutableSortedSet<Integer> integers1 = this.classUnderTest();
Assert.assertEquals(SortedSets.immutable.of(integers1.comparator()), integers1.take(0));
Assert.assertSame(integers1.comparator(), integers1.take(0).comparator());
Assert.assertEquals(SortedSets.immutable.of(integers1.comparator(), 1, 2, 3), integers1.take(3));
Assert.assertSame(integers1.comparator(), integers1.take(3).comparator());
Assert.assertEquals(SortedSets.immutable.of(integers1.comparator(), 1, 2, 3), integers1.take(integers1.size() - 1));
ImmutableSortedSet<Integer> integers2 = this.classUnderTest(Comparators.reverseNaturalOrder());
Assert.assertSame(integers2, integers2.take(integers2.size()));
Assert.assertSame(integers2, integers2.take(10));
Assert.assertSame(integers2, integers2.take(Integer.MAX_VALUE));
}
@Test(expected = IllegalArgumentException.class)
public void take_throws()
{
this.classUnderTest().take(-1);
}
@Test
public void drop()
{
ImmutableSortedSet<Integer> integers1 = this.classUnderTest();
Assert.assertSame(integers1, integers1.drop(0));
Assert.assertSame(integers1.comparator(), integers1.drop(0).comparator());
Assert.assertEquals(SortedSets.immutable.of(integers1.comparator(), 4), integers1.drop(3));
Assert.assertSame(integers1.comparator(), integers1.drop(3).comparator());
Assert.assertEquals(SortedSets.immutable.of(integers1.comparator(), 4), integers1.drop(integers1.size() - 1));
ImmutableSortedSet<Integer> expectedSet = SortedSets.immutable.of(Comparators.reverseNaturalOrder());
ImmutableSortedSet<Integer> integers2 = this.classUnderTest(Comparators.reverseNaturalOrder());
Assert.assertEquals(expectedSet, integers2.drop(integers2.size()));
Assert.assertEquals(expectedSet, integers2.drop(10));
Assert.assertEquals(expectedSet, integers2.drop(Integer.MAX_VALUE));
}
@Test(expected = IllegalArgumentException.class)
public void drop_throws()
{
this.classUnderTest().drop(-1);
}
@Test
public abstract void subSet();
@Test
public abstract void headSet();
@Test
public abstract void tailSet();
@Test
public abstract void collectBoolean();
@Test
public abstract void collectByte();
@Test
public abstract void collectChar();
@Test
public abstract void collectDouble();
@Test
public abstract void collectFloat();
@Test
public abstract void collectInt();
@Test
public abstract void collectLong();
@Test
public abstract void collectShort();
private static final class Holder
{
private final int number;
private Holder(int i)
{
this.number = i;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || this.getClass() != o.getClass())
{
return false;
}
Holder holder = (Holder) o;
return this.number == holder.number;
}
@Override
public int hashCode()
{
return this.number;
}
@Override
public String toString()
{
return String.valueOf(this.number);
}
}
}
| 18,605 |
1,318 | <filename>venv/Lib/site-packages/defusedxml/xmlrpc.py
# defusedxml
#
# Copyright (c) 2013 by <NAME> <<EMAIL>>
# Licensed to PSF under a Contributor Agreement.
# See https://www.python.org/psf/license for licensing details.
"""Defused xmlrpclib
Also defuses gzip bomb
"""
from __future__ import print_function, absolute_import
import io
from .common import DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden, PY3
if PY3:
__origin__ = "xmlrpc.client"
from xmlrpc.client import ExpatParser
from xmlrpc import client as xmlrpc_client
from xmlrpc import server as xmlrpc_server
from xmlrpc.client import gzip_decode as _orig_gzip_decode
from xmlrpc.client import GzipDecodedResponse as _OrigGzipDecodedResponse
else:
__origin__ = "xmlrpclib"
from xmlrpclib import ExpatParser
import xmlrpclib as xmlrpc_client
xmlrpc_server = None
from xmlrpclib import gzip_decode as _orig_gzip_decode
from xmlrpclib import GzipDecodedResponse as _OrigGzipDecodedResponse
try:
import gzip
except ImportError: # pragma: no cover
gzip = None
# Limit maximum request size to prevent resource exhaustion DoS
# Also used to limit maximum amount of gzip decoded data in order to prevent
# decompression bombs
# A value of -1 or smaller disables the limit
MAX_DATA = 30 * 1024 * 1024 # 30 MB
def defused_gzip_decode(data, limit=None):
"""gzip encoded data -> unencoded data
Decode data using the gzip content encoding as described in RFC 1952
"""
if not gzip: # pragma: no cover
raise NotImplementedError
if limit is None:
limit = MAX_DATA
f = io.BytesIO(data)
gzf = gzip.GzipFile(mode="rb", fileobj=f)
try:
if limit < 0: # no limit
decoded = gzf.read()
else:
decoded = gzf.read(limit + 1)
except IOError: # pragma: no cover
raise ValueError("invalid data")
f.close()
gzf.close()
if limit >= 0 and len(decoded) > limit:
raise ValueError("max gzipped payload length exceeded")
return decoded
class DefusedGzipDecodedResponse(gzip.GzipFile if gzip else object):
"""a file-like object to decode a response encoded with the gzip
method, as described in RFC 1952.
"""
def __init__(self, response, limit=None):
# response doesn't support tell() and read(), required by
# GzipFile
if not gzip: # pragma: no cover
raise NotImplementedError
self.limit = limit = limit if limit is not None else MAX_DATA
if limit < 0: # no limit
data = response.read()
self.readlength = None
else:
data = response.read(limit + 1)
self.readlength = 0
if limit >= 0 and len(data) > limit:
raise ValueError("max payload length exceeded")
self.stringio = io.BytesIO(data)
gzip.GzipFile.__init__(self, mode="rb", fileobj=self.stringio)
def read(self, n):
if self.limit >= 0:
left = self.limit - self.readlength
n = min(n, left + 1)
data = gzip.GzipFile.read(self, n)
self.readlength += len(data)
if self.readlength > self.limit:
raise ValueError("max payload length exceeded")
return data
else:
return gzip.GzipFile.read(self, n)
def close(self):
gzip.GzipFile.close(self)
self.stringio.close()
class DefusedExpatParser(ExpatParser):
def __init__(self, target, forbid_dtd=False, forbid_entities=True, forbid_external=True):
ExpatParser.__init__(self, target)
self.forbid_dtd = forbid_dtd
self.forbid_entities = forbid_entities
self.forbid_external = forbid_external
parser = self._parser
if self.forbid_dtd:
parser.StartDoctypeDeclHandler = self.defused_start_doctype_decl
if self.forbid_entities:
parser.EntityDeclHandler = self.defused_entity_decl
parser.UnparsedEntityDeclHandler = self.defused_unparsed_entity_decl
if self.forbid_external:
parser.ExternalEntityRefHandler = self.defused_external_entity_ref_handler
def defused_start_doctype_decl(self, name, sysid, pubid, has_internal_subset):
raise DTDForbidden(name, sysid, pubid)
def defused_entity_decl(
self, name, is_parameter_entity, value, base, sysid, pubid, notation_name
):
raise EntitiesForbidden(name, value, base, sysid, pubid, notation_name)
def defused_unparsed_entity_decl(self, name, base, sysid, pubid, notation_name):
# expat 1.2
raise EntitiesForbidden(name, None, base, sysid, pubid, notation_name) # pragma: no cover
def defused_external_entity_ref_handler(self, context, base, sysid, pubid):
raise ExternalReferenceForbidden(context, base, sysid, pubid)
def monkey_patch():
xmlrpc_client.FastParser = DefusedExpatParser
xmlrpc_client.GzipDecodedResponse = DefusedGzipDecodedResponse
xmlrpc_client.gzip_decode = defused_gzip_decode
if xmlrpc_server:
xmlrpc_server.gzip_decode = defused_gzip_decode
def unmonkey_patch():
xmlrpc_client.FastParser = None
xmlrpc_client.GzipDecodedResponse = _OrigGzipDecodedResponse
xmlrpc_client.gzip_decode = _orig_gzip_decode
if xmlrpc_server:
xmlrpc_server.gzip_decode = _orig_gzip_decode
| 2,196 |
379 | package cc.bitky.clustermanage.netty.message.web;
import cc.bitky.clustermanage.netty.message.MsgType;
import cc.bitky.clustermanage.netty.message.base.BaseMessage;
/**
* 服务器操作远程开锁
*/
public class WebMsgDeployLedStop extends BaseMessage {
public WebMsgDeployLedStop(int groupId, int boxId) {
super(groupId, boxId);
setMsgId(MsgType.SERVER_LED_STOP);
}
}
| 168 |
450 | //===- MsgHandling.h ------------------------------------------------------===//
//
// The ONNC Project
//
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef ONNC_DIAGNOSTIC_MSG_HANDLING_H
#define ONNC_DIAGNOSTIC_MSG_HANDLING_H
#include <onnc/ADT/OwningPtr.h>
#include <onnc/ADT/StringRef.h>
#include <onnc/Diagnostic/Engine.h>
#include <onnc/Diagnostic/MsgHandler.h>
namespace onnc {
/// Program should not pass though this code piece.
diagnostic::MsgHandler unreachable(unsigned int pID);
/// A fatal error. The program should stop immediately.
diagnostic::MsgHandler fatal (unsigned int pID);
/// A normal error. The program tries to run as far as possible.
diagnostic::MsgHandler error (unsigned int pID);
/// A warning. The result of the program is correct.
diagnostic::MsgHandler warning (unsigned int pID);
/// A message for debugging.
diagnostic::MsgHandler debug (unsigned int pID);
/// A message for noting.
diagnostic::MsgHandler note (unsigned int pID);
/// A message that can be ignored in most cases.
diagnostic::MsgHandler ignore (unsigned int pID);
diagnostic::MsgHandler unreachable(StringRef pMessage);
diagnostic::MsgHandler fatal (StringRef pMessage);
diagnostic::MsgHandler error (StringRef pMessage);
diagnostic::MsgHandler warning (StringRef pMessage);
diagnostic::MsgHandler debug (StringRef pMessage);
diagnostic::MsgHandler note (StringRef pMessage);
diagnostic::MsgHandler ignore (StringRef pMessage);
/** \namespace onnc::diagnostic
* \brief classes of diagnostic system
*
* \b diagnostic namespace is the namespace for diagnostic system.
* The most frequent used library of the diagnostic system is
* @ref MsgHandling.h. It provides error-report functions to show
* error messages with appropriate severity. For example:
*
* \code
* #include <onnc/Diagnostic/MsgHandling.h>
*
* using namespace onnc;
* // show "Error parsing JSON file: file.json"
* fatal(fatal_json_parsing) << "file.json";
* \endcode
*
* @ref fatal reads a message ID and print out formatted error message.
*
* There are seven error severities of report functions:
* - @ref unreachable, the program should not run though these code pieces
* - @ref fatal, a fatal error. The program stops immediately.
* - @ref error, a normal error. The program keeps running as far as possible.
* - @ref warning, a warning. The program keeps running and the result is correct.
* - @ref debug, a message for debugging.
* - @ref note, a message for noting
* - @ref ignore, a message that can be ignored in most cases.
*/
namespace diagnostic {
/// diagnostic::getEngine - Get the global-wise diagnostic engine.
Engine& getEngine();
/// Diagnose - check system status and flush all error messages.
bool Diagnose();
} // namespace of diagnostic
//===----------------------------------------------------------------------===//
// Inline non-member function
//===----------------------------------------------------------------------===//
inline diagnostic::MsgHandler unreachable(unsigned int pID)
{
return diagnostic::getEngine().report(pID, diagnostic::Unreachable);
}
inline diagnostic::MsgHandler fatal(unsigned int pID)
{
return diagnostic::getEngine().report(pID, diagnostic::Fatal);
}
inline diagnostic::MsgHandler error(unsigned int pID)
{
return diagnostic::getEngine().report(pID, diagnostic::Error);
}
inline diagnostic::MsgHandler warning(unsigned int pID)
{
return diagnostic::getEngine().report(pID, diagnostic::Warning);
}
inline diagnostic::MsgHandler debug(unsigned int pID)
{
return diagnostic::getEngine().report(pID, diagnostic::Debug);
}
inline diagnostic::MsgHandler note(unsigned int pID)
{
return diagnostic::getEngine().report(pID, diagnostic::Note);
}
inline diagnostic::MsgHandler ignore(unsigned int pID)
{
return diagnostic::getEngine().report(pID, diagnostic::Ignore);
}
inline diagnostic::MsgHandler unreachable(StringRef pMessage)
{
return diagnostic::getEngine().report(pMessage, diagnostic::Unreachable);
}
inline diagnostic::MsgHandler fatal(StringRef pMessage)
{
return diagnostic::getEngine().report(pMessage, diagnostic::Fatal);
}
inline diagnostic::MsgHandler error(StringRef pMessage)
{
return diagnostic::getEngine().report(pMessage, diagnostic::Error);
}
inline diagnostic::MsgHandler warning(StringRef pMessage)
{
return diagnostic::getEngine().report(pMessage, diagnostic::Warning);
}
inline diagnostic::MsgHandler debug(StringRef pMessage)
{
return diagnostic::getEngine().report(pMessage, diagnostic::Debug);
}
inline diagnostic::MsgHandler note(StringRef pMessage)
{
return diagnostic::getEngine().report(pMessage, diagnostic::Note);
}
inline diagnostic::MsgHandler ignore(StringRef pMessage)
{
return diagnostic::getEngine().report(pMessage, diagnostic::Ignore);
}
} // namespace of onnc
#endif
| 1,418 |
375 | /*
* Copyright 2018 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.rf.ide.core.testdata.model.table.setting;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.rf.ide.core.testdata.model.AModelElement;
import org.rf.ide.core.testdata.model.FilePosition;
import org.rf.ide.core.testdata.model.ICommentHolder;
import org.rf.ide.core.testdata.model.TemplateSetting;
import org.rf.ide.core.testdata.model.ModelType;
import org.rf.ide.core.testdata.model.table.SettingTable;
import org.rf.ide.core.testdata.text.read.recognizer.RobotToken;
import org.rf.ide.core.testdata.text.read.recognizer.RobotTokenType;
public class TaskTemplate extends AModelElement<SettingTable>
implements TemplateSetting, ICommentHolder, Serializable {
private static final long serialVersionUID = 1L;
private final RobotToken declaration;
private RobotToken keywordName;
private final List<RobotToken> unexpectedTrashArguments = new ArrayList<>();
private final List<RobotToken> comment = new ArrayList<>();
public TaskTemplate(final RobotToken declaration) {
this.declaration = declaration;
fixForTheType(declaration, RobotTokenType.SETTING_TASK_TEMPLATE_DECLARATION);
}
@Override
public boolean isPresent() {
return declaration != null;
}
@Override
public RobotToken getDeclaration() {
return declaration;
}
@Override
public RobotToken getKeywordName() {
return keywordName;
}
public void setKeywordName(final RobotToken keywordName) {
this.keywordName = updateOrCreate(this.keywordName, keywordName,
RobotTokenType.SETTING_TASK_TEMPLATE_KEYWORD_NAME);
}
public void setKeywordName(final String keywordName) {
this.keywordName = updateOrCreate(this.keywordName, keywordName,
RobotTokenType.SETTING_TASK_TEMPLATE_KEYWORD_NAME);
}
@Override
public List<RobotToken> getUnexpectedArguments() {
return Collections.unmodifiableList(unexpectedTrashArguments);
}
public void addUnexpectedTrashArgument(final String trashArgument) {
final RobotToken rt = new RobotToken();
rt.setText(trashArgument);
addUnexpectedTrashArgument(rt);
}
public void addUnexpectedTrashArgument(final RobotToken trashArgument) {
this.unexpectedTrashArguments.add(
fixForTheType(trashArgument, RobotTokenType.SETTING_TASK_TEMPLATE_KEYWORD_UNWANTED_ARGUMENT, true));
}
public void setUnexpectedTrashArgument(final int index, final String argument) {
updateOrCreateTokenInside(unexpectedTrashArguments, index, argument,
RobotTokenType.SETTING_TASK_TEMPLATE_KEYWORD_UNWANTED_ARGUMENT);
}
public void setUnexpectedTrashArgument(final int index, final RobotToken argument) {
updateOrCreateTokenInside(unexpectedTrashArguments, index, argument,
RobotTokenType.SETTING_TASK_TEMPLATE_KEYWORD_UNWANTED_ARGUMENT);
}
@Override
public List<RobotToken> getComment() {
return comment;
}
@Override
public void addCommentPart(final RobotToken rt) {
fixComment(getComment(), rt);
this.comment.add(rt);
}
@Override
public void setComment(final String comment) {
final RobotToken tok = new RobotToken();
tok.setText(comment);
setComment(tok);
}
@Override
public void setComment(final RobotToken comment) {
this.comment.clear();
addCommentPart(comment);
}
@Override
public void removeCommentPart(final int index) {
this.comment.remove(index);
}
@Override
public void clearComment() {
this.comment.clear();
}
@Override
public ModelType getModelType() {
return ModelType.SUITE_TASK_TEMPLATE;
}
@Override
public FilePosition getBeginPosition() {
return getDeclaration().getFilePosition();
}
@Override
public List<RobotToken> getElementTokens() {
final List<RobotToken> tokens = new ArrayList<>();
if (isPresent()) {
tokens.add(getDeclaration());
if (getKeywordName() != null) {
tokens.add(getKeywordName());
}
tokens.addAll(getUnexpectedArguments());
tokens.addAll(getComment());
}
return tokens;
}
@Override
public boolean removeElementToken(final int index) {
return super.removeElementFromList(unexpectedTrashArguments, index);
}
@Override
public void insertValueAt(final String value, final int position) {
final RobotToken tokenToInsert = new RobotToken();
tokenToInsert.setText(value);
if (position - 2 <= unexpectedTrashArguments.size()) { // new argument
fixForTheType(tokenToInsert, RobotTokenType.SETTING_TASK_TEMPLATE_KEYWORD_UNWANTED_ARGUMENT, true);
unexpectedTrashArguments.add(position - 2, tokenToInsert);
} else if (position - 2 - unexpectedTrashArguments.size() <= comment.size()) { // new comment part
fixComment(comment, tokenToInsert);
comment.add(position - 2 - unexpectedTrashArguments.size(), tokenToInsert);
}
}
}
| 2,271 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
/**
* Package containing the data models for SqlManagementClient. The Azure SQL Database management API provides a RESTful
* set of web services that interact with Azure SQL Database services to manage your databases. The API enables you to
* create, retrieve, update, and delete databases.
*/
package com.azure.resourcemanager.sql.models;
| 112 |
4,403 | package cn.hutool.json.test.bean;
import lombok.Data;
import java.io.Serializable;
@Data
public class JsonNode implements Serializable {
private static final long serialVersionUID = -2280206942803550272L;
private Long id;
private Integer parentId;
private String name;
public JsonNode() {
}
public JsonNode(Long id, Integer parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
}
| 152 |
1,073 | /*
* -\-\-
* Mobius
* --
* Copyright (c) 2017-2020 Spotify AB
* --
* 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.spotify.mobius.rx2;
import com.spotify.mobius.MobiusLoop;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Cancellable;
import io.reactivex.functions.Consumer;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Wraps a MobiusLoop into an observable transformer.
*
* <p>Compose it on top of an event of streams to convert it into a stream of models.
*/
class RxMobiusLoop<E, M, F> implements ObservableTransformer<E, M> {
private final MobiusLoop.Factory<M, E, F> loopFactory;
private final M startModel;
@Nullable private final Set<F> startEffects;
RxMobiusLoop(
MobiusLoop.Factory<M, E, F> loopFactory, M startModel, @Nullable Set<F> startEffects) {
this.loopFactory = loopFactory;
this.startModel = startModel;
this.startEffects = startEffects;
}
@Override
public ObservableSource<M> apply(final Observable<E> events) {
return Observable.create(
new ObservableOnSubscribe<M>() {
@Override
public void subscribe(final ObservableEmitter<M> emitter) throws Exception {
final MobiusLoop<M, E, ?> loop;
if (startEffects == null) {
loop = loopFactory.startFrom(startModel);
} else {
loop = loopFactory.startFrom(startModel, startEffects);
}
loop.observe(
new com.spotify.mobius.functions.Consumer<M>() {
@Override
public void accept(M newModel) {
emitter.onNext(newModel);
}
});
final Disposable eventsDisposable =
events.subscribe(
new Consumer<E>() {
@Override
public void accept(E event) throws Exception {
loop.dispatchEvent(event);
}
},
new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
emitter.onError(new UnrecoverableIncomingException(throwable));
}
});
emitter.setCancellable(
new Cancellable() {
@Override
public void cancel() throws Exception {
loop.dispose();
eventsDisposable.dispose();
}
});
}
});
}
}
| 1,484 |
16,989 | // Copyright 2020 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.packages;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.util.DetailedExitCode;
import java.util.OptionalLong;
/** Provides loaded-package validation functionality. */
public interface PackageValidator {
/** No-op implementation of {@link PackageValidator}. */
PackageValidator NOOP_VALIDATOR = (pkg, overhead, eventHandler) -> {};
/** Thrown when a package is deemed invalid. */
class InvalidPackageException extends NoSuchPackageException {
public InvalidPackageException(PackageIdentifier pkgId, String message) {
super(pkgId, message);
}
public InvalidPackageException(
PackageIdentifier pkgId, String message, DetailedExitCode detailedExitCode) {
super(pkgId, message, detailedExitCode);
}
}
/**
* Validates a loaded package. Throws {@link InvalidPackageException} if the package is deemed
* invalid.
*/
void validate(Package pkg, OptionalLong packageOverhead, ExtendedEventHandler eventHandler)
throws InvalidPackageException;
}
| 490 |
2,434 | <filename>swagger2markup-asciidoc/src/main/java/io/github/swagger2markup/adoc/converter/internal/Style.java
package io.github.swagger2markup.adoc.converter.internal;
import org.apache.commons.lang3.StringUtils;
public enum Style {
ASCIIDOC("a"), EMPHASIS("e"), HEADER("h"), LITERAL("l"), MONOSPACED("m"), NONE("d"), STRONG("s"), VERSE("v");
String shortHand;
Style(String h) {
this.shortHand = h;
}
public static Style fromString(String text) {
if(StringUtils.isNotBlank(text)) {
for (Style s : Style.values()) {
if (s.shortHand.equalsIgnoreCase(text)) {
return s;
}
}
}
return null;
}
public static Style fromName(String text) {
if(StringUtils.isNotBlank(text)) {
return valueOf(text.toUpperCase());
}
return null;
}
public String getShortHand() {
return shortHand;
}
}
| 458 |
10,225 | <filename>extensions/smallrye-context-propagation/deployment/src/test/java/io/quarkus/context/test/customContext/CustomContextTest.java
package io.quarkus.context.test.customContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.inject.Inject;
import org.eclipse.microprofile.context.ThreadContext;
import org.eclipse.microprofile.context.spi.ThreadContextProvider;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
/**
* Tests that custom context can be declared and is propagated.
* Note that default TC (and ME) propagate ALL contexts.
*/
public class CustomContextTest {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(CustomContextTest.class, CustomContext.class, CustomContextProvider.class)
.addAsServiceProvider(ThreadContextProvider.class, CustomContextProvider.class));
@Inject
ThreadContext tc;
@Test
public void testCustomContextPropagation() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
// set something to custom context
CustomContext.set("foo");
CompletableFuture<String> ret = tc.withContextCapture(CompletableFuture.completedFuture("void"));
CompletableFuture<Void> cfs = ret.thenApplyAsync(text -> {
Assertions.assertEquals("foo", CustomContext.get());
return null;
}, executor);
cfs.get();
}
}
| 663 |
14,443 | <reponame>proletarius101/material-components-android
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.material.catalog.chip;
import io.material.catalog.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import com.google.android.material.chip.Chip;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.switchmaterial.SwitchMaterial;
import io.material.catalog.feature.DemoFragment;
import io.material.catalog.feature.DemoUtils;
import java.util.List;
/** A fragment that displays the main Chip demos for the Catalog app. */
public class ChipMainDemoFragment extends DemoFragment {
@Nullable
@Override
public View onCreateDemoView(
LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup, @Nullable Bundle bundle) {
View view =
layoutInflater.inflate(R.layout.cat_chip_fragment, viewGroup, false /* attachToRoot */);
ViewGroup content = view.findViewById(R.id.content);
View.inflate(getContext(), getChipContent(), content);
List<Chip> chips = DemoUtils.findViewsWithType(view, Chip.class);
for (Chip chip : chips) {
chip.setOnCloseIconClickListener(
v -> {
Snackbar.make(view, "Clicked close icon.", Snackbar.LENGTH_SHORT).show();
});
if (chip.isEnabled() && !chip.isCheckable()) {
chip.setOnClickListener(
v -> {
Snackbar.make(view, "Activated chip.", Snackbar.LENGTH_SHORT)
.show();
});
}
}
SwitchMaterial longTextSwitch = view.findViewById(R.id.cat_chip_text_length_switch);
longTextSwitch.setOnCheckedChangeListener(
(buttonView, isChecked) -> {
CharSequence updatedText =
getText(isChecked ? R.string.cat_chip_text_to_truncate : R.string.cat_chip_text);
for (Chip chip : chips) {
chip.setText(updatedText);
}
});
SwitchMaterial enabledSwitch = view.findViewById(R.id.cat_chip_enabled_switch);
enabledSwitch.setOnCheckedChangeListener(
(buttonView, isChecked) -> {
for (Chip chip : chips) {
chip.setEnabled(isChecked);
}
});
return view;
}
@LayoutRes
protected int getChipContent() {
return R.layout.cat_chip_content;
}
}
| 1,105 |
11,356 | // Copyright <NAME>, 2017
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/math/concepts/std_real_concept.hpp>
#include <boost/math/tools/polynomial.hpp>
#include <boost/multiprecision/cpp_int.hpp>
template <class T>
bool check_concepts()
{
boost::math::tools::polynomial<T> a(2), b(3), c(4);
a += b;
a -= b;
a *= b;
a /= b;
a %= b;
a = c;
a += b + c;
a += b - c;
a += b * c;
a += b / c;
a += b % c;
int i = 4;
a += i;
a -= i;
a *= i;
a /= i;
a %= i;
a += b + i;
a += i + b;
a += b - i;
a += i - b;
a += b * i;
a += i * b;
a += b / i;
a += b % i;
bool bb = false;
bb |= a == b;
bb |= a != b;
return bb;
}
int main()
{
check_concepts<int>();
check_concepts<boost::multiprecision::cpp_int>();
return 0;
}
| 459 |
2,151 | // Copyright 2014 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 "extensions/shell/browser/shell_oauth2_token_service.h"
#include "base/logging.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/shell/browser/shell_oauth2_token_service_delegate.h"
namespace extensions {
namespace {
ShellOAuth2TokenService* g_instance = nullptr;
} // namespace
ShellOAuth2TokenService::ShellOAuth2TokenService(
content::BrowserContext* browser_context,
std::string account_id,
std::string refresh_token)
: OAuth2TokenService(
std::make_unique<ShellOAuth2TokenServiceDelegate>(browser_context,
account_id,
refresh_token)) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(!g_instance);
g_instance = this;
}
ShellOAuth2TokenService::~ShellOAuth2TokenService() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(g_instance);
g_instance = nullptr;
}
// static
ShellOAuth2TokenService* ShellOAuth2TokenService::GetInstance() {
DCHECK(g_instance);
return g_instance;
}
void ShellOAuth2TokenService::SetRefreshToken(
const std::string& account_id,
const std::string& refresh_token) {
GetDelegate()->UpdateCredentials(account_id, refresh_token);
}
std::string ShellOAuth2TokenService::AccountId() const {
return GetAccounts()[0];
}
} // namespace extensions
| 622 |
589 | package rocks.inspectit.agent.java.sensor.platform;
import java.sql.Timestamp;
import java.util.Calendar;
import rocks.inspectit.agent.java.sensor.platform.provider.RuntimeInfoProvider;
import rocks.inspectit.agent.java.sensor.platform.provider.factory.PlatformSensorInfoProviderFactory;
import rocks.inspectit.shared.all.communication.SystemSensorData;
import rocks.inspectit.shared.all.communication.data.CompilationInformationData;
/**
* This class provides dynamic information about the compilation system through MXBeans.
*
* @author <NAME>
* @author <NAME> (NovaTec Consulting GmbH)
*/
public class CompilationInformation extends AbstractPlatformSensor {
/** Collector class. */
private CompilationInformationData compilationInformationData = new CompilationInformationData();
/**
* The {@link RuntimeInfoProvider} used to retrieve information from the compilation system.
*/
private RuntimeInfoProvider runtimeBean;
/**
* {@inheritDoc}
*/
@Override
public void gather() {
// The timestamp is set in the {@link CompilationInformation#reset()} to avoid multiple
// renewal. It will not be set on the first execution of
// {@link CompilationInformation#gather()}, but shortly before.
long totalCompilationTime = this.getRuntimeBean().getTotalCompilationTime();
this.compilationInformationData.incrementCount();
this.compilationInformationData.addTotalCompilationTime(totalCompilationTime);
if (totalCompilationTime < this.compilationInformationData.getMinTotalCompilationTime()) {
this.compilationInformationData.setMinTotalCompilationTime(totalCompilationTime);
} else if (totalCompilationTime > this.compilationInformationData.getMaxTotalCompilationTime()) {
this.compilationInformationData.setMaxTotalCompilationTime(totalCompilationTime);
}
}
/**
* {@inheritDoc}
*/
@Override
public SystemSensorData get() {
CompilationInformationData newCompilationInformationData = new CompilationInformationData();
newCompilationInformationData.setPlatformIdent(this.compilationInformationData.getPlatformIdent());
newCompilationInformationData.setSensorTypeIdent(this.compilationInformationData.getSensorTypeIdent());
newCompilationInformationData.setCount(this.compilationInformationData.getCount());
newCompilationInformationData.setTotalTotalCompilationTime(this.compilationInformationData.getTotalTotalCompilationTime());
newCompilationInformationData.setMaxTotalCompilationTime(this.compilationInformationData.getMaxTotalCompilationTime());
newCompilationInformationData.setMinTotalCompilationTime(this.compilationInformationData.getMinTotalCompilationTime());
newCompilationInformationData.setTimeStamp(this.compilationInformationData.getTimeStamp());
return this.compilationInformationData;
}
/**
* {@inheritDoc}
*/
@Override
public void reset() {
this.compilationInformationData.setCount(0);
this.compilationInformationData.setTotalTotalCompilationTime(0L);
this.compilationInformationData.setMinTotalCompilationTime(Long.MAX_VALUE);
this.compilationInformationData.setMaxTotalCompilationTime(0L);
Timestamp timestamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
this.compilationInformationData.setTimeStamp(timestamp);
}
/**
* {@inheritDoc}
*/
@Override
protected SystemSensorData getSystemSensorData() {
return this.compilationInformationData;
}
/**
* Gets the {@link RuntimeInfoProvider}. The getter method is provided for better testability.
*
* @return {@link RuntimeInfoProvider}.
*/
private RuntimeInfoProvider getRuntimeBean() {
if (this.runtimeBean == null) {
this.runtimeBean = PlatformSensorInfoProviderFactory.getPlatformSensorInfoProvider().getRuntimeInfoProvider();
}
return this.runtimeBean;
}
}
| 1,055 |
365 | <filename>viz/web/webserve.py
import sys
import os
import base64
import threading
import ssl
import SocketServer
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
WEB_PORT=5000
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
def log_request(self, *args, **kwargs):
pass
class WebHandler(SimpleHTTPRequestHandler):
def do_GET(self):
import webhandle
reload(webhandle)
webhandle.do_get(self)
def do_POST(self):
import webhandle
reload(webhandle)
webhandle.do_post(self)
SERVER=None
def serve_http(https_port=80, HandlerClass = WebHandler):
global SERVER
SocketServer.TCPServer.allow_reuse_address = True
httpd = ThreadedTCPServer(("", https_port), HandlerClass)
debug("Serving HTTP on", https_port)
SERVER = httpd
SERVER.serve_forever()
def debug(*args):
print(" ".join(map(str, args)))
def start():
port = int(WEB_PORT)
def run_webserve():
serve_http(port)
web_thread = threading.Thread(target=run_webserve)
web_thread.daemon = True
web_thread.start()
return web_thread
def stop():
SERVER.shutdown()
SERVER.server_close()
def restart():
stop()
start()
def main():
t = start()
import helpers
# TODO: add argument parsing with argparse
helpers.select_embedding()
while True:
t.join(0.5)
if not t.isAlive():
print "WEBSERVER DIED, EXITING"
break
if __name__ == '__main__':
main()
| 637 |
418 | <filename>01.Firmware/components/nofrendo-esp32/psxcontroller.c
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
#include "soc/gpio_struct.h"
#include "psxcontroller.h"
#include "sdkconfig.h"
#define PSX_CLK CONFIG_HW_PSX_CLK
#define PSX_DAT CONFIG_HW_PSX_DAT
#define PSX_ATT CONFIG_HW_PSX_ATT
#define PSX_CMD CONFIG_HW_PSX_CMD
#define DELAY() asm("nop; nop; nop; nop;nop; nop; nop; nop;nop; nop; nop; nop;nop; nop; nop; nop;")
#if CONFIG_HW_PSX_ENA
/* Sends and receives a byte from/to the PSX controller using SPI */
static int psxSendRecv(int send) {
int x;
int ret=0;
volatile int delay;
#if 0
while(1) {
GPIO.out_w1ts=(1<<PSX_CMD);
GPIO.out_w1ts=(1<<PSX_CLK);
GPIO.out_w1tc=(1<<PSX_CMD);
GPIO.out_w1tc=(1<<PSX_CLK);
}
#endif
GPIO.out_w1tc=(1<<PSX_ATT);
for (delay=0; delay<100; delay++);
for (x=0; x<8; x++) {
if (send&1) {
GPIO.out_w1ts=(1<<PSX_CMD);
} else {
GPIO.out_w1tc=(1<<PSX_CMD);
}
DELAY();
for (delay=0; delay<100; delay++);
GPIO.out_w1tc=(1<<PSX_CLK);
for (delay=0; delay<100; delay++);
GPIO.out_w1ts=(1<<PSX_CLK);
ret>>=1;
send>>=1;
if (GPIO.in&(1<<PSX_DAT)) ret|=128;
}
return ret;
}
static void psxDone() {
DELAY();
GPIO_REG_WRITE(GPIO_OUT_W1TS_REG, (1<<PSX_ATT));
}
int psxReadInput() {
int b1, b2;
psxSendRecv(0x01); //wake up
psxSendRecv(0x42); //get data
psxSendRecv(0xff); //should return 0x5a
b1=psxSendRecv(0xff); //buttons byte 1
b2=psxSendRecv(0xff); //buttons byte 2
psxDone();
return (b2<<8)|b1;
}
void psxcontrollerInit() {
volatile int delay;
int t;
gpio_config_t gpioconf[2]={
{
.pin_bit_mask=(1<<PSX_CLK)|(1<<PSX_CMD)|(1<<PSX_ATT),
.mode=GPIO_MODE_OUTPUT,
.pull_up_en=GPIO_PULLUP_DISABLE,
.pull_down_en=GPIO_PULLDOWN_DISABLE,
.intr_type=GPIO_PIN_INTR_DISABLE
},{
.pin_bit_mask=(1<<PSX_DAT),
.mode=GPIO_MODE_INPUT,
.pull_up_en=GPIO_PULLUP_ENABLE,
.pull_down_en=GPIO_PULLDOWN_DISABLE,
.intr_type=GPIO_PIN_INTR_DISABLE
}
};
gpio_config(&gpioconf[0]);
gpio_config(&gpioconf[1]);
//Send a few dummy bytes to clean the pipes.
psxSendRecv(0);
psxDone();
for (delay=0; delay<500; delay++) DELAY();
psxSendRecv(0);
psxDone();
for (delay=0; delay<500; delay++) DELAY();
//Try and detect the type of controller, so we can give the user some diagnostics.
psxSendRecv(0x01);
t=psxSendRecv(0x00);
psxDone();
if (t==0 || t==0xff) {
printf("No PSX/PS2 controller detected (0x%X). You will not be able to control the game.\n", t);
} else {
printf("PSX controller type 0x%X\n", t);
}
}
#else
int psxReadInput() {
return 0xFFFF;
}
void psxcontrollerInit() {
printf("PSX controller disabled in menuconfig; no input enabled.\n");
}
#endif | 1,559 |
2,206 | <filename>libnd4j/include/ops/declarable/generic/nn/convo/dilation2d.cpp
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author <EMAIL>
//
#include <system/op_boilerplate.h>
#if NOT_EXCLUDED(OP_dilation2d)
#include <ops/declarable/headers/convo.h>
#include <ops/declarable/helpers/dilation2d.h>
namespace sd {
namespace ops {
CUSTOM_OP_IMPL(dilation2d, 2, 1, false, 0, 1) {
auto input = INPUT_VARIABLE(0);
auto weights = INPUT_VARIABLE(1);
auto output = OUTPUT_VARIABLE(0);
REQUIRE_TRUE(input->rankOf() == 4, 0, "Dilation2D: input should be 4D");
REQUIRE_TRUE(weights->rankOf() == 3, 0, "Dilation2D: weights should be 3D");
const int bS = input->sizeAt(0);
const int iC = input->sizeAt(3);
const bool isSameShape = INT_ARG(0) == 1;
REQUIRE_TRUE(input->sizeAt(3) == weights->sizeAt(2), 0,
"Dilation2D: number of input channels doesn't match number of channels in weights: %i vs %i",
input->sizeAt(3), weights->sizeAt(2));
std::vector<int> strides(4);
std::vector<int> rates(4);
if (block.width() > 2) {
REQUIRE_TRUE(block.width() >= 4, 0, "Dilation2D: number of input arrays should be 4 at least");
auto r = INPUT_VARIABLE(2);
auto s = INPUT_VARIABLE(3);
strides = s->template asVectorT<int>();
rates = r->template asVectorT<int>();
} else {
REQUIRE_TRUE(block.numI() >= 9, 0, "Dilation2D: number of Int arguments should be 9 at least");
int e = 1;
for (int cnt = 0; cnt < 4; cnt++) rates[cnt] = INT_ARG(e++);
for (int cnt = 0; cnt < 4; cnt++) strides[cnt] = INT_ARG(e++);
}
int sH = 0, sW = 0;
int dH = 0, dW = 0;
int pH = 0, pW = 0;
int oH = 0, oW = 0;
helpers::dilation_hw(block.launchContext(), input->shapeInfo(), weights->shapeInfo(), strides, rates, isSameShape,
&sH, &sW, &pH, &pW, &dH, &dW, &oH, &oW);
REQUIRE_TRUE(oH > 0 && oW > 0, 0, "Dilation2D: outY and outX should have positive values, but got [%i, %i] instead",
oH, oW);
helpers::dilation2d(block.launchContext(), input, weights, output, sH, sW, pH, pW, dH, dW);
return sd::Status::OK;
}
DECLARE_TYPES(dilation2d) {
getOpDescriptor()->setAllowedInputTypes(sd::DataType::ANY)->setAllowedOutputTypes({ALL_FLOATS});
}
DECLARE_SHAPE_FN(dilation2d) {
auto input = inputShape->at(0);
auto weights = inputShape->at(1);
const int bS = shape::sizeAt(input, 0);
const int iC = shape::sizeAt(input, 3);
const bool isSameShape = INT_ARG(0) == 1;
std::vector<int> strides(4);
std::vector<int> rates(4);
if (block.width() > 2) {
auto r = INPUT_VARIABLE(2);
auto s = INPUT_VARIABLE(3);
strides = s->template asVectorT<int>();
rates = r->template asVectorT<int>();
} else {
if (block.numI() < 9) {
auto newShape = ConstantShapeHelper::getInstance().scalarShapeInfo(block.dataType());
return SHAPELIST(newShape);
}
int e = 1;
for (int cnt = 0; cnt < 4; cnt++) rates[cnt] = INT_ARG(e++);
for (int cnt = 0; cnt < 4; cnt++) strides[cnt] = INT_ARG(e++);
}
int sH = 0, sW = 0;
int dH = 0, dW = 0;
int pH = 0, pW = 0;
int oH = 0, oW = 0;
helpers::dilation_hw(block.launchContext(), input, weights, strides, rates, isSameShape, &sH, &sW, &pH, &pW, &dH, &dW,
&oH, &oW);
std::array<sd::LongType, 4> shape = {{bS, oH, oW, iC}};
auto newShape =
ConstantShapeHelper::getInstance().createShapeInfo(ArrayOptions::dataType(weights), 'c', 4, shape.data());
return SHAPELIST(newShape);
}
} // namespace ops
} // namespace sd
#endif
| 1,706 |
1,144 | <reponame>dram/metasfresh
package de.metas.product.impl;
/*
* #%L
* de.metas.swat.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import org.adempiere.warehouse.WarehouseId;
import org.adempiere.warehouse.api.IWarehouseDAO;
import org.compiere.model.I_M_Locator;
import org.compiere.model.I_M_Storage;
import org.compiere.model.MStorage;
import org.compiere.util.DB;
import org.compiere.util.Env;
import de.metas.product.IStoragePA;
import de.metas.util.Services;
public final class StoragePA implements IStoragePA
{
private static final String SQL_SELECT_QTY_ORDERED = //
"SELECT SUM(" + I_M_Storage.COLUMNNAME_QtyOrdered + ") " //
+ "FROM " + I_M_Storage.Table_Name + " s " //
+ " LEFT JOIN " + I_M_Locator.Table_Name + " l " //
+ " ON s." + I_M_Storage.COLUMNNAME_M_Locator_ID //
+ " = l." + I_M_Locator.COLUMNNAME_M_Locator_ID //
+ " WHERE s." + I_M_Storage.COLUMNNAME_M_Product_ID + "=? " //
+ "AND l." + I_M_Locator.COLUMNNAME_M_Warehouse_ID + "=?";
@Override
public Collection<I_M_Storage> retrieveStorages(final int productId,
final String trxName)
{
final I_M_Storage[] storages = MStorage.getOfProduct(Env.getCtx(),
productId, trxName);
return Arrays.asList(storages);
}
@Override
public WarehouseId retrieveWarehouseId(final I_M_Storage storage)
{
final int locatorId = storage.getM_Locator_ID();
return Services.get(IWarehouseDAO.class).getWarehouseIdByLocatorRepoId(locatorId);
}
/**
* Invokes {@link MStorage#getQtyAvailable(int, int, int, int, String)}.
*/
@Override
public BigDecimal retrieveQtyAvailable(final int wareHouseId,
final int locatorId, final int productId,
final int attributeSetInstanceId, final String trxName)
{
return MStorage.getQtyAvailable(wareHouseId, locatorId, productId,
attributeSetInstanceId, trxName);
}
@Override
public BigDecimal retrieveQtyOrdered(final int productId,
final int warehouseId)
{
ResultSet rs = null;
final PreparedStatement pstmt = DB.prepareStatement(
SQL_SELECT_QTY_ORDERED, null);
try
{
pstmt.setInt(1, productId);
pstmt.setInt(2, warehouseId);
rs = pstmt.executeQuery();
if (rs.next())
{
final BigDecimal qtyOrdered = rs.getBigDecimal(1);
if (qtyOrdered == null)
{
return BigDecimal.ZERO;
}
return qtyOrdered;
}
throw new RuntimeException(
"Unable to retrive qtyOrdererd for M_Product_ID '"
+ productId + "'");
}
catch (SQLException e)
{
throw new RuntimeException(e);
}
finally
{
DB.close(rs, pstmt);
}
}
}
| 1,306 |
14,668 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/win/src/restricted_token_utils.h"
#include <aclapi.h>
#include <sddl.h>
#include <memory>
#include <vector>
#include "base/check.h"
#include "base/notreached.h"
#include "base/strings/stringprintf.h"
#include "base/win/scoped_handle.h"
#include "base/win/windows_version.h"
#include "sandbox/win/src/job.h"
#include "sandbox/win/src/restricted_token.h"
#include "sandbox/win/src/sandbox_utils.h"
#include "sandbox/win/src/security_level.h"
#include "sandbox/win/src/win_utils.h"
namespace sandbox {
namespace {
DWORD GetObjectSecurityDescriptor(HANDLE handle,
SECURITY_INFORMATION security_info,
std::vector<char>* security_desc_buffer,
PSECURITY_DESCRIPTOR* security_desc) {
DWORD last_error = 0;
DWORD length_needed = 0;
::GetKernelObjectSecurity(handle, security_info, nullptr, 0, &length_needed);
last_error = ::GetLastError();
if (last_error != ERROR_INSUFFICIENT_BUFFER)
return last_error;
security_desc_buffer->resize(length_needed);
*security_desc =
reinterpret_cast<PSECURITY_DESCRIPTOR>(security_desc_buffer->data());
if (!::GetKernelObjectSecurity(handle, security_info, *security_desc,
length_needed, &length_needed)) {
return ::GetLastError();
}
return ERROR_SUCCESS;
}
void AddSidException(std::vector<base::win::Sid>& sids,
base::win::WellKnownSid known_sid) {
absl::optional<base::win::Sid> sid = base::win::Sid::FromKnownSid(known_sid);
DCHECK(sid);
sids.push_back(std::move(*sid));
}
} // namespace
DWORD CreateRestrictedToken(
HANDLE effective_token,
TokenLevel security_level,
IntegrityLevel integrity_level,
TokenType token_type,
bool lockdown_default_dacl,
const absl::optional<base::win::Sid>& unique_restricted_sid,
base::win::ScopedHandle* token) {
RestrictedToken restricted_token;
restricted_token.Init(effective_token);
if (lockdown_default_dacl)
restricted_token.SetLockdownDefaultDacl();
if (unique_restricted_sid) {
restricted_token.AddDefaultDaclSid(*unique_restricted_sid,
SecurityAccessMode::kGrant, GENERIC_ALL);
restricted_token.AddDefaultDaclSid(
base::win::WellKnownSid::kCreatorOwnerRights,
SecurityAccessMode::kGrant, READ_CONTROL);
}
std::vector<std::wstring> privilege_exceptions;
std::vector<base::win::Sid> sid_exceptions;
bool deny_sids = true;
bool remove_privileges = true;
bool remove_traverse_privilege = false;
switch (security_level) {
case USER_UNPROTECTED: {
deny_sids = false;
remove_privileges = false;
break;
}
case USER_RESTRICTED_SAME_ACCESS: {
deny_sids = false;
remove_privileges = false;
unsigned err_code = restricted_token.AddRestrictingSidAllSids();
if (ERROR_SUCCESS != err_code)
return err_code;
break;
}
case USER_RESTRICTED_NON_ADMIN: {
AddSidException(sid_exceptions, base::win::WellKnownSid::kBuiltinUsers);
AddSidException(sid_exceptions, base::win::WellKnownSid::kWorld);
AddSidException(sid_exceptions, base::win::WellKnownSid::kInteractive);
AddSidException(sid_exceptions,
base::win::WellKnownSid::kAuthenticatedUser);
restricted_token.AddRestrictingSid(
base::win::WellKnownSid::kBuiltinUsers);
restricted_token.AddRestrictingSid(base::win::WellKnownSid::kWorld);
restricted_token.AddRestrictingSid(base::win::WellKnownSid::kInteractive);
restricted_token.AddRestrictingSid(
base::win::WellKnownSid::kAuthenticatedUser);
restricted_token.AddRestrictingSid(base::win::WellKnownSid::kRestricted);
restricted_token.AddRestrictingSidCurrentUser();
restricted_token.AddRestrictingSidLogonSession();
if (unique_restricted_sid)
restricted_token.AddRestrictingSid(*unique_restricted_sid);
break;
}
case USER_INTERACTIVE: {
AddSidException(sid_exceptions, base::win::WellKnownSid::kBuiltinUsers);
AddSidException(sid_exceptions, base::win::WellKnownSid::kWorld);
AddSidException(sid_exceptions, base::win::WellKnownSid::kInteractive);
AddSidException(sid_exceptions,
base::win::WellKnownSid::kAuthenticatedUser);
restricted_token.AddRestrictingSid(
base::win::WellKnownSid::kBuiltinUsers);
restricted_token.AddRestrictingSid(base::win::WellKnownSid::kWorld);
restricted_token.AddRestrictingSid(base::win::WellKnownSid::kRestricted);
restricted_token.AddRestrictingSidCurrentUser();
restricted_token.AddRestrictingSidLogonSession();
if (unique_restricted_sid)
restricted_token.AddRestrictingSid(*unique_restricted_sid);
break;
}
case USER_LIMITED: {
AddSidException(sid_exceptions, base::win::WellKnownSid::kBuiltinUsers);
AddSidException(sid_exceptions, base::win::WellKnownSid::kWorld);
AddSidException(sid_exceptions, base::win::WellKnownSid::kInteractive);
restricted_token.AddRestrictingSid(
base::win::WellKnownSid::kBuiltinUsers);
restricted_token.AddRestrictingSid(base::win::WellKnownSid::kWorld);
restricted_token.AddRestrictingSid(base::win::WellKnownSid::kRestricted);
if (unique_restricted_sid)
restricted_token.AddRestrictingSid(*unique_restricted_sid);
// This token has to be able to create objects in BNO, it needs the
// current logon sid in the token to achieve this. You should also set the
// process to be low integrity level so it can't access object created by
// other processes.
restricted_token.AddRestrictingSidLogonSession();
break;
}
case USER_RESTRICTED: {
restricted_token.AddUserSidForDenyOnly();
restricted_token.AddRestrictingSid(base::win::WellKnownSid::kRestricted);
if (unique_restricted_sid)
restricted_token.AddRestrictingSid(*unique_restricted_sid);
break;
}
case USER_LOCKDOWN: {
remove_traverse_privilege = true;
restricted_token.AddUserSidForDenyOnly();
restricted_token.AddRestrictingSid(base::win::WellKnownSid::kNull);
if (unique_restricted_sid)
restricted_token.AddRestrictingSid(*unique_restricted_sid);
break;
}
case USER_LAST:
return ERROR_BAD_ARGUMENTS;
}
DWORD err_code = ERROR_SUCCESS;
if (deny_sids) {
err_code = restricted_token.AddAllSidsForDenyOnly(sid_exceptions);
if (ERROR_SUCCESS != err_code)
return err_code;
}
if (remove_privileges) {
err_code = restricted_token.DeleteAllPrivileges(remove_traverse_privilege);
if (ERROR_SUCCESS != err_code)
return err_code;
}
restricted_token.SetIntegrityLevel(integrity_level);
switch (token_type) {
case PRIMARY: {
err_code = restricted_token.GetRestrictedToken(token);
break;
}
case IMPERSONATION: {
err_code = restricted_token.GetRestrictedTokenForImpersonation(token);
break;
}
default: {
err_code = ERROR_BAD_ARGUMENTS;
break;
}
}
return err_code;
}
DWORD SetTokenIntegrityLevel(HANDLE token, IntegrityLevel integrity_level) {
absl::optional<base::win::Sid> sid = GetIntegrityLevelSid(integrity_level);
if (!sid) {
// No mandatory level specified, we don't change it.
return ERROR_SUCCESS;
}
TOKEN_MANDATORY_LABEL label = {};
label.Label.Attributes = SE_GROUP_INTEGRITY;
label.Label.Sid = sid->GetPSID();
if (!::SetTokenInformation(token, TokenIntegrityLevel, &label, sizeof(label)))
return ::GetLastError();
return ERROR_SUCCESS;
}
DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) {
// We don't check for an invalid level here because we'll just let it
// fail on the SetTokenIntegrityLevel call later on.
if (integrity_level == INTEGRITY_LEVEL_LAST) {
// No mandatory level specified, we don't change it.
return ERROR_SUCCESS;
}
HANDLE token_handle;
if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT,
&token_handle))
return ::GetLastError();
base::win::ScopedHandle token(token_handle);
return SetTokenIntegrityLevel(token.Get(), integrity_level);
}
DWORD HardenTokenIntegrityLevelPolicy(HANDLE token) {
std::vector<char> security_desc_buffer;
PSECURITY_DESCRIPTOR security_desc = nullptr;
DWORD last_error = GetObjectSecurityDescriptor(
token, LABEL_SECURITY_INFORMATION, &security_desc_buffer, &security_desc);
if (last_error != ERROR_SUCCESS)
return last_error;
PACL sacl = nullptr;
BOOL sacl_present = false;
BOOL sacl_defaulted = false;
if (!::GetSecurityDescriptorSacl(security_desc, &sacl_present, &sacl,
&sacl_defaulted)) {
return ::GetLastError();
}
for (DWORD ace_index = 0; ace_index < sacl->AceCount; ++ace_index) {
PSYSTEM_MANDATORY_LABEL_ACE ace;
if (::GetAce(sacl, ace_index, reinterpret_cast<LPVOID*>(&ace)) &&
ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE) {
ace->Mask |= SYSTEM_MANDATORY_LABEL_NO_READ_UP |
SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP;
break;
}
}
if (!::SetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION,
security_desc))
return ::GetLastError();
return ERROR_SUCCESS;
}
DWORD HardenProcessIntegrityLevelPolicy() {
HANDLE token_handle;
if (!::OpenProcessToken(GetCurrentProcess(), READ_CONTROL | WRITE_OWNER,
&token_handle))
return ::GetLastError();
base::win::ScopedHandle token(token_handle);
return HardenTokenIntegrityLevelPolicy(token.Get());
}
DWORD CreateLowBoxToken(HANDLE base_token,
TokenType token_type,
SECURITY_CAPABILITIES* security_capabilities,
HANDLE* saved_handles,
DWORD saved_handles_count,
base::win::ScopedHandle* token) {
NtCreateLowBoxToken CreateLowBoxToken = nullptr;
ResolveNTFunctionPtr("NtCreateLowBoxToken", &CreateLowBoxToken);
if (base::win::GetVersion() < base::win::Version::WIN8)
return ERROR_CALL_NOT_IMPLEMENTED;
if (token_type != PRIMARY && token_type != IMPERSONATION)
return ERROR_INVALID_PARAMETER;
if (!token)
return ERROR_INVALID_PARAMETER;
base::win::ScopedHandle base_token_handle;
if (!base_token) {
HANDLE process_token = nullptr;
if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
&process_token)) {
return ::GetLastError();
}
base_token_handle.Set(process_token);
base_token = process_token;
}
OBJECT_ATTRIBUTES obj_attr;
InitializeObjectAttributes(&obj_attr, nullptr, 0, nullptr, nullptr);
HANDLE token_lowbox = nullptr;
NTSTATUS status = CreateLowBoxToken(
&token_lowbox, base_token, TOKEN_ALL_ACCESS, &obj_attr,
security_capabilities->AppContainerSid,
security_capabilities->CapabilityCount,
security_capabilities->Capabilities, saved_handles_count,
saved_handles_count > 0 ? saved_handles : nullptr);
if (!NT_SUCCESS(status))
return GetLastErrorFromNtStatus(status);
base::win::ScopedHandle token_lowbox_handle(token_lowbox);
DCHECK(token_lowbox_handle.IsValid());
// Default from NtCreateLowBoxToken is a Primary token.
if (token_type == PRIMARY) {
*token = std::move(token_lowbox_handle);
return ERROR_SUCCESS;
}
HANDLE dup_handle = nullptr;
if (!::DuplicateTokenEx(token_lowbox_handle.Get(), TOKEN_ALL_ACCESS, nullptr,
::SecurityImpersonation, ::TokenImpersonation,
&dup_handle)) {
return ::GetLastError();
}
// Copy security descriptor from primary token as the new object will have
// the DACL from the current token's default DACL.
base::win::ScopedHandle token_for_sd(dup_handle);
std::vector<char> security_desc_buffer;
PSECURITY_DESCRIPTOR security_desc = nullptr;
DWORD last_error = GetObjectSecurityDescriptor(
token_lowbox_handle.Get(), DACL_SECURITY_INFORMATION,
&security_desc_buffer, &security_desc);
if (last_error != ERROR_SUCCESS)
return last_error;
if (!::SetKernelObjectSecurity(token_for_sd.Get(), DACL_SECURITY_INFORMATION,
security_desc)) {
return ::GetLastError();
}
*token = std::move(token_for_sd);
return ERROR_SUCCESS;
}
DWORD CreateLowBoxObjectDirectory(const base::win::Sid& lowbox_sid,
bool open_directory,
base::win::ScopedHandle* directory) {
DWORD session_id = 0;
if (!::ProcessIdToSessionId(::GetCurrentProcessId(), &session_id))
return ::GetLastError();
absl::optional<std::wstring> sid_string = lowbox_sid.ToSddlString();
if (!sid_string)
return ERROR_INVALID_SID;
std::wstring directory_path =
base::StringPrintf(L"\\Sessions\\%d\\AppContainerNamedObjects\\%ls",
session_id, sid_string->c_str());
NtCreateDirectoryObjectFunction CreateObjectDirectory = nullptr;
ResolveNTFunctionPtr("NtCreateDirectoryObject", &CreateObjectDirectory);
OBJECT_ATTRIBUTES obj_attr;
UNICODE_STRING obj_name;
DWORD attributes = OBJ_CASE_INSENSITIVE;
if (open_directory)
attributes |= OBJ_OPENIF;
sandbox::InitObjectAttribs(directory_path, attributes, nullptr, &obj_attr,
&obj_name, nullptr);
HANDLE handle = nullptr;
NTSTATUS status =
CreateObjectDirectory(&handle, DIRECTORY_ALL_ACCESS, &obj_attr);
if (!NT_SUCCESS(status))
return GetLastErrorFromNtStatus(status);
directory->Set(handle);
return ERROR_SUCCESS;
}
bool CanLowIntegrityAccessDesktop() {
// Access required for UI thread to initialize (when user32.dll loads without
// win32k lockdown).
DWORD desired_access = DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS;
// From MSDN
// https://docs.microsoft.com/en-us/windows/win32/winstation/desktop-security-and-access-rights
GENERIC_MAPPING generic_mapping{
STANDARD_RIGHTS_READ | DESKTOP_READOBJECTS | DESKTOP_ENUMERATE,
STANDARD_RIGHTS_WRITE | DESKTOP_CREATEWINDOW | DESKTOP_CREATEMENU |
DESKTOP_HOOKCONTROL | DESKTOP_JOURNALRECORD |
DESKTOP_JOURNALPLAYBACK | DESKTOP_WRITEOBJECTS,
STANDARD_RIGHTS_EXECUTE | DESKTOP_SWITCHDESKTOP,
STANDARD_RIGHTS_REQUIRED | DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL | DESKTOP_JOURNALPLAYBACK |
DESKTOP_JOURNALRECORD | DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP |
DESKTOP_WRITEOBJECTS};
::MapGenericMask(&desired_access, &generic_mapping);
// Desktop is inherited by child process unless overridden, e.g. by sandbox.
HDESK hdesk = ::GetThreadDesktop(GetCurrentThreadId());
// Get the security descriptor of the desktop.
DWORD size = 0;
SECURITY_INFORMATION security_information =
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
DACL_SECURITY_INFORMATION | LABEL_SECURITY_INFORMATION;
::GetUserObjectSecurity(hdesk, &security_information, nullptr, 0, &size);
std::vector<char> sd_buffer(size);
PSECURITY_DESCRIPTOR sd =
reinterpret_cast<PSECURITY_DESCRIPTOR>(sd_buffer.data());
if (!::GetUserObjectSecurity(hdesk, &security_information, sd, size, &size)) {
return false;
}
// Get a low IL token starting with the current process token and lowering it.
HANDLE temp_process_token = nullptr;
if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
&temp_process_token)) {
return false;
}
base::win::ScopedHandle process_token(temp_process_token);
HANDLE temp_duplicate_token = nullptr;
if (!::DuplicateTokenEx(process_token.Get(), MAXIMUM_ALLOWED, nullptr,
SecurityImpersonation, TokenImpersonation,
&temp_duplicate_token)) {
return false;
}
base::win::ScopedHandle low_il_token(temp_duplicate_token);
// The token should still succeed before lowered, even if the lowered token
// fails.
PRIVILEGE_SET priv_set = {};
DWORD priv_set_length = sizeof(PRIVILEGE_SET);
DWORD granted_access = 0;
BOOL access_status = false;
DCHECK(!!::AccessCheck(sd, low_il_token.Get(), desired_access,
&generic_mapping, &priv_set, &priv_set_length,
&granted_access, &access_status) &&
access_status);
if (sandbox::SetTokenIntegrityLevel(
low_il_token.Get(), sandbox::INTEGRITY_LEVEL_LOW) != ERROR_SUCCESS) {
return false;
}
// Access check the Low-IL token against the desktop - known to fail for third
// party, winlogon, other non-default desktops, and required for user32.dll to
// load.
if (::AccessCheck(sd, low_il_token.Get(), desired_access, &generic_mapping,
&priv_set, &priv_set_length, &granted_access,
&access_status) &&
access_status) {
return true;
}
return false;
}
} // namespace sandbox
| 7,020 |
370 | #define DINT
#include <../Source/umf_cholmod.c>
| 21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.