max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
6,989 | <filename>scipy/io/arff/__init__.py<gh_stars>1000+
"""
Module to read ARFF files, which are the standard data format for WEKA.
ARFF is a text file format which support numerical, string and data values.
The format can also represent missing data and sparse data.
See the `WEKA website
<http://weka.wikispaces.com/ARFF>`_
for more details about arff format and available datasets.
"""
from __future__ import division, print_function, absolute_import
from .arffread import *
from . import arffread
__all__ = arffread.__all__
from numpy.testing import Tester
test = Tester().test
| 176 |
5,169 | <filename>Specs/e/b/8/FancyTextField/0.1.1/FancyTextField.podspec.json
{
"name": "FancyTextField",
"version": "0.1.1",
"summary": "Its the UITextField but prettier",
"description": "This TextField is really fancy! It will make your app look slick!",
"homepage": "https://github.com/gtdrag/FancyTextField",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/gtdrag/FancyTextField.git",
"tag": "0.1.1"
},
"platforms": {
"ios": "10.0"
},
"source_files": "CustomTextInput/includes/*",
"pushed_with_swift_version": "4.0"
}
| 274 |
10,225 | @PersistenceUnit(PersistenceUnit.DEFAULT)
@PersistenceUnit("users")
@PersistenceUnit("inventory")
package io.quarkus.hibernate.orm.multiplepersistenceunits.model.annotation.shared;
import io.quarkus.hibernate.orm.PersistenceUnit; | 75 |
533 | <filename>test/saber/test_saber_activation.cpp
#include "saber/core/context.h"
#include "saber/core/tensor_op.h"
#include "saber/funcs/activation.h"
#include "saber/saber_types.h"
#include "test_saber_func.h"
#include "test_saber_base.h"
#include <vector>
#include<cmath>
using namespace anakin::saber;
int active = 1;
int num_in = 1;
int ch_in = 2;
int h_in = 3;
int w_in = 5;
template <typename dtype, typename TargetType_D, typename TargetType_H>
void activation_basic(const std::vector<Tensor<TargetType_H>*>& inputs,
std::vector<Tensor<TargetType_H>*>& outputs, ActivationParam<TargetType_D>& param) {
int num = inputs[0]->num();
int channel = inputs[0]->channel();
int height = inputs[0]->height();
int width = inputs[0]->width();
dtype* dout = (dtype*)outputs[0]->mutable_data();
const dtype* din = (const dtype*)inputs[0]->data();
size_t count = inputs[0]->valid_size();
int size = height * width;
switch (param.active) {
//x > 0 ? x : 0
case Active_relu:
for (size_t i = 0; i < count; i++) {
dout[i] = din[i] > 0 ? din[i] : 0;
}
break;
// sigmoid: 1/(exp(-x) + 1)
case Active_sigmoid:
for (size_t i = 0; i < count; i++) {
dout[i] = 1.0f / (exp(-din[i]) + 1.0f);
}
break;
// swish: x/(1 + exp(-(b * x)))
case Active_swish:
for (size_t i = 0; i < count; i++) {
const dtype beta = param.coef;
dout[i] = din[i] / (1.0f + exp(-(din[i] * beta)));
}
break;
// tanh : (exp(x) - exp(-x)) / (exp(x) + exp(-x))
case Active_tanh:
for (size_t i = 0; i < count; i++) {
dout[i] = tanh(din[i]);//(exp(din[i]) - exp(-din[i])) / (exp(din[i]) + exp(-din[i]));
}
break;
// stanh : b * \frac{e^{a * x} - e^{-a * x}}{e^{a * x} + e^{-a * x}}
case Active_stanh:
for (size_t i = 0; i < count; i++) {
dtype val = din[i] * param.negative_slope;
dout[i] = param.coef * tanh(val);
}
break;
// x > 0 ? x : 0;
// x < threshold ? x : threshold
case Active_clipped_relu:
for (size_t i = 0; i < count; i++) {
const dtype threshold = param.coef;
dout[i] = din[i] > 0 ? (din[i] < threshold ? din[i] : threshold) : 0;
}
break;
//elu: x > 0 ? x : coef * (exp(x) - 1)
case Active_elu:
for (size_t i = 0; i < count; i++) {
dout[i] = din[i] > 0 ? din[i] : param.coef * (exp(din[i]) - 1);
}
break;
//gelu: y = x * 0.5 * (erf(x/sqrt(2)) + 1)
case Active_gelu:
for (size_t i = 0; i < count; i++) {
dtype x = din[i];
dtype coeff = 0.5 * (erf(x/sqrt(2)) + 1);
dout[i] = x * coeff;
}
break;
//prelu: x > 0 ? x : slope[c] * x
case Active_prelu:
auto prelu_param = param.prelu_param;
for (int n = 0; n < num; n++) {
const dtype* in_ptr = din + n * channel * size;
dtype* out_ptr = dout + n * channel * size;
// const dtype *slope_ptr = nullptr;
Tensor<TargetType_D>* slop_dev;
slop_dev = prelu_param.slope;
Shape shape = slop_dev->valid_shape();
Tensor<TargetType_H>* slop_host;//(shape);
// LOG(INFO) << "slop_dev: " << shape[0] << ", " << shape[2];
//slop_host->set_shape(shape);
slop_host = new Tensor<TargetType_H>(shape);
//LOG(INFO) << "slop_dev: " << slop_dev->valid_size();
slop_host->copy_from(*slop_dev);
//LOG(INFO) << "slop_host: " << slop_host->valid_size();
const dtype* slope_ptr = (const dtype*)slop_host->data();
// const dtype *slope_ptr = (const dtype*)prelu_param.slope->data();
for (int c = 0; c < channel; c++) {
const dtype* in_ch_ptr = in_ptr + c * size;
dtype* out_ch_ptr = out_ptr + c * size;
dtype slope = prelu_param.channel_shared ? slope_ptr[0] : slope_ptr[c];
for (int k = 0; k < size; k++) {
out_ch_ptr[k] = in_ch_ptr[k] > 0 ? in_ch_ptr[k] : in_ch_ptr[k] * slope;
}
}
delete slop_host;
}
break;
}
}
template <DataType Dtype, typename TargetType_D, typename TargetType_H>
void test_model() {
int num = num_in;
int channel = ch_in;
int height = h_in;
int width = w_in;
TestSaberBase<TargetType_D, TargetType_H, Dtype, Activation, ActivationParam> testbase(1, 1);
Shape input_shape({num, channel, height, width}, Layout_NCHW);
Shape input_shape2({2, 2, 12, 22}, Layout_NCHW);
//test example
for (auto shape : {input_shape, input_shape2}) {
#if defined(USE_ARM_PLACE)
for (auto act : {Active_sigmoid,Active_relu, Active_tanh, Active_clipped_relu, Active_prelu}) {
#elif defined(USE_MLU)
for (auto act : {Active_sigmoid,Active_relu, Active_tanh, Active_clipped_relu, Active_prelu, Active_elu, Active_stanh}) {
#else
for (auto act : {Active_sigmoid, Active_relu, Active_tanh, Active_clipped_relu, Active_prelu, Active_elu, Active_stanh,
Active_gelu, Active_swish}) {
#endif
LOG(INFO) << "================ active: " << act;
for (auto neg_slope : {-1.0, 0.5}) {
for (auto coef : {1.0, 0.5}) {
for (auto has : {true, false}) {
if (act == 10) {
for (auto shared : {true, false}) {
Shape slope_shape({1, shape[1], 1, 1}, Layout_NCHW);
Tensor<TargetType_D> slope_tensor;
slope_tensor.re_alloc(slope_shape, Dtype);
fill_tensor_rand(slope_tensor, -1.0, 1.0);
PreluParam<TargetType_D> prelu(shared, &slope_tensor);
ActivationParam<TargetType_D> param(act, neg_slope, coef, prelu, has);
testbase.set_param(param);//set param
testbase.set_input_shape(shape, SPECIAL);
if (std::is_same<TargetType_D, MLU>::value) {
testbase.run_test(activation_basic<float, TargetType_D, TargetType_H>, 0.02, true);//run test
}else {
testbase.run_test(activation_basic<float, TargetType_D, TargetType_H>);//run test
}
// LOG(INFO) << "NV run end";
}
} else {
PreluParam<TargetType_D> prelu(false, nullptr);
if (act == 2) {
neg_slope = 0.f; //relu
}
ActivationParam<TargetType_D> param(act, neg_slope, coef, prelu, has);
//LOG(INFO) << "neg_slope: " << neg_slope << ", coef: " << coef << ", has: " << has;
testbase.set_param(param);//set param
testbase.set_input_shape(shape, SPECIAL);
if (std::is_same<TargetType_D, MLU>::value) {
testbase.run_test(activation_basic<float, TargetType_D, TargetType_H>, 0.02, true);//run test
}else {
testbase.run_test(activation_basic<float, TargetType_D, TargetType_H>);//run test
}
// LOG(INFO) << "NV run end";
}
}
}
}
}
}
}
TEST(TestSaberFunc, test_func_activation) {
#ifdef USE_CUDA
//Init the test_base
test_model<AK_FLOAT, NV, NVHX86>();
#endif
#ifdef USE_X86_PLACE
test_model<AK_FLOAT, X86, X86>();
#endif
#ifdef USE_ARM_PLACE
Env<ARM>::env_init();
test_model<AK_FLOAT, ARM, ARM>();
#endif
#ifdef AMD_GPU
// Env<AMD>::env_init();
// test_model<AK_FLOAT, AMD, AMDHX86>();
#endif
#ifdef USE_BM_PLACE
// Env<BM>::env_init();
// test_accuracy<BM, X86>(num, channel, height, width,VENDER_IMPL);
#endif
#ifdef USE_MLU
Env<MLUHX86>::env_init();
Env<MLU>::env_init();
test_model<AK_FLOAT, MLU, MLUHX86>();
#endif // USE_MLU
}
int main(int argc, const char** argv) {
// initial logger
logger::init(argv[0]);
if (argc >= 2) {
active = atoi(argv[1]);
}
if (argc >= 3) {
if (argc < 6) {
LOG(ERROR) << "usage: ./" << argv[0] << "axis " << \
" num ch_in h_in w_in" ;
return 0;
}
num_in = atoi(argv[2]);
ch_in = atoi(argv[3]);
h_in = atoi(argv[4]);
w_in = atoi(argv[5]);
}
InitTest();
RUN_ALL_TESTS(argv[0]);
return 0;
}
| 4,099 |
2,996 | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.world.generation.facets.base;
import com.google.common.collect.Maps;
import org.joml.Vector3i;
import org.joml.Vector3ic;
import org.terasology.engine.world.block.BlockRegionc;
import org.terasology.engine.world.generation.Border3D;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
/**
* A sparse (map-based) implementation
* of {@link ObjectFacet3D}.
*
*/
public abstract class SparseObjectFacet3D<T> extends SparseFacet3D implements ObjectFacet3D<T> {
private final Map<Vector3ic, T> relData = Maps.newLinkedHashMap();
/**
* @param targetRegion
* @param border
*/
public SparseObjectFacet3D(BlockRegionc targetRegion, Border3D border) {
super(targetRegion, border);
}
@Override
public T get(int x, int y, int z) {
return get(new Vector3i(x, y, z));
}
@Override
public T get(Vector3ic pos) {
checkRelativeCoords(pos.x(), pos.y(), pos.z());
return relData.get(pos);
}
@Override
public void set(int x, int y, int z, T value) {
set(new Vector3i(x, y, z), value);
}
@Override
public void set(Vector3ic pos, T value) {
checkRelativeCoords(pos.x(), pos.y(), pos.z());
relData.put(pos, value); // TODO: consider using an immutable vector here
}
@Override
public T getWorld(Vector3ic pos) {
return getWorld(pos.x(), pos.y(), pos.z());
}
@Override
public T getWorld(int x, int y, int z) {
checkWorldCoords(x, y, z);
Vector3i index = worldToRelative(x, y, z);
return relData.get(index);
}
@Override
public void setWorld(Vector3ic pos, T value) {
setWorld(pos.x(), pos.y(), pos.z(), value);
}
@Override
public void setWorld(int x, int y, int z, T value) {
checkWorldCoords(x, y, z);
Vector3i index = worldToRelative(x, y, z);
relData.put(index, value);
}
/**
* @return an unmodifiable view on the relative entries
*/
public Map<Vector3ic, T> getRelativeEntries() {
return Collections.unmodifiableMap(relData);
}
/**
* @return a <b>new</b> map with world-based position entries
*/
public Map<Vector3ic, T> getWorldEntries() {
Map<Vector3ic, T> result = Maps.newLinkedHashMap();
for (Entry<Vector3ic, T> entry : relData.entrySet()) {
Vector3ic relPos = entry.getKey();
Vector3ic worldPos = relativeToWorld(relPos.x(), relPos.y(), relPos.z());
result.put(worldPos, entry.getValue());
}
return result;
}
}
| 1,134 |
1,133 | //////////////////////////////////////
// <NAME>, NASA JPL/Caltech
// Copyright 2017
//////////////////////////////////////
// program for mosaicking multiple consecutive subswaths
// <NAME>, 03-JUN-2015
// JPL/Caltech
//////////////////////////////////////////////////////////////////
//update history
//12-APR-2016, CL. output data of both adjacent subswaths as BIL
// file, instead of output the difference.
//////////////////////////////////////////////////////////////////
#include "resamp.h"
//int main(int argc, char *argv[]){
int mosaicsubswath(char *outputfile, int nrgout, int nazout, int delta, int diffflag, int n, char **inputfile, int *nrgin, int *nrgoff, int *nazoff, float *phc, int *oflag){
FILE **infp;
FILE *outfp;
fcomplex **in;
fcomplex *out, out1, out2;
//fcomplex *leftoverlap;
//fcomplex *rightoverlap;
fcomplex tmp;
int cnt;
//int n;
//int *nrgin;
int *nazin;
//int *nrgoff;
//int *nazoff;
//int *oflag;
//int nrgout;
//int nazout;
int nrginmax;
int los, loe, low; //start, end and width of left overlap area
int ros, roe, row; //start, end and width of right overlap area
int cnw; //width of center area
int paroff;
int parcyc;
char diffname[256][256];
FILE **difffp;
fcomplex **diff;
fcomplex **diff2;
//int diffflag;
//diffflag = 0;
int ns;
float r;
int i, j, k, l;
//int delta; //edge to be removed of the overlap area (number of samples)
//delta = 20;
// if(argc < 5){
// fprintf(stderr, "\nUsage: %s outputfile nrgout nazout delta diffflag n [inputfile0] [nrgin0] [nrgoff0] [nazoff0] [oflag0] (repeat...)\n\n", argv[0]);
// fprintf(stderr, " for each frame\n");
// fprintf(stderr, " range offset is relative to the first sample of last subswath\n");
// fprintf(stderr, " azimuth offset is relative to the uppermost line\n\n");
// exit(1);
// }
//read mandatory parameters
outfp = openfile(outputfile, "wb");
//nrgout = atoi(argv[2]);
//nazout = atoi(argv[3]);
//delta = atoi(argv[4]);
//diffflag = atoi(argv[5]);
//n = atoi(argv[6]);
//allocate memory
infp = array1d_FILE(n);
//nrgin = array1d_int(n);
nazin = array1d_int(n);
//nrgoff = array1d_int(n); //nrgoff must be <= 0
//nazoff = array1d_int(n); //nazoff must be <= 0
//oflag = array1d_int(n);
difffp = array1d_FILE(n - 1);
//read optional parameters
paroff = 6;
parcyc = 5;
for(i = 0; i < n; i++){
infp[i] = openfile(inputfile[i], "rb");
//nrgin[i] = atoi(argv[paroff + parcyc*i + 2]);
//nrgoff[i] = atoi(argv[paroff + parcyc*i + 3]);
//nazoff[i] = atoi(argv[paroff + parcyc*i + 4]);
//oflag[i] = atoi(argv[paroff + parcyc*i + 5]);
nazin[i] = file_length(infp[i], nrgin[i], sizeof(fcomplex));
if(nrgoff[i] > 0){
fprintf(stderr,"Error: positive range offset: %d\n\n", nrgoff[i]);
exit(1);
}
if(nazoff[i] > 0){
fprintf(stderr,"Error: positive azimuth offset: %d\n\n", nazoff[i]);
exit(1);
}
if(nazout < nazin[i] - nazoff[i]){
fprintf(stderr,"Error: ouput length < nazin[%d] - nazoff[%d], %d, %d\n\n", i, i, nazout, nazin[i] - nazoff[i]);
exit(1);
}
}
//find max width
nrginmax = nrgin[0];
for(i = 0; i < n; i++)
if(nrgin[i] > nrginmax)
nrginmax = nrgin[i];
in = array2d_fcomplex(n, nrginmax);
out = array1d_fcomplex(nrgout);
//out1 = array1d_fcomplex(nrginmax);
//out2 = array1d_fcomplex(nrginmax);
diff = array2d_fcomplex(n-1, nrginmax);
diff2 = array2d_fcomplex(n-1, nrginmax);
if(diffflag == 0)
for(i = 0; i < n - 1; i++){
sprintf(diffname[i], "%d-%d.int", i, i+1);
difffp[i] = openfile(diffname[i], "wb");
}
for(i = 0; i < nazout; i++){
if((i + 1) % 1000 == 0)
fprintf(stderr,"processing line: %6d of %6d\r", i + 1, nazout);
if(i + 1 == nazout)
fprintf(stderr,"processing line: %6d of %6d\n\n", i + 1, nazout);
//prepare for writing data
for(j = 0; j < nrgout; j++){
out[j].re = 0.0;
out[j].im = 0.0;
}
//prepare for reading data
for(j = 0; j < n; j++){
for(k = 0; k < nrginmax; k++){
in[j][k].re = 0.0;
in[j][k].im = 0.0;
}
}
for(j = 0; j < n; j++){
if(i + nazoff[j] >= 0 && i + nazoff[j] <= nazin[j] - 1)
readdata((fcomplex *)in[j], nrgin[j] * sizeof(fcomplex), infp[j]);
if(phc[j]!=0.0){
tmp.re = cos(phc[j]);
tmp.im = sin(phc[j]);
for(k = 0; k < nrgin[j]; k++)
in[j][k] = cmul(in[j][k], tmp);
}
}
cnt = 0;
for(j = 0; j < n; j++){
//we follow the following convention: line and column number start with 0.
//left overlap area of subswath j
if(j != 0){
los = - nrgoff[j];
loe = nrgin[j-1] - 1;
low = loe - los + 1;
if(low < delta * 2){
fprintf(stderr,"Error: not enough overlap area between subswath: %d and %d\n\n", j-1, j);
exit(1);
}
}
else{
los = 0;
loe = 0;
low = 0;
}
//right overlap area of subswath j
if(j != n - 1){
ros = - nrgoff[j+1];
roe = nrgin[j] - 1;
row = roe - ros + 1;
if(row < delta * 2){
fprintf(stderr,"Error: not enough overlap area between subswath: %d and %d\n\n", j, j+1);
exit(1);
}
}
else{
ros = 0;
roe = 0;
row = 0;
}
//center non-overlap area of subswath j
//should add a check here?
cnw = nrgin[j] - low - row;
//deal with center non-overlap area.
//this only excludes the right overlap area for the first subswath
//this only excludes the left overlap area for the last subswath
for(k = 0; k < cnw; k++){
out[cnt + k].re = in[j][low + k].re;
out[cnt + k].im = in[j][low + k].im;
}
cnt += cnw;
//deal with right overlap area of subswath j, which is also the left overlap area
//of subswath j + 1 (next subswath)
//for last subswath, just skip
if(j == n - 1){
break;
}
for(k = 0; k < nrginmax; k++){
diff[j][k].re = 0.0;
diff[j][k].im = 0.0;
diff2[j][k].re = 0.0;
diff2[j][k].im = 0.0;
}
for(k = 0; k < row; k++){
out1.re = in[j][low + cnw + k].re;
out1.im = in[j][low + cnw + k].im;
out2.re = in[j+1][k].re;
out2.im = in[j+1][k].im;
//left edge of overlap area
//use current subswath: subswath j
if(k < delta){
out[cnt + k].re = out1.re;
out[cnt + k].im = out1.im;
}
else if(k >= delta && k < row - delta){
//output difference of overlap area
//diffflag 0: subswath j phase - subswath j+1 phase
if(diffflag == 0){
if(out1.re != 0.0 && out1.im != 0.0 && out2.re != 0.0 && out2.im != 0.0){
//diff[j][k - delta] = cmul(out1, cconj(out2));
diff[j][k - delta] = out1;
diff2[j][k - delta] = out2;
}
}
//diffflag 1: subswath j - subswath j+1
//else if(diffflag == 1){
// if(out1.re != 0.0 && out1.im != 0.0 && out2.re != 0.0 && out2.im != 0.0){
// diff[j][k - delta].re = out1.re - out2.re;
// diff[j][k - delta].im = out1.im - out2.im;
// }
//}
else{
;
}
//mosaic overlap area
//case 0: mosaic at the center of overlap area
if(oflag[j] == 0){
if(k < row / 2){
//avoid holes, <NAME>, Dec. 18, 2015.
if(out1.re != 0.0 && out1.im != 0.0){
out[cnt + k].re = out1.re;
out[cnt + k].im = out1.im;
}
else{
out[cnt + k].re = out2.re;
out[cnt + k].im = out2.im;
}
}
else{
//avoid holes, <NAME>, Dec. 18, 2015.
if(out2.re != 0.0 && out2.im != 0.0){
out[cnt + k].re = out2.re;
out[cnt + k].im = out2.im;
}
else{
out[cnt + k].re = out1.re;
out[cnt + k].im = out1.im;
}
}
}
//case 1: mosaic at the right egde of overlap area
else if(oflag[j] == 1){
out[cnt + k].re = out1.re;
out[cnt + k].im = out1.im;
}
//case 2: mosaic at the left edge of overlap area
else if(oflag[j] == 2){
out[cnt + k].re = out2.re;
out[cnt + k].im = out2.im;
}
//case 3: add overlap area
else if(oflag[j] == 3){
out[cnt + k].re = out1.re + out2.re;
out[cnt + k].im = out1.im + out2.im;
if(out1.re != 0.0 && out1.im != 0.0 && out2.re != 0.0 && out2.im != 0.0){
out[cnt + k].re /= 2.0;
out[cnt + k].im /= 2.0;
}
}
//case 4: add by weight determined by distance to overlap center
//perform overlapp area smoothing using a method discribed in:
//<NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, ScanSAR interferometric processing
//using existing standard InSAR software for measuring large scale land deformation
//Computers & Geosciences, 2013.
else{
l = k - delta + 1; // l start with 1
ns = row - 2 * delta;
if(out1.re != 0.0 && out1.im != 0.0 && out2.re != 0.0 && out2.im != 0.0){
r = sqrt((out1.re * out1.re + out1.im * out1.im) / (out2.re * out2.re + out2.im * out2.im));
out[cnt + k].re = ((ns - l + 0.5) * out1.re + r * (l - 0.5) * out2.re) / ns;
out[cnt + k].im = ((ns - l + 0.5) * out1.im + r * (l - 0.5) * out2.im) / ns;
}
else{
out[cnt + k].re = out1.re + out2.re;
out[cnt + k].im = out1.im + out2.im;
}
}
//cnt += row - 2 * delta;
}
//right edge of overlap area
//use next subswath: subswath j+1
//else if(k >= row - delta){
else{
out[cnt + k].re = out2.re;
out[cnt + k].im = out2.im;
}
//cnt += 1;
}
cnt += row;
if(diffflag == 0){
writedata((fcomplex *)diff[j], (row - 2 * delta) * sizeof(fcomplex), difffp[j]);
writedata((fcomplex *)diff2[j], (row - 2 * delta) * sizeof(fcomplex), difffp[j]);
}
} //loop of j, subswath
writedata((fcomplex *)out, nrgout * sizeof(fcomplex), outfp);
} //loop of i, output line
for(i = 0; i < n; i++)
fclose(infp[i]);
fclose(outfp);
if(diffflag == 0)
for(i = 0; i < n - 1; i++)
fclose(difffp[i]);
free_array1d_FILE(infp);
free_array1d_FILE(difffp);
free_array2d_fcomplex(in);
free_array1d_fcomplex(out);
//free_array1d_int(nrgin);
free_array1d_int(nazin);
//free_array1d_int(nrgoff); //nrgoff must be <= 0
//free_array1d_int(nazoff); //nazoff must be <= 0
//free_array1d_int(oflag);
free_array2d_fcomplex(diff);
free_array2d_fcomplex(diff2);
return 0;
}
| 6,375 |
5,169 | {
"name": "ADAlertController",
"version": "1.0.0",
"summary": "ADAlertController 是一个与 UIAlertController 类似风格的 UI 控件",
"description": "ADAlertController 是一个与 UIAlertController 类似风格的 UI 控件,包含 Alert 和 ActionSheet 以及无边距的 ActionSheet(ADAlertControllerStyleSheet) 等 UI类型.与UIAlertController 有相似的 API.并支持自定义视图,以及优先级队列",
"homepage": "https://github.com/huangxianhui001/ADAlertController",
"license": "MIT",
"authors": {
"huangxianhuiMacBook": "<EMAIL>"
},
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/huangxianhui001/ADAlertController.git",
"tag": "1.0.0"
},
"source_files": "ADAlertController/**/*.{h,m}",
"frameworks": [
"UIKit",
"Foundation"
],
"requires_arc": true
}
| 385 |
5,169 | <gh_stars>1000+
{
"name": "shopAR",
"version": "1.5",
"summary": "shopAR enables retail-based iOS apps to easily integrate Augmented Reality product-viewing at the touch of a button.",
"screenshots": [
"./IMG_9023.JPG",
"./IMG_9024.JPG",
"./IMG_9025.JPG"
],
"description": "shopAR for iOS\n\nOverview\n\t\nshopAR allows you to upload .scn files through our React app accessible at shoppar.herokuapp.com/. Files are stored by our API using AWS s3, and our CocoaPod enables interaction with these services for easy in-app retrieval and display.\n\nshopAR provides an example project that includes a ViewController that enables you to view .scn objects in Augmented Reality. If your app does not already have AR capabilities, instructions for easy integration of this file are below.\n\nPod Installation\n\n1. Add the following line to the Podfile:\n pod \"ShopApp_Shopify\", \"~> 1.0\"\n2. Install the dependencies:\n pod install\n\nAR ViewController Installation\n\n1. Drag ARPopUpViewController.swift into your build target directory.\n2. In Main.storyboard (or your app’s primary storyboard), add a new ViewController and set its class to ARPopUpViewController.\n3. Add the below tag to your app’s info.plist:\n <key>NSCameraUsageDescription</key>\n <string>For Augemented Reality</string>\n\nUsage\n\n1. Upload a .scn file at shoppar.herokuapp.com/\n2. Import shopAR atop your file and create an instance with var shop = shopAR()\n **For the following steps, we highly recommend you closely follow the shopAR Example project included. There you can find code for the steps described here.**\n3. In your desired file’s viewDidLoad(), call shop.fetchObject(user_id, file_id) for each file_id that you uploaded online. Here, file_id refers to the exact name of the file you uploaded. User_id is a constant found in the shopAR example until login functionality is finalized at shoppar.herokuapp.com/.\n4. Save each returned url String from fetchObject(). All of this should be done in viewDidLoad().\n5. When an item’s button is pressed, create an instance of the ARPopUpViewController, pass it the desired url String, and present it",
"homepage": "https://github.com/thefishstick/shopAR",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>",
"<NAME>": "<EMAIL>"
},
"platforms": {
"ios": "11.3"
},
"source": {
"git": "https://github.com/thefishstick/shopAR.git",
"tag": "1.5"
},
"source_files": [
"shopAR",
"shopAR/**/*.{h,m}"
],
"exclude_files": "shopAR/Exclude"
}
| 813 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_EDITOR_AI_NAVDATAGENERATION_WAYPOINTHUMANNAVREGION_H
#define CRYINCLUDE_EDITOR_AI_NAVDATAGENERATION_WAYPOINTHUMANNAVREGION_H
#pragma once
#include "NavRegion.h"
#include "AICollision.h"
#include <set>
class CNavigation;
#ifdef STATUS_PENDING
#undef STATUS_PENDING
#endif
/// Handles all graph operations that relate to the indoor/waypoint aspect
class CWaypointHumanNavRegion
: public CNavRegion
{
public:
CWaypointHumanNavRegion(CNavigation* pGraph);
virtual ~CWaypointHumanNavRegion();
/// inherited
virtual unsigned GetEnclosing(const Vec3& pos, float passRadius = 0.0f, unsigned startIndex = 0,
float range = -1.0f, Vec3* closestValid = 0, bool returnSuspect = false, const char* requesterName = "");
/// Serialise the _modifications_ since load-time
virtual void Serialize(TSerialize ser);
/// inherited
virtual void Clear();
/// inherited
virtual void Reset(IAISystem::EResetReason reason);
/// inherited
virtual size_t MemStats();
// Functions specific to this navigation region
unsigned GetClosestNode(const Vec3& pos, int nBuildingID);
/// As IGraph. If flushQueue then the pending update queue is processed.
/// If false then this reconnection request gets queued
void ReconnectWaypointNodesInBuilding(int nBuildingID);
/// Removes all automatically generated links (not affecting
/// hand-generated links)
void RemoveAutoLinksInBuilding(int nBuildingID);
/// Finds the floor position then checks if a body will fit there, using the passability
/// parameters. If pRenderer != 0 then the body gets drawn (green if it's OK, red if not)
bool CheckAndDrawBody(const Vec3& pos, IRenderer* pRenderer);
// should be called when anything happens that might upset the dynamic updates (e.g. node created/destroyed)
void ResetUpdateStatus();
//void CheckLinkLengths() const;
// TODO Mai 21, 2007: <pvl> if there are links connecting two waypoints
// in both directions, this iterator currently returns only one of them,
// picked up at random essentially. This means that it's only useful
// for retrieving unidirectional data (that are the same in both directions).
// It would be fairly easy make the iterator configurable so it can
// optionally return both directions for any two given nodes.
/// Iterates over all links in a graph that connect two human waypoints.
class LinkIterator
{
const CGraph* m_pGraph;
std::unique_ptr <CAllNodesContainer::Iterator> m_currNodeIt;
unsigned int m_currLinkIndex;
void FindNextWaypointLink();
public:
LinkIterator (const CWaypointHumanNavRegion*);
LinkIterator (const LinkIterator&);
operator bool () const {
return m_currLinkIndex != 0;
}
LinkIterator& operator++ ();
unsigned int operator* () const { return m_currLinkIndex; }
};
// TODO Mai 21, 2007: <pvl> doesn't really need to be a friend, just needs to access
// region's m_pGraph member ...
friend class LinkIterator;
LinkIterator CreateLinkIterator () const { return LinkIterator (this); }
private:
void FillGreedyMap(unsigned nodeIndex, const Vec3& pos,
IVisArea* pTargetArea, bool bStayInArea, CandidateIdMap& candidates);
/// Returns true if the link between two nodes would intersect the boundary (in 2D)
bool WouldLinkIntersectBoundary(const Vec3& pos1, const Vec3& pos2, const ListPositions& boundary) const;
/// just disconnects automatically created links
void RemoveAutoLinks(unsigned nodeIndex);
/// Connect all nodes - the two cache lists can overlap.
/// Links are connected in order of increasing distance. Linking continues
/// until (1) dist > maxDistNormal and either (2.1) a node has > nLinksForMaxDistMax
/// or (2.2) dist > maxDistMax
void ConnectNodes(const struct SpecialArea* pArea, EAICollisionEntities collisionEntities, float maxDistNormal, float maxDistMax, unsigned nLinksForMaxDistMax);
/// Modify all connections within an area
void ModifyConnections(const struct SpecialArea* pArea, EAICollisionEntities collisionEntities, bool adjustOriginalEditorLinks);
/// checks and modifies a single connection coming from a node.
void ModifyNodeConnections(unsigned nodeIndex, EAICollisionEntities collisionEntities, unsigned iLink, bool adjustOriginalEditorLinks);
#if 0
/// Checks walkability using a faster algorithm than CheckWalkability() if possible.
bool CheckPassability(unsigned linkIndex, Vec3 from, Vec3 to,
float paddingRadius, bool checkStart,
const ListPositions& boundary,
EAICollisionEntities aiCollisionEntities,
SCachedPassabilityResult* pCachedResult,
SCheckWalkabilityState* pCheckWalkabilityState);
#endif
/// Finds out if a link is eligible for simplified passability check. The
/// first return value says if the link is passable at all. If not, the second
/// one is not meaningful, otherwise it indicates if the link is also "simple".
/// Note that all of the above is only valid if pCheckWalkabilityState->state
/// is RESULT on return - otherwise the computation hasn't completed yet
/// and passability information isn't available at all in the first place.
std::pair<bool, bool> CheckIfLinkSimple(Vec3 from, Vec3 to,
float paddingRadius, bool checkStart,
const ListPositions& boundary,
EAICollisionEntities aiCollisionEntities,
SCheckWalkabilityState* pCheckWalkabilityState);
private:
typedef std::vector< std::pair<float, unsigned> > TNodes;
private:
static size_t s_instanceCount;
static TNodes s_tmpNodes;
private:
/// Iterator over all nodes for distributing the cxn modifications over multiple updates
CAllNodesContainer::Iterator* m_currentNodeIt;
/// link counter for distributing the cxn modifications over multiple updates
unsigned m_currentLink;
/// Used for distributing walkability checks over multiple updates
SCheckWalkabilityState m_checkWalkabilityState;
CNavigation* m_pNavigation;
// Prevent copy as it would break the instance count
CWaypointHumanNavRegion(const CWaypointHumanNavRegion&);
CWaypointHumanNavRegion& operator=(const CWaypointHumanNavRegion&);
};
#endif // CRYINCLUDE_EDITOR_AI_NAVDATAGENERATION_WAYPOINTHUMANNAVREGION_H
| 2,189 |
2,151 | <reponame>zipated/src
// 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.
#include "components/spellcheck/renderer/spellcheck_panel.h"
#include "base/bind.h"
#include "base/metrics/histogram_macros.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/local_interface_provider.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/web/web_local_frame.h"
SpellCheckPanel::SpellCheckPanel(
content::RenderFrame* render_frame,
service_manager::BinderRegistry* registry,
service_manager::LocalInterfaceProvider* embedder_provider)
: content::RenderFrameObserver(render_frame),
spelling_panel_visible_(false),
embedder_provider_(embedder_provider) {
DCHECK(render_frame);
DCHECK(embedder_provider);
registry->AddInterface(base::BindRepeating(
&SpellCheckPanel::SpellCheckPanelRequest, base::Unretained(this)));
render_frame->GetWebFrame()->SetSpellCheckPanelHostClient(this);
}
SpellCheckPanel::~SpellCheckPanel() = default;
void SpellCheckPanel::OnDestruct() {
delete this;
}
bool SpellCheckPanel::IsShowingSpellingUI() {
return spelling_panel_visible_;
}
void SpellCheckPanel::ShowSpellingUI(bool show) {
UMA_HISTOGRAM_BOOLEAN("SpellCheck.api.showUI", show);
GetSpellCheckPanelHost()->ShowSpellingPanel(show);
}
void SpellCheckPanel::UpdateSpellingUIWithMisspelledWord(
const blink::WebString& word) {
GetSpellCheckPanelHost()->UpdateSpellingPanelWithMisspelledWord(word.Utf16());
}
void SpellCheckPanel::SpellCheckPanelRequest(
spellcheck::mojom::SpellCheckPanelRequest request) {
bindings_.AddBinding(this, std::move(request));
}
void SpellCheckPanel::AdvanceToNextMisspelling() {
auto* render_frame = content::RenderFrameObserver::render_frame();
DCHECK(render_frame->GetWebFrame());
render_frame->GetWebFrame()->ExecuteCommand(
blink::WebString::FromUTF8("AdvanceToNextMisspelling"));
}
void SpellCheckPanel::ToggleSpellPanel(bool visible) {
auto* render_frame = content::RenderFrameObserver::render_frame();
DCHECK(render_frame->GetWebFrame());
// Tell our frame whether the spelling panel is visible or not so
// that it won't need to make mojo calls later.
spelling_panel_visible_ = visible;
render_frame->GetWebFrame()->ExecuteCommand(
blink::WebString::FromUTF8("ToggleSpellPanel"));
}
spellcheck::mojom::SpellCheckPanelHostPtr
SpellCheckPanel::GetSpellCheckPanelHost() {
spellcheck::mojom::SpellCheckPanelHostPtr spell_check_panel_host;
embedder_provider_->GetInterface(&spell_check_panel_host);
return spell_check_panel_host;
}
| 922 |
432 | <reponame>lambdaxymox/DragonFlyBSD
/*-
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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.
*
* @(#)cribcur.h 8.1 (Berkeley) 5/31/93
* $DragonFly: src/games/cribbage/cribcur.h,v 1.2 2005/08/03 13:31:00 eirikn Exp $
*/
# define PLAY_Y 15 /* size of player's hand window */
# define PLAY_X 12
# define TABLE_Y 21 /* size of table window */
# define TABLE_X 14
# define COMP_Y 15 /* size of computer's hand window */
# define COMP_X 12
# define Y_SCORE_SZ 9 /* Y size of score board */
# define X_SCORE_SZ 41 /* X size of score board */
# define SCORE_Y 0 /* starting position of scoring board */
# define SCORE_X (PLAY_X + TABLE_X + COMP_X)
# define CRIB_Y 17 /* position of crib (cut card) */
# define CRIB_X (PLAY_X + TABLE_X)
# define MSG_Y (LINES - (Y_SCORE_SZ + 1))
# define MSG_X (COLS - SCORE_X - 1)
# define Y_MSG_START (Y_SCORE_SZ + 1)
# define PEG '*' /* what a peg looks like on the board */
extern WINDOW *Compwin; /* computer's hand window */
extern WINDOW *Msgwin; /* message window */
extern WINDOW *Playwin; /* player's hand window */
extern WINDOW *Tablewin; /* table window */
| 902 |
799 | <reponame>diCagri/content<filename>Packs/PenfieldAI/Scripts/PenfieldAssign/PenfieldAssign_test.py
"""Base Script for Cortex XSOAR - Unit Tests file
Pytest Unit Tests: all funcion names must start with "test_"
More details: https://xsoar.pan.dev/docs/integrations/unit-testing
MAKE SURE YOU REVIEW/REPLACE ALL THE COMMENTS MARKED AS "TODO"
"""
import demistomock as demisto
import json
import io
from PenfieldAssign import penfield_assign, main
# from pytest import *
def util_load_json(path):
with io.open(path, mode='r', encoding='utf-8') as f:
return json.loads(f.read())
# DUMMY DATA
fake_analyst_ids = 'admin,person'
fake_category = 'fake_cat'
fake_created = 'fake_date'
fake_id = 'fake_id'
fake_name = 'fake_name'
fake_severity = 'Low'
# TODO: REMOVE the following dummy unit test function
fake_response = [{
'Contents': 'test_user'
}]
def test_penfield_assign(mocker):
# this overwrite the command call
mocker.patch.object(demisto, 'executeCommand', return_value=fake_response)
assert penfield_assign(
analyst_ids=fake_analyst_ids,
category=fake_category,
created=fake_created,
id=fake_id,
name=fake_name,
severity=fake_severity
) == fake_response
def test_main(mocker):
mock_users = util_load_json('test_data/test_2_users.json')
mock_incident = util_load_json('test_data/test_incident.json')
# overwrite get users, incidents, and args
mocker.patch.object(demisto, 'executeCommand', return_value=mock_users)
mocker.patch.object(demisto, 'incidents', return_value=mock_incident)
mocker.patch.object(demisto, 'args', return_value={'assign': "No"})
mocker.patch('PenfieldAssign.penfield_assign', return_value=fake_response)
mocker.patch.object(demisto, 'results')
main()
assert demisto.results.call_args.args[0] == 'penfield suggests: test_user'
| 719 |
1,102 | /*
#include "actor.h"
#include "p_enemy.h"
#include "a_action.h"
#include "m_random.h"
#include "thingdef/thingdef.h"
*/
static FRandom pr_centaurdefend ("CentaurDefend");
//============================================================================
//
// A_CentaurDefend
//
//============================================================================
DEFINE_ACTION_FUNCTION(AActor, A_CentaurDefend)
{
A_FaceTarget (self);
if (self->CheckMeleeRange() && pr_centaurdefend() < 32)
{
// This should unset REFLECTIVE as well
// (unless you want the Centaur to reflect projectiles forever!)
self->flags2&=~(MF2_REFLECTIVE|MF2_INVULNERABLE);
self->SetState (self->MeleeState);
}
}
| 253 |
429 | /*
* Copyright (c) 2020, <NAME>. All Rights Reserved.
*
* This file is part of Efficient Java Matrix Library (EJML).
*
* 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.ejml.data;
import org.ejml.UtilEjml;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author <NAME>
*/
public class TestDMatrixSparseTriplet extends GenericTestsDMatrixSparse {
@Test
void constructor() {
DMatrixSparseTriplet m = new DMatrixSparseTriplet(1, 1, 10);
assertEquals(0, m.getLength());
assertEquals(10, m.nz_value.data.length);
assertEquals(20, m.nz_rowcol.data.length);
}
@Test
void addItem() {
DMatrixSparseTriplet m = new DMatrixSparseTriplet(1, 1, 2);
m.addItem(1, 2, 3);
m.addItem(1, 3, 4);
assertEquals(2, m.nz_length);
assertTrue(2 <= m.nz_value.data.length);
assertTrue(4 <= m.nz_rowcol.data.length);
check(m, 0, 1, 2, 3);
check(m, 1, 1, 3, 4);
// now force it to grow
m.addItem(2, 3, 5);
assertEquals(3, m.nz_length);
assertTrue(m.nz_value.data.length >= 3);
check(m, 0, 1, 2, 3);
check(m, 1, 1, 3, 4);
check(m, 2, 2, 3, 5);
}
private void check( DMatrixSparseTriplet m, int index, int row, int col, double value ) {
assertEquals(row, m.nz_rowcol.data[index*2]);
assertEquals(col, m.nz_rowcol.data[index*2 + 1]);
assertEquals(value, m.nz_value.data[index], UtilEjml.TEST_F64);
}
@Test
void findItem() {
DMatrixSparseTriplet m = new DMatrixSparseTriplet(3, 4, 5);
m.addItem(1, 2, 5);
assertEquals(-1, m.nz_index(0, 1));
check(m, m.nz_index(1, 2), 1, 2, 5);
}
@Override
public DMatrixSparse createSparse( int numRows, int numCols ) {
return new DMatrixSparseTriplet(numRows, numCols, 10);
}
@Override
public DMatrixSparse createSparse( DMatrixSparseTriplet orig ) {
return new DMatrixSparseTriplet(orig);
}
@Override
public boolean isStructureValid( DMatrixSparse m ) {
return true;
}
}
| 1,155 |
5,411 | #include <StdInc.h>
#include <CoreConsole.h>
#include <GameInit.h>
#include <Error.h>
#include <MinHook.h>
#include <Hooking.h>
#include <nutsnbolts.h>
//
// Game reload code flow:
// 1. GameInit::KillNetwork
// 2. Triggers OnKillNetwork, where we'll set loading screen override and set the init state to 'reload save'.
// 3. Game will execute session shutdown, which we intercept with a blocking (busy-ish) loop at the end,
// and triggering events before and after.
// 4. When GameInit::ReloadGame is called, we'll return and let the game finish reloading.
//
static bool g_setLoadingScreens;
static bool g_shouldKillNetwork;
bool g_isNetworkKilled;
// 1207.80
// instead of setting init state
static hook::cdecl_stub<void(bool)> _newGame([]()
{
return hook::get_call(hook::get_pattern("33 C9 E8 ? ? ? ? B1 01 E8 ? ? ? ? 83 63 08 00", 9));
});
static hook::cdecl_stub<void(int)> setupLoadingScreens([]()
{
return hook::get_pattern("83 FA 01 75 ? 8B 05 ? ? ? ? 8A CA 89 05", -0x3A);
});
static hook::cdecl_stub<void()> loadingScreenUpdate([]()
{
return hook::get_pattern("74 53 48 83 64 24 20 00 4C 8D", -0x31);
});
void SetRenderThreadOverride()
{
g_setLoadingScreens = true;
}
static void(*g_shutdownSession)();
extern hook::cdecl_stub<void()> _doLookAlive;
void ShutdownSessionWrap()
{
Instance<ICoreGameInit>::Get()->SetVariable("gameKilled");
Instance<ICoreGameInit>::Get()->SetVariable("shutdownGame");
g_isNetworkKilled = true;
AddCrashometry("kill_network_game", "true");
OnKillNetworkDone();
g_shutdownSession();
Instance<ICoreGameInit>::Get()->OnShutdownSession();
g_shouldKillNetwork = false;
while (g_isNetworkKilled)
{
// warning screens apparently need to run on main thread
OnGameFrame();
OnMainGameFrame();
Sleep(0);
_doLookAlive();
// todo: add critical servicing
}
Instance<ICoreGameInit>::Get()->OnGameRequestLoad();
}
static InitFunction initFunction([]()
{
OnKillNetwork.Connect([=](const char* message)
{
AddCrashometry("kill_network", "true");
AddCrashometry("kill_network_msg", message);
trace("Killing network: %s\n", message);
g_shouldKillNetwork = true;
Instance<ICoreGameInit>::Get()->ClearVariable("networkInited");
SetRenderThreadOverride();
}, 500);
OnLookAliveFrame.Connect([]()
{
if (g_setLoadingScreens)
{
setupLoadingScreens(1);
loadingScreenUpdate();
g_setLoadingScreens = false;
}
if (g_shouldKillNetwork)
{
trace("Killing network, stage 2...\n");
_newGame(false);
g_shouldKillNetwork = false;
}
});
static ConsoleCommand reloadTest("reloadTest", []()
{
g_setLoadingScreens = true;
g_shouldKillNetwork = true;
});
});
static int Return0()
{
return 0;
}
static int Return2()
{
return 2;
}
static HookFunction hookFunction([]()
{
// never try to reload SP save
//hook::jump(hook::get_pattern("48 8B 03 48 8B CB FF 50 38 48 8B C8 E8 ? ? ? ? F6 D8", -0x12), Return0);
hook::jump(hook::get_pattern("84 C0 8D 4B 02 0F 44 D9", -0x10), Return2);
// don't try the SP transition if we're init type 15
hook::put<uint8_t>(hook::get_pattern("83 F8 0F 75 58 8B 4B 0C", 3), 0xEB);
// shutdown session wrapper
{
MH_Initialize();
MH_CreateHook(hook::get_pattern("41 B9 13 00 00 00 45 33 C0 33 D2", -0x51), ShutdownSessionWrap, (void**)&g_shutdownSession);
MH_EnableHook(MH_ALL_HOOKS);
}
});
| 1,238 |
366 | from django.conf import settings
redis_host = None
redis_port = None
redis_db = None
redis_password = None
redis_socket = None
def get_redis_host():
global redis_host
if not redis_host:
redis_host = getattr(settings, 'SWAMP_DRAGON_REDIS_HOST', 'localhost')
return redis_host
def get_redis_port():
global redis_port
if not redis_port:
redis_port = getattr(settings, 'SWAMP_DRAGON_REDIS_PORT', 6379)
return redis_port
def get_redis_db():
global redis_db
if not redis_db:
redis_db = getattr(settings, 'SWAMP_DRAGON_REDIS_DB', 0)
return redis_db
def get_redis_password():
global redis_password
if not redis_password:
redis_password = getattr(settings, 'SWAMP_DRAGON_REDIS_PASSWORD', None)
return redis_password
def get_redis_socket():
global redis_socket
if not redis_socket:
redis_socket = getattr(settings, 'SWAMP_DRAGON_REDIS_SOCKET', None)
return redis_socket
| 411 |
679 | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include "rtl/textcvt.h"
#include <tools/debug.hxx>
namespace { // anonymous namespace
// ====================================================================
#define MAX_CVT_SELECT 6
class ConverterCache
{
public:
explicit ConverterCache( void );
~ConverterCache( void );
sal_uInt16 convertOne( int nSelect, sal_Unicode );
void convertStr( int nSelect, const sal_Unicode* pSrc, sal_uInt16* pDst, int nCount );
protected:
void ensureConverter( int nSelect );
private:
rtl_UnicodeToTextConverter maConverterCache[ MAX_CVT_SELECT+1 ];
rtl_UnicodeToTextContext maContexts[ MAX_CVT_SELECT+1 ];
};
// ====================================================================
ConverterCache::ConverterCache( void)
{
for( int i = 0; i <= MAX_CVT_SELECT; ++i)
{
maConverterCache[i] = NULL;
maContexts[i] = NULL;
}
}
// --------------------------------------------------------------------
ConverterCache::~ConverterCache( void)
{
for( int i = 0; i <= MAX_CVT_SELECT; ++i)
{
if( !maContexts[i] )
continue;
rtl_destroyUnicodeToTextContext( maConverterCache[i], maContexts[i] );
rtl_destroyUnicodeToTextConverter( maConverterCache[i] );
}
}
// --------------------------------------------------------------------
void ConverterCache::ensureConverter( int nSelect )
{
// DBG_ASSERT( (2<=nSelect) && (nSelect<=MAX_CVT_SELECT)), "invalid XLAT.Converter requested" );
rtl_UnicodeToTextContext aContext = maContexts[ nSelect ];
if( !aContext )
{
rtl_TextEncoding eRecodeFrom = RTL_TEXTENCODING_UNICODE;
switch( nSelect )
{
default: nSelect = 1; // fall through to unicode recoding
case 1: eRecodeFrom = RTL_TEXTENCODING_UNICODE; break;
case 2: eRecodeFrom = RTL_TEXTENCODING_SHIFT_JIS; break;
case 3: eRecodeFrom = RTL_TEXTENCODING_GB_2312; break;
case 4: eRecodeFrom = RTL_TEXTENCODING_BIG5; break;
case 5: eRecodeFrom = RTL_TEXTENCODING_MS_949; break;
case 6: eRecodeFrom = RTL_TEXTENCODING_MS_1361; break;
}
rtl_UnicodeToTextConverter aRecodeConverter = rtl_createUnicodeToTextConverter( eRecodeFrom );
maConverterCache[ nSelect ] = aRecodeConverter;
aContext = rtl_createUnicodeToTextContext( aRecodeConverter );
maContexts[ nSelect ] = aContext;
}
rtl_resetUnicodeToTextContext( maConverterCache[ nSelect ], aContext );
}
// --------------------------------------------------------------------
sal_uInt16 ConverterCache::convertOne( int nSelect, sal_Unicode aChar )
{
ensureConverter( nSelect );
sal_Unicode aUCS2Char = aChar;
sal_Char aTempArray[8];
sal_Size nTempSize;
sal_uInt32 nCvtInfo;
// TODO: use direct unicode->mbcs converter should there ever be one
int nCodeLen = rtl_convertUnicodeToText(
maConverterCache[ nSelect ], maContexts[ nSelect ],
&aUCS2Char, 1, aTempArray, sizeof(aTempArray),
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_0
| RTL_UNICODETOTEXT_FLAGS_INVALID_0,
&nCvtInfo, &nTempSize );
sal_uInt16 aCode = aTempArray[0];
for( int i = 1; i < nCodeLen; ++i )
aCode = (aCode << 8) + (aTempArray[i] & 0xFF);
return aCode;
}
// --------------------------------------------------------------------
void ConverterCache::convertStr( int nSelect, const sal_Unicode* pSrc, sal_uInt16* pDst, int nCount )
{
ensureConverter( nSelect );
for( int n = 0; n < nCount; ++n )
{
sal_Unicode aUCS2Char = pSrc[n];
sal_Char aTempArray[8];
sal_Size nTempSize;
sal_uInt32 nCvtInfo;
// assume that non-unicode-fonts do not support codepoints >U+FFFF
// TODO: use direct unicode->mbcs converter should there ever be one
int nCodeLen = rtl_convertUnicodeToText(
maConverterCache[ nSelect ], maContexts[ nSelect ],
&aUCS2Char, 1, aTempArray, sizeof(aTempArray),
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_0
| RTL_UNICODETOTEXT_FLAGS_INVALID_0,
&nCvtInfo, &nTempSize );
sal_uInt16 aCode = aTempArray[0];
for( int i = 1; i < nCodeLen; ++i )
aCode = (aCode << 8) + (aTempArray[i] & 0xFF);
pDst[n] = aCode;
}
}
} // anonymous namespace
// ====================================================================
#include "xlat.hxx"
namespace vcl
{
static ConverterCache aCC;
sal_uInt16 TranslateChar12(sal_uInt16 src)
{
return aCC.convertOne( 2, src);
}
sal_uInt16 TranslateChar13(sal_uInt16 src)
{
return aCC.convertOne( 3, src);
}
sal_uInt16 TranslateChar14(sal_uInt16 src)
{
return aCC.convertOne( 4, src);
}
sal_uInt16 TranslateChar15(sal_uInt16 src)
{
return aCC.convertOne( 5, src);
}
sal_uInt16 TranslateChar16(sal_uInt16 src)
{
return aCC.convertOne( 6, src);
}
void TranslateString12(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n)
{
aCC.convertStr( 2, src, dst, n);
}
void TranslateString13(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n)
{
aCC.convertStr( 3, src, dst, n);
}
void TranslateString14(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n)
{
aCC.convertStr( 4, src, dst, n);
}
void TranslateString15(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n)
{
aCC.convertStr( 5, src, dst, n);
}
void TranslateString16(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n)
{
aCC.convertStr( 6, src, dst, n);
}
} // namespace vcl
| 2,306 |
310 | {
"name": "ExpressVPN",
"description": "A VPN service.",
"url": "https://www.expressvpn.com/"
}
| 39 |
2,151 | <reponame>lianhuaren/webrtc
/*
* Copyright 2018 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <memory>
#include <tuple>
#include <utility>
#include "media/base/fakertp.h"
#include "p2p/base/fakedtlstransport.h"
#include "p2p/base/fakeicetransport.h"
#include "pc/jseptransport.h"
#include "rtc_base/gunit.h"
namespace cricket {
using webrtc::SdpType;
static const char kIceUfrag1[] = "U001";
static const char kIcePwd1[] = "<PASSWORD>";
static const char kIceUfrag2[] = "U002";
static const char kIcePwd2[] = "<PASSWORD>";
static const char kTransportName[] = "Test Transport";
enum class SrtpMode {
kSdes,
kDtlsSrtp,
};
struct NegotiateRoleParams {
ConnectionRole local_role;
ConnectionRole remote_role;
SdpType local_type;
SdpType remote_type;
};
class JsepTransport2Test : public testing::Test, public sigslot::has_slots<> {
protected:
std::unique_ptr<webrtc::SrtpTransport> CreateSdesTransport(
rtc::PacketTransportInternal* rtp_packet_transport,
rtc::PacketTransportInternal* rtcp_packet_transport) {
auto srtp_transport = rtc::MakeUnique<webrtc::SrtpTransport>(
rtcp_packet_transport == nullptr);
srtp_transport->SetRtpPacketTransport(rtp_packet_transport);
if (rtcp_packet_transport) {
srtp_transport->SetRtcpPacketTransport(rtp_packet_transport);
}
return srtp_transport;
}
std::unique_ptr<webrtc::DtlsSrtpTransport> CreateDtlsSrtpTransport(
cricket::DtlsTransportInternal* rtp_dtls_transport,
cricket::DtlsTransportInternal* rtcp_dtls_transport) {
auto dtls_srtp_transport = rtc::MakeUnique<webrtc::DtlsSrtpTransport>(
rtcp_dtls_transport == nullptr);
dtls_srtp_transport->SetDtlsTransports(rtp_dtls_transport,
rtcp_dtls_transport);
return dtls_srtp_transport;
}
// Create a new JsepTransport with a FakeDtlsTransport and a
// FakeIceTransport.
std::unique_ptr<JsepTransport> CreateJsepTransport2(bool rtcp_mux_enabled,
SrtpMode srtp_mode) {
auto ice = rtc::MakeUnique<FakeIceTransport>(kTransportName,
ICE_CANDIDATE_COMPONENT_RTP);
auto rtp_dtls_transport =
rtc::MakeUnique<FakeDtlsTransport>(std::move(ice));
std::unique_ptr<FakeDtlsTransport> rtcp_dtls_transport;
if (!rtcp_mux_enabled) {
ice = rtc::MakeUnique<FakeIceTransport>(kTransportName,
ICE_CANDIDATE_COMPONENT_RTCP);
rtcp_dtls_transport = rtc::MakeUnique<FakeDtlsTransport>(std::move(ice));
}
std::unique_ptr<webrtc::RtpTransport> unencrypted_rtp_transport;
std::unique_ptr<webrtc::SrtpTransport> sdes_transport;
std::unique_ptr<webrtc::DtlsSrtpTransport> dtls_srtp_transport;
switch (srtp_mode) {
case SrtpMode::kSdes:
sdes_transport = CreateSdesTransport(rtp_dtls_transport.get(),
rtcp_dtls_transport.get());
sdes_transport_ = sdes_transport.get();
break;
case SrtpMode::kDtlsSrtp:
dtls_srtp_transport = CreateDtlsSrtpTransport(
rtp_dtls_transport.get(), rtcp_dtls_transport.get());
break;
default:
RTC_NOTREACHED();
}
auto jsep_transport = rtc::MakeUnique<JsepTransport>(
kTransportName, /*local_certificate=*/nullptr,
std::move(unencrypted_rtp_transport), std::move(sdes_transport),
std::move(dtls_srtp_transport), std::move(rtp_dtls_transport),
std::move(rtcp_dtls_transport));
signal_rtcp_mux_active_received_ = false;
jsep_transport->SignalRtcpMuxActive.connect(
this, &JsepTransport2Test::OnRtcpMuxActive);
return jsep_transport;
}
JsepTransportDescription MakeJsepTransportDescription(
bool rtcp_mux_enabled,
const char* ufrag,
const char* pwd,
const rtc::scoped_refptr<rtc::RTCCertificate>& cert,
ConnectionRole role = CONNECTIONROLE_NONE) {
JsepTransportDescription jsep_description;
jsep_description.rtcp_mux_enabled = rtcp_mux_enabled;
std::unique_ptr<rtc::SSLFingerprint> fingerprint;
if (cert) {
fingerprint.reset(rtc::SSLFingerprint::CreateFromCertificate(cert));
}
jsep_description.transport_desc =
TransportDescription(std::vector<std::string>(), ufrag, pwd,
ICEMODE_FULL, role, fingerprint.get());
return jsep_description;
}
Candidate CreateCandidate(int component) {
Candidate c;
c.set_address(rtc::SocketAddress("192.168.1.1", 8000));
c.set_component(component);
c.set_protocol(UDP_PROTOCOL_NAME);
c.set_priority(1);
return c;
}
void OnRtcpMuxActive() { signal_rtcp_mux_active_received_ = true; }
std::unique_ptr<JsepTransport> jsep_transport_;
bool signal_rtcp_mux_active_received_ = false;
// The SrtpTransport is owned by |jsep_transport_|. Keep a raw pointer here
// for testing.
webrtc::SrtpTransport* sdes_transport_ = nullptr;
};
// The parameterized tests cover both cases when RTCP mux is enable and
// disabled.
class JsepTransport2WithRtcpMux : public JsepTransport2Test,
public testing::WithParamInterface<bool> {};
// This test verifies the ICE parameters are properly applied to the transports.
TEST_P(JsepTransport2WithRtcpMux, SetIceParameters) {
bool rtcp_mux_enabled = GetParam();
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
JsepTransportDescription jsep_description;
jsep_description.transport_desc = TransportDescription(kIceUfrag1, kIcePwd1);
jsep_description.rtcp_mux_enabled = rtcp_mux_enabled;
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(jsep_description, SdpType::kOffer)
.ok());
auto fake_ice_transport = static_cast<FakeIceTransport*>(
jsep_transport_->rtp_dtls_transport()->ice_transport());
EXPECT_EQ(ICEMODE_FULL, fake_ice_transport->remote_ice_mode());
EXPECT_EQ(kIceUfrag1, fake_ice_transport->ice_ufrag());
EXPECT_EQ(kIcePwd1, fake_ice_transport->ice_pwd());
if (!rtcp_mux_enabled) {
fake_ice_transport = static_cast<FakeIceTransport*>(
jsep_transport_->rtcp_dtls_transport()->ice_transport());
ASSERT_TRUE(fake_ice_transport);
EXPECT_EQ(ICEMODE_FULL, fake_ice_transport->remote_ice_mode());
EXPECT_EQ(kIceUfrag1, fake_ice_transport->ice_ufrag());
EXPECT_EQ(kIcePwd1, fake_ice_transport->ice_pwd());
}
jsep_description.transport_desc = TransportDescription(kIceUfrag2, kIcePwd2);
ASSERT_TRUE(jsep_transport_
->SetRemoteJsepTransportDescription(jsep_description,
SdpType::kAnswer)
.ok());
fake_ice_transport = static_cast<FakeIceTransport*>(
jsep_transport_->rtp_dtls_transport()->ice_transport());
EXPECT_EQ(ICEMODE_FULL, fake_ice_transport->remote_ice_mode());
EXPECT_EQ(kIceUfrag2, fake_ice_transport->remote_ice_ufrag());
EXPECT_EQ(kIcePwd2, fake_ice_transport->remote_ice_pwd());
if (!rtcp_mux_enabled) {
fake_ice_transport = static_cast<FakeIceTransport*>(
jsep_transport_->rtcp_dtls_transport()->ice_transport());
ASSERT_TRUE(fake_ice_transport);
EXPECT_EQ(ICEMODE_FULL, fake_ice_transport->remote_ice_mode());
EXPECT_EQ(kIceUfrag2, fake_ice_transport->remote_ice_ufrag());
EXPECT_EQ(kIcePwd2, fake_ice_transport->remote_ice_pwd());
}
}
// Similarly, test DTLS parameters are properly applied to the transports.
TEST_P(JsepTransport2WithRtcpMux, SetDtlsParameters) {
bool rtcp_mux_enabled = GetParam();
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
// Create certificates.
rtc::scoped_refptr<rtc::RTCCertificate> local_cert =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("local", rtc::KT_DEFAULT)));
rtc::scoped_refptr<rtc::RTCCertificate> remote_cert =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("remote", rtc::KT_DEFAULT)));
jsep_transport_->SetLocalCertificate(local_cert);
// Apply offer.
JsepTransportDescription local_description =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag1, kIcePwd1,
local_cert, CONNECTIONROLE_ACTPASS);
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_description, SdpType::kOffer)
.ok());
// Apply Answer.
JsepTransportDescription remote_description =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag2, kIcePwd2,
remote_cert, CONNECTIONROLE_ACTIVE);
ASSERT_TRUE(jsep_transport_
->SetRemoteJsepTransportDescription(remote_description,
SdpType::kAnswer)
.ok());
// Verify that SSL role and remote fingerprint were set correctly based on
// transport descriptions.
auto role = jsep_transport_->GetDtlsRole();
ASSERT_TRUE(role);
EXPECT_EQ(rtc::SSL_SERVER, role); // Because remote description was "active".
auto fake_dtls =
static_cast<FakeDtlsTransport*>(jsep_transport_->rtp_dtls_transport());
EXPECT_EQ(remote_description.transport_desc.identity_fingerprint->ToString(),
fake_dtls->dtls_fingerprint().ToString());
if (!rtcp_mux_enabled) {
auto fake_rtcp_dtls =
static_cast<FakeDtlsTransport*>(jsep_transport_->rtcp_dtls_transport());
EXPECT_EQ(
remote_description.transport_desc.identity_fingerprint->ToString(),
fake_rtcp_dtls->dtls_fingerprint().ToString());
}
}
// Same as above test, but with remote transport description using
// CONNECTIONROLE_PASSIVE, expecting SSL_CLIENT role.
TEST_P(JsepTransport2WithRtcpMux, SetDtlsParametersWithPassiveAnswer) {
bool rtcp_mux_enabled = GetParam();
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
// Create certificates.
rtc::scoped_refptr<rtc::RTCCertificate> local_cert =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("local", rtc::KT_DEFAULT)));
rtc::scoped_refptr<rtc::RTCCertificate> remote_cert =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("remote", rtc::KT_DEFAULT)));
jsep_transport_->SetLocalCertificate(local_cert);
// Apply offer.
JsepTransportDescription local_description =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag1, kIcePwd1,
local_cert, CONNECTIONROLE_ACTPASS);
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_description, SdpType::kOffer)
.ok());
// Apply Answer.
JsepTransportDescription remote_description =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag2, kIcePwd2,
remote_cert, CONNECTIONROLE_PASSIVE);
ASSERT_TRUE(jsep_transport_
->SetRemoteJsepTransportDescription(remote_description,
SdpType::kAnswer)
.ok());
// Verify that SSL role and remote fingerprint were set correctly based on
// transport descriptions.
auto role = jsep_transport_->GetDtlsRole();
ASSERT_TRUE(role);
EXPECT_EQ(rtc::SSL_CLIENT,
role); // Because remote description was "passive".
auto fake_dtls =
static_cast<FakeDtlsTransport*>(jsep_transport_->rtp_dtls_transport());
EXPECT_EQ(remote_description.transport_desc.identity_fingerprint->ToString(),
fake_dtls->dtls_fingerprint().ToString());
if (!rtcp_mux_enabled) {
auto fake_rtcp_dtls =
static_cast<FakeDtlsTransport*>(jsep_transport_->rtcp_dtls_transport());
EXPECT_EQ(
remote_description.transport_desc.identity_fingerprint->ToString(),
fake_rtcp_dtls->dtls_fingerprint().ToString());
}
}
// Tests SetNeedsIceRestartFlag and need_ice_restart, ensuring needs_ice_restart
// only starts returning "false" once an ICE restart has been initiated.
TEST_P(JsepTransport2WithRtcpMux, NeedsIceRestart) {
bool rtcp_mux_enabled = GetParam();
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
// Use the same JsepTransportDescription for both offer and answer.
JsepTransportDescription description;
description.transport_desc = TransportDescription(kIceUfrag1, kIcePwd1);
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(description, SdpType::kOffer)
.ok());
ASSERT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(description, SdpType::kAnswer)
.ok());
// Flag initially should be false.
EXPECT_FALSE(jsep_transport_->needs_ice_restart());
// After setting flag, it should be true.
jsep_transport_->SetNeedsIceRestartFlag();
EXPECT_TRUE(jsep_transport_->needs_ice_restart());
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(description, SdpType::kOffer)
.ok());
ASSERT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(description, SdpType::kAnswer)
.ok());
EXPECT_TRUE(jsep_transport_->needs_ice_restart());
// Doing an offer/answer that restarts ICE should clear the flag.
description.transport_desc = TransportDescription(kIceUfrag2, kIcePwd2);
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(description, SdpType::kOffer)
.ok());
ASSERT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(description, SdpType::kAnswer)
.ok());
EXPECT_FALSE(jsep_transport_->needs_ice_restart());
}
TEST_P(JsepTransport2WithRtcpMux, GetStats) {
bool rtcp_mux_enabled = GetParam();
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
size_t expected_stats_size = rtcp_mux_enabled ? 1u : 2u;
TransportStats stats;
EXPECT_TRUE(jsep_transport_->GetStats(&stats));
EXPECT_EQ(expected_stats_size, stats.channel_stats.size());
EXPECT_EQ(ICE_CANDIDATE_COMPONENT_RTP, stats.channel_stats[0].component);
if (!rtcp_mux_enabled) {
EXPECT_EQ(ICE_CANDIDATE_COMPONENT_RTCP, stats.channel_stats[1].component);
}
}
// Tests that VerifyCertificateFingerprint only returns true when the
// certificate matches the fingerprint.
TEST_P(JsepTransport2WithRtcpMux, VerifyCertificateFingerprint) {
bool rtcp_mux_enabled = GetParam();
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
EXPECT_FALSE(
jsep_transport_->VerifyCertificateFingerprint(nullptr, nullptr).ok());
rtc::KeyType key_types[] = {rtc::KT_RSA, rtc::KT_ECDSA};
for (auto& key_type : key_types) {
rtc::scoped_refptr<rtc::RTCCertificate> certificate =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("testing", key_type)));
ASSERT_NE(nullptr, certificate);
std::string digest_algorithm;
ASSERT_TRUE(certificate->ssl_certificate().GetSignatureDigestAlgorithm(
&digest_algorithm));
ASSERT_FALSE(digest_algorithm.empty());
std::unique_ptr<rtc::SSLFingerprint> good_fingerprint(
rtc::SSLFingerprint::Create(digest_algorithm, certificate->identity()));
ASSERT_NE(nullptr, good_fingerprint);
EXPECT_TRUE(jsep_transport_
->VerifyCertificateFingerprint(certificate.get(),
good_fingerprint.get())
.ok());
EXPECT_FALSE(jsep_transport_
->VerifyCertificateFingerprint(certificate.get(), nullptr)
.ok());
EXPECT_FALSE(
jsep_transport_
->VerifyCertificateFingerprint(nullptr, good_fingerprint.get())
.ok());
rtc::SSLFingerprint bad_fingerprint = *good_fingerprint;
bad_fingerprint.digest.AppendData("0", 1);
EXPECT_FALSE(
jsep_transport_
->VerifyCertificateFingerprint(certificate.get(), &bad_fingerprint)
.ok());
}
}
// Tests the logic of DTLS role negotiation for an initial offer/answer.
TEST_P(JsepTransport2WithRtcpMux, ValidDtlsRoleNegotiation) {
bool rtcp_mux_enabled = GetParam();
// Just use the same certificate for both sides; doesn't really matter in a
// non end-to-end test.
rtc::scoped_refptr<rtc::RTCCertificate> certificate =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("testing", rtc::KT_ECDSA)));
JsepTransportDescription local_description = MakeJsepTransportDescription(
rtcp_mux_enabled, kIceUfrag1, kIcePwd1, certificate);
JsepTransportDescription remote_description = MakeJsepTransportDescription(
rtcp_mux_enabled, kIceUfrag2, kIcePwd2, certificate);
// Parameters which set the SSL role to SSL_CLIENT.
NegotiateRoleParams valid_client_params[] = {
{CONNECTIONROLE_ACTIVE, CONNECTIONROLE_ACTPASS, SdpType::kAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTIVE, CONNECTIONROLE_ACTPASS, SdpType::kPrAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTPASS, CONNECTIONROLE_PASSIVE, SdpType::kOffer,
SdpType::kAnswer},
{CONNECTIONROLE_ACTPASS, CONNECTIONROLE_PASSIVE, SdpType::kOffer,
SdpType::kPrAnswer}};
for (auto& param : valid_client_params) {
jsep_transport_ =
CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
jsep_transport_->SetLocalCertificate(certificate);
local_description.transport_desc.connection_role = param.local_role;
remote_description.transport_desc.connection_role = param.remote_role;
// Set the offer first.
if (param.local_type == SdpType::kOffer) {
EXPECT_TRUE(jsep_transport_
->SetLocalJsepTransportDescription(local_description,
param.local_type)
.ok());
EXPECT_TRUE(jsep_transport_
->SetRemoteJsepTransportDescription(remote_description,
param.remote_type)
.ok());
} else {
EXPECT_TRUE(jsep_transport_
->SetRemoteJsepTransportDescription(remote_description,
param.remote_type)
.ok());
EXPECT_TRUE(jsep_transport_
->SetLocalJsepTransportDescription(local_description,
param.local_type)
.ok());
}
EXPECT_EQ(rtc::SSL_CLIENT, *jsep_transport_->GetDtlsRole());
}
// Parameters which set the SSL role to SSL_SERVER.
NegotiateRoleParams valid_server_params[] = {
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_ACTPASS, SdpType::kAnswer,
SdpType::kOffer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_ACTPASS, SdpType::kPrAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTPASS, CONNECTIONROLE_ACTIVE, SdpType::kOffer,
SdpType::kAnswer},
{CONNECTIONROLE_ACTPASS, CONNECTIONROLE_ACTIVE, SdpType::kOffer,
SdpType::kPrAnswer}};
for (auto& param : valid_server_params) {
jsep_transport_ =
CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
jsep_transport_->SetLocalCertificate(certificate);
local_description.transport_desc.connection_role = param.local_role;
remote_description.transport_desc.connection_role = param.remote_role;
// Set the offer first.
if (param.local_type == SdpType::kOffer) {
EXPECT_TRUE(jsep_transport_
->SetLocalJsepTransportDescription(local_description,
param.local_type)
.ok());
EXPECT_TRUE(jsep_transport_
->SetRemoteJsepTransportDescription(remote_description,
param.remote_type)
.ok());
} else {
EXPECT_TRUE(jsep_transport_
->SetRemoteJsepTransportDescription(remote_description,
param.remote_type)
.ok());
EXPECT_TRUE(jsep_transport_
->SetLocalJsepTransportDescription(local_description,
param.local_type)
.ok());
}
EXPECT_EQ(rtc::SSL_SERVER, *jsep_transport_->GetDtlsRole());
}
}
// Tests the logic of DTLS role negotiation for an initial offer/answer.
TEST_P(JsepTransport2WithRtcpMux, InvalidDtlsRoleNegotiation) {
bool rtcp_mux_enabled = GetParam();
// Just use the same certificate for both sides; doesn't really matter in a
// non end-to-end test.
rtc::scoped_refptr<rtc::RTCCertificate> certificate =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("testing", rtc::KT_ECDSA)));
JsepTransportDescription local_description = MakeJsepTransportDescription(
rtcp_mux_enabled, kIceUfrag1, kIcePwd1, certificate);
JsepTransportDescription remote_description = MakeJsepTransportDescription(
rtcp_mux_enabled, kIceUfrag2, kIcePwd2, certificate);
NegotiateRoleParams duplicate_params[] = {
{CONNECTIONROLE_ACTIVE, CONNECTIONROLE_ACTIVE, SdpType::kAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTPASS, CONNECTIONROLE_ACTPASS, SdpType::kAnswer,
SdpType::kOffer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_PASSIVE, SdpType::kAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTIVE, CONNECTIONROLE_ACTIVE, SdpType::kPrAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTPASS, CONNECTIONROLE_ACTPASS, SdpType::kPrAnswer,
SdpType::kOffer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_PASSIVE, SdpType::kPrAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTIVE, CONNECTIONROLE_ACTIVE, SdpType::kOffer,
SdpType::kAnswer},
{CONNECTIONROLE_ACTPASS, CONNECTIONROLE_ACTPASS, SdpType::kOffer,
SdpType::kAnswer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_PASSIVE, SdpType::kOffer,
SdpType::kAnswer},
{CONNECTIONROLE_ACTIVE, CONNECTIONROLE_ACTIVE, SdpType::kOffer,
SdpType::kPrAnswer},
{CONNECTIONROLE_ACTPASS, CONNECTIONROLE_ACTPASS, SdpType::kOffer,
SdpType::kPrAnswer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_PASSIVE, SdpType::kOffer,
SdpType::kPrAnswer}};
for (auto& param : duplicate_params) {
jsep_transport_ =
CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
jsep_transport_->SetLocalCertificate(certificate);
local_description.transport_desc.connection_role = param.local_role;
remote_description.transport_desc.connection_role = param.remote_role;
if (param.local_type == SdpType::kOffer) {
EXPECT_TRUE(jsep_transport_
->SetLocalJsepTransportDescription(local_description,
param.local_type)
.ok());
EXPECT_FALSE(jsep_transport_
->SetRemoteJsepTransportDescription(remote_description,
param.remote_type)
.ok());
} else {
EXPECT_TRUE(jsep_transport_
->SetRemoteJsepTransportDescription(remote_description,
param.remote_type)
.ok());
EXPECT_FALSE(jsep_transport_
->SetLocalJsepTransportDescription(local_description,
param.local_type)
.ok());
}
}
// Invalid parameters due to the offerer not using ACTPASS.
NegotiateRoleParams offerer_without_actpass_params[] = {
{CONNECTIONROLE_ACTIVE, CONNECTIONROLE_PASSIVE, SdpType::kAnswer,
SdpType::kOffer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_ACTIVE, SdpType::kAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTPASS, CONNECTIONROLE_PASSIVE, SdpType::kAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTIVE, CONNECTIONROLE_PASSIVE, SdpType::kPrAnswer,
SdpType::kOffer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_ACTIVE, SdpType::kPrAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTPASS, CONNECTIONROLE_PASSIVE, SdpType::kPrAnswer,
SdpType::kOffer},
{CONNECTIONROLE_ACTIVE, CONNECTIONROLE_PASSIVE, SdpType::kOffer,
SdpType::kAnswer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_ACTIVE, SdpType::kOffer,
SdpType::kAnswer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_ACTPASS, SdpType::kOffer,
SdpType::kAnswer},
{CONNECTIONROLE_ACTIVE, CONNECTIONROLE_PASSIVE, SdpType::kOffer,
SdpType::kPrAnswer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_ACTIVE, SdpType::kOffer,
SdpType::kPrAnswer},
{CONNECTIONROLE_PASSIVE, CONNECTIONROLE_ACTPASS, SdpType::kOffer,
SdpType::kPrAnswer}};
for (auto& param : offerer_without_actpass_params) {
jsep_transport_ =
CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
jsep_transport_->SetLocalCertificate(certificate);
local_description.transport_desc.connection_role = param.local_role;
remote_description.transport_desc.connection_role = param.remote_role;
if (param.local_type == SdpType::kOffer) {
EXPECT_TRUE(jsep_transport_
->SetLocalJsepTransportDescription(local_description,
param.local_type)
.ok());
EXPECT_FALSE(jsep_transport_
->SetRemoteJsepTransportDescription(remote_description,
param.remote_type)
.ok());
} else {
EXPECT_TRUE(jsep_transport_
->SetRemoteJsepTransportDescription(remote_description,
param.remote_type)
.ok());
EXPECT_FALSE(jsep_transport_
->SetLocalJsepTransportDescription(local_description,
param.local_type)
.ok());
}
}
}
INSTANTIATE_TEST_CASE_P(JsepTransport2Test,
JsepTransport2WithRtcpMux,
testing::Bool());
// Test that a reoffer in the opposite direction is successful as long as the
// role isn't changing. Doesn't test every possible combination like the test
// above.
TEST_F(JsepTransport2Test, ValidDtlsReofferFromAnswerer) {
// Just use the same certificate for both sides; doesn't really matter in a
// non end-to-end test.
rtc::scoped_refptr<rtc::RTCCertificate> certificate =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("testing", rtc::KT_ECDSA)));
bool rtcp_mux_enabled = true;
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
jsep_transport_->SetLocalCertificate(certificate);
JsepTransportDescription local_offer =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag1, kIcePwd1,
certificate, CONNECTIONROLE_ACTPASS);
JsepTransportDescription remote_answer =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag2, kIcePwd2,
certificate, CONNECTIONROLE_ACTIVE);
EXPECT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_offer, SdpType::kOffer)
.ok());
EXPECT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_answer, SdpType::kAnswer)
.ok());
// We were actpass->active previously, now in the other direction it's
// actpass->passive.
JsepTransportDescription remote_offer =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag2, kIcePwd2,
certificate, CONNECTIONROLE_ACTPASS);
JsepTransportDescription local_answer =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag1, kIcePwd1,
certificate, CONNECTIONROLE_PASSIVE);
EXPECT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_offer, SdpType::kOffer)
.ok());
EXPECT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_answer, SdpType::kAnswer)
.ok());
}
// Test that a reoffer in the opposite direction fails if the role changes.
// Inverse of test above.
TEST_F(JsepTransport2Test, InvalidDtlsReofferFromAnswerer) {
// Just use the same certificate for both sides; doesn't really matter in a
// non end-to-end test.
rtc::scoped_refptr<rtc::RTCCertificate> certificate =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("testing", rtc::KT_ECDSA)));
bool rtcp_mux_enabled = true;
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
jsep_transport_->SetLocalCertificate(certificate);
JsepTransportDescription local_offer =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag1, kIcePwd1,
certificate, CONNECTIONROLE_ACTPASS);
JsepTransportDescription remote_answer =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag2, kIcePwd2,
certificate, CONNECTIONROLE_ACTIVE);
EXPECT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_offer, SdpType::kOffer)
.ok());
EXPECT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_answer, SdpType::kAnswer)
.ok());
// Changing role to passive here isn't allowed. Though for some reason this
// only fails in SetLocalTransportDescription.
JsepTransportDescription remote_offer =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag2, kIcePwd2,
certificate, CONNECTIONROLE_PASSIVE);
JsepTransportDescription local_answer =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag1, kIcePwd1,
certificate, CONNECTIONROLE_ACTIVE);
EXPECT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_offer, SdpType::kOffer)
.ok());
EXPECT_FALSE(
jsep_transport_
->SetLocalJsepTransportDescription(local_answer, SdpType::kAnswer)
.ok());
}
// Test that a remote offer with the current negotiated role can be accepted.
// This is allowed by dtls-sdp, though we'll never generate such an offer,
// since JSEP requires generating "actpass".
TEST_F(JsepTransport2Test, RemoteOfferWithCurrentNegotiatedDtlsRole) {
rtc::scoped_refptr<rtc::RTCCertificate> certificate =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("testing", rtc::KT_ECDSA)));
bool rtcp_mux_enabled = true;
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
jsep_transport_->SetLocalCertificate(certificate);
JsepTransportDescription remote_desc =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag1, kIcePwd1,
certificate, CONNECTIONROLE_ACTPASS);
JsepTransportDescription local_desc =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag2, kIcePwd2,
certificate, CONNECTIONROLE_ACTIVE);
// Normal initial offer/answer with "actpass" in the offer and "active" in
// the answer.
ASSERT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_desc, SdpType::kOffer)
.ok());
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_desc, SdpType::kAnswer)
.ok());
// Sanity check that role was actually negotiated.
rtc::Optional<rtc::SSLRole> role = jsep_transport_->GetDtlsRole();
ASSERT_TRUE(role);
EXPECT_EQ(rtc::SSL_CLIENT, *role);
// Subsequent offer with current negotiated role of "passive".
remote_desc.transport_desc.connection_role = CONNECTIONROLE_PASSIVE;
EXPECT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_desc, SdpType::kOffer)
.ok());
EXPECT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_desc, SdpType::kAnswer)
.ok());
}
// Test that a remote offer with the inverse of the current negotiated DTLS
// role is rejected.
TEST_F(JsepTransport2Test, RemoteOfferThatChangesNegotiatedDtlsRole) {
rtc::scoped_refptr<rtc::RTCCertificate> certificate =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("testing", rtc::KT_ECDSA)));
bool rtcp_mux_enabled = true;
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
jsep_transport_->SetLocalCertificate(certificate);
JsepTransportDescription remote_desc =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag1, kIcePwd1,
certificate, CONNECTIONROLE_ACTPASS);
JsepTransportDescription local_desc =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag2, kIcePwd2,
certificate, CONNECTIONROLE_ACTIVE);
// Normal initial offer/answer with "actpass" in the offer and "active" in
// the answer.
ASSERT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_desc, SdpType::kOffer)
.ok());
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_desc, SdpType::kAnswer)
.ok());
// Sanity check that role was actually negotiated.
rtc::Optional<rtc::SSLRole> role = jsep_transport_->GetDtlsRole();
ASSERT_TRUE(role);
EXPECT_EQ(rtc::SSL_CLIENT, *role);
// Subsequent offer with current negotiated role of "passive".
remote_desc.transport_desc.connection_role = CONNECTIONROLE_ACTIVE;
EXPECT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_desc, SdpType::kOffer)
.ok());
EXPECT_FALSE(
jsep_transport_
->SetLocalJsepTransportDescription(local_desc, SdpType::kAnswer)
.ok());
}
// Testing that a legacy client that doesn't use the setup attribute will be
// interpreted as having an active role.
TEST_F(JsepTransport2Test, DtlsSetupWithLegacyAsAnswerer) {
rtc::scoped_refptr<rtc::RTCCertificate> certificate =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("testing", rtc::KT_ECDSA)));
bool rtcp_mux_enabled = true;
jsep_transport_ = CreateJsepTransport2(rtcp_mux_enabled, SrtpMode::kDtlsSrtp);
jsep_transport_->SetLocalCertificate(certificate);
JsepTransportDescription remote_desc =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag1, kIcePwd1,
certificate, CONNECTIONROLE_ACTPASS);
JsepTransportDescription local_desc =
MakeJsepTransportDescription(rtcp_mux_enabled, kIceUfrag2, kIcePwd2,
certificate, CONNECTIONROLE_ACTIVE);
local_desc.transport_desc.connection_role = CONNECTIONROLE_ACTPASS;
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_desc, SdpType::kOffer)
.ok());
// Use CONNECTIONROLE_NONE to simulate legacy endpoint.
remote_desc.transport_desc.connection_role = CONNECTIONROLE_NONE;
ASSERT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_desc, SdpType::kAnswer)
.ok());
rtc::Optional<rtc::SSLRole> role = jsep_transport_->GetDtlsRole();
ASSERT_TRUE(role);
// Since legacy answer ommitted setup atribute, and we offered actpass, we
// should act as passive (server).
EXPECT_EQ(rtc::SSL_SERVER, *role);
}
// Tests that when the RTCP mux is successfully negotiated, the RTCP transport
// will be destroyed and the SignalRtpMuxActive will be fired.
TEST_F(JsepTransport2Test, RtcpMuxNegotiation) {
jsep_transport_ =
CreateJsepTransport2(/*rtcp_mux_enabled=*/false, SrtpMode::kDtlsSrtp);
JsepTransportDescription local_desc;
local_desc.rtcp_mux_enabled = true;
EXPECT_NE(nullptr, jsep_transport_->rtcp_dtls_transport());
EXPECT_FALSE(signal_rtcp_mux_active_received_);
// The remote side supports RTCP-mux.
JsepTransportDescription remote_desc;
remote_desc.rtcp_mux_enabled = true;
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_desc, SdpType::kOffer)
.ok());
ASSERT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_desc, SdpType::kAnswer)
.ok());
EXPECT_EQ(nullptr, jsep_transport_->rtcp_dtls_transport());
EXPECT_TRUE(signal_rtcp_mux_active_received_);
// The remote side doesn't support RTCP-mux.
jsep_transport_ =
CreateJsepTransport2(/*rtcp_mux_enabled=*/false, SrtpMode::kDtlsSrtp);
signal_rtcp_mux_active_received_ = false;
remote_desc.rtcp_mux_enabled = false;
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(local_desc, SdpType::kOffer)
.ok());
ASSERT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(remote_desc, SdpType::kAnswer)
.ok());
EXPECT_NE(nullptr, jsep_transport_->rtcp_dtls_transport());
EXPECT_FALSE(signal_rtcp_mux_active_received_);
}
TEST_F(JsepTransport2Test, SdesNegotiation) {
jsep_transport_ =
CreateJsepTransport2(/*rtcp_mux_enabled=*/true, SrtpMode::kSdes);
ASSERT_TRUE(sdes_transport_);
EXPECT_FALSE(sdes_transport_->IsSrtpActive());
JsepTransportDescription offer_desc;
offer_desc.cryptos.push_back(cricket::CryptoParams(
1, rtc::CS_AES_CM_128_HMAC_SHA1_32,
"inline:" + rtc::CreateRandomString(40), std::string()));
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(offer_desc, SdpType::kOffer)
.ok());
JsepTransportDescription answer_desc;
answer_desc.cryptos.push_back(cricket::CryptoParams(
1, rtc::CS_AES_CM_128_HMAC_SHA1_32,
"inline:" + rtc::CreateRandomString(40), std::string()));
ASSERT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(answer_desc, SdpType::kAnswer)
.ok());
EXPECT_TRUE(sdes_transport_->IsSrtpActive());
}
TEST_F(JsepTransport2Test, SdesNegotiationWithEmptyCryptosInAnswer) {
jsep_transport_ =
CreateJsepTransport2(/*rtcp_mux_enabled=*/true, SrtpMode::kSdes);
ASSERT_TRUE(sdes_transport_);
EXPECT_FALSE(sdes_transport_->IsSrtpActive());
JsepTransportDescription offer_desc;
offer_desc.cryptos.push_back(cricket::CryptoParams(
1, rtc::CS_AES_CM_128_HMAC_SHA1_32,
"inline:" + rtc::CreateRandomString(40), std::string()));
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(offer_desc, SdpType::kOffer)
.ok());
JsepTransportDescription answer_desc;
ASSERT_TRUE(
jsep_transport_
->SetRemoteJsepTransportDescription(answer_desc, SdpType::kAnswer)
.ok());
// SRTP is not active because the crypto parameter is answer is empty.
EXPECT_FALSE(sdes_transport_->IsSrtpActive());
}
TEST_F(JsepTransport2Test, SdesNegotiationWithMismatchedCryptos) {
jsep_transport_ =
CreateJsepTransport2(/*rtcp_mux_enabled=*/true, SrtpMode::kSdes);
ASSERT_TRUE(sdes_transport_);
EXPECT_FALSE(sdes_transport_->IsSrtpActive());
JsepTransportDescription offer_desc;
offer_desc.cryptos.push_back(cricket::CryptoParams(
1, rtc::CS_AES_CM_128_HMAC_SHA1_32,
"inline:" + rtc::CreateRandomString(40), std::string()));
ASSERT_TRUE(
jsep_transport_
->SetLocalJsepTransportDescription(offer_desc, SdpType::kOffer)
.ok());
JsepTransportDescription answer_desc;
answer_desc.cryptos.push_back(cricket::CryptoParams(
1, rtc::CS_AES_CM_128_HMAC_SHA1_80,
"inline:" + rtc::CreateRandomString(40), std::string()));
// Expected to fail because the crypto parameters don't match.
ASSERT_FALSE(
jsep_transport_
->SetRemoteJsepTransportDescription(answer_desc, SdpType::kAnswer)
.ok());
}
// Tests that the remote candidates can be added to the transports after both
// local and remote descriptions are set.
TEST_F(JsepTransport2Test, AddRemoteCandidates) {
jsep_transport_ =
CreateJsepTransport2(/*rtcp_mux_enabled=*/true, SrtpMode::kDtlsSrtp);
auto fake_ice_transport = static_cast<FakeIceTransport*>(
jsep_transport_->rtp_dtls_transport()->ice_transport());
Candidates candidates;
candidates.push_back(CreateCandidate(/*COMPONENT_RTP*/ 1));
candidates.push_back(CreateCandidate(/*COMPONENT_RTP*/ 1));
JsepTransportDescription desc;
ASSERT_TRUE(
jsep_transport_->SetLocalJsepTransportDescription(desc, SdpType::kOffer)
.ok());
// Expected to fail because the remote description is unset.
EXPECT_FALSE(jsep_transport_->AddRemoteCandidates(candidates).ok());
ASSERT_TRUE(
jsep_transport_->SetRemoteJsepTransportDescription(desc, SdpType::kAnswer)
.ok());
EXPECT_EQ(0u, fake_ice_transport->remote_candidates().size());
EXPECT_TRUE(jsep_transport_->AddRemoteCandidates(candidates).ok());
EXPECT_EQ(candidates.size(), fake_ice_transport->remote_candidates().size());
}
enum class Scenario {
kSdes,
kDtlsBeforeCallerSendOffer,
kDtlsBeforeCallerSetAnswer,
kDtlsAfterCallerSetAnswer,
};
class JsepTransport2HeaderExtensionTest
: public JsepTransport2Test,
public ::testing::WithParamInterface<std::tuple<Scenario, bool>> {
protected:
JsepTransport2HeaderExtensionTest() {}
void CreateJsepTransportPair(SrtpMode mode) {
jsep_transport1_ = CreateJsepTransport2(/*rtcp_mux_enabled=*/true, mode);
jsep_transport2_ = CreateJsepTransport2(/*rtcp_mux_enabled=*/true, mode);
auto fake_dtls1 =
static_cast<FakeDtlsTransport*>(jsep_transport1_->rtp_dtls_transport());
auto fake_dtls2 =
static_cast<FakeDtlsTransport*>(jsep_transport2_->rtp_dtls_transport());
fake_dtls1->fake_ice_transport()->SignalReadPacket.connect(
this, &JsepTransport2HeaderExtensionTest::OnReadPacket1);
fake_dtls2->fake_ice_transport()->SignalReadPacket.connect(
this, &JsepTransport2HeaderExtensionTest::OnReadPacket2);
if (mode == SrtpMode::kDtlsSrtp) {
auto cert1 =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("session1", rtc::KT_DEFAULT)));
jsep_transport1_->rtp_dtls_transport()->SetLocalCertificate(cert1);
auto cert2 =
rtc::RTCCertificate::Create(std::unique_ptr<rtc::SSLIdentity>(
rtc::SSLIdentity::Generate("session1", rtc::KT_DEFAULT)));
jsep_transport2_->rtp_dtls_transport()->SetLocalCertificate(cert2);
}
}
void OnReadPacket1(rtc::PacketTransportInternal* transport,
const char* data,
size_t size,
const rtc::PacketTime& time,
int flags) {
RTC_LOG(LS_INFO) << "JsepTransport 1 Received a packet.";
CompareHeaderExtensions(
reinterpret_cast<const char*>(kPcmuFrameWithExtensions),
sizeof(kPcmuFrameWithExtensions), data, size, recv_encrypted_headers1_,
false);
received_packet_count_++;
}
void OnReadPacket2(rtc::PacketTransportInternal* transport,
const char* data,
size_t size,
const rtc::PacketTime& time,
int flags) {
RTC_LOG(LS_INFO) << "JsepTransport 2 Received a packet.";
CompareHeaderExtensions(
reinterpret_cast<const char*>(kPcmuFrameWithExtensions),
sizeof(kPcmuFrameWithExtensions), data, size, recv_encrypted_headers2_,
false);
received_packet_count_++;
}
void ConnectTransport() {
auto rtp_dtls_transport1 =
static_cast<FakeDtlsTransport*>(jsep_transport1_->rtp_dtls_transport());
auto rtp_dtls_transport2 =
static_cast<FakeDtlsTransport*>(jsep_transport2_->rtp_dtls_transport());
rtp_dtls_transport1->SetDestination(rtp_dtls_transport2);
}
int GetRtpAuthLen() {
bool use_gcm = std::get<1>(GetParam());
if (use_gcm) {
return 16;
}
return 10;
}
void TestSendRecvPacketWithEncryptedHeaderExtension() {
TestOneWaySendRecvPacketWithEncryptedHeaderExtension(
jsep_transport1_.get());
TestOneWaySendRecvPacketWithEncryptedHeaderExtension(
jsep_transport2_.get());
}
void TestOneWaySendRecvPacketWithEncryptedHeaderExtension(
JsepTransport* sender_transport) {
size_t rtp_len = sizeof(kPcmuFrameWithExtensions);
size_t packet_size = rtp_len + GetRtpAuthLen();
rtc::Buffer rtp_packet_buffer(packet_size);
char* rtp_packet_data = rtp_packet_buffer.data<char>();
memcpy(rtp_packet_data, kPcmuFrameWithExtensions, rtp_len);
// In order to be able to run this test function multiple times we can not
// use the same sequence number twice. Increase the sequence number by one.
rtc::SetBE16(reinterpret_cast<uint8_t*>(rtp_packet_data) + 2,
++sequence_number_);
rtc::CopyOnWriteBuffer rtp_packet(rtp_packet_data, rtp_len, packet_size);
int packet_count_before = received_packet_count_;
rtc::PacketOptions options;
// Send a packet and verify that the packet can be successfully received and
// decrypted.
ASSERT_TRUE(sender_transport->rtp_transport()->SendRtpPacket(
&rtp_packet, options, cricket::PF_SRTP_BYPASS));
EXPECT_EQ(packet_count_before + 1, received_packet_count_);
}
int sequence_number_ = 0;
int received_packet_count_ = 0;
std::unique_ptr<JsepTransport> jsep_transport1_;
std::unique_ptr<JsepTransport> jsep_transport2_;
std::vector<int> recv_encrypted_headers1_;
std::vector<int> recv_encrypted_headers2_;
};
// Test that the encrypted header extension works and can be changed in
// different scenarios.
TEST_P(JsepTransport2HeaderExtensionTest, EncryptedHeaderExtensionNegotiation) {
Scenario scenario = std::get<0>(GetParam());
bool use_gcm = std::get<1>(GetParam());
SrtpMode mode = SrtpMode ::kDtlsSrtp;
if (scenario == Scenario::kSdes) {
mode = SrtpMode::kSdes;
}
CreateJsepTransportPair(mode);
recv_encrypted_headers1_.push_back(kHeaderExtensionIDs[0]);
recv_encrypted_headers2_.push_back(kHeaderExtensionIDs[1]);
cricket::CryptoParams sdes_param(1, rtc::CS_AES_CM_128_HMAC_SHA1_80,
"inline:" + rtc::CreateRandomString(40),
std::string());
if (use_gcm) {
auto fake_dtls1 =
static_cast<FakeDtlsTransport*>(jsep_transport1_->rtp_dtls_transport());
auto fake_dtls2 =
static_cast<FakeDtlsTransport*>(jsep_transport2_->rtp_dtls_transport());
fake_dtls1->SetSrtpCryptoSuite(rtc::SRTP_AEAD_AES_256_GCM);
fake_dtls2->SetSrtpCryptoSuite(rtc::SRTP_AEAD_AES_256_GCM);
}
if (scenario == Scenario::kDtlsBeforeCallerSendOffer) {
ConnectTransport();
}
JsepTransportDescription offer_desc;
offer_desc.encrypted_header_extension_ids = recv_encrypted_headers1_;
if (scenario == Scenario::kSdes) {
offer_desc.cryptos.push_back(sdes_param);
}
ASSERT_TRUE(
jsep_transport1_
->SetLocalJsepTransportDescription(offer_desc, SdpType::kOffer)
.ok());
ASSERT_TRUE(
jsep_transport2_
->SetRemoteJsepTransportDescription(offer_desc, SdpType::kOffer)
.ok());
JsepTransportDescription answer_desc;
answer_desc.encrypted_header_extension_ids = recv_encrypted_headers2_;
if (scenario == Scenario::kSdes) {
answer_desc.cryptos.push_back(sdes_param);
}
ASSERT_TRUE(
jsep_transport2_
->SetLocalJsepTransportDescription(answer_desc, SdpType::kAnswer)
.ok());
if (scenario == Scenario::kDtlsBeforeCallerSetAnswer) {
ConnectTransport();
// Sending packet from transport2 to transport1 should work when they are
// partially configured.
TestOneWaySendRecvPacketWithEncryptedHeaderExtension(
/*sender_transport=*/jsep_transport2_.get());
}
ASSERT_TRUE(
jsep_transport1_
->SetRemoteJsepTransportDescription(answer_desc, SdpType::kAnswer)
.ok());
if (scenario == Scenario::kDtlsAfterCallerSetAnswer ||
scenario == Scenario::kSdes) {
ConnectTransport();
}
EXPECT_TRUE(jsep_transport1_->rtp_transport()->IsSrtpActive());
EXPECT_TRUE(jsep_transport2_->rtp_transport()->IsSrtpActive());
TestSendRecvPacketWithEncryptedHeaderExtension();
// Change the encrypted header extension in a new offer/answer exchange.
recv_encrypted_headers1_.clear();
recv_encrypted_headers2_.clear();
recv_encrypted_headers1_.push_back(kHeaderExtensionIDs[1]);
recv_encrypted_headers2_.push_back(kHeaderExtensionIDs[0]);
offer_desc.encrypted_header_extension_ids = recv_encrypted_headers1_;
answer_desc.encrypted_header_extension_ids = recv_encrypted_headers2_;
ASSERT_TRUE(
jsep_transport1_
->SetLocalJsepTransportDescription(offer_desc, SdpType::kOffer)
.ok());
ASSERT_TRUE(
jsep_transport2_
->SetRemoteJsepTransportDescription(offer_desc, SdpType::kOffer)
.ok());
ASSERT_TRUE(
jsep_transport2_
->SetLocalJsepTransportDescription(answer_desc, SdpType::kAnswer)
.ok());
ASSERT_TRUE(
jsep_transport1_
->SetRemoteJsepTransportDescription(answer_desc, SdpType::kAnswer)
.ok());
EXPECT_TRUE(jsep_transport1_->rtp_transport()->IsSrtpActive());
EXPECT_TRUE(jsep_transport2_->rtp_transport()->IsSrtpActive());
TestSendRecvPacketWithEncryptedHeaderExtension();
}
INSTANTIATE_TEST_CASE_P(
JsepTransport2Test,
JsepTransport2HeaderExtensionTest,
::testing::Values(
std::make_tuple(Scenario::kSdes, false),
std::make_tuple(Scenario::kDtlsBeforeCallerSendOffer, true),
std::make_tuple(Scenario::kDtlsBeforeCallerSetAnswer, true),
std::make_tuple(Scenario::kDtlsAfterCallerSetAnswer, true),
std::make_tuple(Scenario::kDtlsBeforeCallerSendOffer, false),
std::make_tuple(Scenario::kDtlsBeforeCallerSetAnswer, false),
std::make_tuple(Scenario::kDtlsAfterCallerSetAnswer, false)));
} // namespace cricket
| 23,005 |
343 | <reponame>nzeh/syzygy<gh_stars>100-1000
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Declares the sample grinder, which processes trace files containing
// TraceSampleData records. It can aggregate to a variety of targets
// (basic blocks, functions, compilands, lines), and output to a variety of
// formats (CSV, KCacheGrind).
#ifndef SYZYGY_GRINDER_GRINDERS_SAMPLE_GRINDER_H_
#define SYZYGY_GRINDER_GRINDERS_SAMPLE_GRINDER_H_
#include "syzygy/core/address_space.h"
#include "syzygy/core/string_table.h"
#include "syzygy/grinder/basic_block_util.h"
#include "syzygy/grinder/grinder.h"
#include "syzygy/pe/pe_file.h"
namespace grinder {
namespace grinders {
// This class processes trace files containing TraceSampleData records and
// produces estimates of block/function/compiland heat.
class SampleGrinder : public GrinderInterface {
public:
// The level of aggregation to be used in processing samples.
enum AggregationLevel {
kBasicBlock,
kFunction,
kCompiland,
kLine,
kAggregationLevelMax, // Must be last.
};
// The names of the aggregation levels. These must be kept in sync with
// AggregationLevel.
static const char* kAggregationLevelNames[];
SampleGrinder();
~SampleGrinder();
// @name SampleInterface implementation.
// @{
virtual bool ParseCommandLine(const base::CommandLine* command_line) override;
virtual void SetParser(Parser* parser) override;
virtual bool Grind() override;
virtual bool OutputData(FILE* file) override;
// @}
// @name ParseEventHandler implementation.
// @{
// Override of the OnProcessStarted callback. This is required to get
// the system clock rate for scaling frequency data.
virtual void OnProcessStarted(base::Time time,
DWORD process_id,
const TraceSystemInfo* data) override;
// Override of the OnSampleData callback.
virtual void OnSampleData(base::Time Time,
DWORD process_id,
const TraceSampleData* data) override;
// @}
// @name Parameter names.
// @{
static const char kAggregationLevel[];
static const char kImage[];
// @}
// Forward declarations. These are public so that they are accessible by
// anonymous helper functions.
struct ModuleKey;
struct ModuleData;
// Some type definitions. There are public so that they are accessible by
// anonymous helper functions.
// We store some metadata for each basic-block in an image, allowing us to
// roll up the heat based on different categories.
struct BasicBlockData {
const std::string* compiland;
const std::string* function;
double heat;
};
// This is the type of address-space that is used for representing estimates
// of heat calculated from aggregate sample data.
typedef core::AddressSpace<core::RelativeAddress, size_t, BasicBlockData>
HeatMap;
// This is the final aggregate type used to represent heat as rolled up to
// named objects (compilands or functions).
typedef std::map<const std::string*, double> NameHeatMap;
protected:
// Finds or creates the sample data associated with the given module.
ModuleData* GetModuleData(
const base::FilePath& module_path,
const TraceSampleData* sample_data);
// Upsamples the provided @p module_data so that it has at least as many
// buckets as the @p sample_data. If the resolution is already sufficient
// this does nothing.
// @param sample_data The sample data to be used as a reference.
// @param module_data The module data to be potentially upsampled.
// @note This is exposed for unit testing.
static void UpsampleModuleData(
const TraceSampleData* sample_data,
SampleGrinder::ModuleData* module_data);
// Updates the @p module_data with the samples from @p sample_data. The
// @p module_data must already be at sufficient resolution to accept the
// data in @p sample_data. This can fail if the @p sample_data and the
// @p module_data do not have consistent metadata.
// @param clock_rate The clock rate to be used in scaling the sample data.
// @param sample_data The sample data to be added.
// @param module_data The module data to be incremented.
// @returns True on success, false otherwise.
static bool IncrementModuleData(
double clock_rate,
const TraceSampleData* sample_data,
SampleGrinder::ModuleData* module_data);
// Given a populated @p heat_map and aggregate @p module_data, estimates heat
// for each range in the @p heat_map. The values represent an estimate of
// amount of time spent in the range, in seconds.
// @param module_data Aggregate module data.
// @param heat A pre-populated address space representing the basic blocks of
// the module in question.
// @param total_samples The total number of samples processed will be returned
// here. This is optional and may be NULL.
// @returns the total weight of orphaned samples that were unable to be mapped
// to any range in the heat map.
static double IncrementHeatMapFromModuleData(
const SampleGrinder::ModuleData& module_data,
HeatMap* heat_map,
double* total_samples);
// Given a populated @p heat_map performs an aggregation of the heat based
// on function or compiland names.
// @param aggregation_level The aggregation level. Must be one of
// kFunction or kCompiland.
// @param heat_map The BB heat map to be aggregated.
// @param name_heat_map The named heat map to be populated.
static void RollUpByName(AggregationLevel aggregation_level,
const HeatMap& heat_map,
NameHeatMap* name_heat_map);
// The aggregation level to be used in processing samples.
AggregationLevel aggregation_level_;
// If image_path_ is not empty, then this data is used as a filter for
// processing.
base::FilePath image_path_;
pe::PEFile image_;
pe::PEFile::Signature image_signature_;
// Points to the parser that is feeding us events. Used to get module
// information.
Parser* parser_;
// Set to true if any call to OnIndexedFrequency fails. Processing will
// continue with a warning that results may be partial.
bool event_handler_errored_;
// The clock rate that is currently in force. This is used for scaling
// sample values.
double clock_rate_;
// As we parse sample data we update a running tally at the finest bucket
// size observed in trace files.
typedef std::map<ModuleKey, ModuleData> ModuleDataMap;
ModuleDataMap module_data_;
// These are used for holding final results. They are populated by Grind()
// when the aggregation mode is anything except 'line'.
core::StringTable string_table_;
HeatMap heat_map_;
NameHeatMap name_heat_map_;
// Used only in 'line' aggregation mode. Populated by Grind().
LineInfo line_info_;
private:
DISALLOW_COPY_AND_ASSIGN(SampleGrinder);
};
struct SampleGrinder::ModuleKey {
size_t module_size;
uint32_t module_checksum;
uint32_t module_time_date_stamp;
bool operator<(const ModuleKey& rhs) const;
};
struct SampleGrinder::ModuleData {
ModuleData::ModuleData() : bucket_size(0) {}
base::FilePath module_path;
uint32_t bucket_size;
core::RelativeAddress bucket_start;
std::vector<double> buckets;
};
} // namespace grinders
} // namespace grinder
#endif // SYZYGY_GRINDER_GRINDERS_SAMPLE_GRINDER_H_
| 2,453 |
424 | /*
* Copyright (c) 2011-2020 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.sqlclient.impl.command;
import io.vertx.core.Future;
import io.vertx.core.AsyncResult;
import io.vertx.core.impl.NoStackTraceThrowable;
public class CommandResponse<R> {
public static <R> CommandResponse<R> failure(String msg) {
return failure(new NoStackTraceThrowable(msg));
}
public static <R> CommandResponse<R> failure(Throwable cause) {
return new CommandResponse<>(Future.failedFuture(cause));
}
public static <R> CommandResponse<R> success(R result) {
return new CommandResponse<>(Future.succeededFuture(result));
}
// The connection that executed the command
public CommandBase<R> cmd;
private final AsyncResult<R> res;
public CommandResponse(AsyncResult<R> res) {
this.res = res;
}
public AsyncResult<R> toAsyncResult() {
return res;
}
public void fire() {
if (cmd.handler != null) {
cmd.handler.handle(toAsyncResult());
}
}
}
| 440 |
646 | <gh_stars>100-1000
"""Default command line arguments."""
from nboost.helpers import ListOrCommaDelimitedString
from nboost import PKG_PATH
host = '0.0.0.0'
port = 8000
uhost = '0.0.0.0'
uport = 9200
ussl = False
backlog = 100
verbose = False
query_delim = '. '
lr = 10e-3
max_seq_len = 64
bufsize = 2048
batch_size = 4
topn = 50
workers = 10
data_dir = PKG_PATH.joinpath('.cache')
no_rerank = False
model = 'PtTransformersRerankPlugin'
model_dir = 'nboost/pt-tinybert-msmarco'
qa = False
qa_model = 'PtDistilBertQAModelPlugin'
qa_model_dir = 'distilbert-base-uncased-distilled-squad'
qa_threshold = 0
max_query_length = 64
filter_results = False
query_prep = 'lambda query: query'
debug = False
db_file = data_dir.joinpath('nboost.db')
rerank_cids = ListOrCommaDelimitedString()
prerank = False
# by default, nboost is configured for elasticsearch
search_route = '/<index>/_search'
frontend_route = '/nboost'
status_route = '/status'
query_path = '(body.query.match) | (body.query.term.*) | (url.query.q)'
topk_path = '(body.size) | (url.query.size)'
default_topk = 10
choices_path = 'body.hits.hits'
cvalues_path = '_source.*'
cids_path = '_id'
| 445 |
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.tax.dom;
import org.w3c.dom.*;
import org.netbeans.tax.*;
/**
*
* @author <NAME>
*/
class AttrImpl extends NodeImpl implements Attr {
private final TreeAttribute peer;
/** Creates a new instance of AttrImpl */
public AttrImpl(TreeAttribute peer) {
this.peer = peer;
}
/** The name of this node, depending on its type; see the table above.
*
*/
public String getNodeName() {
return getName();
}
/** A code representing the type of the underlying object, as defined above.
*
*/
public short getNodeType() {
return Node.ATTRIBUTE_NODE;
}
/** The value of this node, depending on its type; see the table above.
* When it is defined to be <code>null</code>, setting it has no effect.
* @exception DOMException
* NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
* @exception DOMException
* DOMSTRING_SIZE_ERR: Raised when it would return more characters than
* fit in a <code>DOMString</code> variable on the implementation
* platform.
*
*/
public String getNodeValue() throws DOMException {
return getValue();
}
/** The parent of this node. All nodes, except <code>Attr</code>,
* <code>Document</code>, <code>DocumentFragment</code>,
* <code>Entity</code>, and <code>Notation</code> may have a parent.
* However, if a node has just been created and not yet added to the
* tree, or if it has been removed from the tree, this is
* <code>null</code>.
*
*/
public Node getParentNode() {
return null;
}
/** Returns the name of this attribute.
*
*/
public String getName() {
return peer.getQName();
}
/** The <code>Element</code> node this attribute is attached to or
* <code>null</code> if this attribute is not in use.
* @since DOM Level 2
*
*/
public Element getOwnerElement() {
return Wrapper.wrap(peer.getOwnerElement());
}
/** If this attribute was explicitly given a value in the original
* document, this is <code>true</code>; otherwise, it is
* <code>false</code>. Note that the implementation is in charge of this
* attribute, not the user. If the user changes the value of the
* attribute (even if it ends up having the same value as the default
* value) then the <code>specified</code> flag is automatically flipped
* to <code>true</code>. To re-specify the attribute as the default
* value from the DTD, the user must delete the attribute. The
* implementation will then make a new attribute available with
* <code>specified</code> set to <code>false</code> and the default
* value (if one exists).
* <br>In summary: If the attribute has an assigned value in the document
* then <code>specified</code> is <code>true</code>, and the value is
* the assigned value.If the attribute has no assigned value in the
* document and has a default value in the DTD, then
* <code>specified</code> is <code>false</code>, and the value is the
* default value in the DTD.If the attribute has no assigned value in
* the document and has a value of #IMPLIED in the DTD, then the
* attribute does not appear in the structure model of the document.If
* the <code>ownerElement</code> attribute is <code>null</code> (i.e.
* because it was just created or was set to <code>null</code> by the
* various removal and cloning operations) <code>specified</code> is
* <code>true</code>.
*
*/
public boolean getSpecified() {
return peer.isSpecified();
}
/** On retrieval, the value of the attribute is returned as a string.
* Character and general entity references are replaced with their
* values. See also the method <code>getAttribute</code> on the
* <code>Element</code> interface.
* <br>On setting, this creates a <code>Text</code> node with the unparsed
* contents of the string. I.e. any characters that an XML processor
* would recognize as markup are instead treated as literal text. See
* also the method <code>setAttribute</code> on the <code>Element</code>
* interface.
* @exception DOMException
* NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
*
*/
public String getValue() {
return peer.getValue();
}
/** On retrieval, the value of the attribute is returned as a string.
* Character and general entity references are replaced with their
* values. See also the method <code>getAttribute</code> on the
* <code>Element</code> interface.
* <br>On setting, this creates a <code>Text</code> node with the unparsed
* contents of the string. I.e. any characters that an XML processor
* would recognize as markup are instead treated as literal text. See
* also the method <code>setAttribute</code> on the <code>Element</code>
* interface.
* @exception DOMException
* NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
*
*/
public void setValue(String value) throws DOMException {
throw new ROException();
}
}
| 2,044 |
72,551 | //===--- Tracing.cpp ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SourceKit/Support/Tracing.h"
#include "swift/Frontend/Frontend.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/YAMLTraits.h"
using namespace SourceKit;
using namespace llvm;
using swift::OptionSet;
static llvm::sys::Mutex consumersLock;
// Must hold consumersLock to access.
static std::vector<trace::TraceConsumer *> consumers;
// Must hold consumersLock to modify, but can be read any time.
static std::atomic<uint64_t> tracedOperations;
//===----------------------------------------------------------------------===//
// Trace commands
//===----------------------------------------------------------------------===//
// Is tracing enabled
bool trace::anyEnabled() { return static_cast<bool>(tracedOperations); }
bool trace::enabled(OperationKind op) {
return OptionSet<OperationKind>(tracedOperations).contains(op);
}
// Trace start of perform sema call, returns OpId
uint64_t trace::startOperation(trace::OperationKind OpKind,
const trace::SwiftInvocation &Inv,
const trace::StringPairs &OpArgs) {
static std::atomic<uint64_t> operationId(0);
auto OpId = ++operationId;
if (trace::anyEnabled()) {
llvm::sys::ScopedLock L(consumersLock);
for (auto *consumer : consumers) {
consumer->operationStarted(OpId, OpKind, Inv, OpArgs);
}
}
return OpId;
}
// Operation previously started with startXXX has finished
void trace::operationFinished(uint64_t OpId, trace::OperationKind OpKind,
ArrayRef<DiagnosticEntryInfo> Diagnostics) {
if (trace::anyEnabled()) {
llvm::sys::ScopedLock L(consumersLock);
for (auto *consumer : consumers) {
consumer->operationFinished(OpId, OpKind, Diagnostics);
}
}
}
// Must be called with consumersLock held.
static void updateTracedOperations() {
OptionSet<trace::OperationKind> operations;
for (auto *consumer : consumers) {
operations |= consumer->desiredOperations();
}
// It is safe to store without a compare, because writers hold consumersLock.
tracedOperations.store(uint64_t(operations), std::memory_order_relaxed);
}
// Register trace consumer
void trace::registerConsumer(trace::TraceConsumer *Consumer) {
llvm::sys::ScopedLock L(consumersLock);
consumers.push_back(Consumer);
updateTracedOperations();
}
void trace::unregisterConsumer(trace::TraceConsumer *Consumer) {
llvm::sys::ScopedLock L(consumersLock);
consumers.erase(std::remove(consumers.begin(), consumers.end(), Consumer),
consumers.end());
updateTracedOperations();
}
| 968 |
1,144 | package org.compiere.model;
import org.adempiere.model.ModelColumn;
import javax.annotation.Nullable;
/** Generated Interface for C_User_Role
* @author metasfresh (generated)
*/
@SuppressWarnings("unused")
public interface I_C_User_Role
{
String Table_Name = "C_User_Role";
// /** AD_Table_ID=541776 */
// int Table_ID = org.compiere.model.MTable.getTable_ID(Table_Name);
/**
* Get Mandant.
* Mandant für diese Installation.
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getAD_Client_ID();
String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/**
* Set Organisation.
* Organisatorische Einheit des Mandanten
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setAD_Org_ID (int AD_Org_ID);
/**
* Get Organisation.
* Organisatorische Einheit des Mandanten
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getAD_Org_ID();
String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/**
* Get Erstellt.
* Datum, an dem dieser Eintrag erstellt wurde
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.sql.Timestamp getCreated();
ModelColumn<I_C_User_Role, Object> COLUMN_Created = new ModelColumn<>(I_C_User_Role.class, "Created", null);
String COLUMNNAME_Created = "Created";
/**
* Get Erstellt durch.
* Nutzer, der diesen Eintrag erstellt hat
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getCreatedBy();
String COLUMNNAME_CreatedBy = "CreatedBy";
/**
* Set User Role.
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setC_User_Role_ID (int C_User_Role_ID);
/**
* Get User Role.
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getC_User_Role_ID();
ModelColumn<I_C_User_Role, Object> COLUMN_C_User_Role_ID = new ModelColumn<>(I_C_User_Role.class, "C_User_Role_ID", null);
String COLUMNNAME_C_User_Role_ID = "C_User_Role_ID";
/**
* Set Aktiv.
* Der Eintrag ist im System aktiv
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsActive (boolean IsActive);
/**
* Get Aktiv.
* Der Eintrag ist im System aktiv
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isActive();
ModelColumn<I_C_User_Role, Object> COLUMN_IsActive = new ModelColumn<>(I_C_User_Role.class, "IsActive", null);
String COLUMNNAME_IsActive = "IsActive";
/**
* Set Is Unique For Business Partner.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsUniqueForBPartner (boolean IsUniqueForBPartner);
/**
* Get Is Unique For Business Partner.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isUniqueForBPartner();
ModelColumn<I_C_User_Role, Object> COLUMN_IsUniqueForBPartner = new ModelColumn<>(I_C_User_Role.class, "IsUniqueForBPartner", null);
String COLUMNNAME_IsUniqueForBPartner = "IsUniqueForBPartner";
/**
* Set Name.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setName (@Nullable java.lang.String Name);
/**
* Get Name.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
@Nullable java.lang.String getName();
ModelColumn<I_C_User_Role, Object> COLUMN_Name = new ModelColumn<>(I_C_User_Role.class, "Name", null);
String COLUMNNAME_Name = "Name";
/**
* Get Aktualisiert.
* Datum, an dem dieser Eintrag aktualisiert wurde
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.sql.Timestamp getUpdated();
ModelColumn<I_C_User_Role, Object> COLUMN_Updated = new ModelColumn<>(I_C_User_Role.class, "Updated", null);
String COLUMNNAME_Updated = "Updated";
/**
* Get Aktualisiert durch.
* Nutzer, der diesen Eintrag aktualisiert hat
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getUpdatedBy();
String COLUMNNAME_UpdatedBy = "UpdatedBy";
}
| 1,615 |
332 | package io.github.quickmsg.common.ack;
import io.netty.util.HashedWheelTimer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/**
* @author luxurong
*/
public class TimeAckManager extends HashedWheelTimer implements AckManager {
private final Map<Long, Ack> ackMap = new ConcurrentHashMap<>();
public TimeAckManager(long tickDuration, TimeUnit unit, int ticksPerWheel) {
super( tickDuration, unit, ticksPerWheel);
}
@Override
public void addAck(Ack ack) {
ackMap.put(ack.getId(),ack);
this.newTimeout(ack,ack.getTimed(),ack.getTimeUnit());
}
@Override
public Ack getAck(Long id) {
return ackMap.get(id);
}
@Override
public void deleteAck(Long id) {
ackMap.remove(id);
}
}
| 324 |
372 | <reponame>mjhopkins/google-api-java-client-services
/*
* 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.servicemanagement.model;
/**
* `QuotaLimit` defines a specific limit that applies over a specified duration for a limit type.
* There can be at most one limit for a duration and limit type combination defined within a
* `QuotaGroup`.
*
* <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 Service Management 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 QuotaLimit extends com.google.api.client.json.GenericJson {
/**
* Default number of tokens that can be consumed during the specified duration. This is the number
* of tokens assigned when a client application developer activates the service for his/her
* project.
*
* Specifying a value of 0 will block all requests. This can be used if you are provisioning quota
* to selected consumers and blocking others. Similarly, a value of -1 will indicate an unlimited
* quota. No other negative values are allowed.
*
* Used by group-based quotas only.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long defaultLimit;
/**
* Optional. User-visible, extended description for this quota limit. Should be used only when
* more context is needed to understand this limit than provided by the limit's display name (see:
* `display_name`).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* User-visible display name for this limit. Optional. If not set, the UI will provide a default
* display name based on the quota configuration. This field can be used to override the default
* display name generated from the configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String displayName;
/**
* Duration of this limit in textual notation. Example: "100s", "24h", "1d". For duration longer
* than a day, only multiple of days is supported. We support only "100s" and "1d" for now.
* Additional support will be added in the future. "0" indicates indefinite duration.
*
* Used by group-based quotas only.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String duration;
/**
* Free tier value displayed in the Developers Console for this limit. The free tier is the number
* of tokens that will be subtracted from the billed amount when billing is enabled. This field
* can only be set on a limit with duration "1d", in a billable group; it is invalid on any other
* limit. If this field is not set, it defaults to 0, indicating that there is no free tier for
* this service.
*
* Used by group-based quotas only.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long freeTier;
/**
* Maximum number of tokens that can be consumed during the specified duration. Client application
* developers can override the default limit up to this maximum. If specified, this value cannot
* be set to a value less than the default limit. If not specified, it is set to the default
* limit.
*
* To allow clients to apply overrides with no upper bound, set this to -1, indicating unlimited
* maximum quota.
*
* Used by group-based quotas only.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long maxLimit;
/**
* The name of the metric this quota limit applies to. The quota limits with the same metric will
* be checked together during runtime. The metric must be defined within the service config.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String metric;
/**
* Name of the quota limit.
*
* The name must be provided, and it must be unique within the service. The name can only include
* alphanumeric characters as well as '-'.
*
* The maximum length of the limit name is 64 characters.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Specify the unit of the quota limit. It uses the same syntax as Metric.unit. The supported unit
* kinds are determined by the quota backend system.
*
* Here are some examples: * "1/min/{project}" for quota per minute per project.
*
* Note: the order of unit components is insignificant. The "1" at the beginning is required to
* follow the metric unit syntax.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String unit;
/**
* Tiered limit values. You must specify this as a key:value pair, with an integer value that is
* the maximum number of requests allowed for the specified unit. Currently only STANDARD is
* supported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.util.Map<String, java.lang.Long> values;
/**
* Default number of tokens that can be consumed during the specified duration. This is the number
* of tokens assigned when a client application developer activates the service for his/her
* project.
*
* Specifying a value of 0 will block all requests. This can be used if you are provisioning quota
* to selected consumers and blocking others. Similarly, a value of -1 will indicate an unlimited
* quota. No other negative values are allowed.
*
* Used by group-based quotas only.
* @return value or {@code null} for none
*/
public java.lang.Long getDefaultLimit() {
return defaultLimit;
}
/**
* Default number of tokens that can be consumed during the specified duration. This is the number
* of tokens assigned when a client application developer activates the service for his/her
* project.
*
* Specifying a value of 0 will block all requests. This can be used if you are provisioning quota
* to selected consumers and blocking others. Similarly, a value of -1 will indicate an unlimited
* quota. No other negative values are allowed.
*
* Used by group-based quotas only.
* @param defaultLimit defaultLimit or {@code null} for none
*/
public QuotaLimit setDefaultLimit(java.lang.Long defaultLimit) {
this.defaultLimit = defaultLimit;
return this;
}
/**
* Optional. User-visible, extended description for this quota limit. Should be used only when
* more context is needed to understand this limit than provided by the limit's display name (see:
* `display_name`).
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* Optional. User-visible, extended description for this quota limit. Should be used only when
* more context is needed to understand this limit than provided by the limit's display name (see:
* `display_name`).
* @param description description or {@code null} for none
*/
public QuotaLimit setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* User-visible display name for this limit. Optional. If not set, the UI will provide a default
* display name based on the quota configuration. This field can be used to override the default
* display name generated from the configuration.
* @return value or {@code null} for none
*/
public java.lang.String getDisplayName() {
return displayName;
}
/**
* User-visible display name for this limit. Optional. If not set, the UI will provide a default
* display name based on the quota configuration. This field can be used to override the default
* display name generated from the configuration.
* @param displayName displayName or {@code null} for none
*/
public QuotaLimit setDisplayName(java.lang.String displayName) {
this.displayName = displayName;
return this;
}
/**
* Duration of this limit in textual notation. Example: "100s", "24h", "1d". For duration longer
* than a day, only multiple of days is supported. We support only "100s" and "1d" for now.
* Additional support will be added in the future. "0" indicates indefinite duration.
*
* Used by group-based quotas only.
* @return value or {@code null} for none
*/
public java.lang.String getDuration() {
return duration;
}
/**
* Duration of this limit in textual notation. Example: "100s", "24h", "1d". For duration longer
* than a day, only multiple of days is supported. We support only "100s" and "1d" for now.
* Additional support will be added in the future. "0" indicates indefinite duration.
*
* Used by group-based quotas only.
* @param duration duration or {@code null} for none
*/
public QuotaLimit setDuration(java.lang.String duration) {
this.duration = duration;
return this;
}
/**
* Free tier value displayed in the Developers Console for this limit. The free tier is the number
* of tokens that will be subtracted from the billed amount when billing is enabled. This field
* can only be set on a limit with duration "1d", in a billable group; it is invalid on any other
* limit. If this field is not set, it defaults to 0, indicating that there is no free tier for
* this service.
*
* Used by group-based quotas only.
* @return value or {@code null} for none
*/
public java.lang.Long getFreeTier() {
return freeTier;
}
/**
* Free tier value displayed in the Developers Console for this limit. The free tier is the number
* of tokens that will be subtracted from the billed amount when billing is enabled. This field
* can only be set on a limit with duration "1d", in a billable group; it is invalid on any other
* limit. If this field is not set, it defaults to 0, indicating that there is no free tier for
* this service.
*
* Used by group-based quotas only.
* @param freeTier freeTier or {@code null} for none
*/
public QuotaLimit setFreeTier(java.lang.Long freeTier) {
this.freeTier = freeTier;
return this;
}
/**
* Maximum number of tokens that can be consumed during the specified duration. Client application
* developers can override the default limit up to this maximum. If specified, this value cannot
* be set to a value less than the default limit. If not specified, it is set to the default
* limit.
*
* To allow clients to apply overrides with no upper bound, set this to -1, indicating unlimited
* maximum quota.
*
* Used by group-based quotas only.
* @return value or {@code null} for none
*/
public java.lang.Long getMaxLimit() {
return maxLimit;
}
/**
* Maximum number of tokens that can be consumed during the specified duration. Client application
* developers can override the default limit up to this maximum. If specified, this value cannot
* be set to a value less than the default limit. If not specified, it is set to the default
* limit.
*
* To allow clients to apply overrides with no upper bound, set this to -1, indicating unlimited
* maximum quota.
*
* Used by group-based quotas only.
* @param maxLimit maxLimit or {@code null} for none
*/
public QuotaLimit setMaxLimit(java.lang.Long maxLimit) {
this.maxLimit = maxLimit;
return this;
}
/**
* The name of the metric this quota limit applies to. The quota limits with the same metric will
* be checked together during runtime. The metric must be defined within the service config.
* @return value or {@code null} for none
*/
public java.lang.String getMetric() {
return metric;
}
/**
* The name of the metric this quota limit applies to. The quota limits with the same metric will
* be checked together during runtime. The metric must be defined within the service config.
* @param metric metric or {@code null} for none
*/
public QuotaLimit setMetric(java.lang.String metric) {
this.metric = metric;
return this;
}
/**
* Name of the quota limit.
*
* The name must be provided, and it must be unique within the service. The name can only include
* alphanumeric characters as well as '-'.
*
* The maximum length of the limit name is 64 characters.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the quota limit.
*
* The name must be provided, and it must be unique within the service. The name can only include
* alphanumeric characters as well as '-'.
*
* The maximum length of the limit name is 64 characters.
* @param name name or {@code null} for none
*/
public QuotaLimit setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Specify the unit of the quota limit. It uses the same syntax as Metric.unit. The supported unit
* kinds are determined by the quota backend system.
*
* Here are some examples: * "1/min/{project}" for quota per minute per project.
*
* Note: the order of unit components is insignificant. The "1" at the beginning is required to
* follow the metric unit syntax.
* @return value or {@code null} for none
*/
public java.lang.String getUnit() {
return unit;
}
/**
* Specify the unit of the quota limit. It uses the same syntax as Metric.unit. The supported unit
* kinds are determined by the quota backend system.
*
* Here are some examples: * "1/min/{project}" for quota per minute per project.
*
* Note: the order of unit components is insignificant. The "1" at the beginning is required to
* follow the metric unit syntax.
* @param unit unit or {@code null} for none
*/
public QuotaLimit setUnit(java.lang.String unit) {
this.unit = unit;
return this;
}
/**
* Tiered limit values. You must specify this as a key:value pair, with an integer value that is
* the maximum number of requests allowed for the specified unit. Currently only STANDARD is
* supported.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.Long> getValues() {
return values;
}
/**
* Tiered limit values. You must specify this as a key:value pair, with an integer value that is
* the maximum number of requests allowed for the specified unit. Currently only STANDARD is
* supported.
* @param values values or {@code null} for none
*/
public QuotaLimit setValues(java.util.Map<String, java.lang.Long> values) {
this.values = values;
return this;
}
@Override
public QuotaLimit set(String fieldName, Object value) {
return (QuotaLimit) super.set(fieldName, value);
}
@Override
public QuotaLimit clone() {
return (QuotaLimit) super.clone();
}
}
| 4,654 |
19,529 | SZSE_TSS_DIALOG = 1
SZSE_TSS_PRIVATE = 2
SZSE_TSS_PUBLIC = 3
SZSE_TSS_QUERY = 4
SZSE_FTDC_OWNER_Per = 1
SZSE_FTDC_OWNER_Ex = 101
SZSE_FTDC_OWNER_Op = 102
SZSE_FTDC_OWNER_Institutional = 103
SZSE_FTDC_OWNER_Proprietary = 104
SZSE_FTDC_OWNER_Maker = 105
SZSE_FTDC_OWNER_Clear = 106
SZSE_FTDC_SIDE_Buy = '1'
SZSE_FTDC_SIDE_Sell = '2'
SZSE_FTDC_LOCK_Lock = 'Z'
SZSE_FTDC_LOCK_UnLock = 'Y'
SZSE_FTDC_OC_Open = 'O'
SZSE_FTDC_OC_Close = 'C'
SZSE_FTDC_OrdType_Market = '1'
SZSE_FTDC_OrdType_Limit = '2'
SZSE_FTDC_OrdType_BestPrice = 'U'
SZSE_FTDC_TimeInForce_GFD = '0'
SZSE_FTDC_TimeInForce_IOC = '3'
SZSE_FTDC_TimeInForce_FOK = '4'
SZSE_FTDC_Covered_Covered = 0
SZSE_FTDC_Covered_Uncovered = 1
SZSE_FTDC_Exec_Success = '0'
SZSE_FTDC_Exec_Cancel = '4'
SZSE_FTDC_Exec_Reject = '8'
SZSE_FTDC_Exec_Trade = 'F'
SZSE_FTDC_Status_Success = '0'
SZSE_FTDC_Status_Trade = '1'
SZSE_FTDC_Status_All = '2'
SZSE_FTDC_Status_Cancel = '4'
SZSE_FTDC_Status_Reject = '8'
SZSE_FTDC_HF_Speculation = '1'
SZSE_FTDC_HF_Arbitrage = '2'
SZSE_FTDC_HF_Hedge = '3'
SZSE_FTDC_OptionType_E = 'E'
SZSE_FTDC_OptionType_A = 'A'
SZSE_FTDC__PC_Options = 'O'
SZSE_FTDC__PC_Stocks = 'S'
SZSE_FTDC_CallOrPut_E = 'C'
SZSE_FTDC_CallOrPut_A = 'P'
SZSE_FTDC_ClientType_Spec = 1
SZSE_FTDC_ClientType_Arbit = 2
SZSE_FTDC_ClientType_Hedg = 3
SZSE_FTDC_ClientType_Market = 88
SZSE_FTDC_TradStatus_Normal = 0
SZSE_FTDC_TradStatus_Forbid = 1
| 753 |
1,603 | <filename>smoke-test/tests/test_stateful_ingestion.py<gh_stars>1000+
from typing import Any, Dict, Optional, cast
from datahub.ingestion.api.committable import StatefulCommittable
from datahub.ingestion.run.pipeline import Pipeline
from datahub.ingestion.source.sql.mysql import MySQLConfig, MySQLSource
from datahub.ingestion.source.sql.sql_common import \
BaseSQLAlchemyCheckpointState
from datahub.ingestion.source.state.checkpoint import Checkpoint
from sqlalchemy import create_engine
from sqlalchemy.sql import text
def test_stateful_ingestion(wait_for_healthchecks):
def create_mysql_engine(mysql_source_config_dict: Dict[str, Any]) -> Any:
mysql_config = MySQLConfig.parse_obj(mysql_source_config_dict)
url = mysql_config.get_sql_alchemy_url()
return create_engine(url)
def create_table(engine: Any, name: str, defn: str) -> None:
create_table_query = text(f"CREATE TABLE IF NOT EXISTS {name}{defn};")
engine.execute(create_table_query)
def drop_table(engine: Any, table_name: str) -> None:
drop_table_query = text(f"DROP TABLE {table_name};")
engine.execute(drop_table_query)
def run_and_get_pipeline(pipeline_config_dict: Dict[str, Any]) -> Pipeline:
pipeline = Pipeline.create(pipeline_config_dict)
pipeline.run()
pipeline.raise_from_status()
return pipeline
def validate_all_providers_have_committed_successfully(pipeline: Pipeline) -> None:
provider_count: int = 0
for name, provider in pipeline.ctx.get_committables():
provider_count += 1
assert isinstance(provider, StatefulCommittable)
stateful_committable = cast(StatefulCommittable, provider)
assert stateful_committable.has_successfully_committed()
assert stateful_committable.state_to_commit
assert provider_count == 2
def get_current_checkpoint_from_pipeline(
pipeline: Pipeline,
) -> Optional[Checkpoint]:
mysql_source = cast(MySQLSource, pipeline.source)
return mysql_source.get_current_checkpoint(
mysql_source.get_default_ingestion_job_id()
)
source_config_dict: Dict[str, Any] = {
"username": "datahub",
"password": "<PASSWORD>",
"database": "datahub",
"stateful_ingestion": {
"enabled": True,
"remove_stale_metadata": True,
"state_provider": {
"type": "datahub",
"config": {"datahub_api": {"server": "http://localhost:8080"}},
},
},
}
pipeline_config_dict: Dict[str, Any] = {
"source": {
"type": "mysql",
"config": source_config_dict,
},
"sink": {
"type": "datahub-rest",
"config": {"server": "http://localhost:8080"},
},
"pipeline_name": "mysql_stateful_ingestion_smoke_test_pipeline",
"reporting": [
{
"type": "datahub",
"config": {"datahub_api": {"server": "http://localhost:8080"}},
}
],
}
# 1. Setup the SQL engine
mysql_engine = create_mysql_engine(source_config_dict)
# 2. Create test tables for first run of the pipeline.
table_prefix = "stateful_ingestion_test"
table_defs = {
f"{table_prefix}_t1": "(id INT, name VARCHAR(10))",
f"{table_prefix}_t2": "(id INT)",
}
table_names = sorted(table_defs.keys())
for table_name, defn in table_defs.items():
create_table(mysql_engine, table_name, defn)
# 3. Do the first run of the pipeline and get the default job's checkpoint.
pipeline_run1 = run_and_get_pipeline(pipeline_config_dict)
checkpoint1 = get_current_checkpoint_from_pipeline(pipeline_run1)
assert checkpoint1
assert checkpoint1.state
# 4. Drop table t1 created during step 2 + rerun the pipeline and get the checkpoint state.
drop_table(mysql_engine, table_names[0])
pipeline_run2 = run_and_get_pipeline(pipeline_config_dict)
checkpoint2 = get_current_checkpoint_from_pipeline(pipeline_run2)
assert checkpoint2
assert checkpoint2.state
# 5. Perform all assertions on the states
state1 = cast(BaseSQLAlchemyCheckpointState, checkpoint1.state)
state2 = cast(BaseSQLAlchemyCheckpointState, checkpoint2.state)
difference_urns = list(state1.get_table_urns_not_in(state2))
assert len(difference_urns) == 1
assert (
difference_urns[0]
== "urn:li:dataset:(urn:li:dataPlatform:mysql,datahub.stateful_ingestion_test_t1,PROD)"
)
# 6. Perform all assertions on the config.
assert checkpoint1.config == checkpoint2.config
# 7. Cleanup table t2 as well to prevent other tests that rely on data in the smoke-test world.
drop_table(mysql_engine, table_names[1])
# 8. Validate that all providers have committed successfully.
# NOTE: The following validation asserts for presence of state as well
# and validates reporting.
validate_all_providers_have_committed_successfully(pipeline_run1)
validate_all_providers_have_committed_successfully(pipeline_run2)
| 2,125 |
345 | /*
* Copyright 2016 HuntBugs contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package one.util.huntbugs.detect;
import com.strobel.assembler.metadata.MethodReference;
import com.strobel.decompiler.ast.AstCode;
import com.strobel.decompiler.ast.Expression;
import com.strobel.decompiler.ast.Node;
import one.util.huntbugs.registry.MethodContext;
import one.util.huntbugs.registry.anno.AstVisitor;
import one.util.huntbugs.registry.anno.WarningDefinition;
import one.util.huntbugs.util.Nodes;
import one.util.huntbugs.warning.Role.NumberRole;
import one.util.huntbugs.warning.Role.StringRole;
/**
* @author <NAME>
*
*/
@WarningDefinition(category = "Correctness", name = "InvalidMinMax", maxScore = 80)
public class InvalidMinMax {
private static final NumberRole OUTER_NUMBER = NumberRole.forName("OUTER_NUMBER");
private static final NumberRole INNER_NUMBER = NumberRole.forName("INNER_NUMBER");
private static final StringRole OUTER_FUNC = StringRole.forName("OUTER_FUNC");
private static final StringRole INNER_FUNC = StringRole.forName("INNER_FUNC");
private static final int NONE = 0;
private static final int MIN = -1;
private static final int MAX = 1;
private static int detectMethod(Node node) {
if (!Nodes.isOp(node, AstCode.InvokeStatic)
|| node.getChildren().size() != 2)
return NONE;
MethodReference mr = (MethodReference) ((Expression) node).getOperand();
if (!mr.getDeclaringType().getPackageName().equals("java.lang"))
return NONE;
if (mr.getName().equals("max"))
return MAX;
if (mr.getName().equals("min"))
return MIN;
return NONE;
}
@AstVisitor
public void visit(Node node, MethodContext mc) {
int outer = detectMethod(node);
if (outer == NONE)
return;
Node left = Nodes.getChild(node, 0);
Node right = Nodes.getChild(node, 1);
int leftChild = detectMethod(left);
int rightChild = detectMethod(right);
if (leftChild == NONE && rightChild == NONE)
return;
if (outer == leftChild || outer == rightChild
|| leftChild == rightChild)
return;
if (rightChild != NONE) {
Node tmp = left;
left = right;
right = tmp;
}
Object outerConst = Nodes.getConstant(right);
if (!(outerConst instanceof Number))
return;
Node expr = left.getChildren().get(0);
Object innerConst = Nodes.getConstant(expr);
if (!(innerConst instanceof Number)) {
innerConst = Nodes.getConstant(left.getChildren().get(1));
} else {
expr = left.getChildren().get(1);
}
if (!(innerConst instanceof Number))
return;
@SuppressWarnings("unchecked")
int cmp = ((Comparable<Object>) outerConst).compareTo(innerConst)
* outer;
if (cmp > 0)
mc.report("InvalidMinMax", 0, expr, OUTER_NUMBER.create((Number) outerConst), OUTER_FUNC.create(outer == MAX
? "max" : "min"), INNER_NUMBER.create((Number) innerConst), INNER_FUNC.create(outer == MAX ? "min"
: "max"));
}
}
| 1,218 |
473 | /*
* Copyright (c) 2015 Kaprica Security, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "cgc_stdio.h"
#include "cgc_calendar.h"
#define MAX_AGENDA_EVENTS 8
#define AGENDA_LOOKAHEAD 3
void cgc_view_day(calendar_t * cal, date_t date)
{
char date_str[16];
cgc_get_date_str(date_str, &date);
event_list_t *iter = cal->events;
int datecmp = 0;
cgc_printf("Viewing Calendar Appointments for %s\n", date_str);
while(iter) {
datecmp = cgc_compare_date(&iter->event->duration.start.date, &date);
if (datecmp > 0)
break;
if (cgc_date_within(iter->event->duration, date)) {
cgc_printf("------------------------\n");
cgc_print_event(iter->event);
}
iter = iter->next;
}
cgc_printf("------------------------\n");
}
void cgc_view_month(calendar_t * cal, date_t date)
{
char date_str[16];
cgc_get_date_str(date_str, &date);
event_list_t *iter = cal->events;
int datecmp = 0;
char *month = cgc_get_month(&date);
cgc_printf("Viewing Monthly Calendar for %s %d\n", month, date.year);
while(iter) {
if (iter->event->duration.start.date.month >= date.month &&
iter->event->duration.end.date.month <= date.month) {
cgc_printf("------------------------\n");
cgc_print_event(iter->event);
}
iter = iter->next;
}
cgc_printf("------------------------\n");
}
date_t cgc_calc_agenda_lookahead(date_t date)
{
date_t lookahead = date;
lookahead.year += AGENDA_LOOKAHEAD / 12;
if (AGENDA_LOOKAHEAD % 12 == 0)
return lookahead;
lookahead.month = (date.month + AGENDA_LOOKAHEAD);
if (lookahead.month > 12) {
lookahead.year++;
lookahead.month %= 12;
}
return lookahead;
}
void cgc_view_agenda(calendar_t *cal, date_t date)
{
int i = 0, printed_events = 0;
char date_str[16];
cgc_get_date_str(date_str, &date);
date_t lookahead = cgc_calc_agenda_lookahead(date);
event_list_t *iter = cal->events;
int datecmp = 0;
char *month = cgc_get_month(&date);
cgc_printf("Agenda View\n");
while(i++ < cal->num_events && printed_events < MAX_AGENDA_EVENTS) {
datecmp = cgc_compare_date(&iter->event->duration.start.date, &date);
if (datecmp < 0) {
iter = iter->next;
continue;
}
if (cgc_compare_date(&iter->event->duration.start.date, &lookahead) <= 0) {
cgc_printf("------------------------\n");
cgc_print_event(iter->event);
printed_events++;
} else {
break;
}
iter = iter->next;
}
cgc_printf("------------------------\n");
}
bool cgc_add_calendar_event(calendar_t *cal, event_t *event)
{
if (cgc_insert_in_order((list_t **)&cal->events, event, &cgc_compare_event_dates)) {
cal->num_events++;
return true;
}
return false;
}
bool cgc_remove_calendar_event(calendar_t *cal, event_t *event)
{
event = cgc_pop((list_t **)&cal->events, event, &cgc_compare_events);
if (cgc_delete_event(&event)) {
cal->num_events--;
return true;
}
return false;
}
| 1,730 |
348 | {"nom":"Saint-Sauveur-de-Pierrepont","dpt":"Manche","inscrits":109,"abs":27,"votants":82,"blancs":10,"nuls":4,"exp":68,"res":[{"panneau":"2","voix":38},{"panneau":"1","voix":30}]} | 77 |
1,587 | package io.reflectoring.modules.mail;
import io.reflectoring.modules.mail.api.EmailNotificationService;
import org.mockito.Mockito;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.*;
@TestConfiguration
public class EmailModuleMock {
private final EmailNotificationService emailNotificationServiceMock = Mockito.mock(EmailNotificationService.class);
@Bean
@Primary
EmailNotificationService emailNotificationServiceMock() {
return emailNotificationServiceMock;
}
public void givenSendMailSucceeds() {
// nothing to do, the mock will simply return 0
}
public void givenSendMailThrowsError() {
doThrow(new RuntimeException("error when sending mail"))
.when(emailNotificationServiceMock).sendEmail(anyString(), anyString(), anyString());
}
public void assertSentMailContains(String repositoryUrl) {
verify(emailNotificationServiceMock).sendEmail(anyString(), anyString(), contains(repositoryUrl));
}
public void assertNoMailSent() {
verify(emailNotificationServiceMock, never()).sendEmail(anyString(), anyString(), anyString());
}
}
| 452 |
2,366 | /*
* =============================================================================
*
* Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.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 org.thymeleaf.engine;
import java.io.Writer;
import org.thymeleaf.exceptions.TemplateOutputException;
import org.thymeleaf.model.ICDATASection;
import org.thymeleaf.model.ICloseElementTag;
import org.thymeleaf.model.IComment;
import org.thymeleaf.model.IDocType;
import org.thymeleaf.model.IOpenElementTag;
import org.thymeleaf.model.IProcessingInstruction;
import org.thymeleaf.model.IStandaloneElementTag;
import org.thymeleaf.model.IText;
import org.thymeleaf.model.IXMLDeclaration;
/**
*
* @author <NAME>
* @since 3.0.0
*
*/
public final class OutputTemplateHandler extends AbstractTemplateHandler {
private final Writer writer;
/**
* <p>
* Creates a new instance of this handler.
* </p>
*
* @param writer the writer to which output will be written.
*/
public OutputTemplateHandler(final Writer writer) {
super();
if (writer == null) {
throw new IllegalArgumentException("Writer cannot be null");
}
this.writer = writer;
}
@Override
public void handleText(final IText text) {
try {
text.write(this.writer);
} catch (final Exception e) {
throw new TemplateOutputException(
"An error happened during template rendering",
text.getTemplateName(), text.getLine(), text.getCol(), e);
}
// Just in case someone set us a 'next'
super.handleText(text);
}
@Override
public void handleComment(final IComment comment) {
try {
comment.write(this.writer);
} catch (final Exception e) {
throw new TemplateOutputException(
"An error happened during template rendering",
comment.getTemplateName(), comment.getLine(), comment.getCol(), e);
}
// Just in case someone set us a 'next'
super.handleComment(comment);
}
@Override
public void handleCDATASection(final ICDATASection cdataSection) {
try {
cdataSection.write(this.writer);
} catch (final Exception e) {
throw new TemplateOutputException(
"An error happened during template rendering",
cdataSection.getTemplateName(), cdataSection.getLine(), cdataSection.getCol(), e);
}
// Just in case someone set us a 'next'
super.handleCDATASection(cdataSection);
}
@Override
public void handleStandaloneElement(final IStandaloneElementTag standaloneElementTag) {
try {
standaloneElementTag.write(this.writer);
} catch (final Exception e) {
throw new TemplateOutputException(
"An error happened during template rendering",
standaloneElementTag.getTemplateName(), standaloneElementTag.getLine(), standaloneElementTag.getCol(), e);
}
// Just in case someone set us a 'next'
super.handleStandaloneElement(standaloneElementTag);
}
@Override
public void handleOpenElement(final IOpenElementTag openElementTag) {
try {
openElementTag.write(this.writer);
} catch (final Exception e) {
throw new TemplateOutputException(
"An error happened during template rendering",
openElementTag.getTemplateName(), openElementTag.getLine(), openElementTag.getCol(), e);
}
// Just in case someone set us a 'next'
super.handleOpenElement(openElementTag);
}
@Override
public void handleCloseElement(final ICloseElementTag closeElementTag) {
try {
closeElementTag.write(this.writer);
} catch (final Exception e) {
throw new TemplateOutputException(
"An error happened during template rendering",
closeElementTag.getTemplateName(), closeElementTag.getLine(), closeElementTag.getCol(), e);
}
// Just in case someone set us a 'next'
super.handleCloseElement(closeElementTag);
}
@Override
public void handleDocType(final IDocType docType) {
try {
docType.write(this.writer);
} catch (final Exception e) {
throw new TemplateOutputException(
"An error happened during template rendering",
docType.getTemplateName(), docType.getLine(), docType.getCol(), e);
}
// Just in case someone set us a 'next'
super.handleDocType(docType);
}
@Override
public void handleXMLDeclaration(final IXMLDeclaration xmlDeclaration) {
try {
xmlDeclaration.write(this.writer);
} catch (final Exception e) {
throw new TemplateOutputException(
"An error happened during template rendering",
xmlDeclaration.getTemplateName(), xmlDeclaration.getLine(), xmlDeclaration.getCol(), e);
}
// Just in case someone set us a 'next'
super.handleXMLDeclaration(xmlDeclaration);
}
@Override
public void handleProcessingInstruction(final IProcessingInstruction processingInstruction) {
try {
processingInstruction.write(this.writer);
} catch (final Exception e) {
throw new TemplateOutputException(
"An error happened during template rendering",
processingInstruction.getTemplateName(), processingInstruction.getLine(), processingInstruction.getCol(), e);
}
// Just in case someone set us a 'next'
super.handleProcessingInstruction(processingInstruction);
}
} | 2,592 |
14,668 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/task_manager/providers/browser_process_task.h"
#include "chrome/browser/task_manager/task_manager_observer.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/grit/theme_resources.h"
#include "third_party/sqlite/sqlite3.h"
#include "ui/base/l10n/l10n_util.h"
namespace task_manager {
gfx::ImageSkia* BrowserProcessTask::s_icon_ = nullptr;
BrowserProcessTask::BrowserProcessTask()
: Task(l10n_util::GetStringUTF16(IDS_TASK_MANAGER_WEB_BROWSER_CELL_TEXT),
FetchIcon(IDR_PRODUCT_LOGO_16, &s_icon_),
base::GetCurrentProcessHandle()),
used_sqlite_memory_(-1) {}
BrowserProcessTask::~BrowserProcessTask() {
}
bool BrowserProcessTask::IsKillable() {
// Never kill the browser process.
return false;
}
void BrowserProcessTask::Kill() {
// Never kill the browser process.
}
void BrowserProcessTask::Refresh(const base::TimeDelta& update_interval,
int64_t refresh_flags) {
Task::Refresh(update_interval, refresh_flags);
if ((refresh_flags & REFRESH_TYPE_SQLITE_MEMORY) != 0)
used_sqlite_memory_ = static_cast<int64_t>(sqlite3_memory_used());
}
Task::Type BrowserProcessTask::GetType() const {
return Task::BROWSER;
}
int BrowserProcessTask::GetChildProcessUniqueID() const {
return 0;
}
int64_t BrowserProcessTask::GetSqliteMemoryUsed() const {
return used_sqlite_memory_;
}
} // namespace task_manager
| 587 |
1,604 | <reponame>matheus-eyng/bc-java
package org.bouncycastle.asn1;
import java.io.IOException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;
public abstract class ASN1GraphicString
extends ASN1Primitive
implements ASN1String
{
static final ASN1UniversalType TYPE = new ASN1UniversalType(ASN1GraphicString.class, BERTags.GRAPHIC_STRING)
{
ASN1Primitive fromImplicitPrimitive(DEROctetString octetString)
{
return createPrimitive(octetString.getOctets());
}
};
/**
* Return a GraphicString from the passed in object.
*
* @param obj an ASN1GraphicString or an object that can be converted into one.
* @exception IllegalArgumentException if the object cannot be converted.
* @return an ASN1GraphicString instance, or null.
*/
public static ASN1GraphicString getInstance(Object obj)
{
if (obj == null || obj instanceof ASN1GraphicString)
{
return (ASN1GraphicString)obj;
}
if (obj instanceof ASN1Encodable)
{
ASN1Primitive primitive = ((ASN1Encodable)obj).toASN1Primitive();
if (primitive instanceof ASN1GraphicString)
{
return (ASN1GraphicString)primitive;
}
}
if (obj instanceof byte[])
{
try
{
return (ASN1GraphicString)TYPE.fromByteArray((byte[])obj);
}
catch (Exception e)
{
throw new IllegalArgumentException("encoding error in getInstance: " + e.toString());
}
}
throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
}
/**
* Return a GraphicString from a tagged object.
*
* @param taggedObject the tagged object holding the object we want.
* @param explicit true if the object is meant to be explicitly tagged,
* false otherwise.
* @exception IllegalArgumentException if the tagged object cannot be converted.
* @return an ASN1GraphicString instance, or null.
*/
public static ASN1GraphicString getInstance(ASN1TaggedObject taggedObject, boolean explicit)
{
return (ASN1GraphicString)TYPE.getContextInstance(taggedObject, explicit);
}
final byte[] contents;
ASN1GraphicString(byte[] contents, boolean clone)
{
this.contents = clone ? Arrays.clone(contents) : contents;
}
public final byte[] getOctets()
{
return Arrays.clone(contents);
}
final boolean isConstructed()
{
return false;
}
final int encodedLength(boolean withTag)
{
return ASN1OutputStream.getLengthOfEncodingDL(withTag, contents.length);
}
final void encode(ASN1OutputStream out, boolean withTag) throws IOException
{
out.writeEncodingDL(withTag, BERTags.GRAPHIC_STRING, contents);
}
final boolean asn1Equals(ASN1Primitive other)
{
if (!(other instanceof ASN1GraphicString))
{
return false;
}
ASN1GraphicString that = (ASN1GraphicString)other;
return Arrays.areEqual(this.contents, that.contents);
}
public final int hashCode()
{
return Arrays.hashCode(contents);
}
public final String getString()
{
return Strings.fromByteArray(contents);
}
static ASN1GraphicString createPrimitive(byte[] contents)
{
return new DERGraphicString(contents, false);
}
}
| 1,507 |
339 | /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate to change the passphrase for a
* private key file instead of creating a new private key.
* $ CLASSPATH=.:../build javac ChangePassphrase.java
* $ CLASSPATH=.:../build java ChangePassphrase private-key
* A passphrase will be prompted if the given private-key has been
* encrypted. After successfully loading the content of the
* private-key, the new passphrase will be prompted and the given
* private-key will be re-encrypted with that new passphrase.
*
*/
import com.jcraft.jsch.*;
import javax.swing.*;
class ChangePassphrase{
public static void main(String[] arg){
if(arg.length!=1){
System.err.println("usage: java ChangePassphrase private_key");
System.exit(-1);
}
JSch jsch=new JSch();
String pkey=arg[0];
try{
KeyPair kpair=KeyPair.load(jsch, pkey);
System.out.println(pkey+" has "+(kpair.isEncrypted()?"been ":"not been ")+"encrypted");
String passphrase="";
while(kpair.isEncrypted()){
JTextField passphraseField=(JTextField)new JPasswordField(20);
Object[] ob={passphraseField};
int result=JOptionPane.showConfirmDialog(null, ob,
"Enter passphrase for "+pkey,
JOptionPane.OK_CANCEL_OPTION);
if(result!=JOptionPane.OK_OPTION){
System.exit(-1);
}
passphrase=passphraseField.getText();
if(!kpair.decrypt(passphrase)){
System.out.println("failed to decrypt "+pkey);
}
else{
System.out.println(pkey+" is decrypted.");
}
}
passphrase="";
JTextField passphraseField=(JTextField)new JPasswordField(20);
Object[] ob={passphraseField};
int result=JOptionPane.showConfirmDialog(null, ob,
"Enter new passphrase for "+pkey+
" (empty for no passphrase)",
JOptionPane.OK_CANCEL_OPTION);
if(result!=JOptionPane.OK_OPTION){
System.exit(-1);
}
passphrase=passphraseField.getText();
kpair.setPassphrase(passphrase);
kpair.writePrivateKey(pkey);
kpair.dispose();
}
catch(Exception e){
System.out.println(e);
}
System.exit(0);
}
}
| 849 |
2,759 | <reponame>Liang813/graphics
# Copyright 2020 The TensorFlow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module implements the precision metric."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow_graphics.util import export_api
from tensorflow_graphics.util import safe_ops
from tensorflow_graphics.util import shape
def _cast_to_int(prediction):
return tf.cast(x=prediction, dtype=tf.int32)
def evaluate(ground_truth,
prediction,
classes=None,
reduce_average=True,
prediction_to_category_function=_cast_to_int,
name="precision_evaluate"):
"""Computes the precision metric for the given ground truth and predictions.
Note:
In the following, A1 to An are optional batch dimensions, which must be
broadcast compatible.
Args:
ground_truth: A tensor of shape `[A1, ..., An, N]`, where the last axis
represents the ground truth labels. Will be cast to int32.
prediction: A tensor of shape `[A1, ..., An, N]`, where the last axis
represents the predictions (which can be continuous).
classes: An integer or a list/tuple of integers representing the classes for
which the precision will be evaluated. In case 'classes' is 'None', the
number of classes will be inferred from the given labels and the precision
will be calculated for each of the classes. Defaults to 'None'.
reduce_average: Whether to calculate the average of the precision for each
class and return a single precision value. Defaults to true.
prediction_to_category_function: A function to associate a `prediction` to a
category. Defaults to rounding down the value of the prediction to the
nearest integer value.
name: A name for this op. Defaults to "precision_evaluate".
Returns:
A tensor of shape `[A1, ..., An, C]`, where the last axis represents the
precision calculated for each of the requested classes.
Raises:
ValueError: if the shape of `ground_truth`, `prediction` is not supported.
"""
with tf.name_scope(name):
ground_truth = tf.cast(
x=tf.convert_to_tensor(value=ground_truth), dtype=tf.int32)
prediction = tf.convert_to_tensor(value=prediction)
shape.compare_batch_dimensions(
tensors=(ground_truth, prediction),
tensor_names=("ground_truth", "prediction"),
last_axes=-1,
broadcast_compatible=True)
prediction = prediction_to_category_function(prediction)
if classes is None:
num_classes = tf.math.maximum(
tf.math.reduce_max(input_tensor=ground_truth),
tf.math.reduce_max(input_tensor=prediction)) + 1
classes = tf.range(num_classes)
else:
classes = tf.convert_to_tensor(value=classes)
# Make sure classes is a tensor of rank 1.
classes = tf.reshape(classes, [1]) if tf.rank(classes) == 0 else classes
# Create a confusion matrix for each of the classes (with dimensions
# [A1, ..., An, C, N]).
classes = tf.expand_dims(classes, -1)
ground_truth_per_class = tf.equal(tf.expand_dims(ground_truth, -2), classes)
prediction_per_class = tf.equal(tf.expand_dims(prediction, -2), classes)
# Calculate the precision for each of the classes.
true_positives = tf.math.reduce_sum(
input_tensor=tf.cast(
x=tf.math.logical_and(ground_truth_per_class, prediction_per_class),
dtype=tf.float32),
axis=-1)
total_predicted_positives = tf.math.reduce_sum(
input_tensor=tf.cast(x=prediction_per_class, dtype=tf.float32), axis=-1)
precision_per_class = safe_ops.safe_signed_div(true_positives,
total_predicted_positives)
if reduce_average:
return tf.math.reduce_mean(input_tensor=precision_per_class, axis=-1)
else:
return precision_per_class
# API contains all public functions and classes.
__all__ = export_api.get_functions_and_classes()
| 1,618 |
892 | <reponame>github/advisory-database
{
"schema_version": "1.2.0",
"id": "GHSA-42mf-g9wr-grvh",
"modified": "2022-05-17T00:01:47Z",
"published": "2022-05-17T00:01:47Z",
"aliases": [
"CVE-2022-30778"
],
"details": "Laravel 9.1.8, when processing attacker-controlled data for deserialization, allows Remote Code Execution via an unserialize pop chain in __destruct in Illuminate\\Broadcasting\\PendingBroadcast.php and dispatch($command) in Illuminate\\Bus\\QueueingDispatcher.php.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-30778"
},
{
"type": "WEB",
"url": "https://github.com/1nhann/vulns/issues/1"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": null,
"github_reviewed": false
}
} | 372 |
852 | <gh_stars>100-1000
// BasicJet.cc
// <NAME>, UMd
#include <sstream>
//Own header file
#include "DataFormats/JetReco/interface/BasicJet.h"
using namespace reco;
BasicJet::BasicJet(const LorentzVector& fP4, const Point& fVertex) : Jet(fP4, fVertex) {}
BasicJet::BasicJet(const LorentzVector& fP4, const Point& fVertex, const Jet::Constituents& fConstituents)
: Jet(fP4, fVertex, fConstituents) {}
BasicJet* BasicJet::clone() const { return new BasicJet(*this); }
bool BasicJet::overlap(const Candidate&) const { return false; }
std::string BasicJet::print() const {
std::ostringstream out;
out << Jet::print() // generic jet info
<< " BasicJet specific: None" << std::endl;
return out.str();
}
| 262 |
678 | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/IMCore.framework/Frameworks/IMTranscoding.framework/IMTranscoding
*/
#import <IMTranscoding/IMTranscoding-Structs.h>
#import <IMTranscoding/IMTranscodeController.h>
| 89 |
869 | <reponame>stjordanis/PyTables<gh_stars>100-1000
"""This script compares the speed of the computation of a polynomial for
different (numpy.memmap and tables.Expr) out-of-memory paradigms."""
from pathlib import Path
from time import perf_counter as clock
import numpy as np
import tables as tb
import numexpr as ne
expr = ".25*x**3 + .75*x**2 - 1.5*x - 2" # the polynomial to compute
N = 10 * 1000 * 1000 # the number of points to compute expression (80 MB)
step = 100 * 1000 # perform calculation in slices of `step` elements
dtype = np.dtype('f8') # the datatype
#CHUNKSHAPE = (2**17,)
CHUNKSHAPE = None
# Global variable for the x values for pure numpy & numexpr
x = None
# *** The next variables do not need to be changed ***
# Filenames for numpy.memmap
fprefix = "numpy.memmap" # the I/O file prefix
mpfnames = [fprefix + "-x.bin", fprefix + "-r.bin"]
# Filename for tables.Expr
h5fname = "tablesExpr.h5" # the I/O file
MB = 1024 * 1024 # a MegaByte
def print_filesize(filename, clib=None, clevel=0):
"""Print some statistics about file sizes."""
# os.system("sync") # make sure that all data has been flushed to disk
if isinstance(filename, list):
filesize_bytes = sum(Path(fname).stat().st_size for fname in filename)
else:
filesize_bytes = Path(filename).stat().st_size
print(
f"\t\tTotal file sizes: {filesize_bytes} -- "
f"({filesize_bytes / MB:.1f} MB)", end=' ')
if clevel > 0:
print(f"(using {clib} lvl{clevel})")
else:
print()
def populate_x_numpy():
"""Populate the values in x axis for numpy."""
global x
# Populate x in range [-1, 1]
x = np.linspace(-1, 1, N)
def populate_x_memmap():
"""Populate the values in x axis for numpy.memmap."""
# Create container for input
x = np.memmap(mpfnames[0], dtype=dtype, mode="w+", shape=(N,))
# Populate x in range [-1, 1]
for i in range(0, N, step):
chunk = np.linspace((2 * i - N) / N,
(2 * (i + step) - N) / N, step)
x[i:i + step] = chunk
del x # close x memmap
def populate_x_tables(clib, clevel):
"""Populate the values in x axis for pytables."""
f = tb.open_file(h5fname, "w")
# Create container for input
atom = tb.Atom.from_dtype(dtype)
filters = tb.Filters(complib=clib, complevel=clevel)
x = f.create_carray(f.root, "x", atom=atom, shape=(N,),
filters=filters,
chunkshape=CHUNKSHAPE,
)
# Populate x in range [-1, 1]
for i in range(0, N, step):
chunk = np.linspace((2 * i - N) / N,
(2 * (i + step) - N) / N, step)
x[i:i + step] = chunk
f.close()
def compute_numpy():
"""Compute the polynomial with pure numpy."""
y = eval(expr)
def compute_numexpr():
"""Compute the polynomial with pure numexpr."""
y = ne.evaluate(expr)
def compute_memmap():
"""Compute the polynomial with numpy.memmap."""
# Reopen inputs in read-only mode
x = np.memmap(mpfnames[0], dtype=dtype, mode='r', shape=(N,))
# Create the array output
r = np.memmap(mpfnames[1], dtype=dtype, mode="w+", shape=(N,))
# Do the computation by chunks and store in output
r[:] = eval(expr) # where is stored the result?
# r = eval(expr) # result is stored in-memory
del x, r # close x and r memmap arrays
print_filesize(mpfnames)
def compute_tables(clib, clevel):
"""Compute the polynomial with tables.Expr."""
f = tb.open_file(h5fname, "a")
x = f.root.x # get the x input
# Create container for output
atom = tb.Atom.from_dtype(dtype)
filters = tb.Filters(complib=clib, complevel=clevel)
r = f.create_carray(f.root, "r", atom=atom, shape=(N,),
filters=filters,
chunkshape=CHUNKSHAPE,
)
# Do the actual computation and store in output
ex = tb.Expr(expr) # parse the expression
ex.set_output(r) # where is stored the result?
# when commented out, the result goes in-memory
ex.eval() # evaluate!
f.close()
print_filesize(h5fname, clib, clevel)
if __name__ == '__main__':
tb.print_versions()
print(f"Total size for datasets: {2 * N * dtype.itemsize / MB:.1f} MB")
# Get the compression libraries supported
# supported_clibs = [clib for clib in ("zlib", "lzo", "bzip2", "blosc")
# supported_clibs = [clib for clib in ("zlib", "lzo", "blosc")
supported_clibs = [clib for clib in ("blosc",)
if tb.which_lib_version(clib)]
# Initialization code
# for what in ["numpy", "numpy.memmap", "numexpr"]:
for what in ["numpy", "numexpr"]:
# break
print("Populating x using %s with %d points..." % (what, N))
t0 = clock()
if what == "numpy":
populate_x_numpy()
compute = compute_numpy
elif what == "numexpr":
populate_x_numpy()
compute = compute_numexpr
elif what == "numpy.memmap":
populate_x_memmap()
compute = compute_memmap
print(f"*** Time elapsed populating: {clock() - t0:.3f}")
print(f"Computing: {expr!r} using {what}")
t0 = clock()
compute()
print(f"**************** Time elapsed computing: {clock() - t0:.3f}")
for what in ["tables.Expr"]:
t0 = clock()
first = True # Sentinel
for clib in supported_clibs:
# for clevel in (0, 1, 3, 6, 9):
for clevel in range(10):
# for clevel in (1,):
if not first and clevel == 0:
continue
print("Populating x using %s with %d points..." % (what, N))
populate_x_tables(clib, clevel)
print(f"*** Time elapsed populating: {clock() - t0:.3f}")
print(f"Computing: {expr!r} using {what}")
t0 = clock()
compute_tables(clib, clevel)
print(
f"**************** Time elapsed computing: "
f"{clock() - t0:.3f}")
first = False
| 2,968 |
13,885 | <gh_stars>1000+
#include <stdlib.h>
#include <stdio.h>
#if defined(_WIN32) && _MSC_VER > 1200
#define STBIR_ASSERT(x) \
if (!(x)) { \
__debugbreak(); \
} else
#else
#include <assert.h>
#define STBIR_ASSERT(x) assert(x)
#endif
#define STBIR_MALLOC stbir_malloc
#define STBIR_FREE stbir_free
class stbir_context {
public:
stbir_context()
{
size = 1000000;
memory = malloc(size);
}
~stbir_context()
{
free(memory);
}
size_t size;
void* memory;
} g_context;
void* stbir_malloc(size_t size, void* context)
{
if (!context)
return malloc(size);
stbir_context* real_context = (stbir_context*)context;
if (size > real_context->size)
return 0;
return real_context->memory;
}
void stbir_free(void* memory, void* context)
{
if (!context)
free(memory);
}
//#include <stdio.h>
void stbir_progress(float p)
{
//printf("%f\n", p);
STBIR_ASSERT(p >= 0 && p <= 1);
}
#define STBIR_PROGRESS_REPORT stbir_progress
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_STATIC
#include "stb_image_resize.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#ifdef _WIN32
#include <sys/timeb.h>
#include <direct.h>
#define mkdir(a, b) _mkdir(a)
#else
#include <sys/stat.h>
#endif
#define MT_SIZE 624
static size_t g_aiMT[MT_SIZE];
static size_t g_iMTI = 0;
// Mersenne Twister implementation from Wikipedia.
// Avoiding use of the system rand() to be sure that our tests generate the same test data on any system.
void mtsrand(size_t iSeed)
{
g_aiMT[0] = iSeed;
for (size_t i = 1; i < MT_SIZE; i++)
{
size_t inner1 = g_aiMT[i - 1];
size_t inner2 = (g_aiMT[i - 1] >> 30);
size_t inner = inner1 ^ inner2;
g_aiMT[i] = (0x6c078965 * inner) + i;
}
g_iMTI = 0;
}
size_t mtrand()
{
if (g_iMTI == 0)
{
for (size_t i = 0; i < MT_SIZE; i++)
{
size_t y = (0x80000000 & (g_aiMT[i])) + (0x7fffffff & (g_aiMT[(i + 1) % MT_SIZE]));
g_aiMT[i] = g_aiMT[(i + 397) % MT_SIZE] ^ (y >> 1);
if ((y % 2) == 1)
g_aiMT[i] = g_aiMT[i] ^ 0x9908b0df;
}
}
size_t y = g_aiMT[g_iMTI];
y = y ^ (y >> 11);
y = y ^ ((y << 7) & (0x9d2c5680));
y = y ^ ((y << 15) & (0xefc60000));
y = y ^ (y >> 18);
g_iMTI = (g_iMTI + 1) % MT_SIZE;
return y;
}
inline float mtfrand()
{
const int ninenine = 999999;
return (float)(mtrand() % ninenine)/ninenine;
}
static void resizer(int argc, char **argv)
{
unsigned char* input_pixels;
unsigned char* output_pixels;
int w, h;
int n;
int out_w, out_h;
input_pixels = stbi_load(argv[1], &w, &h, &n, 0);
out_w = w*3;
out_h = h*3;
output_pixels = (unsigned char*) malloc(out_w*out_h*n);
//stbir_resize_uint8_srgb(input_pixels, w, h, 0, output_pixels, out_w, out_h, 0, n, -1,0);
stbir_resize_uint8(input_pixels, w, h, 0, output_pixels, out_w, out_h, 0, n);
stbi_write_png("output.png", out_w, out_h, n, output_pixels, 0);
exit(0);
}
static void performance(int argc, char **argv)
{
unsigned char* input_pixels;
unsigned char* output_pixels;
int w, h, count;
int n, i;
int out_w, out_h, srgb=1;
input_pixels = stbi_load(argv[1], &w, &h, &n, 0);
#if 0
out_w = w/4; out_h = h/4; count=100; // 1
#elif 0
out_w = w*2; out_h = h/4; count=20; // 2 // note this is structured pessimily, would be much faster to downsample vertically first
#elif 0
out_w = w/4; out_h = h*2; count=50; // 3
#elif 0
out_w = w*3; out_h = h*3; count=2; srgb=0; // 4
#else
out_w = w*3; out_h = h*3; count=2; // 5 // this is dominated by linear->sRGB conversion
#endif
output_pixels = (unsigned char*) malloc(out_w*out_h*n);
for (i=0; i < count; ++i)
if (srgb)
stbir_resize_uint8_srgb(input_pixels, w, h, 0, output_pixels, out_w, out_h, 0, n,-1,0);
else
stbir_resize(input_pixels, w, h, 0, output_pixels, out_w, out_h, 0, STBIR_TYPE_UINT8, n,-1, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, STBIR_COLORSPACE_LINEAR, NULL);
exit(0);
}
void test_suite(int argc, char **argv);
int main(int argc, char** argv)
{
//resizer(argc, argv);
//performance(argc, argv);
test_suite(argc, argv);
return 0;
}
void resize_image(const char* filename, float width_percent, float height_percent, stbir_filter filter, stbir_edge edge, stbir_colorspace colorspace, const char* output_filename)
{
int w, h, n;
unsigned char* input_data = stbi_load(filename, &w, &h, &n, 0);
if (!input_data)
{
printf("Input image could not be loaded\n");
return;
}
int out_w = (int)(w * width_percent);
int out_h = (int)(h * height_percent);
unsigned char* output_data = (unsigned char*)malloc(out_w * out_h * n);
stbir_resize(input_data, w, h, 0, output_data, out_w, out_h, 0, STBIR_TYPE_UINT8, n, STBIR_ALPHA_CHANNEL_NONE, 0, edge, edge, filter, filter, colorspace, &g_context);
stbi_image_free(input_data);
stbi_write_png(output_filename, out_w, out_h, n, output_data, 0);
free(output_data);
}
template <typename F, typename T>
void convert_image(const F* input, T* output, int length)
{
double f = (pow(2.0, 8.0 * sizeof(T)) - 1) / (pow(2.0, 8.0 * sizeof(F)) - 1);
for (int i = 0; i < length; i++)
output[i] = (T)(((double)input[i]) * f);
}
template <typename T>
void test_format(const char* file, float width_percent, float height_percent, stbir_datatype type, stbir_colorspace colorspace)
{
int w, h, n;
unsigned char* input_data = stbi_load(file, &w, &h, &n, 0);
if (input_data == NULL)
return;
int new_w = (int)(w * width_percent);
int new_h = (int)(h * height_percent);
T* T_data = (T*)malloc(w * h * n * sizeof(T));
memset(T_data, 0, w*h*n*sizeof(T));
convert_image<unsigned char, T>(input_data, T_data, w * h * n);
T* output_data = (T*)malloc(new_w * new_h * n * sizeof(T));
stbir_resize(T_data, w, h, 0, output_data, new_w, new_h, 0, type, n, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, colorspace, &g_context);
free(T_data);
stbi_image_free(input_data);
unsigned char* char_data = (unsigned char*)malloc(new_w * new_h * n * sizeof(char));
convert_image<T, unsigned char>(output_data, char_data, new_w * new_h * n);
char output[200];
sprintf(output, "test-output/type-%d-%d-%d-%d-%s", type, colorspace, new_w, new_h, file);
stbi_write_png(output, new_w, new_h, n, char_data, 0);
free(char_data);
free(output_data);
}
void convert_image_float(const unsigned char* input, float* output, int length)
{
for (int i = 0; i < length; i++)
output[i] = ((float)input[i])/255;
}
void convert_image_float(const float* input, unsigned char* output, int length)
{
for (int i = 0; i < length; i++)
output[i] = (unsigned char)(stbir__saturate(input[i]) * 255);
}
void test_float(const char* file, float width_percent, float height_percent, stbir_datatype type, stbir_colorspace colorspace)
{
int w, h, n;
unsigned char* input_data = stbi_load(file, &w, &h, &n, 0);
if (input_data == NULL)
return;
int new_w = (int)(w * width_percent);
int new_h = (int)(h * height_percent);
float* T_data = (float*)malloc(w * h * n * sizeof(float));
convert_image_float(input_data, T_data, w * h * n);
float* output_data = (float*)malloc(new_w * new_h * n * sizeof(float));
stbir_resize_float_generic(T_data, w, h, 0, output_data, new_w, new_h, 0, n, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, colorspace, &g_context);
free(T_data);
stbi_image_free(input_data);
unsigned char* char_data = (unsigned char*)malloc(new_w * new_h * n * sizeof(char));
convert_image_float(output_data, char_data, new_w * new_h * n);
char output[200];
sprintf(output, "test-output/type-%d-%d-%d-%d-%s", type, colorspace, new_w, new_h, file);
stbi_write_png(output, new_w, new_h, n, char_data, 0);
free(char_data);
free(output_data);
}
void test_channels(const char* file, float width_percent, float height_percent, int channels)
{
int w, h, n;
unsigned char* input_data = stbi_load(file, &w, &h, &n, 0);
if (input_data == NULL)
return;
int new_w = (int)(w * width_percent);
int new_h = (int)(h * height_percent);
unsigned char* channels_data = (unsigned char*)malloc(w * h * channels * sizeof(unsigned char));
for (int i = 0; i < w * h; i++)
{
int input_position = i * n;
int output_position = i * channels;
for (int c = 0; c < channels; c++)
channels_data[output_position + c] = input_data[input_position + stbir__min(c, n)];
}
unsigned char* output_data = (unsigned char*)malloc(new_w * new_h * channels * sizeof(unsigned char));
stbir_resize_uint8_srgb(channels_data, w, h, 0, output_data, new_w, new_h, 0, channels, STBIR_ALPHA_CHANNEL_NONE, 0);
free(channels_data);
stbi_image_free(input_data);
char output[200];
sprintf(output, "test-output/channels-%d-%d-%d-%s", channels, new_w, new_h, file);
stbi_write_png(output, new_w, new_h, channels, output_data, 0);
free(output_data);
}
void test_subpixel(const char* file, float width_percent, float height_percent, float s1, float t1)
{
int w, h, n;
unsigned char* input_data = stbi_load(file, &w, &h, &n, 0);
if (input_data == NULL)
return;
s1 = ((float)w - 1 + s1)/w;
t1 = ((float)h - 1 + t1)/h;
int new_w = (int)(w * width_percent);
int new_h = (int)(h * height_percent);
unsigned char* output_data = (unsigned char*)malloc(new_w * new_h * n * sizeof(unsigned char));
stbir_resize_region(input_data, w, h, 0, output_data, new_w, new_h, 0, STBIR_TYPE_UINT8, n, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 0, 0, s1, t1);
stbi_image_free(input_data);
char output[200];
sprintf(output, "test-output/subpixel-%d-%d-%f-%f-%s", new_w, new_h, s1, t1, file);
stbi_write_png(output, new_w, new_h, n, output_data, 0);
free(output_data);
}
void test_subpixel_region(const char* file, float width_percent, float height_percent, float s0, float t0, float s1, float t1)
{
int w, h, n;
unsigned char* input_data = stbi_load(file, &w, &h, &n, 0);
if (input_data == NULL)
return;
int new_w = (int)(w * width_percent);
int new_h = (int)(h * height_percent);
unsigned char* output_data = (unsigned char*)malloc(new_w * new_h * n * sizeof(unsigned char));
stbir_resize_region(input_data, w, h, 0, output_data, new_w, new_h, 0, STBIR_TYPE_UINT8, n, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, s0, t0, s1, t1);
stbi_image_free(input_data);
char output[200];
sprintf(output, "test-output/subpixel-region-%d-%d-%f-%f-%f-%f-%s", new_w, new_h, s0, t0, s1, t1, file);
stbi_write_png(output, new_w, new_h, n, output_data, 0);
free(output_data);
}
void test_subpixel_command(const char* file, float width_percent, float height_percent, float x_scale, float y_scale, float x_offset, float y_offset)
{
int w, h, n;
unsigned char* input_data = stbi_load(file, &w, &h, &n, 0);
if (input_data == NULL)
return;
int new_w = (int)(w * width_percent);
int new_h = (int)(h * height_percent);
unsigned char* output_data = (unsigned char*)malloc(new_w * new_h * n * sizeof(unsigned char));
stbir_resize_subpixel(input_data, w, h, 0, output_data, new_w, new_h, 0, STBIR_TYPE_UINT8, n, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, x_scale, y_scale, x_offset, y_offset);
stbi_image_free(input_data);
char output[200];
sprintf(output, "test-output/subpixel-command-%d-%d-%f-%f-%f-%f-%s", new_w, new_h, x_scale, y_scale, x_offset, y_offset, file);
stbi_write_png(output, new_w, new_h, n, output_data, 0);
free(output_data);
}
unsigned int* pixel(unsigned int* buffer, int x, int y, int c, int w, int n)
{
return &buffer[y*w*n + x*n + c];
}
void test_premul()
{
unsigned int input[2 * 2 * 4];
unsigned int output[1 * 1 * 4];
unsigned int output2[2 * 2 * 4];
memset(input, 0, sizeof(input));
// First a test to make sure premul is working properly.
// Top left - solid red
*pixel(input, 0, 0, 0, 2, 4) = 255;
*pixel(input, 0, 0, 3, 2, 4) = 255;
// Bottom left - solid red
*pixel(input, 0, 1, 0, 2, 4) = 255;
*pixel(input, 0, 1, 3, 2, 4) = 255;
// Top right - transparent green
*pixel(input, 1, 0, 1, 2, 4) = 255;
*pixel(input, 1, 0, 3, 2, 4) = 25;
// Bottom right - transparent green
*pixel(input, 1, 1, 1, 2, 4) = 255;
*pixel(input, 1, 1, 3, 2, 4) = 25;
stbir_resize(input, 2, 2, 0, output, 1, 1, 0, STBIR_TYPE_UINT32, 4, 3, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, &g_context);
float r = (float)255 / 4294967296;
float g = (float)255 / 4294967296;
float ra = (float)255 / 4294967296;
float ga = (float)25 / 4294967296;
float a = (ra + ga) / 2;
STBIR_ASSERT(output[0] == (unsigned int)(r * ra / 2 / a * 4294967296 + 0.5f)); // 232
STBIR_ASSERT(output[1] == (unsigned int)(g * ga / 2 / a * 4294967296 + 0.5f)); // 23
STBIR_ASSERT(output[2] == 0);
STBIR_ASSERT(output[3] == (unsigned int)(a * 4294967296 + 0.5f)); // 140
// Now a test to make sure it doesn't clobber existing values.
// Top right - completely transparent green
*pixel(input, 1, 0, 1, 2, 4) = 255;
*pixel(input, 1, 0, 3, 2, 4) = 0;
// Bottom right - completely transparent green
*pixel(input, 1, 1, 1, 2, 4) = 255;
*pixel(input, 1, 1, 3, 2, 4) = 0;
stbir_resize(input, 2, 2, 0, output2, 2, 2, 0, STBIR_TYPE_UINT32, 4, 3, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, &g_context);
STBIR_ASSERT(*pixel(output2, 0, 0, 0, 2, 4) == 255);
STBIR_ASSERT(*pixel(output2, 0, 0, 1, 2, 4) == 0);
STBIR_ASSERT(*pixel(output2, 0, 0, 2, 2, 4) == 0);
STBIR_ASSERT(*pixel(output2, 0, 0, 3, 2, 4) == 255);
STBIR_ASSERT(*pixel(output2, 0, 1, 0, 2, 4) == 255);
STBIR_ASSERT(*pixel(output2, 0, 1, 1, 2, 4) == 0);
STBIR_ASSERT(*pixel(output2, 0, 1, 2, 2, 4) == 0);
STBIR_ASSERT(*pixel(output2, 0, 1, 3, 2, 4) == 255);
STBIR_ASSERT(*pixel(output2, 1, 0, 0, 2, 4) == 0);
STBIR_ASSERT(*pixel(output2, 1, 0, 1, 2, 4) == 255);
STBIR_ASSERT(*pixel(output2, 1, 0, 2, 2, 4) == 0);
STBIR_ASSERT(*pixel(output2, 1, 0, 3, 2, 4) == 0);
STBIR_ASSERT(*pixel(output2, 1, 1, 0, 2, 4) == 0);
STBIR_ASSERT(*pixel(output2, 1, 1, 1, 2, 4) == 255);
STBIR_ASSERT(*pixel(output2, 1, 1, 2, 2, 4) == 0);
STBIR_ASSERT(*pixel(output2, 1, 1, 3, 2, 4) == 0);
}
// test that splitting a pow-2 image into tiles produces identical results
void test_subpixel_1()
{
unsigned char image[8 * 8];
mtsrand(0);
for (int i = 0; i < sizeof(image); i++)
image[i] = mtrand() & 255;
unsigned char output_data[16 * 16];
stbir_resize_region(image, 8, 8, 0, output_data, 16, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 0, 0, 1, 1);
unsigned char output_left[8 * 16];
unsigned char output_right[8 * 16];
stbir_resize_region(image, 8, 8, 0, output_left, 8, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 0, 0, 0.5f, 1);
stbir_resize_region(image, 8, 8, 0, output_right, 8, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 0.5f, 0, 1, 1);
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 16; y++)
{
STBIR_ASSERT(output_data[y * 16 + x] == output_left[y * 8 + x]);
STBIR_ASSERT(output_data[y * 16 + x + 8] == output_right[y * 8 + x]);
}
}
stbir_resize_subpixel(image, 8, 8, 0, output_left, 8, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 2, 2, 0, 0);
stbir_resize_subpixel(image, 8, 8, 0, output_right, 8, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 2, 2, 8, 0);
{for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 16; y++)
{
STBIR_ASSERT(output_data[y * 16 + x] == output_left[y * 8 + x]);
STBIR_ASSERT(output_data[y * 16 + x + 8] == output_right[y * 8 + x]);
}
}}
}
// test that replicating an image and using a subtile of it produces same results as wraparound
void test_subpixel_2()
{
unsigned char image[8 * 8];
mtsrand(0);
for (int i = 0; i < sizeof(image); i++)
image[i] = mtrand() & 255;
unsigned char large_image[32 * 32];
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
large_image[j*4*8*8 + i*8 + y*4*8 + x] = image[y*8 + x];
}
}
}
unsigned char output_data_1[16 * 16];
unsigned char output_data_2[16 * 16];
stbir_resize(image, 8, 8, 0, output_data_1, 16, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_WRAP, STBIR_EDGE_WRAP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context);
stbir_resize_region(large_image, 32, 32, 0, output_data_2, 16, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_WRAP, STBIR_EDGE_WRAP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 0.25f, 0.25f, 0.5f, 0.5f);
{for (int x = 0; x < 16; x++)
{
for (int y = 0; y < 16; y++)
STBIR_ASSERT(output_data_1[y * 16 + x] == output_data_2[y * 16 + x]);
}}
stbir_resize_subpixel(large_image, 32, 32, 0, output_data_2, 16, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_WRAP, STBIR_EDGE_WRAP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 2, 2, 16, 16);
{for (int x = 0; x < 16; x++)
{
for (int y = 0; y < 16; y++)
STBIR_ASSERT(output_data_1[y * 16 + x] == output_data_2[y * 16 + x]);
}}
}
// test that 0,0,1,1 subpixel produces same result as no-rect
void test_subpixel_3()
{
unsigned char image[8 * 8];
mtsrand(0);
for (int i = 0; i < sizeof(image); i++)
image[i] = mtrand() & 255;
unsigned char output_data_1[32 * 32];
unsigned char output_data_2[32 * 32];
stbir_resize_region(image, 8, 8, 0, output_data_1, 32, 32, 0, STBIR_TYPE_UINT8, 1, 0, STBIR_ALPHA_CHANNEL_NONE, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_LINEAR, NULL, 0, 0, 1, 1);
stbir_resize_uint8(image, 8, 8, 0, output_data_2, 32, 32, 0, 1);
for (int x = 0; x < 32; x++)
{
for (int y = 0; y < 32; y++)
STBIR_ASSERT(output_data_1[y * 32 + x] == output_data_2[y * 32 + x]);
}
stbir_resize_subpixel(image, 8, 8, 0, output_data_1, 32, 32, 0, STBIR_TYPE_UINT8, 1, 0, STBIR_ALPHA_CHANNEL_NONE, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_LINEAR, NULL, 4, 4, 0, 0);
{for (int x = 0; x < 32; x++)
{
for (int y = 0; y < 32; y++)
STBIR_ASSERT(output_data_1[y * 32 + x] == output_data_2[y * 32 + x]);
}}
}
// test that 1:1 resample using s,t=0,0,1,1 with bilinear produces original image
void test_subpixel_4()
{
unsigned char image[8 * 8];
mtsrand(0);
for (int i = 0; i < sizeof(image); i++)
image[i] = mtrand() & 255;
unsigned char output[8 * 8];
stbir_resize_region(image, 8, 8, 0, output, 8, 8, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_TRIANGLE, STBIR_FILTER_TRIANGLE, STBIR_COLORSPACE_LINEAR, &g_context, 0, 0, 1, 1);
STBIR_ASSERT(memcmp(image, output, 8 * 8) == 0);
stbir_resize_subpixel(image, 8, 8, 0, output, 8, 8, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_TRIANGLE, STBIR_FILTER_TRIANGLE, STBIR_COLORSPACE_LINEAR, &g_context, 1, 1, 0, 0);
STBIR_ASSERT(memcmp(image, output, 8 * 8) == 0);
}
static unsigned int image88_int[8][8];
static unsigned char image88 [8][8];
static unsigned char output88[8][8];
static unsigned char output44[4][4];
static unsigned char output22[2][2];
static unsigned char output11[1][1];
void resample_88(stbir_filter filter)
{
stbir_resize_uint8_generic(image88[0],8,8,0, output88[0],8,8,0, 1,-1,0, STBIR_EDGE_CLAMP, filter, STBIR_COLORSPACE_LINEAR, NULL);
stbir_resize_uint8_generic(image88[0],8,8,0, output44[0],4,4,0, 1,-1,0, STBIR_EDGE_CLAMP, filter, STBIR_COLORSPACE_LINEAR, NULL);
stbir_resize_uint8_generic(image88[0],8,8,0, output22[0],2,2,0, 1,-1,0, STBIR_EDGE_CLAMP, filter, STBIR_COLORSPACE_LINEAR, NULL);
stbir_resize_uint8_generic(image88[0],8,8,0, output11[0],1,1,0, 1,-1,0, STBIR_EDGE_CLAMP, filter, STBIR_COLORSPACE_LINEAR, NULL);
}
void verify_box(void)
{
int i,j,t;
resample_88(STBIR_FILTER_BOX);
for (i=0; i < sizeof(image88); ++i)
STBIR_ASSERT(image88[0][i] == output88[0][i]);
t = 0;
for (j=0; j < 4; ++j)
for (i=0; i < 4; ++i) {
int n = image88[j*2+0][i*2+0]
+ image88[j*2+0][i*2+1]
+ image88[j*2+1][i*2+0]
+ image88[j*2+1][i*2+1];
STBIR_ASSERT(output44[j][i] == ((n+2)>>2) || output44[j][i] == ((n+1)>>2)); // can't guarantee exact rounding due to numerical precision
t += n;
}
STBIR_ASSERT(output11[0][0] == ((t+32)>>6) || output11[0][0] == ((t+31)>>6)); // can't guarantee exact rounding due to numerical precision
}
void verify_filter_normalized(stbir_filter filter, int output_size, unsigned int value)
{
int i, j;
unsigned int output[64];
stbir_resize(image88_int[0], 8, 8, 0, output, output_size, output_size, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, filter, filter, STBIR_COLORSPACE_LINEAR, NULL);
for (j = 0; j < output_size; ++j)
for (i = 0; i < output_size; ++i)
STBIR_ASSERT(value == output[j*output_size + i]);
}
float round2(float f)
{
return (float) floor(f+0.5f); // round() isn't C standard pre-C99
}
void test_filters(void)
{
int i,j;
mtsrand(0);
for (i=0; i < sizeof(image88); ++i)
image88[0][i] = mtrand() & 255;
verify_box();
for (i=0; i < sizeof(image88); ++i)
image88[0][i] = 0;
image88[4][4] = 255;
verify_box();
for (j=0; j < 8; ++j)
for (i=0; i < 8; ++i)
image88[j][i] = (j^i)&1 ? 255 : 0;
verify_box();
for (j=0; j < 8; ++j)
for (i=0; i < 8; ++i)
image88[j][i] = i&2 ? 255 : 0;
verify_box();
int value = 64;
for (j = 0; j < 8; ++j)
for (i = 0; i < 8; ++i)
image88_int[j][i] = value;
verify_filter_normalized(STBIR_FILTER_BOX, 8, value);
verify_filter_normalized(STBIR_FILTER_TRIANGLE, 8, value);
verify_filter_normalized(STBIR_FILTER_CUBICBSPLINE, 8, value);
verify_filter_normalized(STBIR_FILTER_CATMULLROM, 8, value);
verify_filter_normalized(STBIR_FILTER_MITCHELL, 8, value);
verify_filter_normalized(STBIR_FILTER_BOX, 4, value);
verify_filter_normalized(STBIR_FILTER_TRIANGLE, 4, value);
verify_filter_normalized(STBIR_FILTER_CUBICBSPLINE, 4, value);
verify_filter_normalized(STBIR_FILTER_CATMULLROM, 4, value);
verify_filter_normalized(STBIR_FILTER_MITCHELL, 4, value);
verify_filter_normalized(STBIR_FILTER_BOX, 2, value);
verify_filter_normalized(STBIR_FILTER_TRIANGLE, 2, value);
verify_filter_normalized(STBIR_FILTER_CUBICBSPLINE, 2, value);
verify_filter_normalized(STBIR_FILTER_CATMULLROM, 2, value);
verify_filter_normalized(STBIR_FILTER_MITCHELL, 2, value);
verify_filter_normalized(STBIR_FILTER_BOX, 1, value);
verify_filter_normalized(STBIR_FILTER_TRIANGLE, 1, value);
verify_filter_normalized(STBIR_FILTER_CUBICBSPLINE, 1, value);
verify_filter_normalized(STBIR_FILTER_CATMULLROM, 1, value);
verify_filter_normalized(STBIR_FILTER_MITCHELL, 1, value);
{
// This test is designed to produce coefficients that are very badly denormalized.
unsigned int v = 556;
unsigned int input[100 * 100];
unsigned int output[11 * 11];
for (j = 0; j < 100 * 100; ++j)
input[j] = v;
stbir_resize(input, 100, 100, 0, output, 11, 11, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_TRIANGLE, STBIR_FILTER_TRIANGLE, STBIR_COLORSPACE_LINEAR, NULL);
for (j = 0; j < 11 * 11; ++j)
STBIR_ASSERT(v == output[j]);
}
{
// Now test the trapezoid filter for downsampling.
unsigned int input[3 * 1];
unsigned int output[2 * 1];
input[0] = 0;
input[1] = 255;
input[2] = 127;
stbir_resize(input, 3, 1, 0, output, 2, 1, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);
STBIR_ASSERT(output[0] == (unsigned int)round2((float)(input[0] * 2 + input[1]) / 3));
STBIR_ASSERT(output[1] == (unsigned int)round2((float)(input[2] * 2 + input[1]) / 3));
stbir_resize(input, 1, 3, 0, output, 1, 2, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);
STBIR_ASSERT(output[0] == (unsigned int)round2((float)(input[0] * 2 + input[1]) / 3));
STBIR_ASSERT(output[1] == (unsigned int)round2((float)(input[2] * 2 + input[1]) / 3));
}
{
// Now test the trapezoid filter for upsampling.
unsigned int input[2 * 1];
unsigned int output[3 * 1];
input[0] = 0;
input[1] = 255;
stbir_resize(input, 2, 1, 0, output, 3, 1, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);
STBIR_ASSERT(output[0] == input[0]);
STBIR_ASSERT(output[1] == (input[0] + input[1]) / 2);
STBIR_ASSERT(output[2] == input[1]);
stbir_resize(input, 1, 2, 0, output, 1, 3, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);
STBIR_ASSERT(output[0] == input[0]);
STBIR_ASSERT(output[1] == (input[0] + input[1]) / 2);
STBIR_ASSERT(output[2] == input[1]);
}
// checkerboard
{
unsigned char input[64][64];
unsigned char output[16][16];
int i,j;
for (j=0; j < 64; ++j)
for (i=0; i < 64; ++i)
input[j][i] = (i^j)&1 ? 255 : 0;
stbir_resize_uint8_generic(input[0], 64, 64, 0, output[0],16,16,0, 1,-1,0,STBIR_EDGE_WRAP,STBIR_FILTER_DEFAULT,STBIR_COLORSPACE_LINEAR,0);
for (j=0; j < 16; ++j)
for (i=0; i < 16; ++i)
STBIR_ASSERT(output[j][i] == 128);
stbir_resize_uint8_srgb_edgemode(input[0], 64, 64, 0, output[0],16,16,0, 1,-1,0,STBIR_EDGE_WRAP);
for (j=0; j < 16; ++j)
for (i=0; i < 16; ++i)
STBIR_ASSERT(output[j][i] == 188);
}
{
// Test trapezoid box filter
unsigned char input[2 * 1];
unsigned char output[127 * 1];
input[0] = 0;
input[1] = 255;
stbir_resize(input, 2, 1, 0, output, 127, 1, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);
STBIR_ASSERT(output[0] == 0);
STBIR_ASSERT(output[127 / 2 - 1] == 0);
STBIR_ASSERT(output[127 / 2] == 128);
STBIR_ASSERT(output[127 / 2 + 1] == 255);
STBIR_ASSERT(output[126] == 255);
stbi_write_png("test-output/trapezoid-upsample-horizontal.png", 127, 1, 1, output, 0);
stbir_resize(input, 1, 2, 0, output, 1, 127, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);
STBIR_ASSERT(output[0] == 0);
STBIR_ASSERT(output[127 / 2 - 1] == 0);
STBIR_ASSERT(output[127 / 2] == 128);
STBIR_ASSERT(output[127 / 2 + 1] == 255);
STBIR_ASSERT(output[126] == 255);
stbi_write_png("test-output/trapezoid-upsample-vertical.png", 1, 127, 1, output, 0);
}
}
#define UMAX32 4294967295U
static void write32(const char *filename, stbir_uint32 *output, int w, int h)
{
stbir_uint8 *data = (stbir_uint8*) malloc(w*h*3);
for (int i=0; i < w*h*3; ++i)
data[i] = output[i]>>24;
stbi_write_png(filename, w, h, 3, data, 0);
free(data);
}
static void test_32(void)
{
int w=100,h=120,x,y, out_w,out_h;
stbir_uint32 *input = (stbir_uint32*) malloc(4 * 3 * w * h);
stbir_uint32 *output = (stbir_uint32*) malloc(4 * 3 * 3*w * 3*h);
for (y=0; y < h; ++y) {
for (x=0; x < w; ++x) {
input[y*3*w + x*3 + 0] = x * ( UMAX32/w );
input[y*3*w + x*3 + 1] = y * ( UMAX32/h );
input[y*3*w + x*3 + 2] = UMAX32/2;
}
}
out_w = w*33/16;
out_h = h*33/16;
stbir_resize(input,w,h,0,output,out_w,out_h,0,STBIR_TYPE_UINT32,3,-1,0,STBIR_EDGE_CLAMP,STBIR_EDGE_CLAMP,STBIR_FILTER_DEFAULT,STBIR_FILTER_DEFAULT,STBIR_COLORSPACE_LINEAR,NULL);
write32("test-output/seantest_1.png", output,out_w,out_h);
out_w = w*16/33;
out_h = h*16/33;
stbir_resize(input,w,h,0,output,out_w,out_h,0,STBIR_TYPE_UINT32,3,-1,0,STBIR_EDGE_CLAMP,STBIR_EDGE_CLAMP,STBIR_FILTER_DEFAULT,STBIR_FILTER_DEFAULT,STBIR_COLORSPACE_LINEAR,NULL);
write32("test-output/seantest_2.png", output,out_w,out_h);
}
void test_suite(int argc, char **argv)
{
int i;
const char *barbara;
mkdir("test-output", 777);
if (argc > 1)
barbara = argv[1];
else
barbara = "barbara.png";
// check what cases we need normalization for
#if 1
{
float x, y;
for (x = -1; x < 1; x += 0.05f) {
float sums[5] = { 0 };
float o;
for (o = -5; o <= 5; ++o) {
sums[0] += stbir__filter_mitchell(x + o, 1);
sums[1] += stbir__filter_catmullrom(x + o, 1);
sums[2] += stbir__filter_cubic(x + o, 1);
sums[3] += stbir__filter_triangle(x + o, 1);
sums[4] += stbir__filter_trapezoid(x + o, 0.5f);
}
for (i = 0; i < 5; ++i)
STBIR_ASSERT(sums[i] >= 1.0 - 0.001 && sums[i] <= 1.0 + 0.001);
}
#if 1
for (y = 0.11f; y < 1; y += 0.01f) { // Step
for (x = -1; x < 1; x += 0.05f) { // Phase
float sums[5] = { 0 };
float o;
for (o = -5; o <= 5; o += y) {
sums[0] += y * stbir__filter_mitchell(x + o, 1);
sums[1] += y * stbir__filter_catmullrom(x + o, 1);
sums[2] += y * stbir__filter_cubic(x + o, 1);
sums[4] += y * stbir__filter_trapezoid(x + o, 0.5f);
sums[3] += y * stbir__filter_triangle(x + o, 1);
}
for (i = 0; i < 3; ++i)
STBIR_ASSERT(sums[i] >= 1.0 - 0.0170 && sums[i] <= 1.0 + 0.0170);
}
}
#endif
}
#endif
#if 0 // linear_to_srgb_uchar table
for (i=0; i < 256; ++i) {
float f = stbir__srgb_to_linear((i-0.5f)/255.0f);
printf("%9d, ", (int) ((f) * (1<<28)));
if ((i & 7) == 7)
printf("\n");
}
#endif
// old tests that hacky fix worked on - test that
// every uint8 maps to itself
for (i = 0; i < 256; i++) {
float f = stbir__srgb_to_linear(float(i) / 255);
int n = stbir__linear_to_srgb_uchar(f);
STBIR_ASSERT(n == i);
}
// new tests that hacky fix failed for - test that
// values adjacent to uint8 round to nearest uint8
for (i = 0; i < 256; i++) {
for (float y = -0.42f; y <= 0.42f; y += 0.01f) {
float f = stbir__srgb_to_linear((i+y) / 255.0f);
int n = stbir__linear_to_srgb_uchar(f);
STBIR_ASSERT(n == i);
}
}
test_filters();
test_subpixel_1();
test_subpixel_2();
test_subpixel_3();
test_subpixel_4();
test_premul();
test_32();
// Some tests to make sure errors don't pop up with strange filter/dimension combinations.
stbir_resize(image88, 8, 8, 0, output88, 4, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context);
stbir_resize(image88, 8, 8, 0, output88, 4, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_BOX, STBIR_COLORSPACE_SRGB, &g_context);
stbir_resize(image88, 8, 8, 0, output88, 16, 4, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context);
stbir_resize(image88, 8, 8, 0, output88, 16, 4, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_BOX, STBIR_COLORSPACE_SRGB, &g_context);
int barbara_width, barbara_height, barbara_channels;
stbi_image_free(stbi_load(barbara, &barbara_width, &barbara_height, &barbara_channels, 0));
int res = 10;
// Downscaling
{for (int i = 0; i <= res; i++)
{
float t = (float)i/res;
float scale = 0.5;
float out_scale = 2.0f/3;
float x_shift = (barbara_width*out_scale - barbara_width*scale) * t;
float y_shift = (barbara_height*out_scale - barbara_height*scale) * t;
test_subpixel_command(barbara, scale, scale, out_scale, out_scale, x_shift, y_shift);
}}
// Upscaling
{for (int i = 0; i <= res; i++)
{
float t = (float)i/res;
float scale = 2;
float out_scale = 3;
float x_shift = (barbara_width*out_scale - barbara_width*scale) * t;
float y_shift = (barbara_height*out_scale - barbara_height*scale) * t;
test_subpixel_command(barbara, scale, scale, out_scale, out_scale, x_shift, y_shift);
}}
// Downscaling
{for (int i = 0; i <= res; i++)
{
float t = (float)i/res / 2;
test_subpixel_region(barbara, 0.25f, 0.25f, t, t, t+0.5f, t+0.5f);
}}
// No scaling
{for (int i = 0; i <= res; i++)
{
float t = (float)i/res / 2;
test_subpixel_region(barbara, 0.5f, 0.5f, t, t, t+0.5f, t+0.5f);
}}
// Upscaling
{for (int i = 0; i <= res; i++)
{
float t = (float)i/res / 2;
test_subpixel_region(barbara, 1, 1, t, t, t+0.5f, t+0.5f);
}}
{for (i = 0; i < 10; i++)
test_subpixel(barbara, 0.5f, 0.5f, (float)i / 10, 1);
}
{for (i = 0; i < 10; i++)
test_subpixel(barbara, 0.5f, 0.5f, 1, (float)i / 10);
}
{for (i = 0; i < 10; i++)
test_subpixel(barbara, 2, 2, (float)i / 10, 1);
}
{for (i = 0; i < 10; i++)
test_subpixel(barbara, 2, 2, 1, (float)i / 10);
}
// Channels test
test_channels(barbara, 0.5f, 0.5f, 1);
test_channels(barbara, 0.5f, 0.5f, 2);
test_channels(barbara, 0.5f, 0.5f, 3);
test_channels(barbara, 0.5f, 0.5f, 4);
test_channels(barbara, 2, 2, 1);
test_channels(barbara, 2, 2, 2);
test_channels(barbara, 2, 2, 3);
test_channels(barbara, 2, 2, 4);
// filter tests
resize_image(barbara, 2, 2, STBIR_FILTER_BOX , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, "test-output/barbara-upsample-nearest.png");
resize_image(barbara, 2, 2, STBIR_FILTER_TRIANGLE , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, "test-output/barbara-upsample-bilinear.png");
resize_image(barbara, 2, 2, STBIR_FILTER_CUBICBSPLINE, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, "test-output/barbara-upsample-bicubic.png");
resize_image(barbara, 2, 2, STBIR_FILTER_CATMULLROM , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, "test-output/barbara-upsample-catmullrom.png");
resize_image(barbara, 2, 2, STBIR_FILTER_MITCHELL , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, "test-output/barbara-upsample-mitchell.png");
resize_image(barbara, 0.5f, 0.5f, STBIR_FILTER_BOX , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, "test-output/barbara-downsample-nearest.png");
resize_image(barbara, 0.5f, 0.5f, STBIR_FILTER_TRIANGLE , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, "test-output/barbara-downsample-bilinear.png");
resize_image(barbara, 0.5f, 0.5f, STBIR_FILTER_CUBICBSPLINE, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, "test-output/barbara-downsample-bicubic.png");
resize_image(barbara, 0.5f, 0.5f, STBIR_FILTER_CATMULLROM , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, "test-output/barbara-downsample-catmullrom.png");
resize_image(barbara, 0.5f, 0.5f, STBIR_FILTER_MITCHELL , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, "test-output/barbara-downsample-mitchell.png");
{for (i = 10; i < 100; i++)
{
char outname[200];
sprintf(outname, "test-output/barbara-width-%d.jpg", i);
resize_image(barbara, (float)i / 100, 1, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, outname);
}}
{for (i = 110; i < 500; i += 10)
{
char outname[200];
sprintf(outname, "test-output/barbara-width-%d.jpg", i);
resize_image(barbara, (float)i / 100, 1, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, outname);
}}
{for (i = 10; i < 100; i++)
{
char outname[200];
sprintf(outname, "test-output/barbara-height-%d.jpg", i);
resize_image(barbara, 1, (float)i / 100, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, outname);
}}
{for (i = 110; i < 500; i += 10)
{
char outname[200];
sprintf(outname, "test-output/barbara-height-%d.jpg", i);
resize_image(barbara, 1, (float)i / 100, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, outname);
}}
{for (i = 50; i < 200; i += 10)
{
char outname[200];
sprintf(outname, "test-output/barbara-width-height-%d.jpg", i);
resize_image(barbara, 100 / (float)i, (float)i / 100, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, outname);
}}
test_format<unsigned short>(barbara, 0.5, 2.0, STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB);
test_format<unsigned short>(barbara, 0.5, 2.0, STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR);
test_format<unsigned short>(barbara, 2.0, 0.5, STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB);
test_format<unsigned short>(barbara, 2.0, 0.5, STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR);
test_format<unsigned int>(barbara, 0.5, 2.0, STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB);
test_format<unsigned int>(barbara, 0.5, 2.0, STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR);
test_format<unsigned int>(barbara, 2.0, 0.5, STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB);
test_format<unsigned int>(barbara, 2.0, 0.5, STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR);
test_float(barbara, 0.5, 2.0, STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB);
test_float(barbara, 0.5, 2.0, STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR);
test_float(barbara, 2.0, 0.5, STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB);
test_float(barbara, 2.0, 0.5, STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR);
// Edge behavior tests
resize_image("hgradient.png", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR, "test-output/hgradient-clamp.png");
resize_image("hgradient.png", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_WRAP, STBIR_COLORSPACE_LINEAR, "test-output/hgradient-wrap.png");
resize_image("vgradient.png", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR, "test-output/vgradient-clamp.png");
resize_image("vgradient.png", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_WRAP, STBIR_COLORSPACE_LINEAR, "test-output/vgradient-wrap.png");
resize_image("1px-border.png", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_REFLECT, STBIR_COLORSPACE_LINEAR, "test-output/1px-border-reflect.png");
resize_image("1px-border.png", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR, "test-output/1px-border-clamp.png");
// sRGB tests
resize_image("gamma_colors.jpg", .5f, .5f, STBIR_FILTER_CATMULLROM, STBIR_EDGE_REFLECT, STBIR_COLORSPACE_SRGB, "test-output/gamma_colors.jpg");
resize_image("gamma_2.2.jpg", .5f, .5f, STBIR_FILTER_CATMULLROM, STBIR_EDGE_REFLECT, STBIR_COLORSPACE_SRGB, "test-output/gamma_2.2.jpg");
resize_image("gamma_dalai_lama_gray.jpg", .5f, .5f, STBIR_FILTER_CATMULLROM, STBIR_EDGE_REFLECT, STBIR_COLORSPACE_SRGB, "test-output/gamma_dalai_lama_gray.jpg");
}
| 18,558 |
30,785 | <reponame>DSYliangweihao/jadx
package jadx.tests.integration.inner;
import org.junit.jupiter.api.Test;
import jadx.NotYetImplemented;
import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.IntegrationTest;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
public class TestAnonymousClass3 extends IntegrationTest {
public static class TestCls {
public static class Inner {
private int f;
public double d;
public void test() {
new Thread() {
@Override
public void run() {
int a = f--;
p(a);
f += 2;
f *= 2;
a = ++f;
p(a);
d /= 3;
}
public void p(int a) {
}
}.start();
}
}
}
@Test
public void test() {
disableCompilation();
ClassNode cls = getClassNode(TestCls.class);
String code = cls.getCode().toString();
assertThat(code, containsString(indent(4) + "public void run() {"));
assertThat(code, containsString(indent(3) + "}.start();"));
assertThat(code, not(containsString("AnonymousClass_")));
}
@Test
@NotYetImplemented
public void test2() {
disableCompilation();
ClassNode cls = getClassNode(TestCls.class);
String code = cls.getCode().toString();
assertThat(code, not(containsString("synthetic")));
assertThat(code, containsString("a = f--;"));
}
}
| 571 |
376 | /**
* @file
*
* @version 1.0
* @date 2014/04/25
*
* @section DESCRIPTION
*
* No standard functions for these in glibc so rolling our own.
*/
#ifndef PACK_H__
#define PACK_H__
#include <stddef.h>
/* Public API *****************************************************************/
/**
* Convert a C string of hex characters to a byte array
*
* "001122ac" becomes [0x00, 0x11, 0x22, 0xac]
*/
int pack(void *dest, const char *hex, size_t line);
/**
* Write the bytes in source as a hex string
*
* [0x00, 0x11, 0x22, 0xac] becomes "001122ac"
*/
void unpack(char *dest, const void *src, size_t count);
#endif
| 216 |
648 | <gh_stars>100-1000
{"resourceType":"DataElement","id":"Provenance.target","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/Provenance.target","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"Provenance.target","path":"Provenance.target","short":"Target Reference(s) (usually version specific)","definition":"The Reference(s) that were generated or updated by the activity described in this resource. A provenance can point to more than one target if multiple resources were created/updated by the same activity.","comment":"Target references are usually version specific, but may not be, if a version has not been assigned or if the provenance information is part of the set of resources being maintained (i.e. a document). When using the RESTful API, the identity of the resource may not be known (especially not the version specific one); the client may either submit the resource first, and then the provenance, or it may submit both using a single transaction. See the notes on transaction for further discussion.","min":1,"max":"*","type":[{"code":"Reference","targetProfile":"http://hl7.org/fhir/StructureDefinition/Resource"}],"isSummary":true,"mapping":[{"identity":"rim","map":"./outboundRelationship[isNormalActRelationship() and typeCode=SUBJ]/target OR ./participation[isNormalParticipation() and typeCode=SBJ]/role OR ./participation[isNormalParticipation() and typeCode=SBJ]/role[isNormalRole()]/player"},{"identity":"fhirauditevent","map":"AuditEvent.entity.reference"},{"identity":"w3c.prov","map":"Entity Created/Updated"},{"identity":"w5","map":"what"}]}]} | 432 |
348 | {"nom":"Sainte-Marie-de-Vatimesnil","dpt":"Eure","inscrits":183,"abs":28,"votants":155,"blancs":25,"nuls":1,"exp":129,"res":[{"panneau":"2","voix":71},{"panneau":"1","voix":58}]} | 76 |
737 | <reponame>etnrlz/rtbkit<gh_stars>100-1000
/* bid_request_parser.h -*- C++ -*-
<NAME>, 19 August 2014
Copyright (c) 2014 Datacratic Inc. All rights reserved.
Bid request parser interface
*/
#pragma once
namespace RTBKIT {
/*****************************************************************************/
/* BID REQUEST PARSER */
/*****************************************************************************/
template <typename T, typename V>
struct IBidRequestParser {
virtual T parseBidRequest(V & value);
};
} // namespace RTBKIT
| 262 |
2,236 | // Authored by : tony9402
// Co-authored by : -
// Link : http://boj.kr/bb3cca54213d47268ddc82a82728f730
#include<bits/stdc++.h>
using namespace std;
int n, ans;
bool Y[22], DL[44], DR[44];
void dfs(int y, int cnt){
if(cnt == n){
ans++;
return;
}
for(int j=0;j<n;j++){
if(Y[j] || DL[y + j] || DR[y - j + n])continue;
Y[j] = DL[y + j] = DR[y - j + n] = true;
dfs(y + 1, cnt + 1);
Y[j] = DL[y + j] = DR[y - j + n] = false;
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
dfs(0, 0);
cout << ans;
return 0;
}
| 344 |
1,259 | <gh_stars>1000+
from rest_framework import serializers
from integrations.mixpanel.models import MixpanelConfiguration
class MixpanelConfigurationSerializer(serializers.ModelSerializer):
class Meta:
model = MixpanelConfiguration
fields = ("id", "api_key")
| 84 |
1,062 | <filename>MailHeaders/Catalina/MailFW/MFMessageDelivererDelegate-Protocol.h
//
// Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <MailFW/NSObject-Protocol.h>
@class MFMessageDeliverer;
@protocol MFMessageDelivererDelegate <NSObject>
- (void)messageDeliveryDidFinish:(MFMessageDeliverer *)arg1;
@optional
- (void)messageDeliveryWillBegin:(MFMessageDeliverer *)arg1;
@end
| 167 |
1,841 | <reponame>mitsuhiko/pipsi
import os
import sys
import pkg_resources
pkg = sys.argv[1]
prefix = sys.argv[2]
dist = pkg_resources.get_distribution(pkg)
if dist.has_metadata('RECORD'):
for line in dist.get_metadata_lines('RECORD'):
print(os.path.join(dist.location, line.split(',')[0]))
elif dist.has_metadata('installed-files.txt'):
for line in dist.get_metadata_lines('installed-files.txt'):
print(os.path.join(dist.egg_info, line.split(',')[0]))
elif dist.has_metadata('entry_points.txt'):
try:
from ConfigParser import SafeConfigParser
from StringIO import StringIO
except ImportError:
from configparser import SafeConfigParser
from io import StringIO
parser = SafeConfigParser()
parser.readfp(StringIO(
'\n'.join(dist.get_metadata_lines('entry_points.txt'))))
if parser.has_section('console_scripts'):
for name, _ in parser.items('console_scripts'):
print(os.path.join(prefix, name))
| 391 |
1,444 | <filename>Mage.Sets/src/mage/sets/ArenaNewPlayerExperience.java
package mage.sets;
import mage.cards.CardGraphicInfo;
import mage.cards.ExpansionSet;
import mage.cards.FrameStyle;
import mage.constants.Rarity;
import mage.constants.SetType;
/**
* @author JayDi85
*/
public final class ArenaNewPlayerExperience extends ExpansionSet {
private static final ArenaNewPlayerExperience instance = new ArenaNewPlayerExperience();
public static ArenaNewPlayerExperience getInstance() {
return instance;
}
private ArenaNewPlayerExperience() {
super("Arena New Player Experience", "ANA", ExpansionSet.buildDate(2018, 7, 14), SetType.MAGIC_ONLINE);
this.hasBoosters = false;
this.hasBasicLands = true;
final CardGraphicInfo FULL_ART = new CardGraphicInfo(FrameStyle.ANA_FULL_ART_BASIC, true);
cards.add(new SetCardInfo("Forest", "10a", Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Forest", "9a", Rarity.LAND, mage.cards.basiclands.Forest.class, FULL_ART));
cards.add(new SetCardInfo("Forest", 18, Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Forest", 19, Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Forest", 20, Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Forest", 33, Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Forest", 34, Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Forest", 35, Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Island", "3a", Rarity.LAND, mage.cards.basiclands.Island.class, FULL_ART));
cards.add(new SetCardInfo("Island", "4a", Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Island", 10, Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Island", 11, Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Island", 24, Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Island", 25, Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Island", 26, Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Island", 9, Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mountain", "7a", Rarity.LAND, mage.cards.basiclands.Mountain.class, FULL_ART));
cards.add(new SetCardInfo("Mountain", "8a", Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mountain", 15, Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mountain", 16, Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mountain", 17, Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mountain", 30, Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mountain", 31, Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mountain", 32, Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plains", "1a", Rarity.LAND, mage.cards.basiclands.Plains.class, FULL_ART));
cards.add(new SetCardInfo("Plains", "2a", Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plains", 21, Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plains", 22, Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plains", 23, Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plains", 6, Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plains", 7, Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plains", 8, Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swamp", "5a", Rarity.LAND, mage.cards.basiclands.Swamp.class, FULL_ART));
cards.add(new SetCardInfo("Swamp", "6a", Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swamp", 12, Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swamp", 13, Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swamp", 14, Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swamp", 27, Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swamp", 28, Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swamp", 29, Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
}
} | 2,211 |
966 | <reponame>dstoeckel/MOE
# -*- coding: utf-8 -*-
"""Request/response schemas for the MOE REST interface.
Contains schemas for each endpoint represented in :mod:`moe.views.rest`.
.. Warning:: Outputs of colander schema serialization/deserialization should be treated as
READ-ONLY. It appears that "missing=" and "default=" value are weak-copied (by reference).
Thus changing missing/default fields in the output dict can modify the schema!
"""
| 132 |
1,006 | <filename>include/nuttx/syslog/syslog_console.h
/****************************************************************************
* include/nuttx/syslog/syslog_console.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
#ifndef __INCLUDE_NUTTX_SYSLOG_SYSLOG_CONSOLE_H
#define __INCLUDE_NUTTX_SYSLOG_SYSLOG_CONSOLE_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <nuttx/syslog/syslog.h>
#ifdef CONFIG_CONSOLE_SYSLOG
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Configuration ************************************************************/
/* CONFIG_CONSOLE_SYSLOG - Use the syslog logging output as a system console.
* If this feature is enabled (along with CONFIG_DEV_CONSOLE), then all
* console output will be re-directed to the SYSLOG output channel. This
* is useful, for example, if the only console is a Telnet console. Then
* in that case, console output from non-Telnet threads will go to the
* SYSLOG output channel.
*/
#ifndef CONFIG_DEV_CONSOLE
# undef CONFIG_CONSOLE_SYSLOG
#endif
/****************************************************************************
* Public Data
****************************************************************************/
#ifndef __ASSEMBLY__
#ifdef __cplusplus
#define EXTERN extern "C"
extern "C"
{
#else
#define EXTERN extern
#endif
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
/****************************************************************************
* Name: syslog_console_init
*
* Description:
* Create the console logging device and register it at the '/dev/console'
* path.
*
****************************************************************************/
#ifdef CONFIG_CONSOLE_SYSLOG
int syslog_console_init(void);
#endif
#undef EXTERN
#ifdef __cplusplus
}
#endif
#endif /* __ASSEMBLY__ */
#endif /* CONFIG_CONSOLE_SYSLOG */
#endif /* __INCLUDE_NUTTX_SYSLOG_SYSLOG_CONSOLE_H */
| 763 |
3,970 | // Copyright 2004-present Facebook. All Rights Reserved.
#import <Foundation/Foundation.h>
@interface TestProjectLibrary64bit : NSObject
- (void)randomMethod;
@end
| 50 |
372 | /*
* 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.sysds.runtime.io.hdf5;
import org.apache.sysds.runtime.io.hdf5.message.H5Message;
import org.apache.sysds.runtime.io.hdf5.message.H5DataTypeMessage;
import org.apache.sysds.runtime.io.hdf5.message.H5DataSpaceMessage;
import org.apache.sysds.runtime.io.hdf5.message.H5FillValueMessage;
import org.apache.sysds.runtime.io.hdf5.message.H5NilMessage;
import org.apache.sysds.runtime.io.hdf5.message.H5ObjectModificationTimeMessage;
import org.apache.sysds.runtime.io.hdf5.message.H5SymbolTableMessage;
import org.apache.sysds.runtime.io.hdf5.message.H5DataLayoutMessage;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.stream.Collectors;
import static org.apache.sysds.runtime.io.hdf5.Utils.readBytesAsUnsignedInt;
public class H5ObjectHeader {
private final H5RootObject rootObject;
private final List<H5Message> messages = new ArrayList<>();
private int referenceCount = 1;
private String datasetName;
public H5ObjectHeader(H5RootObject rootObject, long address) {
this.rootObject = rootObject;
try {
ByteBuffer header = rootObject.readBufferFromAddress(address, 12);
// Version
rootObject.setObjectHeaderVersion(header.get());
if(rootObject.getObjectHeaderVersion() != 1) {
throw new H5RuntimeException("Invalid version detected. Version is = " + rootObject.getObjectHeaderVersion());
}
// Skip reserved byte
header.position(header.position() + 1);
// Number of messages
final int numberOfMessages = readBytesAsUnsignedInt(header, 2);
// Reference Count
referenceCount = readBytesAsUnsignedInt(header, 4);
// Size of the messages
int headerSize = readBytesAsUnsignedInt(header, 4);
// 12 up to this point + 4 missed in format spec = 16
address += 16;
header = rootObject.readBufferFromAddress(address, headerSize);
readMessages(header, numberOfMessages);
}
catch(Exception e) {
throw new H5RuntimeException("Failed to read object header at address: " + address, e);
}
}
public <T extends H5Message> List<T> getMessagesOfType(Class<T> type) {
return getMessages().stream().filter(type::isInstance).map(type::cast).collect(Collectors.toList());
}
public <T extends H5Message> boolean hasMessageOfType(Class<T> type) {
return !getMessagesOfType(type).isEmpty();
}
public <T extends H5Message> T getMessageOfType(Class<T> type) {
List<T> messagesOfType = getMessagesOfType(type);
// Validate only one message exists
if(messagesOfType.isEmpty()) {
throw new H5RuntimeException("Requested message type '" + type.getSimpleName() + "' not present");
}
if(messagesOfType.size() > 1) {
throw new H5RuntimeException("Requested message type '" + type.getSimpleName() + "' is not unique");
}
return messagesOfType.get(0);
}
private void readMessages(ByteBuffer bb, int numberOfMessages) {
while(bb.remaining() > 4 && messages.size() < numberOfMessages) {
H5Message m = H5Message.readObjectHeaderMessage(rootObject, bb);
messages.add(m);
}
}
public H5ObjectHeader(H5RootObject rootObject, String datasetName) {
this.rootObject = rootObject;
this.datasetName = datasetName;
}
private void writeObjectHeader(H5BufferBuilder bb, short numberOfMessages, int headerSize) {
// Version
bb.writeByte(rootObject.objectHeaderVersion);
// Skip reserved byte
bb.writeByte(0);
// Number of messages
bb.writeShort(numberOfMessages);
// Reference Count
bb.writeInt(this.referenceCount);
// Size of the messages
bb.writeInt(headerSize);
bb.writeInt(0);
}
public H5BufferBuilder toBuffer() {
H5BufferBuilder bb = new H5BufferBuilder();
this.toBuffer(bb);
return bb;
}
public void toBuffer(H5BufferBuilder bb) {
// 1. Write Object Header Message for first step
this.writeObjectHeader(bb, (short) 1, 24);
//1.1 Write SymbolTableMessage
BitSet flags = new BitSet();
long localHeapAddress = 680;
H5SymbolTableMessage symbolTableMessage = new H5SymbolTableMessage(rootObject, flags, 136, localHeapAddress);
symbolTableMessage.toBuffer(bb);
//1.2 Write BTree data
List<Long> childAddresses = new ArrayList<>();
childAddresses.add(1072L);
H5BTree bTree = new H5BTree(rootObject, (byte) 0, (byte) 0, 1, -1, -1, childAddresses);
bTree.toBuffer(bb);
// and static value!
bb.writeShort((short) 8);
//long l = bb.getSize();
// 1.3 Write LocalHeap
bb.goToPositionWithWriteZero(localHeapAddress);
H5LocalHeap localHeap = new H5LocalHeap(rootObject, datasetName, 88, 16, 712);
localHeap.toBuffer(bb);
// 2. Write Object Header Message for second step
this.writeObjectHeader(bb, (short) 6, 256);
// 2.1 Write Data Space
flags = new BitSet(8);
//flags.set(0);
H5DataSpaceMessage dataSpaceMessage = new H5DataSpaceMessage(rootObject, flags);
dataSpaceMessage.toBuffer(bb);
flags.set(0);
// 2.2 Write Data Type
H5DoubleDataType doubleDataType = new H5DoubleDataType();
H5DataTypeMessage dataTypeMessage = new H5DataTypeMessage(rootObject, flags, doubleDataType);
dataTypeMessage.toBuffer(bb);
// 2.3 Write Fill Value
H5FillValueMessage fillValueMessage = new H5FillValueMessage(rootObject, flags, 2, 2, true);
fillValueMessage.toBuffer(bb);
// 2.4 Write Data Layout Message
flags = new BitSet();
H5DataLayoutMessage dataLayoutMessage = new H5DataLayoutMessage(rootObject, flags, 2048,
(rootObject.row * rootObject.col) * rootObject.superblock.sizeOfLengths);
dataLayoutMessage.toBuffer(bb);
// 2.5 Write Object Modification Time
long time = Instant.now().getEpochSecond();
H5ObjectModificationTimeMessage objectModificationTimeMessage = new H5ObjectModificationTimeMessage(rootObject,
flags, time);
objectModificationTimeMessage.toBuffer(bb);
//2.6 Write Nil
H5NilMessage nilMessage = new H5NilMessage(rootObject, flags);
nilMessage.toBuffer(bb);
// Write Group Symbol Table Node
int i = 0;
for(long child : childAddresses) {
bb.goToPositionWithWriteZero(child);
H5SymbolTableEntry[] symbolTableEntries = new H5SymbolTableEntry[1];
symbolTableEntries[i++] = new H5SymbolTableEntry(8, 800, 0, -1, -1);
H5GroupSymbolTableNode groupSTE = new H5GroupSymbolTableNode(rootObject, (short) 1, symbolTableEntries);
groupSTE.toBuffer(bb);
}
}
public List<H5Message> getMessages() {
return messages;
}
}
| 2,417 |
525 | /*
* Copyright 2018 Odnoklassniki Ltd, Mail.Ru Group
*
* 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 one.nio.net;
import one.nio.util.ByteArrayBuilder;
import one.nio.util.Utf8;
import java.io.IOException;
import java.net.ConnectException;
public class SocksProxy implements Proxy {
private final String proxyHost;
private final int proxyPort;
private String user;
private String password;
public SocksProxy(String proxyHost, int proxyPort) {
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
}
public SocksProxy withAuth(String user, String password) {
this.user = user;
this.password = password;
return this;
}
@Override
public void connect(Socket socket, String host, int port) throws IOException {
socket.connect(proxyHost, proxyPort);
ByteArrayBuilder builder = new ByteArrayBuilder(400);
byte authMethod = user == null || password == null ? (byte) 0 : (byte) 2;
// Handshake
builder.append((byte) 5)
.append((byte) 1)
.append(authMethod);
// Auth
if (authMethod != 0) {
int userLength = Utf8.length(user);
int passwordLength = Utf8.length(password);
builder.append((byte) 1)
.append((byte) userLength)
.append(user)
.append((byte) passwordLength)
.append(password);
}
// Connect
builder.append((byte) 5)
.append((byte) 1)
.append((byte) 0)
.append((byte) 3)
.append((byte) host.length())
.append(host)
.append((byte) (port >>> 8))
.append((byte) port);
// Send all commands in one packet to avoid extra round trips
socket.writeFully(builder.buffer(), 0, builder.length());
readResponse(socket, builder.buffer(), authMethod);
}
private void readResponse(Socket socket, byte[] buf, byte authMethod) throws IOException {
// Handshake response
socket.readFully(buf, 0, 2);
if (buf[0] != 5 || buf[1] != authMethod) {
socket.close();
throw new ConnectException("SocksProxy handshake error");
}
// Auth response
if (authMethod != 0) {
socket.readFully(buf, 0, 2);
if (buf[1] != 0) {
socket.close();
throw new ConnectException("SocksProxy auth error");
}
}
// Connect response
socket.readFully(buf, 0, 10);
if (buf[1] != 0) {
socket.close();
throw new ConnectException(getErrorMessage(buf[1]));
}
// Read remaining reply header for IPv6 address
if (buf[3] == 4) {
socket.readFully(buf, 10, 12);
}
}
private static String getErrorMessage(byte b) {
switch (b) {
case 1:
return "SocksProxy: general SOCKS server failure";
case 2:
return "SocksProxy: connection not allowed by ruleset";
case 3:
return "SocksProxy: Network unreachable";
case 4:
return "SocksProxy: Host unreachable";
case 5:
return "SocksProxy: Connection refused";
case 6:
return "SocksProxy: TTL expired";
case 7:
return "SocksProxy: Command not supported";
case 8:
return "SocksProxy: Address type not supported";
default:
return "SocksProxy connect error " + (b & 0xff);
}
}
}
| 1,883 |
321 | <gh_stars>100-1000
/**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - <EMAIL>
*
*/
package org.hoteia.qalingo.core.email.bean;
import java.io.Serializable;
import org.apache.commons.lang.StringUtils;
import org.hoteia.qalingo.core.Constants;
import org.hoteia.qalingo.core.util.CoreUtil;
public class OrderItemEmailBean extends AbstractEmailBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8722711859740312774L;
protected String skuCode;
protected String ean;
protected String i18nName;
protected String i18nDescription;
protected String i18nShortDescription;
protected String storeCode;
protected String storeName;
protected int quantity;
protected String price;
protected String priceWithTaxes;
protected String amount;
protected String defaultAssetFullPath;
public String getSkuCode() {
return skuCode;
}
public void setSkuCode(String skuCode) {
this.skuCode = skuCode;
}
public String getEan() {
return ean;
}
public void setEan(String ean) {
this.ean = ean;
}
public String getI18nName() {
return i18nName;
}
public void setI18nName(String i18nName) {
this.i18nName = i18nName;
}
public String getI18nTruncatedName() {
int size = Constants.POJO_NAME_MAX_LENGTH;
if (StringUtils.isNotEmpty(getI18nName())){
if(getI18nName().length() >= size){
return CoreUtil.handleTruncatedString(getI18nName(), size);
} else {
return getI18nName();
}
}
return "";
}
public String getI18nDescription() {
return i18nDescription;
}
public void setI18nDescription(String i18nDescription) {
this.i18nDescription = i18nDescription;
}
public String getI18nShortDescription() {
return i18nShortDescription;
}
public void setI18nShortDescription(String i18nShortDescription) {
this.i18nShortDescription = i18nShortDescription;
}
public String getI18nTruncatedDescription() {
int size = Constants.POJO_DESCRIPTION_MAX_LENGTH;
if(StringUtils.isNotEmpty(getI18nShortDescription())){
if(getI18nShortDescription().length() >= size){
return CoreUtil.handleTruncatedString(getI18nShortDescription(), size);
} else {
return getI18nShortDescription();
}
} else if (StringUtils.isNotEmpty(getI18nDescription())){
if(getI18nDescription().length() >= size){
return CoreUtil.handleTruncatedString(getI18nDescription(), size);
} else {
return getI18nDescription();
}
}
return "";
}
public String getStoreCode() {
return storeCode;
}
public void setStoreCode(String storeCode) {
this.storeCode = storeCode;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getPriceWithTaxes() {
return priceWithTaxes;
}
public void setPriceWithTaxes(String priceWithTaxes) {
this.priceWithTaxes = priceWithTaxes;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDefaultAssetFullPath() {
return defaultAssetFullPath;
}
public void setDefaultAssetFullPath(String defaultAssetFullPath) {
this.defaultAssetFullPath = defaultAssetFullPath;
}
} | 1,834 |
7,482 | /*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2018/10/01 Bernard The first version
*/
#include <rthw.h>
#include <board.h>
#include <RV32M1_ri5cy.h>
typedef void (*irq_handler_t)(void);
extern const irq_handler_t isrTable[];
void SystemIrqHandler(uint32_t mcause)
{
uint32_t intNum;
if (mcause & 0x80000000) /* For external interrupt. */
{
intNum = mcause & 0x1FUL;
/* Clear pending flag in EVENT unit .*/
EVENT_UNIT->INTPTPENDCLEAR = (1U << intNum);
/* Now call the real irq handler for intNum */
isrTable[intNum]();
}
}
| 313 |
1,615 | <gh_stars>1000+
package org.luaj.vm2;
import com.immomo.mls.UDTest;
import com.immomo.mls.wrapper.Register;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.*;
/**
* Created by Xiong.Fangyu on 2019-06-18
*/
public class IsolateTest extends BaseLuaTest {
private static final String IsolateLua = "test_isolate.lua";
protected void registerBridge() {
register.registerUserdata(Register.newUDHolder("UDTest", UDTest.class, false, "test"));
}
@Test
public void loadIsolateLua() throws InterruptedException {
initGlobals(true);
String path = Utils.getAssetsPath() + File.separator + IsolateLua;
assertTrue(globals.loadFile(path, IsolateLua));
assertTrue(globals.callLoadedData());
checkStackSize(1);
assertTrue(quitLooperDelay(1000));
}
}
| 330 |
1,056 | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.editor.guards;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import org.netbeans.spi.editor.guards.support.AbstractGuardedSectionsProvider;
/** This stream is able to filter special guarded comments.
* Holding this information is optional and depends on the construction
* of this stream - the reason of this feature is that
* GuardedReader is used also for parser (and it doesn't require
* the storing the guarded block information - just filter the comments).
*/
final class GuardedReader extends Reader {
/** Encapsulated reader */
Reader reader;
private NewLineInputStream newLineStream;
/** Character buffer */
char[] charBuff;
int howmany;
/** The flag determining if this stream should store the guarded
* block information (list of the SectionDesc).
*/
boolean justFilter;
/** The position at the current line. */
int position;
// /** The list of the SectionsDesc. */
// LinkedList<GuardedSection> list;
// /** The count of types new line delimiters used in the file */
// final int[] newLineTypes;
private final GuardedSectionsImpl callback;
private final AbstractGuardedSectionsProvider gr;
private boolean isClosed = false;
private AbstractGuardedSectionsProvider.Result result;
/** Creates new stream.
* @param is encapsulated input stream.
* @param justFilter The flag determining if this stream should
* store the guarded block information. True means just filter,
* false means store the information.
*/
// GuardedReader(InputStream is, boolean justFilter) throws UnsupportedEncodingException {
// this(is, justFilter, null);
// }
//
GuardedReader(AbstractGuardedSectionsProvider gr, InputStream is, boolean justFilter, Charset encoding, GuardedSectionsImpl guards) {
newLineStream = new NewLineInputStream(is);
if (encoding == null)
reader = new InputStreamReader(newLineStream);
else
reader = new InputStreamReader(newLineStream, encoding);
this.justFilter = justFilter;
// list = new LinkedList<SectionDescriptor>();
// newLineTypes = new int[] { 0, 0, 0 };
this.callback = guards;
this.gr = gr;
}
/** Read the array of chars */
public int read(char[] cbuf, int off, int len) throws IOException {
if (charBuff == null) {
char[] readBuff = readCharBuff();
this.result = this.gr.readSections(readBuff);
charBuff = this.result.getContent();
howmany = charBuff.length;
}
if (howmany <= 0) {
return -1;
} else {
int min = Math.min(len, howmany);
System.arraycopy(charBuff, position, cbuf, off, min);
howmany -= min;
position += min;
return min;
}
}
/** Reads readBuff */
final char[] readCharBuff() throws IOException {
char[] readBuff;
char[] tmp = new char[2048];
int read;
ArrayList<char[]> buffs = new ArrayList<char[]>(20);
for (; ; ) {
read = readFully(tmp);
buffs.add(tmp);
if (read < 2048) {
break;
} else {
tmp = new char[2048];
}
}
int listsize = buffs.size() - 1;
int size = listsize * 2048 + read;
readBuff = new char[size];
charBuff = new char[size];
int copy = 0;
for (int i = 0; i < listsize; i++) {
char[] tmp2 = (char[]) buffs.get(i);
System.arraycopy(tmp2, 0, readBuff, copy, 2048);
copy += 2048;
}
System.arraycopy(tmp, 0, readBuff, copy, read);
return readBuff;
}
/** reads fully given buffer */
final int readFully(final char[] buff) throws IOException {
int read = 0;
int sum = 0;
do {
read = reader.read(buff, sum, buff.length - sum);
sum += read;
} while ((sum < buff.length) && (read > 0));
return sum + 1;
}
/** Close underlying writer. */
public void close() throws IOException {
if (!isClosed) {
isClosed = true;
reader.close();
if (this.result != null) {
callback.fillSections(gr, this.result.getGuardedSections(), newLineStream.getNewLineType());
}
}
}
private final class NewLineInputStream extends InputStream {
private final InputStream stream;
private int b;
private int lookahead;
private boolean isLookahead = false;
/** The count of types new line delimiters used in the file */
final int[] newLineTypes;
public NewLineInputStream(InputStream source) {
this.stream = source;
this.newLineTypes = new int[] { 0, 0, 0 };
}
/** @return most frequent type of new line delimiter */
public NewLine getNewLineType() {
// special case: an empty file (all newline types equal)
if (newLineTypes[NewLine.N.ordinal()] == newLineTypes[NewLine.R.ordinal()] &&
newLineTypes[NewLine.R.ordinal()] == newLineTypes[NewLine.RN.ordinal()]) {
String s = System.getProperty("line.separator"); // NOI18N
return NewLine.resolve(s);
}
if (newLineTypes[NewLine.N.ordinal()] > newLineTypes[NewLine.R.ordinal()]) {
return (newLineTypes[NewLine.N.ordinal()] > newLineTypes[NewLine.RN.ordinal()]) ? NewLine.N : NewLine.RN;
} else {
return (newLineTypes[NewLine.R.ordinal()] > newLineTypes[NewLine.RN.ordinal()]) ? NewLine.R : NewLine.RN;
}
}
public int read() throws IOException {
b = isLookahead? lookahead: this.stream.read();
isLookahead = false;
switch (b) {
case (int) '\n':
newLineTypes[NewLine.N.ordinal()/*NEW_LINE_N*/]++;
return b;
case (int) '\r':
lookahead = this.stream.read();
if (lookahead != (int) '\n') {
newLineTypes[NewLine.R.ordinal()/*NEW_LINE_R*/]++;
isLookahead = true;
} else {
newLineTypes[NewLine.RN.ordinal()/*NEW_LINE_RN*/]++;
}
return (int) '\n';
default:
return b;
}
}
public void close() throws IOException {
super.close();
this.stream.close();
}
}
}
| 3,385 |
6,115 | <filename>MavLinkCom/src/impl/MavLinkTcpServerImpl.cpp
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "MavLinkTcpServerImpl.hpp"
#include "../serial_com/TcpClientPort.hpp"
using namespace mavlinkcom_impl;
MavLinkTcpServerImpl::MavLinkTcpServerImpl(const std::string& local_addr, int local_port)
{
local_address_ = local_addr;
local_port_ = local_port;
}
MavLinkTcpServerImpl::~MavLinkTcpServerImpl()
{
}
std::shared_ptr<MavLinkConnection> MavLinkTcpServerImpl::acceptTcp(const std::string& nodeName)
{
accept_node_name_ = nodeName;
std::shared_ptr<TcpClientPort> result = std::make_shared<TcpClientPort>();
result->accept(local_address_, local_port_);
auto con = std::make_shared<MavLinkConnection>();
con->startListening(nodeName, result);
return con;
}
| 342 |
887 | <reponame>joey00072/onnxjs<gh_stars>100-1000
{
"name": "add",
"version": "1.0.0",
"description": "A simple example which adds two Tensors and validates the result.",
"main": "index.js",
"scripts": {},
"author": "",
"license": "ISC",
"dependencies": {
"onnxjs": "^0.1.8",
"onnxjs-node": "^1.4.0"
}
}
| 148 |
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.identitytoolkit.model;
/**
* Template for a single idp configuration.
*
* <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 Identity Toolkit 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 IdpConfig extends com.google.api.client.json.GenericJson {
/**
* OAuth2 client ID.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String clientId;
/**
* Whether this IDP is enabled.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean enabled;
/**
* Percent of users who will be prompted/redirected federated login for this IDP.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer experimentPercent;
/**
* OAuth2 provider.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String provider;
/**
* OAuth2 client secret.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String secret;
/**
* Whitelisted client IDs for audience check.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> whitelistedAudiences;
/**
* OAuth2 client ID.
* @return value or {@code null} for none
*/
public java.lang.String getClientId() {
return clientId;
}
/**
* OAuth2 client ID.
* @param clientId clientId or {@code null} for none
*/
public IdpConfig setClientId(java.lang.String clientId) {
this.clientId = clientId;
return this;
}
/**
* Whether this IDP is enabled.
* @return value or {@code null} for none
*/
public java.lang.Boolean getEnabled() {
return enabled;
}
/**
* Whether this IDP is enabled.
* @param enabled enabled or {@code null} for none
*/
public IdpConfig setEnabled(java.lang.Boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Percent of users who will be prompted/redirected federated login for this IDP.
* @return value or {@code null} for none
*/
public java.lang.Integer getExperimentPercent() {
return experimentPercent;
}
/**
* Percent of users who will be prompted/redirected federated login for this IDP.
* @param experimentPercent experimentPercent or {@code null} for none
*/
public IdpConfig setExperimentPercent(java.lang.Integer experimentPercent) {
this.experimentPercent = experimentPercent;
return this;
}
/**
* OAuth2 provider.
* @return value or {@code null} for none
*/
public java.lang.String getProvider() {
return provider;
}
/**
* OAuth2 provider.
* @param provider provider or {@code null} for none
*/
public IdpConfig setProvider(java.lang.String provider) {
this.provider = provider;
return this;
}
/**
* OAuth2 client secret.
* @return value or {@code null} for none
*/
public java.lang.String getSecret() {
return secret;
}
/**
* OAuth2 client secret.
* @param secret secret or {@code null} for none
*/
public IdpConfig setSecret(java.lang.String secret) {
this.secret = secret;
return this;
}
/**
* Whitelisted client IDs for audience check.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getWhitelistedAudiences() {
return whitelistedAudiences;
}
/**
* Whitelisted client IDs for audience check.
* @param whitelistedAudiences whitelistedAudiences or {@code null} for none
*/
public IdpConfig setWhitelistedAudiences(java.util.List<java.lang.String> whitelistedAudiences) {
this.whitelistedAudiences = whitelistedAudiences;
return this;
}
@Override
public IdpConfig set(String fieldName, Object value) {
return (IdpConfig) super.set(fieldName, value);
}
@Override
public IdpConfig clone() {
return (IdpConfig) super.clone();
}
}
| 1,645 |
23,439 | <gh_stars>1000+
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.core.cluster.lookup;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.cluster.MemberLookup;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.file.WatchFileCenter;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.env.StandardEnvironment;
import javax.servlet.ServletContext;
import java.io.File;
import java.util.Objects;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class LookupFactoryTest extends TestCase {
@Mock
private ServletContext servletContext;
private static final String LOOKUP_MODE_TYPE = "nacos.core.member.lookup.type";
private ServerMemberManager memberManager;
private MemberLookup memberLookup;
@Before
public void setUp() throws Exception {
when(servletContext.getContextPath()).thenReturn("");
EnvUtil.setEnvironment(new StandardEnvironment());
memberManager = new ServerMemberManager(servletContext);
}
@After
public void tearDown() throws NacosException {
WatchFileCenter.deregisterAllWatcher(EnvUtil.getConfPath());
memberManager.shutdown();
}
@Test
public void testCreateLookUp() throws NacosException {
memberLookup = LookupFactory.createLookUp(memberManager);
if (EnvUtil.getStandaloneMode()) {
assertEquals(memberLookup.getClass(), StandaloneMemberLookup.class);
} else {
String lookupType = EnvUtil.getProperty(LOOKUP_MODE_TYPE);
if (StringUtils.isNotBlank(lookupType)) {
LookupFactory.LookupType type = LookupFactory.LookupType.sourceOf(lookupType);
if (Objects.nonNull(type)) {
if (LookupFactory.LookupType.FILE_CONFIG.equals(type)) {
assertEquals(memberLookup.getClass(), FileConfigMemberLookup.class);
}
if (LookupFactory.LookupType.ADDRESS_SERVER.equals(type)) {
assertEquals(memberLookup.getClass(), AddressServerMemberLookup.class);
}
} else {
File file = new File(EnvUtil.getClusterConfFilePath());
if (file.exists() || StringUtils.isNotBlank(EnvUtil.getMemberList())) {
assertEquals(memberLookup.getClass(), FileConfigMemberLookup.class);
} else {
assertEquals(memberLookup.getClass(), AddressServerMemberLookup.class);
}
}
} else {
File file = new File(EnvUtil.getClusterConfFilePath());
if (file.exists() || StringUtils.isNotBlank(EnvUtil.getMemberList())) {
assertEquals(memberLookup.getClass(), FileConfigMemberLookup.class);
} else {
assertEquals(memberLookup.getClass(), AddressServerMemberLookup.class);
}
}
}
}
@Test
public void testSwitchLookup() throws NacosException {
String name1 = "file";
MemberLookup memberLookup = LookupFactory.switchLookup(name1, memberManager);
assertEquals(memberLookup.getClass(), FileConfigMemberLookup.class);
String name2 = "address-server";
memberLookup = LookupFactory.switchLookup(name2, memberManager);
assertEquals(memberLookup.getClass(), AddressServerMemberLookup.class);
}
} | 1,842 |
435 | /*
* Copyright (C) 2014 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.h6ah4i.android.media.openslmediaplayer.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import com.h6ah4i.android.media.IReleasable;
public class CommonTestCaseUtils {
private CommonTestCaseUtils() {
}
/*
* NOTE: The AssetFileDescriptor does not implement
* Closeable interface until API level 19 (issue #8)
*/
public static void closeQuietly(AssetFileDescriptor afd) {
if (afd == null)
return;
try {
afd.close();
} catch (Exception e) {
}
}
public static void closeQuietly(InputStream is) {
if (is == null)
return;
try {
is.close();
} catch (Exception e) {
}
}
public static void closeQuietly(OutputStream os) {
if (os == null)
return;
try {
os.close();
} catch (Exception e) {
}
}
public static void closeQuietly(FileChannel is) {
if (is == null)
return;
try {
is.close();
} catch (Exception e) {
}
}
public static void releaseQuietly(IReleasable releasable) {
if (releasable == null)
return;
try {
releasable.release();
} catch (Exception e) {
}
}
public static void copyAssetFile(AssetManager am, String assetName, File destBaseDir,
boolean overwrite)
throws IOException {
File destFile = new File(
destBaseDir
.getAbsolutePath()
.concat(File.separator)
.concat(assetName));
if (destFile.exists() && !overwrite)
return;
if (overwrite) {
destFile.delete();
}
destFile.getParentFile().mkdirs();
InputStream is = null;
OutputStream os = null;
try {
byte[] buff = new byte[4096];
is = am.open(assetName, AssetManager.ACCESS_STREAMING);
os = new FileOutputStream(destFile);
while (true) {
int nread = is.read(buff);
if (nread <= 0)
break;
os.write(buff, 0, nread);
}
} finally {
closeQuietly(is);
closeQuietly(os);
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
closeQuietly(source);
closeQuietly(destination);
}
}
public static void removeDirectory(File dir) {
if (dir.isDirectory()) {
final File[] files = dir.listFiles();
if (files != null) {
for (final File file : files) {
removeDirectory(file);
}
}
dir.delete();
} else {
dir.delete();
}
}
}
| 1,952 |
3,799 | <reponame>semoro/androidx
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.biometric;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import android.os.Build;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.internal.DoNotInstrument;
import javax.crypto.Cipher;
@RunWith(RobolectricTestRunner.class)
@DoNotInstrument
public class AuthenticationCallbackProviderTest {
@Mock private AuthenticationCallbackProvider.Listener mListener;
@Mock private Cipher mCipher;
@Captor private ArgumentCaptor<BiometricPrompt.AuthenticationResult> mResultCaptor;
private AuthenticationCallbackProvider mAuthenticationCallbackProvider;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mAuthenticationCallbackProvider = new AuthenticationCallbackProvider(mListener);
}
@Test
@Config(minSdk = Build.VERSION_CODES.P)
public void testBiometricCallback_IsCached() {
final android.hardware.biometrics.BiometricPrompt.AuthenticationCallback callback =
mAuthenticationCallbackProvider.getBiometricCallback();
assertThat(mAuthenticationCallbackProvider.getBiometricCallback()).isEqualTo(callback);
}
@Test
@Config(minSdk = Build.VERSION_CODES.P)
public void testBiometricCallback_HandlesSuccess() {
final android.hardware.biometrics.BiometricPrompt.AuthenticationResult result =
mock(android.hardware.biometrics.BiometricPrompt.AuthenticationResult.class);
final android.hardware.biometrics.BiometricPrompt.CryptoObject crypto =
new android.hardware.biometrics.BiometricPrompt.CryptoObject(mCipher);
when(result.getCryptoObject()).thenReturn(crypto);
mAuthenticationCallbackProvider.getBiometricCallback().onAuthenticationSucceeded(result);
verify(mListener).onSuccess(mResultCaptor.capture());
verifyNoMoreInteractions(mListener);
assertThat(mResultCaptor.getValue().getCryptoObject()).isNotNull();
assertThat(mResultCaptor.getValue().getCryptoObject().getCipher()).isEqualTo(mCipher);
}
@Test
@Config(minSdk = Build.VERSION_CODES.P)
public void testBiometricCallback_HandlesError() {
final int errorCode = BiometricPrompt.ERROR_HW_NOT_PRESENT;
final String errorMessage = "Lorem ipsum";
mAuthenticationCallbackProvider.getBiometricCallback()
.onAuthenticationError(errorCode, errorMessage);
verify(mListener).onError(errorCode, errorMessage);
verifyNoMoreInteractions(mListener);
}
@Test
@Config(minSdk = Build.VERSION_CODES.P)
public void testBiometricCallback_IgnoresHelp() {
final int helpCode = BiometricPrompt.ERROR_UNABLE_TO_PROCESS;
final String helpMessage = "Dolor sit amet";
mAuthenticationCallbackProvider.getBiometricCallback()
.onAuthenticationHelp(helpCode, helpMessage);
verifyZeroInteractions(mListener);
}
@Test
@Config(minSdk = Build.VERSION_CODES.P)
public void testBiometricCallback_HandlesFailure() {
mAuthenticationCallbackProvider.getBiometricCallback().onAuthenticationFailed();
verify(mListener).onFailure();
verifyNoMoreInteractions(mListener);
}
@SuppressWarnings("deprecation")
@Test
public void testFingerprintCallback_IsCached() {
final androidx.core.hardware.fingerprint.FingerprintManagerCompat.AuthenticationCallback
callback = mAuthenticationCallbackProvider.getFingerprintCallback();
assertThat(mAuthenticationCallbackProvider.getFingerprintCallback()).isEqualTo(callback);
}
@SuppressWarnings("deprecation")
@Test
public void testFingerprintCallback_HandlesSuccess() {
final androidx.core.hardware.fingerprint.FingerprintManagerCompat.CryptoObject crypto =
new androidx.core.hardware.fingerprint.FingerprintManagerCompat.CryptoObject(
mCipher);
final androidx.core.hardware.fingerprint.FingerprintManagerCompat.AuthenticationResult
result = new androidx.core.hardware.fingerprint.FingerprintManagerCompat
.AuthenticationResult(crypto);
mAuthenticationCallbackProvider.getFingerprintCallback().onAuthenticationSucceeded(result);
verify(mListener).onSuccess(mResultCaptor.capture());
verifyNoMoreInteractions(mListener);
assertThat(mResultCaptor.getValue().getCryptoObject()).isNotNull();
assertThat(mResultCaptor.getValue().getCryptoObject().getCipher()).isEqualTo(mCipher);
}
@Test
public void testFingerprintCallback_HandlesError() {
final int errorCode = BiometricPrompt.ERROR_CANCELED;
final String errorMessage = "Foo bar";
mAuthenticationCallbackProvider.getFingerprintCallback()
.onAuthenticationError(errorCode, errorMessage);
verify(mListener).onError(errorCode, errorMessage);
verifyNoMoreInteractions(mListener);
}
@Test
public void testFingerprintCallback_HandlesHelp() {
final int helpCode = BiometricPrompt.ERROR_TIMEOUT;
final String helpMessage = "Baz qux";
mAuthenticationCallbackProvider.getFingerprintCallback()
.onAuthenticationHelp(helpCode, helpMessage);
verify(mListener).onHelp(helpMessage);
verifyNoMoreInteractions(mListener);
}
@Test
public void testFingerprintCallback_HandlesFailure() {
mAuthenticationCallbackProvider.getFingerprintCallback().onAuthenticationFailed();
verify(mListener).onFailure();
verifyNoMoreInteractions(mListener);
}
}
| 2,424 |
338 | package com.tvd12.ezyfoxserver.setting;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@ToString
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "ssl-config")
public class EzySimpleSslConfigSetting implements EzySslConfigSetting {
@XmlElement(name = "file")
protected String file = "ssl-config.properties";
@XmlElement(name = "loader")
protected String loader = "com.tvd12.ezyfoxserver.ssl.EzySimpleSslConfigLoader";
@XmlElement(name = "context-factory-builder")
protected String contextFactoryBuilder = "com.tvd12.ezyfoxserver.ssl.EzySimpleSslContextFactoryBuilder";
@Override
public Map<Object, Object> toMap() {
Map<Object, Object> map = new HashMap<>();
map.put("file", file);
map.put("loader", loader);
map.put("contextFactoryBuilder", contextFactoryBuilder);
return map;
}
}
| 453 |
2,100 | /*
* Copyright (C) 2017 Google 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.google.gapid.util;
import com.google.common.collect.ImmutableMap;
import com.google.gapid.proto.stream.Stream;
import java.util.Map;
/**
* Data {@link Stream} utilities.
*/
public class Streams {
// U8 represents a 8-bit unsigned, integer.
public static final Stream.DataType U8 = newInt(false, 8);
// F10 represents a 10-bit unsigned floating-point number.
public static final Stream.DataType F10 = newFloat(false, 5, 5);
// F11 represents a 11-bit unsigned floating-point number.
public static final Stream.DataType F11 = newFloat(false, 5, 6);
// F16 represents a 16-bit signed, floating-point number.
public static final Stream.DataType F16 = newFloat(true, 5, 10);
// F32 represents a 32-bit signed, floating-point number.
public static final Stream.DataType F32 = newFloat(true, 7, 24);
// F64 represents a 64-bit signed, floating-point number.
public static final Stream.DataType F64 = newFloat(true, 10, 53);
// LINEAR is a Sampling state using a linear curve.
public static final Stream.Sampling LINEAR = Stream.Sampling.newBuilder()
.setCurve(Stream.Curve.Linear)
.build();
// LINEAR_NORMALIZED is a Sampling state using a linear curve with normalized sampling.
public static final Stream.Sampling LINEAR_NORMALIZED = Stream.Sampling.newBuilder()
.setCurve(Stream.Curve.Linear)
.setNormalized(true)
.build();
public static final Stream.Format FMT_XYZ_F32 = Stream.Format.newBuilder()
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.X)
.setDataType(F32)
.setSampling(LINEAR))
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Y)
.setDataType(F32)
.setSampling(LINEAR))
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Z)
.setDataType(F32)
.setSampling(LINEAR))
.build();
public static final Stream.Format FMT_RGBA_U8_NORM = Stream.Format.newBuilder()
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Red)
.setDataType(U8)
.setSampling(LINEAR_NORMALIZED))
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Green)
.setDataType(U8)
.setSampling(LINEAR_NORMALIZED))
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Blue)
.setDataType(U8)
.setSampling(LINEAR_NORMALIZED))
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Alpha)
.setDataType(U8)
.setSampling(LINEAR_NORMALIZED))
.build();
public static final Stream.Format FMT_RGBA_FLOAT = Stream.Format.newBuilder()
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Red)
.setDataType(F32)
.setSampling(LINEAR))
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Green)
.setDataType(F32)
.setSampling(LINEAR))
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Blue)
.setDataType(F32)
.setSampling(LINEAR))
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Alpha)
.setDataType(F32)
.setSampling(LINEAR))
.build();
public static final Stream.Format FMT_LUMINANCE_FLOAT = Stream.Format.newBuilder()
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Luminance)
.setDataType(F32)
.setSampling(LINEAR))
.build();
public static final Stream.Format FMT_DEPTH_U8_NORM = Stream.Format.newBuilder()
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Depth)
.setDataType(U8)
.setSampling(LINEAR_NORMALIZED))
.build();
public static final Stream.Format FMT_DEPTH_FLOAT = Stream.Format.newBuilder()
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Depth)
.setDataType(F32)
.setSampling(LINEAR))
.build();
public static final Stream.Format FMT_COUNT_U8 = Stream.Format.newBuilder()
.addComponents(Stream.Component.newBuilder()
.setChannel(Stream.Channel.Count)
.setDataType(U8)
.setSampling(LINEAR))
.build();
public static Stream.DataType newInt(boolean signed, int bits) {
return Stream.DataType.newBuilder()
.setSigned(signed)
.setInteger(Stream.Integer.newBuilder()
.setBits(bits)
).build();
}
public static Stream.DataType newFloat(boolean signed, int exponentBits, int mantissaBits) {
return Stream.DataType.newBuilder()
.setSigned(signed)
.setFloat(Stream.Float.newBuilder()
.setExponentBits(exponentBits)
.setMantissaBits(mantissaBits)
).build();
}
private static final Map<Stream.DataType, String> FIXED_DATATYPE_NAMES =
ImmutableMap.<Stream.DataType, String>builder()
.put(F10, "float10")
.put(F11, "float11")
.put(F16, "float16")
.put(F32, "float32")
.put(F64, "float64")
.build();
private Streams() {
}
public static String toString(Stream.Format format) {
StringBuilder sb = new StringBuilder();
int count = 0;
String lastType = null;
for (Stream.Component c : format.getComponentsList()) {
String type = toString(c.getDataType());
if (lastType == null || type.equals(lastType)) {
lastType = type;
count++;
} else {
append(sb, lastType, count).append(", ");
lastType = type;
count = 1;
}
}
if (lastType != null) {
append(sb, lastType, count);
}
return sb.toString();
}
private static StringBuilder append(StringBuilder sb, String type, int count) {
sb.append(type);
if (count > 1) {
sb.append(" vec").append(count);
}
return sb;
}
public static String toString(Stream.DataType type) {
String name = FIXED_DATATYPE_NAMES.get(type);
if (name != null) {
return name;
}
switch (type.getKindCase()) {
case FLOAT:
Stream.Float f = type.getFloat();
return "float" + (type.getSigned() ? "S" : "U") + f.getMantissaBits() + "E" + f.getExponentBits();
case FIXED:
Stream.Fixed x = type.getFixed();
return "fixed" + (type.getSigned() ? "S" : "U") + x.getIntegerBits() + "." + x.getFractionalBits();
case INTEGER:
Stream.Integer i = type.getInteger();
return (type.getSigned() ? "s" : "u") + "int" + i.getBits();
default:
return "unknown";
}
}
}
| 3,042 |
398 | # Copyright edalize contributors
# Licensed under the 2-Clause BSD License, see LICENSE for details.
# SPDX-License-Identifier: BSD-2-Clause
import logging
import os.path
from edalize.edatool import Edatool
logger = logging.getLogger(__name__)
class Radiant(Edatool):
argtypes = ['generic', 'vlogdefine', 'vlogparam']
@classmethod
def get_doc(cls, api_ver):
if api_ver == 0:
return {'description' : "Backend for Lattice Radiant",
'members' : [
{'name' : 'part',
'type' : 'String',
'desc' : 'FPGA part number (e.g. LIFCL-40-9BG400C)'},
]}
def configure_main(self):
(src_files, incdirs) = self._get_fileset_files()
pdc_file = None
prj_name = self.name.replace('.','_')
for f in src_files:
if f.file_type == 'PDC':
if pdc_file:
logger.warning("Multiple PDC files detected. Only the first one will be used")
else:
pdc_file = f.name
with open(os.path.join(self.work_root, self.name+'.tcl'), 'w') as f:
TCL_TEMPLATE = """#Generated by Edalize
prj_create -name {} -impl "impl" -dev {}
prj_set_impl_opt top {}
"""
f.write(TCL_TEMPLATE.format(prj_name,
self.tool_options['part'],
self.toplevel,
))
if incdirs:
_s = 'prj_set_impl_opt {include path} {'
_s += ' '.join(incdirs)
f.write(_s + '}\n')
if self.generic: # ?
_s = ';'.join(['{}={}'.format(k, v) for k,v in self.generic.items()])
f.write('prj_set_impl_opt HDL_PARAM {')
f.write(_s)
f.write('}\n')
if self.vlogparam:
_s = ';'.join(['{}={}'.format(k, self._param_value_str(v, '"')) for k,v in self.vlogparam.items()])
f.write('prj_set_impl_opt HDL_PARAM {')
f.write(_s)
f.write('}\n')
if self.vlogdefine:
_s = ";".join(['{}={}'.format(k,v) for k,v in self.vlogdefine.items()])
f.write('prj_set_impl_opt VERILOG_DIRECTIVES {')
f.write(_s)
f.write('}\n')
for src_file in src_files:
_s = self.src_file_filter(src_file)
if _s:
f.write(_s+'\n')
f.write('prj_save\nprj_close\n')
with open(os.path.join(self.work_root, self.name+'_run.tcl'), 'w') as f:
f.write("""#Generated by Edalize
prj_open {}.rdf
prj_run Synthesis -impl impl -forceOne
prj_run Map -impl impl
prj_run PAR -impl impl
prj_run Export -impl impl -task Bitgen
prj_save
prj_close
""".format(prj_name))
def src_file_filter(self, f):
def _work_source(f):
s = ' -work '
if f.logical_name:
s += f.logical_name
else:
s += "work"
return s
file_types = {
'verilogSource' : 'prj_add_source ',
'vhdlSource' : 'prj_add_source ',
'PDC' : 'prj_add_source ',
}
_file_type = f.file_type.split('-')[0]
if _file_type in file_types:
return file_types[_file_type] + f.name + _work_source(f)
elif _file_type == 'tclSource':
return "source " + f.name
elif _file_type in ['user', 'LPF']:
return ''
else:
_s = "{} has unknown file type '{}'"
logger.warning(_s.format(f.name,
f.file_type))
return ''
def build_main(self):
self._run_tool('radiantc', [self.name+'.tcl'], quiet=True)
self._run_tool('radiantc', [self.name+'_run.tcl'], quiet=True)
def run_main(self):
pass
| 2,237 |
14,668 | <filename>ash/public/cpp/external_arc/message_center/arc_notification_item.h
// Copyright 2016 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 ASH_PUBLIC_CPP_EXTERNAL_ARC_MESSAGE_CENTER_ARC_NOTIFICATION_ITEM_H_
#define ASH_PUBLIC_CPP_EXTERNAL_ARC_MESSAGE_CENTER_ARC_NOTIFICATION_ITEM_H_
#include "ash/components/arc/mojom/notifications.mojom.h"
#include "ui/gfx/image/image_skia.h"
namespace ash {
class ArcNotificationItem {
public:
class Observer {
public:
// Invoked when the notification data for this item has changed.
virtual void OnItemDestroying() = 0;
// Invoked when the type of the shown content is changed.
virtual void OnItemContentChanged(
arc::mojom::ArcNotificationShownContents content) {}
// Invoked when the remote input textbox on notification is activated or
// deactivated.
virtual void OnRemoteInputActivationChanged(bool activated) {}
protected:
virtual ~Observer() = default;
};
virtual ~ArcNotificationItem() = default;
// Called when the notification is closed on Android-side. This is called from
// ArcNotificationManager.
virtual void OnClosedFromAndroid() = 0;
// Called when the notification is updated on Android-side. This is called
// from ArcNotificationManager.
virtual void OnUpdatedFromAndroid(arc::mojom::ArcNotificationDataPtr data,
const std::string& app_id) = 0;
// Called when the notification is closed on Chrome-side. This is called from
// ArcNotificationDelegate.
virtual void Close(bool by_user) = 0;
// Called when the notification is clicked by user. This is called from
// ArcNotificationDelegate.
virtual void Click() = 0;
// Called when the user wants to open an intrinsic setting of notification.
// This is called from ArcNotificationContentView.
virtual void OpenSettings() = 0;
// Called when the user wants to open an intrinsic snooze setting of
// notification. This is called from ArcNotificationContentView.
virtual void OpenSnooze() = 0;
// Called when the user wants to toggle expansio of notification. This is
// called from ArcNotificationContentView.
virtual void ToggleExpansion() = 0;
// Called when the notification is activated i.e. starts accepting input for
// inline reply. Called from ArcNotificationContentView.
virtual void OnWindowActivated(bool activated) = 0;
// Called from ArcNotificationManager when the remote input textbox on
// notification is activated or deactivated.
virtual void OnRemoteInputActivationChanged(bool activate) = 0;
// Adds an observer.
virtual void AddObserver(Observer* observer) = 0;
// Removes the observer.
virtual void RemoveObserver(Observer* observer) = 0;
// Increments |window_ref_count_| and a CreateNotificationWindow request
// is sent when |window_ref_count_| goes from zero to one.
virtual void IncrementWindowRefCount() = 0;
// Decrements |window_ref_count_| and a CloseNotificationWindow request
// is sent when |window_ref_count_| goes from one to zero.
virtual void DecrementWindowRefCount() = 0;
// Returns the current snapshot.
virtual const gfx::ImageSkia& GetSnapshot() const = 0;
// Returns the current expand state.
virtual arc::mojom::ArcNotificationType GetNotificationType() const = 0;
// Returns the current expand state.
virtual arc::mojom::ArcNotificationExpandState GetExpandState() const = 0;
virtual bool IsManuallyExpandedOrCollapsed() const = 0;
// Cancel long press operation on Android side.
virtual void CancelPress() = 0;
// Returns the rect for which Android wants to handle all swipe events.
// Defaults to the empty rectangle.
virtual gfx::Rect GetSwipeInputRect() const = 0;
// Returns the notification key passed from Android-side.
virtual const std::string& GetNotificationKey() const = 0;
// Returns the notification ID used in the Chrome message center.
virtual const std::string& GetNotificationId() const = 0;
};
} // namespace ash
#endif // ASH_PUBLIC_CPP_EXTERNAL_ARC_MESSAGE_CENTER_ARC_NOTIFICATION_ITEM_H_
| 1,227 |
601 | package events;
public class Connected {
public Connected() {
}
}
| 27 |
348 | {"nom":"Notre-Dame-d'Epine","circ":"2ème circonscription","dpt":"Eure","inscrits":71,"abs":35,"votants":36,"blancs":0,"nuls":1,"exp":35,"res":[{"nuance":"REM","nom":"<NAME>","voix":22},{"nuance":"FN","nom":"M. <NAME>","voix":13}]} | 97 |
450 | //===- InterpreterPass.h --------------------------------------------------===//
//
// The ONNC Project
//
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef ONNC_NVDLAM_TASKSUBMIT_PASS_H
#define ONNC_NVDLAM_TASKSUBMIT_PASS_H
#include "NvDlaMeta.h"
#include "Version.h"
#include <onnc/Core/CustomPass.h>
namespace onnc {
class TargetBackend;
class NvDlaTaskSubmitPass : public CustomPass<NvDlaTaskSubmitPass>
{
public:
NvDlaTaskSubmitPass(NvDlaBackendMeta* pMeta, Version pDlaVersion, Version pEmuVersion);
ReturnType runOnModule(Module& pModule) override;
int submitEvent(int task_id, int event_type);
int submitMemAllocAddress(int size, std::string blob_name);
private:
NvDlaBackendMeta* m_pMeta;
const Version m_DlaVersion;
const Version m_EmuVersion;
};
} // namespace onnc
#endif
| 352 |
575 | // 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.
#include "ui/events/ozone/gamepad/gamepad_provider_ozone.h"
#include "base/macros.h"
#include "base/memory/singleton.h"
#include "ui/events/ozone/gamepad/gamepad_observer.h"
namespace ui {
GamepadProviderOzone::GamepadProviderOzone() {}
GamepadProviderOzone::~GamepadProviderOzone() {}
GamepadProviderOzone* GamepadProviderOzone::GetInstance() {
// GamepadProviderOzone is not holding any important resource. It's best to be
// leaky to reduce shutdown time.
return base::Singleton<
GamepadProviderOzone,
base::LeakySingletonTraits<GamepadProviderOzone>>::get();
}
void GamepadProviderOzone::DispatchGamepadDevicesUpdated(
std::vector<GamepadDevice> gamepad_devices) {
gamepad_devices_.swap(gamepad_devices);
for (auto& observer : observers_) {
observer.OnGamepadDevicesUpdated();
}
}
void GamepadProviderOzone::DispatchGamepadEvent(const GamepadEvent& event) {
for (auto& observer : observers_) {
observer.OnGamepadEvent(event);
}
}
void GamepadProviderOzone::AddGamepadObserver(GamepadObserver* observer) {
observers_.AddObserver(observer);
}
void GamepadProviderOzone::RemoveGamepadObserver(GamepadObserver* observer) {
observers_.RemoveObserver(observer);
}
std::vector<GamepadDevice> GamepadProviderOzone::GetGamepadDevices() {
return gamepad_devices_;
}
} // namespace ui
| 489 |
14,425 | <reponame>luoyuan3471/hadoop
/**
* 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.hadoop.yarn.server.resourcemanager.scheduler.capacity;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider;
import org.apache.hadoop.yarn.LocalConfigurationProvider;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.MockRM;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestQueueConfigurationAutoRefreshPolicy {
private Configuration configuration;
private MockRM rm = null;
private FileSystem fs;
private Path workingPath;
private Path workingPathRecover;
private Path fileSystemWorkingPath;
private Path tmpDir;
private QueueConfigurationAutoRefreshPolicy policy;
static {
YarnConfiguration.addDefaultResource(
YarnConfiguration.CS_CONFIGURATION_FILE);
YarnConfiguration.addDefaultResource(
YarnConfiguration.DR_CONFIGURATION_FILE);
}
@Before
public void setup() throws IOException {
QueueMetrics.clearQueueMetrics();
DefaultMetricsSystem.setMiniClusterMode(true);
configuration = new YarnConfiguration();
configuration.set(YarnConfiguration.RM_SCHEDULER,
CapacityScheduler.class.getCanonicalName());
fs = FileSystem.get(configuration);
workingPath = new Path(QueueConfigurationAutoRefreshPolicy.
class.getClassLoader().
getResource(".").toString());
workingPathRecover = new Path(QueueConfigurationAutoRefreshPolicy.
class.getClassLoader().
getResource(".").toString() + "/" + "Recover");
fileSystemWorkingPath =
new Path(new File("target", this.getClass().getSimpleName()
+ "-remoteDir").getAbsolutePath());
tmpDir = new Path(new File("target", this.getClass().getSimpleName()
+ "-tmpDir").getAbsolutePath());
fs.delete(fileSystemWorkingPath, true);
fs.mkdirs(fileSystemWorkingPath);
fs.delete(tmpDir, true);
fs.mkdirs(tmpDir);
policy =
new QueueConfigurationAutoRefreshPolicy();
}
private String writeConfigurationXML(Configuration conf, String confXMLName)
throws IOException {
DataOutputStream output = null;
try {
final File confFile = new File(tmpDir.toString(), confXMLName);
if (confFile.exists()) {
confFile.delete();
}
if (!confFile.createNewFile()) {
Assert.fail("Can not create " + confXMLName);
}
output = new DataOutputStream(
new FileOutputStream(confFile));
conf.writeXml(output);
return confFile.getAbsolutePath();
} finally {
if (output != null) {
output.close();
}
}
}
private void uploadConfiguration(Boolean isFileSystemBased,
Configuration conf, String confFileName)
throws IOException {
String csConfFile = writeConfigurationXML(conf, confFileName);
if (isFileSystemBased) {
// upload the file into Remote File System
uploadToRemoteFileSystem(new Path(csConfFile),
fileSystemWorkingPath);
} else {
// upload the file into Work Path for Local File
uploadToRemoteFileSystem(new Path(csConfFile),
workingPath);
}
}
private void uploadToRemoteFileSystem(Path filePath, Path remotePath)
throws IOException {
fs.copyFromLocalFile(filePath, remotePath);
}
private void uploadDefaultConfiguration(Boolean
isFileSystemBased) throws IOException {
Configuration conf = new Configuration();
uploadConfiguration(isFileSystemBased,
conf, "core-site.xml");
YarnConfiguration yarnConf = new YarnConfiguration();
uploadConfiguration(isFileSystemBased,
yarnConf, "yarn-site.xml");
CapacitySchedulerConfiguration csConf =
new CapacitySchedulerConfiguration();
uploadConfiguration(isFileSystemBased,
csConf, "capacity-scheduler.xml");
Configuration hadoopPolicyConf = new Configuration(false);
hadoopPolicyConf
.addResource(YarnConfiguration.HADOOP_POLICY_CONFIGURATION_FILE);
uploadConfiguration(isFileSystemBased,
hadoopPolicyConf, "hadoop-policy.xml");
}
@Test
public void testFileSystemBasedEditSchedule() throws Exception {
// Test FileSystemBasedConfigurationProvider scheduled
testCommon(true);
}
@Test
public void testLocalFileBasedEditSchedule() throws Exception {
// Prepare for recover for local file default.
fs.mkdirs(workingPath);
fs.copyFromLocalFile(new Path(workingPath.toString()
+ "/" + YarnConfiguration.CORE_SITE_CONFIGURATION_FILE),
new Path(workingPathRecover.toString()
+ "/" + YarnConfiguration.CORE_SITE_CONFIGURATION_FILE));
fs.copyFromLocalFile(new Path(workingPath.toString()
+ "/" + YarnConfiguration.YARN_SITE_CONFIGURATION_FILE),
new Path(workingPathRecover.toString()
+ "/" + YarnConfiguration.YARN_SITE_CONFIGURATION_FILE));
fs.copyFromLocalFile(new Path(workingPath.toString()
+ "/" + YarnConfiguration.CS_CONFIGURATION_FILE),
new Path(workingPathRecover.toString()
+ "/" + YarnConfiguration.CS_CONFIGURATION_FILE));
// Test LocalConfigurationProvider scheduled
testCommon(false);
// Recover for recover for local file default.
fs.copyFromLocalFile(new Path(workingPathRecover.toString()
+ "/" + YarnConfiguration.CORE_SITE_CONFIGURATION_FILE),
new Path(workingPath.toString()
+ "/" + YarnConfiguration.CORE_SITE_CONFIGURATION_FILE));
fs.copyFromLocalFile(new Path(workingPathRecover.toString()
+ "/" + YarnConfiguration.YARN_SITE_CONFIGURATION_FILE),
new Path(workingPath.toString()
+ "/" + YarnConfiguration.YARN_SITE_CONFIGURATION_FILE));
fs.copyFromLocalFile(new Path(workingPathRecover.toString()
+ "/" + YarnConfiguration.CS_CONFIGURATION_FILE),
new Path(workingPath.toString()
+ "/" + YarnConfiguration.CS_CONFIGURATION_FILE));
fs.delete(workingPathRecover, true);
}
public void testCommon(Boolean isFileSystemBased) throws Exception {
// Set auto refresh interval to 1s
configuration.setLong(CapacitySchedulerConfiguration.
QUEUE_AUTO_REFRESH_MONITORING_INTERVAL,
1000L);
if (isFileSystemBased) {
configuration.set(YarnConfiguration.FS_BASED_RM_CONF_STORE,
fileSystemWorkingPath.toString());
}
//upload default configurations
uploadDefaultConfiguration(isFileSystemBased);
if (isFileSystemBased) {
configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS,
FileSystemBasedConfigurationProvider.class.getCanonicalName());
} else {
configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS,
LocalConfigurationProvider.class.getCanonicalName());
}
// upload the auto refresh related configurations
uploadConfiguration(isFileSystemBased,
configuration, "yarn-site.xml");
uploadConfiguration(isFileSystemBased,
configuration, "capacity-scheduler.xml");
rm = new MockRM(configuration);
rm.init(configuration);
policy.init(configuration,
rm.getRMContext(),
rm.getResourceScheduler());
rm.start();
CapacityScheduler cs =
(CapacityScheduler) rm.getRMContext().getScheduler();
int maxAppsBefore = cs.getConfiguration().getMaximumSystemApplications();
CapacitySchedulerConfiguration csConf =
new CapacitySchedulerConfiguration();
csConf.setInt(CapacitySchedulerConfiguration.MAXIMUM_SYSTEM_APPLICATIONS,
5000);
uploadConfiguration(isFileSystemBased,
csConf, "capacity-scheduler.xml");
// Refreshed first time.
policy.editSchedule();
// Make sure refresh successfully.
Assert.assertFalse(policy.getLastReloadAttemptFailed());
long oldModified = policy.getLastModified();
long oldSuccess = policy.getLastReloadAttempt();
Assert.assertTrue(oldSuccess > oldModified);
int maxAppsAfter = cs.getConfiguration().getMaximumSystemApplications();
Assert.assertEquals(maxAppsAfter, 5000);
Assert.assertTrue(maxAppsAfter != maxAppsBefore);
// Trigger interval for refresh.
GenericTestUtils.waitFor(() -> (policy.getClock().getTime() -
policy.getLastReloadAttempt()) / 1000 > 1,
500, 3000);
// Upload for modified.
csConf.setInt(CapacitySchedulerConfiguration.MAXIMUM_SYSTEM_APPLICATIONS,
3000);
uploadConfiguration(isFileSystemBased,
csConf, "capacity-scheduler.xml");
policy.editSchedule();
// Wait for triggered refresh.
GenericTestUtils.waitFor(() -> policy.getLastReloadAttempt() >
policy.getLastModified(),
500, 3000);
// Make sure refresh successfully.
Assert.assertFalse(policy.getLastReloadAttemptFailed());
oldModified = policy.getLastModified();
oldSuccess = policy.getLastReloadAttempt();
Assert.assertTrue(oldSuccess > oldModified);
Assert.assertEquals(cs.getConfiguration().
getMaximumSystemApplications(), 3000);
// Trigger interval for refresh.
GenericTestUtils.waitFor(() -> (policy.getClock().getTime() -
policy.getLastReloadAttempt()) / 1000 > 1,
500, 3000);
// Without modified
policy.editSchedule();
Assert.assertEquals(oldModified,
policy.getLastModified());
Assert.assertEquals(oldSuccess,
policy.getLastReloadAttempt());
}
@After
public void tearDown() throws IOException {
if (rm != null) {
rm.stop();
}
fs.delete(fileSystemWorkingPath, true);
fs.delete(tmpDir, true);
}
}
| 3,799 |
1,206 | """
The MIT License (MIT)
Copyright (C) 2017 <NAME> (<EMAIL>)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
# pylint: disable=unused-import
from typing import Dict, List, Set, Sequence, Tuple, Iterable # noqa: F401
from typing import Callable, Optional, Union, Any # noqa: F401
from ssh_audit.ssh1 import SSH1
from ssh_audit.readbuf import ReadBuf
from ssh_audit.utils import Utils
from ssh_audit.writebuf import WriteBuf
class SSH1_PublicKeyMessage:
def __init__(self, cookie: bytes, skey: Tuple[int, int, int], hkey: Tuple[int, int, int], pflags: int, cmask: int, amask: int) -> None:
if len(skey) != 3:
raise ValueError('invalid server key pair: {}'.format(skey))
if len(hkey) != 3:
raise ValueError('invalid host key pair: {}'.format(hkey))
self.__cookie = cookie
self.__server_key = skey
self.__host_key = hkey
self.__protocol_flags = pflags
self.__supported_ciphers_mask = cmask
self.__supported_authentications_mask = amask
@property
def cookie(self) -> bytes:
return self.__cookie
@property
def server_key_bits(self) -> int:
return self.__server_key[0]
@property
def server_key_public_exponent(self) -> int:
return self.__server_key[1]
@property
def server_key_public_modulus(self) -> int:
return self.__server_key[2]
@property
def host_key_bits(self) -> int:
return self.__host_key[0]
@property
def host_key_public_exponent(self) -> int:
return self.__host_key[1]
@property
def host_key_public_modulus(self) -> int:
return self.__host_key[2]
@property
def host_key_fingerprint_data(self) -> bytes:
# pylint: disable=protected-access
mod = WriteBuf._create_mpint(self.host_key_public_modulus, False)
e = WriteBuf._create_mpint(self.host_key_public_exponent, False)
return mod + e
@property
def protocol_flags(self) -> int:
return self.__protocol_flags
@property
def supported_ciphers_mask(self) -> int:
return self.__supported_ciphers_mask
@property
def supported_ciphers(self) -> List[str]:
ciphers = []
for i in range(len(SSH1.CIPHERS)): # pylint: disable=consider-using-enumerate
if self.__supported_ciphers_mask & (1 << i) != 0:
ciphers.append(Utils.to_text(SSH1.CIPHERS[i]))
return ciphers
@property
def supported_authentications_mask(self) -> int:
return self.__supported_authentications_mask
@property
def supported_authentications(self) -> List[str]:
auths = []
for i in range(1, len(SSH1.AUTHS)):
if self.__supported_authentications_mask & (1 << i) != 0:
auths.append(Utils.to_text(SSH1.AUTHS[i]))
return auths
def write(self, wbuf: 'WriteBuf') -> None:
wbuf.write(self.cookie)
wbuf.write_int(self.server_key_bits)
wbuf.write_mpint1(self.server_key_public_exponent)
wbuf.write_mpint1(self.server_key_public_modulus)
wbuf.write_int(self.host_key_bits)
wbuf.write_mpint1(self.host_key_public_exponent)
wbuf.write_mpint1(self.host_key_public_modulus)
wbuf.write_int(self.protocol_flags)
wbuf.write_int(self.supported_ciphers_mask)
wbuf.write_int(self.supported_authentications_mask)
@property
def payload(self) -> bytes:
wbuf = WriteBuf()
self.write(wbuf)
return wbuf.write_flush()
@classmethod
def parse(cls, payload: bytes) -> 'SSH1_PublicKeyMessage':
buf = ReadBuf(payload)
cookie = buf.read(8)
server_key_bits = buf.read_int()
server_key_exponent = buf.read_mpint1()
server_key_modulus = buf.read_mpint1()
skey = (server_key_bits, server_key_exponent, server_key_modulus)
host_key_bits = buf.read_int()
host_key_exponent = buf.read_mpint1()
host_key_modulus = buf.read_mpint1()
hkey = (host_key_bits, host_key_exponent, host_key_modulus)
pflags = buf.read_int()
cmask = buf.read_int()
amask = buf.read_int()
pkm = cls(cookie, skey, hkey, pflags, cmask, amask)
return pkm
| 2,188 |
1,679 | <reponame>andysan/loramac-node
/*!
* \file sx1272Regs-LoRa.h
*
* \brief SX1272 LoRa modem registers and bits definitions
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* \endcode
*
* \author <NAME> ( Semtech )
*
* \author <NAME> ( Semtech )
*/
#ifndef __SX1272_REGS_LORA_H__
#define __SX1272_REGS_LORA_H__
#ifdef __cplusplus
extern "C"
{
#endif
/*!
* ============================================================================
* SX1272 Internal registers Address
* ============================================================================
*/
#define REG_LR_FIFO 0x00
// Common settings
#define REG_LR_OPMODE 0x01
#define REG_LR_FRFMSB 0x06
#define REG_LR_FRFMID 0x07
#define REG_LR_FRFLSB 0x08
// Tx settings
#define REG_LR_PACONFIG 0x09
#define REG_LR_PARAMP 0x0A
#define REG_LR_OCP 0x0B
// Rx settings
#define REG_LR_LNA 0x0C
// LoRa registers
#define REG_LR_FIFOADDRPTR 0x0D
#define REG_LR_FIFOTXBASEADDR 0x0E
#define REG_LR_FIFORXBASEADDR 0x0F
#define REG_LR_FIFORXCURRENTADDR 0x10
#define REG_LR_IRQFLAGSMASK 0x11
#define REG_LR_IRQFLAGS 0x12
#define REG_LR_RXNBBYTES 0x13
#define REG_LR_RXHEADERCNTVALUEMSB 0x14
#define REG_LR_RXHEADERCNTVALUELSB 0x15
#define REG_LR_RXPACKETCNTVALUEMSB 0x16
#define REG_LR_RXPACKETCNTVALUELSB 0x17
#define REG_LR_MODEMSTAT 0x18
#define REG_LR_PKTSNRVALUE 0x19
#define REG_LR_PKTRSSIVALUE 0x1A
#define REG_LR_RSSIVALUE 0x1B
#define REG_LR_HOPCHANNEL 0x1C
#define REG_LR_MODEMCONFIG1 0x1D
#define REG_LR_MODEMCONFIG2 0x1E
#define REG_LR_SYMBTIMEOUTLSB 0x1F
#define REG_LR_PREAMBLEMSB 0x20
#define REG_LR_PREAMBLELSB 0x21
#define REG_LR_PAYLOADLENGTH 0x22
#define REG_LR_PAYLOADMAXLENGTH 0x23
#define REG_LR_HOPPERIOD 0x24
#define REG_LR_FIFORXBYTEADDR 0x25
#define REG_LR_FEIMSB 0x28
#define REG_LR_FEIMID 0x29
#define REG_LR_FEILSB 0x2A
#define REG_LR_RSSIWIDEBAND 0x2C
#define REG_LR_DETECTOPTIMIZE 0x31
#define REG_LR_INVERTIQ 0x33
#define REG_LR_DETECTIONTHRESHOLD 0x37
#define REG_LR_SYNCWORD 0x39
#define REG_LR_INVERTIQ2 0x3B
// end of documented register in datasheet
// I/O settings
#define REG_LR_DIOMAPPING1 0x40
#define REG_LR_DIOMAPPING2 0x41
// Version
#define REG_LR_VERSION 0x42
// Additional settings
#define REG_LR_AGCREF 0x43
#define REG_LR_AGCTHRESH1 0x44
#define REG_LR_AGCTHRESH2 0x45
#define REG_LR_AGCTHRESH3 0x46
#define REG_LR_PLLHOP 0x4B
#define REG_LR_TCXO 0x58
#define REG_LR_PADAC 0x5A
#define REG_LR_PLL 0x5C
#define REG_LR_PLLLOWPN 0x5E
#define REG_LR_FORMERTEMP 0x6C
/*!
* ============================================================================
* SX1272 LoRa bits control definition
* ============================================================================
*/
/*!
* RegFifo
*/
/*!
* RegOpMode
*/
#define RFLR_OPMODE_LONGRANGEMODE_MASK 0x7F
#define RFLR_OPMODE_LONGRANGEMODE_OFF 0x00 // Default
#define RFLR_OPMODE_LONGRANGEMODE_ON 0x80
#define RFLR_OPMODE_ACCESSSHAREDREG_MASK 0xBF
#define RFLR_OPMODE_ACCESSSHAREDREG_ENABLE 0x40
#define RFLR_OPMODE_ACCESSSHAREDREG_DISABLE 0x00 // Default
#define RFLR_OPMODE_MASK 0xF8
#define RFLR_OPMODE_SLEEP 0x00
#define RFLR_OPMODE_STANDBY 0x01 // Default
#define RFLR_OPMODE_SYNTHESIZER_TX 0x02
#define RFLR_OPMODE_TRANSMITTER 0x03
#define RFLR_OPMODE_SYNTHESIZER_RX 0x04
#define RFLR_OPMODE_RECEIVER 0x05
// LoRa specific modes
#define RFLR_OPMODE_RECEIVER_SINGLE 0x06
#define RFLR_OPMODE_CAD 0x07
/*!
* RegFrf (MHz)
*/
#define RFLR_FRFMSB_915_MHZ 0xE4 // Default
#define RFLR_FRFMID_915_MHZ 0xC0 // Default
#define RFLR_FRFLSB_915_MHZ 0x00 // Default
/*!
* RegPaConfig
*/
#define RFLR_PACONFIG_PASELECT_MASK 0x7F
#define RFLR_PACONFIG_PASELECT_PABOOST 0x80
#define RFLR_PACONFIG_PASELECT_RFO 0x00 // Default
#define RFLR_PACONFIG_OUTPUTPOWER_MASK 0xF0
/*!
* RegPaRamp
*/
#define RFLR_PARAMP_LOWPNTXPLL_MASK 0xE0
#define RFLR_PARAMP_LOWPNTXPLL_OFF 0x10 // Default
#define RFLR_PARAMP_LOWPNTXPLL_ON 0x00
#define RFLR_PARAMP_MASK 0xF0
#define RFLR_PARAMP_3400_US 0x00
#define RFLR_PARAMP_2000_US 0x01
#define RFLR_PARAMP_1000_US 0x02
#define RFLR_PARAMP_0500_US 0x03
#define RFLR_PARAMP_0250_US 0x04
#define RFLR_PARAMP_0125_US 0x05
#define RFLR_PARAMP_0100_US 0x06
#define RFLR_PARAMP_0062_US 0x07
#define RFLR_PARAMP_0050_US 0x08
#define RFLR_PARAMP_0040_US 0x09 // Default
#define RFLR_PARAMP_0031_US 0x0A
#define RFLR_PARAMP_0025_US 0x0B
#define RFLR_PARAMP_0020_US 0x0C
#define RFLR_PARAMP_0015_US 0x0D
#define RFLR_PARAMP_0012_US 0x0E
#define RFLR_PARAMP_0010_US 0x0F
/*!
* RegOcp
*/
#define RFLR_OCP_MASK 0xDF
#define RFLR_OCP_ON 0x20 // Default
#define RFLR_OCP_OFF 0x00
#define RFLR_OCP_TRIM_MASK 0xE0
#define RFLR_OCP_TRIM_045_MA 0x00
#define RFLR_OCP_TRIM_050_MA 0x01
#define RFLR_OCP_TRIM_055_MA 0x02
#define RFLR_OCP_TRIM_060_MA 0x03
#define RFLR_OCP_TRIM_065_MA 0x04
#define RFLR_OCP_TRIM_070_MA 0x05
#define RFLR_OCP_TRIM_075_MA 0x06
#define RFLR_OCP_TRIM_080_MA 0x07
#define RFLR_OCP_TRIM_085_MA 0x08
#define RFLR_OCP_TRIM_090_MA 0x09
#define RFLR_OCP_TRIM_095_MA 0x0A
#define RFLR_OCP_TRIM_100_MA 0x0B // Default
#define RFLR_OCP_TRIM_105_MA 0x0C
#define RFLR_OCP_TRIM_110_MA 0x0D
#define RFLR_OCP_TRIM_115_MA 0x0E
#define RFLR_OCP_TRIM_120_MA 0x0F
#define RFLR_OCP_TRIM_130_MA 0x10
#define RFLR_OCP_TRIM_140_MA 0x11
#define RFLR_OCP_TRIM_150_MA 0x12
#define RFLR_OCP_TRIM_160_MA 0x13
#define RFLR_OCP_TRIM_170_MA 0x14
#define RFLR_OCP_TRIM_180_MA 0x15
#define RFLR_OCP_TRIM_190_MA 0x16
#define RFLR_OCP_TRIM_200_MA 0x17
#define RFLR_OCP_TRIM_210_MA 0x18
#define RFLR_OCP_TRIM_220_MA 0x19
#define RFLR_OCP_TRIM_230_MA 0x1A
#define RFLR_OCP_TRIM_240_MA 0x1B
/*!
* RegLna
*/
#define RFLR_LNA_GAIN_MASK 0x1F
#define RFLR_LNA_GAIN_G1 0x20 // Default
#define RFLR_LNA_GAIN_G2 0x40
#define RFLR_LNA_GAIN_G3 0x60
#define RFLR_LNA_GAIN_G4 0x80
#define RFLR_LNA_GAIN_G5 0xA0
#define RFLR_LNA_GAIN_G6 0xC0
#define RFLR_LNA_BOOST_MASK 0xFC
#define RFLR_LNA_BOOST_OFF 0x00 // Default
#define RFLR_LNA_BOOST_ON 0x03
/*!
* RegFifoAddrPtr
*/
#define RFLR_FIFOADDRPTR 0x00 // Default
/*!
* RegFifoTxBaseAddr
*/
#define RFLR_FIFOTXBASEADDR 0x80 // Default
/*!
* RegFifoTxBaseAddr
*/
#define RFLR_FIFORXBASEADDR 0x00 // Default
/*!
* RegFifoRxCurrentAddr (Read Only)
*/
/*!
* RegIrqFlagsMask
*/
#define RFLR_IRQFLAGS_RXTIMEOUT_MASK 0x80
#define RFLR_IRQFLAGS_RXDONE_MASK 0x40
#define RFLR_IRQFLAGS_PAYLOADCRCERROR_MASK 0x20
#define RFLR_IRQFLAGS_VALIDHEADER_MASK 0x10
#define RFLR_IRQFLAGS_TXDONE_MASK 0x08
#define RFLR_IRQFLAGS_CADDONE_MASK 0x04
#define RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL_MASK 0x02
#define RFLR_IRQFLAGS_CADDETECTED_MASK 0x01
/*!
* RegIrqFlags
*/
#define RFLR_IRQFLAGS_RXTIMEOUT 0x80
#define RFLR_IRQFLAGS_RXDONE 0x40
#define RFLR_IRQFLAGS_PAYLOADCRCERROR 0x20
#define RFLR_IRQFLAGS_VALIDHEADER 0x10
#define RFLR_IRQFLAGS_TXDONE 0x08
#define RFLR_IRQFLAGS_CADDONE 0x04
#define RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL 0x02
#define RFLR_IRQFLAGS_CADDETECTED 0x01
/*!
* RegFifoRxNbBytes (Read Only)
*/
/*!
* RegRxHeaderCntValueMsb (Read Only)
*/
/*!
* RegRxHeaderCntValueLsb (Read Only)
*/
/*!
* RegRxPacketCntValueMsb (Read Only)
*/
/*!
* RegRxPacketCntValueLsb (Read Only)
*/
/*!
* RegModemStat (Read Only)
*/
#define RFLR_MODEMSTAT_RX_CR_MASK 0x1F
#define RFLR_MODEMSTAT_MODEM_STATUS_MASK 0xE0
/*!
* RegPktSnrValue (Read Only)
*/
/*!
* RegPktRssiValue (Read Only)
*/
/*!
* RegRssiValue (Read Only)
*/
/*!
* RegHopChannel (Read Only)
*/
#define RFLR_HOPCHANNEL_PLL_LOCK_TIMEOUT_MASK 0x7F
#define RFLR_HOPCHANNEL_PLL_LOCK_FAIL 0x80
#define RFLR_HOPCHANNEL_PLL_LOCK_SUCCEED 0x00 // Default
#define RFLR_HOPCHANNEL_CRCONPAYLOAD_MASK 0xBF
#define RFLR_HOPCHANNEL_CRCONPAYLOAD_ON 0x40
#define RFLR_HOPCHANNEL_CRCONPAYLOAD_OFF 0x00 // Default
#define RFLR_HOPCHANNEL_CHANNEL_MASK 0x3F
/*!
* RegModemConfig1
*/
#define RFLR_MODEMCONFIG1_BW_MASK 0x3F
#define RFLR_MODEMCONFIG1_BW_125_KHZ 0x00 // Default
#define RFLR_MODEMCONFIG1_BW_250_KHZ 0x40
#define RFLR_MODEMCONFIG1_BW_500_KHZ 0x80
#define RFLR_MODEMCONFIG1_CODINGRATE_MASK 0xC7
#define RFLR_MODEMCONFIG1_CODINGRATE_4_5 0x08
#define RFLR_MODEMCONFIG1_CODINGRATE_4_6 0x10 // Default
#define RFLR_MODEMCONFIG1_CODINGRATE_4_7 0x18
#define RFLR_MODEMCONFIG1_CODINGRATE_4_8 0x20
#define RFLR_MODEMCONFIG1_IMPLICITHEADER_MASK 0xFB
#define RFLR_MODEMCONFIG1_IMPLICITHEADER_ON 0x04
#define RFLR_MODEMCONFIG1_IMPLICITHEADER_OFF 0x00 // Default
#define RFLR_MODEMCONFIG1_RXPAYLOADCRC_MASK 0xFD
#define RFLR_MODEMCONFIG1_RXPAYLOADCRC_ON 0x02
#define RFLR_MODEMCONFIG1_RXPAYLOADCRC_OFF 0x00 // Default
#define RFLR_MODEMCONFIG1_LOWDATARATEOPTIMIZE_MASK 0xFE
#define RFLR_MODEMCONFIG1_LOWDATARATEOPTIMIZE_ON 0x01
#define RFLR_MODEMCONFIG1_LOWDATARATEOPTIMIZE_OFF 0x00 // Default
/*!
* RegModemConfig2
*/
#define RFLR_MODEMCONFIG2_SF_MASK 0x0F
#define RFLR_MODEMCONFIG2_SF_6 0x60
#define RFLR_MODEMCONFIG2_SF_7 0x70 // Default
#define RFLR_MODEMCONFIG2_SF_8 0x80
#define RFLR_MODEMCONFIG2_SF_9 0x90
#define RFLR_MODEMCONFIG2_SF_10 0xA0
#define RFLR_MODEMCONFIG2_SF_11 0xB0
#define RFLR_MODEMCONFIG2_SF_12 0xC0
#define RFLR_MODEMCONFIG2_TXCONTINUOUSMODE_MASK 0xF7
#define RFLR_MODEMCONFIG2_TXCONTINUOUSMODE_ON 0x08
#define RFLR_MODEMCONFIG2_TXCONTINUOUSMODE_OFF 0x00
#define RFLR_MODEMCONFIG2_AGCAUTO_MASK 0xFB
#define RFLR_MODEMCONFIG2_AGCAUTO_ON 0x04 // Default
#define RFLR_MODEMCONFIG2_AGCAUTO_OFF 0x00
#define RFLR_MODEMCONFIG2_SYMBTIMEOUTMSB_MASK 0xFC
#define RFLR_MODEMCONFIG2_SYMBTIMEOUTMSB 0x00 // Default
/*!
* RegSymbTimeoutLsb
*/
#define RFLR_SYMBTIMEOUTLSB_SYMBTIMEOUT 0x64 // Default
/*!
* RegPreambleLengthMsb
*/
#define RFLR_PREAMBLELENGTHMSB 0x00 // Default
/*!
* RegPreambleLengthLsb
*/
#define RFLR_PREAMBLELENGTHLSB 0x08 // Default
/*!
* RegPayloadLength
*/
#define RFLR_PAYLOADLENGTH 0x0E // Default
/*!
* RegPayloadMaxLength
*/
#define RFLR_PAYLOADMAXLENGTH 0xFF // Default
/*!
* RegHopPeriod
*/
#define RFLR_HOPPERIOD_FREQFOPPINGPERIOD 0x00 // Default
/*!
* RegFifoRxByteAddr (Read Only)
*/
/*!
* RegFeiMsb (Read Only)
*/
/*!
* RegFeiMid (Read Only)
*/
/*!
* RegFeiLsb (Read Only)
*/
/*!
* RegRssiWideband (Read Only)
*/
/*!
* RegDetectOptimize
*/
#define RFLR_DETECTIONOPTIMIZE_MASK 0xF8
#define RFLR_DETECTIONOPTIMIZE_SF7_TO_SF12 0x03 // Default
#define RFLR_DETECTIONOPTIMIZE_SF6 0x05
/*!
* RegInvertIQ
*/
#define RFLR_INVERTIQ_RX_MASK 0xBF
#define RFLR_INVERTIQ_RX_OFF 0x00
#define RFLR_INVERTIQ_RX_ON 0x40
#define RFLR_INVERTIQ_TX_MASK 0xFE
#define RFLR_INVERTIQ_TX_OFF 0x01
#define RFLR_INVERTIQ_TX_ON 0x00
/*!
* RegDetectionThreshold
*/
#define RFLR_DETECTIONTHRESH_SF7_TO_SF12 0x0A // Default
#define RFLR_DETECTIONTHRESH_SF6 0x0C
/*!
* RegInvertIQ2
*/
#define RFLR_INVERTIQ2_ON 0x19
#define RFLR_INVERTIQ2_OFF 0x1D
/*!
* RegDioMapping1
*/
#define RFLR_DIOMAPPING1_DIO0_MASK 0x3F
#define RFLR_DIOMAPPING1_DIO0_00 0x00 // Default
#define RFLR_DIOMAPPING1_DIO0_01 0x40
#define RFLR_DIOMAPPING1_DIO0_10 0x80
#define RFLR_DIOMAPPING1_DIO0_11 0xC0
#define RFLR_DIOMAPPING1_DIO1_MASK 0xCF
#define RFLR_DIOMAPPING1_DIO1_00 0x00 // Default
#define RFLR_DIOMAPPING1_DIO1_01 0x10
#define RFLR_DIOMAPPING1_DIO1_10 0x20
#define RFLR_DIOMAPPING1_DIO1_11 0x30
#define RFLR_DIOMAPPING1_DIO2_MASK 0xF3
#define RFLR_DIOMAPPING1_DIO2_00 0x00 // Default
#define RFLR_DIOMAPPING1_DIO2_01 0x04
#define RFLR_DIOMAPPING1_DIO2_10 0x08
#define RFLR_DIOMAPPING1_DIO2_11 0x0C
#define RFLR_DIOMAPPING1_DIO3_MASK 0xFC
#define RFLR_DIOMAPPING1_DIO3_00 0x00 // Default
#define RFLR_DIOMAPPING1_DIO3_01 0x01
#define RFLR_DIOMAPPING1_DIO3_10 0x02
#define RFLR_DIOMAPPING1_DIO3_11 0x03
/*!
* RegDioMapping2
*/
#define RFLR_DIOMAPPING2_DIO4_MASK 0x3F
#define RFLR_DIOMAPPING2_DIO4_00 0x00 // Default
#define RFLR_DIOMAPPING2_DIO4_01 0x40
#define RFLR_DIOMAPPING2_DIO4_10 0x80
#define RFLR_DIOMAPPING2_DIO4_11 0xC0
#define RFLR_DIOMAPPING2_DIO5_MASK 0xCF
#define RFLR_DIOMAPPING2_DIO5_00 0x00 // Default
#define RFLR_DIOMAPPING2_DIO5_01 0x10
#define RFLR_DIOMAPPING2_DIO5_10 0x20
#define RFLR_DIOMAPPING2_DIO5_11 0x30
#define RFLR_DIOMAPPING2_MAP_MASK 0xFE
#define RFLR_DIOMAPPING2_MAP_PREAMBLEDETECT 0x01
#define RFLR_DIOMAPPING2_MAP_RSSI 0x00 // Default
/*!
* RegVersion (Read Only)
*/
/*!
* RegAgcRef
*/
/*!
* RegAgcThresh1
*/
/*!
* RegAgcThresh2
*/
/*!
* RegAgcThresh3
*/
/*!
* RegPllHop
*/
#define RFLR_PLLHOP_FASTHOP_MASK 0x7F
#define RFLR_PLLHOP_FASTHOP_ON 0x80
#define RFLR_PLLHOP_FASTHOP_OFF 0x00 // Default
/*!
* RegTcxo
*/
#define RFLR_TCXO_TCXOINPUT_MASK 0xEF
#define RFLR_TCXO_TCXOINPUT_ON 0x10
#define RFLR_TCXO_TCXOINPUT_OFF 0x00 // Default
/*!
* RegPaDac
*/
#define RFLR_PADAC_20DBM_MASK 0xF8
#define RFLR_PADAC_20DBM_ON 0x07
#define RFLR_PADAC_20DBM_OFF 0x04 // Default
/*!
* RegPll
*/
#define RFLR_PLL_BANDWIDTH_MASK 0x3F
#define RFLR_PLL_BANDWIDTH_75 0x00
#define RFLR_PLL_BANDWIDTH_150 0x40
#define RFLR_PLL_BANDWIDTH_225 0x80
#define RFLR_PLL_BANDWIDTH_300 0xC0 // Default
/*!
* RegPllLowPn
*/
#define RFLR_PLLLOWPN_BANDWIDTH_MASK 0x3F
#define RFLR_PLLLOWPN_BANDWIDTH_75 0x00
#define RFLR_PLLLOWPN_BANDWIDTH_150 0x40
#define RFLR_PLLLOWPN_BANDWIDTH_225 0x80
#define RFLR_PLLLOWPN_BANDWIDTH_300 0xC0 // Default
/*!
* RegFormerTemp
*/
#ifdef __cplusplus
}
#endif
#endif // __SX1272_REGS_LORA_H__
| 12,901 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <AzTest/AzTest.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <AzCore/Component/ComponentApplication.h>
#include <Mocks/IRendererMock.h>
#include <Mocks/I3DEngineMock.h>
#include "Mocks/ISystemMock.h"
#include <Shape/PolygonPrismShapeComponent.h>
#include <AzFramework/Components/TransformComponent.h>
#include <LmbrCentral/Rendering/ClipVolumeComponentBus.h>
#include <Rendering/ClipVolumeComponent.h>
namespace UnitTest
{
class ClipVolumeComponentTests
: public UnitTest::AllocatorsTestFixture
, public LmbrCentral::ClipVolumeComponentNotificationBus::Handler
{
public:
ClipVolumeComponentTests()
: AllocatorsTestFixture()
{}
protected:
void SetUp() override
{
AllocatorsTestFixture::SetUp();
m_priorEnv = gEnv;
m_data.reset(new DataMembers);
memset(&m_data->m_stubEnv, 0, sizeof(SSystemGlobalEnvironment));
m_data->m_stubEnv.pRenderer = &m_data->m_renderer;
m_data->m_stubEnv.p3DEngine = &m_data->m_3DEngine;
m_data->m_stubEnv.pSystem = &m_data->m_system;
ON_CALL(m_data->m_3DEngine, CreateClipVolume())
.WillByDefault(::testing::Return(m_expectedClipVolumePtr));
gEnv = &m_data->m_stubEnv;
m_serializeContext = AZStd::make_unique<AZ::SerializeContext>();
m_transformComponentDescriptor = AZStd::unique_ptr<AZ::ComponentDescriptor>(AzFramework::TransformComponent::CreateDescriptor());
m_clipVolumeComponentDescriptor = AZStd::unique_ptr<AZ::ComponentDescriptor>(LmbrCentral::ClipVolumeComponent::CreateDescriptor());
m_polygonPrismComponentDescriptor = AZStd::unique_ptr<AZ::ComponentDescriptor>(LmbrCentral::PolygonPrismShapeComponent::CreateDescriptor());
m_transformComponentDescriptor->Reflect(m_serializeContext.get());
m_clipVolumeComponentDescriptor->Reflect(m_serializeContext.get());
m_polygonPrismComponentDescriptor->Reflect(m_serializeContext.get());
}
void TearDown() override
{
LmbrCentral::ClipVolumeComponentNotificationBus::Handler::BusDisconnect();
m_clipVolumeComponentDescriptor.reset();
m_transformComponentDescriptor.reset();
m_polygonPrismComponentDescriptor.reset();
m_serializeContext.reset();
gEnv = m_priorEnv;
m_data.reset();
AllocatorsTestFixture::TearDown();
}
void CreateDefaultSetup(AZ::Entity& entity)
{
entity.CreateComponent<AzFramework::TransformComponent>();
entity.CreateComponent<LmbrCentral::PolygonPrismShapeComponent>();
entity.CreateComponent<LmbrCentral::ClipVolumeComponent>();
entity.Init();
entity.Activate();
}
struct DataMembers
{
::testing::NiceMock<SystemMock> m_system;
::testing::NiceMock<IRendererMock> m_renderer;
::testing::NiceMock<I3DEngineMock> m_3DEngine;
SSystemGlobalEnvironment m_stubEnv;
};
void ConnectBus(AZ::EntityId entityId)
{
LmbrCentral::ClipVolumeComponentNotificationBus::Handler::BusConnect(entityId);
}
void OnClipVolumeCreated(IClipVolume* clipVolume) override
{
m_clipVolume = clipVolume;
}
void OnClipVolumeDestroyed(IClipVolume* clipVolume) override
{
m_receivedClipVolumeDestroy = true;
}
IClipVolume* m_expectedClipVolumePtr = reinterpret_cast<IClipVolume*>(0x1234);
AZStd::unique_ptr<DataMembers> m_data;
SSystemGlobalEnvironment* m_priorEnv = nullptr;
IClipVolume* m_clipVolume = nullptr;
bool m_receivedClipVolumeDestroy = false;
private:
AZStd::unique_ptr<AZ::SerializeContext> m_serializeContext;
AZStd::unique_ptr<AZ::ComponentDescriptor> m_clipVolumeComponentDescriptor;
AZStd::unique_ptr<AZ::ComponentDescriptor> m_transformComponentDescriptor;
AZStd::unique_ptr<AZ::ComponentDescriptor> m_polygonPrismComponentDescriptor;
};
TEST_F(ClipVolumeComponentTests, CreateClipVolumeComponent_FT)
{
AZ::Entity entity;
CreateDefaultSetup(entity);
LmbrCentral::ClipVolumeComponent* clipVolumeComponent = entity.FindComponent<LmbrCentral::ClipVolumeComponent>();
EXPECT_TRUE(clipVolumeComponent != nullptr);
}
TEST_F(ClipVolumeComponentTests, ComponentReceivesClipVolume_FT)
{
AZ::Entity entity;
ConnectBus(entity.GetId());
EXPECT_FALSE(m_clipVolume == m_expectedClipVolumePtr);
CreateDefaultSetup(entity);
EXPECT_TRUE(m_clipVolume == m_expectedClipVolumePtr);
EXPECT_FALSE(m_receivedClipVolumeDestroy);
entity.Deactivate();
EXPECT_TRUE(m_receivedClipVolumeDestroy);
}
} | 2,374 |
399 | /*
*
* * 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.wgzhao.addax.storage.reader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wgzhao.addax.common.base.Constant;
import com.wgzhao.addax.common.base.Key;
import com.wgzhao.addax.common.compress.ExpandLzopInputStream;
import com.wgzhao.addax.common.compress.ZipCycleInputStream;
import com.wgzhao.addax.common.constant.Type;
import com.wgzhao.addax.common.element.BoolColumn;
import com.wgzhao.addax.common.element.Column;
import com.wgzhao.addax.common.element.ColumnEntry;
import com.wgzhao.addax.common.element.DateColumn;
import com.wgzhao.addax.common.element.DoubleColumn;
import com.wgzhao.addax.common.element.LongColumn;
import com.wgzhao.addax.common.element.Record;
import com.wgzhao.addax.common.element.StringColumn;
import com.wgzhao.addax.common.exception.AddaxException;
import com.wgzhao.addax.common.plugin.RecordSender;
import com.wgzhao.addax.common.plugin.TaskPluginCollector;
import com.wgzhao.addax.common.util.Configuration;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorInputStream;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.UnsupportedCharsetException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class StorageReaderUtil
{
private static final Logger LOG = LoggerFactory.getLogger(StorageReaderUtil.class);
private StorageReaderUtil()
{
}
public static void readFromStream(InputStream inputStream, String fileName,
Configuration readerSliceConfig, RecordSender recordSender,
TaskPluginCollector taskPluginCollector)
{
String compress = readerSliceConfig.getString(Key.COMPRESS, "");
String encoding = readerSliceConfig.getString(Key.ENCODING, Constant.DEFAULT_ENCODING);
// handle blank encoding
if (StringUtils.isBlank(encoding)) {
encoding = Constant.DEFAULT_ENCODING;
LOG.warn("The encoding: '{}' is illegal, uses '{}' by default", encoding, Constant.DEFAULT_ENCODING);
}
List<Configuration> column = readerSliceConfig.getListConfiguration(Key.COLUMN);
// handle ["*"] -> [], null
if (null != column && 1 == column.size() && "\"*\"".equals(column.get(0).toString())) {
readerSliceConfig.set(Key.COLUMN, null);
}
BufferedReader reader = null;
int bufferSize = readerSliceConfig.getInt(Key.BUFFER_SIZE, Constant.DEFAULT_BUFFER_SIZE);
// compress logic
try {
if (compress == null || "".equals(compress) || "none".equalsIgnoreCase(compress)) {
reader = new BufferedReader(new InputStreamReader(inputStream, encoding), bufferSize);
}
else {
if ("zip".equalsIgnoreCase(compress)) {
ZipCycleInputStream zipCycleInputStream = new ZipCycleInputStream(inputStream);
reader = new BufferedReader(new InputStreamReader(zipCycleInputStream, encoding), bufferSize);
}
else if ("lzo".equalsIgnoreCase(compress)) {
ExpandLzopInputStream expandLzopInputStream = new ExpandLzopInputStream(inputStream);
reader = new BufferedReader(new InputStreamReader(expandLzopInputStream, encoding), bufferSize);
}
else {
// common-compress supports almost compress alg
CompressorInputStream input = new CompressorStreamFactory().createCompressorInputStream(compress.toUpperCase(), inputStream, true);
reader = new BufferedReader(new InputStreamReader(input, encoding), bufferSize);
}
}
StorageReaderUtil.doReadFromStream(reader, fileName, readerSliceConfig, recordSender, taskPluginCollector);
}
catch (UnsupportedEncodingException uee) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.OPEN_FILE_WITH_CHARSET_ERROR,
String.format("%s is unsupported", encoding), uee);
}
catch (NullPointerException e) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.RUNTIME_EXCEPTION, e);
}
catch (IOException e) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.READ_FILE_IO_ERROR, String.format("Read stream %s failure ", fileName), e);
}
catch (CompressorException e) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.ILLEGAL_VALUE,
"The compress algorithm'" + compress + "' is unsupported yet"
);
}
finally {
IOUtils.closeQuietly(reader, null);
}
}
public static void doReadFromStream(BufferedReader reader, String fileName,
Configuration readerSliceConfig, RecordSender recordSender,
TaskPluginCollector taskPluginCollector)
{
CSVFormat.Builder csvFormatBuilder = CSVFormat.DEFAULT.builder();
String encoding = readerSliceConfig.getString(Key.ENCODING, Constant.DEFAULT_ENCODING);
Character fieldDelimiter;
String delimiterInStr = readerSliceConfig
.getString(Key.FIELD_DELIMITER);
if (null != delimiterInStr && 1 != delimiterInStr.length()) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.ILLEGAL_VALUE,
String.format("The delimiter ONLY has one char, '%s' is illegal", delimiterInStr));
}
if (null == delimiterInStr) {
LOG.warn("Use {} as delimiter by default", Constant.DEFAULT_FIELD_DELIMITER);
}
// warn: default value ',', fieldDelimiter could be \n(lineDelimiter) for no fieldDelimiter
fieldDelimiter = readerSliceConfig.getChar(Key.FIELD_DELIMITER, Constant.DEFAULT_FIELD_DELIMITER);
csvFormatBuilder.setDelimiter(fieldDelimiter);
// warn: no default value '\N'
String nullFormat = readerSliceConfig.getString(Key.NULL_FORMAT);
csvFormatBuilder.setNullString(nullFormat);
Boolean skipHeader = readerSliceConfig.getBool(Key.SKIP_HEADER, Constant.DEFAULT_SKIP_HEADER);
csvFormatBuilder.setSkipHeaderRecord(skipHeader);
List<ColumnEntry> column = StorageReaderUtil.getListColumnEntry(readerSliceConfig, Key.COLUMN);
// every line logic
try {
CSVParser csvParser = new CSVParser(reader, csvFormatBuilder.build());
csvParser.stream().filter(Objects::nonNull).forEach(csvRecord ->
StorageReaderUtil.transportOneRecord(recordSender, column, csvRecord.toList().toArray(new String[0]), nullFormat, taskPluginCollector)
);
}
catch (UnsupportedEncodingException uee) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.OPEN_FILE_WITH_CHARSET_ERROR,
String.format("encoding: '%s' is unsupported", encoding), uee);
}
catch (FileNotFoundException fnfe) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.FILE_NOT_EXISTS, String.format("The file '%s' does not exists ", fileName), fnfe);
}
catch (IOException ioe) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.READ_FILE_IO_ERROR, String.format("Read file '%s' failure ", fileName), ioe);
}
catch (Exception e) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.RUNTIME_EXCEPTION, e);
}
finally {
IOUtils.closeQuietly(reader, null);
}
}
public static void transportOneRecord(RecordSender recordSender, Configuration configuration,
TaskPluginCollector taskPluginCollector, String line)
{
List<ColumnEntry> column = StorageReaderUtil.getListColumnEntry(configuration, Key.COLUMN);
// 注意: nullFormat 没有默认值
String nullFormat = configuration.getString(Key.NULL_FORMAT);
// warn: default value ',', fieldDelimiter could be \n(lineDelimiter)
// for no fieldDelimiter
Character fieldDelimiter = configuration.getChar(Key.FIELD_DELIMITER, Constant.DEFAULT_FIELD_DELIMITER);
String[] sourceLine = StringUtils.split(line, fieldDelimiter);
transportOneRecord(recordSender, column, sourceLine, nullFormat, taskPluginCollector);
}
public static void transportOneRecord(RecordSender recordSender, List<ColumnEntry> columnConfigs, String[] sourceLine,
String nullFormat, TaskPluginCollector taskPluginCollector)
{
Record record = recordSender.createRecord();
Column columnGenerated;
// 创建都为String类型column的record
if (null == columnConfigs || columnConfigs.isEmpty()) {
for (String columnValue : sourceLine) {
// not equalsIgnoreCase, it's all ok if nullFormat is null
if (columnValue.equals(nullFormat)) {
columnGenerated = new StringColumn(null);
}
else {
columnGenerated = new StringColumn(columnValue);
}
record.addColumn(columnGenerated);
}
recordSender.sendToWriter(record);
}
else {
try {
for (ColumnEntry columnConfig : columnConfigs) {
String columnType = columnConfig.getType();
Integer columnIndex = columnConfig.getIndex();
String columnConst = columnConfig.getValue();
String columnValue;
if (null == columnIndex && null == columnConst) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.NO_INDEX_VALUE, "The index or type is required when type is present.");
}
if (null != columnIndex && null != columnConst) {
throw AddaxException.asAddaxException(
StorageReaderErrorCode.MIXED_INDEX_VALUE, "The index and value are both present, choose one of them");
}
if (null != columnIndex) {
if (columnIndex >= sourceLine.length) {
throw new IndexOutOfBoundsException(String.format("The column index %s you try to read is out of range(%s): [%s]",
columnIndex + 1, sourceLine.length, StringUtils.join(sourceLine, ",")));
}
columnValue = sourceLine[columnIndex];
}
else {
columnValue = columnConst;
}
Type type = Type.valueOf(columnType.toUpperCase());
// it's all ok if nullFormat is null
if (columnValue == null || columnValue.equals(nullFormat)) {
record.addColumn(new StringColumn());
continue;
}
try {
switch (type) {
case STRING:
columnGenerated = new StringColumn(columnValue);
break;
case LONG:
columnGenerated = new LongColumn(columnValue);
break;
case DOUBLE:
columnGenerated = new DoubleColumn(columnValue);
break;
case BOOLEAN:
columnGenerated = new BoolColumn(columnValue);
break;
case DATE:
String formatString = columnConfig.getFormat();
if (StringUtils.isNotBlank(formatString)) {
// 用户自己配置的格式转换, 脏数据行为出现变化
DateFormat format = columnConfig.getDateFormat();
columnGenerated = new DateColumn(format.parse(columnValue));
}
else {
// 框架尝试转换
columnGenerated = new DateColumn(new StringColumn(columnValue).asDate());
}
break;
default:
String errorMessage = String.format("The column type '%s' is unsupported", columnType);
LOG.error(errorMessage);
throw AddaxException.asAddaxException(StorageReaderErrorCode.NOT_SUPPORT_TYPE, errorMessage);
}
}
catch (Exception e) {
throw new IllegalArgumentException(String.format("Cast value '%s' to type '%s' failure", columnValue, type.name()));
}
record.addColumn(columnGenerated);
}
recordSender.sendToWriter(record);
}
catch (IllegalArgumentException | IndexOutOfBoundsException iae) {
LOG.error(iae.getMessage());
taskPluginCollector.collectDirtyRecord(record, iae.getMessage());
}
catch (Exception e) {
if (e instanceof AddaxException) {
throw (AddaxException) e;
}
// 每一种转换失败都是脏数据处理,包括数字格式 & 日期格式
taskPluginCollector.collectDirtyRecord(record, e.getMessage());
}
}
}
public static List<ColumnEntry> getListColumnEntry(Configuration configuration, final String path)
{
List<JSONObject> lists = configuration.getList(path, JSONObject.class);
if (lists == null) {
return null;
}
List<ColumnEntry> result = new ArrayList<>();
for (final JSONObject object : lists) {
result.add(JSON.parseObject(object.toJSONString(), ColumnEntry.class));
}
return result;
}
/**
* check parameter:encoding, compress, filedDelimiter
*
* @param readerConfiguration 配置项
*/
public static void validateParameter(Configuration readerConfiguration)
{
// encoding check
validateEncoding(readerConfiguration);
//only support compress types
// validateCompress(readerConfiguration);
//fieldDelimiter check
validateFieldDelimiter(readerConfiguration);
// column: 1. index type 2.value type 3.when type is Date, may have format
validateColumn(readerConfiguration);
}
public static void validateEncoding(Configuration readerConfiguration)
{
// encoding check
String encoding = readerConfiguration.getString(Key.ENCODING, Constant.DEFAULT_ENCODING);
try {
encoding = encoding.trim();
readerConfiguration.set(Key.ENCODING, encoding);
Charsets.toCharset(encoding);
}
catch (UnsupportedCharsetException uce) {
throw AddaxException.asAddaxException(StorageReaderErrorCode.ILLEGAL_VALUE,
String.format("不支持您配置的编码格式 : [%s]", encoding), uce);
}
catch (Exception e) {
throw AddaxException.asAddaxException(StorageReaderErrorCode.CONFIG_INVALID_EXCEPTION,
String.format("编码配置异常, 请联系我们: %s", e.getMessage()), e);
}
}
public static void validateCompress(Configuration readerConfiguration)
{
String compress = readerConfiguration.getUnnecessaryValue(Key.COMPRESS, "").toLowerCase();
if ("gzip".equals(compress)) {
compress = "gz";
}
readerConfiguration.set(Key.COMPRESS, compress);
}
public static void validateFieldDelimiter(Configuration readerConfiguration)
{
//fieldDelimiter check
String delimiterInStr = readerConfiguration.getString(Key.FIELD_DELIMITER, ",");
if (null == delimiterInStr) {
throw AddaxException.asAddaxException(StorageReaderErrorCode.REQUIRED_VALUE,
String.format("您提供配置文件有误,[%s]是必填参数.",
Key.FIELD_DELIMITER));
}
else if (1 != delimiterInStr.length()) {
// warn: if have, length must be one
throw AddaxException.asAddaxException(StorageReaderErrorCode.ILLEGAL_VALUE,
String.format("仅仅支持单字符切分, 您配置的切分为 : [%s]", delimiterInStr));
}
}
public static void validateColumn(Configuration readerConfiguration)
{
// column: 1. index type 2.value type 3.when type is Date, may have
// format
List<Configuration> columns = readerConfiguration.getListConfiguration(Key.COLUMN);
if (null == columns || columns.isEmpty()) {
throw AddaxException.asAddaxException(StorageReaderErrorCode.REQUIRED_VALUE, "您需要指定 columns");
}
// handle ["*"]
if (1 == columns.size()) {
String columnsInStr = columns.get(0).toString();
if ("\"*\"".equals(columnsInStr) || "'*'".equals(columnsInStr)) {
readerConfiguration.set(Key.COLUMN, null);
columns = null;
}
}
if (null != columns && !columns.isEmpty()) {
for (Configuration eachColumnConf : columns) {
eachColumnConf.getNecessaryValue(Key.TYPE, StorageReaderErrorCode.REQUIRED_VALUE);
Integer columnIndex = eachColumnConf.getInt(Key.INDEX);
String columnValue = eachColumnConf.getString(Key.VALUE);
if (null == columnIndex && null == columnValue) {
throw AddaxException.asAddaxException(StorageReaderErrorCode.NO_INDEX_VALUE,
"You must configure one of index or name or value");
}
if (null != columnIndex && null != columnValue) {
throw AddaxException.asAddaxException(StorageReaderErrorCode.MIXED_INDEX_VALUE,
"You both configure index, value, or name, you can ONLY specify the one each column");
}
if (null != columnIndex && columnIndex < 0) {
throw AddaxException.asAddaxException(StorageReaderErrorCode.ILLEGAL_VALUE,
String.format("The value of index must be greater than 0, %s is illegal", columnIndex));
}
}
}
}
/**
* 获取含有通配符路径的父目录,目前只支持在最后一级目录使用通配符*或者
*
* @param regexPath path
* @return String
*/
public static String getRegexPathParentPath(String regexPath)
{
int lastDirSeparator = regexPath.lastIndexOf(IOUtils.DIR_SEPARATOR);
String parentPath;
parentPath = regexPath.substring(0, lastDirSeparator + 1);
if (parentPath.contains("*") || parentPath.contains("?")) {
throw AddaxException.asAddaxException(StorageReaderErrorCode.ILLEGAL_VALUE,
String.format("The path '%s' is illegal, ONLY the trail folder can container wildcard * or ? ",
regexPath));
}
return parentPath;
}
}
| 9,760 |
2,134 | c.BinderHub.appendix = """
USER root
ENV BINDER_URL={binder_url}
ENV REPO_URL={repo_url}
RUN cd /tmp \
&& wget -q https://github.com/jupyterhub/binderhub/archive/master.tar.gz -O binderhub.tar.gz \
&& tar --wildcards -xzf binderhub.tar.gz --strip 2 */examples/appendix\
&& ./appendix/run-appendix \
&& rm -rf binderhub.tar.gz appendix
USER $NB_USER
"""
| 146 |
474 | <reponame>jacobp100/navigation<filename>NavigationReactNative/src/android/src/main/java/com/navigation/reactnative/NavigationBarView.java
package com.navigation.reactnative;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.ViewOutlineProvider;
import androidx.core.util.Pools;
import androidx.core.view.ViewCompat;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.i18nmanager.I18nUtil;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.events.Event;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.google.android.material.appbar.AppBarLayout;
public class NavigationBarView extends AppBarLayout {
final ViewOutlineProvider defaultOutlineProvider;
final Drawable defaultBackground;
public NavigationBarView(Context context) {
super(context);
ViewCompat.setLayoutDirection(this, !I18nUtil.getInstance().isRTL(context) ? ViewCompat.LAYOUT_DIRECTION_LTR : ViewCompat.LAYOUT_DIRECTION_RTL);
setLayoutParams(new AppBarLayout.LayoutParams(AppBarLayout.LayoutParams.MATCH_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT));
defaultOutlineProvider = getOutlineProvider();
defaultBackground = getBackground();
addOnOffsetChangedListener(new OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int offset) {
OffsetChangedEvent event = OffsetChangedEvent.obtain(getId(), offset);
ReactContext reactContext = (ReactContext) getContext();
reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher().dispatchEvent(event);
}
});
}
static class OffsetChangedEvent extends Event<OffsetChangedEvent> {
private int offset;
private static final Pools.SynchronizedPool<OffsetChangedEvent> pool = new Pools.SynchronizedPool<>(3);
private OffsetChangedEvent() {
}
private static OffsetChangedEvent obtain(int viewTag, int offset) {
OffsetChangedEvent event = pool.acquire();
if (event == null)
event = new OffsetChangedEvent();
event.init(viewTag);
event.offset = offset;
return event;
}
@Override
public void onDispose() {
pool.release(this);
}
@Override
public short getCoalescingKey() {
return 0;
}
@Override
public boolean canCoalesce() {
return true;
}
@Override
public String getEventName() {
return "onOffsetChanged";
}
@Override
public void dispatch(RCTEventEmitter rctEventEmitter) {
WritableMap event = Arguments.createMap();
event.putDouble("offset", PixelUtil.toDIPFromPixel(offset));
rctEventEmitter.receiveEvent(getViewTag(), getEventName(), event);
}
}
}
| 1,250 |
399 | #include "stream_prototype_shim.h"
#include "bytes_view.h"
namespace Envoy {
namespace Python {
namespace StreamPrototype {
template <typename... Ts> std::function<void(Ts...)> makeShim(std::function<void(Ts...)> closure) {
return [closure](Ts... args) {
py::gil_scoped_acquire acquire;
closure(std::forward<Ts>(args)...);
};
}
Platform::StreamPrototype& setOnHeadersShim(Platform::StreamPrototype& self,
Platform::OnHeadersCallback closure) {
return self.setOnHeaders(makeShim(closure));
}
// set_on_data_shim can't be represented by the makeShim above, because it
// also constructs a bytes view onto the envoy_data provided.
Platform::StreamPrototype& setOnDataShim(Platform::StreamPrototype& self,
OnPyBytesDataCallback closure) {
return self.setOnData([closure](envoy_data data, bool end_stream) {
py::gil_scoped_acquire acquire;
py::bytes bytes = envoyDataAsPyBytes(data);
closure(bytes, end_stream);
});
}
Platform::StreamPrototype& setOnTrailersShim(Platform::StreamPrototype& self,
Platform::OnTrailersCallback closure) {
return self.setOnTrailers(makeShim(closure));
}
Platform::StreamPrototype& setOnErrorShim(Platform::StreamPrototype& self,
Platform::OnErrorCallback closure) {
return self.setOnError(makeShim(closure));
}
Platform::StreamPrototype& setOnCompleteShim(Platform::StreamPrototype& self,
Platform::OnCompleteCallback closure) {
return self.setOnComplete(makeShim(closure));
}
Platform::StreamPrototype& setOnCancelShim(Platform::StreamPrototype& self,
Platform::OnCancelCallback closure) {
return self.setOnCancel(makeShim(closure));
}
} // namespace StreamPrototype
} // namespace Python
} // namespace Envoy
| 786 |
934 | <filename>src/mongocxx/hint.hpp
// Copyright 2015 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.
#pragma once
#include <bsoncxx/document/value.hpp>
#include <bsoncxx/document/view_or_value.hpp>
#include <bsoncxx/stdx/optional.hpp>
#include <bsoncxx/string/view_or_value.hpp>
#include <bsoncxx/types/bson_value/view.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/config/prelude.hpp>
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN
///
/// Class representing a hint to be passed to a database operation.
///
class MONGOCXX_API hint {
public:
///
/// Constructs a new hint.
///
/// Note: this constructor is purposefully not explicit, to allow conversion
/// from either document::view or document::value to view_or_value.
///
/// @param index
/// Document view or value representing the index to be used.
///
hint(bsoncxx::document::view_or_value index);
///
/// Constructs a new hint.
///
/// @param index
/// String representing the name of the index to be used.
///
explicit hint(bsoncxx::string::view_or_value index);
///
/// @{
///
/// Compare this hint to a string for (in)-equality
///
/// @relates hint
///
friend MONGOCXX_API bool MONGOCXX_CALL operator==(const hint& index_hint, std::string index);
friend MONGOCXX_API bool MONGOCXX_CALL operator==(const hint& index_hint,
bsoncxx::document::view index);
///
/// @}
///
///
/// Returns a types::bson_value::view representing this hint.
///
/// @return Hint, as a types::bson_value::view. The caller must ensure that the returned object
/// not outlive
/// the hint object that it was created from.
///
bsoncxx::types::bson_value::view to_value() const;
///
/// Returns a types::bson_value::view representing this hint.
///
/// @return Hint, as a types::bson_value::view. The caller must ensure that the returned object
/// not outlive
/// the hint object that it was created from.
///
MONGOCXX_INLINE operator bsoncxx::types::bson_value::view() const;
private:
stdx::optional<bsoncxx::document::view_or_value> _index_doc;
stdx::optional<bsoncxx::string::view_or_value> _index_string;
};
///
/// Convenience methods to compare for equality against an index name.
///
/// Return true if this hint contains an index name that matches.
///
/// @relates hint
///
MONGOCXX_API bool MONGOCXX_CALL operator==(std::string index, const hint& index_hint);
///
/// @{
///
/// Convenience methods to compare for inequality against an index name.
///
/// Return true if this hint contains an index name that matches.
///
/// @relates hint
///
MONGOCXX_API bool MONGOCXX_CALL operator!=(const hint& index_hint, std::string index);
MONGOCXX_API bool MONGOCXX_CALL operator!=(std::string index, const hint& index_index);
///
/// @}
///
///
/// Convenience methods to compare for equality against an index document.
///
/// Return true if this hint contains an index document that matches.
///
/// @relates hint
///
MONGOCXX_API bool MONGOCXX_CALL operator==(bsoncxx::document::view index, const hint& index_hint);
///
/// @{
///
/// Convenience methods to compare for equality against an index document.
///
/// Return true if this hint contains an index document that matches.
///
///
/// @relates hint
///
MONGOCXX_API bool MONGOCXX_CALL operator!=(const hint& index_hint, bsoncxx::document::view index);
MONGOCXX_API bool MONGOCXX_CALL operator!=(bsoncxx::document::view index, const hint& index_hint);
///
/// @}
///
MONGOCXX_INLINE hint::operator bsoncxx::types::bson_value::view() const {
return to_value();
}
MONGOCXX_INLINE_NAMESPACE_END
} // namespace mongocxx
#include <mongocxx/config/postlude.hpp>
| 1,509 |
1,040 | //{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by dplaunch.rc
//
#define IDD_DIALOG1 101
#define IDD_LAUNCHERDIALOG 102
#define IDI_ICON1 102
#define IDC_HOSTRADIO 1000
#define IDC_JOINRADIO 1001
#define IDC_APPCOMBO 1002
#define IDC_SPCOMBO 1003
#define IDC_ADDRESSEDIT 1004
#define IDC_PLAYEREDIT 1005
#define IDC_SESSIONEDIT 1006
#define IDC_RUNAPPBUTTON 1007
#define IDC_STATUSEDIT 1008
#define IDC_ADDRESSCOMBO 1009
#define IDC_ADDRESSEDITLABEL 1010
#define IDC_ADDRESSCOMBOLABEL 1011
#define IDC_PORTEDIT 1013
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 103
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1015
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 633 |
831 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.profiling.view;
import com.intellij.designer.DesignerEditorPanelFacade;
import com.intellij.designer.LightToolWindow;
import com.intellij.designer.LightToolWindowContent;
import com.intellij.designer.LightToolWindowManager;
import com.intellij.designer.ToggleEditorModeAction;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindowAnchor;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Dummy LightToolWindowManager because the framework requires two managers at the same time.
*/
public class EmptyManager extends CaptureEditorLightToolWindowManager {
@NotNull private final JPanel myEmptyPanel = new JPanel();
@NotNull
public static EmptyManager getInstance(@NotNull Project project) {
return project.getService(EmptyManager.class);
}
protected EmptyManager(@NotNull Project project) {
super(project);
}
@Nullable
@Override
protected DesignerEditorPanelFacade getDesigner(@NotNull FileEditor editor) {
return null;
}
@Override
protected void updateToolWindow(@Nullable DesignerEditorPanelFacade designer) {
}
@NotNull
@Override
protected Icon getIcon() {
return AllIcons.Toolwindows.ProblemsEmpty;
}
@NotNull
@Override
protected String getManagerName() {
return "Capture Tool";
}
@NotNull
@Override
protected String getToolWindowTitleBarText() {
return "Unused";
}
@NotNull
@Override
protected List<AnAction> createActions() {
return Collections.emptyList();
}
@NotNull
@Override
protected JComponent getContent() {
return myEmptyPanel;
}
@Nullable
@Override
protected JComponent getFocusedComponent() {
return myEmptyPanel;
}
@Override
protected ToolWindowAnchor getAnchor() {
return ToolWindowAnchor.LEFT;
}
@Override
protected ToggleEditorModeAction createToggleAction(ToolWindowAnchor anchor) {
return new ToggleEditorModeAction(this, myProject, anchor) {
@Override
protected LightToolWindowManager getOppositeManager() {
return AnalysisResultsManager.getInstance(myProject);
}
};
}
@Override
protected LightToolWindow createContent(@NotNull DesignerEditorPanelFacade designer) {
return createContent(designer, new LightToolWindowContent() {
@Override
public void dispose() {
}
}, getToolWindowTitleBarText(), getIcon(), myEmptyPanel, myEmptyPanel, 0, createActions());
}
@NotNull
@Override
public String getComponentName() {
return "CaptureTool";
}
}
| 1,041 |
716 | <filename>tools/flang1/flang1exe/symutl.c<gh_stars>100-1000
/*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
/** \file
\brief Fortran symbol utilities.
*/
#include "gbldefs.h"
#include "global.h"
#include "error.h"
#include "symtab.h"
#include "symfun.h"
#include "symutl.h"
#include "dtypeutl.h"
#include "soc.h"
#include "ast.h"
#include "gramtk.h"
#include "comm.h"
#include "extern.h"
#include "hpfutl.h"
#include "rte.h"
#include "semant.h"
#define CONTIGUOUS_ARR(sptr) (ALLOCG(sptr) || CONTIGATTRG(sptr))
static int find_alloc_size(int ast, int foralllist, int *allocss,
int *allocdtype, int *allocdim);
static int do_check_member_id(int astmem, int astid);
SYMUTL symutl;
static int symutl_sc = SC_LOCAL; /* should symutl.sc be used instead?? */
void
set_symutl_sc(int sc)
{
symutl_sc = sc;
symutl.sc = sc;
}
int
get_next_sym(const char *basename, const char *purpose)
{
int sptr;
char *p;
p = mangle_name(basename, purpose);
sptr = getsymbol(p);
HCCSYMP(sptr, 1);
HIDDENP(sptr, 1); /* can't see this, if in the parser */
SCOPEP(sptr, stb.curr_scope);
if (gbl.internal > 1)
INTERNALP(sptr, 1);
return sptr;
}
int
get_next_sym_dt(const char *basename, const char *purpose, int encldtype)
{
int sptr;
char *p;
p = mangle_name_dt(basename, purpose, encldtype);
sptr = getsymbol(p);
HCCSYMP(sptr, 1);
HIDDENP(sptr, 1); /* can't see this, if in the parser */
SCOPEP(sptr, stb.curr_scope);
if (gbl.internal > 1)
INTERNALP(sptr, 1);
return sptr;
}
/* rename to get_ast_of_deferlen? */
int
get_len_of_deferchar_ast(int ast)
{
int sdsc, sdsc_ast;
int sdscofmem_ast;
int first;
int subs[1];
/* Need to add a check for subscript type */
first = first_element(ast);
if (A_TYPEG(first) == A_SUBSCR) {
first = A_LOPG(first);
}
if (A_TYPEG(first) != A_MEM) {
sdsc = SDSCG(A_SPTRG(first));
assert(sdsc != 0, "Deferred-length character symbol must have descriptor",
A_SPTRG(ast), 0);
return get_byte_len(sdsc);
}
/* this can be done partly by calling check_member() */
sdsc = SDSCG(A_SPTRG(A_MEMG(first)));
sdsc_ast = mk_id(sdsc);
sdscofmem_ast = mk_member(A_PARENTG(first), sdsc_ast, A_DTYPEG(sdsc_ast));
subs[0] = mk_isz_cval(get_byte_len_indx(), astb.bnd.dtype);
return mk_subscr(sdscofmem_ast, subs, 1, astb.bnd.dtype);
}
/** \brief Get the sptr of a specific name & SYMTYPE in the hash list
\param stype the SYMTYPE
\param first where to start the search (also establishes the name )
*/
SPTR
get_symtype(SYMTYPE stype, SPTR first)
{
SPTR sptr;
for (sptr = first; sptr > NOSYM; sptr = HASHLKG(sptr)) {
if (NMPTRG(sptr) != NMPTRG(first))
continue;
if (STYPEG(sptr) == stype)
return sptr;
}
return 0;
}
int
sym_get_scalar(const char *basename, const char *purpose, int dtype)
{
int sptr;
sptr = get_next_sym(basename, purpose);
DTYPEP(sptr, dtype);
STYPEP(sptr, ST_VAR);
DCLDP(sptr, 1);
SCP(sptr, symutl.sc);
NODESCP(sptr, 1);
SCOPEP(sptr, stb.curr_scope);
return sptr;
}
int
sym_get_ptr(int base)
{
int sptr;
char *basename;
basename = SYMNAME(base);
if (STYPEG(base) == ST_MEMBER) {
sptr = get_next_sym_dt(basename, "p", ENCLDTYPEG(base));
} else {
sptr = get_next_sym(basename, "p");
}
DTYPEP(sptr, DT_PTR);
STYPEP(sptr, ST_VAR);
SCP(sptr, symutl_sc);
NODESCP(sptr, 1);
PTRVP(sptr, 1);
if (CONSTRUCTSYMG(base)) {
CONSTRUCTSYMP(sptr, true);
ENCLFUNCP(sptr, ENCLFUNCG(base));
}
return sptr;
}
int
sym_get_ptr_name(char *basename)
{
int sptr;
sptr = get_next_sym(basename, "p");
DTYPEP(sptr, DT_PTR);
STYPEP(sptr, ST_VAR);
SCP(sptr, symutl_sc);
NODESCP(sptr, 1);
PTRVP(sptr, 1);
return sptr;
}
int
sym_get_offset(int base)
{
int sptr;
char *basename;
basename = SYMNAME(base);
if (STYPEG(base) == ST_MEMBER) {
sptr = get_next_sym_dt(basename, "o", ENCLDTYPEG(base));
} else {
sptr = get_next_sym(basename, "o");
}
DTYPEP(sptr, DT_PTR);
STYPEP(sptr, ST_VAR);
SCP(sptr, symutl_sc);
NODESCP(sptr, 1);
if (CONSTRUCTSYMG(base)) {
CONSTRUCTSYMP(sptr, true);
ENCLFUNCP(sptr, ENCLFUNCG(base));
}
return sptr;
}
/** \brief Make a temporary array, not deferred shape. Bounds need to be
filled in later.
*/
int
sym_get_array(const char *basename, const char *purpose, int dtype, int ndim)
{
int sptr;
ADSC *ad;
int i;
sptr = get_next_sym(basename, purpose);
dtype = get_array_dtype(ndim, dtype);
ALLOCP(sptr, 1);
ad = AD_DPTR(dtype);
AD_NOBOUNDS(ad) = 1;
for (i = 0; i < ndim; ++i) {
AD_LWAST(ad, i) = AD_UPAST(ad, i) = 0;
AD_LWBD(ad, i) = AD_UPBD(ad, i) = 0;
AD_EXTNTAST(ad, i) = 0;
}
DTYPEP(sptr, dtype);
STYPEP(sptr, ST_ARRAY);
DCLDP(sptr, 1);
SCP(sptr, symutl_sc);
return sptr;
}
/** \brief Create a function ST item given a name */
int
sym_mkfunc(const char *nmptr, int dtype)
{
register int sptr;
sptr = getsymbol(nmptr);
STYPEP(sptr, ST_PROC);
DTYPEP(sptr, dtype);
if (dtype != DT_NONE) {
DCLDP(sptr, 1);
FUNCP(sptr, 1);
if (XBIT(57, 0x2000))
TYPDP(sptr, 1);
}
SCP(sptr, SC_EXTERN);
SCOPEP(sptr, 0);
HCCSYMP(sptr, 1);
/*NODESCP(sptr,1);*/
return sptr;
}
/** \brief Create a function ST item given a name; set its NODESC flag */
int
sym_mkfunc_nodesc(const char *nmptr, int dtype)
{
register int sptr;
sptr = sym_mkfunc(nmptr, dtype);
NODESCP(sptr, 1);
PUREP(sptr, 1);
return sptr;
}
/** \brief Create a function ST item given a name; set its NODESC and EXPST
flag.
Could replace EXPST with a new flag. If the flag is set
we still need transform_call() to fix arguments which are
array sections.
*/
int
sym_mkfunc_nodesc_expst(const char *nmptr, int dtype)
{
register int sptr;
sptr = sym_mkfunc_nodesc(nmptr, dtype);
EXPSTP(sptr, 1);
return sptr;
}
/** \brief Create a function ST item given a name; set its NODESC and NOCOMM
* flag */
int
sym_mkfunc_nodesc_nocomm(const char *nmptr, int dtype)
{
register int sptr;
sptr = sym_mkfunc(nmptr, dtype);
NODESCP(sptr, 1);
NOCOMMP(sptr, 1);
PUREP(sptr, 1);
return sptr;
}
int
sym_mknproc(void)
{
STYPEP(gbl.sym_nproc, ST_VAR);
return gbl.sym_nproc;
}
/* This create descriptor and section descriptor
for each user defined array */
void
trans_mkdescr(int sptr)
{
int descr;
char *p;
if (DESCRG(sptr) != 0)
return;
/* save the basename in case it is a SYMNAME (might be realloc'd) */
p = sym_strsave(SYMNAME(sptr));
descr = get_next_sym(p, "arrdsc");
STYPEP(descr, ST_ARRDSC);
/*
* 2nd try for f15624 - use the storage class field of the arrdsc so
* that the SC_PRIVATE of arrdsc is propagated to the actual descriptor.
*/
SCP(descr, symutl_sc);
ARRAYP(descr, sptr);
ALNDP(descr, 0);
SECDP(descr, 0);
SECDSCP(descr, 0);
DESCRP(sptr, descr);
NODESCP(sptr, 0);
if (XBIT(57, 0x10000) && SCG(sptr) == SC_DUMMY && NEWDSCG(sptr)) {
SECDSCP(descr, NEWDSCG(sptr));
}
FREE(p);
}
/** \brief Create a section descriptor */
int
sym_get_sec(const char *basename, int is_dummy)
{
int sec, sec_ptr;
ADSC *ad;
int dtype;
char *p;
/* save the basename in case it is a SYMNAME (might be realloc'd) */
p = sym_strsave(basename);
sec = get_next_sym(p, "s");
if (!is_dummy)
sec_ptr = get_next_sym(p, "sp");
FREE(p);
/* make sec be array(1) */
STYPEP(sec, ST_ARRAY);
dtype = aux.dt_iarray_int;
ad = AD_DPTR(dtype);
AD_LWAST(ad, 0) = 0;
AD_UPBD(ad, 0) = AD_UPAST(ad, 0) = mk_isz_cval(1, astb.bnd.dtype);
AD_EXTNTAST(ad, 0) = mk_isz_cval(1, astb.bnd.dtype);
DTYPEP(sec, dtype);
DCLDP(sec, 1);
/* array section for dummy doesn't have a pointer */
if (!is_dummy) {
SCP(sec, SC_BASED);
/* make the pointer point to sec */
STYPEP(sec_ptr, ST_VAR);
DTYPEP(sec_ptr, DT_PTR);
SCP(sec_ptr, symutl_sc);
MIDNUMP(sec, sec_ptr);
} else
SCP(sec, SC_DUMMY);
NODESCP(sec, 1);
return sec;
}
/** \brief Create a channel pointer (cp) */
int
sym_get_cp(void)
{
int cp_ptr;
/* save the basename in case it is a SYMNAME (might be realloc'd) */
cp_ptr = trans_getbound(0, 11);
/* make the pointer point to cp */
STYPEP(cp_ptr, ST_VAR);
DTYPEP(cp_ptr, DT_ADDR);
SCP(cp_ptr, SC_LOCAL);
DCLDP(cp_ptr, 1);
return cp_ptr;
}
/** \brief Create a channel pointer (xfer) */
int
sym_get_xfer(void)
{
int xfer_ptr;
xfer_ptr = trans_getbound(0, 12);
STYPEP(xfer_ptr, ST_VAR);
DTYPEP(xfer_ptr, DT_ADDR);
SCP(xfer_ptr, SC_LOCAL);
DCLDP(xfer_ptr, 1);
return xfer_ptr;
}
/** \brief Create a section descriptor for a dummy argument */
int
sym_get_arg_sec(int sptr)
{
int sec;
ADSC *ad;
int dtype;
char *p;
char *basename;
int sdsc;
if (XBIT(57, 0x10000)) {
sdsc = sym_get_sdescr(sptr, -1);
/* sym_get_sdescr will return existing descriptor but we don't want that if
* this is
* an interface. It is possible that the current routine has same name
* descriptor
* due to use associate.
*/
if (SCOPEG(sptr)) {
int scope = SCOPEG(sptr);
if (STYPEG(scope) == ST_ALIAS)
scope = SYMLKG(scope);
if (SCG(scope) == SC_EXTERN && STYPEG(scope) == ST_PROC) {
sdsc = get_next_sym(SYMNAME(sptr), "sd");
}
}
SCP(sdsc, SC_DUMMY);
HCCSYMP(sdsc, 1);
return sdsc;
}
basename = SYMNAME(sptr);
/* save the basename in case it is a SYMNAME (might be realloc'd) */
p = sym_strsave(basename);
sec = get_next_sym(p, "s0");
FREE(p);
dtype = DDTG(DTYPEG(sptr));
if ((STYPEG(sptr) != ST_ARRAY || DTY(dtype) == TY_CHAR ||
DTY(dtype) == TY_NCHAR) &&
!POINTERG(sptr)) {
/* make sec be integer scalar */
DTYPEP(sec, DT_INT);
STYPEP(sec, ST_VAR);
} else {
/* make sec be array(1) */
STYPEP(sec, ST_ARRAY);
dtype = aux.dt_iarray_int;
ad = AD_DPTR(dtype);
AD_LWAST(ad, 0) = 0;
AD_UPBD(ad, 0) = AD_UPAST(ad, 0) = mk_isz_cval(1, astb.bnd.dtype);
AD_EXTNTAST(ad, 0) = mk_isz_cval(1, astb.bnd.dtype);
DTYPEP(sec, dtype);
}
DCLDP(sec, 1);
SCP(sec, SC_DUMMY);
HCCSYMP(sec, 1);
NODESCP(sec, 1);
return sec;
}
/** \brief Get a symbol for the base address of the formal argument */
int
sym_get_formal(int basevar)
{
int formal;
int dtype;
char *basename;
basename = SYMNAME(basevar);
formal = get_next_sym(basename, "bs");
dtype = DTYPEG(basevar);
if (DTY(dtype) != TY_ARRAY) {
/* declare as pointer to the datatype */
STYPEP(formal, ST_VAR);
DTYPEP(formal, dtype);
/*POINTERP( formal, 1 );*/
} else {
/* make sec be array(1) */
STYPEP(formal, ST_ARRAY);
dtype = DDTG(dtype);
dtype = get_array_dtype(1, dtype);
ADD_LWBD(dtype, 0) = 0;
ADD_LWAST(dtype, 0) = ADD_NUMELM(dtype) = ADD_UPBD(dtype, 0) =
ADD_UPAST(dtype, 0) = ADD_EXTNTAST(dtype, 0) =
mk_isz_cval(1, astb.bnd.dtype);
DTYPEP(formal, dtype);
}
DCLDP(formal, 1);
SCP(formal, SC_DUMMY);
HCCSYMP(formal, 1);
OPTARGP(formal, OPTARGG(basevar));
INTENTP(formal, INTENTG(basevar));
return formal;
}
/*-------------------------------------------------------------------------*/
/** \brief Return TRUE if the ast (triplet or shape stride)
has a constant value, and return its constant value
*/
int
constant_stride(int a, int *value)
{
int sptr;
/* ast of zero is treated as constant one */
if (a == 0) {
*value = 1;
return TRUE;
}
if (A_TYPEG(a) != A_CNST)
return FALSE;
sptr = A_SPTRG(a);
if (!DT_ISINT(DTYPEG(sptr)))
return FALSE;
if ((CONVAL1G(sptr) == 0 && CONVAL2G(sptr) >= 0) ||
(CONVAL1G(sptr) == -1 && CONVAL2G(sptr) < 0)) {
*value = CONVAL2G(sptr);
return TRUE;
}
return FALSE;
} /* constant_stride */
/* Temporary allocation */
/* subscripts (triples) for temp */
int
mk_forall_sptr(int forall_ast, int subscr_ast, int *subscr, int elem_dty)
{
int astli;
int submap[MAXSUBS], arr_sptr, memberast;
int i, ndims, lwbnd[MAXSUBS], upbnd[MAXSUBS];
int sptr, sdtype;
assert(A_TYPEG(forall_ast) == A_FORALL, "mk_forall_sptr: ast not forall",
forall_ast, 4);
/* get the forall index list */
astli = A_LISTG(forall_ast);
ndims = 0;
do {
if (A_TYPEG(subscr_ast) == A_MEM) {
subscr_ast = A_PARENTG(subscr_ast);
} else if (A_TYPEG(subscr_ast) == A_SUBSCR) {
int lop, dtype;
int asd, n, i;
for (i = 0; i < ndims; ++i)
submap[i] = -1;
memberast = 0;
lop = A_LOPG(subscr_ast);
if (A_TYPEG(lop) == A_MEM) {
memberast = lop;
arr_sptr = A_SPTRG(A_MEMG(memberast));
} else if (A_TYPEG(lop) == A_ID) {
arr_sptr = A_SPTRG(lop);
} else {
interr("mk_forall_sptr: subscript has no member/id", subscr_ast, 3);
}
dtype = DTYPEG(arr_sptr);
/* determine how many dimensions are needed, and which ones they are */
asd = A_ASDG(subscr_ast);
n = ASD_NDIM(asd);
for (i = 0; i < n; ++i) {
/* need to include the dimension if it is vector as well */
int k, ast, allocss, allocdtype, allocdim, c, stride, lw, up;
allocss = 0;
allocdtype = 0;
allocdim = 0;
ast = ASD_SUBS(asd, i);
if (ASUMSZG(arr_sptr) || XBIT(58, 0x20000)) {
if (A_TYPEG(ast) == A_TRIPLE) {
assert(ndims < MAXDIMS, "temporary has too many dimensions",
ndims, 4);
lw = check_member(memberast, A_LBDG(ast));
up = check_member(memberast, A_UPBDG(ast));
c = constant_stride(A_STRIDEG(ast), &stride);
if (flg.opt >= 2 && !XBIT(2, 0x400000)) {
lwbnd[ndims] = astb.i1;
stride = A_STRIDEG(ast);
if (stride == 0)
stride = astb.i1;
upbnd[ndims] = mk_binop(
OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, up, lw, stb.user.dt_int),
stride, stb.user.dt_int),
stride, stb.user.dt_int);
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else if (c && stride == 1) {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
} else if (c && stride == -1) {
lwbnd[ndims] = up;
upbnd[ndims] = lw;
subscr[ndims] = mk_triple(lw, up, 0);
} else if (XBIT(58, 0x20000)) {
lwbnd[ndims] = astb.i1;
stride = A_STRIDEG(ast);
if (stride == 0)
stride = astb.i1;
upbnd[ndims] = mk_binop(
OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, up, lw, stb.user.dt_int),
stride, stb.user.dt_int),
stride, stb.user.dt_int);
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
}
submap[ndims] = i;
++ndims;
} else if (A_SHAPEG(ast)) {
int shd;
assert(ndims < MAXDIMS, "temporary has too many dimensions",
ndims, 4);
shd = A_SHAPEG(ast);
lw = check_member(memberast, SHD_LWB(shd, i));
up = check_member(memberast, SHD_UPB(shd, i));
c = constant_stride(SHD_STRIDE(shd, i), &stride);
if (c && stride == 1) {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
} else if (c && stride == -1) {
lwbnd[ndims] = up;
upbnd[ndims] = lw;
subscr[ndims] = mk_triple(lw, up, A_STRIDEG(ast));
} else if (XBIT(58, 0x20000)) {
lwbnd[ndims] = astb.bnd.one;
stride = SHD_STRIDE(shd, i);
if (stride == 0)
stride = astb.bnd.one;
upbnd[ndims] = mk_binop(
OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, up, lw, astb.bnd.dtype),
stride, astb.bnd.dtype),
stride, astb.bnd.dtype);
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
}
submap[ndims] = i;
++ndims;
} else if ((k = search_forall_var(ast, astli)) != 0) {
assert(ndims < MAXDIMS, "temporary has too many dimensions",
ndims, 4);
/* make sure the bounds don't have other forall indices */
lw = A_LBDG(ASTLI_TRIPLE(k));
up = A_UPBDG(ASTLI_TRIPLE(k));
if (search_forall_var(lw, astli) || search_forall_var(up, astli)) {
/* can't use forall indices, they are triangular.
* use the bounds of the host array */
lwbnd[ndims] = check_member(memberast, ADD_LWAST(dtype, i));
upbnd[ndims] = check_member(memberast, ADD_UPAST(dtype, i));
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else if (other_forall_var(ast, astli, k)) {
lwbnd[ndims] = check_member(memberast, ADD_LWAST(dtype, i));
upbnd[ndims] = check_member(memberast, ADD_UPAST(dtype, i));
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else {
c = constant_stride(A_STRIDEG(ASTLI_TRIPLE(k)), &stride);
if (flg.opt >= 2 && !XBIT(2, 0x400000)) {
lwbnd[ndims] = astb.i1;
stride = A_STRIDEG(ASTLI_TRIPLE(k));
if (stride == 0)
stride = astb.i1;
upbnd[ndims] = mk_binop(
OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, up, lw, stb.user.dt_int),
stride, stb.user.dt_int),
stride, stb.user.dt_int);
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else if (c && stride == 1) {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
} else if (c && stride == -1) {
lwbnd[ndims] = up;
upbnd[ndims] = lw;
subscr[ndims] = mk_triple(up, lw, 0);
} else if (XBIT(58, 0x20000)) {
lwbnd[ndims] = astb.i1;
stride = A_STRIDEG(ASTLI_TRIPLE(k));
if (stride == 0)
stride = astb.i1;
upbnd[ndims] = mk_binop(
OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, up, lw, stb.user.dt_int),
stride, stb.user.dt_int),
stride, stb.user.dt_int);
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
}
}
submap[ndims] = i;
++ndims;
}
} else if (A_TYPEG(ast) == A_TRIPLE) {
/* include this dimension */
/* build a triplet for the allocate statement off of the
* dimensions for the array */
assert(ndims < MAXDIMS, "temporary has too many dimensions",
ndims, 4);
lwbnd[ndims] = check_member(memberast, ADD_LWAST(dtype, i));
upbnd[ndims] = check_member(memberast, ADD_UPAST(dtype, i));
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
submap[ndims] = i;
++ndims;
} else if (find_alloc_size(ast, astli, &allocss, &allocdtype,
&allocdim)) {
/* make this dimension the same size as dimension
* allocdim of datatype allocdtype for which the subscript
* is at allocss */
assert(ndims < MAXDIMS, "temporary has too many dimensions",
ndims, 4);
if (allocdtype == 0) {
allocdtype = dtype;
allocdim = i;
allocss = memberast;
}
lwbnd[ndims] = check_member(allocss, ADD_LWAST(allocdtype, allocdim));
upbnd[ndims] = check_member(allocss, ADD_UPAST(allocdtype, allocdim));
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
submap[ndims] = i;
++ndims;
} else if (A_SHAPEG(ast) || search_forall_var(ast, astli)) {
/* include this dimension */
/* build a triplet for the allocate statement off of the
* dimensions for the array */
assert(ndims < MAXDIMS, "temporary has too many dimensions",
ndims, 4);
lwbnd[ndims] = check_member(memberast, ADD_LWAST(dtype, i));
upbnd[ndims] = check_member(memberast, ADD_UPAST(dtype, i));
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
submap[ndims] = i;
++ndims;
}
}
subscr_ast = A_LOPG(subscr_ast);
} else {
interr("mk_forall_sptr: not member or subscript", subscr_ast, 3);
}
} while (A_TYPEG(subscr_ast) != A_ID);
/* get the temporary */
assert(ndims > 0, "mk_forall_sptr: not enough dimensions", ndims, 4);
sptr = sym_get_array(SYMNAME(arr_sptr), "f", elem_dty, ndims);
/* set the bounds to the correct bounds from the array */
sdtype = DTYPEG(sptr);
if (flg.opt >= 2 && !XBIT(2, 0x400000)) {
for (i = 0; i < ndims; ++i) {
ADD_LWBD(sdtype, i) = ADD_LWAST(sdtype, i) = astb.bnd.one;
ADD_UPBD(sdtype, i) = ADD_UPAST(sdtype, i) =
mk_binop(OP_ADD, mk_binop(OP_SUB, upbnd[i], lwbnd[i], astb.bnd.dtype),
astb.bnd.one, astb.bnd.dtype);
ADD_EXTNTAST(sdtype, i) =
mk_extent(ADD_LWAST(sdtype, i), ADD_UPAST(sdtype, i), i);
}
} else {
for (i = 0; i < ndims; ++i) {
ADD_LWBD(sdtype, i) = ADD_LWAST(sdtype, i) = lwbnd[i];
ADD_UPBD(sdtype, i) = ADD_UPAST(sdtype, i) = upbnd[i];
ADD_EXTNTAST(sdtype, i) =
mk_extent(ADD_LWAST(sdtype, i), ADD_UPAST(sdtype, i), i);
}
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
/* mark as compiler created */
HCCSYMP(sptr, 1);
return sptr;
}
/* get the subscript forall sptr, reuse temporary */
/* subscripts (triples) for temp */
int
get_forall_subscr(int forall_ast, int subscr_ast, int *subscr, int elem_dty)
{
int astli;
int submap[MAXSUBS], arr_sptr, memberast;
int ndims, lwbnd[MAXSUBS], upbnd[MAXSUBS];
int sptr = 0;
assert(A_TYPEG(forall_ast) == A_FORALL, "get_forall_subscr: ast not forall",
forall_ast, 4);
/* get the forall index list */
astli = A_LISTG(forall_ast);
ndims = 0;
do {
if (A_TYPEG(subscr_ast) == A_MEM) {
subscr_ast = A_PARENTG(subscr_ast);
} else if (A_TYPEG(subscr_ast) == A_SUBSCR) {
int lop, dtype;
int asd, n, i;
for (i = 0; i < ndims; ++i)
submap[i] = -1;
memberast = 0;
lop = A_LOPG(subscr_ast);
if (A_TYPEG(lop) == A_MEM) {
memberast = lop;
arr_sptr = A_SPTRG(A_MEMG(memberast));
} else if (A_TYPEG(lop) == A_ID) {
arr_sptr = A_SPTRG(lop);
} else {
interr("get_forall_subscr: subscript has no member/id", subscr_ast, 3);
}
dtype = DTYPEG(arr_sptr);
/* determine how many dimensions are needed, and which ones they are */
asd = A_ASDG(subscr_ast);
n = ASD_NDIM(asd);
for (i = 0; i < n; ++i) {
/* need to include the dimension if it is vector as well */
int k, ast, allocss, allocdtype, allocdim, c, stride, lw, up;
allocss = 0;
allocdtype = 0;
allocdim = 0;
ast = ASD_SUBS(asd, i);
if (ASUMSZG(arr_sptr) || XBIT(58, 0x20000)) {
if (A_TYPEG(ast) == A_TRIPLE) {
assert(ndims < MAXDIMS, "temporary has too many dimensions",
ndims, 4);
lw = check_member(memberast, A_LBDG(ast));
up = check_member(memberast, A_UPBDG(ast));
c = constant_stride(A_STRIDEG(ast), &stride);
if (flg.opt >= 2 && !XBIT(2, 0x400000)) {
lwbnd[ndims] = astb.i1;
stride = A_STRIDEG(ast);
if (stride == 0)
stride = astb.i1;
upbnd[ndims] = mk_binop(
OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, up, lw, stb.user.dt_int),
stride, stb.user.dt_int),
stride, stb.user.dt_int);
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else if (c && stride == 1) {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
} else if (c && stride == -1) {
lwbnd[ndims] = up;
upbnd[ndims] = lw;
subscr[ndims] = mk_triple(lw, up, 0);
} else if (XBIT(58, 0x20000)) {
lwbnd[ndims] = astb.i1;
stride = A_STRIDEG(ast);
if (stride == 0)
stride = astb.i1;
upbnd[ndims] = mk_binop(
OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, up, lw, stb.user.dt_int),
stride, stb.user.dt_int),
stride, stb.user.dt_int);
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
}
submap[ndims] = i;
++ndims;
} else if (A_SHAPEG(ast)) {
int shd;
assert(ndims < MAXDIMS, "temporary has too many dimensions",
ndims, 4);
shd = A_SHAPEG(ast);
lw = check_member(memberast, SHD_LWB(shd, i));
up = check_member(memberast, SHD_UPB(shd, i));
c = constant_stride(SHD_STRIDE(shd, i), &stride);
if (c && stride == 1) {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
} else if (c && stride == -1) {
lwbnd[ndims] = up;
upbnd[ndims] = lw;
subscr[ndims] = mk_triple(lw, up, A_STRIDEG(ast));
} else if (XBIT(58, 0x20000)) {
lwbnd[ndims] = astb.bnd.one;
stride = SHD_STRIDE(shd, i);
if (stride == 0)
stride = astb.bnd.one;
upbnd[ndims] = mk_binop(
OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, up, lw, astb.bnd.dtype),
stride, astb.bnd.dtype),
stride, astb.bnd.dtype);
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
}
submap[ndims] = i;
++ndims;
} else if ((k = search_forall_var(ast, astli)) != 0) {
assert(ndims < MAXDIMS, "temporary has too many dimensions",
ndims, 4);
/* make sure the bounds don't have other forall indices */
lw = A_LBDG(ASTLI_TRIPLE(k));
up = A_UPBDG(ASTLI_TRIPLE(k));
if (search_forall_var(lw, astli) || search_forall_var(up, astli)) {
/* can't use forall indices, they are triangular.
* use the bounds of the host array */
lwbnd[ndims] = check_member(memberast, ADD_LWAST(dtype, i));
upbnd[ndims] = check_member(memberast, ADD_UPAST(dtype, i));
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else if (other_forall_var(ast, astli, k)) {
lwbnd[ndims] = check_member(memberast, ADD_LWAST(dtype, i));
upbnd[ndims] = check_member(memberast, ADD_UPAST(dtype, i));
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else {
c = constant_stride(A_STRIDEG(ASTLI_TRIPLE(k)), &stride);
if (flg.opt >= 2 && !XBIT(2, 0x400000)) {
lwbnd[ndims] = astb.i1;
stride = A_STRIDEG(ASTLI_TRIPLE(k));
if (stride == 0)
stride = astb.i1;
upbnd[ndims] = mk_binop(
OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, up, lw, stb.user.dt_int),
stride, stb.user.dt_int),
stride, stb.user.dt_int);
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else if (c && stride == 1) {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
} else if (c && stride == -1) {
lwbnd[ndims] = up;
upbnd[ndims] = lw;
subscr[ndims] = mk_triple(up, lw, 0);
} else if (XBIT(58, 0x20000)) {
lwbnd[ndims] = astb.i1;
stride = A_STRIDEG(ASTLI_TRIPLE(k));
if (stride == 0)
stride = astb.i1;
upbnd[ndims] = mk_binop(
OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, up, lw, stb.user.dt_int),
stride, stb.user.dt_int),
stride, stb.user.dt_int);
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
} else {
lwbnd[ndims] = lw;
upbnd[ndims] = up;
subscr[ndims] = mk_triple(lw, up, 0);
}
}
submap[ndims] = i;
++ndims;
}
} else if (A_TYPEG(ast) == A_TRIPLE) {
/* include this dimension */
/* build a triplet for the allocate statement off of the
* dimensions for the array */
assert(ndims < MAXDIMS, "temporary has >MAXDIMS dimensions",
ndims, 4);
lwbnd[ndims] = check_member(memberast, ADD_LWAST(dtype, i));
upbnd[ndims] = check_member(memberast, ADD_UPAST(dtype, i));
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
submap[ndims] = i;
++ndims;
} else if (find_alloc_size(ast, astli, &allocss, &allocdtype,
&allocdim)) {
/* make this dimension the same size as dimension
* allocdim of datatype allocdtype for which the subscript
* is at allocss */
assert(ndims < MAXDIMS, "temporary has >MAXDIMS dimensions",
ndims, 4);
if (allocdtype == 0) {
allocdtype = dtype;
allocdim = i;
allocss = memberast;
}
lwbnd[ndims] = check_member(allocss, ADD_LWAST(allocdtype, allocdim));
upbnd[ndims] = check_member(allocss, ADD_UPAST(allocdtype, allocdim));
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
submap[ndims] = i;
++ndims;
} else if (A_SHAPEG(ast) || search_forall_var(ast, astli)) {
/* include this dimension */
/* build a triplet for the allocate statement off of the
* dimensions for the array */
assert(ndims < MAXDIMS, "temporary has >MAXDIMS dimensions",
ndims, 4);
lwbnd[ndims] = check_member(memberast, ADD_LWAST(dtype, i));
upbnd[ndims] = check_member(memberast, ADD_UPAST(dtype, i));
subscr[ndims] = mk_triple(lwbnd[ndims], upbnd[ndims], 0);
submap[ndims] = i;
++ndims;
}
}
subscr_ast = A_LOPG(subscr_ast);
} else {
interr("get_forall_subscr: not member or subscript", subscr_ast, 3);
}
} while (A_TYPEG(subscr_ast) != A_ID);
return sptr;
}
/** \brief Allocate a temporary to hold an array. Create the symbol pointer,
add the allocate and deallocate statements, and return the array.
\param forall_ast ast for forall
\param subscr_ast ast for subscript expression
\param alloc_stmt statement before which to allocate temp
\param dealloc_stmt statement after which to deallocate temp
\param dty datatype, or zero
\param ast_dty ast with data type of element required
\return symbol table pointer for array
The dimensions and mapping for the array are determined from the
subscr_ast and the forall_ast. The subscr_ast has dimensions which
are indexed by forall variables, and dimensions that are not. Those
that are not are excluded from the temp. The caller can use the
same index expressions to index this temp, as are used in the subscr_ast.
The dimensions included in the temp are taken from the array referenced
by the subscr ast. Alignments for those dimensions are also taken from
this array.
The allocate for the temporary is placed before alloc_stmt, and
the deallocate is placed after dealloc_stmt. The name of the temporary
is derived from the name of the array in the subscr_ast.
*/
int
get_temp_forall(int forall_ast, int subscr_ast, int alloc_stmt,
int dealloc_stmt, int dty, int ast_dty)
{
int sptr;
int subscr[MAXSUBS];
int par;
int save_sc;
int astd, dstd;
par = STD_PAR(alloc_stmt) || STD_TASK(alloc_stmt);
if (par) {
save_sc = symutl.sc;
set_descriptor_sc(SC_PRIVATE);
}
if (dty) {
sptr = mk_forall_sptr(forall_ast, subscr_ast, subscr, dty);
} else {
sptr = mk_forall_sptr(forall_ast, subscr_ast, subscr,
DDTG(A_DTYPEG(ast_dty)));
if (ast_dty > 0 &&
sptr > NOSYM &&
A_TYPEG(ast_dty) == A_SUBSCR &&
is_dtype_runtime_length_char(A_DTYPEG(ast_dty)) &&
SDSCG(sptr) <= NOSYM) {
int length_ast = string_expr_length(ast_dty);
if (length_ast > 0) {
int descr_length_ast;
get_static_descriptor(sptr);
descr_length_ast = symbol_descriptor_length_ast(sptr, 0);
if (descr_length_ast > 0) {
add_stmt_before(mk_assn_stmt(descr_length_ast, length_ast,
astb.bnd.dtype), alloc_stmt);
}
}
}
}
if (par) {
set_descriptor_sc(save_sc);
}
astd = mk_mem_allocate(mk_id(sptr), subscr, alloc_stmt, ast_dty);
dstd = mk_mem_deallocate(mk_id(sptr), dealloc_stmt);
if (STD_ACCEL(alloc_stmt))
STD_RESCOPE(astd) = 1;
if (STD_ACCEL(dealloc_stmt))
STD_RESCOPE(dstd) = 1;
return sptr;
}
/** \brief This is almost identical to get_temp_forall() except that it has
one more parameter, \p rhs.
\param forall_ast ast for forall
\param lhs ast for LHS
\param rhs ast for RHS
\param alloc_stmt statement before which to allocate temp
\param dealloc_stmt statement after which to deallocate temp
\param ast_dty ast with data type of element required
\return symbol table pointer for array
For copy_section, we would like to decide the rank of temp
according to rhs and distribution will be according to lhs.
This case arise since we let copy_section to do also multicasting
For example a(i,j) = b(2*i,3) kind of cases.
tmp will be 1 dimensional and that will be distribute according
to the fist dim of a.
*/
int
get_temp_copy_section(int forall_ast, int lhs, int rhs, int alloc_stmt,
int dealloc_stmt, int ast_dty)
{
int sptr, dty, subscr[MAXSUBS];
dty = DDTG(A_DTYPEG(ast_dty));
sptr = mk_forall_sptr_copy_section(forall_ast, lhs, rhs, subscr, dty);
mk_mem_allocate(mk_id(sptr), subscr, alloc_stmt, ast_dty);
mk_mem_deallocate(mk_id(sptr), dealloc_stmt);
return sptr;
}
/**
\param forall_ast ast for forall
\param lhs ast for LHS
\param rhs ast for RHS
\param alloc_stmt statement before which to allocate temp
\param dealloc_stmt statement after which to deallocate temp
\param ast_dty ast with data type of element required
*/
int
get_temp_pure(int forall_ast, int lhs, int rhs, int alloc_stmt,
int dealloc_stmt, int ast_dty)
{
int sptr, dty, subscr[MAXSUBS];
dty = DDTG(A_DTYPEG(ast_dty));
sptr = mk_forall_sptr_pure(forall_ast, lhs, rhs, subscr, dty);
mk_mem_allocate(mk_id(sptr), subscr, alloc_stmt, ast_dty);
mk_mem_deallocate(mk_id(sptr), dealloc_stmt);
return sptr;
}
/** \brief Get a temp sptr1 which will be as big as sptr
it will be replicated and allocated
\param sptr sptr to replicate
\param alloc_stmt statement before which to allocate temp
\param dealloc_stmt statement after which to deallocate temp
\param astmem - tbw.
*/
int
get_temp_pure_replicated(int sptr, int alloc_stmt, int dealloc_stmt, int astmem)
{
int sptr1;
int subscr[MAXSUBS];
int i, ndim;
ADSC *ad, *ad1;
ndim = rank_of_sym(sptr);
sptr1 = sym_get_array(SYMNAME(sptr), "pure$repl", DDTG(DTYPEG(sptr)), ndim);
ad = AD_DPTR(DTYPEG(sptr));
ad1 = AD_DPTR(DTYPEG(sptr1));
for (i = 0; i < ndim; i++) {
AD_LWAST(ad1, i) = check_member(astmem, AD_LWAST(ad, i));
AD_UPAST(ad1, i) = check_member(astmem, AD_UPAST(ad, i));
AD_LWBD(ad1, i) = check_member(astmem, AD_LWBD(ad, i));
AD_UPBD(ad1, i) = check_member(astmem, AD_UPBD(ad, i));
AD_EXTNTAST(ad1, i) = check_member(astmem, AD_EXTNTAST(ad, i));
subscr[i] = mk_triple(AD_LWAST(ad1, i), AD_UPAST(ad1, i), 0);
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr1);
mk_mem_allocate(mk_id(sptr1), subscr, alloc_stmt, astmem);
mk_mem_deallocate(mk_id(sptr1), dealloc_stmt);
return sptr1;
}
/**
\param arr_ast ast for arr_ast
\param alloc_stmt statement before which to allocate temp
\param dealloc_stmt statement after which to deallocate temp
\param dty ast with data type of element required
*/
int
get_temp_remapping(int arr_ast, int alloc_stmt, int dealloc_stmt, int dty)
{
int sptr;
int subscr[MAXSUBS];
sptr = mk_shape_sptr(A_SHAPEG(arr_ast), subscr, dty);
mk_mem_allocate(mk_id(sptr), subscr, alloc_stmt, arr_ast);
mk_mem_deallocate(mk_id(sptr), dealloc_stmt);
return sptr;
}
static LOGICAL
chk_temp_bnds(int lhs, int arr_sptr, int *subscr, int ndim)
{
ADSC *tad;
int sptr;
int i;
if (A_TYPEG(lhs) != A_ID)
return FALSE;
sptr = A_SPTRG(lhs);
tad = AD_DPTR(DTYPEG(sptr));
/* runtime can't handle dest==src */
if (arr_sptr == sptr)
return FALSE;
if (ndim != AD_NUMDIM(tad))
return FALSE;
for (i = 0; i < ndim; ++i) {
if (AD_LWAST(tad, i) != A_LBDG(subscr[i]))
return FALSE;
if (AD_UPAST(tad, i) != A_UPBDG(subscr[i]))
return FALSE;
}
return TRUE;
}
/*
* Make a symbol pointer from an array or subscripted array, assuming
* that that symbol will be assigned the array
*/
int
mk_assign_sptr(int arr_ast, const char *purpose, int *subscr, int elem_dty,
int *retval)
{
return chk_assign_sptr(arr_ast, purpose, subscr, elem_dty, 0, retval);
}
/*
* Find the sptr of the dummy at position 'pos' for subprogram ent
*/
int
find_dummy(int entry, int pos)
{
int dscptr;
proc_arginfo(entry, NULL, &dscptr, NULL);
if (!dscptr)
return 0;
return aux.dpdsc_base[dscptr + pos];
}
/*
* return the symbol pointer to the array symbol,
* and in *returnast, return the pointer to the A_SUBSCR
* (or A_MEM or A_ID, if an unsubscripted array reference)
*/
int
find_array(int ast, int *returnast)
{
int sptr = 0;
if (A_TYPEG(ast) == A_SUBSCR) {
int lop;
lop = A_LOPG(ast);
if (A_TYPEG(lop) == A_ID) {
if (returnast)
*returnast = ast;
sptr = A_SPTRG(lop);
} else if (A_TYPEG(lop) == A_MEM) {
/* child or parent? */
int parent = A_PARENTG(lop);
if ((A_SHAPEG(ast) != 0 && A_SHAPEG(ast) == A_SHAPEG(parent)) ||
A_SHAPEG(lop) == 0) {
return find_array(parent, returnast);
}
if (returnast)
*returnast = ast;
sptr = A_SPTRG(A_MEMG(lop));
} else {
interr("find_array: subscript parent is not id or member", ast, 3);
}
} else if (A_TYPEG(ast) == A_MEM) {
int parent = A_PARENTG(ast);
assert(A_SHAPEG(ast) != 0, "find_array: member ast has no shape", ast, 4);
if (A_SHAPEG(ast) == A_SHAPEG(parent)) {
return find_array(parent, returnast);
}
if (returnast)
*returnast = ast;
sptr = A_SPTRG(A_MEMG(ast));
} else if (A_TYPEG(ast) == A_ID) {
assert(A_SHAPEG(ast) != 0, "find_array: ast has no shape", ast, 4);
if (returnast)
*returnast = ast;
sptr = A_SPTRG(ast);
} else {
interr("find_array: not subscript or id or member", ast, 3);
}
assert(DTY(DTYPEG(sptr)) == TY_ARRAY, "find_array: symbol is not ARRAY", sptr,
4);
return sptr;
}
/* ast is ast to search */
static LOGICAL
found_forall_var(int ast)
{
int argt, n, i;
int asd;
switch (A_TYPEG(ast)) {
case A_BINOP:
if (found_forall_var(A_LOPG(ast)))
return TRUE;
return found_forall_var(A_ROPG(ast));
case A_CONV:
case A_UNOP:
case A_PAREN:
return found_forall_var(A_LOPG(ast));
case A_CMPLXC:
case A_CNST:
return FALSE;
case A_INTR:
case A_FUNC:
argt = A_ARGSG(ast);
n = A_ARGCNTG(ast);
for (i = 0; i < n; ++i) {
if (found_forall_var(ARGT_ARG(argt, i)))
return TRUE;
}
return FALSE;
case A_TRIPLE:
if (found_forall_var(A_LBDG(ast)))
return TRUE;
if (found_forall_var(A_UPBDG(ast)))
return TRUE;
if (A_STRIDEG(ast) && found_forall_var(A_STRIDEG(ast)))
return TRUE;
return FALSE;
case A_MEM:
return found_forall_var(A_PARENTG(ast));
case A_SUBSCR:
asd = A_ASDG(ast);
n = ASD_NDIM(asd);
for (i = 0; i < n; ++i) {
if (found_forall_var(ASD_SUBS(asd, i)))
return TRUE;
}
return found_forall_var(A_LOPG(ast));
case A_ID:
if (FORALLNDXG(A_SPTRG(ast)))
return TRUE;
return FALSE;
default:
interr("found_forall_index: bad opc", ast, 3);
return FALSE;
}
}
static void
fixup_allocd_tmp_bounds(int *subscr, int *newsubscr, int ndim)
{
int i;
int c_subscr;
/*
* As per the Fortran spec, ALLOCATE allocates an array of size
* zero when lb>ub. If the variable being allocated is a compiler
* generated temp to hold the result of an expression that has a
* negative stride, then the lb>ub. Reset the ub, lb, and stride
* for this case (tpr3551)
*
* Update -- resetting the ub, lb, and stride has the effect of
* computing the exact size needed for the temp. However, the
* subscripts for the temp are not normalized with respect to
* the actual size -- the original strided subscripts are used
* and therefore, array bounds violations will occur. The computed
* size just needs the direction of the stride (1 or -1) factored in;
* the direction just needs to be computed as sign(1,stride).
*/
for (i = 0; i < ndim; ++i) {
c_subscr = subscr[i];
if (A_TYPEG(c_subscr) == A_TRIPLE && A_STRIDEG(c_subscr) != astb.bnd.one &&
A_STRIDEG(c_subscr) != 0) {
int ub;
int stride;
stride = A_STRIDEG(c_subscr);
if (A_ALIASG(stride)) {
ISZ_T v;
v = get_isz_cval(A_SPTRG((A_ALIASG(stride))));
stride = astb.bnd.one;
if (v < 0)
stride = mk_isz_cval(-1, astb.bnd.dtype);
} else {
int isign;
isign = I_ISIGN;
if (astb.bnd.dtype == DT_INT8) {
isign = I_KISIGN;
}
stride = ast_intr(isign, astb.bnd.dtype, 2, astb.bnd.one, stride);
}
ub = mk_binop(OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, A_UPBDG(c_subscr),
A_LBDG(c_subscr), astb.bnd.dtype),
stride, astb.bnd.dtype),
stride, astb.bnd.dtype);
newsubscr[i] = mk_triple(astb.bnd.one, ub, 0);
} else {
newsubscr[i] = subscr[i];
}
}
}
void
fixup_srcalloc_bounds(int *subscr, int *newsubscr, int ndim)
{
int i;
int c_subscr;
for (i = 0; i < ndim; ++i) {
c_subscr = subscr[i];
if (A_TYPEG(c_subscr) == A_TRIPLE) {
int ub;
int stride;
stride = A_STRIDEG(c_subscr);
if (stride == 0)
stride = astb.bnd.one;
if (A_ALIASG(stride)) {
ISZ_T v;
v = get_isz_cval(A_SPTRG((A_ALIASG(stride))));
if (v < 0)
stride = mk_isz_cval(-1, astb.bnd.dtype);
}
ub = mk_binop(OP_DIV,
mk_binop(OP_ADD, mk_binop(OP_SUB, A_UPBDG(c_subscr),
A_LBDG(c_subscr), astb.bnd.dtype),
stride, astb.bnd.dtype),
stride, astb.bnd.dtype);
newsubscr[i] = mk_triple(astb.bnd.one, ub, 0);
} else {
newsubscr[i] = subscr[i];
}
}
}
/* This routine is just like old routine above.
* However, it does not try to create temporary
* based on in indirection, because that is wrong.
* because distribution becomes wrong.
* You can not align temporary with one dimension
* aligned with a template the other dimension aligned with another
* template.
*/
int
chk_assign_sptr(int arr_ast, const char *purpose, int *subscr, int elem_dty,
int lhs, int *retval)
{
int arr_sptr;
int ast;
int submap[MAXSUBS];
int newsubs[MAXSUBS];
int i, n, j;
int asd;
int sptr, ssast;
ADSC *ad;
int dtype;
ADSC *tad;
int lb, ub;
int lb1, ub1, st1;
int vsubsptr[MAXSUBS];
int extent;
/* find the array */
arr_sptr = find_array(arr_ast, &ssast);
if (ASUMSZG(arr_sptr)) {
sptr = mk_shape_sptr(A_SHAPEG(ssast), subscr, elem_dty);
*retval = mk_id(sptr);
return sptr;
}
dtype = DTYPEG(arr_sptr);
ad = AD_DPTR(dtype);
/* determine how many dimensions are needed, and which ones they are */
if (A_TYPEG(ssast) == A_SUBSCR) {
asd = A_ASDG(ssast);
n = ASD_NDIM(asd);
} else {
asd = 0;
n = AD_NUMDIM(ad);
}
j = 0;
assert(n <= MAXDIMS, "chk_assign_sptr: too many dimensions", n, 4);
for (i = 0; i < n; ++i) {
lb = AD_LWAST(ad, i);
if (lb == 0)
lb = mk_isz_cval(1, astb.bnd.dtype);
lb = check_member(ssast, lb);
ub = AD_UPAST(ad, i);
ub = check_member(ssast, ub);
vsubsptr[j] = 0;
/* If this is a pointer member, we need to use the shape */
if (A_TYPEG(ssast) == A_ID && STYPEG(arr_sptr) == ST_MEMBER &&
POINTERG(arr_sptr)) {
int shape;
shape = A_SHAPEG(ssast);
subscr[j] = mk_triple(SHD_LWB(shape, i), SHD_UPB(shape, i), 0);
submap[j] = i;
if (asd)
ast = ASD_SUBS(asd, i);
else
ast = subscr[j];
newsubs[j] = ast;
++j;
} else if (asd) {
ast = ASD_SUBS(asd, i);
/* if it is from where-block
* include each dimension */
if (!XBIT(58, 0x20000) && !strcmp(purpose, "ww")) {
subscr[j] = mk_triple(lb, ub, 0);
newsubs[j] = ast;
submap[j] = i;
++j;
continue;
}
if (A_TYPEG(ast) == A_TRIPLE) {
/* include this one */
if (XBIT(58, 0x20000)) {
subscr[j] = mk_triple(A_LBDG(ast), A_UPBDG(ast), A_STRIDEG(ast));
newsubs[j] = ast;
submap[j] = i;
++j;
} else {
/* would like to allocate to full size for hpf
* so all processors get a chunk, even if ignored */
subscr[j] = mk_triple(lb, ub, 0);
newsubs[j] = ast;
submap[j] = i;
++j;
}
} else if (A_SHAPEG(ast)) {
/* vector subscript */
/* (ub-lb+s)/st = extent */
extent = extent_of_shape(A_SHAPEG(ast), 0);
lb1 = lb;
st1 = astb.i1;
ub1 = opt_binop(OP_SUB, extent, st1, astb.bnd.dtype);
ub1 = opt_binop(OP_ADD, ub1, lb1, astb.bnd.dtype);
newsubs[j] = mk_triple(lb1, ub1, 0);
subscr[j] = newsubs[j];
submap[j] = i;
++j;
} else if (found_forall_var(ast)) {
/* a forall index appears in the subscript */
/* allocate to full size instead of trying to
* decipher the max/min size of the expression */
subscr[j] = mk_triple(lb, ub, 0);
newsubs[j] = ast;
submap[j] = i;
++j;
}
/* else don't include scalar dims */
} else {
subscr[j] = mk_triple(lb, ub, 0);
submap[j] = i;
newsubs[j] = subscr[j];
++j;
}
}
assert(j > 0, "chk_assign_sptr: not enough dimensions", j, 4);
if (lhs && chk_temp_bnds(lhs, arr_sptr, subscr, j)) {
*retval = lhs;
return 0;
}
/* get the temporary */
sptr = sym_get_array(SYMNAME(arr_sptr), purpose, elem_dty, j);
/* set the bounds to the correct bounds from the array */
ad = AD_DPTR(dtype);
tad = AD_DPTR(DTYPEG(sptr));
fixup_allocd_tmp_bounds(newsubs, newsubs, j);
for (i = 0; i < j; ++i) {
if (A_TYPEG(newsubs[i]) == A_TRIPLE) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) = A_LBDG(newsubs[i]);
AD_UPBD(tad, i) = AD_UPAST(tad, i) = A_UPBDG(newsubs[i]);
AD_EXTNTAST(tad, i) = mk_extent(AD_LWAST(tad, i), AD_UPAST(tad, i), i);
} else {
/* assuming A_TYPE is A_CNST or A_ID */
AD_LWBD(tad, i) = AD_LWAST(tad, i) = AD_UPBD(tad, i) = AD_UPAST(tad, i) =
newsubs[i];
AD_EXTNTAST(tad, i) = astb.bnd.one;
}
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
#ifdef NOEXTENTG
if ((!HCCSYMG(arr_sptr) && CONTIGUOUS_ARR(arr_sptr)) ||
(HCCSYMG(arr_sptr) && SCG(arr_sptr) == SC_LOCAL &&
CONTIGUOUS_ARR(arr_sptr) && NOEXTENTG(arr_sptr))) {
NOEXTENTP(sptr, 1);
}
#endif
/* mark as compiler created */
HCCSYMP(sptr, 1);
/* make the subscript expression */
*retval = mk_subscr(mk_id(sptr), newsubs, j, DTYPEG(sptr));
return sptr;
}
/*
* Make a symbol pointer from an array or subscripted array, assuming
* that that symbol will be assigned the array
*/
int
mk_shape_sptr(int shape, int *subscr, int elem_dty)
{
int i, n, size, notshort;
int sptr;
ADSC *tad;
int ub;
/* determine how many dimensions are needed, and which ones they are */
n = SHD_NDIM(shape);
assert(n <= MAXDIMS, "mk_assign_sptr: too many dimensions", n, 4);
for (i = 0; i < n; ++i) {
/* (ub - lb + stride) / stride */
assert(SHD_LWB(shape, i), "mk_assign_sptr: lower bound missing", 0, 4);
assert(SHD_UPB(shape, i), "mk_assign_sptr: upper bound missing", 0, 4);
if (SHD_STRIDE(shape, i) == astb.i1)
ub = mk_binop(OP_ADD, mk_binop(OP_SUB, SHD_UPB(shape, i),
SHD_LWB(shape, i), astb.bnd.dtype),
astb.bnd.one, astb.bnd.dtype);
else
ub = mk_binop(
OP_DIV, mk_binop(OP_ADD, mk_binop(OP_SUB, SHD_UPB(shape, i),
SHD_LWB(shape, i), astb.bnd.dtype),
SHD_STRIDE(shape, i), astb.bnd.dtype),
SHD_STRIDE(shape, i), astb.bnd.dtype);
subscr[i] = mk_triple(astb.bnd.one, ub, 0);
}
/* get the temporary */
sptr = sym_get_array("tmp", "r", elem_dty, n);
/* set the bounds to the correct bounds from the array */
tad = AD_DPTR(DTYPEG(sptr));
AD_MLPYR(tad, 0) = astb.bnd.one;
notshort = 0;
size = 1;
for (i = 0; i < n; ++i) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) = A_LBDG(subscr[i]);
AD_UPBD(tad, i) = AD_UPAST(tad, i) = A_UPBDG(subscr[i]);
AD_EXTNTAST(tad, i) = mk_extent(AD_LWAST(tad, i), AD_UPAST(tad, i), i);
AD_MLPYR(tad, i + 1) =
mk_binop(OP_MUL, AD_MLPYR(tad, i), AD_UPBD(tad, i), astb.bnd.dtype);
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
check_small_allocatable(sptr);
/* mark as compiler created */
HCCSYMP(sptr, 1);
return sptr;
}
/*
* If this is a temporary allocatable array,
* see if it is small enough that we should just leave it on the stack.
*/
void
check_small_allocatable(int sptr)
{
int i, n, ex, small;
int eldt;
ISZ_T size;
ADSC *ad;
if (!XBIT(2, 0x1000))
return;
eldt = DTY(DTYPEG(sptr) + 1);
if (DTY(eldt) == TY_CHAR
|| DTY(eldt) == TY_NCHAR
) {
if (eldt == DT_ASSCHAR || eldt == DT_DEFERCHAR
|| eldt == DT_ASSNCHAR || eldt == DT_DEFERNCHAR
)
return;
if (!A_ALIASG(DTY(eldt + 1)))
return;
}
ad = AD_DPTR(DTYPEG(sptr));
n = AD_NUMDIM(ad);
small = 1;
size = 1;
for (i = 0; i < n; ++i) {
ex = AD_EXTNTAST(ad, i);
if (!A_ALIASG(ex)) {
return;
}
ex = A_ALIASG(ex);
size *= ad_val_of(A_SPTRG(ex));
if (size > 20) {
return;
}
}
/* still small enough */
ALLOCP(sptr, 0);
if (MIDNUMG(sptr)) {
SCP(sptr, SCG(MIDNUMG(sptr)));
MIDNUMP(sptr, 0);
}
} /* check_small_allocatable */
/* if non-constant DIM
* This routine is to handle non-constant dimension for reduction and spread.
* Idea is to create temporary with right dimension, and
* rely on pghpf_reduce_descriptor and pghpf_spread_descriptor
* for tempoary bounds and alignment. Mark temp as if DYNAMIC since
* compiler does not know the alignment of temporary.
* This routine is alo try to use lhs
*/
static int
handle_non_cnst_dim(int arr_ast, const char *purpose, int *subscr, int elem_dty,
int dim, int lhs, int *retval, int ndim)
{
int arr_sptr;
int newsubs[MAXSUBS];
int i;
int sptr;
int dtype;
int desc;
int lb, ub, ssast;
/* find the array */
arr_sptr = find_array(arr_ast, &ssast);
dtype = DTYPEG(arr_sptr);
/* constant DIM */
assert(dim != 0, "handle_non_cnst_dim: no dim", 0, 4);
assert(!A_ALIASG(dim), "handle_non_cnst_dim: dim must be non-constant", 0, 4);
sptr = sym_get_array(SYMNAME(arr_sptr), purpose, elem_dty, ndim);
desc = sym_get_sdescr(sptr, ndim);
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
NODESCP(sptr, 1);
SECDSCP(DESCRG(sptr), desc);
/* mark as compiler created */
HCCSYMP(sptr, 1);
for (i = 0; i < ndim; ++i) {
int a;
lb = get_global_lower(desc, i);
a = get_extent(desc, i);
a = mk_binop(OP_SUB, a, mk_cval(1, A_DTYPEG(a)), A_DTYPEG(a));
ub = mk_binop(OP_ADD, lb, a, A_DTYPEG(lb));
subscr[i] = newsubs[i] = mk_triple(lb, ub, 0);
}
/* *retval = mk_id(sptr);*/
*retval = mk_subscr(mk_id(sptr), newsubs, ndim, DTYPEG(sptr));
return sptr;
}
/*
* Make a symbol pointer from an array or subscripted array, assuming
* that that symbol will be used as the result of a reduction expression
* that reduces the array. One dimension is squeezed out.
*/
int
chk_reduc_sptr(int arr_ast, const char *purpose, int *subscr, int elem_dty,
int dim, int lhs, int *retval)
{
int arr_sptr;
int ast;
int submap[MAXSUBS];
int newsubs[MAXSUBS];
int i, n, j, k;
int asd;
int sptr, ssast;
ADSC *ad;
int dtype;
ADSC *tad;
/* find the array */
arr_sptr = find_array(arr_ast, &ssast);
dtype = DTYPEG(arr_sptr);
ad = AD_DPTR(dtype);
/* determine how many dimensions are needed, and which ones they are */
if (A_TYPEG(ssast) == A_SUBSCR) {
asd = A_ASDG(ssast);
n = ASD_NDIM(asd);
} else {
asd = 0;
n = AD_NUMDIM(ad);
}
/* constant DIM */
assert(dim != 0, "chk_reduc_sptr: dim must be constant", 0, 4);
/* if non-constant DIM */
if (!A_ALIASG(dim))
return handle_non_cnst_dim(ssast, purpose, subscr, elem_dty, dim, lhs,
retval, n - 1);
dim = get_int_cval(A_SPTRG(A_ALIASG(dim)));
j = 0; /* dimension counter in temp */
k = 0; /* vector dimensions in array */
assert(n <= MAXDIMS, "chk_reduc_sptr: too many dimensions", n, 4);
for (i = 0; i < n; ++i) {
if (asd) {
ast = ASD_SUBS(asd, i);
if (A_TYPEG(ast) == A_TRIPLE) {
k++;
if (k == dim)
continue;
if (ASUMSZG(arr_sptr))
subscr[j] = mk_triple(A_LBDG(ast), A_UPBDG(ast), 0);
else
subscr[j] = mk_triple(check_member(arr_ast, AD_LWAST(ad, i)),
check_member(arr_ast, AD_UPAST(ad, i)), 0);
submap[j] = i;
newsubs[j] = ast;
++j;
}
} else {
k++;
if (k == dim)
continue;
subscr[j] = mk_triple(check_member(arr_ast, AD_LWAST(ad, i)),
check_member(arr_ast, AD_UPAST(ad, i)), 0);
submap[j] = i;
newsubs[j] = subscr[j];
++j;
}
}
/* get the temporary */
assert(k > 1, "chk_reduc_sptr: not enough dimensions", 0, 4);
assert(j == k - 1, "chk_reduc_sptr: dim out of range", 0, 4);
if (lhs && chk_temp_bnds(lhs, arr_sptr, subscr, j)) {
*retval = lhs;
return 0;
}
sptr = sym_get_array(SYMNAME(arr_sptr), purpose, elem_dty, j);
/* set the bounds to the correct bounds from the array */
ad = AD_DPTR(dtype);
tad = AD_DPTR(DTYPEG(sptr));
if (!ASUMSZG(arr_sptr)) {
for (i = 0; i < j; ++i) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) =
check_member(arr_ast, AD_LWAST(ad, submap[i]));
AD_UPBD(tad, i) = AD_UPAST(tad, i) =
check_member(arr_ast, AD_UPAST(ad, submap[i]));
AD_EXTNTAST(tad, i) = mk_extent(AD_LWAST(tad, i), AD_UPAST(tad, i), i);
}
} else {
for (i = 0; i < j; ++i) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) = A_LBDG(subscr[i]);
AD_UPBD(tad, i) = AD_UPAST(tad, i) = A_UPBDG(subscr[i]);
AD_EXTNTAST(tad, i) = mk_extent(AD_LWAST(tad, i), AD_UPAST(tad, i), i);
}
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
check_small_allocatable(sptr);
/* mark as compiler created */
HCCSYMP(sptr, 1);
*retval = mk_subscr(mk_id(sptr), newsubs, j, DTYPEG(sptr));
return sptr;
}
static void
mk_temp_based(int sptr)
{
int tempbase;
/* create a pointer variable */
tempbase = get_next_sym(SYMNAME(sptr), "cp");
/* make the pointer point to sptr */
STYPEP(tempbase, ST_VAR);
DTYPEP(tempbase, DT_PTR);
SCP(tempbase, symutl_sc);
MIDNUMP(sptr, tempbase);
SCP(sptr, SC_BASED);
}
/*
* Make a symbol pointer from an array or subscripted array, assuming
* that that symbol will be used as the result of a spread expression
* that adds a dimension to the array. One dimension is added.
*/
int
mk_spread_sptr(int arr_ast, const char *purpose, int *subscr, int elem_dty,
int dim, int ncopies, int lhs, int *retval)
{
int arr_sptr;
int ast, shape;
int submap[MAXSUBS];
int newsubs[MAXSUBS];
int i, n, j;
int asd;
int sptr, ssast;
ADSC *ad = NULL;
int dtype;
ADSC *tad = NULL;
int ttype = 0;
/* if it has a scalar spread(3, dim, ncopies) */
if (A_TYPEG(arr_ast) != A_SUBSCR && A_SHAPEG(arr_ast) == 0) { /*scalar */
sptr = sym_get_array("spread", purpose, elem_dty, 1);
/* set the bounds to the correct bounds from the array */
tad = AD_DPTR(DTYPEG(sptr));
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) = mk_isz_cval(1, astb.bnd.dtype);
AD_NUMELM(tad) = AD_UPBD(tad, 0) = AD_UPAST(tad, 0) = ncopies;
AD_EXTNTAST(tad, 0) = mk_extent(AD_LWAST(tad, 0), AD_UPAST(tad, 0), 0);
if (elem_dty == DT_ASSCHAR || elem_dty == DT_DEFERCHAR
|| elem_dty == DT_ASSNCHAR || elem_dty == DT_DEFERNCHAR
) {
/* make the temporary a based symbol; mk_mem_allocate() will compute
* the length
*/
mk_temp_based(sptr);
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
check_small_allocatable(sptr);
/* mark as compiler created */
HCCSYMP(sptr, 1);
subscr[0] = mk_triple(mk_isz_cval(1, astb.bnd.dtype), ncopies, 0);
newsubs[0] = subscr[0];
*retval = mk_subscr(mk_id(sptr), newsubs, 1, DTYPEG(sptr));
return sptr;
}
switch (A_TYPEG(arr_ast)) {
case A_SUBSCR:
asd = A_ASDG(arr_ast);
n = ASD_NDIM(asd);
for (j = 0; j < n; j++) {
int sb;
sb = ASD_SUBS(asd, j);
if (A_TYPEG(sb) != A_TRIPLE && A_SHAPEG(sb)) {
/* has index vector */
goto no_arr_sptr;
}
}
FLANG_FALLTHROUGH;
case A_ID:
case A_MEM:
arr_sptr = find_array(arr_ast, &ssast);
ttype = dtype = DTYPEG(arr_sptr);
ad = AD_DPTR(dtype);
shape = 0;
/* determine how many dimensions are needed, and which ones they are */
if (A_TYPEG(ssast) == A_SUBSCR) {
asd = A_ASDG(ssast);
n = ASD_NDIM(asd);
} else {
asd = 0;
n = AD_NUMDIM(ad);
}
break;
default:
no_arr_sptr:
arr_sptr = 0;
dtype = A_DTYPEG(arr_ast);
ad = NULL;
asd = 0;
shape = A_SHAPEG(arr_ast);
n = SHD_NDIM(shape);
break;
}
/* constant DIM */
assert(dim != 0, "chk_reduc_sptr: dim must be constant", 0, 4);
/* if non-constant DIM */
if (!A_ALIASG(dim))
return handle_non_cnst_dim(ssast, purpose, subscr, elem_dty, dim, lhs,
retval, n + 1);
dim = get_int_cval(A_SPTRG(A_ALIASG(dim)));
j = 0;
assert(n <= MAXDIMS, "chk_spread_sptr: too many dimensions", n, 4);
for (i = 0; i < n; ++i) {
if (asd) {
ast = ASD_SUBS(asd, i);
if (A_TYPEG(ast) == A_TRIPLE) {
if (j == dim - 1) {
/* add before this dimension */
subscr[j] = mk_triple(mk_isz_cval(1, astb.bnd.dtype), ncopies, 0);
submap[j] = -1;
newsubs[j] = subscr[j];
++j;
}
/* include this one */
if (ASUMSZG(arr_sptr))
subscr[j] = mk_triple(A_LBDG(ast), A_UPBDG(ast), 0);
else
subscr[j] = mk_triple(check_member(ssast, AD_LWAST(ad, i)),
check_member(ssast, AD_UPAST(ad, i)), 0);
submap[j] = i;
newsubs[j] = ast;
++j;
}
} else {
if (j == dim - 1) {
/* add before this dimension */
subscr[j] = mk_triple(mk_isz_cval(1, astb.bnd.dtype), ncopies, 0);
submap[j] = -1;
newsubs[j] = subscr[j];
++j;
}
if (ad) {
subscr[j] = mk_triple(check_member(ssast, AD_LWAST(ad, i)),
check_member(ssast, AD_UPAST(ad, i)), 0);
} else if (shape) {
subscr[j] = mk_triple(SHD_LWB(shape, i), SHD_UPB(shape, i), 0);
} else {
interr("spread with no shape", ast, 3);
}
submap[j] = i;
newsubs[j] = subscr[j];
++j;
}
}
if (j == dim - 1) {
/* add after last dimension */
subscr[j] = mk_triple(mk_cval(1, DT_INT), ncopies, 0);
submap[j] = -1;
newsubs[j] = subscr[j];
++j;
}
/* get the temporary */
assert(j > 0, "chk_spread_sptr: not enough dimensions", 0, 4);
if (arr_sptr) {
sptr = sym_get_array(SYMNAME(arr_sptr), purpose, elem_dty, j);
} else {
sptr = sym_get_array("sprd", purpose, elem_dty, j);
}
/* set the bounds to the correct bounds from the array */
tad = AD_DPTR(DTYPEG(sptr));
if (ad) {
if (ttype) {
ad = AD_DPTR(ttype);
}
for (i = 0; i < j; ++i) {
if (ASUMSZG(arr_sptr)) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) = A_LBDG(subscr[i]);
AD_UPBD(tad, i) = AD_UPAST(tad, i) = A_UPBDG(subscr[i]);
AD_EXTNTAST(tad, i) = mk_extent(AD_LWAST(tad, i), AD_UPAST(tad, i), i);
} else if (submap[i] != -1) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) =
check_member(ssast, AD_LWAST(ad, submap[i]));
AD_UPBD(tad, i) = AD_UPAST(tad, i) =
check_member(ssast, AD_UPAST(ad, submap[i]));
AD_EXTNTAST(tad, i) = check_member(ssast, AD_EXTNTAST(ad, submap[i]));
} else {
AD_LWBD(tad, i) = AD_LWAST(tad, i) = mk_isz_cval(1, astb.bnd.dtype);
AD_UPBD(tad, i) = AD_UPAST(tad, i) = ncopies;
AD_EXTNTAST(tad, i) = mk_extent(AD_LWAST(tad, i), AD_UPAST(tad, i), i);
}
}
} else {
for (i = 0; i < j; ++i) {
if (submap[i] != -1) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) = SHD_LWB(shape, submap[i]);
AD_UPBD(tad, i) = AD_UPAST(tad, i) = SHD_UPB(shape, submap[i]);
AD_EXTNTAST(tad, i) = mk_extent_expr(SHD_LWB(shape, submap[i]),
SHD_UPB(shape, submap[i]));
} else {
AD_LWBD(tad, i) = AD_LWAST(tad, i) = mk_isz_cval(1, astb.bnd.dtype);
AD_UPBD(tad, i) = AD_UPAST(tad, i) = ncopies;
AD_EXTNTAST(tad, i) =
mk_extent_expr(AD_LWAST(tad, i), AD_UPAST(tad, i));
}
}
}
if (elem_dty == DT_ASSCHAR || elem_dty == DT_DEFERCHAR
|| dtype == DT_ASSNCHAR || elem_dty == DT_DEFERNCHAR
) {
/* make the temporary a based symbol; mk_mem_allocate() will compute
* the length
*/
mk_temp_based(sptr);
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
check_small_allocatable(sptr);
/* mark as compiler created */
HCCSYMP(sptr, 1);
*retval = mk_subscr(mk_id(sptr), newsubs, j, DTYPEG(sptr));
return sptr;
}
/*
* Make sptr for matmul
*/
int
mk_matmul_sptr(int arg1, int arg2, const char *purpose, int *subscr,
int elem_dty, int *retval)
{
int arr_sptr1, arr_sptr2;
int ast;
int submap1[MAXSUBS], submap2[MAXSUBS];
int subscr1[MAXSUBS], subscr2[MAXSUBS];
int newsubs1[MAXSUBS], newsubs2[MAXSUBS];
int newsubs[MAXSUBS];
int rank1, rank2, rank;
int i, n, j;
int asd;
int sptr, ssast1, ssast2;
ADSC *ad1, *ad2;
int dtype;
ADSC *tad;
arr_sptr1 = find_array(arg1, &ssast1);
dtype = DTYPEG(arr_sptr1);
ad1 = AD_DPTR(dtype);
/* find the first vector dimension of the first arg */
if (A_TYPEG(ssast1) == A_SUBSCR) {
asd = A_ASDG(ssast1);
n = ASD_NDIM(asd);
} else {
asd = 0;
n = AD_NUMDIM(ad1);
}
assert(n <= MAXDIMS, "mk_matmul_sptr: too many dimensions", n, 4);
j = 0;
for (i = 0; i < n; ++i) {
if (asd) {
ast = ASD_SUBS(asd, i);
if (A_TYPEG(ast) == A_TRIPLE) {
int lb, ub;
if (ASUMSZG(arr_sptr1)) {
lb = A_LBDG(ast);
ub = A_UPBDG(ast);
} else {
lb = check_member(ssast1, AD_LWAST(ad1, i));
ub = check_member(ssast1, AD_UPAST(ad1, i));
}
subscr1[j] = mk_triple(lb, ub, 0);
submap1[j] = i;
newsubs1[j] = ast;
++j;
}
} else {
int lb, ub;
lb = check_member(ssast1, AD_LWAST(ad1, i));
ub = check_member(ssast1, AD_UPAST(ad1, i));
subscr1[j] = mk_triple(lb, ub, 0);
submap1[j] = i;
newsubs1[j] = subscr1[j];
++j;
}
}
rank1 = j;
arr_sptr2 = find_array(arg2, &ssast2);
dtype = DTYPEG(arr_sptr2);
ad2 = AD_DPTR(dtype);
/* find the second vector dimension of the second arg */
if (A_TYPEG(ssast2) == A_SUBSCR) {
asd = A_ASDG(ssast2);
n = ASD_NDIM(asd);
} else {
asd = 0;
n = AD_NUMDIM(ad2);
}
assert(n <= MAXDIMS, "mk_matmul_sptr: too many dimensions", n, 4);
j = 0;
for (i = 0; i < n; ++i) {
if (asd) {
ast = ASD_SUBS(asd, i);
if (A_TYPEG(ast) == A_TRIPLE) {
int lb, ub;
if (ASUMSZG(arr_sptr2)) {
lb = A_LBDG(ast);
ub = A_UPBDG(ast);
} else {
lb = check_member(ssast2, AD_LWAST(ad2, i));
ub = check_member(ssast2, AD_UPAST(ad2, i));
}
subscr2[j] = mk_triple(lb, ub, 0);
submap2[j] = i;
newsubs2[j] = ast;
++j;
}
} else {
int lb, ub;
lb = check_member(ssast2, AD_LWAST(ad2, i));
ub = check_member(ssast2, AD_UPAST(ad2, i));
subscr2[j] = mk_triple(lb, ub, 0);
submap2[j] = i;
newsubs2[j] = subscr2[j];
++j;
}
}
rank2 = j;
if (rank1 == 1) {
/* dimension is second dimension of second array */
assert(rank2 == 2, "mk_matmul_sptr: rank mismatch (1,2)", 0, 4);
rank = 1;
subscr[0] = subscr2[1];
newsubs[0] = newsubs2[1];
/* get the temporary */
sptr = sym_get_array(SYMNAME(arr_sptr1), purpose, elem_dty, rank);
dtype = DTYPEG(arr_sptr2);
ad2 = AD_DPTR(dtype);
/* set the bounds to the correct bounds from the arrays */
tad = AD_DPTR(DTYPEG(sptr));
if (ASUMSZG(arr_sptr2)) {
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) = A_LBDG(subscr[0]);
AD_UPBD(tad, 0) = AD_UPAST(tad, 0) = A_UPBDG(subscr[0]);
AD_EXTNTAST(tad, 0) = mk_extent(AD_LWAST(tad, 0), AD_UPAST(tad, 0), i);
} else {
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) =
check_member(ssast2, AD_LWAST(ad2, submap2[1]));
AD_UPBD(tad, 0) = AD_UPAST(tad, 0) =
check_member(ssast2, AD_UPAST(ad2, submap2[1]));
AD_EXTNTAST(tad, 0) = check_member(ssast2, AD_EXTNTAST(ad2, submap2[1]));
}
} else if (rank2 == 1) {
/* dimension is first dimension of first array */
assert(rank1 == 2, "mk_matmul_sptr: rank mismatch (2,1)", 0, 4);
rank = 1;
subscr[0] = subscr1[0];
newsubs[0] = newsubs1[0];
/* get the temporary */
sptr = sym_get_array(SYMNAME(arr_sptr1), purpose, elem_dty, rank);
dtype = DTYPEG(arr_sptr1);
ad1 = AD_DPTR(dtype);
/* set the bounds to the correct bounds from the arrays */
tad = AD_DPTR(DTYPEG(sptr));
if (ASUMSZG(arr_sptr1)) {
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) = A_LBDG(subscr[0]);
AD_UPBD(tad, 0) = AD_UPAST(tad, 0) = A_UPBDG(subscr[0]);
AD_EXTNTAST(tad, 0) = mk_extent(AD_LWAST(tad, 0), AD_UPAST(tad, 0), i);
} else {
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) =
check_member(ssast1, AD_LWAST(ad1, submap1[0]));
AD_UPBD(tad, 0) = AD_UPAST(tad, 0) =
check_member(ssast1, AD_UPAST(ad1, submap1[0]));
AD_EXTNTAST(tad, 0) = check_member(ssast1, AD_EXTNTAST(ad1, submap1[0]));
}
} else {
/* dimension is 1st of 1st and 2nd of 2nd */
assert(rank1 == 2 && rank2 == 2, "mk_matmul_sptr: rank mismatch (2,2)", 0,
4);
rank = 2;
subscr[0] = subscr1[0];
newsubs[0] = newsubs1[0];
subscr[1] = subscr2[1];
newsubs[1] = newsubs2[1];
/* get the temporary */
sptr = sym_get_array(SYMNAME(arr_sptr1), purpose, elem_dty, rank);
dtype = DTYPEG(arr_sptr1);
ad1 = AD_DPTR(dtype);
dtype = DTYPEG(arr_sptr2);
ad2 = AD_DPTR(dtype);
/* set the bounds to the correct bounds from the arrays */
tad = AD_DPTR(DTYPEG(sptr));
if (ASUMSZG(arr_sptr1)) {
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) = A_LBDG(subscr[0]);
AD_UPBD(tad, 0) = AD_UPAST(tad, 0) = A_UPBDG(subscr[0]);
AD_EXTNTAST(tad, 0) = mk_extent(AD_LWAST(tad, 0), AD_UPAST(tad, 0), 0);
} else {
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) =
check_member(ssast1, AD_LWAST(ad1, submap1[0]));
AD_UPBD(tad, 0) = AD_UPAST(tad, 0) =
check_member(ssast1, AD_UPAST(ad1, submap1[0]));
AD_EXTNTAST(tad, 0) = check_member(ssast1, AD_EXTNTAST(ad1, submap1[0]));
}
if (ASUMSZG(arr_sptr2)) {
AD_LWBD(tad, 1) = AD_LWAST(tad, 1) = A_LBDG(subscr[1]);
AD_UPBD(tad, 1) = AD_UPAST(tad, 1) = A_UPBDG(subscr[1]);
AD_EXTNTAST(tad, 1) = mk_extent(AD_LWAST(tad, 1), AD_UPAST(tad, 1), 1);
} else {
AD_LWBD(tad, 1) = AD_LWAST(tad, 1) =
check_member(ssast2, AD_LWAST(ad2, submap2[1]));
AD_UPBD(tad, 1) = AD_UPAST(tad, 1) =
check_member(ssast2, AD_UPAST(ad2, submap2[1]));
AD_EXTNTAST(tad, 1) = check_member(ssast2, AD_EXTNTAST(ad2, submap2[1]));
}
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
check_small_allocatable(sptr);
#ifdef NOEXTENTG
if (ALLOCG(sptr)) {
if ((!HCCSYMG(arr_sptr1) && CONTIGUOUS_ARR(arr_sptr1)) ||
(HCCSYMG(arr_sptr1) && SCG(arr_sptr1) == SC_LOCAL &&
CONTIGUOUS_ARR(arr_sptr1) && NOEXTENTG(arr_sptr1))) {
NOEXTENTP(sptr, 1);
}
}
#endif
/* mark as compiler created */
HCCSYMP(sptr, 1);
*retval = mk_subscr(mk_id(sptr), newsubs, rank, DTYPEG(sptr));
return sptr;
}
/*
* Make sptr for transpose
*/
int
mk_transpose_sptr(int arr_ast, const char *purpose, int *subscr, int elem_dty,
int *retval)
{
int arr_sptr;
int ast;
int submap[MAXSUBS];
int newsubs[MAXSUBS];
int i, n, j;
int asd;
int sptr, ssast;
ADSC *ad;
int dtype;
ADSC *tad;
arr_sptr = find_array(arr_ast, &ssast);
dtype = DTYPEG(arr_sptr);
ad = AD_DPTR(dtype);
/* determine how many dimensions are needed, and which ones they are */
if (A_TYPEG(ssast) == A_SUBSCR) {
asd = A_ASDG(ssast);
n = ASD_NDIM(asd);
} else {
asd = 0;
n = AD_NUMDIM(ad);
}
j = 0;
assert(n <= MAXDIMS, "mk_transpose_sptr: too many dimensions", n, 4);
for (i = 0; i < n; ++i) {
if (asd) {
ast = ASD_SUBS(asd, i);
if (A_TYPEG(ast) == A_TRIPLE) {
/* include this one */
if (ASUMSZG(arr_sptr))
subscr[j] = mk_triple(A_LBDG(ast), A_UPBDG(ast), 0);
else
subscr[j] = mk_triple(check_member(ssast, AD_LWAST(ad, i)),
check_member(ssast, AD_UPAST(ad, i)), 0);
submap[j] = i;
newsubs[j] = ast;
++j;
}
} else {
subscr[j] = mk_triple(check_member(ssast, AD_LWAST(ad, i)),
check_member(ssast, AD_UPAST(ad, i)), 0);
submap[j] = i;
newsubs[j] = subscr[j];
++j;
}
}
/* get the temporary */
assert(j == 2, "mk_transpose_sptr: not enough dimensions", 0, 4);
sptr = sym_get_array(SYMNAME(arr_sptr), purpose, elem_dty, j);
/* set the bounds to the correct bounds from the array */
ad = AD_DPTR(dtype);
tad = AD_DPTR(DTYPEG(sptr));
if (ASUMSZG(arr_sptr)) {
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) = subscr[1];
AD_UPBD(tad, 0) = AD_UPAST(tad, 0) = subscr[1];
AD_EXTNTAST(tad, 0) = mk_extent(AD_LWAST(tad, 0), AD_UPAST(tad, 0), 0);
AD_LWBD(tad, 1) = AD_LWAST(tad, 1) = subscr[0];
AD_UPBD(tad, 1) = AD_UPAST(tad, 1) = subscr[0];
AD_EXTNTAST(tad, 1) = mk_extent(AD_LWAST(tad, 1), AD_UPAST(tad, 1), 1);
} else {
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) =
check_member(arr_ast, AD_LWAST(ad, submap[1]));
AD_UPBD(tad, 0) = AD_UPAST(tad, 0) =
check_member(arr_ast, AD_UPAST(ad, submap[1]));
AD_EXTNTAST(tad, 0) =
check_member(arr_ast, mk_extent(AD_LWAST(tad, 0), AD_UPAST(tad, 0), 0));
AD_LWBD(tad, 1) = AD_LWAST(tad, 1) =
check_member(arr_ast, AD_LWAST(ad, submap[0]));
AD_UPBD(tad, 1) = AD_UPAST(tad, 1) =
check_member(arr_ast, AD_UPAST(ad, submap[0]));
AD_EXTNTAST(tad, 1) =
check_member(arr_ast, mk_extent(AD_LWAST(tad, 1), AD_UPAST(tad, 1), 1));
}
i = newsubs[1];
newsubs[1] = newsubs[0];
newsubs[0] = i;
i = subscr[1];
subscr[1] = subscr[0];
subscr[0] = i;
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
check_small_allocatable(sptr);
/* mark as compiler created */
HCCSYMP(sptr, 1);
*retval = mk_subscr(mk_id(sptr), newsubs, j, DTYPEG(sptr));
return sptr;
}
int
mk_pack_sptr(int shape, int elem_dty)
{
int sptr;
ADSC *tad;
assert(SHD_NDIM(shape) == 1, "mk_pack_sptr: not rank 1", 0, 4);
sptr = sym_get_array("pack", "r", elem_dty, 1);
tad = AD_DPTR(DTYPEG(sptr));
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) = SHD_LWB(shape, 0);
AD_UPBD(tad, 0) = AD_UPAST(tad, 0) = SHD_UPB(shape, 0);
AD_EXTNTAST(tad, 0) = mk_extent(AD_LWAST(tad, 0), AD_UPAST(tad, 0), 0);
trans_mkdescr(sptr);
check_small_allocatable(sptr);
return sptr;
}
/*
* Replicated array to hold result of 'scalar' min/maxloc
*/
int
mk_maxloc_sptr(int shape, int elem_dty)
{
int sptr;
int dtype;
ADSC *tad;
assert(SHD_NDIM(shape) == 1, "mk_maxloc_sptr: not rank 1", 0, 4);
sptr = get_next_sym("mloc", "r");
dtype = get_array_dtype(1, elem_dty);
tad = AD_DPTR(dtype);
AD_LWBD(tad, 0) = AD_LWAST(tad, 0) = SHD_LWB(shape, 0);
AD_UPBD(tad, 0) = AD_UPAST(tad, 0) = SHD_UPB(shape, 0);
AD_EXTNTAST(tad, 0) = mk_extent(AD_LWAST(tad, 0), AD_UPAST(tad, 0), 0);
DTYPEP(sptr, dtype);
STYPEP(sptr, ST_ARRAY);
DCLDP(sptr, 1);
SCP(sptr, symutl.sc);
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
return sptr;
}
/* ast to search
* list pointer of forall indices
*/
int
search_forall_var(int ast, int list)
{
int argt, n, i;
int asd;
int j;
switch (A_TYPEG(ast)) {
case A_BINOP:
if ((j = search_forall_var(A_LOPG(ast), list)) != 0)
return j;
return search_forall_var(A_ROPG(ast), list);
case A_CONV:
case A_UNOP:
case A_PAREN:
return search_forall_var(A_LOPG(ast), list);
case A_CMPLXC:
case A_CNST:
break;
case A_INTR:
case A_FUNC:
argt = A_ARGSG(ast);
n = A_ARGCNTG(ast);
for (i = 0; i < n; ++i) {
if ((j = search_forall_var(ARGT_ARG(argt, i), list)) != 0)
return j;
}
break;
case A_TRIPLE:
if ((j = search_forall_var(A_LBDG(ast), list)) != 0)
return j;
if ((j = search_forall_var(A_UPBDG(ast), list)) != 0)
return j;
if (A_STRIDEG(ast) && (j = search_forall_var(A_STRIDEG(ast), list)) != 0)
return j;
break;
case A_MEM:
return search_forall_var(A_PARENTG(ast), list);
case A_SUBSCR:
asd = A_ASDG(ast);
n = ASD_NDIM(asd);
for (i = 0; i < n; ++i)
if ((j = search_forall_var(ASD_SUBS(asd, i), list)) != 0)
return j;
return search_forall_var(A_LOPG(ast), list);
case A_ID:
for (i = list; i != 0; i = ASTLI_NEXT(i)) {
if (A_SPTRG(ast) == ASTLI_SPTR(i))
return i;
}
break;
default:
interr("search_forall_var: bad opc", ast, 3);
break;
}
return 0;
}
int
other_forall_var(int ast, int list, int fnd)
{
/* ast to search
* list pointer of forall indices
* fnd - astli item of a forall index which appears in ast
* f2731.
*/
int argt, n, i;
int asd;
int j;
switch (A_TYPEG(ast)) {
case A_BINOP:
if ((j = other_forall_var(A_LOPG(ast), list, fnd)) != 0)
return j;
return other_forall_var(A_ROPG(ast), list, fnd);
case A_CONV:
case A_UNOP:
case A_PAREN:
return other_forall_var(A_LOPG(ast), list, fnd);
case A_CMPLXC:
case A_CNST:
break;
case A_INTR:
case A_FUNC:
argt = A_ARGSG(ast);
n = A_ARGCNTG(ast);
for (i = 0; i < n; ++i) {
if ((j = other_forall_var(ARGT_ARG(argt, i), list, fnd)) != 0)
return j;
}
break;
case A_TRIPLE:
if ((j = other_forall_var(A_LBDG(ast), list, fnd)) != 0)
return j;
if ((j = other_forall_var(A_UPBDG(ast), list, fnd)) != 0)
return j;
if (A_STRIDEG(ast) &&
(j = other_forall_var(A_STRIDEG(ast), list, fnd)) != 0)
return j;
return 0;
case A_MEM:
return other_forall_var(A_PARENTG(ast), list, fnd);
case A_SUBSCR:
asd = A_ASDG(ast);
n = ASD_NDIM(asd);
for (i = 0; i < n; ++i)
if ((j = other_forall_var(ASD_SUBS(asd, i), list, fnd)) != 0)
return j;
return other_forall_var(A_LOPG(ast), list, fnd);
case A_ID:
for (i = list; i != 0; i = ASTLI_NEXT(i)) {
if (i == fnd)
continue;
if (A_SPTRG(ast) == ASTLI_SPTR(i))
return i;
}
break;
default:
interr("other_forall_var: bad opc", ast, 3);
}
return 0;
}
static int
find_alloc_size(int ast, int foralllist, int *ss, int *dtype, int *dim)
{
int argt, n, i;
int asd;
int j;
if (ast <= 0)
return 0;
switch (A_TYPEG(ast)) {
case A_BINOP:
j = find_alloc_size(A_LOPG(ast), foralllist, ss, dtype, dim);
if (j != 0)
return j;
return find_alloc_size(A_ROPG(ast), foralllist, ss, dtype, dim);
case A_CONV:
case A_UNOP:
case A_PAREN:
return find_alloc_size(A_LOPG(ast), foralllist, ss, dtype, dim);
case A_CMPLXC:
case A_CNST:
return 0;
case A_INTR:
case A_FUNC:
argt = A_ARGSG(ast);
n = A_ARGCNTG(ast);
for (i = 0; i < n; ++i) {
j = find_alloc_size(ARGT_ARG(argt, i), foralllist, ss, dtype, dim);
if (j != 0)
return j;
}
return 0;
case A_TRIPLE:
j = find_alloc_size(A_LBDG(ast), foralllist, ss, dtype, dim);
if (j != 0)
return j;
j = find_alloc_size(A_UPBDG(ast), foralllist, ss, dtype, dim);
if (j != 0)
return j;
if (A_STRIDEG(ast)) {
j = find_alloc_size(A_STRIDEG(ast), foralllist, ss, dtype, dim);
if (j != 0)
return j;
}
return 0;
case A_MEM:
return find_alloc_size(A_PARENTG(ast), foralllist, ss, dtype, dim);
case A_SUBSCR:
asd = A_ASDG(ast);
n = ASD_NDIM(asd);
for (i = 0; i < n; ++i) {
j = find_alloc_size(ASD_SUBS(asd, i), foralllist, ss, dtype, dim);
if (j != 0) {
/* this subscript? another? */
if (*ss == 0) {
*ss = ast;
*dim = i;
*dtype = DTYPEG(memsym_of_ast(ast));
}
return j;
}
}
return find_alloc_size(A_LOPG(ast), foralllist, ss, dtype, dim);
case A_ID:
for (i = foralllist; i != 0; i = ASTLI_NEXT(i)) {
if (A_SPTRG(ast) == ASTLI_SPTR(i))
return i;
}
return 0;
default:
interr("find_alloc_size: bad opc", ast, 3);
return 0;
}
}
/* subscripts (triples) for temp */
int
mk_forall_sptr_copy_section(int forall_ast, int lhs, int rhs, int *subscr,
int elem_dty)
{
int arr_sptr, ssast;
int ast;
int submap[MAXSUBS];
int i, n, j;
int asd;
int sptr;
ADSC *ad;
int dtype;
ADSC *tad;
int list;
int asd1;
int n1;
int k;
LOGICAL found;
int astli, astli1;
int nidx, nidx1;
/* find the array */
assert(A_TYPEG(lhs) == A_SUBSCR,
"mk_forall_sptr_copy_section: ast not subscript", lhs, 4);
arr_sptr = find_array(lhs, &ssast);
dtype = DTYPEG(arr_sptr);
assert(DTY(dtype) == TY_ARRAY,
"mk_forall_sptr_copy_section: subscr sym not ARRAY", arr_sptr, 4);
ad = AD_DPTR(dtype);
/* get the forall index list */
assert(A_TYPEG(forall_ast) == A_FORALL,
"mk_forall_sptr_copy_section: ast not forall", forall_ast, 4);
list = A_LISTG(forall_ast);
/* determine how many dimensions are needed, and which ones they are */
asd = A_ASDG(lhs);
n = ASD_NDIM(asd);
asd1 = A_ASDG(rhs);
n1 = ASD_NDIM(asd1);
j = 0;
assert(n <= MAXDIMS && n1 <= MAXDIMS,
"mk_forall_sptr_copy_section: too many dimensions", 0, 4);
for (k = 0; k < n1; ++k) {
astli1 = 0;
nidx1 = 0;
search_forall_idx(ASD_SUBS(asd1, k), list, &astli1, &nidx1);
assert(nidx1 < 2, "mk_forall_sptr_copy_section: something is wrong", 2,
rhs);
if (nidx1 == 1 && astli1) {
found = FALSE;
for (i = 0; i < n; i++) {
astli = 0;
nidx = 0;
search_forall_idx(ASD_SUBS(asd, i), list, &astli, &nidx);
if (astli != 0) {
assert(nidx == 1, "mk_forall_sptr_copy_section: something is wrong",
2, lhs);
if (astli == astli1) {
found = TRUE;
break;
}
}
}
assert(found, "mk_forall_sptr_copy_section: something is wrong", 0, 4);
/* include this dimension */
/* build a triplet for the allocate statement off of the
* dimensions for a */
if (ASUMSZG(arr_sptr)) {
ast = ASD_SUBS(asd, i);
if (A_TYPEG(ast) == A_TRIPLE)
subscr[j] = mk_triple(A_LBDG(ast), A_UPBDG(ast), 0);
else if (A_SHAPEG(ast)) {
int shd;
shd = A_SHAPEG(ast);
subscr[j] = mk_triple(SHD_LWB(shd, i), SHD_UPB(shd, i), 0);
} else
subscr[j] = mk_triple(A_LBDG(ASTLI_TRIPLE(astli)),
A_UPBDG(ASTLI_TRIPLE(astli)), 0);
submap[j] = i;
++j;
} else {
subscr[j] = mk_triple(check_member(lhs, AD_LWAST(ad, i)),
check_member(lhs, AD_UPAST(ad, i)), 0);
submap[j] = i;
++j;
}
}
}
/* get the temporary */
assert(j > 0, "mk_forall_sptr_copy_section: not enough dimensions", 0, 4);
sptr = sym_get_array(SYMNAME(arr_sptr), "cs", elem_dty, j);
/* set the bounds to the correct bounds from the array */
ad = AD_DPTR(dtype); /* may have realloc'd */
tad = AD_DPTR(DTYPEG(sptr));
if (!ASUMSZG(arr_sptr)) {
for (i = 0; i < j; ++i) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) =
check_member(lhs, AD_LWAST(ad, submap[i]));
AD_UPBD(tad, i) = AD_UPAST(tad, i) =
check_member(lhs, AD_UPAST(ad, submap[i]));
AD_EXTNTAST(tad, i) = mk_extent(AD_LWAST(tad, i), AD_UPAST(tad, i), i);
}
} else {
for (i = 0; i < j; ++i) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) = A_LBDG(subscr[i]);
AD_UPBD(tad, i) = AD_UPAST(tad, i) = A_UPBDG(subscr[i]);
AD_EXTNTAST(tad, i) = mk_extent(AD_LWAST(tad, i), AD_UPAST(tad, i), i);
}
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
check_small_allocatable(sptr);
/* mark as compiler created */
HCCSYMP(sptr, 1);
return sptr;
}
/* This is just like mk_forall_sptr_copy_section expect that
* It also includes scalar dimension.
*/
int
mk_forall_sptr_gatherx(int forall_ast, int lhs, int rhs, int *subscr,
int elem_dty)
{
int arr_sptr;
int ast, ssast;
int submap[MAXSUBS];
int i, n, j;
int asd;
int sptr;
ADSC *ad;
int dtype;
ADSC *tad;
int list;
int asd1;
int n1;
int k;
LOGICAL found;
int astli, astli1;
int nidx, nidx1;
/* find the array */
assert(A_TYPEG(lhs) == A_SUBSCR, "mk_forall_sptr_gatherx: ast not subscript",
lhs, 4);
arr_sptr = find_array(lhs, &ssast);
dtype = DTYPEG(arr_sptr);
assert(DTY(dtype) == TY_ARRAY, "mk_forall_sptr_gatherx: subscr sym not ARRAY",
arr_sptr, 4);
ad = AD_DPTR(dtype);
/* get the forall index list */
assert(A_TYPEG(forall_ast) == A_FORALL,
"mk_foral_sptr_gatherx: ast not forall", forall_ast, 4);
list = A_LISTG(forall_ast);
/* determine how many dimensions are needed, and which ones they are */
asd = A_ASDG(lhs);
n = ASD_NDIM(asd);
asd1 = A_ASDG(rhs);
n1 = ASD_NDIM(asd1);
j = 0;
assert(n <= MAXDIMS && n1 <= MAXDIMS,
"mk_forall_sptr_gatherx: too many dimensions", 0, 4);
for (k = 0; k < n1; ++k) {
astli1 = 0;
nidx1 = 0;
search_forall_idx(ASD_SUBS(asd1, k), list, &astli1, &nidx1);
assert(nidx1 < 2, "mk_forall_sptr_gatherx: something is wrong", 2, rhs);
if (nidx1 == 1 && astli1) {
found = FALSE;
for (i = 0; i < n; i++) {
astli = 0;
nidx = 0;
search_forall_idx(ASD_SUBS(asd, i), list, &astli, &nidx);
if (astli != 0) {
assert(nidx == 1, "mk_forall_sptr_gatherx: something is wrong", 2,
lhs);
if (astli == astli1) {
found = TRUE;
break;
}
}
}
assert(found, "mk_forall_sptr_gatherx: something is wrong", 0, 4);
/* include this dimension */
/* build a triplet for the allocate statement off of the
* dimensions for a */
if (ASUMSZG(arr_sptr)) {
ast = ASD_SUBS(asd, i);
if (A_TYPEG(ast) == A_TRIPLE)
subscr[j] = mk_triple(A_LBDG(ast), A_UPBDG(ast), 0);
else if (A_SHAPEG(ast)) {
int shd;
shd = A_SHAPEG(ast);
subscr[j] = mk_triple(SHD_LWB(shd, i), SHD_UPB(shd, i), 0);
} else
subscr[j] = mk_triple(A_LBDG(ASTLI_TRIPLE(astli)),
A_UPBDG(ASTLI_TRIPLE(astli)), 0);
submap[j] = i;
++j;
} else {
subscr[j] = mk_triple(check_member(ssast, AD_LWAST(ad, i)),
check_member(ssast, AD_UPAST(ad, i)), 0);
submap[j] = i;
++j;
}
} else if (nidx1 == 0 && astli1 == 0) {
/* include scalar dimension too */
subscr[j] = mk_triple(check_member(ssast, AD_LWAST(ad, k)),
check_member(ssast, AD_UPAST(ad, k)), 0);
submap[j] = k;
++j;
}
}
/* get the temporary */
assert(j > 0, "mk_forall_sptr_gatherx: not enough dimensions", 0, 4);
sptr = sym_get_array(SYMNAME(arr_sptr), "g", elem_dty, j);
/* set the bounds to the correct bounds from the array */
ad = AD_DPTR(dtype); /* may have realloc'd */
tad = AD_DPTR(DTYPEG(sptr));
if (!ASUMSZG(arr_sptr)) {
for (i = 0; i < j; ++i) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) =
check_member(ssast, AD_LWAST(ad, submap[i]));
AD_UPBD(tad, i) = AD_UPAST(tad, i) =
check_member(ssast, AD_UPAST(ad, submap[i]));
AD_EXTNTAST(tad, i) = check_member(ssast, AD_EXTNTAST(ad, submap[i]));
}
} else {
for (i = 0; i < j; ++i) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) = A_LBDG(subscr[i]);
AD_UPBD(tad, i) = AD_UPAST(tad, i) = A_UPBDG(subscr[i]);
AD_EXTNTAST(tad, i) = mk_extent(AD_LWAST(tad, i), AD_UPAST(tad, i), i);
}
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
check_small_allocatable(sptr);
/* mark as compiler created */
HCCSYMP(sptr, 1);
return sptr;
}
/* the size and shape of TMP will be based on both LHS and RHS.
* There are two rules for TMP:
* 1-) heading dimensions size and distribution from LHS
* 2-) tailling dimensions size from shape of arg with no distribution
*/
int
mk_forall_sptr_pure(int forall_ast, int lhs, int rhs, int *subscr, int elem_dty)
{
int submap[MAXSUBS];
int i, j;
int asd;
int sptr;
int lhs_sptr, rhs_sptr, lhsmem, rhsmem;
int ndim;
ADSC *ad;
ADSC *tad;
int list;
assert(A_TYPEG(lhs) == A_SUBSCR, "mk_forall_sptr_pure: ast not subscript",
lhs, 4);
assert(A_TYPEG(rhs) == A_SUBSCR, "mk_forall_sptr_pure: ast not subscript",
rhs, 4);
lhs_sptr = memsym_of_ast(lhs);
lhsmem = A_LOPG(lhs);
if (A_TYPEG(lhsmem) != A_MEM)
lhsmem = 0;
assert(DTY(DTYPEG(lhs_sptr)) == TY_ARRAY,
"mk_forall_sptr_pure: subscr sym not ARRAY", lhs_sptr, 4);
rhs_sptr = memsym_of_ast(rhs);
rhsmem = A_LOPG(rhs);
if (A_TYPEG(rhsmem) != A_MEM)
rhsmem = 0;
assert(DTY(DTYPEG(rhs_sptr)) == TY_ARRAY,
"mk_forall_sptr_pure: subscr sym not ARRAY", rhs_sptr, 4);
/* get the forall index list */
assert(A_TYPEG(forall_ast) == A_FORALL, "mk_forall_sptr_pure: ast not forall",
forall_ast, 4);
list = A_LISTG(forall_ast);
/* determine how many dimensions are needed, and which ones they are */
asd = A_ASDG(lhs);
ndim = ASD_NDIM(asd);
ad = AD_DPTR(DTYPEG(lhs_sptr));
j = 0;
/* find size and distribution of heading dimension from lhs */
for (i = 0; i < ndim; i++) {
/* include this dimension */
if (search_forall_var(ASD_SUBS(asd, i), list)) {
subscr[j] = mk_triple(check_member(lhsmem, AD_LWAST(ad, i)),
check_member(lhsmem, AD_UPAST(ad, i)), 0);
submap[j] = i;
++j;
}
}
/* find tailling dimension from rhs with no distribution*/
ad = AD_DPTR(DTYPEG(rhs_sptr));
asd = A_ASDG(rhs);
ndim = ASD_NDIM(asd);
for (i = 0; i < ndim; i++) {
if (A_TYPEG(ASD_SUBS(asd, i)) == A_TRIPLE || A_SHAPEG(ASD_SUBS(asd, i))) {
/* include this dimension */
subscr[j] = mk_triple(check_member(rhsmem, AD_LWAST(ad, i)),
check_member(rhsmem, AD_UPAST(ad, i)), 0);
submap[j] = -1;
++j;
}
}
/* get the temporary */
assert(j > 0 && j <= MAXDIMS, "mk_forall_sptr_pure: not enough dimensions",
j, 4);
sptr = sym_get_array(SYMNAME(lhs_sptr), "pure", elem_dty, j);
/* set the bounds to the correct bounds from the array */
tad = AD_DPTR(DTYPEG(sptr));
for (i = 0; i < j; ++i) {
AD_LWBD(tad, i) = AD_LWAST(tad, i) = A_LBDG(subscr[i]);
AD_UPBD(tad, i) = AD_UPAST(tad, i) = A_UPBDG(subscr[i]);
AD_EXTNTAST(tad, i) = mk_extent(AD_LWAST(tad, i), AD_UPAST(tad, i), i);
}
/* make the descriptors for the temporary */
trans_mkdescr(sptr);
check_small_allocatable(sptr);
/* mark as compiler created */
HCCSYMP(sptr, 1);
return sptr;
}
int
first_element(int ast)
{
int i, n, subs[MAXSUBS], asd, ss, doit, lop, dtype, parent, sptr;
switch (A_TYPEG(ast)) {
case A_SUBSCR:
/* if any subscript is a triplet, take the first one */
asd = A_ASDG(ast);
n = ASD_NDIM(asd);
doit = 0;
for (i = 0; i < n; ++i) {
ss = ASD_SUBS(asd, i);
if (A_TYPEG(ss) == A_TRIPLE) {
subs[i] = A_LBDG(ss);
doit = 1;
} else {
subs[i] = ss;
}
}
lop = A_LOPG(ast);
if (A_TYPEG(lop) == A_MEM) {
parent = first_element(A_PARENTG(lop));
if (parent != A_PARENTG(lop)) {
doit = 1;
lop = mk_member(parent, A_MEMG(lop), A_DTYPEG(lop));
}
}
if (doit) {
ast = mk_subscr(lop, subs, n, A_DTYPEG(ast));
}
break;
case A_ID:
sptr = A_SPTRG(ast);
parent = 0;
goto hit;
case A_MEM:
sptr = A_SPTRG(A_MEMG(ast));
parent = first_element(A_PARENTG(ast));
if (parent != A_PARENTG(ast)) {
ast = mk_member(parent, A_MEMG(ast), A_DTYPEG(ast));
}
hit:
dtype = DTYPEG(sptr);
if (DTY(dtype) == TY_ARRAY) {
n = ADD_NUMDIM(dtype);
for (i = 0; i < n; ++i) {
if (ADD_LWAST(dtype, i))
subs[i] = check_member(ast, ADD_LWAST(dtype, i));
else
subs[i] = astb.bnd.one;
}
ast = mk_subscr(ast, subs, n, DTY(dtype + 1));
}
}
return ast;
} /* first_element */
int
mk_mem_allocate(int in_ast, int *subscr, int alloc_stmt, int ast_len_from)
{
int n, ast, shape, dtype, eldtype, sptr;
int atp;
int newstd = 0;
int par;
int task;
par = STD_PAR(alloc_stmt);
task = STD_TASK(alloc_stmt);
shape = A_SHAPEG(in_ast);
assert(shape != 0, "mk_mem_allocate: no shape", in_ast, 4);
n = SHD_NDIM(shape);
if (A_TYPEG(in_ast) == A_ID) {
sptr = A_SPTRG(in_ast);
} else if (A_TYPEG(in_ast) == A_MEM) {
sptr = A_SPTRG(A_MEMG(in_ast));
} else {
interr("mk_mem_allocate: not id/member", in_ast, 4);
sptr = 0;
}
if (sptr && !ALLOCG(sptr) && !POINTERG(sptr) && !ADJARRG(sptr) &&
!ADJLENG(sptr))
return 0;
dtype = A_DTYPEG(in_ast);
eldtype = DDTG(dtype);
if (ast_len_from && (eldtype == DT_ASSCHAR || eldtype == DT_ASSNCHAR ||
eldtype == DT_DEFERCHAR || eldtype == DT_DEFERNCHAR) &&
!EARLYSPECG(sptr)) {
int cvsptr, cvast, cvlenast;
int cvlen = CVLENG(sptr);
if (eldtype == DT_ASSCHAR || eldtype == DT_ASSNCHAR) {
if (cvlen == 0) {
cvlen = sym_get_scalar(SYMNAME(sptr), "len", DT_INT);
CVLENP(sptr, cvlen);
if (SCG(sptr) == SC_DUMMY)
CCSYMP(cvlen, 1);
}
ADJLENP(sptr, 1);
cvlenast = mk_id(cvlen);
} else {
cvlenast = get_len_of_deferchar_ast(in_ast);
}
ast = mk_stmt(A_ASN, 0);
A_DESTP(ast, cvlenast);
/* see if the source length can be resolved a little */
cvsptr = 0;
cvast = ast_len_from;
if (A_TYPEG(cvast) == A_SUBSCR) {
cvast = A_LOPG(cvast);
}
if (A_TYPEG(cvast) == A_ID) {
cvsptr = A_SPTRG(cvast);
} else if (A_TYPEG(cvast) == A_MEM) {
cvsptr = A_SPTRG(A_MEMG(cvast));
}
if (cvsptr) {
int cvdtype = DDTG(DTYPEG(cvsptr));
if (cvdtype == DT_ASSCHAR || cvdtype == DT_ASSNCHAR) {
if (CVLENG(cvsptr)) {
atp = mk_id(CVLENG(cvsptr));
A_SRCP(ast, atp);
} else { /* formal argument */
atp = size_ast(cvsptr, cvdtype);
A_SRCP(ast, atp);
}
} else if (cvdtype == DT_DEFERCHAR || cvdtype == DT_DEFERNCHAR) {
cvsptr = 0;
} else if (DTY(cvdtype) == TY_CHAR || DTY(cvdtype) == TY_NCHAR) {
A_SRCP(ast, DTY(cvdtype + 1));
} else {
cvsptr = 0;
}
}
if (cvsptr == 0) {
ast_len_from = first_element(ast_len_from);
atp = ast_intr(I_LEN, DT_INT, 1, ast_len_from);
A_SRCP(ast, atp);
}
newstd = add_stmt_before(ast, alloc_stmt);
STD_PAR(newstd) = par;
STD_TASK(newstd) = task;
} else if ((DTY(eldtype) == TY_CHAR || DTY(eldtype) == TY_NCHAR) &&
(DTY(eldtype + 1) == 0 ||
(DTY(eldtype + 1) > 0 && !A_ALIASG(DTY(eldtype + 1)))) &&
!EARLYSPECG(sptr)) {
/* nonconstant length */
int rhs;
int cvlen = CVLENG(sptr);
if (cvlen == 0) {
cvlen = sym_get_scalar(SYMNAME(sptr), "len", DT_INT);
CVLENP(sptr, cvlen);
if (SCG(sptr) == SC_DUMMY)
CCSYMP(cvlen, 1);
}
ADJLENP(sptr, 1);
ast = mk_stmt(A_ASN, 0);
atp = mk_id(cvlen);
A_DESTP(ast, atp);
rhs = DTY(eldtype + 1);
rhs = mk_convert(rhs, DTYPEG(cvlen));
rhs = ast_intr(I_MAX, DTYPEG(cvlen), 2, rhs, mk_cval(0, DTYPEG(cvlen)));
A_SRCP(ast, rhs);
newstd = add_stmt_before(ast, alloc_stmt);
STD_PAR(newstd) = par;
STD_TASK(newstd) = task;
}
/* build and insert the allocate statement */
ast = mk_stmt(A_ALLOC, 0);
A_TKNP(ast, TK_ALLOCATE);
A_LOPP(ast, 0);
if (subscr != 0) {
/*
* As per the Fortran spec, ALLOCATE allocates an array of size
* zero when lb>ub. If the variable being allocated is a compiler
* generated temp to hold the result of an expression that has a
* negative stride, then the lb>ub. Reset the ub, lb, and stride
* for this case (tpr3551)
*
* Update -- resetting the ub, lb, and stride has the effect of
* computing the exact size needed for the temp. However, the
* subscripts for the temp are not normalized with respect to
* the actual size -- the original strided subscripts are used
* and therefore, array bounds violations will occur. The computed
* size just needs the direction of the stride (1 or -1) factored in;
* the direction just needs to be computed as sign(1,stride).
*/
if (A_TYPEG(in_ast) == A_ID && (HCCSYMG(sptr) || CCSYMG(sptr))) {
int newsubscr[MAXSUBS];
fixup_allocd_tmp_bounds(subscr, newsubscr, n);
atp = mk_subscr(in_ast, newsubscr, n, DDTG(A_DTYPEG(in_ast)));
} else {
atp = mk_subscr(in_ast, subscr, n, DDTG(A_DTYPEG(in_ast)));
}
A_SRCP(ast, atp);
} else
A_SRCP(ast, in_ast);
newstd = add_stmt_before(ast, alloc_stmt);
STD_PAR(newstd) = par;
STD_TASK(newstd) = task;
return newstd;
}
/* see mk_mem_allocate -- should be always called */
int
mk_mem_deallocate(int in_ast, int dealloc_stmt)
{
int ast, sptr;
int par, task;
int newstd = 0;
/* build and insert the deallocate statement */
assert(A_SHAPEG(in_ast), "mk_mem_deallocate: var not array", in_ast, 4);
sptr = memsym_of_ast(in_ast);
if (sptr && !ALLOCG(sptr) && !POINTERG(sptr) && !ADJARRG(sptr) &&
!ADJLENG(sptr))
return 0;
par = STD_PAR(dealloc_stmt);
task = STD_TASK(dealloc_stmt);
ast = mk_stmt(A_ALLOC, 0);
A_TKNP(ast, TK_DEALLOCATE);
A_LOPP(ast, 0);
A_SRCP(ast, in_ast);
newstd = add_stmt_after(ast, dealloc_stmt);
STD_PAR(newstd) = par;
STD_TASK(newstd) = task;
return newstd;
}
typedef struct {
int count0;
int count1;
int count2;
int count3;
int count4;
int count5;
int count6;
int count7;
int count8;
int count9;
int count10;
int count11;
int count12;
} BOUND;
static BOUND bound;
void
init_bnd(void)
{
if (gbl.internal)
return;
bound.count0 = 0;
bound.count1 = 0;
bound.count2 = 0;
bound.count3 = 0;
bound.count4 = 0;
bound.count5 = 0;
bound.count6 = 0;
bound.count7 = 0;
bound.count8 = 0;
bound.count9 = 0;
bound.count10 = 0;
bound.count11 = 0;
bound.count12 = 0;
}
int
getbnd(const char *basename, const char *purpose, int n, int dtype)
{
int sptr;
#if DEBUG
assert(n >= 0 && n <= 99999, "getbnd-n too large", n, 0);
#endif
if (n) {
if (purpose)
sptr = getsymf("%s%s%s%d", basename, "$$", purpose, n);
else
sptr = getsymf("%s%d", basename, n);
} else {
if (purpose)
sptr = getsymf("%s%s%s", basename, "$$", purpose);
else
sptr = getsymbol(basename);
}
if (gbl.internal > 1 && !INTERNALG(sptr))
sptr = insert_sym(sptr);
assert(STYPEG(sptr) == ST_UNKNOWN, "getbnd: name crash", sptr, 2);
DTYPEP(sptr, dtype);
STYPEP(sptr, ST_VAR);
DCLDP(sptr, 1);
SCP(sptr, SC_LOCAL);
NODESCP(sptr, 1);
HCCSYMP(sptr, 1);
return sptr;
}
int
trans_getbound(int sym, int type)
{
int sptr;
switch (type) {
case 0:
sptr = getbnd("i", "l", bound.count0, DT_INT);
bound.count0++;
return sptr;
case 1:
sptr = getbnd("i", "u", bound.count1, DT_INT);
bound.count1++;
return sptr;
case 2:
sptr = getbnd("i", "s", bound.count2, DT_INT);
bound.count2++;
return sptr;
case 3:
sptr = getbnd("c", "l", bound.count3, DT_INT);
bound.count3++;
return sptr;
case 4:
sptr = getbnd("c", "u", bound.count4, DT_INT);
bound.count4++;
return sptr;
case 5:
sptr = getbnd("c", "cs", bound.count5, DT_INT);
bound.count5++;
return sptr;
case 6:
sptr = getbnd("c", "lo", bound.count6, DT_INT);
bound.count6++;
return sptr;
case 7:
sptr = getbnd("c", "ls", bound.count7, DT_INT);
bound.count7++;
return sptr;
case 8:
sptr = getbnd("i", "c", bound.count8, DT_INT);
bound.count8++;
return sptr;
case 9:
sptr = getbnd("l", "b", bound.count9, DT_INT);
bound.count9++;
return sptr;
case 10:
sptr = getbnd("u", "b", bound.count10, DT_INT);
bound.count10++;
return sptr;
case 11:
sptr = getbnd("cp", "com", bound.count11, DT_INT);
bound.count11++;
return sptr;
case 12:
sptr = getbnd("xfer", "com", bound.count12, DT_INT);
bound.count12++;
return sptr;
default:
assert(TRUE, "trans_getbound: unknown type", 0, 4);
sptr = getbnd("i", "l", bound.count0, DT_INT);
bound.count0++;
return sptr;
}
}
/* astmem is either zero, or an A_MEM */
/* astid is an A_ID */
/* if astmem is zero, return astid; otherwise, return an A_MEM with
* the same parent as astmem, and with astid as member */
int
check_member(int astmem, int astid)
{
if (astmem != 0 && A_TYPEG(astmem) == A_SUBSCR) {
astmem = A_LOPG(astmem);
}
if (astmem == 0 || A_TYPEG(astmem) != A_MEM) {
int sptr, stype;
/* error check */
/* astid may be A_ID or A_SUBSCR */
if (A_TYPEG(astid) == A_ID) {
sptr = A_SPTRG(astid);
} else if (A_TYPEG(astid) == A_SUBSCR) {
int lop;
lop = A_LOPG(astid);
if (A_TYPEG(lop) != A_ID)
return astid;
sptr = A_SPTRG(lop);
} else {
return astid;
}
stype = STYPEG(sptr);
if (stype == ST_ARRDSC) {
int secdsc;
secdsc = SECDSCG(sptr);
if (secdsc) {
stype = STYPEG(secdsc);
} else {
stype = STYPEG(ARRAYG(sptr));
}
}
if (stype == ST_MEMBER && !DESCARRAYG(sptr)) {
interr("check_member: cannot match member with derived type", sptr, 3);
}
return astid;
}
/* In the new array/pointer runtime descriptor, the extent may be an
* expression of lower bound and upper bound. Handle this case.
*/
if (A_TYPEG(astid) == A_BINOP) {
/* get the values we need, in case astb.stg_base gets reallocated! */
int lop = check_member(astmem, A_LOPG(astid));
int rop = check_member(astmem, A_ROPG(astid));
return mk_binop(A_OPTYPEG(astid), lop, rop, A_DTYPEG(astid));
}
/* check that the ID is a ST_MEMBER of the same datatype */
if (A_TYPEG(astid) == A_ID) {
return do_check_member_id(astmem, astid);
}
if (A_TYPEG(astid) == A_SUBSCR) {
int lop = A_LOPG(astid);
if (A_TYPEG(lop) != A_ID) {
return astid;
} else {
int subs[MAXSUBS];
int i;
int lop2 = do_check_member_id(astmem, lop);
int asd = A_ASDG(astid);
int n = ASD_NDIM(asd);
for (i = 0; i < n; ++i) {
subs[i] = ASD_SUBS(asd, i);
}
return mk_subscr(lop2, subs, n, A_DTYPEG(astid));
}
}
return astid;
} /* check_member */
static int
do_check_member_id(int astmem, int astid)
{
int sptr2, checksptr;
int sptr = A_SPTRG(astid);
SYMTYPE stype = STYPEG(sptr);
assert(A_TYPEG(astid) == A_ID, "expecting A_TYPE == A_ID",
A_TYPEG(astid), ERR_Fatal);
if (XBIT(58, 0x10000) && stype == ST_ARRDSC) {
checksptr = ARRAYG(sptr);
if (checksptr && SDSCG(checksptr)) {
checksptr = SDSCG(checksptr);
stype = STYPEG(checksptr);
} else if (checksptr) {
/* see if the array is a member and needs a local
* section descriptor */
DTYPE dtype = DTYPEG(checksptr);
if (ALIGNG(checksptr) || DISTG(checksptr) || POINTERG(checksptr) ||
ADD_DEFER(dtype) || ADD_ADJARR(dtype) || ADD_NOBOUNDS(dtype)) {
stype = STYPEG(checksptr);
}
}
} else {
checksptr = sptr;
}
if (stype != ST_MEMBER) {
return astid;
}
sptr2 = A_SPTRG(A_MEMG(astmem));
if (ENCLDTYPEG(checksptr) != ENCLDTYPEG(sptr2)) {
interr("check_member: member arrived with wrong derived type", sptr, 3);
}
return mk_member(A_PARENTG(astmem), astid, A_DTYPEG(astid));
}
/* get the first symbol with the same hash link */
int
first_hash(int sptr)
{
char *name;
int len, hashval;
name = SYMNAME(sptr);
len = strlen(name);
HASH_ID(hashval, name, len);
if (hashval < 0)
hashval = -hashval;
return stb.hashtb[hashval];
} /* first_hash */
LOGICAL
has_allocattr(int sptr)
{
int dtype;
if (ALLOCATTRG(sptr))
return TRUE;
dtype = DTYPEG(sptr);
dtype = DDTG(dtype);
if (DTY(dtype) == TY_DERIVED && ALLOCFLDG(DTY(dtype + 3)))
return TRUE;
return FALSE;
}
/**
* \brief utility function for visiting symbols of a specified name.
*
* This function is used to visit symbols of a specified name. The user of
* this function should first initialize the search by calling the function
* with task == 0.
*
* After initializing the search, the user can call this function with the
* same sptr and a task == 1 or task == 2. The function
* will return the sptr of the next unvisited symbol based on the criteria
* specified in the task argument. Below summarizes the values for task:
*
* If task == 0, then this function will unset the VISIT flag for all symbols
* with the same name as sptr.
*
* If task == 1, then return symbol must have the same symbol table type
* as the sptr argument.
*
* If task == 2, then the returned symbol can have any symbol table type.
*
* Caveat: Do not use this function when another phase is using the
* the VISIT field. For example, during the lower phase.
*
* \param sptr is the symbol table pointer of the name you wish to find.
* \param task is the task the function will perform (see comments above).
*
* \return symbol table pointer of next unvisited symbol or 0 if no more
* symbols have been found.
*/
int
get_next_hash_link(int sptr, int task)
{
int hash, hptr, len;
char *symname;
if (!sptr)
return 0;
symname = SYMNAME(sptr);
len = strlen(symname);
HASH_ID(hash, symname, len);
if (task == 0) {
/* init visit flag for all symbols with same name as sptr */
for (hptr = stb.hashtb[hash]; hptr; hptr = HASHLKG(hptr)) {
if (STYPEG(hptr) == STYPEG(sptr) && strcmp(symname, SYMNAME(hptr)) == 0) {
VISITP(hptr, 0);
}
}
} else if (task == 1) {
VISITP(sptr, 1);
for (hptr = stb.hashtb[hash]; hptr; hptr = HASHLKG(hptr)) {
if (hptr != sptr && !VISITG(hptr) && STYPEG(hptr) == STYPEG(sptr) &&
strcmp(symname, SYMNAME(hptr)) == 0) {
return hptr;
}
}
} else if (task == 2) {
VISITP(sptr, 1);
for (hptr = stb.hashtb[hash]; hptr; hptr = HASHLKG(hptr)) {
if (hptr != sptr && !VISITG(hptr) &&
strcmp(symname, SYMNAME(hptr)) == 0) {
return hptr;
}
}
}
return 0;
}
/** \brief utility function for finding a symbol in the symbol table that
* has a specified name.
*
* Note: The first symbol that meets the criteria specified in the arguments
* is returned. If you need to make multiple queries of the symbol table,
* consider using the function get_next_hash_link() instead.
*
* \param symname is a C string that specifies the name of the symbol to find
* \param stype specifies a particular symbol type to find or 0 will locate
* any symbol type.
* \param scope specifies the scope symbol table pointer to search for the
* symbol. If scope is 0 then the symbol can appear in any scope.
* If scope is -1, then the first symbol that's in scope is returned.
*
* \return symbol table pointer of the first symbol found that meets the
* criteria mentioned above; else 0.
*/
int
findByNameStypeScope(char *symname, int stype, int scope)
{
int hash, hptr, len;
len = strlen(symname);
HASH_ID(hash, symname, len);
for (hptr = stb.hashtb[hash]; hptr; hptr = HASHLKG(hptr)) {
if ((stype == 0 || STYPEG(hptr) == stype) &&
strcmp(SYMNAME(hptr), symname) == 0) {
if (scope == 0 || (scope == -1 && test_scope(hptr) > 0) ||
scope == SCOPEG(hptr)) {
return hptr;
}
}
}
return 0;
}
LOGICAL
is_array_sptr(int sptr)
{
if (sptr > NOSYM) {
switch (STYPEG(sptr)) {
case ST_ARRAY:
return TRUE;
case ST_VAR:
return is_array_dtype(DTYPEG(sptr));
default:
return FALSE;
}
}
return FALSE;
}
LOGICAL
is_unl_poly(int sptr)
{
return sptr > NOSYM &&
CLASSG(sptr) &&
is_dtype_unlimited_polymorphic(DTYPEG(sptr));
}
bool
is_impure(int sptr)
{
if ((STYPEG(sptr) == ST_INTRIN || STYPEG(sptr) == ST_PD) &&
INKINDG(sptr) == IK_ELEMENTAL)
return false;
return IMPUREG(sptr) || (!PUREG(sptr) && !ELEMENTALG(sptr));
}
LOGICAL
needs_descriptor(int sptr)
{
if (sptr > NOSYM) {
if (IS_PROC_DUMMYG(sptr)) {
return TRUE;
}
if (ST_ISVAR(STYPEG(sptr)) || STYPEG(sptr) == ST_IDENT) {
DTYPE dtype = DTYPEG(sptr);
return ASSUMSHPG(sptr) || POINTERG(sptr) || ALLOCATTRG(sptr) ||
IS_PROC_DUMMYG(sptr) ||
(is_array_dtype(dtype) && ADD_ASSUMSHP(dtype));
}
}
/* N.B. Scalar CLASS polymorphic dummy arguments get type descriptors only,
* not full descriptors, as a special case in add_class_arg_descr_arg().
*/
return FALSE;
}
/* \brief Returns true if a procedure dummy argument needs a procedure
* descriptor.
*
* By default, we do not use a descriptor argument for dummy arguments
* declared EXTERNAL since they could be non-Fortran procedures.
* If the procedure dummy argument is an interface, not declared
* EXTERNAL, or a part of an internal procedure, then we assume it is a Fortran
* procedure and we will use a descriptor argument.
*
* XBIT(54, 0x20) overrides this restriction. That is, we will always use a
* procedure descriptor when XBIT(54, 0x20) is enabled.
*
* \param symfunc is the procedure dummy argument we are testing.
*
* \return true if procedure dummy needs a descriptor; else false.
*/
bool
proc_arg_needs_proc_desc(SPTR symfunc)
{
return IS_PROC_DUMMYG(symfunc) && (XBIT(54, 0x20) ||
IS_INTERFACEG(symfunc) || !TYPDG(symfunc) || INTERNALG(gbl.currsub));
}
/* This function encloses an idiom that appears more than once in the
* Fortran front-end to follow the symbol linkage convention
* used to locate descriptor members in derived types.
*/
SPTR
get_member_descriptor(int sptr)
{
SPTR mem;
assert(sptr > NOSYM && STYPEG(sptr) == ST_MEMBER,
"get_member_descriptor: bad member", sptr, ERR_Severe);
for (mem = SYMLKG(sptr); mem > NOSYM && HCCSYMG(mem); mem = SYMLKG(mem)) {
if (DESCARRAYG(mem))
return mem;
}
return NOSYM;
}
int
find_member_descriptor(int sptr)
{
if (sptr > NOSYM && STYPEG(sptr) == ST_MEMBER &&
(CLASSG(sptr) || FINALIZEDG(sptr))) {
int dsc_mem = get_member_descriptor(sptr);
if (dsc_mem > NOSYM && DESCARRAYG(dsc_mem))
return dsc_mem;
}
return 0;
}
/* Ferret out a variable's descriptor from any of the places in which
* the front-end might have hidden it. Represent it as an AST
* if it exists.
*/
int
find_descriptor_ast(int sptr, int ast)
{
int desc_ast, desc_sptr;
if (sptr <= NOSYM)
return 0;
if ((desc_ast = DSCASTG(sptr)))
return desc_ast;
if ((desc_sptr = find_member_descriptor(sptr)) > NOSYM ||
(desc_sptr = SDSCG(sptr)) > NOSYM ||
(desc_sptr = DESCRG(sptr)) > NOSYM) {
if (STYPEG(desc_sptr) != ST_MEMBER || ast > 0) {
desc_ast = mk_id(desc_sptr);
if (STYPEG(desc_sptr) == ST_MEMBER)
desc_ast = check_member(ast, desc_ast);
DESCUSEDP(sptr, TRUE);
return desc_ast;
}
}
if (SCG(sptr) == SC_DUMMY && CLASSG(sptr)) {
/* Identify a type descriptor argument */
int scope_sptr = gbl.currsub;
if (gbl.internal > 0)
scope_sptr = resolve_sym_aliases(SCOPEG(sptr));
desc_sptr = get_type_descr_arg(scope_sptr, sptr);
if (desc_sptr > NOSYM) {
DESCUSEDP(sptr, TRUE);
return mk_id(desc_sptr);
}
}
return 0;
}
/* Scan a dummy argument list for a specific symbol's name (if valid) and
* return its 1-based position if it's present in the list, else 0.
* Done the hard way by comparing names, ignoring case.
*/
int
find_dummy_position(int proc_sptr, int arg_sptr)
{
if (proc_sptr > NOSYM && arg_sptr > NOSYM) {
const char *name = SYMNAME(arg_sptr);
int paramct, dpdsc, iface;
proc_arginfo(proc_sptr, ¶mct, &dpdsc, &iface);
if (dpdsc > 0) {
int j, *argument = &aux.dpdsc_base[dpdsc];
for (j = 0; j < paramct; ++j) {
if (argument[j] > NOSYM && strcmp(SYMNAME(argument[j]), name) == 0)
return 1 + j; /* 1-based list position */
}
}
}
return 0;
}
/* Scan the whole symbol table(!) and return the maximum value of
* the INVOBJ field for every valid binding of a t.b.p. for which
* the argument is an implementation without NOPASS.
*/
int
max_binding_invobj(int impl_sptr, int invobj)
{
int sptr;
for (sptr = 1; sptr < stb.stg_avail; ++sptr) {
if (STYPEG(sptr) == ST_MEMBER && CLASSG(sptr) &&
VTABLEG(sptr) == impl_sptr && !NOPASSG(sptr)) {
int bind_sptr = BINDG(sptr);
if (bind_sptr > NOSYM && INVOBJG(bind_sptr) > invobj)
invobj = INVOBJG(bind_sptr);
}
}
return invobj;
}
static LOGICAL
test_tbp_or_final(int sptr)
{
/* Subtlety: For type-bound procedures, BIND and VTABLE are nonzero,
* but might be set to NOSYM (1). The FINAL field's value is documented
* as being the rank of the final procedure's argument plus one, but
* it can also be -1 to represent a forward reference to a final subroutine.
*/
return sptr > NOSYM && STYPEG(sptr) == ST_MEMBER && CCSYMG(sptr) &&
CLASSG(sptr) && VTABLEG(sptr) != 0;
}
LOGICAL
is_tbp(int sptr)
{
return test_tbp_or_final(sptr) && (BINDG(sptr) != 0 || IS_TBP(sptr));
}
LOGICAL
is_final_procedure(int sptr)
{
return test_tbp_or_final(sptr) && FINALG(sptr) != 0;
}
LOGICAL
is_tbp_or_final(int sptr)
{
return is_tbp(sptr) || is_final_procedure(sptr);
}
/** \brief create a temporary variable that holds a temporary descriptor.
*
* \param dtype is the data type of the temporary variable.
*
* \returns the temporary variable.
*/
int
get_tmp_descr(DTYPE dtype)
{
int tmpv = getcctmp_sc('d', sem.dtemps++, ST_VAR, dtype, sem.sc);
if (DTY(dtype) != TY_ARRAY && !SDSCG(tmpv)) {
set_descriptor_rank(1); /* force a full (true) descriptor on a scalar */
get_static_descriptor(tmpv);
set_descriptor_rank(0);
} else if (!SDSCG(tmpv)) {
get_static_descriptor(tmpv);
}
return tmpv;
}
/** \brief get a temporary procedure pointer to a specified procedure.
*
* \param sptr is the ST_PROC pointer target.
*
* \returns the procedure pointer.
*/
SPTR
get_proc_ptr(SPTR sptr)
{
DTYPE dtype;
SPTR tmpv;
int sc;
if (!IS_PROC(STYPEG(sptr)))
return NOSYM;
dtype = DTYPEG(sptr);
tmpv = getcctmp_sc('d', sem.dtemps++, ST_VAR, dtype, sem.sc);
dtype = get_type(6, TY_PROC, dtype);
DTY(dtype + 2) = sptr; /* interface */
DTY(dtype + 3) = PARAMCTG(sptr); /* PARAMCT */
DTY(dtype + 4) = DPDSCG(sptr); /* DPDSC */
DTY(dtype + 5) = FVALG(sptr); /* FVAL */
dtype = get_type(2, TY_PTR, dtype);
POINTERP(tmpv, 1);
DTYPEP(tmpv, dtype);
sc = get_descriptor_sc();
set_descriptor_sc(SC_LOCAL);
get_static_descriptor(tmpv);
set_descriptor_sc(sc);
return tmpv;
}
/* Build an AST that references the byte length field in a descriptor,
* if it exists and can be subscripted, else return 0.
*/
int
get_descriptor_length_ast(int descriptor_ast)
{
if (descriptor_ast > 0 && is_array_dtype(A_DTYPEG(descriptor_ast))) {
int subs = mk_isz_cval(get_byte_len_indx(), astb.bnd.dtype);
return mk_subscr(descriptor_ast, &subs, 1, astb.bnd.dtype);
}
return 0;
}
/* If a symbol has a descriptor that might need its byte length field
* defined, return an AST to which the length should be stored, else 0.
*/
int
symbol_descriptor_length_ast(SPTR sptr, int ast)
{
int descr_ast = find_descriptor_ast(sptr, ast);
if (descr_ast > 0) {
DTYPE dtype = DTYPEG(sptr);
if (DT_ISCHAR(dtype) ||
is_unl_poly(sptr) ||
is_array_dtype(dtype)) {
return get_descriptor_length_ast(descr_ast);
}
}
return 0;
}
/* Build an AST to characterize the length of a value.
* Pass values for arguments when they're known, or the
* appropriate invalid value (NOSYM, DT_NONE, &c.) when not.
*/
int
get_value_length_ast(DTYPE value_dtype, int value_ast,
SPTR sptr, DTYPE sptr_dtype,
int value_descr_ast)
{
int ast;
if (value_dtype > DT_NONE) {
if (is_array_dtype(value_dtype))
value_dtype = array_element_dtype(value_dtype);
if (DT_ISCHAR(value_dtype)) {
int len = string_length(value_dtype);
if (len > 0) {
return mk_isz_cval(len, astb.bnd.dtype);
}
if ((ast = DTY(value_dtype + 1)) > 0) {
return ast;
}
if (value_ast > 0 &&
(ast = string_expr_length(value_ast)) > 0) {
return ast;
}
}
}
if (sptr > NOSYM && sptr_dtype > DT_NONE &&
(ast = size_ast(sptr, sptr_dtype)) > 0)
return ast;
return get_descriptor_length_ast(value_descr_ast);
}
void
add_auto_len(int sym, int Lbegin)
{
int dtype, cvlen;
int lhs, rhs, ast, std;
dtype = DDTG(DTYPEG(sym));
if (DTY(dtype) != TY_CHAR && DTY(dtype) != TY_NCHAR)
return;
cvlen = CVLENG(sym);
#if DEBUG
assert(
(DDTG(DTYPEG(sym)) != DT_DEFERCHAR && DDTG(DTYPEG(sym)) != DT_DEFERNCHAR),
"set_auto_len: arg is deferred-length character", sym, 4);
#endif
if (cvlen == 0) {
cvlen = sym_get_scalar(SYMNAME(sym), "len", DT_INT);
CVLENP(sym, cvlen);
ADJLENP(sym, 1);
if (SCG(sym) == SC_DUMMY)
CCSYMP(cvlen, 1);
}
/* If EARLYSPEC is set, the length assignment was done earlier. */
if (!EARLYSPECG(CVLENG(sym))) {
lhs = mk_id(cvlen);
rhs = DTyCharLength(dtype);
rhs = mk_convert(rhs, DTYPEG(cvlen));
rhs = ast_intr(I_MAX, DTYPEG(cvlen), 2, rhs, mk_cval(0, DTYPEG(cvlen)));
ast = mk_assn_stmt(lhs, rhs, DTYPEG(cvlen));
std = add_stmt_before(ast, Lbegin);
}
} /* add_auto_len */
| 60,168 |
450 | "doc"
class Test:
"'No attribute (alias) found' warning should not be generated"
def __init__(self):
self.alias()
def real(self):
pass
alias = real
def rcParseTest(a = 10, b = 'ten', c = (5, 5)):
print '%s, %s, %s' % (a, b, str(c))
def a(i):
[0, 1, 3].index(i)
| 147 |
1,139 | <gh_stars>1000+
package com.journaldev.layoutsparttwo;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by anupamchugh on 23/10/15.
*/
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_frame);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
} | 173 |
584 | package com.mercury.platform.ui.adr.components;
import com.mercury.platform.shared.config.Configuration;
import com.mercury.platform.shared.config.descriptor.FrameDescriptor;
import com.mercury.platform.shared.config.descriptor.adr.AdrComponentDescriptor;
import com.mercury.platform.shared.config.descriptor.adr.AdrProfileDescriptor;
import com.mercury.platform.shared.store.MercuryStoreCore;
import com.mercury.platform.ui.adr.components.panel.page.AdrPagePanel;
import com.mercury.platform.ui.adr.components.panel.tree.AdrTreePanel;
import com.mercury.platform.ui.adr.components.panel.tree.main.AdrMainTreeNodeRenderer;
import com.mercury.platform.ui.adr.dialog.AdrExportDialog;
import com.mercury.platform.ui.adr.dialog.AdrIconSelectDialog;
import com.mercury.platform.ui.adr.dialog.AdrNewProfileDialog;
import com.mercury.platform.ui.adr.routing.AdrPageDefinition;
import com.mercury.platform.ui.adr.routing.AdrPageState;
import com.mercury.platform.ui.components.fields.font.FontStyle;
import com.mercury.platform.ui.frame.titled.AbstractTitledComponentFrame;
import com.mercury.platform.ui.manager.FramesManager;
import com.mercury.platform.ui.misc.AppThemeColor;
import com.mercury.platform.ui.misc.MercuryStoreUI;
import com.mercury.platform.ui.misc.TooltipConstants;
import lombok.Getter;
import javax.swing.*;
import javax.swing.plaf.InsetsUIResource;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class AdrManagerFrame extends AbstractTitledComponentFrame {
private JPanel currentPage;
private JPanel root;
private AdrTreePanel tree;
private JComboBox profileSelector;
private AdrExportDialog exportDialog;
private AdrIconSelectDialog iconSelectDialog;
@Getter
private AdrProfileDescriptor selectedProfile;
public AdrManagerFrame(AdrProfileDescriptor selectedProfile) {
super();
this.processingHideEvent = false;
this.setTitle("MercuryTrade ADR");
this.setFocusable(true);
this.setFocusableWindowState(true);
this.setAlwaysOnTop(false);
this.selectedProfile = selectedProfile;
this.exportDialog = new AdrExportDialog(this, new ArrayList<>());
this.iconSelectDialog = new AdrIconSelectDialog();
this.iconSelectDialog.setLocationRelativeTo(null);
FrameDescriptor frameDescriptor = this.framesConfig.get(this.getClass().getSimpleName());
this.setPreferredSize(frameDescriptor.getFrameSize());
UIManager.put("MenuItem.background", AppThemeColor.ADR_BG);
UIManager.put("MenuItem.selectionBackground", AppThemeColor.ADR_POPUP_BG);
UIManager.put("Menu.contentMargins", new InsetsUIResource(2, 0, 2, 0));
UIManager.put("MenuItem.opaque", true);
UIManager.put("ComboBox.selectionBackground", AppThemeColor.HEADER);
UIManager.put("ComboBox.selectionForeground", AppThemeColor.ADR_POPUP_BG);
UIManager.put("ComboBox.disabledForeground", AppThemeColor.ADR_FOOTER_BG);
}
@Override
public void onViewInit() {
this.initRootPanel();
this.hideButton.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
MercuryStoreCore.showingDelaySubject.onNext(true);
FramesManager.INSTANCE.performAdr();
}
}
});
this.add(this.root, BorderLayout.CENTER);
this.add(this.getBottomPanel(), BorderLayout.PAGE_END);
}
public void setPage(AdrPagePanel page) {
if (currentPage != null) {
this.root.remove(currentPage);
}
this.root.add(page, BorderLayout.CENTER);
this.currentPage = page;
this.pack();
this.repaint();
}
private void initRootPanel() {
this.root = componentsFactory.getTransparentPanel(new BorderLayout());
this.root.setBackground(AppThemeColor.FRAME);
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBackground(AppThemeColor.FRAME);
leftPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, AppThemeColor.BORDER));
this.tree = new AdrTreePanel(
this.selectedProfile.getContents(),
new AdrMainTreeNodeRenderer());
this.tree.updateTree();
JButton addComponent = this.componentsFactory.getButton("New");
addComponent.setBackground(AppThemeColor.FRAME);
addComponent.setFont(this.componentsFactory.getFont(FontStyle.BOLD, 20f));
addComponent.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(2, 2, 2, 2),
BorderFactory.createMatteBorder(1, 1, 1, 1, AppThemeColor.BORDER)));
addComponent.addActionListener(action -> {
MercuryStoreUI.adrSelectSubject.onNext(null);
MercuryStoreUI.adrStateSubject.onNext(new AdrPageDefinition<>(AdrPageState.MAIN, null));
});
leftPanel.add(addComponent, BorderLayout.PAGE_START);
leftPanel.add(this.tree, BorderLayout.CENTER);
this.root.add(leftPanel, BorderLayout.LINE_START);
}
@Override
public void subscribe() {
MercuryStoreUI.adrReloadSubject.subscribe(state -> {
this.tree.updateUI();
MercuryStoreCore.saveConfigSubject.onNext(true);
});
MercuryStoreUI.adrManagerPack.subscribe(state -> {
this.repaint();
this.pack();
});
MercuryStoreUI.adrManagerRepaint.subscribe(state -> {
this.repaint();
});
MercuryStoreUI.adrOpenIconSelectSubject.subscribe(callback -> {
this.iconSelectDialog.setCallback(callback);
this.iconSelectDialog.setVisible(true);
});
}
public void setSelectedProfile(AdrProfileDescriptor profile) {
this.selectedProfile = profile;
this.tree.updateTree(profile.getContents());
}
public void onProfileLoaded() {
this.profileSelector.setEnabled(true);
}
@Override
protected String getFrameTitle() {
return "Mercury: Overseer";
}
public void addNewNode(AdrComponentDescriptor descriptor, AdrComponentDescriptor parent) {
this.tree.addNode(descriptor, parent);
this.pack();
this.repaint();
}
public void removeNode(AdrComponentDescriptor descriptor) {
this.tree.removeNode(descriptor);
this.pack();
this.repaint();
}
public void duplicateNode(AdrComponentDescriptor descriptor) {
this.tree.duplicateNode(descriptor);
this.pack();
this.repaint();
}
public void removeProfileFromSelect(AdrProfileDescriptor profile) {
this.profileSelector.removeItem(profile.getProfileName());
}
public void addProfileToSelect(String profileName) {
this.profileSelector.removeItem("Create new");
this.profileSelector.addItem(profileName);
this.profileSelector.addItem("Create new");
this.profileSelector.setSelectedItem(profileName);
}
public void onProfileRename(List<AdrProfileDescriptor> entities) {
this.profileSelector.removeAllItems();
List<String> profilesNames = entities
.stream()
.map(AdrProfileDescriptor::getProfileName)
.collect(Collectors.toList());
profilesNames.add("Create new");
profilesNames.forEach(it -> this.profileSelector.addItem(it));
this.profileSelector.setSelectedItem(this.selectedProfile.getProfileName());
this.repaint();
}
private JPanel getBottomPanel() {
JPanel root = this.componentsFactory.getJPanel(new BorderLayout());
root.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, AppThemeColor.MSG_HEADER_BORDER));
root.setBackground(AppThemeColor.ADR_FOOTER_BG);
JPanel profilePanel = this.componentsFactory.getJPanel(new GridLayout(1, 3));
profilePanel.setBackground(AppThemeColor.ADR_FOOTER_BG);
List<String> profilesNames = Configuration.get()
.adrConfiguration()
.getEntities()
.stream()
.map(AdrProfileDescriptor::getProfileName)
.collect(Collectors.toList());
profilesNames.add("Create new");
this.profileSelector = this.componentsFactory.getComboBox(profilesNames.toArray(new String[0]));
this.profileSelector.setPreferredSize(new Dimension(120, 20));
this.profileSelector.setBorder(BorderFactory.createLineBorder(AppThemeColor.MSG_HEADER_BORDER));
this.profileSelector.setSelectedItem(this.selectedProfile.getProfileName());
this.profileSelector.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
if (!profileSelector.getSelectedItem().equals("Create new")) {
if (!profileSelector.getSelectedItem().equals(this.selectedProfile.getProfileName())) {
profileSelector.setEnabled(false);
MercuryStoreUI.adrSelectProfileSubject.onNext((String) profileSelector.getSelectedItem());
}
} else {
profileSelector.setSelectedItem(this.selectedProfile.getProfileName());
new AdrNewProfileDialog(
MercuryStoreUI.adrNewProfileSubject::onNext,
profileSelector, profilesNames).setVisible(true);
}
}
});
JButton exportButton = this.componentsFactory.getIconButton("app/adr/export_node.png", 15, AppThemeColor.FRAME, TooltipConstants.ADR_EXPORT_BUTTON);
exportButton.addActionListener(action -> {
this.exportDialog.getPayload().addAll(this.selectedProfile.getContents());
this.exportDialog.postConstruct();
this.exportDialog.setVisible(true);
});
exportButton.setBackground(AppThemeColor.ADR_FOOTER_BG);
profilePanel.add(exportButton);
JPanel bottomPanel = this.componentsFactory.getJPanel(new BorderLayout());
bottomPanel.setBackground(AppThemeColor.ADR_FOOTER_BG);
profilePanel.add(this.componentsFactory.getTextLabel("Selected profile: "), BorderLayout.LINE_START);
profilePanel.add(profileSelector);
// JButton reloadButton = this.componentsFactory.getIconButton("app/adr/export_node.png", 15, AppThemeColor.FRAME, TooltipConstants.ADR_EXPORT_BUTTON);
// reloadButton.addActionListener(action -> {
// this.tree.updateTree();
// });
// profilePanel.add(reloadButton);
JButton profileSettingsButton = this.componentsFactory.getIconButton("app/adr/profile_settings_icon.png", 18, AppThemeColor.FRAME, TooltipConstants.ADR_EXPORT_BUTTON);
profileSettingsButton.addActionListener(action -> {
MercuryStoreUI.adrStateSubject.onNext(new AdrPageDefinition<>(AdrPageState.PROFILES_SETTINGS, null));
});
profileSettingsButton.setBackground(AppThemeColor.ADR_FOOTER_BG);
bottomPanel.add(exportButton, BorderLayout.LINE_START);
bottomPanel.add(profilePanel, BorderLayout.CENTER);
bottomPanel.add(profileSettingsButton, BorderLayout.LINE_END);
root.add(bottomPanel, BorderLayout.LINE_START);
root.add(profileSettingsButton, BorderLayout.LINE_END);
return root;
}
}
| 4,732 |
1,048 | <reponame>glebshevchukk/gradslam<filename>gradslam/version.py<gh_stars>1000+
# Export version number
__version__ = "0.1.0"
| 51 |
1,830 | /*
* Copyright © 2017 camunda services GmbH (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.camunda.zeebe.model.bpmn.validation.zeebe;
import io.camunda.zeebe.model.bpmn.instance.Error;
import io.camunda.zeebe.model.bpmn.instance.ErrorEventDefinition;
import org.camunda.bpm.model.xml.validation.ModelElementValidator;
import org.camunda.bpm.model.xml.validation.ValidationResultCollector;
public class ErrorEventDefinitionValidator implements ModelElementValidator<ErrorEventDefinition> {
@Override
public Class<ErrorEventDefinition> getElementType() {
return ErrorEventDefinition.class;
}
@Override
public void validate(
final ErrorEventDefinition element,
final ValidationResultCollector validationResultCollector) {
final Error error = element.getError();
if (error == null) {
validationResultCollector.addError(0, "Must reference an error");
} else {
final String errorCode = error.getErrorCode();
if (errorCode == null || errorCode.isEmpty()) {
validationResultCollector.addError(0, "ErrorCode must be present and not empty");
}
}
}
}
| 498 |
1,444 | package mage.cards.l;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.ExileSpellEffect;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.filter.FilterCard;
import mage.game.Game;
import mage.players.Player;
import mage.target.common.TargetCardInYourGraveyard;
import mage.target.targetadjustment.TargetAdjuster;
/**
*
* @author weirddan455
*/
public final class LongRest extends CardImpl {
public LongRest(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{X}{G}{G}{G}");
// Return X target cards with different mana values from your graveyard to your hand.
// If eight or more cards were returned to your hand this way, your life total becomes equal to your starting life total.
// Exile Long Rest.
this.getSpellAbility().setTargetAdjuster(LongRestAdjuster.instance);
this.getSpellAbility().addEffect(new LongRestEffect());
this.getSpellAbility().addEffect(new ExileSpellEffect());
}
private LongRest(final LongRest card) {
super(card);
}
@Override
public LongRest copy() {
return new LongRest(this);
}
}
class LongRestTarget extends TargetCardInYourGraveyard {
private static final FilterCard filter = new FilterCard("cards with different mana values from your graveyard");
public LongRestTarget(int xValue) {
super(xValue, filter);
}
private LongRestTarget(final LongRestTarget target) {
super(target);
}
@Override
public LongRestTarget copy() {
return new LongRestTarget(this);
}
@Override
public Set<UUID> possibleTargets(UUID sourceId, UUID sourceControllerId, Game game) {
Set<UUID> possibleTargets = new HashSet<>();
Set<Integer> manaValues = new HashSet<>();
for (UUID targetId : this.getTargets()) {
Card card = game.getCard(targetId);
if (card != null) {
manaValues.add(card.getManaValue());
}
}
for (UUID possibleTargetId : super.possibleTargets(sourceId, sourceControllerId, game)) {
Card card = game.getCard(possibleTargetId);
if (card != null && !manaValues.contains(card.getManaValue())) {
possibleTargets.add(possibleTargetId);
}
}
return possibleTargets;
}
}
enum LongRestAdjuster implements TargetAdjuster {
instance;
@Override
public void adjustTargets(Ability ability, Game game) {
ability.getTargets().clear();
ability.addTarget(new LongRestTarget(ability.getManaCostsToPay().getX()));
}
}
class LongRestEffect extends OneShotEffect {
public LongRestEffect() {
super(Outcome.Benefit);
this.staticText = "Return X target cards with different mana values from your graveyard to your hand. "
+ "If eight or more cards were returned to your hand this way, your life total becomes equal to your starting life total";
}
private LongRestEffect(final LongRestEffect effect) {
super(effect);
}
@Override
public LongRestEffect copy() {
return new LongRestEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player controller = game.getPlayer(source.getControllerId());
if (controller != null) {
Set<Card> cardsToHand = new HashSet<>();
for (UUID targetId : targetPointer.getTargets(game, source)) {
Card card = game.getCard(targetId);
if (card != null && game.getState().getZone(targetId) == Zone.GRAVEYARD) {
cardsToHand.add(card);
}
}
int numCards = cardsToHand.size();
if (numCards > 0) {
controller.moveCards(cardsToHand, Zone.HAND, source, game);
if (numCards >= 8) {
controller.setLife(game.getStartingLife(), game, source);
}
return true;
}
}
return false;
}
}
| 1,725 |
26,932 | <reponame>OsmanDere/metasploit-framework
// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
//
// This file is part of the VNC system.
//
// The VNC system 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, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
// TightVNC distribution homepage on the Web: http://www.tightvnc.com/
//
// If the source code for the VNC system is not available from the place
// whence you received this file, check http://www.uk.research.att.com/vnc or contact
// the authors on <EMAIL> for information on obtaining it.
// vncDesktop object
// The vncDesktop object handles retrieval of data from the
// display buffer. It also uses the RFBLib DLL to supply
// information on mouse movements and screen updates to
// the server
class vncDesktop;
#if !defined(_WINVNC_VNCDESKTOP)
#define _WINVNC_VNCDESKTOP
#pragma once
// Include files
#include "stdhdrs.h"
#include "vncServer.h"
#include "vncRegion.h"
#include "RectList.h"
#include "translate.h"
#include <omnithread.h>
#include "VideoDriver.h"
// Constants
extern const UINT RFB_SCREEN_UPDATE;
extern const UINT RFB_COPYRECT_UPDATE;
extern const UINT RFB_MOUSE_UPDATE;
extern const char szDesktopSink[];
#define MAX_REG_ENTRY_LEN (80)
// Class definition
class vncDesktop
{
// Fields
public:
// Methods
public:
// Make the desktop thread & window proc friends
friend class vncDesktopThread;
friend LRESULT CALLBACK DesktopWndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp);
// Create/Destroy methods
vncDesktop();
~vncDesktop();
BOOL Init(vncServer *pSrv);
// Hooking stuff
void TryActivateHooks();
BOOL DriverActive() { return m_videodriver != NULL; }
// Routine to signal a vncServer to trigger an update
void RequestUpdate();
// Screen translation, capture, info
void FillDisplayInfo(rfbServerInitMsg *scrInfo);
void SetLocalInputDisableHook(BOOL enable);
void SetLocalInputPriorityHook(BOOL enable);
void CaptureScreen(RECT &UpdateArea, BYTE *scrBuff);
void CaptureScreenFromAdapterGeneral(RECT UpdateArea, BYTE *scrBuff);
void CaptureScreenFromMirage(RECT UpdateArea, BYTE *scrBuff);
int ScreenBuffSize();
HWND Window() { return m_hwnd; }
// Mouse related
void CaptureMouse(BYTE *scrBuff, UINT scrBuffSize);
void CaptureMouseRect();
BOOL GetRichCursorData(BYTE *databuf, HCURSOR hcursor, int width, int height);
RECT MouseRect();
void SetCursor(HCURSOR cursor);
HCURSOR GetCursor() { return m_hcursor; }
// created for debug purposes. not used in normal builds.
bool bDbgDumpSurfBuffers(const RECT &rcl);
// Clipboard manipulation
static void ConvertClipText(char *dst, const char *src);
void SetClipText(LPSTR text);
// Method to obtain the DIBsection buffer if fast blits are enabled
// If they're disabled, it'll return NULL
inline BYTE *MainBuffer() { return m_mainbuff; }
inline RECT MainBufferRect() { return m_bmrect; }
void CopyRect(const RECT &dest, const POINT &source);
BOOL m_initialClipBoardSeen;
// Implementation
protected:
// Routines to hook and unhook us
BOOL Startup();
BOOL Shutdown();
void ActivateHooks();
void ShutdownHooks();
// Init routines called by the child thread
BOOL InitDesktop();
void KillScreenSaver();
RECT GetSourceRect();
BOOL GetSourceDisplayRect(RECT &rdisp_rect);
static BOOL IsMultiMonDesktop();
void ChangeResNow();
void SetupDisplayForConnection();
void ResetDisplayToNormal();
BOOL InitBitmap();
BOOL InitWindow();
BOOL ThunkBitmapInfo();
BOOL SetPixFormat();
BOOL SetPixShifts();
BOOL InitHooks();
BOOL SetPalette();
void CopyToBuffer(RECT rect, BYTE *scrBuff);
void CopyToBuffer(RECT rect, BYTE *scrBuff, const BYTE *SourceBuff);
void CopyRectToBuffer(const RECT &dest, const POINT &source);
void CalcCopyRects();
// Routine to attempt enabling optimised DIBsection blits
BOOL CreateBuffers();
// Convert a bit mask eg. 00111000 to max=7, shift=3
static void MaskToMaxAndShift(DWORD mask, CARD16 &max, CARD8 &shift);
// Enabling & disabling clipboard handling
void SetClipboardActive(BOOL active) {m_clipboard_active = active;};
// Detecting updates
BOOL CheckUpdates();
void SetPollingTimer();
void SetPollingFlag(BOOL set) { m_polling_flag = set; }
BOOL GetPollingFlag() { return m_polling_flag; }
void PerformPolling();
void PollWindow(HWND hwnd);
void PollArea(const RECT &rect);
void CheckRects(vncRegion &rgn, rectlist &rects);
void GetChangedRegion(vncRegion &rgn, const RECT &rect);
void UpdateChangedRect(vncRegion &rgn, const RECT &rect);
void UpdateChangedSubRect(vncRegion &rgn, const RECT &rect);
// Blank screen feature
void UpdateBlankScreenTimer();
void BlankScreen(BOOL set);
// Timer identifiers (the third one is not used in any real timer)
enum TimerID {
TIMER_POLL = 1,
TIMER_BLANK_SCREEN = 2,
TIMER_RESTORE_SCREEN = 3
};
// Video driver stuff
BOOL InitVideoDriver();
void ShutdownVideoDriver();
// DATA
// Generally useful stuff
vncServer *m_server;
omni_thread *m_thread;
HWND m_hwnd;
BOOL m_polling_flag;
UINT m_timer_polling;
UINT m_timer_blank_screen;
HWND m_hnextviewer;
BOOL m_clipboard_active;
BOOL m_hooks_active;
BOOL m_hooks_may_change;
// Video driver stuff
vncVideoDriver *m_videodriver;
// device contexts for memory and the screen
HDC m_hmemdc;
HDC m_hrootdc;
// New and old bitmaps
HBITMAP m_membitmap;
omni_mutex m_bitbltlock;
// frame buffer relative to the entire (virtual) desktop.
// NOTE: non-zero offsets possible
RECT m_bmrect;
struct _BMInfo {
BOOL truecolour;
BITMAPINFO bmi;
// Colormap info - comes straight after BITMAPINFO - **HACK**
RGBQUAD cmap[256];
} m_bminfo;
// Screen info
rfbServerInitMsg m_scrinfo;
// These are the red, green & blue masks for a pixel
DWORD m_rMask, m_gMask, m_bMask;
// This is always handy to have
int m_bytesPerRow;
// Handle of the default cursor
HCURSOR m_hcursor;
// Handle of the basic arrow cursor
HCURSOR m_hdefcursor;
// The current mouse position
RECT m_cursorpos;
// Boolean flag to indicate when the display resolution has changed
BOOL m_displaychanged;
// Extra vars used for the DIBsection optimisation
VOID *m_DIBbits;
BYTE *m_mainbuff;
BYTE *m_backbuff;
BOOL m_freemainbuff;
BOOL m_formatmunged;
// DevMode alteration
DEVMODE *m_lpAlternateDevMode; // *** used for res changes - <NAME>
long origPelsWidth; // *** To set the original resolution
long origPelsHeight; // *** - <NAME>
vncRegion m_changed_rgn;
BOOL m_copyrect_set;
RECT m_copyrect_rect;
POINT m_copyrect_src;
static const int m_pollingOrder[32];
static int m_pollingStep;
};
#endif // _WINVNC_VNCDESKTOP
| 2,896 |
14,668 | <reponame>zealoussnow/chromium<gh_stars>1000+
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net.impl;
import androidx.annotation.IntDef;
import org.chromium.net.InlineExecutionProhibitedException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.concurrent.Executor;
/**
* Utilities for Java-based UrlRequest implementations.
* {@hide}
*/
public final class JavaUrlRequestUtils {
/**
* State interface for keeping track of the internal state of a {@link UrlRequest}.
*
* /- AWAITING_FOLLOW_REDIRECT <- REDIRECT_RECEIVED <-\ /- READING <--\
* | | | |
* V / V /
* NOT_STARTED -> STARTED -----------------------------------------------> AWAITING_READ -------
* --> COMPLETE
*
*
*/
@IntDef({State.NOT_STARTED, State.STARTED, State.REDIRECT_RECEIVED,
State.AWAITING_FOLLOW_REDIRECT, State.AWAITING_READ, State.READING, State.ERROR,
State.COMPLETE, State.CANCELLED})
@Retention(RetentionPolicy.SOURCE)
public @interface State {
int NOT_STARTED = 0;
int STARTED = 1;
int REDIRECT_RECEIVED = 2;
int AWAITING_FOLLOW_REDIRECT = 3;
int AWAITING_READ = 4;
int READING = 5;
int ERROR = 6;
int COMPLETE = 7;
int CANCELLED = 8;
}
/**
* Interface used to run commands that could throw an exception. Specifically useful for
* calling {@link UrlRequest.Callback}s on a user-supplied executor.
*/
public interface CheckedRunnable { void run() throws Exception; }
/**
* Executor that detects and throws if its mDelegate runs a submitted runnable inline.
*/
public static final class DirectPreventingExecutor implements Executor {
private final Executor mDelegate;
/**
* Constructs an {@link DirectPreventingExecutor} that executes {@link runnable}s on the
* provided {@link Executor}.
*
* @param delegate the {@link Executor} used to run {@link Runnable}s
*/
public DirectPreventingExecutor(Executor delegate) {
this.mDelegate = delegate;
}
/**
* Executes a {@link Runnable} on this {@link Executor} and throws an exception if it is
* being run on the same thread as the calling thread.
*
* @param command the {@link Runnable} to attempt to run
*/
@Override
public void execute(Runnable command) {
Thread currentThread = Thread.currentThread();
InlineCheckingRunnable runnable = new InlineCheckingRunnable(command, currentThread);
mDelegate.execute(runnable);
// This next read doesn't require synchronization; only the current thread could have
// written to runnable.mExecutedInline.
if (runnable.mExecutedInline != null) {
throw runnable.mExecutedInline;
} else {
// It's possible that this method is being called on an executor, and the runnable
// that was just queued will run on this thread after the current runnable returns.
// By nulling out the mCallingThread field, the InlineCheckingRunnable's current
// thread comparison will not fire.
//
// Java reference assignment is always atomic (no tearing, even on 64-bit VMs, see
// JLS 17.7), but other threads aren't guaranteed to ever see updates without
// something like locking, volatile, or AtomicReferences. We're ok in
// this instance, since this write only needs to be seen in the case that
// InlineCheckingRunnable.run() runs on the same thread as this execute() method.
runnable.mCallingThread = null;
}
}
private static final class InlineCheckingRunnable implements Runnable {
private final Runnable mCommand;
private Thread mCallingThread;
private InlineExecutionProhibitedException mExecutedInline;
private InlineCheckingRunnable(Runnable command, Thread callingThread) {
this.mCommand = command;
this.mCallingThread = callingThread;
}
@Override
public void run() {
if (Thread.currentThread() == mCallingThread) {
// Can't throw directly from here, since the delegate executor could catch this
// exception.
mExecutedInline = new InlineExecutionProhibitedException();
return;
}
mCommand.run();
}
}
}
}
| 2,210 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-6xhr-5mv6-f4jf",
"modified": "2022-05-01T07:36:50Z",
"published": "2022-05-01T07:36:50Z",
"aliases": [
"CVE-2006-6301"
],
"details": "DenyHosts 2.5 does not properly parse sshd log files, which allows remote attackers to add arbitrary hosts to the /etc/hosts.deny file and cause a denial of service by adding arbitrary IP addresses to the sshd log file, as demonstrated by logging in via ssh with a login name containing certain strings with an IP address, which is not properly handled by a regular expression.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2006-6301"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/30761"
},
{
"type": "WEB",
"url": "http://bugs.gentoo.org/show_bug.cgi?id=157163"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/23236"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/23603"
},
{
"type": "WEB",
"url": "http://security.gentoo.org/glsa/glsa-200701-01.xml"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/21468"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2006/4876"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 683 |
1,350 | <reponame>Manny27nyc/azure-sdk-for-java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.loganalytics.models;
import com.azure.resourcemanager.loganalytics.fluent.models.WorkspacePurgeResponseInner;
/** An immutable client-side representation of WorkspacePurgeResponse. */
public interface WorkspacePurgeResponse {
/**
* Gets the operationId property: Id to use when querying for status for a particular purge operation.
*
* @return the operationId value.
*/
String operationId();
/**
* Gets the inner com.azure.resourcemanager.loganalytics.fluent.models.WorkspacePurgeResponseInner object.
*
* @return the inner object.
*/
WorkspacePurgeResponseInner innerModel();
}
| 271 |
2,023 | <reponame>tdiprima/code
try:
from Tkinter import Entry, Frame, Label, StringVar
from Tkconstants import *
except ImportError:
from tkinter import Entry, Frame, Label, StringVar
from tkinter.constants import *
def hex2rgb(str_rgb):
try:
rgb = str_rgb[1:]
if len(rgb) == 6:
r, g, b = rgb[0:2], rgb[2:4], rgb[4:6]
elif len(rgb) == 3:
r, g, b = rgb[0] * 2, rgb[1] * 2, rgb[2] * 2
else:
raise ValueError()
except:
raise ValueError("Invalid value %r provided for rgb color."% str_rgb)
return tuple(int(v, 16) for v in (r, g, b))
class Placeholder_State(object):
__slots__ = 'normal_color', 'normal_font', 'placeholder_text', 'placeholder_color', 'placeholder_font', 'contains_placeholder'
def add_placeholder_to(entry, placeholder, color="grey", font=None):
normal_color = entry.cget("fg")
normal_font = entry.cget("font")
if font is None:
font = normal_font
state = Placeholder_State()
state.normal_color=normal_color
state.normal_font=normal_font
state.placeholder_color=color
state.placeholder_font=font
state.placeholder_text = placeholder
state.contains_placeholder=True
def on_focusin(event, entry=entry, state=state):
if state.contains_placeholder:
entry.delete(0, "end")
entry.config(fg = state.normal_color, font=state.normal_font)
state.contains_placeholder = False
def on_focusout(event, entry=entry, state=state):
if entry.get() == '':
entry.insert(0, state.placeholder_text)
entry.config(fg = state.placeholder_color, font=state.placeholder_font)
state.contains_placeholder = True
entry.insert(0, placeholder)
entry.config(fg = color, font=font)
entry.bind('<FocusIn>', on_focusin, add="+")
entry.bind('<FocusOut>', on_focusout, add="+")
entry.placeholder_state = state
return state
class SearchBox(Frame):
def __init__(self, master, entry_width=30, entry_font=None, entry_background="white", entry_highlightthickness=1, button_text="Search", button_ipadx=10, button_background="#009688", button_foreground="white", button_font=None, opacity=0.8, placeholder=None, placeholder_font=None, placeholder_color="grey", spacing=3, command=None):
Frame.__init__(self, master)
self._command = command
self.entry = Entry(self, width=entry_width, background=entry_background, highlightcolor=button_background, highlightthickness=entry_highlightthickness)
self.entry.pack(side=LEFT, fill=BOTH, ipady=1, padx=(0,spacing))
if entry_font:
self.entry.configure(font=entry_font)
if placeholder:
add_placeholder_to(self.entry, placeholder, color=placeholder_color, font=placeholder_font)
self.entry.bind("<Escape>", lambda event: self.entry.nametowidget(".").focus())
self.entry.bind("<Return>", self._on_execute_command)
opacity = float(opacity)
if button_background.startswith("#"):
r,g,b = hex2rgb(button_background)
else:
# Color name
r,g,b = master.winfo_rgb(button_background)
r = int(opacity*r)
g = int(opacity*g)
b = int(opacity*b)
if r <= 255 and g <= 255 and b <=255:
self._button_activebackground = '#%02x%02x%02x' % (r,g,b)
else:
self._button_activebackground = '#%04x%04x%04x' % (r,g,b)
self._button_background = button_background
self.button_label = Label(self, text=button_text, background=button_background, foreground=button_foreground, font=button_font)
if entry_font:
self.button_label.configure(font=button_font)
self.button_label.pack(side=LEFT, fill=Y, ipadx=button_ipadx)
self.button_label.bind("<Enter>", self._state_active)
self.button_label.bind("<Leave>", self._state_normal)
self.button_label.bind("<ButtonRelease-1>", self._on_execute_command)
def get_text(self):
entry = self.entry
if hasattr(entry, "placeholder_state"):
if entry.placeholder_state.contains_placeholder:
return ""
else:
return entry.get()
else:
return entry.get()
def set_text(self, text):
entry = self.entry
if hasattr(entry, "placeholder_state"):
entry.placeholder_state.contains_placeholder = False
entry.delete(0, END)
entry.insert(0, text)
def clear(self):
self.entry_var.set("")
def focus(self):
self.entry.focus()
def _on_execute_command(self, event):
text = self.get_text()
self._command(text)
def _state_normal(self, event):
self.button_label.configure(background=self._button_background)
def _state_active(self, event):
self.button_label.configure(background=self._button_activebackground)
if __name__ == "__main__":
try:
from Tkinter import Tk
from tkMessageBox import showinfo
except ImportError:
from tkinter import Tk
from tkinter.messagebox import showinfo
def command(text):
showinfo("search command", "searching:%s"%text)
root = Tk()
SearchBox(root, command=command, placeholder="Type and press enter", entry_highlightthickness=0).pack(pady=6, padx=3)
root.mainloop()
| 2,430 |
852 | <gh_stars>100-1000
import FWCore.ParameterSet.Config as cms
etaRangeCaloJetSelector = cms.EDFilter( "EtaRangeCaloJetSelector",
src = cms.InputTag("hltCaloJetL1FastJetCorrected"),
etaMin = cms.double( -99.9 ), #2.4
etaMax = cms.double( +99.9 ), #2.4
)
| 114 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.