code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
# Calanthe amamiana var. latilabellata VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Calanthe/Calanthe aristulifera/ Syn. Calanthe amamiana latilabellata/README.md
|
Markdown
|
apache-2.0
| 193
|
# Agropyron fuegianum var. chaetophorum VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Elymus/Elymus magellanicus/ Syn. Agropyron fuegianum chaetophorum/README.md
|
Markdown
|
apache-2.0
| 194
|
# Miconia brevipes var. longifolia Cogn. VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Melastomataceae/Miconia/Miconia trianae/ Syn. Miconia brevipes longifolia/README.md
|
Markdown
|
apache-2.0
| 195
|
# Meliola ingae (F. Stevens & Tehon) Cif. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycopath. Mycol. appl. 7: 86 (1954)
#### Original name
Irene ingae F. Stevens & Tehon
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Dothideomycetes/Meliolales/Meliolaceae/Meliola/Meliola ingae/README.md
|
Markdown
|
apache-2.0
| 229
|
# Ziziphora mussini Adam SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Ziziphora/Ziziphora mussini/README.md
|
Markdown
|
apache-2.0
| 172
|
# Calathea lasiophylla H.A.Kenn. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Zingiberales/Marantaceae/Calathea/Calathea lasiophylla/README.md
|
Markdown
|
apache-2.0
| 188
|
# Octospora feurichiana (Kirschst.) Yei Z. Wang SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Monographic Studies of North American Species of Octospora previously ascribed to Lamprospora (Pezizales, Ascomycetes) (Taiwan), Special Publication no. 4, National Museum of Natural Science 40 (1992)
#### Original name
Barlaeina feurichiana Kirschst.
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Pezizomycetes/Pezizales/Pyronemataceae/Octospora/Octospora feurichiana/README.md
|
Markdown
|
apache-2.0
| 401
|
# Arundinaria amoena Nakai SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Sasa/Sasa masamuneana/ Syn. Arundinaria amoena/README.md
|
Markdown
|
apache-2.0
| 181
|
# Tellima racemosa Greene SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Saxifragales/Saxifragaceae/Tellima/Tellima racemosa/README.md
|
Markdown
|
apache-2.0
| 173
|
# Tanacetum macrophyllum f. angustiloba M.Gajic FORM
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Tanacetum/Tanacetum macrophyllum/Tanacetum macrophyllum angustiloba/README.md
|
Markdown
|
apache-2.0
| 192
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Management;
using System.Threading;
using System.Windows.Forms;
using CommandLine;
using CommandLine.Text;
namespace BatteryMonitor
{
class Program
{
private const uint NotCharging = 1;
private const uint Charging = 2;
class Options
{
[Option('p', "polling", Required = false, DefaultValue = 60,
HelpText = "Time to wait before polling battery level")]
public int PollingTime { get; set; }
[Option('m', "min", Required = false, DefaultValue = 40,
HelpText = "Minimum battery level")]
public int MinBatteryLevel { get; set; }
[Option('x', "max", Required = false, DefaultValue = 80,
HelpText = "Maximum battery level")]
public int MaxBatteryLevel { get; set; }
[ParserState]
public IParserState LastParserState { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
static void Main(string[] args)
{
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options))
{
int pollingTimeMillis = options.PollingTime * 1000;
while (true)
{
System.Management.ObjectQuery query =
new ObjectQuery("Select EstimatedChargeRemaining, BatteryStatus FROM Win32_Battery");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection collection = searcher.Get();
ushort batteryChargeRemaining = 0;
ushort batteryStatus = 0;
foreach (ManagementObject mo in collection)
{
foreach (PropertyData property in mo.Properties)
{
if (property.Name.Equals("EstimatedChargeRemaining"))
{
batteryChargeRemaining = (ushort) property.Value;
}
if (property.Name.Equals("BatteryStatus"))
{
batteryStatus = (ushort) property.Value;
}
}
}
if ((batteryChargeRemaining > options.MaxBatteryLevel) && (batteryStatus == Charging))
{
DialogResult result =
System.Windows.Forms.MessageBox.Show(
batteryChargeRemaining + "% is enough. Stop recharging.", "Battery Monitor");
}
else if ((batteryChargeRemaining < options.MinBatteryLevel) && (batteryStatus == NotCharging))
{
DialogResult result =
System.Windows.Forms.MessageBox.Show(
batteryChargeRemaining + "% is too low. Start recharging.", "Battery Monitor");
}
// Wait before polling again for battery level
Thread.Sleep(pollingTimeMillis);
}
}
}
}
}
|
hasanzaidi/win-battery-monitor
|
Program.cs
|
C#
|
apache-2.0
| 3,579
|
/*
* 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 __PWM_H__
#define __PWM_H__
#include <os/os_dev.h>
#ifdef __cplusplus
extern "C" {
#endif
struct pwm_dev;
struct pwm_chan_cfg;
/**
* Configure a channel on the PWM device.
*
* @param dev The device to configure.
* @param cnum The channel number to configure.
* @param cfg Configuration data for this channel.
*
* @return 0 on success, non-zero error code on failure.
*/
typedef int (*pwm_configure_channel_func_t)(struct pwm_dev *,
uint8_t,
struct pwm_chan_cfg *);
/**
* Enable the PWM with specified duty cycle.
*
* This duty cycle is a fractional duty cycle where 0 == off, 65535=on,
* and any value in between is on for fraction clocks and off
* for 65535-fraction clocks.
*
* @param dev The device to configure.
* @param cnum The channel to configure.
* @param fraction The fraction value.
*
* @return 0 on success, negative on error.
*/
typedef int (*pwm_enable_duty_cycle_func_t)(struct pwm_dev *,
uint8_t,
uint16_t);
/**
* Set the frequency for the device's clock.
* This frequency must be between 1/2 the clock frequency and
* the clock divided by the resolution.
*
* @param dev The device to configure.
* @param freq_hz The frequency value in Hz.
*
* @return 0 on success, negative on error.
*/
typedef int (*pwm_set_frequency_func_t) (struct pwm_dev *, uint32_t);
/**
* Get the underlying clock driving the PWM device.
*
* @param dev
*
* @return value is in Hz on success, negative on error.
*/
typedef int (*pwm_get_clock_freq_func_t) (struct pwm_dev *);
/**
* Get the resolution of the PWM in bits.
*
* @param dev The device to query.
*
* @return The value in bits on success, negative on error.
*/
typedef int (*pwm_get_resolution_bits_func_t) (struct pwm_dev *);
/**
* Disable the PWM channel, it will be marked as unconfigured.
*
* @param dev The device to configure.
* @param cnum The channel number.
*
* @return 0 on success, negative on error.
*/
typedef int (*pwm_disable_func_t) (struct pwm_dev *, uint8_t);
struct pwm_driver_funcs {
pwm_configure_channel_func_t pwm_configure_channel;
pwm_enable_duty_cycle_func_t pwm_enable_duty_cycle;
pwm_set_frequency_func_t pwm_set_frequency;
pwm_get_clock_freq_func_t pwm_get_clock_freq;
pwm_get_resolution_bits_func_t pwm_get_resolution_bits;
pwm_disable_func_t pwm_disable;
};
struct pwm_dev {
struct os_dev pwm_os_dev;
struct os_mutex pwm_lock;
struct pwm_driver_funcs pwm_funcs;
uint32_t pwm_chan_count;
int pwm_instance_id;
};
/**
* PWM channel configuration data.
*
* pin - The pin to be assigned to this pwm channel.
* inverted - Whether this channel's output polarity is inverted or not.
* data - A pointer do a driver specific parameter.
*/
struct pwm_chan_cfg {
uint8_t pin;
bool inverted;
void* data;
};
int pwm_chan_config(struct pwm_dev *dev, uint8_t cnum, struct pwm_chan_cfg *cfg);
int pwm_enable_duty_cycle(struct pwm_dev *pwm_d, uint8_t cnum, uint16_t fraction);
int pwm_set_frequency(struct pwm_dev *dev, uint32_t freq_hz);
int pwm_get_clock_freq(struct pwm_dev *dev);
int pwm_get_resolution_bits(struct pwm_dev *dev);
int pwm_disable(struct pwm_dev *dev, uint8_t cnum);
#ifdef __cplusplus
}
#endif
#endif /* __PWM_H__ */
|
IMGJulian/incubator-mynewt-core
|
hw/drivers/pwm/include/pwm/pwm.h
|
C
|
apache-2.0
| 4,218
|
package com.immortal.colzfeed.datamodels;
import java.util.Date;
public class Course {
private long courseId;
private String subject;
private String faculty;
private String batch;
private String lecturer;
private Date publishDate;
private String title;
private String details;
private long externalId;
private String localFilePath;
private String webFilePath;
private String attachment;
public String getAttachment() {
return attachment;
}
public String getBatch() {
return batch;
}
public long getCourseId() {
return courseId;
}
public String getDetails() {
return details;
}
public long getExternalId() {
return externalId;
}
public String getFaculty() {
return faculty;
}
public String getLecturer() {
return lecturer;
}
public String getLocalFilePath() {
return localFilePath;
}
public Date getPublishDate() {
return publishDate;
}
public String getSubject() {
return subject;
}
public String getTitle() {
return title;
}
public String getWebFilePath() {
return webFilePath;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
public void setBatch(String batch) {
this.batch = batch;
}
public void setCourseId(long courseId) {
this.courseId = courseId;
}
public void setDetails(String details) {
this.details = details;
}
public void setExternalId(long externalId) {
this.externalId = externalId;
}
public void setFaculty(String faculty) {
this.faculty = faculty;
}
public void setLecturer(String lecturer) {
this.lecturer = lecturer;
}
public void setLocalFilePath(String localFilePath) {
this.localFilePath = localFilePath;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setTitle(String title) {
this.title = title;
}
public void setWebFilePath(String webFilePath) {
this.webFilePath = webFilePath;
}
}
|
immortalinfidel/colappmaster
|
src/com/immortal/colzfeed/datamodels/Course.java
|
Java
|
apache-2.0
| 1,989
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/reference_util.h"
#include <array>
#include <utility>
#include "absl/memory/memory.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/hlo_evaluator.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/shape_inference.h"
#include "tensorflow/compiler/xla/window_util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/math/math_util.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
/* static */ std::unique_ptr<Array2D<Eigen::half>> ReferenceUtil::MatmulArray2D(
const Array2D<Eigen::half>& lhs, const Array2D<Eigen::half>& rhs) {
return HloEvaluator::MatmulArray2D(lhs, rhs);
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MatmulArray2D(
const Array2D<float>& lhs, const Array2D<float>& rhs) {
return HloEvaluator::MatmulArray2D(lhs, rhs);
}
/* static */ std::unique_ptr<Array2D<double>> ReferenceUtil::MatmulArray2D(
const Array2D<double>& lhs, const Array2D<double>& rhs) {
return HloEvaluator::MatmulArray2D(lhs, rhs);
}
/* static */ std::unique_ptr<Array2D<double>> ReferenceUtil::Array2DF32ToF64(
const Array2D<float>& input) {
auto result =
absl::make_unique<Array2D<double>>(input.height(), input.width());
for (int64 rowno = 0; rowno < input.height(); ++rowno) {
for (int64 colno = 0; colno < input.height(); ++colno) {
(*result)(rowno, colno) = input(rowno, colno);
}
}
return result;
}
/* static */ std::unique_ptr<Array3D<float>> ReferenceUtil::ConvArray3D(
const Array3D<float>& lhs, const Array3D<float>& rhs, int64 kernel_stride,
Padding padding) {
return ConvArray3DGeneralDimensionsDilated(
lhs, rhs, kernel_stride, padding, 1, 1,
XlaBuilder::CreateDefaultConvDimensionNumbers(1));
}
/*static*/ std::unique_ptr<Array3D<float>>
ReferenceUtil::ConvArray3DGeneralDimensionsDilated(
const Array3D<float>& lhs, const Array3D<float>& rhs, int64 kernel_stride,
Padding padding, int64 lhs_dilation, int64 rhs_dilation,
const ConvolutionDimensionNumbers& dnums) {
CHECK_EQ(dnums.input_spatial_dimensions_size(), 1);
CHECK_EQ(dnums.kernel_spatial_dimensions_size(), 1);
CHECK_EQ(dnums.output_spatial_dimensions_size(), 1);
// Reuse the code for Array4D-convolution by extending the 3D input into a 4D
// array by adding a fourth dummy dimension of size 1 without stride, padding
// and dilation.
Array4D<float> a4dlhs(lhs.n1(), lhs.n2(), lhs.n3(), 1);
a4dlhs.Each([&](absl::Span<const int64> indices, float* value_ptr) {
CHECK_EQ(indices[3], 0);
*value_ptr = lhs.operator()(indices[0], indices[1], indices[2]);
});
Array4D<float> a4drhs(rhs.n1(), rhs.n2(), rhs.n3(), 1);
a4drhs.Each([&](absl::Span<const int64> indices, float* value_ptr) {
CHECK_EQ(indices[3], 0);
*value_ptr = rhs.operator()(indices[0], indices[1], indices[2]);
});
// Add a second dummy spatial dimensions.
ConvolutionDimensionNumbers dnums2d = dnums;
dnums2d.add_input_spatial_dimensions(3);
dnums2d.add_kernel_spatial_dimensions(3);
dnums2d.add_output_spatial_dimensions(3);
std::unique_ptr<Array4D<float>> convr4 = ConvArray4DGeneralDimensionsDilated(
a4dlhs, a4drhs, {kernel_stride, 1}, padding, {lhs_dilation, 1},
{rhs_dilation, 1}, dnums2d);
auto convr3 = absl::make_unique<Array3D<float>>(
convr4->planes(), convr4->depth(), convr4->height());
convr4->Each([&](absl::Span<const int64> indices, float* value_ptr) {
CHECK_EQ(indices[3], 0);
convr3->operator()(indices[0], indices[1], indices[2]) = *value_ptr;
});
return convr3;
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::ConvArray4D(
const Array4D<float>& lhs, const Array4D<float>& rhs,
std::pair<int64, int64> kernel_stride, Padding padding) {
return ConvArray4DGeneralDimensions(
lhs, rhs, kernel_stride, padding,
XlaBuilder::CreateDefaultConvDimensionNumbers());
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::SeparableConvArray4D(const Array4D<float>& input,
const Array4D<float>& depthwise_weights,
const Array4D<float>& pointwise_weights,
std::pair<int64, int64> kernel_stride,
Padding padding) {
const int64 depth_multiplier = depthwise_weights.planes();
CHECK_EQ(pointwise_weights.depth(), input.depth() * depth_multiplier);
// Combine the two weights by reducing the depth_multiplier, so that we can
// apply a single convolution on the combined weights.
Array4D<float> weights(pointwise_weights.planes(), input.depth(),
depthwise_weights.height(), depthwise_weights.width());
for (int64 kx = 0; kx < depthwise_weights.width(); ++kx) {
for (int64 ky = 0; ky < depthwise_weights.height(); ++ky) {
for (int64 kz = 0; kz < input.depth(); ++kz) {
for (int64 out = 0; out < pointwise_weights.planes(); ++out) {
float weight = 0.0;
for (int64 depth = 0; depth < depth_multiplier; ++depth) {
weight +=
depthwise_weights(depth, kz, ky, kx) *
pointwise_weights(out, depth + kz * depth_multiplier, 0, 0);
}
weights(out, kz, ky, kx) = weight;
}
}
}
}
return ConvArray4D(input, weights, kernel_stride, padding);
}
/* static */ int64 ReferenceUtil::WindowCount(int64 unpadded_width,
int64 window_len, int64 stride,
Padding padding) {
if (padding == Padding::kValid) {
return window_util::StridedBound(unpadded_width, window_len, stride);
}
return tensorflow::MathUtil::CeilOfRatio(unpadded_width, stride);
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceWindow1DGeneric(
absl::Span<const float> operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
absl::Span<const std::pair<int64, int64>> padding) {
std::vector<int64> dim_lengths{static_cast<int64>(operand.size())};
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
int64 padded_width = padding[i].first + dim_lengths[i] + padding[i].second;
window_counts[i] =
window_util::StridedBound(padded_width, window[i], stride[i]);
pad_low[i] = padding[i].first;
}
auto result = absl::make_unique<std::vector<float>>(window_counts[0]);
// Do a full 1D reduce window.
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
int64 i0_base = i0 * stride[0] - pad_low[0];
float val = init;
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
if (i0_base + i0_win >= 0 && i0_base + i0_win < dim_lengths[0]) {
val = reduce_func(val, operand[i0_base + i0_win]);
}
}
(*result)[i0] = val;
}
return result;
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceWindow1DAdd(absl::Span<const float> operand, float init,
absl::Span<const int64> window,
absl::Span<const int64> stride,
Padding padding) {
const auto add_reduce = [](float arg1, float arg2) { return arg1 + arg2; };
std::vector<int64> dim_lengths{static_cast<int64>(operand.size())};
return ReduceWindow1DGeneric(
operand, init, add_reduce, window, stride,
xla::MakePadding(dim_lengths, window, stride, padding));
}
/* static */ std::unique_ptr<Array2D<float>>
ReferenceUtil::ReduceWindow2DGeneric(
const Array2D<float>& operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
absl::Span<const std::pair<int64, int64>> padding) {
std::vector<int64> dim_lengths{operand.height(), operand.width()};
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
int64 padded_width = padding[i].first + dim_lengths[i] + padding[i].second;
window_counts[i] =
window_util::StridedBound(padded_width, window[i], stride[i]);
pad_low[i] = padding[i].first;
}
auto result =
absl::make_unique<Array2D<float>>(window_counts[0], window_counts[1]);
// Do a full 2D reduce window.
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
float val = init;
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2()) {
val = reduce_func(val, operand(i0_base + i0_win, i1_base + i1_win));
}
}
}
(*result)(i0, i1) = val;
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::ReduceWindow2DAdd(
const Array2D<float>& operand, float init, absl::Span<const int64> window,
absl::Span<const int64> stride, Padding padding) {
const auto add_reduce = [](float arg1, float arg2) { return arg1 + arg2; };
std::vector<int64> dim_lengths{operand.height(), operand.width()};
return ReduceWindow2DGeneric(
operand, init, add_reduce, window, stride,
xla::MakePadding(dim_lengths, window, stride, padding));
}
/* static */ std::unique_ptr<Array3D<float>> ReferenceUtil::ReduceWindow3DAdd(
const Array3D<float>& operand, float init, absl::Span<const int64> window,
absl::Span<const int64> stride, Padding padding) {
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3()};
auto padding_both = xla::MakePadding(dim_lengths, window, stride, padding);
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
window_counts[i] =
WindowCount(dim_lengths[i], window[i], stride[i], padding);
pad_low[i] = padding_both[i].first;
}
auto result = absl::make_unique<Array3D<float>>(
window_counts[0], window_counts[1], window_counts[2]);
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
for (int64 i2 = 0; i2 < window_counts[2]; ++i2) {
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
int64 i2_base = i2 * stride[2] - pad_low[2];
float val = init;
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
for (int64 i2_win = 0; i2_win < window[2]; ++i2_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i2_base + i2_win >= 0 && i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2() &&
i2_base + i2_win < operand.n3()) {
val += operand(i0_base + i0_win, i1_base + i1_win,
i2_base + i2_win);
}
}
}
}
(*result)(i0, i1, i2) = val;
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ReduceWindow4DGeneric(
const Array4D<float>& operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
Padding padding) {
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3(),
operand.n4()};
return ReduceWindow4DGeneric(
operand, init, reduce_func, window, stride,
xla::MakePadding(dim_lengths, window, stride, padding));
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ReduceWindow4DGeneric(
const Array4D<float>& operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
absl::Span<const std::pair<int64, int64>> padding) {
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3(),
operand.n4()};
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
int64 padded_width = padding[i].first + dim_lengths[i] + padding[i].second;
window_counts[i] =
window_util::StridedBound(padded_width, window[i], stride[i]);
pad_low[i] = padding[i].first;
}
auto result = absl::make_unique<Array4D<float>>(
window_counts[0], window_counts[1], window_counts[2], window_counts[3]);
// Do a full 4D reduce window.
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
for (int64 i2 = 0; i2 < window_counts[2]; ++i2) {
for (int64 i3 = 0; i3 < window_counts[3]; ++i3) {
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
int64 i2_base = i2 * stride[2] - pad_low[2];
int64 i3_base = i3 * stride[3] - pad_low[3];
float val = init;
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
for (int64 i2_win = 0; i2_win < window[2]; ++i2_win) {
for (int64 i3_win = 0; i3_win < window[3]; ++i3_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i2_base + i2_win >= 0 && i3_base + i3_win >= 0 &&
i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2() &&
i2_base + i2_win < operand.n3() &&
i3_base + i3_win < operand.n4()) {
val = reduce_func(
val, operand(i0_base + i0_win, i1_base + i1_win,
i2_base + i2_win, i3_base + i3_win));
}
}
}
}
}
(*result)(i0, i1, i2, i3) = val;
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::ReduceWindow4DAdd(
const Array4D<float>& operand, float init, absl::Span<const int64> window,
absl::Span<const int64> stride, Padding padding) {
const auto add_reduce = [](float arg1, float arg2) { return arg1 + arg2; };
return ReduceWindow4DGeneric(operand, init, add_reduce, window, stride,
padding);
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::BatchNorm4D(
const Array4D<float>& input, const Array4D<float>& mean,
const Array4D<float>& var, const Array4D<float>& scale,
const Array4D<float>& offset, float epsilon) {
auto normalized =
*MapArray4D(input, mean, [](float a, float b) { return a - b; });
normalized = *MapArray4D(normalized, var, [&](float a, float b) {
return a / std::sqrt(b + epsilon);
});
normalized =
*MapArray4D(normalized, scale, [](float a, float b) { return a * b; });
return MapArray4D(normalized, offset, [](float a, float b) { return a + b; });
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::SelectAndScatter4DGePlus(const Array4D<float>& operand,
const Array4D<float>& source,
float init,
absl::Span<const int64> window,
absl::Span<const int64> stride,
bool same_padding) {
Padding padding = same_padding ? Padding::kSame : Padding::kValid;
auto result = absl::make_unique<Array4D<float>>(operand.n1(), operand.n2(),
operand.n3(), operand.n4());
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3(),
operand.n4()};
auto padding_both = xla::MakePadding(dim_lengths, window, stride, padding);
// Fill the output, with the initial value.
result->Fill(init);
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
window_counts[i] =
WindowCount(dim_lengths[i], window[i], stride[i], padding);
pad_low[i] = padding_both[i].first;
}
CHECK_EQ(window_counts[0], source.n1());
CHECK_EQ(window_counts[1], source.n2());
CHECK_EQ(window_counts[2], source.n3());
CHECK_EQ(window_counts[3], source.n4());
// Do a full 4D select and Scatter.
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
for (int64 i2 = 0; i2 < window_counts[2]; ++i2) {
for (int64 i3 = 0; i3 < window_counts[3]; ++i3) {
// Now we are inside a window and need to find the max and the argmax.
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
int64 i2_base = i2 * stride[2] - pad_low[2];
int64 i3_base = i3 * stride[3] - pad_low[3];
int64 scatter_0 = (i0_base >= 0) ? i0_base : 0;
int64 scatter_1 = (i1_base >= 0) ? i1_base : 0;
int64 scatter_2 = (i2_base >= 0) ? i2_base : 0;
int64 scatter_3 = (i3_base >= 0) ? i3_base : 0;
float val = operand(scatter_0, scatter_1, scatter_2, scatter_3);
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
for (int64 i2_win = 0; i2_win < window[2]; ++i2_win) {
for (int64 i3_win = 0; i3_win < window[3]; ++i3_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i2_base + i2_win >= 0 && i3_base + i3_win >= 0 &&
i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2() &&
i2_base + i2_win < operand.n3() &&
i3_base + i3_win < operand.n4()) {
float tmp = operand(i0_base + i0_win, i1_base + i1_win,
i2_base + i2_win, i3_base + i3_win);
if (tmp > val) {
val = tmp;
scatter_0 = i0_base + i0_win;
scatter_1 = i1_base + i1_win;
scatter_2 = i2_base + i2_win;
scatter_3 = i3_base + i3_win;
}
}
}
}
}
}
(*result)(scatter_0, scatter_1, scatter_2, scatter_3) +=
source(i0, i1, i2, i3);
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ConvArray4DGeneralDimensions(
const Array4D<float>& lhs, const Array4D<float>& rhs,
std::pair<int64, int64> kernel_stride, Padding padding,
ConvolutionDimensionNumbers dimension_numbers) {
return ConvArray4DGeneralDimensionsDilated(lhs, rhs, kernel_stride, padding,
{1, 1}, {1, 1},
std::move(dimension_numbers));
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ConvArray4DGeneralDimensionsDilated(
const Array4D<float>& lhs, const Array4D<float>& rhs,
std::pair<int64, int64> kernel_stride, Padding padding,
std::pair<int64, int64> lhs_dilation, std::pair<int64, int64> rhs_dilation,
ConvolutionDimensionNumbers dnums) {
HloComputation::Builder b("ConvArray4DGeneralDimensionDilated");
auto lhs_literal = LiteralUtil::CreateR4FromArray4D<float>(lhs);
auto rhs_literal = LiteralUtil::CreateR4FromArray4D<float>(rhs);
std::array<int64, 2> ordered_kernel_strides;
std::array<int64, 2> ordered_input_dimensions;
std::array<int64, 2> ordered_kernel_dimensions;
if (dnums.kernel_spatial_dimensions(0) > dnums.kernel_spatial_dimensions(1)) {
ordered_kernel_strides[0] = kernel_stride.second;
ordered_kernel_strides[1] = kernel_stride.first;
} else {
ordered_kernel_strides[0] = kernel_stride.first;
ordered_kernel_strides[1] = kernel_stride.second;
}
ordered_input_dimensions[0] =
lhs_literal.shape().dimensions(dnums.input_spatial_dimensions(0));
ordered_input_dimensions[1] =
lhs_literal.shape().dimensions(dnums.input_spatial_dimensions(1));
ordered_kernel_dimensions[0] =
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(0));
ordered_kernel_dimensions[1] =
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(1));
std::vector<std::pair<int64, int64>> paddings =
MakePadding(ordered_input_dimensions, ordered_kernel_dimensions,
ordered_kernel_strides, padding);
CHECK_EQ(paddings.size(), 2);
Window window;
WindowDimension dim;
dim.set_size(
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(0)));
dim.set_stride(kernel_stride.first);
dim.set_padding_low(paddings[0].first);
dim.set_padding_high(paddings[0].second);
dim.set_window_dilation(rhs_dilation.first);
dim.set_base_dilation(lhs_dilation.first);
*window.add_dimensions() = dim;
WindowDimension dim2;
dim2.set_size(
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(1)));
dim2.set_stride(kernel_stride.second);
dim2.set_padding_low(paddings[1].first);
dim2.set_padding_high(paddings[1].second);
dim2.set_window_dilation(rhs_dilation.second);
dim2.set_base_dilation(lhs_dilation.second);
*window.add_dimensions() = dim2;
const Shape& shape =
ShapeInference::InferConvolveShape(
lhs_literal.shape(), rhs_literal.shape(),
/*feature_group_count=*/1, /*batch_group_count=*/1, window, dnums)
.ConsumeValueOrDie();
HloInstruction* lhs_instruction =
b.AddInstruction(HloInstruction::CreateConstant(std::move(lhs_literal)));
HloInstruction* rhs_instruction =
b.AddInstruction(HloInstruction::CreateConstant(std::move(rhs_literal)));
PrecisionConfig precision_config;
precision_config.mutable_operand_precision()->Resize(
/*new_size=*/2, PrecisionConfig::DEFAULT);
b.AddInstruction(HloInstruction::CreateConvolve(
shape, lhs_instruction, rhs_instruction, /*feature_group_count=*/1,
/*batch_group_count=*/1, window, dnums, precision_config));
HloModuleConfig config;
HloModule module("ReferenceUtil", config);
auto computation = module.AddEntryComputation(b.Build());
HloEvaluator evaluator;
Literal result_literal =
evaluator.Evaluate<const Literal*>(*computation, {}).ConsumeValueOrDie();
CHECK_EQ(ShapeUtil::Rank(result_literal.shape()), 4);
auto result =
absl::make_unique<Array4D<float>>(result_literal.shape().dimensions(0),
result_literal.shape().dimensions(1),
result_literal.shape().dimensions(2),
result_literal.shape().dimensions(3));
result->Each([&](absl::Span<const int64> indices, float* value) {
*value = result_literal.Get<float>(indices);
});
return result;
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceToColArray2D(
const Array2D<float>& matrix, float init,
const std::function<float(float, float)>& reduce_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<std::vector<float>>();
for (int64 i = 0; i < rows; ++i) {
float acc = init;
for (int64 j = 0; j < cols; ++j) {
acc = reduce_function(acc, matrix(i, j));
}
result->push_back(acc);
}
return result;
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceToRowArray2D(
const Array2D<float>& matrix, float init,
const std::function<float(float, float)>& reduce_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<std::vector<float>>();
for (int64 i = 0; i < cols; ++i) {
float acc = init;
for (int64 j = 0; j < rows; ++j) {
acc = reduce_function(acc, matrix(j, i));
}
result->push_back(acc);
}
return result;
}
/*static*/ std::vector<float> ReferenceUtil::Reduce4DTo1D(
const Array4D<float>& array, float init, absl::Span<const int64> dims,
const std::function<float(float, float)>& reduce_function) {
std::vector<float> result;
CHECK_EQ(dims.size(), 3);
const std::set<int64> dim_set(dims.begin(), dims.end());
CHECK_EQ(dim_set.size(), 3);
for (int64 a0 = 0; a0 == 0 || (!dim_set.count(0) && a0 < array.n1()); ++a0) {
for (int64 a1 = 0; a1 == 0 || (!dim_set.count(1) && a1 < array.n2());
++a1) {
for (int64 a2 = 0; a2 == 0 || (!dim_set.count(2) && a2 < array.n3());
++a2) {
for (int64 a3 = 0; a3 == 0 || (!dim_set.count(3) && a3 < array.n4());
++a3) {
float accumulator = init;
for (int64 i0 = 0; i0 == 0 || (dim_set.count(0) && i0 < array.n1());
++i0) {
for (int64 i1 = 0; i1 == 0 || (dim_set.count(1) && i1 < array.n2());
++i1) {
for (int64 i2 = 0;
i2 == 0 || (dim_set.count(2) && i2 < array.n3()); ++i2) {
for (int64 i3 = 0;
i3 == 0 || (dim_set.count(3) && i3 < array.n4()); ++i3) {
// Handle zero-sized arrays.
if (array.n1() > 0 && array.n2() > 0 && array.n3() > 0 &&
array.n4() > 0) {
accumulator = reduce_function(
accumulator, array(a0 + i0, a1 + i1, a2 + i2, a3 + i3));
}
}
}
}
}
result.push_back(accumulator);
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::Broadcast1DTo4D(
const std::vector<float>& array, const std::vector<int64>& bounds,
int64 broadcast_from_dim) {
auto result = absl::make_unique<Array4D<float>>(bounds[0], bounds[1],
bounds[2], bounds[3]);
for (int64 i = 0; i < result->n1(); ++i) {
for (int64 j = 0; j < result->n2(); ++j) {
for (int64 k = 0; k < result->n3(); ++k) {
for (int64 l = 0; l < result->n4(); ++l) {
switch (broadcast_from_dim) {
case 0:
(*result)(i, j, k, l) = array[i];
break;
case 1:
(*result)(i, j, k, l) = array[j];
break;
case 2:
(*result)(i, j, k, l) = array[k];
break;
case 3:
(*result)(i, j, k, l) = array[l];
break;
default:
break;
}
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::Reduce3DTo2D(
const Array3D<float>& array, float init, absl::Span<const int64> dims,
const std::function<float(float, float)>& reduce_function) {
CHECK_EQ(dims.size(), 1);
int64 rows = dims[0] == 0 ? array.n2() : array.n1();
int64 cols = dims[0] == 2 ? array.n2() : array.n3();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
result->Fill(init);
for (int i0 = 0; i0 < array.n1(); ++i0) {
for (int i1 = 0; i1 < array.n2(); ++i1) {
for (int i2 = 0; i2 < array.n3(); ++i2) {
int64 row = dims[0] == 0 ? i1 : i0;
int64 col = dims[0] == 2 ? i1 : i2;
(*result)(row, col) =
reduce_function((*result)(row, col), array(i0, i1, i2));
}
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MapArray2D(
const Array2D<float>& matrix,
const std::function<float(float)>& map_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
for (int64 i = 0; i < rows; ++i) {
for (int64 j = 0; j < cols; ++j) {
(*result)(i, j) = map_function(matrix(i, j));
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MapArray2D(
const Array2D<float>& lhs, const Array2D<float>& rhs,
const std::function<float(float, float)>& map_function) {
CHECK_EQ(lhs.height(), rhs.height());
CHECK_EQ(lhs.width(), rhs.width());
int64 rows = lhs.height();
int64 cols = rhs.width();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
for (int64 i = 0; i < rows; ++i) {
for (int64 j = 0; j < cols; ++j) {
(*result)(i, j) = map_function(lhs(i, j), rhs(i, j));
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MapWithIndexArray2D(
const Array2D<float>& matrix,
const std::function<float(float, int64, int64)>& map_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
for (int64 i = 0; i < rows; ++i) {
for (int64 j = 0; j < cols; ++j) {
(*result)(i, j) = map_function(matrix(i, j), i, j);
}
}
return result;
}
} // namespace xla
|
Bismarrck/tensorflow
|
tensorflow/compiler/xla/reference_util.cc
|
C++
|
apache-2.0
| 30,380
|
# android矢量动画
> 原创:余俊卿 转载请:<yujunqing@meizu.com>
----

看到这个动画是不是很炫酷,觉得在android L 之前难以实现?
近日才看到这篇文章<http://www.curious-creature.com/2013/12/21/android-recipe-4-path-tracing/>
这个demo和这篇文章都是弄android图形框架的人写的。。
捡重要的翻译一下:
路径效果可以基于一个鲜为人知的API实现--[PathEffect](http://developer.android.com/intl/zh-cn/reference/android/graphics/PathEffect.html),它可以设置在画笔(Paint)上,然后用于Canvas.drawPath()。现在已经实现四种类型的路径效果:
* CornerPathEffect
* DashPathEffect
* DiscretePathEffect
* PathDashPathEffect
这四种效果可以通过ComposePathEffect或者SumPathEffect来混合使用。
例子如下:

|
kenaiX/snowball
|
android矢量动画/README.md
|
Markdown
|
apache-2.0
| 879
|
<html>
<head>
<style type="text/css">
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
p { color: red; }
</style>
</head>
<body>
</body>
</html>
|
passmarked/inspect
|
samples/inline.styles.head.html
|
HTML
|
apache-2.0
| 13,545
|
/*
* jmemnobs.c
*
* Copyright (C) 1992-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file provides a really simple implementation of the system-
* dependent portion of the JPEG memory manager. This implementation
* assumes that no backing-store files are needed: all required space
* can be obtained from malloc().
* This is very portable in the sense that it'll compile on almost anything,
* but you'd better have lots of main memory (or virtual memory) if you want
* to process big images.
* Note that the max_memory_to_use option is ignored by this implementation.
*/
#define JPEG_INTERNALS
#include "MoJpgInclude.h"
#include "MoJpgLib.h"
#include "MoJpgMemory.h" /* import the system-dependent declarations */
#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
extern void * malloc JPP((size_t size));
extern void free JPP((void *ptr));
#endif
/*
* Memory allocation and freeing are controlled by the regular library
* routines malloc() and free().
*/
GLOBAL(void *)
jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
{
return (void *) malloc(sizeofobject);
}
GLOBAL(void)
jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
{
free(object);
}
/*
* "Large" objects are treated the same as "small" ones.
* NB: although we include FAR keywords in the routine declarations,
* this file won't actually work in 80x86 small/medium model; at least,
* you probably won't be able to process useful-size images in only 64KB.
*/
GLOBAL(void FAR *)
jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
{
return (void FAR *) malloc(sizeofobject);
}
GLOBAL(void)
jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
{
free(object);
}
/*
* This routine computes the total memory space available for allocation.
* Here we always say, "we got all you want bud!"
*/
GLOBAL(long)
jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
long max_bytes_needed, long already_allocated)
{
return max_bytes_needed;
}
/*
* Backing store (temporary file) management.
* Since jpeg_mem_available always promised the moon,
* this should never be called and we can just error out.
*/
GLOBAL(void)
jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
long total_bytes_needed)
{
ERREXIT(cinfo, JERR_NO_BACKING_STORE);
}
/*
* These routines take care of any system-dependent initialization and
* cleanup required. Here, there isn't any.
*/
GLOBAL(long)
jpeg_mem_init (j_common_ptr cinfo)
{
return 0; /* just set max_memory_to_use to 0 */
}
GLOBAL(void)
jpeg_mem_term (j_common_ptr cinfo)
{
/* no work */
}
|
favedit/MoCross
|
Source/Library/LibJpeg/jmemnobs.c
|
C
|
apache-2.0
| 2,781
|
package com.github.alexcojocaru.mojo.elasticsearch.v2;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.apache.maven.plugin.logging.Log;
import com.github.alexcojocaru.mojo.elasticsearch.v2.client.ElasticsearchClient;
import com.github.alexcojocaru.mojo.elasticsearch.v2.client.ElasticsearchClientException;
import com.github.alexcojocaru.mojo.elasticsearch.v2.client.Monitor;
/**
*
* @author Alex Cojocaru
*
*/
@RunWith(MockitoJUnitRunner.class)
public class InitScriptsTest extends ItBase
{
@Test
public void testClusterRunning()
{
boolean isRunning = Monitor.isClusterRunning(clusterName, instanceCount, client);
Assert.assertTrue("The ES cluster should be running", isRunning);
}
@Test
public void testIndexesExist() throws ElasticsearchClientException
{
Map index = client.get("/load_test_index", HashMap.class);
Assert.assertTrue(index.containsKey("load_test_index"));
index = client.get("/load_test_other_index", HashMap.class);
Assert.assertTrue(index.containsKey("load_test_other_index"));
}
@Test
public void testUser1ExistsInIndex1() throws ElasticsearchClientException
{
Map user = client.get("/load_test_index/test_type/1", HashMap.class);
// the user must exist
Assert.assertEquals(Boolean.TRUE, user.get("found"));
// the user was updated after it was created
Assert.assertEquals(new Integer(2), user.get("_version"));
// verify the user attributes
Map userData = (Map)user.get("_source");
Assert.assertEquals("alexc", userData.get("name"));
Assert.assertEquals(new Long(1388000499000L), userData.get("lastModified"));
}
@Test(expected = ElasticsearchClientException.class)
public void testUser2DoesNotExistInIndex1() throws ElasticsearchClientException
{
client.get("/load_test_index/test_type/2", HashMap.class);
}
@Test
public void testUser2ExistsInIndex2() throws ElasticsearchClientException
{
Map user = client.get("/load_test_other_index/test_type/1", HashMap.class);
// the user must exist
Assert.assertEquals(Boolean.TRUE, user.get("found"));
// verify the user attributes
Map userData = (Map)user.get("_source");
Assert.assertEquals("otherAlex", userData.get("name"));
}
}
|
alexcojocaru/elasticsearch-maven-plugin
|
src/it/runforked-with-init-scripts/src/test/java/com/github/alexcojocaru/mojo/elasticsearch/v2/InitScriptsTest.java
|
Java
|
apache-2.0
| 2,704
|
/*******************************************************************************
* Copyright 2014 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package gov.nasa.ensemble.core.plan.temporal.modification;
import gov.nasa.ensemble.core.jscience.TemporalExtent;
import gov.nasa.ensemble.core.model.plan.EPlanElement;
import gov.nasa.ensemble.core.model.plan.temporal.TemporalMember;
import gov.nasa.ensemble.core.model.plan.util.EPlanUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.measure.quantity.Duration;
import org.jscience.physics.amount.Amount;
public class TemporalExtentsCache {
private final Map<EPlanElement, TemporalExtent> planElementToExtent = new HashMap<EPlanElement, TemporalExtent>();
public TemporalExtentsCache() {
// default constructor
}
public TemporalExtentsCache(EPlanElement plan) {
cache(plan);
}
public TemporalExtentsCache(TemporalExtentsCache initialState) {
planElementToExtent.putAll(initialState.planElementToExtent);
}
public void cache(EPlanElement pe) {
planElementToExtent.put(pe, pe.getMember(TemporalMember.class).getExtent());
for (EPlanElement child : EPlanUtils.getChildren(pe)) {
cache(child);
}
}
public TemporalExtent get(EPlanElement pe) {
return planElementToExtent.get(pe);
}
public Date getStart(EPlanElement element) {
TemporalExtent initialExtent = get(element);
if (initialExtent != null) {
return initialExtent.getStart();
}
return element.getMember(TemporalMember.class).getStartTime();
}
public Amount<Duration> getDuration(EPlanElement element) {
TemporalExtent initialExtent = get(element);
if (initialExtent != null) {
return initialExtent.getDuration();
}
return element.getMember(TemporalMember.class).getDuration();
}
public Date getEnd(EPlanElement element) {
TemporalExtent initialExtent = get(element);
if (initialExtent != null) {
return initialExtent.getEnd();
}
return element.getMember(TemporalMember.class).getEndTime();
}
protected void set(EPlanElement element, TemporalExtent extent) {
planElementToExtent.put(element, extent);
}
public void clear() {
planElementToExtent.clear();
}
@Override
public TemporalExtentsCache clone() {
return new TemporalExtentsCache(this);
}
}
|
nasa/OpenSPIFe
|
gov.nasa.ensemble.core.plan.temporal/src/gov/nasa/ensemble/core/plan/temporal/modification/TemporalExtentsCache.java
|
Java
|
apache-2.0
| 3,027
|
package org.zstack.sdk;
import java.util.HashMap;
import java.util.Map;
import org.zstack.sdk.*;
public class GetVolumeQosAction extends AbstractAction {
private static final HashMap<String, Parameter> parameterMap = new HashMap<>();
private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>();
public static class Result {
public ErrorCode error;
public org.zstack.sdk.GetVolumeQosResult value;
public Result throwExceptionIfError() {
if (error != null) {
throw new ApiException(
String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
);
}
return this;
}
}
@Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String uuid;
@Param(required = false)
public java.util.List systemTags;
@Param(required = false)
public java.util.List userTags;
@Param(required = true)
public String sessionId;
private Result makeResult(ApiResult res) {
Result ret = new Result();
if (res.error != null) {
ret.error = res.error;
return ret;
}
org.zstack.sdk.GetVolumeQosResult value = res.getResult(org.zstack.sdk.GetVolumeQosResult.class);
ret.value = value == null ? new org.zstack.sdk.GetVolumeQosResult() : value;
return ret;
}
public Result call() {
ApiResult res = ZSClient.call(this);
return makeResult(res);
}
public void call(final Completion<Result> completion) {
ZSClient.call(this, new InternalCompletion() {
@Override
public void complete(ApiResult res) {
completion.complete(makeResult(res));
}
});
}
protected Map<String, Parameter> getParameterMap() {
return parameterMap;
}
protected Map<String, Parameter> getNonAPIParameterMap() {
return nonAPIParameterMap;
}
protected RestInfo getRestInfo() {
RestInfo info = new RestInfo();
info.httpMethod = "GET";
info.path = "/volumes/{uuid}/qos";
info.needSession = true;
info.needPoll = false;
info.parameterName = "";
return info;
}
}
|
camilesing/zstack
|
sdk/src/main/java/org/zstack/sdk/GetVolumeQosAction.java
|
Java
|
apache-2.0
| 2,403
|
package br.cefetrj.sagitarii.core;
import java.io.File;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import br.cefetrj.sagitarii.core.config.Configurator;
import br.cefetrj.sagitarii.core.filetransfer.FileReceiverManager;
import br.cefetrj.sagitarii.core.statistics.AgeCalculator;
import br.cefetrj.sagitarii.core.types.UserType;
import br.cefetrj.sagitarii.metrics.Chronos;
import br.cefetrj.sagitarii.misc.PathFinder;
import br.cefetrj.sagitarii.misc.json.GSONThreadLocalImmolater;
import br.cefetrj.sagitarii.persistence.entity.Domain;
import br.cefetrj.sagitarii.persistence.entity.Experiment;
import br.cefetrj.sagitarii.persistence.entity.User;
import br.cefetrj.sagitarii.persistence.exceptions.NotFoundException;
import br.cefetrj.sagitarii.persistence.infra.ConnFactory;
import br.cefetrj.sagitarii.persistence.repository.RelationRepository;
import br.cefetrj.sagitarii.persistence.services.ExperimentService;
import br.cefetrj.sagitarii.persistence.services.UserService;
@WebListener
public class Orchestrator implements ServletContextListener {
private ScheduledExecutorService scheduler;
private void loggerDebug( String log ) {
System.out.println( log );
}
private void loggerError( String log ){
System.out.println( log );
}
@Override
public void contextInitialized(ServletContextEvent event) {
loggerDebug("--------------------------------------");
loggerDebug("Sagitarii Workflow Data Science System");
loggerDebug("CEFET-RJ 2015");
loggerDebug("Carlos M. Abreu magno.mabreu@gmail.com");
loggerDebug("--------------------------------------");
ServletContext context = event.getServletContext();
System.setProperty("rootPath", context.getRealPath("/") );
String databaseName = System.getProperty("SAGITARII_DATABASE");
String password = System.getProperty("SAGITARII_PASSWORD");
String userName = System.getProperty("SAGITARII_USER");
System.out.println( " >>>>> " + userName + "@" + password + ":" + databaseName );
UserService us;
try {
int interval = 5;
int maxInputBufferCapacity = 500;
int fileReceiverPort = 3333;
int chunkBuffer = 100;
Configurator config = Configurator.getInstance("config.xml");
interval = config.getPoolIntervalSeconds();
maxInputBufferCapacity = config.getMaxInputBufferCapacity();
fileReceiverPort = config.getFileReceiverPort();
chunkBuffer = config.getFileReceiverChunkBufferSize();
String user = config.getUserName();
String passwd = config.getPassword();
String database = config.getDatabaseName();
ConnFactory.setCredentials(user, passwd, database);
try {
AgeCalculator.getInstance().retrieveList();
} catch ( NotFoundException e ) {
//
} catch ( Exception e ) {
loggerError("Critical database initialization error: " + e.getMessage() );
return;
}
us = new UserService();
try {
us.getList().size();
} catch (NotFoundException ignored ) {
// No users found. We need an Admin!
User usr = new User();
usr.setFullName("System Administrator");
usr.setLoginName("admin");
usr.setType( UserType.ADMIN );
usr.setPassword("admin");
usr.setUserMail("no.mail@localhost");
us.newTransaction();
us.insertUser(usr);
loggerDebug("System Administrator created");
}
loggerDebug("check for interrupted work");
try {
ExperimentService ws = new ExperimentService();
List<Experiment> running = ws.getRunning();
Sagitarii.getInstance().setRunningExperiments( running );
Sagitarii.getInstance().reloadAfterCrash();
loggerDebug("found " + Sagitarii.getInstance().getRunningExperiments().size() + " running experiments");
} catch ( NotFoundException e ) {
loggerDebug("no running experiments found");
}
loggerDebug("done.");
Sagitarii.getInstance().setMaxInputBufferCapacity(maxInputBufferCapacity);
loggerDebug("Sagitarii Scheduler: check every " + interval + " seconds");
try {
RelationRepository rr = new RelationRepository();
List<Domain> domains = rr.getDomains();
DomainStorage.getInstance().setDomains( domains );
} catch ( NotFoundException ignored ) {
}
loggerDebug("Start File Receiver Manager on port " + fileReceiverPort);
loggerDebug("Cache directory:");
loggerDebug(" > " + PathFinder.getInstance().getPath() + "/cache");
FileReceiverManager.getInstance().startServer( fileReceiverPort, chunkBuffer );
loggerDebug("File Receiver Manager started.");
File createStorage = new File( PathFinder.getInstance().getPath() + "/storage/" );
createStorage.mkdirs();
scheduler = Executors.newSingleThreadScheduledExecutor();
MainHeartBeat as = new MainHeartBeat();
scheduler.scheduleAtFixedRate(as, 0, interval , TimeUnit.SECONDS);
Chronos chronos = new Chronos();
scheduler.scheduleAtFixedRate( chronos , 0, 1, TimeUnit.SECONDS);
} catch (Exception e) {
System.out.println( e.getMessage() );
loggerError( e.getMessage() );
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent event) {
loggerDebug("shutdown");
scheduler.shutdownNow();
loggerDebug("immolating JSON threads...");
int result = 0;
try {
result = GSONThreadLocalImmolater.immolate();
} catch ( Exception e ) {
loggerError( e.getMessage() );
}
loggerDebug("done: " + result + " threads killed.");
try {
FileReceiverManager.getInstance().stopServer();
} catch (Exception e) {
//
}
}
}
|
eic-cefet-rj/sagitarii
|
src/main/java/br/cefetrj/sagitarii/core/Orchestrator.java
|
Java
|
apache-2.0
| 6,199
|
# go-stocks
Some Go code to fetch and process stock market data
|
eldritchideen/go-stocks
|
README.md
|
Markdown
|
apache-2.0
| 64
|
package com.suncht.wordread.model;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import com.suncht.wordread.parser.WordTableParser.WordDocType;
public final class WordTableCellContents {
public static WordTableCellContent<?> getCellContent(XWPFTableCell cell) {
WordTableCellContent<?> content = null;
if (isFormula(cell)) { //是公式
content = new WordTableCellContentFormula(WordDocType.DOCX);
} else if (isImage(cell)) { //图片
content = new WordTableCellContentImage(WordDocType.DOCX);
} else if (isOleObject(cell)) { //OLE对象
content = new WordTableCellContentOleObject(WordDocType.DOCX);
} else { //一般文本
content = new WordTableCellContentText(WordDocType.DOCX);
}
content.load(cell);
return content;
}
public static boolean isFormula(XWPFTableCell cell) {
String xmlText = cell.getCTTc().xmlText();
return xmlText.contains("<m:oMathPara>") && xmlText.contains("</m:oMathPara>");
}
public static boolean isImage(XWPFTableCell cell) {
String xmlText = cell.getCTTc().xmlText();
return xmlText.contains("<w:drawing>") && xmlText.contains("</w:drawing>");
}
public static boolean isOleObject(XWPFTableCell cell) {
String xmlText = cell.getCTTc().xmlText();
return xmlText.contains("<w:object>") && xmlText.contains("</w:object>");
}
public static WordTableCellContent<?> getCellContent(TableCell cell) {
WordTableCellContent<?> content = null;
if (isFormula(cell)) { //是公式
content = new WordTableCellContentFormula(WordDocType.DOC);
} else if (isImage(cell)) { //图片
content = new WordTableCellContentImage(WordDocType.DOC);
} else if (isOleObject(cell)) { //OLE对象
content = new WordTableCellContentOleObject(WordDocType.DOC);
} else { //一般文本
content = new WordTableCellContentText(WordDocType.DOC);
}
content.load(cell);
return content;
}
public static boolean isFormula(TableCell cell) {
String xmlText = cell.text();
return xmlText.contains("<m:oMathPara>") && xmlText.contains("</m:oMathPara>");
}
public static boolean isImage(TableCell cell) {
String xmlText = cell.text();
return xmlText.contains("<w:drawing>") && xmlText.contains("</w:drawing>");
}
public static boolean isOleObject(TableCell cell) {
String xmlText = cell.text();
return xmlText.contains("<w:object>") && xmlText.contains("</w:object>");
}
}
|
suncht/wordtable-read
|
src/main/java/com/suncht/wordread/model/WordTableCellContents.java
|
Java
|
apache-2.0
| 2,428
|
/*
* Copyright the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package therian.operation;
import java.util.Collection;
import therian.position.Position;
/**
* "Add" transformation. Like {@link Collection#add(Object)}, the result of an {@link Add} operation is intended to
* reflect whether a change was made to the target position.
*
* @param <SOURCE>
* @param <TARGET>
*/
public class Add<SOURCE, TARGET> extends Transform<SOURCE, TARGET, Boolean, Position.Readable<TARGET>> {
/**
* Fluent factory method.
* @param targetPosition
* @param sourcePosition
* @return {@link Add}
*/
public static <SOURCE, TARGET> Add<SOURCE, TARGET> to(Position.Readable<TARGET> targetPosition,
Position.Readable<SOURCE> sourcePosition) {
return new Add<>(sourcePosition, targetPosition);
}
protected Add(Position.Readable<SOURCE> sourcePosition, Position.Readable<TARGET> targetPosition) {
super(sourcePosition, targetPosition);
}
public void setResult(boolean result) {
setResult(Boolean.valueOf(result));
}
}
|
mbenson/therian
|
core/src/main/java/therian/operation/Add.java
|
Java
|
apache-2.0
| 1,647
|
use std::thread;
use std::sync::mpsc;
pub struct CancelSender(mpsc::Sender<()>);
impl CancelSender {
pub fn cancel_thread(self) {
let CancelSender(sender) = self;
let _ = sender.send(());
}
}
pub struct CancelReceiver(mpsc::Receiver<()>);
impl CancelReceiver {
pub fn has_been_canceled(&self) -> bool {
let &CancelReceiver(ref receiver) = self;
match receiver.try_recv() {
Ok(_) | Err(mpsc::TryRecvError::Disconnected) => return true,
Err(mpsc::TryRecvError::Empty) => return false,
}
}
}
// Wraps the standard thread::spawn, creating a channel to be used for canceling the thread.
// Note that is_canceled will automatically become true if the cancel sender is lost, so be sure to
// hold onto it!
pub fn spawn_cancelable<F>(to_execute: F) -> CancelSender
where F: FnOnce(CancelReceiver), F: Send + 'static {
let (sender, receiver) = mpsc::channel();
thread::spawn(move || to_execute(CancelReceiver(receiver)));
CancelSender(sender)
}
|
aeidelson/realtime-peer-sync
|
lib/src/utils/thread.rs
|
Rust
|
apache-2.0
| 1,040
|
/****************************************************************************/
/* File: Write.java */
/* Author: F. Georges */
/* Company: H2O Consulting */
/* Date: 2015-01-07 */
/* Tags: */
/* Copyright (c) 2015 Florent Georges (see end of file.) */
/* ------------------------------------------------------------------------ */
package org.expath.file;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.List;
import org.expath.tools.model.Sequence;
import org.expath.tools.ToolsException;
import org.expath.tools.model.Element;
import org.expath.tools.serial.SerialParameters;
/**
* Facade for the `write*` and `append*` functions of the EXPath File module.
*
* @author Florent Georges
* @date 2015-01-07
* @see http://expath.org/spec/file#in-out
* @see http://expath.org/spec/file/20131203#in-out
*/
public class Write
{
// file:append($file as xs:string,
// $items as item()*) as empty-sequence()
// file:append($file as xs:string,
// $items as item()*,
// $params as element(output:serialization-parameters)) as empty-sequence()
// [file:no-dir] is raised if the parent directory of $file does not exist.
// [file:is-dir] is raised if $file points to a directory.
// [file:io-error] is raised if any other error occurs.
public void append(String file, Sequence items)
throws FileException
{
SerialParameters params = new SerialParameters();
append(file, items, params);
}
public void append(String file, Sequence items, Element params)
throws FileException
{
write(file, items, params, true);
}
public void append(String file, Sequence items, SerialParameters params)
throws FileException
{
write(file, items, params, true);
}
// file:append-binary($file as xs:string,
// $value as xs:base64Binary) as empty-sequence()
// [file:no-dir] is raised if the parent directory of $file does not exist.
// [file:is-dir] is raised if $file points to a directory.
// [file:io-error] is raised if any other error occurs.
public void appendBinary(String file, byte[] value)
throws FileException
{
writeBinary(file, value, true);
}
// file:append-text($file as xs:string,
// $value as xs:string) as empty-sequence()
// file:append-text($file as xs:string,
// $value as xs:string,
// $encoding as xs:string) as empty-sequence()
// [file:no-dir] is raised if the parent directory of $file does not exist.
// [file:is-dir] is raised if $file points to a directory.
// [file:unknown-encoding] is raised if $encoding is invalid or not supported by the implementation.
// [file:io-error] is raised if any other error occurs.
public void appendText(String file, String value)
throws FileException
{
writeText(file, value, true);
}
public void appendText(String file, String value, String encoding)
throws FileException
{
writeText(file, value, encoding, true);
}
// file:append-text-lines($file as xs:string,
// $values as xs:string*) as empty-sequence()
// file:append-text-lines($file as xs:string,
// $lines as xs:string*,
// $encoding as xs:string) as empty-sequence()
// [file:no-dir] is raised if the parent directory of $file does not exist.
// [file:is-dir] is raised if $file points to a directory.
// [file:unknown-encoding] is raised if $encoding is invalid or not supported by the implementation.
// [file:io-error] is raised if any other error occurs.
public void appendTextLines(String file, List<String> values)
throws FileException
{
writeTextLines(file, values, true);
}
public void appendTextLines(String file, List<String> values, String encoding)
throws FileException
{
writeTextLines(file, values, encoding, true);
}
// file:write($file as xs:string,
// $items as item()*) as empty-sequence()
// file:write($file as xs:string,
// $items as item()*,
// $params as element(output:serialization-parameters)) as empty-sequence()
// [file:no-dir] is raised if the parent directory of $file does not exist.
// [file:is-dir] is raised if $file points to a directory.
// [file:io-error] is raised if any other error occurs.
public void write(String file, Sequence items)
throws FileException
{
SerialParameters params = new SerialParameters();
write(file, items, params);
}
public void write(String file, Sequence items, Element params)
throws FileException
{
write(file, items, params, false);
}
public void write(String file, Sequence items, SerialParameters params)
throws FileException
{
write(file, items, params, false);
}
// file:write-binary($file as xs:string,
// $value as xs:base64Binary) as empty-sequence()
// file:write-binary($file as xs:string,
// $value as xs:base64Binary,
// $offset as xs:integer) as empty-sequence()
// [file:no-dir] is raised if the parent directory of $file does not exist.
// [file:is-dir] is raised if $file points to a directory.
// [file:out-of-range] is raised if $offset is negative, or if it exceeds the current file size.
// [file:io-error] is raised if any other error occurs.
public void writeBinary(String file, byte[] value)
throws FileException
{
writeBinary(file, value, false);
}
public void writeBinary(String file, byte[] value, long offset)
throws FileException
{
// is offset negative?
if ( offset < 0 ) {
throw FileException.outOfRange("Offset is negative: " + offset);
}
// open the file
RandomAccessFile f = Util.openRandomAccess(file);
// global try/catch to properly close the file, whatever exec path is taken
try {
// get its length
long len;
try {
len = f.length();
}
catch ( IOException ex ) {
throw FileException.ioError("Error getting the size of the file: " + file, ex);
}
// is offset greater than file size?
if ( offset > len ) {
throw FileException.outOfRange("Offset (" + offset + ") is greater than the file size (" + len + "): " + file);
}
// position to offset
try {
f.seek(offset);
}
catch ( IOException ex ) {
throw FileException.ioError("Error seeking to offset (" + offset + ") on the file: " + file, ex);
}
// write it!
f.write(value);
}
catch ( IOException ex ) {
throw FileException.ioError("Error writing at offset (" + offset + ") "
+ value.length + " bytes in the file: " + file, ex);
}
finally {
Util.close(f);
}
}
// file:write-text($file as xs:string,
// $value as xs:string) as empty-sequence()
// file:write-text($file as xs:string,
// $value as xs:string,
// $encoding as xs:string) as empty-sequence()
// [file:no-dir] is raised if the parent directory of $file does not exist.
// [file:is-dir] is raised if $file points to a directory.
// [file:unknown-encoding] is raised if $encoding is invalid or not supported by the implementation.
// [file:io-error] is raised if any other error occurs.
public void writeText(String file, String value)
throws FileException
{
writeText(file, value, false);
}
public void writeText(String file, String value, String encoding)
throws FileException
{
writeText(file, value, encoding, false);
}
// file:write-text-lines($file as xs:string,
// $values as xs:string*) as empty-sequence()
// file:write-text-lines($file as xs:string,
// $values as xs:string*,
// $encoding as xs:string) as empty-sequence()
// [file:no-dir] is raised if the parent directory of $file does not exist.
// [file:is-dir] is raised if $file points to a directory.
// [file:unknown-encoding] is raised if $encoding is invalid or not supported by the implementation.
// [file:io-error] is raised if any other error occurs.
public void writeTextLines(String file, List<String> values)
throws FileException
{
writeTextLines(file, values, false);
}
public void writeTextLines(String file, List<String> values, String encoding)
throws FileException
{
writeTextLines(file, values, encoding, false);
}
private void write(String file, Sequence items, Element params, boolean append)
throws FileException
{
try {
SerialParameters sp = SerialParameters.parse(params);
write(file, items, sp, append);
}
catch ( ToolsException ex ) {
throw FileException.ioError("Error parsing the serialization parameters", ex);
}
}
private void write(String file, Sequence items, SerialParameters params, boolean append)
throws FileException
{
Util.ensureNotNull(file, "file cannot be null");
Util.ensureNotNull(items, "items cannot be null");
OutputStream out = null;
try {
out = Util.openOutputStream(file, append);
items.serialize(out, params);
}
catch ( ToolsException ex ) {
throw FileException.ioError("Error serializing to the file: " + file, ex);
}
finally {
Util.close(out);
}
}
private void writeBinary(String file, byte[] value, boolean append)
throws FileException
{
Util.ensureNotNull(file, "file cannot be null");
Util.ensureNotNull(value, "value cannot be null");
OutputStream out = null;
try {
out = Util.openOutputStream(file, append);
out.write(value);
}
catch ( IOException ex ) {
throw FileException.ioError("Error writing binary to the file: " + file, ex);
}
finally {
Util.close(out);
}
}
private void writeText(String file, String value, boolean append)
throws FileException
{
Util.ensureNotNull(file, "file cannot be null");
Util.ensureNotNull(value, "value cannot be null");
Writer out = null;
try {
out = Util.openWriter(file, append);
out.write(value);
}
catch ( IOException ex ) {
throw FileException.ioError("Error writing text to the file: " + file, ex);
}
finally {
Util.close(out);
}
}
private void writeText(String file, String value, String encoding, boolean append)
throws FileException
{
Util.ensureNotNull(file, "file cannot be null");
Util.ensureNotNull(value, "value cannot be null");
Util.ensureNotNull(encoding, "encoding cannot be null");
OutputStream out = null;
try {
out = Util.openOutputStream(file, append);
byte[] bytes = value.getBytes(encoding);
out.write(bytes);
}
catch ( UnsupportedEncodingException ex ) {
throw FileException.unknownEncoding("Unsupported encoding: " + encoding, ex);
}
catch ( IOException ex ) {
throw FileException.ioError("Error writing text to the file: " + file, ex);
}
finally {
Util.close(out);
}
}
private void writeTextLines(String file, List<String> values, boolean append)
throws FileException
{
Util.ensureNotNull(file, "file cannot be null");
Util.ensureNotNull(values, "values cannot be null");
final String nl = new Properties().lineSeparator();
Writer out = null;
try {
out = Util.openWriter(file, append);
for ( String line : values ) {
out.write(line);
out.write(nl);
}
}
catch ( IOException ex ) {
throw FileException.ioError("Error writing text to the file: " + file, ex);
}
finally {
Util.close(out);
}
}
private void writeTextLines(String file, List<String> values, String encoding, boolean append)
throws FileException
{
Util.ensureNotNull(file, "file cannot be null");
Util.ensureNotNull(values, "values cannot be null");
Util.ensureNotNull(encoding, "encoding cannot be null");
// get the newline separator, as bytes
final String nlstr = new Properties().lineSeparator();
final byte[] nl;
try {
nl = nlstr.getBytes(encoding);
}
catch ( UnsupportedEncodingException ex ) {
throw FileException.unknownEncoding("Unsupported encoding: " + encoding, ex);
}
OutputStream out = null;
try {
out = Util.openOutputStream(file, true);
for ( String line : values ) {
byte[] bytes = line.getBytes(encoding);
out.write(bytes);
out.write(nl);
}
}
catch ( IOException ex ) {
throw FileException.ioError("Error writing text to the file: " + file, ex);
}
finally {
Util.close(out);
}
}
}
/* ------------------------------------------------------------------------ */
/* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS COMMENT. */
/* */
/* The contents of this file are subject to the Mozilla Public License */
/* Version 1.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.mozilla.org/MPL/. */
/* */
/* Software distributed under the License is distributed on an "AS IS" */
/* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See */
/* the License for the specific language governing rights and limitations */
/* under the License. */
/* */
/* The Original Code is: all this file. */
/* */
/* The Initial Developer of the Original Code is Florent Georges. */
/* */
/* Contributor(s): none. */
/* ------------------------------------------------------------------------ */
|
fgeorges/expath-file-java
|
file-java/src/org/expath/file/Write.java
|
Java
|
apache-2.0
| 15,927
|
/*******************************************************************************
* 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.olingo.odata2.janos.processor.ref;
import junit.framework.Assert;
import org.apache.http.HttpResponse;
import org.apache.olingo.odata2.api.commons.HttpContentType;
import org.apache.olingo.odata2.api.commons.HttpHeaders;
import org.apache.olingo.odata2.api.commons.HttpStatusCodes;
import org.apache.olingo.odata2.api.edm.Edm;
import org.custommonkey.xmlunit.SimpleNamespaceContext;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.custommonkey.xmlunit.XMLAssert.assertXpathExists;
/**
* Tests employing the reference scenario reading the service document in JSON format.
*
*/
public class ServiceJsonTest extends AbstractRefTest {
public ServiceJsonTest(String modelPackage) {
super(modelPackage);
}
@Test
public void serviceDocumentDollarFormatJson() throws Exception {
final HttpResponse response = callUri("?$format=json");
// checkMediaType(response, HttpContentType.APPLICATION_JSON);
String body = getBody(response);
Assert.assertTrue(jsonDataResponseContains(body, "Buildings"));
Assert.assertTrue(jsonDataResponseContains(body, "Employees"));
Assert.assertTrue(jsonDataResponseContains(body, "Managers"));
Assert.assertTrue(jsonDataResponseContains(body, "Photos"));
Assert.assertTrue(jsonDataResponseContains(body, "Rooms"));
Assert.assertTrue(jsonDataResponseContains(body, "Teams"));
}
private boolean jsonDataResponseContains(final String content, final String containingValue) {
return content.matches("\\{\"d\":\\{\"EntitySets\":\\[.*"
+ containingValue + ".*\"\\]\\}\\}");
}
@Test
public void serviceDocumentAcceptHeaderJson() throws Exception {
final HttpResponse response = callUri("", HttpHeaders.ACCEPT, HttpContentType.APPLICATION_JSON);
String body = getBody(response);
Assert.assertTrue(jsonDataResponseContains(body, "Buildings"));
Assert.assertTrue(jsonDataResponseContains(body, "Employees"));
Assert.assertTrue(jsonDataResponseContains(body, "Managers"));
Assert.assertTrue(jsonDataResponseContains(body, "Photos"));
Assert.assertTrue(jsonDataResponseContains(body, "Rooms"));
Assert.assertTrue(jsonDataResponseContains(body, "Teams"));
}
@Test
public void serviceDocumentAcceptHeaderInvalidCharset() throws Exception {
final HttpResponse response =
callUri("", HttpHeaders.ACCEPT, HttpContentType.APPLICATION_XML + "; charset=iso-latin-1",
HttpStatusCodes.NOT_ACCEPTABLE);
final String body = getBody(response);
Map<String, String> prefixMap = new HashMap<>();
prefixMap.put("a", Edm.NAMESPACE_M_2007_08);
XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));
assertXpathExists("/a:error", body);
assertXpathExists("/a:error/a:code", body);
assertXpathExists("/a:error/a:message", body);
}
}
|
mibo/janos
|
janos-it/src/test/java/org/apache/olingo/odata2/janos/processor/ref/ServiceJsonTest.java
|
Java
|
apache-2.0
| 3,873
|
//
// ViewController.h
// TestGit
//
// Created by ws on 17/4/17.
// Copyright © 2017年 ws. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
nlgb/Test
|
TestGit/TestGit/ViewController.h
|
C
|
apache-2.0
| 201
|
/* ====================================================================
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.
==================================================================== */
using System;
using System.Collections;
using System.Text;
using NPOI.POIFS.FileSystem;
using NPOI.POIFS.Properties;
using NPOI.POIFS.Dev;
namespace NPOI.POIFS.FileSystem
{
/// <summary>
/// Simple implementation of DocumentEntry
/// @author Marc Johnson (mjohnson at apache dot org)
/// </summary>
internal class DocumentNode : EntryNode, POIFSViewable, DocumentEntry
{
// underlying POIFSDocument instance
private POIFSDocument _document;
/**
* create a DocumentNode. This method Is not public by design; it
* Is intended strictly for the internal use of this package
*
* @param property the DocumentProperty for this DocumentEntry
* @param parent the parent of this entry
*/
public DocumentNode(DocumentProperty property, DirectoryNode parent):base(property, parent)
{
_document = property.Document;
}
/**
* get the POIFSDocument
*
* @return the internal POIFSDocument
*/
public POIFSDocument Document
{
get { return _document; }
}
/**
* get the zize of the document, in bytes
*
* @return size in bytes
*/
public int Size
{
get { return Property.Size; }
}
/**
* Is this a DocumentEntry?
*
* @return true if the Entry Is a DocumentEntry, else false
*/
public override bool IsDocumentEntry
{
get{return true;}
}
/**
* extensions use this method to verify internal rules regarding
* deletion of the underlying store.
*
* @return true if it's ok to delete the underlying store, else
* false
*/
protected override bool IsDeleteOK
{
get { return true; }
}
/**
* Get an array of objects, some of which may implement
* POIFSViewable
*
* @return an array of Object; may not be null, but may be empty
*/
public Array ViewableArray
{
get { return new Object[0]; }
}
/**
* Get an Iterator of objects, some of which may implement
* POIFSViewable
*
* @return an Iterator; may not be null, but may have an empty
* back end store
*/
public IEnumerator ViewableIterator
{
get
{
IList components = new ArrayList();
components.Add(Property);
components.Add(_document);
return components.GetEnumerator();
}
}
/**
* Give viewers a hint as to whether to call getViewableArray or
* getViewableIterator
*
* @return true if a viewer should call getViewableArray, false if
* a viewer should call getViewableIterator
*/
public bool PreferArray
{
get { return false; }
}
/**
* Provides a short description of the object, to be used when a
* POIFSViewable object has not provided its contents.
*
* @return short description
*/
public String ShortDescription
{
get{return Name;}
}
}
}
|
treenew/sofire
|
src/Core/Sofire.Extends/Excel/NPOI/POIFS/FileSystem/DocumentNode.cs
|
C#
|
apache-2.0
| 4,539
|
FROM centurylink/apache-php:latest
MAINTAINER CenturyLink
# Install packages
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get -y upgrade && \
DEBIAN_FRONTEND=noninteractive apt-get -y install supervisor pwgen && \
apt-get -y install mysql-client && \
apt-get -y install postgresql-client
# Download v7.38 of Drupal into /app
RUN rm -fr /app && mkdir /app && cd /app && \
curl -O http://ftp.drupal.org/files/projects/drupal-7.38.tar.gz && \
tar -xzvf drupal-7.38.tar.gz && \
rm drupal-7.38.tar.gz && \
mv drupal-7.38/* drupal-7.38/.htaccess ./ && \
mv drupal-7.38/.gitignore ./ && \
rmdir drupal-7.38
#Config and set permissions for setting.php
RUN cp app/sites/default/default.settings.php app/sites/default/settings.php && \
chmod a+w app/sites/default/settings.php && \
chmod a+w app/sites/default
EXPOSE 80
CMD exec supervisord -n
|
CenturyLinkLabs/docker-drupal
|
Dockerfile
|
Dockerfile
|
apache-2.0
| 877
|
/**
* 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 io.openwire.codec.v3;
import io.openwire.codec.BaseDataStreamMarshaller;
import io.openwire.codec.BooleanStream;
import io.openwire.codec.OpenWireFormat;
import io.openwire.commands.DataStructure;
import io.openwire.commands.SessionId;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class SessionIdMarshaller extends BaseDataStreamMarshaller {
/**
* Return the type of Data Structure we marshal
*
* @return short representation of the type data structure
*/
@Override
public byte getDataStructureType() {
return SessionId.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
@Override
public DataStructure createObject() {
return new SessionId();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
SessionId info = (SessionId) o;
info.setConnectionId(tightUnmarshalString(dataIn, bs));
info.setValue(tightUnmarshalLong(wireFormat, dataIn, bs));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
SessionId info = (SessionId) o;
int rc = super.tightMarshal1(wireFormat, o, bs);
rc += tightMarshalString1(info.getConnectionId(), bs);
rc += tightMarshalLong1(wireFormat, info.getValue(), bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o
* the instance to be marshaled
* @param dataOut
* the output stream
* @throws IOException
* thrown if an error occurs
*/
@Override
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
SessionId info = (SessionId) o;
tightMarshalString2(info.getConnectionId(), dataOut, bs);
tightMarshalLong2(wireFormat, info.getValue(), dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
SessionId info = (SessionId) o;
info.setConnectionId(looseUnmarshalString(dataIn));
info.setValue(looseUnmarshalLong(wireFormat, dataIn));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
SessionId info = (SessionId) o;
super.looseMarshal(wireFormat, o, dataOut);
looseMarshalString(info.getConnectionId(), dataOut);
looseMarshalLong(wireFormat, info.getValue(), dataOut);
}
}
|
tabish121/OpenWire
|
openwire-legacy/src/main/java/io/openwire/codec/v3/SessionIdMarshaller.java
|
Java
|
apache-2.0
| 4,339
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="zh">
<head>
<!-- Generated by javadoc (1.8.0_91) on Thu Jul 13 16:16:26 CST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>接口 com.webside.quartz.service.ScheduleJobService的使用 (webside 0.0.1-SNAPSHOT API)</title>
<meta name="date" content="2017-07-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="\u63A5\u53E3 com.webside.quartz.service.ScheduleJobService\u7684\u4F7F\u7528 (webside 0.0.1-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>您的浏览器已禁用 JavaScript。</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="跳过导航链接">跳过导航链接</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../../overview-summary.html">概览</a></li>
<li><a href="../package-summary.html">程序包</a></li>
<li><a href="../../../../../com/webside/quartz/service/ScheduleJobService.html" title="com.webside.quartz.service中的接口">类</a></li>
<li class="navBarCell1Rev">使用</li>
<li><a href="../package-tree.html">树</a></li>
<li><a href="../../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../../index-all.html">索引</a></li>
<li><a href="../../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>上一个</li>
<li>下一个</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/webside/quartz/service/class-use/ScheduleJobService.html" target="_top">框架</a></li>
<li><a href="ScheduleJobService.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">所有类</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="接口的使用 com.webside.quartz.service.ScheduleJobService" class="title">接口的使用<br>com.webside.quartz.service.ScheduleJobService</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表程序包和解释">
<caption><span>使用<a href="../../../../../com/webside/quartz/service/ScheduleJobService.html" title="com.webside.quartz.service中的接口">ScheduleJobService</a>的程序包</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">程序包</th>
<th class="colLast" scope="col">说明</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.webside.quartz.controller">com.webside.quartz.controller</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.webside.quartz.service.impl">com.webside.quartz.service.impl</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.webside.quartz.controller">
<!-- -->
</a>
<h3><a href="../../../../../com/webside/quartz/controller/package-summary.html">com.webside.quartz.controller</a>中<a href="../../../../../com/webside/quartz/service/ScheduleJobService.html" title="com.webside.quartz.service中的接口">ScheduleJobService</a>的使用</h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表字段和解释">
<caption><span>声明为<a href="../../../../../com/webside/quartz/service/ScheduleJobService.html" title="com.webside.quartz.service中的接口">ScheduleJobService</a>的<a href="../../../../../com/webside/quartz/controller/package-summary.html">com.webside.quartz.controller</a>中的字段</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">限定符和类型</th>
<th class="colLast" scope="col">字段和说明</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>private <a href="../../../../../com/webside/quartz/service/ScheduleJobService.html" title="com.webside.quartz.service中的接口">ScheduleJobService</a></code></td>
<td class="colLast"><span class="typeNameLabel">ScheduleJobController.</span><code><span class="memberNameLink"><a href="../../../../../com/webside/quartz/controller/ScheduleJobController.html#scheduleJobService">scheduleJobService</a></span></code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.webside.quartz.service.impl">
<!-- -->
</a>
<h3><a href="../../../../../com/webside/quartz/service/impl/package-summary.html">com.webside.quartz.service.impl</a>中<a href="../../../../../com/webside/quartz/service/ScheduleJobService.html" title="com.webside.quartz.service中的接口">ScheduleJobService</a>的使用</h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表类和解释">
<caption><span>实现<a href="../../../../../com/webside/quartz/service/ScheduleJobService.html" title="com.webside.quartz.service中的接口">ScheduleJobService</a>的<a href="../../../../../com/webside/quartz/service/impl/package-summary.html">com.webside.quartz.service.impl</a>中的类</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">限定符和类型</th>
<th class="colLast" scope="col">类和说明</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/webside/quartz/service/impl/ScheduleJobServiceImpl.html" title="com.webside.quartz.service.impl中的类">ScheduleJobServiceImpl</a></span></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="跳过导航链接">跳过导航链接</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../../overview-summary.html">概览</a></li>
<li><a href="../package-summary.html">程序包</a></li>
<li><a href="../../../../../com/webside/quartz/service/ScheduleJobService.html" title="com.webside.quartz.service中的接口">类</a></li>
<li class="navBarCell1Rev">使用</li>
<li><a href="../package-tree.html">树</a></li>
<li><a href="../../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../../index-all.html">索引</a></li>
<li><a href="../../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>上一个</li>
<li>下一个</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/webside/quartz/service/class-use/ScheduleJobService.html" target="_top">框架</a></li>
<li><a href="ScheduleJobService.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">所有类</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017. All rights reserved.</small></p>
</body>
</html>
|
ofpteam/ofp
|
target/apidocs/com/webside/quartz/service/class-use/ScheduleJobService.html
|
HTML
|
apache-2.0
| 8,266
|
# Copyright (C) 2015-2021 Regents of the University of California
#
# 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.
from toil.common import Config
from toil.job import CheckpointJobDescription, JobDescription
from toil.jobStores.fileJobStore import FileJobStore
from toil.test import ToilTest, travis_test
from toil.worker import nextChainable
class WorkerTests(ToilTest):
"""Test miscellaneous units of the worker."""
def setUp(self):
super(WorkerTests, self).setUp()
path = self._getTestJobStorePath()
self.jobStore = FileJobStore(path)
self.config = Config()
self.config.jobStore = 'file:%s' % path
self.jobStore.initialize(self.config)
self.jobNumber = 0
@travis_test
def testNextChainable(self):
"""Make sure chainable/non-chainable jobs are identified correctly."""
def createTestJobDesc(memory, cores, disk, preemptable, checkpoint):
"""
Create a JobDescription with no command (representing a Job that
has already run) and return the JobDescription.
"""
name = 'job%d' % self.jobNumber
self.jobNumber += 1
descClass = CheckpointJobDescription if checkpoint else JobDescription
jobDesc = descClass(requirements={'memory': memory, 'cores': cores, 'disk': disk, 'preemptable': preemptable}, jobName=name)
# Assign an ID
self.jobStore.assignID(jobDesc)
# Save and return the JobDescription
return self.jobStore.create(jobDesc)
for successorType in ['addChild', 'addFollowOn']:
# Try with the branch point at both child and follow-on stages
# Identical non-checkpoint jobs should be chainable.
jobDesc1 = createTestJobDesc(1, 2, 3, True, False)
jobDesc2 = createTestJobDesc(1, 2, 3, True, False)
getattr(jobDesc1, successorType)(jobDesc2.jobStoreID)
chainable = nextChainable(jobDesc1, self.jobStore, self.config)
self.assertNotEqual(chainable, None)
self.assertEqual(jobDesc2.jobStoreID, chainable.jobStoreID)
# Identical checkpoint jobs should not be chainable.
jobDesc1 = createTestJobDesc(1, 2, 3, True, False)
jobDesc2 = createTestJobDesc(1, 2, 3, True, True)
getattr(jobDesc1, successorType)(jobDesc2.jobStoreID)
self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config))
# If there is no child we should get nothing to chain.
jobDesc1 = createTestJobDesc(1, 2, 3, True, False)
self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config))
# If there are 2 or more children we should get nothing to chain.
jobDesc1 = createTestJobDesc(1, 2, 3, True, False)
jobDesc2 = createTestJobDesc(1, 2, 3, True, False)
jobDesc3 = createTestJobDesc(1, 2, 3, True, False)
getattr(jobDesc1, successorType)(jobDesc2.jobStoreID)
getattr(jobDesc1, successorType)(jobDesc3.jobStoreID)
self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config))
# If there is an increase in resource requirements we should get nothing to chain.
reqs = {'memory': 1, 'cores': 2, 'disk': 3, 'preemptable': True, 'checkpoint': False}
for increased_attribute in ('memory', 'cores', 'disk'):
jobDesc1 = createTestJobDesc(**reqs)
reqs[increased_attribute] += 1
jobDesc2 = createTestJobDesc(**reqs)
getattr(jobDesc1, successorType)(jobDesc2.jobStoreID)
self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config))
# A change in preemptability from True to False should be disallowed.
jobDesc1 = createTestJobDesc(1, 2, 3, True, False)
jobDesc2 = createTestJobDesc(1, 2, 3, False, True)
getattr(jobDesc1, successorType)(jobDesc2.jobStoreID)
self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config))
|
BD2KGenomics/slugflow
|
src/toil/test/src/workerTest.py
|
Python
|
apache-2.0
| 4,647
|
package ru.technoserv.wss;
import java.net.MalformedURLException;
import java.net.URL;
import javax.annotation.Resource;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.handler.*;
import javax.xml.ws.*;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b130926.1035
* Generated source version: 2.2
*
*/
@WebServiceClient(name = "EmployeeWebServiceImplService", targetNamespace = "http://ws.technoserv.ru/", wsdlLocation = "file:/D:/EmployeeWebServiceImplService.wsdl")
public class EmployeeWebServiceImplService
extends Service
{
@Resource
private WebServiceContext context;
private final static URL EMPLOYEEWEBSERVICEIMPLSERVICE_WSDL_LOCATION;
private final static WebServiceException EMPLOYEEWEBSERVICEIMPLSERVICE_EXCEPTION;
private final static QName EMPLOYEEWEBSERVICEIMPLSERVICE_QNAME = new QName("http://ws.technoserv.ru/", "EmployeeWebServiceImplService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("classpath://EmployeeWebServiceImplService.wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
EMPLOYEEWEBSERVICEIMPLSERVICE_WSDL_LOCATION = url;
EMPLOYEEWEBSERVICEIMPLSERVICE_EXCEPTION = e;
}
public EmployeeWebServiceImplService() {
super(__getWsdlLocation(), EMPLOYEEWEBSERVICEIMPLSERVICE_QNAME);
}
public EmployeeWebServiceImplService(WebServiceFeature... features) {
super(__getWsdlLocation(), EMPLOYEEWEBSERVICEIMPLSERVICE_QNAME, features);
}
public EmployeeWebServiceImplService(URL wsdlLocation) {
super(wsdlLocation, EMPLOYEEWEBSERVICEIMPLSERVICE_QNAME);
}
public EmployeeWebServiceImplService(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, EMPLOYEEWEBSERVICEIMPLSERVICE_QNAME, features);
}
public EmployeeWebServiceImplService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public EmployeeWebServiceImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns EmployeeWebService
*/
@WebEndpoint(name = "EmployeeWebServiceImpl")
public EmployeeWebService getEmployeeWebServiceImpl() {
return super.getPort(new QName("http://ws.technoserv.ru/", "EmployeeWebServiceImpl"), EmployeeWebService.class);
}
/**
*
* @param features
* A list of {@link WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns EmployeeWebService
*/
@WebEndpoint(name = "EmployeeWebServiceImpl")
public EmployeeWebService getEmployeeWebServiceImpl(WebServiceFeature... features) {
return super.getPort(new QName("http://ws.technoserv.ru/", "EmployeeWebServiceImpl"), EmployeeWebService.class, features);
}
private static URL __getWsdlLocation() {
if (EMPLOYEEWEBSERVICEIMPLSERVICE_EXCEPTION!= null) {
throw EMPLOYEEWEBSERVICEIMPLSERVICE_EXCEPTION;
}
return EMPLOYEEWEBSERVICEIMPLSERVICE_WSDL_LOCATION;
}
}
|
AMaiyndy/employees
|
src/main/java/ru/technoserv/wss/EmployeeWebServiceImplService.java
|
Java
|
apache-2.0
| 3,492
|
Website: https://git-scm.com/
See also:
* https://tortoisegit.org/
|
rboman/progs
|
classes/wiki/git.md
|
Markdown
|
apache-2.0
| 72
|
/*
* 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.commons.math4.util;
import java.io.Serializable;
import org.apache.commons.math4.exception.MathIllegalArgumentException;
/**
* Classic median of 3 strategy given begin and end indices.
* @since 3.4
*/
public class MedianOf3PivotingStrategy implements PivotingStrategyInterface, Serializable {
/** Serializable UID. */
private static final long serialVersionUID = 20140713L;
/**{@inheritDoc}
* This in specific makes use of median of 3 pivoting.
* @return The index corresponding to a pivot chosen between the
* first, middle and the last indices of the array slice
* @throws MathIllegalArgumentException when indices exceeds range
*/
@Override
public int pivotIndex(final double[] work, final int begin, final int end)
throws MathIllegalArgumentException {
MathArrays.verifyValues(work, begin, end-begin);
final int inclusiveEnd = end - 1;
final int middle = begin + (inclusiveEnd - begin) / 2;
final double wBegin = work[begin];
final double wMiddle = work[middle];
final double wEnd = work[inclusiveEnd];
if (wBegin < wMiddle) {
if (wMiddle < wEnd) {
return middle;
} else {
return wBegin < wEnd ? inclusiveEnd : begin;
}
} else {
if (wBegin < wEnd) {
return begin;
} else {
return wMiddle < wEnd ? inclusiveEnd : middle;
}
}
}
}
|
virtualdataset/metagen-java
|
virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MedianOf3PivotingStrategy.java
|
Java
|
apache-2.0
| 2,330
|
/*
* Copyright (c) 2010-2013 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/
SELECT
d.date,
d.id.curlocation.area as CurrentArea,
d.id.curlocation.room as CurrentRoom,
d.id.curlocation.cage as CurrentCage,
t.lsid,
t.id,
t.code,
t.qualifier,
t.route,
t.code.meaning as meaning,
t.volume, t.vol_units,
t.amount, t.amount_units,
t.concentration, t.conc_units,
t.dosage, t.dosage_units,
t.performedby,
d.id as drug_id,
d.code as drug_code,
d.qualifier as drug_qualifier,
d.route as drug_route,
d.code.meaning as drug_meaning,
d.volume as drug_volume, d.vol_units as drug_vol_units,
d.amount as drug_amount, d.amount_units as drug_amount_units,
d.concentration as drug_concentration, t.conc_units as drug_conc_units,
d.dosage as drug_dosage, d.dosage_units as drug_dosage_units,
d.performedby as drug_performedby,
FROM study."Drug Administration" d
LEFT JOIN study.treatmentSchedule t
ON (d.parentid is not null AND t.primaryKey = d.parentid)
WHERE
t.id != d.id OR
t.code != d.code OR
(t.volume is not null and t.volume != 0 and t.volume != d.volume) OR
(t.vol_units is not null and t.vol_units != d.vol_units) OR
(t.amount is not null and t.amount != 0 and t.amount != d.amount) OR
(t.amount_units is not null and t.amount_units != d.amount_units) OR
(t.dosage is not null and t.dosage != 0 and t.dosage != d.dosage) OR
(t.dosage_units is not null and t.dosage_units != d.dosage_units) OR
(t.concentration is not null and t.concentration != 0 and t.concentration != d.concentration) OR
(t.conc_units is not null and t.conc_units != d.conc_units) OR
t.route != d.route
|
WNPRC-EHR-Services/wnprc-modules
|
WNPRC_EHR/resources/queries/study/TreatmentsThatDiffer.sql
|
SQL
|
apache-2.0
| 1,695
|
/*
+---------------------------------------------------------------------------+
| PHP Driver for MongoDB |
+---------------------------------------------------------------------------+
| Copyright 2013-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. |
+---------------------------------------------------------------------------+
| Copyright (c) 2014-2015 MongoDB, Inc. |
+---------------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
/* External libs */
#include <bson.h>
#include <mongoc.h>
/* PHP Core stuff */
#include <php.h>
#include <php_ini.h>
#include <ext/standard/info.h>
#include <Zend/zend_interfaces.h>
#include <ext/spl/spl_iterators.h>
/* Our Compatability header */
#include "phongo_compat.h"
/* Our stuffz */
#include "php_phongo.h"
#include "php_bson.h"
PHONGO_API zend_class_entry *php_phongo_javascript_ce;
zend_object_handlers php_phongo_handler_javascript;
/* {{{ proto BSON\Javascript Javascript::__construct(string $javascript[, array|object $document])
* The string is JavaScript code. The document is a mapping from identifiers to values, representing the scope in which the string should be evaluated
* NOTE: eJSON does not support this type :( */
PHP_METHOD(Javascript, __construct)
{
php_phongo_javascript_t *intern;
zend_error_handling error_handling;
char *javascript;
int javascript_len;
zval *document = NULL;
bson_t scope = BSON_INITIALIZER;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = (php_phongo_javascript_t *)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|A!", &javascript, &javascript_len, &document) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
if (document) {
zval_to_bson(document, PHONGO_BSON_NONE, &scope, NULL TSRMLS_CC);
}
php_phongo_new_javascript_from_javascript_and_scope(0, getThis(), javascript, javascript_len, &scope TSRMLS_CC);
bson_destroy(&scope);
}
/* }}} */
/* {{{ BSON\Javascript */
ZEND_BEGIN_ARG_INFO_EX(ai_Javascript___construct, 0, 0, 1)
ZEND_ARG_INFO(0, javascript)
ZEND_ARG_INFO(0, scope)
ZEND_END_ARG_INFO();
static zend_function_entry php_phongo_javascript_me[] = {
PHP_ME(Javascript, __construct, ai_Javascript___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
PHP_ME(Manager, __wakeUp, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* }}} */
/* {{{ php_phongo_javascript_t object handlers */
static void php_phongo_javascript_free_object(void *object TSRMLS_DC) /* {{{ */
{
php_phongo_javascript_t *intern = (php_phongo_javascript_t*)object;
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->javascript) {
efree(intern->javascript);
}
if (intern->document) {
bson_destroy(intern->document);
intern->document = NULL;
}
efree(intern);
} /* }}} */
zend_object_value php_phongo_javascript_create_object(zend_class_entry *class_type TSRMLS_DC) /* {{{ */
{
zend_object_value retval;
php_phongo_javascript_t *intern;
intern = (php_phongo_javascript_t *)emalloc(sizeof(php_phongo_javascript_t));
memset(intern, 0, sizeof(php_phongo_javascript_t));
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_javascript_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_javascript;
intern->document = NULL;
return retval;
} /* }}} */
HashTable *php_phongo_javascript_get_debug_info(zval *object, int *is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_javascript_t *intern;
zval retval = zval_used_for_init;
*is_temp = 1;
intern = (php_phongo_javascript_t *)zend_object_store_get_object(object TSRMLS_CC);
array_init(&retval);
add_assoc_stringl_ex(&retval, ZEND_STRS("javascript"), intern->javascript, intern->javascript_len, 1);
if (intern->document) {
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
MAKE_STD_ZVAL(state.zchild);
if (bson_to_zval(bson_get_data(intern->document), intern->document->len, &state)) {
Z_ADDREF_P(state.zchild);
add_assoc_zval_ex(&retval, ZEND_STRS("scope"), state.zchild);
} else {
add_assoc_null_ex(&retval, ZEND_STRS("scope"));
}
zval_ptr_dtor(&state.zchild);
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(Javascript)
{
zend_class_entry ce;
(void)type;(void)module_number;
INIT_NS_CLASS_ENTRY(ce, BSON_NAMESPACE, "Javascript", php_phongo_javascript_me);
php_phongo_javascript_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_javascript_ce->create_object = php_phongo_javascript_create_object;
PHONGO_CE_INIT(php_phongo_javascript_ce);
zend_class_implements(php_phongo_javascript_ce TSRMLS_CC, 1, php_phongo_type_ce);
memcpy(&php_phongo_handler_javascript, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_javascript.get_debug_info = php_phongo_javascript_get_debug_info;
return SUCCESS;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
bjori/mongo-php-driver-prototype
|
src/BSON/Javascript.c
|
C
|
apache-2.0
| 6,546
|
#!/usr/bin/env python3
import unittest
from unittest.mock import MagicMock
import logging
import nat_monitor
import utils
class NatInstanceTest(unittest.TestCase):
def setUp(self):
self.vpc_conn = MagicMock()
self.ec2_conn = MagicMock()
self.instance_id = 'i-abc123'
self.subnet = MagicMock()
self.subnet.id = 'subnetid'
self.route_table = MagicMock()
self.route_table.id = 'rt-123'
self.vpc_conn.get_all_subnets = MagicMock(return_value=[self.subnet])
self.vpc_conn.get_all_route_tables = MagicMock(
return_value=[self.route_table])
self.vpc_conn.create_route = MagicMock()
self.vpc_id = 'vpc123'
self.az = 'us-east-1a'
self.instance = MagicMock()
self.role = 'nat'
self.instance.tags = {
'Role': self.role, 'Name': NatInstanceTest.__name__}
self.instance_tags = MagicMock()
self.name = 'name'
self.instance_tags.get_name = MagicMock(return_value=self.name)
self.instances = [self.instance]
self.ec2_conn.get_only_instances = MagicMock(
return_value=self.instances)
self.ec2_conn.modify_instance_attribute = MagicMock()
self.instance_metadata = {
'instance-id': self.instance_id,
'network': {
'interfaces': {
'macs': {
'0e:bf:0c:a1:f6:59': {
'vpc-id': self.vpc_id
}
}
}
},
'placement': {
'availability-zone': self.az
}
}
self.nat_instance = nat_monitor.NatInstance(
self.vpc_conn, self.ec2_conn, self.instance_tags, self.instance_metadata)
def test_init(self):
self.assertEqual(self.nat_instance.vpc_conn, self.vpc_conn)
self.assertEqual(self.nat_instance.ec2_conn, self.ec2_conn)
self.assertEqual(self.nat_instance.vpc_id, self.vpc_id)
self.assertEqual(self.nat_instance.az, self.az)
self.assertEqual(self.nat_instance.instance_id, self.instance_id)
self.assertEqual(
self.nat_instance.my_route_table_id, self.route_table.id)
self.assertEqual(self.nat_instance.name_tag, self.name)
def test_disable_source_dest_check(self):
self.nat_instance.disable_source_dest_check()
self.ec2_conn.modify_instance_attribute.assert_called_with(
self.instance_id, 'sourceDestCheck', False)
def test_set_route(self):
self.nat_instance.set_route()
self.vpc_conn.create_route.assert_called_with(
self.nat_instance.my_route_table_id, '0.0.0.0/0',
instance_id=self.nat_instance.instance_id)
if __name__ == '__main__':
unittest.main()
|
ridecharge/aws-startup-utils-docker
|
scripts/nat_monitor_test.py
|
Python
|
apache-2.0
| 2,843
|
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Training script for RetinaNet segmentation model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import app
from absl import flags
import absl.logging as _logging # pylint: disable=unused-import
import tensorflow.compat.v1 as tf
import dataloader
import retinanet_segmentation_model
from tensorflow.contrib import cluster_resolver as contrib_cluster_resolver
from tensorflow.contrib import tpu as contrib_tpu
from tensorflow.contrib import training as contrib_training
# Cloud TPU Cluster Resolvers
flags.DEFINE_string(
'tpu', default=None,
help='The Cloud TPU to use for training. This should be either the name '
'used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 '
'url.')
flags.DEFINE_string(
'gcp_project', default=None,
help='Project name for the Cloud TPU-enabled project. If not specified, we '
'will attempt to automatically detect the GCE project from metadata.')
flags.DEFINE_string(
'tpu_zone', default=None,
help='GCE zone where the Cloud TPU is located in. If not specified, we '
'will attempt to automatically detect the GCE project from metadata.')
# Model specific paramenters
flags.DEFINE_bool('use_tpu', True, 'Use TPUs rather than CPUs')
flags.DEFINE_string('model_dir', None, 'Location of model_dir')
flags.DEFINE_string('resnet_checkpoint', None,
'Location of the ResNet50 checkpoint to use for model '
'initialization.')
flags.DEFINE_string('hparams', '',
'Comma separated k=v pairs of hyperparameters.')
flags.DEFINE_integer(
'num_shards', default=8, help='Number of shards (TPU cores)')
flags.DEFINE_integer('train_batch_size', 64, 'training batch size')
flags.DEFINE_integer('eval_batch_size', 8, 'evaluation batch size')
flags.DEFINE_integer('eval_samples', 1449, 'The number of samples for '
'evaluation.')
flags.DEFINE_integer(
'iterations_per_loop', 100, 'Number of iterations per TPU training loop')
flags.DEFINE_string(
'training_file_pattern', None,
'Glob for training data files (e.g., Pascal VOC train set)')
flags.DEFINE_string(
'validation_file_pattern', None,
'Glob for evaluation tfrecords (e.g., Pascal VOC validation set)')
flags.DEFINE_integer('num_examples_per_epoch', 10582,
'Number of examples in one epoch')
flags.DEFINE_integer('num_epochs', 45, 'Number of epochs for training')
flags.DEFINE_string('mode', 'train_and_eval',
'Mode to run: train or eval (default: train)')
flags.DEFINE_bool('eval_after_training', False, 'Run one eval after the '
'training finishes.')
# For Eval mode
flags.DEFINE_integer('min_eval_interval', 180,
'Minimum seconds between evaluations.')
flags.DEFINE_integer(
'eval_timeout', None,
'Maximum seconds between checkpoints before evaluation terminates.')
FLAGS = flags.FLAGS
def main(argv):
del argv # Unused.
if FLAGS.use_tpu:
tpu_cluster_resolver = contrib_cluster_resolver.TPUClusterResolver(
FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
tpu_grpc_url = tpu_cluster_resolver.get_master()
tf.Session.reset(tpu_grpc_url)
if FLAGS.mode in ('train',
'train_and_eval') and FLAGS.training_file_pattern is None:
raise RuntimeError('You must specify --training_file_pattern for training.')
if FLAGS.mode in ('eval', 'train_and_eval'):
if FLAGS.validation_file_pattern is None:
raise RuntimeError('You must specify'
'--validation_file_pattern for evaluation.')
# Parse hparams
hparams = retinanet_segmentation_model.default_hparams()
hparams.parse(FLAGS.hparams)
params = dict(
hparams.values(),
num_shards=FLAGS.num_shards,
num_examples_per_epoch=FLAGS.num_examples_per_epoch,
use_tpu=FLAGS.use_tpu,
resnet_checkpoint=FLAGS.resnet_checkpoint,
mode=FLAGS.mode,
)
run_config = contrib_tpu.RunConfig(
cluster=tpu_cluster_resolver,
evaluation_master='',
model_dir=FLAGS.model_dir,
keep_checkpoint_max=3,
log_step_count_steps=FLAGS.iterations_per_loop,
session_config=tf.ConfigProto(
allow_soft_placement=True, log_device_placement=False),
tpu_config=contrib_tpu.TPUConfig(
FLAGS.iterations_per_loop,
FLAGS.num_shards,
per_host_input_for_training=(
contrib_tpu.InputPipelineConfig.PER_HOST_V2)))
model_fn = retinanet_segmentation_model.segmentation_model_fn
# TPU Estimator
eval_params = dict(
params,
use_tpu=FLAGS.use_tpu,
input_rand_hflip=False,
resnet_checkpoint=None,
is_training_bn=False,
)
if FLAGS.mode == 'train':
train_estimator = contrib_tpu.TPUEstimator(
model_fn=model_fn,
use_tpu=FLAGS.use_tpu,
train_batch_size=FLAGS.train_batch_size,
config=run_config,
params=params)
train_estimator.train(
input_fn=dataloader.SegmentationInputReader(
FLAGS.training_file_pattern, is_training=True),
max_steps=int((FLAGS.num_epochs * FLAGS.num_examples_per_epoch) /
FLAGS.train_batch_size),
)
if FLAGS.eval_after_training:
# Run evaluation on CPU after training finishes.
eval_estimator = contrib_tpu.TPUEstimator(
model_fn=retinanet_segmentation_model.segmentation_model_fn,
use_tpu=FLAGS.use_tpu,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
config=run_config,
params=eval_params)
eval_results = eval_estimator.evaluate(
input_fn=dataloader.SegmentationInputReader(
FLAGS.validation_file_pattern, is_training=False),
steps=FLAGS.eval_samples//FLAGS.eval_batch_size)
tf.logging.info('Eval results: %s' % eval_results)
elif FLAGS.mode == 'eval':
eval_estimator = contrib_tpu.TPUEstimator(
model_fn=retinanet_segmentation_model.segmentation_model_fn,
use_tpu=FLAGS.use_tpu,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
config=run_config,
params=eval_params)
def terminate_eval():
tf.logging.info('Terminating eval after %d seconds of no checkpoints' %
FLAGS.eval_timeout)
return True
# Run evaluation when there's a new checkpoint
for ckpt in contrib_training.checkpoints_iterator(
FLAGS.model_dir,
min_interval_secs=FLAGS.min_eval_interval,
timeout=FLAGS.eval_timeout,
timeout_fn=terminate_eval):
tf.logging.info('Starting to evaluate.')
try:
# Note that if the eval_samples size is not fully divided by the
# eval_batch_size. The remainder will be dropped and result in
# differet evaluation performance than validating on the full set.
eval_results = eval_estimator.evaluate(
input_fn=dataloader.SegmentationInputReader(
FLAGS.validation_file_pattern, is_training=False),
steps=FLAGS.eval_samples//FLAGS.eval_batch_size)
tf.logging.info('Eval results: %s' % eval_results)
# Terminate eval job when final checkpoint is reached
current_step = int(os.path.basename(ckpt).split('-')[1])
total_step = int((FLAGS.num_epochs * FLAGS.num_examples_per_epoch) /
FLAGS.train_batch_size)
if current_step >= total_step:
tf.logging.info('Evaluation finished after training step %d' %
current_step)
break
except tf.errors.NotFoundError:
# Since the coordinator is on a different job than the TPU worker,
# sometimes the TPU worker does not finish initializing until long after
# the CPU job tells it to start evaluating. In this case, the checkpoint
# file could have been deleted already.
tf.logging.info('Checkpoint %s no longer exists, skipping checkpoint' %
ckpt)
elif FLAGS.mode == 'train_and_eval':
train_estimator = contrib_tpu.TPUEstimator(
model_fn=retinanet_segmentation_model.segmentation_model_fn,
use_tpu=FLAGS.use_tpu,
train_batch_size=FLAGS.train_batch_size,
config=run_config,
params=params)
eval_estimator = contrib_tpu.TPUEstimator(
model_fn=retinanet_segmentation_model.segmentation_model_fn,
use_tpu=FLAGS.use_tpu,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
config=run_config,
params=eval_params)
for cycle in range(0, FLAGS.num_epochs):
tf.logging.info('Starting training cycle, epoch: %d.' % cycle)
train_estimator.train(
input_fn=dataloader.SegmentationInputReader(
FLAGS.training_file_pattern, is_training=True),
steps=int(FLAGS.num_examples_per_epoch / FLAGS.train_batch_size))
tf.logging.info('Starting evaluation cycle, epoch: {:d}.'.format(
cycle + 1))
# Run evaluation after training finishes.
eval_results = eval_estimator.evaluate(
input_fn=dataloader.SegmentationInputReader(
FLAGS.validation_file_pattern, is_training=False),
steps=FLAGS.eval_samples//FLAGS.eval_batch_size)
tf.logging.info('Evaluation results: %s' % eval_results)
else:
tf.logging.info('Mode not found.')
if __name__ == '__main__':
tf.logging.set_verbosity(tf.logging.INFO)
app.run(main)
|
tensorflow/tpu
|
models/official/retinanet/retinanet_segmentation_main.py
|
Python
|
apache-2.0
| 10,349
|
package com.infoDiscover.adminCenter.ui.component.infoDiscoverSpaceManagement.businessDataDefinitionManagement;
import com.infoDiscover.adminCenter.ui.component.common.SecondarySectionActionBarTitle;
import com.infoDiscover.adminCenter.ui.component.infoDiscoverSpaceManagement.InfoDiscoverSpaceDetail;
import com.infoDiscover.adminCenter.ui.component.infoDiscoverSpaceManagement.event.DiscoverSpaceLaunchDataAnalyzeApplicationEvent;
import com.infoDiscover.adminCenter.ui.component.infoDiscoverSpaceManagement.event.DiscoverSpaceOpenProcessingDataListEvent;
import com.infoDiscover.adminCenter.ui.util.UserClientInfo;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.FontAwesome;
import com.vaadin.ui.Button;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.ValoTheme;
/**
* Created by wangychu on 25/05/2017.
*/
public class InfoDiscoverSpaceBusinessDataDefinitionsInfo extends VerticalLayout {
private UserClientInfo currentUserClientInfo;
private String discoverSpaceName;
private InfoDiscoverSpaceDetail parentInfoDiscoverSpaceDetail;
private SecondarySectionActionBarTitle secondarySectionActionBarTitle;
private CustomPropertyAliasNameManagementPanel customPropertyAliasNameManagementPanel;
private CommonDataRelationMappingManagementPanel commonDataRelationMappingManagementPanel;
private DataAndDateDimensionMappingManagementPanel dataAndDateDimensionMappingManagementPanel;
private DataPropertiesDuplicateMappingManagementPanel dataPropertiesDuplicateMappingManagementPanel;
public InfoDiscoverSpaceBusinessDataDefinitionsInfo(UserClientInfo currentUserClientInfo){
this.currentUserClientInfo=currentUserClientInfo;
Button openProcessingDataListButton = new Button("待处理数据");
openProcessingDataListButton.setIcon(VaadinIcons.MAILBOX);
openProcessingDataListButton.setDescription("显示待处理数据列表");
openProcessingDataListButton.addStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
openProcessingDataListButton.addStyleName(ValoTheme.BUTTON_SMALL);
openProcessingDataListButton.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
DiscoverSpaceOpenProcessingDataListEvent discoverSpaceOpenProcessingDataListEvent =new DiscoverSpaceOpenProcessingDataListEvent(discoverSpaceName);
currentUserClientInfo.getEventBlackBoard().fire(discoverSpaceOpenProcessingDataListEvent);
}
});
Button launchDataAnalyzeApplicationButton = new Button("信息分析发现应用");
launchDataAnalyzeApplicationButton.setIcon(VaadinIcons.CHART_TIMELINE);
launchDataAnalyzeApplicationButton.setDescription("启动信息分析发现应用系统");
launchDataAnalyzeApplicationButton.addStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
launchDataAnalyzeApplicationButton.addStyleName(ValoTheme.BUTTON_SMALL);
launchDataAnalyzeApplicationButton.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
DiscoverSpaceLaunchDataAnalyzeApplicationEvent discoverSpaceLaunchDataAnalyzeApplicationEvent =new DiscoverSpaceLaunchDataAnalyzeApplicationEvent(discoverSpaceName);
currentUserClientInfo.getEventBlackBoard().fire(discoverSpaceLaunchDataAnalyzeApplicationEvent);
}
});
secondarySectionActionBarTitle=new SecondarySectionActionBarTitle("-------",new Button[]{openProcessingDataListButton,launchDataAnalyzeApplicationButton});
addComponent(secondarySectionActionBarTitle);
TabSheet tabs=new TabSheet();
addComponent(tabs);
this.customPropertyAliasNameManagementPanel =new CustomPropertyAliasNameManagementPanel(this.currentUserClientInfo);
TabSheet.Tab customPropertyAliasManagementPanelTab =tabs.addTab(this.customPropertyAliasNameManagementPanel, "自定义属性别名管理");
customPropertyAliasManagementPanelTab.setIcon(VaadinIcons.COINS);
this.commonDataRelationMappingManagementPanel=new CommonDataRelationMappingManagementPanel(this.currentUserClientInfo);
TabSheet.Tab commonDataRelationMappingDefinitionInfoLayoutTab =tabs.addTab(this.commonDataRelationMappingManagementPanel, "常规数据属性关联映射管理");
commonDataRelationMappingDefinitionInfoLayoutTab.setIcon(FontAwesome.COGS);
this.dataAndDateDimensionMappingManagementPanel=new DataAndDateDimensionMappingManagementPanel(this.currentUserClientInfo);
TabSheet.Tab factAndDateDimensionMappingDefinitionInfoLayoutTab =tabs.addTab(this.dataAndDateDimensionMappingManagementPanel, "数据与时间维度关联定义管理");
factAndDateDimensionMappingDefinitionInfoLayoutTab.setIcon(FontAwesome.CLOCK_O);
this.dataPropertiesDuplicateMappingManagementPanel=new DataPropertiesDuplicateMappingManagementPanel(this.currentUserClientInfo);
TabSheet.Tab dataPropertiesDuplicateMappingDefinitionInfoLayoutTab =tabs.addTab(this.dataPropertiesDuplicateMappingManagementPanel, "数据属性复制规则定义管理");
dataPropertiesDuplicateMappingDefinitionInfoLayoutTab.setIcon(FontAwesome.COPY);
}
public void setDiscoverSpaceName(String discoverSpaceName) {
this.discoverSpaceName = discoverSpaceName;
}
public void setParentInfoDiscoverSpaceDetail(InfoDiscoverSpaceDetail parentInfoDiscoverSpaceDetail) {
this.parentInfoDiscoverSpaceDetail = parentInfoDiscoverSpaceDetail;
}
public void renderBusinessDataDefinitionsInfo(){
this.secondarySectionActionBarTitle.updateSectionTitle(this.discoverSpaceName);
this.customPropertyAliasNameManagementPanel.setDiscoverSpaceName(this.discoverSpaceName);
this.customPropertyAliasNameManagementPanel.renderCustomPropertyAliasInfo();
this.commonDataRelationMappingManagementPanel.setDiscoverSpaceName(this.discoverSpaceName);
this.commonDataRelationMappingManagementPanel.renderCommonDataRelationMappingInfo();
this.dataAndDateDimensionMappingManagementPanel.setDiscoverSpaceName(this.discoverSpaceName);
this.dataAndDateDimensionMappingManagementPanel.renderDataAndDateDimensionMappingInfo();
this.dataPropertiesDuplicateMappingManagementPanel.setDiscoverSpaceName(this.discoverSpaceName);
this.dataPropertiesDuplicateMappingManagementPanel.renderDataPropertiesDuplicateMappingInfo();
}
}
|
wangyingchu/AdminCenter_InfoDiscover
|
src/com/infoDiscover/adminCenter/ui/component/infoDiscoverSpaceManagement/businessDataDefinitionManagement/InfoDiscoverSpaceBusinessDataDefinitionsInfo.java
|
Java
|
apache-2.0
| 6,624
|
/**
* CIS 120 Game HW
* (c) University of Pennsylvania
*
* @version 2.0, Mar 2013
*/
import java.awt.*;
/** An object in the game.
*
* Game objects exist in the game court. They have a position,
* velocity, size and bounds. Their velocity controls how they
* move; their position should always be within their bounds.
*/
public class GameObj {
/**
* Current position of the object (in terms of graphics coordinates)
* <p>
* Coordinates are given by the upper-left hand corner of the object.
* This position should always be within bounds.
* 0 <= pos_x <= max_x
* 0 <= pos_y <= max_y
*/
public int pos_x;
public int pos_y;
/**
* Size of object, in pixels
*/
public int width;
public int height;
/**
* Velocity: number of pixels to move every time move() is called
*/
public int v_x;
public int v_y;
/**
* Upper bounds of the area in which the object can be positioned.
* Maximum permissible x, y positions for the upper-left
* hand corner of the object
*/
public int max_x;
public int max_y;
/**
* Constructor
*/
public GameObj(int v_x, int v_y, int pos_x, int pos_y,
int width, int height, int court_width, int court_height) {
this.v_x = v_x;
this.v_y = v_y;
this.pos_x = pos_x;
this.pos_y = pos_y;
this.width = width;
this.height = height;
// take the width and height into account when setting the
// bounds for the upper left corner of the object.
this.max_x = court_width - width;
this.max_y = court_height - height;
}
/**
* Moves the object by its velocity. Ensures that the object does
* not go outside its bounds by clipping.
*/
public void move() {
pos_x += v_x;
pos_y += v_y;
clip();
}
public void setPos_x(int pos_x) {
this.pos_x = pos_x;
}
public void setPos_y(int pos_y) {
this.pos_y = pos_y;
}
/**
* Prevents the object from going outside of the bounds of the area
* designated for the object. (i.e. Object cannot go outside of the
* active area the user defines for it).
*/
public void clip() {
if (pos_x < 0) pos_x = 0;
else if (pos_x > max_x) pos_x = max_x;
if (pos_y < 0) pos_y = 0;
else if (pos_y > max_y) pos_y = max_y;
}
/**
* Determine whether this game object is currently intersecting
* another object.
* <p>
* Intersection is determined by comparing bounding boxes. If the
* bounding boxes overlap, then an intersection is considered to occur.
*
* @param obj : other object
* @return whether this object intersects the other object.
*/
public boolean intersects(GameObj obj) {
return (pos_x + width >= obj.pos_x
&& pos_y + height >= obj.pos_y
&& obj.pos_x + obj.width >= pos_x
&& obj.pos_y + obj.height >= pos_y);
}
/**
* Determine whether this game object will intersect another in the
* next time step, assuming that both objects continue with their
* current velocity.
* <p>
* Intersection is determined by comparing bounding boxes. If the
* bounding boxes (for the next time step) overlap, then an
* intersection is considered to occur.
*
* @param obj : other object
* @return whether an intersection will occur.
*/
public boolean willIntersect(GameObj obj) {
int next_x = pos_x + v_x;
int next_y = pos_y + v_y;
int next_obj_x = obj.pos_x + obj.v_x;
int next_obj_y = obj.pos_y + obj.v_y;
return (next_x + width >= next_obj_x
&& next_y + height >= next_obj_y
&& next_obj_x + obj.width >= next_x
&& next_obj_y + obj.height >= next_y);
}
/**
* Update the velocity of the object in response to hitting
* an obstacle in the given direction. If the direction is
* null, this method has no effect on the object.
*/
public void bounce(Direction d) {
if (d == null) return;
switch (d) {
case UP:
v_y = Math.abs(v_y);
break;
case DOWN:
v_y = -Math.abs(v_y);
break;
case LEFT:
v_x = Math.abs(v_x);
break;
case RIGHT:
v_x = -Math.abs(v_x);
break;
}
}
/**
* Determine whether the game object will hit a
* wall in the next time step. If so, return the direction
* of the wall in relation to this game object.
*
* @return direction of impending wall, null if all clear.
*/
public Direction hitWall() {
if (pos_x <= 0)
return Direction.LEFT;
else if (pos_x >= max_x) {
return Direction.RIGHT;
}
if (pos_y <= 0)
return Direction.UP;
else if (pos_y >= max_y)
return Direction.DOWN;
else return null;
}
/** Determine whether the game object will hit another
* object in the next time step. If so, return the direction
* of the other object in relation to this game object.
*
* @return direction of impending object, null if all clear.
*/
public Direction hitObj(GameObj other) {
if (this.willIntersect(other)) {
double dx = other.pos_x + other.width / 2 - (pos_x + width / 2);
double dy = other.pos_y + other.height / 2 - (pos_y + height / 2);
double theta = Math.acos(dx / (Math.sqrt(dx * dx + dy * dy)));
double diagTheta = Math.atan2(height / 2, width / 2);
if (theta <= diagTheta) {
return Direction.RIGHT;
} else if (theta > diagTheta && theta <= Math.PI - diagTheta) {
if (dy > 0) {
// Coordinate system for GUIs is switched
return Direction.DOWN;
} else {
return Direction.UP;
}
} else {
return Direction.LEFT;
}
} else {
return null;
}
}
/**
* Default draw method that provides how the object should be drawn
* in the GUI. This method does not draw anything. Subclass should
* override this method based on how their object should appear.
*
* @param g
* The <code>Graphics</code> context used for drawing the object.
* Remember graphics contexts that we used in OCaml, it gives the
* context in which the object should be drawn (a canvas, a frame,
* etc.)
*/
public void draw(Graphics g) {
}
}
|
coxjc/penn-pong
|
GameObj.java
|
Java
|
apache-2.0
| 6,865
|
package com.chbi.rest;
import com.chbi.json.entities.*;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Map;
import java.util.Set;
/*
* TODO: if there is an error like 404 because jenkins is unavailable,
* exceptions should be catched...
*/
@Service
public class DataProvider {
private static final String UNKNOWN_USER = "Luke Buildwalker";
@Autowired
private RequestManager requestManager;
@Autowired
private UrlRewriter urlRewriter;
public List<JenkinsJob> getJenkinsJobs() {
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> request = requestManager.getJsonHttpEntity();
String url = urlRewriter.getPreparedBaseUrl();
ResponseEntity<JenkinsView> response = restTemplate.exchange(url, HttpMethod.GET, request, JenkinsView.class);
JenkinsView jenkinsView = response.getBody();
return jenkinsView.getJobs();
}
public List<JenkinsBuildPipeline> getBuildsFor(JenkinsJob jenkinsJob) {
return Lists.newArrayList();
}
public JenkinsBuildPipeline getJenkinsBuildPipeline(JenkinsJob jenkinsJob) {
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> request = requestManager.getJsonHttpEntity();
String url = urlRewriter.prepareUrl(jenkinsJob.getUrl()) + "?tree=displayName,lastBuild[number,url]";
ResponseEntity<JenkinsBuildPipeline> response = restTemplate.exchange(url, HttpMethod.GET, request, JenkinsBuildPipeline.class);
JenkinsBuildPipeline pipeline = response.getBody();
//lastbuild is null, if buildPipeline was never executed
if (pipeline.getLastBuild() == null) {
pipeline.setLastBuild(new JenkinsBuild());
pipeline.getLastBuild().setNumber(-1);
pipeline.getLastBuild().setUrl(jenkinsJob.getUrl());
pipeline.getLastBuild().set_class("never built");
}
return pipeline;
}
public JenkinsBuildInstance getBuildInstance(String lastBuildUrl) {
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> request = requestManager.getJsonHttpEntity();
String url = urlRewriter.prepareUrl(lastBuildUrl) + "?tree=fullDisplayName,culprits[fullName,absoluteUrl],changeSets[items[*]]";
ResponseEntity<JenkinsBuildInstance> response = restTemplate.exchange(url, HttpMethod.GET, request, JenkinsBuildInstance.class);
return response.getBody();
}
public String getChangingUserFor(JenkinsBuildInstance buildInstance) {
String users;
if (buildInstance.getCulprits() != null && buildInstance.getCulprits().size() > 0) {
users = Joiner.on(", ").join(buildInstance.getCulprits());
} else if (buildInstance.getChangeSets() != null) {
users = Joiner.on(", ").join(getAuthorsFromChangeSet(buildInstance.getChangeSets()));
} else {
users = UNKNOWN_USER;
}
return users;
}
private List<JenkinsAuthor> getAuthorsFromChangeSet(List<JenkinsChangeSets> changeSets) {
Set<JenkinsAuthor> authors = Sets.newHashSet();
changeSets.forEach(jenkinsChangeSets -> jenkinsChangeSets.getItems()
.stream().filter(stringObjectMap -> stringObjectMap.containsKey("author"))
.forEach(filteredObject -> authors.add(new JenkinsAuthor((Map) filteredObject.get("author")))));
return Lists.newArrayList(authors.iterator());
}
public static String getUnknownUser() {
return UNKNOWN_USER;
}
}
|
chris060986/jenkins-dashboard
|
src/main/java/com/chbi/rest/DataProvider.java
|
Java
|
apache-2.0
| 4,064
|
/* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. 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.esri.gpt.control.rest;
import com.esri.gpt.catalog.arcims.ImsMetadataAdminDao;
import com.esri.gpt.catalog.harvest.protocols.HarvestProtocol.ProtocolType;
import com.esri.gpt.catalog.harvest.repository.HrAssertUrlException;
import com.esri.gpt.catalog.harvest.repository.HrCompleteUpdateRequest;
import com.esri.gpt.catalog.harvest.repository.HrRecord;
import com.esri.gpt.catalog.harvest.repository.HrRecord.HarvestFrequency;
import com.esri.gpt.catalog.management.MmdActionCriteria;
import com.esri.gpt.catalog.management.MmdActionRequest;
import com.esri.gpt.catalog.management.MmdCriteria;
import com.esri.gpt.catalog.management.MmdEnums;
import com.esri.gpt.catalog.management.MmdResult;
import com.esri.gpt.catalog.publication.PublicationRecord;
import com.esri.gpt.catalog.publication.PublicationRequest;
import com.esri.gpt.catalog.schema.MetadataDocument;
import com.esri.gpt.catalog.schema.SchemaException;
import com.esri.gpt.catalog.schema.ValidationException;
import com.esri.gpt.control.webharvest.client.arcgis.ArcGISProtocol;
import com.esri.gpt.control.webharvest.protocol.ProtocolFactory;
import com.esri.gpt.control.webharvest.protocol.ProtocolInvoker;
import com.esri.gpt.framework.robots.BotsMode;
import com.esri.gpt.framework.collection.StringAttribute;
import com.esri.gpt.framework.collection.StringAttributeMap;
import com.esri.gpt.framework.context.ApplicationConfiguration;
import com.esri.gpt.framework.context.ApplicationContext;
import com.esri.gpt.framework.context.BaseServlet;
import com.esri.gpt.framework.context.RequestContext;
import com.esri.gpt.framework.jsf.FacesContextBroker;
import com.esri.gpt.framework.jsf.MessageBroker;
import com.esri.gpt.framework.security.credentials.Credentials;
import com.esri.gpt.framework.security.credentials.CredentialsDeniedException;
import com.esri.gpt.framework.security.identity.NotAuthorizedException;
import com.esri.gpt.framework.security.principal.Publisher;
import com.esri.gpt.framework.util.EnumerationAdapter;
import com.esri.gpt.framework.util.UuidUtil;
import com.esri.gpt.framework.util.Val;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Provides an HTTP REST interface for the management of an XML based metadata document.
* <p/>
* The URL pattern for this end-point is:<br/>
* <i>http://host:port/application/</i><b>rest/manage/document</b>
* <p/>
* Four HTTP methods are supported:
* <ul>
* <li>GET - gets an XML document from the catalog
* <ul>
* <li>the subject document must be specified within the URL</li>
* <li>the XML is returned within the body of the HTTP response</li>
* </ul>
* <li>PUT - publishes an XML document to the catalog
* <ul>
* <li>the XML must be supplied within the body of the HTTP request.</li>
* <li>URL parameter publicationMethod is accepted, values are upload,editor,other</li>
* <li>URL parameter asDraft=true is accepted</li>
* <li>URL parameter approve=true is accepted</li>
* <li>if no document provided, that means this is resource registration request.</li>
* <li>returns HTTP 200 when a document is replaced</li>
* <li>returns HTTP 201 when a document is created</li>
* </ul>
* <li>POST - same as PUT</li>
* <li>DELETE - deletes a document from the catalog
* <ul>
* <li>the subject document must be specified within the URL</li>
* <li>returns HTTP 200 when a document is deleted</li>
* </ul>
* </ul>
* The subject document can be specified within the URL as follows:
* <ul>
* <li>.../rest/manage/document/<b>identifier</b></li>
* <li>.../rest/manage/document<b>?id=identifier</b></li>
* <li><b>identifier</b> can be the catalog's UUID for the document,
* or the file identifier internal to the XML document</li>
* <li><b>identifier</b> must be properly URL encoded</li>
* </ul>
* Attributes applicable for resource registration:
* <ul>
* <li>url - resource URL (required)</li>
* <li>uuid - UUID of the resource (optional). If provided this is an update of the already existing resource</li>
* <li>name - resource name/title (optional)</li>
* <li>protocol - protocol type (optional: res,arcgis,arcims,csw,oai,waf). Default: res</li>
* <li>frequency - frequency (optional: Monthly, BiWeekly, Weekly, Dayly, Hourly, Once, Skip). Default: Skip</li>
* <li>sendNotification - to send notification (optional: true,false). Default: false</li>
* <li>updateContent - to harvest content during synchronization (optional: true,false). Default: true</li>
* <li>updateDefinition - to update definition during synchronization (optional: true,false). Default: true</li>
* <li>autoApprove - to automatically approve newly acquired metadata (optional: true,false). Default: true</li>
* <li>findable - to make this resource findable when searching for metadata (optional: true, false), Default: true</li>
* <li>searchable - to make this resource to act as distributed search endpoint (only if csw) (optional: true, false), Default: true</li>
* <li>synchronizable - to make this resource synchronizable (optional: true, false), Default: true</li>
* <li>username - user name required to access protected resource (optional)</li>
* <li>password - password required to access protected resource (optional)</li>
* <li>soapurl - (ARCGIS only) resource SOAP URL</li>
* <li>profile - (CSW only) profile</li>
* <li>set - (OAI only) set</li>
* <li>prefix - (OAI only) prefix</li>
* <li>service - (ARCIMS only) service</li>
* <li>port - (ARCIMS only) port</li>
* <li>rootFolder - (ARCIMS only) root folder</li>
* </ul>
* Exceptions applicable to all methods:
* <ul>
* <li>HTTP 401 Unauthorized
* - indicates that valid credentials must be supplied to access this URL</li>
* <li>HTTP 403 The document is owned by another user.
* - when an attempt is made to access a document owned by another user</li>
* </ul>
* Exceptions applicable to GET/DETETE:
* <ul>
* <li>HTTP 404 Document not found..
* - when the document specified within the request URL could not be located
* within the catalog</li>
* </ul>
* Exceptions applicable to PUT/POST:
* <ul>
* <li>HTTP 400 IOException while reading request body.
* - when characters could not be read from the request body</li>
* <li>HTTP 409 Document was empty.
* - when the request body was empty</li>
* <li>HTTP 409 Unable to parse document as XML.
* - when the content of the request body cannot be parsed as XML</li>
* <li>HTTP 409 Unrecognized metadata schema.
* - when the supplied XML does not match a configured XML standard for the catalog</li>
* <li>HTTP 409 Document failed to validate..
* - when the supplied XML is invalid with respect to the configured validation rules
* for the catalog</li>
* <li>HTTP 409 XSD violation.
* - when the supplied XML is invalid with respect to it's XSD</li>
* <li>HTTP 409 Duplicated resource URL.
* - when registering new resource with URL as another already registered resource</li>
* </ul>
*
*/
public class ManageDocumentServlet extends BaseServlet {
/** class variables ========================================================= */
/** The logger.*/
private static final Logger LOGGER = Logger.getLogger(ManageDocumentServlet.class.getName());
/** methods ================================================================= */
/**
* Determines the source uri for a publication request.
* @param request the servlet request
* @param context the request context
* @param publisher the publisher
* @throws SQLException if an exception occurs while communicating with the database
* @throws ServletException
*/
private void determineSourceUri(HttpServletRequest request, RequestContext context,
PublicationRequest publicationRequest) throws SQLException, ServletException {
String uuid = this.determineUuid(request, context, false);
if ((uuid != null) && (uuid.length() > 0)) {
publicationRequest.getPublicationRecord().setSourceFileName(uuid+".xml");
//sourceUri = uuid;
} else {
String pathInfo = Val.chkStr(request.getPathInfo());
String queryString = Val.chkStr(request.getQueryString());
if (pathInfo.startsWith("/")) pathInfo = pathInfo.substring(1);
if (queryString.length() > 0) {
pathInfo = pathInfo+"?"+queryString;
}
if (pathInfo.length() > 0) {
//sourceUri = "userid:"+pubRequest.getPublisher().getLocalID()+"/"+pathInfo;
}
}
}
/**
* Determines the specified document UIID from the HTTP request URL.
* @param request the servlet request
* @param context the request context
* @param force if true, throw a ServletException if the document UUID is undetermined
* @return the document UUID
* @throws SQLException if an exception occurs while communicating with the database
* @throws ServletException if the document UUID is undetermined (force=true only)
*/
private String determineUuid(HttpServletRequest request, RequestContext context, boolean force)
throws SQLException, ServletException {
String uuid = "";
String id = Val.chkStr(request.getParameter("id"));
if (id.length() == 0) {
String tmp = Val.chkStr(request.getPathInfo()).replaceAll("^/", "");
try {
id = Val.chkStr(URLDecoder.decode(tmp,"UTF-8"));
} catch (UnsupportedEncodingException e) {
// will never happen
}
}
// determine the document uuid (the supplied id could be a gpt uuid or file identifier)
if (id.length() > 0) {
ImsMetadataAdminDao dao = new ImsMetadataAdminDao(context);
uuid = dao.findUuid(id);
if (!force && ((uuid == null) || (uuid.length() == 0))) {
String tmpId = UuidUtil.addCurlies(id);
if (tmpId.length() == 38) {
uuid = tmpId;
}
}
}
// throw an exception if the document uuid was not located
if (force && ((uuid == null) || (uuid.length() == 0))) {
throw new ServletException("404: Document not found.");
}
return uuid;
}
/**
* Deletes a document from the catalog.
* <br/>An HTTP 200 response code is set when a document is successfully deleted.
* @param request the servlet request
* @param response the servlet response
* @throws ServletException if the request cannot be handled
* @throws IOException if an I/O error occurs while handling the request
*/
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.execute(request,response,"DELETE");
}
/**
* Gets an XML document from the catalog.
* <br/>The XML is returned within the body of the HTTP response.
* @param request the servlet request
* @param response the servlet response
* @throws ServletException if the request cannot be handled
* @throws IOException if an I/O error occurs while handling the request
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.execute(request,response,"GET");
}
/**
* Handles a POST request.
* <br/>Same as doPut().
* @param request the servlet request
* @param response the servlet response
* @throws ServletException if the request cannot be handled
* @throws IOException if an I/O error occurs while handling the request
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.execute(request,response,"POST");
}
/**
* Publishes an XML document to the catalog.
* <br/>The XML must be supplied within the body of the HTTP request.
* <br/>An HTTP 200 response code is set when a document is successfully replaced.
* <br/>An HTTP 201 response code is set when a document is successfully created.
* @param request the servlet request
* @param response the servlet response
* @throws ServletException if the request cannot be handled
* @throws IOException if an I/O error occurs while handling the request
*/
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.execute(request,response,"PUT");
}
/**
* Provides a concrete executeUpdate() method to fulfill the sub-class requirement of the parent
* BaseServlet class.
* This method is never invoked, all work is handled through
* doGet(), doPut(), doPost() and doDelete().
*/
@Override
protected void execute(HttpServletRequest request, HttpServletResponse response, RequestContext context)
throws Exception {
}
/**
* Processes the HTTP request.
* @param request the HTTP request
* @param response HTTP response
* @param context request context
* @param method the method to executeUpdate GET|PUT|POST|DELETE
* @throws ServletException if the request cannot be handled
* @throws IOException if an I/O error occurs while handling the request
*/
private void execute(HttpServletRequest request, HttpServletResponse response, String method)
throws ServletException, IOException {
RequestContext context = null;
try {
String msg = "HTTP "+method+", "+request.getRequestURL().toString();
if ((request.getQueryString() != null) && (request.getQueryString().length() > 0)) {
msg += "?"+request.getQueryString();
}
getLogger().fine(msg);
String sEncoding = request.getCharacterEncoding();
if ((sEncoding == null) || (sEncoding.trim().length() == 0)) {
request.setCharacterEncoding("UTF-8");
}
context = RequestContext.extract(request);
/// estabish the publisher
StringAttributeMap params = context.getCatalogConfiguration().getParameters();
String autoAuthenticate = Val.chkStr(params.getValue("BaseServlet.autoAuthenticate"));
if (!autoAuthenticate.equalsIgnoreCase("false")) {
Credentials credentials = getCredentials(request);
if (credentials != null) {
this.authenticate(context,credentials);
}
}
Publisher publisher = new Publisher(context);
// executeUpdate the appropriate action
if (method.equals("GET")) {
this.executeGet(request,response,context,publisher);
} else if (method.equals("POST")) {
this.executePost(request,response,context,publisher);
} else if (method.equals("PUT")) {
this.executePut(request,response,context,publisher);
} else if (method.equals("DELETE")) {
this.executeDelete(request,response,context,publisher);
}
} catch (CredentialsDeniedException e) {
String sRealm = this.getRealm(context);
response.setHeader("WWW-Authenticate","Basic realm=\""+sRealm+"\"");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
} catch (NotAuthorizedException e) {
String sRealm = this.getRealm(context);
response.setHeader("WWW-Authenticate","Basic realm=\""+sRealm+"\"");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
} catch (ValidationException e) {
String sMsg = e.toString();
if (sMsg.contains("XSD violation.")) {
sMsg = "XSD violation.";
} else if (sMsg.contains("Invalid metadata document.")) {
sMsg = "Invalid metadata document.";
} else {
sMsg = "Invalid metadata document.";
}
String json = Val.chkStr(request.getParameter("errorsAsJson"));
if (json.length()>0) {
json = Val.escapeXmlForBrowser(json);
FacesContextBroker fcb = new FacesContextBroker(request, response);
MessageBroker msgBroker = fcb.extractMessageBroker();
ArrayList<String> validationMessages = new ArrayList<String>();
e.getValidationErrors().buildMessages(msgBroker, validationMessages, true);
StringBuilder sb = new StringBuilder();
sb.append(json).append(" = {\r\n");
sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n");
sb.append("code: 409,\r\n");
sb.append("errors: [\r\n");
for (int i=0; i<validationMessages.size(); i++) {
if (i>0) {
sb.append(",\r\n");
}
sb.append("\"").append(Val.escapeStrForJson(validationMessages.get(i))).append("\"");
}
if (validationMessages.size()>0) {
sb.append("\r\n");
}
sb.append("]}");
LOGGER.log(Level.SEVERE, sb.toString());
response.getWriter().print(sb.toString());
} else {
response.sendError(409,sMsg);
}
} catch (ServletException e) {
String sMsg = e.getMessage();
int nCode = Val.chkInt(sMsg.substring(0,3),500);
sMsg = Val.chkStr(sMsg.substring(4));
String json = Val.chkStr(request.getParameter("errorsAsJson"));
if (json.length()>0) {
json = Val.escapeXmlForBrowser(json);
StringBuilder sb = new StringBuilder();
sb.append(json).append(" = {\r\n");
sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n");
sb.append("code: ").append(nCode).append(",\r\n");
sb.append("errors: [\r\n");
sb.append("\"").append(Val.escapeStrForJson(sMsg)).append("\"");
sb.append("]}");
LOGGER.log(Level.SEVERE, sb.toString());
response.getWriter().print(sb.toString());
} else {
response.sendError(nCode,sMsg);
}
} catch (Throwable t) {
String sMsg = t.toString();
String json = Val.chkStr(request.getParameter("errorsAsJson"));
if (json.length()>0) {
json = Val.escapeXmlForBrowser(json);
StringBuilder sb = new StringBuilder();
sb.append(json).append(" = {\r\n");
sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n");
sb.append("code: ").append(500).append(",\r\n");
sb.append("errors: [\r\n");
sb.append("\"").append(Val.escapeStrForJson(sMsg)).append("\"");
sb.append("]}");
LOGGER.log(Level.SEVERE, sb.toString());
response.getWriter().print(sb.toString());
} else if (sMsg.contains("The document is owned by another user:")) {
response.sendError(HttpServletResponse.SC_FORBIDDEN,"The document is owned by another user.");
} else {
String sErr = "Exception occured while processing servlet request.";
getLogger().log(Level.SEVERE,sErr,t);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
sMsg + sErr);
}
} finally {
if (context != null) context.onExecutionPhaseCompleted();
}
}
/**
* Deletes the metadata document specified within the URL.
* @param request the servlet request
* @param response the servlet response
* @param context the request context
* @param publisher the publisher
* @throws Exception if an exception occurs
*/
private void executeDelete(HttpServletRequest request, HttpServletResponse response,
RequestContext context, Publisher publisher) throws Exception {
String uuid = this.determineUuid(request,context,true);
MmdActionCriteria actionCriteria = new MmdActionCriteria();
actionCriteria.setActionKey("delete");
actionCriteria.getSelectedRecordIdSet().add(uuid);
MmdResult result = new MmdResult();
MmdCriteria criteria = new MmdCriteria();
criteria.setActionCriteria(actionCriteria);
MmdActionRequest actionRequest = new MmdActionRequest(context,publisher,criteria,result);
actionRequest.execute();
LOGGER.finer(result.getActionResult().getNumberOfRecordsModified()+" document(s) deleted.");
}
/**
* Gets the XML string associated with the metadata document specified within the URL.
* @param request the servlet request
* @param response the servlet response
* @param context the request context
* @param publisher the publisher
* @throws Exception if an exception occurs
*/
private void executeGet(HttpServletRequest request, HttpServletResponse response,
RequestContext context, Publisher publisher) throws Exception {
String uuid = this.determineUuid(request,context,true);
MetadataDocument mdDoc = new MetadataDocument();
String xml = Val.chkStr(mdDoc.prepareForDownload(context,publisher,uuid));
if (xml.length() > 0) {
this.writeXmlResponse(response,xml);
}
}
/**
* Publishes the XML metadata document supplied within the request body.
* <br/>this method is a pass-turu to executePut().
* @param request the servlet request
* @param response the servlet response
* @param context the request context
* @param publisher the publisher
* @throws Exception if an exception occurs
*/
private void executePost(HttpServletRequest request, HttpServletResponse response,
RequestContext context, Publisher publisher) throws Exception {
this.executePut(request,response,context,publisher);
}
/**
* Publishes the XML metadata document supplied within the request body.
* @param request the servlet request
* @param response the servlet response
* @param context the request context
* @param publisher the publisher
* @throws Exception if an exception occurs
*/
private void executePut(HttpServletRequest request, HttpServletResponse response,
RequestContext context, Publisher publisher) throws Exception {
String xml = null;
HrRecord record = extractRegistrationInfo(request);
if (record==null) {
try {
xml = this.readInputCharacters(request);
} catch (IOException e) {
throw new ServletException("400: IOException while reading request body.");
}
xml = Val.chkStr(Val.removeBOM(xml));
if (xml.length() > 0) {
PublicationRequest pubRequest = new PublicationRequest(context,publisher,xml);
PublicationRecord pubRecord = pubRequest.getPublicationRecord();
pubRecord.setPublicationMethod(MmdEnums.PublicationMethod.upload.toString());
String pubMethod = Val.chkStr(request.getParameter("publicationMethod"));
if (pubMethod.length() > 0) {
try {
pubMethod = MmdEnums.PublicationMethod.valueOf(Val.chkStr(pubMethod)).toString();
pubRecord.setPublicationMethod(pubMethod);
} catch (IllegalArgumentException ex) {
}
}
String asDraft = Val.chkStr(request.getParameter("asDraft"));
String approve = Val.chkStr(request.getParameter("approve"));
LOGGER.fine("Approving of uploaded documents through the REST with 'approve' flag: "+approve);
if (asDraft.equals("true")) {
pubRecord.setApprovalStatus(MmdEnums.ApprovalStatus.draft.toString());
} else if (approve.equals("true")) {
pubRecord.setApprovalStatus(MmdEnums.ApprovalStatus.approved.toString());
if (!publisher.getIsAdministrator()) {
throw new NotAuthorizedException("Not authorized.");
}
}
this.determineSourceUri(request,context,pubRequest);
try {
pubRequest.publish();
if (!pubRecord.getWasDocumentReplaced()) {
response.setStatus(HttpServletResponse.SC_CREATED);
}
// } catch (ValidationException e) {
// String sMsg = e.toString();
// if (sMsg.contains("XSD violation.")) {
// throw new ServletException("409: XSD violation.");
// } else if (sMsg.contains("Invalid metadata document.")) {
// throw new ServletException("409: Document failed to validate.");
// } else {
// throw new ServletException("409: Document failed to validate.");
// }
} catch (SchemaException e) {
String sMsg = e.toString();
if (sMsg.contains("Unrecognized metadata schema.")) {
throw new ServletException("409: Unrecognized metadata schema.");
} else if (sMsg.contains("Unable to parse document.")) {
throw new ServletException("409: Unable to parse document as XML.");
} else {
throw e;
}
}
} else {
throw new ServletException("409: Document was empty.");
}
} else {
try {
HrCompleteUpdateRequest req = new HrCompleteUpdateRequest(context, record);
req.execute();
response.setStatus(HttpServletResponse.SC_CREATED);
} catch (HrAssertUrlException e) {
throw new ServletException("409: Duplicated resource URL.");
} catch (ValidationException e) {
String sMsg = e.toString();
if (sMsg.contains("XSD violation.")) {
throw new ServletException("409: XSD violation.");
} else if (sMsg.contains("Invalid metadata document.")) {
throw new ServletException("409: Document failed to validate.");
} else {
throw new ServletException("409: Document failed to validate.");
}
} catch (SchemaException e) {
String sMsg = e.toString();
if (sMsg.contains("Unrecognized metadata schema.")) {
throw new ServletException("409: Unrecognized metadata schema.");
} else if (sMsg.contains("Unable to parse document.")) {
throw new ServletException("409: Unable to parse document as XML.");
} else {
throw e;
}
} catch (Exception ex) {
throw new ServletException("409: Unable to register resource.");
}
}
}
/**
* Extracts registration info.
* @param request HTTP request
* @return registration info or <code>null</code> if unable to extract registration info
*/
private HrRecord extractRegistrationInfo(HttpServletRequest request) {
ApplicationContext appCtx = ApplicationContext.getInstance();
ApplicationConfiguration appCfg = appCtx.getConfiguration();
HrRecord record = new HrRecord();
StringAttributeMap attributes = new StringAttributeMap();
boolean updateContent = true;
boolean updateDefinition = true;
boolean autoApprove = true;
BotsMode robotsTxtMode = BotsMode.getDefault();
for (String paramName : new EnumerationAdapter<String>(request.getParameterNames())) {
String paramValue = request.getParameter(paramName);
if (paramName.equalsIgnoreCase("uuid")) {
record.setUuid(paramValue);
}
if (paramName.equalsIgnoreCase("name")) {
record.setName(paramValue);
}
else if (paramName.equalsIgnoreCase("url")) {
record.setHostUrl(paramValue);
}
else if (paramName.equalsIgnoreCase("soapurl")) {
attributes.add(new StringAttribute(ArcGISProtocol.SOAP_URL,paramValue));
}
else if (paramName.equalsIgnoreCase("protocol")) {
ProtocolFactory factory = appCfg.getProtocolFactories().get(paramValue);
if (factory!=null) {
record.setProtocol(factory.newProtocol());
}
}
else if (paramName.equalsIgnoreCase("frequency")) {
record.setHarvestFrequency(HarvestFrequency.checkValueOf(paramValue));
}
else if (paramName.equalsIgnoreCase("sendNotification")) {
record.setSendNotification(Val.chkBool(paramValue, false));
}
else if (paramName.equalsIgnoreCase("updateContent")) {
updateContent = Val.chkBool(paramValue, true);
}
else if (paramName.equalsIgnoreCase("updateDefinition")) {
updateDefinition = Val.chkBool(paramValue, true);
}
else if (paramName.equalsIgnoreCase("autoApprove")) {
autoApprove = Val.chkBool(paramValue, true);
}
else if (paramName.equalsIgnoreCase("findable")) {
record.setFindable(Val.chkBool(paramValue, true));
}
else if (paramName.equalsIgnoreCase("searchable")) {
record.setSearchable(Val.chkBool(paramValue, true));
}
else if (paramName.equalsIgnoreCase("synchronizable")) {
record.setSynchronizable(Val.chkBool(paramValue, true));
}
else if (paramName.equalsIgnoreCase("robotstxtmode")) {
robotsTxtMode = BotsMode.parseMode(paramValue);
}
else {
attributes.add(new StringAttribute(paramName,paramValue));
}
}
if (record.getProtocol()==null || record.getProtocol().getKind().equalsIgnoreCase(ProtocolType.None.name())) {
ProtocolFactory factory = appCfg.getProtocolFactories().get(ProtocolType.RES.name());
if (factory!=null) {
record.setProtocol(factory.newProtocol());
}
}
if (record.getProtocol()!=null) {
record.getProtocol().setAttributeMap(attributes);
ProtocolInvoker.setUpdateDefinition(record.getProtocol(), updateDefinition);
ProtocolInvoker.setUpdateContent(record.getProtocol(), updateContent);
ProtocolInvoker.setAutoApprove(record.getProtocol(), autoApprove);
ProtocolInvoker.setRobotsTxtMode(record.getProtocol(), robotsTxtMode);
}
record = record.getName().length()>0 && record.getHostUrl().length()>0 && record.getProtocol()!=null? record: null;
return record;
}
}
|
Esri/geoportal-server
|
geoportal/src/com/esri/gpt/control/rest/ManageDocumentServlet.java
|
Java
|
apache-2.0
| 30,411
|
package com.github.linggify.attic.resources;
import com.github.linggify.attic.Application;
import com.github.linggify.attic.IFileManager;
/**
* {@link IResourceLoader}s are used to load specific files as resources
* @author Freddy
*/
public interface IResourceLoader {
/**
*
* @return the type of resource this {@link IResourceLoader} loads
*/
String loadingType();
/**
* Sets the {@link Application} to load the resources into
* @param app
*/
void setApplication(Application app);
/**
* Loads the given resource
* @param file
* @return the handle of the resource
*/
int load(IFileManager.IFileHandle file);
/**
* Destroys the given resource, thereby making it unusable
* @param handle
*/
void destroy(int handle);
}
|
Linggify/AtticEngine
|
attic/core/src/main/java/com/github/linggify/attic/resources/IResourceLoader.java
|
Java
|
apache-2.0
| 823
|
namespace MessyLab.Platforms.Pico
{
partial class ConsolePad
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConsolePad));
this.queryLabel = new System.Windows.Forms.Label();
this.inTextBox = new System.Windows.Forms.TextBox();
this.enterButton = new System.Windows.Forms.Button();
this.inputPanel = new System.Windows.Forms.Panel();
this.outTextBox = new System.Windows.Forms.TextBox();
this.inputPanel.SuspendLayout();
this.SuspendLayout();
//
// queryLabel
//
this.queryLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.queryLabel.AutoSize = true;
this.queryLabel.Location = new System.Drawing.Point(3, 6);
this.queryLabel.Name = "queryLabel";
this.queryLabel.Size = new System.Drawing.Size(0, 13);
this.queryLabel.TabIndex = 0;
//
// inTextBox
//
this.inTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.inTextBox.Location = new System.Drawing.Point(3, 22);
this.inTextBox.Name = "inTextBox";
this.inTextBox.Size = new System.Drawing.Size(246, 22);
this.inTextBox.TabIndex = 1;
//
// enterButton
//
this.enterButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.enterButton.Image = ((System.Drawing.Image)(resources.GetObject("enterButton.Image")));
this.enterButton.Location = new System.Drawing.Point(255, 22);
this.enterButton.Name = "enterButton";
this.enterButton.Size = new System.Drawing.Size(26, 23);
this.enterButton.TabIndex = 2;
this.enterButton.UseVisualStyleBackColor = true;
this.enterButton.Click += new System.EventHandler(this.enterButton_Click);
//
// inputPanel
//
this.inputPanel.Controls.Add(this.enterButton);
this.inputPanel.Controls.Add(this.inTextBox);
this.inputPanel.Controls.Add(this.queryLabel);
this.inputPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.inputPanel.Location = new System.Drawing.Point(0, 340);
this.inputPanel.Name = "inputPanel";
this.inputPanel.Size = new System.Drawing.Size(284, 48);
this.inputPanel.TabIndex = 4;
this.inputPanel.Visible = false;
//
// outTextBox
//
this.outTextBox.BackColor = System.Drawing.SystemColors.Window;
this.outTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.outTextBox.Location = new System.Drawing.Point(0, 0);
this.outTextBox.Multiline = true;
this.outTextBox.Name = "outTextBox";
this.outTextBox.ReadOnly = true;
this.outTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.outTextBox.Size = new System.Drawing.Size(284, 340);
this.outTextBox.TabIndex = 5;
//
// ConsolePad
//
this.AcceptButton = this.enterButton;
this.AutoHidePortion = 300;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.ClientSize = new System.Drawing.Size(284, 388);
this.Controls.Add(this.outTextBox);
this.Controls.Add(this.inputPanel);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "ConsolePad";
this.TabText = "Console";
this.Text = "Console";
this.inputPanel.ResumeLayout(false);
this.inputPanel.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label queryLabel;
private System.Windows.Forms.TextBox inTextBox;
private System.Windows.Forms.Button enterButton;
private System.Windows.Forms.Panel inputPanel;
private System.Windows.Forms.TextBox outTextBox;
}
}
|
drstorm/messylab
|
MessyLab/Platforms/Pico/ConsolePad.Designer.cs
|
C#
|
apache-2.0
| 4,668
|
# -*- coding: utf-8 -*-
from troubleshooting.framework.modules.manager import ManagerFactory
from troubleshooting.framework.variable.variable import *
from troubleshooting.framework.libraries.baseList import list2stringAndFormat
from troubleshooting.framework.libraries.system import createDir
from troubleshooting.framework.modules.configuration import ConfigManagerInstance
import time
import os,sys
from htmltemplate import *
import re
class html(object):
def __init__(self):
super(html,self).__init__()
self.caseResult = ManagerFactory().getManager(LAYER.Case).case_record
self.currenttime = time.strftime("%Y-%m-%d %X %Z",time.localtime())
def write(self):
data = ""
data += HTML_BEFORE
data += HTML_HEAD
data +="""
<body bgcolor = "#E9EAEE">
<h1 align="center">TroubleShooting Framework Report</h1>
<p><i>%s</i></p>
<table width="100%%" border="2" class="bordered">
<thead>
<tr ><th width="15%%">CaseName</th><th width="5%%" >Status</th><th width="80%%">Attribute</th></tr>
</thead>
<tbody>
"""%(self.currenttime,)
recovery_id = 1
for i,caseName in enumerate(self.caseResult):
i += 1
caseStatus = self.caseResult[caseName]["STATUS"]
DESCRIPTION = self.caseResult[caseName]["DESCRIPTION"]
REFERENCE = self.caseResult[caseName]["REFERENCE"]
REFERENCEHtml = '<a href="%s">reference document</>'%REFERENCE if REFERENCE else '<font color="#d0d0d0">NA</font>'
TAGS = self.caseResult[caseName]["TAGS"]
TESTPOINT = self.caseResult[caseName]["TESTPOINT"]
parent_pass = """
<tr bgcolor="#53C579" class="parent" id="row_0%s"><td colspan="1">%s</td><td>PASS</td><td colspan="1"></td></tr>"""%(i,caseName,)
parent_fail = """
<tr bgcolor="#FF3030" class="parent" id="row_0%s"><td colspan="1">%s</td><td>FAIL</td><td colspan="1"></td></tr>"""%(i,caseName,)
parent_warn = """
<tr bgcolor="#FF7F00" class="parent" id="row_0%s"><td colspan="1">%s</td><td>WARN</td><td colspan="1"></td></tr>"""%(i,caseName,)
if caseStatus:
data += parent_pass
else:
_level = self.caseResult[caseName]["LEVEL"]
if _level is LEVEL.CRITICAL:
data += parent_fail
else:
data += parent_warn
data += """
<tr class="child_row_0%s" style="display:none"><td>Description</td><td></td><td>%s</td></tr>
<tr class="child_row_0%s" style="display:none"><td>Reference</td><td></td><td>%s</td></tr>
<tr class="child_row_0%s" style="display:none"><td>Tags</td><td></td><td>%s</td></tr>
"""%(i,DESCRIPTION,i,REFERENCEHtml,i,TAGS)
data += """
<tr class="child_row_0%s" style="display:none">
<td colspan="3" >
<table border="1" width="100%%" style="margin:0px">
"""%i
data += """
<tr>
<th width="5%%">
<b>TestPoint</b>
</th>
<th width="5%%">
<b>Status</b>
</th>
<th width="5%%">
<b>Level</b>
</th>
<th width="15%%" name="nolog">
<b>Impact</b>
</th>
<th width="35%%" name="nolog">
<b>Root Cause</b>
</th>
<th width="15%%" name="nolog">
<b>Fix Method</b>
</th>
<th width="20%%" name="nolog">
<b>Auto Fix Method</b>
</th>
<th style="display:none;" width="85%%" name="log">
<b>LOG</b>
</th>
</tr>
"""
for testpoint in TESTPOINT:
testpointStatus = TESTPOINT[testpoint]["STATUS"]
testpointStatusHtml = '<font color="green"><b><i>%s</i></b></font>' % STATUS.PASS.value.lower() if testpointStatus else '<font color="red"><b><i>%s</i></b></font>' % STATUS.FAIL.value.lower()
testpointImpact = TESTPOINT[testpoint]["IMPACT"]
testpointImpact = list2stringAndFormat(testpointImpact)
if not testpointImpact:
testpointImpact = '<font color="#d0d0d0">NA</font>'
testpointImpactHtml = testpointImpact.replace("\n","</br>")
testpointLevel = TESTPOINT[testpoint]["LEVEL"]
testpointLevelHtml = testpointLevel.value
testpointDescribe = TESTPOINT[testpoint]["DESCRIBE"]
testpointRCA = TESTPOINT[testpoint]["RCA"]
testpointRCA = list2stringAndFormat(testpointRCA)
if not testpointRCA:
testpointRCA = '<font color="#d0d0d0">NA</font>'
testpointRCAHtml = testpointRCA.replace("\n","</br>")
testpointFIXSTEP = TESTPOINT[testpoint]["FIXSTEP"]
testpointFIXSTEP = list2stringAndFormat(testpointFIXSTEP)
if not testpointFIXSTEP:
testpointFIXSTEP = '<font color="#d0d0d0">NA</font>'
testpointFIXSTEPHtml = testpointFIXSTEP.replace("\n","</br>")
testpointAutoFixStep = TESTPOINT[testpoint]["AUTOFIXSTEP"]
if not testpointAutoFixStep:
testpointAutoFixStep = '<font color="#d0d0d0">NA</font>'
else:
if ConfigManagerInstance.config["Host"]:
reportHash = ConfigManagerInstance.config["__ReportHash__"]
reportName = ConfigManagerInstance.config["__ReportName__"]
host = ConfigManagerInstance.config["Host"]
port = ConfigManagerInstance.config["Port"]
user = ConfigManagerInstance.config["User"]
password = ConfigManagerInstance.config["Password"]
cwd =ConfigManagerInstance.config["__ProjectCWD__"]
recovery = {"ProjectDir":cwd,"Host":host,"Port":port,"User":user,"Password":password,"Recovery":",".join(testpointAutoFixStep)}
testpointAutoFixStep = """
<iframe scrolling="no" src="/www/iframe/growl-genie.html?recovery=%s&reportHash=%s&reportName=%s"></iframe>
"""%(recovery,reportHash,reportName)
testpointAutoFixStepHtml = testpointAutoFixStep
testpointLog = TESTPOINT[testpoint]["LOG"]
testpointLogHtml = testpointLog
pattern = re.compile(r"\<.+\>")
match = pattern.finditer(testpointLog)
if match:
for m in match:
className = m.group()
testpointLogHtml = testpointLogHtml.replace(className,'<font color="#FFB90F">%s</font>'%className)
testpointLogHtml = testpointLogHtml.replace("\n", "</br>")
testpointTimeout = TESTPOINT[testpoint]["TIMEOUT"]
testpointCost = TESTPOINT[testpoint]["COST"]
testpointHtml = '<i title="Timeout: %s\nCostTime: %s">%s<i>'%(testpointTimeout,testpointCost,testpoint.strip("{}"))
attribute = """
<tr>
<td>
<i>%s</i>
</td>
<td>
<i>%s</i>
</td>
<td>
<i>%s</i>
</td>
<td name="nolog">
<i>%s</i>
</td>
<td name="nolog">
<i>%s</i>
</td>
<td name="nolog">
<i>%s</i>
</td>
<td name="nolog">
<i>%s</i>
</td>
<td style="display:none" name="log">
<i>%s</i>
</td>
</tr>
"""%(testpointHtml,testpointStatusHtml,testpointLevelHtml,testpointImpactHtml,testpointRCAHtml,testpointFIXSTEPHtml,testpointAutoFixStepHtml,testpointLogHtml)
data += attribute
data += """
</table>
</td>
</tr>
"""
data += """
</tbody>
</table>
"""
data += BUTTON
# data += HTML_LOG
data += BODY_AFTER
data += HTML_AFTER
reportDir = os.path.dirname(ConfigManagerInstance.config["Report"])
createDir(reportDir)
reportPath = ConfigManagerInstance.config["Report"]
with open(reportPath,"w") as f:
f.write(data)
|
gaoxiaofeng/troubleShooting
|
src/troubleshooting/framework/output/writehtml.py
|
Python
|
apache-2.0
| 9,570
|
# AUTOGENERATED FILE
FROM balenalib/generic-amd64-fde-fedora:33-build
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
RUN dnf install -y \
python3-pip \
python3-dbus \
&& dnf clean all
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install -U --no-cache-dir --ignore-installed pip setuptools \
&& pip3 install --no-cache-dir virtualenv
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warning
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Fedora 33 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.7.12, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
resin-io-library/base-images
|
balena-base-images/python/generic-amd64-fde/fedora/33/3.7.12/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,460
|
package krasa.core.frontend.commons.table;
import java.util.List;
import krasa.core.frontend.commons.StyledLabel;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.ChoiceFilteredPropertyColumn;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
public class StyledChoiceFilteredPropertyColumn<T, Y, S> extends ChoiceFilteredPropertyColumn<T, Y, S> {
public StyledChoiceFilteredPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression,
IModel<List<? extends Y>> filterChoices) {
super(displayModel, sortProperty, propertyExpression, filterChoices);
}
public StyledChoiceFilteredPropertyColumn(IModel<String> displayModel, String propertyExpression,
IModel<List<? extends Y>> filterChoices) {
super(displayModel, propertyExpression, filterChoices);
}
@Override
public void populateItem(Item<ICellPopulator<T>> item, String componentId, IModel<T> rowModel) {
item.add(new StyledLabel(componentId, getDataModel(rowModel)));
}
}
|
krasa/DevSupportApp
|
src/main/java/krasa/core/frontend/commons/table/StyledChoiceFilteredPropertyColumn.java
|
Java
|
apache-2.0
| 1,123
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 itkAnchorOpenImageFilter_h
#define itkAnchorOpenImageFilter_h
#include "itkAnchorOpenCloseImageFilter.h"
namespace itk
{
template< typename TImage, typename TKernel >
class AnchorOpenImageFilter:
public AnchorOpenCloseImageFilter< TImage, TKernel, std::less< typename TImage::PixelType >,
std::greater< typename TImage::PixelType > >
{
public:
typedef AnchorOpenImageFilter Self;
typedef AnchorOpenCloseImageFilter< TImage, TKernel, std::less< typename TImage::PixelType >,
std::greater< typename TImage::PixelType > > Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
protected:
AnchorOpenImageFilter()
{
this->m_Boundary1 = NumericTraits< typename TImage::PixelType >::max();
this->m_Boundary2 = NumericTraits< typename TImage::PixelType >::NonpositiveMin();
}
virtual ~AnchorOpenImageFilter() {}
private:
ITK_DISALLOW_COPY_AND_ASSIGN(AnchorOpenImageFilter);
};
} // namespace itk
#endif
|
RayRuizhiLiao/ITK_4D
|
Modules/Filtering/MathematicalMorphology/include/itkAnchorOpenImageFilter.h
|
C
|
apache-2.0
| 1,975
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var tape = require( 'tape' );
var Readable = require( 'readable-stream' ).Readable;
var now = require( '@stdlib/time/now' );
var poisson = require( '@stdlib/random/base/poisson' ).factory;
var isBuffer = require( '@stdlib/assert/is-buffer' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var Uint32Array = require( '@stdlib/array/uint32' );
var minstd = require( '@stdlib/random/base/minstd' );
var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
var randomStream = require( './../lib/main.js' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof randomStream, 'function', 'main export is a function' );
t.end();
});
tape( 'the function throws an error if mean parameter `lambda` is not a positive number primitive', function test( t ) {
var values;
var i;
values = [
'5',
-1.0,
0.0,
null,
true,
false,
void 0,
NaN,
[],
{},
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
randomStream( value );
};
}
});
tape( 'the function throws an error if provided an options argument which is not an object', function test( t ) {
var values;
var i;
values = [
'abc',
5,
null,
true,
false,
void 0,
NaN,
[],
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
randomStream( 3.0, value );
};
}
});
tape( 'the function throws an error if provided an invalid `iter` option', function test( t ) {
var values;
var i;
values = [
'abc',
-5,
3.14,
null,
true,
false,
void 0,
NaN,
[],
{},
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
randomStream( 3.0, {
'iter': value
});
};
}
});
tape( 'if provided a `prng` option which is not a function, the function throws an error', function test( t ) {
var values;
var i;
values = [
'5',
3.14,
NaN,
true,
false,
null,
void 0,
[],
{}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
randomStream( 3.0, {
'prng': value
});
};
}
});
tape( 'if provided a `copy` option which is not a boolean, the function throws an error', function test( t ) {
var values;
var i;
values = [
'5',
5,
NaN,
null,
void 0,
{},
[],
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
randomStream( 3.0, {
'copy': value
});
};
}
});
tape( 'if provided a `seed` which is not a positive integer or a non-empty array-like object, the function throws an error', function test( t ) {
var values;
var i;
values = [
'5',
3.14,
0.0,
-5.0,
NaN,
true,
false,
null,
void 0,
{},
[],
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
randomStream( 3.0, {
'seed': value
});
};
}
});
tape( 'the function throws a range error if provided a `seed` which is an integer greater than the maximum unsigned 32-bit integer', function test( t ) {
var values;
var i;
values = [
UINT32_MAX + 1,
UINT32_MAX + 2,
UINT32_MAX + 3
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), RangeError, 'throws a range error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
randomStream( 3.0, {
'seed': value
});
};
}
});
tape( 'if provided a `state` option which is not a Uint32Array, the function throws an error', function test( t ) {
var values;
var i;
values = [
'5',
5,
NaN,
true,
false,
null,
void 0,
{},
[],
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
randomStream( 3.0, {
'state': value
});
};
}
});
tape( 'if provided an invalid `state` option, the function throws an error', function test( t ) {
var values;
var i;
values = [
new Uint32Array( 0 ),
new Uint32Array( 10 ),
new Uint32Array( 100 )
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
randomStream( 3.0, {
'state': value
});
};
}
});
tape( 'if provided an invalid readable stream option, the function throws an error', function test( t ) {
var values;
var i;
values = [
'5',
5,
NaN,
null,
void 0,
{},
[],
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
randomStream( 3.0, {
'objectMode': value
});
};
}
});
tape( 'the function is a constructor which returns a readable stream', function test( t ) {
var RandomStream = randomStream;
var s;
s = new RandomStream( 3.0 );
t.equal( s instanceof Readable, true, 'returns expected value' );
t.end();
});
tape( 'the constructor does not require the `new` operator', function test( t ) {
var RandomStream = randomStream;
var s;
s = randomStream( 3.0 );
t.equal( s instanceof RandomStream, true, 'returns expected value' );
t.end();
});
tape( 'the constructor returns a readable stream (no new)', function test( t ) {
var s = randomStream( 3.0 );
t.equal( s instanceof Readable, true, 'returns expected value' );
t.end();
});
tape( 'the returned stream provides a method to destroy a stream (object)', function test( t ) {
var count = 0;
var s;
s = randomStream( 3.0 );
t.equal( typeof s.destroy, 'function', 'has destroy method' );
s.on( 'error', onError );
s.on( 'close', onClose );
s.destroy({
'message': 'beep'
});
function onError( err ) {
count += 1;
if ( err ) {
t.ok( true, err.message );
} else {
t.ok( false, 'does not error' );
}
if ( count === 2 ) {
t.end();
}
}
function onClose() {
count += 1;
t.ok( true, 'stream closes' );
if ( count === 2 ) {
t.end();
}
}
});
tape( 'the returned stream provides a method to destroy a stream (error object)', function test( t ) {
var count = 0;
var s;
s = randomStream( 3.0 );
t.equal( typeof s.destroy, 'function', 'has destroy method' );
s.on( 'error', onError );
s.on( 'close', onClose );
s.destroy( new Error( 'beep' ) );
function onError( err ) {
count += 1;
if ( err ) {
t.ok( true, err.message );
} else {
t.ok( false, 'does not error' );
}
if ( count === 2 ) {
t.end();
}
}
function onClose() {
count += 1;
t.ok( true, 'stream closes' );
if ( count === 2 ) {
t.end();
}
}
});
tape( 'the returned stream does not allow itself to be destroyed more than once', function test( t ) {
var s;
s = randomStream( 3.0 );
s.on( 'error', onError );
s.on( 'close', onClose );
// If the stream is closed twice, the test will error...
s.destroy();
s.destroy();
function onClose() {
t.ok( true, 'stream closes' );
t.end();
}
function onError( err ) {
t.ok( false, err.message );
}
});
tape( 'attached to the returned stream is the underlying PRNG', function test( t ) {
var s = randomStream( 3.0 );
t.equal( typeof s.PRNG, 'function', 'has property' );
s = randomStream( 3.0, {
'prng': minstd.normalized
});
t.equal( s.PRNG, minstd.normalized, 'has property' );
t.end();
});
tape( 'attached to the returned stream is the generator seed', function test( t ) {
var s = randomStream( 3.0, {
'seed': 12345
});
t.equal( isUint32Array( s.seed ), true, 'has property' );
t.equal( s.seed[ 0 ], 12345, 'equal to provided seed' );
s = randomStream( 3.0, {
'seed': 12345,
'prng': minstd.normalized
});
t.equal( s.seed, null, 'equal to `null`' );
t.end();
});
tape( 'attached to the returned stream is the generator seed (array seed)', function test( t ) {
var actual;
var seed;
var s;
var i;
seed = [ 1234, 5678 ];
s = randomStream( 3.0, {
'seed': seed
});
actual = s.seed;
t.equal( isUint32Array( actual ), true, 'has property' );
for ( i = 0; i < seed.length; i++ ) {
t.equal( actual[ i ], seed[ i ], 'returns expected value for word '+i );
}
t.end();
});
tape( 'attached to the returned stream is the generator seed length', function test( t ) {
var s = randomStream( 3.0 );
t.equal( typeof s.seedLength, 'number', 'has property' );
s = randomStream( 3.0, {
'prng': minstd.normalized
});
t.equal( s.seedLength, null, 'equal to `null`' );
t.end();
});
tape( 'attached to the returned stream is the generator state', function test( t ) {
var s = randomStream( 3.0 );
t.equal( isUint32Array( s.state ), true, 'has property' );
s = randomStream( 3.0, {
'prng': minstd.normalized
});
t.equal( s.state, null, 'equal to `null`' );
t.end();
});
tape( 'attached to the returned stream is the generator state length', function test( t ) {
var s = randomStream( 3.0 );
t.equal( typeof s.stateLength, 'number', 'has property' );
s = randomStream( 3.0, {
'prng': minstd.normalized
});
t.equal( s.stateLength, null, 'equal to `null`' );
t.end();
});
tape( 'attached to the returned stream is the generator state size', function test( t ) {
var s = randomStream( 3.0 );
t.equal( typeof s.byteLength, 'number', 'has property' );
s = randomStream( 3.0, {
'prng': minstd.normalized
});
t.equal( s.byteLength, null, 'equal to `null`' );
t.end();
});
tape( 'the constructor returns a stream for generating pseudorandom numbers from a Poisson distribution', function test( t ) {
var iStream;
var result;
var rand;
var opts;
var s;
// Note: we assume that the underlying generator is the following PRNG...
rand = poisson( 3.0, {
'seed': 12345
});
opts = {
'seed': 12345,
'iter': 10,
'sep': '\n'
};
s = randomStream( 3.0, opts );
s.on( 'end', onEnd );
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect );
result = '';
s.pipe( iStream );
function inspect( chunk ) {
t.equal( isBuffer( chunk ), true, 'returns a buffer' );
result += chunk.toString();
}
function onEnd() {
var i;
t.pass( 'stream ended' );
result = result.split( '\n' );
t.equal( result.length, 10, 'has expected length' );
for ( i = 0; i < result.length; i++ ) {
t.equal( parseFloat( result[ i ] ), rand(), 'returns expected value. i: ' + i + '.' );
}
t.end();
}
});
tape( 'the constructor returns a stream for generating pseudorandom numbers from a Poisson distribution (object mode)', function test( t ) {
var iStream;
var count;
var rand;
var opts;
var s;
// Note: we assume that the underlying generator is the following PRNG...
rand = poisson( 3.0, {
'seed': 12345
});
opts = {
'seed': 12345,
'objectMode': true
};
s = randomStream( 3.0, opts );
s.on( 'close', onClose );
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect );
count = 0;
s.pipe( iStream );
function inspect( v ) {
count += 1;
t.equal( rand(), v, 'returns expected value. i: '+count+'.' );
if ( count >= 10 ) {
s.destroy();
}
}
function onClose() {
t.pass( 'stream closed' );
t.end();
}
});
tape( 'the constructor supports limiting the number of iterations', function test( t ) {
var iStream;
var count;
var niter;
var opts;
var s;
niter = 10;
count = 0;
opts = {
'iter': niter,
'objectMode': true
};
s = randomStream( 3.0, opts );
s.on( 'end', onEnd );
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect );
s.pipe( iStream );
function inspect( v ) {
count += 1;
t.equal( typeof v, 'number', 'returns expected value' );
}
function onEnd() {
t.equal( count === niter, true, 'performs expected number of iterations' );
t.end();
}
});
tape( 'by default, the constructor generates newline-delimited pseudorandom numbers', function test( t ) {
var iStream;
var result;
var opts;
var s;
opts = {
'iter': 10
};
s = randomStream( 3.0, opts );
s.on( 'end', onEnd );
iStream = inspectStream( inspect );
result = '';
s.pipe( iStream );
function inspect( chunk ) {
result += chunk.toString();
}
function onEnd() {
var v;
var i;
result = result.split( '\n' );
t.equal( result.length, opts.iter, 'has expected length' );
for ( i = 0; i < result.length; i++ ) {
v = parseFloat( result[ i ] );
t.equal( typeof v, 'number', 'returns expected value' );
t.equal( isnan( v ), false, 'is not NaN' );
}
t.end();
}
});
tape( 'the constructor supports providing a custom separator for streamed values', function test( t ) {
var iStream;
var result;
var opts;
var s;
opts = {
'iter': 10,
'sep': '--++--'
};
s = randomStream( 3.0, opts );
s.on( 'end', onEnd );
iStream = inspectStream( inspect );
result = '';
s.pipe( iStream );
function inspect( chunk ) {
result += chunk.toString();
}
function onEnd() {
var v;
var i;
result = result.split( opts.sep );
t.equal( result.length, opts.iter, 'has expected length' );
for ( i = 0; i < result.length; i++ ) {
v = parseFloat( result[ i ] );
t.equal( typeof v, 'number', 'returns expected value' );
t.equal( isnan( v ), false, 'is not NaN' );
}
t.end();
}
});
tape( 'the constructor supports returning a seeded readable stream', function test( t ) {
var iStream;
var opts;
var seed;
var arr;
var s1;
var s2;
var i;
seed = now();
opts = {
'objectMode': true,
'seed': seed,
'iter': 10
};
s1 = randomStream( 3.0, opts );
s1.on( 'end', onEnd1 );
s2 = randomStream( 3.0, opts );
s2.on( 'end', onEnd2 );
t.notEqual( s1, s2, 'separate streams' );
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect1 );
arr = [];
i = 0;
s1.pipe( iStream );
function inspect1( v ) {
arr.push( v );
}
function onEnd1() {
var iStream;
var opts;
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect2 );
s2.pipe( iStream );
}
function inspect2( v ) {
t.equal( v, arr[ i ], 'returns expected value' );
i += 1;
}
function onEnd2() {
t.end();
}
});
tape( 'the constructor supports specifying the underlying PRNG', function test( t ) {
var iStream;
var opts;
var s;
opts = {
'prng': minstd.normalized,
'objectMode': true,
'iter': 10
};
s = randomStream( 3.0, opts );
s.on( 'end', onEnd );
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect );
s.pipe( iStream );
function inspect( v ) {
t.equal( typeof v, 'number', 'returns a number' );
}
function onEnd() {
t.end();
}
});
tape( 'the constructor supports providing a seeded underlying PRNG', function test( t ) {
var iStream1;
var iStream2;
var randu;
var seed;
var opts;
var FLG;
var s1;
var s2;
var r1;
var r2;
seed = now();
randu = minstd.factory({
'seed': seed
});
opts = {
'prng': randu.normalized,
'objectMode': true,
'iter': 10
};
s1 = randomStream( 3.0, opts );
s1.on( 'end', onEnd );
randu = minstd.factory({
'seed': seed
});
opts = {
'prng': randu.normalized,
'objectMode': true,
'iter': 10
};
s2 = randomStream( 3.0, opts );
s2.on( 'end', onEnd );
t.notEqual( s1, s2, 'separate streams' );
opts = {
'objectMode': true
};
iStream1 = inspectStream( opts, inspect1 );
iStream2 = inspectStream( opts, inspect2 );
r1 = [];
r2 = [];
s1.pipe( iStream1 );
s2.pipe( iStream2 );
function inspect1( v ) {
r1.push( v );
}
function inspect2( v ) {
r2.push( v );
}
function onEnd() {
if ( FLG ) {
t.deepEqual( r1, r2, 'streams expected values' );
return t.end();
}
FLG = true;
}
});
tape( 'the constructor supports specifying the underlying generator state', function test( t ) {
var iStream;
var state;
var count;
var opts;
var arr;
var s;
opts = {
'objectMode': true,
'iter': 10,
'siter': 5
};
s = randomStream( 3.0, opts );
s.on( 'state', onState );
s.on( 'end', onEnd1 );
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect1 );
count = 0;
arr = [];
// Move to a future state...
s.pipe( iStream );
function onState( s ) {
// Only capture the first emitted state...
if ( !state ) {
state = s;
}
}
function inspect1( v ) {
count += 1;
if ( count > 5 ) {
arr.push( v );
}
}
function onEnd1() {
var iStream;
var opts;
var s;
t.pass( 'first stream ended' );
// Create another stream using the captured state:
opts = {
'objectMode': true,
'iter': 5,
'state': state
};
s = randomStream( 3.0, opts );
s.on( 'end', onEnd2 );
t.deepEqual( state, s.state, 'same state' );
// Create a new inspect stream:
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect2 );
// Replay previously generated values...
count = 0;
s.pipe( iStream );
}
function inspect2( v ) {
count += 1;
t.equal( v, arr[ count-1 ], 'returns expected value. i: '+(count-1)+'.' );
}
function onEnd2() {
t.pass( 'second stream ended' );
t.end();
}
});
tape( 'the constructor supports specifying a shared underlying generator state', function test( t ) {
var iStream;
var shared;
var state;
var count;
var opts;
var arr;
var s;
opts = {
'objectMode': true,
'iter': 10,
'siter': 4
};
s = randomStream( 3.0, opts );
s.on( 'state', onState );
s.on( 'end', onEnd1 );
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect1 );
count = 0;
arr = [];
// Move to a future state...
s.pipe( iStream );
function onState( s ) {
// Only capture the first emitted state...
if ( !state ) {
state = s;
// Create a copy of the state (to prevent mutation) which will be shared by more than one PRNG:
shared = new Uint32Array( state );
}
}
function inspect1( v ) {
count += 1;
if ( count > 4 ) {
arr.push( v );
}
}
function onEnd1() {
var iStream;
var opts;
var s;
t.pass( 'first stream ended' );
// Create another stream using the captured state:
opts = {
'objectMode': true,
'iter': 3,
'state': shared,
'copy': false
};
s = randomStream( 3.0, opts );
s.on( 'end', onEnd2 );
t.deepEqual( state, s.state, 'same state' );
// Create a new inspect stream:
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect2 );
// Replay previously generated values...
count = 0;
s.pipe( iStream );
}
function inspect2( v ) {
count += 1;
t.equal( v, arr[ count-1 ], 'returns expected value. i: '+(count-1)+'.' );
}
function onEnd2() {
var iStream;
var opts;
var s;
t.pass( 'second stream ended' );
// Create another stream using the captured state:
opts = {
'objectMode': true,
'iter': 3,
'state': shared,
'copy': false
};
s = randomStream( 3.0, opts );
s.on( 'end', onEnd3 );
t.notDeepEqual( state, s.state, 'different state' );
// Create a new inspect stream:
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect3 );
// Continue replaying previously generated values...
s.pipe( iStream );
}
function inspect3( v ) {
count += 1;
t.equal( v, arr[ count-1 ], 'returns expected value. i: '+(count-1)+'.' );
}
function onEnd3() {
t.pass( 'third stream ended' );
t.end();
}
});
tape( 'the returned stream supports setting the underlying generator state', function test( t ) {
var iStream;
var state;
var rand;
var opts;
var arr;
var s;
var i;
rand = poisson( 3.0 );
// Move to a future state...
for ( i = 0; i < 5; i++ ) {
rand();
}
// Capture the current state:
state = rand.state;
// Move to a future state...
arr = [];
for ( i = 0; i < 5; i++ ) {
arr.push( rand() );
}
// Create a random stream:
opts = {
'objectMode': true,
'iter': 5
};
s = randomStream( 3.0, opts );
s.on( 'end', onEnd );
// Set the PRNG state:
s.state = state;
// Create a new inspect stream:
opts = {
'objectMode': true
};
iStream = inspectStream( opts, inspect );
// Replay previously generated values:
i = 0;
s.pipe( iStream );
function inspect( v ) {
t.equal( v, arr[ i ], 'returns expected value. i: ' + i + '.' );
i += 1;
}
function onEnd() {
t.end();
}
});
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/random/streams/poisson/test/test.main.js
|
JavaScript
|
apache-2.0
| 21,863
|
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../殴/index.html">
<meta http-equiv=refresh content="0; url='../殴/index.html'">
<h1>Redirecting...</h1>
<a href="../殴/index.html">Click here if you are not redirected.</a>
<script>location='../殴/index.html'</script>
|
hochanh/hochanh.github.io
|
rtk/v4/1698.html
|
HTML
|
apache-2.0
| 316
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#ifndef GB_STDIO_H
#define GB_STDIO_H
/*this file, if included instead of <stdio.h> has the following functionality:
1) if GB_STDIO_INTERCEPT is defined then
a) some of the stdio.h symbols shall be redefined, for example: fopen => gb_fopen
b) all "code" using the fopen will actually (because of the preprocessor) call to gb_fopen
c) gb_fopen shall blindly call into fopen, thus realizing a passthrough
reason is: unittesting. fopen is comes with the C Run Time and cannot be mocked (that is, in the global namespace cannot exist a function called fopen
2) if GB_STDIO_INTERCEPT is not defined then
a) it shall include <stdio.h> => no passthrough, just direct linking.
*/
#ifndef GB_STDIO_INTERCEPT
#include <stdio.h>
#else
/*source level intercepting of function calls*/
#define fopen fopen_never_called_never_implemented_always_forgotten
#define fclose fclose_never_called_never_implemented_always_forgotten
#define fseek fseek_never_called_never_implemented_always_forgotten
#define ftell ftell_never_called_never_implemented_always_forgotten
#define fprintf fprintf_never_called_never_implemented_always_forgotten
#include "azure_c_shared_utility/umock_c_prod.h"
#ifdef __cplusplus
#include <cstdio.h>
extern "C"
{
#else
#include <stdio.h>
#endif
#undef fopen
#define fopen gb_fopen
MOCKABLE_FUNCTION(, FILE*, gb_fopen, const char*, filename, const char*, mode);
#undef fclose
#define fclose gb_fclose
MOCKABLE_FUNCTION(, int, fclose, FILE *, stream);
#undef fseek
#define fseek gb_fseek
MOCKABLE_FUNCTION(, int, fseek, FILE *,stream, long int, offset, int, whence);
#undef ftell
#define ftell gb_ftell
MOCKABLE_FUNCTION(, long int, ftell, FILE *, stream);
#undef fprintf
#define fprintf gb_fprintf
extern int fprintf(FILE * stream, const char * format, ...);
#ifdef __cplusplus
}
#endif
#endif /*GB_STDIO_INTERCEPT*/
#endif /* GB_STDIO_H */
|
maxpeng/mbedos_iothub_client_sample_mqtt
|
azure_c_shared_utility/gb_stdio.h
|
C
|
apache-2.0
| 2,156
|
// Copyright (C) 2016 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.google.gerrit.extensions.api.changes;
/** Output options available for submitted_together requests. */
public enum SubmittedTogetherOption {
NON_VISIBLE_CHANGES,
TOPIC_CLOSURE;
}
|
GerritCodeReview/gerrit
|
java/com/google/gerrit/extensions/api/changes/SubmittedTogetherOption.java
|
Java
|
apache-2.0
| 805
|
// Copyright (C) 2010 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.google.gerrit.server.git.receive;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.entities.Account;
import com.google.gerrit.entities.PatchSet;
import com.google.gerrit.entities.Project;
import com.google.gerrit.entities.RefNames;
import com.google.gerrit.exceptions.StorageException;
import com.google.gerrit.index.query.Predicate;
import com.google.gerrit.server.git.HookUtil;
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gerrit.server.query.change.ChangePredicates;
import com.google.gerrit.server.query.change.ChangeStatusPredicate;
import com.google.gerrit.server.query.change.InternalChangeQuery;
import com.google.gerrit.server.util.MagicBranch;
import com.google.inject.Provider;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.AdvertiseRefsHook;
import org.eclipse.jgit.transport.ReceivePack;
import org.eclipse.jgit.transport.ServiceMayNotContinueException;
import org.eclipse.jgit.transport.UploadPack;
/**
* Exposes only the non refs/changes/ reference names and provide additional haves.
*
* <p>Negotiation on Git push is suboptimal in that it tends to send more objects to the server than
* it should. This results in increased latencies for {@code git push}.
*
* <p>Ref advertisement for Git pushes still works in a "the server speaks first fashion" as Git
* Protocol V2 only addressed fetches Therefore the server needs to send all available references.
* For large repositories, this can be in the tens of megabytes to send to the client. We therefore
* remove all refs in refs/changes/* to scale down that footprint. Trivially, this would increase
* the unnecessary objects that the client has to send to the server because the common ancestor it
* finds in negotiation might be further back in history.
*
* <p>To work around this, we advertise the last 32 changes in that repository as additional {@code
* .haves}. This is a heuristical approach that aims at scaling down the number of unnecessary
* objects that client sends to the server. Unnecessary here refers to objects that the server
* already has.
*
* <p>TODO(hiesel): Instrument this heuristic and proof its value.
*/
public class ReceiveCommitsAdvertiseRefsHook implements AdvertiseRefsHook {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final Provider<InternalChangeQuery> queryProvider;
private final Project.NameKey projectName;
private final Account.Id user;
public ReceiveCommitsAdvertiseRefsHook(
Provider<InternalChangeQuery> queryProvider, Project.NameKey projectName, Account.Id user) {
this.queryProvider = queryProvider;
this.projectName = projectName;
this.user = user;
}
@Override
public void advertiseRefs(UploadPack us) {
throw new UnsupportedOperationException(
"ReceiveCommitsAdvertiseRefsHook cannot be used for UploadPack");
}
@Override
public void advertiseRefs(ReceivePack rp) throws ServiceMayNotContinueException {
Map<String, Ref> advertisedRefs = HookUtil.ensureAllRefsAdvertised(rp);
advertisedRefs.keySet().stream()
.filter(ReceiveCommitsAdvertiseRefsHook::skip)
.collect(toImmutableList())
.forEach(r -> advertisedRefs.remove(r));
try {
rp.setAdvertisedRefs(advertisedRefs, advertiseOpenChanges(rp.getRepository()));
} catch (IOException e) {
throw new ServiceMayNotContinueException(e);
}
}
private Set<ObjectId> advertiseOpenChanges(Repository repo)
throws ServiceMayNotContinueException {
// Advertise the user's most recent open changes. It's likely that the user has one of these in
// their local repo and they can serve as starting points to figure out the common ancestor of
// what the client and server have in common.
int limit = 32;
try {
Set<ObjectId> r = Sets.newHashSetWithExpectedSize(limit);
for (ChangeData cd :
queryProvider
.get()
.setRequestedFields(
// Required for ChangeIsVisibleToPrdicate.
ChangeField.CHANGE,
ChangeField.REVIEWER,
// Required during advertiseOpenChanges.
ChangeField.PATCH_SET)
.enforceVisibility(true)
.setLimit(limit)
.query(
Predicate.and(
ChangePredicates.project(projectName),
ChangeStatusPredicate.open(),
ChangePredicates.owner(user)))) {
PatchSet ps = cd.currentPatchSet();
if (ps != null) {
// Ensure we actually observed a patch set ref pointing to this
// object, in case the database is out of sync with the repo and the
// object doesn't actually exist.
try {
Ref psRef = repo.getRefDatabase().exactRef(RefNames.patchSetRef(ps.id()));
if (psRef != null) {
r.add(ps.commitId());
}
} catch (IOException e) {
throw new ServiceMayNotContinueException(e);
}
}
}
return r;
} catch (StorageException err) {
logger.atSevere().withCause(err).log("Cannot list open changes of %s", projectName);
return Collections.emptySet();
}
}
private static boolean skip(String name) {
return name.startsWith(RefNames.REFS_CHANGES)
|| name.startsWith(RefNames.REFS_CACHE_AUTOMERGE)
|| MagicBranch.isMagicBranch(name);
}
}
|
GerritCodeReview/gerrit
|
java/com/google/gerrit/server/git/receive/ReceiveCommitsAdvertiseRefsHook.java
|
Java
|
apache-2.0
| 6,482
|
var User = require('../source/models/User').model;
var mongoose = require('../lib/mongoose');
var logger = require('../lib/logging').logger;
var list = require('./mocks/users');
exports.testAddUser = function(test){
var length = list.length;
for(var i=0; i<length; i++){
var item = list[i];
logger.info( 'User-index ' + i + ' : ' +JSON.stringify(item) );
var user = new User(item);
user.save(function(err){
if(err){
logger.error('Fail to save user: '+err);
}
else{
logger.info('succeed to save user ' + user.username);
}
});
}
test.done();
};
exports.testLoadUser = function(test){
User.find({'_id': 0}, function(err, docs){
if(err){
logger.error('Fail to find: '+err);
return;
}
test.equals(docs.length, 0);
test.equals(docs[0].username, 'henryleu');
});
test.done();
};
|
tomatolabs/frankon
|
test/user.js
|
JavaScript
|
apache-2.0
| 976
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PhpMvcUploader.Core.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PhpMvcUploader.Core.Test")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0b476b31-a223-41c2-b80a-f3780bca2c58")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
skewwhiffy/PhpMvcUploader
|
PhpMvcUploader.Core.Test/Properties/AssemblyInfo.cs
|
C#
|
apache-2.0
| 1,424
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="inc/style.css"/>
<title>J2EP Manual</title>
</head>
<body>
<div id="helasidan">
<div id="meny">
<ul>
<li><a href="install.html">Install</a></li>
<li><a href="configuration.html">Configuration</a>
<ul>
<li><a href="rules.html">Rules</a></li>
<li><a href="servers.html">Servers</a></li>
<li><a href="rewrite.html">Rewriting</a></li>
<li><a href="logging.html">Logging</a></li>
</ul>
</li>
<li><a href="examples.html">Examples</a></li>
<li>Misc
<ul>
<li><a href="faq.html">FAQ</a></li>
<li><a href="future_features.html">The future</a></li>
<li><a href="license.html">License</a></li>
</ul>
</li>
<li>Current release
<ul>
<li><a href="changelog.html">Changelog</a></li>
<li><a href="release-notes.html">Release notes</a></li>
</ul>
</li>
</ul>
</div>
<div id="text">
<h1>Servers</h1>
<h2>BaseServer</h2>
<p>
The BaseServer marks which host name and path we want to proxy.
We can configure the server with the parameters <em>domainName</em> and
<em>path</em>.
</p>
<h3>Parameters</h3>
<h4>domainName</h4>
<h5>
REQUIRED
</h5>
<p>
The domain name this server should be proxying to, it can include a port.
</p>
<h4>path</h4>
<h5>
<br />
</h5>
<p>
Will mark the path on the server we are mapping to.
</p>
<h4>isRewriting</h4>
<h5>
Default: false
<br />
</h5>
<p>
Mark if absolute links matching this server should be rewritten.
</p>
<h3>Example</h3>
<p class="code">
<server className="net.sf.j2ep.servers.BaseServer"
domainName="www.nytimes.com"
isRewriting="true">
<rule className="net.sf.j2ep.rules.DirectoryRule"
directory="/news"
/>
</server>
</p>
<h2>RoundRobinCluster</h2>
<p>
The RoundRobinCluster contains numerous servers and will
choose which server to proxy to separate for each request in a round-robin fashion.
If a server starts a session the proxy will make
sure that when a request is made to the server, with the same session id, the
server that created the session is the one that will receive the
request.
</p>
<h2>Parameters</h2>
<p>There are multiple servers objects in the RoundRobinCluster, each of
them have the following parameters</p>
<h4>domainName</h4>
<h5>
REQUIRED
</h5>
<p>
The domain name that can include a port this server should be proxying to
</p>
<h4>path</h4>
<h5>
<br />
</h5>
<p>
Will mark the path on the server we are mapping to.
</p>
<h3>Example</h3>
<p class="code">
<cluster-server className="net.sf.j2ep.servers.RoundRobinCluster">
<server
domainName="internal1.company.com"
path="/somepath"
/>
<server
domainName="internal2.company.com"
path="/otherpath"
/>
<rule className="net.sf.j2ep.rules.DirectoryRule"
directory="/cluster"
/>
</cluster-server>
</p>
<p>
Note that the RoundRobinCluster uses the element <em>cluster-server</em>
instead of the normal <em>server</em>.
</p><div id="footer">
<a href="http://www.sourceforge.net/projects/j2ep">http://www.sourceforge.net/projects/j2ep</a>
</div>
</div>
</div>
<div id="sf">
<a href="http://sourceforge.net"><img src="http://sourceforge.net/sflogo.php?group_id=144132&type=5" alt="SourceForge.net Logo" /></a>
</div>
</body>
</html>
|
jacarrichan/j2ep
|
docs/servers.html
|
HTML
|
apache-2.0
| 3,532
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>ScanWildcardColumnTracker xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />
</head>
<body>
<div id="overview"><a href="../../../../../../apidocs/org/apache/hadoop/hbase/regionserver/ScanWildcardColumnTracker.html">View Javadoc</a></div><pre>
<a class="jxr_linenumber" name="1" href="#1">1</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="2" href="#2">2</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="3" href="#3">3</a> <em class="jxr_javadoccomment"> * Licensed to the Apache Software Foundation (ASF) under one</em>
<a class="jxr_linenumber" name="4" href="#4">4</a> <em class="jxr_javadoccomment"> * or more contributor license agreements. See the NOTICE file</em>
<a class="jxr_linenumber" name="5" href="#5">5</a> <em class="jxr_javadoccomment"> * distributed with this work for additional information</em>
<a class="jxr_linenumber" name="6" href="#6">6</a> <em class="jxr_javadoccomment"> * regarding copyright ownership. The ASF licenses this file</em>
<a class="jxr_linenumber" name="7" href="#7">7</a> <em class="jxr_javadoccomment"> * to you under the Apache License, Version 2.0 (the</em>
<a class="jxr_linenumber" name="8" href="#8">8</a> <em class="jxr_javadoccomment"> * "License"); you may not use this file except in compliance</em>
<a class="jxr_linenumber" name="9" href="#9">9</a> <em class="jxr_javadoccomment"> * with the License. You may obtain a copy of the License at</em>
<a class="jxr_linenumber" name="10" href="#10">10</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="11" href="#11">11</a> <em class="jxr_javadoccomment"> * <a href="http://www.apache.org/licenses/LICENSE-2.0" target="alexandria_uri">http://www.apache.org/licenses/LICENSE-2.0</a></em>
<a class="jxr_linenumber" name="12" href="#12">12</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="13" href="#13">13</a> <em class="jxr_javadoccomment"> * Unless required by applicable law or agreed to in writing, software</em>
<a class="jxr_linenumber" name="14" href="#14">14</a> <em class="jxr_javadoccomment"> * distributed under the License is distributed on an "AS IS" BASIS,</em>
<a class="jxr_linenumber" name="15" href="#15">15</a> <em class="jxr_javadoccomment"> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</em>
<a class="jxr_linenumber" name="16" href="#16">16</a> <em class="jxr_javadoccomment"> * See the License for the specific language governing permissions and</em>
<a class="jxr_linenumber" name="17" href="#17">17</a> <em class="jxr_javadoccomment"> * limitations under the License.</em>
<a class="jxr_linenumber" name="18" href="#18">18</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="19" href="#19">19</a>
<a class="jxr_linenumber" name="20" href="#20">20</a> <strong class="jxr_keyword">package</strong> org.apache.hadoop.hbase.regionserver;
<a class="jxr_linenumber" name="21" href="#21">21</a>
<a class="jxr_linenumber" name="22" href="#22">22</a> <strong class="jxr_keyword">import</strong> java.io.IOException;
<a class="jxr_linenumber" name="23" href="#23">23</a>
<a class="jxr_linenumber" name="24" href="#24">24</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.classification.InterfaceAudience;
<a class="jxr_linenumber" name="25" href="#25">25</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.HConstants;
<a class="jxr_linenumber" name="26" href="#26">26</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.KeyValue;
<a class="jxr_linenumber" name="27" href="#27">27</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.regionserver.ScanQueryMatcher.MatchCode;
<a class="jxr_linenumber" name="28" href="#28">28</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.util.Bytes;
<a class="jxr_linenumber" name="29" href="#29">29</a>
<a class="jxr_linenumber" name="30" href="#30">30</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="31" href="#31">31</a> <em class="jxr_javadoccomment"> * Keeps track of the columns for a scan if they are not explicitly specified</em>
<a class="jxr_linenumber" name="32" href="#32">32</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="33" href="#33">33</a> @InterfaceAudience.Private
<a class="jxr_linenumber" name="34" href="#34">34</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../../org/apache/hadoop/hbase/regionserver/ScanWildcardColumnTracker.html">ScanWildcardColumnTracker</a> <strong class="jxr_keyword">implements</strong> <a href="../../../../../org/apache/hadoop/hbase/regionserver/ColumnTracker.html">ColumnTracker</a> {
<a class="jxr_linenumber" name="35" href="#35">35</a> <strong class="jxr_keyword">private</strong> byte [] columnBuffer = <strong class="jxr_keyword">null</strong>;
<a class="jxr_linenumber" name="36" href="#36">36</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> columnOffset = 0;
<a class="jxr_linenumber" name="37" href="#37">37</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> columnLength = 0;
<a class="jxr_linenumber" name="38" href="#38">38</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> currentCount = 0;
<a class="jxr_linenumber" name="39" href="#39">39</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> maxVersions;
<a class="jxr_linenumber" name="40" href="#40">40</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> minVersions;
<a class="jxr_linenumber" name="41" href="#41">41</a> <em class="jxr_comment">/*<em class="jxr_comment"> Keeps track of the latest timestamp and type included for current column.</em></em>
<a class="jxr_linenumber" name="42" href="#42">42</a> <em class="jxr_comment"> * Used to eliminate duplicates. */</em>
<a class="jxr_linenumber" name="43" href="#43">43</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">long</strong> latestTSOfCurrentColumn;
<a class="jxr_linenumber" name="44" href="#44">44</a> <strong class="jxr_keyword">private</strong> byte latestTypeOfCurrentColumn;
<a class="jxr_linenumber" name="45" href="#45">45</a>
<a class="jxr_linenumber" name="46" href="#46">46</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">long</strong> oldestStamp;
<a class="jxr_linenumber" name="47" href="#47">47</a>
<a class="jxr_linenumber" name="48" href="#48">48</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="49" href="#49">49</a> <em class="jxr_javadoccomment"> * Return maxVersions of every row.</em>
<a class="jxr_linenumber" name="50" href="#50">50</a> <em class="jxr_javadoccomment"> * @param minVersion Minimum number of versions to keep</em>
<a class="jxr_linenumber" name="51" href="#51">51</a> <em class="jxr_javadoccomment"> * @param maxVersion Maximum number of versions to return</em>
<a class="jxr_linenumber" name="52" href="#52">52</a> <em class="jxr_javadoccomment"> * @param oldestUnexpiredTS oldest timestamp that has not expired according</em>
<a class="jxr_linenumber" name="53" href="#53">53</a> <em class="jxr_javadoccomment"> * to the TTL.</em>
<a class="jxr_linenumber" name="54" href="#54">54</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="55" href="#55">55</a> <strong class="jxr_keyword">public</strong> <a href="../../../../../org/apache/hadoop/hbase/regionserver/ScanWildcardColumnTracker.html">ScanWildcardColumnTracker</a>(<strong class="jxr_keyword">int</strong> minVersion, <strong class="jxr_keyword">int</strong> maxVersion,
<a class="jxr_linenumber" name="56" href="#56">56</a> <strong class="jxr_keyword">long</strong> oldestUnexpiredTS) {
<a class="jxr_linenumber" name="57" href="#57">57</a> <strong class="jxr_keyword">this</strong>.maxVersions = maxVersion;
<a class="jxr_linenumber" name="58" href="#58">58</a> <strong class="jxr_keyword">this</strong>.minVersions = minVersion;
<a class="jxr_linenumber" name="59" href="#59">59</a> <strong class="jxr_keyword">this</strong>.oldestStamp = oldestUnexpiredTS;
<a class="jxr_linenumber" name="60" href="#60">60</a> }
<a class="jxr_linenumber" name="61" href="#61">61</a>
<a class="jxr_linenumber" name="62" href="#62">62</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="63" href="#63">63</a> <em class="jxr_javadoccomment"> * {@inheritDoc}</em>
<a class="jxr_linenumber" name="64" href="#64">64</a> <em class="jxr_javadoccomment"> * This receives puts *and* deletes.</em>
<a class="jxr_linenumber" name="65" href="#65">65</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="66" href="#66">66</a> @Override
<a class="jxr_linenumber" name="67" href="#67">67</a> <strong class="jxr_keyword">public</strong> <a href="../../../../../org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.html">MatchCode</a> checkColumn(byte[] bytes, <strong class="jxr_keyword">int</strong> offset, <strong class="jxr_keyword">int</strong> length, byte type)
<a class="jxr_linenumber" name="68" href="#68">68</a> <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="69" href="#69">69</a> <strong class="jxr_keyword">return</strong> MatchCode.INCLUDE;
<a class="jxr_linenumber" name="70" href="#70">70</a> }
<a class="jxr_linenumber" name="71" href="#71">71</a>
<a class="jxr_linenumber" name="72" href="#72">72</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="73" href="#73">73</a> <em class="jxr_javadoccomment"> * {@inheritDoc}</em>
<a class="jxr_linenumber" name="74" href="#74">74</a> <em class="jxr_javadoccomment"> * This receives puts *and* deletes. Deletes do not count as a version, but rather</em>
<a class="jxr_linenumber" name="75" href="#75">75</a> <em class="jxr_javadoccomment"> * take the version of the previous put (so eventually all but the last can be reclaimed).</em>
<a class="jxr_linenumber" name="76" href="#76">76</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="77" href="#77">77</a> @Override
<a class="jxr_linenumber" name="78" href="#78">78</a> <strong class="jxr_keyword">public</strong> ScanQueryMatcher.MatchCode checkVersions(byte[] bytes, <strong class="jxr_keyword">int</strong> offset, <strong class="jxr_keyword">int</strong> length,
<a class="jxr_linenumber" name="79" href="#79">79</a> <strong class="jxr_keyword">long</strong> timestamp, byte type, <strong class="jxr_keyword">boolean</strong> ignoreCount) <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="80" href="#80">80</a>
<a class="jxr_linenumber" name="81" href="#81">81</a> <strong class="jxr_keyword">if</strong> (columnBuffer == <strong class="jxr_keyword">null</strong>) {
<a class="jxr_linenumber" name="82" href="#82">82</a> <em class="jxr_comment">// first iteration.</em>
<a class="jxr_linenumber" name="83" href="#83">83</a> resetBuffer(bytes, offset, length);
<a class="jxr_linenumber" name="84" href="#84">84</a> <strong class="jxr_keyword">if</strong> (ignoreCount) <strong class="jxr_keyword">return</strong> ScanQueryMatcher.MatchCode.INCLUDE;
<a class="jxr_linenumber" name="85" href="#85">85</a> <em class="jxr_comment">// do not count a delete marker as another version</em>
<a class="jxr_linenumber" name="86" href="#86">86</a> <strong class="jxr_keyword">return</strong> checkVersion(type, timestamp);
<a class="jxr_linenumber" name="87" href="#87">87</a> }
<a class="jxr_linenumber" name="88" href="#88">88</a> <strong class="jxr_keyword">int</strong> cmp = Bytes.compareTo(bytes, offset, length,
<a class="jxr_linenumber" name="89" href="#89">89</a> columnBuffer, columnOffset, columnLength);
<a class="jxr_linenumber" name="90" href="#90">90</a> <strong class="jxr_keyword">if</strong> (cmp == 0) {
<a class="jxr_linenumber" name="91" href="#91">91</a> <strong class="jxr_keyword">if</strong> (ignoreCount) <strong class="jxr_keyword">return</strong> ScanQueryMatcher.MatchCode.INCLUDE;
<a class="jxr_linenumber" name="92" href="#92">92</a>
<a class="jxr_linenumber" name="93" href="#93">93</a> <em class="jxr_comment">//If column matches, check if it is a duplicate timestamp</em>
<a class="jxr_linenumber" name="94" href="#94">94</a> <strong class="jxr_keyword">if</strong> (sameAsPreviousTSAndType(timestamp, type)) {
<a class="jxr_linenumber" name="95" href="#95">95</a> <strong class="jxr_keyword">return</strong> ScanQueryMatcher.MatchCode.SKIP;
<a class="jxr_linenumber" name="96" href="#96">96</a> }
<a class="jxr_linenumber" name="97" href="#97">97</a> <strong class="jxr_keyword">return</strong> checkVersion(type, timestamp);
<a class="jxr_linenumber" name="98" href="#98">98</a> }
<a class="jxr_linenumber" name="99" href="#99">99</a>
<a class="jxr_linenumber" name="100" href="#100">100</a> resetTSAndType();
<a class="jxr_linenumber" name="101" href="#101">101</a>
<a class="jxr_linenumber" name="102" href="#102">102</a> <em class="jxr_comment">// new col > old col</em>
<a class="jxr_linenumber" name="103" href="#103">103</a> <strong class="jxr_keyword">if</strong> (cmp > 0) {
<a class="jxr_linenumber" name="104" href="#104">104</a> <em class="jxr_comment">// switched columns, lets do something.x</em>
<a class="jxr_linenumber" name="105" href="#105">105</a> resetBuffer(bytes, offset, length);
<a class="jxr_linenumber" name="106" href="#106">106</a> <strong class="jxr_keyword">if</strong> (ignoreCount) <strong class="jxr_keyword">return</strong> ScanQueryMatcher.MatchCode.INCLUDE;
<a class="jxr_linenumber" name="107" href="#107">107</a> <strong class="jxr_keyword">return</strong> checkVersion(type, timestamp);
<a class="jxr_linenumber" name="108" href="#108">108</a> }
<a class="jxr_linenumber" name="109" href="#109">109</a>
<a class="jxr_linenumber" name="110" href="#110">110</a> <em class="jxr_comment">// new col < oldcol</em>
<a class="jxr_linenumber" name="111" href="#111">111</a> <em class="jxr_comment">// WARNING: This means that very likely an edit for some other family</em>
<a class="jxr_linenumber" name="112" href="#112">112</a> <em class="jxr_comment">// was incorrectly stored into the store for this one. Throw an exception,</em>
<a class="jxr_linenumber" name="113" href="#113">113</a> <em class="jxr_comment">// because this might lead to data corruption.</em>
<a class="jxr_linenumber" name="114" href="#114">114</a> <strong class="jxr_keyword">throw</strong> <strong class="jxr_keyword">new</strong> IOException(
<a class="jxr_linenumber" name="115" href="#115">115</a> <span class="jxr_string">"ScanWildcardColumnTracker.checkColumn ran into a column actually "</span> +
<a class="jxr_linenumber" name="116" href="#116">116</a> <span class="jxr_string">"smaller than the previous column: "</span> +
<a class="jxr_linenumber" name="117" href="#117">117</a> Bytes.toStringBinary(bytes, offset, length));
<a class="jxr_linenumber" name="118" href="#118">118</a> }
<a class="jxr_linenumber" name="119" href="#119">119</a>
<a class="jxr_linenumber" name="120" href="#120">120</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">void</strong> resetBuffer(byte[] bytes, <strong class="jxr_keyword">int</strong> offset, <strong class="jxr_keyword">int</strong> length) {
<a class="jxr_linenumber" name="121" href="#121">121</a> columnBuffer = bytes;
<a class="jxr_linenumber" name="122" href="#122">122</a> columnOffset = offset;
<a class="jxr_linenumber" name="123" href="#123">123</a> columnLength = length;
<a class="jxr_linenumber" name="124" href="#124">124</a> currentCount = 0;
<a class="jxr_linenumber" name="125" href="#125">125</a> }
<a class="jxr_linenumber" name="126" href="#126">126</a>
<a class="jxr_linenumber" name="127" href="#127">127</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="128" href="#128">128</a> <em class="jxr_javadoccomment"> * Check whether this version should be retained.</em>
<a class="jxr_linenumber" name="129" href="#129">129</a> <em class="jxr_javadoccomment"> * There are 4 variables considered:</em>
<a class="jxr_linenumber" name="130" href="#130">130</a> <em class="jxr_javadoccomment"> * If this version is past max versions -> skip it</em>
<a class="jxr_linenumber" name="131" href="#131">131</a> <em class="jxr_javadoccomment"> * If this kv has expired or was deleted, check min versions</em>
<a class="jxr_linenumber" name="132" href="#132">132</a> <em class="jxr_javadoccomment"> * to decide whther to skip it or not.</em>
<a class="jxr_linenumber" name="133" href="#133">133</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="134" href="#134">134</a> <em class="jxr_javadoccomment"> * Increase the version counter unless this is a delete</em>
<a class="jxr_linenumber" name="135" href="#135">135</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="136" href="#136">136</a> <strong class="jxr_keyword">private</strong> <a href="../../../../../org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.html">MatchCode</a> checkVersion(byte type, <strong class="jxr_keyword">long</strong> timestamp) {
<a class="jxr_linenumber" name="137" href="#137">137</a> <strong class="jxr_keyword">if</strong> (!KeyValue.isDelete(type)) {
<a class="jxr_linenumber" name="138" href="#138">138</a> currentCount++;
<a class="jxr_linenumber" name="139" href="#139">139</a> }
<a class="jxr_linenumber" name="140" href="#140">140</a> <strong class="jxr_keyword">if</strong> (currentCount > maxVersions) {
<a class="jxr_linenumber" name="141" href="#141">141</a> <strong class="jxr_keyword">return</strong> ScanQueryMatcher.MatchCode.SEEK_NEXT_COL; <em class="jxr_comment">// skip to next col</em>
<a class="jxr_linenumber" name="142" href="#142">142</a> }
<a class="jxr_linenumber" name="143" href="#143">143</a> <em class="jxr_comment">// keep the KV if required by minversions or it is not expired, yet</em>
<a class="jxr_linenumber" name="144" href="#144">144</a> <strong class="jxr_keyword">if</strong> (currentCount <= minVersions || !isExpired(timestamp)) {
<a class="jxr_linenumber" name="145" href="#145">145</a> setTSAndType(timestamp, type);
<a class="jxr_linenumber" name="146" href="#146">146</a> <strong class="jxr_keyword">return</strong> ScanQueryMatcher.MatchCode.INCLUDE;
<a class="jxr_linenumber" name="147" href="#147">147</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="148" href="#148">148</a> <strong class="jxr_keyword">return</strong> MatchCode.SEEK_NEXT_COL;
<a class="jxr_linenumber" name="149" href="#149">149</a> }
<a class="jxr_linenumber" name="150" href="#150">150</a>
<a class="jxr_linenumber" name="151" href="#151">151</a> }
<a class="jxr_linenumber" name="152" href="#152">152</a>
<a class="jxr_linenumber" name="153" href="#153">153</a> @Override
<a class="jxr_linenumber" name="154" href="#154">154</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> reset() {
<a class="jxr_linenumber" name="155" href="#155">155</a> columnBuffer = <strong class="jxr_keyword">null</strong>;
<a class="jxr_linenumber" name="156" href="#156">156</a> resetTSAndType();
<a class="jxr_linenumber" name="157" href="#157">157</a> }
<a class="jxr_linenumber" name="158" href="#158">158</a>
<a class="jxr_linenumber" name="159" href="#159">159</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">void</strong> resetTSAndType() {
<a class="jxr_linenumber" name="160" href="#160">160</a> latestTSOfCurrentColumn = HConstants.LATEST_TIMESTAMP;
<a class="jxr_linenumber" name="161" href="#161">161</a> latestTypeOfCurrentColumn = 0;
<a class="jxr_linenumber" name="162" href="#162">162</a> }
<a class="jxr_linenumber" name="163" href="#163">163</a>
<a class="jxr_linenumber" name="164" href="#164">164</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">void</strong> setTSAndType(<strong class="jxr_keyword">long</strong> timestamp, byte type) {
<a class="jxr_linenumber" name="165" href="#165">165</a> latestTSOfCurrentColumn = timestamp;
<a class="jxr_linenumber" name="166" href="#166">166</a> latestTypeOfCurrentColumn = type;
<a class="jxr_linenumber" name="167" href="#167">167</a> }
<a class="jxr_linenumber" name="168" href="#168">168</a>
<a class="jxr_linenumber" name="169" href="#169">169</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">boolean</strong> sameAsPreviousTSAndType(<strong class="jxr_keyword">long</strong> timestamp, byte type) {
<a class="jxr_linenumber" name="170" href="#170">170</a> <strong class="jxr_keyword">return</strong> timestamp == latestTSOfCurrentColumn && type == latestTypeOfCurrentColumn;
<a class="jxr_linenumber" name="171" href="#171">171</a> }
<a class="jxr_linenumber" name="172" href="#172">172</a>
<a class="jxr_linenumber" name="173" href="#173">173</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">boolean</strong> isExpired(<strong class="jxr_keyword">long</strong> timestamp) {
<a class="jxr_linenumber" name="174" href="#174">174</a> <strong class="jxr_keyword">return</strong> timestamp < oldestStamp;
<a class="jxr_linenumber" name="175" href="#175">175</a> }
<a class="jxr_linenumber" name="176" href="#176">176</a>
<a class="jxr_linenumber" name="177" href="#177">177</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="178" href="#178">178</a> <em class="jxr_javadoccomment"> * Used by matcher and scan/get to get a hint of the next column</em>
<a class="jxr_linenumber" name="179" href="#179">179</a> <em class="jxr_javadoccomment"> * to seek to after checkColumn() returns SKIP. Returns the next interesting</em>
<a class="jxr_linenumber" name="180" href="#180">180</a> <em class="jxr_javadoccomment"> * column we want, or NULL there is none (wildcard scanner).</em>
<a class="jxr_linenumber" name="181" href="#181">181</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="182" href="#182">182</a> <em class="jxr_javadoccomment"> * @return The column count.</em>
<a class="jxr_linenumber" name="183" href="#183">183</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="184" href="#184">184</a> <strong class="jxr_keyword">public</strong> <a href="../../../../../org/apache/hadoop/hbase/regionserver/ColumnCount.html">ColumnCount</a> getColumnHint() {
<a class="jxr_linenumber" name="185" href="#185">185</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">null</strong>;
<a class="jxr_linenumber" name="186" href="#186">186</a> }
<a class="jxr_linenumber" name="187" href="#187">187</a>
<a class="jxr_linenumber" name="188" href="#188">188</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="189" href="#189">189</a> <em class="jxr_javadoccomment"> * We can never know a-priori if we are done, so always return false.</em>
<a class="jxr_linenumber" name="190" href="#190">190</a> <em class="jxr_javadoccomment"> * @return false</em>
<a class="jxr_linenumber" name="191" href="#191">191</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="192" href="#192">192</a> @Override
<a class="jxr_linenumber" name="193" href="#193">193</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">boolean</strong> done() {
<a class="jxr_linenumber" name="194" href="#194">194</a> <strong class="jxr_keyword">return</strong> false;
<a class="jxr_linenumber" name="195" href="#195">195</a> }
<a class="jxr_linenumber" name="196" href="#196">196</a>
<a class="jxr_linenumber" name="197" href="#197">197</a> <strong class="jxr_keyword">public</strong> <a href="../../../../../org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.html">MatchCode</a> getNextRowOrNextColumn(byte[] bytes, <strong class="jxr_keyword">int</strong> offset,
<a class="jxr_linenumber" name="198" href="#198">198</a> <strong class="jxr_keyword">int</strong> qualLength) {
<a class="jxr_linenumber" name="199" href="#199">199</a> <strong class="jxr_keyword">return</strong> MatchCode.SEEK_NEXT_COL;
<a class="jxr_linenumber" name="200" href="#200">200</a> }
<a class="jxr_linenumber" name="201" href="#201">201</a>
<a class="jxr_linenumber" name="202" href="#202">202</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">boolean</strong> isDone(<strong class="jxr_keyword">long</strong> timestamp) {
<a class="jxr_linenumber" name="203" href="#203">203</a> <strong class="jxr_keyword">return</strong> minVersions <= 0 && isExpired(timestamp);
<a class="jxr_linenumber" name="204" href="#204">204</a> }
<a class="jxr_linenumber" name="205" href="#205">205</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html>
|
lshain/hbase-0.98.6-hadoop2
|
docs/xref/org/apache/hadoop/hbase/regionserver/ScanWildcardColumnTracker.html
|
HTML
|
apache-2.0
| 25,952
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Jun 10 13:52:52 MST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>VaultExpressionConstraintConsumer (BOM: * : All 2.7.0.Final API)</title>
<meta name="date" content="2020-06-10">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="VaultExpressionConstraintConsumer (BOM: * : All 2.7.0.Final API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":18};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/VaultExpressionConstraintConsumer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.7.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraint.html" title="class in org.wildfly.swarm.config.management.access"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintSupplier.html" title="interface in org.wildfly.swarm.config.management.access"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" target="_top">Frames</a></li>
<li><a href="VaultExpressionConstraintConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.wildfly.swarm.config.management.access</div>
<h2 title="Interface VaultExpressionConstraintConsumer" class="title">Interface VaultExpressionConstraintConsumer<T extends <a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraint.html" title="class in org.wildfly.swarm.config.management.access">VaultExpressionConstraint</a><T>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Functional Interface:</dt>
<dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd>
</dl>
<hr>
<br>
<pre><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a>
public interface <span class="typeNameLabel">VaultExpressionConstraintConsumer<T extends <a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraint.html" title="class in org.wildfly.swarm.config.management.access">VaultExpressionConstraint</a><T>></span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html#accept-T-">accept</a></span>(<a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" title="type parameter in VaultExpressionConstraintConsumer">T</a> value)</code>
<div class="block">Configure a pre-constructed instance of VaultExpressionConstraint
resource</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>default <a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" title="interface in org.wildfly.swarm.config.management.access">VaultExpressionConstraintConsumer</a><<a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" title="type parameter in VaultExpressionConstraintConsumer">T</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html#andThen-org.wildfly.swarm.config.management.access.VaultExpressionConstraintConsumer-">andThen</a></span>(<a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" title="interface in org.wildfly.swarm.config.management.access">VaultExpressionConstraintConsumer</a><<a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" title="type parameter in VaultExpressionConstraintConsumer">T</a>> after)</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="accept-org.wildfly.swarm.config.management.access.VaultExpressionConstraint-">
<!-- -->
</a><a name="accept-T-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>accept</h4>
<pre>void accept(<a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" title="type parameter in VaultExpressionConstraintConsumer">T</a> value)</pre>
<div class="block">Configure a pre-constructed instance of VaultExpressionConstraint
resource</div>
</li>
</ul>
<a name="andThen-org.wildfly.swarm.config.management.access.VaultExpressionConstraintConsumer-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>andThen</h4>
<pre>default <a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" title="interface in org.wildfly.swarm.config.management.access">VaultExpressionConstraintConsumer</a><<a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" title="type parameter in VaultExpressionConstraintConsumer">T</a>> andThen(<a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" title="interface in org.wildfly.swarm.config.management.access">VaultExpressionConstraintConsumer</a><<a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" title="type parameter in VaultExpressionConstraintConsumer">T</a>> after)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/VaultExpressionConstraintConsumer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.7.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraint.html" title="class in org.wildfly.swarm.config.management.access"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/management/access/VaultExpressionConstraintSupplier.html" title="interface in org.wildfly.swarm.config.management.access"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html" target="_top">Frames</a></li>
<li><a href="VaultExpressionConstraintConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
wildfly-swarm/wildfly-swarm-javadocs
|
2.7.0.Final/apidocs/org/wildfly/swarm/config/management/access/VaultExpressionConstraintConsumer.html
|
HTML
|
apache-2.0
| 12,305
|
/*
* 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.camel.coap;
import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.AvailablePortFinder;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CoAPComponentTest extends CoAPTestSupport {
protected static final int TCP_PORT = AvailablePortFinder.getNextAvailable();
@Produce("direct:start")
protected ProducerTemplate sender;
@Produce("direct:starttcp")
protected ProducerTemplate tcpSender;
@Test
void testCoAPComponent() throws Exception {
CoapClient client = createClient("/TestResource");
CoapResponse response = client.post("Camel", MediaTypeRegistry.TEXT_PLAIN);
assertEquals("Hello Camel", response.getResponseText());
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMinimumMessageCount(1);
mock.expectedBodiesReceived("Hello Camel CoAP");
mock.expectedHeaderReceived(Exchange.CONTENT_TYPE, MediaTypeRegistry.toString(MediaTypeRegistry.APPLICATION_OCTET_STREAM));
mock.expectedHeaderReceived(CoAPConstants.COAP_RESPONSE_CODE, CoAP.ResponseCode.CONTENT.toString());
sender.sendBody("Camel CoAP");
assertMockEndpointsSatisfied();
}
@Test
void testCoAPComponentTLS() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMinimumMessageCount(1);
mock.expectedBodiesReceived("Hello Camel CoAP");
mock.expectedHeaderReceived(Exchange.CONTENT_TYPE, MediaTypeRegistry.toString(MediaTypeRegistry.APPLICATION_OCTET_STREAM));
mock.expectedHeaderReceived(CoAPConstants.COAP_RESPONSE_CODE, CoAP.ResponseCode.CONTENT.toString());
tcpSender.sendBody("Camel CoAP");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
fromF("coap://localhost:%d/TestResource", PORT).convertBodyTo(String.class).transform(body().prepend("Hello "));
fromF("coap+tcp://localhost:%d/TestResource", TCP_PORT).convertBodyTo(String.class).transform(body().prepend("Hello "));
from("direct:start").toF("coap://localhost:%d/TestResource", PORT).to("mock:result");
from("direct:starttcp").toF("coap+tcp://localhost:%d/TestResource", TCP_PORT).to("mock:result");
}
};
}
}
|
DariusX/camel
|
components/camel-coap/src/test/java/org/apache/camel/coap/CoAPComponentTest.java
|
Java
|
apache-2.0
| 3,668
|
/*
* Created by SharpDevelop.
* User: Mejov Andrei <andrei.mejov@gmail.com>
* Date: 01.01.2009
* Time: 15:34
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Messaging;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
namespace MOMAdapters
{
[AutoLocate("MSMQAdapter")]
[ComVisible(true)]
[ComSourceInterfacesAttribute(typeof(IAdapter))]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("MOMAdapters.MSMQAdapter")]
[Guid("F89F8898-CE26-4A69-833F-D7F11F81B894")]
public class MSMQAdapter : IAdapter
{
private static readonly string AdapterType = "MSMQ";
public static readonly string ReceiveQueueName = "ReceiveQueueName";
public static readonly string SendQueueName = "SendQueueName";
public static readonly string UserName = "UserName";
public static readonly string Password = "Password";
public static readonly string UseZip = "UseZip";
private MessageQueue receiveQueue = null;
private MessageQueue sendQueue = null;
private MessageQueueTransaction transaction = null;
private bool transactionStarted = false;
private bool useZipFlag = false;
private Dictionary<string, string> parameters = new Dictionary<string, string>();
[ComVisible(false)]
public Dictionary<string, string> Parameters
{
get {return parameters;}
}
public string GetAdapterType()
{
return AdapterType;
}
public void SetParameter(string _name, string _value)
{
parameters.Add(_name, _value);
}
public void ClearParameters()
{
parameters.Clear();
}
public void SendFile(string _fileName)
{
using (FileStream fs = new FileStream(_fileName, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs, System.Text.UTF8Encoding.UTF8, true))
{
string buf = "";
while (!sr.EndOfStream)
{
buf += sr.ReadLine();
}
Send(buf);
}
}
}
public void Send(string _text)
{
if (sendQueue == null)
{
throw new Exception("This connector not configured for sending");
}
if (!transactionStarted)
{
Begin();
}
if (useZipFlag)
{
sendQueue.Send(CompressString(_text), transaction);
}
else
{
sendQueue.Send(_text, transaction);
}
}
public bool HasMessage()
{
if (receiveQueue == null)
{
throw new Exception("This connector not configured for receiving");
}
IAsyncResult r = receiveQueue.BeginPeek();
Thread.Sleep(20);
return r.IsCompleted;
}
public string Receive()
{
if (receiveQueue == null)
{
throw new Exception("This connector not configured for receiving");
}
if (!transactionStarted)
{
Begin();
}
Message message = receiveQueue.Receive(transaction);
if (useZipFlag)
{
return DecompressString((byte[])(message.Body));
}
else
{
return message.Body.ToString();
}
}
private void ValidateParameters()
{
if (!((Parameters.ContainsKey(SendQueueName)) || (Parameters.ContainsKey(ReceiveQueueName))))
{
throw new Exception("SendQueueName and/or ReceiveQueueName must be set");
}
if ((Parameters.ContainsKey(UserName)) && (!Parameters.ContainsKey(Password)))
{
throw new Exception("Password must not be empty");
}
}
public void Start()
{
ValidateParameters();
transaction = new MessageQueueTransaction();
if (MessageQueue.Exists(this.Parameters[ReceiveQueueName]))
{
receiveQueue = new MessageQueue(this.Parameters[ReceiveQueueName], true);
}
else
{
receiveQueue = MessageQueue.Create(this.Parameters[ReceiveQueueName], true);
}
if (MessageQueue.Exists(this.Parameters[SendQueueName]))
{
sendQueue = new MessageQueue(this.Parameters[SendQueueName], true);
}
else
{
sendQueue = MessageQueue.Create(this.Parameters[SendQueueName], true);
}
if (Parameters.ContainsKey(UseZip))
{
if (
(Parameters[UseZip].Equals("true")) || (Parameters[UseZip].Equals("True")) ||
(Parameters[UseZip].Equals("1"))
)
{
useZipFlag = true;
sendQueue.Formatter = new BinaryMessageFormatter();
receiveQueue.Formatter = new BinaryMessageFormatter();
}
}
if (!useZipFlag)
{
sendQueue.Formatter = new XmlMessageFormatter(new Type[]{typeof(string)});
receiveQueue.Formatter = new XmlMessageFormatter(new Type[]{typeof(string)});
}
}
public void Stop()
{
if (transactionStarted)
{
transaction.Abort();
}
receiveQueue.Dispose();
sendQueue.Dispose();
receiveQueue = null;
sendQueue = null;
useZipFlag = false;
}
public void Begin()
{
transaction.Begin();
transactionStarted = true;
}
public void Commit()
{
if (transactionStarted)
{
transaction.Commit();
transactionStarted = false;
}
}
public void Rollback()
{
if (transactionStarted)
{
transaction.Abort();
transactionStarted = false;
}
}
public static byte[] CompressString(string _s)
{
byte[] buf = UTF8Encoding.UTF8.GetBytes(_s);
using (MemoryStream ms = new MemoryStream())
{
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress))
{
ds.Write(buf,0, buf.Length);
ds.Close();
return ms.GetBuffer();
}
}
}
public static string DecompressString(byte[] _bytes)
{
using (MemoryStream ms = new MemoryStream(_bytes))
{
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress))
{
using (MemoryStream resStream = new MemoryStream())
{
int b = ds.ReadByte();
while (b>0)
{
resStream.WriteByte((byte)b);
b = ds.ReadByte();
}
byte[] buf = new byte[resStream.Position];
resStream.Seek(0L, SeekOrigin.Begin);
resStream.Read(buf, 0, buf.Length);
return new string(UTF8Encoding.UTF8.GetChars(buf));
}//using resStream
}//using ds
}//using ms
}
public void Dispose()
{
Stop();
}
}
}
|
allustin/one-c-connectors
|
Projects/MOMAdapters/MOMAdapters/MSMQAdapter.cs
|
C#
|
apache-2.0
| 6,550
|
package com.zy17.exception;
import com.zy17.exception.UserAlreadyExsists;
import com.zy17.protobuf.domain.Eng;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.xml.bind.ValidationException;
/**
* Created with IntelliJ IDEA. User: Administrator Date: 13-6-19 Time: 下午3:32 To
* change this template use File | Settings | File Templates.
*/
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {UserAlreadyExsists.class,
ValidationException.class,
AuthenticationException.class,
Exception.class})
public ResponseEntity<Object> exceptionHandler(Exception ex,
WebRequest request) {
HttpHeaders headers = new HttpHeaders();
if (ex instanceof IllegalArgumentException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
return handleException((IllegalArgumentException) ex, headers,
status, request);
} else if (ex instanceof ValidationException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
return handleException((ValidationException) ex, headers, status,
request);
} else if (ex instanceof AuthenticationException) {
HttpStatus status = HttpStatus.NETWORK_AUTHENTICATION_REQUIRED;
return handleException((AuthenticationException) ex, headers,
status, request);
} else if (ex instanceof Exception) {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return handleException(ex, headers,
status, request);
} else {
logger.warn("Unknown exception type: " + ex.getClass().getName());
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return handleExceptionInternal(ex, null, headers, status, request);
}
}
protected ResponseEntity<Object> handleException(Exception ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
Eng.Err error = Eng.Err.newBuilder()
.setErrorCode(status.value())
.setErrMessage(ex.getMessage())
.build();
return handleExceptionInternal(ex, error.toByteArray(), headers, status,
request);
}
@Override
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(
HttpRequestMethodNotSupportedException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
Eng.Err error = Eng.Err.newBuilder()
.setErrorCode(status.value())
.setErrMessage(ex.getMessage())
.build();
return handleExceptionInternal(ex, error.toByteArray(), headers, status,
request);
}
}
|
iforgetyou/helloorm
|
src/com/zy17/exception/RestExceptionHandler.java
|
Java
|
apache-2.0
| 3,426
|
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Calls;
using Ds3.Models;
using Ds3.Runtime;
using System.Linq;
using System.Net;
using System.Xml.Linq;
namespace Ds3.ResponseParsers
{
internal class GetSuspectBlobPoolsSpectraS3ResponseParser : IResponseParser<GetSuspectBlobPoolsSpectraS3Request, GetSuspectBlobPoolsSpectraS3Response>
{
public GetSuspectBlobPoolsSpectraS3Response Parse(GetSuspectBlobPoolsSpectraS3Request request, IWebResponse response)
{
using (response)
{
ResponseParseUtilities.HandleStatusCode(response, (HttpStatusCode)200);
using (var stream = response.GetResponseStream())
{
return new GetSuspectBlobPoolsSpectraS3Response(
ModelParsers.ParseSuspectBlobPoolList(
XmlExtensions.ReadDocument(stream).ElementOrThrow("Data")),
ResponseParseUtilities.ParseIntHeader("page-truncated", response.Headers),
ResponseParseUtilities.ParseIntHeader("total-result-count", response.Headers)
);
}
}
}
}
}
|
rpmoore/ds3_net_sdk
|
Ds3/ResponseParsers/GetSuspectBlobPoolsSpectraS3ResponseParser.cs
|
C#
|
apache-2.0
| 1,958
|
package org.wso2.qa.testlink.extension.model;
import java.net.MalformedURLException;
/**
* Created by sewmini on 2/8/17.
*/
public class TestLinkException extends Exception {
public TestLinkException(String message, Throwable e) {
super(message,e);
}
}
|
Sewmi/test-results-manager
|
src/main/java/org/wso2/qa/testlink/extension/model/TestLinkException.java
|
Java
|
apache-2.0
| 274
|
// @flow
/**
* Selector to return lobby enable state.
*
* @param {any} state - State object.
* @returns {boolean}
*/
export function getLobbyEnabled(state: any) {
return state['features/lobby'].lobbyEnabled;
}
/**
* Selector to return a list of knocking participants.
*
* @param {any} state - State object.
* @returns {Array<Object>}
*/
export function getKnockingParticipants(state: any) {
return state['features/lobby'].knockingParticipants;
}
/**
* Selector to return lobby visibility.
*
* @param {any} state - State object.
* @returns {any}
*/
export function getIsLobbyVisible(state: any) {
return state['features/lobby'].lobbyVisible;
}
/**
* Selector to return array with knocking participant ids.
*
* @param {any} state - State object.
* @returns {Array}
*/
export function getKnockingParticipantsById(state: any) {
return getKnockingParticipants(state).map(participant => participant.id);
}
|
gpolitis/jitsi-meet
|
react/features/lobby/functions.js
|
JavaScript
|
apache-2.0
| 930
|
/*
* Copyright (C) 2017 Julien Viet
*
* 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.vertx.pgclient.impl.codec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* @author <a href="mailto:emad.albloushi@gmail.com">Emad Alblueshi</a>
*/
class StartupMessage {
static final ByteBuf BUFF_USER = Unpooled.copiedBuffer("user", UTF_8).asReadOnly();
static final ByteBuf BUFF_DATABASE = Unpooled.copiedBuffer("database", UTF_8).asReadOnly();
final String username;
final String database;
final Map<String, String> properties;
StartupMessage(String username, String database, Map<String, String> properties) {
this.username = username;
this.database = database;
this.properties = properties;
}
}
|
vietj/vertx-pg-client
|
vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/StartupMessage.java
|
Java
|
apache-2.0
| 1,344
|
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Wrapper control suite environments that adds Gaussian noise to actions."""
import dm_env
import numpy as np
_BOUNDS_MUST_BE_FINITE = (
'All bounds in `env.action_spec()` must be finite, got: {action_spec}')
class Wrapper(dm_env.Environment):
"""Wraps a control environment and adds Gaussian noise to actions."""
def __init__(self, env, scale=0.01):
"""Initializes a new action noise Wrapper.
Args:
env: The control suite environment to wrap.
scale: The standard deviation of the noise, expressed as a fraction
of the max-min range for each action dimension.
Raises:
ValueError: If any of the action dimensions of the wrapped environment are
unbounded.
"""
action_spec = env.action_spec()
if not (np.all(np.isfinite(action_spec.minimum)) and
np.all(np.isfinite(action_spec.maximum))):
raise ValueError(_BOUNDS_MUST_BE_FINITE.format(action_spec=action_spec))
self._minimum = action_spec.minimum
self._maximum = action_spec.maximum
self._noise_std = scale * (action_spec.maximum - action_spec.minimum)
self._env = env
def step(self, action):
noisy_action = action + self._env.task.random.normal(scale=self._noise_std)
# Clip the noisy actions in place so that they fall within the bounds
# specified by the `action_spec`. Note that MuJoCo implicitly clips out-of-
# bounds control inputs, but we also clip here in case the actions do not
# correspond directly to MuJoCo actuators, or if there are other wrapper
# layers that expect the actions to be within bounds.
np.clip(noisy_action, self._minimum, self._maximum, out=noisy_action)
return self._env.step(noisy_action)
def reset(self):
return self._env.reset()
def observation_spec(self):
return self._env.observation_spec()
def action_spec(self):
return self._env.action_spec()
def __getattr__(self, name):
return getattr(self._env, name)
|
deepmind/dm_control
|
dm_control/suite/wrappers/action_noise.py
|
Python
|
apache-2.0
| 2,630
|
require 'spec_helper'
describe 'smforum::install' do
context 'supported operating systems' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:params) do
{
:version => '2.0.11',
:document_root => '/opt/smforum',
:user => 'webuser',
}
end
let(:facts) do
facts
end
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_class('smforum::install') }
it do
is_expected.to contain_archive('smf_2-0-11_install').with(
'target' => '/opt/smforum',
'user' => 'webuser',
'url' => 'http://download.simplemachines.org/index.php/smf_2-0-11_install.tar.gz',
)
end
end
end
end
end
|
BarnacleBob/barnaclebob-smforum
|
spec/classes/smforum__install_spec.rb
|
Ruby
|
apache-2.0
| 839
|
// This file is automagically generated by mphtogen, do not edit
//0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
-1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 4, -1, -1, 1, 5, -1, -1, -1, -1, 6,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1,
-1, -1, 7, 8, -1, -1, -1, -1, 10, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 12, 13
|
dAck2cC2/m3e
|
src/frameworks/wilhelm/src/autogen/MPH_to_AudioRecorder.h
|
C
|
apache-2.0
| 521
|
/* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. 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.esri.gpt.server.csw.provider.components;
import com.esri.gpt.framework.xml.DomUtil;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Represents an operation response.
*/
public class OperationResponse {
/** instance variables ====================================================== */
private String outputFormat;
private Document responseDom;
private String responseXml;
/** constructors ============================================================ */
/** Default constructor */
public OperationResponse() {
super();
}
/** properties ============================================================== */
/**
* Gets the HTTP output format (MIME type).
* @return the output format (can be null)
*/
public String getOutputFormat() {
return this.outputFormat;
}
/**
* Sets the HTTP output format (MIME type).
* @param outputFormat the output format
*/
public void setOutputFormat(String outputFormat) {
this.outputFormat = outputFormat;
}
/**
* Gets the response XML.
* @return the response XML (can be null)
*/
public String getResponseXml() {
return this.responseXml;
}
/**
* Sets the response XML.
* @param xml the response XML
*/
public void setResponseXml(String xml) {
this.responseXml = xml;
}
/**
* Gets the XML response document under construction.
* @return the XML response document (can be null)
*/
public Document getResponseDom() {
return this.responseDom;
}
/**
* Sets the XML response document under construction.
* @param responseDom the XML response document
*/
public void setResponseDom(Document responseDom) {
this.responseDom = responseDom;
}
/** methods ================================================================= */
/**
* Creates and appends the root element to the XML document.
* @param rootName the name of the root element
* @return the root element
*/
private Element appendRootElement(String rootName) {
if (!rootName.startsWith("csw:")) {
rootName = "csw:"+rootName;
}
Element root = this.getResponseDom().createElementNS(CswNamespaces.URI_CSW,rootName);
root.setAttribute("xmlns:csw",CswNamespaces.URI_CSW);
root.setAttribute("xmlns:dc", CswNamespaces.URI_DC);
root.setAttribute("xmlns:dct",CswNamespaces.URI_DCT);
root.setAttribute("xmlns:gml",CswNamespaces.URI_GML);
root.setAttribute("xmlns:ows",CswNamespaces.URI_OWS);
root.setAttribute("xmlns:dcmiBox",CswNamespaces.URI_dcmiBox);
root.setAttribute("xmlns:xsd",CswNamespaces.URI_XSD);
this.getResponseDom().appendChild(root);
return root;
}
/**
* Creates a new XML document for response construction.
* @return the XML response document
* @throws Exception if the document fails during creation
*/
public Document newResponseDom() throws Exception {
return DomUtil.newDocument();
}
/**
* Creates a new XML document for response construction.
* @param rootName the name of the root element
* @return the root element
* @throws DiscoveryException if the document fails to create
*/
public Element newResponseDom(String rootName) throws Exception {
this.setResponseDom(this.newResponseDom());
return appendRootElement(rootName);
}
/**
* Converts a Timestamp to ISO-8601 format.
* @param timestamp the timestamp
* @return the formatted result
*/
public String toIso8601(Timestamp timestamp) {
String sTimestamp = "";
if (timestamp != null) {
SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
sTimestamp = ISO8601FORMAT.format(timestamp);
sTimestamp = sTimestamp.substring(0,sTimestamp.length()-2)
+ ":" + sTimestamp.substring(sTimestamp.length()-2);
}
return sTimestamp;
}
/**
* Converts a Timestamp to ISO-8601 Date format.
* @param timestamp the timestamp
* @return the formatted result
*/
public String toIso8601Date(Timestamp timestamp) {
String sTimestamp = "";
if (timestamp != null) {
SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'Z'");
sTimestamp = ISO8601FORMAT.format(timestamp);
}
return sTimestamp;
}
}
|
usgin/usgin-geoportal
|
src/com/esri/gpt/server/csw/provider/components/OperationResponse.java
|
Java
|
apache-2.0
| 5,222
|
/*
* Copyright (c) 2008-2017, Hazelcast, 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.
*/
package com.hazelcast.config;
import com.hazelcast.config.helpers.DummyMapStore;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.quorum.QuorumType;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.topic.TopicOverloadPolicy;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URL;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static com.hazelcast.config.EvictionConfig.MaxSizePolicy.ENTRY_COUNT;
import static com.hazelcast.config.EvictionPolicy.LRU;
import static java.io.File.createTempFile;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class XMLConfigBuilderTest extends HazelcastTestSupport {
static final String HAZELCAST_START_TAG = "<hazelcast xmlns=\"http://www.hazelcast.com/schema/config\">\n";
static final String HAZELCAST_END_TAG = "</hazelcast>\n";
@Test
public void testConfigurationURL() throws Exception {
URL configURL = getClass().getClassLoader().getResource("hazelcast-default.xml");
Config config = new XmlConfigBuilder(configURL).build();
assertEquals(configURL, config.getConfigurationUrl());
}
@Test
public void testConfigurationWithFileName() throws Exception {
File file = createTempFile("foo", "bar");
file.deleteOnExit();
String xml = HAZELCAST_START_TAG
+ " <group>\n"
+ " <name>foobar</name>\n"
+ " <password>dev-pass</password>\n"
+ " </group>\n"
+ HAZELCAST_END_TAG;
Writer writer = new PrintWriter(file, "UTF-8");
writer.write(xml);
writer.close();
String path = file.getAbsolutePath();
Config config = new XmlConfigBuilder(path).build();
assertEquals(path, config.getConfigurationFile().getAbsolutePath());
}
@Test(expected = IllegalArgumentException.class)
public void testConfiguration_withNullInputStream() {
new XmlConfigBuilder((InputStream) null);
}
@Test(expected = InvalidConfigurationException.class)
public void testInvalidRootElement() {
String xml = "<hazelcast-client>"
+ "<group>"
+ "<name>dev</name>"
+ "<password>clusterpass</password>"
+ "</group>"
+ "</hazelcast-client>";
buildConfig(xml);
}
@Test(expected = InvalidConfigurationException.class)
public void testJoinValidation() {
String xml = HAZELCAST_START_TAG
+ " <network>\n"
+ " <join>\n"
+ " <multicast enabled=\"true\"/>\n"
+ " <tcp-ip enabled=\"true\"/>\n"
+ " </join>\n"
+ " </network>\n"
+ HAZELCAST_END_TAG;
buildConfig(xml);
}
@Test
public void testSecurityInterceptorConfig() {
String xml = HAZELCAST_START_TAG
+ "<security enabled=\"true\">"
+ " <security-interceptors>"
+ " <interceptor class-name=\"foo\"/>"
+ " <interceptor class-name=\"bar\"/>"
+ " </security-interceptors>"
+ "</security>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
SecurityConfig securityConfig = config.getSecurityConfig();
List<SecurityInterceptorConfig> interceptorConfigs = securityConfig.getSecurityInterceptorConfigs();
assertEquals(2, interceptorConfigs.size());
assertEquals("foo", interceptorConfigs.get(0).className);
assertEquals("bar", interceptorConfigs.get(1).className);
}
@Test
public void readAwsConfig() {
String xml = HAZELCAST_START_TAG
+ " <group>\n"
+ " <name>dev</name>\n"
+ " <password>dev-pass</password>\n"
+ " </group>\n"
+ " <network>\n"
+ " <port auto-increment=\"true\">5701</port>\n"
+ " <join>\n"
+ " <multicast enabled=\"false\">\n"
+ " <multicast-group>224.2.2.3</multicast-group>\n"
+ " <multicast-port>54327</multicast-port>\n"
+ " </multicast>\n"
+ " <tcp-ip enabled=\"false\">\n"
+ " <interface>127.0.0.1</interface>\n"
+ " </tcp-ip>\n"
+ " <aws enabled=\"true\" connection-timeout-seconds=\"10\" >\n"
+ " <access-key>access</access-key>\n"
+ " <secret-key>secret</secret-key>\n"
+ " </aws>\n"
+ " </join>\n"
+ " <interfaces enabled=\"false\">\n"
+ " <interface>10.10.1.*</interface>\n"
+ " </interfaces>\n"
+ " </network>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
AwsConfig awsConfig = config.getNetworkConfig().getJoin().getAwsConfig();
assertTrue(awsConfig.isEnabled());
assertEquals(10, config.getNetworkConfig().getJoin().getAwsConfig().getConnectionTimeoutSeconds());
assertEquals("access", awsConfig.getAccessKey());
assertEquals("secret", awsConfig.getSecretKey());
}
@Test
public void readPortCount() {
// check when it is explicitly set
Config config = buildConfig(HAZELCAST_START_TAG
+ " <network>\n"
+ " <port port-count=\"200\">5701</port>\n"
+ " </network>\n"
+ HAZELCAST_END_TAG);
assertEquals(200, config.getNetworkConfig().getPortCount());
// check if the default is passed in correctly
config = buildConfig(HAZELCAST_START_TAG
+ " <network>\n"
+ " <port>5701</port>\n"
+ " </network>\n"
+ HAZELCAST_END_TAG);
assertEquals(100, config.getNetworkConfig().getPortCount());
}
@Test
public void readPortAutoIncrement() {
// explicitly set
Config config = buildConfig(HAZELCAST_START_TAG
+ " <network>\n"
+ " <port auto-increment=\"false\">5701</port>\n"
+ " </network>\n"
+ HAZELCAST_END_TAG);
assertFalse(config.getNetworkConfig().isPortAutoIncrement());
// check if the default is picked up correctly
config = buildConfig(HAZELCAST_START_TAG
+ " <network>\n"
+ " <port>5701</port>\n"
+ " </network>\n"
+ HAZELCAST_END_TAG);
assertTrue(config.getNetworkConfig().isPortAutoIncrement());
}
@Test
public void networkReuseAddress() {
Config config = buildConfig(HAZELCAST_START_TAG
+ " <network>\n"
+ " <reuse-address>true</reuse-address>\n"
+ " </network>\n"
+ HAZELCAST_END_TAG);
assertTrue(config.getNetworkConfig().isReuseAddress());
}
@Test
public void readSemaphoreConfig() {
String xml = HAZELCAST_START_TAG
+ " <semaphore name=\"default\">\n"
+ " <initial-permits>1</initial-permits>\n"
+ " </semaphore>"
+ " <semaphore name=\"custom\">\n"
+ " <initial-permits>10</initial-permits>\n"
+ " </semaphore>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
SemaphoreConfig defaultConfig = config.getSemaphoreConfig("default");
SemaphoreConfig customConfig = config.getSemaphoreConfig("custom");
assertEquals(1, defaultConfig.getInitialPermits());
assertEquals(10, customConfig.getInitialPermits());
}
@Test
public void readQueueConfig() {
final String xml = HAZELCAST_START_TAG
+ " <queue name=\"custom\">" +
" <statistics-enabled>true</statistics-enabled>" +
" <max-size>100</max-size>" +
" <backup-count>1</backup-count>" +
" <async-backup-count>0</async-backup-count>" +
" <empty-queue-ttl>-1</empty-queue-ttl>" +
" <item-listeners>" +
" <item-listener>com.hazelcast.examples.ItemListener</item-listener>" +
" </item-listeners>" +
" <queue-store>" +
" <class-name>com.hazelcast.QueueStoreImpl</class-name>" +
" <properties>" +
" <property name=\"binary\">false</property>" +
" <property name=\"memory-limit\">1000</property>" +
" <property name=\"bulk-load\">500</property>" +
" </properties>" +
" </queue-store>" +
" <quorum-ref>customQuorumRule</quorum-ref>" +
" </queue>"
+ HAZELCAST_END_TAG;
final Config config = buildConfig(xml);
final QueueConfig qConfig = config.getQueueConfig("custom");
assertTrue(qConfig.isStatisticsEnabled());
assertEquals(100, qConfig.getMaxSize());
assertEquals(1, qConfig.getBackupCount());
assertEquals(0, qConfig.getAsyncBackupCount());
assertEquals(-1, qConfig.getEmptyQueueTtl());
assertTrue(qConfig.getItemListenerConfigs().size() == 1);
final ItemListenerConfig listenerConfig = qConfig.getItemListenerConfigs().iterator().next();
assertEquals("com.hazelcast.examples.ItemListener", listenerConfig.getClassName());
final QueueStoreConfig storeConfig = qConfig.getQueueStoreConfig();
assertNotNull(storeConfig);
assertTrue(storeConfig.isEnabled());
assertEquals("com.hazelcast.QueueStoreImpl", storeConfig.getClassName());
final Properties storeConfigProperties = storeConfig.getProperties();
assertEquals(3, storeConfigProperties.size());
assertEquals("500", storeConfigProperties.getProperty("bulk-load"));
assertEquals("1000", storeConfigProperties.getProperty("memory-limit"));
assertEquals("false", storeConfigProperties.getProperty("binary"));
assertEquals("customQuorumRule", qConfig.getQuorumName());
}
@Test
public void readLockConfig() {
final String xml = HAZELCAST_START_TAG
+ " <lock name=\"default\">"
+ " <quorum-ref>quorumRuleWithThreeNodes</quorum-ref>"
+ " </lock>"
+ " <lock name=\"custom\">"
+ " <quorum-ref>customQuorumRule</quorum-ref>"
+ " </lock>"
+ HAZELCAST_END_TAG;
final Config config = buildConfig(xml);
final LockConfig defaultConfig = config.getLockConfig("default");
final LockConfig customConfig = config.getLockConfig("custom");
assertEquals("quorumRuleWithThreeNodes", defaultConfig.getQuorumName());
assertEquals("customQuorumRule", customConfig.getQuorumName());
}
@Test
public void readReliableTopic() {
String xml = HAZELCAST_START_TAG
+ " <reliable-topic name=\"custom\">"
+ " <read-batch-size>35</read-batch-size>"
+ " <statistics-enabled>false</statistics-enabled>"
+ " <topic-overload-policy>DISCARD_OLDEST</topic-overload-policy>"
+ " <message-listeners>"
+ " <message-listener>MessageListenerImpl</message-listener>"
+ " </message-listeners>"
+ " </reliable-topic>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
ReliableTopicConfig topicConfig = config.getReliableTopicConfig("custom");
assertEquals(35, topicConfig.getReadBatchSize());
assertFalse(topicConfig.isStatisticsEnabled());
assertEquals(TopicOverloadPolicy.DISCARD_OLDEST, topicConfig.getTopicOverloadPolicy());
// checking listener configuration
assertEquals(1, topicConfig.getMessageListenerConfigs().size());
ListenerConfig listenerConfig = topicConfig.getMessageListenerConfigs().get(0);
assertEquals("MessageListenerImpl", listenerConfig.getClassName());
assertNull(listenerConfig.getImplementation());
}
@Test
public void readRingbuffer() {
String xml = HAZELCAST_START_TAG
+ " <ringbuffer name=\"custom\">"
+ " <capacity>10</capacity>"
+ " <backup-count>2</backup-count>"
+ " <async-backup-count>1</async-backup-count>"
+ " <time-to-live-seconds>9</time-to-live-seconds>"
+ " <in-memory-format>OBJECT</in-memory-format>"
+ " </ringbuffer>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
RingbufferConfig ringbufferConfig = config.getRingbufferConfig("custom");
assertEquals(10, ringbufferConfig.getCapacity());
assertEquals(2, ringbufferConfig.getBackupCount());
assertEquals(1, ringbufferConfig.getAsyncBackupCount());
assertEquals(9, ringbufferConfig.getTimeToLiveSeconds());
assertEquals(InMemoryFormat.OBJECT, ringbufferConfig.getInMemoryFormat());
}
@Test
public void testConfig2Xml2DefaultConfig() {
testConfig2Xml2Config("hazelcast-default.xml");
}
@Test
public void testConfig2Xml2FullConfig() {
testConfig2Xml2Config("hazelcast-fullconfig.xml");
}
private static void testConfig2Xml2Config(String fileName) {
String pass = "password";
Config config = new ClasspathXmlConfig(fileName);
config.getGroupConfig().setPassword(pass);
String xml = new ConfigXmlGenerator(true).generate(config);
Config config2 = new InMemoryXmlConfig(xml);
config2.getGroupConfig().setPassword(pass);
assertTrue(ConfigCompatibilityChecker.isCompatible(config, config2));
}
@Test
public void testXSDDefaultXML() throws Exception {
testXSDConfigXML("hazelcast-default.xml");
}
@Test
public void testFullConfigXML() throws Exception {
testXSDConfigXML("hazelcast-fullconfig.xml");
}
@Test
public void testCaseInsensitivityOfSettings() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"testCaseInsensitivity\">"
+ " <in-memory-format>BINARY</in-memory-format>"
+ " <backup-count>1</backup-count>"
+ " <async-backup-count>0</async-backup-count>"
+ " <time-to-live-seconds>0</time-to-live-seconds>"
+ " <max-idle-seconds>0</max-idle-seconds> "
+ " <eviction-policy>NONE</eviction-policy> "
+ " <max-size policy=\"per_partition\">0</max-size>"
+ " <eviction-percentage>25</eviction-percentage>"
+ " <merge-policy>com.hazelcast.map.merge.PassThroughMergePolicy</merge-policy>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("testCaseInsensitivity");
assertTrue(mapConfig.getInMemoryFormat().equals(InMemoryFormat.BINARY));
assertTrue(mapConfig.getEvictionPolicy().equals(EvictionPolicy.NONE));
assertTrue(mapConfig.getMaxSizeConfig().getMaxSizePolicy().equals(MaxSizeConfig.MaxSizePolicy.PER_PARTITION));
}
@Test
public void testManagementCenterConfig() {
String xml = HAZELCAST_START_TAG
+ "<management-center enabled=\"true\">"
+ "someUrl"
+ "</management-center>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
ManagementCenterConfig manCenterCfg = config.getManagementCenterConfig();
assertTrue(manCenterCfg.isEnabled());
assertEquals("someUrl", manCenterCfg.getUrl());
}
@Test
public void testNullManagementCenterConfig() {
String xml = HAZELCAST_START_TAG
+ "<management-center>"
+ "</management-center>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
ManagementCenterConfig manCenterCfg = config.getManagementCenterConfig();
assertFalse(manCenterCfg.isEnabled());
assertNull(manCenterCfg.getUrl());
}
@Test
public void testEmptyManagementCenterConfig() {
String xml = HAZELCAST_START_TAG + HAZELCAST_END_TAG;
Config config = buildConfig(xml);
ManagementCenterConfig manCenterCfg = config.getManagementCenterConfig();
assertFalse(manCenterCfg.isEnabled());
assertNull(manCenterCfg.getUrl());
}
@Test
public void testNotEnabledManagementCenterConfig() {
String xml = HAZELCAST_START_TAG
+ "<management-center enabled=\"false\">"
+ "</management-center>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
ManagementCenterConfig manCenterCfg = config.getManagementCenterConfig();
assertFalse(manCenterCfg.isEnabled());
assertNull(manCenterCfg.getUrl());
}
@Test
public void testNotEnabledWithURLManagementCenterConfig() {
String xml = HAZELCAST_START_TAG
+ "<management-center enabled=\"false\">"
+ "http://localhost:8080/mancenter"
+ "</management-center>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
ManagementCenterConfig manCenterCfg = config.getManagementCenterConfig();
assertFalse(manCenterCfg.isEnabled());
assertEquals("http://localhost:8080/mancenter", manCenterCfg.getUrl());
}
@Test
public void testMapStoreInitialModeLazy() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "<map-store enabled=\"true\" initial-mode=\"LAZY\"></map-store>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapStoreConfig mapStoreConfig = config.getMapConfig("mymap").getMapStoreConfig();
assertTrue(mapStoreConfig.isEnabled());
assertEquals(MapStoreConfig.InitialLoadMode.LAZY, mapStoreConfig.getInitialLoadMode());
}
@Test
public void testMapConfig_minEvictionCheckMillis() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "<min-eviction-check-millis>123456789</min-eviction-check-millis>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("mymap");
assertEquals(123456789L, mapConfig.getMinEvictionCheckMillis());
}
@Test
public void testMapConfig_minEvictionCheckMillis_defaultValue() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("mymap");
assertEquals(MapConfig.DEFAULT_MIN_EVICTION_CHECK_MILLIS, mapConfig.getMinEvictionCheckMillis());
}
@Test
public void testMapConfig_evictions() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"lruMap\">" +
" <eviction-policy>LRU</eviction-policy>\n" +
" </map>\n"
+ "<map name=\"lfuMap\">" +
" <eviction-policy>LFU</eviction-policy>\n" +
" </map>\n"
+ "<map name=\"noneMap\">" +
" <eviction-policy>NONE</eviction-policy>\n" +
" </map>\n"
+ "<map name=\"randomMap\">" +
" <eviction-policy>RANDOM</eviction-policy>\n" +
" </map>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
assertEquals(EvictionPolicy.LRU, config.getMapConfig("lruMap").getEvictionPolicy());
assertEquals(EvictionPolicy.LFU, config.getMapConfig("lfuMap").getEvictionPolicy());
assertEquals(EvictionPolicy.NONE, config.getMapConfig("noneMap").getEvictionPolicy());
assertEquals(EvictionPolicy.RANDOM, config.getMapConfig("randomMap").getEvictionPolicy());
}
@Test
public void testMapConfig_optimizeQueries() {
String xml1 = HAZELCAST_START_TAG
+ "<map name=\"mymap1\">"
+ "<optimize-queries>true</optimize-queries>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config1 = buildConfig(xml1);
MapConfig mapConfig1 = config1.getMapConfig("mymap1");
assertEquals(CacheDeserializedValues.ALWAYS, mapConfig1.getCacheDeserializedValues());
String xml2 = HAZELCAST_START_TAG
+ "<map name=\"mymap2\">"
+ "<optimize-queries>false</optimize-queries>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config2 = buildConfig(xml2);
MapConfig mapConfig2 = config2.getMapConfig("mymap2");
assertEquals(CacheDeserializedValues.INDEX_ONLY, mapConfig2.getCacheDeserializedValues());
}
@Test
public void testMapConfig_cacheValueConfig_defaultValue() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("mymap");
assertEquals(CacheDeserializedValues.INDEX_ONLY, mapConfig.getCacheDeserializedValues());
}
@Test
public void testMapConfig_cacheValueConfig_never() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "<cache-deserialized-values>NEVER</cache-deserialized-values>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("mymap");
assertEquals(CacheDeserializedValues.NEVER, mapConfig.getCacheDeserializedValues());
}
@Test
public void testMapConfig_cacheValueConfig_always() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "<cache-deserialized-values>ALWAYS</cache-deserialized-values>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("mymap");
assertEquals(CacheDeserializedValues.ALWAYS, mapConfig.getCacheDeserializedValues());
}
@Test
public void testMapConfig_cacheValueConfig_indexOnly() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "<cache-deserialized-values>INDEX-ONLY</cache-deserialized-values>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("mymap");
assertEquals(CacheDeserializedValues.INDEX_ONLY, mapConfig.getCacheDeserializedValues());
}
@Test
public void testMapStoreInitialModeEager() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "<map-store enabled=\"true\" initial-mode=\"EAGER\"></map-store>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapStoreConfig mapStoreConfig = config.getMapConfig("mymap").getMapStoreConfig();
assertTrue(mapStoreConfig.isEnabled());
assertEquals(MapStoreConfig.InitialLoadMode.EAGER, mapStoreConfig.getInitialLoadMode());
}
@Test
public void testMapStoreWriteBatchSize() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "<map-store >"
+ "<write-batch-size>23</write-batch-size>"
+ "</map-store>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapStoreConfig mapStoreConfig = config.getMapConfig("mymap").getMapStoreConfig();
assertEquals(23, mapStoreConfig.getWriteBatchSize());
}
@Test
public void testMapStoreConfig_writeCoalescing_whenDefault() {
MapStoreConfig mapStoreConfig = getWriteCoalescingMapStoreConfig(MapStoreConfig.DEFAULT_WRITE_COALESCING, true);
assertTrue(mapStoreConfig.isWriteCoalescing());
}
@Test
public void testMapStoreConfig_writeCoalescing_whenSetFalse() {
MapStoreConfig mapStoreConfig = getWriteCoalescingMapStoreConfig(false, false);
assertFalse(mapStoreConfig.isWriteCoalescing());
}
@Test
public void testMapStoreConfig_writeCoalescing_whenSetTrue() {
MapStoreConfig mapStoreConfig = getWriteCoalescingMapStoreConfig(true, false);
assertTrue(mapStoreConfig.isWriteCoalescing());
}
private MapStoreConfig getWriteCoalescingMapStoreConfig(boolean writeCoalescing, boolean useDefault) {
String xml = getWriteCoalescingConfigXml(writeCoalescing, useDefault);
Config config = buildConfig(xml);
return config.getMapConfig("mymap").getMapStoreConfig();
}
private String getWriteCoalescingConfigXml(boolean value, boolean useDefault) {
return HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "<map-store >"
+ (useDefault ? "" : "<write-coalescing>" + String.valueOf(value) + "</write-coalescing>")
+ "</map-store>"
+ "</map>"
+ HAZELCAST_END_TAG;
}
@Test
public void testNearCacheInMemoryFormat() {
String mapName = "testMapNearCacheInMemoryFormat";
String xml = HAZELCAST_START_TAG
+ " <map name=\"" + mapName + "\">\n"
+ " <near-cache>\n"
+ " <in-memory-format>OBJECT</in-memory-format>\n"
+ " </near-cache>\n"
+ " </map>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig(mapName);
NearCacheConfig ncConfig = mapConfig.getNearCacheConfig();
assertEquals(InMemoryFormat.OBJECT, ncConfig.getInMemoryFormat());
}
@Test
public void testNearCacheEvictionPolicy() {
String xml = HAZELCAST_START_TAG
+ " <map name=\"lfuNearCache\">"
+ " <near-cache>"
+ " <eviction eviction-policy=\"LFU\"/>"
+ " </near-cache>"
+ " </map>"
+ " <map name=\"lruNearCache\">"
+ " <near-cache>"
+ " <eviction eviction-policy=\"LRU\"/>"
+ " </near-cache>"
+ " </map>"
+ " <map name=\"noneNearCache\">"
+ " <near-cache>"
+ " <eviction eviction-policy=\"NONE\"/>"
+ " </near-cache>"
+ " </map>"
+ " <map name=\"randomNearCache\">"
+ " <near-cache>"
+ " <eviction eviction-policy=\"RANDOM\"/>"
+ " </near-cache>"
+ " </map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
assertEquals(EvictionPolicy.LFU, getNearCacheEvictionPolicy("lfuNearCache", config));
assertEquals(EvictionPolicy.LRU, getNearCacheEvictionPolicy("lruNearCache", config));
assertEquals(EvictionPolicy.NONE, getNearCacheEvictionPolicy("noneNearCache", config));
assertEquals(EvictionPolicy.RANDOM, getNearCacheEvictionPolicy("randomNearCache", config));
}
private EvictionPolicy getNearCacheEvictionPolicy(String mapName, Config config) {
return config.getMapConfig(mapName).getNearCacheConfig().getEvictionConfig().getEvictionPolicy();
}
@Test
public void testPartitionGroupZoneAware() {
String xml = HAZELCAST_START_TAG +
"<partition-group enabled=\"true\" group-type=\"ZONE_AWARE\" />"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
assertEquals(config.getPartitionGroupConfig().getGroupType(), PartitionGroupConfig.MemberGroupType.ZONE_AWARE);
}
@Test
public void testPartitionGroupSPI() {
String xml = HAZELCAST_START_TAG +
"<partition-group enabled=\"true\" group-type=\"SPI\" />"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
assertEquals(config.getPartitionGroupConfig().getGroupType(), PartitionGroupConfig.MemberGroupType.SPI);
}
@Test
public void testNearCacheFullConfig() {
String mapName = "testNearCacheFullConfig";
String xml = HAZELCAST_START_TAG
+ " <map name=\"" + mapName + "\">\n"
+ " <near-cache name=\"test\">\n"
+ " <in-memory-format>OBJECT</in-memory-format>\n"
+ " <max-size>1234</max-size>\n"
+ " <time-to-live-seconds>77</time-to-live-seconds>\n"
+ " <max-idle-seconds>92</max-idle-seconds>\n"
+ " <eviction-policy>LFU</eviction-policy>\n"
+ " <invalidate-on-change>false</invalidate-on-change>\n"
+ " <cache-local-entries>false</cache-local-entries>\n"
+ " <eviction eviction-policy=\"LRU\" max-size-policy=\"ENTRY_COUNT\" size=\"3333\"/>\n"
+ " </near-cache>\n"
+ " </map>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig(mapName);
NearCacheConfig nearCacheConfig = mapConfig.getNearCacheConfig();
assertEquals(InMemoryFormat.OBJECT, nearCacheConfig.getInMemoryFormat());
assertEquals(1234, nearCacheConfig.getMaxSize());
assertEquals(77, nearCacheConfig.getTimeToLiveSeconds());
assertEquals(92, nearCacheConfig.getMaxIdleSeconds());
assertEquals("LFU", nearCacheConfig.getEvictionPolicy());
assertFalse(nearCacheConfig.isInvalidateOnChange());
assertFalse(nearCacheConfig.isCacheLocalEntries());
assertEquals(LRU, nearCacheConfig.getEvictionConfig().getEvictionPolicy());
assertEquals(ENTRY_COUNT, nearCacheConfig.getEvictionConfig().getMaximumSizePolicy());
assertEquals(3333, nearCacheConfig.getEvictionConfig().getSize());
assertEquals("test", nearCacheConfig.getName());
}
@Test
public void testMapWanReplicationRef() {
String mapName = "testMapWanReplicationRef";
String refName = "test";
String mergePolicy = "TestMergePolicy";
String xml = HAZELCAST_START_TAG
+ " <map name=\"" + mapName + "\">\n"
+ " <wan-replication-ref name=\"test\">\n"
+ " <merge-policy>TestMergePolicy</merge-policy>\n"
+ " <filters>\n"
+ " <filter-impl>com.example.SampleFilter</filter-impl>\n"
+ " </filters>\n"
+ " </wan-replication-ref>\n"
+ " </map>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
WanReplicationRef wanRef = config.getMapConfig(mapName).getWanReplicationRef();
assertEquals(refName, wanRef.getName());
assertEquals(mergePolicy, wanRef.getMergePolicy());
assertTrue(wanRef.isRepublishingEnabled());
assertEquals(1, wanRef.getFilters().size());
assertEquals("com.example.SampleFilter", wanRef.getFilters().get(0));
}
@Test(expected = InvalidConfigurationException.class)
public void testParseExceptionIsNotSwallowed() {
String invalidXml = HAZELCAST_START_TAG + "</hazelcast";
buildConfig(invalidXml);
// if we (for any reason) get through the parsing, then fail
fail();
}
@Test
public void setMapStoreConfigImplementationTest() {
String mapName = "mapStoreImpObjTest";
String xml = HAZELCAST_START_TAG
+ "<map name=\"" + mapName + "\">\n"
+ "<map-store enabled=\"true\">\n"
+ "<class-name>com.hazelcast.config.helpers.DummyMapStore</class-name>\n"
+ "<write-delay-seconds>5</write-delay-seconds>\n"
+ "</map-store>\n"
+ "</map>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
HazelcastInstance hz = createHazelcastInstance(config);
IMap<String, String> map = hz.getMap(mapName);
// MapStore is not instantiated until the MapContainer is created lazily
map.put("sample", "data");
MapConfig mapConfig = hz.getConfig().getMapConfig(mapName);
MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig();
Object o = mapStoreConfig.getImplementation();
assertNotNull(o);
assertTrue(o instanceof DummyMapStore);
}
@Test
public void testMapPartitionLostListenerConfig() {
String mapName = "map1";
String listenerName = "DummyMapPartitionLostListenerImpl";
String xml = createMapPartitionLostListenerConfiguredXml(mapName, listenerName);
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("map1");
assertMapPartitionLostListener(listenerName, mapConfig);
}
@Test
public void testMapPartitionLostListenerConfigReadOnly() {
String mapName = "map1";
String listenerName = "DummyMapPartitionLostListenerImpl";
String xml = createMapPartitionLostListenerConfiguredXml(mapName, listenerName);
Config config = buildConfig(xml);
MapConfig mapConfig = config.findMapConfig("map1");
assertMapPartitionLostListener(listenerName, mapConfig);
}
private void assertMapPartitionLostListener(String listenerName, MapConfig mapConfig) {
assertFalse(mapConfig.getPartitionLostListenerConfigs().isEmpty());
assertEquals(listenerName, mapConfig.getPartitionLostListenerConfigs().get(0).getClassName());
}
private String createMapPartitionLostListenerConfiguredXml(String mapName, String listenerName) {
return HAZELCAST_START_TAG
+ "<map name=\"" + mapName + "\">\n"
+ "<partition-lost-listeners>\n"
+ "<partition-lost-listener>" + listenerName + "</partition-lost-listener>\n"
+ "</partition-lost-listeners>\n"
+ "</map>\n"
+ HAZELCAST_END_TAG;
}
@Test
public void testCachePartitionLostListenerConfig() {
String cacheName = "cache1";
String listenerName = "DummyCachePartitionLostListenerImpl";
String xml = createCachePartitionLostListenerConfiguredXml(cacheName, listenerName);
Config config = buildConfig(xml);
CacheSimpleConfig cacheConfig = config.getCacheConfig("cache1");
assertCachePartitionLostListener(listenerName, cacheConfig);
}
@Test
public void testCachePartitionLostListenerConfigReadOnly() {
String cacheName = "cache1";
String listenerName = "DummyCachePartitionLostListenerImpl";
String xml = createCachePartitionLostListenerConfiguredXml(cacheName, listenerName);
Config config = buildConfig(xml);
CacheSimpleConfig cacheConfig = config.findCacheConfig("cache1");
assertCachePartitionLostListener(listenerName, cacheConfig);
}
private void assertCachePartitionLostListener(String listenerName, CacheSimpleConfig cacheConfig) {
assertFalse(cacheConfig.getPartitionLostListenerConfigs().isEmpty());
assertEquals(listenerName, cacheConfig.getPartitionLostListenerConfigs().get(0).getClassName());
}
private String createCachePartitionLostListenerConfiguredXml(String cacheName, String listenerName) {
return HAZELCAST_START_TAG
+ "<cache name=\"" + cacheName + "\">\n"
+ "<partition-lost-listeners>\n"
+ "<partition-lost-listener>" + listenerName + "</partition-lost-listener>\n"
+ "</partition-lost-listeners>\n"
+ "</cache>\n"
+ HAZELCAST_END_TAG;
}
private void testXSDConfigXML(String xmlFileName) throws Exception {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL schemaResource = XMLConfigBuilderTest.class.getClassLoader().getResource("hazelcast-config-3.9.xsd");
assertNotNull(schemaResource);
InputStream xmlResource = XMLConfigBuilderTest.class.getClassLoader().getResourceAsStream(xmlFileName);
Schema schema = factory.newSchema(schemaResource);
Source source = new StreamSource(xmlResource);
Validator validator = schema.newValidator();
try {
validator.validate(source);
} catch (SAXException ex) {
fail(xmlFileName + " is not valid because: " + ex.toString());
}
}
private Config buildConfig(String xml) {
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
XmlConfigBuilder configBuilder = new XmlConfigBuilder(bis);
return configBuilder.build();
}
@Test
public void readMulticastConfig() {
String xml = HAZELCAST_START_TAG
+ " <group>\n"
+ " <name>dev</name>\n"
+ " <password>dev-pass</password>\n"
+ " </group>\n"
+ " <network>\n"
+ " <port auto-increment=\"true\">5701</port>\n"
+ " <join>\n"
+ " <multicast enabled=\"true\" loopbackModeEnabled=\"true\">\n"
+ " <multicast-group>224.2.2.3</multicast-group>\n"
+ " <multicast-port>54327</multicast-port>\n"
+ " </multicast>\n"
+ " <tcp-ip enabled=\"false\">\n"
+ " <interface>127.0.0.1</interface>\n"
+ " </tcp-ip>\n"
+ " <aws enabled=\"false\" connection-timeout-seconds=\"10\" >\n"
+ " <access-key>access</access-key>\n"
+ " <secret-key>secret</secret-key>\n"
+ " </aws>\n"
+ " </join>\n"
+ " <interfaces enabled=\"false\">\n"
+ " <interface>10.10.1.*</interface>\n"
+ " </interfaces>\n"
+ " </network>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MulticastConfig multicastConfig = config.getNetworkConfig().getJoin().getMulticastConfig();
assertTrue(multicastConfig.isEnabled());
assertTrue(multicastConfig.isLoopbackModeEnabled());
assertEquals("224.2.2.3", multicastConfig.getMulticastGroup());
assertEquals(54327, multicastConfig.getMulticastPort());
}
@Test
public void testWanConfig() {
String xml = HAZELCAST_START_TAG
+ "<wan-replication name=\"my-wan-cluster\">\n"
+ " <wan-publisher group-name=\"istanbul\">\n"
+ " <class-name>com.hazelcast.wan.custom.WanPublisher</class-name>\n"
+ " <queue-full-behavior>THROW_EXCEPTION</queue-full-behavior>\n"
+ " <queue-capacity>21</queue-capacity>\n"
+ " <properties>\n"
+ " <property name=\"custom.prop.publisher\">prop.publisher</property>\n"
+ " </properties>\n"
+ " </wan-publisher>\n"
+ " <wan-publisher group-name=\"ankara\">\n"
+ " <class-name>com.hazelcast.wan.custom.WanPublisher</class-name>\n"
+ " <queue-full-behavior>THROW_EXCEPTION_ONLY_IF_REPLICATION_ACTIVE</queue-full-behavior>\n"
+ " </wan-publisher>\n"
+ " <wan-consumer>\n"
+ " <class-name>com.hazelcast.wan.custom.WanConsumer</class-name>\n"
+ " <properties>\n"
+ " <property name=\"custom.prop.consumer\">prop.consumer</property>\n"
+ " </properties>\n"
+ " </wan-consumer>\n"
+ "</wan-replication>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
WanReplicationConfig wanConfig = config.getWanReplicationConfig("my-wan-cluster");
assertNotNull(wanConfig);
List<WanPublisherConfig> publisherConfigs = wanConfig.getWanPublisherConfigs();
assertEquals(2, publisherConfigs.size());
WanPublisherConfig publisherConfig1 = publisherConfigs.get(0);
assertEquals("istanbul", publisherConfig1.getGroupName());
assertEquals("com.hazelcast.wan.custom.WanPublisher", publisherConfig1.getClassName());
assertEquals(WANQueueFullBehavior.THROW_EXCEPTION, publisherConfig1.getQueueFullBehavior());
assertEquals(21, publisherConfig1.getQueueCapacity());
Map<String, Comparable> pubProperties = publisherConfig1.getProperties();
assertEquals("prop.publisher", pubProperties.get("custom.prop.publisher"));
WanPublisherConfig publisherConfig2 = publisherConfigs.get(1);
assertEquals("ankara", publisherConfig2.getGroupName());
assertEquals(WANQueueFullBehavior.THROW_EXCEPTION_ONLY_IF_REPLICATION_ACTIVE, publisherConfig2.getQueueFullBehavior());
WanConsumerConfig consumerConfig = wanConfig.getWanConsumerConfig();
assertEquals("com.hazelcast.wan.custom.WanConsumer", consumerConfig.getClassName());
Map<String, Comparable> consProperties = consumerConfig.getProperties();
assertEquals("prop.consumer", consProperties.get("custom.prop.consumer"));
}
@Test
public void testQuorumConfig() {
String xml = HAZELCAST_START_TAG
+ " <quorum enabled=\"true\" name=\"myQuorum\">\n"
+ " <quorum-size>3</quorum-size>\n"
+ " <quorum-function-class-name>com.my.quorum.function</quorum-function-class-name>\n"
+ " <quorum-type>READ</quorum-type>\n"
+ " </quorum>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
QuorumConfig quorumConfig = config.getQuorumConfig("myQuorum");
assertTrue("quorum should be enabled", quorumConfig.isEnabled());
assertEquals(3, quorumConfig.getSize());
assertEquals(QuorumType.READ, quorumConfig.getType());
assertEquals("com.my.quorum.function", quorumConfig.getQuorumFunctionClassName());
assertTrue(quorumConfig.getListenerConfigs().isEmpty());
}
@Test
public void testQuorumListenerConfig() {
String xml = HAZELCAST_START_TAG
+ " <quorum enabled=\"true\" name=\"myQuorum\">\n"
+ " <quorum-size>3</quorum-size>\n"
+ " <quorum-listeners>"
+ " <quorum-listener>com.abc.my.quorum.listener</quorum-listener>"
+ " <quorum-listener>com.abc.my.second.listener</quorum-listener>"
+ " </quorum-listeners> "
+ " </quorum>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
QuorumConfig quorumConfig = config.getQuorumConfig("myQuorum");
assertFalse(quorumConfig.getListenerConfigs().isEmpty());
assertEquals("com.abc.my.quorum.listener", quorumConfig.getListenerConfigs().get(0).getClassName());
assertEquals("com.abc.my.second.listener", quorumConfig.getListenerConfigs().get(1).getClassName());
}
@Test
public void testDurableExecutorConfig() {
String xml = HAZELCAST_START_TAG
+ " <durable-executor-service name=\"foobar\">\n" +
" <pool-size>2</pool-size>\n" +
" <durability>3</durability>\n" +
" <capacity>4</capacity>\n" +
" </durable-executor-service>"
+ HAZELCAST_END_TAG;
final Config config = buildConfig(xml);
final DurableExecutorConfig durableExecutorConfig = config.getDurableExecutorConfig("foobar");
assertFalse(config.getDurableExecutorConfigs().isEmpty());
assertEquals(2, durableExecutorConfig.getPoolSize());
assertEquals(3, durableExecutorConfig.getDurability());
assertEquals(4, durableExecutorConfig.getCapacity());
}
@Test
public void testScheduledExecutorConfig() {
String xml = HAZELCAST_START_TAG
+ " <scheduled-executor-service name=\"foobar\">\n"
+ " <durability>4</durability>\n"
+ " <pool-size>5</pool-size>\n"
+ " <capacity>2</capacity>\n"
+ " </scheduled-executor-service>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
ScheduledExecutorConfig scheduledExecutorConfig = config.getScheduledExecutorConfig("foobar");
assertFalse(config.getScheduledExecutorConfigs().isEmpty());
assertEquals(4, scheduledExecutorConfig.getDurability());
assertEquals(5, scheduledExecutorConfig.getPoolSize());
assertEquals(2, scheduledExecutorConfig.getCapacity());
}
@Test
public void testCardinalityEstimatorConfig() {
String xml = HAZELCAST_START_TAG
+ " <cardinality-estimator name=\"foobar\">\n"
+ " <backup-count>2</backup-count>\n"
+ " <async-backup-count>3</async-backup-count>\n"
+ " </cardinality-estimator>\n"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
CardinalityEstimatorConfig cardinalityEstimatorConfig = config.getCardinalityEstimatorConfig("foobar");
assertFalse(config.getCardinalityEstimatorConfigs().isEmpty());
assertEquals(2, cardinalityEstimatorConfig.getBackupCount());
assertEquals(3, cardinalityEstimatorConfig.getAsyncBackupCount());
}
@Test
public void testIndexesConfig() {
String xml = HAZELCAST_START_TAG
+ " <map name=\"people\">\n"
+ " <indexes>\n"
+ " <index ordered=\"false\">name</index>\n"
+ " <index ordered=\"true\">age</index>\n"
+ " </indexes>"
+ " </map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("people");
assertFalse(mapConfig.getMapIndexConfigs().isEmpty());
assertIndexEqual("name", false, mapConfig.getMapIndexConfigs().get(0));
assertIndexEqual("age", true, mapConfig.getMapIndexConfigs().get(1));
}
private static void assertIndexEqual(String expectedAttribute, boolean expectedOrdered, MapIndexConfig indexConfig) {
assertEquals(expectedAttribute, indexConfig.getAttribute());
assertEquals(expectedOrdered, indexConfig.isOrdered());
}
@Test
public void testAttributeConfig() {
String xml = HAZELCAST_START_TAG
+ " <map name=\"people\">\n"
+ " <attributes>\n"
+ " <attribute extractor=\"com.car.PowerExtractor\">power</attribute>\n"
+ " <attribute extractor=\"com.car.WeightExtractor\">weight</attribute>\n"
+ " </attributes>"
+ " </map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("people");
assertFalse(mapConfig.getMapAttributeConfigs().isEmpty());
assertAttributeEqual("power", "com.car.PowerExtractor", mapConfig.getMapAttributeConfigs().get(0));
assertAttributeEqual("weight", "com.car.WeightExtractor", mapConfig.getMapAttributeConfigs().get(1));
}
@Test(expected = IllegalArgumentException.class)
public void testAttributeConfig_noName_emptyTag() {
String xml = HAZELCAST_START_TAG
+ " <map name=\"people\">\n"
+ " <attributes>\n"
+ " <attribute extractor=\"com.car.WeightExtractor\"></attribute>\n"
+ " </attributes>"
+ " </map>"
+ HAZELCAST_END_TAG;
buildConfig(xml);
}
private static void assertAttributeEqual(String expectedName, String expectedExtractor, MapAttributeConfig attributeConfig) {
assertEquals(expectedName, attributeConfig.getName());
assertEquals(expectedExtractor, attributeConfig.getExtractor());
}
@Test(expected = IllegalArgumentException.class)
public void testAttributeConfig_noName_singleTag() {
String xml = HAZELCAST_START_TAG
+ " <map name=\"people\">\n"
+ " <attributes>\n"
+ " <attribute extractor=\"com.car.WeightExtractor\"/>\n"
+ " </attributes>"
+ " </map>"
+ HAZELCAST_END_TAG;
buildConfig(xml);
}
@Test(expected = IllegalArgumentException.class)
public void testAttributeConfig_noName_noExtractor() {
String xml = HAZELCAST_START_TAG
+ " <map name=\"people\">\n"
+ " <attributes>\n"
+ " <attribute></attribute>\n"
+ " </attributes>"
+ " </map>"
+ HAZELCAST_END_TAG;
buildConfig(xml);
}
@Test(expected = IllegalArgumentException.class)
public void testAttributeConfig_noName_noExtractor_singleTag() {
String xml = HAZELCAST_START_TAG
+ " <map name=\"people\">\n"
+ " <attributes>\n"
+ " <attribute/>\n"
+ " </attributes>"
+ " </map>"
+ HAZELCAST_END_TAG;
buildConfig(xml);
}
@Test(expected = IllegalArgumentException.class)
public void testAttributeConfig_noExtractor() {
String xml = HAZELCAST_START_TAG
+ " <map name=\"people\">\n"
+ " <attributes>\n"
+ " <attribute>weight</attribute>\n"
+ " </attributes>"
+ " </map>"
+ HAZELCAST_END_TAG;
buildConfig(xml);
}
@Test(expected = IllegalArgumentException.class)
public void testAttributeConfig_emptyExtractor() {
String xml = HAZELCAST_START_TAG
+ " <map name=\"people\">\n"
+ " <attributes>\n"
+ " <attribute extractor=\"\">weight</attribute>\n"
+ " </attributes>"
+ " </map>"
+ HAZELCAST_END_TAG;
buildConfig(xml);
}
@Test
public void testQueryCacheFullConfig() {
String xml = HAZELCAST_START_TAG
+ "<map name=\"test\">"
+ "<query-caches>"
+ "<query-cache name=\"cache-name\">"
+ "<entry-listeners>"
+ "<entry-listener include-value=\"true\" local=\"false\">com.hazelcast.examples.EntryListener</entry-listener>"
+ "</entry-listeners>"
+ "<include-value>true</include-value>"
+ "<batch-size>1</batch-size>"
+ "<buffer-size>16</buffer-size>"
+ "<delay-seconds>0</delay-seconds>"
+ "<in-memory-format>BINARY</in-memory-format>"
+ "<coalesce>false</coalesce>"
+ "<populate>true</populate>"
+ "<indexes>"
+ "<index ordered=\"false\">name</index>"
+ "</indexes>"
+ "<predicate type=\"class-name\"> "
+ "com.hazelcast.examples.SimplePredicate"
+ "</predicate>"
+ "<eviction eviction-policy=\"LRU\" max-size-policy=\"ENTRY_COUNT\" size=\"133\"/>"
+ "</query-cache>"
+ "</query-caches>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
QueryCacheConfig queryCacheConfig = config.getMapConfig("test").getQueryCacheConfigs().get(0);
EntryListenerConfig entryListenerConfig = queryCacheConfig.getEntryListenerConfigs().get(0);
assertEquals("cache-name", queryCacheConfig.getName());
assertTrue(entryListenerConfig.isIncludeValue());
assertFalse(entryListenerConfig.isLocal());
assertEquals("com.hazelcast.examples.EntryListener", entryListenerConfig.getClassName());
assertTrue(queryCacheConfig.isIncludeValue());
assertEquals(1, queryCacheConfig.getBatchSize());
assertEquals(16, queryCacheConfig.getBufferSize());
assertEquals(0, queryCacheConfig.getDelaySeconds());
assertEquals(InMemoryFormat.BINARY, queryCacheConfig.getInMemoryFormat());
assertFalse(queryCacheConfig.isCoalesce());
assertTrue(queryCacheConfig.isPopulate());
assertIndexesEqual(queryCacheConfig);
assertEquals("com.hazelcast.examples.SimplePredicate", queryCacheConfig.getPredicateConfig().getClassName());
assertEquals(LRU, queryCacheConfig.getEvictionConfig().getEvictionPolicy());
assertEquals(ENTRY_COUNT, queryCacheConfig.getEvictionConfig().getMaximumSizePolicy());
assertEquals(133, queryCacheConfig.getEvictionConfig().getSize());
}
@Test
public void testLiteMemberConfig() {
String xml = HAZELCAST_START_TAG
+ " <lite-member enabled=\"true\"/>\n"
+ HAZELCAST_END_TAG;
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
XmlConfigBuilder configBuilder = new XmlConfigBuilder(bis);
Config config = configBuilder.build();
assertTrue(config.isLiteMember());
}
@Test
public void testNonLiteMemberConfig() {
String xml = HAZELCAST_START_TAG
+ " <lite-member enabled=\"false\"/>\n"
+ HAZELCAST_END_TAG;
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
XmlConfigBuilder configBuilder = new XmlConfigBuilder(bis);
Config config = configBuilder.build();
assertFalse(config.isLiteMember());
}
@Test(expected = InvalidConfigurationException.class)
public void testNonLiteMemberConfigWithoutEnabledField() {
String xml = HAZELCAST_START_TAG
+ " <lite-member/>\n"
+ HAZELCAST_END_TAG;
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
XmlConfigBuilder configBuilder = new XmlConfigBuilder(bis);
configBuilder.build();
}
@Test(expected = InvalidConfigurationException.class)
public void testInvalidLiteMemberConfig() {
String xml = HAZELCAST_START_TAG
+ " <lite-member enabled=\"dummytext\"/>\n"
+ HAZELCAST_END_TAG;
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
XmlConfigBuilder configBuilder = new XmlConfigBuilder(bis);
configBuilder.build();
}
@Test(expected = InvalidConfigurationException.class)
public void testDuplicateLiteMemberConfig() {
String xml = HAZELCAST_START_TAG
+ " <lite-member enabled=\"true\"/>\n"
+ " <lite-member enabled=\"true\"/>\n"
+ HAZELCAST_END_TAG;
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
XmlConfigBuilder configBuilder = new XmlConfigBuilder(bis);
configBuilder.build();
fail();
}
private void assertIndexesEqual(QueryCacheConfig queryCacheConfig) {
for (MapIndexConfig mapIndexConfig : queryCacheConfig.getIndexConfigs()) {
assertEquals("name", mapIndexConfig.getAttribute());
assertFalse(mapIndexConfig.isOrdered());
}
}
@Test
public void testMapNativeMaxSizePolicy() {
String xmlFormat = HAZELCAST_START_TAG
+ "<map name=\"mymap\">"
+ "<in-memory-format>NATIVE</in-memory-format>"
+ "<max-size policy=\"{0}\">9991</max-size>"
+ "</map>"
+ HAZELCAST_END_TAG;
MessageFormat messageFormat = new MessageFormat(xmlFormat);
MaxSizeConfig.MaxSizePolicy[] maxSizePolicies = MaxSizeConfig.MaxSizePolicy.values();
for (MaxSizeConfig.MaxSizePolicy maxSizePolicy : maxSizePolicies) {
Object[] objects = {maxSizePolicy.toString()};
String xml = messageFormat.format(objects);
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("mymap");
MaxSizeConfig maxSizeConfig = mapConfig.getMaxSizeConfig();
assertEquals(9991, maxSizeConfig.getSize());
assertEquals(maxSizePolicy, maxSizeConfig.getMaxSizePolicy());
}
}
@Test
public void testInstanceName() {
String name = randomName();
String xml = HAZELCAST_START_TAG
+ "<instance-name>" + name + "</instance-name>\n"
+ HAZELCAST_END_TAG;
Config config = new InMemoryXmlConfig(xml);
assertEquals(name, config.getInstanceName());
}
@Test
public void testUserCodeDeployment() {
String xml = HAZELCAST_START_TAG
+ "<user-code-deployment enabled=\"true\">"
+ "<class-cache-mode>OFF</class-cache-mode>"
+ "<provider-mode>LOCAL_CLASSES_ONLY</provider-mode>"
+ "<blacklist-prefixes>com.blacklisted,com.other.blacklisted</blacklist-prefixes>"
+ "<whitelist-prefixes>com.whitelisted,com.other.whitelisted</whitelist-prefixes>"
+ "<provider-filter>HAS_ATTRIBUTE:foo</provider-filter>"
+ "</user-code-deployment>"
+ HAZELCAST_END_TAG;
Config config = new InMemoryXmlConfig(xml);
UserCodeDeploymentConfig dcConfig = config.getUserCodeDeploymentConfig();
assertTrue(dcConfig.isEnabled());
assertEquals(UserCodeDeploymentConfig.ClassCacheMode.OFF, dcConfig.getClassCacheMode());
assertEquals(UserCodeDeploymentConfig.ProviderMode.LOCAL_CLASSES_ONLY, dcConfig.getProviderMode());
assertEquals("com.blacklisted,com.other.blacklisted", dcConfig.getBlacklistedPrefixes());
assertEquals("com.whitelisted,com.other.whitelisted", dcConfig.getWhitelistedPrefixes());
assertEquals("HAS_ATTRIBUTE:foo", dcConfig.getProviderFilter());
}
@Test
public void testGlobalSerializer() {
String name = randomName();
String val = "true";
String xml = HAZELCAST_START_TAG
+ "<serialization><serializers><global-serializer override-java-serialization=\"" + val + "\">" + name
+ "</global-serializer></serializers></serialization>"
+ HAZELCAST_END_TAG;
Config config = new InMemoryXmlConfig(xml);
GlobalSerializerConfig globalSerializerConfig = config.getSerializationConfig().getGlobalSerializerConfig();
globalSerializerConfig.getClassName();
assertEquals(name, globalSerializerConfig.getClassName());
assertTrue(globalSerializerConfig.isOverrideJavaSerialization());
}
@Test
public void testHotRestart() {
final String dir = "/mnt/hot-restart-root/";
final String backupDir = "/mnt/hot-restart-backup/";
final int parallelism = 3;
final int validationTimeout = 13131;
final int dataLoadTimeout = 45454;
final HotRestartClusterDataRecoveryPolicy policy = HotRestartClusterDataRecoveryPolicy.PARTIAL_RECOVERY_MOST_RECENT;
final String xml = HAZELCAST_START_TAG
+ "<hot-restart-persistence enabled=\"true\">"
+ "<base-dir>" + dir + "</base-dir>"
+ "<backup-dir>" + backupDir + "</backup-dir>"
+ "<parallelism>" + parallelism + "</parallelism>"
+ "<validation-timeout-seconds>" + validationTimeout + "</validation-timeout-seconds>"
+ "<data-load-timeout-seconds>" + dataLoadTimeout + "</data-load-timeout-seconds>"
+ "<cluster-data-recovery-policy>" + policy + "</cluster-data-recovery-policy>"
+ "</hot-restart-persistence>\n" +
HAZELCAST_END_TAG;
final Config config = new InMemoryXmlConfig(xml);
final HotRestartPersistenceConfig hotRestartPersistenceConfig = config.getHotRestartPersistenceConfig();
assertTrue(hotRestartPersistenceConfig.isEnabled());
assertEquals(new File(dir).getAbsolutePath(), hotRestartPersistenceConfig.getBaseDir().getAbsolutePath());
assertEquals(new File(backupDir).getAbsolutePath(), hotRestartPersistenceConfig.getBackupDir().getAbsolutePath());
assertEquals(parallelism, hotRestartPersistenceConfig.getParallelism());
assertEquals(validationTimeout, hotRestartPersistenceConfig.getValidationTimeoutSeconds());
assertEquals(dataLoadTimeout, hotRestartPersistenceConfig.getDataLoadTimeoutSeconds());
assertEquals(policy, hotRestartPersistenceConfig.getClusterDataRecoveryPolicy());
}
@Test(expected = InvalidConfigurationException.class)
public void testMissingNamespace() {
String xml = "<hazelcast/>";
buildConfig(xml);
}
@Test(expected = InvalidConfigurationException.class)
public void testInvalidNamespace() {
String xml = "<hazelcast xmlns=\"http://foo.bar\"/>";
buildConfig(xml);
}
@Test
public void testValidNamespace() {
String xml = HAZELCAST_START_TAG + HAZELCAST_END_TAG;
buildConfig(xml);
}
@Test(expected = InvalidConfigurationException.class)
public void testHazelcastTagAppearsTwice() {
String xml = HAZELCAST_START_TAG + "<hazelcast/>" + HAZELCAST_END_TAG;
buildConfig(xml);
}
@Test
public void testMapEvictionPolicyClassName() {
String mapEvictionPolicyClassName = "com.hazelcast.map.eviction.LRUEvictionPolicy";
String xml = HAZELCAST_START_TAG
+ "<map name=\"test\">"
+ "<map-eviction-policy-class-name>" + mapEvictionPolicyClassName + "</map-eviction-policy-class-name> "
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("test");
assertEquals(mapEvictionPolicyClassName, mapConfig.getMapEvictionPolicy().getClass().getName());
}
@Test
public void testMapEvictionPolicyIsSelected_whenEvictionPolicySet() {
String mapEvictionPolicyClassName = "com.hazelcast.map.eviction.LRUEvictionPolicy";
String xml = HAZELCAST_START_TAG
+ "<map name=\"test\">"
+ "<map-eviction-policy-class-name>" + mapEvictionPolicyClassName + "</map-eviction-policy-class-name> "
+ "<eviction-policy>LFU</eviction-policy>"
+ "</map>"
+ HAZELCAST_END_TAG;
Config config = buildConfig(xml);
MapConfig mapConfig = config.getMapConfig("test");
assertEquals(mapEvictionPolicyClassName, mapConfig.getMapEvictionPolicy().getClass().getName());
}
}
|
emrahkocaman/hazelcast
|
hazelcast/src/test/java/com/hazelcast/config/XMLConfigBuilderTest.java
|
Java
|
apache-2.0
| 66,377
|
{% extends base_template %}
{% load i18n %}
{% load xadmin_tags %}
{% load crispy_forms_tags %}
{% block bodyclass %}{{ opts.app_label }}-{{ opts.object_name.lower }} detail{% endblock %}
{% block nav_title %}
{% if model_icon %}<i class="{{model_icon}}"></i> {% endif %}{{ object|truncatewords:"18" }}
{% endblock %}
{% block nav_toggles %}
{% include "xadmin/includes/toggle_back.html" %}
{% if has_change_permission %}
<a href="{% url opts|admin_urlname:'change' object.pk %}" class="navbar-toggle pull-right"><i class="fa fa-pencil"></i></a>
{% endif %}
{% if has_delete_permission %}
<a href="{% url opts|admin_urlname:'delete' object.pk %}" class="navbar-toggle pull-right"><i class="fa fa-trash-o"></i></a>
{% endif %}
{% endblock %}
{% block nav_btns %}
{% if has_change_permission %}
<a href="{% url opts|admin_urlname:'change' object.pk %}" class="btn btn-primary"><i class="fa fa-pencil"></i> <span>{% trans "Edit" %}</span></a>
{% endif %}
{% if has_delete_permission %}
<a href="{% url opts|admin_urlname:'delete' object.pk %}" class="btn btn-danger"><i class="fa fa-trash-o"></i> <span>{% trans "Delete" %}</span></a>
{% endif %}
{% endblock %}
{% block content %}
{% view_block 'before_fieldsets' %}
{% crispy form %}
{% view_block 'after_fieldsets' %}
{% endblock %}
|
LennonChin/Django-Practices
|
MxOnline/extra_apps/xadmin/templates/xadmin/views/model_detail.html
|
HTML
|
apache-2.0
| 1,345
|
using Castle.DynamicProxy;
using TrackerDog.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace TrackerDog
{
[DebuggerDisplay("{Property.DeclaringType}.{Property.Name} = {CurrentValue} (Has changed? {HasChanged})")]
internal sealed class DeclaredObjectPropertyChangeTracking : IDeclaredObjectPropertyChangeTracking
{
private object _oldValue;
private object _currentValue;
private IEnumerable _oldCollectionValue;
private IEnumerable _currentCollectionValue;
public DeclaredObjectPropertyChangeTracking(IObjectChangeTrackingConfiguration configuration, ITrackableObjectFactoryInternal trackableObjectFactory, ObjectChangeTracker tracker, object targetObject, PropertyInfo ownerProperty, PropertyInfo property, object currentValue)
{
Configuration = configuration;
TrackableObjectFactory = trackableObjectFactory;
Tracker = tracker;
TargetObject = targetObject;
Property = property;
OldValue = currentValue;
CurrentValue = currentValue;
}
private IObjectChangeTrackingConfiguration Configuration { get; }
private ITrackableObjectFactoryInternal TrackableObjectFactory { get; }
public ObjectChangeTracker Tracker { get; }
IObjectChangeTracker IObjectPropertyChangeTracking.Tracker => Tracker;
public object TargetObject { get; }
public PropertyInfo Property { get; private set; }
public string PropertyName => Property.Name;
private bool CollectionItemsAreTrackable { get; set; }
public object OldValue
{
get { return _oldValue; }
set
{
_oldValue = value;
if (_oldValue != null && Configuration.Collections.CanTrack(_oldValue.GetType()))
{
IEnumerable enumerable = _oldValue as IEnumerable;
if (enumerable != null)
{
_oldCollectionValue = enumerable.CloneEnumerable(Configuration);
if (_oldValue is IProxyTargetAccessor)
_oldCollectionValue = (IEnumerable)TrackableObjectFactory.CreateForCollection
(
_oldCollectionValue, (IChangeTrackableObject)TargetObject, Property
);
_oldValue = _oldCollectionValue;
CollectionItemsAreTrackable = Configuration.CanTrackType(_oldValue.GetCollectionItemType());
}
}
}
}
public object CurrentValue
{
get { return _currentValue; }
set
{
_currentValue = value;
if (!(value is string))
{
_currentCollectionValue = value as IEnumerable;
}
}
}
private IEnumerable OldCollectionValue => _oldCollectionValue;
private IEnumerable CurrentCollectionValue => _currentCollectionValue;
public bool IsCollection => OldCollectionValue != null;
public bool HasChanged
{
get
{
if (!IsCollection)
{
if (CurrentValue == null && OldValue == null)
return false;
else
{
var result = CurrentValue?.Equals(OldValue);
return result != null && !(bool)result;
}
}
else
{
IEnumerable<object> oldCollection = OldCollectionValue.Cast<object>();
IEnumerable<object> currentCollection = CurrentCollectionValue.Cast<object>();
if (oldCollection.Count() != currentCollection.Count())
return true;
else if (CollectionItemsAreTrackable)
return currentCollection.Any(o =>
{
IChangeTrackableObject trackable = o as IChangeTrackableObject;
if (trackable != null) return trackable.GetChangeTrackingContext().ChangeTracker.ChangedProperties.Count > 0;
else return false;
});
else
return currentCollection.Intersect(oldCollection).Count() != currentCollection.Count();
}
}
}
public override bool Equals(object obj)
{
IDeclaredObjectPropertyChangeTracking declared = obj as IDeclaredObjectPropertyChangeTracking;
if (declared != null) return Equals(declared);
else return Equals(obj as IObjectPropertyChangeTracking);
}
public bool Equals(IDeclaredObjectPropertyChangeTracking other) =>
other != null && other.Property == Property;
public bool Equals(IObjectPropertyChangeTracking other) =>
other != null && other.PropertyName == PropertyName;
public override int GetHashCode() =>
Property.Name.GetHashCode() + Property.DeclaringType.AssemblyQualifiedName.GetHashCode();
}
}
|
mfidemraizer/trackerdog
|
TrackerDog/DeclaredObjectPropertyChangeTracking.cs
|
C#
|
apache-2.0
| 5,452
|
using System.Collections.Generic;
using System.Linq;
using CodeModel.Dependencies;
using CodeModel.Graphs;
using CodeModel.RuleEngine;
namespace CodeModel.Extensions.Cqrs.Rules
{
[Need(CqrsResources.CommandHandlers, CqrsResources.QueryExecutionLinks)]
public class DoNotUseQueriesInCommandHandlers : INodeRule
{
public bool IsApplicableTo(Node node)
{
return node is CommandHandlerNode;
}
public IEnumerable<Violation> Verify(VerificationContext context, Node node)
{
foreach (var queryExecutionLink in node.OutboundLinks.OfType<QueryExecutionLink>().GroupBy(x => (QueryNode)x.Target).Select(x => x.Key))
{
yield return new CommandHandlerExecutesQueryViolation((CommandHandlerNode) node, (QueryNode) queryExecutionLink);
}
}
}
}
|
Novakov/HighLevelCodeAnalysis
|
src/CodeModel.Extensions.Cqrs/Rules/DoNotUseQueriesInCommandHandlers.cs
|
C#
|
apache-2.0
| 861
|
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.exec.planner.cost.janio;
import static com.dremio.exec.planner.cost.janio.CodeGeneratorUtil.argList;
import static com.dremio.exec.planner.cost.janio.CodeGeneratorUtil.paramList;
import java.lang.reflect.Method;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.calcite.plan.hep.HepRelVertex;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.metadata.MetadataHandler;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import com.google.common.collect.ImmutableSet;
/**
* Generates the metadata dispatch to handlers.
*/
public class DispatchGenerator {
private final Map<MetadataHandler<?>, String> metadataHandlerToName;
public DispatchGenerator(Map<MetadataHandler<?>, String> metadataHandlerToName) {
this.metadataHandlerToName = metadataHandlerToName;
}
public void dispatchMethod(StringBuilder buff, Method method,
Collection<? extends MetadataHandler<?>> metadataHandlers) {
String delegatingRelClass = HepRelVertex.class.getName();
Map<MetadataHandler<?>, Set<Class<? extends RelNode>>> handlersToClasses =
metadataHandlers.stream()
.distinct()
.collect(
Collectors.toMap(
Function.identity(),
mh -> methodAndInstanceToImplementingClass(method, mh)));
Set<Class<? extends RelNode>> delegateClassSet = handlersToClasses.values().stream()
.flatMap(Set::stream)
.collect(Collectors.toSet());
List<Class<? extends RelNode>> delegateClassList = topologicalSort(delegateClassSet);
buff
.append(" private ")
.append(method.getReturnType().getName())
.append(" ");
CodeGeneratorUtil.dispatchMethodName(buff, method)
.append("(\n")
.append(" ")
.append(RelNode.class.getName())
.append(" r,\n")
.append(" ")
.append(RelMetadataQuery.class.getName())
.append(" mq");
paramList(buff, method, 2)
.append(") {\n");
if (delegateClassList.isEmpty()) {
throwUnknown(buff.append(" "), method)
.append(" }\n");
} else {
buff
.append(" if (r instanceof ").append(delegatingRelClass).append(") {\n")
.append(" do {\n")
.append(" r = ((").append(delegatingRelClass).append(") r).getCurrentRel();\n")
.append(" } while (r instanceof ").append(delegatingRelClass).append(");\n")
.append(" return ");
dispatchedCall(buff, "this", method, RelNode.class);
buff.append(" }\n");
buff
.append(
delegateClassList.stream()
.map(clazz ->
ifInstanceThenDispatch(method,
metadataHandlers, handlersToClasses, clazz))
.collect(
Collectors.joining(" } else if ",
" if ", " } else {\n")));
throwUnknown(buff.append(" "), method)
.append(" }\n")
.append(" }\n");
}
}
private StringBuilder ifInstanceThenDispatch(Method method,
Collection<? extends MetadataHandler<?>> metadataHandlers,
Map<MetadataHandler<?>, Set<Class<? extends RelNode>>> handlersToClasses,
Class<? extends RelNode> clazz) {
String handlerName = findProvider(metadataHandlers, handlersToClasses, clazz);
StringBuilder buff = new StringBuilder()
.append("(r instanceof ").append(clazz.getName()).append(") {\n")
.append(" return ");
dispatchedCall(buff, handlerName, method, clazz);
return buff;
}
private String findProvider(Collection<? extends MetadataHandler<?>> metadataHandlers,
Map<MetadataHandler<?>, Set<Class<? extends RelNode>>> handlerToClasses,
Class<? extends RelNode> clazz) {
for (MetadataHandler<?> mh : metadataHandlers) {
if (handlerToClasses.getOrDefault(mh, ImmutableSet.of()).contains(clazz)) {
return this.metadataHandlerToName.get(mh);
}
}
throw new RuntimeException();
}
private static StringBuilder throwUnknown(StringBuilder buff, Method method) {
return buff
.append(" throw new ")
.append(IllegalArgumentException.class.getName())
.append("(\"No handler for method [").append(method)
.append("] applied to argument of type [\" + r.getClass() + ")
.append("\"]; we recommend you create a catch-all (RelNode) handler\"")
.append(");\n");
}
private static void dispatchedCall(StringBuilder buff, String handlerName, Method method,
Class<? extends RelNode> clazz) {
buff.append(handlerName).append(".").append(method.getName())
.append("((").append(clazz.getName()).append(") r, mq");
argList(buff, method, 2);
buff.append(");\n");
}
private static Set<Class<? extends RelNode>> methodAndInstanceToImplementingClass(
Method method, MetadataHandler<?> handler) {
Set<Class<? extends RelNode>> set = new HashSet<>();
for (Method m : handler.getClass().getMethods()) {
Class<? extends RelNode> aClass = toRelClass(method, m);
if (aClass != null) {
set.add(aClass);
}
}
return set;
}
private static Class<? extends RelNode> toRelClass(Method superMethod,
Method candidate) {
if (!superMethod.getName().equals(candidate.getName())
|| superMethod.getParameterCount() != candidate.getParameterCount()) {
return null;
} else {
Class<?>[] cpt = candidate.getParameterTypes();
Class<?>[] smpt = superMethod.getParameterTypes();
if (!RelNode.class.isAssignableFrom(cpt[0]) || !RelMetadataQuery.class.equals(cpt[1])) {
return null;
}
for (int i = 2; i < smpt.length; i++) {
if (cpt[i] != smpt[i]) {
return null;
}
}
return (Class<? extends RelNode>) cpt[0];
}
}
private static List<Class<? extends RelNode>> topologicalSort(
Collection<Class<? extends RelNode>> list) {
List<Class<? extends RelNode>> l = new ArrayList<>();
ArrayDeque<Class<? extends RelNode>> s = new ArrayDeque<>(list);
while (!s.isEmpty()) {
Class<? extends RelNode> n = s.remove();
boolean found = false;
for (Class<? extends RelNode> other : s) {
if (n.isAssignableFrom(other)) {
found = true;
break;
}
}
if (found) {
s.add(n);
} else {
l.add(n);
}
}
return l;
}
}
|
dremio/dremio-oss
|
sabot/kernel/src/main/java/com/dremio/exec/planner/cost/janio/DispatchGenerator.java
|
Java
|
apache-2.0
| 7,353
|
package yid
/*
import "testing"
// S = eps | S
func rec_alt1() Grammar {
s := Alt{ Eps, Eps }
s.Right = s
return s
}
// S = eps . S
func rec_cat1() Grammar {
s := Cat{ Eps, Eps }
s.Second = s
return s
}
// S = S . eps
func rec_cat2() Grammar {
s := &Cat{ &Eps{}, &Eps{} }
s.First = s
return s
}
//
// Nullable
//
var nullable_tests = []struct {
grammar Grammar
nullable bool
}{
{ Empty, false },
{ Eps, true },
{ Cat(func() Grammar { return Empty }, func() Grammar { return Eps }), false },
{ Cat(func() Grammar { return Eps }, func() { return Empty }), false },
{ Cat(func() Grammar { return Eps}, func() { return Eps }}, true },
{ rec_alt1(), true },
{ rec_cat1(), false },
{ rec_cat2(), false },
}
func TestNullable(t *testing.T) {
for idx, test_case := range nullable_tests {
if (Nullable(test_case.grammar) != test_case.nullable) {
t.Errorf("Nullable test at index %d failed test (should be %b)", idx, test_case.nullable)
}
}
}
//
// Compact
//
var compact_tests = []struct {
grammar Grammar
compacted Grammar
}{
{ &Empty{}, TheEmpty },
{ &Eps{}, TheEps },
{ &Lit{ "hello" }, &Lit{ "hello" } },
{ &Cat{ &Empty{}, &Empty{} }, TheEmpty },
{ &Cat{ &Eps{}, &Empty{} }, TheEmpty },
{ &Cat{ &Empty{}, &Eps{} }, TheEmpty },
{ &Cat{ &Eps{}, &Eps{} }, TheEps },
{ &Cat{ &Eps{}, &Lit{ "hello" } }, &Lit{ "hello" } },
{ &Cat{ &Lit{ "hello" }, &Eps{} }, &Lit{ "hello" } },
{ &Alt{ &Empty{}, &Empty{} }, TheEmpty },
{ &Alt{ &Empty{}, &Eps{} }, TheEps },
{ &Alt{ &Eps{}, &Empty{} }, TheEps },
{ &Alt{ &Eps{}, &Eps{} }, TheEps },
{ &Alt{ &Empty{}, &Lit{ "foo" } }, &Lit{ "foo" } },
{ &Alt{ &Lit{ "foo" }, &Empty{} }, &Lit{ "foo" } },
}
func TestCompact(t *testing.T) {
for idx, test_case := range compact_tests {
if !Eq(Compact(test_case.grammar), test_case.compacted) {
t.Errorf("Compact test at index %d failed", idx)
}
}
}
//
// Deriv
//
var deriv_tests = []struct {
grammar Grammar
next string
deriv Grammar
}{
{ &Empty{}, "a", &Empty{} },
{ &Eps{}, "b", &Empty{} },
{ &Lit{"x"}, "x", &Eps{} },
{ &Lit{"x"}, "y", &Empty{} },
{ &Cat{ &Eps{}, &Eps{} }, "foo", &Empty{} },
{ &Cat{ &Lit{ "foo" }, &Eps{} }, "foo", &Eps{} },
{ &Cat{ &Lit{ "foo" }, &Lit{ "baz" } }, "foo", &Lit{ "baz" } },
}
func TestDeriv(t *testing.T) {
for idx, test_case := range deriv_tests {
if !Eq(Compact(Deriv(test_case.next, test_case.grammar)), test_case.deriv) {
t.Errorf("Deriv test at index %d failed test", idx)
}
}
}
//
// TODO: test equiv-acceptance on many strings of a grammar and its compaction
//
*/
|
kennknowles/go-yid
|
src/yid/yid_test.go
|
GO
|
apache-2.0
| 2,576
|
package com.project.dao;
import com.project.model.Vacancy;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository("vacancyDao")
public class VacancyDaoImpl extends AbstractDao<Integer, Vacancy> implements DaoInterface<Vacancy> {
@Override
public Vacancy findByIdOrdinalNumber(int id, int ordinalNumber) {
return getByKey(id, ordinalNumber);
}
@Override
public List<Vacancy> search(Vacancy object) {
Criteria crit = createEntityCriteria();
crit.add(Restrictions.eq("vacancyCode", object.getVacancyCode()));
List<Vacancy> list = null;
Vacancy vacancy = (Vacancy) crit.uniqueResult();
if (vacancy != null) {
list = new ArrayList<>();
list.add(vacancy);
}
return list;
}
@Override
public List<Vacancy> findAll() {
Criteria criteria = createEntityCriteria();
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return (List<Vacancy>) criteria.list();
}
@Override
public void save(Vacancy vacancy) {
persist(vacancy);
}
@Override
public void delete(Integer id, Integer ordinalNumber) {
Criteria crit = createEntityCriteria();
crit.add(Restrictions.eq("id", id));
Vacancy vacancy = (Vacancy) crit.uniqueResult();
delete(vacancy);
}
}
|
exp2Tapavicki/AutoFillingObjectsWithData
|
SpringHibernate/src/main/java/com/project/dao/VacancyDaoImpl.java
|
Java
|
apache-2.0
| 1,542
|
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.tasks.testing.junitplatform;
import org.gradle.api.internal.tasks.testing.junit.JUnitTestEventAdapter;
import org.junit.platform.engine.TestDescriptor;
import org.junit.platform.engine.TestSource;
import org.junit.platform.engine.UniqueId;
import org.junit.platform.engine.support.descriptor.ClassSource;
import org.junit.platform.launcher.TestIdentifier;
import java.util.List;
class VintageTestNameAdapter {
private static final String VINTAGE_DESCRIPTOR_CLASS_NAME = "VintageTestDescriptor";
private static final String VINTAGE_ENGINE = "[engine:junit-vintage]";
static boolean isVintageDynamicLeafTest(TestIdentifier test) {
return test.getParentId().isPresent()
&& !VINTAGE_ENGINE.equals(test.getParentId().get())
&& isClassAndTest(test);
}
private static boolean isClassAndTest(TestIdentifier test) {
return test.getSource().isPresent()
&& test.getSource().get() instanceof ClassSource
&& test.isTest();
}
static boolean isVintageDynamicTestClass(TestIdentifier test) {
return test.getParentId().isPresent()
&& VINTAGE_ENGINE.equals(test.getParentId().get())
&& isClassAndTest(test);
}
static boolean isVintageDynamicLeafTest(TestDescriptor test, TestSource source) {
return test.isTest()
&& source instanceof ClassSource
&& VINTAGE_DESCRIPTOR_CLASS_NAME.equals(test.getClass().getSimpleName());
}
static String vintageDynamicClassName(UniqueId uniqueId) {
return JUnitTestEventAdapter.className(vintageTestName(uniqueId));
}
static String vintageDynamicMethodName(UniqueId uniqueId) {
return JUnitTestEventAdapter.methodName(vintageTestName(uniqueId));
}
private static String vintageTestName(UniqueId uniqueId) {
List<UniqueId.Segment> segments = uniqueId.getSegments();
return segments.get(segments.size() - 1).getValue();
}
}
|
lsmaira/gradle
|
subprojects/testing-junit-platform/src/main/java/org/gradle/api/internal/tasks/testing/junitplatform/VintageTestNameAdapter.java
|
Java
|
apache-2.0
| 2,619
|
namespace Ahmedowsky.Core.Extensions
{
using System;
public static class EnumExtensions
{
public static object GetUnderlyingValue(this Enum @enum)
{
var enumType = @enum.GetTypeOfObj();
var underlyingType = Enum.GetUnderlyingType(@enumType);
if (underlyingType.IsTypeOf<byte>())
return @enum.CastObj<byte>();
if (underlyingType.IsTypeOf<sbyte>())
return @enum.CastObj<sbyte>();
if (underlyingType.IsTypeOf<short>())
return @enum.CastObj<short>();
if (underlyingType.IsTypeOf<ushort>())
return @enum.CastObj<ushort>();
if (underlyingType.IsTypeOf<int>())
return @enum.CastObj<int>();
if (underlyingType.IsTypeOf<uint>())
return @enum.CastObj<uint>();
if (underlyingType.IsTypeOf<long>())
return @enum.CastObj<long>();
if (underlyingType.IsTypeOf<ulong>())
return @enum.CastObj<ulong>();
throw new Exception(string.Format("Unknown underlying type of enum. Enum type : ({0}) Underlying Type : ({1})",
enumType.FullName, underlyingType.FullName));
}
}
}
|
ahmedowsky/Ahmedowsky
|
Other/Ahmedowsky.Core/Extensions/EnumExtensions.cs
|
C#
|
apache-2.0
| 1,269
|
import boto3
import botocore
import tarfile
import os
import shutil
class Persistor(object):
def __init__(self, data_dir, aws_region, bucket_name):
self.data_dir = data_dir
self.s3 = boto3.resource('s3', region_name=aws_region)
self.bucket_name = bucket_name
try:
self.s3.create_bucket(Bucket=bucket_name, CreateBucketConfiguration={'LocationConstraint': aws_region})
except botocore.exceptions.ClientError, e:
pass # bucket already exists
self.bucket = self.s3.Bucket(bucket_name)
def send_tar_to_s3(self, target_dir):
if not os.path.isdir(target_dir):
raise ValueError('target_dir %r not found.' % target_dir)
base_name = os.path.basename(target_dir)
base_dir = os.path.dirname(target_dir)
tarname = shutil.make_archive(base_name, 'gztar', root_dir=base_dir, base_dir=base_name)
filekey = os.path.basename(tarname)
self.s3.Object(self.bucket_name, filekey).put(Body=open(tarname, 'rb'))
def fetch_and_extract(self, filename):
with open(filename, 'wb') as f:
self.bucket.download_fileobj(filename, f)
with tarfile.open(filename, "r:gz") as tar:
tar.extractall(self.data_dir)
|
kreuks/liven
|
nlp/persistor.py
|
Python
|
apache-2.0
| 1,267
|
# finnkinotxt
Turn Finnkino xml to text (for later to be used in a bot perhaps)
# packaging for AWS Lambda
zip -r package.zip movieparser.py requests/ fuzzywuzzy/
|
timokoola/finnkinotxt
|
README.md
|
Markdown
|
apache-2.0
| 165
|
package com.sathy.evlo.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by sathy on 27/6/15.
*/
public class Database extends SQLiteOpenHelper {
private static final String CreateTable = "Create Table ";
private static final String DB = "evlo.db";
public Database(Context context) {
super(context, DB, null, 1);
}
@Override
public void onCreate(SQLiteDatabase database) {
String createTag = CreateTable + Tag.TableName
+ "(_id integer primary key autoincrement, name text not null)";
String createSource = CreateTable + Source.TableName
+ "(_id integer primary key autoincrement, name text not null)";
String createExpense = CreateTable
+ Expense.TableName
+ "(_id integer primary key autoincrement, expense_date integer not null, source_id integer not null, tag_id integer not null, amount real not null, notes text)";
String createIncome = CreateTable
+ Income.TableName
+ "(_id integer primary key autoincrement, income_date integer not null, amount real not null, source integer not null, notes text)";
database.execSQL(createTag);
database.execSQL(createSource);
database.execSQL(createExpense);
database.execSQL(createIncome);
database.execSQL("INSERT INTO source (name) VALUES ('CASH') ");
database.execSQL("INSERT INTO source (name) VALUES ('CREDIT CARD') ");
database.execSQL("INSERT INTO source (name) VALUES ('DEBIT CARD') ");
database.execSQL("INSERT INTO source (name) VALUES ('ECS') ");
database.execSQL("INSERT INTO source (name) VALUES ('WIRE TRANSFER') ");
database.execSQL("INSERT INTO tag (name) VALUES ('HOME') ");
database.execSQL("INSERT INTO tag (name) VALUES ('OFFICE') ");
database.execSQL("INSERT INTO tag (name) VALUES ('GROCERIES') ");
database.execSQL("INSERT INTO tag (name) VALUES ('DRESS') ");
database.execSQL("INSERT INTO tag (name) VALUES ('TRANSPORT') ");
database.execSQL("INSERT INTO tag (name) VALUES ('DINING') ");
database.execSQL("INSERT INTO tag (name) VALUES ('HEALTH') ");
database.execSQL("INSERT INTO tag (name) VALUES ('FITNESS') ");
database.execSQL("INSERT INTO tag (name) VALUES ('ELECTRONICS') ");
database.execSQL("INSERT INTO tag (name) VALUES ('COMMUNICATION') ");
database.execSQL("INSERT INTO tag (name) VALUES ('ENTERTAINMENT') ");
database.execSQL("INSERT INTO tag (name) VALUES ('INVESTMENT') ");
database.execSQL("INSERT INTO tag (name) VALUES ('EDUCATION') ");
database.execSQL("INSERT INTO tag (name) VALUES ('SPORTS') ");
database.execSQL("INSERT INTO tag (name) VALUES ('SHOPPING') ");
database.execSQL("INSERT INTO tag (name) VALUES ('LOAN') ");
database.execSQL("INSERT INTO tag (name) VALUES ('FUEL') ");
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
}
}
|
legendjaks/evlo
|
app/src/main/java/com/sathy/evlo/data/Database.java
|
Java
|
apache-2.0
| 2,973
|
package cn.songm.common.utils;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PictureTool {
protected static Logger logger = LoggerFactory.getLogger(PictureTool.class);
public static void main(String[] args) throws IOException {
File fileOne = new File("c:\\1.jpg");
BufferedImage imageFirst = ImageIO.read(fileOne);
imageFirst =crop(imageFirst,0,10,297,300);
File outFile = new File("d:\\2.jpg");
// 写图片
ImageIO.write(imageFirst, "jpg", outFile);
}
/**
* 纵向合图的x坐标像素
*/
private final static int y_width = 645;
/**
* 标准图片的y坐标像素,920,是一般照片,1099是邮票照片
*/
private final static int y_height = 920;
/**
* 裁剪x坐标缩进像素
*/
private final static int x_retract = 50;
/**
* 裁剪y坐标缩进像素
*/
private final static int y_retract = 50;
/**
* 系统默认图片边框为20
*/
public final static int BORDER = 20;
/**
* 横向合成图片
*/
public static void xPic(String first, String second, String out) {
try {
/* 1 读取第一张图片 */
File fileOne = new File(first);
BufferedImage imageFirst = ImageIO.read(fileOne);
int width = imageFirst.getWidth();// 图片宽度
int height = imageFirst.getHeight();// 图片高度
int[] imageArrayFirst = new int[width * height];// 从图片中读取RGB
imageArrayFirst = imageFirst.getRGB(0, 0, width, height, imageArrayFirst, 0, width);
/* 1 对第二张图片做相同的处理 */
File fileTwo = new File(second);
BufferedImage imageSecond = ImageIO.read(fileTwo);
int widthTwo = imageSecond.getWidth();// 图片宽度
int heightTwo = imageSecond.getHeight();// 图片高度
int[] imageArraySecond = new int[widthTwo * heightTwo];
imageArraySecond = imageSecond.getRGB(0, 0, widthTwo, heightTwo, imageArraySecond, 0, widthTwo);
int h = height;
if (height < heightTwo) {
h = heightTwo;
}
// 生成新图片
BufferedImage imageResult = new BufferedImage(width + widthTwo, h, BufferedImage.TYPE_INT_RGB);
imageResult.setRGB(0, 0, width, height, imageArrayFirst, 0, width);// 设置左半部分的RGB
imageResult.setRGB(width, 0, widthTwo, heightTwo, imageArraySecond, 0, widthTwo);// 设置右半部分的RGB
File outFile = new File(out);
ImageIO.write(imageResult, "jpg", outFile);// 写图片
} catch (Exception e) {
logger.error("横向合成图片出错....", e);
}
}
/**
* 纵向合成图片
*
* @param first
* 放上面的图片路径
* @param second
* 放下面的图片路径
* @param out
* 文件输出目录
* @param border
* 图片预留边框
*/
public static boolean yPic(String first, String second, String out, int border) {
boolean isOk = true;
try {
/* 1 读取第一张图片 */
File fileOne = new File(first);
BufferedImage imageFirst = ImageIO.read(fileOne);
int width = imageFirst.getWidth();// 图片宽度
int height = imageFirst.getHeight();// 图片高度
/* 2对第二张图片做相同的处理 */
File fileTwo = new File(second);
BufferedImage imageSecond = ImageIO.read(fileTwo);
int widthTwo = imageSecond.getWidth();// 图片宽度
int heightTwo = imageSecond.getHeight();// 图片高度
/* 1 读取第一张图片begin */
int t_height = y_height - heightTwo;
// 图片是横图,逆时针旋转90度再等比缩放
if (width > height) {
imageFirst = rotateImageLeft90(imageFirst);
}
// 等比缩放
imageFirst = resize(imageFirst, y_width, t_height);
// 缩放后图片的大小
width = imageFirst.getWidth();// 图片宽度
height = imageFirst.getHeight();// 图片高度
// 等比缩放后,图片还是太大,裁剪图片
boolean a_w, a_h = false;
if ((a_w = (width > y_width)) || (a_h = (height > t_height))) {
// 起始位置x,y坐标
int s_w = 0, s_h = 0;
// 裁剪x坐标时,缩进属性x_retract
if (a_w) {
int temp = width - y_width;
if (temp > x_retract) {
temp = x_retract;
} else {
temp = 0;
}
s_w = s_w + temp;
}
// 裁剪y坐标时,缩进属性y_retract
if (a_h) {
int temp = height - t_height;
if (temp > y_retract) {
temp = y_retract;
} else {
temp = 0;
}
s_h = s_h + temp;
}
imageFirst = crop(imageFirst, s_w, s_h, y_width, t_height);
width = imageFirst.getWidth();
height = imageFirst.getHeight();
}
int[] imageArrayFirst = new int[(width - border) * height];// 从图片中读取RGB
imageArrayFirst = imageFirst.getRGB(border, 0, (width - border), height, imageArrayFirst, 0,
(width - border));
/* 2对第二张图片做相同的处理begin */
int[] imageArraySecond = new int[widthTwo * heightTwo];
imageArraySecond = imageSecond.getRGB(0, 0, widthTwo, heightTwo, imageArraySecond, 0, widthTwo);
int w = width;
if (width < widthTwo) {
w = widthTwo;
}
// 图片高度
int h = height + heightTwo;
// 生成新图片
BufferedImage imageResult = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
// 解决黑色背景,默认的TYPE_INT_RGB都是0,都是黑色的
Graphics2D g = (Graphics2D) imageResult.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, w, h);// 填充整个屏幕
g.dispose();
// 留边框
imageResult.setRGB(border, 0, (width - border * 2), height, imageArrayFirst, 0, (width - border));// 设置左半部分的RGB
imageResult.setRGB(0, height, widthTwo, heightTwo, imageArraySecond, 0, widthTwo);// 设置右半部分的RGB
File outFile = new File(out);
ImageIO.write(imageResult, "jpg", outFile);// 写图片
} catch (Exception e) {
logger.error("纵向合成图片失败....", e);
isOk = false;
}
return isOk;
}
/**
* 全图打印,图片缩放、旋转处理
*
* @param source
* 待处理的图片
* @param out
* 处理后文件输出目录
* @param border
* 图片预留边框
*/
public static boolean maigaoPic(String source, String out, int border) {
boolean isOk = true;
try {
/* 1 读取第一张图片 */
File fileOne = new File(source);
BufferedImage imageFirst = ImageIO.read(fileOne);
int width = imageFirst.getWidth();// 图片宽度
int height = imageFirst.getHeight();// 图片高度
// 图片是横图,逆时针旋转90度再等比缩放
if (width > height) {
imageFirst = rotateImageLeft90(imageFirst);
}
// 等比缩放
imageFirst = resize(imageFirst, y_width, y_height);
// 缩放后图片的大小
width = imageFirst.getWidth();// 图片宽度
height = imageFirst.getHeight();// 图片高度
// 等比缩放后,图片还是太大,裁剪图片
boolean a_w, a_h = false;
if ((a_w = (width > y_width)) || (a_h = (height > y_height))) {
// 起始位置x,y坐标
int s_w = 0, s_h = 0;
// 裁剪x坐标时,缩进属性x_retract
if (a_w) {
int temp = width - y_width;
if (temp > x_retract) {
temp = x_retract;
} else {
temp = 0;
}
s_w = s_w + temp;
}
// 裁剪y坐标时,缩进属性y_retract
if (a_h) {
int temp = height - y_height;
if (temp > y_retract) {
temp = y_retract;
} else {
temp = 0;
}
s_h = s_h + temp;
}
imageFirst = crop(imageFirst, s_w, s_h, y_width, y_height);
width = imageFirst.getWidth();
height = imageFirst.getHeight();
}
int[] imageArrayFirst = new int[(width - border) * height];// 从图片中读取RGB
imageArrayFirst = imageFirst.getRGB(border, 0, (width - border), height, imageArrayFirst, 0,
(width - border));
// 生成新图片
BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 解决黑色背景,默认的TYPE_INT_RGB都是0,都是黑色的
Graphics2D g = (Graphics2D) imageResult.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);// 填充整个屏幕
g.dispose();
// 留边框
imageResult.setRGB(border, 0, (width - border * 2), height, imageArrayFirst, 0, (width - border));// 设置左半部分的RGB
File outFile = new File(out);
ImageIO.write(imageResult, "jpg", outFile);// 写图片
} catch (IOException e) {
logger.error("全图打印,图片缩放、旋转处理失败....", e);
isOk = false;
}
return isOk;
}
/**
* 实现图像的等比缩放
*
* @param source
* 待处理的图片流
* @param targetW
* 宽度
* @param targetH
* 高度
* @return
*/
public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
//int width = source.getWidth();// 图片宽度
//int height = source.getHeight();// 图片高度
return zoomInImage(source, targetW, targetH);
// 图片宽高都太小时,强制放大图片
/*
if (width < targetW && height < targetH) {
return zoomInImage(source, targetW, targetH);
} else if ((width < targetW && width == height) || (height < targetH && width == height)) {
return zoomInImage(source, targetW, targetH);
}
return null;
*/
}
/**
* 按比例裁剪图片
*
* @param source
* 待处理的图片流
* @param startX
* 开始x坐标
* @param startY
* 开始y坐标
* @param endX
* 结束x坐标
* @param endY
* 结束y坐标
* @return
*/
public static BufferedImage crop(BufferedImage source, int startX, int startY, int wdith, int height) {
int ow = source.getWidth();
int oh = source.getHeight();
if (startX <= -1) {
startX = 0;
}
if (startY <= -1) {
startY = 0;
}
if (wdith <= -1) {
wdith = ow - 1;
}
if (height <= -1) {
height = oh - 1;
}
BufferedImage result = new BufferedImage(wdith, height , source.getType());
for (int y = startY; y < height+startY; y++) {
for (int x = startX; x < wdith+startX; x++) {
int rgb = source.getRGB(x, y);
result.setRGB(x - startX, y - startY, rgb);
}
}
return result;
}
/**
* 旋转图片为指定角度
*
* @param bufferedimage
* 目标图像
* @param degree
* 旋转角度
* @return
*/
public static BufferedImage rotateImage(final BufferedImage bufferedimage, final int degree) {
int w = bufferedimage.getWidth();
int h = bufferedimage.getHeight();
int type = bufferedimage.getColorModel().getTransparency();
BufferedImage img;
Graphics2D graphics2d;
(graphics2d = (img = new BufferedImage(h, w, type)).createGraphics()).setRenderingHint(
RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2d.rotate(Math.toRadians(degree), w / 2, h / 2 + (w > h ? (w - h) / 2 : (h - w) / 2));
graphics2d.drawImage(bufferedimage, 0, 0, null);
graphics2d.dispose();
return img;
}
/**
* 图片左转90度
*
* @param bufferedimage
* @return
*/
public static BufferedImage rotateImageLeft90(BufferedImage bufferedimage) {
int w = bufferedimage.getWidth();
int h = bufferedimage.getHeight();
int type = bufferedimage.getColorModel().getTransparency();
BufferedImage img;
Graphics2D graphics2d;
(graphics2d = (img = new BufferedImage(h, w, type)).createGraphics()).setRenderingHint(
RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2d.rotate(Math.toRadians(270), w / 2, h / 2 + (w - h) / 2);
graphics2d.drawImage(bufferedimage, 0, 0, null);
graphics2d.dispose();
return img;
}
/**
* 图片右转90度
*
* @param bufferedimage
* @return
*/
public static BufferedImage rotateImageRight90(BufferedImage bufferedimage) {
int w = bufferedimage.getWidth();
int h = bufferedimage.getHeight();
int type = bufferedimage.getColorModel().getTransparency();
BufferedImage img;
Graphics2D graphics2d;
(graphics2d = (img = new BufferedImage(h, w, type)).createGraphics()).setRenderingHint(
RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2d.rotate(Math.toRadians(90), w / 2 - (w - h) / 2, h / 2);
graphics2d.drawImage(bufferedimage, 0, 0, null);
graphics2d.dispose();
return img;
}
// 对转
public File rotateImageOppo(File file) throws Exception {
BufferedImage bufferedimage = ImageIO.read(file);
int w = bufferedimage.getWidth();
int h = bufferedimage.getHeight();
int type = bufferedimage.getColorModel().getTransparency();
BufferedImage img;
Graphics2D graphics2d;
(graphics2d = (img = new BufferedImage(w, h, type)).createGraphics()).setRenderingHint(
RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2d.rotate(Math.toRadians(180), w / 2, h / 2);
graphics2d.drawImage(bufferedimage, 0, 0, null);
graphics2d.dispose();
ImageIO.write(img, "jpg", file);
return file;
}
/***
* 图片镜像处理
*
* @param file
* @param FX
* 0 为上下反转 1 为左右反转
* @return
*/
public void imageMisro(File file, int FX) {
try {
BufferedImage bufferedimage = ImageIO.read(file);
int w = bufferedimage.getWidth();
int h = bufferedimage.getHeight();
int[][] datas = new int[w][h];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
datas[j][i] = bufferedimage.getRGB(j, i);
}
}
int[][] tmps = new int[w][h];
if (FX == 0) {
for (int i = 0, a = h - 1; i < h; i++, a--) {
for (int j = 0; j < w; j++) {
tmps[j][a] = datas[j][i];
}
}
} else if (FX == 1) {
for (int i = 0; i < h; i++) {
for (int j = 0, b = w - 1; j < w; j++, b--) {
tmps[b][i] = datas[j][i];
}
}
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
bufferedimage.setRGB(j, i, tmps[j][i]);
}
}
ImageIO.write(bufferedimage, "jpg", file);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 对图片进行强制放大或缩小
*
* @param originalImage
* 原始图片
* @return
*/
public static BufferedImage zoomInImage(BufferedImage originalImage, int width, int height) {
BufferedImage newImage = new BufferedImage(width, height, originalImage.getType());
Graphics g = newImage.getGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return newImage;
}
/**
* 简易图片识别原理
*
* @param img
* 图片路径
*/
public static void discernImg(String img) {
try {
File fileOne = new File(img);
BufferedImage bi = ImageIO.read(fileOne);
// 获取图像的宽度和高度
int width = bi.getWidth();
int height = bi.getHeight();
// 扫描图片
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {// 行扫描
int dip = bi.getRGB(j, i);
if (dip == -1)
System.out.print(" ");
else
System.out.print("♦");
}
System.out.println();// 换行
}
} catch (Exception e) {
logger.error("图片识别出错", e);
}
}
}
|
songzigw/songm-common
|
songm-common-utils/src/main/java/cn/songm/common/utils/PictureTool.java
|
Java
|
apache-2.0
| 17,626
|
package tccpoutputs
import (
"context"
"github.com/giantswarm/microerror"
"github.com/giantswarm/aws-operator/service/controller/controllercontext"
"github.com/giantswarm/aws-operator/service/controller/key"
"github.com/giantswarm/aws-operator/service/internal/cloudformation"
)
const (
APIServerPublicLoadBalancerKey = "APIServerPublicLoadBalancer"
HostedZoneID = "HostedZoneID"
HostedZoneNameServersKey = "HostedZoneNameServers"
InternalHostedZoneID = "InternalHostedZoneID"
OperatorVersion = "OperatorVersion"
VPCIDKey = "VPCID"
VPCPeeringConnectionIDKey = "VPCPeeringConnectionID"
)
func (r *Resource) EnsureCreated(ctx context.Context, obj interface{}) error {
cr, err := r.toClusterFunc(ctx, obj)
if err != nil {
return microerror.Mask(err)
}
cc, err := controllercontext.FromContext(ctx)
if err != nil {
return microerror.Mask(err)
}
var cloudFormation *cloudformation.CloudFormation
{
c := cloudformation.Config{
Client: cc.Client.TenantCluster.AWS.CloudFormation,
}
cloudFormation, err = cloudformation.New(c)
if err != nil {
return microerror.Mask(err)
}
}
var outputs []cloudformation.Output
{
r.logger.Debugf(ctx, "finding the tenant cluster's control plane cloud formation stack outputs")
o, s, err := cloudFormation.DescribeOutputsAndStatus(key.StackNameTCCP(&cr))
if cloudformation.IsStackNotFound(err) {
r.logger.Debugf(ctx, "did not find the tenant cluster's control plane cloud formation stack outputs")
r.logger.Debugf(ctx, "the tenant cluster's control plane cloud formation stack does not exist")
r.logger.Debugf(ctx, "canceling resource")
return nil
} else if cloudformation.IsOutputsNotAccessible(err) {
r.logger.Debugf(ctx, "did not find the tenant cluster's control plane cloud formation stack outputs")
r.logger.Debugf(ctx, "the tenant cluster's control plane cloud formation stack output values are not accessible due to stack status %#q", s)
r.logger.Debugf(ctx, "canceling resource")
cc.Status.TenantCluster.TCCP.IsTransitioning = true
return nil
} else if err != nil {
return microerror.Mask(err)
}
outputs = o
r.logger.Debugf(ctx, "found the tenant cluster's control plane cloud formation stack outputs")
}
if r.route53Enabled {
{
v, err := cloudFormation.GetOutputValue(outputs, APIServerPublicLoadBalancerKey)
// migration code to dont throw error when the old CF Stack dont yet have the new output value
// TODO https://github.com/giantswarm/giantswarm/issues/13851
// Related: https://github.com/giantswarm/giantswarm/issues/10139
// after migration we can remove the check for IsOutputNotFound
if cloudformation.IsOutputNotFound(err) {
r.logger.Debugf(ctx, "did not find the tenant cluster's control plane APIServerPublicLoadBalancer output")
} else {
if err != nil {
return microerror.Mask(err)
}
cc.Status.TenantCluster.DNS.APIPublicLoadBalancer = v
}
}
{
v, err := cloudFormation.GetOutputValue(outputs, HostedZoneID)
if err != nil {
return microerror.Mask(err)
}
cc.Status.TenantCluster.DNS.HostedZoneID = v
}
{
v, err := cloudFormation.GetOutputValue(outputs, HostedZoneNameServersKey)
if err != nil {
return microerror.Mask(err)
}
cc.Status.TenantCluster.DNS.HostedZoneNameServers = v
}
{
v, err := cloudFormation.GetOutputValue(outputs, InternalHostedZoneID)
// We do not throw error when the TC does not
// have internal hosted zone as it is not a strict requirement.
//
if cloudformation.IsOutputNotFound(err) {
r.logger.Debugf(ctx, "did not find the tenant cluster's control plane internalHostedZoneID output")
} else {
if err != nil {
return microerror.Mask(err)
}
cc.Status.TenantCluster.DNS.InternalHostedZoneID = v
}
}
}
{
v, err := cloudFormation.GetOutputValue(outputs, OperatorVersion)
if err != nil {
return microerror.Mask(err)
}
cc.Status.TenantCluster.OperatorVersion = v
}
{
v, err := cloudFormation.GetOutputValue(outputs, VPCIDKey)
if err != nil {
return microerror.Mask(err)
}
cc.Status.TenantCluster.TCCP.VPC.ID = v
}
{
v, err := cloudFormation.GetOutputValue(outputs, VPCPeeringConnectionIDKey)
if err != nil {
return microerror.Mask(err)
}
cc.Status.TenantCluster.TCCP.VPC.PeeringConnectionID = v
}
return nil
}
|
giantswarm/aws-operator
|
service/controller/resource/tccpoutputs/create.go
|
GO
|
apache-2.0
| 4,442
|
Test with zuul server, eureka and config server. Config server is located by discovery.
Test that zuul server updates routes when new routes are added (at least doesn't fail with a stack overflow exception)
|
spring-cloud/spring-cloud-release-tools
|
releaser-core/src/test/resources/projects/spring-cloud-core-tests/zuul-config-discovery/README.md
|
Markdown
|
apache-2.0
| 209
|
/*
* 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.gobblin.metrics.kafka;
import java.io.IOException;
import org.apache.avro.Schema;
import com.google.common.base.Optional;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.reporter.util.AvroBinarySerializer;
import org.apache.gobblin.metrics.reporter.util.AvroSerializer;
import org.apache.gobblin.metrics.reporter.util.SchemaRegistryVersionWriter;
import org.apache.gobblin.metrics.reporter.util.SchemaVersionWriter;
/**
* {@link org.apache.gobblin.metrics.reporter.EventReporter} that emits events to Kafka as serialized Avro records.
*/
public class KafkaAvroEventReporter extends KafkaEventReporter {
protected KafkaAvroEventReporter(Builder<?> builder) throws IOException {
super(builder);
if(builder.registry.isPresent()) {
Schema schema =
new Schema.Parser().parse(getClass().getClassLoader().getResourceAsStream("GobblinTrackingEvent.avsc"));
this.serializer.setSchemaVersionWriter(new SchemaRegistryVersionWriter(builder.registry.get(), builder.topic,
Optional.of(schema)));
}
}
@Override
protected AvroSerializer<GobblinTrackingEvent> createSerializer(SchemaVersionWriter schemaVersionWriter)
throws IOException {
return new AvroBinarySerializer<GobblinTrackingEvent>(GobblinTrackingEvent.SCHEMA$, schemaVersionWriter);
}
/**
* Returns a new {@link KafkaAvroEventReporter.Builder} for {@link KafkaAvroEventReporter}.
*
* @param context the {@link org.apache.gobblin.metrics.MetricContext} to report
* @return KafkaAvroReporter builder
* @deprecated this method is bugged. Use {@link KafkaAvroEventReporter.Factory#forContext} instead.
*/
@Deprecated
public static Builder<? extends Builder<?>> forContext(MetricContext context) {
return new BuilderImpl(context);
}
private static class BuilderImpl extends Builder<BuilderImpl> {
private BuilderImpl(MetricContext context) {
super(context);
}
@Override
protected BuilderImpl self() {
return this;
}
}
public static abstract class Factory {
/**
* Returns a new {@link KafkaAvroEventReporter.Builder} for {@link KafkaAvroEventReporter}.
*
* @param context the {@link org.apache.gobblin.metrics.MetricContext} to report
* @return KafkaAvroReporter builder
*/
public static KafkaAvroEventReporter.BuilderImpl forContext(MetricContext context) {
return new BuilderImpl(context);
}
}
/**
* Builder for {@link KafkaAvroEventReporter}.
* Defaults to no filter, reporting rates in seconds and times in milliseconds.
*/
public static abstract class Builder<T extends Builder<T>> extends KafkaEventReporter.Builder<T> {
private Optional<KafkaAvroSchemaRegistry> registry = Optional.absent();
private Builder(MetricContext context) {
super(context);
}
public T withSchemaRegistry(KafkaAvroSchemaRegistry registry) {
this.registry = Optional.of(registry);
return self();
}
/**
* Builds and returns {@link KafkaAvroEventReporter}.
*
* @param brokers string of Kafka brokers
* @param topic topic to send metrics to
* @return KafkaAvroReporter
*/
public KafkaAvroEventReporter build(String brokers, String topic) throws IOException {
this.brokers = brokers;
this.topic = topic;
return new KafkaAvroEventReporter(this);
}
}
}
|
jenniferzheng/gobblin
|
gobblin-modules/gobblin-kafka-08/src/main/java/org/apache/gobblin/metrics/kafka/KafkaAvroEventReporter.java
|
Java
|
apache-2.0
| 4,289
|
/* Copyright 2015 Constant Innovations 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.constantinnovationsinc.livemultimedia.previews;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.AttributeSet;
import android.util.Log;
import android.graphics.SurfaceTexture;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.widget.TextView;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import java.io.IOException;
import com.constantinnovationsinc.livemultimedia.activities.LiveMultimediaActivity;
import com.constantinnovationsinc.livemultimedia.callbacks.FramesReadyCallback;
import com.constantinnovationsinc.livemultimedia.cameras.JellyBeanCamera;
import com.constantinnovationsinc.livemultimedia.encoders.AudioEncoder;
import com.constantinnovationsinc.livemultimedia.encoders.GPUEncoder;
import com.constantinnovationsinc.livemultimedia.handlers.CameraHandler;
import com.constantinnovationsinc.livemultimedia.handlers.VideoEncoderHandler;
import com.constantinnovationsinc.livemultimedia.handlers.AudioEncoderHandler;
import com.constantinnovationsinc.livemultimedia.recorders.AVRecorder;
import com.constantinnovationsinc.livemultimedia.servers.VideoServer;
import com.constantinnovationsinc.livemultimedia.threads.AudioEncoderThread;
import com.constantinnovationsinc.livemultimedia.threads.CameraThread;
import com.constantinnovationsinc.livemultimedia.threads.VideoEncoderThread;
import com.constantinnovationsinc.livemultimedia.utilities.DeviceNetwork;
import com.constantinnovationsinc.livemultimedia.R;
/****************************************************************************************************************
* This class provides the camera app preview that Android requires if you going to operate the hardware camera
* This preview serves two purposes. Firstly it allows the user to see what the camera sees and it also allows
* the app to capture video frame from the preview window.
***************************************************************************************************************/
public class VideoPreview extends TextureView implements SurfaceTextureListener, FramesReadyCallback {
private static final String TAG = VideoPreview.class.getCanonicalName();
private static final String START_CAPTURE_FRAMES_SOUND = "StartCaptureSound";
private static final String START_ENCODERS_SOUND = "StartEncodersSound";
private JellyBeanCamera mCamera = null;
private AVRecorder mAVRecorder = null;
private Context mContext = null;
private CameraHandler mCameraHandler = null;
private VideoEncoderHandler mVideoEncoderHandler = null;
private AudioEncoderHandler mAudioEncoderHandler = null;
private Handler mWebServerHandler = null;
private HandlerThread mWebServerThread = null;
private CameraThread mCameraThread = null;
private VideoEncoderThread mVideoEncoderThread = null;
private AudioEncoderThread mAudioEncodingThread = null;
private VideoServer mWebServer = null;
private AudioEncoder mAudioEncoder = null;
private int mRatioWidth = 0;
private int mRatioHeight = 0;
public int mRotation = -1;
public int mActiveCam = -1;
public Boolean recordStarted = false;
public FramesReadyCallback mVideoFramesReadylistener = null;
public VideoPreview(Context context) {
super(context);
Log.d(TAG, "Constructor of VideoPreview(Context context)");
mContext = context;
}
public VideoPreview(Context context, AttributeSet attrs) {
super(context, attrs);
Log.d(TAG, "Constructor of VideoPreview(Context context, AttributeSet attrs)");
mContext = context;
}
public VideoPreview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Log.d(TAG, "Constructor of VideoPreview(Context context, AttributeSet attrs, int defStyle)");
mContext = context;
}
public void prepare() {
Log.d(TAG, "Camera created as well as SurfaceTextureListener!");
mCamera = new JellyBeanCamera(mContext, this);
setSurfaceTextureListener(this);
setFrameReadyListener(this);
}
public void halt() {
Log.d(TAG, "Camera released and SurfaceTextureListener is not null!");
setSurfaceTextureListener(null);
if (mCamera != null) {
mCamera.stopCamera();
mCamera = null;
}
}
/******************************************
* release() - fully releases everything
*****************************************/
public void release() {
Log.d(TAG, "Release() existing previewWindow()");
// clear handlers
mWebServerHandler = null;
mVideoEncoderHandler = null;
mAudioEncoderHandler = null;
mCameraHandler = null;
// stop the threads
if (mCameraThread != null) {
mCameraThread.quitSafely();
}
if (mVideoEncoderThread != null) {
mVideoEncoderThread.quitSafely();
}
if (mAudioEncodingThread != null) {
mAudioEncodingThread.quitSafely();
}
if (mWebServerThread != null) {
mWebServerThread.quitSafely();
}
// clear threads
mWebServerThread = null;
mVideoEncoderHandler = null;
mWebServerHandler = null;
mCameraThread = null;
mActiveCam = -1;
}
/**
* **********************************************************************************************
* Sets the aspect ratio for this view. The size of the view will be measured based on the ratio
* calculated from the parameters. Note that the actual sizes of parameters don't matter, that
* is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result.
*
* @param width Relative horizontal size
* @param height Relative vertical size
***********************************************************************************************/
public void setAspectRatio(int width, int height) {
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Size cannot be negative.");
}
mRatioWidth = width;
mRatioHeight = height;
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.d(TAG, "VideoPreview Window being measured!");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (0 == mRatioWidth || 0 == mRatioHeight) {
setMeasuredDimension(width, height);
} else {
if (width < (height * (mRatioWidth / mRatioHeight))) {
setMeasuredDimension(width, width * mRatioHeight / mRatioWidth);
} else {
setMeasuredDimension(height * mRatioWidth / mRatioHeight, height);
}
}
}
/********************************************************************************************
* As the surface is being created the camera preview size can be set
* This may be called multiple times during the app as the user starts and stops the camera
* Each time a new surface may be created and a new preview window set
* ******************************************************************************************/
@SuppressWarnings("deprecation")
@Override
public void onSurfaceTextureAvailable(SurfaceTexture image,
int arg1,
int arg2) {
Log.d(TAG, "SurfaceTexture now Available!");
createCameraThread( image );
setAlpha(1.0f);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
setRotation(90.0f);
}
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {
Log.d(TAG, "SurfaceTexture now Destroyed!");
release();
return true;
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1,
int arg2) {
Log.d(TAG, "SurfaceTexture size has changed!");
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture arg0) {
}
public int getPreviewSizeWidth() {
return (int) mCamera.getPreviewSizeWidth();
}
public int getPreviewSizeHeight() {
return (int) mCamera.getPreviewSizeHeight();
}
public void setActiveCamera(int activeCam) {
// this is set when the CameraThread is created
mActiveCam = activeCam;
}
public void setFrameReadyListener(FramesReadyCallback listener) {
mVideoFramesReadylistener = listener;
}
public synchronized void setRecordingState(Boolean state) {
if (mCamera != null) {
mCamera.setRecordingState(state);
}
if (state && mContext != null && mCamera != null) {
startWebServer();
createAVRecorder();
recordAudio();
}
}
public synchronized void createAVRecorder() {
Log.d(TAG, "createAVRecorder()");
if (mCamera == null) {
Log.e(TAG, "Null Camera in createAVRecorder() method!");
return;
}
if (mCamera.mFrameCatcher == null) {
Log.e(TAG, "Null FrameCatcher in createAVRecorder() method!");
return;
}
if (mCamera.mFrameCatcher.mRecording) {
mAVRecorder = new AVRecorder(mContext);
mAVRecorder.setSize((int) mCamera.getPreviewSizeWidth(), (int) mCamera.getPreviewSizeHeight());
mAVRecorder.setEncodingWidth((int) mCamera.getPreviewSizeWidth());
mAVRecorder.setEncodingHeight((int) mCamera.getPreviewSizeHeight());
mAVRecorder.prepare();
mCamera.setOnFramesReadyCallBack(this);
}
}
public synchronized void createCameraThread( SurfaceTexture texture ) {
Log.d(TAG, "Creating Camera Thread!");
if (mCameraThread != null) {
Log.d(TAG, "Releasing existing Camera Thread!");
mCamera.release();
mCameraThread.quitSafely();
mCameraThread = null;
mCameraHandler = null;
mCamera = null;
}
// recreate the camera object
if (mCamera == null) {
mCamera = new JellyBeanCamera(mContext, this);
}
mCameraThread = new CameraThread("CameraThread");
mCameraThread.setCamera(mCamera);
mCameraThread.setCameraTexture(texture);
mCameraThread.start();
if (mCameraThread != null && mCameraThread.isAlive()) {
mCameraThread.setActiveCameraId(mActiveCam);
}
mCameraHandler = new CameraHandler(mCameraThread.getLooper());
}
public synchronized void recordAudio() {
// record audio on the same threade you encode
startAudioEncoder();
}
public synchronized void startAudioEncoder() {
try {
if (mAVRecorder != null) {
mAudioEncoder = mAVRecorder.getAudioEncoder();
if (mAudioEncoder != null) {
if (mAudioEncoderHandler == null) {
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
Log.e(TAG, "Uncaught exception: in Audio Encoder " + ex);
}
};
mAudioEncodingThread = new AudioEncoderThread("AudioEncoderThread");
mAudioEncodingThread.setUncaughtExceptionHandler(handler);
mAudioEncodingThread.start();
mAudioEncoderHandler = new AudioEncoderHandler(mAudioEncodingThread.getLooper());
}
}
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
@SuppressWarnings("all")
public synchronized void stopAudioRecording() {
try {
if (mAudioEncodingThread == null) {
Log.e(TAG, "Audio Encoding thread is dead!!");
return;
}
if (mAVRecorder != null) {
if (mAudioEncodingThread != null) {
if (mAudioEncodingThread.isAlive()) {
if (mAudioEncoder != null) {
// just kill the thread;
mAudioEncodingThread.quitSafely();
} else {
Log.e(TAG, "Audio Encoder is null in stopAudioRecording!");
}
}
} else {
Log.e(TAG, "Audio Encoding thread is not alive in stopAudioRecording()");
}
} else {
Log.e(TAG, "AVRecorder is null in stopAudioRecording()");
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
@SuppressWarnings("all")
public synchronized void startVideoEncoder() throws IllegalArgumentException {
if (mCamera == null) {
throw new IllegalStateException("Camera is null in startVideoEncoder()");
}
if ( mAVRecorder == null) {
throw new IllegalStateException("AVRecorder is null in startVideoEncoder()");
}
GPUEncoder encoder = mAVRecorder.getVideoEncoder();
if (encoder == null) {
throw new IllegalStateException("GPUEncoder is null in startVideoEncoder()");
}
if (mVideoEncoderHandler != null && mVideoEncoderHandler != null && mVideoEncoderThread != null && mVideoEncoderThread.isAlive()) {
throw new IllegalStateException("Video Encoding process is still ongoing in startVideoEncoder");
}
// passed the shared memory reference from the catcher to the recorder
mAVRecorder.setSharedMemFile(mCamera.mFrameCatcher.getSharedMemFile());
stopAudioRecording();
try {
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
Log.e(TAG, "Uncaught exception: in Video Encoder " + ex);
}
};
mVideoEncoderThread = new VideoEncoderThread("GPUEncoderThread");
mVideoEncoderThread.setUncaughtExceptionHandler(handler);
if (mAVRecorder.getVideoEncoder() != null && mCamera != null) {
mAVRecorder.getVideoEncoder().setSharedVideoFramesStore(mCamera.mFrameCatcher.getSharedMemFile());
}
mVideoEncoderThread.start();
mVideoEncoderHandler = new VideoEncoderHandler(mVideoEncoderThread.getLooper());
mAVRecorder.playSound(START_ENCODERS_SOUND);
mAVRecorder.getVideoEncoder().runGPUEncoder();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
public synchronized void startWebServer() {
try {
String host = DeviceNetwork.getLocalIpAddress();
TextView text = new TextView(mContext);
text.setText(host + ":8080");
text.setX(0f);
text.setY(20.0f);
LiveMultimediaActivity activity = (LiveMultimediaActivity) mContext;
if (activity != null) {
FrameLayout layout = (FrameLayout) activity.findViewById(R.id.fragment_container);
text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout.addView(text);
}
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
Log.e(TAG, "Uncaught exception: in Start Web Server " + ex);
}
};
mWebServerThread = new HandlerThread("WebServerThread");
mWebServerThread.setUncaughtExceptionHandler(handler);
mWebServerThread.start();
mWebServerHandler = new Handler(mWebServerThread.getLooper());
mWebServerHandler.post(new Runnable() {
@Override
public void run() {
try {
String host = DeviceNetwork.getLocalIpAddress();
Log.w(TAG, "Device ip is " + host);
int port = 8080;
mWebServer = new VideoServer(host, port);
mWebServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
/********************************************************
* playerLazerSound 0 sound when frames are being captured
*********************************************************/
public synchronized void playLazerSound() {
if (mAVRecorder != null) {
mAVRecorder.playSound(START_CAPTURE_FRAMES_SOUND);
} else {
Log.e(TAG, "mACRecorder is null in the VideoPreview");
}
}
}
|
tonyconstantinides/LiveMultimedia
|
app/src/main/java/com/constantinnovationsinc/livemultimedia/previews/VideoPreview.java
|
Java
|
apache-2.0
| 18,245
|
package sleepless.gather
import akka.actor.{ActorSystem, Props, Actor}
import sleepless.gather.sources.vk_http.{VkUserId, VkHttpSupervisor}
import concurrent.duration._
object Sleepless extends App {
val system = ActorSystem("system")
val users = Seq("dm", "kate_clapp", "daniilova_anya", "adam_moran").map(VkUserId)
val vkSupervisor = system.actorOf(VkHttpSupervisor.props)
val csvWriter = system.actorOf(CsvWriter.props)
users.foreach(vkSupervisor ! VkHttpSupervisor.Commands.AddNewUser(_))
}
|
last-g/sleepless
|
src/main/scala/sleepless/gather/Sleepless.scala
|
Scala
|
apache-2.0
| 512
|
package org.spider.filter.bloom;
import com.google.common.hash.Funnels;
import org.spider.filter.IFilter;
import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created on 2015-8-29.
* <p>布隆过滤器.
*
* @author dolphineor
*/
public class BloomFilter implements IFilter {
/**
* 需要插入的数据量.
*/
private int expectedInsertions;
/**
* 精准度.
*/
private double fpp;
/**
* 当前数据量.
*/
private AtomicInteger counter;
private final com.google.common.hash.BloomFilter<CharSequence> bloomFilter;
public BloomFilter() {
this(1000, 0.01);
}
public BloomFilter(int expectedInsertions) {
this(expectedInsertions, 0.01);
}
public BloomFilter(int expectedInsertions, double fpp) {
this.expectedInsertions = expectedInsertions;
this.fpp = fpp;
this.bloomFilter = buildBloomFilter();
}
protected com.google.common.hash.BloomFilter<CharSequence> buildBloomFilter() {
counter = new AtomicInteger(0);
return com.google.common.hash.BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), expectedInsertions, fpp);
}
@Override
public float similar(String content) {
float similarValue = 1;
boolean isDuplicate = bloomFilter.mightContain(content);
if (!isDuplicate) {
bloomFilter.put(content);
counter.incrementAndGet();
similarValue = 0;
}
return similarValue;
}
}
|
dolphineor/elasticCrawler
|
src/main/java/org/spider/filter/bloom/BloomFilter.java
|
Java
|
apache-2.0
| 1,569
|
namespace DNCP.ConsulClient
{
/// <summary>
/// Consul 节点信息
/// </summary>
public class ConsulNode
{
public string Node { get; set; }
public string Address { get; set; }
}
}
|
hausthy/DNCP
|
Consul/DNCP.ConsulClient/Models/ConsulNode.cs
|
C#
|
apache-2.0
| 225
|
package com.redhat.issues.hawtio;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MemoryTest {
private static final Logger LOG = LoggerFactory.getLogger(MemoryTest.class);
private static final String HAWTIO_URL = "http://localhost:8181/hawtio";
private static final String USERNAME = "admin";
private static final String PASSWORD = "admin";
private RemoteWebDriver driver;
@Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
driver = new ChromeDriver();
//driver = new FirefoxDriver();
driver.get(HAWTIO_URL + "/login");
sleep(5);
driver.findElement(By.id("username")).sendKeys(USERNAME);
driver.findElement(By.id("password")).sendKeys(PASSWORD);
driver.findElement(By.tagName("button")).click();
LOG.info("Test starts in 10 secs");
for (int i = 0; i < 10; i++) {
System.out.print(".");
sleep(1);
}
System.out.println();
}
//@After
public void tearDown() {
LOG.info("Test ends in 5 mins");
sleep(5 * 60);
driver.quit();
}
@Test
public void run() throws Exception {
int round = 4 * 60;
//int round = 1;
for (int i = 1; i <= round; i++) {
LOG.info("Round {} / {}", i, round);
driver.get(HAWTIO_URL + "/#/jmx/attributes");
sleep(5);
driver.get(HAWTIO_URL + "/#/logs");
sleep(5);
driver.get(HAWTIO_URL + "/#/osgi/bundles");
sleep(5);
}
}
private void sleep(int sec) {
try {
Thread.sleep(sec * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
tadayosi/issues
|
ENTMQ-1787/hawtio-memory-test/src/test/java/com/redhat/issues/hawtio/MemoryTest.java
|
Java
|
apache-2.0
| 2,014
|
package API;
public class DoublesMatch {
Match matchOne;
Match matchTwo;
Player winnerOne;
Player winnerTwo;
int winnerScore;
int loserScore;
Player loserOne;
Player loserTwo;
public Match getMatchOne() {
return matchOne;
}
public void setMatchOne(Match matchOne) {
this.matchOne = matchOne;
}
public Match getMatchTwo() {
return matchTwo;
}
public void setMatchTwo(Match matchTwo) {
this.matchTwo = matchTwo;
}
public Player getWinnerOne() {
return this.winnerOne;
}
public void setWinnerOne(Player winnerOne) {
this.winnerOne = winnerOne;
}
public Player getWinnerTwo() {
return winnerTwo;
}
public void setWinnerTwo(Player winnerTwo) {
this.winnerTwo = winnerTwo;
}
public int getWinnerScore() {
return winnerScore;
}
public void setWinnerScore(int winnerScore) {
this.winnerScore = winnerScore;
}
public int getLoserScore() {
return loserScore;
}
public void setLoserScore(int loserScore) {
this.loserScore = loserScore;
}
public Player getLoserOne() {
return loserOne;
}
public void setLoserOne(Player loserOne) {
this.loserOne = loserOne;
}
public Player getLoserTwo() {
return loserTwo;
}
public void setLoserTwo(Player loserTwo) {
this.loserTwo = loserTwo;
}
public DoublesMatch(Match matchOne, Match matchTwo){
this.matchOne = matchOne;
this.matchTwo = matchTwo;
}
}
|
kmandryk/PoolManager
|
src/API/DoublesMatch.java
|
Java
|
apache-2.0
| 1,377
|
/*
* Copyright 2000-2014 Vaadin 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.vaadin.client.ui.dd;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.RootPanel;
import com.vaadin.client.WidgetUtil;
import com.vaadin.client.widgets.Grid;
/**
* A simple event handler for elements that can be drag and dropped. Properly
* handles drag start, cancel and end. For example, used in {@link Grid} column
* header reordering.
* <p>
* The showing of the dragged element, drag hints and reacting to drop/cancel is
* delegated to {@link DragAndDropCallback} implementation.
*
* @since 7.5.0
* @author Vaadin Ltd
*/
public class DragAndDropHandler {
/**
* Callback interface for drag and drop.
*/
public interface DragAndDropCallback {
/**
* Called when the drag has started. The drag can be canceled by
* returning {@code false}.
*
* @param e
* the original event that started the drag
* @return {@code true} if the drag is OK to start, {@code false} to
* cancel
*/
boolean onDragStart(Event e);
/**
* Called on drag.
*
* @param e
* the event related to the drag
*/
void onDragUpdate(Event e);
/**
* Called after the has ended on a drop or cancel.
*/
void onDragEnd();
/**
* Called when the drag has ended on a drop.
*/
void onDrop();
/**
* Called when the drag has been canceled.
*/
void onDragCancel();
}
private HandlerRegistration startPreviewHandler;
private HandlerRegistration dragHandlerRegistration;
private DragAndDropCallback callback;
private boolean dragging;
// XXX: This is a hack to stop a click event from propagating through to the
// client once dragging has completed. In the Grid case, this caused
// erroneous selections and/or sorting events.
private Timer stopTimer = new Timer() {
@Override
public void run() {
Event.releaseCapture(RootPanel.getBodyElement());
if (callback != null) {
callback.onDragEnd();
callback = null;
}
if (dragHandlerRegistration != null) {
dragHandlerRegistration.removeHandler();
dragHandlerRegistration = null;
}
dragging = false;
}
};
private final NativePreviewHandler dragPreviewHandler = new NativePreviewHandler() {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (dragging) {
final int typeInt = event.getTypeInt();
switch (typeInt) {
case Event.ONMOUSEMOVE:
case Event.ONTOUCHMOVE:
callback.onDragUpdate(Event.as(event.getNativeEvent()));
break;
case Event.ONKEYDOWN:
// End drag if ESC is pressed
int keyCode = event.getNativeEvent().getKeyCode();
if (keyCode == KeyCodes.KEY_ESCAPE) {
cancelDrag(event);
}
break;
case Event.ONTOUCHCANCEL:
cancelDrag(event);
break;
case Event.ONTOUCHEND:
case Event.ONMOUSEUP:
callback.onDragUpdate(Event.as(event.getNativeEvent()));
callback.onDrop();
stopDrag();
break;
case Event.ONCLICK:
break;
default:
break;
}
} else {
stopDrag();
}
// Kill events - as long as this thing is active, we don't want to
// let any event through.
event.getNativeEvent().stopPropagation();
event.getNativeEvent().preventDefault();
event.cancel();
}
};
/**
* This method can be called to trigger drag and drop on any grid element
* that can be dragged and dropped.
*
* @param dragStartingEvent
* the drag triggering event, usually a {@link Event#ONMOUSEDOWN}
* or {@link Event#ONTOUCHSTART} event on the draggable element
*
* @param callback
* the callback that will handle actual drag and drop related
* operations
*/
public void onDragStartOnDraggableElement(
final NativeEvent dragStartingEvent,
final DragAndDropCallback callback) {
startPreviewHandler = Event
.addNativePreviewHandler(new NativePreviewHandler() {
private int startX = WidgetUtil
.getTouchOrMouseClientX(dragStartingEvent);
private int startY = WidgetUtil
.getTouchOrMouseClientY(dragStartingEvent);
@Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
final int typeInt = event.getTypeInt();
if (typeInt == -1
&& event.getNativeEvent().getType()
.toLowerCase().contains("pointer")) {
/*
* Ignore PointerEvents since IE10 and IE11 send
* also MouseEvents for backwards compatibility.
*/
return;
}
switch (typeInt) {
case Event.ONMOUSEOVER:
case Event.ONMOUSEOUT:
// we don't care
break;
case Event.ONKEYDOWN:
case Event.ONKEYPRESS:
case Event.ONKEYUP:
case Event.ONBLUR:
case Event.ONFOCUS:
// don't cancel possible drag start
break;
case Event.ONMOUSEMOVE:
case Event.ONTOUCHMOVE:
int currentX = WidgetUtil
.getTouchOrMouseClientX(event
.getNativeEvent());
int currentY = WidgetUtil
.getTouchOrMouseClientY(event
.getNativeEvent());
if (Math.abs(startX - currentX) > 3
|| Math.abs(startY - currentY) > 3) {
removeStartPreviewHandler();
startDrag(dragStartingEvent, event, callback);
}
event.getNativeEvent().stopPropagation();
event.getNativeEvent().preventDefault();
event.cancel();
break;
default:
// on any other events, clean up this preview
// listener
removeStartPreviewHandler();
break;
}
}
});
}
private void startDrag(NativeEvent startEvent,
NativePreviewEvent triggerEvent, DragAndDropCallback callback) {
if (callback.onDragStart(Event.as(startEvent))) {
this.callback = callback;
dragging = true;
// just capture something to prevent text selection in IE
Event.setCapture(RootPanel.getBodyElement());
dragHandlerRegistration = Event
.addNativePreviewHandler(dragPreviewHandler);
callback.onDragUpdate(Event.as(triggerEvent.getNativeEvent()));
}
}
private void stopDrag() {
if (!stopTimer.isRunning()) {
stopTimer.schedule(100);
}
}
private void cancelDrag(NativePreviewEvent event) {
callback.onDragCancel();
callback.onDragEnd();
stopDrag();
}
private void removeStartPreviewHandler() {
if (startPreviewHandler != null) {
startPreviewHandler.removeHandler();
startPreviewHandler = null;
}
}
}
|
jdahlstrom/vaadin.react
|
client/src/main/java/com/vaadin/client/ui/dd/DragAndDropHandler.java
|
Java
|
apache-2.0
| 9,501
|
/*
Copyright 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.
*/
import {
Article,
} from '../../models';
import { Category } from '../../models';
export async function denormalizeCommentCountsForCategory(category: Category) {
const query = { where: { categoryId: category.id } };
const [
allCount,
unprocessedCount,
unmoderatedCount,
moderatedCount,
highlightedCount,
approvedCount,
rejectedCount,
deferredCount,
flaggedCount,
batchedCount,
] = await Promise.all([
Article.sum('allCount', query),
Article.sum('unprocessedCount', query),
Article.sum('unmoderatedCount', query),
Article.sum('moderatedCount', query),
Article.sum('highlightedCount', query),
Article.sum('approvedCount', query),
Article.sum('rejectedCount', query),
Article.sum('deferredCount', query),
Article.sum('flaggedCount', query),
Article.sum('batchedCount', query),
]);
return category.update({
allCount,
unprocessedCount,
unmoderatedCount,
moderatedCount,
highlightedCount,
approvedCount,
rejectedCount,
deferredCount,
flaggedCount,
batchedCount,
});
}
|
conversationai/conversationai-moderator
|
packages/backend-api/src/domain/categories/countDenormalization.ts
|
TypeScript
|
apache-2.0
| 1,658
|
/**
* 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.fusesource.hudsonresults;
public class JdkPlatformTuple {
private JDK jdk;
private PLATFORM platform;
public JdkPlatformTuple(JDK jdk, PLATFORM platform) {
this.jdk = jdk;
this.platform = platform;
}
public JDK getJdk() {
return jdk;
}
public void setJdk(JDK jdk) {
this.jdk = jdk;
}
public PLATFORM getPlatform() {
return platform;
}
public void setPlatform(PLATFORM platform) {
this.platform = platform;
}
}
|
fusesource/hudson-results
|
src/main/java/org/fusesource/hudsonresults/JdkPlatformTuple.java
|
Java
|
apache-2.0
| 1,263
|
package org.tamilscriptconverter;
import java.io.File;
import java.io.IOException;
/**
* @author James Selvakumar
* @since 1.0.0
*/
public class Main
{
public static void main(String[] args)
{
if(args.length > 0) {
try {
TamilScriptConverter.convertFiles(new File(args[0]));
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Run the program again by specifying the name of the file or directory which you would like to convert");
System.out.println("Example 1:");
System.out.println("java -jar <jar-file> /foo/files-to-be-converted/file1.txt");
System.out.println("");
System.out.println("Example 2:");
System.out.println("java -jar <jar-file> /foo/files-to-be-converted");
}
}
}
|
sskjames/tamilscriptconverter
|
src/main/java/org/tamilscriptconverter/Main.java
|
Java
|
apache-2.0
| 889
|
/*
* Copyright 2006 The Depan Project Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.depan.graph.basic;
import com.google.devtools.depan.graph.api.Edge;
import com.google.devtools.depan.graph.api.Node;
import com.google.devtools.depan.graph.api.Relation;
/**
* @author <a href="leeca@google.com">Lee Carver</a>
* @param <T> Node content type.
*/
public class BasicEdge<T> implements Edge<T> {
private final Node<? extends T> head;
private final Node<? extends T> tail;
private final Relation relation;
public BasicEdge(final Relation relation,
final Node<? extends T> head, final Node<? extends T> tail) {
this.relation = relation;
this.head = head;
this.tail = tail;
}
@Override
public Relation getRelation() {
return relation;
}
@Override
public Node<? extends T> getHead() {
return head;
}
@Override
public Node<? extends T> getTail() {
return tail;
}
}
|
google/depan
|
DepanCore/prod/src/com/google/devtools/depan/graph/basic/BasicEdge.java
|
Java
|
apache-2.0
| 1,482
|
/*
Copyright 2020 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1beta1
import (
"context"
"github.com/google/uuid"
)
const (
uuidPrefix = "knative-kafka-source-"
)
// SetDefaults ensures KafkaSource reflects the default values.
func (k *KafkaSource) SetDefaults(ctx context.Context) {
if k != nil && k.Spec.ConsumerGroup == "" {
k.Spec.ConsumerGroup = uuidPrefix + uuid.New().String()
}
}
|
knative/client-contrib
|
plugins/source-kafka/vendor/knative.dev/eventing-contrib/kafka/source/pkg/apis/sources/v1beta1/kafka_defaults.go
|
GO
|
apache-2.0
| 912
|
package com.weisong.common.messaging;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import com.weisong.common.messaging.admin.AbstractMMessagingConfigSupport;
public class MBinding {
private MExchange exchange;
private MQueue queue;
private String routingKey;
public MBinding(MExchange exchange, MQueue queue, String routingKey) {
this.exchange = exchange;
this.queue = queue;
this.routingKey = routingKey;
}
public Binding getBinding(AbstractMMessagingConfigSupport configSupport) {
return BindingBuilder
.bind(MQueue.convert(queue))
.to(MExchange.convert(exchange))
.with(routingKey).noargs();
}
}
|
weisong44/weisong-common-rabbitmq
|
src/main/java/com/weisong/common/messaging/MBinding.java
|
Java
|
apache-2.0
| 698
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.