repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
larrystone/BC-26-More-Recipes | server/tests/models/recipe.js | 6393 | /* eslint-disable no-unused-expressions */
import { expect } from 'chai';
import { Recipe } from '../../models';
import * as seedData from '../../seedData/testSeedData';
let name;
let userId;
let recipeId;
describe('RECIPE MODEL', () => {
before((done) => {
Recipe.destroy({
truncate: true,
cascade: true,
restartIdentity: true
})
.then(() => {
done();
});
});
it('should create a new recipe', (done) => {
Recipe.create(seedData.validRecipe)
.then((recipe) => {
name = recipe.dataValues.name;
recipeId = recipe.dataValues.id;
userId = recipe.dataValues.userId;
expect(recipe.dataValues).to.have.property('id');
expect(recipe.dataValues).to.have.property('name');
expect(recipe.dataValues).to.have.property('description');
expect(recipe.dataValues).to.have.property('ingredients');
expect(recipe.dataValues).to.have.property('createdAt');
expect(recipe.dataValues).to.have.property('updatedAt');
expect(recipe.dataValues).to.have.property('downvotes');
expect(recipe.dataValues).to.have.property('upvotes');
expect(recipe.dataValues.name).to.equal(seedData.validRecipe.name);
expect(recipe.dataValues.description)
.to.equal(seedData.validRecipe.description);
expect(recipe.dataValues.ingredients)
.to.equal(seedData.validRecipe.ingredients);
expect(recipe.dataValues.createdAt).to.exist;
expect(recipe.dataValues.updatedAt).to.exist;
expect(recipe.dataValues.viewCount).to.exist;
done();
});
});
it(
'should throw a validation error for an empty recipe name ',
(done) => {
Recipe.create(seedData.recipeWithNoName)
.catch((error) => {
expect(error.errors[0].message)
.to.equal('recipe name cannot be empty');
expect(error.errors[0].type).to.equal('Validation error');
done();
});
}
);
it('should throw a validation error for an empty ingredient list', (done) => {
Recipe.create(seedData.recipeWithNoIngredient)
.catch((error) => {
expect(error.errors).to.be.an('array');
expect(error.errors[0].message).to.equal('ingredients cannot be empty');
expect(error.errors[0].type).to.equal('Validation error');
done();
});
});
it('should throw a validation error for a null procedure ', (done) => {
Recipe.create(seedData.recipeWithNoProcedure)
.catch((error) => {
expect(error.errors).to.be.an('array');
expect(error.errors[0].message).to.equal('enter procedure clearly');
expect(error.errors[0].type).to.equal('Validation error');
done();
});
});
it('should be able to find recipe by Id', (done) => {
Recipe.findById(recipeId)
.then((recipe) => {
expect(recipe.dataValues).to.have.property('id');
expect(recipe.dataValues).to.have.property('name');
expect(recipe.dataValues).to.have.property('description');
expect(recipe.dataValues).to.have.property('createdAt');
expect(recipe.dataValues).to.have.property('updatedAt');
expect(recipe.dataValues).to.have.property('ingredients');
expect(recipe.dataValues.id).to.equal(recipeId);
expect(recipe.dataValues.name).to.equal(seedData.validRecipe.name);
expect(recipe.dataValues.description)
.to.equal(seedData.validRecipe.description);
expect(recipe.dataValues.createdAt).to.exist;
expect(recipe.dataValues.updatedAt).to.exist;
done();
});
});
it('should be able to find recipe by name', (done) => {
Recipe.findOne({
where: {
name
}
})
.then((recipe) => {
expect(recipe.dataValues).to.have.property('id');
expect(recipe.dataValues).to.have.property('name');
expect(recipe.dataValues).to.have.property('description');
expect(recipe.dataValues).to.have.property('createdAt');
expect(recipe.dataValues).to.have.property('updatedAt');
expect(recipe.dataValues).to.have.property('ingredients');
expect(recipe.dataValues.id).to.equal(recipeId);
expect(recipe.dataValues.name).to.equal(seedData.validRecipe.name);
expect(recipe.dataValues.description)
.to.equal(seedData.validRecipe.description);
expect(recipe.dataValues.createdAt).to.exist;
expect(recipe.dataValues.updatedAt).to.exist;
done();
});
});
it('should be able to find recipe by userId', (done) => {
Recipe.findAll({
where: {
userId
}
})
.then((recipe) => {
expect(recipe).to.be.an('array');
expect(recipe.length).to.equal(1);
expect(recipe[0].dataValues).to.have.property('id');
expect(recipe[0].dataValues).to.have.property('name');
expect(recipe[0].dataValues).to.have.property('description');
expect(recipe[0].dataValues).to.have.property('ingredients');
expect(recipe[0].dataValues).to.have.property('procedure');
expect(recipe[0].dataValues.id).to.equal(recipeId);
expect(recipe[0].dataValues.name).to.equal(seedData.validRecipe.name);
expect(recipe[0].dataValues.ingredients)
.to.equal(seedData.validRecipe.ingredients);
expect(recipe[0].dataValues.procedure)
.to.equal(seedData.validRecipe.procedure);
done();
});
});
it('should be able to find all recipes in the database', (done) => {
Recipe.findAll()
.then((recipe) => {
expect(recipe).to.be.an('array');
expect(recipe.length).to.equal(1);
expect(recipe[0].dataValues).to.have.property('id');
expect(recipe[0].dataValues).to.have.property('name');
expect(recipe[0].dataValues).to.have.property('description');
expect(recipe[0].dataValues).to.have.property('ingredients');
expect(recipe[0].dataValues).to.have.property('procedure');
expect(recipe[0].dataValues.id).to.equal(recipeId);
expect(recipe[0].dataValues.name).to.equal(seedData.validRecipe.name);
expect(recipe[0].dataValues.ingredients)
.to.equal(seedData.validRecipe.ingredients);
expect(recipe[0].dataValues.procedure)
.to.equal(seedData.validRecipe.procedure);
done();
});
});
});
| apache-2.0 |
groupe-sii/ogham | ogham-test-classpath/src/main/java/fr/sii/ogham/test/classpath/core/exception/PackagedAppNameException.java | 441 | package fr.sii.ogham.test.classpath.core.exception;
public class PackagedAppNameException extends AdaptativeClasspathException {
/**
*
*/
private static final long serialVersionUID = 1L;
public PackagedAppNameException(String message, Throwable cause) {
super(message, cause);
}
public PackagedAppNameException(String message) {
super(message);
}
public PackagedAppNameException(Throwable cause) {
super(cause);
}
}
| apache-2.0 |
DavidMoore/Foundation | Code/Foundation/Models/IEntity.cs | 595 | namespace Foundation.Models
{
/// <summary>
/// Defines an entity. An entity is simply a model object that
/// has a unique identifier of type <typeparamref name="T"/>. If
/// the model object is stored in a database, <see cref="Id"/>
/// would be the primary key.
/// </summary>
/// <typeparam name="T">The type of the identifier field <see cref="Id"/>.</typeparam>
public interface IEntity<T>
{
/// <summary>
/// Unique identifier.
/// </summary>
/// <value>The id.</value>
T Id { get; set; }
}
} | apache-2.0 |
southasia/scada | ScadaScheme/ScadaSchemeCommon/FrmCondDialog.cs | 6644 | /*
* Copyright 2014 Mikhail Shiryaev
*
* 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.
*
*
* Product : Rapid SCADA
* Module : ScadaSchemeCommon
* Summary : Editing image visibility conditions form
*
* Author : Mikhail Shiryaev
* Created : 2012
* Modified : 2014
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Scada.Scheme
{
/// <summary>
/// Editing image visibility conditions form
/// <para>Форма редактирования условий вывода изображений</para>
/// </summary>
public partial class FrmCondDialog : Form
{
/// <summary>
/// Конструктор
/// </summary>
public FrmCondDialog()
{
InitializeComponent();
SelectedConds = null;
}
/// <summary>
/// Получить или установить выбранные условия
/// </summary>
public List<SchemeView.Condition> SelectedConds { get; set; }
/// <summary>
/// Установить доступность кнопок
/// </summary>
private void SetBtnsEnabled()
{
int selInd = lbCond.SelectedIndex;
if (selInd < 0)
{
btnDel.Enabled = false;
btnUp.Enabled = false;
btnDown.Enabled = false;
}
else
{
btnDel.Enabled = true;
btnUp.Enabled = selInd > 0;
btnDown.Enabled = selInd < lbCond.Items.Count - 1;
}
}
private void FrmCondDialog_Load(object sender, EventArgs e)
{
// перевод формы
Localization.TranslateForm(this, "Scada.Scheme.FrmCondDialog");
// вывод выбранных условий
if (SelectedConds != null)
{
lbCond.BeginUpdate();
foreach (SchemeView.Condition cond in SelectedConds)
lbCond.Items.Add(cond.Clone());
lbCond.EndUpdate();
if (lbCond.Items.Count > 0)
lbCond.SelectedIndex = 0;
}
}
private void lbCond_SelectedIndexChanged(object sender, EventArgs e)
{
// вывод свойств выбранного условия
propGrid.SelectedObject = lbCond.SelectedItem;
SetBtnsEnabled();
}
private void propGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
// перерисовка условия в списке
int selInd = lbCond.SelectedIndex;
if (selInd >= 0)
{
lbCond.SelectedIndexChanged -= lbCond_SelectedIndexChanged;
lbCond.BeginUpdate();
object item = lbCond.SelectedItem;
lbCond.Items.RemoveAt(selInd);
lbCond.Items.Insert(selInd, item);
lbCond.SelectedIndex = selInd;
lbCond.EndUpdate();
lbCond.SelectedIndexChanged += lbCond_SelectedIndexChanged;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
// добавление условия
SchemeView.Condition cond = new SchemeView.Condition();
lbCond.SelectedIndex = lbCond.Items.Add(cond);
propGrid.Select();
}
private void btnDel_Click(object sender, EventArgs e)
{
// удаление условия
int selInd = lbCond.SelectedIndex;
if (selInd >= 0)
{
lbCond.Items.RemoveAt(selInd);
int itemCnt = lbCond.Items.Count;
if (itemCnt > 0)
lbCond.SelectedIndex = selInd < itemCnt ? selInd : itemCnt - 1;
}
propGrid.Select();
}
private void btnUp_Click(object sender, EventArgs e)
{
// перемещение условия вверх
int selInd = lbCond.SelectedIndex;
if (selInd > 0)
{
lbCond.SelectedIndexChanged -= lbCond_SelectedIndexChanged;
lbCond.BeginUpdate();
object item = lbCond.SelectedItem;
lbCond.Items.RemoveAt(selInd);
lbCond.Items.Insert(selInd - 1, item);
lbCond.SelectedIndex = selInd - 1;
lbCond.EndUpdate();
lbCond.SelectedIndexChanged += lbCond_SelectedIndexChanged;
SetBtnsEnabled();
}
propGrid.Select();
}
private void btnDown_Click(object sender, EventArgs e)
{
// перемещение условия вверх
int selInd = lbCond.SelectedIndex;
int itemCnt = lbCond.Items.Count;
if (selInd < itemCnt - 1)
{
lbCond.SelectedIndexChanged -= lbCond_SelectedIndexChanged;
lbCond.BeginUpdate();
object item = lbCond.SelectedItem;
lbCond.Items.RemoveAt(selInd);
lbCond.Items.Insert(selInd + 1, item);
lbCond.SelectedIndex = selInd + 1;
lbCond.EndUpdate();
lbCond.SelectedIndexChanged += lbCond_SelectedIndexChanged;
SetBtnsEnabled();
}
propGrid.Select();
}
private void btnOK_Click(object sender, EventArgs e)
{
// заполнение списка выбранных условий
if (lbCond.Items.Count > 0)
{
SelectedConds = new List<SchemeView.Condition>();
foreach (object item in lbCond.Items)
SelectedConds.Add((SchemeView.Condition)item);
}
else
{
SelectedConds = null;
}
DialogResult = DialogResult.OK;
}
}
}
| apache-2.0 |
JoelMarcey/buck | src/com/facebook/buck/distributed/DistBuildConfig.java | 3667 | /*
* Copyright 2016-present Facebook, 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.facebook.buck.distributed;
import com.facebook.buck.cli.BuckConfig;
import com.facebook.buck.distributed.thrift.BuildMode;
import com.facebook.buck.slb.SlbBuckConfig;
import com.google.common.collect.ImmutableList;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
public class DistBuildConfig {
public static final String STAMPEDE_SECTION = "stampede";
private static final String FRONTEND_REQUEST_TIMEOUT_MILLIS = "stampede_timeout_millis";
private static final long REQUEST_TIMEOUT_MILLIS_DEFAULT_VALUE = TimeUnit.SECONDS.toMillis(60);
private static final String ALWAYS_MATERIALIZE_WHITELIST = "always_materialize_whitelist";
private static final String ENABLE_SLOW_LOCAL_BUILD_FALLBACK = "enable_slow_local_build_fallback";
private static final boolean ENABLE_SLOW_LOCAL_BUILD_FALLBACK_DEFAULT_VALUE = false;
private static final String BUILD_MODE = "build_mode";
private static final BuildMode BUILD_MODE_DEFAULT_VALUE = BuildMode.REMOTE_BUILD;
private static final String NUMBER_OF_MINIONS = "number_of_minions";
private static final Integer NUMBER_OF_MINIONS_DEFAULT_VALUE = 2;
private final SlbBuckConfig frontendConfig;
private final BuckConfig buckConfig;
public DistBuildConfig(BuckConfig config) {
this.buckConfig = config;
this.frontendConfig = new SlbBuckConfig(config, STAMPEDE_SECTION);
}
public SlbBuckConfig getFrontendConfig() {
return frontendConfig;
}
public BuckConfig getBuckConfig() {
return buckConfig;
}
public Optional<ImmutableList<Path>> getOptionalPathWhitelist() {
return buckConfig.getOptionalPathList(STAMPEDE_SECTION, ALWAYS_MATERIALIZE_WHITELIST);
}
public long getFrontendRequestTimeoutMillis() {
return buckConfig
.getLong(STAMPEDE_SECTION, FRONTEND_REQUEST_TIMEOUT_MILLIS)
.orElse(REQUEST_TIMEOUT_MILLIS_DEFAULT_VALUE);
}
public BuildMode getBuildMode() {
return buckConfig
.getEnum(STAMPEDE_SECTION, BUILD_MODE, BuildMode.class)
.orElse(BUILD_MODE_DEFAULT_VALUE);
}
public int getNumberOfMinions() {
return buckConfig
.getInteger(STAMPEDE_SECTION, NUMBER_OF_MINIONS)
.orElse(NUMBER_OF_MINIONS_DEFAULT_VALUE);
}
/**
* Whether buck distributed build should stop building if remote/distributed build fails (true) or
* if it should fallback to building locally if remote/distributed build fails (false).
*/
public boolean isSlowLocalBuildFallbackModeEnabled() {
return buckConfig.getBooleanValue(
STAMPEDE_SECTION,
ENABLE_SLOW_LOCAL_BUILD_FALLBACK,
ENABLE_SLOW_LOCAL_BUILD_FALLBACK_DEFAULT_VALUE);
}
public OkHttpClient createOkHttpClient() {
return new OkHttpClient.Builder()
.connectTimeout(getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS)
.readTimeout(getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS)
.writeTimeout(getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS)
.build();
}
}
| apache-2.0 |
cedral/aws-sdk-cpp | aws-cpp-sdk-glacier/source/model/UploadMultipartPartRequest.cpp | 1669 | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/glacier/model/UploadMultipartPartRequest.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <aws/core/utils/HashingUtils.h>
#include <utility>
using namespace Aws::Glacier::Model;
using namespace Aws::Utils::Stream;
using namespace Aws::Utils;
using namespace Aws;
UploadMultipartPartRequest::UploadMultipartPartRequest() :
m_accountIdHasBeenSet(false),
m_vaultNameHasBeenSet(false),
m_uploadIdHasBeenSet(false),
m_checksumHasBeenSet(false),
m_rangeHasBeenSet(false)
{
}
Aws::Http::HeaderValueCollection UploadMultipartPartRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("x-amz-glacier-version", "2012-06-01"));
Aws::StringStream ss;
if(m_checksumHasBeenSet)
{
ss << m_checksum;
headers.emplace("x-amz-sha256-tree-hash", ss.str());
ss.str("");
}
if(m_rangeHasBeenSet)
{
ss << m_range;
headers.emplace("content-range", ss.str());
ss.str("");
}
return headers;
}
| apache-2.0 |
Blankj/AndroidUtilCode | lib/utilcode/src/main/java/com/blankj/utilcode/util/LogUtils.java | 47013 | package com.blankj.utilcode.util;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Formatter;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import androidx.annotation.IntDef;
import androidx.annotation.IntRange;
import androidx.annotation.RequiresApi;
import androidx.collection.SimpleArrayMap;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/09/21
* desc : utils about log
* </pre>
*/
public final class LogUtils {
public static final int V = Log.VERBOSE;
public static final int D = Log.DEBUG;
public static final int I = Log.INFO;
public static final int W = Log.WARN;
public static final int E = Log.ERROR;
public static final int A = Log.ASSERT;
@IntDef({V, D, I, W, E, A})
@Retention(RetentionPolicy.SOURCE)
public @interface TYPE {
}
private static final char[] T = new char[]{'V', 'D', 'I', 'W', 'E', 'A'};
private static final int FILE = 0x10;
private static final int JSON = 0x20;
private static final int XML = 0x30;
private static final String FILE_SEP = System.getProperty("file.separator");
private static final String LINE_SEP = System.getProperty("line.separator");
private static final String TOP_CORNER = "┌";
private static final String MIDDLE_CORNER = "├";
private static final String LEFT_BORDER = "│ ";
private static final String BOTTOM_CORNER = "└";
private static final String SIDE_DIVIDER =
"────────────────────────────────────────────────────────";
private static final String MIDDLE_DIVIDER =
"┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄";
private static final String TOP_BORDER = TOP_CORNER + SIDE_DIVIDER + SIDE_DIVIDER;
private static final String MIDDLE_BORDER = MIDDLE_CORNER + MIDDLE_DIVIDER + MIDDLE_DIVIDER;
private static final String BOTTOM_BORDER = BOTTOM_CORNER + SIDE_DIVIDER + SIDE_DIVIDER;
private static final int MAX_LEN = 1100;// fit for Chinese character
private static final String NOTHING = "log nothing";
private static final String NULL = "null";
private static final String ARGS = "args";
private static final String PLACEHOLDER = " ";
private static final Config CONFIG = new Config();
private static SimpleDateFormat simpleDateFormat;
private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();
private static final SimpleArrayMap<Class, IFormatter> I_FORMATTER_MAP = new SimpleArrayMap<>();
private LogUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
public static Config getConfig() {
return CONFIG;
}
public static void v(final Object... contents) {
log(V, CONFIG.getGlobalTag(), contents);
}
public static void vTag(final String tag, final Object... contents) {
log(V, tag, contents);
}
public static void d(final Object... contents) {
log(D, CONFIG.getGlobalTag(), contents);
}
public static void dTag(final String tag, final Object... contents) {
log(D, tag, contents);
}
public static void i(final Object... contents) {
log(I, CONFIG.getGlobalTag(), contents);
}
public static void iTag(final String tag, final Object... contents) {
log(I, tag, contents);
}
public static void w(final Object... contents) {
log(W, CONFIG.getGlobalTag(), contents);
}
public static void wTag(final String tag, final Object... contents) {
log(W, tag, contents);
}
public static void e(final Object... contents) {
log(E, CONFIG.getGlobalTag(), contents);
}
public static void eTag(final String tag, final Object... contents) {
log(E, tag, contents);
}
public static void a(final Object... contents) {
log(A, CONFIG.getGlobalTag(), contents);
}
public static void aTag(final String tag, final Object... contents) {
log(A, tag, contents);
}
public static void file(final Object content) {
log(FILE | D, CONFIG.getGlobalTag(), content);
}
public static void file(@TYPE final int type, final Object content) {
log(FILE | type, CONFIG.getGlobalTag(), content);
}
public static void file(final String tag, final Object content) {
log(FILE | D, tag, content);
}
public static void file(@TYPE final int type, final String tag, final Object content) {
log(FILE | type, tag, content);
}
public static void json(final Object content) {
log(JSON | D, CONFIG.getGlobalTag(), content);
}
public static void json(@TYPE final int type, final Object content) {
log(JSON | type, CONFIG.getGlobalTag(), content);
}
public static void json(final String tag, final Object content) {
log(JSON | D, tag, content);
}
public static void json(@TYPE final int type, final String tag, final Object content) {
log(JSON | type, tag, content);
}
public static void xml(final String content) {
log(XML | D, CONFIG.getGlobalTag(), content);
}
public static void xml(@TYPE final int type, final String content) {
log(XML | type, CONFIG.getGlobalTag(), content);
}
public static void xml(final String tag, final String content) {
log(XML | D, tag, content);
}
public static void xml(@TYPE final int type, final String tag, final String content) {
log(XML | type, tag, content);
}
public static void log(final int type, final String tag, final Object... contents) {
if (!CONFIG.isLogSwitch()) return;
final int type_low = type & 0x0f, type_high = type & 0xf0;
if (CONFIG.isLog2ConsoleSwitch() || CONFIG.isLog2FileSwitch() || type_high == FILE) {
if (type_low < CONFIG.mConsoleFilter && type_low < CONFIG.mFileFilter) return;
final TagHead tagHead = processTagAndHead(tag);
final String body = processBody(type_high, contents);
if (CONFIG.isLog2ConsoleSwitch() && type_high != FILE && type_low >= CONFIG.mConsoleFilter) {
print2Console(type_low, tagHead.tag, tagHead.consoleHead, body);
}
if ((CONFIG.isLog2FileSwitch() || type_high == FILE) && type_low >= CONFIG.mFileFilter) {
EXECUTOR.execute(new Runnable() {
@Override
public void run() {
print2File(type_low, tagHead.tag, tagHead.fileHead + body);
}
});
}
}
}
public static String getCurrentLogFilePath() {
return getCurrentLogFilePath(new Date());
}
public static List<File> getLogFiles() {
String dir = CONFIG.getDir();
File logDir = new File(dir);
if (!logDir.exists()) return new ArrayList<>();
File[] files = logDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return isMatchLogFileName(name);
}
});
List<File> list = new ArrayList<>();
Collections.addAll(list, files);
return list;
}
private static TagHead processTagAndHead(String tag) {
if (!CONFIG.mTagIsSpace && !CONFIG.isLogHeadSwitch()) {
tag = CONFIG.getGlobalTag();
} else {
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
final int stackIndex = 3 + CONFIG.getStackOffset();
if (stackIndex >= stackTrace.length) {
StackTraceElement targetElement = stackTrace[3];
final String fileName = getFileName(targetElement);
if (CONFIG.mTagIsSpace && UtilsBridge.isSpace(tag)) {
int index = fileName.indexOf('.');// Use proguard may not find '.'.
tag = index == -1 ? fileName : fileName.substring(0, index);
}
return new TagHead(tag, null, ": ");
}
StackTraceElement targetElement = stackTrace[stackIndex];
final String fileName = getFileName(targetElement);
if (CONFIG.mTagIsSpace && UtilsBridge.isSpace(tag)) {
int index = fileName.indexOf('.');// Use proguard may not find '.'.
tag = index == -1 ? fileName : fileName.substring(0, index);
}
if (CONFIG.isLogHeadSwitch()) {
String tName = Thread.currentThread().getName();
final String head = new Formatter()
.format("%s, %s.%s(%s:%d)",
tName,
targetElement.getClassName(),
targetElement.getMethodName(),
fileName,
targetElement.getLineNumber())
.toString();
final String fileHead = " [" + head + "]: ";
if (CONFIG.getStackDeep() <= 1) {
return new TagHead(tag, new String[]{head}, fileHead);
} else {
final String[] consoleHead =
new String[Math.min(
CONFIG.getStackDeep(),
stackTrace.length - stackIndex
)];
consoleHead[0] = head;
int spaceLen = tName.length() + 2;
String space = new Formatter().format("%" + spaceLen + "s", "").toString();
for (int i = 1, len = consoleHead.length; i < len; ++i) {
targetElement = stackTrace[i + stackIndex];
consoleHead[i] = new Formatter()
.format("%s%s.%s(%s:%d)",
space,
targetElement.getClassName(),
targetElement.getMethodName(),
getFileName(targetElement),
targetElement.getLineNumber())
.toString();
}
return new TagHead(tag, consoleHead, fileHead);
}
}
}
return new TagHead(tag, null, ": ");
}
private static String getFileName(final StackTraceElement targetElement) {
String fileName = targetElement.getFileName();
if (fileName != null) return fileName;
// If name of file is null, should add
// "-keepattributes SourceFile,LineNumberTable" in proguard file.
String className = targetElement.getClassName();
String[] classNameInfo = className.split("\\.");
if (classNameInfo.length > 0) {
className = classNameInfo[classNameInfo.length - 1];
}
int index = className.indexOf('$');
if (index != -1) {
className = className.substring(0, index);
}
return className + ".java";
}
private static String processBody(final int type, final Object... contents) {
String body = NULL;
if (contents != null) {
if (contents.length == 1) {
body = formatObject(type, contents[0]);
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0, len = contents.length; i < len; ++i) {
Object content = contents[i];
sb.append(ARGS)
.append("[")
.append(i)
.append("]")
.append(" = ")
.append(formatObject(content))
.append(LINE_SEP);
}
body = sb.toString();
}
}
return body.length() == 0 ? NOTHING : body;
}
private static String formatObject(int type, Object object) {
if (object == null) return NULL;
if (type == JSON) return LogFormatter.object2String(object, JSON);
if (type == XML) return LogFormatter.object2String(object, XML);
return formatObject(object);
}
private static String formatObject(Object object) {
if (object == null) return NULL;
if (!I_FORMATTER_MAP.isEmpty()) {
IFormatter iFormatter = I_FORMATTER_MAP.get(getClassFromObject(object));
if (iFormatter != null) {
//noinspection unchecked
return iFormatter.format(object);
}
}
return LogFormatter.object2String(object);
}
private static void print2Console(final int type,
final String tag,
final String[] head,
final String msg) {
if (CONFIG.isSingleTagSwitch()) {
printSingleTagMsg(type, tag, processSingleTagMsg(type, tag, head, msg));
} else {
printBorder(type, tag, true);
printHead(type, tag, head);
printMsg(type, tag, msg);
printBorder(type, tag, false);
}
}
private static void printBorder(final int type, final String tag, boolean isTop) {
if (CONFIG.isLogBorderSwitch()) {
print2Console(type, tag, isTop ? TOP_BORDER : BOTTOM_BORDER);
}
}
private static void printHead(final int type, final String tag, final String[] head) {
if (head != null) {
for (String aHead : head) {
print2Console(type, tag, CONFIG.isLogBorderSwitch() ? LEFT_BORDER + aHead : aHead);
}
if (CONFIG.isLogBorderSwitch()) print2Console(type, tag, MIDDLE_BORDER);
}
}
private static void printMsg(final int type, final String tag, final String msg) {
int len = msg.length();
int countOfSub = len / MAX_LEN;
if (countOfSub > 0) {
int index = 0;
for (int i = 0; i < countOfSub; i++) {
printSubMsg(type, tag, msg.substring(index, index + MAX_LEN));
index += MAX_LEN;
}
if (index != len) {
printSubMsg(type, tag, msg.substring(index, len));
}
} else {
printSubMsg(type, tag, msg);
}
}
private static void printSubMsg(final int type, final String tag, final String msg) {
if (!CONFIG.isLogBorderSwitch()) {
print2Console(type, tag, msg);
return;
}
StringBuilder sb = new StringBuilder();
String[] lines = msg.split(LINE_SEP);
for (String line : lines) {
print2Console(type, tag, LEFT_BORDER + line);
}
}
private static String processSingleTagMsg(final int type,
final String tag,
final String[] head,
final String msg) {
StringBuilder sb = new StringBuilder();
if (CONFIG.isLogBorderSwitch()) {
sb.append(PLACEHOLDER).append(LINE_SEP);
sb.append(TOP_BORDER).append(LINE_SEP);
if (head != null) {
for (String aHead : head) {
sb.append(LEFT_BORDER).append(aHead).append(LINE_SEP);
}
sb.append(MIDDLE_BORDER).append(LINE_SEP);
}
for (String line : msg.split(LINE_SEP)) {
sb.append(LEFT_BORDER).append(line).append(LINE_SEP);
}
sb.append(BOTTOM_BORDER);
} else {
if (head != null) {
sb.append(PLACEHOLDER).append(LINE_SEP);
for (String aHead : head) {
sb.append(aHead).append(LINE_SEP);
}
}
sb.append(msg);
}
return sb.toString();
}
private static void printSingleTagMsg(final int type, final String tag, final String msg) {
int len = msg.length();
int countOfSub = CONFIG.isLogBorderSwitch() ? (len - BOTTOM_BORDER.length()) / MAX_LEN : len / MAX_LEN;
if (countOfSub > 0) {
if (CONFIG.isLogBorderSwitch()) {
print2Console(type, tag, msg.substring(0, MAX_LEN) + LINE_SEP + BOTTOM_BORDER);
int index = MAX_LEN;
for (int i = 1; i < countOfSub; i++) {
print2Console(type, tag, PLACEHOLDER + LINE_SEP + TOP_BORDER + LINE_SEP
+ LEFT_BORDER + msg.substring(index, index + MAX_LEN)
+ LINE_SEP + BOTTOM_BORDER);
index += MAX_LEN;
}
if (index != len - BOTTOM_BORDER.length()) {
print2Console(type, tag, PLACEHOLDER + LINE_SEP + TOP_BORDER + LINE_SEP
+ LEFT_BORDER + msg.substring(index, len));
}
} else {
print2Console(type, tag, msg.substring(0, MAX_LEN));
int index = MAX_LEN;
for (int i = 1; i < countOfSub; i++) {
print2Console(type, tag,
PLACEHOLDER + LINE_SEP + msg.substring(index, index + MAX_LEN));
index += MAX_LEN;
}
if (index != len) {
print2Console(type, tag, PLACEHOLDER + LINE_SEP + msg.substring(index, len));
}
}
} else {
print2Console(type, tag, msg);
}
}
private static void print2Console(int type, String tag, String msg) {
Log.println(type, tag, msg);
if (CONFIG.mOnConsoleOutputListener != null) {
CONFIG.mOnConsoleOutputListener.onConsoleOutput(type, tag, msg);
}
}
private static void print2File(final int type, final String tag, final String msg) {
Date d = new Date();
String format = getSdf().format(d);
String date = format.substring(0, 10);
String currentLogFilePath = getCurrentLogFilePath(d);
if (!createOrExistsFile(currentLogFilePath, date)) {
Log.e("LogUtils", "create " + currentLogFilePath + " failed!");
return;
}
String time = format.substring(11);
final String content = time +
T[type - V] +
"/" +
tag +
msg +
LINE_SEP;
input2File(currentLogFilePath, content);
}
private static String getCurrentLogFilePath(Date d) {
String format = getSdf().format(d);
String date = format.substring(0, 10);
return CONFIG.getDir() + CONFIG.getFilePrefix() + "_"
+ date + "_" +
CONFIG.getProcessName() + CONFIG.getFileExtension();
}
private static SimpleDateFormat getSdf() {
if (simpleDateFormat == null) {
simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd HH:mm:ss.SSS ", Locale.getDefault());
}
return simpleDateFormat;
}
private static boolean createOrExistsFile(final String filePath, final String date) {
File file = new File(filePath);
if (file.exists()) return file.isFile();
if (!UtilsBridge.createOrExistsDir(file.getParentFile())) return false;
try {
deleteDueLogs(filePath, date);
boolean isCreate = file.createNewFile();
if (isCreate) {
printDeviceInfo(filePath, date);
}
return isCreate;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private static void deleteDueLogs(final String filePath, final String date) {
if (CONFIG.getSaveDays() <= 0) return;
File file = new File(filePath);
File parentFile = file.getParentFile();
File[] files = parentFile.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return isMatchLogFileName(name);
}
});
if (files == null || files.length <= 0) return;
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd", Locale.getDefault());
try {
long dueMillis = sdf.parse(date).getTime() - CONFIG.getSaveDays() * 86400000L;
for (final File aFile : files) {
String name = aFile.getName();
int l = name.length();
String logDay = findDate(name);
if (sdf.parse(logDay).getTime() <= dueMillis) {
EXECUTOR.execute(new Runnable() {
@Override
public void run() {
boolean delete = aFile.delete();
if (!delete) {
Log.e("LogUtils", "delete " + aFile + " failed!");
}
}
});
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
private static boolean isMatchLogFileName(String name) {
return name.matches("^" + CONFIG.getFilePrefix() + "_[0-9]{4}_[0-9]{2}_[0-9]{2}_.*$");
}
private static String findDate(String str) {
Pattern pattern = Pattern.compile("[0-9]{4}_[0-9]{2}_[0-9]{2}");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
return matcher.group();
}
return "";
}
private static void printDeviceInfo(final String filePath, final String date) {
CONFIG.mFileHead.addFirst("Date of Log", date);
input2File(filePath, CONFIG.mFileHead.toString());
}
private static void input2File(final String filePath, final String input) {
if (CONFIG.mFileWriter == null) {
UtilsBridge.writeFileFromString(filePath, input, true);
} else {
CONFIG.mFileWriter.write(filePath, input);
}
if (CONFIG.mOnFileOutputListener != null) {
CONFIG.mOnFileOutputListener.onFileOutput(filePath, input);
}
}
public static final class Config {
private String mDefaultDir; // The default storage directory of log.
private String mDir; // The storage directory of log.
private String mFilePrefix = "util";// The file prefix of log.
private String mFileExtension = ".txt";// The file extension of log.
private boolean mLogSwitch = true; // The switch of log.
private boolean mLog2ConsoleSwitch = true; // The logcat's switch of log.
private String mGlobalTag = ""; // The global tag of log.
private boolean mTagIsSpace = true; // The global tag is space.
private boolean mLogHeadSwitch = true; // The head's switch of log.
private boolean mLog2FileSwitch = false; // The file's switch of log.
private boolean mLogBorderSwitch = true; // The border's switch of log.
private boolean mSingleTagSwitch = true; // The single tag of log.
private int mConsoleFilter = V; // The console's filter of log.
private int mFileFilter = V; // The file's filter of log.
private int mStackDeep = 1; // The stack's deep of log.
private int mStackOffset = 0; // The stack's offset of log.
private int mSaveDays = -1; // The save days of log.
private String mProcessName = UtilsBridge.getCurrentProcessName();
private IFileWriter mFileWriter;
private OnConsoleOutputListener mOnConsoleOutputListener;
private OnFileOutputListener mOnFileOutputListener;
private UtilsBridge.FileHead mFileHead = new UtilsBridge.FileHead("Log");
private Config() {
if (UtilsBridge.isSDCardEnableByEnvironment()
&& Utils.getApp().getExternalFilesDir(null) != null)
mDefaultDir = Utils.getApp().getExternalFilesDir(null) + FILE_SEP + "log" + FILE_SEP;
else {
mDefaultDir = Utils.getApp().getFilesDir() + FILE_SEP + "log" + FILE_SEP;
}
}
public final Config setLogSwitch(final boolean logSwitch) {
mLogSwitch = logSwitch;
return this;
}
public final Config setConsoleSwitch(final boolean consoleSwitch) {
mLog2ConsoleSwitch = consoleSwitch;
return this;
}
public final Config setGlobalTag(final String tag) {
if (UtilsBridge.isSpace(tag)) {
mGlobalTag = "";
mTagIsSpace = true;
} else {
mGlobalTag = tag;
mTagIsSpace = false;
}
return this;
}
public final Config setLogHeadSwitch(final boolean logHeadSwitch) {
mLogHeadSwitch = logHeadSwitch;
return this;
}
public final Config setLog2FileSwitch(final boolean log2FileSwitch) {
mLog2FileSwitch = log2FileSwitch;
return this;
}
public final Config setDir(final String dir) {
if (UtilsBridge.isSpace(dir)) {
mDir = null;
} else {
mDir = dir.endsWith(FILE_SEP) ? dir : dir + FILE_SEP;
}
return this;
}
public final Config setDir(final File dir) {
mDir = dir == null ? null : (dir.getAbsolutePath() + FILE_SEP);
return this;
}
public final Config setFilePrefix(final String filePrefix) {
if (UtilsBridge.isSpace(filePrefix)) {
mFilePrefix = "util";
} else {
mFilePrefix = filePrefix;
}
return this;
}
public final Config setFileExtension(final String fileExtension) {
if (UtilsBridge.isSpace(fileExtension)) {
mFileExtension = ".txt";
} else {
if (fileExtension.startsWith(".")) {
mFileExtension = fileExtension;
} else {
mFileExtension = "." + fileExtension;
}
}
return this;
}
public final Config setBorderSwitch(final boolean borderSwitch) {
mLogBorderSwitch = borderSwitch;
return this;
}
public final Config setSingleTagSwitch(final boolean singleTagSwitch) {
mSingleTagSwitch = singleTagSwitch;
return this;
}
public final Config setConsoleFilter(@TYPE final int consoleFilter) {
mConsoleFilter = consoleFilter;
return this;
}
public final Config setFileFilter(@TYPE final int fileFilter) {
mFileFilter = fileFilter;
return this;
}
public final Config setStackDeep(@IntRange(from = 1) final int stackDeep) {
mStackDeep = stackDeep;
return this;
}
public final Config setStackOffset(@IntRange(from = 0) final int stackOffset) {
mStackOffset = stackOffset;
return this;
}
public final Config setSaveDays(@IntRange(from = 1) final int saveDays) {
mSaveDays = saveDays;
return this;
}
public final <T> Config addFormatter(final IFormatter<T> iFormatter) {
if (iFormatter != null) {
I_FORMATTER_MAP.put(getTypeClassFromParadigm(iFormatter), iFormatter);
}
return this;
}
public final Config setFileWriter(final IFileWriter fileWriter) {
mFileWriter = fileWriter;
return this;
}
public final Config setOnConsoleOutputListener(final OnConsoleOutputListener listener) {
mOnConsoleOutputListener = listener;
return this;
}
public final Config setOnFileOutputListener(final OnFileOutputListener listener) {
mOnFileOutputListener = listener;
return this;
}
public final Config addFileExtraHead(final Map<String, String> fileExtraHead) {
mFileHead.append(fileExtraHead);
return this;
}
public final Config addFileExtraHead(final String key, final String value) {
mFileHead.append(key, value);
return this;
}
public final String getProcessName() {
if (mProcessName == null) return "";
return mProcessName.replace(":", "_");
}
public final String getDefaultDir() {
return mDefaultDir;
}
public final String getDir() {
return mDir == null ? mDefaultDir : mDir;
}
public final String getFilePrefix() {
return mFilePrefix;
}
public final String getFileExtension() {
return mFileExtension;
}
public final boolean isLogSwitch() {
return mLogSwitch;
}
public final boolean isLog2ConsoleSwitch() {
return mLog2ConsoleSwitch;
}
public final String getGlobalTag() {
if (UtilsBridge.isSpace(mGlobalTag)) return "";
return mGlobalTag;
}
public final boolean isLogHeadSwitch() {
return mLogHeadSwitch;
}
public final boolean isLog2FileSwitch() {
return mLog2FileSwitch;
}
public final boolean isLogBorderSwitch() {
return mLogBorderSwitch;
}
public final boolean isSingleTagSwitch() {
return mSingleTagSwitch;
}
public final char getConsoleFilter() {
return T[mConsoleFilter - V];
}
public final char getFileFilter() {
return T[mFileFilter - V];
}
public final int getStackDeep() {
return mStackDeep;
}
public final int getStackOffset() {
return mStackOffset;
}
public final int getSaveDays() {
return mSaveDays;
}
public final boolean haveSetOnConsoleOutputListener() {
return mOnConsoleOutputListener != null;
}
public final boolean haveSetOnFileOutputListener() {
return mOnFileOutputListener != null;
}
@Override
public String toString() {
return "process: " + getProcessName()
+ LINE_SEP + "logSwitch: " + isLogSwitch()
+ LINE_SEP + "consoleSwitch: " + isLog2ConsoleSwitch()
+ LINE_SEP + "tag: " + (getGlobalTag().equals("") ? "null" : getGlobalTag())
+ LINE_SEP + "headSwitch: " + isLogHeadSwitch()
+ LINE_SEP + "fileSwitch: " + isLog2FileSwitch()
+ LINE_SEP + "dir: " + getDir()
+ LINE_SEP + "filePrefix: " + getFilePrefix()
+ LINE_SEP + "borderSwitch: " + isLogBorderSwitch()
+ LINE_SEP + "singleTagSwitch: " + isSingleTagSwitch()
+ LINE_SEP + "consoleFilter: " + getConsoleFilter()
+ LINE_SEP + "fileFilter: " + getFileFilter()
+ LINE_SEP + "stackDeep: " + getStackDeep()
+ LINE_SEP + "stackOffset: " + getStackOffset()
+ LINE_SEP + "saveDays: " + getSaveDays()
+ LINE_SEP + "formatter: " + I_FORMATTER_MAP
+ LINE_SEP + "fileWriter: " + mFileWriter
+ LINE_SEP + "onConsoleOutputListener: " + mOnConsoleOutputListener
+ LINE_SEP + "onFileOutputListener: " + mOnFileOutputListener
+ LINE_SEP + "fileExtraHeader: " + mFileHead.getAppended();
}
}
public abstract static class IFormatter<T> {
public abstract String format(T t);
}
public interface IFileWriter {
void write(String file, String content);
}
public interface OnConsoleOutputListener {
void onConsoleOutput(@TYPE int type, String tag, String content);
}
public interface OnFileOutputListener {
void onFileOutput(String filePath, String content);
}
private final static class TagHead {
String tag;
String[] consoleHead;
String fileHead;
TagHead(String tag, String[] consoleHead, String fileHead) {
this.tag = tag;
this.consoleHead = consoleHead;
this.fileHead = fileHead;
}
}
private final static class LogFormatter {
static String object2String(Object object) {
return object2String(object, -1);
}
static String object2String(Object object, int type) {
if (object.getClass().isArray()) return array2String(object);
if (object instanceof Throwable)
return UtilsBridge.getFullStackTrace((Throwable) object);
if (object instanceof Bundle) return bundle2String((Bundle) object);
if (object instanceof Intent) return intent2String((Intent) object);
if (type == JSON) {
return object2Json(object);
} else if (type == XML) {
return formatXml(object.toString());
}
return object.toString();
}
private static String bundle2String(Bundle bundle) {
Iterator<String> iterator = bundle.keySet().iterator();
if (!iterator.hasNext()) {
return "Bundle {}";
}
StringBuilder sb = new StringBuilder(128);
sb.append("Bundle { ");
for (; ; ) {
String key = iterator.next();
Object value = bundle.get(key);
sb.append(key).append('=');
if (value instanceof Bundle) {
sb.append(value == bundle ? "(this Bundle)" : bundle2String((Bundle) value));
} else {
sb.append(formatObject(value));
}
if (!iterator.hasNext()) return sb.append(" }").toString();
sb.append(',').append(' ');
}
}
private static String intent2String(Intent intent) {
StringBuilder sb = new StringBuilder(128);
sb.append("Intent { ");
boolean first = true;
String mAction = intent.getAction();
if (mAction != null) {
sb.append("act=").append(mAction);
first = false;
}
Set<String> mCategories = intent.getCategories();
if (mCategories != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("cat=[");
boolean firstCategory = true;
for (String c : mCategories) {
if (!firstCategory) {
sb.append(',');
}
sb.append(c);
firstCategory = false;
}
sb.append("]");
}
Uri mData = intent.getData();
if (mData != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("dat=").append(mData);
}
String mType = intent.getType();
if (mType != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("typ=").append(mType);
}
int mFlags = intent.getFlags();
if (mFlags != 0) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("flg=0x").append(Integer.toHexString(mFlags));
}
String mPackage = intent.getPackage();
if (mPackage != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("pkg=").append(mPackage);
}
ComponentName mComponent = intent.getComponent();
if (mComponent != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("cmp=").append(mComponent.flattenToShortString());
}
Rect mSourceBounds = intent.getSourceBounds();
if (mSourceBounds != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("bnds=").append(mSourceBounds.toShortString());
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
ClipData mClipData = intent.getClipData();
if (mClipData != null) {
if (!first) {
sb.append(' ');
}
first = false;
clipData2String(mClipData, sb);
}
}
Bundle mExtras = intent.getExtras();
if (mExtras != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("extras={");
sb.append(bundle2String(mExtras));
sb.append('}');
}
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
Intent mSelector = intent.getSelector();
if (mSelector != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("sel={");
sb.append(mSelector == intent ? "(this Intent)" : intent2String(mSelector));
sb.append("}");
}
}
sb.append(" }");
return sb.toString();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private static void clipData2String(ClipData clipData, StringBuilder sb) {
ClipData.Item item = clipData.getItemAt(0);
if (item == null) {
sb.append("ClipData.Item {}");
return;
}
sb.append("ClipData.Item { ");
String mHtmlText = item.getHtmlText();
if (mHtmlText != null) {
sb.append("H:");
sb.append(mHtmlText);
sb.append("}");
return;
}
CharSequence mText = item.getText();
if (mText != null) {
sb.append("T:");
sb.append(mText);
sb.append("}");
return;
}
Uri uri = item.getUri();
if (uri != null) {
sb.append("U:").append(uri);
sb.append("}");
return;
}
Intent intent = item.getIntent();
if (intent != null) {
sb.append("I:");
sb.append(intent2String(intent));
sb.append("}");
return;
}
sb.append("NULL");
sb.append("}");
}
private static String object2Json(Object object) {
if (object instanceof CharSequence) {
return UtilsBridge.formatJson(object.toString());
}
try {
return UtilsBridge.getGson4LogUtils().toJson(object);
} catch (Throwable t) {
return object.toString();
}
}
private static String formatJson(String json) {
try {
for (int i = 0, len = json.length(); i < len; i++) {
char c = json.charAt(i);
if (c == '{') {
return new JSONObject(json).toString(2);
} else if (c == '[') {
return new JSONArray(json).toString(2);
} else if (!Character.isWhitespace(c)) {
return json;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
private static String formatXml(String xml) {
try {
Source xmlInput = new StreamSource(new StringReader(xml));
StreamResult xmlOutput = new StreamResult(new StringWriter());
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
xml = xmlOutput.getWriter().toString().replaceFirst(">", ">" + LINE_SEP);
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
private static String array2String(Object object) {
if (object instanceof Object[]) {
return Arrays.deepToString((Object[]) object);
} else if (object instanceof boolean[]) {
return Arrays.toString((boolean[]) object);
} else if (object instanceof byte[]) {
return Arrays.toString((byte[]) object);
} else if (object instanceof char[]) {
return Arrays.toString((char[]) object);
} else if (object instanceof double[]) {
return Arrays.toString((double[]) object);
} else if (object instanceof float[]) {
return Arrays.toString((float[]) object);
} else if (object instanceof int[]) {
return Arrays.toString((int[]) object);
} else if (object instanceof long[]) {
return Arrays.toString((long[]) object);
} else if (object instanceof short[]) {
return Arrays.toString((short[]) object);
}
throw new IllegalArgumentException("Array has incompatible type: " + object.getClass());
}
}
private static <T> Class getTypeClassFromParadigm(final IFormatter<T> formatter) {
Type[] genericInterfaces = formatter.getClass().getGenericInterfaces();
Type type;
if (genericInterfaces.length == 1) {
type = genericInterfaces[0];
} else {
type = formatter.getClass().getGenericSuperclass();
}
type = ((ParameterizedType) type).getActualTypeArguments()[0];
while (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getRawType();
}
String className = type.toString();
if (className.startsWith("class ")) {
className = className.substring(6);
} else if (className.startsWith("interface ")) {
className = className.substring(10);
}
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
private static Class getClassFromObject(final Object obj) {
Class objClass = obj.getClass();
if (objClass.isAnonymousClass() || objClass.isSynthetic()) {
Type[] genericInterfaces = objClass.getGenericInterfaces();
String className;
if (genericInterfaces.length == 1) {// interface
Type type = genericInterfaces[0];
while (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getRawType();
}
className = type.toString();
} else {// abstract class or lambda
Type type = objClass.getGenericSuperclass();
while (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getRawType();
}
className = type.toString();
}
if (className.startsWith("class ")) {
className = className.substring(6);
} else if (className.startsWith("interface ")) {
className = className.substring(10);
}
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return objClass;
}
}
| apache-2.0 |
yokurin/titanium_tab | Resources/ui/handheld/tantoAddWindow.js | 1709 | function tantoAddWindow()
{
var tantoAddWin = Ti.UI.createWindow({
backgroundColor: '#fff',
title: L('tanto_add')
});
//担当者というラベル
var label1 = Ti.UI.createLabel({
color: '#999',
top: 0,
text: L('tanto_name'),
//font: ...
textAlign: 'center',
width: 'auto'
});
tantoAddWin.add(label1);
//担当者を入力するテキストフィールド
var textField1 = Ti.UI.createTextField({
value: '',
hintText: L('hint_tanto_name'),
//color:'#999',
top:45,
//left:5,
width:'60%',
borderStyle: Ti.UI.INPUT_BORDERSTYLE_BEZEL
});
tantoAddWin.add(textField1);
var button1 = Ti.UI.createButton({
title: L('tanto_add'),
//backgroundColor: ...,
top: 90,
width: '100',
left: 110
});
button1.addEventListener('click', function(e){
if(textField1.value.length === 0)
{
alert('担当者を入力してください');
textField1.focus();
return false;
}
//console.log('入力内容:'+textField1.value);
//データベースの登録処理
var db = Ti.Database.open('sampleDB');
try{
//テーブルが存在しなければつくる
db.execute('CREATE TABLE IF NOT EXISTS tantotb (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)');
//レコード追加
db.execute('INSERT INTO tantotb(name) VALUES (?)', textField1.value);
}
catch(e){
console.log('insert-error');
Ti.API.info(e);
}
db.close();
//追加したレコードをテーブルビューに反映させるために、updateTablesをfireEventで発生させる
Ti.App.fireEvent('updateTables');
tantoAddWin.close({animated:true});
});
tantoAddWin.add(button1);
return tantoAddWin;
}
module.exports = tantoAddWindow; | apache-2.0 |
icotting/The-GreenLeaf-Project | FirmCore/src/main/java/edu/unl/act/rma/firm/core/TemporalPeriod.java | 2624 | /* Created On: Sep 11, 2005 */
package edu.unl.act.rma.firm.core;
import org.joda.time.DateTime;
/**
* @author Ian Cottingham
*
*/
public final class TemporalPeriod extends DTOBase {
public static final TemporalPeriod EMPTY_PERIOD = new TemporalPeriod((Long)null, null);
private static final long serialVersionUID = 2L;
private DateTime start;
private DateTime end;
public TemporalPeriod() { }
public TemporalPeriod(DateTime start, DateTime end) {
this.start = start;
this.end = end;
}
public TemporalPeriod(Long start, Long end) {
if ( start == null || start == -1 || end == null || end == -1 ) {
return;
} else {
this.start = new DateTime(start);
this.end = new DateTime(end);
}
}
/**
*
* @return the period end date, if there is no valid end date then the current instant is returned
*/
public DateTime getEnd() {
return (end != null) ? end : new DateTime(System.currentTimeMillis());
}
/**
*
* @return the period start date, if there is no valid start date then the current instant is returned
*/
public DateTime getStart() {
return (start != null) ? start : new DateTime(System.currentTimeMillis());
}
public boolean valid() {
return ( start == null | end == null ) ? false : true;
}
public int getYears() {
return ( start == null | end == null ) ? 0 : ( end.getYear() - start.getYear() ) + 1;
}
public TemporalPeriod concatenate(TemporalPeriod period) {
if (!this.valid()) {
return period;
}
DateTime start = (this.start.isBefore(period.start)) ? period.start : this.start;
DateTime end = (this.end.isAfter(period.end)) ? period.end : this.end;
return new TemporalPeriod(start, end);
}
public TemporalPeriod union(TemporalPeriod period) {
if (!this.valid()) {
return period;
}
DateTime start = (this.start.isBefore(period.start)) ? this.start : period.start;
DateTime end = (this.end.isAfter(period.end)) ? this.end : period.end;
return new TemporalPeriod(start, end);
}
public boolean contains(DateTime time) {
if ( !this.valid() ) {
return false;
}
return ( !(time.isBefore(start)) && !(time.isAfter(end)) );
}
public boolean contains(TemporalPeriod period) {
if ( !this.valid() || !period.valid() ) {
return false;
}
return ( contains(period.getStart()) && contains(period.getEnd()) );
}
public void setStart(DateTime start) {
this.start = start;
}
public void setEnd(DateTime end) {
this.end = end;
}
@Override
public String toString() {
return new StringBuffer("start=").append(start).append(",end=").append(end).toString();
}
}
| apache-2.0 |
wesleyegberto/study | ExerciciosLivros/src/javaComoProgramar/cap22/StackComposition.java | 2027 | // Fig. 22.12: StackComposition.java
// StackComposition uses a composed List object.
package javaComoProgramar.cap22;
public class StackComposition< T >
{
private List< T > stackList;
// no-argument constructor
public StackComposition()
{
stackList = new List< T >( "stack" );
} // end StackComposition no-argument constructor
// add object to stack
public void push( T object )
{
stackList.insertAtFront( object );
} // end method push
// remove object from stack
public T pop() throws EmptyListException
{
return stackList.removeFromFront();
} // end method pop
// determine if stack is empty
public boolean isEmpty()
{
return stackList.isEmpty();
} // end method isEmpty
// output stack contents
public void print()
{
stackList.print();
} // end method print
} // end class StackComposition
/**************************************************************************
* (C) Copyright 1992-2010 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
| apache-2.0 |
gosu-lang/old-gosu-repo | gosu-core-api/src/main/java/gw/lang/reflect/features/IConstructorReference.java | 326 | /*
* Copyright 2013 Guidewire Software, Inc.
*/
package gw.lang.reflect.features;
import gw.lang.reflect.IConstructorInfo;
public interface IConstructorReference<R, T> extends IInvokableFeatureReference<R,T>
{
/**
* Returns the method info for this reference
*/
public IConstructorInfo getConstructorInfo();
}
| apache-2.0 |
fogbeam/jFriendOfAFriend | src/main/java/org/fogbeam/foaf/model/FoafPersonalProfileDocumentImpl.java | 184 | package org.fogbeam.foaf.model;
import org.fogbeam.foaf.api.FoafPersonalProfileDocument;
public class FoafPersonalProfileDocumentImpl
implements
FoafPersonalProfileDocument
{
}
| apache-2.0 |
dimagi/javarosa | application/src/org/commcare/entity/VectorIterator.java | 988 | /**
*
*/
package org.commcare.entity;
import org.javarosa.core.util.Iterator;
import java.util.Vector;
/**
* @author ctsims
*
*/
public class VectorIterator<E> implements Iterator<E> {
Vector<E> set;
final int[] count = new int[] { 0 };
public VectorIterator(Vector<E> set) {
//TODO: Safety: Is this ever going to change?
this.set = set;
}
public int numRecords() {
return set.size();
}
public int peekID() {
synchronized(count) {
return count[0];
}
}
public int nextID() {
synchronized(count) {
int retVal = count[0];
count[0] = count[0] + 1;
return retVal;
}
}
public E nextRecord() {
synchronized(count) {
int id = nextID();
return set.elementAt(id);
}
}
public boolean hasMore() {
synchronized(count) {
return peekID() < set.size();
}
}
}
| apache-2.0 |
PerfCake/PerfClipse | org.perfclipse.wizards/src/org/perfclipse/wizards/DestinationAddWizard.java | 2174 | /*
* Perfclispe
*
*
* Copyright (c) 2013 Jakub Knetl
*
* 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.perfclipse.wizards;
import org.eclipse.swt.widgets.TableItem;
import org.perfcake.model.ObjectFactory;
import org.perfcake.model.Scenario.Reporting.Reporter.Destination;
import org.perfclipse.core.model.PeriodModel;
import org.perfclipse.core.model.PropertyModel;
import org.perfclipse.wizards.pages.DestinationPage;
/**
* @author Jakub Knetl
*
*/
public class DestinationAddWizard extends AbstractPerfCakeAddWizard {
private DestinationPage destinationPage;
private Destination destination;
/**
*
*/
public DestinationAddWizard() {
super();
setWindowTitle("Add destination");
}
@Override
public boolean performFinish() {
destination = new ObjectFactory().createScenarioReportingReporterDestination();
destination.setClazz(destinationPage.getDestinationType());
destination.setEnabled(destinationPage.getEnabled());
for (TableItem i : destinationPage.getPeriodViewer().getTable().getItems()){
if (i.getData() instanceof PeriodModel){
PeriodModel p = (PeriodModel) i.getData();
destination.getPeriod().add(p.getPeriod());
}
}
for (TableItem i : destinationPage.getPropertyViewer().getTable().getItems()){
if (i.getData() instanceof PropertyModel){
PropertyModel p = (PropertyModel) i.getData();
destination.getProperty().add(p.getProperty());
}
}
return true;
}
@Override
public void addPages() {
destinationPage = new DestinationPage();
addPage(destinationPage);
super.addPages();
}
public Destination getDestination() {
return destination;
}
}
| apache-2.0 |
sbower/kuali-rice-1 | impl/src/main/java/org/kuali/rice/kcb/deliverer/impl/EmailMessageDeliverer.java | 7938 | /*
* Copyright 2007-2008 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kcb.deliverer.impl;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Set;
import org.apache.commons.validator.EmailValidator;
import org.apache.log4j.Logger;
import org.kuali.rice.kcb.bo.MessageDelivery;
import org.kuali.rice.kcb.deliverer.MessageDeliverer;
import org.kuali.rice.kcb.exception.ErrorList;
import org.kuali.rice.kcb.exception.MessageDeliveryException;
import org.kuali.rice.kcb.exception.MessageDismissalException;
import org.kuali.rice.kcb.service.EmailService;
import org.kuali.rice.kcb.service.GlobalKCBServiceLocator;
import org.kuali.rice.kcb.service.RecipientPreferenceService;
/**
* This class is responsible for describing the email delivery mechanism for
* the system.
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class EmailMessageDeliverer implements MessageDeliverer {
private static Logger LOG = Logger.getLogger(EmailMessageDeliverer.class);
private EmailService emailService;
private RecipientPreferenceService recipientPreferenceService;
public static final String NAME = "Email";
public static final String EMAIL_ADDR_PREF_KEY = "email_address";
public static final String EMAIL_DELIV_FRMT_PREF_KEY = "email_delivery_format";
/**
* Constructs a EmailMessageDeliverer.java.
*/
public EmailMessageDeliverer() {
this.emailService = GlobalKCBServiceLocator.getInstance().getEmailService();
this.recipientPreferenceService = GlobalKCBServiceLocator.getInstance().getRecipientPreferenceService();
}
/**
* This implementation uses the email service to deliver a notification.
* @see org.kuali.rice.kcb.deliverer.MessageDeliverer#deliver(MessageDelivery)
*/
public void deliver(MessageDelivery messageDelivery) throws MessageDeliveryException {
try {
// figure out the proper recipient email address
String recipientEmailAddressPrefKey = getName()+"."+EMAIL_ADDR_PREF_KEY;
String recipientEmailFormatPrefKey = getName()+"."+EMAIL_DELIV_FRMT_PREF_KEY;
String recipientEmailAddress = recipientPreferenceService.getRecipientPreference(messageDelivery.getMessage().getRecipient(), recipientEmailAddressPrefKey).getValue();
String recipientEmailFormat = recipientPreferenceService.getRecipientPreference(messageDelivery.getMessage().getRecipient(), recipientEmailFormatPrefKey).getValue();
//String recipientEmailAddress = GlobalNotificationServiceLocator.getInstance().getKENAPIService().getRecipientPreference(messageDelivery.getMessage().getRecipient(), recipientEmailAddressPrefKey);
//String recipientEmailFormat = GlobalNotificationServiceLocator.getInstance().getKENAPIService().getRecipientPreference(messageDelivery.getMessage().getRecipient(), recipientEmailFormatPrefKey);
Long emailMessageId = emailService.sendEmail(messageDelivery, recipientEmailAddress, recipientEmailFormat);
String deliverySystemId = null;
if (emailMessageId != null) {
deliverySystemId = emailMessageId.toString();
}
messageDelivery.setDelivererSystemId(deliverySystemId);
} catch (Exception we) {
LOG.error("Error delivering email notification", we);
throw new MessageDeliveryException("Error delivering email notification", we);
}
}
/**
* This implementation does an auto-remove by "canceling" the workflow email with the message delivery record.
* In the case of email, it's a noop
* @see org.kuali.rice.kcb.deliverer.MessageDeliverer#autoRemoveMessageDelivery(org.kuali.rice.ken.bo.NotificationMessageDelivery)
*/
public void autoRemoveMessageDelivery(MessageDelivery messageDelivery) /*throws NotificationAutoRemoveException*/ {
// we can't remove an email message once it has been sent
}
/**
* @see org.kuali.rice.kcb.deliverer.MessageDeliverer#dismiss(org.kuali.rice.kcb.bo.MessageDelivery, java.lang.String, java.lang.String)
*/
public void dismiss(MessageDelivery messageDelivery, String user, String cause) throws MessageDismissalException {
// we can't remove an email message once it has been sent
}
/**
* @see org.kuali.rice.kcb.deliverer.MessageDeliverer#getDescription()
*/
public String getDescription() {
return "Enter an Email Address and Email Delivery Format below and select the channels for which you would like email delivery " +
"notifications. Select \"None\" in the channel list to remove a delivery type for all channels. " +
"Only one Email Address and Email Delivery Format may be specified. Any data entered and " +
"saved will override prior Delivery Type selections.";
}
/**
* @see org.kuali.rice.kcb.deliverer.MessageDeliverer#getName()
*/
public String getName() {
return NAME;
}
/**
* @see org.kuali.rice.kcb.deliverer.MessageDeliverer#getTitle()
*/
public String getTitle() {
return "Email Message Delivery";
}
/**
* This implementation returns an address field.
* @see org.kuali.rice.kcb.deliverer.MessageDeliverer#getPreferenceKeys()
*/
public LinkedHashMap<String, String> getPreferenceKeys() {
LinkedHashMap<String, String> prefKeys = new LinkedHashMap<String, String>();
prefKeys.put(EMAIL_ADDR_PREF_KEY, "Email Address (\"abc@def.edu\")");
prefKeys.put(EMAIL_DELIV_FRMT_PREF_KEY, "Email Delivery Format (text or html)");
return prefKeys;
}
/**
* @see org.kuali.rice.kcb.deliverer.MessageDeliverer#validatePreferenceValues(java.util.HashMap)
*/
public void validatePreferenceValues(HashMap<String, String> prefs) throws ErrorList {
boolean error = false;
ErrorList errorList = new ErrorList();
String[] validformats = {"text","html"};
if (!prefs.containsKey(getName()+"."+EMAIL_ADDR_PREF_KEY)) {
errorList.addError("Email Address is a required field.");
error = true;
} else {
String addressValue = (String) prefs.get(getName()+"."+EMAIL_ADDR_PREF_KEY);
EmailValidator validator = EmailValidator.getInstance();
if (!validator.isValid(addressValue)) {
errorList.addError("Email Address is required and must be properly formatted - \"abc@def.edu\".");
error = true;
}
}
// validate format
if (!prefs.containsKey(getName()+"."+EMAIL_DELIV_FRMT_PREF_KEY)) {
errorList.addError("Email Delivery Format is required.");
error = true;
} else {
String formatValue = (String) prefs.get(getName()+"."+EMAIL_DELIV_FRMT_PREF_KEY);
Set<String> formats = new HashSet<String>();
for (int i=0; i < validformats.length ; i++) {
formats.add(validformats[i]);
}
if (!formats.contains(formatValue)) {
errorList.addError("Email Delivery Format is required and must be entered as \"text\" or \"html\".");
error = true;
}
}
if (error) throw errorList;
}
}
| apache-2.0 |
Ninputer/VBF | src/Compilers/Compilers.Intermediate/BinaryExpression.cs | 1094 | // Copyright 2012 Fan Shi
//
// This file is part of the VBF 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.
namespace VBF.Compilers.Intermediate
{
public enum BinaryOperator
{
Unknown,
Add,
Substract,
Multiply,
Divide,
Modulo,
Min,
Max,
Member,
DereferenceMember
}
public class BinaryExpression : Expression
{
public Operand Operand1 { get; set; }
public Operand Operand2 { get; set; }
public BinaryOperator Operator { get; set; }
}
}
| apache-2.0 |
freeVM/freeVM | enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/api/java/lang/Thread/setPriority/setPriority20/setPriority2010/setPriority2010.java | 4208 | /*
* 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.
*/
/**
* Date: Dec 13, 2005
* Time: 12:33:48
*/
package org.apache.harmony.test.func.api.java.lang.Thread.setPriority.setPriority20.setPriority2010;
import org.apache.harmony.share.Test;
import org.apache.harmony.test.func.api.java.lang.Thread.setName.setName20.setName2010.setName2010;
import java.security.Permission;
public class setPriority2010 extends Test {
public static final String TESTED_THREAD_NAME = "SecurityManagerTestThread";
volatile static boolean tStop = false;
class T extends Thread {
public T( String str){
super( str );
}
public void run () {
while ( !tStop ) {
try {
Thread.currentThread().sleep(2000);
}catch( InterruptedException ie){
}catch( Exception e ){
e.printStackTrace();
setPriority2010.tStop = true;
}
}
}
}
class locSecurityManager extends SecurityManager{
/* This Security Manager blocks any access to the thtread wint given name */
private String prohibitedThreadName;
public locSecurityManager( String prohibitedThreadName){
super();
this.prohibitedThreadName = prohibitedThreadName;
}
public void checkAccess(Thread t){
if( t.getName().equals(prohibitedThreadName))
throw new SecurityException( "Acces denied to thread "+ prohibitedThreadName +
" by SecurityManager " + getClass().getName() );
else
super.checkAccess( t );
}
public void checkPermission( Permission perm ){
info(" started checkPermission( " + perm +" )from Security Manager " + getClass().getName());
if( perm.equals( new RuntimePermission("setSecurityManager") ) ) {
log.info("checking RuntimePermission( " + perm.getName()+ " ): PERMITTED");
} else {
//super.checkPermission( perm );
return;
}
}
}
public static void main(String args[]) {
System.exit(new setPriority2010().test());
}
public int test() {
info( getClass().getName() );
SecurityManager ts = new locSecurityManager( TESTED_THREAD_NAME );
SecurityManager sSM = System.getSecurityManager();
info( "System Security Manager is: " + sSM );
T t1;
t1 = new T( TESTED_THREAD_NAME );
t1.start();
System.setSecurityManager( ts );
info( "System Security Manager was changed to: " + System.getSecurityManager());
try{
t1.setPriority( Thread.MAX_PRIORITY );
tStop = true;
System.setSecurityManager( sSM );
info( "System Security Manager has been changed to: " + System.getSecurityManager());
return fail( "Expected SecurityException has NOT been thrown" );
}catch( SecurityException se ){
tStop = true;
System.setSecurityManager( sSM );
info( "System Security Manager has been changed to: " + System.getSecurityManager());
return pass( "Expected SecurityException has been thrown" );
}
}
void info(String text){
log.info( text );
// System.out.println(text); System.out.flush();
}
}
| apache-2.0 |
glenacota/seine | seine-src/src/experiment/accuracy/bitthief/Queue.java | 2541 | package experiment.accuracy.bitthief;
import peersim.core.Node;
/**
* Class type of the queues's items in {@link example.bitthief.BitTorrent#incomingPieces}
* and {@link example.bitthief.BitTorrent#requestToServe}.
*/
class Queue{
int maxSize;
int head = 0;
int tail = 0;
int dim = 0;
Request queue[];
/**
* Public constructor. Creates a queue of size <tt>size</tt>.
*/
public Queue(int size){
maxSize = size;
queue = new Request[size];
for(int i=0; i< size; i++)
queue[i]= new Request();
}
/**
* Enqueues the request of the block <tt>id</tt> and its <tt>sender</tt>
* @param id the id of the block in the request
* @param sender a reference to the sender of the request
* @return <tt>true</tt> if the request has been correctly added, <tt>false</tt>
* otherwise.
*/
public boolean enqueue(int id, Node sender){
if(dim < maxSize){
queue[tail%maxSize].id = id;
queue[tail%maxSize].sender = sender;
tail++;
dim++;
return true;
}
else return false;
}
/**
* Returns the {@link Request} in the head of the queue.
* @return the element in the head.<br/>
* <tt>null</tt> if the queue is empty.
*/
public Request dequeue(){
Request value;
if(dim > 0){
value = queue[head%maxSize];
head++;
dim--;
return value;
}
else return null; //empty queue
}
/**
* Returns the status of the queue.
* @return <tt>true</tt> if the queue is empty, <tt>false</tt>
* otherwise.
*/
public boolean empty(){
return (dim == 0);
}
/**
* Returns <tt>true</tt> if block given as parameter is in.
* @param value the id of the block to search.
* @return <tt>true</tt> if the block <tt>value</tt> is in the queue, <tt>false</tt>
* otherwise.
*/
public boolean contains(int value){
if(empty())
return false;
for(int i=head; i<head+dim; i++){
if(queue[i%maxSize].id == value)
return true;
}
return false;
}
/**
* Removes a request from the queue.
* @param sender the sender of the request.
* @param value the id of the block requested.
* @return <tt>true</tt> if the request has been correctly removed, <tt>false</tt>
* otherwise.
*/
public boolean remove(Node sender, int value){
if(empty())
return false;
for(int i=head; i<head+dim; i++){
if(queue[i%maxSize].id == value && queue[i%maxSize].sender == sender){
for(int j=i; j>head; j--){ // Shifts the elements for the removal
queue[j%maxSize]= queue[(j-1)%maxSize];
}
head++;
dim--;
return true;
}
}
return false;
}
}
| apache-2.0 |
shefansxyh/eap | eap/eap.core/src/main/java/eap/exception/BizAssert.java | 6253 | package eap.exception;
import java.util.Collection;
/**
* <p> Title: </p>
* <p> Description: </p>
* @作者 chiknin@gmail.com
* @创建时间
* @版本 1.00
* @修改记录
* <pre>
* 版本 修改人 修改时间 修改内容描述
* ----------------------------------------
*
* ----------------------------------------
* </pre>
*/
public class BizAssert {
public static void isNull(Object obj, String msgCode, String[] msgParams, String message) throws BizException {
if (obj == null) {
throw new BizException(msgCode, msgParams, message, null);
}
}
public static void isNull(Object obj, String msgCode, String msgParam, String message) throws BizException {
if (obj == null) {
throw new BizException(msgCode, new String[] {msgParam}, message, null);
}
}
public static void isNull(Object obj, String msgCode, String message) throws BizException {
if (obj == null) {
throw new BizException(msgCode, message, null);
}
}
public static void isEmptyParam(Object param, String paramName, String message) throws BizException {
if (param == null || param.toString().length() == 0) {
throw new BizException("e.paramMustNotBeEmpty", paramName, message, null);
}
}
public static void isEmpty(Object obj, String msgCode, String[] msgParams, String message) throws BizException {
if (obj == null || obj.toString().length() == 0) {
throw new BizException(msgCode, msgParams, message, null);
}
}
public static void isEmpty(Object obj, String msgCode, String msgParam, String message) throws BizException {
if (obj == null || obj.toString().length() == 0) {
throw new BizException(msgCode, new String[] {msgParam}, message, null);
}
}
public static void isEmpty(Object obj, String msgCode, String message) throws BizException {
if (obj == null || obj.toString().length() == 0) {
throw new BizException(msgCode, message, null);
}
}
public static void isTrue(boolean expression, String msgCode, String[] msgParams, String message) throws BizException {
if (expression) {
throw new BizException(msgCode, msgParams, message, null);
}
}
public static void isTrue(boolean expression, String msgCode, String msgParam, String message) throws BizException {
if (expression) {
throw new BizException(msgCode, new String[] {msgParam}, message, null);
}
}
public static void isTrue(boolean expression, String msgCode, String message) throws BizException {
if (expression) {
throw new BizException(msgCode, message, null);
}
}
public static void isTrue(boolean expression, String message) throws BizException {
if (expression) {
throw new BizException(message);
}
}
public static void isFalse(boolean expression, String message) throws BizException {
if (!expression) {
throw new BizException(message);
}
}
public static void isNullR(Object obj, String msgCode, String[] msgParams, String message) throws RollbackableBizException {
if (obj == null) {
throw new RollbackableBizException(msgCode, msgParams, message, null);
}
}
public static void isNullR(Object obj, String msgCode, String msgParam, String message) throws RollbackableBizException {
if (obj == null) {
throw new RollbackableBizException(msgCode, new String[] {msgParam}, message, null);
}
}
public static void isNullR(Object obj, String msgCode, String message) throws RollbackableBizException {
if (obj == null) {
throw new RollbackableBizException(msgCode, message);
}
}
public static void isEmptyRParam(Object param, String paramName, String message) throws RollbackableBizException {
if (param == null || param.toString().length() == 0) {
throw new RollbackableBizException("e.paramMustNotBeEmpty", paramName, message, null);
}
}
public static void isEmptyR(Object obj, String msgCode, String[] msgParams, String message) throws RollbackableBizException {
if (obj == null || obj.toString().length() == 0) {
throw new RollbackableBizException(msgCode, msgParams, message, null);
}
}
public static void isEmptyR(Object obj, String msgCode, String msgParam, String message) throws RollbackableBizException {
if (obj == null || obj.toString().length() == 0) {
throw new RollbackableBizException(msgCode, new String[] {msgParam}, message, null);
}
}
public static void isEmptyR(Object obj, String msgCode, String message) throws RollbackableBizException {
if (obj == null || obj.toString().length() == 0) {
throw new RollbackableBizException(msgCode, message);
}
}
public static void isTrueR(boolean expression, String msgCode, String[] msgParams, String message) throws RollbackableBizException {
if (expression) {
throw new RollbackableBizException(msgCode, msgParams, message, null);
}
}
public static void isTrueR(boolean expression, String msgCode, String msgParam, String message) throws RollbackableBizException {
if (expression) {
throw new RollbackableBizException(msgCode, new String[] {msgParam}, message, null);
}
}
public static void isTrueR(boolean expression, String msgCode, String message) throws RollbackableBizException {
if (expression) {
throw new RollbackableBizException(msgCode, message);
}
}
public static void hasLength(Collection<?> collection, String msgCode, String message) throws BizException{
hasLength(collection, msgCode, null, message);
}
public static void hasLength(Collection<?> collection, String msgCode, String[] msgParams, String message) throws BizException{
if(collection != null && collection.size() > 0){
return;
}
throw new BizException(msgCode, msgParams, message, null);
}
public static void hasLengthR(Collection<?> collection, String msgCode, String message) throws RollbackableBizException{
hasLengthR(collection, msgCode, null, message);
}
public static void hasLengthR(Collection<?> collection, String msgCode, String[] msgParams, String message) throws RollbackableBizException{
if(collection != null && collection.size() > 0){
return;
}
throw new RollbackableBizException(msgCode, msgParams, message, null);
}
} | apache-2.0 |
cbordeman/gameofgo | FuegoUniversalComponent/fuego/smartgame/SgStringUtil.cpp | 1944 | //----------------------------------------------------------------------------
/** @file SgStringUtil.cpp
See SgStringUtil.h */
//----------------------------------------------------------------------------
#include "SgSystem.h"
#include "SgStringUtil.h"
////#include <boost/filesystem.hpp>
#include <cctype>
#include <sstream>
using namespace std;
//using namespace boost::filesystem;
//----------------------------------------------------------------------------
//string SgStringUtil::GetNativeFileName(const path& file)
//{
// path normalizedFile = file;
// normalizedFile.normalize();
// # if defined(BOOST_FILESYSTEM_VERSION)
// //SG_ASSERT (BOOST_FILESYSTEM_VERSION == 2 || BOOST_FILESYSTEM_VERSION == 3);
// #endif
//
// #if (defined (BOOST_FILESYSTEM_VERSION) && (BOOST_FILESYSTEM_VERSION == 3))
// return normalizedFile.string();
// #else
// return normalizedFile.native_file_string();
// #endif
//}
//vector<string> SgStringUtil::SplitArguments(string s)
//{
// vector<string> result;
// bool escape = false;
// bool inString = false;
// ostringstream token;
// for (size_t i = 0; i < s.size(); ++i)
// {
// char c = s[i];
// if (c == '"' && ! escape)
// {
// if (inString)
// {
// result.push_back(token.str());
// token.str("");
// }
// inString = ! inString;
// }
// else if (isspace(c) && ! inString)
// {
// if (! token.str().empty())
// {
// result.push_back(token.str());
// token.str("");
// }
// }
// else
// token << c;
// escape = (c == '\\' && ! escape);
// }
// if (! token.str().empty())
// result.push_back(token.str());
// return result;
//}
//----------------------------------------------------------------------------
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_9833.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_9833 {
}
| apache-2.0 |
vito-c/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/PrivacyList.java | 2270 | /**
*
* 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 org.jivesoftware.smackx.privacy;
import org.jivesoftware.smackx.privacy.packet.PrivacyItem;
import java.util.List;
/**
* A privacy list represents a list of contacts that is a read only class used to represent a set of allowed or blocked communications.
* Basically it can:<ul>
*
* <li>Handle many {@link org.jivesoftware.smackx.privacy.packet.PrivacyItem}.</li>
* <li>Answer if it is the default list.</li>
* <li>Answer if it is the active list.</li>
* </ul>
*
* {@link PrivacyItem Privacy Items} can handle different kind of blocking communications based on JID, group,
* subscription type or globally.
*
* @author Francisco Vives
*/
public class PrivacyList {
/** Holds if it is an active list or not **/
private final boolean isActiveList;
/** Holds if it is an default list or not **/
private final boolean isDefaultList;
/** Holds the list name used to print **/
private final String listName;
/** Holds the list of {@link PrivacyItem} */
private final List<PrivacyItem> items;
protected PrivacyList(boolean isActiveList, boolean isDefaultList,
String listName, List<PrivacyItem> privacyItems) {
super();
this.isActiveList = isActiveList;
this.isDefaultList = isDefaultList;
this.listName = listName;
this.items = privacyItems;
}
public String getName() {
return listName;
}
public boolean isActiveList() {
return isActiveList;
}
public boolean isDefaultList() {
return isDefaultList;
}
public List<PrivacyItem> getItems() {
return items;
}
}
| apache-2.0 |
jamesbperry/PI-Coresight-Automation | src/CoresightAutomation.PIWebAPI/DTO/AFAttributeTemplateDTO.cs | 1645 | //Copyright 2016 Brandon Perry - OSIsoft, LLC
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//<http://www.apache.org/licenses/LICENSE-2.0>
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CoresightAutomation.PIWebAPI.DTO
{
/// <summary>
/// A simplified data transfer object holding Coresight-relevant properties of an Attribute Template.
/// Deserializable from the AttributeTemplate object returned by the PI WebAPI.
/// </summary>
public class AFAttributeTemplateDTO
{
public string WebId { get; set; }
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Path { get; set; }
public string Type { get; set; }
public string TypeQualifier { get; set; }
public bool IsHidden { get; set; }
public string DataReferencePlugIn { get; set; }
public bool HasChildren { get; set; }
public List<string> CategoryNames { get; set; }
public string GetPathRelativeToElement()
{
return Path.Split(new char[] { '|' }, 2)[1];
}
}
}
| apache-2.0 |
takecy/guice | extensions/servlet/test/com/google/inject/servlet/ServletDefinitionPathsTest.java | 12779 | /**
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.servlet;
import static com.google.inject.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import com.google.common.collect.Sets;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.spi.BindingScopingVisitor;
import junit.framework.TestCase;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Ensures servlet spec compliance for CGI-style variables and general
* path/pattern matching.
*
* @author Dhanji R. Prasanna (dhanji@gmail com)
*/
public class ServletDefinitionPathsTest extends TestCase {
// Data-driven test.
public final void testServletPathMatching() throws IOException, ServletException {
servletPath("/index.html", "*.html", "/index.html");
servletPath("/somewhere/index.html", "*.html", "/somewhere/index.html");
servletPath("/somewhere/index.html", "/*", "");
servletPath("/index.html", "/*", "");
servletPath("/", "/*", "");
servletPath("//", "/*", "");
servletPath("/////", "/*", "");
servletPath("", "/*", "");
servletPath("/thing/index.html", "/thing/*", "/thing");
servletPath("/thing/wing/index.html", "/thing/*", "/thing");
}
private void servletPath(final String requestPath, String mapping,
final String expectedServletPath) throws IOException, ServletException {
Injector injector = createMock(Injector.class);
Binding binding = createMock(Binding.class);
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject()))
.andReturn(true);
expect(injector.getBinding(Key.get(HttpServlet.class)))
.andReturn(binding);
final boolean[] run = new boolean[1];
//get an instance of this servlet
expect(injector.getInstance(Key.get(HttpServlet.class)))
.andReturn(new HttpServlet() {
@Override
protected void service(HttpServletRequest servletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
final String path = servletRequest.getServletPath();
assertEquals(String.format("expected [%s] but was [%s]", expectedServletPath, path),
expectedServletPath, path);
run[0] = true;
}
});
expect(request.getServletPath())
.andReturn(requestPath);
replay(injector, binding, request);
ServletDefinition servletDefinition =
new ServletDefinition(
Key.get(HttpServlet.class),
UriPatternType.get(UriPatternType.SERVLET, mapping),
new HashMap<String, String>(),
null);
servletDefinition.init(null, injector, Sets.<HttpServlet>newIdentityHashSet());
servletDefinition.doService(request, response);
assertTrue("Servlet did not run!", run[0]);
verify(injector, binding, request);
}
// Data-driven test.
public final void testPathInfoWithServletStyleMatching() throws IOException, ServletException {
pathInfoWithServletStyleMatching("/path/index.html", "/path", "/*", "/index.html", "");
pathInfoWithServletStyleMatching("/path//hulaboo///index.html", "/path", "/*",
"/hulaboo/index.html", "");
pathInfoWithServletStyleMatching("/path/", "/path", "/*", "/", "");
pathInfoWithServletStyleMatching("/path////////", "/path", "/*", "/", "");
// a servlet mapping of /thing/*
pathInfoWithServletStyleMatching("/path/thing////////", "/path", "/thing/*", "/", "/thing");
pathInfoWithServletStyleMatching("/path/thing/stuff", "/path", "/thing/*", "/stuff", "/thing");
pathInfoWithServletStyleMatching("/path/thing/stuff.html", "/path", "/thing/*", "/stuff.html",
"/thing");
pathInfoWithServletStyleMatching("/path/thing", "/path", "/thing/*", null, "/thing");
// see external issue 372
pathInfoWithServletStyleMatching("/path/some/path/of.jsp", "/path", "/thing/*",
null, "/some/path/of.jsp");
// *.xx style mapping
pathInfoWithServletStyleMatching("/path/thing.thing", "/path", "*.thing", null, "/thing.thing");
pathInfoWithServletStyleMatching("/path///h.thing", "/path", "*.thing", null, "/h.thing");
pathInfoWithServletStyleMatching("/path///...//h.thing", "/path", "*.thing", null,
"/.../h.thing");
pathInfoWithServletStyleMatching("/path/my/h.thing", "/path", "*.thing", null, "/my/h.thing");
// Encoded URLs
pathInfoWithServletStyleMatching("/path/index%2B.html", "/path", "/*", "/index+.html", "");
pathInfoWithServletStyleMatching("/path/a%20file%20with%20spaces%20in%20name.html", "/path", "/*", "/a file with spaces in name.html", "");
pathInfoWithServletStyleMatching("/path/Tam%C3%A1s%20nem%20m%C3%A1s.html", "/path", "/*", "/Tamás nem más.html", "");
}
private void pathInfoWithServletStyleMatching(final String requestUri, final String contextPath,
String mapping, final String expectedPathInfo, final String servletPath)
throws IOException, ServletException {
Injector injector = createMock(Injector.class);
Binding binding = createMock(Binding.class);
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject()))
.andReturn(true);
expect(injector.getBinding(Key.get(HttpServlet.class)))
.andReturn(binding);
final boolean[] run = new boolean[1];
//get an instance of this servlet
expect(injector.getInstance(Key.get(HttpServlet.class)))
.andReturn(new HttpServlet() {
@Override
protected void service(HttpServletRequest servletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
final String path = servletRequest.getPathInfo();
if (null == expectedPathInfo) {
assertNull(String.format("expected [%s] but was [%s]", expectedPathInfo, path),
path);
}
else {
assertEquals(String.format("expected [%s] but was [%s]", expectedPathInfo, path),
expectedPathInfo, path);
}
//assert memoizer
//noinspection StringEquality
assertSame("memo field did not work", path, servletRequest.getPathInfo());
run[0] = true;
}
});
expect(request.getRequestURI())
.andReturn(requestUri);
expect(request.getServletPath())
.andReturn(servletPath)
.anyTimes();
expect(request.getContextPath())
.andReturn(contextPath);
expect(request.getAttribute(REQUEST_DISPATCHER_REQUEST)).andReturn(null);
replay(injector, binding, request);
ServletDefinition servletDefinition =
new ServletDefinition(
Key.get(HttpServlet.class),
UriPatternType.get(UriPatternType.SERVLET, mapping),
new HashMap<String, String>(),
null);
servletDefinition.init(null, injector, Sets.<HttpServlet>newIdentityHashSet());
servletDefinition.doService(request, response);
assertTrue("Servlet did not run!", run[0]);
verify(injector, binding, request);
}
// Data-driven test.
public final void testPathInfoWithRegexMatching() throws IOException, ServletException {
// first a mapping of /*
pathInfoWithRegexMatching("/path/index.html", "/path", "/(.)*", "/index.html", "");
pathInfoWithRegexMatching("/path//hulaboo///index.html", "/path", "/(.)*",
"/hulaboo/index.html", "");
pathInfoWithRegexMatching("/path/", "/path", "/(.)*", "/", "");
pathInfoWithRegexMatching("/path////////", "/path", "/(.)*", "/", "");
// a servlet mapping of /thing/*
pathInfoWithRegexMatching("/path/thing////////", "/path", "/thing/(.)*", "/", "/thing");
pathInfoWithRegexMatching("/path/thing/stuff", "/path", "/thing/(.)*", "/stuff", "/thing");
pathInfoWithRegexMatching("/path/thing/stuff.html", "/path", "/thing/(.)*", "/stuff.html",
"/thing");
pathInfoWithRegexMatching("/path/thing", "/path", "/thing/(.)*", null, "/thing");
// *.xx style mapping
pathInfoWithRegexMatching("/path/thing.thing", "/path", ".*\\.thing", null, "/thing.thing");
pathInfoWithRegexMatching("/path///h.thing", "/path", ".*\\.thing", null, "/h.thing");
pathInfoWithRegexMatching("/path///...//h.thing", "/path", ".*\\.thing", null,
"/.../h.thing");
pathInfoWithRegexMatching("/path/my/h.thing", "/path", ".*\\.thing", null, "/my/h.thing");
// path
pathInfoWithRegexMatching("/path/test.com/com.test.MyServletModule", "", "/path/[^/]+/(.*)",
"com.test.MyServletModule", "/path/test.com/com.test.MyServletModule");
// Encoded URLs
pathInfoWithRegexMatching("/path/index%2B.html", "/path", "/(.)*", "/index+.html", "");
pathInfoWithRegexMatching("/path/a%20file%20with%20spaces%20in%20name.html", "/path", "/(.)*", "/a file with spaces in name.html", "");
pathInfoWithRegexMatching("/path/Tam%C3%A1s%20nem%20m%C3%A1s.html", "/path", "/(.)*", "/Tamás nem más.html", "");
}
public final void pathInfoWithRegexMatching(final String requestUri, final String contextPath,
String mapping, final String expectedPathInfo, final String servletPath)
throws IOException, ServletException {
Injector injector = createMock(Injector.class);
Binding binding = createMock(Binding.class);
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject()))
.andReturn(true);
expect(injector.getBinding(Key.get(HttpServlet.class)))
.andReturn(binding);
final boolean[] run = new boolean[1];
//get an instance of this servlet
expect(injector.getInstance(Key.get(HttpServlet.class)))
.andReturn(new HttpServlet() {
@Override
protected void service(HttpServletRequest servletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
final String path = servletRequest.getPathInfo();
if (null == expectedPathInfo) {
assertNull(String.format("expected [%s] but was [%s]", expectedPathInfo, path),
path);
}
else {
assertEquals(String.format("expected [%s] but was [%s]", expectedPathInfo, path),
expectedPathInfo, path);
}
//assert memoizer
//noinspection StringEquality
assertSame("memo field did not work", path, servletRequest.getPathInfo());
run[0] = true;
}
});
expect(request.getRequestURI())
.andReturn(requestUri);
expect(request.getServletPath())
.andReturn(servletPath)
.anyTimes();
expect(request.getContextPath())
.andReturn(contextPath);
expect(request.getAttribute(REQUEST_DISPATCHER_REQUEST)).andReturn(null);
replay(injector, binding, request);
ServletDefinition servletDefinition =
new ServletDefinition(
Key.get(HttpServlet.class),
UriPatternType.get(UriPatternType.REGEX, mapping),
new HashMap<String, String>(),
null);
servletDefinition.init(null, injector, Sets.<HttpServlet>newIdentityHashSet());
servletDefinition.doService(request, response);
assertTrue("Servlet did not run!", run[0]);
verify(injector, binding, request);
}
}
| apache-2.0 |
Haulmont/vaadin-focus-selector | src/main/groovy/com/haulmont/vaadin/sample/client/ui/FocusTreeConnector.java | 378 | package com.haulmont.vaadin.sample.client.ui;
import com.haulmont.vaadin.sample.ui.FocusTree;
import com.vaadin.client.ui.tree.TreeConnector;
import com.vaadin.shared.ui.Connect;
@Connect(FocusTree.class)
public class FocusTreeConnector extends TreeConnector {
@Override
public FocusTreeWidget getWidget() {
return (FocusTreeWidget) super.getWidget();
}
} | apache-2.0 |
core-lib/jestful | jestful-weixin/src/main/java/org/qfox/jestful/weixin/media/MaterialAPI.java | 5273 | package org.qfox.jestful.weixin.media;
import org.qfox.jestful.client.scheduler.Callback;
import org.qfox.jestful.client.scheduler.OnCompleted;
import org.qfox.jestful.client.scheduler.OnFail;
import org.qfox.jestful.client.scheduler.OnSuccess;
import org.qfox.jestful.core.http.*;
import java.io.File;
/**
* 微信公众号永久素材API
*
* @author 杨昌沛 646742615@qq.com
* @date 2018-03-08 13:31
**/
@HTTP("/cgi-bin/material")
public interface MaterialAPI {
@POST(value = "/add_news", consumes = "application/json", produces = "application/json")
NewsUploadResult upload(
@Query("access_token") String token,
@Body News news
);
@POST(value = "/add_material", consumes = {"multipart/form-data", "application/json"}, produces = "application/json")
MaterialUploadResult upload(
@Query("access_token") String token,
@Query("type") MediaType type,
@Body("media") File media,
@Body("description") Description description
);
@POST(value = "/add_material", consumes = {"multipart/form-data", "application/json"}, produces = "application/json")
void upload(
@Query("access_token") String token,
@Query("type") MediaType type,
@Body("media") File media,
@Body("description") Description description,
Callback<MaterialUploadResult> callback
);
@POST(value = "/add_material", consumes = {"multipart/form-data", "application/json"}, produces = "application/json")
void upload(
@Query("access_token") String token,
@Query("type") MediaType type,
@Body("media") File media,
@Body("description") Description description,
OnCompleted<MaterialUploadResult> onCompleted
);
@POST(value = "/add_material", consumes = {"multipart/form-data", "application/json"}, produces = "application/json")
void upload(
@Query("access_token") String token,
@Query("type") MediaType type,
@Body("media") File media,
@Body("description") Description description,
OnSuccess<MaterialUploadResult> onSuccess
);
@POST(value = "/add_material", consumes = {"multipart/form-data", "application/json"}, produces = "application/json")
void upload(
@Query("access_token") String token,
@Query("type") MediaType type,
@Body("media") File media,
@Body("description") Description description,
OnSuccess<MaterialUploadResult> onSuccess,
OnFail onFail
);
@POST(value = "/add_material", consumes = {"multipart/form-data", "application/json"}, produces = "application/json")
void upload(
@Query("access_token") String token,
@Query("type") MediaType type,
@Body("media") File media,
@Body("description") Description description,
OnSuccess<MaterialUploadResult> onSuccess,
OnFail onFail,
OnCompleted<MaterialUploadResult> onCompleted
);
@POST(value = "/get_material", consumes = "application/json", produces = "application/json")
MaterialQueryResult query(
@Query("access_token") String token,
@Body Material material
);
@POST(value = "/get_material", consumes = "application/json")
File download(
@Query("access_token") String token,
@Body Material material
);
@POST(value = "/get_material", consumes = "application/json")
void download(
@Query("access_token") String token,
@Body Material material,
Callback<File> callback
);
@POST(value = "/get_material", consumes = "application/json")
void download(
@Query("access_token") String token,
@Body Material material,
OnCompleted<File> onCompleted
);
@POST(value = "/get_material", consumes = "application/json")
void download(
@Query("access_token") String token,
@Body Material material,
OnSuccess<File> onSuccess
);
@POST(value = "/get_material", consumes = "application/json")
void download(
@Query("access_token") String token,
@Body Material material,
OnSuccess<File> onSuccess,
OnFail onFail
);
@POST(value = "/get_material", consumes = "application/json")
void download(
@Query("access_token") String token,
@Body Material material,
OnSuccess<File> onSuccess,
OnFail onFail,
OnCompleted<File> onCompleted
);
@POST(value = "/del_material", consumes = "application/json", produces = "application/json")
MaterialDeleteResult delete(
@Query("access_token") String token,
@Body Material material
);
@GET(value = "/get_materialcount", produces = "application/json")
MaterialCountResult count(@Query("access_token") String token);
@POST(value = "/batchget_material", consumes = "application/json", produces = "application/json")
MaterialListResult list(
@Query("access_token") String token,
@Body Pagination pagination
);
}
| apache-2.0 |
firebase/firebase-android-sdk | firebase-database/src/main/java/com/google/firebase/database/snapshot/NamedNode.java | 1889 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.database.snapshot;
public final class NamedNode {
private final ChildKey name;
private final Node node;
private static final NamedNode MIN_NODE = new NamedNode(ChildKey.getMinName(), EmptyNode.Empty());
private static final NamedNode MAX_NODE = new NamedNode(ChildKey.getMaxName(), Node.MAX_NODE);
public static NamedNode getMinNode() {
return MIN_NODE;
}
public static NamedNode getMaxNode() {
return MAX_NODE;
}
public NamedNode(ChildKey name, Node node) {
this.name = name;
this.node = node;
}
public ChildKey getName() {
return this.name;
}
public Node getNode() {
return this.node;
}
@Override
public String toString() {
return "NamedNode{" + "name=" + name + ", node=" + node + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NamedNode namedNode = (NamedNode) o;
if (!name.equals(namedNode.name)) {
return false;
}
if (!node.equals(namedNode.node)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + node.hashCode();
return result;
}
}
| apache-2.0 |
mylifeponraj/or5e-labs | plugin-node-connector/src/main/java/org/or5e/node/connector/processors/PropertiesProcessor.java | 1544 | package org.or5e.node.connector.processors;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.or5e.core.BaseObject;
import org.or5e.node.connector.Processors;
public class PropertiesProcessor extends BaseObject implements Processors {
private final static PropertiesProcessor _processor;
private final Map<String, String> propertiesMap;
static {
_processor = new PropertiesProcessor();
}
public PropertiesProcessor() {
propertiesMap = new HashMap<>();
}
public static PropertiesProcessor getPropertiesProcessor () {
return _processor;
}
public String getAllProperties () {
propertiesMap.clear();
Set<Entry<Object,Object>> entrySet = _props.entrySet();
for (Entry<Object, Object> entry : entrySet) {
propertiesMap.put(entry.getKey().toString(), entry.getValue().toString());
}
return mapToString();
}
public String modifyAndGetAppProperties (String key, String value) {
propertiesMap.put(key, value);
setProperties(key, value);
return getAllProperties ();
}
private String mapToString() {
StringBuilder _builder = new StringBuilder();
_builder.append("{'properties':[");
Set<String> keySet = propertiesMap.keySet();
for (String key : keySet) {
_builder.append("{");
_builder.append("'"+key+"':'"+propertiesMap.get(key)+"'");
_builder.append("},");
}
_builder.append("]}");
return null;
}
@Override public String getName() {
return "PropertiesProcessor";
}
}
| apache-2.0 |
Dinesh-Ramakrishnan/grommet | examples/people-finder/src/js/components/Organization.js | 3626 | // (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
var React = require('react');
var Article = require('grommet/components/Article');
var List = require('grommet/components/List');
var Header = require('grommet/components/Header');
var Rest = require('grommet/utils/Rest');
var Spinning = require('grommet/components/icons/Spinning');
var config = require('../config');
var Organization = React.createClass({
propTypes: {
onSelect: React.PropTypes.func.isRequired,
person: React.PropTypes.object.isRequired
},
getInitialState: function () {
return {team: [], managers: [], scope: config.scopes.people};
},
componentDidMount: function () {
this._getRelatedDetails(this.props);
},
componentWillReceiveProps: function (newProps) {
if (newProps.person.dn !== this.props.person.dn) {
this._getRelatedDetails(newProps);
}
},
_onManagerResponse: function (err, res) {
if (err) {
this.setState({staff: [], error: err});
} else if (res.ok) {
var result = res.body;
var manager = result[0];
// might not match if domain names are different
if (manager) {
var managers = this.state.managers;
managers.unshift(manager);
this.setState({managers: managers, error: null});
// 20 limit is to guard against bugs in the code
if (manager.manager && manager.manager !== manager.dn && managers.length <= 20) {
this._getManager(manager.manager);
} else {
this.setState({busy: false});
}
} else {
console.log('Unknown manager', res.req.url);
this.setState({busy: false});
}
}
},
_getManager: function (managerDn) {
var params = {
url: encodeURIComponent(config.ldap_base_url),
base: managerDn,
scope: 'sub'
};
Rest.get('/ldap/', params).end(this._onManagerResponse);
},
_onTeamResponse: function (err, res) {
if (err) {
this.setState({staff: [], error: err});
} else if (res.ok) {
var result = res.body;
this.setState({team: result, error: null});
}
},
_getRelatedDetails: function (props) {
this.setState({team: [], managers: []});
if (props.person.dn) {
this.setState({busy: true});
var params = {
url: encodeURIComponent(config.ldap_base_url),
base: encodeURIComponent('ou=' + this.state.scope.ou + ',o=' + config.organization),
scope: 'sub',
filter: encodeURIComponent('(&(hpStatus=Active)(manager=' + props.person.dn + '))'),
attributes: config.attributesFromSchema(this.state.scope.schema)
};
Rest.get('/ldap/', params).end(this._onTeamResponse);
this._getManager(props.person.manager);
}
},
render: function() {
var person = this.props.person;
var people = [];
if (person.uid) {
if (this.state.busy) {
people = [{uid: 'spinner', hpPictureThumbnailURI: <Spinning />}, person];
} else {
people = this.state.managers.concat(person);
}
}
var team;
if (this.state.team.length > 0) {
team = [
<Header key="label" tag="h4" pad="medium" separator="top">
{person.givenName + "'s Team"}
</Header>,
<List key="team" large={true} data={this.state.team} schema={this.state.scope.schema}
onSelect={this.props.onSelect} />
];
}
return (
<Article>
<List large={true} data={people} schema={this.state.scope.schema}
onSelect={this.props.onSelect} />
{team}
</Article>
);
}
});
module.exports = Organization;
| apache-2.0 |
lingdongrushui/International-Distribution-System | ids/src/com/thayer/idsservice/task/receive/interf/IReceiveTask.java | 88 | package com.thayer.idsservice.task.receive.interf;
public interface IReceiveTask {
}
| apache-2.0 |
googlestadia/vsi-lldb | YetiVSI.Tests/DebugEngine/CoreDumps/ModuleReaderTests.cs | 10226 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 NUnit.Framework;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using YetiCommon;
using YetiVSI.DebugEngine.CoreDumps;
namespace YetiVSI.Test.DebugEngine.CoreDumps
{
[TestFixture]
public class ModuleReaderTests
{
[Test]
public void EmptyStream()
{
var emptyReader = new BinaryReader(new MemoryStream());
var moduleReader = new ModuleReader(new List<ProgramHeader>(), emptyReader);
var module = moduleReader.GetModule(new FileSection("", 0, 0));
Assert.AreEqual(BuildId.Empty, module.Id);
}
[Test]
public void CorrectBuildIdInSingleSegment()
{
var data = TestData.GetElfFileBytesFromBuildId(TestData.expectedId);
var segment = new ProgramHeader(ProgramHeader.Type.LoadableSegment, 0, 0,
(ulong) data.Length);
var module = ReadModule(data, new[] {segment},
new FileSection("", 0, (ulong) data.Length));
Assert.AreEqual(TestData.expectedId, module.Id);
}
[Test]
public void ElfHeaderEndsOutsideSegment()
{
var data = TestData.GetElfFileBytesFromBuildId(TestData.expectedId);
var segment = new ProgramHeader(
ProgramHeader.Type.LoadableSegment, 0, 0, ElfHeader.Size - 1);
var module = ReadModule(data, new[] {segment},
new FileSection("", 0, (ulong) data.Length));
Assert.AreEqual(BuildId.Empty, module.Id);
}
[Test]
public void ProgramHeaderEndsOutsideSegment()
{
var data = TestData.GetElfFileBytesFromBuildId(TestData.expectedId);
var segment = new ProgramHeader(ProgramHeader.Type.LoadableSegment, 0, 0,
ElfHeader.Size + ProgramHeader.Size - 1);
var module = ReadModule(data, new[] {segment},
new FileSection("", 0, (ulong) data.Length));
Assert.AreEqual(BuildId.Empty, module.Id);
}
[Test]
public void BuildIdEndsOutsideSegment()
{
var data = TestData.GetElfFileBytesFromBuildId(TestData.expectedId);
var segment = new ProgramHeader(
ProgramHeader.Type.LoadableSegment, 0, 0, (ulong)data.Length - 1);
var module = ReadModule(data, new[] {segment},
new FileSection("", 0, (ulong) data.Length));
Assert.AreNotEqual(TestData.expectedId, module.Id);
}
[Test]
public void FileStartBeforeSegment()
{
var data = TestData.GetElfFileBytesFromBuildId(TestData.expectedId);
var segment = new ProgramHeader(ProgramHeader.Type.LoadableSegment, 0, 1,
(ulong) data.Length);
var module = ReadModule(data, new[] {segment},
new FileSection("", 0, (ulong) data.Length));
Assert.AreEqual(BuildId.Empty, module.Id);
}
[Test]
public void FileAtTheMiddleOfSegment()
{
var buildIdFileData = TestData.GetElfFileBytesFromBuildId(TestData.expectedId);
var buildIdLength = buildIdFileData.Length;
var data = new byte[buildIdLength].Concat(buildIdFileData).ToArray();
var segment = new ProgramHeader(ProgramHeader.Type.LoadableSegment, 0, 0,
(ulong) data.Length);
var module = ReadModule(data, new[] { segment },
new FileSection("", (ulong) buildIdLength, (ulong) buildIdLength * 2));
Assert.AreEqual(TestData.expectedId, module.Id);
}
[Test]
public void ExecutableFileAtTheMiddleOfSegment()
{
var buildIdFileData =
TestData.GetElfFileBytesFromBuildId(TestData.expectedId, isExecutable: true);
var buildIdLength = buildIdFileData.Length;
var data = new byte[buildIdLength].Concat(buildIdFileData).ToArray();
var segment = new ProgramHeader(ProgramHeader.Type.LoadableSegment, 0, 0,
(ulong)data.Length);
var module = ReadModule(data, new[] { segment },
new FileSection("", (ulong)buildIdLength, (ulong)buildIdLength * 2));
Assert.AreEqual(TestData.expectedId, module.Id);
Assert.AreEqual(true, module.IsExecutable);
}
[Test]
public void FileInSecondSegment()
{
var buildIdFileData = TestData.GetElfFileBytesFromBuildId(TestData.expectedId);
var buildIdLength = buildIdFileData.Length;
var data = new byte[buildIdLength].Concat(buildIdFileData).ToArray();
var firstSegment = new ProgramHeader(ProgramHeader.Type.LoadableSegment, 0, 0,
(ulong) buildIdLength);
var secondSegment = new ProgramHeader(ProgramHeader.Type.LoadableSegment,
(ulong) buildIdLength, (ulong) buildIdLength, (ulong) buildIdLength * 2);
var module = ReadModule(data, new[] { secondSegment, firstSegment },
new FileSection("", (ulong)buildIdLength, (ulong) buildIdLength * 2));
Assert.AreEqual(TestData.expectedId, module.Id);
}
[Test]
[TestCase(ElfHeader.Size - 1, TestName = "ElfSeparated")]
[TestCase(ElfHeader.Size + ProgramHeader.Size - 1, TestName = "ProgramHeaderSeparated")]
[TestCase(ElfHeader.Size + ProgramHeader.Size + 10, TestName = "DataSeparated")]
public void FileInSeveralSegments(int firstSegmentSize)
{
var data = TestData.GetElfFileBytesFromBuildId(TestData.expectedId);
var secondSegmentSize = data.Length - firstSegmentSize;
var firstSegment = new ProgramHeader(
ProgramHeader.Type.LoadableSegment, 0, 0, (ulong) firstSegmentSize);
var secondSegment = new ProgramHeader(ProgramHeader.Type.LoadableSegment,
(ulong) firstSegmentSize,
(ulong) firstSegmentSize,
(ulong) secondSegmentSize);
var module = ReadModule(data, new[] {secondSegment, firstSegment},
new FileSection("", 0, (ulong) data.Length));
Assert.AreEqual(TestData.expectedId, module.Id);
}
[Test]
public void SeveralFilesInOneSegment()
{
var firstFileBytes = TestData.GetElfFileBytesFromBuildId(TestData.expectedId);
var secondFileBytes = TestData.GetElfFileBytesFromBuildId(TestData.anotherExpectedId);
var data = firstFileBytes.Concat(secondFileBytes).ToArray();
var firstFileSection = new FileSection("", 0, (ulong) firstFileBytes.Length);
var secondFileSection = new FileSection("", (ulong) firstFileBytes.Length,
(ulong) data.Length);
var reader = new BinaryReader(new MemoryStream(data));
var segment = new ProgramHeader(ProgramHeader.Type.LoadableSegment, 0, 0,
(ulong) data.Length);
var firstModule = ReadModule(data, new[] {segment}, firstFileSection);
Assert.AreEqual(TestData.expectedId, firstModule.Id);
var secondModule = ReadModule(data, new[] {segment}, secondFileSection);
Assert.AreEqual(TestData.anotherExpectedId, secondModule.Id);
}
[Test]
public void SeveralFilesInSeveralSegments()
{
var firstFileBytes = TestData.GetElfFileBytesFromBuildId(TestData.expectedId);
var secondFileBytes = TestData.GetElfFileBytesFromBuildId(TestData.anotherExpectedId);
var data = firstFileBytes.Concat(secondFileBytes).ToArray();
var firstFileSection = new FileSection("", 0, (ulong) firstFileBytes.Length);
var secondFileSection = new FileSection("", (ulong) firstFileBytes.Length,
(ulong) data.Length);
var reader = new BinaryReader(new MemoryStream(data));
var firstSegmentSize = firstFileBytes.Length - 1;
var firstSegment = new ProgramHeader(ProgramHeader.Type.LoadableSegment, 0, 0,
(ulong) firstFileBytes.Length - 1);
var secondSegment = new ProgramHeader(ProgramHeader.Type.LoadableSegment,
(ulong) firstSegmentSize,
(ulong) firstSegmentSize,
(ulong) secondFileBytes.Length + 1);
var firstModule = ReadModule(data, new[] { secondSegment, firstSegment },
firstFileSection);
Assert.AreEqual(TestData.expectedId, firstModule.Id);
var secondModule = ReadModule(data, new[] { firstSegment, secondSegment },
secondFileSection);
Assert.AreEqual(TestData.anotherExpectedId, secondModule.Id);
}
private DumpModule ReadModule(byte[] data, ProgramHeader[] segments, FileSection index)
{
var reader = new BinaryReader(new MemoryStream(data));
var moduleReader = new ModuleReader(segments.ToList(), reader);
return moduleReader.GetModule(index);
}
}
} | apache-2.0 |
JiahaiWu/IDCMExpressC | IDCM/IDCM.Service/BGHandler/UpdateLocalLinkTagHandler.cs | 2345 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IDCM.Data.Base;
using System.ComponentModel;
using IDCM.Service.Common;
using System.Windows.Forms;
using IDCM.Service.Utils;
namespace IDCM.Service.BGHandler
{
public class UpdateLocalLinkTagHandler : AbsHandler
{
private GCMSiteMHub gcmHolder;
private DataGridView dataGridView;
private string keyName;
public UpdateLocalLinkTagHandler(GCMSiteMHub gcmHolder, DataGridView dataGridView, string keyName)
{
this.gcmHolder = gcmHolder;
this.dataGridView = dataGridView;
this.keyName = keyName;
}
/// <summary>
/// 后台任务执行方法的主体部分,异步执行代码段!
/// </summary>
/// <param name="worker"></param>
/// <param name="args"></param>
public override Object doWork(BackgroundWorker worker, bool cancel, List<Object> args)
{
bool res = false;
DWorkMHub.note(AsyncMessage.StartBackProgress);
Dictionary<string, int> loadedNoter =gcmHolder.getLoadedNoter();
foreach (DataGridViewRow dgvr in dataGridView.Rows)
{
if (dgvr.IsNewRow || dgvr.Index < 0)
continue;
DataGridViewCell dgvc =dgvr.Cells[keyName];
if (dgvc != null && loadedNoter.ContainsKey(DGVUtil.getCellValue(dgvc)))
{
dgvr.Cells[0].Value = true;
}
else
{
dgvr.Cells[0].Value = false;
}
}
return new object[] { res };
}
/// <summary>
/// 后台任务执行结束,回调代码段
/// </summary>
/// <param name="worker"></param>
/// <param name="args"></param>
public override void complete(BackgroundWorker worker, bool canceled, Exception error, List<Object> args)
{
DWorkMHub.note(AsyncMessage.EndBackProgress);
if (canceled)
return;
if (error != null)
{
log.Error(error);
return;
}
}
}
}
| apache-2.0 |
googleapis/java-dialogflow-cx | google-cloud-dialogflow-cx/src/main/java/com/google/cloud/dialogflow/cx/v3/stub/GrpcDeploymentsCallableFactory.java | 4764 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.dialogflow.cx.v3.stub;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcCallableFactory;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.BatchingCallSettings;
import com.google.api.gax.rpc.BidiStreamingCallable;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientStreamingCallable;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.StreamingCallSettings;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.longrunning.Operation;
import com.google.longrunning.stub.OperationsStub;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC callable factory implementation for the Deployments service API.
*
* <p>This class is for advanced usage.
*/
@Generated("by gapic-generator-java")
public class GrpcDeploymentsCallableFactory implements GrpcStubCallableFactory {
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createUnaryCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
UnaryCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createUnaryCallable(grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, PagedListResponseT>
UnaryCallable<RequestT, PagedListResponseT> createPagedCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
PagedCallSettings<RequestT, ResponseT, PagedListResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createPagedCallable(grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createBatchingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
BatchingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createBatchingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, MetadataT>
OperationCallable<RequestT, ResponseT, MetadataT> createOperationCallable(
GrpcCallSettings<RequestT, Operation> grpcCallSettings,
OperationCallSettings<RequestT, ResponseT, MetadataT> callSettings,
ClientContext clientContext,
OperationsStub operationsStub) {
return GrpcCallableFactory.createOperationCallable(
grpcCallSettings, callSettings, clientContext, operationsStub);
}
@Override
public <RequestT, ResponseT>
BidiStreamingCallable<RequestT, ResponseT> createBidiStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
StreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createBidiStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT>
ServerStreamingCallable<RequestT, ResponseT> createServerStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
ServerStreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createServerStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT>
ClientStreamingCallable<RequestT, ResponseT> createClientStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
StreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createClientStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
}
| apache-2.0 |
hanahmily/sky-walking | apm-collector/apm-collector-storage/collector-storage-h2-provider/src/main/java/org/apache/skywalking/apm/collector/storage/h2/define/srmp/ServiceReferenceDayMetricH2TableDefine.java | 1397 | /*
* 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.skywalking.apm.collector.storage.h2.define.srmp;
import org.apache.skywalking.apm.collector.core.storage.TimePyramid;
import org.apache.skywalking.apm.collector.core.util.Const;
import org.apache.skywalking.apm.collector.storage.table.service.ServiceReferenceMetricTable;
/**
* @author peng-yongsheng
*/
public class ServiceReferenceDayMetricH2TableDefine extends AbstractServiceReferenceMetricH2TableDefine {
public ServiceReferenceDayMetricH2TableDefine() {
super(ServiceReferenceMetricTable.TABLE + Const.ID_SPLIT + TimePyramid.Day.getName());
}
}
| apache-2.0 |
wuyuntao/Nostradamus | NostradamusTests/ServerSimulatorTest.cs | 2743 | using Nostradamus.Client;
using Nostradamus.Examples;
using Nostradamus.Physics;
using Nostradamus.Server;
using NUnit.Framework;
namespace Nostradamus.Tests
{
public class ServerSimulatorTest
{
[Test]
public void TestExampleScene()
{
var simulator = new ServerSimulator();
simulator.RegisterActorFactory<ExampleSceneDesc, ExampleScene>(desc => new ExampleScene());
simulator.RegisterActorFactory<BallDesc, Ball>(desc => new Ball());
simulator.RegisterActorFactory<CubeDesc, Cube>(desc => new Cube());
var sceneDesc = new ExampleSceneDesc(50, 50);
var scene = simulator.CreateScene<ExampleScene>(sceneDesc);
// Time: 0 - 50
simulator.Simulate();
var frame0 = simulator.DeltaSyncFrame;
Assert.AreEqual(0, frame0.Time);
Assert.AreEqual(50, frame0.DeltaTime);
Assert.AreEqual(3, frame0.Events.Count);
var ball50 = (RigidBodySnapshot)scene.Ball.Snapshot;
AssertHelper.AreApproximate(-2.6f, ball50.Position.X);
AssertHelper.AreApproximate(2.575475f, ball50.Position.Y);
AssertHelper.AreApproximate(-2.6f, ball50.Position.Z);
var cube50 = (RigidBodySnapshot)scene.Cube.Snapshot;
AssertHelper.AreApproximate(1.1f, cube50.Position.X);
AssertHelper.AreApproximate(1.07547498f, cube50.Position.Y);
AssertHelper.AreApproximate(1.1f, cube50.Position.Z);
var killBallCommand = new KickBallCommand(1, 0, 1);
var clientId = new ClientId(1);
var command = new Command(clientId, scene.Ball.Desc.Id, 1, 20, 20, killBallCommand);
var clientFrame = new CommandFrame(clientId);
clientFrame.Commands.Add(command);
simulator.ReceiveCommandFrame(clientFrame);
// Time: 50 - 100
simulator.Simulate();
var frame50 = simulator.DeltaSyncFrame;
Assert.AreEqual(50, frame50.Time);
Assert.AreEqual(50, frame50.DeltaTime);
Assert.AreEqual(2, frame50.Events.Count);
var ball100 = (RigidBodySnapshot)scene.Ball.Snapshot;
AssertHelper.AreApproximate(-2.3499999f, ball100.Position.X);
AssertHelper.AreApproximate(2.52669716f, ball100.Position.Y);
AssertHelper.AreApproximate(-2.3499999f, ball100.Position.Z);
var cube100 = (RigidBodySnapshot)scene.Cube.Snapshot;
AssertHelper.AreApproximate(1.1f, cube100.Position.X);
AssertHelper.AreApproximate(1.02669704f, cube100.Position.Y);
AssertHelper.AreApproximate(1.1f, cube100.Position.Z);
}
}
}
| apache-2.0 |
acoburn/image-laplacian | include/boost/gil/extension/numeric/sampler.hpp | 6349 | /*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://opensource.adobe.com/licenses.html)
*/
/*************************************************************************************************/
#ifndef GIL_SAMPLER_HPP
#define GIL_SAMPLER_HPP
#include <boost/gil/extension/dynamic_image/dynamic_image_all.hpp>
#include "pixel_numeric_operations.hpp"
////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief Nearest-neighbor and bilinear image samplers.
/// NOTE: The code is for example use only. It is not optimized for performance
/// \author Lubomir Bourdev and Hailin Jin \n
/// Adobe Systems Incorporated
/// \date 2005-2007 \n October 30, 2006
///
////////////////////////////////////////////////////////////////////////////////////////
namespace boost { namespace gil {
///////////////////////////////////////////////////////////////////////////
////
//// resample_pixels: set each pixel in the destination view as the result of a sampling function over the transformed coordinates of the source view
////
///////////////////////////////////////////////////////////////////////////
/*
template <typename Sampler>
concept SamplerConcept {
template <typename DstP, // Models PixelConcept
typename SrcView, // Models RandomAccessNDImageViewConcept
typename S_COORDS> // Models PointNDConcept, where S_COORDS::num_dimensions == SrcView::num_dimensions
bool sample(const Sampler& s, const SrcView& src, const S_COORDS& p, DstP result);
};
*/
/// \brief A sampler that sets the destination pixel to the closest one in the source. If outside the bounds, it doesn't change the destination
/// \ingroup ImageAlgorithms
struct nearest_neighbor_sampler {};
template <typename DstP, typename SrcView, typename F>
bool sample(nearest_neighbor_sampler, const SrcView& src, const point2<F>& p, DstP& result) {
point2<int> center(iround(p));
if (center.x>=0 && center.y>=0 && center.x<src.width() && center.y<src.height()) {
result=src(center.x,center.y);
return true;
}
return false;
}
struct cast_channel_fn {
template <typename SrcChannel, typename DstChannel>
void operator()(const SrcChannel& src, DstChannel& dst) {
typedef typename channel_traits<DstChannel>::value_type dst_value_t;
dst = dst_value_t(src);
}
};
template <typename SrcPixel, typename DstPixel>
void cast_pixel(const SrcPixel& src, DstPixel& dst) {
static_for_each(src,dst,cast_channel_fn());
}
namespace detail {
template <typename Weight>
struct add_dst_mul_src_channel {
Weight _w;
add_dst_mul_src_channel(Weight w) : _w(w) {}
template <typename SrcChannel, typename DstChannel>
void operator()(const SrcChannel& src, DstChannel& dst) const {
dst += DstChannel(src*_w);
}
};
// dst += DST_TYPE(src * w)
template <typename SrcP,typename Weight,typename DstP>
struct add_dst_mul_src {
void operator()(const SrcP& src, Weight weight, DstP& dst) const {
static_for_each(src,dst, add_dst_mul_src_channel<Weight>(weight));
// pixel_assigns_t<DstP,DstP&>()(
// pixel_plus_t<DstP,DstP,DstP>()(
// pixel_multiplies_scalar_t<SrcP,Weight,DstP>()(src,weight),
// dst),
// dst);
}
};
} // namespace detail
/// \brief A sampler that sets the destination pixel as the bilinear interpolation of the four closest pixels from the source.
/// If outside the bounds, it doesn't change the destination
/// \ingroup ImageAlgorithms
struct bilinear_sampler {};
template <typename DstP, typename SrcView, typename F>
bool sample(bilinear_sampler, const SrcView& src, const point2<F>& p, DstP& result) {
typedef typename SrcView::value_type SrcP;
point2<std::ptrdiff_t> p0(ifloor(p)); // the closest integer coordinate top left from p
point2<F> frac(p.x-p0.x, p.y-p0.y);
if (p0.x < 0 || p0.y < 0 || p0.x>=src.width() || p0.y>=src.height()) return false;
pixel<F,devicen_layout_t<num_channels<SrcView>::value> > mp(0); // suboptimal
typename SrcView::xy_locator loc=src.xy_at(p0.x,p0.y);
if (p0.x+1<src.width()) {
if (p0.y+1<src.height()) {
// most common case - inside the image, not on the last row or column
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, (1-frac.x)*(1-frac.y),mp);
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], frac.x *(1-frac.y),mp);
++loc.y();
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, (1-frac.x)* frac.y ,mp);
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], frac.x * frac.y ,mp);
} else {
// on the last row, but not the bottom-right corner pixel
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, (1-frac.x),mp);
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], frac.x ,mp);
}
} else {
if (p0.y+1<src.height()) {
// on the last column, but not the bottom-right corner pixel
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, (1-frac.y),mp);
++loc.y();
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, frac.y ,mp);
} else {
// the bottom-right corner pixel
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc,1,mp);
}
}
// Convert from floating point average value to the source type
SrcP src_result;
cast_pixel(mp,src_result);
color_convert(src_result, result);
return true;
}
} } // namespace boost::gil
#endif
| apache-2.0 |
OLR-xray/OLR-3.0 | src/xray/xr_3da/xrGame/ui/UIInventoryUtilities.cpp | 13039 | #include "stdafx.h"
#include "UIInventoryUtilities.h"
#include "../WeaponAmmo.h"
#include "../UIStaticItem.h"
#include "UIStatic.h"
#include "../eatable_item.h"
#include "../Level.h"
#include "../HUDManager.h"
#include "../date_time.h"
#include "../string_table.h"
#include "../Inventory.h"
#include "../InventoryOwner.h"
#include "../InfoPortion.h"
#include "../game_base_space.h"
#include "../actor.h"
#define BUY_MENU_TEXTURE "ui\\ui_mp_buy_menu"
#define EQUIPMENT_ICONS "ui\\ui_icon_equipment"
#define CHAR_ICONS "ui\\ui_icons_npc"
#define MAP_ICONS "ui\\ui_icons_map"
#define MP_CHAR_ICONS "ui\\ui_models_multiplayer"
const LPCSTR relationsLtxSection = "game_relations";
const LPCSTR ratingField = "rating_names";
const LPCSTR reputationgField = "reputation_names";
const LPCSTR goodwillField = "goodwill_names";
ref_shader g_BuyMenuShader = NULL;
ref_shader g_EquipmentIconsShader = NULL;
ref_shader g_MPCharIconsShader = NULL;
ref_shader g_tmpWMShader = NULL;
static CUIStatic* GetUIStatic ();
typedef std::pair<CHARACTER_RANK_VALUE, shared_str> CharInfoStringID;
DEF_MAP (CharInfoStrings, CHARACTER_RANK_VALUE, shared_str);
CharInfoStrings *charInfoReputationStrings = NULL;
CharInfoStrings *charInfoRankStrings = NULL;
CharInfoStrings *charInfoGoodwillStrings = NULL;
void InventoryUtilities::CreateShaders()
{
g_tmpWMShader.create("effects\\wallmark", "wm\\wm_grenade");
}
void InventoryUtilities::DestroyShaders()
{
g_BuyMenuShader.destroy ();
g_EquipmentIconsShader.destroy ();
g_MPCharIconsShader.destroy ();
g_tmpWMShader.destroy ();
}
bool InventoryUtilities::GreaterRoomInRuck(PIItem item1, PIItem item2)
{
Ivector2 r1,r2;
r1.x = item1->GetGridWidth();
r1.y = item1->GetGridHeight();
r2.x = item2->GetGridWidth();
r2.y = item2->GetGridHeight();
if(r1.x > r2.x) return true;
if (r1.x == r2.x)
{
if(r1.y > r2.y) return true;
if (r1.y == r2.y){
if(item1->object().cNameSect()==item2->object().cNameSect())
return (item1->object().ID() > item2->object().ID());
else
return (item1->object().cNameSect()>item2->object().cNameSect());
}
return false;
}
return false;
}
bool InventoryUtilities::FreeRoom_inBelt (TIItemContainer& item_list, PIItem _item, int width, int height)
{
bool* ruck_room = (bool*)alloca(width*height);
int i,j,k,m;
int place_row = 0, place_col = 0;
bool found_place;
bool can_place;
for(i=0; i<height; ++i)
for(j=0; j<width; ++j)
ruck_room[i*width + j] = false;
item_list.push_back (_item);
std::sort (item_list.begin(), item_list.end(),GreaterRoomInRuck);
found_place = true;
for(xr_vector<PIItem>::iterator it = item_list.begin(); (item_list.end() != it) && found_place; ++it)
{
PIItem pItem = *it;
int iWidth = pItem->GetGridWidth();
int iHeight = pItem->GetGridHeight();
//ïðîâåðèòü ìîæíî ëè ðàçìåñòèòü ýëåìåíò,
//ïðîâåðÿåì ïîñëåäîâàòåëüíî êàæäóþ êëåòî÷êó
found_place = false;
for(i=0; (i<height - iHeight +1) && !found_place; ++i)
{
for(j=0; (j<width - iWidth +1) && !found_place; ++j)
{
can_place = true;
for(k=0; (k<iHeight) && can_place; ++k)
{
for(m=0; (m<iHeight) && can_place; ++m)
{
if(ruck_room[(i+k)*width + (j+m)])
can_place = false;
}
}
if(can_place)
{
found_place=true;
place_row = i;
place_col = j;
}
}
}
//ðàçìåñòèòü ýëåìåíò íà íàéäåííîì ìåñòå
if(found_place)
{
for(k=0; k<iHeight; ++k)
{
for(m=0; m<iWidth; ++m)
{
ruck_room[(place_row+k)*width + place_col+m] = true;
}
}
}
}
// remove
item_list.erase (std::remove(item_list.begin(),item_list.end(),_item),item_list.end());
//äëÿ êàêîãî-òî ýëåìåíòà ìåñòà íå íàøëîñü
if(!found_place) return false;
return true;
}
ref_shader& InventoryUtilities::GetBuyMenuShader()
{
if(!g_BuyMenuShader)
{
g_BuyMenuShader.create("hud\\default", BUY_MENU_TEXTURE);
}
return g_BuyMenuShader;
}
ref_shader& InventoryUtilities::GetEquipmentIconsShader()
{
if(!g_EquipmentIconsShader)
{
g_EquipmentIconsShader.create("hud\\default", EQUIPMENT_ICONS);
}
return g_EquipmentIconsShader;
}
ref_shader& InventoryUtilities::GetMPCharIconsShader()
{
if(!g_MPCharIconsShader)
{
g_MPCharIconsShader.create("hud\\default", MP_CHAR_ICONS);
}
return g_MPCharIconsShader;
}
//////////////////////////////////////////////////////////////////////////
const shared_str InventoryUtilities::GetGameDateAsString(EDatePrecision datePrec, char dateSeparator)
{
return GetDateAsString(Level().GetGameTime(), datePrec, dateSeparator);
}
//////////////////////////////////////////////////////////////////////////
const shared_str InventoryUtilities::GetGameTimeAsString(ETimePrecision timePrec, char timeSeparator)
{
return GetTimeAsString(Level().GetGameTime(), timePrec, timeSeparator);
}
//////////////////////////////////////////////////////////////////////////
const shared_str InventoryUtilities::GetTimeAsString(ALife::_TIME_ID time, ETimePrecision timePrec, char timeSeparator)
{
string64 bufTime;
ZeroMemory(bufTime, sizeof(bufTime));
u32 year = 0, month = 0, day = 0, hours = 0, mins = 0, secs = 0, milisecs = 0;
split_time(time, year, month, day, hours, mins, secs, milisecs);
// Time
switch (timePrec)
{
case etpTimeToHours:
sprintf_s(bufTime, "%02i", hours);
break;
case etpTimeToMinutes:
sprintf_s(bufTime, "%02i%c%02i", hours, timeSeparator, mins);
break;
case etpTimeToSeconds:
sprintf_s(bufTime, "%02i%c%02i%c%02i", hours, timeSeparator, mins, timeSeparator, secs);
break;
case etpTimeToMilisecs:
sprintf_s(bufTime, "%02i%c%02i%c%02i%c%02i", hours, timeSeparator, mins, timeSeparator, secs, timeSeparator, milisecs);
break;
case etpTimeToSecondsAndDay:
{
int total_day = (int)( time/(1000*60*60*24) );
sprintf_s(bufTime, sizeof(bufTime), "%dd %02i%c%02i%c%02i", total_day, hours, timeSeparator, mins, timeSeparator, secs);
break;
}
default:
R_ASSERT(!"Unknown type of date precision");
}
return bufTime;
}
const shared_str InventoryUtilities::GetDateAsString(ALife::_TIME_ID date, EDatePrecision datePrec, char dateSeparator)
{
string32 bufDate;
ZeroMemory(bufDate, sizeof(bufDate));
u32 year = 0, month = 0, day = 0, hours = 0, mins = 0, secs = 0, milisecs = 0;
split_time(date, year, month, day, hours, mins, secs, milisecs);
// Date
switch (datePrec)
{
case edpDateToYear:
sprintf_s(bufDate, "%04i", year);
break;
case edpDateToMonth:
sprintf_s(bufDate, "%02i%c%04i", month, dateSeparator, year);
break;
case edpDateToDay:
sprintf_s(bufDate, "%02i%c%02i%c%04i", day, dateSeparator, month, dateSeparator, year);
break;
default:
R_ASSERT(!"Unknown type of date precision");
}
return bufDate;
}
LPCSTR InventoryUtilities::GetTimePeriodAsString(LPSTR _buff, u32 buff_sz, ALife::_TIME_ID _from, ALife::_TIME_ID _to)
{
u32 year1,month1,day1,hours1,mins1,secs1,milisecs1;
u32 year2,month2,day2,hours2,mins2,secs2,milisecs2;
split_time(_from, year1, month1, day1, hours1, mins1, secs1, milisecs1);
split_time(_to, year2, month2, day2, hours2, mins2, secs2, milisecs2);
int cnt = 0;
_buff[0] = 0;
if(month1!=month2)
cnt = sprintf_s(_buff+cnt,buff_sz-cnt,"%d %s ",month2-month1, *CStringTable().translate("ui_st_months"));
if(!cnt && day1!=day2)
cnt = sprintf_s(_buff+cnt,buff_sz-cnt,"%d %s",day2-day1, *CStringTable().translate("ui_st_days"));
if(!cnt && hours1!=hours2)
cnt = sprintf_s(_buff+cnt,buff_sz-cnt,"%d %s",hours2-hours1, *CStringTable().translate("ui_st_hours"));
if(!cnt && mins1!=mins2)
cnt = sprintf_s(_buff+cnt,buff_sz-cnt,"%d %s",mins2-mins1, *CStringTable().translate("ui_st_mins"));
if(!cnt && secs1!=secs2)
cnt = sprintf_s(_buff+cnt,buff_sz-cnt,"%d %s",secs2-secs1, *CStringTable().translate("ui_st_secs"));
return _buff;
}
//////////////////////////////////////////////////////////////////////////
void InventoryUtilities::UpdateWeight(CUIStatic &wnd, bool withPrefix)
{
CInventoryOwner *pInvOwner = smart_cast<CInventoryOwner*>(Level().CurrentEntity());
R_ASSERT(pInvOwner);
string128 buf;
ZeroMemory(buf, sizeof(buf));
float total = pInvOwner->inventory().CalcTotalWeight();
float max = pInvOwner->MaxCarryWeight();
string16 cl;
ZeroMemory(cl, sizeof(cl));
if (total > max)
{
strcpy(cl, "%c[red]");
}
else
{
strcpy(cl, "%c[UI_orange]");
}
string32 prefix;
ZeroMemory(prefix, sizeof(prefix));
if (withPrefix)
{
sprintf_s(prefix, "%%c[default]%s ", *CStringTable().translate("ui_inv_weight"));
}
else
{
strcpy(prefix, "");
}
sprintf_s(buf, "%s%s%3.1f %s/%5.1f", prefix, cl, total, "%c[UI_orange]", max);
wnd.SetText(buf);
// UIStaticWeight.ClipperOff();
}
//////////////////////////////////////////////////////////////////////////
void LoadStrings(CharInfoStrings *container, LPCSTR section, LPCSTR field)
{
R_ASSERT(container);
LPCSTR cfgRecord = pSettings->r_string(section, field);
u32 count = _GetItemCount(cfgRecord);
R_ASSERT3 (count%2, "there're must be an odd number of elements", field);
string64 singleThreshold;
ZeroMemory (singleThreshold, sizeof(singleThreshold));
int upBoundThreshold = 0;
CharInfoStringID id;
for (u32 k = 0; k < count; k += 2)
{
_GetItem(cfgRecord, k, singleThreshold);
id.second = singleThreshold;
_GetItem(cfgRecord, k + 1, singleThreshold);
if(k+1!=count)
sscanf(singleThreshold, "%i", &upBoundThreshold);
else
upBoundThreshold += 1;
id.first = upBoundThreshold;
container->insert(id);
}
}
//////////////////////////////////////////////////////////////////////////
void InitCharacterInfoStrings()
{
if (charInfoReputationStrings && charInfoRankStrings) return;
if (!charInfoReputationStrings)
{
// Create string->Id DB
charInfoReputationStrings = xr_new<CharInfoStrings>();
// Reputation
LoadStrings(charInfoReputationStrings, relationsLtxSection, reputationgField);
}
if (!charInfoRankStrings)
{
// Create string->Id DB
charInfoRankStrings = xr_new<CharInfoStrings>();
// Ranks
LoadStrings(charInfoRankStrings, relationsLtxSection, ratingField);
}
if (!charInfoGoodwillStrings)
{
// Create string->Id DB
charInfoGoodwillStrings = xr_new<CharInfoStrings>();
// Goodwills
LoadStrings(charInfoGoodwillStrings, relationsLtxSection, goodwillField);
}
}
//////////////////////////////////////////////////////////////////////////
void InventoryUtilities::ClearCharacterInfoStrings()
{
xr_delete(charInfoReputationStrings);
xr_delete(charInfoRankStrings);
xr_delete(charInfoGoodwillStrings);
}
//////////////////////////////////////////////////////////////////////////
LPCSTR InventoryUtilities::GetRankAsText(CHARACTER_RANK_VALUE rankID)
{
InitCharacterInfoStrings();
CharInfoStrings::const_iterator cit = charInfoRankStrings->upper_bound(rankID);
if(charInfoRankStrings->end() == cit)
return charInfoRankStrings->rbegin()->second.c_str();
return cit->second.c_str();
}
//////////////////////////////////////////////////////////////////////////
LPCSTR InventoryUtilities::GetReputationAsText(CHARACTER_REPUTATION_VALUE rankID)
{
InitCharacterInfoStrings();
CharInfoStrings::const_iterator cit = charInfoReputationStrings->upper_bound(rankID);
if(charInfoReputationStrings->end() == cit)
return charInfoReputationStrings->rbegin()->second.c_str();
return cit->second.c_str();
}
//////////////////////////////////////////////////////////////////////////
LPCSTR InventoryUtilities::GetGoodwillAsText(CHARACTER_GOODWILL goodwill)
{
InitCharacterInfoStrings();
CharInfoStrings::const_iterator cit = charInfoGoodwillStrings->upper_bound(goodwill);
if(charInfoGoodwillStrings->end() == cit)
return charInfoGoodwillStrings->rbegin()->second.c_str();
return cit->second.c_str();
}
//////////////////////////////////////////////////////////////////////////
// ñïåöèàëüíàÿ ôóíêöèÿ äëÿ ïåðåäà÷è info_portions ïðè íàæàòèè êíîïîê UI
// (äëÿ tutorial)
void InventoryUtilities::SendInfoToActor(LPCSTR info_id)
{
if (GameID() != GAME_SINGLE) return;
CActor* actor = smart_cast<CActor*>(Level().CurrentEntity());
if(actor)
{
actor->TransferInfo(info_id, true);
}
}
u32 InventoryUtilities::GetGoodwillColor(CHARACTER_GOODWILL gw)
{
u32 res = 0xffc0c0c0;
if(gw==NEUTRAL_GOODWILL){
res = 0xffc0c0c0;
}else
if(gw>1000){
res = 0xff00ff00;
}else
if(gw<-1000){
res = 0xffff0000;
}
return res;
}
u32 InventoryUtilities::GetReputationColor(CHARACTER_REPUTATION_VALUE rv)
{
u32 res = 0xffc0c0c0;
if(rv==NEUTAL_REPUTATION){
res = 0xffc0c0c0;
}else
if(rv>50){
res = 0xff00ff00;
}else
if(rv<-50){
res = 0xffff0000;
}
return res;
}
u32 InventoryUtilities::GetRelationColor(ALife::ERelationType relation)
{
switch(relation) {
case ALife::eRelationTypeFriend:
return 0xff00ff00;
break;
case ALife::eRelationTypeNeutral:
return 0xffc0c0c0;
break;
case ALife::eRelationTypeEnemy:
return 0xffff0000;
break;
default:
NODEFAULT;
}
#ifdef DEBUG
return 0xffffffff;
#endif
}
| apache-2.0 |
nafae/developer | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201403/ApproveWorkflowApprovalRequests.java | 997 |
package com.google.api.ads.dfp.jaxws.v201403;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* The action used to approve {@link WorkflowApprovalRequest workflow approval requests}.
*
*
* <p>Java class for ApproveWorkflowApprovalRequests complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ApproveWorkflowApprovalRequests">
* <complexContent>
* <extension base="{https://www.google.com/apis/ads/publisher/v201403}WorkflowRequestAction">
* <sequence>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ApproveWorkflowApprovalRequests")
public class ApproveWorkflowApprovalRequests
extends WorkflowRequestAction
{
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_5603.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_5603 {
}
| apache-2.0 |
fenik17/netty | transport/src/main/java/io/netty/channel/ThreadPerChannelEventLoopGroup.java | 11358 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.netty.channel;
import io.netty.util.concurrent.AbstractEventExecutorGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.ThreadPerTaskExecutor;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.ReadOnlyIterator;
import io.netty.util.internal.ThrowableUtil;
import java.util.Collections;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* An {@link EventLoopGroup} that creates one {@link EventLoop} per {@link Channel}.
*
* @deprecated this will be remove in the next-major release.
*/
@Deprecated
public class ThreadPerChannelEventLoopGroup extends AbstractEventExecutorGroup implements EventLoopGroup {
private final Object[] childArgs;
private final int maxChannels;
final Executor executor;
final Set<EventLoop> activeChildren =
Collections.newSetFromMap(PlatformDependent.<EventLoop, Boolean>newConcurrentHashMap());
final Queue<EventLoop> idleChildren = new ConcurrentLinkedQueue<EventLoop>();
private final ChannelException tooManyChannels;
private volatile boolean shuttingDown;
private final Promise<?> terminationFuture = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE);
private final FutureListener<Object> childTerminationListener = new FutureListener<Object>() {
@Override
public void operationComplete(Future<Object> future) throws Exception {
// Inefficient, but works.
if (isTerminated()) {
terminationFuture.trySuccess(null);
}
}
};
/**
* Create a new {@link ThreadPerChannelEventLoopGroup} with no limit in place.
*/
protected ThreadPerChannelEventLoopGroup() {
this(0);
}
/**
* Create a new {@link ThreadPerChannelEventLoopGroup}.
*
* @param maxChannels the maximum number of channels to handle with this instance. Once you try to register
* a new {@link Channel} and the maximum is exceed it will throw an
* {@link ChannelException}. on the {@link #register(Channel)} and
* {@link #register(ChannelPromise)} method.
* Use {@code 0} to use no limit
*/
protected ThreadPerChannelEventLoopGroup(int maxChannels) {
this(maxChannels, (ThreadFactory) null);
}
/**
* Create a new {@link ThreadPerChannelEventLoopGroup}.
*
* @param maxChannels the maximum number of channels to handle with this instance. Once you try to register
* a new {@link Channel} and the maximum is exceed it will throw an
* {@link ChannelException} on the {@link #register(Channel)} and
* {@link #register(ChannelPromise)} method.
* Use {@code 0} to use no limit
* @param threadFactory the {@link ThreadFactory} used to create new {@link Thread} instances that handle the
* registered {@link Channel}s
* @param args arguments which will passed to each {@link #newChild(Object...)} call.
*/
protected ThreadPerChannelEventLoopGroup(int maxChannels, ThreadFactory threadFactory, Object... args) {
this(maxChannels, threadFactory == null ? null : new ThreadPerTaskExecutor(threadFactory), args);
}
/**
* Create a new {@link ThreadPerChannelEventLoopGroup}.
*
* @param maxChannels the maximum number of channels to handle with this instance. Once you try to register
* a new {@link Channel} and the maximum is exceed it will throw an
* {@link ChannelException} on the {@link #register(Channel)} and
* {@link #register(ChannelPromise)} method.
* Use {@code 0} to use no limit
* @param executor the {@link Executor} used to create new {@link Thread} instances that handle the
* registered {@link Channel}s
* @param args arguments which will passed to each {@link #newChild(Object...)} call.
*/
protected ThreadPerChannelEventLoopGroup(int maxChannels, Executor executor, Object... args) {
ObjectUtil.checkPositiveOrZero(maxChannels, "maxChannels");
if (executor == null) {
executor = new ThreadPerTaskExecutor(new DefaultThreadFactory(getClass()));
}
if (args == null) {
childArgs = EmptyArrays.EMPTY_OBJECTS;
} else {
childArgs = args.clone();
}
this.maxChannels = maxChannels;
this.executor = executor;
tooManyChannels = ThrowableUtil.unknownStackTrace(
ChannelException.newStatic("too many channels (max: " + maxChannels + ')', null),
ThreadPerChannelEventLoopGroup.class, "nextChild()");
}
/**
* Creates a new {@link EventLoop}. The default implementation creates a new {@link ThreadPerChannelEventLoop}.
*/
protected EventLoop newChild(@SuppressWarnings("UnusedParameters") Object... args) throws Exception {
return new ThreadPerChannelEventLoop(this);
}
@Override
public Iterator<EventExecutor> iterator() {
return new ReadOnlyIterator<EventExecutor>(activeChildren.iterator());
}
@Override
public EventLoop next() {
throw new UnsupportedOperationException();
}
@Override
public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
shuttingDown = true;
for (EventLoop l: activeChildren) {
l.shutdownGracefully(quietPeriod, timeout, unit);
}
for (EventLoop l: idleChildren) {
l.shutdownGracefully(quietPeriod, timeout, unit);
}
// Notify the future if there was no children.
if (isTerminated()) {
terminationFuture.trySuccess(null);
}
return terminationFuture();
}
@Override
public Future<?> terminationFuture() {
return terminationFuture;
}
@Override
@Deprecated
public void shutdown() {
shuttingDown = true;
for (EventLoop l: activeChildren) {
l.shutdown();
}
for (EventLoop l: idleChildren) {
l.shutdown();
}
// Notify the future if there was no children.
if (isTerminated()) {
terminationFuture.trySuccess(null);
}
}
@Override
public boolean isShuttingDown() {
for (EventLoop l: activeChildren) {
if (!l.isShuttingDown()) {
return false;
}
}
for (EventLoop l: idleChildren) {
if (!l.isShuttingDown()) {
return false;
}
}
return true;
}
@Override
public boolean isShutdown() {
for (EventLoop l: activeChildren) {
if (!l.isShutdown()) {
return false;
}
}
for (EventLoop l: idleChildren) {
if (!l.isShutdown()) {
return false;
}
}
return true;
}
@Override
public boolean isTerminated() {
for (EventLoop l: activeChildren) {
if (!l.isTerminated()) {
return false;
}
}
for (EventLoop l: idleChildren) {
if (!l.isTerminated()) {
return false;
}
}
return true;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
long deadline = System.nanoTime() + unit.toNanos(timeout);
for (EventLoop l: activeChildren) {
for (;;) {
long timeLeft = deadline - System.nanoTime();
if (timeLeft <= 0) {
return isTerminated();
}
if (l.awaitTermination(timeLeft, TimeUnit.NANOSECONDS)) {
break;
}
}
}
for (EventLoop l: idleChildren) {
for (;;) {
long timeLeft = deadline - System.nanoTime();
if (timeLeft <= 0) {
return isTerminated();
}
if (l.awaitTermination(timeLeft, TimeUnit.NANOSECONDS)) {
break;
}
}
}
return isTerminated();
}
@Override
public ChannelFuture register(Channel channel) {
ObjectUtil.checkNotNull(channel, "channel");
try {
EventLoop l = nextChild();
return l.register(new DefaultChannelPromise(channel, l));
} catch (Throwable t) {
return new FailedChannelFuture(channel, GlobalEventExecutor.INSTANCE, t);
}
}
@Override
public ChannelFuture register(ChannelPromise promise) {
try {
return nextChild().register(promise);
} catch (Throwable t) {
promise.setFailure(t);
return promise;
}
}
@Deprecated
@Override
public ChannelFuture register(Channel channel, ChannelPromise promise) {
ObjectUtil.checkNotNull(channel, "channel");
try {
return nextChild().register(channel, promise);
} catch (Throwable t) {
promise.setFailure(t);
return promise;
}
}
private EventLoop nextChild() throws Exception {
if (shuttingDown) {
throw new RejectedExecutionException("shutting down");
}
EventLoop loop = idleChildren.poll();
if (loop == null) {
if (maxChannels > 0 && activeChildren.size() >= maxChannels) {
throw tooManyChannels;
}
loop = newChild(childArgs);
loop.terminationFuture().addListener(childTerminationListener);
}
activeChildren.add(loop);
return loop;
}
}
| apache-2.0 |
glahiru/airavata | modules/orchestrator/airavata-orchestrator-service/src/main/java/org/apache/airavata/orchestrator/server/OrchestratorServer.java | 4900 | /*
*
* 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.airavata.orchestrator.server;
import java.net.InetSocketAddress;
import org.apache.airavata.common.utils.IServer;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.orchestrator.cpi.OrchestratorService;
import org.apache.airavata.orchestrator.util.Constants;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OrchestratorServer implements IServer{
private final static Logger logger = LoggerFactory.getLogger(OrchestratorServer.class);
private static final String SERVER_NAME = "Orchestrator Server";
private static final String SERVER_VERSION = "1.0";
private ServerStatus status;
private TServer server;
public OrchestratorServer() {
setStatus(ServerStatus.STOPPED);
}
public void StartOrchestratorServer(OrchestratorService.Processor<OrchestratorServerHandler> orchestratorServerHandlerProcessor)
throws Exception {
try {
final int serverPort = Integer.parseInt(ServerSettings.getSetting(Constants.ORCHESTRATOT_SERVER_PORT,"8940"));
final String serverHost = ServerSettings.getSetting(Constants.ORCHESTRATOT_SERVER_HOST, null);
TServerTransport serverTransport;
if(serverHost == null){
serverTransport = new TServerSocket(serverPort);
}else{
InetSocketAddress inetSocketAddress = new InetSocketAddress(serverHost, serverPort);
serverTransport = new TServerSocket(inetSocketAddress);
}
//server = new TSimpleServer(
// new TServer.Args(serverTransport).processor(orchestratorServerHandlerProcessor));
TThreadPoolServer.Args options = new TThreadPoolServer.Args(serverTransport);
options.minWorkerThreads = Integer.parseInt(ServerSettings.getSetting(Constants.ORCHESTRATOT_SERVER_MIN_THREADS, "30"));
server = new TThreadPoolServer(options.processor(orchestratorServerHandlerProcessor));
new Thread() {
public void run() {
server.serve();
setStatus(ServerStatus.STOPPED);
logger.info("Orchestrator Server Stopped.");
}
}.start();
new Thread() {
public void run() {
while(!server.isServing()){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
if (server.isServing()){
setStatus(ServerStatus.STARTED);
logger.info("Starting Orchestrator Server on Port " + serverPort);
logger.info("Listening to Orchestrator Clients ....");
}
}
}.start();
} catch (TTransportException e) {
logger.error(e.getMessage());
setStatus(ServerStatus.FAILED);
}
}
public static void main(String[] args) {
try {
new OrchestratorServer().start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void start() throws Exception {
setStatus(ServerStatus.STARTING);
OrchestratorService.Processor<OrchestratorServerHandler> orchestratorService =
new OrchestratorService.Processor<OrchestratorServerHandler>(new OrchestratorServerHandler());
StartOrchestratorServer(orchestratorService);
}
@Override
public void stop() throws Exception {
if (server!=null && server.isServing()){
setStatus(ServerStatus.STOPING);
server.stop();
}
}
@Override
public void restart() throws Exception {
stop();
start();
}
@Override
public void configure() throws Exception {
// TODO Auto-generated method stub
}
@Override
public ServerStatus getStatus() throws Exception {
return status;
}
private void setStatus(ServerStatus stat){
status=stat;
status.updateTime();
}
@Override
public String getName() {
return SERVER_NAME;
}
@Override
public String getVersion() {
return SERVER_VERSION;
}
}
| apache-2.0 |
alancnet/artifactory | backend/core/src/main/java/org/artifactory/search/property/PropertySearcher.java | 6952 | /*
* Artifactory is a binaries repository manager.
* Copyright (C) 2012 JFrog Ltd.
*
* Artifactory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artifactory is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Artifactory. If not, see <http://www.gnu.org/licenses/>.
*/
package org.artifactory.search.property;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.artifactory.api.search.ItemSearchResults;
import org.artifactory.api.search.property.PropertySearchControls;
import org.artifactory.api.search.property.PropertySearchResult;
import org.artifactory.fs.ItemInfo;
import org.artifactory.sapi.search.VfsComparatorType;
import org.artifactory.sapi.search.VfsQuery;
import org.artifactory.sapi.search.VfsQueryResult;
import org.artifactory.sapi.search.VfsQueryResultType;
import org.artifactory.sapi.search.VfsQueryRow;
import org.artifactory.search.SearcherBase;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* @author Noam Tenne
*/
public class PropertySearcher extends SearcherBase<PropertySearchControls, PropertySearchResult> {
@Override
public ItemSearchResults<PropertySearchResult> doSearch(PropertySearchControls controls) {
LinkedHashSet<PropertySearchResult> globalResults = Sets.newLinkedHashSet();
// TODO: [by FSI] Create a real full DB query aggregating properties conditions
// Get all open property keys and search through them
Set<String> openPropertyKeys = controls.getPropertyKeysByOpenness(PropertySearchControls.OPEN);
long totalResultCount = executeOpenPropSearch(controls, openPropertyKeys, globalResults);
// Get all closed property keys and search through them
Set<String> closedPropertyKeys = controls.getPropertyKeysByOpenness(PropertySearchControls.CLOSED);
totalResultCount += executeClosedPropSearch(controls, closedPropertyKeys, globalResults);
//Return global results list
return new ItemSearchResults<>(new ArrayList<>(globalResults), totalResultCount);
}
/**
* Searches and aggregates results of open properties
*
* @param openPropertyKeys Keys to search through
*/
private long executeOpenPropSearch(PropertySearchControls controls,
Set<String> openPropertyKeys,
Set<PropertySearchResult> globalResults) {
if (openPropertyKeys.isEmpty()) {
return 0;
}
VfsQuery repoQuery = createQuery(controls).expectedResult(VfsQueryResultType.ANY_ITEM);
for (String key : openPropertyKeys) {
Set<String> values = controls.get(key);
for (String value : values) {
repoQuery.prop(key).val(value);
}
}
VfsQueryResult queryResult = repoQuery.execute(getLimit(controls));
return processResults(controls, queryResult, globalResults);
}
/**
* Searches and aggregates results of closed properties
*
* @param closedPropertyKeys Keys to search through
*/
@SuppressWarnings({"WhileLoopReplaceableByForEach"})
private long executeClosedPropSearch(PropertySearchControls controls,
Set<String> closedPropertyKeys,
Set<PropertySearchResult> globalResults) {
if (closedPropertyKeys.isEmpty()) {
return 0;
}
VfsQuery repoQuery = createQuery(controls).expectedResult(VfsQueryResultType.ANY_ITEM);
// TODO: Should support any boolean
for (String key : closedPropertyKeys) {
Set<String> values = controls.get(key);
for (String value : values) {
repoQuery.prop(key).comp(VfsComparatorType.EQUAL).val(value);
}
}
VfsQueryResult queryResult = repoQuery.execute(getLimit(controls));
return processResults(controls, queryResult, globalResults);
}
/**
* Processes, filters and aggregates query results into the global results list The filtering creates an AND like
* action. The first batch of results for the session automatically gets put in the global results list. Any batch
* of results after that is compared with the global list. If the new batch of results contains a result that does
* not exist in the global list, we discard it (Means the result does not fall under both searches, thus failing the
* AND requirement
*
* @param queryResult Result object
*/
private long processResults(PropertySearchControls controls, VfsQueryResult queryResult,
Set<PropertySearchResult> globalResults) {
/**
* If the global results is empty (either first query made, or there were no results from queries executed up
* until now
*/
boolean noGlobalResults = globalResults.isEmpty();
int limit = getLimit(controls);
long resultCount = 0L;
List<PropertySearchResult> currentSearchResults = Lists.newArrayList();
for (VfsQueryRow row : queryResult.getAllRows()) {
if (globalResults.size() >= limit) {
break;
}
ItemInfo item = row.getItem();
if (!isResultAcceptable(item.getRepoPath())) {
continue;
}
PropertySearchResult searchResult = new PropertySearchResult(item);
//Make sure that we don't get any double results
if (!currentSearchResults.contains(searchResult)) {
resultCount++;
currentSearchResults.add(searchResult);
}
}
/**
* If the global results list is empty, simply add all our results to set it as a comparison standard for the
* next set of results
*/
if (noGlobalResults) {
globalResults.addAll(currentSearchResults);
} else {
//Create a copy of the global results so we can iterate and remove at the same time
ArrayList<PropertySearchResult> globalCopy = new ArrayList<>(globalResults);
for (PropertySearchResult globalResult : globalCopy) {
//If the received results do not exist in the global results, discard them
if (!currentSearchResults.contains(globalResult)) {
globalResults.remove(globalResult);
resultCount--;
}
}
}
return resultCount;
}
} | apache-2.0 |
NCTUGDC/HearthStone | HearthStone/HearthStone.Library/CommunicationInfrastructure/Response/Handlers/PlayerResponseHandlers/Fetch/FetchAllDecksResponseHandler.cs | 2303 | using HearthStone.Protocol;
using HearthStone.Protocol.Communication.FetchDataCodes;
using HearthStone.Protocol.Communication.FetchDataResponseParameters.Player;
using System.Collections.Generic;
namespace HearthStone.Library.CommunicationInfrastructure.Response.Handlers.PlayerResponseHandlers.Fetch
{
class FetchAllDecksResponseHandler : FetchDataResponseHandler<Player, PlayerFetchDataCode>
{
public FetchAllDecksResponseHandler(Player subject) : base(subject)
{
}
public override bool CheckError(Dictionary<byte, object> parameters, ReturnCode returnCode, string operationMessage, out string errorMessage)
{
switch (returnCode)
{
case ReturnCode.Correct:
{
if (parameters.Count != 3)
{
errorMessage = $"Parameter Error, Parameter Count: {parameters.Count}";
return false;
}
else
{
errorMessage = "";
return true;
}
}
default:
{
errorMessage = "Unknown Error";
return false;
}
}
}
public override bool Handle(PlayerFetchDataCode fetchCode, ReturnCode returnCode, string operationMessage, Dictionary<byte, object> parameters, out string errorMessage)
{
if (base.Handle(fetchCode, returnCode, operationMessage, parameters, out errorMessage))
{
int deckID = (int)parameters[(byte)FetchAllDecksResponseParameterCode.DeckID];
string deckName = (string)parameters[(byte)FetchAllDecksResponseParameterCode.DeckName];
int maxCardCount = (int)parameters[(byte)FetchAllDecksResponseParameterCode.MaxCardCount];
subject.LoadDeck(new Deck(deckID, deckName, maxCardCount));
subject.OperationManager.FetchDataBroker.FetchAllDeckCards(deckID);
return true;
}
else
{
return false;
}
}
}
}
| apache-2.0 |
oudalab/phyllo | phyllo/extractors/marulloDB.py | 3191 | import sqlite3
import urllib
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup, NavigableString
from phyllo.phyllo_logger import logger
import nltk
from itertools import cycle
nltk.download('punkt')
from nltk import sent_tokenize
def parseRes2(soup, title, url, cur, author, date, collectiontitle):
chapter = '-'
[e.extract() for e in soup.find_all('br')]
inv = ['i', 'u']
get = strip_tags(soup, inv)
getp = get.find_all('p')[:-1]
for p in getp:
# make sure it's not a paragraph without the main text
i = 1
try:
if p['class'][0].lower() in ['border', 'pagehead', 'shortborder', 'smallboarder', 'margin',
'internal_navigation']: # these are not part of the main t
continue
except:
pass
sen=p.text
sen=sen.strip()
if sen.startswith('Epigrammata'):
chapter=sen
else:
s1=sen.split('\n')
s2=[]
j=0
for s in s1:
if j + 1 <= len(s1) - 1:
s = s1[j].strip() + ' ' + s1[j + 1].strip()
j += 2
s2.append(s)
i=1
for s in s2:
sentn=s
num=i
cur.execute("INSERT INTO texts VALUES (?,?,?,?,?,?,?, ?, ?, ?, ?)",
(None, collectiontitle, title, 'Latin', author, date, chapter,
num, sentn, url, 'prose'))
i+=1
def strip_tags(soup, invalid_tags):
for tag in soup.findAll(True):
if tag.name in invalid_tags:
s = ""
for c in tag.contents:
if not isinstance(c, NavigableString):
c = strip_tags(str(c), invalid_tags)
s += str(c)
tag.replaceWith(s)
return soup
def main():
# get proper URLs
siteURL = 'http://www.thelatinlibrary.com'
biggsURL = 'http://www.thelatinlibrary.com/marullo.html'
biggsOPEN = urllib.request.urlopen(biggsURL)
biggsSOUP = BeautifulSoup(biggsOPEN, 'html5lib')
textsURL = []
# remove some unnecessary urls
while ("http://www.thelatinlibrary.com/index.html" in textsURL):
textsURL.remove("http://www.thelatinlibrary.com/index.html")
textsURL.remove("http://www.thelatinlibrary.com/classics.html")
textsURL.remove("http://www.thelatinlibrary.com/neo.html")
logger.info("\n".join(textsURL))
title='EPIGRAMMATA SELECTA'
author = 'Michele Marullo'
author = author.strip()
collectiontitle='MICHELE MARULLO'
date = '1450-1500'
with sqlite3.connect('texts.db') as db:
c = db.cursor()
c.execute(
'CREATE TABLE IF NOT EXISTS texts (id INTEGER PRIMARY KEY, title TEXT, book TEXT,'
' language TEXT, author TEXT, date TEXT, chapter TEXT, verse TEXT, passage TEXT,'
' link TEXT, documentType TEXT)')
c.execute("DELETE FROM texts WHERE author = 'Michele Marullo'")
parseRes2(biggsSOUP, title, biggsURL, c, author, date, collectiontitle)
if __name__ == '__main__':
main()
| apache-2.0 |
bseber/fubatra-archiv | src/main/java/de/fubatra/archiv/shared/domain/UserInfoProxy.java | 1016 | package de.fubatra.archiv.shared.domain;
import com.google.gwt.view.client.ProvidesKey;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
import de.fubatra.archiv.server.domain.UserInfo;
import de.fubatra.archiv.server.ioc.ObjectifyEntityLocator;
@ProxyFor(value = UserInfo.class, locator = ObjectifyEntityLocator.class)
public interface UserInfoProxy extends EntityProxy {
public class KeyProvider implements ProvidesKey<UserInfoProxy> {
@Override
public Object getKey(UserInfoProxy item) {
return item.getId();
}
}
Long getId();
String getEmail();
String getGoogleUserId();
void setGoogleUserId(String userId);
String getName();
void setName(String name);
String getGooglePlusUrl();
void setGooglePlusUrl(String url);
String getFacebookUrl();
void setFacebookUrl(String url);
BlobImageProxy getPicture();
void setPicture(BlobImageProxy picture);
boolean isProfileInitiated();
}
| apache-2.0 |
Over-enthusiastic/hostboot | src/include/usr/scom/scomreasoncodes.H | 3787 | /* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/usr/scom/scomreasoncodes.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __SCOM_REASONCODES_H
#define __SCOM_REASONCODES_H
#include <hbotcompid.H>
namespace SCOM
{
enum scomModuleId
{
SCOM_PERFORM_OP = 0x00,
SCOM_TRANSLATE = 0x01,
SCOM_PERFORM_TRANSLATE = 0x02,
SCOM_FIND_PARENT_TARGET = 0x03,
SCOM_CHECK_INDIRECT_AND_DO_SCOM = 0x04,
SCOM_TRANSLATE_P9 = 0x05,
SCOM_DO_FORM_1_INDIRECT_SCOM = 0x06,
SCOM_HANDLE_SPECIAL_WAKEUP = 0x07,
SCOM_TRANSLATE_CENTAUR = 0x08,
};
enum scomReasonCode
{
SCOM_INVALID_ADDR = SCOM_COMP_ID | 0x01,
SCOM_NO_MATCHING_PARENT = SCOM_COMP_ID | 0x02,
SCOM_TRANS_INVALID_TYPE = SCOM_COMP_ID | 0x03,
SCOM_TRANS_UNSUPPORTED = SCOM_COMP_ID | 0x04,
SCOM_INDIRECT_READ_FAIL = SCOM_COMP_ID | 0x05,
SCOM_INDIRECT_READ_TIMEOUT = SCOM_COMP_ID | 0x06,
SCOM_INDIRECT_WRITE_FAIL = SCOM_COMP_ID | 0x07,
SCOM_INDIRECT_WRITE_TIMEOUT = SCOM_COMP_ID | 0x08,
SCOM_P9_TRANS_INVALID_TYPE = SCOM_COMP_ID | 0x09,
SCOM_INVALID_TRANSLATION = SCOM_COMP_ID | 0x0A,
SCOM_TRANS_CANT_FIND_PARENT = SCOM_COMP_ID | 0x0B,
SCOM_TARGET_ADDR_MISMATCH = SCOM_COMP_ID | 0x0C,
SCOM_ISCHIPUNITSCOM_INVALID = SCOM_COMP_ID | 0x0D,
SCOM_INVALID_FORM = SCOM_COMP_ID | 0x0E,
SCOM_FORM_1_INVALID_DATA = SCOM_COMP_ID | 0x0F,
SCOM_FORM_1_READ_REQUEST = SCOM_COMP_ID | 0x10,
SCOM_RUNTIME_WAKEUP_ERR = SCOM_COMP_ID | 0x11,
SCOM_RUNTIME_INTERFACE_ERR = SCOM_COMP_ID | 0x12,
SCOM_RUNTIME_SPCWKUP_COUNT_ERR = SCOM_COMP_ID | 0x13,
SCOM_CEN_TRANS_INVALID_TYPE = SCOM_COMP_ID | 0x14,
};
enum UserDetailsTypes
{
SCOM_UDT_PIB = 0x1
};
};
#endif
| apache-2.0 |
shaftoe/home-assistant | homeassistant/components/media_player/soundtouch.py | 12272 | """
Support for interface with a Bose Soundtouch.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.soundtouch/
"""
import logging
from os import path
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.media_player import (
SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK,
SUPPORT_TURN_OFF, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_STEP,
SUPPORT_VOLUME_SET, SUPPORT_TURN_ON, SUPPORT_PLAY, MediaPlayerDevice,
PLATFORM_SCHEMA)
from homeassistant.config import load_yaml_config_file
from homeassistant.const import (CONF_HOST, CONF_NAME, STATE_OFF, CONF_PORT,
STATE_PAUSED, STATE_PLAYING,
STATE_UNAVAILABLE)
REQUIREMENTS = ['libsoundtouch==0.3.0']
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'media_player'
SERVICE_PLAY_EVERYWHERE = 'soundtouch_play_everywhere'
SERVICE_CREATE_ZONE = 'soundtouch_create_zone'
SERVICE_ADD_ZONE_SLAVE = 'soundtouch_add_zone_slave'
SERVICE_REMOVE_ZONE_SLAVE = 'soundtouch_remove_zone_slave'
MAP_STATUS = {
"PLAY_STATE": STATE_PLAYING,
"BUFFERING_STATE": STATE_PLAYING,
"PAUSE_STATE": STATE_PAUSED,
"STOP_STATE": STATE_OFF
}
DATA_SOUNDTOUCH = "soundtouch"
SOUNDTOUCH_PLAY_EVERYWHERE = vol.Schema({
vol.Required('master'): cv.entity_id
})
SOUNDTOUCH_CREATE_ZONE_SCHEMA = vol.Schema({
vol.Required('master'): cv.entity_id,
vol.Required('slaves'): cv.entity_ids
})
SOUNDTOUCH_ADD_ZONE_SCHEMA = vol.Schema({
vol.Required('master'): cv.entity_id,
vol.Required('slaves'): cv.entity_ids
})
SOUNDTOUCH_REMOVE_ZONE_SCHEMA = vol.Schema({
vol.Required('master'): cv.entity_id,
vol.Required('slaves'): cv.entity_ids
})
DEFAULT_NAME = 'Bose Soundtouch'
DEFAULT_PORT = 8090
SUPPORT_SOUNDTOUCH = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \
SUPPORT_VOLUME_MUTE | SUPPORT_PREVIOUS_TRACK | \
SUPPORT_NEXT_TRACK | SUPPORT_TURN_OFF | \
SUPPORT_VOLUME_SET | SUPPORT_TURN_ON | SUPPORT_PLAY
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Bose Soundtouch platform."""
if DATA_SOUNDTOUCH not in hass.data:
hass.data[DATA_SOUNDTOUCH] = []
if discovery_info:
host = discovery_info['host']
port = int(discovery_info['port'])
# if device already exists by config
if host in [device.config['host'] for device in
hass.data[DATA_SOUNDTOUCH]]:
return
remote_config = {
'id': 'ha.component.soundtouch',
'host': host,
'port': port
}
soundtouch_device = SoundTouchDevice(None, remote_config)
hass.data[DATA_SOUNDTOUCH].append(soundtouch_device)
add_devices([soundtouch_device])
else:
name = config.get(CONF_NAME)
remote_config = {
'id': 'ha.component.soundtouch',
'port': config.get(CONF_PORT),
'host': config.get(CONF_HOST)
}
soundtouch_device = SoundTouchDevice(name, remote_config)
hass.data[DATA_SOUNDTOUCH].append(soundtouch_device)
add_devices([soundtouch_device])
descriptions = load_yaml_config_file(
path.join(path.dirname(__file__), 'services.yaml'))
def service_handle(service):
"""Handle the applying of a service."""
master_device_id = service.data.get('master')
slaves_ids = service.data.get('slaves')
slaves = []
if slaves_ids:
slaves = [device for device in hass.data[DATA_SOUNDTOUCH] if
device.entity_id in slaves_ids]
master = next([device for device in hass.data[DATA_SOUNDTOUCH] if
device.entity_id == master_device_id].__iter__(), None)
if master is None:
_LOGGER.warning("Unable to find master with entity_id: %s",
str(master_device_id))
return
if service.service == SERVICE_PLAY_EVERYWHERE:
slaves = [d for d in hass.data[DATA_SOUNDTOUCH] if
d.entity_id != master_device_id]
master.create_zone(slaves)
elif service.service == SERVICE_CREATE_ZONE:
master.create_zone(slaves)
elif service.service == SERVICE_REMOVE_ZONE_SLAVE:
master.remove_zone_slave(slaves)
elif service.service == SERVICE_ADD_ZONE_SLAVE:
master.add_zone_slave(slaves)
hass.services.register(DOMAIN, SERVICE_PLAY_EVERYWHERE,
service_handle,
descriptions.get(SERVICE_PLAY_EVERYWHERE),
schema=SOUNDTOUCH_PLAY_EVERYWHERE)
hass.services.register(DOMAIN, SERVICE_CREATE_ZONE,
service_handle,
descriptions.get(SERVICE_CREATE_ZONE),
schema=SOUNDTOUCH_CREATE_ZONE_SCHEMA)
hass.services.register(DOMAIN, SERVICE_REMOVE_ZONE_SLAVE,
service_handle,
descriptions.get(SERVICE_REMOVE_ZONE_SLAVE),
schema=SOUNDTOUCH_REMOVE_ZONE_SCHEMA)
hass.services.register(DOMAIN, SERVICE_ADD_ZONE_SLAVE,
service_handle,
descriptions.get(SERVICE_ADD_ZONE_SLAVE),
schema=SOUNDTOUCH_ADD_ZONE_SCHEMA)
class SoundTouchDevice(MediaPlayerDevice):
"""Representation of a SoundTouch Bose device."""
def __init__(self, name, config):
"""Create Soundtouch Entity."""
from libsoundtouch import soundtouch_device
self._device = soundtouch_device(config['host'], config['port'])
if name is None:
self._name = self._device.config.name
else:
self._name = name
self._status = self._device.status()
self._volume = self._device.volume()
self._config = config
@property
def config(self):
"""Return specific soundtouch configuration."""
return self._config
@property
def device(self):
"""Return Soundtouch device."""
return self._device
def update(self):
"""Retrieve the latest data."""
self._status = self._device.status()
self._volume = self._device.volume()
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
return self._volume.actual / 100
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def state(self):
"""Return the state of the device."""
if self._status.source == 'STANDBY':
return STATE_OFF
else:
return MAP_STATUS.get(self._status.play_status, STATE_UNAVAILABLE)
@property
def is_volume_muted(self):
"""Boolean if volume is currently muted."""
return self._volume.muted
@property
def supported_features(self):
"""Flag media player features that are supported."""
return SUPPORT_SOUNDTOUCH
def turn_off(self):
"""Turn off media player."""
self._device.power_off()
self._status = self._device.status()
def turn_on(self):
"""Turn on media player."""
self._device.power_on()
self._status = self._device.status()
def volume_up(self):
"""Volume up the media player."""
self._device.volume_up()
self._volume = self._device.volume()
def volume_down(self):
"""Volume down media player."""
self._device.volume_down()
self._volume = self._device.volume()
def set_volume_level(self, volume):
"""Set volume level, range 0..1."""
self._device.set_volume(int(volume * 100))
self._volume = self._device.volume()
def mute_volume(self, mute):
"""Send mute command."""
self._device.mute()
self._volume = self._device.volume()
def media_play_pause(self):
"""Simulate play pause media player."""
self._device.play_pause()
self._status = self._device.status()
def media_play(self):
"""Send play command."""
self._device.play()
self._status = self._device.status()
def media_pause(self):
"""Send media pause command to media player."""
self._device.pause()
self._status = self._device.status()
def media_next_track(self):
"""Send next track command."""
self._device.next_track()
self._status = self._device.status()
def media_previous_track(self):
"""Send the previous track command."""
self._device.previous_track()
self._status = self._device.status()
@property
def media_image_url(self):
"""Image url of current playing media."""
return self._status.image
@property
def media_title(self):
"""Title of current playing media."""
if self._status.station_name is not None:
return self._status.station_name
elif self._status.artist is not None:
return self._status.artist + " - " + self._status.track
else:
return None
@property
def media_duration(self):
"""Duration of current playing media in seconds."""
return self._status.duration
@property
def media_artist(self):
"""Artist of current playing media."""
return self._status.artist
@property
def media_track(self):
"""Artist of current playing media."""
return self._status.track
@property
def media_album_name(self):
"""Album name of current playing media."""
return self._status.album
def play_media(self, media_type, media_id, **kwargs):
"""Play a piece of media."""
_LOGGER.info("Starting media with media_id:" + str(media_id))
presets = self._device.presets()
preset = next([preset for preset in presets if
preset.preset_id == str(media_id)].__iter__(), None)
if preset is not None:
_LOGGER.info("Playing preset: " + preset.name)
self._device.select_preset(preset)
else:
_LOGGER.warning("Unable to find preset with id " + str(media_id))
def create_zone(self, slaves):
"""
Create a zone (multi-room) and play on selected devices.
:param slaves: slaves on which to play
"""
if not slaves:
_LOGGER.warning("Unable to create zone without slaves")
else:
_LOGGER.info(
"Creating zone with master " + str(self.device.config.name))
self.device.create_zone([slave.device for slave in slaves])
def remove_zone_slave(self, slaves):
"""
Remove slave(s) from and existing zone (multi-room).
Zone must already exist and slaves array can not be empty.
Note: If removing last slave, the zone will be deleted and you'll have
to create a new one. You will not be able to add a new slave anymore
:param slaves: slaves to remove from the zone
"""
if not slaves:
_LOGGER.warning("Unable to find slaves to remove")
else:
_LOGGER.info("Removing slaves from zone with master " +
str(self.device.config.name))
self.device.remove_zone_slave([slave.device for slave in slaves])
def add_zone_slave(self, slaves):
"""
Add slave(s) to and existing zone (multi-room).
Zone must already exist and slaves array can not be empty.
:param slaves:slaves to add
"""
if not slaves:
_LOGGER.warning("Unable to find slaves to add")
else:
_LOGGER.info(
"Adding slaves to zone with master " + str(
self.device.config.name))
self.device.add_zone_slave([slave.device for slave in slaves])
| apache-2.0 |
OpenVnmrJ/OpenVnmrJ | src/vnmrj/src/vnmr/vplaf/jtattoo/BaseTableUI.java | 976 | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
/*
* Copyright 2005 MH-Software-Entwicklung. All rights reserved.
* Use is subject to license terms.
*/
package vnmr.vplaf.jtattoo;
import java.awt.FontMetrics;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicTableUI;
/**
* @author Michael Hagen
*/
public class BaseTableUI extends BasicTableUI {
public static ComponentUI createUI(JComponent c) {
return new BaseTableUI();
}
public void installDefaults() {
super.installDefaults();
// Setup the rowheight. The font may change if UI switches
FontMetrics fm = table.getFontMetrics(table.getFont());
table.setRowHeight(fm.getHeight() + (fm.getHeight() / 4));
}
}
| apache-2.0 |
mercycorps/TolaActivity | indicators/migrations/0062_merge_20190614_1923.py | 363 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-06-15 02:23
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('indicators', '0061_auto_20190614_1201'),
('indicators', '0061_add_deleted_to_levelorder_uniqueness'),
]
operations = [
]
| apache-2.0 |
FasterXML/jackson-databind | src/test/java/com/fasterxml/jackson/databind/util/TestObjectBuffer.java | 2130 | package com.fasterxml.jackson.databind.util;
import java.util.*;
import com.fasterxml.jackson.databind.BaseMapTest;
public class TestObjectBuffer
extends BaseMapTest
{
/**
* First a test that treats results as plain old Object[]
*/
public void testUntyped()
{
_testObjectBuffer(null);
}
public void testTyped()
{
_testObjectBuffer(Integer.class);
}
/*
/**********************************************************
/* Helper methods
/**********************************************************
*/
private void _testObjectBuffer(Class<?> clz)
{
int[] SIZES = new int[] {
3, 19, 99, 1007, 19999, 99001
};
// Let's loop separately for reused instance, new instance
for (int reuse = 0; reuse < 2; ++reuse) {
ObjectBuffer buf = (reuse == 0) ? null : new ObjectBuffer();
// then distinct sizes
for (int sizeIndex = 0; sizeIndex < SIZES.length; ++sizeIndex) {
int size = SIZES[sizeIndex];
Random r = new Random(size);
ObjectBuffer thisBuf = (buf == null) ? new ObjectBuffer() : buf;
Object[] chunk = thisBuf.resetAndStart();
int ix = 0;
for (int i = 0; i < size; ++i) {
if (ix >= chunk.length) {
chunk = thisBuf.appendCompletedChunk(chunk);
ix = 0;
}
chunk[ix++] = Integer.valueOf(r.nextInt());
}
Object[] result;
if (clz == null) {
result = thisBuf.completeAndClearBuffer(chunk, ix);
} else {
result = thisBuf.completeAndClearBuffer(chunk, ix, clz);
}
assertEquals(size, result.length);
r = new Random(size);
for (int i = 0; i < size; ++i) {
assertEquals(r.nextInt(), ((Integer) result[i]).intValue());
}
}
}
}
}
| apache-2.0 |
zhaoshiling1017/voyage | src/main/java/com/lenzhao/framework/connect/IRpcConnection.java | 857 | package com.lenzhao.framework.connect;
import com.lenzhao.framework.protocol.RpcRequest;
import com.lenzhao.framework.protocol.RpcResponse;
/**
*客户端连接
*/
public interface IRpcConnection {
/**
* 发送请求
* @param request
* @param async 标示是否异步发送请求
* @return
* @throws Throwable
*/
RpcResponse sendRequest(RpcRequest request, boolean async) throws Throwable;
/**
* 初始化连接
* @throws Throwable
*/
void open() throws Throwable;
/**
* 重新连接
* @throws Throwable
*/
void connect() throws Throwable;
/**
* 关闭连接
* @throws Throwable
*/
void close() throws Throwable;
/**
* 连接是否已经关闭
* @return
*/
boolean isClosed();
/**
* 心跳是否正常
* @return
*/
boolean isConnected();
}
| apache-2.0 |
SeeSharpSoft/intellij-csv-validator | src/test/java/net/seesharpsoft/intellij/plugins/csv/editor/table/swing/CsvTableEditorMouseListenerTest.java | 7473 | package net.seesharpsoft.intellij.plugins.csv.editor.table.swing;
import org.mockito.Mockito;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
public class CsvTableEditorMouseListenerTest extends CsvTableEditorSwingTestBase {
private static class MockResult<T> {
T result;
public MockResult(T initial) {
result = initial;
}
public T getResult() {
return result;
}
public void setResult(T myResult) {
result = myResult;
}
}
private void mockShowColumnPopupMenu(CsvTableEditorMouseListener spiedMouseListener, MockResult<Boolean> mockResult) {
Mockito.doAnswer(invocation -> {
assertSame(spiedMouseListener.getColumnPopupMenu(), invocation.getArgument(0));
assertSame(fileEditor.getTable().getTableHeader(), invocation.getArgument(1));
mockResult.setResult(true);
return null;
}).when(spiedMouseListener).showPopupMenu(Mockito.any(), Mockito.any(), Mockito.anyInt(), Mockito.anyInt());
}
private void mockShowRowPopupMenu(CsvTableEditorMouseListener spiedMouseListener, MockResult<Boolean> mockResult) {
Mockito.doAnswer(invocation -> {
assertSame(spiedMouseListener.getRowPopupMenu(), invocation.getArgument(0));
assertSame(fileEditor.getTable(), invocation.getArgument(1));
mockResult.setResult(true);
return null;
}).when(spiedMouseListener).showPopupMenu(Mockito.any(), Mockito.any(), Mockito.anyInt(), Mockito.anyInt());
}
public void testColumnPopupMenuPressed() {
MouseEvent mouseEvent = new MouseEvent(fileEditor.getTable().getTableHeader(), MouseEvent.MOUSE_PRESSED, JComponent.WHEN_FOCUSED,
0, 0, 0, 1, true);
CsvTableEditorMouseListener spiedMouseListener = Mockito.spy(fileEditor.tableEditorMouseListener);
final MockResult<Boolean> mockResult = new MockResult(false);
mockShowColumnPopupMenu(spiedMouseListener, mockResult);
spiedMouseListener.mousePressed(mouseEvent);
assertTrue(mockResult.getResult());
}
public void testRowPopupMenuPressed() {
MouseEvent mouseEvent = new MouseEvent(fileEditor.getTable(), MouseEvent.MOUSE_PRESSED, JComponent.WHEN_FOCUSED,
0, 0, 0, 1, true);
CsvTableEditorMouseListener spiedMouseListener = Mockito.spy(fileEditor.tableEditorMouseListener);
final MockResult<Boolean> mockResult = new MockResult(false);
mockShowRowPopupMenu(spiedMouseListener, mockResult);
spiedMouseListener.mousePressed(mouseEvent);
assertTrue(mockResult.getResult());
}
public void testColumnPopupMenuReleased() {
MouseEvent mouseEvent = new MouseEvent(fileEditor.getTable().getTableHeader(), MouseEvent.MOUSE_RELEASED, JComponent.WHEN_FOCUSED,
0, 0, 0, 1, true);
CsvTableEditorMouseListener spiedMouseListener = Mockito.spy(fileEditor.tableEditorMouseListener);
final MockResult<Boolean> mockResult = new MockResult(false);
mockShowColumnPopupMenu(spiedMouseListener, mockResult);
spiedMouseListener.mouseReleased(mouseEvent);
assertTrue(mockResult.getResult());
}
public void testRowPopupMenuReleased() {
MouseEvent mouseEvent = new MouseEvent(fileEditor.getTable(), MouseEvent.MOUSE_RELEASED, JComponent.WHEN_FOCUSED,
0, 0, 0, 1, true);
CsvTableEditorMouseListener spiedMouseListener = Mockito.spy(fileEditor.tableEditorMouseListener);
final MockResult<Boolean> mockResult = new MockResult(false);
mockShowRowPopupMenu(spiedMouseListener, mockResult);
spiedMouseListener.mouseReleased(mouseEvent);
assertTrue(mockResult.getResult());
}
public void testSelectNew() {
MouseEvent mouseEvent = new MouseEvent(fileEditor.getTable().getTableHeader(), MouseEvent.MOUSE_PRESSED, JComponent.WHEN_FOCUSED,
InputEvent.BUTTON1_MASK, 0, 0, 1, true);
CsvTableEditorMouseListener spiedMouseListener = Mockito.spy(fileEditor.tableEditorMouseListener);
final MockResult<Boolean> mockResult = new MockResult(false);
mockShowColumnPopupMenu(spiedMouseListener, mockResult);
JTable spiedTable = Mockito.spy(fileEditor.getTable());
CsvTableEditorSwing spiedTableEditorSwing = Mockito.spy(fileEditor);
Mockito.doReturn(spiedTable).when(spiedTableEditorSwing).getTable();
spiedMouseListener.csvTableEditor = spiedTableEditorSwing;
assertEquals(-1, spiedTable.getSelectedColumn());
Mockito.doReturn(0).when(spiedTable).columnAtPoint(Mockito.any());
spiedMouseListener.mousePressed(mouseEvent);
assertEquals(0, spiedTable.getSelectionModel().getMinSelectionIndex());
assertEquals(3, spiedTable.getSelectionModel().getMaxSelectionIndex());
assertEquals(0, spiedTable.getColumnModel().getSelectionModel().getMinSelectionIndex());
assertEquals(0, spiedTable.getColumnModel().getSelectionModel().getMaxSelectionIndex());
Mockito.doReturn(1).when(spiedTable).columnAtPoint(Mockito.any());
spiedMouseListener.mousePressed(mouseEvent);
assertEquals(0, spiedTable.getSelectionModel().getMinSelectionIndex());
assertEquals(3, spiedTable.getSelectionModel().getMaxSelectionIndex());
assertEquals(1, spiedTable.getColumnModel().getSelectionModel().getMinSelectionIndex());
assertEquals(1, spiedTable.getColumnModel().getSelectionModel().getMaxSelectionIndex());
}
public void testSelectAppend() {
MouseEvent mouseEvent = new MouseEvent(fileEditor.getTable().getTableHeader(), MouseEvent.MOUSE_PRESSED, JComponent.WHEN_FOCUSED,
InputEvent.BUTTON1_MASK | InputEvent.SHIFT_MASK, 0, 0, 1, true);
CsvTableEditorMouseListener spiedMouseListener = Mockito.spy(fileEditor.tableEditorMouseListener);
final MockResult<Boolean> mockResult = new MockResult(false);
mockShowColumnPopupMenu(spiedMouseListener, mockResult);
JTable spiedTable = Mockito.spy(fileEditor.getTable());
CsvTableEditorSwing spiedTableEditorSwing = Mockito.spy(fileEditor);
Mockito.doReturn(spiedTable).when(spiedTableEditorSwing).getTable();
spiedMouseListener.csvTableEditor = spiedTableEditorSwing;
assertEquals(-1, spiedTable.getSelectedColumn());
Mockito.doReturn(0).when(spiedTable).columnAtPoint(Mockito.any());
spiedMouseListener.mousePressed(mouseEvent);
assertEquals(0, spiedTable.getSelectionModel().getMinSelectionIndex());
assertEquals(3, spiedTable.getSelectionModel().getMaxSelectionIndex());
assertEquals(0, spiedTable.getColumnModel().getSelectionModel().getMinSelectionIndex());
assertEquals(0, spiedTable.getColumnModel().getSelectionModel().getMaxSelectionIndex());
Mockito.doReturn(1).when(spiedTable).columnAtPoint(Mockito.any());
spiedMouseListener.mousePressed(mouseEvent);
assertEquals(0, spiedTable.getSelectionModel().getMinSelectionIndex());
assertEquals(3, spiedTable.getSelectionModel().getMaxSelectionIndex());
assertEquals(0, spiedTable.getColumnModel().getSelectionModel().getMinSelectionIndex());
assertEquals(1, spiedTable.getColumnModel().getSelectionModel().getMaxSelectionIndex());
}
}
| apache-2.0 |
ctrlzhang/algorithm | leetcode2/Heap/heap.java | 2592 | package cn.webank.ctrl.learn.lecture.lecture.list;
import java.util.ArrayList;
import java.util.List;
/**
* @author ctrlzhang on 2018/5/16.
*/
public class Heap {
public List<Integer> arr = new ArrayList<>();
private int capacity = 0;
Heap(List<Integer> input) {
this.arr = input;
this.capacity = input.size();
}
public void heapfy() {
int n = arr.size();
for(int i = (n - 1) / 2; i >= 0; i--) {
adjust(i);
}
}
public void adjust(int idx) {
int left = idx * 2 + 1;
int right = idx * 2 + 2;
int end = capacity - 1;
int tmp = idx;
if (left < end) {
if (arr.get(tmp) > arr.get(left)) {
tmp = left;
}
}
if (right < end) {
if (arr.get(tmp) > arr.get(right)) {
tmp = right;
}
}
if (tmp != idx) {
swap(arr, tmp, idx);
adjust(tmp);
}
}
public int pop() {
if (capacity <= 0) return -1;
int ans = arr.get(0);
swap(arr, 0, capacity - 1);
arr.remove(capacity - 1);
capacity--;
adjust(0);
return ans;
}
public void push(int d) {
arr.add(d);
capacity = arr.size();
int idx = capacity - 1;
int parent = (idx - 1) / 2;
while (parent >= 0) {
if (arr.get(idx) < arr.get(parent)) {
swap(arr, idx, parent);
idx = parent;
parent = (idx - 1) / 2;
} else {
break;
}
}
}
void swap(List<Integer> data, int l, int r) {
int tmp = data.get(l);
data.set(l, data.get(r));
data.set(r, tmp);
}
void output() {
for (int i = 0; i < arr.size(); i++) {
System.out.println(this.arr.get(i));
}
}
public static void main(String[] args) {
List<Integer> input = new ArrayList<>();
input.add(10);
input.add(5);
input.add(25);
input.add(3);
input.add(99);
Heap myHeap = new Heap(input);
myHeap.heapfy();
myHeap.output();
System.out.println("==========");
myHeap.push(1);
myHeap.output();
System.out.println("==========");
int k = 0;
while (k < 3) {
int val = myHeap.pop();
System.out.println("pos ans=" + val);
k++;
}
System.out.println("==========");
myHeap.output();
}
}
| apache-2.0 |
alexlau811/azure-xplat-cli | test/recordings/cli.vm.image-tests/suite.cli.vm.image-tests.nock.js | 710 | // This file has been autogenerated.
var profile = require('../../../lib/util/profile');
exports.getMockedProfile = function () {
var newProfile = new profile.Profile();
newProfile.addSubscription(new profile.Subscription({
id: 'bfb5e0bf-124b-4d0c-9352-7c0a9f4d9948',
managementCertificate: {
key: 'mockedKey',
cert: 'mockedCert'
},
name: 'CollaberaInteropTest',
registeredProviders: [],
isDefault: true
}, newProfile.environments['AzureCloud']));
return newProfile;
};
exports.setEnvironment = function() {
process.env['AZURE_VM_TEST_LOCATION'] = 'West US';
};
exports.scopes = [];
exports.randomTestIdsGenerated = function() { return ['clitestvm2811'];}; | apache-2.0 |
Dennis-Koch/ambeth | ambeth/Ambeth.IoC/ambeth/ioc/config/BeanInstanceConfiguration.cs | 1220 | using System;
using De.Osthus.Ambeth.Log;
using De.Osthus.Ambeth.Util;
using De.Osthus.Ambeth.Config;
namespace De.Osthus.Ambeth.Ioc.Config
{
public class BeanInstanceConfiguration : AbstractBeanConfiguration
{
protected Object bean;
protected bool withLifecycle;
public BeanInstanceConfiguration(Object bean, String beanName, bool withLifecycle, IProperties props)
: base(beanName, props)
{
ParamChecker.AssertParamNotNull(bean, "bean");
this.bean = bean;
this.withLifecycle = withLifecycle;
if (withLifecycle && declarationStackTrace != null && bean is IDeclarationStackTraceAware)
{
((IDeclarationStackTraceAware) bean).DeclarationStackTrace = declarationStackTrace;
}
}
public override Type GetBeanType()
{
return bean.GetType();
}
public override Object GetInstance()
{
return bean;
}
public override Object GetInstance(Type instanceType)
{
return bean;
}
public override bool IsWithLifecycle()
{
return withLifecycle;
}
}
} | apache-2.0 |
cloudfoundry/cf-java-client | cloudfoundry-client-reactor/src/test/java/org/cloudfoundry/reactor/uaa/tokens/ReactorTokensTest.java | 18210 | /*
* Copyright 2013-2021 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.cloudfoundry.reactor.uaa.tokens;
import org.cloudfoundry.reactor.InteractionContext;
import org.cloudfoundry.reactor.TestRequest;
import org.cloudfoundry.reactor.TestResponse;
import org.cloudfoundry.reactor.uaa.AbstractUaaApiTest;
import org.cloudfoundry.uaa.tokens.CheckTokenRequest;
import org.cloudfoundry.uaa.tokens.CheckTokenResponse;
import org.cloudfoundry.uaa.tokens.GetTokenByAuthorizationCodeRequest;
import org.cloudfoundry.uaa.tokens.GetTokenByAuthorizationCodeResponse;
import org.cloudfoundry.uaa.tokens.GetTokenByClientCredentialsRequest;
import org.cloudfoundry.uaa.tokens.GetTokenByClientCredentialsResponse;
import org.cloudfoundry.uaa.tokens.GetTokenByOneTimePasscodeRequest;
import org.cloudfoundry.uaa.tokens.GetTokenByOneTimePasscodeResponse;
import org.cloudfoundry.uaa.tokens.GetTokenByOpenIdRequest;
import org.cloudfoundry.uaa.tokens.GetTokenByOpenIdResponse;
import org.cloudfoundry.uaa.tokens.GetTokenByPasswordRequest;
import org.cloudfoundry.uaa.tokens.GetTokenByPasswordResponse;
import org.cloudfoundry.uaa.tokens.GetTokenKeyRequest;
import org.cloudfoundry.uaa.tokens.GetTokenKeyResponse;
import org.cloudfoundry.uaa.tokens.KeyType;
import org.cloudfoundry.uaa.tokens.ListTokenKeysRequest;
import org.cloudfoundry.uaa.tokens.ListTokenKeysResponse;
import org.cloudfoundry.uaa.tokens.RefreshTokenRequest;
import org.cloudfoundry.uaa.tokens.RefreshTokenResponse;
import org.cloudfoundry.uaa.tokens.TokenFormat;
import org.cloudfoundry.uaa.tokens.TokenKey;
import org.junit.Test;
import reactor.test.StepVerifier;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpMethod.POST;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
public final class ReactorTokensTest extends AbstractUaaApiTest {
private final ReactorTokens tokens = new ReactorTokens(CONNECTION_CONTEXT, this.root, TOKEN_PROVIDER, Collections.emptyMap());
@Test
public void check() {
mockRequest(InteractionContext.builder()
.request(TestRequest.builder()
.method(POST).path("/check_token?scopes=password.write%2Cscim.userids&token=f9f2f98d88e04ff7bb1f69041d3c0346")
.header("Authorization", "Basic YXBwOmFwcGNsaWVudHNlY3JldA==")
.build())
.response(TestResponse.builder()
.status(OK)
.payload("fixtures/uaa/check/POST_response.json")
.build())
.build());
this.tokens
.check(CheckTokenRequest.builder()
.token("f9f2f98d88e04ff7bb1f69041d3c0346")
.scope("password.write")
.scope("scim.userids")
.clientId("app")
.clientSecret("appclientsecret")
.build())
.as(StepVerifier::create)
.expectNext(CheckTokenResponse.builder()
.userId("ae77988e-1b25-4e02-87f2-81f98293a356")
.userName("marissa")
.email("marissa@test.org")
.clientId("app")
.expirationTime(1462015244L)
.scopes(Arrays.asList("scim.userids", "openid", "cloud_controller.read", "password.write", "cloud_controller.write"))
.jwtId("f9f2f98d88e04ff7bb1f69041d3c0346")
.audiences(Arrays.asList("app", "scim", "openid", "cloud_controller", "password"))
.subject("ae77988e-1b25-4e02-87f2-81f98293a356")
.issuer("http://localhost:8080/uaa/oauth/token")
.issuedAt(1461972044L)
.cid("app")
.grantType("password")
.authorizedParty("app")
.authorizationTime(1461972044L)
.zoneId("uaa")
.revocationSignature("4e89e4da")
.origin("uaa")
.revocable(true)
.build())
.expectComplete()
.verify(Duration.ofSeconds(5));
}
@Test
public void getKey() {
mockRequest(InteractionContext.builder()
.request(TestRequest.builder()
.method(GET).path("/token_key")
.build())
.response(TestResponse.builder()
.status(OK)
.payload("fixtures/uaa/token_key/GET_response.json")
.build())
.build());
this.tokens
.getKey(GetTokenKeyRequest.builder()
.build())
.as(StepVerifier::create)
.expectNext(GetTokenKeyResponse.builder()
.id("testKey")
.algorithm("SHA256withRSA")
.value("-----BEGIN PUBLIC KEY-----\n" +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO\n" +
"rn2dVQ3vfBJqcDuFUK03d+1PZGbVlNCqnkpIJ8syFppW8ljnWweP7+LiWpRoz0I7\n" +
"fYb3d8TjhV86Y997Fl4DBrxgM6KTJOuE/uxnoDhZQ14LgOU2ckXjOzOdTsnGMKQB\n" +
"LCl0vpcXBtFLMaSbpv1ozi8h7DJyVZ6EnFQZUWGdgTMhDrmqevfx95U/16c5WBDO\n" +
"kqwIn7Glry9n9Suxygbf8g5AzpWcusZgDLIIZ7JTUldBb8qU2a0Dl4mvLZOn4wPo\n" +
"jfj9Cw2QICsc5+Pwf21fP+hzf+1WSRHbnYv8uanRO0gZ8ekGaghM/2H6gqJbo2nI\n" +
"JwIDAQAB\n" +
"-----END PUBLIC KEY-----")
.keyType(KeyType.RSA)
.use("sig")
.n("ANJufZdrvYg5zG61x36pDq59nVUN73wSanA7hVCtN3ftT2Rm1ZTQqp5KSCfLMhaaVvJY51sHj" +
"+/i4lqUaM9CO32G93fE44VfOmPfexZeAwa8YDOikyTrhP7sZ6A4WUNeC4DlNnJF4zsznU7JxjCkASwpdL6XFwbRSzGkm6b9aM4vIewyclWehJxUGVFhnYEzIQ65qnr38feVP9enOVgQzpKsCJ+xpa8vZ/UrscoG3" +
"/IOQM6VnLrGYAyyCGeyU1JXQW/KlNmtA5eJry2Tp+MD6I34/QsNkCArHOfj8H9tXz/oc3/tVkkR252L/Lmp0TtIGfHpBmoITP9h+oKiW6NpyCc=")
.e("AQAB")
.build())
.expectComplete()
.verify(Duration.ofSeconds(5));
}
@Test
public void getTokenByAuthorizationCode() {
mockRequest(InteractionContext.builder()
.request(TestRequest.builder()
.method(POST).path("/oauth/token?code=zI6Z1X&client_id=login&client_secret=loginsecret&redirect_uri=https%3A%2F%2Fuaa.cloudfoundry.com%2Fredirect%2Fcf" +
"&token_format=opaque&grant_type=authorization_code&response_type=token")
.header("Authorization", null)
.header("Content-Type", "application/x-www-form-urlencoded")
.build())
.response(TestResponse.builder()
.status(OK)
.payload("fixtures/uaa/tokens/GET_response_AC.json")
.build())
.build());
this.tokens
.getByAuthorizationCode(GetTokenByAuthorizationCodeRequest.builder()
.clientId("login")
.clientSecret("loginsecret")
.authorizationCode("zI6Z1X")
.redirectUri("https://uaa.cloudfoundry.com/redirect/cf")
.tokenFormat(TokenFormat.OPAQUE)
.build())
.as(StepVerifier::create)
.expectNext(GetTokenByAuthorizationCodeResponse.builder()
.accessToken("555e2047bbc849628ff8cbfa7b342274")
.tokenType("bearer")
.refreshToken("555e2047bbc849628ff8cbfa7b342274-r")
.expiresInSeconds(43199)
.scopes("openid oauth.approvals")
.tokenId("555e2047bbc849628ff8cbfa7b342274")
.build())
.expectComplete()
.verify(Duration.ofSeconds(5));
}
@Test
public void getTokenByClientCredentials() {
mockRequest(InteractionContext.builder()
.request(TestRequest.builder()
.method(POST).path("/oauth/token?client_id=login&client_secret=loginsecret&token_format=opaque&grant_type=client_credentials&response_type=token")
.header("Authorization", null)
.header("Content-Type", "application/x-www-form-urlencoded")
.build())
.response(TestResponse.builder()
.status(OK)
.payload("fixtures/uaa/tokens/GET_response_CC.json")
.build())
.build());
this.tokens
.getByClientCredentials(GetTokenByClientCredentialsRequest.builder()
.clientId("login")
.clientSecret("loginsecret")
.tokenFormat(TokenFormat.OPAQUE)
.build())
.as(StepVerifier::create)
.expectNext(GetTokenByClientCredentialsResponse.builder()
.accessToken("f87f93a2666d4e6eaa54e34df86d160c")
.tokenType("bearer")
.expiresInSeconds(43199)
.scopes("clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write")
.tokenId("f87f93a2666d4e6eaa54e34df86d160c")
.build())
.expectComplete()
.verify(Duration.ofSeconds(5));
}
@Test
public void getTokenByOneTimePasscode() {
mockRequest(InteractionContext.builder()
.request(TestRequest.builder()
.method(POST).path("/oauth/token?client_id=app&client_secret=appclientsecret&passcode=qcZNkd&token_format=opaque&grant_type=password&response_type=token")
.header("Authorization", null)
.header("Content-Type", "application/x-www-form-urlencoded")
.build())
.response(TestResponse.builder()
.status(OK)
.payload("fixtures/uaa/tokens/GET_response_OT.json")
.build())
.build());
this.tokens
.getByOneTimePasscode(GetTokenByOneTimePasscodeRequest.builder()
.clientId("app")
.clientSecret("appclientsecret")
.passcode("qcZNkd")
.tokenFormat(TokenFormat.OPAQUE)
.build())
.as(StepVerifier::create)
.expectNext(GetTokenByOneTimePasscodeResponse.builder()
.accessToken("0ddcada64ef742a28badaf4750ef435f")
.tokenType("bearer")
.refreshToken("0ddcada64ef742a28badaf4750ef435f-r")
.expiresInSeconds(43199)
.scopes("scim.userids openid cloud_controller.read password.write cloud_controller.write")
.tokenId("0ddcada64ef742a28badaf4750ef435f")
.build())
.expectComplete()
.verify(Duration.ofSeconds(5));
}
@Test
public void getTokenByOpenId() {
mockRequest(InteractionContext.builder()
.request(TestRequest.builder()
.method(POST).path("/oauth/token?code=NAlA1d&client_id=app&client_secret=appclientsecret&redirect_uri=https%3A%2F%2Fuaa.cloudfoundry.com%2Fredirect%2Fcf&token_format=opaque" +
"&grant_type=authorization_code&response_type=id_token")
.header("Authorization", null)
.header("Content-Type", "application/x-www-form-urlencoded")
.build())
.response(TestResponse.builder()
.status(OK)
.payload("fixtures/uaa/tokens/GET_response_OI.json")
.build())
.build());
this.tokens
.getByOpenId(GetTokenByOpenIdRequest.builder()
.clientId("app")
.clientSecret("appclientsecret")
.authorizationCode("NAlA1d")
.redirectUri("https://uaa.cloudfoundry.com/redirect/cf")
.tokenFormat(TokenFormat.OPAQUE)
.build())
.as(StepVerifier::create)
.expectNext(GetTokenByOpenIdResponse.builder()
.accessToken("53a58e6581ee49d08f9e572f673bc8db")
.tokenType("bearer")
.openIdToken("eyJhbGciOiJIUzI1NiIsImtpZCI6ImxlZ2FjeS10b2tlbi1rZXkiLC")
.refreshToken("53a58e6581ee49d08f9e572f673bc8db-r")
.expiresInSeconds(43199)
.scopes("openid oauth.approvals")
.tokenId("53a58e6581ee49d08f9e572f673bc8db")
.build())
.expectComplete()
.verify(Duration.ofSeconds(5));
}
@Test
public void getTokenByPassword() {
mockRequest(InteractionContext.builder()
.request(TestRequest.builder()
.method(POST).path("/oauth/token?client_id=app&client_secret=appclientsecret&password=secr3T&token_format=opaque&" +
"username=jENeJj%40test.org&grant_type=password&response_type=token")
.header("Authorization", null)
.header("Content-Type", "application/x-www-form-urlencoded")
.build())
.response(TestResponse.builder()
.status(OK)
.payload("fixtures/uaa/tokens/GET_response_PW.json")
.build())
.build());
this.tokens
.getByPassword(GetTokenByPasswordRequest.builder()
.clientId("app")
.clientSecret("appclientsecret")
.password("secr3T")
.tokenFormat(TokenFormat.OPAQUE)
.username("jENeJj@test.org")
.build())
.as(StepVerifier::create)
.expectNext(GetTokenByPasswordResponse.builder()
.accessToken("cd37a35114084fafb83d21c6f2af0e84")
.tokenType("bearer")
.refreshToken("cd37a35114084fafb83d21c6f2af0e84-r")
.expiresInSeconds(43199)
.scopes("scim.userids openid cloud_controller.read password.write cloud_controller.write")
.tokenId("cd37a35114084fafb83d21c6f2af0e84")
.build())
.expectComplete()
.verify(Duration.ofSeconds(5));
}
@Test
public void listKeys() {
mockRequest(InteractionContext.builder()
.request(TestRequest.builder()
.method(GET).path("/token_keys")
.build())
.response(TestResponse.builder()
.status(OK)
.payload("fixtures/uaa/token_keys/GET_response.json")
.build())
.build());
this.tokens
.listKeys(ListTokenKeysRequest.builder()
.build())
.as(StepVerifier::create)
.expectNext(ListTokenKeysResponse.builder()
.key(TokenKey.builder()
.id("testKey")
.algorithm("SHA256withRSA")
.value("-----BEGIN PUBLIC KEY-----\n" +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO\n" +
"rn2dVQ3vfBJqcDuFUK03d+1PZGbVlNCqnkpIJ8syFppW8ljnWweP7+LiWpRoz0I7\n" +
"fYb3d8TjhV86Y997Fl4DBrxgM6KTJOuE/uxnoDhZQ14LgOU2ckXjOzOdTsnGMKQB\n" +
"LCl0vpcXBtFLMaSbpv1ozi8h7DJyVZ6EnFQZUWGdgTMhDrmqevfx95U/16c5WBDO\n" +
"kqwIn7Glry9n9Suxygbf8g5AzpWcusZgDLIIZ7JTUldBb8qU2a0Dl4mvLZOn4wPo\n" +
"jfj9Cw2QICsc5+Pwf21fP+hzf+1WSRHbnYv8uanRO0gZ8ekGaghM/2H6gqJbo2nI\n" +
"JwIDAQAB\n" +
"-----END PUBLIC KEY-----")
.keyType(KeyType.RSA)
.use("sig")
.n("ANJufZdrvYg5zG61x36pDq59nVUN73wSanA7hVCtN3ftT2Rm1ZTQqp5KSCfLMhaaVvJY51sHj" +
"+/i4lqUaM9CO32G93fE44VfOmPfexZeAwa8YDOikyTrhP7sZ6A4WUNeC4DlNnJF4zsznU7JxjCkASwpdL6XFwbRSzGkm6b9aM4vIewyclWehJxUGVFhnYEzIQ65qnr38feVP9enOVgQzpKsCJ+xpa8vZ/UrscoG3" +
"/IOQM6VnLrGYAyyCGeyU1JXQW/KlNmtA5eJry2Tp+MD6I34/QsNkCArHOfj8H9tXz/oc3/tVkkR252L/Lmp0TtIGfHpBmoITP9h+oKiW6NpyCc=")
.e("AQAB")
.build())
.build())
.expectComplete()
.verify(Duration.ofSeconds(5));
}
@Test
public void refreshToken() {
mockRequest(InteractionContext.builder()
.request(TestRequest.builder()
.method(POST).path("/oauth/token?client_id=app&client_secret=appclientsecret&refresh_token=6af5fc07a8b74c2eafb0079ff477bb11-r&token_format=opaque&grant_type=refresh_token")
.build())
.response(TestResponse.builder()
.status(OK)
.payload("fixtures/uaa/tokens/GET_refresh_response.json")
.build())
.build());
this.tokens
.refresh(RefreshTokenRequest.builder()
.clientId("app")
.clientSecret("appclientsecret")
.refreshToken("6af5fc07a8b74c2eafb0079ff477bb11-r")
.tokenFormat(TokenFormat.OPAQUE)
.build())
.as(StepVerifier::create)
.expectNext(RefreshTokenResponse.builder()
.accessToken("eyJhbGciOiJIUzI1NiIsImtpZCI6Imx")
.tokenType("bearer")
.refreshToken("eyJhbGciOiJIUzI1NiIsImtpZCI6Imx_E")
.expiresInSeconds(43199)
.scopes("scim.userids cloud_controller.read password.write cloud_controller.write openid")
.tokenId("6af5fc07a8b74c2eafb0079ff477bb11")
.build())
.expectComplete()
.verify(Duration.ofSeconds(5));
}
}
| apache-2.0 |
talsma-ict/umldoclet | src/plantuml-asl/src/net/sourceforge/plantuml/svek/extremity/MiddleCircleCircledMode.java | 1202 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.svek.extremity;
public enum MiddleCircleCircledMode {
BOTH, MODE1, MODE2
}
| apache-2.0 |
apurtell/hbase | hbase-server/src/test/java/org/apache/hadoop/hbase/wal/WALPerformanceEvaluation.java | 22786 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.wal;
import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.Scope;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HBaseTestingUtil;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.MockRegionServerServices;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.RegionInfoBuilder;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.LogRoller;
import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
import org.apache.hadoop.hbase.regionserver.wal.SecureProtobufLogReader;
import org.apache.hadoop.hbase.regionserver.wal.SecureProtobufLogWriter;
import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
import org.apache.hadoop.hbase.trace.TraceUtil;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.CommonFSUtils;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.hadoop.hbase.wal.WALProvider.Writer;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// imports for things that haven't moved from regionserver.wal yet.
/**
* This class runs performance benchmarks for {@link WAL}.
* See usage for this tool by running:
* <code>$ hbase org.apache.hadoop.hbase.wal.WALPerformanceEvaluation -h</code>
*/
@InterfaceAudience.Private
public final class WALPerformanceEvaluation extends Configured implements Tool {
private static final Logger LOG =
LoggerFactory.getLogger(WALPerformanceEvaluation.class);
private final MetricRegistry metrics = new MetricRegistry();
private final Meter syncMeter =
metrics.meter(name(WALPerformanceEvaluation.class, "syncMeter", "syncs"));
private final Histogram syncHistogram = metrics.histogram(
name(WALPerformanceEvaluation.class, "syncHistogram", "nanos-between-syncs"));
private final Histogram syncCountHistogram = metrics.histogram(
name(WALPerformanceEvaluation.class, "syncCountHistogram", "countPerSync"));
private final Meter appendMeter = metrics.meter(
name(WALPerformanceEvaluation.class, "appendMeter", "bytes"));
private final Histogram latencyHistogram =
metrics.histogram(name(WALPerformanceEvaluation.class, "latencyHistogram", "nanos"));
private final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();
private HBaseTestingUtil TEST_UTIL;
static final String TABLE_NAME = "WALPerformanceEvaluation";
static final String QUALIFIER_PREFIX = "q";
static final String FAMILY_PREFIX = "cf";
private int numQualifiers = 1;
private int valueSize = 512;
private int keySize = 16;
@Override
public void setConf(Configuration conf) {
super.setConf(conf);
}
/**
* Perform WAL.append() of Put object, for the number of iterations requested.
* Keys and Vaues are generated randomly, the number of column families,
* qualifiers and key/value size is tunable by the user.
*/
class WALPutBenchmark implements Runnable {
private final long numIterations;
private final int numFamilies;
private final boolean noSync;
private final HRegion region;
private final int syncInterval;
private final NavigableMap<byte[], Integer> scopes;
WALPutBenchmark(final HRegion region, final TableDescriptor htd,
final long numIterations, final boolean noSync, final int syncInterval) {
this.numIterations = numIterations;
this.noSync = noSync;
this.syncInterval = syncInterval;
this.numFamilies = htd.getColumnFamilyCount();
this.region = region;
scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
for(byte[] fam : htd.getColumnFamilyNames()) {
scopes.put(fam, 0);
}
}
@Override
public void run() {
byte[] key = new byte[keySize];
byte[] value = new byte[valueSize];
Random rand = new Random(Thread.currentThread().getId());
WAL wal = region.getWAL();
Span threadSpan = TraceUtil.getGlobalTracer()
.spanBuilder("WALPerfEval." + Thread.currentThread().getName()).startSpan();
try (Scope threadScope = threadSpan.makeCurrent()) {
int lastSync = 0;
for (int i = 0; i < numIterations; ++i) {
assert Span.current() == threadSpan : "Span leak detected.";
Span loopSpan = TraceUtil.getGlobalTracer().spanBuilder("runLoopIter" + i).startSpan();
try (Scope loopScope = loopSpan.makeCurrent()) {
long now = System.nanoTime();
Put put = setupPut(rand, key, value, numFamilies);
WALEdit walEdit = new WALEdit();
walEdit.add(put.getFamilyCellMap());
RegionInfo hri = region.getRegionInfo();
final WALKeyImpl logkey =
new WALKeyImpl(hri.getEncodedNameAsBytes(), hri.getTable(), now, mvcc, scopes);
wal.appendData(hri, logkey, walEdit);
if (!this.noSync) {
if (++lastSync >= this.syncInterval) {
wal.sync();
lastSync = 0;
}
}
latencyHistogram.update(System.nanoTime() - now);
} finally {
loopSpan.end();
}
}
} catch (Exception e) {
LOG.error(getClass().getSimpleName() + " Thread failed", e);
} finally {
threadSpan.end();
}
}
}
@Override
public int run(String[] args) throws Exception {
Path rootRegionDir = null;
int numThreads = 1;
long numIterations = 1000000;
int numFamilies = 1;
int syncInterval = 0;
boolean noSync = false;
boolean verify = false;
boolean verbose = false;
boolean cleanup = true;
boolean noclosefs = false;
long roll = Long.MAX_VALUE;
boolean compress = false;
String cipher = null;
int numRegions = 1;
// Process command line args
for (int i = 0; i < args.length; i++) {
String cmd = args[i];
try {
if (cmd.equals("-threads")) {
numThreads = Integer.parseInt(args[++i]);
} else if (cmd.equals("-iterations")) {
numIterations = Long.parseLong(args[++i]);
} else if (cmd.equals("-path")) {
rootRegionDir = new Path(args[++i]);
} else if (cmd.equals("-families")) {
numFamilies = Integer.parseInt(args[++i]);
} else if (cmd.equals("-qualifiers")) {
numQualifiers = Integer.parseInt(args[++i]);
} else if (cmd.equals("-keySize")) {
keySize = Integer.parseInt(args[++i]);
} else if (cmd.equals("-valueSize")) {
valueSize = Integer.parseInt(args[++i]);
} else if (cmd.equals("-syncInterval")) {
syncInterval = Integer.parseInt(args[++i]);
} else if (cmd.equals("-nosync")) {
noSync = true;
} else if (cmd.equals("-verify")) {
verify = true;
} else if (cmd.equals("-verbose")) {
verbose = true;
} else if (cmd.equals("-nocleanup")) {
cleanup = false;
} else if (cmd.equals("-noclosefs")) {
noclosefs = true;
} else if (cmd.equals("-roll")) {
roll = Long.parseLong(args[++i]);
} else if (cmd.equals("-compress")) {
compress = true;
} else if (cmd.equals("-encryption")) {
cipher = args[++i];
} else if (cmd.equals("-regions")) {
numRegions = Integer.parseInt(args[++i]);
} else if (cmd.equals("-traceFreq")) {
// keep it here for compatible
System.err.println("-traceFreq is not supported any more");
} else if (cmd.equals("-h")) {
printUsageAndExit();
} else if (cmd.equals("--help")) {
printUsageAndExit();
} else {
System.err.println("UNEXPECTED: " + cmd);
printUsageAndExit();
}
} catch (Exception e) {
printUsageAndExit();
}
}
if (compress) {
Configuration conf = getConf();
conf.setBoolean(HConstants.ENABLE_WAL_COMPRESSION, true);
}
if (cipher != null) {
// Set up WAL for encryption
Configuration conf = getConf();
conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
conf.set(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, "hbase");
conf.setClass("hbase.regionserver.hlog.reader.impl", SecureProtobufLogReader.class,
WAL.Reader.class);
conf.setClass("hbase.regionserver.hlog.writer.impl", SecureProtobufLogWriter.class,
Writer.class);
conf.setBoolean(HConstants.ENABLE_WAL_ENCRYPTION, true);
conf.set(HConstants.CRYPTO_WAL_ALGORITHM_CONF_KEY, cipher);
}
if (numThreads < numRegions) {
LOG.warn("Number of threads is less than the number of regions; some regions will sit idle.");
}
// Internal config. goes off number of threads; if more threads than handlers, stuff breaks.
// In regionserver, number of handlers == number of threads.
getConf().setInt(HConstants.REGION_SERVER_HANDLER_COUNT, numThreads);
if (rootRegionDir == null) {
TEST_UTIL = new HBaseTestingUtil(getConf());
rootRegionDir = TEST_UTIL.getDataTestDirOnTestFS("WALPerformanceEvaluation");
}
// Run WAL Performance Evaluation
// First set the fs from configs. In case we are on hadoop1
CommonFSUtils.setFsDefault(getConf(), CommonFSUtils.getRootDir(getConf()));
FileSystem fs = FileSystem.get(getConf());
LOG.info("FileSystem={}, rootDir={}", fs, rootRegionDir);
Span span = TraceUtil.getGlobalTracer().spanBuilder("WALPerfEval").startSpan();
try (Scope scope = span.makeCurrent()){
rootRegionDir = rootRegionDir.makeQualified(fs.getUri(), fs.getWorkingDirectory());
cleanRegionRootDir(fs, rootRegionDir);
CommonFSUtils.setRootDir(getConf(), rootRegionDir);
final WALFactory wals = new WALFactory(getConf(), "wals");
final HRegion[] regions = new HRegion[numRegions];
final Runnable[] benchmarks = new Runnable[numRegions];
final MockRegionServerServices mockServices = new MockRegionServerServices(getConf());
final LogRoller roller = new LogRoller(mockServices);
Threads.setDaemonThreadRunning(roller, "WALPerfEval.logRoller");
try {
for(int i = 0; i < numRegions; i++) {
// Initialize Table Descriptor
// a table per desired region means we can avoid carving up the key space
final TableDescriptor htd = createHTableDescriptor(i, numFamilies);
regions[i] = openRegion(fs, rootRegionDir, htd, wals, roll, roller);
benchmarks[i] =
new WALPutBenchmark(regions[i], htd, numIterations, noSync, syncInterval);
}
ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).
outputTo(System.out).convertRatesTo(TimeUnit.SECONDS).filter(MetricFilter.ALL).build();
reporter.start(30, TimeUnit.SECONDS);
long putTime = runBenchmark(benchmarks, numThreads);
logBenchmarkResult("Summary: threads=" + numThreads + ", iterations=" + numIterations +
", syncInterval=" + syncInterval, numIterations * numThreads, putTime);
for (int i = 0; i < numRegions; i++) {
if (regions[i] != null) {
closeRegion(regions[i]);
regions[i] = null;
}
}
if (verify) {
LOG.info("verifying written log entries.");
Path dir = new Path(CommonFSUtils.getRootDir(getConf()),
AbstractFSWALProvider.getWALDirectoryName("wals"));
long editCount = 0;
FileStatus [] fsss = fs.listStatus(dir);
if (fsss.length == 0) throw new IllegalStateException("No WAL found");
for (FileStatus fss: fsss) {
Path p = fss.getPath();
if (!fs.exists(p)) throw new IllegalStateException(p.toString());
editCount += verify(wals, p, verbose);
}
long expected = numIterations * numThreads;
if (editCount != expected) {
throw new IllegalStateException("Counted=" + editCount + ", expected=" + expected);
}
}
} finally {
mockServices.stop("test clean up.");
for (int i = 0; i < numRegions; i++) {
if (regions[i] != null) {
closeRegion(regions[i]);
}
}
if (null != roller) {
LOG.info("shutting down log roller.");
roller.close();
}
wals.shutdown();
// Remove the root dir for this test region
if (cleanup) cleanRegionRootDir(fs, rootRegionDir);
}
} finally {
span.end();
// We may be called inside a test that wants to keep on using the fs.
if (!noclosefs) {
fs.close();
}
}
return 0;
}
private static TableDescriptor createHTableDescriptor(final int regionNum,
final int numFamilies) {
TableDescriptorBuilder builder =
TableDescriptorBuilder.newBuilder(TableName.valueOf(TABLE_NAME + ":" + regionNum));
IntStream.range(0, numFamilies)
.mapToObj(i -> ColumnFamilyDescriptorBuilder.of(FAMILY_PREFIX + i))
.forEachOrdered(builder::setColumnFamily);
return builder.build();
}
/**
* Verify the content of the WAL file.
* Verify that the file has expected number of edits.
* @param wals may not be null
* @param wal
* @return Count of edits.
* @throws IOException
*/
private long verify(final WALFactory wals, final Path wal, final boolean verbose)
throws IOException {
WAL.Reader reader = wals.createReader(wal.getFileSystem(getConf()), wal);
long count = 0;
Map<String, Long> sequenceIds = new HashMap<>();
try {
while (true) {
WAL.Entry e = reader.next();
if (e == null) {
LOG.debug("Read count=" + count + " from " + wal);
break;
}
count++;
long seqid = e.getKey().getSequenceId();
if (sequenceIds.containsKey(Bytes.toString(e.getKey().getEncodedRegionName()))) {
// sequenceIds should be increasing for every regions
if (sequenceIds.get(Bytes.toString(e.getKey().getEncodedRegionName())) >= seqid) {
throw new IllegalStateException("wal = " + wal.getName() + ", " + "previous seqid = "
+ sequenceIds.get(Bytes.toString(e.getKey().getEncodedRegionName()))
+ ", current seqid = " + seqid);
}
}
// update the sequence Id.
sequenceIds.put(Bytes.toString(e.getKey().getEncodedRegionName()), seqid);
if (verbose) LOG.info("seqid=" + seqid);
}
} finally {
reader.close();
}
return count;
}
private static void logBenchmarkResult(String testName, long numTests, long totalTime) {
float tsec = totalTime / 1000.0f;
LOG.info(String.format("%s took %.3fs %.3fops/s", testName, tsec, numTests / tsec));
}
private void printUsageAndExit() {
System.err.printf("Usage: hbase %s [options]\n", getClass().getName());
System.err.println(" where [options] are:");
System.err.println(" -h|-help Show this help and exit.");
System.err.println(" -threads <N> Number of threads writing on the WAL.");
System.err.println(" -regions <N> Number of regions to open in the WAL. Default: 1");
System.err.println(" -iterations <N> Number of iterations per thread.");
System.err.println(" -path <PATH> Path where region's root directory is created.");
System.err.println(" -families <N> Number of column families to write.");
System.err.println(" -qualifiers <N> Number of qualifiers to write.");
System.err.println(" -keySize <N> Row key size in byte.");
System.err.println(" -valueSize <N> Row/Col value size in byte.");
System.err.println(" -nocleanup Do NOT remove test data when done.");
System.err.println(" -noclosefs Do NOT close the filesystem when done.");
System.err.println(" -nosync Append without syncing");
System.err.println(" -syncInterval <N> Append N edits and then sync. " +
"Default=0, i.e. sync every edit.");
System.err.println(" -verify Verify edits written in sequence");
System.err.println(" -verbose Output extra info; " +
"e.g. all edit seq ids when verifying");
System.err.println(" -roll <N> Roll the way every N appends");
System.err.println(" -encryption <A> Encrypt the WAL with algorithm A, e.g. AES");
System.err.println(" -traceFreq <N> Rate of trace sampling. Default: 1.0, " +
"only respected when tracing is enabled, ie -Dhbase.trace.spanreceiver.classes=...");
System.err.println("");
System.err.println("Examples:");
System.err.println("");
System.err.println(" To run 100 threads on hdfs with log rolling every 10k edits and " +
"verification afterward do:");
System.err.println(" $ hbase org.apache.hadoop.hbase.wal." +
"WALPerformanceEvaluation \\");
System.err.println(" -conf ./core-site.xml -path hdfs://example.org:7000/tmp " +
"-threads 100 -roll 10000 -verify");
System.exit(1);
}
private final Set<WAL> walsListenedTo = new HashSet<>();
private HRegion openRegion(final FileSystem fs, final Path dir, final TableDescriptor htd,
final WALFactory wals, final long whenToRoll, final LogRoller roller) throws IOException {
// Initialize HRegion
RegionInfo regionInfo = RegionInfoBuilder.newBuilder(htd.getTableName()).build();
// Initialize WAL
final WAL wal = wals.getWAL(regionInfo);
// If we haven't already, attach a listener to this wal to handle rolls and metrics.
if (walsListenedTo.add(wal)) {
roller.addWAL(wal);
wal.registerWALActionsListener(new WALActionsListener() {
private int appends = 0;
@Override
public void visitLogEntryBeforeWrite(WALKey logKey, WALEdit logEdit) {
this.appends++;
if (this.appends % whenToRoll == 0) {
LOG.info("Rolling after " + appends + " edits");
// We used to do explicit call to rollWriter but changed it to a request
// to avoid dead lock (there are less threads going on in this class than
// in the regionserver -- regionserver does not have the issue).
AbstractFSWALProvider.requestLogRoll(wal);
}
}
@Override
public void postSync(final long timeInNanos, final int handlerSyncs) {
syncMeter.mark();
syncHistogram.update(timeInNanos);
syncCountHistogram.update(handlerSyncs);
}
@Override
public void postAppend(final long size, final long elapsedTime, final WALKey logkey,
final WALEdit logEdit) {
appendMeter.mark(size);
}
});
}
return HRegion.createHRegion(regionInfo, dir, getConf(), htd, wal);
}
private void closeRegion(final HRegion region) throws IOException {
if (region != null) {
region.close();
WAL wal = region.getWAL();
if (wal != null) {
wal.shutdown();
}
}
}
private void cleanRegionRootDir(final FileSystem fs, final Path dir) throws IOException {
if (fs.exists(dir)) {
fs.delete(dir, true);
}
}
private Put setupPut(Random rand, byte[] key, byte[] value, final int numFamilies) {
rand.nextBytes(key);
Put put = new Put(key);
for (int cf = 0; cf < numFamilies; ++cf) {
for (int q = 0; q < numQualifiers; ++q) {
rand.nextBytes(value);
put.addColumn(Bytes.toBytes(FAMILY_PREFIX + cf),
Bytes.toBytes(QUALIFIER_PREFIX + q), value);
}
}
return put;
}
private long runBenchmark(Runnable[] runnable, final int numThreads) throws InterruptedException {
Thread[] threads = new Thread[numThreads];
long startTime = EnvironmentEdgeManager.currentTime();
for (int i = 0; i < numThreads; ++i) {
threads[i] = new Thread(runnable[i%runnable.length], "t" + i + ",r" + (i%runnable.length));
threads[i].start();
}
for (Thread t : threads) t.join();
long endTime = EnvironmentEdgeManager.currentTime();
return(endTime - startTime);
}
/**
* The guts of the {@link #main} method.
* Call this method to avoid the {@link #main(String[])} System.exit.
* @param args
* @return errCode
* @throws Exception
*/
static int innerMain(final Configuration c, final String [] args) throws Exception {
return ToolRunner.run(c, new WALPerformanceEvaluation(), args);
}
public static void main(String[] args) throws Exception {
System.exit(innerMain(HBaseConfiguration.create(), args));
}
}
| apache-2.0 |
DCuckoo/DCuckooHash | other/key-value.cpp | 1433 | #include "key-value.h"
#include <stdlib.h>
#include <iostream>
#include <fstream>
int getFIBSize(char * fibfile)
{
int readlines=0;
char key[20];
int val=0;
FILE *fp = fopen(fibfile,"r");
if (NULL == fp)
{
printf("open %s failed", fibfile);
return NULL;
}
while(!feof(fp))
{
fscanf(fp, "%s %u", key, &val);
if (strlen(key)>4)readlines++;
}
fclose(fp);
return readlines;
}
hashentry * readHashEntries(int & readline, char *inputfile)
{
hashentry *pHashentries=new hashentry[1000000];
memset(pHashentries,0,sizeof(hashentry)*1000000);
char *hashfile=inputfile;
FILE *fp = fopen(hashfile,"r");
if (NULL == fp)
{
printf("open %s failed", hashfile);
return NULL;
}
while(!feof(fp))
{
fscanf(fp, "%s %u", pHashentries[readline].key, &(pHashentries[readline].value));
if (strlen((const char *)(pHashentries[readline].key))>4)readline++;
}
fclose(fp);
return pHashentries;
}
hashentryP * readHashEntriesPointer(int & readline, char *inputfile)
{
hashentryP *pHashentries=new hashentryP[1000000];
memset(pHashentries,0,sizeof(hashentryP)*1000000);
char *hashfile=inputfile;
FILE *fp = fopen(hashfile,"r");
if (NULL == fp)
{
printf("open %s failed", hashfile);
}
while(!feof(fp))
{
fscanf(fp, "%s %u", pHashentries[readline].key, &(pHashentries[readline].value));
if (strlen((const char *)(pHashentries[readline].key))>4)readline++;
}
fclose(fp);
return pHashentries;
} | apache-2.0 |
AdityaMili95/Wallte | vendor/github.com/knq/chromedp/cdp/audits/easyjson.go | 4859 | // Code generated by easyjson for marshaling/unmarshaling. DO NOT EDIT.
package audits
import (
json "encoding/json"
network "github.com/knq/chromedp/cdp/network"
easyjson "github.com/mailru/easyjson"
jlexer "github.com/mailru/easyjson/jlexer"
jwriter "github.com/mailru/easyjson/jwriter"
)
// suppress unused package warning
var (
_ *json.RawMessage
_ *jlexer.Lexer
_ *jwriter.Writer
_ easyjson.Marshaler
)
func easyjsonC5a4559bDecodeGithubComKnqChromedpCdpAudits(in *jlexer.Lexer, out *GetEncodedResponseReturns) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
in.Consumed()
}
in.Skip()
return
}
in.Delim('{')
for !in.IsDelim('}') {
key := in.UnsafeString()
in.WantColon()
if in.IsNull() {
in.Skip()
in.WantComma()
continue
}
switch key {
case "body":
out.Body = string(in.String())
case "originalSize":
out.OriginalSize = int64(in.Int64())
case "encodedSize":
out.EncodedSize = int64(in.Int64())
default:
in.SkipRecursive()
}
in.WantComma()
}
in.Delim('}')
if isTopLevel {
in.Consumed()
}
}
func easyjsonC5a4559bEncodeGithubComKnqChromedpCdpAudits(out *jwriter.Writer, in GetEncodedResponseReturns) {
out.RawByte('{')
first := true
_ = first
if in.Body != "" {
if !first {
out.RawByte(',')
}
first = false
out.RawString("\"body\":")
out.String(string(in.Body))
}
if in.OriginalSize != 0 {
if !first {
out.RawByte(',')
}
first = false
out.RawString("\"originalSize\":")
out.Int64(int64(in.OriginalSize))
}
if in.EncodedSize != 0 {
if !first {
out.RawByte(',')
}
first = false
out.RawString("\"encodedSize\":")
out.Int64(int64(in.EncodedSize))
}
out.RawByte('}')
}
// MarshalJSON supports json.Marshaler interface
func (v GetEncodedResponseReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComKnqChromedpCdpAudits(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v GetEncodedResponseReturns) MarshalEasyJSON(w *jwriter.Writer) {
easyjsonC5a4559bEncodeGithubComKnqChromedpCdpAudits(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *GetEncodedResponseReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComKnqChromedpCdpAudits(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *GetEncodedResponseReturns) UnmarshalEasyJSON(l *jlexer.Lexer) {
easyjsonC5a4559bDecodeGithubComKnqChromedpCdpAudits(l, v)
}
func easyjsonC5a4559bDecodeGithubComKnqChromedpCdpAudits1(in *jlexer.Lexer, out *GetEncodedResponseParams) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
in.Consumed()
}
in.Skip()
return
}
in.Delim('{')
for !in.IsDelim('}') {
key := in.UnsafeString()
in.WantColon()
if in.IsNull() {
in.Skip()
in.WantComma()
continue
}
switch key {
case "requestId":
out.RequestID = network.RequestID(in.String())
case "encoding":
(out.Encoding).UnmarshalEasyJSON(in)
case "quality":
out.Quality = float64(in.Float64())
case "sizeOnly":
out.SizeOnly = bool(in.Bool())
default:
in.SkipRecursive()
}
in.WantComma()
}
in.Delim('}')
if isTopLevel {
in.Consumed()
}
}
func easyjsonC5a4559bEncodeGithubComKnqChromedpCdpAudits1(out *jwriter.Writer, in GetEncodedResponseParams) {
out.RawByte('{')
first := true
_ = first
if !first {
out.RawByte(',')
}
first = false
out.RawString("\"requestId\":")
out.String(string(in.RequestID))
if !first {
out.RawByte(',')
}
first = false
out.RawString("\"encoding\":")
(in.Encoding).MarshalEasyJSON(out)
if in.Quality != 0 {
if !first {
out.RawByte(',')
}
first = false
out.RawString("\"quality\":")
out.Float64(float64(in.Quality))
}
if in.SizeOnly {
if !first {
out.RawByte(',')
}
first = false
out.RawString("\"sizeOnly\":")
out.Bool(bool(in.SizeOnly))
}
out.RawByte('}')
}
// MarshalJSON supports json.Marshaler interface
func (v GetEncodedResponseParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComKnqChromedpCdpAudits1(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v GetEncodedResponseParams) MarshalEasyJSON(w *jwriter.Writer) {
easyjsonC5a4559bEncodeGithubComKnqChromedpCdpAudits1(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *GetEncodedResponseParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComKnqChromedpCdpAudits1(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *GetEncodedResponseParams) UnmarshalEasyJSON(l *jlexer.Lexer) {
easyjsonC5a4559bDecodeGithubComKnqChromedpCdpAudits1(l, v)
}
| apache-2.0 |
shopiz/shopiz | src/app_helper/includes/Api/Taobao/Request/CaipiaoShopInfoInputRequest.php | 2712 | <?php
namespace Api\Taobao\Request;
/**
* TOP API: taobao.caipiao.shop.info.input request
*
* @author auto create
* @since 1.0, 2014-03-20 13:15:50
*/
class CaipiaoShopInfoInputRequest
{
/**
* 活动结束时间,格式需严格遵守yyyy-MM-dd HH:mm:ss,不可为空
**/
private $actEndDate;
/**
* 活动开始时间,格式需严格遵守yyyy-MM-dd HH:mm:ss,不可为空
**/
private $actStartDate;
/**
* 赠送类型:0-满就送;1-好评送;2-分享送;3-游戏送;4-收藏送,不可为空
**/
private $presentType;
/**
* 店铺参加的送彩票活动描述
**/
private $shopDesc;
/**
* 店铺名称
**/
private $shopName;
/**
* 店铺类目编号,不可为空
**/
private $shopType;
private $apiParas = array();
public function setActEndDate($actEndDate)
{
$this->actEndDate = $actEndDate;
$this->apiParas["act_end_date"] = $actEndDate;
}
public function getActEndDate()
{
return $this->actEndDate;
}
public function setActStartDate($actStartDate)
{
$this->actStartDate = $actStartDate;
$this->apiParas["act_start_date"] = $actStartDate;
}
public function getActStartDate()
{
return $this->actStartDate;
}
public function setPresentType($presentType)
{
$this->presentType = $presentType;
$this->apiParas["present_type"] = $presentType;
}
public function getPresentType()
{
return $this->presentType;
}
public function setShopDesc($shopDesc)
{
$this->shopDesc = $shopDesc;
$this->apiParas["shop_desc"] = $shopDesc;
}
public function getShopDesc()
{
return $this->shopDesc;
}
public function setShopName($shopName)
{
$this->shopName = $shopName;
$this->apiParas["shop_name"] = $shopName;
}
public function getShopName()
{
return $this->shopName;
}
public function setShopType($shopType)
{
$this->shopType = $shopType;
$this->apiParas["shop_type"] = $shopType;
}
public function getShopType()
{
return $this->shopType;
}
public function getApiMethodName()
{
return "taobao.caipiao.shop.info.input";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
\Api\Taobao\RequestCheckUtil::checkNotNull($this->actEndDate,"actEndDate");
\Api\Taobao\RequestCheckUtil::checkNotNull($this->actStartDate,"actStartDate");
\Api\Taobao\RequestCheckUtil::checkNotNull($this->presentType,"presentType");
\Api\Taobao\RequestCheckUtil::checkNotNull($this->shopType,"shopType");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
| apache-2.0 |
Mikuz/Pacguy | Assets/Scripts/GhostController.cs | 3646 | using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
public class GhostController : MonoBehaviour {
public bool stop = false;
public float speed;
public Direction direction = Direction.UP;
/// <summary>
/// Direction that is already being touched
/// </summary>
public Direction lockDirection;
/// <summary>
/// Blocks direction changing
/// </summary>
private float freeze;
private float grounded;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (grounded > 5.0f) {
// When lag is really bad a ghost may get lost to the abyss
Debug.LogWarning("Ghost has not been touching the Ground. Reset position.");
transform.position = new Vector3(0, 1.5f, 0);
}
if (!stop) {
Vector3 movement = GetMovement (this.direction, this.speed);
transform.position = transform.position + (movement * Time.deltaTime);
}
freeze = (freeze > 0) ? freeze - Time.deltaTime : 0;
grounded += Time.deltaTime;
}
void OnTriggerEnter(Collider other) {
if (!isFreeze() &&
GhostController.isCollidable(other.gameObject.tag)) {
//Debug.Log("Tag " + other.gameObject.tag);
WallDirectionSwitch();
//Debug.Log("Direction " + direction);
}
}
void OnTriggerExit(Collider other) {
if (other.gameObject.tag == "Ground") {
// Failsafe, if the game lags ghost may leave the ground
Debug.Log("Ghost left the Ground. Go " + direction);
direction = getCounterDirection(direction);
freeze = 1.0f;
}
}
void OnTriggerStay(Collider other) {
if (other.gameObject.tag == "Ground") {
grounded = 0;
}
}
void WallDirectionSwitch() {
List<Direction> randomizable = new List<Direction>();
foreach (Direction d in Enum.GetValues(typeof(Direction))) {
if (d != direction && d != lockDirection) randomizable.Add(d);
}
Direction randomDirection = getRandomDirection(randomizable);
if (randomDirection != getCounterDirection(direction)) {
// Lock current direction if ghost dosn't back off from it
lockDirection = direction;
}
CounterMove();
direction = randomDirection;
}
public void CounterMove() {
// Move slightly back so that passing a gap sideways
// doesn't trigger OnTriggerEnter
Vector3 counterMove = GetMovement(this.direction, 0.1f);
transform.position = transform.position - counterMove;
}
public bool isFreeze() {
return (this.freeze > 0);
}
public static Boolean isCollidable(String tag) {
return !(tag == "Player" ||
tag == "Enemy" ||
tag == "Ghost" ||
tag == "PickUp" ||
tag == "Blocker");
}
static Vector3 GetMovement(Direction direction, float speed) {
Vector3 movement;
if (direction == Direction.UP) {
movement = new Vector3(0, 0, speed);
} else if (direction == Direction.DOWN) {
movement = new Vector3(0, 0, -speed);
} else if (direction == Direction.RIGHT) {
movement = new Vector3(speed, 0, 0);
} else {
movement = new Vector3(-speed, 0, 0);
}
return movement;
}
public static Direction getRandomDirection(List<Direction> directions) {
System.Random random = new System.Random();
int index = random.Next(directions.Count);
return directions[index];
}
static bool isDirectionVertical(Direction direction) {
return direction == Direction.UP || direction == Direction.DOWN;
}
static Direction getCounterDirection(Direction direction) {
if (direction == Direction.UP) return Direction.DOWN;
else if (direction == Direction.DOWN) return Direction.UP;
else if (direction == Direction.LEFT) return Direction.RIGHT;
else return Direction.LEFT;
}
}
| apache-2.0 |
PretenderX/EasyRestClient | EasyRestClient.Test/MockEndpointTemplateImplementations/MockRequest.cs | 397 | using EasyRestClient.EndpointTemplate;
using RestSharp;
namespace EasyRestClient.Test.MockEndpointTemplateImplementations
{
public class MockRequest : IEasyRestRequest<MockResponse>
{
public string Resource => "";
public Method Method => Method.GET;
public DataFormat RequestFormat => DataFormat.Json;
public string Accept => "application/josn";
}
} | apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/CertificateAuthenticationStaxUnmarshaller.java | 2547 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ec2.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* CertificateAuthentication StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CertificateAuthenticationStaxUnmarshaller implements Unmarshaller<CertificateAuthentication, StaxUnmarshallerContext> {
public CertificateAuthentication unmarshall(StaxUnmarshallerContext context) throws Exception {
CertificateAuthentication certificateAuthentication = new CertificateAuthentication();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return certificateAuthentication;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("clientRootCertificateChain", targetDepth)) {
certificateAuthentication.setClientRootCertificateChain(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return certificateAuthentication;
}
}
}
}
private static CertificateAuthenticationStaxUnmarshaller instance;
public static CertificateAuthenticationStaxUnmarshaller getInstance() {
if (instance == null)
instance = new CertificateAuthenticationStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
etechi/ServiceFramework | Projects/Server/Sys/SF.Sys.AspNetCore/Hosting/DefaultFilePathStructure.cs | 1391 | #region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2017 Yang Chen (cy2000@gmail.com)
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.
Detail: https://github.com/etechi/ServiceFramework/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
using Microsoft.AspNetCore.Hosting;
using SF.Sys.Hosting;
namespace SF.Sys.AspNetCore
{
public class DefaultFilePathStructure : IDefaultFilePathStructure
{
IHostingEnvironment Environment { get; }
public string BinaryPath => System.IO.Path.Combine(Environment.ContentRootPath, "bin");
public FilePathDefination FilePathDefination=>new FilePathDefination();
public string RootPath => System.IO.Path.Combine(Environment.ContentRootPath);
public DefaultFilePathStructure(IHostingEnvironment env)
{
Environment = env;
}
}
}
| apache-2.0 |
fkautz/sentry | sentrylib/config.go | 975 | package sentrylib
type Config struct {
AprsServer string
AprsUser string
AprsPasscode string
AprsFilter string
Cutoff string
SkipCooldown bool `json:",omitempty"`
Mailgun *MailgunConfig `json:",omitempty"`
BoltConfig *BoltConfig `json:",omitempty"`
PostgresConfig *PostgresConfig `json:",omitempty"`
GoLevelDBConfig *GoLevelDbConfig `json:",omitempty"`
RethinkDBConfig *RethinkConfig `json:",omitempty"`
}
type MailgunConfig struct {
Domain string
ApiKey string
PubApiKey string
FromAddress string
}
type BoltConfig struct {
File string
}
type PostgresConfig struct {
ConnString string `yaml:"connstring,omitempty" json:",omitempty"`
User string
Password string
Host string
DbName string
SslMode string
}
type RethinkConfig struct {
Address string
Database string
Username string
Password string
}
type GoLevelDbConfig struct {
File string
}
| apache-2.0 |
naturalness/sensibility | sensibility/__main__.py | 3308 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright 2017 Eddie Antonio Santos <easantos@ualberta.ca>
#
# 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.
"""
Allows one to set the language prior to running any of the scripts:
Usage:
sensibility [-l LANGUAGE] <command> [<args>]
"""
import os
import sys
from pathlib import Path
from types import SimpleNamespace
from typing import Dict, List, Tuple
from sensibility._paths import REPOSITORY_ROOT
bin_dir = REPOSITORY_ROOT / 'bin'
def main() -> None:
assert bin_dir.is_dir()
args = parse_args()
# Set up the environment
env: Dict[str, str] = {}
env.update(os.environ)
# Set the language if defined.
if args.language is not None:
env.update(SENSIBILITY_LANGUAGE=args.language)
if args.subcommand:
run_subcommand(args.subcommand, env)
else:
list_commands()
sys.exit(-1)
def run_subcommand(command, env) -> None:
bin, args = get_bin_and_argv(command)
if not bin.exists():
usage_error("Unknown executable:", bin)
os.execve(str(bin.absolute()), args, env)
def list_commands() -> None:
print("Please specify a subcommand:\n", file=sys.stderr)
for bin in bin_dir.rglob('*'):
if bin.is_dir() or not is_executable(bin):
continue
bin = bin.relative_to(bin_dir)
subcommand = ' '.join(bin.parts)
print(f"\t{subcommand}", file=sys.stderr)
def get_bin_and_argv(command: List[str]) -> Tuple[Path, List[str]]:
"""
Returns the absolute path to the binary, AND the argument vector,
including argv[0] (the command name).
"""
first_comp, = command[:1]
# XXX: Only supports one-level subcommands
if (bin_dir / first_comp).is_dir():
return bin_dir / first_comp / command[1], command[1:]
else:
return bin_dir / first_comp, command
def is_executable(path: Path) -> bool:
# access() is deprecated, but we're using it anyway!
return os.access(path, os.X_OK)
def parse_args(argv=sys.argv):
"""
Roll my own parse because argparse will swallow up arguments that don't
belong to it.
"""
argv = argv[1:]
args = SimpleNamespace()
args.language = None
args.subcommand = None
# Parse options one by one.
while argv:
arg = argv.pop(0)
if arg in ('-l', '--language'):
args.language = argv.pop(0)
elif arg.startswith('--language='):
_, args.language = arg.split('=', 1)
elif arg.startswith('-'):
usage_error(f"Unknown argument {arg!r}")
else:
args.subcommand = [arg] + argv[:]
break
return args
def usage_error(*args):
print(f"{sys.argv[0]}:", *args, file=sys.stderr)
sys.exit(2)
if __name__ == '__main__':
main()
| apache-2.0 |
Ardesco/selenium | javascript/node/selenium-webdriver/tools/init_jasmine.js | 1008 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// eslint-disable-next-line node/no-missing-require
require('@bazel/jasmine').boot()
global.after = global.afterAll
global.before = global.beforeAll
global.jasmine.DEFAULT_TIMEOUT_INTERVAL = 120 * 1000
| apache-2.0 |
sjaco002/incubator-asterixdb | asterix-installer/src/main/java/edu/uci/ics/asterix/installer/command/InstallCommand.java | 2939 | /*
* Copyright 2009-2012 by The 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 from
*
* 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 edu.uci.ics.asterix.installer.command;
import org.kohsuke.args4j.Option;
import edu.uci.ics.asterix.event.model.AsterixInstance;
import edu.uci.ics.asterix.event.model.AsterixInstance.State;
import edu.uci.ics.asterix.event.schema.pattern.Patterns;
import edu.uci.ics.asterix.event.service.AsterixEventService;
import edu.uci.ics.asterix.event.service.AsterixEventServiceUtil;
import edu.uci.ics.asterix.event.util.PatternCreator;
import edu.uci.ics.asterix.installer.driver.InstallerDriver;
public class InstallCommand extends AbstractCommand {
@Override
protected void execCommand() throws Exception {
InstallerDriver.initConfig(true);
InstallConfig installConfig = ((InstallConfig) config);
String instanceName = installConfig.name;
AsterixInstance instance = AsterixEventServiceUtil.validateAsterixInstanceExists(instanceName, State.INACTIVE);
PatternCreator pc = PatternCreator.INSTANCE;
Patterns patterns = pc.getLibraryInstallPattern(instance, installConfig.dataverseName,
installConfig.libraryName, installConfig.libraryPath);
AsterixEventService.getAsterixEventServiceClient(instance.getCluster()).submit(patterns);
LOGGER.info("Installed library " + installConfig.libraryName);
}
@Override
protected CommandConfig getCommandConfig() {
return new InstallConfig();
}
@Override
protected String getUsageDescription() {
return "Installs a library to an asterix instance." + "\n" + "Arguments/Options\n"
+ "-n Name of Asterix Instance\n"
+ "-d Name of the dataverse under which the library will be installed\n" + "-l Name of the library\n"
+ "-p Path to library zip bundle";
}
}
class InstallConfig extends CommandConfig {
@Option(name = "-n", required = true, usage = "Name of Asterix Instance")
public String name;
@Option(name = "-d", required = true, usage = "Name of the dataverse under which the library will be installed")
public String dataverseName;
@Option(name = "-l", required = true, usage = "Name of the library")
public String libraryName;
@Option(name = "-p", required = true, usage = "Path to library zip bundle")
public String libraryPath;
}
| apache-2.0 |
Talend/data-prep | dataprep-api/src/main/java/org/talend/dataprep/api/service/command/dataset/DataSetDelete.java | 3109 | // ============================================================================
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataprep.api.service.command.dataset;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpRequestBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.talend.daikon.exception.ExceptionContext;
import org.talend.dataprep.api.service.command.preparation.CheckDatasetUsage;
import org.talend.dataprep.command.GenericCommand;
import org.talend.dataprep.exception.TDPException;
import org.talend.dataprep.exception.error.APIErrorCodes;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.HttpStatus.OK;
import static org.talend.dataprep.command.Defaults.getResponseEntity;
import static org.talend.dataprep.exception.error.APIErrorCodes.DATASET_STILL_IN_USE;
/**
* Delete the dataset if it's not used by any preparation.
*/
@Component
@Scope(SCOPE_PROTOTYPE)
public class DataSetDelete extends GenericCommand<ResponseEntity<String>> {
/**
* This class' logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(DataSetDelete.class);
/**
* Default constructor.
*
* @param dataSetId The dataset id to delete.
*/
private DataSetDelete(final String dataSetId) {
super(GenericCommand.DATASET_GROUP);
execute(() -> onExecute(dataSetId));
on(NOT_FOUND).then((req, resp) -> getResponseEntity(NOT_FOUND, resp));
on(OK).then((req, resp) -> getResponseEntity(OK, resp));
onError(e -> new TDPException(APIErrorCodes.UNABLE_TO_DELETE_DATASET, e,
ExceptionContext.build().put("dataSetId", dataSetId)));
}
private HttpRequestBase onExecute(final String dataSetId) {
final boolean isDatasetUsed = isDatasetUsed(dataSetId);
// if the dataset is used by preparation(s), the deletion is forbidden
if (isDatasetUsed) {
LOG.debug("DataSet {} is used by {} preparation(s) and cannot be deleted", dataSetId);
final ExceptionContext context = ExceptionContext.build().put("dataSetId", dataSetId);
throw new TDPException(DATASET_STILL_IN_USE, context);
}
return new HttpDelete(datasetServiceUrl + "/datasets/" + dataSetId);
}
private boolean isDatasetUsed(final String dataSetId) {
return context.getBean(CheckDatasetUsage.class, dataSetId).execute();
}
}
| apache-2.0 |
alexander-svendsen/elastic4s | elastic4s-core/src/main/scala/com/sksamuel/elastic4s/mappings/MappingDefinition.scala | 6262 | package com.sksamuel.elastic4s.mappings
import com.sksamuel.elastic4s.Analyzer
import org.elasticsearch.common.xcontent.{ XContentFactory, XContentBuilder }
import scala.collection.mutable.ListBuffer
class MappingDefinition(val `type`: String) {
var _all: Option[Boolean] = None
var _source: Option[Boolean] = None
var date_detection: Option[Boolean] = None
var numeric_detection: Option[Boolean] = None
var _size: Option[Boolean] = None
var dynamic_date_formats: Iterable[String] = Nil
val _fields = new ListBuffer[TypedFieldDefinition]
var _analyzer: Option[String] = None
var _boostName: Option[String] = None
var _boostValue: Double = 0
var _parent: Option[String] = None
var _dynamic: Option[DynamicMapping] = None
var _meta: Map[String, Any] = Map.empty
var _routing: Option[RoutingDefinition] = None
var _timestamp: Option[TimestampDefinition] = None
var _ttl: Option[Boolean] = None
var _templates: Iterable[DynamicTemplateDefinition] = Nil
@deprecated("no longer used, simply set ttl or not", "1.5.4")
def useTtl(useTtl: Boolean): this.type = {
this
}
def all(enabled: Boolean): this.type = {
_all = Option(enabled)
this
}
def analyzer(analyzer: String): this.type = {
_analyzer = Option(analyzer)
this
}
def analyzer(analyzer: Analyzer): this.type = {
_analyzer = Option(analyzer.name)
this
}
def boost(name: String): this.type = {
_boostName = Option(name)
this
}
def boostNullValue(value: Double): this.type = {
_boostValue = value
this
}
def parent(parent: String): this.type = {
_parent = Some(parent)
this
}
def dynamic(dynamic: DynamicMapping): this.type = {
_dynamic = Option(dynamic)
this
}
@deprecated("use the DynamicMapping enum version", "1.5.5")
def dynamic(dynamic: Boolean): this.type = {
_dynamic = dynamic match {
case true => Some(DynamicMapping.Dynamic)
case false => Some(DynamicMapping.False)
}
this
}
def timestamp(enabled: Boolean,
path: Option[String] = None,
format: Option[String] = None,
default: Option[String] = None): this.type = {
this._timestamp = Some(TimestampDefinition(enabled, path, format, default))
this
}
def timestamp(timestampDefinition: TimestampDefinition): this.type = {
this._timestamp = Option(timestampDefinition)
this
}
def ttl(enabled: Boolean): this.type = {
_ttl = Option(enabled)
this
}
def dynamicDateFormats(dynamic_date_formats: String*): this.type = {
this.dynamic_date_formats = dynamic_date_formats
this
}
def meta(map: Map[String, Any]): this.type = {
this._meta = map
this
}
def routing(required: Boolean, path: Option[String] = None): this.type = {
this._routing = Some(RoutingDefinition(required, path))
this
}
def source(source: Boolean): this.type = {
this._source = Option(source)
this
}
def dateDetection(date_detection: Boolean): this.type = {
this.date_detection = Some(date_detection)
this
}
def numericDetection(numeric_detection: Boolean): this.type = {
this.numeric_detection = Some(numeric_detection)
this
}
def fields(fields: Iterable[TypedFieldDefinition]): this.type = as(fields)
def as(iterable: Iterable[TypedFieldDefinition]): this.type = {
_fields ++= iterable
this
}
def fields(fields: TypedFieldDefinition*): this.type = as(fields: _*)
def as(fields: TypedFieldDefinition*): this.type = as(fields.toIterable)
def size(size: Boolean): this.type = {
_size = Option(size)
this
}
def dynamicTemplates(temps: Iterable[DynamicTemplateDefinition]): this.type = templates(temps)
def dynamicTemplates(temps: DynamicTemplateDefinition*): this.type = templates(temps)
def templates(temps: Iterable[DynamicTemplateDefinition]): this.type = templates(temps)
def templates(temps: DynamicTemplateDefinition*): this.type = {
_templates = temps
this
}
def build: XContentBuilder = {
val builder = XContentFactory.jsonBuilder().startObject()
build(builder)
builder.endObject()
}
def buildWithName: XContentBuilder = {
val builder = XContentFactory.jsonBuilder().startObject()
builder.startObject(`type`)
build(builder)
builder.endObject()
builder.endObject()
}
def build(json: XContentBuilder): Unit = {
for (all <- _all) json.startObject("_all").field("enabled", all).endObject()
for (source <- _source) json.startObject("_source").field("enabled", source).endObject()
if (dynamic_date_formats.nonEmpty)
json.field("dynamic_date_formats", dynamic_date_formats.toArray: _*)
for (dd <- date_detection) json.field("date_detection", dd)
for (nd <- numeric_detection) json.field("numeric_detection", nd)
_dynamic.foreach(dynamic => {
json.field("dynamic", dynamic match {
case Strict | DynamicMapping.Strict => "strict"
case False | DynamicMapping.False => "false"
case _ => "dynamic"
})
})
_boostName.foreach(x => json.startObject("_boost").field("name", x).field("null_value", _boostValue).endObject())
_analyzer.foreach(x => json.startObject("_analyzer").field("path", x).endObject())
_parent.foreach(x => json.startObject("_parent").field("type", x).endObject())
_size.foreach(x => json.startObject("_size").field("enabled", x).endObject())
_timestamp.foreach(_.build(json))
for (ttl <- _ttl) json.startObject("_ttl").field("enabled", ttl).endObject()
if (_fields.nonEmpty) {
json.startObject("properties")
for (field <- _fields) {
field.build(json)
}
json.endObject() // end properties
}
if (_meta.nonEmpty) {
json.startObject("_meta")
for (meta <- _meta) {
json.field(meta._1, meta._2)
}
json.endObject()
}
_routing.foreach(routing => {
json.startObject("_routing").field("required", routing.required)
routing.path.foreach(path => json.field("path", path))
json.endObject()
})
if (_templates.nonEmpty) {
json.startArray("dynamic_templates")
for (template <- _templates) template.build(json)
json.endArray()
}
}
}
| apache-2.0 |
slok/ragnarok | master/service/experiment/experiment_test.go | 8999 | package experiment_test
import (
"fmt"
"sort"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/slok/ragnarok/api"
chaosv1 "github.com/slok/ragnarok/api/chaos/v1"
clusterv1 "github.com/slok/ragnarok/api/cluster/v1"
"github.com/slok/ragnarok/log"
"github.com/slok/ragnarok/master/service/experiment"
mclichaosv1 "github.com/slok/ragnarok/mocks/client/api/chaos/v1"
mcliclusterv1 "github.com/slok/ragnarok/mocks/client/api/cluster/v1"
)
func TestEnsureFailures(t *testing.T) {
mockCreationTime := time.Now()
tests := []struct {
name string
nodes *clusterv1.NodeList
failures *chaosv1.FailureList
experiment *chaosv1.Experiment
expDeletedFlrIDs []string
expNewFlrs []*chaosv1.Failure
expErr bool
}{
{
name: "A new Experiment should create failures to all available nodes that match the selector",
nodes: &clusterv1.NodeList{
Items: []*clusterv1.Node{
&clusterv1.Node{
Metadata: api.ObjectMeta{ID: "testNode0"},
},
&clusterv1.Node{
Metadata: api.ObjectMeta{ID: "testNode1"},
},
&clusterv1.Node{
Metadata: api.ObjectMeta{ID: "testNode2"},
},
},
},
failures: &chaosv1.FailureList{},
experiment: &chaosv1.Experiment{
Metadata: api.ObjectMeta{
ID: "exp-001",
Annotations: map[string]string{
"name": "first experiment",
"description": "first experiment is the first experiment :|",
},
},
Spec: chaosv1.ExperimentSpec{
Selector: map[string]string{"kind": "master", "az": "eu-west-1a"},
Template: chaosv1.ExperimentFailureTemplate{},
},
},
expDeletedFlrIDs: []string{},
expNewFlrs: []*chaosv1.Failure{
&chaosv1.Failure{
TypeMeta: chaosv1.FailureTypeMeta,
Metadata: api.ObjectMeta{
ID: "flrid-0",
Labels: map[string]string{
"experiment": "exp-001",
"node": "testNode0",
},
},
Status: chaosv1.FailureStatus{
CurrentState: 4,
ExpectedState: 1,
Creation: mockCreationTime,
},
},
&chaosv1.Failure{
TypeMeta: chaosv1.FailureTypeMeta,
Metadata: api.ObjectMeta{
ID: "flrid-1",
Labels: map[string]string{
"experiment": "exp-001",
"node": "testNode1",
},
},
Status: chaosv1.FailureStatus{
CurrentState: 4,
ExpectedState: 1,
Creation: mockCreationTime,
},
},
&chaosv1.Failure{
TypeMeta: chaosv1.FailureTypeMeta,
Metadata: api.ObjectMeta{
ID: "flrid-2",
Labels: map[string]string{
"experiment": "exp-001",
"node": "testNode2",
},
},
Status: chaosv1.FailureStatus{
CurrentState: 4,
ExpectedState: 1,
Creation: mockCreationTime,
},
},
},
expErr: false,
},
{
name: "An already created experiment should create failures only on the nodes that match the selector and that don't have already the failure",
nodes: &clusterv1.NodeList{
Items: []*clusterv1.Node{
&clusterv1.Node{
Metadata: api.ObjectMeta{ID: "testNode0"},
},
&clusterv1.Node{
Metadata: api.ObjectMeta{ID: "testNode1"},
},
&clusterv1.Node{
Metadata: api.ObjectMeta{ID: "testNode2"},
},
},
},
failures: &chaosv1.FailureList{
Items: []*chaosv1.Failure{
&chaosv1.Failure{
TypeMeta: chaosv1.FailureTypeMeta,
Metadata: api.ObjectMeta{
ID: "flrid-x",
Labels: map[string]string{
api.LabelExperiment: "exp-001",
api.LabelNode: "testNode0",
},
},
Status: chaosv1.FailureStatus{
CurrentState: 4,
ExpectedState: 1,
Creation: mockCreationTime,
},
},
},
},
experiment: &chaosv1.Experiment{
Metadata: api.ObjectMeta{
ID: "exp-001",
Annotations: map[string]string{
"name": "first experiment",
"description": "first experiment is the first experiment :|",
},
},
Spec: chaosv1.ExperimentSpec{
Selector: map[string]string{"kind": "master", "az": "eu-west-1a"},
Template: chaosv1.ExperimentFailureTemplate{},
},
},
expDeletedFlrIDs: []string{},
expNewFlrs: []*chaosv1.Failure{
&chaosv1.Failure{
TypeMeta: chaosv1.FailureTypeMeta,
Metadata: api.ObjectMeta{
ID: "flrid-0",
Labels: map[string]string{
api.LabelExperiment: "exp-001",
api.LabelNode: "testNode1",
},
},
Status: chaosv1.FailureStatus{
CurrentState: 4,
ExpectedState: 1,
Creation: mockCreationTime,
},
},
&chaosv1.Failure{
TypeMeta: chaosv1.FailureTypeMeta,
Metadata: api.ObjectMeta{
ID: "flrid-1",
Labels: map[string]string{
api.LabelExperiment: "exp-001",
api.LabelNode: "testNode2",
},
},
Status: chaosv1.FailureStatus{
CurrentState: 4,
ExpectedState: 1,
Creation: mockCreationTime,
},
},
},
expErr: false,
},
{
name: "An already created experiment should create failures only on the nodes that match the selector and that don't have already the failure and delete the ones that don't have nodes",
nodes: &clusterv1.NodeList{
Items: []*clusterv1.Node{
&clusterv1.Node{
Metadata: api.ObjectMeta{ID: "testNode0"},
},
&clusterv1.Node{
Metadata: api.ObjectMeta{ID: "testNode1"},
},
},
},
failures: &chaosv1.FailureList{
Items: []*chaosv1.Failure{
&chaosv1.Failure{
TypeMeta: chaosv1.FailureTypeMeta,
Metadata: api.ObjectMeta{
ID: "flrid-x",
Labels: map[string]string{
api.LabelExperiment: "exp-001",
api.LabelNode: "testNode0",
},
},
Status: chaosv1.FailureStatus{
CurrentState: 4,
ExpectedState: 1,
Creation: mockCreationTime,
},
},
&chaosv1.Failure{
TypeMeta: chaosv1.FailureTypeMeta,
Metadata: api.ObjectMeta{
ID: "flrid-y",
Labels: map[string]string{
api.LabelExperiment: "exp-001",
api.LabelNode: "testNode2",
},
},
Status: chaosv1.FailureStatus{
CurrentState: 4,
ExpectedState: 1,
Creation: mockCreationTime,
},
},
},
},
experiment: &chaosv1.Experiment{
Metadata: api.ObjectMeta{
ID: "exp-001",
Annotations: map[string]string{
"name": "first experiment",
"description": "first experiment is the first experiment :|",
},
},
Spec: chaosv1.ExperimentSpec{
Selector: map[string]string{"kind": "master", "az": "eu-west-1a"},
Template: chaosv1.ExperimentFailureTemplate{},
},
},
expDeletedFlrIDs: []string{
"chaos/v1/failure/flrid-y",
},
expNewFlrs: []*chaosv1.Failure{
&chaosv1.Failure{
TypeMeta: chaosv1.FailureTypeMeta,
Metadata: api.ObjectMeta{
ID: "flrid-0",
Labels: map[string]string{
api.LabelExperiment: "exp-001",
api.LabelNode: "testNode1",
},
},
Status: chaosv1.FailureStatus{
CurrentState: 4,
ExpectedState: 1,
Creation: mockCreationTime,
},
},
},
expErr: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
mockFlrIDCtr := 0
assert := assert.New(t)
gotDeletedFlrIDs := []string{}
gotNewFlrs := []*chaosv1.Failure{}
// mocks.
mnCli := &mcliclusterv1.NodeClientInterface{}
mnCli.On("List", mock.Anything).Return(test.nodes, nil)
mfCli := &mclichaosv1.FailureClientInterface{}
mfCli.On("List", mock.Anything).Return(test.failures, nil)
// Grab actions made on mocks to assert afterwards.
mfCli.On("Delete", mock.Anything).Return(nil).Run(func(args mock.Arguments) {
id := args.Get(0).(string)
gotDeletedFlrIDs = append(gotDeletedFlrIDs, id)
})
mfCli.On("Create", mock.Anything).Return(nil, nil).Run(func(args mock.Arguments) {
flr := args.Get(0).(*chaosv1.Failure)
// Mock ids for equal assertion.
flr.Metadata.ID = fmt.Sprintf("flrid-%d", mockFlrIDCtr)
mockFlrIDCtr++
flr.Status.Creation = mockCreationTime
gotNewFlrs = append(gotNewFlrs, flr)
})
// Create the experiment manager and ensure the failures.
sm := experiment.NewSimpleManager(mnCli, mfCli, log.Dummy)
err := sm.EnsureFailures(test.experiment)
if test.expErr {
assert.Error(err)
} else if assert.NoError(err) {
// Sort before asserting them
sort.Slice(gotDeletedFlrIDs, func(i, j int) bool {
return gotDeletedFlrIDs[i] < gotDeletedFlrIDs[j]
})
sort.Slice(gotNewFlrs, func(i, j int) bool {
return gotNewFlrs[i].Metadata.ID < gotNewFlrs[j].Metadata.ID
})
// Assert.
assert.Equal(test.expDeletedFlrIDs, gotDeletedFlrIDs)
assert.Equal(test.expNewFlrs, gotNewFlrs)
}
})
}
}
| apache-2.0 |
shmul/mule | tests/test_helpers.lua | 945 | require "tests.strict"
local lunit = require "lunit"
if _VERSION >= 'Lua 5.2' then
_ENV = lunit.module('test_helpers','seeall')
else
module( "test_helpers", lunit.testcase,package.seeall )
end
require "helpers"
function test_file_exists()
assert_true(file_exists("tests/fixtures/mule.cfg"))
assert_false(file_exists("tests/fixtures/no-such-file"))
end
function test_file_size()
assert_equal(53, file_size("tests/fixtures/mule.cfg"))
assert_false(file_size("tests/fixtures/no-such-file"))
end
function test_directory_exists()
assert_true(directory_exists("tests/fixtures"))
assert_true(directory_exists("tests/fixtures/"))
assert_false(directory_exists("tests/fixtures/no-such-dir"))
assert_false(directory_exists("tests/fixtures/mule.cfg"))
end
function test_pp_timestamp()
assert_equal(pp_timestamp(1000),"16m40s")
assert_equal(pp_timestamp(10000),"2h46m40s")
assert_equal(pp_timestamp(3*365*24*60*60),"3y")
end
| apache-2.0 |
mikosik/smooth-build | src/main/java/org/smoothbuild/db/record/spec/StringSpec.java | 760 | package org.smoothbuild.db.record.spec;
import static com.google.common.base.Preconditions.checkArgument;
import static org.smoothbuild.db.record.spec.SpecKind.STRING;
import org.smoothbuild.db.hashed.Hash;
import org.smoothbuild.db.hashed.HashedDb;
import org.smoothbuild.db.record.base.MerkleRoot;
import org.smoothbuild.db.record.base.RString;
import org.smoothbuild.db.record.db.RecordDb;
/**
* This class is immutable.
*/
public class StringSpec extends Spec {
public StringSpec(Hash hash, HashedDb hashedDb, RecordDb recordDb) {
super(hash, STRING, hashedDb, recordDb);
}
@Override
public RString newJObject(MerkleRoot merkleRoot) {
checkArgument(this.equals(merkleRoot.spec()));
return new RString(merkleRoot, hashedDb);
}
}
| apache-2.0 |
Orange-OpenSource/elpaaso-core | cloud-paas/cloud-paas-archive/src/main/java/com/francetelecom/clara/cloud/archive/ManageArchiveImpl.java | 13479 | /**
* Copyright (C) 2015 Orange
* 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.francetelecom.clara.cloud.archive;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import com.francetelecom.clara.cloud.commons.MavenReference;
import com.francetelecom.clara.cloud.commons.TechnicalException;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
/**
* Manage ear files or other archives using java 7 nio library
*
* @author BEAL6226
*
*/
public class ManageArchiveImpl implements ManageArchive {
private static Logger logger = LoggerFactory.getLogger(ManageArchiveImpl.class);
/**
* Directory in classpath for source files to put in war
*/
public static final String TEMPLATE_WAR_DIR = "/paas-archive-templates-war/";
/**
* Directory in classpath for source files to put in ear
*/
public static final String TEMPLATE_EAR_DIR = "/paas-archive-templates-ear/";
/**
* freemarker configuration
*/
protected Configuration configuration;
public ManageArchiveImpl() {
super();
}
/*
* (non-Javadoc)
*
* @see
* com.francetelecom.clara.cloud.archive.ManageArchive#generateMinimalEar(com.francetelecom.clara.cloud.commons.MavenReference,
* java.lang.String)
*/
@Override
public File generateMinimalEar(MavenReference mavenReference, String contextRoot) throws TechnicalException {
// Prepare war and ear filename
String earFilename = mavenReference.getArtifactName();
if (!earFilename.endsWith(".ear")) {
logger.error("provided Maven reference {} is not an ear", mavenReference);
throw new TechnicalException("provided Maven reference is not an ear");
}
String warFilename = earFilename.replaceFirst(".ear$", ".war");
// Prepare temp directory to store war and ear
Path tempDir;
try {
tempDir = Files.createTempDirectory("ear");
} catch (IOException e) {
throw new TechnicalException("cannot create empty directory", e);
}
URI earUri = generateJarUri(tempDir, earFilename);
logger.info("URI of ear to be generated : {}", earUri.toString());
// Prepare map for Freemarker (the same map is used for all templates)
Map<String, Object> freemarkerModel = createFreemarkerModel(mavenReference, contextRoot);
Path warFile = generateWar(warFilename, tempDir, freemarkerModel);
// build ear file with war file and files in TEMPLATE_EAR_DIR
try (FileSystem earFileSystem = FileSystems.newFileSystem(earUri, getFileSystemEnv())) { // earFileSystem is automatically closed
addAbsoluteFileToJarFile(warFile.getParent(), warFile, earFileSystem);
// addSourceFilesToJarFile(TEMPLATE_EAR_DIR, freemarkerModel, earFileSystem);
createDirectoryInJarFile("META-INF", earFileSystem);
addClasspathTemplateToJarFile(TEMPLATE_EAR_DIR, "META-INF/application.xml.flt", freemarkerModel, earFileSystem);
} catch (IOException e) {
throw new TechnicalException("cannot create jar filesystem", e);
}
// delete war file as it is no more useful
try {
Files.delete(warFile);
} catch (IOException e) {
logger.debug("cannot delete war file {}", warFile, e);
}
return new File(tempDir.toString(), earFilename);
}
@Override
public File generateMinimalWar(MavenReference mavenReferenceForWarGeneration, String contextRoot) throws TechnicalException {
String warFilename = mavenReferenceForWarGeneration.getArtifactName();
if (!warFilename.endsWith(".war")) {
logger.warn("provided Maven reference {} is not an war", mavenReferenceForWarGeneration);
warFilename=warFilename.substring(0,warFilename.length()-4) + ".war";
logger.warn("renamed {} to {} for maven reference {}", mavenReferenceForWarGeneration.getArtifactName(),warFilename, mavenReferenceForWarGeneration);
}
// Prepare temp directory to store war and ear
Path tempDir;
try {
tempDir = Files.createTempDirectory("war");
} catch (IOException e) {
throw new TechnicalException("cannot create empty directory", e);
}
URI warUri = generateJarUri(tempDir, warFilename);
logger.info("URI of ear to be generated : {}", warUri.toString());
// Prepare map for Freemarker (the same map is used for all templates)
Map<String, Object> freemarkerModel = createFreemarkerModel(mavenReferenceForWarGeneration, contextRoot);
Path warFile = generateWar(warFilename, tempDir, freemarkerModel);
return new File(warFile.toString());
}
private Path generateWar(String warFilename, Path tempDir, Map<String, Object> freemarkerModel) {
URI warUri = generateJarUri(tempDir, warFilename);
// build war file with files in TEMPLATE_WAR_DIR
try (FileSystem warFileSystem = FileSystems.newFileSystem(warUri, getFileSystemEnv())) { // warFileSystem is automatically closed
// Not so easy to list all files in TEMPLATE_WAR_DIR, because on production environment we're inside a jar,
// thus we cannot use NIO Files.walkFileTree() nor File.listFiles()
// So for the moment we just add all files in war manually
addClasspathTemplateToJarFile(TEMPLATE_WAR_DIR, "index.html.flt", freemarkerModel, warFileSystem);
createDirectoryInJarFile("WEB-INF", warFileSystem);
addClasspathFileToJarFile(TEMPLATE_WAR_DIR, "WEB-INF/web.xml", warFileSystem);
createDirectoryInJarFile("styles", warFileSystem);
addClasspathFileToJarFile(TEMPLATE_WAR_DIR, "styles/application.css", warFileSystem);
addClasspathFileToJarFile(TEMPLATE_WAR_DIR, "styles/footer.css", warFileSystem);
addClasspathFileToJarFile(TEMPLATE_WAR_DIR, "styles/gabarits.css", warFileSystem);
addClasspathFileToJarFile(TEMPLATE_WAR_DIR, "styles/orange-main.css", warFileSystem);
addClasspathFileToJarFile(TEMPLATE_WAR_DIR, "styles/signin.css", warFileSystem);
createDirectoryInJarFile("images", warFileSystem);
addClasspathFileToJarFile(TEMPLATE_WAR_DIR, "images/favicon.ico", warFileSystem);
addClasspathFileToJarFile(TEMPLATE_WAR_DIR, "images/orange_logo.jpg", warFileSystem);
} catch (IOException e) {
throw new TechnicalException("cannot create war filesystem", e);
}
return Paths.get(tempDir.toString(), warFilename);
}
private Map<String, String> getFileSystemEnv() {
// Prepare map for FileSystem creation
Map<String, String> env = new HashMap<>();
env.put("create", "true");
return env;
}
/**
* create the freemarker model with all ${} variables and values
*
* @param mavenReference
* the ear Maven reference, used to define war and ear file names
* @param contextRoot
* the war context root
* @return the generated model
*/
protected Map<String, Object> createFreemarkerModel(MavenReference mavenReference, String contextRoot) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("warFilename", mavenReference.getArtifactName().replaceFirst(".ear$", ".war"));
model.put("contextRoot", contextRoot);
model.put("groupid", mavenReference.getGroupId());
model.put("artifactid", mavenReference.getArtifactId());
model.put("version", mavenReference.getVersion());
model.put("classifier", mavenReference.getClassifier());
model.put("extension", mavenReference.getExtension());
model.put("buildDate", Calendar.getInstance().getTime());
return model;
}
/**
* generate a jar URI by using the syntax defined in java.net.JarURLConnection for example
* jar:file:/tmp/ear11111111/myappli-1.0.0-SNAPSHOT.ear
*/
protected URI generateJarUri(Path directory, String jarFile) {
StringBuilder uriString = new StringBuilder("jar:");
uriString.append(directory.toUri().toString());
uriString.append(jarFile);
return URI.create(uriString.toString());
}
/**
* Add a file from classpath to a jar filesystem
* @param templateDir the directory containing file
* @param filename the relative path to the file to be added
* @param jarFileSystem the jar file system (war/ear)
*/
protected void addClasspathFileToJarFile(String templateDir, String filename, FileSystem jarFileSystem) {
InputStream inputStream = getClass().getResourceAsStream(templateDir + filename);
if (inputStream == null) {
logger.debug("file : {}{} not found in classpath", templateDir, filename);
throw new TechnicalException("file " + templateDir + filename + " not found in classpath");
}
addInputStreamToJarFile(inputStream, filename, jarFileSystem);
}
/**
* Add a generated freemarker template to a jar filesystem
* @param templateDir the directory containing template file
* @param templateFile the relative path to the template (*.flt) to be added
* @param freemarkerModel the freemarker model to be used
* @param jarFileSystem the jar file system (war/ear)
*/
protected void addClasspathTemplateToJarFile(String templateDir, String templateFile, Map<String, Object> freemarkerModel, FileSystem jarFileSystem) {
String sourceFile;
if (templateFile.endsWith(".flt")) {
sourceFile = templateFile.replaceFirst(".flt$", "");
} else {
throw new TechnicalException("template file " + templateFile + " do not end with .flt");
}
logger.debug("generating {} content with freemarker", templateFile);
InputStream inputStream = generateFreemarkerContent(templateFile, freemarkerModel);
addInputStreamToJarFile(inputStream, sourceFile, jarFileSystem);
}
/**
* Generate a freemarker content based on a template and a model
* @param templateFile the template file
* @param freemarkerModel the model
* @return an InputStream
*/
protected InputStream generateFreemarkerContent(String templateFile, Map<String, Object> freemarkerModel) {
try {
String fileContent = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate(templateFile), freemarkerModel);
logger.debug("generated content:\n{}", fileContent);
InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes());
return inputStream;
} catch (IOException | TemplateException e) {
throw new TechnicalException("cannot generate template file " + templateFile, e);
}
}
/**
* add some content to jar file system
* @param inputStream the content to be added
* @param filename the filename (relative path) within jar file system
* @param jarFileSystem the jar file system (war/ear)
*/
private void addInputStreamToJarFile(InputStream inputStream, String filename, FileSystem jarFileSystem) {
Path internalFile = jarFileSystem.getPath(filename);
logger.debug("Adding file {} to {}", internalFile, jarFileSystem);
try {
Files.copy(inputStream, internalFile);
} catch (IOException e) {
throw new TechnicalException("cannot copy file " + filename + " in jar file " + jarFileSystem, e);
}
}
/**
* Copy a file in jarFileSystem. Path must be valid in filesystem
*
* @param dir
* the directory containing file
* @param sourceFile
* the file to be copied in jarFileSystem
* @param jarFileSystem
* the jar file system
*/
protected void addAbsoluteFileToJarFile(Path dir, Path sourceFile, FileSystem jarFileSystem) {
if (!sourceFile.startsWith(dir)) {
throw new TechnicalException("source file " + sourceFile + " is not in directory " + dir);
}
Path internalFile = jarFileSystem.getPath(dir.relativize(sourceFile).toString());
logger.debug("Adding file {} to {}", internalFile, jarFileSystem);
try {
Files.copy(sourceFile, internalFile);
} catch (IOException e) {
throw new TechnicalException("cannot copy file " + sourceFile + " in jar file " + jarFileSystem, e);
}
}
/**
* Create a directory in jarFileSystem. Path must be valid in fileSystem
*
* @param sourceDir
* the directory to be created in jarFileSystem
* @param jarFileSystem
* the jar file system
*/
protected void createDirectoryInJarFile(String sourceDir, FileSystem jarFileSystem) {
Path internalDir = jarFileSystem.getPath(sourceDir);
try {
Files.createDirectory(internalDir);
} catch (IOException e) {
throw new TechnicalException("cannot create directory " + internalDir + " in jar file " + jarFileSystem, e);
}
}
/**
* IOC
*
* @param configuration
*/
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}
}
| apache-2.0 |
tesshucom/subsonic-fx-player | subsonic-fx-player-impl/src/main/java/com/tesshu/subsonic/client/fx/view/podcast/control/PodcastControlImpl.java | 4817 | /**
* Copyright © 2017 tesshu.com (webmaster@tesshu.com)
*
* 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.tesshu.subsonic.client.fx.view.podcast.control;
import com.tesshu.subsonic.client.fx.view.TableViewNoSelectionModel;
import com.tesshu.subsonic.client.fx.view.podcast.PodcastControl;
import com.tesshu.subsonic.client.fx.view.podcast.PodcastRow;
import com.tesshu.subsonic.client.model.IEntity;
import com.tesshu.subsonic.client.model.IFileStructureAll;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javafx.beans.binding.Bindings;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Component
@Scope("singleton")
@Lazy
public final class PodcastControlImpl extends TableView<PodcastRow> implements PodcastControl {
private enum COLUMNS {
after, control, last, leaf, play, star
}
{
getStyleClass().add("sc-table");
getStyleClass().add("boder-wrapping");
AnchorPane.setTopAnchor(this, 0.0);
AnchorPane.setRightAnchor(this, 0.0);
AnchorPane.setLeftAnchor(this, 0.0);
AnchorPane.setBottomAnchor(this, 0.0);
setSelectionModel(new TableViewNoSelectionModel<>(this));
setFixedCellSize(30);
prefHeightProperty().bind(Bindings.size(getItems()).multiply(getFixedCellSize()).add(50));
setColumnResizePolicy(CONSTRAINED_RESIZE_POLICY);
TableColumn<PodcastRow, IFileStructureAll> colStar = createStarColumn(COLUMNS.star.name());
colStar.setCellValueFactory(new PropertyValueFactory<>("fileStructureAll"));
colStar.setCellFactory((column) -> {
return new CellStar();
});
TableColumn<PodcastRow, IEntity> colPlay = createIconColumn(COLUMNS.play.name());
colPlay.setCellValueFactory(new PropertyValueFactory<>("entity"));
colPlay.setCellFactory((column) -> {
return new CellPlay();
});
TableColumn<PodcastRow, IEntity> colLast = createIconColumn(COLUMNS.last.name());
colLast.setCellValueFactory(new PropertyValueFactory<>("entity"));
colLast.setCellFactory((column) -> {
return new CellLast();
});
TableColumn<PodcastRow, IEntity> colAfter = createIconColumn(COLUMNS.after.name());
colAfter.setCellValueFactory(new PropertyValueFactory<>("entity"));
colAfter.setCellFactory((column) -> {
return new CellAfter();
});
TableColumn<PodcastRow, IEntity> colLeaf = new TableColumn<>(null);
colLeaf.setCellValueFactory(new PropertyValueFactory<>("entity"));
colLeaf.setId(COLUMNS.leaf.name());
colLeaf.setSortable(false);
colLeaf.setCellFactory((column) -> {
return new CellLeaf();
});
int colWidth = 24;
setWidth(colStar, 30);
setWidth(colPlay, colWidth);
setWidth(colLast, colWidth);
setWidth(colAfter, colWidth);
getColumns().addAll(colStar, colPlay, colLast, colAfter, colLeaf);
}
@Override
public TableView getInstance() {
return this;
}
@Override
public void stateChanged(IFileStructureAll fileStructureAll) {
for (PodcastRow row : getItems()) {
row.stateChanged(fileStructureAll);
}
refresh();
}
private TableColumn<PodcastRow, IEntity> createIconColumn(String id) {
TableColumn<PodcastRow, IEntity> column = new TableColumn<>(null);
column.setCellValueFactory(new PropertyValueFactory<>("fileStructureAll"));
column.setId(id);
column.setSortable(false);
column.setResizable(false);
return column;
}
private TableColumn<PodcastRow, IFileStructureAll> createStarColumn(String id) {
TableColumn<PodcastRow, IFileStructureAll> column = new TableColumn<>(null);
column.setCellValueFactory(new PropertyValueFactory<>("fileStructureAll"));
column.setId(id);
column.setMaxWidth(30);
column.setMinWidth(30);
column.setPrefWidth(30);
column.setSortable(false);
column.setResizable(false);
return column;
}
private void setWidth(TableColumn<?, ?> column, int width) {
column.setMaxWidth(width);
column.setMinWidth(width);
column.setPrefWidth(width);
column.setResizable(false);
}
}
| apache-2.0 |
SpineEventEngine/examples-java | kanban-board/src/main/java/io/spine/examples/kanban/server/board/BoardInitRepository.java | 1870 | /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.examples.kanban.server.board;
import io.spine.examples.kanban.BoardId;
import io.spine.examples.kanban.BoardInit;
import io.spine.examples.kanban.event.ColumnCreated;
import io.spine.server.procman.ProcessManagerRepository;
import static io.spine.server.route.EventRoute.noTargets;
import static io.spine.server.route.EventRoute.withId;
/**
* Manages instances of {@link BoardInitProcess}.
*/
public final class BoardInitRepository
extends ProcessManagerRepository<BoardId, BoardInitProcess, BoardInit> {
public BoardInitRepository() {
super();
eventRouting().route(ColumnCreated.class,
(event, context) -> event.getBoardInit()
? withId(event.getBoard())
: noTargets());
}
}
| apache-2.0 |
emrahkocaman/hazelcast | hazelcast/src/main/java/com/hazelcast/mapreduce/impl/task/MemberAssigningJobProcessInformationImpl.java | 2019 | /*
* 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.mapreduce.impl.task;
import com.hazelcast.mapreduce.JobPartitionState;
import com.hazelcast.nio.Address;
import static com.hazelcast.mapreduce.JobPartitionState.State.WAITING;
import static com.hazelcast.mapreduce.impl.MapReduceUtil.stateChange;
/**
* This {@link com.hazelcast.mapreduce.impl.task.JobProcessInformationImpl} extending class is
* used in non partitionId based map reduce tasks where partitions are kind of simulated using
* a unique id per member.
*/
public class MemberAssigningJobProcessInformationImpl
extends JobProcessInformationImpl {
public MemberAssigningJobProcessInformationImpl(int partitionCount, JobSupervisor supervisor) {
super(partitionCount, supervisor);
}
public int assignMemberId(Address address, String memberUuid, JobTaskConfiguration configuration) {
JobPartitionState[] partitionStates = getPartitionStates();
for (int i = 0; i < partitionStates.length; i++) {
JobPartitionState partitionState = partitionStates[i];
if (partitionState == null || partitionState.getState() == JobPartitionState.State.WAITING) {
// Seems unassigned so let try to use it
if (stateChange(address, i, WAITING, this, configuration) != null) {
return i;
}
}
}
return -1;
}
}
| apache-2.0 |
triniti/schemas | build/php/src/Triniti/Schemas/Curator/Request/RenderWidgetResponseV1.php | 3577 | <?php
declare(strict_types=1);
// @link http://schemas.triniti.io/json-schema/triniti/curator/request/render-widget-response/1-0-0.json#
namespace Triniti\Schemas\Curator\Request;
use Gdbots\Pbj\AbstractMessage;
use Gdbots\Pbj\FieldBuilder as Fb;
use Gdbots\Pbj\Schema;
use Gdbots\Pbj\Type as T;
use Gdbots\Schemas\Pbjx\Mixin\Response\ResponseV1Mixin as GdbotsPbjxResponseV1Mixin;
final class RenderWidgetResponseV1 extends AbstractMessage
{
const SCHEMA_ID = 'pbj:triniti:curator:request:render-widget-response:1-0-0';
const SCHEMA_CURIE = 'triniti:curator:request:render-widget-response';
const SCHEMA_CURIE_MAJOR = 'triniti:curator:request:render-widget-response:v1';
const MIXINS = [
'gdbots:pbjx:mixin:response:v1',
'gdbots:pbjx:mixin:response',
];
use GdbotsPbjxResponseV1Mixin;
protected static function defineSchema(): Schema
{
return new Schema(self::SCHEMA_ID, __CLASS__,
[
Fb::create('response_id', T\UuidType::create())
->required()
->build(),
Fb::create('created_at', T\MicrotimeType::create())
->build(),
/*
* Multi-tenant apps can use this field to track the tenant id.
*/
Fb::create('ctx_tenant_id', T\StringType::create())
->pattern('^[\w\/\.:-]+$')
->build(),
Fb::create('ctx_request_ref', T\MessageRefType::create())
->build(),
/*
* The "ctx_request" is the actual request object that "ctx_request_ref" refers to.
* In some cases it's useful for request handlers to copy the request into the response
* so the requestor has everything in one message. This will NOT always be populated.
* A common use case is search request/response cycles where you want to know what the
* search criteria was so you can render that along with the results.
*/
Fb::create('ctx_request', T\MessageType::create())
->anyOfCuries([
'gdbots:pbjx:mixin:request',
])
->build(),
Fb::create('ctx_correlator_ref', T\MessageRefType::create())
->build(),
/*
* Responses can include "dereferenced" messages to prevent
* the consumer from needing to make multiple HTTP requests.
* It is up to the consumer to make use of the dereferenced
* messages if/when they are provided.
*/
Fb::create('derefs', T\MessageType::create())
->asAMap()
->build(),
/*
* @link https://en.wikipedia.org/wiki/HATEOAS
*/
Fb::create('links', T\TextType::create())
->asAMap()
->build(),
Fb::create('metas', T\TextType::create())
->asAMap()
->build(),
Fb::create('html', T\MediumTextType::create())
->build(),
Fb::create('search_response', T\MessageType::create())
->anyOfCuries([
'triniti:curator:mixin:widget-search-response',
])
->build(),
],
self::MIXINS
);
}
}
| apache-2.0 |
kohsah/akomantoso-lib | src/main/java/org/akomantoso/schema/v3/release/EfficacyMod.java | 1893 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.05.20 at 03:05:24 PM IST
//
package org.akomantoso.schema.v3.release;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0}modificationType">
* <attGroup ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0}efficacyModType"/>
* <anyAttribute processContents='lax' namespace='##other'/>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "efficacyMod")
public class EfficacyMod
extends ModificationType
{
@XmlAttribute(name = "type", required = true)
protected EfficacyMods type;
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link EfficacyMods }
*
*/
public EfficacyMods getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link EfficacyMods }
*
*/
public void setType(EfficacyMods value) {
this.type = value;
}
}
| apache-2.0 |
istio/go-control-plane | envoy/config/filter/http/adaptive_concurrency/v2alpha/adaptive_concurrency.pb.go | 32113 | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.14.0
// source: envoy/config/filter/http/adaptive_concurrency/v2alpha/adaptive_concurrency.proto
package envoy_config_filter_http_adaptive_concurrency_v2alpha
import (
_ "github.com/cncf/xds/go/udpa/annotations"
core "github.com/envoyproxy/go-control-plane/envoy/api/v2/core"
_type "github.com/envoyproxy/go-control-plane/envoy/type"
_ "github.com/envoyproxy/protoc-gen-validate/validate"
proto "github.com/golang/protobuf/proto"
duration "github.com/golang/protobuf/ptypes/duration"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
// Configuration parameters for the gradient controller.
type GradientControllerConfig struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The percentile to use when summarizing aggregated samples. Defaults to p50.
SampleAggregatePercentile *_type.Percent `protobuf:"bytes,1,opt,name=sample_aggregate_percentile,json=sampleAggregatePercentile,proto3" json:"sample_aggregate_percentile,omitempty"`
ConcurrencyLimitParams *GradientControllerConfig_ConcurrencyLimitCalculationParams `protobuf:"bytes,2,opt,name=concurrency_limit_params,json=concurrencyLimitParams,proto3" json:"concurrency_limit_params,omitempty"`
MinRttCalcParams *GradientControllerConfig_MinimumRTTCalculationParams `protobuf:"bytes,3,opt,name=min_rtt_calc_params,json=minRttCalcParams,proto3" json:"min_rtt_calc_params,omitempty"`
}
func (x *GradientControllerConfig) Reset() {
*x = GradientControllerConfig{}
if protoimpl.UnsafeEnabled {
mi := &file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GradientControllerConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GradientControllerConfig) ProtoMessage() {}
func (x *GradientControllerConfig) ProtoReflect() protoreflect.Message {
mi := &file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GradientControllerConfig.ProtoReflect.Descriptor instead.
func (*GradientControllerConfig) Descriptor() ([]byte, []int) {
return file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescGZIP(), []int{0}
}
func (x *GradientControllerConfig) GetSampleAggregatePercentile() *_type.Percent {
if x != nil {
return x.SampleAggregatePercentile
}
return nil
}
func (x *GradientControllerConfig) GetConcurrencyLimitParams() *GradientControllerConfig_ConcurrencyLimitCalculationParams {
if x != nil {
return x.ConcurrencyLimitParams
}
return nil
}
func (x *GradientControllerConfig) GetMinRttCalcParams() *GradientControllerConfig_MinimumRTTCalculationParams {
if x != nil {
return x.MinRttCalcParams
}
return nil
}
type AdaptiveConcurrency struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Types that are assignable to ConcurrencyControllerConfig:
// *AdaptiveConcurrency_GradientControllerConfig
ConcurrencyControllerConfig isAdaptiveConcurrency_ConcurrencyControllerConfig `protobuf_oneof:"concurrency_controller_config"`
// If set to false, the adaptive concurrency filter will operate as a pass-through filter. If the
// message is unspecified, the filter will be enabled.
Enabled *core.RuntimeFeatureFlag `protobuf:"bytes,2,opt,name=enabled,proto3" json:"enabled,omitempty"`
}
func (x *AdaptiveConcurrency) Reset() {
*x = AdaptiveConcurrency{}
if protoimpl.UnsafeEnabled {
mi := &file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AdaptiveConcurrency) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AdaptiveConcurrency) ProtoMessage() {}
func (x *AdaptiveConcurrency) ProtoReflect() protoreflect.Message {
mi := &file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AdaptiveConcurrency.ProtoReflect.Descriptor instead.
func (*AdaptiveConcurrency) Descriptor() ([]byte, []int) {
return file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescGZIP(), []int{1}
}
func (m *AdaptiveConcurrency) GetConcurrencyControllerConfig() isAdaptiveConcurrency_ConcurrencyControllerConfig {
if m != nil {
return m.ConcurrencyControllerConfig
}
return nil
}
func (x *AdaptiveConcurrency) GetGradientControllerConfig() *GradientControllerConfig {
if x, ok := x.GetConcurrencyControllerConfig().(*AdaptiveConcurrency_GradientControllerConfig); ok {
return x.GradientControllerConfig
}
return nil
}
func (x *AdaptiveConcurrency) GetEnabled() *core.RuntimeFeatureFlag {
if x != nil {
return x.Enabled
}
return nil
}
type isAdaptiveConcurrency_ConcurrencyControllerConfig interface {
isAdaptiveConcurrency_ConcurrencyControllerConfig()
}
type AdaptiveConcurrency_GradientControllerConfig struct {
// Gradient concurrency control will be used.
GradientControllerConfig *GradientControllerConfig `protobuf:"bytes,1,opt,name=gradient_controller_config,json=gradientControllerConfig,proto3,oneof"`
}
func (*AdaptiveConcurrency_GradientControllerConfig) isAdaptiveConcurrency_ConcurrencyControllerConfig() {
}
// Parameters controlling the periodic recalculation of the concurrency limit from sampled request
// latencies.
type GradientControllerConfig_ConcurrencyLimitCalculationParams struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The allowed upper-bound on the calculated concurrency limit. Defaults to 1000.
MaxConcurrencyLimit *wrappers.UInt32Value `protobuf:"bytes,2,opt,name=max_concurrency_limit,json=maxConcurrencyLimit,proto3" json:"max_concurrency_limit,omitempty"`
// The period of time samples are taken to recalculate the concurrency limit.
ConcurrencyUpdateInterval *duration.Duration `protobuf:"bytes,3,opt,name=concurrency_update_interval,json=concurrencyUpdateInterval,proto3" json:"concurrency_update_interval,omitempty"`
}
func (x *GradientControllerConfig_ConcurrencyLimitCalculationParams) Reset() {
*x = GradientControllerConfig_ConcurrencyLimitCalculationParams{}
if protoimpl.UnsafeEnabled {
mi := &file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GradientControllerConfig_ConcurrencyLimitCalculationParams) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GradientControllerConfig_ConcurrencyLimitCalculationParams) ProtoMessage() {}
func (x *GradientControllerConfig_ConcurrencyLimitCalculationParams) ProtoReflect() protoreflect.Message {
mi := &file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GradientControllerConfig_ConcurrencyLimitCalculationParams.ProtoReflect.Descriptor instead.
func (*GradientControllerConfig_ConcurrencyLimitCalculationParams) Descriptor() ([]byte, []int) {
return file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescGZIP(), []int{0, 0}
}
func (x *GradientControllerConfig_ConcurrencyLimitCalculationParams) GetMaxConcurrencyLimit() *wrappers.UInt32Value {
if x != nil {
return x.MaxConcurrencyLimit
}
return nil
}
func (x *GradientControllerConfig_ConcurrencyLimitCalculationParams) GetConcurrencyUpdateInterval() *duration.Duration {
if x != nil {
return x.ConcurrencyUpdateInterval
}
return nil
}
// Parameters controlling the periodic minRTT recalculation.
// [#next-free-field: 6]
type GradientControllerConfig_MinimumRTTCalculationParams struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The time interval between recalculating the minimum request round-trip time.
Interval *duration.Duration `protobuf:"bytes,1,opt,name=interval,proto3" json:"interval,omitempty"`
// The number of requests to aggregate/sample during the minRTT recalculation window before
// updating. Defaults to 50.
RequestCount *wrappers.UInt32Value `protobuf:"bytes,2,opt,name=request_count,json=requestCount,proto3" json:"request_count,omitempty"`
// Randomized time delta that will be introduced to the start of the minRTT calculation window.
// This is represented as a percentage of the interval duration. Defaults to 15%.
//
// Example: If the interval is 10s and the jitter is 15%, the next window will begin
// somewhere in the range (10s - 11.5s).
Jitter *_type.Percent `protobuf:"bytes,3,opt,name=jitter,proto3" json:"jitter,omitempty"`
// The concurrency limit set while measuring the minRTT. Defaults to 3.
MinConcurrency *wrappers.UInt32Value `protobuf:"bytes,4,opt,name=min_concurrency,json=minConcurrency,proto3" json:"min_concurrency,omitempty"`
// Amount added to the measured minRTT to add stability to the concurrency limit during natural
// variability in latency. This is expressed as a percentage of the measured value and can be
// adjusted to allow more or less tolerance to the sampled latency values.
//
// Defaults to 25%.
Buffer *_type.Percent `protobuf:"bytes,5,opt,name=buffer,proto3" json:"buffer,omitempty"`
}
func (x *GradientControllerConfig_MinimumRTTCalculationParams) Reset() {
*x = GradientControllerConfig_MinimumRTTCalculationParams{}
if protoimpl.UnsafeEnabled {
mi := &file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GradientControllerConfig_MinimumRTTCalculationParams) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GradientControllerConfig_MinimumRTTCalculationParams) ProtoMessage() {}
func (x *GradientControllerConfig_MinimumRTTCalculationParams) ProtoReflect() protoreflect.Message {
mi := &file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GradientControllerConfig_MinimumRTTCalculationParams.ProtoReflect.Descriptor instead.
func (*GradientControllerConfig_MinimumRTTCalculationParams) Descriptor() ([]byte, []int) {
return file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescGZIP(), []int{0, 1}
}
func (x *GradientControllerConfig_MinimumRTTCalculationParams) GetInterval() *duration.Duration {
if x != nil {
return x.Interval
}
return nil
}
func (x *GradientControllerConfig_MinimumRTTCalculationParams) GetRequestCount() *wrappers.UInt32Value {
if x != nil {
return x.RequestCount
}
return nil
}
func (x *GradientControllerConfig_MinimumRTTCalculationParams) GetJitter() *_type.Percent {
if x != nil {
return x.Jitter
}
return nil
}
func (x *GradientControllerConfig_MinimumRTTCalculationParams) GetMinConcurrency() *wrappers.UInt32Value {
if x != nil {
return x.MinConcurrency
}
return nil
}
func (x *GradientControllerConfig_MinimumRTTCalculationParams) GetBuffer() *_type.Percent {
if x != nil {
return x.Buffer
}
return nil
}
var File_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto protoreflect.FileDescriptor
var file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDesc = []byte{
0x0a, 0x50, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x66,
0x69, 0x6c, 0x74, 0x65, 0x72, 0x2f, 0x68, 0x74, 0x74, 0x70, 0x2f, 0x61, 0x64, 0x61, 0x70, 0x74,
0x69, 0x76, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x2f,
0x76, 0x32, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2f, 0x61, 0x64, 0x61, 0x70, 0x74, 0x69, 0x76, 0x65,
0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x12, 0x35, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67,
0x2e, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x61, 0x64, 0x61,
0x70, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63,
0x79, 0x2e, 0x76, 0x32, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x1a, 0x1c, 0x65, 0x6e, 0x76, 0x6f, 0x79,
0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x32, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x62, 0x61, 0x73,
0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x18, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74,
0x79, 0x70, 0x65, 0x2f, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x1a, 0x1e, 0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x73, 0x2f, 0x6d, 0x69, 0x67, 0x72, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x1a, 0x1d, 0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x73, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x1a, 0x17, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, 0x76, 0x61, 0x6c, 0x69, 0x64,
0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x8f, 0x08, 0x0a, 0x18, 0x47, 0x72,
0x61, 0x64, 0x69, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72,
0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x53, 0x0a, 0x1b, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65,
0x5f, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x65, 0x5f, 0x70, 0x65, 0x72, 0x63, 0x65,
0x6e, 0x74, 0x69, 0x6c, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x65, 0x6e,
0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74,
0x52, 0x19, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74,
0x65, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x69, 0x6c, 0x65, 0x12, 0xb5, 0x01, 0x0a, 0x18,
0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x5f, 0x6c, 0x69, 0x6d, 0x69,
0x74, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x71,
0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x66, 0x69,
0x6c, 0x74, 0x65, 0x72, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x61, 0x64, 0x61, 0x70, 0x74, 0x69,
0x76, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x2e, 0x76,
0x32, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x47, 0x72, 0x61, 0x64, 0x69, 0x65, 0x6e, 0x74, 0x43,
0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e,
0x43, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x4c, 0x69, 0x6d, 0x69, 0x74,
0x43, 0x61, 0x6c, 0x63, 0x75, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x72, 0x61, 0x6d,
0x73, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x16, 0x63, 0x6f, 0x6e,
0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x50, 0x61, 0x72,
0x61, 0x6d, 0x73, 0x12, 0xa4, 0x01, 0x0a, 0x13, 0x6d, 0x69, 0x6e, 0x5f, 0x72, 0x74, 0x74, 0x5f,
0x63, 0x61, 0x6c, 0x63, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28,
0x0b, 0x32, 0x6b, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67,
0x2e, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x61, 0x64, 0x61,
0x70, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63,
0x79, 0x2e, 0x76, 0x32, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x47, 0x72, 0x61, 0x64, 0x69, 0x65,
0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66,
0x69, 0x67, 0x2e, 0x4d, 0x69, 0x6e, 0x69, 0x6d, 0x75, 0x6d, 0x52, 0x54, 0x54, 0x43, 0x61, 0x6c,
0x63, 0x75, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x42, 0x08,
0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x10, 0x6d, 0x69, 0x6e, 0x52, 0x74, 0x74,
0x43, 0x61, 0x6c, 0x63, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x1a, 0xe5, 0x01, 0x0a, 0x21, 0x43,
0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x43,
0x61, 0x6c, 0x63, 0x75, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73,
0x12, 0x59, 0x0a, 0x15, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65,
0x6e, 0x63, 0x79, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32,
0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa,
0x42, 0x04, 0x2a, 0x02, 0x20, 0x00, 0x52, 0x13, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x63, 0x75,
0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x12, 0x65, 0x0a, 0x1b, 0x63,
0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74,
0x65, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b,
0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0a, 0xfa, 0x42, 0x07,
0xaa, 0x01, 0x04, 0x08, 0x01, 0x2a, 0x00, 0x52, 0x19, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72,
0x65, 0x6e, 0x63, 0x79, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76,
0x61, 0x6c, 0x1a, 0xd6, 0x02, 0x0a, 0x1b, 0x4d, 0x69, 0x6e, 0x69, 0x6d, 0x75, 0x6d, 0x52, 0x54,
0x54, 0x43, 0x61, 0x6c, 0x63, 0x75, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x72, 0x61,
0x6d, 0x73, 0x12, 0x41, 0x0a, 0x08, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x01,
0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42,
0x0a, 0xfa, 0x42, 0x07, 0xaa, 0x01, 0x04, 0x08, 0x01, 0x2a, 0x00, 0x52, 0x08, 0x69, 0x6e, 0x74,
0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x4a, 0x0a, 0x0d, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55,
0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x2a,
0x02, 0x20, 0x00, 0x52, 0x0c, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x43, 0x6f, 0x75, 0x6e,
0x74, 0x12, 0x2b, 0x0a, 0x06, 0x6a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28,
0x0b, 0x32, 0x13, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x50,
0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x6a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x12, 0x4e,
0x0a, 0x0f, 0x6d, 0x69, 0x6e, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63,
0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32,
0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x2a, 0x02, 0x20, 0x00, 0x52, 0x0e,
0x6d, 0x69, 0x6e, 0x43, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x12, 0x2b,
0x0a, 0x06, 0x62, 0x75, 0x66, 0x66, 0x65, 0x72, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13,
0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x50, 0x65, 0x72, 0x63,
0x65, 0x6e, 0x74, 0x52, 0x06, 0x62, 0x75, 0x66, 0x66, 0x65, 0x72, 0x22, 0x98, 0x02, 0x0a, 0x13,
0x41, 0x64, 0x61, 0x70, 0x74, 0x69, 0x76, 0x65, 0x43, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65,
0x6e, 0x63, 0x79, 0x12, 0x99, 0x01, 0x0a, 0x1a, 0x67, 0x72, 0x61, 0x64, 0x69, 0x65, 0x6e, 0x74,
0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x5f, 0x63, 0x6f, 0x6e, 0x66,
0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x4f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79,
0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x2e, 0x68,
0x74, 0x74, 0x70, 0x2e, 0x61, 0x64, 0x61, 0x70, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x63, 0x6f, 0x6e,
0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x2e, 0x76, 0x32, 0x61, 0x6c, 0x70, 0x68, 0x61,
0x2e, 0x47, 0x72, 0x61, 0x64, 0x69, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c,
0x6c, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01,
0x02, 0x10, 0x01, 0x48, 0x00, 0x52, 0x18, 0x67, 0x72, 0x61, 0x64, 0x69, 0x65, 0x6e, 0x74, 0x43,
0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12,
0x3f, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b,
0x32, 0x25, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e,
0x63, 0x6f, 0x72, 0x65, 0x2e, 0x52, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x46, 0x65, 0x61, 0x74,
0x75, 0x72, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64,
0x42, 0x24, 0x0a, 0x1d, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x5f,
0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69,
0x67, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0xa6, 0x01, 0x0a, 0x43, 0x69, 0x6f, 0x2e, 0x65, 0x6e,
0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63,
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x2e, 0x68, 0x74, 0x74,
0x70, 0x2e, 0x61, 0x64, 0x61, 0x70, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75,
0x72, 0x72, 0x65, 0x6e, 0x63, 0x79, 0x2e, 0x76, 0x32, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x42, 0x18,
0x41, 0x64, 0x61, 0x70, 0x74, 0x69, 0x76, 0x65, 0x43, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65,
0x6e, 0x63, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0xf2, 0x98, 0xfe, 0x8f, 0x05, 0x37,
0x12, 0x35, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f,
0x6e, 0x73, 0x2e, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x2e,
0x61, 0x64, 0x61, 0x70, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72,
0x65, 0x6e, 0x63, 0x79, 0x2e, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x01, 0x62,
0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescOnce sync.Once
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescData = file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDesc
)
func file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescGZIP() []byte {
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescOnce.Do(func() {
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescData = protoimpl.X.CompressGZIP(file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescData)
})
return file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDescData
}
var file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_goTypes = []interface{}{
(*GradientControllerConfig)(nil), // 0: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig
(*AdaptiveConcurrency)(nil), // 1: envoy.config.filter.http.adaptive_concurrency.v2alpha.AdaptiveConcurrency
(*GradientControllerConfig_ConcurrencyLimitCalculationParams)(nil), // 2: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.ConcurrencyLimitCalculationParams
(*GradientControllerConfig_MinimumRTTCalculationParams)(nil), // 3: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.MinimumRTTCalculationParams
(*_type.Percent)(nil), // 4: envoy.type.Percent
(*core.RuntimeFeatureFlag)(nil), // 5: envoy.api.v2.core.RuntimeFeatureFlag
(*wrappers.UInt32Value)(nil), // 6: google.protobuf.UInt32Value
(*duration.Duration)(nil), // 7: google.protobuf.Duration
}
var file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_depIdxs = []int32{
4, // 0: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.sample_aggregate_percentile:type_name -> envoy.type.Percent
2, // 1: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.concurrency_limit_params:type_name -> envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.ConcurrencyLimitCalculationParams
3, // 2: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.min_rtt_calc_params:type_name -> envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.MinimumRTTCalculationParams
0, // 3: envoy.config.filter.http.adaptive_concurrency.v2alpha.AdaptiveConcurrency.gradient_controller_config:type_name -> envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig
5, // 4: envoy.config.filter.http.adaptive_concurrency.v2alpha.AdaptiveConcurrency.enabled:type_name -> envoy.api.v2.core.RuntimeFeatureFlag
6, // 5: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.ConcurrencyLimitCalculationParams.max_concurrency_limit:type_name -> google.protobuf.UInt32Value
7, // 6: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.ConcurrencyLimitCalculationParams.concurrency_update_interval:type_name -> google.protobuf.Duration
7, // 7: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.MinimumRTTCalculationParams.interval:type_name -> google.protobuf.Duration
6, // 8: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.MinimumRTTCalculationParams.request_count:type_name -> google.protobuf.UInt32Value
4, // 9: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.MinimumRTTCalculationParams.jitter:type_name -> envoy.type.Percent
6, // 10: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.MinimumRTTCalculationParams.min_concurrency:type_name -> google.protobuf.UInt32Value
4, // 11: envoy.config.filter.http.adaptive_concurrency.v2alpha.GradientControllerConfig.MinimumRTTCalculationParams.buffer:type_name -> envoy.type.Percent
12, // [12:12] is the sub-list for method output_type
12, // [12:12] is the sub-list for method input_type
12, // [12:12] is the sub-list for extension type_name
12, // [12:12] is the sub-list for extension extendee
0, // [0:12] is the sub-list for field type_name
}
func init() {
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_init()
}
func file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_init() {
if File_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GradientControllerConfig); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AdaptiveConcurrency); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GradientControllerConfig_ConcurrencyLimitCalculationParams); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GradientControllerConfig_MinimumRTTCalculationParams); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes[1].OneofWrappers = []interface{}{
(*AdaptiveConcurrency_GradientControllerConfig)(nil),
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_goTypes,
DependencyIndexes: file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_depIdxs,
MessageInfos: file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_msgTypes,
}.Build()
File_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto = out.File
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_rawDesc = nil
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_goTypes = nil
file_envoy_config_filter_http_adaptive_concurrency_v2alpha_adaptive_concurrency_proto_depIdxs = nil
}
| apache-2.0 |
jaschenk/jeffaschenk-commons | src/main/java/jeffaschenk/commons/system/internal/file/services/extract/ExtractLifecycleUpdateDetermination.java | 515 | package jeffaschenk.commons.system.internal.file.services.extract;
import jeffaschenk.commons.touchpoint.model.RootElement;
/**
* Extract Processing Service Interface
* <p/>
* Provides Extract Processing Services to Application Framework.
*/
public interface ExtractLifecycleUpdateDetermination {
/**
* Provide indication if Update is Pending or not.
*
* If Pending, no update will occur against the Database.
*
*/
boolean isUpdatePending(RootElement extractEntity);
}
| apache-2.0 |
ProxyFoo/ProxyFoo | source/ProxyFoo/Core/Bindings/ImplicitUserConversionValueBinding.cs | 2433 | #region Apache License Notice
// Copyright © 2014, Silverlake Software LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace ProxyFoo.Core.Bindings
{
public class ImplicitUserConversionValueBinding : DuckValueBindingOption
{
readonly MethodInfo _method;
public static DuckValueBindingOption TryBind(Type fromType, Type toType)
{
Type coreFromType = Nullable.GetUnderlyingType(fromType);
Type coreToType = Nullable.GetUnderlyingType(toType);
// Cannot convert a nullable value type to a non-nullable value type
if (coreFromType!=null && coreToType==null && toType.IsValueType())
return null;
Type finalFromType = coreFromType ?? fromType;
Type finalToType = coreToType ?? toType;
var method = finalFromType.GetMethod("op_Implicit", new[] {finalFromType});
if (method==null)
{
method = finalToType.GetMethod("op_Implicit", new[] {finalFromType});
if (method==null)
return null;
}
DuckValueBindingOption userConvBinding = new ImplicitUserConversionValueBinding(method);
return coreFromType!=null ? new ImplicitNullableValueBinding(true, fromType, toType, coreToType, userConvBinding) : userConvBinding;
}
ImplicitUserConversionValueBinding(MethodInfo method)
{
_method = method;
}
public override bool Bindable
{
get { return true; }
}
public override int Score
{
get { return 1; }
}
public override void GenerateConversion(IProxyModuleCoderAccess proxyModule, ILGenerator gen)
{
gen.Emit(OpCodes.Call, _method);
}
}
} | apache-2.0 |
xamarin/MyCompany | SharedCode/MyCompany.Visitors.Client/DocumentResponse/Team.cs | 632 |
namespace MyCompany.Visitors.Client
{
using System.Collections.Generic;
/// <summary>
/// Team entity
/// </summary>
public class Team
{
/// <summary>
/// UniqueId
/// </summary>
public int TeamId { get; set; }
/// <summary>
/// ManagerId
/// </summary>
public int ManagerId { get; set; }
/// <summary>
/// Manager
/// </summary>
public Employee Manager { get; set; }
/// <summary>
/// Employees
/// </summary>
public ICollection<Employee> Employees { get; set; }
}
}
| apache-2.0 |
nafae/developer | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201406/video/VideoTargetingGroupCriterionService.java | 820 | /**
* VideoTargetingGroupCriterionService.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201406.video;
public interface VideoTargetingGroupCriterionService extends javax.xml.rpc.Service {
public java.lang.String getVideoTargetingGroupCriterionServiceInterfacePortAddress();
public com.google.api.ads.adwords.axis.v201406.video.VideoTargetingGroupCriterionServiceInterface getVideoTargetingGroupCriterionServiceInterfacePort() throws javax.xml.rpc.ServiceException;
public com.google.api.ads.adwords.axis.v201406.video.VideoTargetingGroupCriterionServiceInterface getVideoTargetingGroupCriterionServiceInterfacePort(java.net.URL portAddress) throws javax.xml.rpc.ServiceException;
}
| apache-2.0 |
ly2513/YPPHP | system/ThirdParty/Kint/inc/kintParser.class.php | 18376 | <?php
abstract class kintParser extends kintVariableData {
private static $_level = 0;
private static $_customDataTypes;
private static $_objectParsers;
private static $_objects;
private static $_marker;
private static $_skipAlternatives = FALSE;
private static $_placeFullStringInValue = FALSE;
private static function _init()
{
$fh = opendir( KINT_DIR . 'parsers/custom/' );
while ( $fileName = readdir( $fh ) ) {
if ( substr( $fileName, -4 ) !== '.php' ) { continue;
}
require KINT_DIR . 'parsers/custom/' . $fileName;
self::$_customDataTypes[] = substr( $fileName, 0, -4 );
}
$fh = opendir( KINT_DIR . 'parsers/objects/' );
while ( $fileName = readdir( $fh ) ) {
if ( substr( $fileName, -4 ) !== '.php' ) { continue;
}
require KINT_DIR . 'parsers/objects/' . $fileName;
self::$_objectParsers[] = substr( $fileName, 0, -4 );
}
}
public static function reset()
{
self::$_level = 0;
self::$_objects = self::$_marker = NULL;
}
/**
* main and usually single method a custom parser must implement
*
* @param mixed $variable
*
* @return mixed [!!!] false is returned if the variable is not of current type
*/
abstract protected function _parse( & $variable );
/**
* the only public entry point to return a parsed representation of a variable
*
* @static
*
* @param $variable
* @param null $name
*
* @throws Exception
* @return \kintParser
*/
final public static function factory( & $variable, $name = NULL )
{
isset( self::$_customDataTypes ) or self::_init();
# save internal data to revert after dumping to properly handle recursions etc
$revert = array(
'level' => self::$_level,
'objects' => self::$_objects,
);
self::$_level++;
$varData = new kintVariableData;
$varData->name = $name;
# first parse the variable based on its type
$varType = gettype( $variable );
$varType === 'unknown type' and $varType = 'unknown'; # PHP 5.4 inconsistency
$methodName = '_parse_' . $varType;
# objects can be presented in a different way altogether, INSTEAD, not ALONGSIDE the generic parser
if ( $varType === 'object' ) {
foreach ( self::$_objectParsers as $parserClass ) {
$className = 'Kint_Objects_' . $parserClass;
/**
* @var $object KintObject
*/
$object = new $className;
if ( ( $alternativeTabs = $object->parse( $variable ) ) !== FALSE ) {
self::$_skipAlternatives = TRUE;
$alternativeDisplay = new kintVariableData;
$alternativeDisplay->type = $object->name;
$alternativeDisplay->value = $object->value;
$alternativeDisplay->name = $name;
foreach ( $alternativeTabs as $name => $values ) {
$alternative = kintParser::factory( $values );
$alternative->type = $name;
if ( Kint::enabled() === Kint::MODE_RICH ) {
empty( $alternative->value ) and $alternative->value = $alternative->extendedValue;
$alternativeDisplay->_alternatives[] = $alternative;
} else {
$alternativeDisplay->extendedValue[] = $alternative;
}
}
self::$_skipAlternatives = FALSE;
self::$_level = $revert['level'];
self::$_objects = $revert['objects'];
return $alternativeDisplay;
}
}
}
# base type parser returning false means "stop processing further": e.g. recursion
if ( self::$methodName( $variable, $varData ) === FALSE ) {
self::$_level--;
return $varData;
}
if ( Kint::enabled() === Kint::MODE_RICH && ! self::$_skipAlternatives ) {
# if an alternative returns something that can be represented in an alternative way, don't :)
self::$_skipAlternatives = TRUE;
# now check whether the variable can be represented in a different way
foreach ( self::$_customDataTypes as $parserClass ) {
$className = 'Kint_Parsers_' . $parserClass;
/**
* @var $parser kintParser
*/
$parser = new $className;
$parser->name = $name; # the parser may overwrite the name value, so set it first
if ( $parser->_parse( $variable ) !== FALSE ) {
$varData->_alternatives[] = $parser;
}
}
# if alternatives exist, push extendedValue to their front and display it as one of alternatives
if ( ! empty( $varData->_alternatives ) && isset( $varData->extendedValue ) ) {
$_ = new kintVariableData;
$_->value = $varData->extendedValue;
$_->type = 'contents';
$_->size = NULL;
array_unshift( $varData->_alternatives, $_ );
$varData->extendedValue = NULL;
}
self::$_skipAlternatives = FALSE;
}
self::$_level = $revert['level'];
self::$_objects = $revert['objects'];
if ( strlen( $varData->name ) > 80 ) {
$varData->name =
self::_substr( $varData->name, 0, 37 )
. '...'
. self::_substr( $varData->name, -38, NULL );
}
return $varData;
}
private static function _checkDepth()
{
return Kint::$maxLevels != 0 && self::$_level >= Kint::$maxLevels;
}
private static function _isArrayTabular( array $variable )
{
if ( Kint::enabled() !== Kint::MODE_RICH ) { return FALSE;
}
$arrayKeys = array();
$keys = NULL;
$closeEnough = FALSE;
foreach ( $variable as $row ) {
if ( ! is_array( $row ) || empty( $row ) ) { return FALSE;
}
foreach ( $row as $col ) {
if ( ! empty( $col ) && ! is_scalar( $col ) ) { return FALSE; // todo add tabular "tolerance"
}
}
if ( isset( $keys ) && ! $closeEnough ) {
# let's just see if the first two rows have same keys, that's faster and has the
# positive side effect of easily spotting missing keys in later rows
if ( $keys !== array_keys( $row ) ) { return FALSE;
}
$closeEnough = TRUE;
} else {
$keys = array_keys( $row );
}
$arrayKeys = array_unique( array_merge( $arrayKeys, $keys ) );
}
return $arrayKeys;
}
private static function _decorateCell( kintVariableData $kintVar )
{
if ( $kintVar->extendedValue !== NULL || ! empty( $kintVar->_alternatives ) ) {
return '<td>' . Kint_Decorators_Rich::decorate( $kintVar ) . '</td>';
}
$output = '<td';
if ( $kintVar->value !== NULL ) {
$output .= ' title="' . $kintVar->type;
if ( $kintVar->size !== NULL ) {
$output .= " (" . $kintVar->size . ")";
}
$output .= '">' . $kintVar->value;
} else {
$output .= '>';
if ( $kintVar->type !== 'NULL' ) {
$output .= '<u>' . $kintVar->type;
if ( $kintVar->size !== NULL ) {
$output .= "(" . $kintVar->size . ")";
}
$output .= '</u>';
} else {
$output .= '<u>NULL</u>';
}
}
return $output . '</td>';
}
public static function escape( $value, $encoding = NULL )
{
if ( empty( $value ) ) { return $value;
}
if ( Kint::enabled() === Kint::MODE_CLI ) {
$value = str_replace( "\x1b", "\\x1b", $value );
}
if ( Kint::enabled() === Kint::MODE_CLI || Kint::enabled() === Kint::MODE_WHITESPACE ) { return $value;
}
$encoding or $encoding = self::_detectEncoding( $value );
$value = htmlspecialchars( $value, ENT_NOQUOTES, $encoding === 'ASCII' ? 'UTF-8' : $encoding );
if ( $encoding === 'UTF-8' ) {
// todo we could make the symbols hover-title show the code for the invisible symbol
# when possible force invisible characters to have some sort of display (experimental)
$value = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\x9F]/u', '?', $value );
}
# this call converts all non-ASCII characters into html chars of format
if ( function_exists( 'mb_encode_numericentity' ) ) {
$value = mb_encode_numericentity(
$value,
array(
0x80,
0xffff,
0,
0xffff,
),
$encoding
);
}
return $value;
}
private static $_dealingWithGlobals = FALSE;
private static function _parse_array( &$variable, kintVariableData $variableData )
{
isset( self::$_marker ) or self::$_marker = "\x00" . uniqid();
# naturally, $GLOBALS variable is an intertwined recursion nightmare, use black magic
$globalsDetector = FALSE;
if ( array_key_exists( 'GLOBALS', $variable ) && is_array( $variable['GLOBALS'] ) ) {
$globalsDetector = "\x01" . uniqid();
$variable['GLOBALS'][$globalsDetector] = TRUE;
if ( isset( $variable[$globalsDetector] ) ) {
unset( $variable[$globalsDetector] );
self::$_dealingWithGlobals = TRUE;
} else {
unset( $variable['GLOBALS'][$globalsDetector] );
$globalsDetector = FALSE;
}
}
$variableData->type = 'array';
$variableData->size = count( $variable );
if ( $variableData->size === 0 ) {
return;
}
if ( isset( $variable[self::$_marker] ) ) { # recursion; todo mayhaps show from where
if ( self::$_dealingWithGlobals ) {
$variableData->value = '*RECURSION*';
} else {
unset( $variable[self::$_marker] );
$variableData->value = self::$_marker;
}
return FALSE;
}
if ( self::_checkDepth() ) {
$variableData->extendedValue = "*DEPTH TOO GREAT*";
return FALSE;
}
$isSequential = self::_isSequential( $variable );
if ( $variableData->size > 1 && ( $arrayKeys = self::_isArrayTabular( $variable ) ) !== FALSE ) {
$variable[self::$_marker] = TRUE; # this must be AFTER _isArrayTabular
$firstRow = TRUE;
$extendedValue = '<table class="kint-report"><thead>';
foreach ( $variable as $rowIndex => & $row ) {
# display strings in their full length
self::$_placeFullStringInValue = TRUE;
if ( $rowIndex === self::$_marker ) { continue;
}
if ( isset( $row[self::$_marker] ) ) {
$variableData->value = "*RECURSION*";
return FALSE;
}
$extendedValue .= '<tr>';
if ( $isSequential ) {
$output = '<td>' . '#' . ( $rowIndex + 1 ) . '</td>';
} else {
$output = self::_decorateCell( kintParser::factory( $rowIndex ) );
}
if ( $firstRow ) {
$extendedValue .= '<th> </th>';
}
# we iterate the known full set of keys from all rows in case some appeared at later rows,
# as we only check the first two to assume
foreach ( $arrayKeys as $key ) {
if ( $firstRow ) {
$extendedValue .= '<th>' . self::escape( $key ) . '</th>';
}
if ( ! array_key_exists( $key, $row ) ) {
$output .= '<td class="kint-empty"></td>';
continue;
}
$var = kintParser::factory( $row[$key] );
if ( $var->value === self::$_marker ) {
$variableData->value = '*RECURSION*';
return FALSE;
} elseif ( $var->value === '*RECURSION*' ) {
$output .= '<td class="kint-empty"><u>*RECURSION*</u></td>';
} else {
$output .= self::_decorateCell( $var );
}
unset( $var );
}
if ( $firstRow ) {
$extendedValue .= '</tr></thead><tr>';
$firstRow = FALSE;
}
$extendedValue .= $output . '</tr>';
}
self::$_placeFullStringInValue = FALSE;
$variableData->extendedValue = $extendedValue . '</table>';
} else {
$variable[self::$_marker] = TRUE;
$extendedValue = array();
foreach ( $variable as $key => & $val ) {
if ( $key === self::$_marker ) { continue;
}
$output = kintParser::factory( $val );
if ( $output->value === self::$_marker ) {
$variableData->value = "*RECURSION*"; // recursion occurred on a higher level, thus $this is recursion
return FALSE;
}
if ( ! $isSequential ) {
$output->operator = '=>';
}
$output->name = $isSequential ? NULL : "'" . $key . "'";
$extendedValue[] = $output;
}
$variableData->extendedValue = $extendedValue;
}
if ( $globalsDetector ) {
self::$_dealingWithGlobals = FALSE;
}
unset( $variable[self::$_marker] );
}
private static function _parse_object( &$variable, kintVariableData $variableData )
{
if ( function_exists( 'spl_object_hash' ) ) {
$hash = spl_object_hash( $variable );
} else {
ob_start();
var_dump( $variable );
preg_match( '[#(\d+)]', ob_get_clean(), $match );
$hash = $match[1];
}
$castedArray = (array) $variable;
$variableData->type = get_class( $variable );
$variableData->size = count( $castedArray );
if ( isset( self::$_objects[$hash] ) ) {
$variableData->value = '*RECURSION*';
return FALSE;
}
if ( self::_checkDepth() ) {
$variableData->extendedValue = "*DEPTH TOO GREAT*";
return FALSE;
}
# ArrayObject (and maybe ArrayIterator, did not try yet) unsurprisingly consist of mainly dark magic.
# What bothers me most, var_dump sees no problem with it, and ArrayObject also uses a custom,
# undocumented serialize function, so you can see the properties in internal functions, but
# can never iterate some of them if the flags are not STD_PROP_LIST. Fun stuff.
if ( $variableData->type === 'ArrayObject' || is_subclass_of( $variable, 'ArrayObject' ) ) {
$arrayObjectFlags = $variable->getFlags();
$variable->setFlags( ArrayObject::STD_PROP_LIST );
}
self::$_objects[$hash] = TRUE; // todo store reflectorObject here for alternatives cache
$reflector = new ReflectionObject( $variable );
# add link to definition of userland objects
if ( Kint::enabled() === Kint::MODE_RICH && Kint::$fileLinkFormat && $reflector->isUserDefined() ) {
$url = Kint::getIdeLink( $reflector->getFileName(), $reflector->getStartLine() );
$class = ( strpos( $url, 'http://' ) === 0 ) ? 'class="kint-ide-link" ' : '';
$variableData->type = "<a {$class}href=\"{$url}\">{$variableData->type}</a>";
}
$variableData->size = 0;
$extendedValue = array();
$encountered = array();
# copy the object as an array as it provides more info than Reflection (depends)
foreach ( $castedArray as $key => $value ) {
/* casting object to array:
* integer properties are inaccessible;
* private variables have the class name prepended to the variable name;
* protected variables have a '*' prepended to the variable name.
* These prepended values have null bytes on either side.
* http://www.php.net/manual/en/language.types.array.php#language.types.array.casting
*/
if ( $key{0} === "\x00" ) {
$access = $key{1} === "*" ? "protected" : "private";
// Remove the access level from the variable name
$key = substr( $key, strrpos( $key, "\x00" ) + 1 );
} else {
$access = "public";
}
$encountered[$key] = TRUE;
$output = kintParser::factory( $value, self::escape( $key ) );
$output->access = $access;
$output->operator = '->';
$extendedValue[] = $output;
$variableData->size++;
}
foreach ( $reflector->getProperties() as $property ) {
$name = $property->name;
if ( $property->isStatic() || isset( $encountered[$name] ) ) { continue;
}
if ( $property->isProtected() ) {
$property->setAccessible( TRUE );
$access = "protected";
} elseif ( $property->isPrivate() ) {
$property->setAccessible( TRUE );
$access = "private";
} else {
$access = "public";
}
$value = $property->getValue( $variable );
$output = kintParser::factory( $value, self::escape( $name ) );
$output->access = $access;
$output->operator = '->';
$extendedValue[] = $output;
$variableData->size++;
}
if ( isset( $arrayObjectFlags ) ) {
$variable->setFlags( $arrayObjectFlags );
}
if ( $variableData->size ) {
$variableData->extendedValue = $extendedValue;
}
}
private static function _parse_boolean( &$variable, kintVariableData $variableData )
{
$variableData->type = 'bool';
$variableData->value = $variable ? 'TRUE' : 'FALSE';
}
private static function _parse_double( &$variable, kintVariableData $variableData )
{
$variableData->type = 'float';
$variableData->value = $variable;
}
private static function _parse_integer( &$variable, kintVariableData $variableData )
{
$variableData->type = 'integer';
$variableData->value = $variable;
}
private static function _parse_null( &$variable, kintVariableData $variableData )
{
$variableData->type = 'NULL';
}
private static function _parse_resource( &$variable, kintVariableData $variableData )
{
$resourceType = get_resource_type( $variable );
$variableData->type = "resource ({$resourceType})";
if ( $resourceType === 'stream' && $meta = stream_get_meta_data( $variable ) ) {
if ( isset( $meta['uri'] ) ) {
$file = $meta['uri'];
if ( function_exists( 'stream_is_local' ) ) {
// Only exists on PHP >= 5.2.4
if ( stream_is_local( $file ) ) {
$file = Kint::shortenPath( $file );
}
}
$variableData->value = $file;
}
}
}
private static function _parse_string( &$variable, kintVariableData $variableData )
{
$variableData->type = 'string';
$encoding = self::_detectEncoding( $variable );
if ( $encoding !== 'ASCII' ) {
$variableData->type .= ' ' . $encoding;
}
$variableData->size = self::_strlen( $variable, $encoding );
if ( Kint::enabled() !== Kint::MODE_RICH ) {
$variableData->value = '"' . self::escape( $variable, $encoding ) . '"';
return;
}
if ( ! self::$_placeFullStringInValue ) {
$strippedString = preg_replace( '[\s+]', ' ', $variable );
if ( Kint::$maxStrLength && $variableData->size > Kint::$maxStrLength ) {
// encode and truncate
$variableData->value = '"'
. self::escape( self::_substr( $strippedString, 0, Kint::$maxStrLength, $encoding ), $encoding )
. '…"';
$variableData->extendedValue = self::escape( $variable, $encoding );
return;
} elseif ( $variable !== $strippedString ) { // omit no data from display
$variableData->value = '"' . self::escape( $variable, $encoding ) . '"';
$variableData->extendedValue = self::escape( $variable, $encoding );
return;
}
}
$variableData->value = '"' . self::escape( $variable, $encoding ) . '"';
}
private static function _parse_unknown( &$variable, kintVariableData $variableData )
{
$type = gettype( $variable );
$variableData->type = "UNKNOWN" . ( ! empty( $type ) ? " ({$type})" : '' );
$variableData->value = var_export( $variable, TRUE );
}
}
| apache-2.0 |
IvanovDmytro/Simp | willie/src/main/java/org/simp/willie/arrays/CharsArray.java | 2665 | /*
* Copyright (C) 2016 Dmytro Ivanov
*
* 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.simp.willie.arrays;
/**
* Immutable array of {@code char}.
* Does not use autoboxing, threadsafe.
*
* @author Dmytro Ivanov
*/
@SuppressWarnings("PMD.UseVarargs")
public final class CharsArray {
/**
* Wrapped mutable array.
*/
private final char[] mData;
/**
* Creates new instance of {@link CharsArray} by wrapping provided in a parameters array.
* Normally method should be used for relatively large array that you do not want to create a copy.
* WARNING: method should be used just in case caller will not hold reference and modify content
* of given array.
*
* @param data array to be wrapped
* @return new instance of {@link CharsArray}
*/
public static CharsArray wrap(final char... data) {
if (data == null) {
throw new IllegalArgumentException("Given array could not be null.");
}
return new CharsArray(data);
}
/**
* Creates new instance of {@link CharsArray} by copying provided in a parameters array.
* Method should be used for most cases of {@link CharsArray} creation.
* WARNING: creates new instance of given array, might not be efficient for big arrays.
*
* @param data array to be copied
* @return new instance of {@link CharsArray}
*/
public static CharsArray copy(final char... data) {
if (data == null) {
throw new IllegalArgumentException("Given array could not be null.");
}
final char[] copy = new char[data.length];
System.arraycopy(data, 0, copy, 0, data.length);
return new CharsArray(copy);
}
@SuppressWarnings("PMD.ArrayIsStoredDirectly")
private CharsArray(final char[] data) {
mData = data;
}
/**
* @param index of the item
* @return item of the array on given index
*/
public char itemAt(final int index) {
return mData[index];
}
/**
* @return length of the array
*/
public int length() {
return mData.length;
}
}
| apache-2.0 |
sarnautov/moby | vendor/github.com/docker/swarmkit/manager/scheduler/filter.go | 7637 | package scheduler
import (
"fmt"
"strings"
"github.com/docker/swarmkit/api"
"github.com/docker/swarmkit/manager/constraint"
)
// Filter checks whether the given task can run on the given node.
// A filter may only operate
type Filter interface {
// SetTask returns true when the filter is enabled for a given task
// and assigns the task to the filter. It returns false if the filter
// isn't applicable to this task. For instance, a constraints filter
// would return `false` if the task doesn't contain any constraints.
SetTask(*api.Task) bool
// Check returns true if the task assigned by SetTask can be scheduled
// into the given node. This function should not be called if SetTask
// returned false.
Check(*NodeInfo) bool
// Explain what a failure of this filter means
Explain(nodes int) string
}
// ReadyFilter checks that the node is ready to schedule tasks.
type ReadyFilter struct {
}
// SetTask returns true when the filter is enabled for a given task.
func (f *ReadyFilter) SetTask(_ *api.Task) bool {
return true
}
// Check returns true if the task can be scheduled into the given node.
func (f *ReadyFilter) Check(n *NodeInfo) bool {
return n.Status.State == api.NodeStatus_READY &&
n.Spec.Availability == api.NodeAvailabilityActive
}
// Explain returns an explanation of a failure.
func (f *ReadyFilter) Explain(nodes int) string {
if nodes == 1 {
return "1 node not available for new tasks"
}
return fmt.Sprintf("%d nodes not available for new tasks", nodes)
}
// ResourceFilter checks that the node has enough resources available to run
// the task.
type ResourceFilter struct {
reservations *api.Resources
}
// SetTask returns true when the filter is enabled for a given task.
func (f *ResourceFilter) SetTask(t *api.Task) bool {
r := t.Spec.Resources
if r == nil || r.Reservations == nil {
return false
}
if r.Reservations.NanoCPUs == 0 && r.Reservations.MemoryBytes == 0 {
return false
}
f.reservations = r.Reservations
return true
}
// Check returns true if the task can be scheduled into the given node.
func (f *ResourceFilter) Check(n *NodeInfo) bool {
if f.reservations.NanoCPUs > n.AvailableResources.NanoCPUs {
return false
}
if f.reservations.MemoryBytes > n.AvailableResources.MemoryBytes {
return false
}
return true
}
// Explain returns an explanation of a failure.
func (f *ResourceFilter) Explain(nodes int) string {
if nodes == 1 {
return "insufficient resources on 1 node"
}
return fmt.Sprintf("insufficient resources on %d nodes", nodes)
}
// PluginFilter checks that the node has a specific volume plugin installed
type PluginFilter struct {
t *api.Task
}
func referencesVolumePlugin(mount api.Mount) bool {
return mount.Type == api.MountTypeVolume &&
mount.VolumeOptions != nil &&
mount.VolumeOptions.DriverConfig != nil &&
mount.VolumeOptions.DriverConfig.Name != "" &&
mount.VolumeOptions.DriverConfig.Name != "local"
}
// SetTask returns true when the filter is enabled for a given task.
func (f *PluginFilter) SetTask(t *api.Task) bool {
c := t.Spec.GetContainer()
var volumeTemplates bool
if c != nil {
for _, mount := range c.Mounts {
if referencesVolumePlugin(mount) {
volumeTemplates = true
break
}
}
}
if (c != nil && volumeTemplates) || len(t.Networks) > 0 {
f.t = t
return true
}
return false
}
// Check returns true if the task can be scheduled into the given node.
// TODO(amitshukla): investigate storing Plugins as a map so it can be easily probed
func (f *PluginFilter) Check(n *NodeInfo) bool {
// Get list of plugins on the node
nodePlugins := n.Description.Engine.Plugins
// Check if all volume plugins required by task are installed on node
container := f.t.Spec.GetContainer()
if container != nil {
for _, mount := range container.Mounts {
if referencesVolumePlugin(mount) {
if !f.pluginExistsOnNode("Volume", mount.VolumeOptions.DriverConfig.Name, nodePlugins) {
return false
}
}
}
}
// Check if all network plugins required by task are installed on node
for _, tn := range f.t.Networks {
if tn.Network != nil && tn.Network.DriverState != nil && tn.Network.DriverState.Name != "" {
if !f.pluginExistsOnNode("Network", tn.Network.DriverState.Name, nodePlugins) {
return false
}
}
}
return true
}
// pluginExistsOnNode returns true if the (pluginName, pluginType) pair is present in nodePlugins
func (f *PluginFilter) pluginExistsOnNode(pluginType string, pluginName string, nodePlugins []api.PluginDescription) bool {
for _, np := range nodePlugins {
if pluginType != np.Type {
continue
}
if pluginName == np.Name {
return true
}
// This does not use the reference package to avoid the
// overhead of parsing references as part of the scheduling
// loop. This is okay only because plugin names are a very
// strict subset of the reference grammar that is always
// name:tag.
if strings.HasPrefix(np.Name, pluginName) && np.Name[len(pluginName):] == ":latest" {
return true
}
}
return false
}
// Explain returns an explanation of a failure.
func (f *PluginFilter) Explain(nodes int) string {
if nodes == 1 {
return "missing plugin on 1 node"
}
return fmt.Sprintf("missing plugin on %d nodes", nodes)
}
// ConstraintFilter selects only nodes that match certain labels.
type ConstraintFilter struct {
constraints []constraint.Constraint
}
// SetTask returns true when the filter is enable for a given task.
func (f *ConstraintFilter) SetTask(t *api.Task) bool {
if t.Spec.Placement == nil || len(t.Spec.Placement.Constraints) == 0 {
return false
}
constraints, err := constraint.Parse(t.Spec.Placement.Constraints)
if err != nil {
// constraints have been validated at controlapi
// if in any case it finds an error here, treat this task
// as constraint filter disabled.
return false
}
f.constraints = constraints
return true
}
// Check returns true if the task's constraint is supported by the given node.
func (f *ConstraintFilter) Check(n *NodeInfo) bool {
return constraint.NodeMatches(f.constraints, n.Node)
}
// Explain returns an explanation of a failure.
func (f *ConstraintFilter) Explain(nodes int) string {
if nodes == 1 {
return "scheduling constraints not satisfied on 1 node"
}
return fmt.Sprintf("scheduling constraints not satisfied on %d nodes", nodes)
}
// PlatformFilter selects only nodes that run the required platform.
type PlatformFilter struct {
supportedPlatforms []*api.Platform
}
// SetTask returns true when the filter is enabled for a given task.
func (f *PlatformFilter) SetTask(t *api.Task) bool {
placement := t.Spec.Placement
if placement != nil {
// copy the platform information
f.supportedPlatforms = placement.Platforms
if len(placement.Platforms) > 0 {
return true
}
}
return false
}
// Check returns true if the task can be scheduled into the given node.
func (f *PlatformFilter) Check(n *NodeInfo) bool {
// if the supportedPlatforms field is empty, then either it wasn't
// provided or there are no constraints
if len(f.supportedPlatforms) == 0 {
return true
}
// check if the platform for the node is supported
nodePlatform := n.Description.Platform
for _, p := range f.supportedPlatforms {
if (p.Architecture == "" || p.Architecture == nodePlatform.Architecture) && (p.OS == "" || p.OS == nodePlatform.OS) {
return true
}
}
return false
}
// Explain returns an explanation of a failure.
func (f *PlatformFilter) Explain(nodes int) string {
if nodes == 1 {
return "unsupported platform on 1 node"
}
return fmt.Sprintf("unsupported platform on %d nodes", nodes)
}
| apache-2.0 |
miswenwen/My_bird_work | Bird_work/我的项目/Settings/src/com/mediatek/audioprofile/BesSurroundItem.java | 2499 | /*
* Copyright (C) 2013 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.mediatek.audioprofile;
import android.content.Context;
import android.preference.CheckBoxPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import com.android.settings.R;
/**
* Check box preference with check box replaced by radio button.
*
* Functionally speaking, it's actually a CheckBoxPreference. We only modified
* the widget to RadioButton to make it "look like" a RadioButtonPreference.
*
* In other words, there's no "RadioButtonPreferenceGroup" in this
* implementation. When you check one RadioButtonPreference, if you want to
* uncheck all the other preferences, you should do that by code yourself.
*/
public class BesSurroundItem extends CheckBoxPreference {
public interface OnClickListener {
public abstract void onRadioButtonClicked(BesSurroundItem emiter);
}
private OnClickListener mListener = null;
public BesSurroundItem(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setWidgetLayoutResource(R.layout.preference_widget_radiobutton);
}
public BesSurroundItem(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.checkBoxPreferenceStyle);
}
public BesSurroundItem(Context context) {
this(context, null);
}
void setOnClickListener(OnClickListener listener) {
mListener = listener;
}
@Override
public void onClick() {
if (mListener != null) {
mListener.onRadioButtonClicked(this);
}
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
TextView title = (TextView) view.findViewById(android.R.id.title);
if (title != null) {
title.setSingleLine(false);
title.setMaxLines(3);
}
}
}
| apache-2.0 |
vert-x3/vertx-examples | core-examples/src/main/ruby/io/vertx/example/core/http2/h2c/client.rb | 289 |
options = {
'protocolVersion' => "HTTP_2"
}
$vertx.create_http_client(options).get_now(8080, "localhost", "/") { |resp|
puts "Got response #{resp.status_code()} with protocol #{resp.version()}"
resp.body_handler() { |body|
puts "Got data #{body.to_string("ISO-8859-1")}"
}
}
| apache-2.0 |
GenericStudent/home-assistant | homeassistant/components/broadlink/remote.py | 10921 | """Support for Broadlink remotes."""
import asyncio
from base64 import b64encode
from collections import defaultdict
from datetime import timedelta
from itertools import product
import logging
from broadlink.exceptions import (
AuthorizationError,
BroadlinkException,
NetworkTimeoutError,
ReadError,
StorageError,
)
import voluptuous as vol
from homeassistant.components.remote import (
ATTR_ALTERNATIVE,
ATTR_COMMAND,
ATTR_DELAY_SECS,
ATTR_DEVICE,
ATTR_NUM_REPEATS,
DEFAULT_DELAY_SECS,
PLATFORM_SCHEMA,
SUPPORT_LEARN_COMMAND,
RemoteEntity,
)
from homeassistant.const import CONF_HOST, STATE_ON
from homeassistant.core import callback
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.storage import Store
from homeassistant.util.dt import utcnow
from .const import DOMAIN
from .helpers import data_packet, import_device
_LOGGER = logging.getLogger(__name__)
LEARNING_TIMEOUT = timedelta(seconds=30)
CODE_STORAGE_VERSION = 1
FLAG_STORAGE_VERSION = 1
FLAG_SAVE_DELAY = 15
COMMAND_SCHEMA = vol.Schema(
{
vol.Required(ATTR_COMMAND): vol.All(
cv.ensure_list, [vol.All(cv.string, vol.Length(min=1))], vol.Length(min=1)
),
},
extra=vol.ALLOW_EXTRA,
)
SERVICE_SEND_SCHEMA = COMMAND_SCHEMA.extend(
{
vol.Optional(ATTR_DEVICE): vol.All(cv.string, vol.Length(min=1)),
vol.Optional(ATTR_DELAY_SECS, default=DEFAULT_DELAY_SECS): vol.Coerce(float),
}
)
SERVICE_LEARN_SCHEMA = COMMAND_SCHEMA.extend(
{
vol.Required(ATTR_DEVICE): vol.All(cv.string, vol.Length(min=1)),
vol.Optional(ATTR_ALTERNATIVE, default=False): cv.boolean,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_HOST): cv.string}, extra=vol.ALLOW_EXTRA
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Import the device and discontinue platform.
This is for backward compatibility.
Do not use this method.
"""
import_device(hass, config[CONF_HOST])
_LOGGER.warning(
"The remote platform is deprecated, please remove it from your configuration"
)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up a Broadlink remote."""
device = hass.data[DOMAIN].devices[config_entry.entry_id]
remote = BroadlinkRemote(
device,
Store(hass, CODE_STORAGE_VERSION, f"broadlink_remote_{device.unique_id}_codes"),
Store(hass, FLAG_STORAGE_VERSION, f"broadlink_remote_{device.unique_id}_flags"),
)
loaded = await remote.async_load_storage_files()
if not loaded:
_LOGGER.error("Failed to create '%s Remote' entity: Storage error", device.name)
return
async_add_entities([remote], False)
class BroadlinkRemote(RemoteEntity, RestoreEntity):
"""Representation of a Broadlink remote."""
def __init__(self, device, codes, flags):
"""Initialize the remote."""
self._device = device
self._coordinator = device.update_manager.coordinator
self._code_storage = codes
self._flag_storage = flags
self._codes = {}
self._flags = defaultdict(int)
self._state = True
@property
def name(self):
"""Return the name of the remote."""
return f"{self._device.name} Remote"
@property
def unique_id(self):
"""Return the unique id of the remote."""
return self._device.unique_id
@property
def is_on(self):
"""Return True if the remote is on."""
return self._state
@property
def available(self):
"""Return True if the remote is available."""
return self._device.update_manager.available
@property
def should_poll(self):
"""Return True if the remote has to be polled for state."""
return False
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_LEARN_COMMAND
@property
def device_info(self):
"""Return device info."""
return {
"identifiers": {(DOMAIN, self._device.unique_id)},
"manufacturer": self._device.api.manufacturer,
"model": self._device.api.model,
"name": self._device.name,
"sw_version": self._device.fw_version,
}
def get_code(self, command, device):
"""Return a code and a boolean indicating a toggle command.
If the command starts with `b64:`, extract the code from it.
Otherwise, extract the code from the dictionary, using the device
and command as keys.
You need to change the flag whenever a toggle command is sent
successfully. Use `self._flags[device] ^= 1`.
"""
if command.startswith("b64:"):
code, is_toggle_cmd = command[4:], False
else:
if device is None:
raise KeyError("You need to specify a device")
try:
code = self._codes[device][command]
except KeyError as err:
raise KeyError("Command not found") from err
# For toggle commands, alternate between codes in a list.
if isinstance(code, list):
code = code[self._flags[device]]
is_toggle_cmd = True
else:
is_toggle_cmd = False
try:
return data_packet(code), is_toggle_cmd
except ValueError as err:
raise ValueError("Invalid code") from err
@callback
def get_flags(self):
"""Return a dictionary of toggle flags.
A toggle flag indicates whether the remote should send an
alternative code.
"""
return self._flags
async def async_added_to_hass(self):
"""Call when the remote is added to hass."""
state = await self.async_get_last_state()
self._state = state is None or state.state == STATE_ON
self.async_on_remove(
self._coordinator.async_add_listener(self.async_write_ha_state)
)
async def async_update(self):
"""Update the remote."""
await self._coordinator.async_request_refresh()
async def async_turn_on(self, **kwargs):
"""Turn on the remote."""
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Turn off the remote."""
self._state = False
self.async_write_ha_state()
async def async_load_storage_files(self):
"""Load codes and toggle flags from storage files."""
try:
self._codes.update(await self._code_storage.async_load() or {})
self._flags.update(await self._flag_storage.async_load() or {})
except HomeAssistantError:
return False
return True
async def async_send_command(self, command, **kwargs):
"""Send a list of commands to a device."""
kwargs[ATTR_COMMAND] = command
kwargs = SERVICE_SEND_SCHEMA(kwargs)
commands = kwargs[ATTR_COMMAND]
device = kwargs.get(ATTR_DEVICE)
repeat = kwargs[ATTR_NUM_REPEATS]
delay = kwargs[ATTR_DELAY_SECS]
if not self._state:
_LOGGER.warning(
"remote.send_command canceled: %s entity is turned off", self.entity_id
)
return
should_delay = False
for _, cmd in product(range(repeat), commands):
if should_delay:
await asyncio.sleep(delay)
try:
code, is_toggle_cmd = self.get_code(cmd, device)
except (KeyError, ValueError) as err:
_LOGGER.error("Failed to send '%s': %s", cmd, err)
should_delay = False
continue
try:
await self._device.async_request(self._device.api.send_data, code)
except (AuthorizationError, NetworkTimeoutError, OSError) as err:
_LOGGER.error("Failed to send '%s': %s", command, err)
break
except BroadlinkException as err:
_LOGGER.error("Failed to send '%s': %s", command, err)
should_delay = False
continue
should_delay = True
if is_toggle_cmd:
self._flags[device] ^= 1
self._flag_storage.async_delay_save(self.get_flags, FLAG_SAVE_DELAY)
async def async_learn_command(self, **kwargs):
"""Learn a list of commands from a remote."""
kwargs = SERVICE_LEARN_SCHEMA(kwargs)
commands = kwargs[ATTR_COMMAND]
device = kwargs[ATTR_DEVICE]
toggle = kwargs[ATTR_ALTERNATIVE]
if not self._state:
_LOGGER.warning(
"remote.learn_command canceled: %s entity is turned off", self.entity_id
)
return
should_store = False
for command in commands:
try:
code = await self._async_learn_command(command)
if toggle:
code = [code, await self._async_learn_command(command)]
except (AuthorizationError, NetworkTimeoutError, OSError) as err:
_LOGGER.error("Failed to learn '%s': %s", command, err)
break
except BroadlinkException as err:
_LOGGER.error("Failed to learn '%s': %s", command, err)
continue
self._codes.setdefault(device, {}).update({command: code})
should_store = True
if should_store:
await self._code_storage.async_save(self._codes)
async def _async_learn_command(self, command):
"""Learn a command from a remote."""
try:
await self._device.async_request(self._device.api.enter_learning)
except (BroadlinkException, OSError) as err:
_LOGGER.debug("Failed to enter learning mode: %s", err)
raise
self.hass.components.persistent_notification.async_create(
f"Press the '{command}' button.",
title="Learn command",
notification_id="learn_command",
)
try:
start_time = utcnow()
while (utcnow() - start_time) < LEARNING_TIMEOUT:
await asyncio.sleep(1)
try:
code = await self._device.async_request(self._device.api.check_data)
except (ReadError, StorageError):
continue
return b64encode(code).decode("utf8")
raise TimeoutError("No code received")
finally:
self.hass.components.persistent_notification.async_dismiss(
notification_id="learn_command"
)
| apache-2.0 |
GoogleCloudPlatform/declarative-resource-client-library | python/services/runtimeconfig/variable_server.go | 4583 | // Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"context"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto"
runtimeconfigpb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/runtimeconfig/runtimeconfig_go_proto"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/runtimeconfig"
)
// Server implements the gRPC interface for Variable.
type VariableServer struct{}
// ProtoToVariable converts a Variable resource from its proto representation.
func ProtoToVariable(p *runtimeconfigpb.RuntimeconfigVariable) *runtimeconfig.Variable {
obj := &runtimeconfig.Variable{
Name: dcl.StringOrNil(p.Name),
RuntimeConfig: dcl.StringOrNil(p.RuntimeConfig),
Text: dcl.StringOrNil(p.Text),
Value: dcl.StringOrNil(p.Value),
UpdateTime: dcl.StringOrNil(p.UpdateTime),
Project: dcl.StringOrNil(p.Project),
}
return obj
}
// VariableToProto converts a Variable resource to its proto representation.
func VariableToProto(resource *runtimeconfig.Variable) *runtimeconfigpb.RuntimeconfigVariable {
p := &runtimeconfigpb.RuntimeconfigVariable{
Name: dcl.ValueOrEmptyString(resource.Name),
RuntimeConfig: dcl.ValueOrEmptyString(resource.RuntimeConfig),
Text: dcl.ValueOrEmptyString(resource.Text),
Value: dcl.ValueOrEmptyString(resource.Value),
UpdateTime: dcl.ValueOrEmptyString(resource.UpdateTime),
Project: dcl.ValueOrEmptyString(resource.Project),
}
return p
}
// ApplyVariable handles the gRPC request by passing it to the underlying Variable Apply() method.
func (s *VariableServer) applyVariable(ctx context.Context, c *runtimeconfig.Client, request *runtimeconfigpb.ApplyRuntimeconfigVariableRequest) (*runtimeconfigpb.RuntimeconfigVariable, error) {
p := ProtoToVariable(request.GetResource())
res, err := c.ApplyVariable(ctx, p)
if err != nil {
return nil, err
}
r := VariableToProto(res)
return r, nil
}
// ApplyVariable handles the gRPC request by passing it to the underlying Variable Apply() method.
func (s *VariableServer) ApplyRuntimeconfigVariable(ctx context.Context, request *runtimeconfigpb.ApplyRuntimeconfigVariableRequest) (*runtimeconfigpb.RuntimeconfigVariable, error) {
cl, err := createConfigVariable(ctx, request.ServiceAccountFile)
if err != nil {
return nil, err
}
return s.applyVariable(ctx, cl, request)
}
// DeleteVariable handles the gRPC request by passing it to the underlying Variable Delete() method.
func (s *VariableServer) DeleteRuntimeconfigVariable(ctx context.Context, request *runtimeconfigpb.DeleteRuntimeconfigVariableRequest) (*emptypb.Empty, error) {
cl, err := createConfigVariable(ctx, request.ServiceAccountFile)
if err != nil {
return nil, err
}
return &emptypb.Empty{}, cl.DeleteVariable(ctx, ProtoToVariable(request.GetResource()))
}
// ListVariable handles the gRPC request by passing it to the underlying VariableList() method.
func (s *VariableServer) ListRuntimeconfigVariable(ctx context.Context, request *runtimeconfigpb.ListRuntimeconfigVariableRequest) (*runtimeconfigpb.ListRuntimeconfigVariableResponse, error) {
cl, err := createConfigVariable(ctx, request.ServiceAccountFile)
if err != nil {
return nil, err
}
resources, err := cl.ListVariable(ctx, request.Project, request.RuntimeConfig)
if err != nil {
return nil, err
}
var protos []*runtimeconfigpb.RuntimeconfigVariable
for _, r := range resources.Items {
rp := VariableToProto(r)
protos = append(protos, rp)
}
return &runtimeconfigpb.ListRuntimeconfigVariableResponse{Items: protos}, nil
}
func createConfigVariable(ctx context.Context, service_account_file string) (*runtimeconfig.Client, error) {
conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file))
return runtimeconfig.NewClient(conf), nil
}
| apache-2.0 |
tsaleh/garden | protocol/net_out.pb.go | 5476 | // Code generated by protoc-gen-gogo.
// source: net_out.proto
// DO NOT EDIT!
package garden
import proto "github.com/gogo/protobuf/proto"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf
type NetOutRequest_Protocol int32
const (
NetOutRequest_ALL NetOutRequest_Protocol = 0
NetOutRequest_TCP NetOutRequest_Protocol = 1
NetOutRequest_UDP NetOutRequest_Protocol = 2
NetOutRequest_ICMP NetOutRequest_Protocol = 3
)
var NetOutRequest_Protocol_name = map[int32]string{
0: "ALL",
1: "TCP",
2: "UDP",
3: "ICMP",
}
var NetOutRequest_Protocol_value = map[string]int32{
"ALL": 0,
"TCP": 1,
"UDP": 2,
"ICMP": 3,
}
func (x NetOutRequest_Protocol) Enum() *NetOutRequest_Protocol {
p := new(NetOutRequest_Protocol)
*p = x
return p
}
func (x NetOutRequest_Protocol) String() string {
return proto.EnumName(NetOutRequest_Protocol_name, int32(x))
}
func (x *NetOutRequest_Protocol) UnmarshalJSON(data []byte) error {
value, err := proto.UnmarshalJSONEnum(NetOutRequest_Protocol_value, data, "NetOutRequest_Protocol")
if err != nil {
return err
}
*x = NetOutRequest_Protocol(value)
return nil
}
type NetOutRequest struct {
Handle *string `protobuf:"bytes,1,req,name=handle" json:"handle,omitempty"`
Protocol *NetOutRequest_Protocol `protobuf:"varint,2,req,name=protocol,enum=garden.NetOutRequest_Protocol" json:"protocol,omitempty"`
Networks []*NetOutRequest_IPRange `protobuf:"bytes,3,rep,name=networks" json:"networks,omitempty"`
Ports []*NetOutRequest_PortRange `protobuf:"bytes,4,rep,name=ports" json:"ports,omitempty"`
Icmps *NetOutRequest_ICMPControl `protobuf:"bytes,5,opt,name=icmps" json:"icmps,omitempty"`
Log *bool `protobuf:"varint,6,req,name=log" json:"log,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *NetOutRequest) Reset() { *m = NetOutRequest{} }
func (m *NetOutRequest) String() string { return proto.CompactTextString(m) }
func (*NetOutRequest) ProtoMessage() {}
func (m *NetOutRequest) GetHandle() string {
if m != nil && m.Handle != nil {
return *m.Handle
}
return ""
}
func (m *NetOutRequest) GetProtocol() NetOutRequest_Protocol {
if m != nil && m.Protocol != nil {
return *m.Protocol
}
return NetOutRequest_ALL
}
func (m *NetOutRequest) GetNetworks() []*NetOutRequest_IPRange {
if m != nil {
return m.Networks
}
return nil
}
func (m *NetOutRequest) GetPorts() []*NetOutRequest_PortRange {
if m != nil {
return m.Ports
}
return nil
}
func (m *NetOutRequest) GetIcmps() *NetOutRequest_ICMPControl {
if m != nil {
return m.Icmps
}
return nil
}
func (m *NetOutRequest) GetLog() bool {
if m != nil && m.Log != nil {
return *m.Log
}
return false
}
type NetOutRequest_IPRange struct {
Start *string `protobuf:"bytes,1,req,name=start" json:"start,omitempty"`
End *string `protobuf:"bytes,2,req,name=end" json:"end,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *NetOutRequest_IPRange) Reset() { *m = NetOutRequest_IPRange{} }
func (m *NetOutRequest_IPRange) String() string { return proto.CompactTextString(m) }
func (*NetOutRequest_IPRange) ProtoMessage() {}
func (m *NetOutRequest_IPRange) GetStart() string {
if m != nil && m.Start != nil {
return *m.Start
}
return ""
}
func (m *NetOutRequest_IPRange) GetEnd() string {
if m != nil && m.End != nil {
return *m.End
}
return ""
}
type NetOutRequest_PortRange struct {
Start *uint32 `protobuf:"varint,1,req,name=start" json:"start,omitempty"`
End *uint32 `protobuf:"varint,2,req,name=end" json:"end,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *NetOutRequest_PortRange) Reset() { *m = NetOutRequest_PortRange{} }
func (m *NetOutRequest_PortRange) String() string { return proto.CompactTextString(m) }
func (*NetOutRequest_PortRange) ProtoMessage() {}
func (m *NetOutRequest_PortRange) GetStart() uint32 {
if m != nil && m.Start != nil {
return *m.Start
}
return 0
}
func (m *NetOutRequest_PortRange) GetEnd() uint32 {
if m != nil && m.End != nil {
return *m.End
}
return 0
}
type NetOutRequest_ICMPControl struct {
Type *uint32 `protobuf:"varint,1,req,name=type" json:"type,omitempty"`
Code *int32 `protobuf:"varint,2,opt,name=code,def=-1" json:"code,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *NetOutRequest_ICMPControl) Reset() { *m = NetOutRequest_ICMPControl{} }
func (m *NetOutRequest_ICMPControl) String() string { return proto.CompactTextString(m) }
func (*NetOutRequest_ICMPControl) ProtoMessage() {}
const Default_NetOutRequest_ICMPControl_Code int32 = -1
func (m *NetOutRequest_ICMPControl) GetType() uint32 {
if m != nil && m.Type != nil {
return *m.Type
}
return 0
}
func (m *NetOutRequest_ICMPControl) GetCode() int32 {
if m != nil && m.Code != nil {
return *m.Code
}
return Default_NetOutRequest_ICMPControl_Code
}
type NetOutResponse struct {
XXX_unrecognized []byte `json:"-"`
}
func (m *NetOutResponse) Reset() { *m = NetOutResponse{} }
func (m *NetOutResponse) String() string { return proto.CompactTextString(m) }
func (*NetOutResponse) ProtoMessage() {}
func init() {
proto.RegisterEnum("garden.NetOutRequest_Protocol", NetOutRequest_Protocol_name, NetOutRequest_Protocol_value)
}
| apache-2.0 |
upenn-libraries/solrplugins | src/main/java/edu/upenn/library/solrplugins/JsonReferencePayloadHandler.java | 10590 | package edu.upenn.library.solrplugins;
import java.io.IOException;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.FacetPayload;
/**
* Builds facet payloads from fields containing filing and
* prefix strings joined by a delimiter, and a payload attribute
* containing information about references.
*
* The NamedList structure for a facet will look like this:
*
* <lst name="subject_xfacet">
* <lst name="Hegelianism">
* <int name="count">3</int>
* <lst name="self">
* <long name="count">2</long>
* <str name="filing">Hegelianism</str>
* </lst>
* <lst name="refs">
* <lst name="see_also">
* <lst name="Georg Wilhelm Friedrich Hegel">
* <long name="count">1</int>
* <str name="prefix">Georg Wilhelm Friedrich </str>
* <str name="filing">Hegel</str>
* </lst>
* </lst>
* </lst>
* </lst>
* </lst>
*
* @author jeffchiu
*/
public class JsonReferencePayloadHandler implements FacetPayload<NamedList<Object>> {
private static final String DELIM = "\u0000";
private static final String KEY_SELF = "self";
private static final String KEY_REFS = "refs";
private static final String KEY_PREFIX = "prefix";
private static final String KEY_FILING = "filing";
private static final String KEY_COUNT = "count";
/**
* overwrite entry in NamedList with new value
* (update existing key, or add the key/value if key doesn't already exist)
*/
private static void overwriteInNamedList(NamedList<Object> namedList, String key, Object value) {
int indexOfKey = namedList.indexOf(key, 0);
if(indexOfKey != -1) {
namedList.setVal(indexOfKey, value);
} else {
namedList.add(key, value);
}
}
/**
* Copies a field value from one NamedList into another
*/
private static void copyFieldInNamedList(NamedList<Object> from, NamedList<Object> to, String key) {
int index = from.indexOf(key, 0);
if(index != -1) {
Object value = from.get(key);
int index2 = to.indexOf(key, 0);
if(index2 != -1) {
to.setVal(index2, value);
} else {
to.add(key, value);
}
}
}
/**
* For passed-in NamedList, get the NamedList value for a certain key,
* creating and storing it if it doesn't exist.
* @param namedList
* @param key
*/
private static NamedList<Object> getOrCreateNamedListValue(NamedList<Object> namedList, String key) {
NamedList<Object> result = (NamedList<Object>) namedList.get(key);
if(result == null) {
result = new NamedList<>();
namedList.add(key, result);
}
return result;
}
/**
* increment a Long value in a NamedList stored under "key", creating it with value of 1
* if it doesn't exist.
*/
private static void incrementLongInNamedList(NamedList<Object> namedList, String key) {
int index = namedList.indexOf(key, 0);
if(index != -1) {
long oldCount = ((Number) namedList.getVal(index)).longValue();
namedList.setVal(index, oldCount + 1L);
} else {
namedList.add(key, 1L);
}
}
/**
* Updates the Long value for the specified key in the 'preExisting' NamedList
* by adding the value from the 'add' NamedList.
*/
private static void mergeCount(NamedList<Object> from, NamedList<Object> to, String key) {
// merge count
long existingCount = 0;
int indexOfCount = to.indexOf(key, 0);
if(indexOfCount != -1) {
existingCount = ((Number) to.get(key)).longValue();
}
long newCount = existingCount + ((Number) from.get(key)).longValue();
overwriteInNamedList(to, key, newCount);
}
@Override
public boolean addEntry(String termKey, long count, Term t, List<Entry<LeafReader, Bits>> leaves, NamedList<NamedList<Object>> res) throws IOException {
MultiPartString term = MultiPartString.parseNormalizedFilingAndPrefix(termKey);
NamedList<Object> entry = buildEntryValue(term, count, t, leaves);
res.add(term.getDisplay(), entry);
return true;
}
@Override
public Entry<String, NamedList<Object>> addEntry(String termKey, long count, Term t, List<Entry<LeafReader, Bits>> leaves) throws IOException {
MultiPartString term = MultiPartString.parseNormalizedFilingAndPrefix(termKey);
return new SimpleImmutableEntry<>(termKey, buildEntryValue(term, count, t, leaves));
}
private NamedList<Object> buildEntryValue(MultiPartString term, long count, Term t, List<Entry<LeafReader, Bits>> leaves) throws IOException {
NamedList<Object> entry = new NamedList<>();
// document count for this term
entry.add(KEY_COUNT, count);
NamedList<Object> self = new NamedList<>();
entry.add(KEY_SELF, self);
self.add(KEY_COUNT, 0L);
overwriteInNamedList(self, KEY_FILING, term.getFiling());
if(term.getPrefix() != null) {
overwriteInNamedList(self, KEY_PREFIX, term.getPrefix());
}
NamedList<Object> refs = new NamedList<>();
Set<BytesRef> trackDuplicates = new HashSet<>();
for (Entry<LeafReader, Bits> e : leaves) {
PostingsEnum postings = e.getKey().postings(t, PostingsEnum.PAYLOADS);
if (postings == null) {
continue;
}
Bits liveDocs = e.getValue();
while (postings.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
if (liveDocs != null && !liveDocs.get(postings.docID())) {
continue;
}
trackDuplicates.clear();
for (int j = 0; j < postings.freq(); j++) {
postings.nextPosition();
BytesRef payload = postings.getPayload();
if (!trackDuplicates.add(payload)) {
continue;
}
if (payload != null) {
String payloadStr = payload.utf8ToString();
int pos = payloadStr.indexOf(JsonReferencePayloadTokenizer.PAYLOAD_ATTR_SEPARATOR);
if (pos != -1) {
String referenceType = payloadStr.substring(0, pos);
String target = payloadStr.substring(pos + 1);
MultiPartString multiPartString = MultiPartString.parseFilingAndPrefix(target);
String displayName = multiPartString.getDisplay();
NamedList<Object> displayNameStructs = getOrCreateNamedListValue(refs, referenceType);
NamedList<Object> nameStruct = getOrCreateNamedListValue(displayNameStructs, displayName);
incrementLongInNamedList(nameStruct, KEY_COUNT);
overwriteInNamedList(nameStruct, KEY_FILING, multiPartString.getFiling());
if (multiPartString.getPrefix() != null) {
overwriteInNamedList(nameStruct, KEY_PREFIX, multiPartString.getPrefix());
}
}
} else {
// no payload means term is for self, so increment count
incrementLongInNamedList(self, KEY_COUNT);
}
// Couldn't get this to work: postings.attributes() doesn't return anything: why?
/*
ReferenceAttribute refAtt = postings.attributes().getAttribute(ReferenceAttribute.class);
if(refAtt != null) {
System.out.println("found refAttr, " + refAtt.getReferenceType() + "," + refAtt.getTarget());
}
*/
}
}
}
if(refs.size() > 0) {
entry.add(KEY_REFS, refs);
}
return entry;
}
@Override
public NamedList<Object> mergePayload(NamedList<Object> preExisting, NamedList<Object> add, long preExistingCount, long addCount) {
if (addCount != ((Number)add.get(KEY_COUNT)).longValue()) {
throw new IllegalStateException("fieldType-internal and -external counts do not match");
}
int countIndex = preExisting.indexOf(KEY_COUNT, 0);
long preCount = ((Number)preExisting.getVal(countIndex)).longValue();
preExisting.setVal(countIndex, preCount + addCount);
if(add.get(KEY_SELF) != null) {
NamedList<Object> addSelf = (NamedList<Object>) add.get(KEY_SELF);
NamedList<Object> preExistingSelf = getOrCreateNamedListValue(preExisting, KEY_SELF);
mergeCount(addSelf, preExistingSelf, KEY_COUNT);
copyFieldInNamedList(addSelf, preExistingSelf, KEY_FILING);
copyFieldInNamedList(addSelf, preExistingSelf, KEY_PREFIX);
}
if(add.get(KEY_REFS) != null) {
NamedList<Object> addRefs = (NamedList<Object>) add.get(KEY_REFS);
Iterator<Map.Entry<String, Object>> refTypesIter = addRefs.iterator();
while (refTypesIter.hasNext()) {
Map.Entry<String, Object> entry = refTypesIter.next();
String addReferenceType = entry.getKey();
NamedList<Object> addNameStructs = (NamedList<Object>) entry.getValue();
// if "refs" doesn't exist in preExisting yet, create it
NamedList<Object> preExistingRefs = getOrCreateNamedListValue(preExisting, KEY_REFS);
// if referenceType doesn't exist in preExisting yet, create it
NamedList<Object> preExistingNameStructs = getOrCreateNamedListValue(preExistingRefs, addReferenceType);
// loop through names and merge them into preExisting
Iterator<Map.Entry<String, Object>> addNameStructsIter = addNameStructs.iterator();
while (addNameStructsIter.hasNext()) {
Map.Entry<String, Object> nameStructEntry = addNameStructsIter.next();
String name = nameStructEntry.getKey();
NamedList<Object> addNameStruct = (NamedList<Object>) nameStructEntry.getValue();
// if name doesn't exist in preExisting yet, create it
NamedList<Object> preExistingNameStruct = getOrCreateNamedListValue(preExistingNameStructs, name);
mergeCount(addNameStruct, preExistingNameStruct, KEY_COUNT);
copyFieldInNamedList(addNameStruct, preExistingNameStruct, KEY_FILING);
copyFieldInNamedList(addNameStruct, preExistingNameStruct, KEY_PREFIX);
}
}
}
return preExisting;
}
@Override
public long extractCount(NamedList<Object> val) {
return ((Number) val.get(KEY_COUNT)).longValue();
}
@Override
public Object updateValueExternalRepresentation(NamedList<Object> internal) {
return null;
}
}
| apache-2.0 |
liyazhou/guava | guava/src/com/google/common/collect/Platform.java | 3414 | /*
* Copyright (C) 2008 The Guava 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.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.EntryTransformer;
import java.lang.reflect.Array;
import java.util.Collections;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
/**
* Methods factored out so that they can be emulated differently in GWT.
*
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
final class Platform {
/**
* Returns a new array of the given length with the same type as a reference
* array.
*
* @param reference any array of the desired type
* @param length the length of the new array
*/
static <T> T[] newArray(T[] reference, int length) {
Class<?> type = reference.getClass().getComponentType();
// the cast is safe because
// result.getClass() == reference.getClass().getComponentType()
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(type, length);
return result;
}
static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
return Collections.newSetFromMap(map);
}
/**
* Configures the given map maker to use weak keys, if possible; does nothing
* otherwise (i.e., in GWT). This is sometimes acceptable, when only
* server-side code could generate enough volume that reclamation becomes
* important.
*/
static MapMaker tryWeakKeys(MapMaker mapMaker) {
return mapMaker.weakKeys();
}
static <K, V1, V2> SortedMap<K, V2> mapsTransformEntriesSortedMap(
SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
return (fromMap instanceof NavigableMap)
? Maps.transformEntries((NavigableMap<K, V1>) fromMap, transformer)
: Maps.transformEntriesIgnoreNavigable(fromMap, transformer);
}
static <K, V> SortedMap<K, V> mapsAsMapSortedSet(
SortedSet<K> set, Function<? super K, V> function) {
return (set instanceof NavigableSet)
? Maps.asMap((NavigableSet<K>) set, function)
: Maps.asMapSortedIgnoreNavigable(set, function);
}
static <E> SortedSet<E> setsFilterSortedSet(SortedSet<E> set, Predicate<? super E> predicate) {
return (set instanceof NavigableSet)
? Sets.filter((NavigableSet<E>) set, predicate)
: Sets.filterSortedIgnoreNavigable(set, predicate);
}
static <K, V> SortedMap<K, V> mapsFilterSortedMap(
SortedMap<K, V> map, Predicate<? super Map.Entry<K, V>> predicate) {
return (map instanceof NavigableMap)
? Maps.filterEntries((NavigableMap<K, V>) map, predicate)
: Maps.filterSortedIgnoreNavigable(map, predicate);
}
private Platform() {}
}
| apache-2.0 |
hortonworks/templeton | src/test/org/apache/hcatalog/templeton/test/tool/TempletonUtilsTest.java | 8301 | /*
* 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.hcatalog.templeton.test.tool;
import static org.junit.Assert.*;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.StringUtils;
import org.apache.hcatalog.templeton.tool.TempletonUtils;
import org.junit.Test;
public class TempletonUtilsTest {
public static final String[] CONTROLLER_LINES = {
"2011-12-15 18:12:21,758 [main] INFO org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - More information at: http://localhost:50030/jobdetails.jsp?jobid=job_201112140012_0047",
"2011-12-15 18:12:46,907 [main] INFO org.apache.pig.tools.pigstats.SimplePigStats - Script Statistics: "
};
@Test
public void testIssetString() {
assertFalse(TempletonUtils.isset((String)null));
assertFalse(TempletonUtils.isset(""));
assertTrue(TempletonUtils.isset("hello"));
}
@Test
public void testIssetTArray() {
assertFalse(TempletonUtils.isset((Long[]) null));
assertFalse(TempletonUtils.isset(new String[0]));
String[] parts = new String("hello.world").split("\\.");
assertTrue(TempletonUtils.isset(parts));
}
@Test
public void testPrintTaggedJobID() {
//JobID job = new JobID();
// TODO -- capture System.out?
}
@Test
public void testExtractPercentComplete() {
assertNull(TempletonUtils.extractPercentComplete("fred"));
for (String line : CONTROLLER_LINES)
assertNull(TempletonUtils.extractPercentComplete(line));
String fifty = "2011-12-15 18:12:36,333 [main] INFO org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - 50% complete";
assertEquals("50% complete", TempletonUtils.extractPercentComplete(fifty));
}
@Test
public void testEncodeArray() {
assertEquals(null, TempletonUtils.encodeArray((String []) null));
String[] tmp = new String[0];
assertTrue(TempletonUtils.encodeArray(new String[0]).length() == 0);
tmp = new String[3];
tmp[0] = "fred";
tmp[1] = null;
tmp[2] = "peter,lisa,, barney";
assertEquals("fred,,peter" +
StringUtils.ESCAPE_CHAR + ",lisa" + StringUtils.ESCAPE_CHAR + "," +
StringUtils.ESCAPE_CHAR + ", barney",
TempletonUtils.encodeArray(tmp));
}
@Test
public void testDecodeArray() {
assertTrue(TempletonUtils.encodeArray((String[]) null) == null);
String[] tmp = new String[3];
tmp[0] = "fred";
tmp[1] = null;
tmp[2] = "peter,lisa,, barney";
String[] tmp2 = TempletonUtils.decodeArray(TempletonUtils.encodeArray(tmp));
try {
for (int i=0; i< tmp.length; i++) {
assertEquals((String) tmp[i], (String)tmp2[i]);
}
} catch (Exception e) {
fail("Arrays were not equal" + e.getMessage());
}
}
@Test
public void testHadoopFsPath() {
try {
TempletonUtils.hadoopFsPath(null, null, null);
TempletonUtils.hadoopFsPath("/tmp", null, null);
TempletonUtils.hadoopFsPath("/tmp", new Configuration(), null);
} catch (FileNotFoundException e) {
fail("Couldn't find /tmp");
} catch (Exception e) {
// This is our problem -- it means the configuration was wrong.
e.printStackTrace();
}
try {
TempletonUtils.hadoopFsPath("/scoobydoo/teddybear",
new Configuration(), null);
fail("Should not have found /scoobydoo/teddybear");
} catch (FileNotFoundException e) {
// Should go here.
} catch (Exception e) {
// This is our problem -- it means the configuration was wrong.
e.printStackTrace();
}
}
@Test
public void testHadoopFsFilename() {
try {
assertEquals(null, TempletonUtils.hadoopFsFilename(null, null, null));
assertEquals(null, TempletonUtils.hadoopFsFilename("/tmp", null, null));
assertEquals("file:/tmp",
TempletonUtils.hadoopFsFilename("/tmp",
new Configuration(),
null));
} catch (FileNotFoundException e) {
fail("Couldn't find name for /tmp");
} catch (Exception e) {
// Something else is wrong
e.printStackTrace();
}
try {
TempletonUtils.hadoopFsFilename("/scoobydoo/teddybear",
new Configuration(), null);
fail("Should not have found /scoobydoo/teddybear");
} catch (FileNotFoundException e) {
// Should go here.
} catch (Exception e) {
// Something else is wrong.
e.printStackTrace();
}
}
@Test
public void testHadoopFsListAsArray() {
try {
assertTrue(TempletonUtils.hadoopFsListAsArray(null, null, null) == null);
assertTrue(TempletonUtils.hadoopFsListAsArray("/tmp, /usr",
null, null) == null);
String[] tmp2
= TempletonUtils.hadoopFsListAsArray("/tmp,/usr",
new Configuration(), null);
assertEquals("file:/tmp", tmp2[0]);
assertEquals("file:/usr", tmp2[1]);
} catch (FileNotFoundException e) {
fail("Couldn't find name for /tmp");
} catch (Exception e) {
// Something else is wrong
e.printStackTrace();
}
try {
TempletonUtils.hadoopFsListAsArray("/scoobydoo/teddybear,joe",
new Configuration(),
null);
fail("Should not have found /scoobydoo/teddybear");
} catch (FileNotFoundException e) {
// Should go here.
} catch (Exception e) {
// Something else is wrong.
e.printStackTrace();
}
}
@Test
public void testHadoopFsListAsString() {
try {
assertTrue(TempletonUtils.hadoopFsListAsString(null, null, null) == null);
assertTrue(TempletonUtils.hadoopFsListAsString("/tmp,/usr",
null, null) == null);
assertEquals("file:/tmp,file:/usr", TempletonUtils.hadoopFsListAsString
("/tmp,/usr", new Configuration(), null));
} catch (FileNotFoundException e) {
fail("Couldn't find name for /tmp");
} catch (Exception e) {
// Something else is wrong
e.printStackTrace();
}
try {
TempletonUtils.hadoopFsListAsString("/scoobydoo/teddybear,joe",
new Configuration(),
null);
fail("Should not have found /scoobydoo/teddybear");
} catch (FileNotFoundException e) {
// Should go here.
} catch (Exception e) {
// Something else is wrong.
e.printStackTrace();
}
}
}
| apache-2.0 |
dash-/apache-openaz | openaz-xacml-pdp/src/main/java/org/apache/openaz/xacml/pdp/std/combiners/OnlyOneApplicable.java | 3800 | /*
* 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.openaz.xacml.pdp.std.combiners;
import java.util.Iterator;
import java.util.List;
import org.apache.openaz.xacml.api.Decision;
import org.apache.openaz.xacml.api.Identifier;
import org.apache.openaz.xacml.pdp.eval.EvaluationContext;
import org.apache.openaz.xacml.pdp.eval.EvaluationException;
import org.apache.openaz.xacml.pdp.eval.EvaluationResult;
import org.apache.openaz.xacml.pdp.eval.MatchResult;
import org.apache.openaz.xacml.pdp.policy.CombinerParameter;
import org.apache.openaz.xacml.pdp.policy.CombiningElement;
import org.apache.openaz.xacml.pdp.policy.PolicySetChild;
import org.apache.openaz.xacml.std.StdStatus;
import org.apache.openaz.xacml.std.StdStatusCode;
/**
* OnlyOneApplicable extends {@link org.apache.openaz.xacml.pdp.std.combiners.CombiningAlgorithmBase} to
* implement the XACML 1.0 "only-one-applicable" combining algorithm for policies and rules.
*
* @param <T> the java class of the object to be combined
*/
public class OnlyOneApplicable extends CombiningAlgorithmBase<PolicySetChild> {
public OnlyOneApplicable(Identifier identifierIn) {
super(identifierIn);
}
@Override
public EvaluationResult combine(EvaluationContext evaluationContext,
List<CombiningElement<PolicySetChild>> elements,
List<CombinerParameter> combinerParameters) throws EvaluationException {
Iterator<CombiningElement<PolicySetChild>> iterElements = elements.iterator();
PolicySetChild policySetChildApplicable = null;
while (iterElements.hasNext()) {
CombiningElement<PolicySetChild> combiningElement = iterElements.next();
MatchResult matchResultElement = combiningElement.getEvaluatable().match(evaluationContext);
switch (matchResultElement.getMatchCode()) {
case INDETERMINATE:
return new EvaluationResult(Decision.INDETERMINATE, matchResultElement.getStatus());
case MATCH:
if (policySetChildApplicable == null) {
policySetChildApplicable = combiningElement.getEvaluatable();
} else {
return new EvaluationResult(Decision.INDETERMINATE,
new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR,
"More than one applicable policy"));
}
break;
case NOMATCH:
break;
default:
throw new EvaluationException("Illegal Decision: \""
+ matchResultElement.getMatchCode().toString());
}
}
if (policySetChildApplicable != null) {
return policySetChildApplicable.evaluate(evaluationContext);
} else {
return new EvaluationResult(Decision.NOTAPPLICABLE);
}
}
}
| apache-2.0 |
NECCSiPortal/NECCSPortal-dashboard | nec_portal/dashboards/project/history/views.py | 8258 | # -*- coding: utf-8 -*-
# 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.
#
"""
Views for managing operation logs.
"""
from datetime import date
from datetime import datetime
try:
import urllib2
except Exception:
import urllib.request as urllib2
from django.core.urlresolvers import reverse_lazy
from django.http import Http404
from django.http import HttpResponseForbidden
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from horizon import forms
from nec_portal.dashboards.project.history import forms as history_forms
from nec_portal.local import nec_portal_settings
# iframe src for project/history
PROJECT_HISTORY_FRAME = \
getattr(nec_portal_settings, 'PROJECT_HISTORY_FRAME', '')
DATE_FORMAT = '%Y-%m-%d'
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
START_TIME = ' 00:00:00'
END_TIME = ' 23:59:59'
QUERY_ADD_START = 'AND ('
QUERY_ADD_END = ')'
QUERY_START_MILISEC = '.000Z'
QUERY_END_MILISEC = '.999Z'
# Dictionary for query format
QUERY_DICTIONARY = {
'project_id': '',
'search': '',
'start': '',
'end': '',
}
SESSION_HISTORY_KEY = 'project_history'
# Dictionary for session
SESSION_DICTIONARY = {
'search': '',
'start': '',
'end': '',
}
class IndexView(forms.ModalFormView):
form_class = history_forms.HistoryForm
form_id = "history_modal"
modal_header = ""
modal_id = "history_modal"
page_title = _("Operation Log")
submit_label = _("Filter")
submit_url = reverse_lazy("horizon:project:history:index")
template_name = 'project/history/index.html'
def get_initial(self):
request = self.request
# Initialize value
search_value = ''
default_term = get_default_term()
start_value = default_term[0]
end_value = default_term[1]
referer_url = request.META.get('HTTP_REFERER')
if SESSION_HISTORY_KEY not in request.session.keys():
SESSION_DICTIONARY['search'] = search_value
SESSION_DICTIONARY['start'] = start_value
SESSION_DICTIONARY['end'] = end_value
request.session[SESSION_HISTORY_KEY] = SESSION_DICTIONARY
session = request.session.get(SESSION_HISTORY_KEY, SESSION_DICTIONARY)
if request.method == 'POST':
# When request's method is POST, value get from POST data.
if 'search' in request.POST.keys():
search_value = request.POST['search'].encode('utf-8')
else:
search_value = session.get('search', search_value)
if 'start' in request.POST.keys():
start_value = request.POST['start'] + (
START_TIME if str(request.POST['start']) else '')
else:
start_value = session.get('start', start_value)
if 'end' in request.POST.keys():
end_value = request.POST['end'] + (
END_TIME if str(request.POST['end']) else '')
else:
end_value = session.get('end', end_value)
SESSION_DICTIONARY['search'] = search_value
if start_value == '' or end_value == '':
start_value = default_term[0]
end_value = default_term[1]
SESSION_DICTIONARY['start'] = start_value
SESSION_DICTIONARY['end'] = end_value
request.session[SESSION_HISTORY_KEY] = SESSION_DICTIONARY
elif referer_url is not None and request.path in referer_url:
# When reload screen, value get from session data.
search_value = session.get('search', search_value)
start_value = session.get('start', start_value)
end_value = session.get('end', end_value)
if (not start_value) or (not end_value):
start_value = default_term[0] + DATETIME_FORMAT
end_value = default_term[1] + DATETIME_FORMAT
return {
'search': search_value,
'start': datetime.strptime(start_value, DATETIME_FORMAT).date(),
'end': datetime.strptime(end_value, DATETIME_FORMAT).date(),
}
def form_valid(self, form):
return form.handle(self.request, form.cleaned_data)
class DetailView(forms.ModalFormView):
form_class = history_forms.HistoryForm
form_id = "history_modal"
modal_header = ""
modal_id = "history_modal"
page_title = _("Operation Log")
submit_label = _("Filter")
submit_url = reverse_lazy("horizon:project:history:index")
template_name = 'project/history/index.html'
def dispatch(self, request, *args, **kwargs):
if request.META.get('HTTP_REFERER') is None:
raise Http404
if not request.user.is_authenticated():
return HttpResponseForbidden()
if PROJECT_HISTORY_FRAME == '':
raise Http404
project_id = 'None'
if request.user.is_authenticated():
project_id = request.user.project_id
# Initialize dictionary
QUERY_DICTIONARY['project_id'] = \
urllib2.quote(str('project_id:"' + project_id + '"'))
QUERY_DICTIONARY['search'] = ''
QUERY_DICTIONARY['start'] = ''
QUERY_DICTIONARY['end'] = ''
session = request.session.get(SESSION_HISTORY_KEY,
SESSION_DICTIONARY)
if not session['search'] == '':
QUERY_DICTIONARY['search'] = \
urllib2.quote(
QUERY_ADD_START + session['search'] + QUERY_ADD_END)
if session['start'] == '' or session['end'] == '':
default_term = get_default_term()
start_datetime = datetime.strptime(default_term[0],
DATETIME_FORMAT)
end_datetime = datetime.strptime(default_term[1],
DATETIME_FORMAT)
session['start'] = default_term[0]
session['end'] = default_term[1]
else:
start_datetime = datetime.strptime(
session['start'],
DATETIME_FORMAT
)
end_datetime = datetime.strptime(session['end'], DATETIME_FORMAT)
if start_datetime > end_datetime:
default_term = get_default_term()
start_datetime = datetime.strptime(default_term[0],
DATETIME_FORMAT)
end_datetime = datetime.strptime(default_term[1],
DATETIME_FORMAT)
session['start'] = default_term[0]
session['end'] = default_term[1]
QUERY_DICTIONARY['start'] = \
urllib2.quote(
start_datetime.strftime(DATETIME_FORMAT).replace(' ', 'T')
+ QUERY_START_MILISEC)
QUERY_DICTIONARY['end'] = \
urllib2.quote(
end_datetime.strftime(DATETIME_FORMAT).replace(' ', 'T')
+ QUERY_END_MILISEC)
return redirect(PROJECT_HISTORY_FRAME % QUERY_DICTIONARY)
def char_to_int(value):
try:
# Try whether it can be converted into an integer
return int(value)
except ValueError:
return 0
def get_default_term():
today = date.today()
year = today.year
month = today.month
months = char_to_int(getattr(nec_portal_settings, 'DEFAULT_PERIOD', '13'))
while True:
if month - months <= 0:
year -= 1
month += 12
else:
month -= months
break
start_value = datetime.strftime(
datetime(year, month, 1).date(),
DATE_FORMAT) + START_TIME
end_value = datetime.strftime(today, DATE_FORMAT) + END_TIME
return [start_value, end_value]
| apache-2.0 |
hpcc-systems/cpp-driver | src/hash.hpp | 1509 | /*
Copyright (c) 2014-2016 DataStax
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __CASS_HASH_HPP_INCLUDED__
#define __CASS_HASH_HPP_INCLUDED__
#include <algorithm>
#include <stdint.h>
namespace cass { namespace hash {
typedef int (Op)(int);
inline int nop(int c) { return c; }
#if defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__)
#define FNV1_64_INIT 0xcbf29ce484222325ULL
#define FNV1_64_PRIME 0x100000001b3ULL
inline uint64_t fnv1a(const char* data, size_t length, Op op = nop) {
uint64_t h = FNV1_64_INIT;
for (size_t i = 0; i < length; ++i) {
h ^= static_cast<uint64_t>(op(data[i]));
h *= FNV1_64_PRIME;
}
return h;
}
#else
#define FNV1_32_INIT 0x811c9dc5
#define FNV1_32_PRIME 0x01000193
inline uint32_t fnv1a(const char* data, size_t length, Op op = nop) {
uint32_t h = FNV1_32_INIT;
for (size_t i = 0; i < length; ++i) {
h ^= static_cast<uint32_t>(op(data[i]));
h *= FNV1_32_PRIME;
}
return h;
}
#endif
} } // namespace cass::hash
#endif
| apache-2.0 |
SAP/go-hdb | driver/unicode/cesu8/cesu8.go | 4938 | // SPDX-FileCopyrightText: 2014-2022 SAP SE
//
// SPDX-License-Identifier: Apache-2.0
// Package cesu8 implements functions and constants to support text encoded in CESU-8.
// It implements functions comparable to the unicode/utf8 package for UTF-8 de- and encoding.
package cesu8
import (
"unicode/utf16"
"unicode/utf8"
)
const (
// CESUMax is the maximum amount of bytes used by an CESU-8 codepoint encoding.
CESUMax = 6
)
// Size returns the amount of bytes needed to encode an UTF-8 byte slice to CESU-8.
func Size(p []byte) int {
n := 0
for i := 0; i < len(p); {
r, size, _ := decodeRune(p[i:])
i += size
n += RuneLen(r)
}
return n
}
// StringSize is like Size with a string as parameter.
func StringSize(s string) int {
n := 0
for _, r := range s {
n += RuneLen(r)
}
return n
}
// EncodeRune writes into p (which must be large enough) the CESU-8 encoding of the rune. It returns the number of bytes written.
func EncodeRune(p []byte, r rune) int {
if r <= rune3Max {
return encodeRune(p, r)
}
high, low := utf16.EncodeRune(r)
n := encodeRune(p, high)
n += encodeRune(p[n:], low)
return n
}
// FullRune reports whether the bytes in p begin with a full CESU-8 encoding of a rune.
func FullRune(p []byte) bool {
high, n, short := decodeRune(p)
if short {
return false
}
if !utf16.IsSurrogate(high) {
return true
}
_, _, short = decodeRune(p[n:])
return !short
}
// DecodeRune unpacks the first CESU-8 encoding in p and returns the rune and its width in bytes.
func DecodeRune(p []byte) (rune, int) {
high, n1, _ := decodeRune(p)
if !utf16.IsSurrogate(high) {
return high, n1
}
low, n2, _ := decodeRune(p[n1:])
if low == utf8.RuneError {
return low, n1 + n2
}
return utf16.DecodeRune(high, low), n1 + n2
}
// RuneLen returns the number of bytes required to encode the rune.
func RuneLen(r rune) int {
switch {
case r < 0:
return -1
case r <= rune1Max:
return 1
case r <= rune2Max:
return 2
case r <= rune3Max:
return 3
case r <= utf8.MaxRune:
return CESUMax
}
return -1
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Copied from unicode utf8
// - allow utf8 encoding of utf16 surrogate values
// - see (*) for code changes
// Code points in the surrogate range are not valid for UTF-8.
// (*) const not needed
// const (
// surrogateMin = 0xD800
// surrogateMax = 0xDFFF
// )
const (
t1 = 0x00 // 0000 0000
tx = 0x80 // 1000 0000
t2 = 0xC0 // 1100 0000
t3 = 0xE0 // 1110 0000
t4 = 0xF0 // 1111 0000
t5 = 0xF8 // 1111 1000
maskx = 0x3F // 0011 1111
mask2 = 0x1F // 0001 1111
mask3 = 0x0F // 0000 1111
mask4 = 0x07 // 0000 0111
rune1Max = 1<<7 - 1
rune2Max = 1<<11 - 1
rune3Max = 1<<16 - 1
)
func encodeRune(p []byte, r rune) int {
// Negative values are erroneous. Making it unsigned addresses the problem.
switch i := uint32(r); {
case i <= rune1Max:
p[0] = byte(r)
return 1
case i <= rune2Max:
p[0] = t2 | byte(r>>6)
p[1] = tx | byte(r)&maskx
return 2
// case i > MaxRune, surrogateMin <= i && i <= surrogateMax: // replaced (*)
case i > utf8.MaxRune: // (*)
r = utf8.RuneError
fallthrough
case i <= rune3Max:
p[0] = t3 | byte(r>>12)
p[1] = tx | byte(r>>6)&maskx
p[2] = tx | byte(r)&maskx
return 3
default:
p[0] = t4 | byte(r>>18)
p[1] = tx | byte(r>>12)&maskx
p[2] = tx | byte(r>>6)&maskx
p[3] = tx | byte(r)&maskx
return 4
}
}
func decodeRune(p []byte) (r rune, size int, short bool) {
n := len(p)
if n < 1 {
return utf8.RuneError, 0, true
}
c0 := p[0]
// 1-byte, 7-bit sequence?
if c0 < tx {
return rune(c0), 1, false
}
// unexpected continuation byte?
if c0 < t2 {
return utf8.RuneError, 1, false
}
// need first continuation byte
if n < 2 {
return utf8.RuneError, 1, true
}
c1 := p[1]
if c1 < tx || t2 <= c1 {
return utf8.RuneError, 1, false
}
// 2-byte, 11-bit sequence?
if c0 < t3 {
r = rune(c0&mask2)<<6 | rune(c1&maskx)
if r <= rune1Max {
return utf8.RuneError, 1, false
}
return r, 2, false
}
// need second continuation byte
if n < 3 {
return utf8.RuneError, 1, true
}
c2 := p[2]
if c2 < tx || t2 <= c2 {
return utf8.RuneError, 1, false
}
// 3-byte, 16-bit sequence?
if c0 < t4 {
r = rune(c0&mask3)<<12 | rune(c1&maskx)<<6 | rune(c2&maskx)
if r <= rune2Max {
return utf8.RuneError, 1, false
}
// do not throw error on surrogates // (*)
// if surrogateMin <= r && r <= surrogateMax {
// return RuneError, 1, false
//}
return r, 3, false
}
// need third continuation byte
if n < 4 {
return utf8.RuneError, 1, true
}
c3 := p[3]
if c3 < tx || t2 <= c3 {
return utf8.RuneError, 1, false
}
// 4-byte, 21-bit sequence?
if c0 < t5 {
r = rune(c0&mask4)<<18 | rune(c1&maskx)<<12 | rune(c2&maskx)<<6 | rune(c3&maskx)
if r <= rune3Max || utf8.MaxRune < r {
return utf8.RuneError, 1, false
}
return r, 4, false
}
// error
return utf8.RuneError, 1, false
}
| apache-2.0 |