repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
drumonii/LeagueTrollBuild
|
backend/src/main/java/com/drumonii/loltrollbuild/batch/maps/MapsRetrievalItemReadListener.java
|
<filename>backend/src/main/java/com/drumonii/loltrollbuild/batch/maps/MapsRetrievalItemReadListener.java<gh_stars>1-10
package com.drumonii.loltrollbuild.batch.maps;
import com.drumonii.loltrollbuild.model.GameMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.ItemReadListener;
public class MapsRetrievalItemReadListener implements ItemReadListener<GameMap> {
private static final Logger LOGGER = LoggerFactory.getLogger(MapsRetrievalItemReadListener.class);
@Override
public void beforeRead() {
// nothing to do before read
}
@Override
public void afterRead(GameMap gameMap) {
LOGGER.info("Finished reading Map: {}", gameMap.getMapName());
}
@Override
public void onReadError(Exception ex) {
// nothing to do on read error
}
}
|
alexamy/electric-circuit-testing-platform
|
spec/features/tests/index_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
feature 'User can view list of tests', "
In order to start preferable test
As an unauthenticated user
I would like to select a test
" do
given(:student) { create(:student) }
given!(:test) { create(:test, name: 'with questions') }
given!(:test_without_questions) { create(:test, name: 'without questions') }
given!(:questions) { create_list(:question, 3, test: test) }
scenario 'User views list of tests' do
sign_in(student)
visit tests_path
expect(page).not_to have_content test_without_questions.name
expect(page).to have_link test.name, href: start_attempt_path(test)
end
end
|
colesadam/hill-lists
|
app/src/main/java/uk/colessoft/android/hilllist/ui/activity/AboutActivity.java
|
package uk.colessoft.android.hilllist.ui.activity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.util.Linkify;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Map;
import uk.colessoft.android.hilllist.R;
import uk.colessoft.android.hilllist.utility.ResourceUtils;
public class AboutActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
TextView link = (TextView) findViewById(R.id.abt1);
Map<String,String> attributions= ResourceUtils.getHashMapResource(this,R.xml.cc_attributions);
for(String key:attributions.keySet()){
if(key.endsWith("attribution")) {
TextView atv = new TextView(this);
atv.setText(key.replace("_attribution"," ").replace("_"," ").toUpperCase()+attributions.get(key));
TextView ltv = new TextView(this);
ltv.setText(attributions.get(key.replace("attribution", "link")));
ltv.setPadding(0, 0, 0, getResources().getDimensionPixelSize(R.dimen.about_padding));
Linkify.addLinks(atv, Linkify.ALL);
Linkify.addLinks(ltv, Linkify.ALL);
((LinearLayout)findViewById(R.id.aboutLayout)).addView(atv);
((LinearLayout)findViewById(R.id.aboutLayout)).addView(ltv);
}
}
Linkify.addLinks(link, Linkify.ALL);
}
}
|
smallst/esper.js
|
src/stdlib/Assert.js
|
'use strict';
const Value = require('../Value');
const CompletionRecord = require('../CompletionRecord');
const ObjectValue = require('../values/ObjectValue');
class AssertFunction extends ObjectValue {
*rawCall(n, evalu, scope) {
if ( n.arguments.length == 0 ) return Value.undef;
let args = new Array(n.arguments.length);
let why = '';
let check = n.arguments[0];
switch ( check.type ) {
case 'BinaryExpression':
let left = yield * evalu.branch(check.left, scope);
let right = yield * evalu.branch(check.right, scope);
args[0] = yield * evalu.doBinaryEvaluation(check.operator, left, right, scope);
why = n.arguments[0].srcName + ' (' + left.debugString + ' ' + check.operator + ' ' + right.debugString + ')';
break;
default:
why = (n.arguments[0].srcName || '???');
args[0] = yield * evalu.branch(n.arguments[0], scope);
}
for ( let i = 1; i < args.length; ++i ) {
args[i] = yield * evalu.branch(n.arguments[i], scope);
}
if ( args[0].truthy ) return Value.undef;
if ( args.length > 1 ) why = yield * args[1].toStringNative();
let err = scope.realm.Error.make(why, 'AssertionError');
return new CompletionRecord(CompletionRecord.THROW, err);
}
*call(thiz, args, scope, ext) {
let val = Value.undef;
if ( args.length > 0 ) return Value.undef;
if ( val.truthy ) return Value.undef;
let reason = '';
if ( args.length > 1 ) {
reason = ( yield * args[1].toStringValue() ).toNative();
} else if ( ext.callNode && ext.callNode.arguments[0] ) {
reason = (ext.callNode.arguments[0].srcName || '???');
}
let err = scope.realm.Error.make(reason, 'AssertionError');
return new CompletionRecord(CompletionRecord.THROW, err);
}
}
module.exports = AssertFunction;
|
shalomeir/generator-snippod-hackathon
|
client/scripts/actions/messagesActions.js
|
<reponame>shalomeir/generator-snippod-hackathon
'use strict';
var Reflux = require('reflux'),
assign = require('object-assign');
var messagesActions = Reflux.createActions({
//by pass to store
'setMessages':{},
'setError':{}
});
module.exports = messagesActions;
|
CDFN/panda
|
panda-framework/src/main/java/org/panda_lang/language/resource/internal/java/JavaModule.java
|
<reponame>CDFN/panda
/*
* Copyright (c) 2020 Dzikoysk
*
* 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.panda_lang.language.resource.internal.java;
import org.panda_lang.language.architecture.module.Module;
import org.panda_lang.language.architecture.module.TypeLoader;
import org.panda_lang.language.architecture.type.Autocast;
import org.panda_lang.language.architecture.type.Type;
import org.panda_lang.language.architecture.type.PandaTypeUtils;
import org.panda_lang.language.resource.internal.InternalModuleInfo;
import org.panda_lang.language.resource.internal.InternalModuleInfo.CustomInitializer;
import org.panda_lang.utilities.commons.ClassUtils;
@InternalModuleInfo(module = "java", pkg = "java.lang", classes = {
"String",
"Number",
"Iterable"
})
public final class JavaModule implements CustomInitializer {
@Override
public void initialize(Module module, TypeLoader typeLoader) {
PandaTypeUtils.of(module, void.class);
PandaTypeUtils.of(module, Void.class);
type(module, typeLoader, "Int", int.class);
type(module, typeLoader, "Bool", boolean.class);
type(module, typeLoader, "Char", char.class);
type(module, typeLoader, "Byte", byte.class);
type(module, typeLoader, "Short", short.class);
type(module, typeLoader, "Long", long.class);
type(module, typeLoader, "Float", float.class);
type(module, typeLoader, "Double", double.class);
typeLoader.load(module, Object.class);
Type intType = generate(module, typeLoader, int.class, "Int");
Type boolType = generate(module, typeLoader, boolean.class, "Bool");
Type charType = generate(module, typeLoader, char.class, "Char");
Type byteType = generate(module, typeLoader, byte.class, "Byte");
Type shortType = generate(module, typeLoader, short.class, "Short");
Type longType = generate(module, typeLoader, long.class, "Long");
Type floatType = generate(module, typeLoader, float.class, "Float");
Type doubleType = generate(module, typeLoader, double.class, "Double");
intType.addAutocast(longType, (Autocast<Number, Long>) (originalType, object, resultType) -> object.longValue());
intType.addAutocast(doubleType, (Autocast<Number, Double>) (originalType, object, resultType) -> object.doubleValue());
intType.addAutocast(floatType, (Autocast<Number, Float>) (originalType, object, resultType) -> object.floatValue());
floatType.addAutocast(doubleType, (Autocast<Number, Double>) (originalType, object, resultType) -> object.doubleValue());
charType.addAutocast(intType, (Autocast<Character, Integer>) (originalType, object, resultType) -> Character.getNumericValue(object));
byteType.addAutocast(intType, (Autocast<Number, Integer>) (originalType, object, resultType) -> object.intValue());
shortType.addAutocast(intType, (Autocast<Number, Integer>) (originalType, object, resultType) -> object.intValue());
}
private void type(Module module, TypeLoader typeLoader, String name, Class<?> primitiveClass) {
PandaTypeUtils.of(module, "Primitive" + name, primitiveClass);
typeLoader.load(module, ClassUtils.getNonPrimitiveClass(primitiveClass), name);
}
private Type generate(Module module, TypeLoader typeLoader, Class<?> primitiveClass, String name) {
PandaTypeUtils.of(module, "Primitive" + name, primitiveClass);
return typeLoader.load(module, ClassUtils.getNonPrimitiveClass(primitiveClass), name);
}
}
|
pm4j/org.pm4j
|
pm4j-common/src/main/java/org/pm4j/common/util/collection/FilteringIterable.java
|
package org.pm4j.common.util.collection;
import java.util.Iterator;
/**
* An iterator that filters the items of a given base iterator.
*/
public abstract class FilteringIterable<T> implements Iterable<T> {
private Iterable<T> baseIterable;
public FilteringIterable(Iterable<T> baseIterable) {
this.baseIterable = baseIterable;
}
@Override
public Iterator<T> iterator() {
return new FilteringIterator<T>(baseIterable) {
@Override
protected boolean doesMatch(T t) {
return FilteringIterable.this.doesMatch(t);
}
};
}
protected abstract boolean doesMatch(T t);
}
|
pidster/spring-migration-analyzer
|
analyze/src/test/java/org/springframework/migrationanalyzer/analyze/fs/support/FileFileSystemEntryTests.java
|
/*
* Copyright 2010 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.springframework.migrationanalyzer.analyze.fs.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.junit.Test;
public class FileFileSystemEntryTests {
@Test
public void getName() {
File root = new File("src/test/resources");
File file = new File(root, "file-file-system-entry/file.txt");
FileFileSystemEntry entry = new FileFileSystemEntry(root, file);
assertEquals("file-file-system-entry/file.txt", entry.getName());
}
@Test
public void isDirectory() {
File root = new File("src/test/resources");
File file = new File(root, "file-file-system-entry");
FileFileSystemEntry entry = new FileFileSystemEntry(root, file);
assertTrue(entry.isDirectory());
root = new File("src/test/resources");
file = new File(root, "file-file-system-entry/file.txt");
entry = new FileFileSystemEntry(root, file);
assertFalse(entry.isDirectory());
}
@Test
public void getReaderFromDirectoryEntry() {
File root = new File("src/test/resources");
File file = new File(root, "file-file-system-entry");
FileFileSystemEntry entry = new FileFileSystemEntry(root, file);
try {
entry.getReader();
fail("getReader should fail for a directory entry");
} catch (RuntimeException re) {
assertEquals("Cannot create Reader for directory entry 'file-file-system-entry'", re.getMessage());
}
}
@Test
public void getInputStreamFromDirectoryEntry() {
File root = new File("src/test/resources");
File file = new File(root, "file-file-system-entry");
FileFileSystemEntry entry = new FileFileSystemEntry(root, file);
try {
entry.getInputStream();
fail("getInputStream should fail for a directory entry");
} catch (RuntimeException re) {
assertEquals("Cannot create InputStream for directory entry 'file-file-system-entry'", re.getMessage());
}
}
@Test
public void getReader() throws IOException {
File root = new File("src/test/resources");
File file = new File(root, "file-file-system-entry/file.txt");
FileFileSystemEntry entry = new FileFileSystemEntry(root, file);
Reader reader = entry.getReader();
BufferedReader bufferedReader = new BufferedReader(reader);
assertEquals("Some content", bufferedReader.readLine());
assertNull(bufferedReader.readLine());
}
@Test
public void getInputStream() throws IOException {
File root = new File("src/test/resources");
File file = new File(root, "file-file-system-entry/file.txt");
FileFileSystemEntry entry = new FileFileSystemEntry(root, file);
InputStream inputStream = entry.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
assertEquals("Some content", bufferedReader.readLine());
assertNull(bufferedReader.readLine());
}
}
|
philswan/vms-tool
|
node_modules/xo/node_modules/eslint-plugin-ava/rules/no-unknown-modifiers.js
|
'use strict';
var createAvaRule = require('../create-ava-rule');
var modifiers = [
'after',
'afterEach',
'before',
'beforeEach',
'cb',
'only',
'serial',
'skip',
'todo'
];
function getTestModifiers(node) {
if (node.type === 'CallExpression') {
return getTestModifiers(node.callee);
}
if (node.type === 'MemberExpression') {
return getTestModifiers(node.object).concat(node.property.name);
}
return [];
}
function unknownModifiers(node) {
return getTestModifiers(node)
.filter(function (modifier) {
return modifiers.indexOf(modifier) === -1;
});
}
module.exports = function (context) {
var ava = createAvaRule();
return ava.merge({
CallExpression: function (node) {
if (!ava.isTestFile || ava.currentTestNode !== node) {
return;
}
var unknown = unknownModifiers(node);
if (unknown.length !== 0) {
context.report({
node: node,
message: 'Unknown test modifier `' + unknown[0] + '`.'
});
}
}
});
};
|
lanpinguo/apple-sauce
|
ofagent/indigo/modules/OFConnectionManager/module/src/ofconnectionmanager_int.h
|
/****************************************************************
*
* Copyright 2013, Big Switch Networks, Inc.
*
* Licensed under the Eclipse Public License, Version 1.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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.
*
****************************************************************/
/**
* @file
* @brief Private module definitions for OF connection manager
*/
#ifndef __OFCONNECTIONMANAGER_INT_H__
#define __OFCONNECTIONMANAGER_INT_H__
#include <OFConnectionManager/ofconnectionmanager_config.h>
#include "ofconnectionmanager_log.h"
#include "cxn_instance.h"
#include <cjson/cJSON.h>
/* Very verbose for debugging */
/* #define OF_CXN_DUMP_ALL_OBJECTS 1 */
#if defined(OF_CXN_DUMP_ALL_OBJECTS) /* Global enable for logging OF objects */
#define LOG_OBJECT(obj) of_object_log(obj)
#else
#define LOG_OBJECT(obj)
#endif
/**
* Try an operation and return the error code on failure.
*/
#define _TRY(op) do { \
int _rv; \
if ((_rv = (op)) < 0) { \
AIM_LOG_ERROR("ERROR %d at %s:%d\n", _rv, __FILE__, __LINE__); \
return _rv; \
} \
} while (0)
/**
* Does the connection manager have a local connection?
*/
extern int have_local_connection;
/**
* How many remote connections does the connection manager have?
*/
extern int remote_connection_count;
/**
* Role request generation ID
*/
extern uint64_t ind_cxn_generation_id;
/* conversion functions from cookie with generation id to connection and vice versa */
void *cxn_to_cookie(connection_t *cxn);
connection_t* cookie_to_cxn(void* cookie);
/*
* Priority for sockets and timers registered with SocketManager.
*/
#define IND_CXN_EVENT_PRIORITY 10
extern void indigo_cxn_socket_ready_callback(int socket_id,
void *cookie,
int read_ready,
int write_ready,
int error_seen);
extern void ind_cxn_local_listen_socket_ready(int socket_id,
void *cookie,
int read_ready,
int write_ready,
int error_seen);
extern int ind_cxn_xid_get(void);
extern indigo_error_t ind_cxn_send_controller_message(indigo_cxn_id_t cxn_id,
of_object_t *obj);
extern void cxn_message_track_setup(connection_t *cxn, of_object_t *obj);
void ind_cxn_change_master(indigo_cxn_id_t master_id);
void ind_cxn_populate_connection_list(of_list_bsn_controller_connection_t *list);
/**
* The OF message callback vector from state manager
*/
#define OF_MSG_CALLBACK(cxn, obj) \
indigo_core_receive_controller_message((cxn)->cxn_id, obj)
/**
* A connection instance calls this when it has data ready for output
* @param sd The socket descriptor that will be written to
*/
#define CXN_WRITE_READY(sd) ind_soc_data_out_ready(sd)
#define CXN_WRITE_CLEAR(sd) ind_soc_data_out_clear(sd)
/****************************************************************
* Status change callback bookkeeping
****************************************************************/
extern void ind_cxn_status_change(connection_t *cxn);
/****************************************************************
* State machine timeout handler
****************************************************************/
extern void ind_cxn_state_timeout(void *cookie);
/****************************************************************
* Logging/debug helpers
****************************************************************/
extern void ind_cxn_stats_show(aim_pvs_t* pvs, int details);
/**
* @brief Update the configuration of the connection manager
* @param config Pointer to the implementation specific configuration
* structure
*/
extern const struct ind_cfg_ops ind_cxn_cfg_ops;
#include <OFConnectionManager/ofconnectionmanager.h>
#endif /* __OFCONNECTIONMANAGER_INT_H__ */
|
imcloudfloating/Cloud-OJ
|
judge-service/src/main/java/group/_204/oj/judge/component/Judgement.java
|
<filename>judge-service/src/main/java/group/_204/oj/judge/component/Judgement.java
package group._204.oj.judge.component;
import com.fasterxml.jackson.databind.ObjectMapper;
import group._204.oj.judge.dao.*;
import group._204.oj.judge.error.UnsupportedLanguageError;
import group._204.oj.judge.model.*;
import group._204.oj.judge.model.Runtime;
import group._204.oj.judge.type.Language;
import group._204.oj.judge.type.SolutionResult;
import group._204.oj.judge.type.SolutionState;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;
import java.util.*;
@Slf4j
@Component
public class Judgement {
private static final Integer MAX_MEM_LIMIT = 512; // MB
@Value("${project.file-dir}")
private String fileDir;
@Value("${project.code-dir}")
private String codeDir;
@Resource
private ObjectMapper objectMapper;
@Resource
private RuntimeDao runtimeDao;
@Resource
private CompileDao compileDao;
@Resource
private ProblemDao problemDao;
@Resource
private SolutionDao solutionDao;
@Resource
private RankingDao rankingDao;
@Resource
private DatabaseConfig dbConfig;
@Resource
private Compiler compiler;
private static class RuntimeError extends Exception {
RuntimeError(String msg) {
super(msg);
}
}
@PostConstruct
private void init() {
if (!codeDir.endsWith("/")) {
codeDir += '/';
}
if (!fileDir.endsWith("/")) {
fileDir += '/';
}
}
/**
* 判题入口
* <p>隔离级别:读提交</p>
*
* @param solution {@link Solution}
*/
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public void judge(Solution solution) {
log.info("Judging: solution({}), user({}).", solution.getSolutionId(), solution.getUserId());
// 为当前事务禁用外键约束
dbConfig.disableFKChecks();
Compile compile = compiler.compile(solution);
compileDao.add(compile);
if (compile.getState() == 0) {
Limit limit = problemDao.getLimit(solution.getProblemId());
Runtime runtime = new Runtime(solution.getSolutionId());
runtimeDao.add(runtime);
RunResult result = execute(solution, runtime, limit);
saveResult(solution, runtime, result, limit);
runtimeDao.update(runtime);
} else {
solution.setResult(SolutionResult.CE);
solution.setState(SolutionState.JUDGED);
solutionDao.update(solution);
}
}
/**
* 计算并结果
* <p>计算分数并更新排名</p>
*
* @param result {@link RunResult}
*/
private void saveResult(Solution solution, Runtime runtime, RunResult result, Limit limit) {
if (runtime.getResult() == SolutionResult.IE || runtime.getResult() == SolutionResult.RE) {
solution.setResult(runtime.getResult());
solution.setState(SolutionState.JUDGED);
solutionDao.update(solution);
return;
}
String userId = solution.getUserId();
Integer problemId = solution.getProblemId();
Integer contestId = solution.getContestId();
Double passRate = result.getPassRate();
if (Double.isNaN(passRate)) {
passRate = 0d;
}
// 查询历史提交中的最高分
Double maxScore = solutionDao.getMaxScoreOfUser(userId, problemId, contestId);
runtime.setTotal(result.getTotal());
runtime.setPassed(result.getPassed());
runtime.setTime(result.getTime());
runtime.setMemory(result.getMemory());
solution.setResult(SolutionResult.getByString(result.getResult()));
solution.setPassRate(passRate);
solution.setScore(passRate * limit.getScore());
solution.setState(SolutionState.JUDGED);
solutionDao.update(solution);
// 本次得分不为 0 且历史最高分小于本次得分时才更新排名
if (passRate > 0 && (maxScore == null || maxScore < solution.getScore())) {
if (contestId == null) {
rankingDao.update(userId, solution.getSubmitTime());
} else {
rankingDao.updateContest(contestId, userId, solution.getSubmitTime());
}
}
}
/**
* 执行用户程序
*
* @return 运行结果 {@link RunResult}
*/
private RunResult execute(Solution solution, Runtime runtime, Limit limit) {
RunResult result = null;
try {
String testDataDir = fileDir + "test_data/" + solution.getProblemId();
ProcessBuilder cmd = buildCommand(solution, limit, testDataDir);
result = run(cmd);
} catch (RuntimeError e) {
log.warn("Runtime Error: {}", e.getMessage());
runtime.setInfo(e.getMessage());
runtime.setResult(SolutionResult.RE);
} catch (InterruptedException | IOException | UnsupportedLanguageError e) {
log.warn("Judge Error: {}", e.getMessage());
runtime.setResult(SolutionResult.IE);
runtime.setInfo(e.getMessage());
}
runtimeDao.update(runtime);
return result;
}
/**
* 调用判题程序执行
*
* @param cmd 命令 & 参数
* @return 运行结果 {@link RunResult}
*/
private RunResult run(ProcessBuilder cmd)
throws RuntimeError, IOException, InterruptedException {
RunResult result;
Process process = cmd.start();
int exitValue = process.waitFor();
if (exitValue == 0) {
// 正常退出
String resultStr = IOUtils.toString(process.getInputStream());
result = objectMapper.readValue(resultStr, RunResult.class);
} else {
// 非正常退出
String stderr = IOUtils.toString(process.getErrorStream());
if (exitValue == 1) {
throw new RuntimeError(stderr);
} else {
throw new InterruptedException(stderr);
}
}
process.destroy();
return result;
}
/**
* 生成命令
*/
private ProcessBuilder buildCommand(Solution solution, Limit limit, String testDataDir)
throws UnsupportedLanguageError {
Language language = Language.get(solution.getLanguage());
if (language == null) {
throw new UnsupportedLanguageError("NULL");
}
String solutionDir = codeDir + solution.getSolutionId();
ProcessBuilder builder = new ProcessBuilder();
List<String> cmd = new ArrayList<>();
cmd.add("/opt/bin/judge-runner");
long timeLimit = limit.getTimeout();
int outputLimit = limit.getOutputLimit();
int memoryLimit = limit.getMemoryLimit();
int maxMemoryLimit = memoryLimit << 2;
int procLimit = 0;
// Java/Kotlin/JS 内存限制按 2 倍计算
switch (language) {
case C:
case CPP:
procLimit = 1;
cmd.add("--cmd=./Solution");
break;
case JAVA:
memoryLimit <<= 1;
maxMemoryLimit = 1536;
cmd.add("--cmd=java@Solution");
break;
case KOTLIN:
timeLimit <<= 1;
memoryLimit <<= 1;
maxMemoryLimit = 1536;
cmd.add("--cmd=kotlin@SolutionKt");
break;
case JAVA_SCRIPT:
memoryLimit <<= 1;
cmd.add("--cmd=node@Solution.js");
break;
case PYTHON:
procLimit = 1;
cmd.add("--cmd=python3@Solution.py");
break;
case BASH:
procLimit = 1;
cmd.add("--cmd=sh@Solution.sh");
break;
case C_SHARP:
memoryLimit <<= 1;
cmd.add("--cmd=mono@Solution.exe");
break;
case GO:
maxMemoryLimit = 1536;
cmd.add("--cmd=./Solution");
break;
default:
throw new UnsupportedLanguageError(language.toString());
}
List<String> config = Arrays.asList(
"--time=" + timeLimit,
"--memory=" + memoryLimit,
"--max-memory=" + maxMemoryLimit,
"--output-size=" + outputLimit,
"--workdir=" + solutionDir,
"--data=" + testDataDir,
"--proc=" + procLimit
);
cmd.addAll(config);
builder.command(cmd);
return builder;
}
}
|
Natsurii/nicabot-monkee
|
neko3/features/bot_developer_toolkit.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Nekozilla is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Nekozilla is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Nekozilla. If not, see <https://www.gnu.org/licenses/>.
"""
Bits and bobs helpful when making Discord bots I guess.
"""
from discord import utils
from neko3 import neko_commands
from neko3 import permission_bits
class BotUtils(neko_commands.Cog):
@neko_commands.command(
name="makeinvite",
brief="Generates an OAuth invite URL from a given snowflake client ID",
help="Valid options: ```" + ", ".join(permission_bits.Permissions.__members__.keys()) + "```",
aliases=["devinvite", "mkinvite"],
)
async def generate_invite_command(self, ctx, client_id: str, *permissions: str):
perm_bits = 0
for permission in permissions:
if permission.upper() not in permission_bits.Permissions.__members__.keys():
return await ctx.send(f"{permission} is not recognised.")
else:
perm_bits |= permission_bits.Permissions[permission.upper()]
try:
int(client_id)
await ctx.send(
utils.oauth_url(
client_id, permissions=perm_bits if hasattr(perm_bits, "value") else None, guild=ctx.guild
)
)
except Exception:
await ctx.send("Please provide a valid client ID")
def setup(bot):
bot.add_cog(BotUtils())
|
brycelelbach/hpx
|
src/components/security/certificate_authority_base.cpp
|
<gh_stars>0
// Copyright (c) 2013 <NAME>
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <hpx/config.hpp>
#include <hpx/runtime/actions/basic_action.hpp>
#include <hpx/runtime/components/component_type.hpp>
#include <hpx/components/security/server/certificate_authority_base.hpp>
HPX_REGISTER_COMPONENT_MODULE();
typedef hpx::components::security::server::certificate_authority_base
certificate_authority_base_type;
typedef hpx::components::fixed_component<
certificate_authority_base_type
> certificate_authority_base_component_type;
HPX_DEFINE_GET_COMPONENT_TYPE(certificate_authority_base_type);
HPX_DEFINE_GET_COMPONENT_TYPE(certificate_authority_base_component_type);
HPX_REGISTER_ACTION(
certificate_authority_base_type::sign_certificate_signing_request_action
, certificate_authority_base_sign_certificate_signing_request_action);
HPX_REGISTER_ACTION(
certificate_authority_base_type::get_certificate_action
, certificate_authority_base_get_certificate_action);
HPX_REGISTER_ACTION(
certificate_authority_base_type::is_valid_action
, certificate_authority_base_is_valid_action);
|
boostcd/console-ui
|
src/components/MicroserviceCard/MicroserviceCard.styled.js
|
<reponame>boostcd/console-ui<filename>src/components/MicroserviceCard/MicroserviceCard.styled.js
import { CheckCircle, ExclamationCircle } from '@styled-icons/fa-solid';
import styled, { css } from 'styled-components';
import { ifProp } from 'styled-tools';
import Card from '../Card/Card';
export const Wrapper = styled(Card)`
height: 120px;
margin-top: 0.5rem;
${ifProp('isActive', `background: #e5f4f7;`)};
`;
const testIconStyles = css`
width: 0.8rem;
height: 0.8rem;
margin-left: 0.25rem;
vertical-align: middle;
`;
export const TestsSuccessfulIcon = styled(CheckCircle)`
${testIconStyles};
color: green;
`;
export const TestsFailedIcon = styled(ExclamationCircle)`
${testIconStyles};
color: red;
`;
export const Name = styled.div`
min-height: 1.35rem;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
word-break: break-all;
`;
export const Version = styled.div`
font-weight: bold;
font-size: 0.9rem;
`;
export const Date = styled.div`
color: #a2a2a2;
font-size: 0.8rem;
`;
export const Actions = styled.div`
min-height: 1.5rem;
display: flex;
flex-flow: row;
* ~ * {
margin-left: 0.2rem;
}
`;
|
thezerothcat/LaMulanaRandomizer
|
src/main/java/lmr/randomizer/rcd/object/Chest.java
|
package lmr.randomizer.rcd.object;
/**
* 0x2c chest Reversed
* 0 - item type, 1-10 are drop types, 11+ are inventory word - 11, 0 is empty
* 1 - if drop then quantity
* // if item then item arg 2 (whether it's a real item)
* 2 - if 0 then brown else blue
* 3 - if >0, cursed
* 4 - if 0 then flat curse damage else percentage
* 5 - curse damage
* update 0 // if world[idx] == val then set chest to empty (creation and every frame)
* // op not used
* update 1 // if world[idx] == val then set chest to ajar (creation and every frame)
* // op not used
* update 2 // performed when chest is opened
* update 3 // if chest has item then performed on item pickup
* // if chest has drop then performed on drop
* // if chest is empty then performed when chest is opened
*/
public class Chest extends GameObject {
public static final short COIN_CHEST = 0;
public static final short ITEM_CHEST = 1;
public Chest(ObjectContainer objectContainer, int x, int y) {
super(objectContainer, 6);
setId(ObjectIdConstants.Chest);
setX(x);
setY(y);
}
public Chest(GameObject gameObject) {
super(gameObject);
}
public void setDrops(int dropType, int quantity) {
setDropType(dropType);
setDropQuantity(quantity);
}
public void setDropType(int dropType) {
getArgs().set(0, (short)dropType);
}
public int getDropQuantity() {
return getArgs().get(1);
}
public void setDropQuantity(int quantity) {
getArgs().set(1, (short)quantity);
}
public void setChestGraphic(int chestGraphic) {
getArgs().set(2, (short)chestGraphic);
}
public boolean isCursed() {
return getArgs().get(3) > 0;
}
public void setCursed(boolean cursed) {
getArgs().set(3, (short)(cursed ? 1 : 0));
}
public void setFlatCurseDamage(int damage) {
setPercentDamage(false);
setCurseDamage(damage);
}
public void setPercentCurseDamage(int damage) {
setPercentDamage(true);
setCurseDamage(damage);
}
public void setPercentDamage(boolean percentDamage) {
getArgs().set(4, (short)(percentDamage ? 1 : 0));
}
public void setCurseDamage(int damage) {
getArgs().set(5, (short)damage);
}
public void setEmptyCheck(WriteByteOperation writeByteOperation) {
// update 0 // if world[idx] == val then set chest to empty (creation and every frame)
// op not used
getWriteByteOperations().set(0, writeByteOperation);
}
/**
* @return WriteByteOperation for the chest's puzzle flag
*/
public WriteByteOperation getUnlockedCheck() {
// update 1 // if world[idx] == val then set chest to ajar (creation and every frame)
return getWriteByteOperations().get(1);
}
public void setUnlockedCheck(WriteByteOperation writeByteOperation) {
// update 1 // if world[idx] == val then set chest to ajar (creation and every frame)
getWriteByteOperations().set(1, writeByteOperation);
}
public void setUpdateWhenOpened(WriteByteOperation writeByteOperation) {
// update 2 // performed when chest is opened
getWriteByteOperations().set(2, writeByteOperation);
}
public void setUpdateWhenCollected(WriteByteOperation writeByteOperation) {
// update 3 // if chest has item then performed on item pickup
// if chest has drop then performed on drop
// if chest is empty then performed when chest is opened
getWriteByteOperations().set(3, writeByteOperation);
}
}
|
arnavpisces/saksham-refined
|
app/src/main/java/com/zuccessful/trueharmony/pojo/DailyRoutineRecord.java
|
package com.zuccessful.trueharmony.pojo;
/**
* Created by Admin on 07-08-2018.
*/
public class DailyRoutineRecord {
private String dailyRoutId;
private String name;
private long timestamp;
private int slot;
private int done;
public DailyRoutineRecord() {
}
public DailyRoutineRecord(String dailyRoutId, String name, long timestamp, int slot, int done) {
this.dailyRoutId = dailyRoutId;
this.name = name;
this.timestamp = timestamp;
this.slot = slot;
this.done = done;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public int getSlot() {
return slot;
}
public void setSlot(int slot) {
this.slot = slot;
}
public String getDailyRoutId() {
return dailyRoutId;
}
public void setDailyRoutId(String dailyRoutId) {
this.dailyRoutId = dailyRoutId;
}
public int isDone() {
return done;
}
public void setDone(int done) {
this.done = done;
}
}
|
seoh/scastie
|
migration/src/main/scala/full.scala
|
import com.olegych.scastie.api._
import java.nio.file._
import System.{lineSeparator => nl}
import play.api.libs.json._
import play.api.libs.functional.syntax._
import java.nio.file._
import scala.collection.JavaConverters._
import play.api.libs.json._
import play.api.libs.json.OFormat
object SnippetProgressV1 {
implicit val formatSnippetProgressV1: Reads[SnippetProgressV1] =
Json.reads[SnippetProgressV1]
}
case class SnippetProgressV1(
snippetId: Option[SnippetIdV1],
userOutput: Option[String],
sbtOutput: Option[String],
compilationInfos: List[Problem],
instrumentations: List[Instrumentation],
runtimeError: Option[RuntimeError],
scalaJsContent: Option[String],
scalaJsSourceMapContent: Option[String],
done: Boolean,
timeout: Boolean,
sbtError: Boolean,
forcedProgramMode: Boolean
)
object InputsV1 {
implicit val reads: Reads[InputsV1] =
Json.reads[InputsV1]
}
case class InputsV1(
worksheetMode: Boolean,
code: String,
target: ScalaTarget,
libraries: Set[ScalaDependency],
librariesFromList: List[(ScalaDependency, ProjectV1)],
sbtConfigExtra: String,
sbtPluginsConfigExtra: String,
showInUserProfile: Boolean = false,
forked: Option[SnippetIdV1]
)
object ProjectV1 {
implicit val reads: Reads[ProjectV1] = {
(
(JsPath \ "organization").read[String] and
(JsPath \ "repository").read[String] and
(
(JsPath \ "logo").read[List[String]].map(logo => logo.headOption) or
(JsPath \ "logo").readNullable[String]
) and
(JsPath \ "artifacts").read[List[String]]
)(ProjectV1.apply _)
}
}
case class ProjectV1(
organization: String,
repository: String,
logo: Option[String],
artifacts: List[String]
)
object UserV1 {
implicit val formatUser: OFormat[UserV1] =
Json.format[UserV1]
}
case class UserV1(login: String, name: Option[String], avatar_url: String)
object SnippetUserPartV1 {
implicit val reads: Reads[SnippetUserPartV1] = {
val r1 =
(
(JsPath \ "login").read[String] and
(JsPath \ "update").read[Int]
)(SnippetUserPartV1.apply _)
val r2 =
(JsPath \ "login").read[String].map(login => SnippetUserPartV1(login, 0))
r1 or r2
}
}
case class SnippetUserPartV1(login: String, update: Int)
object SnippetIdV1 {
implicit val reads: Reads[SnippetIdV1] =
Json.reads[SnippetIdV1]
}
case class SnippetIdV1(base64UUID: String, user: Option[SnippetUserPartV1])
object Main {
def main(args: Array[String]): Unit = {
val dir = Paths.get(args.head)
assert(Files.isDirectory(dir))
val inputs = collection.mutable.Buffer.empty[Path]
val outputs = collection.mutable.Buffer.empty[Path]
/*
_anonymous_
MSTWUrJdQ6uIfeIRTr5n4g
input2.json
output2.json
ches
project_7xo3oHKVRgmQRxZYUxAnRA/
project_7xo3oHKVRgmQRxZYUxAnRA.zip
7xo3oHKVRgmQRxZYUxAnRA
0
input2.json
.snapshot (epfl backup)
*/
def addSnippet(dir: Path): Unit = {
val in = dir.resolve("input2.json")
if (Files.isRegularFile(in)) {
inputs += in
}
val out = dir.resolve("output2.json")
if (Files.isRegularFile(out)) {
outputs += out
}
}
val ignored = Set(".snapshot", ".gitignore")
val ds = Files.newDirectoryStream(dir)
ds.asScala.foreach { user =>
println(user)
if (!(ignored.contains(user.getFileName.toString))) {
val userStream = Files.newDirectoryStream(user)
userStream.asScala.foreach { base64UUID =>
if (Files.isDirectory(base64UUID) &&
!base64UUID.getFileName.toString.startsWith("project_")) {
val baseStream = Files.newDirectoryStream(base64UUID)
baseStream.asScala.foreach { update =>
addSnippet(update)
}
baseStream.close
addSnippet(base64UUID)
}
}
userStream.close
}
}
ds.close()
println()
println("Scanning done. Found")
println(" " + inputs.size + " inputs")
println(" " + outputs.size + " outputs")
val failedInputs = collection.mutable.Buffer.empty[(Path, Throwable)]
var successInputs = 0
def doSuccessInput(inputs: Inputs, path: Path): Unit = {
successInputs += 1
if (successInputs % 100 == 0) {
print("*")
}
val json = Json.prettyPrint(Json.toJson(inputs))
val path2 = path.getParent().resolve("input3.json")
Files.write(path2, json.getBytes)
}
inputs.foreach { path =>
val content = Files.readAllLines(path).toArray.mkString(nl)
try {
Json.fromJson[Inputs](Json.parse(content)) match {
case JsSuccess(inputs, _) => {
doSuccessInput(inputs, path)
}
case jsError1: JsError => {
Json.fromJson[InputsV1](Json.parse(content)) match {
case JsSuccess(inputs, _) => {
doSuccessInput(convert(inputs), path)
}
case jsError2: JsError => {
throw new Exception(
content + nl + nl +
jsError1.toString + nl + nl +
jsError2.toString
)
}
}
}
}
} catch {
case scala.util.control.NonFatal(e) => {
failedInputs += ((path, e))
}
}
}
println("Inputs")
println(" success: " + successInputs)
println(" failure: " + failedInputs.size)
failedInputs
.take(3)
.map(
inputs =>
nl +
"-----------------" +
nl +
inputs.toString +
nl +
"-----------------" +
nl
)
.foreach(println)
val failedOutputs = collection.mutable.Buffer.empty[(Path, Throwable)]
var successOutputs = 0
outputs.foreach { path =>
try {
val outputsLines0 =
Files
.readAllLines(path)
.asScala
.map(
line =>
Json.fromJson[SnippetProgressV1](Json.parse(line)) match {
case JsSuccess(v, _) => v
case jsError: JsError => {
throw new Exception(
jsError.toString + nl +
line
)
}
}
)
val outputsLines =
outputsLines0
.map(ouputs => Json.stringify(Json.toJson(convert(ouputs))))
.mkString(nl)
val path2 = path.getParent().resolve("output3.json")
Files.write(path2, outputsLines.getBytes)
successOutputs += 1
if (successOutputs % 100 == 0) {
print("*")
}
} catch {
case scala.util.control.NonFatal(e) => {
failedOutputs += ((path, e))
}
}
}
println("Outputs")
println(" success: " + successOutputs)
println(" failure: " + failedOutputs.size)
failedOutputs
.take(3)
.map(
inputs =>
nl +
"-----------------" +
nl +
inputs.toString +
nl +
"-----------------" +
nl
)
.foreach(println)
}
private def convert(p: ProjectV1): Project = {
import p._
Project(
organization,
repository,
logo,
artifacts
)
}
private def convert(inputs: InputsV1): Inputs = {
import inputs._
Inputs(
isWorksheetMode = worksheetMode,
code = code,
target = target,
libraries = libraries,
librariesFromList = librariesFromList.map {
case (sd, p) => (sd, convert(p))
},
sbtConfigExtra = sbtConfigExtra,
sbtPluginsConfigExtra = sbtPluginsConfigExtra,
isShowingInUserProfile = showInUserProfile,
forked = forked.map(convert),
)
}
private def convert(user: SnippetUserPartV1): SnippetUserPart = {
import user._
SnippetUserPart(login, update)
}
private def convert(snippetId: SnippetIdV1): SnippetId = {
import snippetId._
SnippetId(
base64UUID = base64UUID,
user = user.map(convert)
)
}
private def convert(progress: SnippetProgressV1): SnippetProgress = {
import progress._
def stdout(line: String) =
ProcessOutput(line, ProcessOutputType.StdOut)
SnippetProgress(
snippetId = snippetId.map(convert),
userOutput = userOutput.map(stdout),
sbtOutput = sbtOutput.map(stdout),
compilationInfos = compilationInfos,
instrumentations = instrumentations,
runtimeError = runtimeError,
scalaJsContent = scalaJsContent,
scalaJsSourceMapContent = scalaJsSourceMapContent,
isDone = done,
isTimeout = timeout,
isSbtError = sbtError,
isForcedProgramMode = forcedProgramMode,
)
}
}
|
Muhammad-Adnan-Ahmad/Aspose.Slides-for-Java
|
Examples/src/main/java/com/aspose/slides/examples/Slides/Charts/SettingNumberFormatForChartDataCell.java
|
<reponame>Muhammad-Adnan-Ahmad/Aspose.Slides-for-Java<filename>Examples/src/main/java/com/aspose/slides/examples/Slides/Charts/SettingNumberFormatForChartDataCell.java
package com.aspose.slides.examples.Slides.Charts;
import com.aspose.slides.ChartType;
import com.aspose.slides.IChart;
import com.aspose.slides.IChartDataPoint;
import com.aspose.slides.IChartSeries;
import com.aspose.slides.IChartSeriesCollection;
import com.aspose.slides.ISlide;
import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
import com.aspose.slides.examples.Utils;
public class SettingNumberFormatForChartDataCell {
public static void main(String[] args) {
//ExStart:SettingNumberFormatForChartDataCell
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingNumberFormatForChartDataCell.class);
// Instantiate the presentation
Presentation pres = new Presentation();
// Access the first presentation slide
ISlide slide = pres.getSlides().get_Item(0);
// Adding a default clustered column chart
IChart chart = slide.getShapes().addChart(ChartType.ClusteredColumn, 50, 50, 500, 400);
// Accessing the chart series collection
IChartSeriesCollection series = chart.getChartData().getSeries();
// Setting the preset number format
// Traverse through every chart series
for (IChartSeries ser : series) {
// Traverse through every data cell in series
for (IChartDataPoint cell : ser.getDataPoints()) {
// Setting the number format
cell.getValue().getAsCell().setPresetNumberFormat((byte) 10); // 0.00%
}
}
// Saving presentation
pres.save(dataDir + "PresetNumberFormat.pptx", SaveFormat.Pptx);
//ExEnd:SettingNumberFormatForChartDataCell
}
}
|
AlexeyMalafeev/kfw-the-game
|
kf_lib/actors/human_controlled_fighter.py
|
<reponame>AlexeyMalafeev/kfw-the-game
from kf_lib.ui import align_text, cls, get_bar, menu, pak, pretty_table
from kf_lib.utils import roman
from .fighter import Fighter
ALIGN = 60
INDENT = 0
# todo break HCF into submodules like Fighter
class HumanControlledFighter(Fighter):
is_human = True
def upgrade_att(self):
self.show('')
self.show(self.get_f_info(show_st_emph=True))
options = self.get_atts_to_choose()
att = menu(options, 'Improve:')
self.change_att(att, 1)
# def choose_best_norm_wp(self):
# wpts = techniques.get_weapon_techs(self)
# line = 'Pick a weapon:'
# if wpts:
# line += f"\n({self.name}'s weapon techniques: {', '.join(wpts)})"
# options = [(f'{wp.name} {wp.descr}', wp) for wp in weapons.NORMAL_WEAPONS]
# wn = self.menu(sorted(options), line)
# self.arm(wn)
def choose_move(self):
if self.is_auto_fighting:
Fighter.choose_move(self)
else:
self.av_moves = self.get_av_moves() # this depends on target
self.see_fight_info(show_opp=True)
# print('status', self.status)
# print('opp status', self.target.status)
# print(self.dfs_bonus)
m_names = [
f'{m.name}{self.get_move_stars(m)}{self.get_move_tier_string(m)}'
for m in self.av_moves
]
max_len = max((len(m_name) for m_name in m_names))
m_hints = [self.get_move_hints(m) for m in self.av_moves]
options = [
('{:<{}} {}'.format(m_names[i], max_len, m_hints[i]), m)
for i, m in enumerate(self.av_moves)
]
options.sort(key=lambda x: not x[1].power)
# print(self.current_fight.order)
d = self.get_vis_distance(self.distances[self.target])
self.action = menu(options, title=f' {d}')
def choose_new_move(self, sample):
first_line = ('Move', 'Tier', 'Dist', 'Pwr', 'Acc', 'Cmpl', 'Sta', 'Time', 'Qi', 'Func')
options = [
(
f'{m.name}{self.get_move_stars(m)}',
roman(m.tier),
f'{m.distance}({m.dist_change})' if m.dist_change else str(m.distance),
str(m.power),
str(m.accuracy),
str(m.complexity),
str(m.stam_cost),
str(m.time_cost),
str(m.qi_cost),
', '.join(m.functions),
)
for m in sample
]
options = [first_line] + options
options = pretty_table(options, sep=' ', as_list=True)
first_line = options[0]
options = options[1:]
options = list(zip(options, [m.name for m in sample]))
mn = menu(
options,
title='Choose a move to learn:\n ' + first_line,
)
self.learn_move(mn)
def choose_new_tech(self):
sample = self.get_techs_to_choose(annotated=True)
if not sample:
return
choice = self.menu(sample, 'Choose a technique to learn:')
self.learn_tech(choice)
def choose_target(self):
if self.is_auto_fighting:
Fighter.choose_target(self)
else:
if len(self.act_targets) == 1:
self.set_target(self.act_targets[0])
else:
self.see_fight_info(show_opp=False)
# self.show(self.visualize_fight_state())
options = []
for f in self.act_targets:
dist = self.get_vis_distance(self.distances[f])
n, lev, hp, stam, qi = f.name, f.level, f.hp, f.stamina, f.qp
if f.weapon:
wp_info = f' {f.weapon.name}'
else:
wp_info = ''
marks = f.get_status_marks(right=True)
options.append(
(
f'{dist}',
f'{n}{marks}',
f'(lv.{lev}',
f'HP:{hp}',
f'SP:{stam}',
f'QP:{qi}{wp_info})',
)
)
options = pretty_table(options, sep=' ', as_list=True)
options = list(zip(options, self.act_targets))
tgt = self.menu(options, title='Choose target:')
self.set_target(tgt)
def choose_tech_to_upgrade(self):
av_techs = self.get_techs_to_choose(annotated=True, for_upgrade=True)
if not av_techs:
return
t = self.menu(av_techs, 'Choose a technique to improve:')
self.upgrade_tech(t)
def cls(self):
cls()
def get_move_hints(self, move_obj):
targ = self.target
t_cost = self.get_move_time_cost(move_obj)
fail_warning = ''
fail_chance = self.get_move_fail_chance(move_obj)
if fail_chance >= 0.6:
fail_warning = '~~~'
elif fail_chance >= 0.25:
fail_warning = '~~'
elif fail_chance >= 0.1:
fail_warning = '~'
likely_hit = ''
if move_obj.power:
self.action = move_obj # this is needed to calc dfs correctly
self.calc_atk(self.action)
targ.calc_dfs()
defend_chance = max(targ.to_dodge / self.to_hit, targ.to_block / self.to_hit)
if defend_chance <= 0.1:
likely_hit = '%%%'
elif defend_chance <= 0.25:
likely_hit = '%%'
elif defend_chance <= 0.4:
likely_hit = '%'
init = self.current_fight.check_initiative(t_cost, targ)
have_time = '+' if not init else ''
most_powerful = ''
most_accurate = ''
least_stamina = ''
effects = ''
if move_obj.power:
moves_pool = [m for m in self.get_av_moves() if m.power]
max_p = max(m.power for m in moves_pool)
max_a = max(m.accuracy for m in moves_pool)
min_s = min(m.stam_cost for m in moves_pool)
if move_obj.power == max_p:
most_powerful = 'P'
if move_obj.accuracy == max_a:
most_accurate = 'A'
if move_obj.stam_cost == min_s:
least_stamina = 's'
effects = '!' * len(move_obj.functions)
mh = '{}{}{}{}{}{}{}'.format(
fail_warning,
likely_hit,
have_time,
most_powerful,
most_accurate,
least_stamina,
effects,
)
return mh
def get_move_stars(self, move_obj):
n = 0
for feature in move_obj.features:
if isinstance(feature, str): # todo reimplement this
val_a = getattr(self, feature + '_strike_mult', 1.0)
val_b = getattr(self, feature + '_mult', 1.0)
if max(val_a, val_b) > 1.0:
n += 1
if (
hasattr(move_obj, 'distance')
and getattr(self, f'dist{move_obj.distance}_bonus', 1.0) > 1.0
):
n += 1
return '*' * n
def level_up(self, times=1):
self.msg(f'{self.name}: *LEVEL UP*')
self.cls()
self.show('*LEVEL UP*')
Fighter.level_up(self, times)
@staticmethod
def menu(opt_list, *args, **kw_args):
return menu(opt_list, *args, **kw_args)
def msg(self, text, align=True):
self.write(text, align=align)
self.pak()
def pak(self):
pak()
def refresh_screen(self):
cls()
self.show(self.get_f_info())
def see_fight_info(self, show_opp=True):
def align_lines(lines_to_be_aligned):
lines_a = lines_to_be_aligned[:]
if len(lines_a[0]) == 1:
return [line[0] for line in lines_a]
else:
line_len = max([len(a) + len(b) for a, b in lines_a])
min_len = 26
if line_len < min_len:
line_len = min_len
for i, line in enumerate(lines_a):
a, b = line
pad = line_len - (len(a) + len(b)) + 1
lines_a[i] = f"{a}{' ' * pad}{b}"
return lines_a
def fill_lines(lines_to_be_filled, f, right=False):
lines_f = lines_to_be_filled
marks = f.get_status_marks(right=right)
lines_f[0].append(f.name + marks)
health_bar = get_bar(f.hp, f.hp_max, '%', '.', 10, mirror=right)
elt1, elt2, elt3 = 'HP', health_bar, f.hp
if right:
elt1, elt3 = elt3, elt1
lines_f[1].append(f'{elt1} {elt2} {elt3}')
stamina_bar = get_bar(f.stamina, f.stamina_max, '#', '-', 10, mirror=right)
elt1, elt2, elt3 = 'SP', stamina_bar, f.stamina
if right:
elt1, elt3 = elt3, elt1
lines_f[2].append(f'{elt1} {elt2} {elt3}')
qi_bar = get_bar(f.qp, f.qp_max, '@', '~', 10, mirror=right)
elt1, elt2, elt3 = 'QP', qi_bar, f.qp
if right:
elt1, elt3 = elt3, elt1
lines_f[3].append(f'{elt1} {elt2} {elt3}')
if f.weapon:
lines_f[4].append(f'({f.weapon.name})')
else:
lines_f[4].append('')
lines = [[], [], [], [], []]
fill_lines(lines, self)
if show_opp:
fill_lines(lines, self.target, right=True)
lines = align_lines(lines)
lines.append(self.visualize_fight_state())
self.cls()
output = '\n'.join(lines)
self.show(output, align=False)
# todo show standing fighters with distance?
def show(self, text, align=True):
"""Print aligned text in paragraphs."""
# from rich import print
if align:
pars = [align_text(t, INDENT, ALIGN) for t in text.split('\n')]
for p in pars:
print(p)
else:
print(text)
@staticmethod
def spectate(side_a, side_b, environment_allowed=True):
from kf_lib.fighting.fight import SpectateFight
SpectateFight(side_a, side_b, environment_allowed)
def write(self, text, align=False):
self.show(text, align=align)
self.log(text)
|
sureshHARDIYA/idpt
|
backend/src/api/assignmentResponse/types/index.js
|
<gh_stars>10-100
module.exports = [
require('./assignmentResponse'),
require('./assignmentResponsePage'),
require('./assignmentResponseInput')
]
|
philconst/dynatrace-service
|
internal/monitoring/project_create_finished_event_handler.go
|
<gh_stars>0
package monitoring
import (
"github.com/keptn-contrib/dynatrace-service/internal/dynatrace"
"github.com/keptn-contrib/dynatrace-service/internal/keptn"
log "github.com/sirupsen/logrus"
)
type ProjectCreateFinishedEventHandler struct {
event ProjectCreateFinishedAdapterInterface
dtClient dynatrace.ClientInterface
kClient keptn.ClientInterface
resourceClient keptn.ResourceClientInterface
serviceClient keptn.ServiceClientInterface
}
// NewProjectCreateFinishedEventHandler creates a new ProjectCreateFinishedEventHandler
func NewProjectCreateFinishedEventHandler(event ProjectCreateFinishedAdapterInterface, dtClient dynatrace.ClientInterface, kClient keptn.ClientInterface, resourceClient keptn.ResourceClientInterface, serviceClient keptn.ServiceClientInterface) ProjectCreateFinishedEventHandler {
return ProjectCreateFinishedEventHandler{
event: event,
dtClient: dtClient,
kClient: kClient,
resourceClient: resourceClient,
serviceClient: serviceClient,
}
}
func (eh ProjectCreateFinishedEventHandler) HandleEvent() error {
shipyard, err := eh.event.GetShipyard()
if err != nil {
log.WithError(err).Error("Could not load Keptn shipyard file")
}
cfg := NewConfiguration(eh.dtClient, eh.kClient, eh.resourceClient, eh.serviceClient)
_, err = cfg.ConfigureMonitoring(eh.event.GetProject(), shipyard)
if err != nil {
return err
}
log.Info("Dynatrace Monitoring setup done")
return nil
}
|
chiendm/gooddata-ruby
|
spec/lcm/userprov/user_provisioning_extended_spec.rb
|
require_relative '../fixtures/user_provisioning_fixtures'
require_relative 'support/user_provisioning_helper'
require_relative '../integration/support/configuration_helper'
require_relative '../integration/support/s3_helper'
require_relative '../../../lib/gooddata/models/user_filters/user_filter_builder'
require_relative '../../../lib/gooddata/lcm/lcm2'
describe 'the extended user provisioning functionality' do
before(:all) do
@fixtures = Fixtures::UserProvisioningFixtures.new projects_amount: 2,
user_amount: 2
end
after(:all) do
@fixtures.teardown
end
describe 'when provisioning in the declarative mode' do
it 'removes MUFs from projects not mentioned in the input' do
Support::UserProvisioningHelper.test_users_brick(projects: @fixtures[:projects],
test_context: @fixtures[:brick_params],
user_data: @fixtures[:user_data])
Support::UserProvisioningHelper.test_user_filters_brick(projects: @fixtures[:projects],
test_context: @fixtures[:brick_params],
mufs: @fixtures[:mufs])
extra_project = @fixtures[:projects].first
mufs = @fixtures[:mufs].reject { |m| m[:project_id] == extra_project.pid }
Support::UserProvisioningHelper.upload_mufs(mufs)
Support::UserProvisioningHelper.test_user_filters_brick(projects: @fixtures[:projects],
test_context: @fixtures[:brick_params],
mufs: mufs)
end
end
end
|
jingcao80/Elastos
|
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGGlyphRefElement.cpp
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#if ENABLE(SVG_FONTS)
#include "V8SVGGlyphRefElement.h"
#include "SVGNames.h"
#include "bindings/core/v8/V8SVGAnimatedString.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8DOMConfiguration.h"
#include "bindings/v8/V8HiddenValue.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/dom/custom/CustomElementCallbackDispatcher.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace WebCore {
static void initializeScriptWrappableForInterface(SVGGlyphRefElement* object)
{
if (ScriptWrappable::wrapperCanBeStoredInObject(object))
ScriptWrappable::fromObject(object)->setTypeInfo(&V8SVGGlyphRefElement::wrapperTypeInfo);
else
ASSERT_NOT_REACHED();
}
} // namespace WebCore
void webCoreInitializeScriptWrappableForInterface(WebCore::SVGGlyphRefElement* object)
{
WebCore::initializeScriptWrappableForInterface(object);
}
namespace WebCore {
const WrapperTypeInfo V8SVGGlyphRefElement::wrapperTypeInfo = { gin::kEmbedderBlink, V8SVGGlyphRefElement::domTemplate, V8SVGGlyphRefElement::derefObject, 0, V8SVGGlyphRefElement::toEventTarget, 0, V8SVGGlyphRefElement::installPerContextEnabledMethods, &V8SVGElement::wrapperTypeInfo, WrapperTypeObjectPrototype, WillBeGarbageCollectedObject };
namespace SVGGlyphRefElementV8Internal {
template <typename T> void V8_USE(T) { }
static void glyphRefAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
v8SetReturnValueString(info, impl->glyphRef(), info.GetIsolate());
}
static void glyphRefAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGGlyphRefElementV8Internal::glyphRefAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void glyphRefAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
TOSTRING_VOID(V8StringResource<>, cppValue, v8Value);
impl->setGlyphRef(cppValue);
}
static void glyphRefAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
SVGGlyphRefElementV8Internal::glyphRefAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void formatAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
Element* impl = V8Element::toNative(holder);
v8SetReturnValueString(info, impl->fastGetAttribute(SVGNames::formatAttr), info.GetIsolate());
}
static void formatAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGGlyphRefElementV8Internal::formatAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void formatAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
Element* impl = V8Element::toNative(holder);
TOSTRING_VOID(V8StringResource<WithNullCheck>, cppValue, v8Value);
impl->setAttribute(SVGNames::formatAttr, cppValue);
}
static void formatAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope;
SVGGlyphRefElementV8Internal::formatAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void xAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
v8SetReturnValue(info, impl->x());
}
static void xAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGGlyphRefElementV8Internal::xAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void xAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue()));
impl->setX(cppValue);
}
static void xAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
SVGGlyphRefElementV8Internal::xAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void yAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
v8SetReturnValue(info, impl->y());
}
static void yAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGGlyphRefElementV8Internal::yAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void yAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue()));
impl->setY(cppValue);
}
static void yAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
SVGGlyphRefElementV8Internal::yAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void dxAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
v8SetReturnValue(info, impl->dx());
}
static void dxAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGGlyphRefElementV8Internal::dxAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void dxAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue()));
impl->setDx(cppValue);
}
static void dxAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
SVGGlyphRefElementV8Internal::dxAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void dyAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
v8SetReturnValue(info, impl->dy());
}
static void dyAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGGlyphRefElementV8Internal::dyAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void dyAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue()));
impl->setDy(cppValue);
}
static void dyAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
SVGGlyphRefElementV8Internal::dyAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void hrefAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGGlyphRefElement* impl = V8SVGGlyphRefElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->href()), impl);
}
static void hrefAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGGlyphRefElementV8Internal::hrefAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
} // namespace SVGGlyphRefElementV8Internal
static const V8DOMConfiguration::AttributeConfiguration V8SVGGlyphRefElementAttributes[] = {
{"glyphRef", SVGGlyphRefElementV8Internal::glyphRefAttributeGetterCallback, SVGGlyphRefElementV8Internal::glyphRefAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"format", SVGGlyphRefElementV8Internal::formatAttributeGetterCallback, SVGGlyphRefElementV8Internal::formatAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"x", SVGGlyphRefElementV8Internal::xAttributeGetterCallback, SVGGlyphRefElementV8Internal::xAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"y", SVGGlyphRefElementV8Internal::yAttributeGetterCallback, SVGGlyphRefElementV8Internal::yAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"dx", SVGGlyphRefElementV8Internal::dxAttributeGetterCallback, SVGGlyphRefElementV8Internal::dxAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"dy", SVGGlyphRefElementV8Internal::dyAttributeGetterCallback, SVGGlyphRefElementV8Internal::dyAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"href", SVGGlyphRefElementV8Internal::hrefAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
};
static void configureV8SVGGlyphRefElementTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "SVGGlyphRefElement", V8SVGElement::domTemplate(isolate), V8SVGGlyphRefElement::internalFieldCount,
V8SVGGlyphRefElementAttributes, WTF_ARRAY_LENGTH(V8SVGGlyphRefElementAttributes),
0, 0,
0, 0,
isolate);
v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate();
v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate();
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Handle<v8::FunctionTemplate> V8SVGGlyphRefElement::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8SVGGlyphRefElementTemplate);
}
bool V8SVGGlyphRefElement::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Handle<v8::Object> V8SVGGlyphRefElement::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
SVGGlyphRefElement* V8SVGGlyphRefElement::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value)
{
return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0;
}
EventTarget* V8SVGGlyphRefElement::toEventTarget(v8::Handle<v8::Object> object)
{
return toNative(object);
}
v8::Handle<v8::Object> wrap(SVGGlyphRefElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8SVGGlyphRefElement>(impl, isolate));
return V8SVGGlyphRefElement::createWrapper(impl, creationContext, isolate);
}
v8::Handle<v8::Object> V8SVGGlyphRefElement::createWrapper(PassRefPtrWillBeRawPtr<SVGGlyphRefElement> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8SVGGlyphRefElement>(impl.get(), isolate));
if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo();
// Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have
// the same object de-ref functions, though, so use that as the basis of the check.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
}
v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
if (UNLIKELY(wrapper.IsEmpty()))
return wrapper;
installPerContextEnabledProperties(wrapper, impl.get(), isolate);
V8DOMWrapper::associateObjectWithWrapper<V8SVGGlyphRefElement>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Dependent);
return wrapper;
}
void V8SVGGlyphRefElement::derefObject(void* object)
{
#if !ENABLE(OILPAN)
fromInternalPointer(object)->deref();
#endif // !ENABLE(OILPAN)
}
template<>
v8::Handle<v8::Value> toV8NoInline(SVGGlyphRefElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl, creationContext, isolate);
}
} // namespace WebCore
#endif // ENABLE(SVG_FONTS)
|
shaojiankui/iOS10-Runtime-Headers
|
PrivateFrameworks/FMCore.framework/FMXPCTransactionManager.h
|
<reponame>shaojiankui/iOS10-Runtime-Headers
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/FMCore.framework/FMCore
*/
@interface FMXPCTransactionManager : NSObject {
NSCountedSet * _activeTransactions;
NSString * _keepAliveActivityIdentifier;
NSObject<OS_dispatch_queue> * _txn_ops_queue;
}
@property (nonatomic, retain) NSCountedSet *activeTransactions;
@property (nonatomic, retain) NSString *keepAliveActivityIdentifier;
@property (nonatomic, retain) NSObject<OS_dispatch_queue> *txn_ops_queue;
+ (id)sharedInstance;
- (void).cxx_destruct;
- (void)_disableKeepAlive;
- (void)_disableLaunchOnRebootActivity:(id)arg1;
- (void)_disableOldKeepAliveActivity;
- (void)_enableKeepAlive;
- (id)activeTransactions;
- (void)beginTransaction:(id)arg1;
- (void)dealloc;
- (id)dumpActiveTransactions;
- (void)endTransaction:(id)arg1;
- (id)init;
- (id)initSingleton;
- (id)keepAliveActivityIdentifier;
- (void)setActiveTransactions:(id)arg1;
- (void)setKeepAliveActivityIdentifier:(id)arg1;
- (void)setLaunchOnRebootActivity:(id)arg1 keepAliveActivity:(id)arg2;
- (void)setTxn_ops_queue:(id)arg1;
- (id)txn_ops_queue;
@end
|
ericho/stx-neutron
|
neutron/tests/unit/plugins/wrs/test_host_driver.py
|
# Copyright (c) 2013 OpenStack Foundation
# 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.
#
# Copyright (c) 2015 Wind River Systems, Inc.
#
import uuid
from oslo_log import log as logging
from neutron.common import constants
from neutron.drivers import host as host_driver
from neutron.extensions import host as ext_host
from neutron_lib.plugins import directory
LOG = logging.getLogger(__name__)
class TestHostDriver(host_driver.HostDriver):
def __init__(self):
super(TestHostDriver, self).__init__()
self._hosts_by_name = {}
self._hosts_by_uuid = {}
self._pnets_by_name = {}
self._pnet_bindings = {}
self._interface_by_host = {}
self._plugin = None
LOG.info("Test host driver loaded")
def _get_plugin(self):
if not self._plugin:
self._plugin = directory.get_plugin()
return self._plugin
def get_host_uuid(self, context, hostname):
if hostname in self._hosts_by_name[hostname]:
host = self._hosts_by_name[hostname]
return host['id']
return None
def get_host_providernets(self, context, host_uuid):
if host_uuid not in self._hosts_by_uuid:
return {}
host = self._hosts_by_uuid[host_uuid]
if host['name'] not in self._interface_by_host:
return {}
data = self._interface_by_host[host['name']]
names = data['providernets'].strip()
providernets = names.split(',') if names else []
values = []
for name in providernets:
providernet = self._get_plugin().get_providernet_by_name(
context, name.strip())
if providernet:
values.append(providernet['id'])
return {data['uuid']: {'providernets': values}}
def get_host_interfaces(self, context, host_uuid):
if host_uuid in self._hosts_by_uuid:
host = self._hosts_by_uuid[host_uuid]
if host['name'] in self._interface_by_host:
data = self._interface_by_host[host['name']]
return {data['uuid']: data}
return {}
def add_host(self, host):
self._hosts_by_name[host['name']] = host
self._hosts_by_uuid[host['id']] = host
self._interface_by_host[host['name']] = {
'uuid': str(uuid.uuid4()),
'mtu': constants.DEFAULT_MTU,
'vlans': '',
'network_type': 'data',
'providernets': ''}
def add_interface(self, host, interface):
self._interface_by_host[host] = interface
def is_host_available(self, context, hostname):
"""
Returns whether the host is available or not. This code should live in
the plugin instead of the driver but since we do have our own subclass
of the ml2 plugin this call needs to return true so that existing unit
tests continue to work. If we had our own subclass we would simply
return true in the base class and run this code in our subclass.
"""
try:
host = self._get_plugin().get_host_by_name(context, hostname)
return host['availability'] == constants.HOST_UP
except ext_host.HostNotFoundByName:
# Does not exist yet
return False
|
pussbb/pymaillib
|
pymaillib/imap/entity/envelope.py
|
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Imap Envelope Entity
~~~~~~~~~~~~~~~~
Imap Envelope Entity
:copyright: (c) 2017 WTFPL.
:license: WTFPL, see LICENSE for more details.
"""
from typing import Iterator, List
from email.headerregistry import Address as HeaderAddress
from ..utils import decode_parameter_value, parse_datetime
from . import ImapEntity, SlotBasedImapEntity
class Envelope(SlotBasedImapEntity):
"""Represents IMAP ENVELOPE
"""
__slots__ = ('date', 'subject', 'from_', 'sender', 'reply_to', 'to', 'cc',
'bcc', 'in_reply_to', 'message_id')
@staticmethod
def from_list(items: list) -> 'Envelope':
"""Construct Envelope object from a list
:param items: list
:return:
"""
date, subj, *addrs, in_reply, msg_id = items
return Envelope(
parse_datetime(date),
decode_parameter_value(subj),
*[AddressList.from_list(addr) for addr in addrs],
in_reply_to=in_reply,
message_id=msg_id
)
class Address(SlotBasedImapEntity, HeaderAddress):
"""Represents email address in ENVELOPE
"""
__slots__ = 'name', 'route', 'mailbox', 'host', '_display_name', \
'_username', '_domain'
def __init__(self, *args, **kwargs):
args += (None,)*3
super().__init__(*args, **kwargs)
self._display_name = self.name
self.name = decode_parameter_value(self.name)
self._username = self.mailbox
self._domain = self.host
@property
def rfc(self) -> str:
"""Get formatted address with display name and email
:return:
"""
if not self.domain:
return self.username
return '{}<{}@{}>'.format(self.display_name, self.username,
self.domain).strip()
def dump(self) -> dict:
"""
:return:
"""
return {
'name': self.name,
'route': self.route,
'mailbox': self.mailbox,
'host': self.host,
'addr_spec': self.addr_spec,
'display': self.rfc,
}
class AddressList(ImapEntity):
"""Address list for an envelope response
"""
__slots__ = '_addresses',
def __init__(self, addresses: List[Address]):
self._addresses = addresses
@staticmethod
def from_list(items) -> 'AddressList':
"""Convert list into AddresList object with Address objects
:param items: iterable
:return:
"""
if not items:
return AddressList([])
return AddressList([Address(*item) for item in items])
def __iter__(self) -> Iterator[Address]:
yield from self._addresses
def dump(self) -> List[Address]:
"""Serialize class attributes
:return:
"""
return self._addresses
|
abilashgt/study_java
|
java/hibernate/maven-hibernate/src/main/java/org/koushik/javabrains/dto/many2many/M2MVehicle.java
|
package org.koushik.javabrains.dto.many2many;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
@Entity
@Table(name = "m2m_vehicle")
public class M2MVehicle {
@Id
@GeneratedValue
private int vehicleId;
private String vehicleName;
@ManyToMany(mappedBy = "vehicles")
private Collection<M2MUserDetails> users = new ArrayList<M2MUserDetails>();
public int getVehicleId() {
return vehicleId;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
public Collection<M2MUserDetails> getUsers() {
return users;
}
public void setUsers(Collection<M2MUserDetails> users) {
this.users = users;
}
}
|
zhangpf/fuchsia-rs
|
zircon/system/utest/core/handle-info/handle-info.cc
|
<reponame>zhangpf/fuchsia-rs
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdio.h>
#include <stdlib.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/object.h>
#include <lib/zx/event.h>
#include <lib/zx/thread.h>
#include <lib/zx/job.h>
#include <lib/zx/process.h>
#include <lib/zx/socket.h>
#include <zxtest/zxtest.h>
namespace {
constexpr uint32_t kEventOption = 0u;
constexpr uint32_t kSocketOption = 0u;
TEST(HandleInfoTest, ReplaceSuccessOrigInvalid) {
zx::event orig_event;
ASSERT_OK(zx::event::create(kEventOption, &orig_event));
zx::event replaced_event;
ASSERT_OK(orig_event.replace(ZX_RIGHTS_BASIC, &replaced_event));
EXPECT_FALSE(orig_event.is_valid());
EXPECT_TRUE(replaced_event.is_valid());
}
TEST(HandleInfoTest, ReplaceFailureBothInvalid) {
zx::event orig_event;
ASSERT_OK(zx::event::create(kEventOption, &orig_event));
zx::event failed_event;
EXPECT_EQ(orig_event.replace(ZX_RIGHT_EXECUTE, &failed_event),
ZX_ERR_INVALID_ARGS);
// Even on failure, a replaced object is now invalid.
EXPECT_FALSE(orig_event.is_valid());
EXPECT_FALSE(failed_event.is_valid());
}
TEST(HandleInfoTest, DupAndInfoRights) {
zx::event orig_event;
ASSERT_OK(zx::event::create(kEventOption, &orig_event));
zx::event duped_event;
ASSERT_OK(orig_event.duplicate(ZX_RIGHT_SAME_RIGHTS, &duped_event));
ASSERT_OK(orig_event.get_info(ZX_INFO_HANDLE_VALID, nullptr,
0u /*buffer_size*/, nullptr, nullptr));
orig_event.reset();
ASSERT_EQ(orig_event.get_info(ZX_INFO_HANDLE_VALID, nullptr,
0u /*buffer_size*/, nullptr, nullptr), ZX_ERR_BAD_HANDLE);
zx_info_handle_basic_t info = {};
ASSERT_EQ(duped_event.get_info(ZX_INFO_HANDLE_BASIC, &info,
4u /*buffer_size*/, nullptr, nullptr),
ZX_ERR_BUFFER_TOO_SMALL);
ASSERT_OK(duped_event.get_info(ZX_INFO_HANDLE_BASIC, &info, sizeof(info),
nullptr, nullptr));
constexpr zx_rights_t evr = ZX_RIGHTS_BASIC | ZX_RIGHT_SIGNAL;
EXPECT_GT(info.koid, 0ULL, "object id should be positive");
EXPECT_EQ(info.type, ZX_OBJ_TYPE_EVENT, "handle should be an event");
EXPECT_EQ(info.rights, evr, "wrong set of rights");
EXPECT_EQ(info.props, ZX_OBJ_PROP_WAITABLE);
EXPECT_EQ(info.related_koid, 0ULL, "events don't have associated koid");
}
TEST(HandleInfoTest, RelatedKoid) {
zx_info_handle_basic_t info_job = {};
zx_info_handle_basic_t info_process = {};
ASSERT_OK(zx::job::default_job()->get_info(ZX_INFO_HANDLE_BASIC,
&info_job, sizeof(info_job), nullptr, nullptr));
ASSERT_OK(zx::process::self()->get_info(ZX_INFO_HANDLE_BASIC,
&info_process, sizeof(info_process), nullptr, nullptr));
EXPECT_EQ(info_job.type, ZX_OBJ_TYPE_JOB);
EXPECT_EQ(info_process.type, ZX_OBJ_TYPE_PROCESS);
zx::thread thread;
ASSERT_OK(zx::thread::create(*zx::process::self(), "hitr", 4, 0u, &thread));
zx_info_handle_basic_t info_thread = {};
ASSERT_OK(thread.get_info(ZX_INFO_HANDLE_BASIC, &info_thread,
sizeof(info_thread), nullptr, nullptr));
EXPECT_EQ(info_thread.type, ZX_OBJ_TYPE_THREAD);
// The related koid of a process is its job and this test assumes that the
// default job is in fact the parent job of this test. Equivalently, a thread's
// associated koid is the process koid.
EXPECT_EQ(info_process.related_koid, info_job.koid);
EXPECT_EQ(info_thread.related_koid, info_process.koid);
thread.reset();
zx::socket socket_local, socket_remote;
ASSERT_OK(zx::socket::create(kSocketOption, &socket_local, &socket_remote));
zx_info_handle_basic_t info_socket_local = {};
ASSERT_OK(socket_local.get_info(ZX_INFO_HANDLE_BASIC, &info_socket_local,
sizeof(info_socket_local), nullptr, nullptr));
zx_info_handle_basic_t info_socket_remote = {};
ASSERT_OK(socket_remote.get_info(ZX_INFO_HANDLE_BASIC, &info_socket_remote,
sizeof(info_socket_remote), nullptr, nullptr));
EXPECT_EQ(info_socket_local.type, ZX_OBJ_TYPE_SOCKET);
EXPECT_EQ(info_socket_remote.type, ZX_OBJ_TYPE_SOCKET);
// The related koid of a socket pair are each other koids.
EXPECT_EQ(info_socket_local.related_koid, info_socket_remote.koid);
EXPECT_EQ(info_socket_remote.related_koid, info_socket_local.koid);
}
TEST(HandleInfoTest, DuplicateRights) {
zx::event orig_event;
ASSERT_OK(zx::event::create(kEventOption, &orig_event));
zx::event duped_ro1_event, duped_ro2_event;
ASSERT_OK(orig_event.duplicate(ZX_RIGHT_WAIT, &duped_ro1_event));
ASSERT_OK(orig_event.duplicate(ZX_RIGHT_WAIT, &duped_ro2_event));
zx_info_handle_basic_t info = {};
ASSERT_OK(duped_ro1_event.get_info(ZX_INFO_HANDLE_BASIC, &info,
sizeof(info), nullptr, nullptr));
EXPECT_EQ(info.rights, ZX_RIGHT_WAIT, "wrong set of rights");
zx::event duped_ro3_event;
// Duplicate right removed, so this fails.
ASSERT_EQ(duped_ro1_event.duplicate(ZX_RIGHT_SAME_RIGHTS, &duped_ro3_event),
ZX_ERR_ACCESS_DENIED);
ASSERT_EQ(orig_event.duplicate(ZX_RIGHT_EXECUTE | ZX_RIGHT_WAIT,
&duped_ro3_event), ZX_ERR_INVALID_ARGS, "invalid right");
EXPECT_TRUE(orig_event.is_valid(), "original handle should be valid");
EXPECT_TRUE(duped_ro1_event.is_valid(), "duped handle should be valid");
EXPECT_TRUE(duped_ro2_event.is_valid(), "duped handle should be valid");
EXPECT_FALSE(duped_ro3_event.is_valid(), "duped handle should be invalid");
}
TEST(HandleInfoTest, ReplaceRights) {
zx::event event1, event2;
ASSERT_OK(zx::event::create(kEventOption, &event1));
ASSERT_OK(event1.replace(ZX_RIGHT_WAIT, &event2));
zx_info_handle_basic_t info = {};
ASSERT_OK(event2.get_info(ZX_INFO_HANDLE_BASIC, &info,
sizeof(info), nullptr, nullptr));
EXPECT_EQ(info.rights, ZX_RIGHT_WAIT, "wrong set of rights");
EXPECT_FALSE(event1.is_valid(), "replaced event should be invalid");
EXPECT_EQ(event2.replace(ZX_RIGHT_SIGNAL | ZX_RIGHT_WAIT,
&event1), ZX_ERR_INVALID_ARGS, "cannot upgrade rights");
// event2 should also now be invalid.
EXPECT_FALSE(event2.is_valid(),
"replaced event should be invalid on failure");
}
} // namespace
|
xformation/xformation-compliancemanager-service
|
compliancemanager-server/src/test/java/com/synectiks/process/server/plugin/indexer/searches/timeranges/AbsoluteRangeEntityTest.java
|
/*
* */
package com.synectiks.process.server.plugin.indexer.searches.timeranges;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Test;
import com.synectiks.process.server.plugin.indexer.searches.timeranges.AbsoluteRange;
import com.synectiks.process.server.plugin.indexer.searches.timeranges.InvalidRangeParametersException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class AbsoluteRangeEntityTest {
@Test
public void testStringParse() throws Exception {
final AbsoluteRange range1 = AbsoluteRange.create("2016-03-24T00:00:00.000Z", "2016-03-24T23:59:59.000Z");
assertThat(range1.from().toString(ISODateTimeFormat.dateTime()))
.isEqualTo("2016-03-24T00:00:00.000Z");
assertThat(range1.to().toString(ISODateTimeFormat.dateTime()))
.isEqualTo("2016-03-24T23:59:59.000Z");
final AbsoluteRange range2 = AbsoluteRange.create("2016-03-24T00:00:00.000+09:00", "2016-03-24T23:59:59.000+09:00");
// Check that time zone is kept while parsing.
assertThat(range2.from().toString(ISODateTimeFormat.dateTime()))
.isEqualTo("2016-03-24T00:00:00.000+09:00");
assertThat(range2.to().toString(ISODateTimeFormat.dateTime()))
.isEqualTo("2016-03-24T23:59:59.000+09:00");
}
@Test
public void nullOrEmptyStringsThrowException() {
assertThatThrownBy(() -> AbsoluteRange.create(null, "2018-07-11T14:32:00.000Z"))
.isInstanceOf(InvalidRangeParametersException.class)
.hasMessage("Invalid start of range: <null>");
assertThatThrownBy(() -> AbsoluteRange.create("", "2018-07-11T14:32:00.000Z"))
.isInstanceOf(InvalidRangeParametersException.class)
.hasMessage("Invalid start of range: <>");
assertThatThrownBy(() -> AbsoluteRange.create("2018-07-11T14:32:00.000Z", null))
.isInstanceOf(InvalidRangeParametersException.class)
.hasMessage("Invalid end of range: <null>");
assertThatThrownBy(() -> AbsoluteRange.create("2018-07-11T14:32:00.000Z", ""))
.isInstanceOf(InvalidRangeParametersException.class)
.hasMessage("Invalid end of range: <>");
}
}
|
ssynhtn/leetcode
|
src/com/ssynhtn/medium/PushDominoes.java
|
package com.ssynhtn.medium;
import java.util.*;
public class PushDominoes {
public String pushDominoes(String dominoes) {
char[] chs = dominoes.toCharArray();
int i = 0;
int j = 0;
final int len = chs.length;
while (true) {
while (i < len && chs[i] != '.') {
i++;
}
if (i == len) break;
// i at start of .
j = i + 1;
while (j < len && chs[j] == '.') {
j++;
}
// j at end of .
if (i == 0 || chs[i - 1] == 'L') {
if (j < len && chs[j] == 'L') {
// [i, j) to L
while (i < j) {
chs[i++] = 'L';
}
}
} else {
if (j < len && chs[j] == 'L') {
// [i, j) to middle
int r = j - 1;
while (i < r) {
chs[i++] = 'R';
chs[r--] = 'L';
}
} else {
// to R
while (i < j) {
chs[i++] = 'R';
}
}
}
i = j;
}
return new String(chs);
}
public static void main(String[] args) {
System.out.println(new PushDominoes().pushDominoes("RR.L"));
}
}
|
JoonasVali/Mirrors
|
mirrors-core/src/main/java/ee/joonasvali/mirrors/EvolutionPropertyLoader.java
|
package ee.joonasvali.mirrors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import java.util.function.Function;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.ACCELERATORS_ENABLED;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.BENDERS_ENABLED;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.BOTTOM_PRODUCER_ENABLED;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.CONCURRENT;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.ELITES;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.GENE_ADDITION_RATE;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.GENE_DELETION_RATE;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.GENE_MUTATION_RATE;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.KEEP_MACHINE_ALIVE;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.MIDDLE_PRODUCER_ENABLED;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.REFLECTORS_ENABLED;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.REPELLENTS_ENABLED;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.TARGET_FITNESS;
import static ee.joonasvali.mirrors.DefaultEvolutionPropertyValues.TOP_PRODUCER_ENABLED;
public class EvolutionPropertyLoader {
private final static Logger log = LoggerFactory.getLogger(EvolutionPropertyLoader.class);
public EvolutionProperties loadProperties(Path propertiesFile) {
EvolutionProperties properties;
try {
log.info("Properties read from: " + propertiesFile);
Properties props = new Properties();
try (InputStream stream = Files.newInputStream(propertiesFile)) {
props.load(stream);
}
properties = new EvolutionProperties(
getProperty(props, "elites", Integer::parseInt, ELITES),
getProperty(props, "concurrent", Integer::parseInt, CONCURRENT),
getProperty(props, "target.fitness", Integer::parseInt, TARGET_FITNESS),
getProperty(props, "keep.machine.alive", Boolean::parseBoolean, KEEP_MACHINE_ALIVE),
getProperty(props, "gene.mutation.rate", Double::parseDouble, GENE_MUTATION_RATE),
getProperty(props, "gene.addition.rate", Double::parseDouble, GENE_ADDITION_RATE),
getProperty(props, "gene.deletion.rate", Double::parseDouble, GENE_DELETION_RATE),
getProperty(props, "reflectors.enabled", Boolean::parseBoolean, REFLECTORS_ENABLED),
getProperty(props, "benders.enabled", Boolean::parseBoolean, BENDERS_ENABLED),
getProperty(props, "accelerators.enabled", Boolean::parseBoolean, ACCELERATORS_ENABLED),
getProperty(props, "repellents.enabled", Boolean::parseBoolean, REPELLENTS_ENABLED)
);
boolean topProducerEnabled = getProperty(
props, "top.producer.enabled", Boolean::parseBoolean, TOP_PRODUCER_ENABLED
);
boolean middleProducerEnabled = getProperty(
props, "middle.producer.enabled", Boolean::parseBoolean, MIDDLE_PRODUCER_ENABLED
);
boolean bottomProducerEnabled = getProperty(
props, "bottom.producer.enabled", Boolean::parseBoolean, BOTTOM_PRODUCER_ENABLED
);
properties.setTopProducerEnabled(topProducerEnabled);
properties.setMiddleProducerEnabled(middleProducerEnabled);
properties.setBottomProducerEnabled(bottomProducerEnabled);
} catch (IOException e) {
log.error("Can't read properties " + propertiesFile, e);
throw new RuntimeException(e);
}
return properties;
}
private <T> T getProperty(Properties props, String key, Function<String, T> parseFunction, T defaultVal) {
String value = props.getProperty(key);
if (value == null) {
return defaultVal;
}
try {
return parseFunction.apply(value);
} catch (Exception e) {
log.error("Unable to parse value " + value + " for key " + key, e);
return defaultVal;
}
}
}
|
avinfinity/UnmanagedCodeSnippets
|
spheregeometry.cpp
|
#include "spheregeometry.h"
namespace vc{
SphereGeometry::SphereGeometry()
{
}
}
|
XpressAI/frovedis
|
test/core/test2.6.2/test.cc
|
<filename>test/core/test2.6.2/test.cc<gh_stars>10-100
#include <frovedis.hpp>
#define BOOST_TEST_MODULE FrovedisTest
#include <boost/test/unit_test.hpp>
using namespace frovedis;
using namespace std;
int sum(std::string key, int a, int b) {return a + b;}
int optional_sum(std::string key, int a, boost::optional<int> b) {
if(b) return a + *b;
else return a;
}
BOOST_AUTO_TEST_CASE( frovedis_test )
{
int argc = 1;
char** argv = NULL;
use_frovedis use(argc, argv);
// filling sample input imap
auto d1 = frovedis::make_dunordered_map_allocate<std::string,int>();
auto d2 = d1;
d1.put("apple", 10);
d1.put("orange", 20);
d2.put("apple", 50);
d2.put("grape", 20);
auto z = zip(d1,d2);
auto d3 = z.map_values(sum);
auto r = d3.as_dvector().sort().gather();
//for(auto i: r) std::cout << i.first << ": " << i.second << std::endl;
std::vector<std::pair<std::string,int>> ref1;
ref1.push_back(std::make_pair("apple",60));
BOOST_CHECK (r == ref1);
auto d4 = z.leftouter_map_values(optional_sum);
r = d4.as_dvector().sort().gather();
//for(auto i: r) std::cout << i.first << ": " << i.second << std::endl;
std::vector<std::pair<std::string,int>> ref2;
ref2.push_back(std::make_pair("apple",60));
ref2.push_back(std::make_pair("orange",20));
BOOST_CHECK (r == ref2);
}
|
Fuge2008/saasdriver
|
src/com/small/saasdriver/global/HttpConstant.java
|
<gh_stars>0
package com.small.saasdriver.global;
/**
* 项目中使用的URL控制管理类
*
* @author ZhangKui
*
*/
public class HttpConstant {
// 测试用服务器
public final static String BASE_URL = "http://192.168.3.11:82";
// 正式发布用服务器
//public final static String BASE_URL="http://192.168.1.254:130";
/** ================== 订单部分用到的URL接口 ================== */
/** 订单接收开关URL */
// public final static String ORDER_SWITCH_URL =BASE_URL+
// "/VehicleDriverWorking/UpdateWorkStatus";
/** 第一期暂无 订单接收模式URL :0-即时,1-预约,2-全部 */
// public final static String ORDER_MODEL_URL =BASE_URL+ "";
/** 向服务器获取最新订单URL:订单刷新 */
public final static String ORDER_NEW_URL = BASE_URL + "/Order/ReceivedOrder";
/** 订单确认URL */
public final static String ORDER_ENSURE_URL = BASE_URL + "/Order/AgreedOrRefusedOrder";
/** 订单开始确认URL */
public final static String ORDER_START_URL = BASE_URL + "/Order/ConfirmOrderStart";
/** 订单结束确认URL */
public final static String ORDER_END_URL = BASE_URL + "/Order/ConfirmOrderEnd";
/** 订单数据提交URL */
public final static String ORDER_DATA_COMMIT_URL = BASE_URL + "/OrderVehicleTravel/UploadData";
/** 加载订单信息 */
// public final static String ORDER_DATA_LOAD =BASE_URL+
// "/Order/ReceivedOrder/";
/** 订单接收确认 */
public final static String ORDER_START_CONFIRM = BASE_URL + "/Order/ConfirmationReceivedOrder/";
/** 订单开始或订单结束 */
public final static String ORDER_START_OR_END = BASE_URL + "/Order/ConfirmOrderStartOrEnd/";
/** 未来订单或当前订单 */
public final static String ORDER_NOW_OR_PLAN = BASE_URL + "/Order/GetOngoingOrderOrFuturePlanning/";
/** 上传行程数据 */
public final static String UPLOAD_ORDER_DATA = BASE_URL + "/Order/UploadData/";
/** 获取历史订单 */
public final static String ORDER_DATA_RECORD = BASE_URL + "/Order/GetTaskRecord/";
/** 订单数据统计 */
public final static String ORDER_DATA_STATISTICS = BASE_URL + "/Order/GetDataStatistics/";
// 新闻
public final static String NEWS = "http://v.juhe.cn/toutiao/index";
/** ================== 车主中心的URL接口 ================== */
/** 获取司机个人信息 */
public final static String DRIVER_PRESONAL_INFROMATION = BASE_URL + "/Driver/GetDriverInfo";
/** 获取司机个人信息(简单) */
public final static String DRIVER_PRESONAL_INFROMATION2 = BASE_URL + "/Driver/GetSimpleBasicInfo";
/** 获取车辆信息 */
public final static String DRIVER_VEHICLE_CENTER = BASE_URL + "/Vehicle/GetCarInfoModel";
/** 任务记录 */
public final static String DRIVER_TASK_RECORD = BASE_URL + "/Driver/GetTaskRecord";
/** 头像上传 */
public final static String header_post = BASE_URL + "/DriverInfo/UploadProfilePicture/";
/** ================== 登录注册的URL接口 ================== */
/** 未登录 ——>改密验证码 */
public final static String DRIVER_LOGIN_VERIFICATION = BASE_URL + "/DriverInfo/GetForgetCode/";
/** 未登录 ——>修改密码 */
public final static String DRIVER_UNCHANGE_PASSWORD = BASE_URL + "/DriverInfo/UpdatePassword/";
/** 登录——> 修改密码 */
public final static String DRIVER_CHANGE_PASSWORD = BASE_URL + "/DriverInfo/LoggedUpdatePwd/";
/** 登录 */
public final static String DRIVER_LOGIN = BASE_URL + "/DriverInfo/LoginResult/";
// public static final String BASE_URL = "http://192.168.1.135:5000/";
}
|
vgauri1797/Eclipse
|
WebAppBuilderForArcGIS/server/apps/2/widgets/Analysis/nls/pl/strings.js
|
define({
"_widgetLabel": "Analiza",
"executeAnalysisTip": "Kliknij narzędzie analizy, aby uruchomić analizę",
"noToolTip": "Nie skonfigurowano narzędzia analizy!",
"jobSubmitted": "przesłane.",
"jobCancelled": "Anulowano.",
"jobFailed": "Niepowodzenie",
"jobSuccess": "Powodzenie.",
"executing": "Wykonywanie",
"cancelJob": "Anuluj zadanie analizy",
"paramName": "Nazwa parametru",
"learnMore": "Dowiedz się więcej",
"outputtip": "Uwaga: Dane wynikowe obiektów i tabeli są dodawane do mapy jako warstwy operacyjne.",
"outputSaveInPortal": "Dane zostały zapisane w portalu.",
"privilegeError": "Twoja rola użytkownika nie może dokonać analizy. Aby możliwe było wykonanie analizy, niezbędne jest nadanie użytkownikowi przez administratora instytucji odpowiednich <a href=\"http://doc.arcgis.com/en/arcgis-online/reference/roles.htm\" target=\"_blank\">uprawnień</a>."
});
|
jarocho105/pre2
|
erp_desktop_all/src_activosfijos/com/bydan/erp/activosfijos/presentation/swing/jinternalframes/report/ResponsablesJInternalFrame.java
|
<reponame>jarocho105/pre2
/*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.activosfijos.presentation.swing.jinternalframes.report;
import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*;
import com.bydan.erp.activosfijos.presentation.web.jsf.sessionbean.*;//.report;
import com.bydan.erp.activosfijos.presentation.swing.jinternalframes.*;
import com.bydan.erp.activosfijos.presentation.swing.jinternalframes.auxiliar.report.*;
import com.bydan.erp.activosfijos.presentation.web.jsf.sessionbean.report.*;
import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.seguridad.business.entity.*;
//import com.bydan.erp.activosfijos.presentation.report.source.report.*;
import com.bydan.framework.erp.business.entity.Reporte;
import com.bydan.erp.seguridad.business.entity.Modulo;
import com.bydan.erp.seguridad.business.entity.Opcion;
import com.bydan.erp.seguridad.business.entity.Usuario;
import com.bydan.erp.seguridad.business.entity.ResumenUsuario;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralSg;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralUsuario;
import com.bydan.erp.seguridad.util.SistemaParameterReturnGeneral;
import com.bydan.erp.activosfijos.business.entity.report.*;
import com.bydan.erp.activosfijos.util.report.ResponsablesConstantesFunciones;
import com.bydan.erp.activosfijos.business.logic.report.*;
import com.bydan.framework.erp.business.entity.DatoGeneral;
import com.bydan.framework.erp.business.entity.OrderBy;
import com.bydan.framework.erp.business.entity.Mensajes;
import com.bydan.framework.erp.business.entity.Classe;
import com.bydan.framework.erp.business.logic.*;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverter;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverterFromDate;
import com.bydan.framework.erp.presentation.desktop.swing.FuncionesSwing;
import com.bydan.framework.erp.presentation.desktop.swing.JInternalFrameBase;
import com.bydan.framework.erp.presentation.desktop.swing.*;
import com.bydan.framework.erp.util.*;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.*;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.TableColumn;
import com.toedter.calendar.JDateChooser;
@SuppressWarnings("unused")
public class ResponsablesJInternalFrame extends ResponsablesBeanSwingJInternalFrameAdditional {
private static final long serialVersionUID = 1L;
//protected Usuario usuarioActual=null;
public JToolBar jTtoolBarResponsables;
protected JMenuBar jmenuBarResponsables;
protected JMenu jmenuResponsables;
protected JMenu jmenuDatosResponsables;
protected JMenu jmenuArchivoResponsables;
protected JMenu jmenuAccionesResponsables;
protected JPanel jContentPane = null;
protected JPanel jPanelBusquedasParametrosResponsables = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
protected GridBagLayout gridaBagLayoutResponsables;
protected GridBagConstraints gridBagConstraintsResponsables;
//protected JInternalFrameBase jInternalFrameParent;
public ResponsablesDetalleFormJInternalFrame jInternalFrameDetalleFormResponsables;
protected ReporteDinamicoJInternalFrame jInternalFrameReporteDinamicoResponsables;
protected ImportacionJInternalFrame jInternalFrameImportacionResponsables;
//VENTANAS PARA ACTUALIZAR Y BUSCAR FK
protected EmpresaBeanSwingJInternalFrame empresaBeanSwingJInternalFrame;
public String sFinalQueryGeneral_empresa="";
public ResponsablesSessionBean responsablesSessionBean;
public EmpresaSessionBean empresaSessionBean;
//protected JDesktopPane jDesktopPane;
public List<Responsables> responsabless;
public List<Responsables> responsablessEliminados;
public List<Responsables> responsablessAux;
protected OrderByJInternalFrame jInternalFrameOrderByResponsables;
protected JButton jButtonAbrirOrderByResponsables;
//protected JPanel jPanelOrderByResponsables;
//public JScrollPane jScrollPanelOrderByResponsables;
//protected JButton jButtonCerrarOrderByResponsables;
public ArrayList<OrderBy> arrOrderBy= new ArrayList<OrderBy>();
public ResponsablesLogic responsablesLogic;
public JScrollPane jScrollPanelDatosResponsables;
public JScrollPane jScrollPanelDatosEdicionResponsables;
public JScrollPane jScrollPanelDatosGeneralResponsables;
//public JScrollPane jScrollPanelDatosResponsablesOrderBy;
//public JScrollPane jScrollPanelReporteDinamicoResponsables;
//public JScrollPane jScrollPanelImportacionResponsables;
protected JPanel jPanelAccionesResponsables;
protected JPanel jPanelPaginacionResponsables;
protected JPanel jPanelParametrosReportesResponsables;
protected JPanel jPanelParametrosReportesAccionesResponsables;
;
protected JPanel jPanelParametrosAuxiliar1Responsables;
protected JPanel jPanelParametrosAuxiliar2Responsables;
protected JPanel jPanelParametrosAuxiliar3Responsables;
protected JPanel jPanelParametrosAuxiliar4Responsables;
//protected JPanel jPanelParametrosAuxiliar5Responsables;
//protected JPanel jPanelReporteDinamicoResponsables;
//protected JPanel jPanelImportacionResponsables;
public JTable jTableDatosResponsables;
//public JTable jTableDatosResponsablesOrderBy;
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
protected JButton jButtonNuevoResponsables;
protected JButton jButtonDuplicarResponsables;
protected JButton jButtonCopiarResponsables;
protected JButton jButtonVerFormResponsables;
protected JButton jButtonNuevoRelacionesResponsables;
protected JButton jButtonModificarResponsables;
protected JButton jButtonGuardarCambiosTablaResponsables;
protected JButton jButtonCerrarResponsables;
protected JButton jButtonRecargarInformacionResponsables;
protected JButton jButtonProcesarInformacionResponsables;
protected JButton jButtonAnterioresResponsables;
protected JButton jButtonSiguientesResponsables;
protected JButton jButtonNuevoGuardarCambiosResponsables;
//protected JButton jButtonGenerarReporteDinamicoResponsables;
//protected JButton jButtonCerrarReporteDinamicoResponsables;
//protected JButton jButtonGenerarExcelReporteDinamicoResponsables;
//protected JButton jButtonAbrirImportacionResponsables;
//protected JButton jButtonGenerarImportacionResponsables;
//protected JButton jButtonCerrarImportacionResponsables;
//protected JFileChooser jFileChooserImportacionResponsables;
//protected File fileImportacionResponsables;
//TOOLBAR
protected JButton jButtonNuevoToolBarResponsables;
protected JButton jButtonDuplicarToolBarResponsables;
protected JButton jButtonNuevoRelacionesToolBarResponsables;
public JButton jButtonGuardarCambiosToolBarResponsables;
protected JButton jButtonCopiarToolBarResponsables;
protected JButton jButtonVerFormToolBarResponsables;
public JButton jButtonGuardarCambiosTablaToolBarResponsables;
protected JButton jButtonMostrarOcultarTablaToolBarResponsables;
protected JButton jButtonCerrarToolBarResponsables;
protected JButton jButtonRecargarInformacionToolBarResponsables;
protected JButton jButtonProcesarInformacionToolBarResponsables;
protected JButton jButtonAnterioresToolBarResponsables;
protected JButton jButtonSiguientesToolBarResponsables;
protected JButton jButtonNuevoGuardarCambiosToolBarResponsables;
protected JButton jButtonAbrirOrderByToolBarResponsables;
//TOOLBAR
//MENU
protected JMenuItem jMenuItemNuevoResponsables;
protected JMenuItem jMenuItemDuplicarResponsables;
protected JMenuItem jMenuItemNuevoRelacionesResponsables;
protected JMenuItem jMenuItemGuardarCambiosResponsables;
protected JMenuItem jMenuItemCopiarResponsables;
protected JMenuItem jMenuItemVerFormResponsables;
protected JMenuItem jMenuItemGuardarCambiosTablaResponsables;
protected JMenuItem jMenuItemCerrarResponsables;
protected JMenuItem jMenuItemDetalleCerrarResponsables;
protected JMenuItem jMenuItemDetalleAbrirOrderByResponsables;
protected JMenuItem jMenuItemDetalleMostarOcultarResponsables;
protected JMenuItem jMenuItemRecargarInformacionResponsables;
protected JMenuItem jMenuItemProcesarInformacionResponsables;
protected JMenuItem jMenuItemAnterioresResponsables;
protected JMenuItem jMenuItemSiguientesResponsables;
protected JMenuItem jMenuItemNuevoGuardarCambiosResponsables;
protected JMenuItem jMenuItemAbrirOrderByResponsables;
protected JMenuItem jMenuItemMostrarOcultarResponsables;
//MENU
protected JLabel jLabelAccionesResponsables;
protected JCheckBox jCheckBoxSeleccionarTodosResponsables;
protected JCheckBox jCheckBoxSeleccionadosResponsables;
protected JCheckBox jCheckBoxConAltoMaximoTablaResponsables;
protected JCheckBox jCheckBoxConGraficoReporteResponsables;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposArchivosReportesResponsables;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposReportesResponsables;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxTiposArchivosReportesDinamicoResponsables;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxTiposReportesDinamicoResponsables;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposGraficosReportesResponsables;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposPaginacionResponsables;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposRelacionesResponsables;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposAccionesResponsables;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposSeleccionarResponsables;
protected JTextField jTextFieldValorCampoGeneralResponsables;
//REPORTE DINAMICO
//@SuppressWarnings("rawtypes")
//public JLabel jLabelColumnasSelectReporteResponsables;
//public JList<Reporte> jListColumnasSelectReporteResponsables;
//public JScrollPane jScrollColumnasSelectReporteResponsables;
//public JLabel jLabelRelacionesSelectReporteResponsables;
//public JList<Reporte> jListRelacionesSelectReporteResponsables;
//public JScrollPane jScrollRelacionesSelectReporteResponsables;
//public JLabel jLabelConGraficoDinamicoResponsables;
//protected JCheckBox jCheckBoxConGraficoDinamicoResponsables;
//public JLabel jLabelGenerarExcelReporteDinamicoResponsables;
//public JLabel jLabelTiposArchivoReporteDinamicoResponsables;
//public JLabel jLabelArchivoImportacionResponsables;
//public JLabel jLabelPathArchivoImportacionResponsables;
//protected JTextField jTextFieldPathArchivoImportacionResponsables;
//public JLabel jLabelColumnaCategoriaGraficoResponsables;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxColumnaCategoriaGraficoResponsables;
//public JLabel jLabelColumnaCategoriaValorResponsables;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxColumnaCategoriaValorResponsables;
//public JLabel jLabelColumnasValoresGraficoResponsables;
//public JList<Reporte> jListColumnasValoresGraficoResponsables;
//public JScrollPane jScrollColumnasValoresGraficoResponsables;
//public JLabel jLabelTiposGraficosReportesDinamicoResponsables;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxTiposGraficosReportesDinamicoResponsables;
protected Boolean conMaximoRelaciones=true;
protected Boolean conFuncionalidadRelaciones=true;
public Boolean conCargarMinimo=false;
public Boolean cargarRelaciones=false;
public Boolean conMostrarAccionesCampo=false;
public Boolean permiteRecargarForm=false;//PARA NUEVO PREPARAR Y MANEJO DE EVENTOS, EVITAR QUE SE EJECUTE AL CARGAR VENTANA O LOAD
public Boolean conCargarFormDetalle=false;
//BYDAN_BUSQUEDAS
public JTabbedPane jTabbedPaneBusquedasResponsables;
public JPanel jPanelBusquedaResponsablesResponsables;
public JButton jButtonBusquedaResponsablesResponsables;
public JPanel jPanelIdIdBusquedaResponsablesResponsables;
public JLabel jLabelidBusquedaResponsablesResponsables;
public JTextFieldMe jLabelidResponsablesBusquedaResponsables;
public JButton jButtonidBusquedaResponsablesResponsablesBusqueda= new JButtonMe();
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
public static int openFrameCount = 0;
public static final int xOffset = 10, yOffset = 35;
//LOS DATOS DE NUEVO Y EDICION ACTUAL APARECEN EN OTRA VENTANA(true) O NO(false)
public static Boolean CON_DATOS_FRAME=true;
public static Boolean ISBINDING_MANUAL=true;
public static Boolean ISLOAD_FKLOTE=false;
public static Boolean ISBINDING_MANUAL_TABLA=true;
public static Boolean CON_CARGAR_MEMORIA_INICIAL=true;
//Al final no se utilizan, se inicializan desde JInternalFrameBase, desde ParametroGeneralUsuario
public static String STIPO_TAMANIO_GENERAL="NORMAL";
public static String STIPO_TAMANIO_GENERAL_TABLA="NORMAL";
public static Boolean CONTIPO_TAMANIO_MANUAL=false;
public static Boolean CON_LLAMADA_SIMPLE=true;
public static Boolean CON_LLAMADA_SIMPLE_TOTAL=true;
public static Boolean ESTA_CARGADO_PORPARTE=false;
public int iWidthScroll=0;//(screenSize.width-screenSize.width/2)+(250*1);
public int iHeightScroll=0;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//public int iWidthFormulario=750;//(screenSize.width-screenSize.width/2)+(250*1);
//public int iHeightFormulario=946;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//Esto va en DetalleForm
//public int iHeightFormularioMaximo=0;
//public int iWidthFormularioMaximo=0;
public int iWidthTableDefinicion=0;
public double dStart = 0;
public double dEnd = 0;
public double dDif = 0;
/*
double start=(double)System.currentTimeMillis();
double end=0;
double dif=0;
end=(double)System.currentTimeMillis();
dif=end - start;
start=(double)System.currentTimeMillis();
System.out.println("Tiempo(ms) Carga TEST 1_2 DetalleMovimientoInventario: " + dif);
*/
public SistemaParameterReturnGeneral sistemaReturnGeneral;
public List<Opcion> opcionsRelacionadas=new ArrayList<Opcion>();
//ES AUXILIAR PARA WINDOWS FORMS
public ResponsablesJInternalFrame() throws Exception {
super(PaginaTipo.PRINCIPAL);
//super("Responsables No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
//Boolean cargarRelaciones=false;
initialize(null,false,false,false/*cargarRelaciones*/,null,null,null,null,null,null,PaginaTipo.PRINCIPAL);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public ResponsablesJInternalFrame(Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("Responsables No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,paginaTipo);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public ResponsablesJInternalFrame(Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("Responsables No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
initialize(null,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,null,null,null,null,null,null,paginaTipo);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public ResponsablesJInternalFrame(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);//,jdesktopPane
this.jDesktopPane=jdesktopPane;
this.dStart=(double)System.currentTimeMillis();
//super("Responsables No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
long start_time=0;
long end_time=0;
if(Constantes2.ISDEVELOPING2) {
start_time = System.currentTimeMillis();
}
initialize(jdesktopPane,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo);
if(Constantes2.ISDEVELOPING2) {
end_time = System.currentTimeMillis();
String sTipo="Clase Padre Ventana";
Funciones2.getMensajeTiempoEjecucion(start_time, end_time, sTipo,false);
}
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public JInternalFrameBase getJInternalFrameParent() {
return jInternalFrameParent;
}
public void setJInternalFrameParent(JInternalFrameBase internalFrameParent) {
jInternalFrameParent = internalFrameParent;
}
public void setjButtonRecargarInformacion(JButton jButtonRecargarInformacionResponsables) {
this.jButtonRecargarInformacionResponsables = jButtonRecargarInformacionResponsables;
}
public JButton getjButtonProcesarInformacionResponsables() {
return this.jButtonProcesarInformacionResponsables;
}
public void setjButtonProcesarInformacion(JButton jButtonProcesarInformacionResponsables) {
this.jButtonProcesarInformacionResponsables = jButtonProcesarInformacionResponsables;
}
public JButton getjButtonRecargarInformacionResponsables() {
return this.jButtonRecargarInformacionResponsables;
}
public List<Responsables> getresponsabless() {
return this.responsabless;
}
public void setresponsabless(List<Responsables> responsabless) {
this.responsabless = responsabless;
}
public List<Responsables> getresponsablessAux() {
return this.responsablessAux;
}
public void setresponsablessAux(List<Responsables> responsablessAux) {
this.responsablessAux = responsablessAux;
}
public List<Responsables> getresponsablessEliminados() {
return this.responsablessEliminados;
}
public void setResponsablessEliminados(List<Responsables> responsablessEliminados) {
this.responsablessEliminados = responsablessEliminados;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposSeleccionarResponsables() {
return jComboBoxTiposSeleccionarResponsables;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposSeleccionarResponsables(
JComboBox jComboBoxTiposSeleccionarResponsables) {
this.jComboBoxTiposSeleccionarResponsables = jComboBoxTiposSeleccionarResponsables;
}
public void setBorderResaltarTiposSeleccionarResponsables() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarResponsables.setBorder(borderResaltar);
this.jComboBoxTiposSeleccionarResponsables .setBorder(borderResaltar);
}
public JTextField getjTextFieldValorCampoGeneralResponsables() {
return jTextFieldValorCampoGeneralResponsables;
}
public void setjTextFieldValorCampoGeneralResponsables(
JTextField jTextFieldValorCampoGeneralResponsables) {
this.jTextFieldValorCampoGeneralResponsables = jTextFieldValorCampoGeneralResponsables;
}
public void setBorderResaltarValorCampoGeneralResponsables() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarResponsables.setBorder(borderResaltar);
this.jTextFieldValorCampoGeneralResponsables .setBorder(borderResaltar);
}
public JCheckBox getjCheckBoxSeleccionarTodosResponsables() {
return this.jCheckBoxSeleccionarTodosResponsables;
}
public void setjCheckBoxSeleccionarTodosResponsables(
JCheckBox jCheckBoxSeleccionarTodosResponsables) {
this.jCheckBoxSeleccionarTodosResponsables = jCheckBoxSeleccionarTodosResponsables;
}
public void setBorderResaltarSeleccionarTodosResponsables() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarResponsables.setBorder(borderResaltar);
this.jCheckBoxSeleccionarTodosResponsables .setBorder(borderResaltar);
}
public JCheckBox getjCheckBoxSeleccionadosResponsables() {
return this.jCheckBoxSeleccionadosResponsables;
}
public void setjCheckBoxSeleccionadosResponsables(
JCheckBox jCheckBoxSeleccionadosResponsables) {
this.jCheckBoxSeleccionadosResponsables = jCheckBoxSeleccionadosResponsables;
}
public void setBorderResaltarSeleccionadosResponsables() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarResponsables.setBorder(borderResaltar);
this.jCheckBoxSeleccionadosResponsables .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposArchivosReportesResponsables() {
return this.jComboBoxTiposArchivosReportesResponsables;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposArchivosReportesResponsables(
JComboBox jComboBoxTiposArchivosReportesResponsables) {
this.jComboBoxTiposArchivosReportesResponsables = jComboBoxTiposArchivosReportesResponsables;
}
public void setBorderResaltarTiposArchivosReportesResponsables() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarResponsables.setBorder(borderResaltar);
this.jComboBoxTiposArchivosReportesResponsables .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposReportesResponsables() {
return this.jComboBoxTiposReportesResponsables;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposReportesResponsables(
JComboBox jComboBoxTiposReportesResponsables) {
this.jComboBoxTiposReportesResponsables = jComboBoxTiposReportesResponsables;
}
//@SuppressWarnings("rawtypes")
//public JComboBox getjComboBoxTiposReportesDinamicoResponsables() {
// return jComboBoxTiposReportesDinamicoResponsables;
//}
//@SuppressWarnings("rawtypes")
//public void setjComboBoxTiposReportesDinamicoResponsables(
// JComboBox jComboBoxTiposReportesDinamicoResponsables) {
// this.jComboBoxTiposReportesDinamicoResponsables = jComboBoxTiposReportesDinamicoResponsables;
//}
//@SuppressWarnings("rawtypes")
//public JComboBox getjComboBoxTiposArchivosReportesDinamicoResponsables() {
// return jComboBoxTiposArchivosReportesDinamicoResponsables;
//}
//@SuppressWarnings("rawtypes")
//public void setjComboBoxTiposArchivosReportesDinamicoResponsables(
// JComboBox jComboBoxTiposArchivosReportesDinamicoResponsables) {
// this.jComboBoxTiposArchivosReportesDinamicoResponsables = jComboBoxTiposArchivosReportesDinamicoResponsables;
//}
public void setBorderResaltarTiposReportesResponsables() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarResponsables.setBorder(borderResaltar);
this.jComboBoxTiposReportesResponsables .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposGraficosReportesResponsables() {
return this.jComboBoxTiposGraficosReportesResponsables;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposGraficosReportesResponsables(
JComboBox jComboBoxTiposGraficosReportesResponsables) {
this.jComboBoxTiposGraficosReportesResponsables = jComboBoxTiposGraficosReportesResponsables;
}
public void setBorderResaltarTiposGraficosReportesResponsables() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarResponsables.setBorder(borderResaltar);
this.jComboBoxTiposGraficosReportesResponsables .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposPaginacionResponsables() {
return this.jComboBoxTiposPaginacionResponsables;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposPaginacionResponsables(
JComboBox jComboBoxTiposPaginacionResponsables) {
this.jComboBoxTiposPaginacionResponsables = jComboBoxTiposPaginacionResponsables;
}
public void setBorderResaltarTiposPaginacionResponsables() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarResponsables.setBorder(borderResaltar);
this.jComboBoxTiposPaginacionResponsables .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposRelacionesResponsables() {
return this.jComboBoxTiposRelacionesResponsables;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposAccionesResponsables() {
return this.jComboBoxTiposAccionesResponsables;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposRelacionesResponsables(
JComboBox jComboBoxTiposRelacionesResponsables) {
this.jComboBoxTiposRelacionesResponsables = jComboBoxTiposRelacionesResponsables;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposAccionesResponsables(
JComboBox jComboBoxTiposAccionesResponsables) {
this.jComboBoxTiposAccionesResponsables = jComboBoxTiposAccionesResponsables;
}
public void setBorderResaltarTiposRelacionesResponsables() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarResponsables.setBorder(borderResaltar);
this.jComboBoxTiposRelacionesResponsables .setBorder(borderResaltar);
}
public void setBorderResaltarTiposAccionesResponsables() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarResponsables.setBorder(borderResaltar);
this.jComboBoxTiposAccionesResponsables .setBorder(borderResaltar);
}
//public JCheckBox getjCheckBoxConGraficoDinamicoResponsables() {
// return jCheckBoxConGraficoDinamicoResponsables;
//}
//public void setjCheckBoxConGraficoDinamicoResponsables(
// JCheckBox jCheckBoxConGraficoDinamicoResponsables) {
// this.jCheckBoxConGraficoDinamicoResponsables = jCheckBoxConGraficoDinamicoResponsables;
//}
//public void setBorderResaltarConGraficoDinamicoResponsables() {
// Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
// this.jTtoolBarResponsables.setBorder(borderResaltar);
// this.jCheckBoxConGraficoDinamicoResponsables .setBorder(borderResaltar);
//}
/*
public JDesktopPane getJDesktopPane() {
return jDesktopPane;
}
public void setJDesktopPane(JDesktopPane desktopPane) {
jDesktopPane = desktopPane;
}
*/
private void initialize(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
this.responsablesSessionBean=new ResponsablesSessionBean();
this.responsablesSessionBean.setConGuardarRelaciones(conGuardarRelaciones);
this.responsablesSessionBean.setEsGuardarRelacionado(esGuardarRelacionado);
this.conCargarMinimo=this.responsablesSessionBean.getEsGuardarRelacionado();
this.cargarRelaciones=cargarRelaciones;
if(!this.conCargarMinimo) {
}
//this.sTipoTamanioGeneral=ResponsablesJInternalFrame.STIPO_TAMANIO_GENERAL;
//this.sTipoTamanioGeneralTabla=ResponsablesJInternalFrame.STIPO_TAMANIO_GENERAL_TABLA;
this.sTipoTamanioGeneral=FuncionesSwing.getTipoTamanioGeneral(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.sTipoTamanioGeneralTabla=FuncionesSwing.getTipoTamanioGeneralTabla(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.conTipoTamanioManual=FuncionesSwing.getConTipoTamanioManual(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.conTipoTamanioTodo=FuncionesSwing.getConTipoTamanioTodo(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
ResponsablesJInternalFrame.STIPO_TAMANIO_GENERAL=this.sTipoTamanioGeneral;
ResponsablesJInternalFrame.STIPO_TAMANIO_GENERAL_TABLA=this.sTipoTamanioGeneralTabla;
ResponsablesJInternalFrame.CONTIPO_TAMANIO_MANUAL=this.conTipoTamanioManual;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int iWidth=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO);
int iHeight=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//this.setTitle(Funciones.GetTituloSistema(this.parametroGeneralSg,this.moduloActual,this.opcionActual,this.usuarioActual,"Responsables MANTENIMIENTO"));
if(iWidth > 1550) {
iWidth=1550;
}
if(iHeight > 660) {
iHeight=660;
}
this.setSize(iWidth,iHeight);
this.setFrameIcon(new ImageIcon(FuncionesSwing.getImagenBackground(Constantes2.S_ICON_IMAGE)));
this.setContentPane(this.getJContentPane(iWidth,iHeight,jdesktopPane,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo));
if(!this.responsablesSessionBean.getEsGuardarRelacionado()) {
this.setResizable(true);
this.setClosable(true);
this.setMaximizable(true);
this.iconable=true;
setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
if(Constantes.CON_VARIAS_VENTANAS) {
openFrameCount++;
if(openFrameCount==Constantes.INUM_MAX_VENTANAS) {
openFrameCount=0;
}
}
}
ResponsablesJInternalFrame.ESTA_CARGADO_PORPARTE=true;
//super("Responsables No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
//SwingUtilities.updateComponentTreeUI(this);
}
public void inicializarToolBar() {
this.jTtoolBarResponsables= new JToolBar("MENU PRINCIPAL");
//TOOLBAR
//PRINCIPAL
this.jButtonNuevoToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonNuevoToolBarResponsables,this.jTtoolBarResponsables,
"nuevo","nuevo","Nuevo"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO"),"Nuevo",false);
this.jButtonNuevoGuardarCambiosToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonNuevoGuardarCambiosToolBarResponsables,this.jTtoolBarResponsables,
"nuevoguardarcambios","nuevoguardarcambios","Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"),"Nuevo",false);
this.jButtonGuardarCambiosTablaToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonGuardarCambiosTablaToolBarResponsables,this.jTtoolBarResponsables,
"guardarcambiostabla","guardarcambiostabla","Guardar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"),"Guardar",false);
this.jButtonDuplicarToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonDuplicarToolBarResponsables,this.jTtoolBarResponsables,
"duplicar","duplicar","Duplicar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("DUPLICAR"),"Duplicar",false);
this.jButtonCopiarToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonCopiarToolBarResponsables,this.jTtoolBarResponsables,
"copiar","copiar","Copiar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("COPIAR"),"Copiar",false);
this.jButtonVerFormToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonVerFormToolBarResponsables,this.jTtoolBarResponsables,
"ver_form","ver_form","Ver"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("VER_FORM"),"Ver",false);
this.jButtonRecargarInformacionToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonRecargarInformacionToolBarResponsables,this.jTtoolBarResponsables,
"recargar","recargar","Buscar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("RECARGAR"),"Buscar",false);
this.jButtonAnterioresToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonRecargarInformacionToolBarResponsables,this.jTtoolBarResponsables,
"anteriores","anteriores","Anteriores Datos" + FuncionesSwing.getKeyMensaje("ANTERIORES"),"<<",false);
this.jButtonSiguientesToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonRecargarInformacionToolBarResponsables,this.jTtoolBarResponsables,
"siguientes","siguientes","Siguientes Datos" + FuncionesSwing.getKeyMensaje("SIGUIENTES"),">>",false);
this.jButtonAbrirOrderByToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonAbrirOrderByToolBarResponsables,this.jTtoolBarResponsables,
"orden","orden","Orden" + FuncionesSwing.getKeyMensaje("ORDEN"),"Orden",false);
this.jButtonNuevoRelacionesToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonNuevoRelacionesToolBarResponsables,this.jTtoolBarResponsables,
"nuevo_relaciones","nuevo_relaciones","NUEVO RELACIONES" + FuncionesSwing.getKeyMensaje("NUEVO_RELACIONES"),"NUEVO RELACIONES",false);
this.jButtonMostrarOcultarTablaToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonMostrarOcultarTablaToolBarResponsables,this.jTtoolBarResponsables,
"mostrar_ocultar","mostrar_ocultar","Mostrar Ocultar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"),"Mostrar Ocultar",false);
this.jButtonCerrarToolBarResponsables=FuncionesSwing.getButtonToolBarGeneral(this.jButtonCerrarToolBarResponsables,this.jTtoolBarResponsables,
"cerrar","cerrar","Salir"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CERRAR"),"Salir",false);
//this.jButtonNuevoRelacionesToolBarResponsables=new JButtonMe();
//protected JButton jButtonNuevoRelacionesToolBarResponsables;
this.jButtonProcesarInformacionToolBarResponsables=new JButtonMe();
//protected JButton jButtonProcesarInformacionToolBarResponsables;
//protected JButton jButtonModificarToolBarResponsables;
//PRINCIPAL
//DETALLE
//DETALLE_FIN
}
public void cargarMenus() {
this.jmenuBarResponsables=new JMenuBarMe();
//PRINCIPAL
this.jmenuResponsables=new JMenuMe("General");
this.jmenuArchivoResponsables=new JMenuMe("Archivo");
this.jmenuAccionesResponsables=new JMenuMe("Acciones");
this.jmenuDatosResponsables=new JMenuMe("Datos");
//PRINCIPAL_FIN
//DETALLE
//DETALLE_FIN
this.jMenuItemNuevoResponsables= new JMenuItem("Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jMenuItemNuevoResponsables.setActionCommand("Nuevo");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoResponsables,"nuevo_button","Nuevo");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDuplicarResponsables= new JMenuItem("Duplicar" + FuncionesSwing.getKeyMensaje("DUPLICAR"));
this.jMenuItemDuplicarResponsables.setActionCommand("Duplicar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDuplicarResponsables,"duplicar_button","Duplicar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDuplicarResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemNuevoRelacionesResponsables= new JMenuItem("Nuevo Rel" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"));
this.jMenuItemNuevoRelacionesResponsables.setActionCommand("Nuevo Rel");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoRelacionesResponsables,"nuevorelaciones_button","Nuevo Rel");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoRelacionesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemGuardarCambiosResponsables= new JMenuItem("Guardar" + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jMenuItemGuardarCambiosResponsables.setActionCommand("Guardar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemGuardarCambiosResponsables,"guardarcambios_button","Guardar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemGuardarCambiosResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCopiarResponsables= new JMenuItem("Copiar" + FuncionesSwing.getKeyMensaje("COPIAR"));
this.jMenuItemCopiarResponsables.setActionCommand("Copiar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCopiarResponsables,"copiar_button","Copiar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCopiarResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemVerFormResponsables= new JMenuItem("Ver" + FuncionesSwing.getKeyMensaje("VER_FORM"));
this.jMenuItemVerFormResponsables.setActionCommand("Ver");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemVerFormResponsables,"ver_form_button","Ver");
FuncionesSwing.setBoldMenuItem(this.jMenuItemVerFormResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemGuardarCambiosTablaResponsables= new JMenuItem("Guardar Tabla" + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jMenuItemGuardarCambiosTablaResponsables.setActionCommand("Guardar Tabla");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemGuardarCambiosTablaResponsables,"guardarcambiostabla_button","Guardar Tabla");
FuncionesSwing.setBoldMenuItem(this.jMenuItemGuardarCambiosTablaResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCerrarResponsables= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR"));
this.jMenuItemCerrarResponsables.setActionCommand("Cerrar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCerrarResponsables,"cerrar_button","Salir");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCerrarResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemRecargarInformacionResponsables= new JMenuItem("Recargar" + FuncionesSwing.getKeyMensaje("RECARGAR"));
this.jMenuItemRecargarInformacionResponsables.setActionCommand("Recargar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemRecargarInformacionResponsables,"recargar_button","Recargar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemRecargarInformacionResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemProcesarInformacionResponsables= new JMenuItem("Procesar Informacion");
this.jMenuItemProcesarInformacionResponsables.setActionCommand("Procesar Informacion");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemProcesarInformacionResponsables,"procesar_button","Procesar Informacion");
this.jMenuItemAnterioresResponsables= new JMenuItem("Anteriores" + FuncionesSwing.getKeyMensaje("ANTERIORES"));
this.jMenuItemAnterioresResponsables.setActionCommand("Anteriores");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemAnterioresResponsables,"anteriores_button","Anteriores");
FuncionesSwing.setBoldMenuItem(this.jMenuItemAnterioresResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemSiguientesResponsables= new JMenuItem("Siguientes" + FuncionesSwing.getKeyMensaje("SIGUIENTES"));
this.jMenuItemSiguientesResponsables.setActionCommand("Siguientes");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemSiguientesResponsables,"siguientes_button","Siguientes");
FuncionesSwing.setBoldMenuItem(this.jMenuItemSiguientesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemAbrirOrderByResponsables= new JMenuItem("Orden" + FuncionesSwing.getKeyMensaje("ORDEN"));
this.jMenuItemAbrirOrderByResponsables.setActionCommand("Orden");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemAbrirOrderByResponsables,"orden_button","Orden");
FuncionesSwing.setBoldMenuItem(this.jMenuItemAbrirOrderByResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemMostrarOcultarResponsables= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemMostrarOcultarResponsables.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemMostrarOcultarResponsables,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemMostrarOcultarResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleAbrirOrderByResponsables= new JMenuItem("Orden" + FuncionesSwing.getKeyMensaje("ORDEN"));
this.jMenuItemDetalleAbrirOrderByResponsables.setActionCommand("Orden");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleAbrirOrderByResponsables,"orden_button","Orden");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleAbrirOrderByResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleMostarOcultarResponsables= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemDetalleMostarOcultarResponsables.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleMostarOcultarResponsables,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleMostarOcultarResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemNuevoGuardarCambiosResponsables= new JMenuItem("Nuevo Tabla" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"));
this.jMenuItemNuevoGuardarCambiosResponsables.setActionCommand("Nuevo Tabla");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoGuardarCambiosResponsables,"nuevoguardarcambios_button","Nuevo");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoGuardarCambiosResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
//PRINCIPAL
if(!this.conCargarMinimo) {
this.jmenuArchivoResponsables.add(this.jMenuItemCerrarResponsables);
this.jmenuAccionesResponsables.add(this.jMenuItemNuevoResponsables);
this.jmenuAccionesResponsables.add(this.jMenuItemNuevoGuardarCambiosResponsables);
this.jmenuAccionesResponsables.add(this.jMenuItemNuevoRelacionesResponsables);
this.jmenuAccionesResponsables.add(this.jMenuItemGuardarCambiosTablaResponsables);
this.jmenuAccionesResponsables.add(this.jMenuItemDuplicarResponsables);
this.jmenuAccionesResponsables.add(this.jMenuItemCopiarResponsables);
this.jmenuAccionesResponsables.add(this.jMenuItemVerFormResponsables);
this.jmenuDatosResponsables.add(this.jMenuItemRecargarInformacionResponsables);
this.jmenuDatosResponsables.add(this.jMenuItemAnterioresResponsables);
this.jmenuDatosResponsables.add(this.jMenuItemSiguientesResponsables);
this.jmenuDatosResponsables.add(this.jMenuItemAbrirOrderByResponsables);
this.jmenuDatosResponsables.add(this.jMenuItemMostrarOcultarResponsables);
}
//PRINCIPAL_FIN
//DETALLE
//this.jmenuDetalleAccionesResponsables.add(this.jMenuItemGuardarCambiosResponsables);
//DETALLE_FIN
//RELACIONES
//RELACIONES
//PRINCIPAL
if(!this.conCargarMinimo) {
FuncionesSwing.setBoldMenu(this.jmenuArchivoResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuAccionesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuDatosResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jmenuBarResponsables.add(this.jmenuArchivoResponsables);
this.jmenuBarResponsables.add(this.jmenuAccionesResponsables);
this.jmenuBarResponsables.add(this.jmenuDatosResponsables);
}
//PRINCIPAL_FIN
//DETALLE
//DETALLE_FIN
//AGREGA MENU A PANTALLA
if(!this.conCargarMinimo) {
this.setJMenuBar(this.jmenuBarResponsables);
}
//AGREGA MENU DETALLE A PANTALLA
}
public void inicializarElementosBusquedasResponsables() {
//BYDAN_BUSQUEDAS
//INDICES BUSQUEDA
this.jPanelBusquedaResponsablesResponsables=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelBusquedaResponsablesResponsables.setToolTipText("Buscar Por ");
this.jButtonBusquedaResponsablesResponsables= new JButtonMe();
this.jButtonBusquedaResponsablesResponsables.setText("Buscar");
this.jButtonBusquedaResponsablesResponsables.setToolTipText("Buscar Por ");
FuncionesSwing.addImagenButtonGeneral(this.jButtonBusquedaResponsablesResponsables,"buscar_button","Buscar Por ");
FuncionesSwing.setBoldButton(this.jButtonBusquedaResponsablesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
jLabelidBusquedaResponsablesResponsables = new JLabelMe();
jLabelidBusquedaResponsablesResponsables.setText("Id :");
jLabelidBusquedaResponsablesResponsables.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,-4),Constantes.ISWING_ALTO_CONTROL));
jLabelidBusquedaResponsablesResponsables.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,-4),Constantes.ISWING_ALTO_CONTROL));
jLabelidBusquedaResponsablesResponsables.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,-4),Constantes.ISWING_ALTO_CONTROL));
FuncionesSwing.setBoldLabel(jLabelidBusquedaResponsablesResponsables,STIPO_TAMANIO_GENERAL,false,true,this);
jLabelidResponsablesBusquedaResponsables= new JTextFieldMe();
jLabelidResponsablesBusquedaResponsables.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
jLabelidResponsablesBusquedaResponsables.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
jLabelidResponsablesBusquedaResponsables.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
//SE OCULTA CAMPO ID AUXILIAR PARA REPORTE
jLabelidResponsablesBusquedaResponsables.setVisible(false);
this.jTabbedPaneBusquedasResponsables=new JTabbedPane();
this.jTabbedPaneBusquedasResponsables.setMinimumSize(new Dimension(this.getWidth(),Constantes.ISWING_ALTO_TABPANE_BUSQUEDA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_TABPANE_BUSQUEDA,0)));
this.jTabbedPaneBusquedasResponsables.setMaximumSize(new Dimension(this.getWidth(),Constantes.ISWING_ALTO_TABPANE_BUSQUEDA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_TABPANE_BUSQUEDA,0)));
this.jTabbedPaneBusquedasResponsables.setPreferredSize(new Dimension(this.getWidth(),Constantes.ISWING_ALTO_TABPANE_BUSQUEDA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_TABPANE_BUSQUEDA,0)));
//this.jTabbedPaneBusquedasResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Busqueda"));
this.jTabbedPaneBusquedasResponsables.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
FuncionesSwing.setBoldTabbedPane(this.jTabbedPaneBusquedasResponsables,STIPO_TAMANIO_GENERAL,false,true,this);
//INDICES BUSQUEDA_FIN
}
//JPanel
//@SuppressWarnings({"unchecked" })//"rawtypes"
public JScrollPane getJContentPane(int iWidth,int iHeight,JDesktopPane jDesktopPane,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
//PARA TABLA PARAMETROS
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
this.jContentPane = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.usuarioActual=usuarioActual;
this.resumenUsuarioActual=resumenUsuarioActual;
this.opcionActual=opcionActual;
this.moduloActual=moduloActual;
this.parametroGeneralSg=parametroGeneralSg;
this.parametroGeneralUsuario=parametroGeneralUsuario;
this.jDesktopPane=jDesktopPane;
this.conFuncionalidadRelaciones=parametroGeneralUsuario.getcon_guardar_relaciones();
int iGridyPrincipal=0;
this.inicializarToolBar();
//CARGAR MENUS
if(this.conCargarFormDetalle) { //true) {
//this.jInternalFrameDetalleResponsables = new ResponsablesDetalleJInternalFrame(paginaTipo);//JInternalFrameBase("Responsables DATOS");
this.jInternalFrameDetalleFormResponsables = new ResponsablesDetalleFormJInternalFrame(jDesktopPane,this.responsablesSessionBean.getConGuardarRelaciones(),this.responsablesSessionBean.getEsGuardarRelacionado(),cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo);
} else {
this.jInternalFrameDetalleFormResponsables = null;//new ResponsablesDetalleFormJInternalFrame("MINIMO");
}
this.cargarMenus();
this.gridaBagLayoutResponsables= new GridBagLayout();
this.jTableDatosResponsables = new JTableMe();
String sToolTipResponsables="";
sToolTipResponsables=ResponsablesConstantesFunciones.SCLASSWEBTITULO;
if(Constantes.ISDEVELOPING) {
sToolTipResponsables+="(ActivosFijos.Responsables)";
}
if(!this.responsablesSessionBean.getEsGuardarRelacionado()) {
sToolTipResponsables+="_"+this.opcionActual.getId();
}
this.jTableDatosResponsables.setToolTipText(sToolTipResponsables);
//SE DEFINE EN DETALLE
//FuncionesSwing.setBoldLabelTable(this.jTableDatosResponsables);
this.jTableDatosResponsables.setAutoCreateRowSorter(true);
this.jTableDatosResponsables.setRowHeight(Constantes.ISWING_ALTO_FILA_TABLA + Constantes.ISWING_ALTO_FILA_TABLA_EXTRA_FECHA);
//MULTIPLE SELECTION
this.jTableDatosResponsables.setRowSelectionAllowed(true);
this.jTableDatosResponsables.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
FuncionesSwing.setBoldTable(jTableDatosResponsables,STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonNuevoResponsables = new JButtonMe();
this.jButtonDuplicarResponsables = new JButtonMe();
this.jButtonCopiarResponsables = new JButtonMe();
this.jButtonVerFormResponsables = new JButtonMe();
this.jButtonNuevoRelacionesResponsables = new JButtonMe();
this.jButtonGuardarCambiosTablaResponsables = new JButtonMe();
this.jButtonCerrarResponsables = new JButtonMe();
this.jScrollPanelDatosResponsables = new JScrollPane();
this.jScrollPanelDatosGeneralResponsables = new JScrollPane();
this.jPanelAccionesResponsables = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
//if(!this.conCargarMinimo) {
;
//}
this.sPath=" <---> Acceso: Responsables";
if(!this.responsablesSessionBean.getEsGuardarRelacionado()) {
this.jScrollPanelDatosResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Responsableses" + this.sPath));
} else {
this.jScrollPanelDatosResponsables.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
}
this.jScrollPanelDatosGeneralResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos"));
this.jPanelAccionesResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));
this.jPanelAccionesResponsables.setToolTipText("Acciones");
this.jPanelAccionesResponsables.setName("Acciones");
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosGeneralResponsables, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosResponsables, STIPO_TAMANIO_GENERAL,false,false,this);
//if(!this.conCargarMinimo) {
;
//}
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
if(!this.conCargarMinimo) {
//REPORTE DINAMICO
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameReporteDinamicoResponsables=new ReporteDinamicoJInternalFrame(ResponsablesConstantesFunciones.SCLASSWEBTITULO,this);
//this.cargarReporteDinamicoResponsables();
//IMPORTACION
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameImportacionResponsables=new ImportacionJInternalFrame(ResponsablesConstantesFunciones.SCLASSWEBTITULO,this);
//this.cargarImportacionResponsables();
}
String sMapKey = "";
InputMap inputMap =null;
this.jButtonAbrirOrderByResponsables = new JButtonMe();
this.jButtonAbrirOrderByResponsables.setText("Orden");
this.jButtonAbrirOrderByResponsables.setToolTipText("Orden"+FuncionesSwing.getKeyMensaje("ORDEN"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonAbrirOrderByResponsables,"orden_button","Orden");
FuncionesSwing.setBoldButton(this.jButtonAbrirOrderByResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
sMapKey = "AbrirOrderBySistema";
inputMap = this.jButtonAbrirOrderByResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ORDEN") , FuncionesSwing.getMaskKey("ORDEN")), sMapKey);
this.jButtonAbrirOrderByResponsables.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"AbrirOrderBySistema"));
if(!this.conCargarMinimo) {
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameOrderByResponsables=new OrderByJInternalFrame(STIPO_TAMANIO_GENERAL,this.jButtonAbrirOrderByResponsables,false,this);
//this.cargarOrderByResponsables(false);
} else {
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameOrderByResponsables=new OrderByJInternalFrame(STIPO_TAMANIO_GENERAL,this.jButtonAbrirOrderByResponsables,true,this);
//this.cargarOrderByResponsables(true);
}
//<NAME>
/*
this.jTableDatosResponsables.setMinimumSize(new Dimension(400,50));//1530
this.jTableDatosResponsables.setMaximumSize(new Dimension(400,50));//1530
this.jTableDatosResponsables.setPreferredSize(new Dimension(400,50));//1530
this.jScrollPanelDatosResponsables.setMinimumSize(new Dimension(400,50));
this.jScrollPanelDatosResponsables.setMaximumSize(new Dimension(400,50));
this.jScrollPanelDatosResponsables.setPreferredSize(new Dimension(400,50));
*/
this.jButtonNuevoResponsables.setText("Nuevo");
this.jButtonDuplicarResponsables.setText("Duplicar");
this.jButtonCopiarResponsables.setText("Copiar");
this.jButtonVerFormResponsables.setText("Ver");
this.jButtonNuevoRelacionesResponsables.setText("Nuevo Rel");
this.jButtonGuardarCambiosTablaResponsables.setText("Guardar");
this.jButtonCerrarResponsables.setText("Salir");
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoResponsables,"nuevo_button","Nuevo",this.responsablesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonDuplicarResponsables,"duplicar_button","Duplicar",this.responsablesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCopiarResponsables,"copiar_button","Copiar",this.responsablesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonVerFormResponsables,"ver_form","Ver",this.responsablesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoRelacionesResponsables,"nuevorelaciones_button","Nuevo Rel",this.responsablesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosTablaResponsables,"guardarcambiostabla_button","Guardar",this.responsablesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarResponsables,"cerrar_button","Salir",this.responsablesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.setBoldButton(this.jButtonNuevoResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonDuplicarResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonCopiarResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonVerFormResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonNuevoRelacionesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosTablaResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonCerrarResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonNuevoResponsables.setToolTipText("Nuevo"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jButtonDuplicarResponsables.setToolTipText("Duplicar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("DUPLICAR"));
this.jButtonCopiarResponsables.setToolTipText("Copiar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO+ FuncionesSwing.getKeyMensaje("COPIAR"));
this.jButtonVerFormResponsables.setToolTipText("Ver"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO+ FuncionesSwing.getKeyMensaje("VER_FORM"));
this.jButtonNuevoRelacionesResponsables.setToolTipText("Nuevo Rel"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO_RELACIONES"));
this.jButtonGuardarCambiosTablaResponsables.setToolTipText("Guardar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jButtonCerrarResponsables.setToolTipText("Salir"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CERRAR"));
//HOT KEYS
/*
N->Nuevo
N->Alt + Nuevo Relaciones (ANTES R)
A->Actualizar
E->Eliminar
S->Cerrar
C->->Mayus + Cancelar (ANTES Q->Quit)
G->Guardar Cambios
D->Duplicar
C->Alt + Cop?ar
O->Orden
N->Nuevo Tabla
R->Recargar Informacion Inicial (ANTES I)
Alt + Pag.Down->Siguientes
Alt + Pag.Up->Anteriores
NO UTILIZADOS
M->Modificar
*/
//String sMapKey = "";
//InputMap inputMap =null;
//NUEVO
sMapKey = "NuevoResponsables";
inputMap = this.jButtonNuevoResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO") , FuncionesSwing.getMaskKey("NUEVO")), sMapKey);
this.jButtonNuevoResponsables.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"NuevoResponsables"));
//DUPLICAR
sMapKey = "DuplicarResponsables";
inputMap = this.jButtonDuplicarResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("DUPLICAR") , FuncionesSwing.getMaskKey("DUPLICAR")), sMapKey);
this.jButtonDuplicarResponsables.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"DuplicarResponsables"));
//COPIAR
sMapKey = "CopiarResponsables";
inputMap = this.jButtonCopiarResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("COPIAR") , FuncionesSwing.getMaskKey("COPIAR")), sMapKey);
this.jButtonCopiarResponsables.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"CopiarResponsables"));
//VEr FORM
sMapKey = "VerFormResponsables";
inputMap = this.jButtonVerFormResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("VER_FORM") , FuncionesSwing.getMaskKey("VER_FORM")), sMapKey);
this.jButtonVerFormResponsables.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"VerFormResponsables"));
//NUEVO RELACIONES
sMapKey = "NuevoRelacionesResponsables";
inputMap = this.jButtonNuevoRelacionesResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO_RELACIONES") , FuncionesSwing.getMaskKey("NUEVO_RELACIONES")), sMapKey);
this.jButtonNuevoRelacionesResponsables.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"NuevoRelacionesResponsables"));
//MODIFICAR
/*
sMapKey = "ModificarResponsables";
inputMap = this.jButtonModificarResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("MODIFICAR") , FuncionesSwing.getMaskKey("MODIFICAR")), sMapKey);
this.jButtonModificarResponsables.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"ModificarResponsables"));
*/
//CERRAR
sMapKey = "CerrarResponsables";
inputMap = this.jButtonCerrarResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CERRAR") , FuncionesSwing.getMaskKey("CERRAR")), sMapKey);
this.jButtonCerrarResponsables.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CerrarResponsables"));
//GUARDAR CAMBIOS
sMapKey = "GuardarCambiosTablaResponsables";
inputMap = this.jButtonGuardarCambiosTablaResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("GUARDAR_CAMBIOS") , FuncionesSwing.getMaskKey("GUARDAR_CAMBIOS")), sMapKey);
this.jButtonGuardarCambiosTablaResponsables.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"GuardarCambiosTablaResponsables"));
//ABRIR ORDER BY
if(!this.conCargarMinimo) {
}
//HOT KEYS
this.jPanelParametrosReportesResponsables = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosReportesAccionesResponsables = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelPaginacionResponsables = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar1Responsables= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar2Responsables= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar3Responsables= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar4Responsables= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
//this.jPanelParametrosAuxiliar5Responsables= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosReportesResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Parametros Reportes-Acciones"));
this.jPanelParametrosReportesResponsables.setName("jPanelParametrosReportesResponsables");
this.jPanelParametrosReportesAccionesResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Parametros Acciones"));
//this.jPanelParametrosReportesAccionesResponsables.setBorder(javax.swing.BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
this.jPanelParametrosReportesAccionesResponsables.setName("jPanelParametrosReportesAccionesResponsables");
FuncionesSwing.setBoldPanel(this.jPanelParametrosReportesResponsables, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelParametrosReportesAccionesResponsables, STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonRecargarInformacionResponsables = new JButtonMe();
this.jButtonRecargarInformacionResponsables.setText("Buscar");
this.jButtonRecargarInformacionResponsables.setToolTipText("Buscar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("RECARGAR"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonRecargarInformacionResponsables,"recargar_button","Buscar");
this.jButtonRecargarInformacionResponsables.setVisible(false);
this.jButtonProcesarInformacionResponsables = new JButtonMe();
this.jButtonProcesarInformacionResponsables.setText("Procesar");
this.jButtonProcesarInformacionResponsables.setToolTipText("Procesar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO);
this.jButtonProcesarInformacionResponsables.setVisible(false);
this.jButtonProcesarInformacionResponsables.setMinimumSize(new Dimension(185,25));
this.jButtonProcesarInformacionResponsables.setMaximumSize(new Dimension(185,25));
this.jButtonProcesarInformacionResponsables.setPreferredSize(new Dimension(185,25));
this.jComboBoxTiposArchivosReportesResponsables = new JComboBoxMe();
//this.jComboBoxTiposArchivosReportesResponsables.setText("TIPO");
this.jComboBoxTiposArchivosReportesResponsables.setToolTipText("Tipos De Archivo");
this.jComboBoxTiposReportesResponsables = new JComboBoxMe();
//this.jComboBoxTiposArchivosReportesResponsables.setText("TIPO");
this.jComboBoxTiposReportesResponsables.setToolTipText("Tipos De Reporte");
this.jComboBoxTiposGraficosReportesResponsables = new JComboBoxMe();
//this.jComboBoxTiposArchivosReportesResponsables.setText("TIPO");
this.jComboBoxTiposGraficosReportesResponsables.setToolTipText("Tipos De Reporte");
this.jComboBoxTiposPaginacionResponsables = new JComboBoxMe();
//this.jComboBoxTiposPaginacionResponsables.setText("Paginacion");
this.jComboBoxTiposPaginacionResponsables.setToolTipText("Tipos De Paginacion");
this.jComboBoxTiposRelacionesResponsables = new JComboBoxMe();
//this.jComboBoxTiposRelacionesResponsables.setText("Accion");
this.jComboBoxTiposRelacionesResponsables.setToolTipText("Tipos de Relaciones");
this.jComboBoxTiposAccionesResponsables = new JComboBoxMe();
//this.jComboBoxTiposAccionesResponsables.setText("Accion");
this.jComboBoxTiposAccionesResponsables.setToolTipText("Tipos de Acciones");
this.jComboBoxTiposSeleccionarResponsables = new JComboBoxMe();
//this.jComboBoxTiposSeleccionarResponsables.setText("Accion");
this.jComboBoxTiposSeleccionarResponsables.setToolTipText("Tipos de Seleccion");
this.jTextFieldValorCampoGeneralResponsables=new JTextFieldMe();
this.jTextFieldValorCampoGeneralResponsables.setMinimumSize(new Dimension(100,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldValorCampoGeneralResponsables.setMaximumSize(new Dimension(100,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldValorCampoGeneralResponsables.setPreferredSize(new Dimension(100,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesResponsables = new JLabelMe();
this.jLabelAccionesResponsables.setText("Acciones");
this.jLabelAccionesResponsables.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesResponsables.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesResponsables.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jCheckBoxSeleccionarTodosResponsables = new JCheckBoxMe();
this.jCheckBoxSeleccionarTodosResponsables.setText("Sel. Todos");
this.jCheckBoxSeleccionarTodosResponsables.setToolTipText("Sel. Todos");
this.jCheckBoxSeleccionadosResponsables = new JCheckBoxMe();
//this.jCheckBoxSeleccionadosResponsables.setText("Seleccionados");
this.jCheckBoxSeleccionadosResponsables.setToolTipText("SELECCIONAR SELECCIONADOS");
this.jCheckBoxConAltoMaximoTablaResponsables = new JCheckBoxMe();
//this.jCheckBoxConAltoMaximoTablaResponsables.setText("Con Maximo Alto Tabla");
this.jCheckBoxConAltoMaximoTablaResponsables.setToolTipText("Con Maximo Alto Tabla");
this.jCheckBoxConGraficoReporteResponsables = new JCheckBoxMe();
this.jCheckBoxConGraficoReporteResponsables.setText("Graf.");
this.jCheckBoxConGraficoReporteResponsables.setToolTipText("Con Grafico");
this.jButtonAnterioresResponsables = new JButtonMe();
//this.jButtonAnterioresResponsables.setText("<<");
this.jButtonAnterioresResponsables.setToolTipText("Anteriores Datos" + FuncionesSwing.getKeyMensaje("ANTERIORES"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonAnterioresResponsables,"anteriores_button","<<");
FuncionesSwing.setBoldButton(this.jButtonAnterioresResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonSiguientesResponsables = new JButtonMe();
//this.jButtonSiguientesResponsables.setText(">>");
this.jButtonSiguientesResponsables.setToolTipText("Siguientes Datos" + FuncionesSwing.getKeyMensaje("SIGUIENTES"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonSiguientesResponsables,"siguientes_button",">>");
FuncionesSwing.setBoldButton(this.jButtonSiguientesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonNuevoGuardarCambiosResponsables = new JButtonMe();
this.jButtonNuevoGuardarCambiosResponsables.setText("Nue");
this.jButtonNuevoGuardarCambiosResponsables.setToolTipText("Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoGuardarCambiosResponsables,"nuevoguardarcambios_button","Nue",this.responsablesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.setBoldButton(this.jButtonNuevoGuardarCambiosResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
//HOT KEYS2
/*
T->Nuevo Tabla
*/
//NUEVO GUARDAR CAMBIOS O NUEVO TABLA
sMapKey = "NuevoGuardarCambiosResponsables";
inputMap = this.jButtonNuevoGuardarCambiosResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO_TABLA") , FuncionesSwing.getMaskKey("NUEVO_TABLA")), sMapKey);
this.jButtonNuevoGuardarCambiosResponsables.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"NuevoGuardarCambiosResponsables"));
//RECARGAR
sMapKey = "RecargarInformacionResponsables";
inputMap = this.jButtonRecargarInformacionResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("RECARGAR") , FuncionesSwing.getMaskKey("RECARGAR")), sMapKey);
this.jButtonRecargarInformacionResponsables.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"RecargarInformacionResponsables"));
//SIGUIENTES
sMapKey = "SiguientesResponsables";
inputMap = this.jButtonSiguientesResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("SIGUIENTES") , FuncionesSwing.getMaskKey("SIGUIENTES")), sMapKey);
this.jButtonSiguientesResponsables.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"SiguientesResponsables"));
//ANTERIORES
sMapKey = "AnterioresResponsables";
inputMap = this.jButtonAnterioresResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ANTERIORES") , FuncionesSwing.getMaskKey("ANTERIORES")), sMapKey);
this.jButtonAnterioresResponsables.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"AnterioresResponsables"));
//HOT KEYS2
//DETALLE
//TOOLBAR
//INDICES BUSQUEDA
//INDICES BUSQUEDA_FIN
//INDICES BUSQUEDA
if(!this.conCargarMinimo) {
this.inicializarElementosBusquedasResponsables();
}
//INDICES BUSQUEDA_FIN
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
//ELEMENTOS TABLAS PARAMETOS_FIN
//ESTA EN BEAN
/*
this.jTabbedPaneRelacionesResponsables.setMinimumSize(new Dimension(this.getWidth(),ResponsablesBean.ALTO_TABPANE_RELACIONES + FuncionesSwing.getValorProporcion(ResponsablesBean.ALTO_TABPANE_RELACIONES,0)));
this.jTabbedPaneRelacionesResponsables.setMaximumSize(new Dimension(this.getWidth(),ResponsablesBean.ALTO_TABPANE_RELACIONES + FuncionesSwing.getValorProporcion(ResponsablesBean.ALTO_TABPANE_RELACIONES,0)));
this.jTabbedPaneRelacionesResponsables.setPreferredSize(new Dimension(this.getWidth(),ResponsablesBean.ALTO_TABPANE_RELACIONES + FuncionesSwing.getValorProporcion(ResponsablesBean.ALTO_TABPANE_RELACIONES,0)));
*/
int iPosXAccionPaginacion=0;
GridBagLayout gridaBagLayoutPaginacionResponsables = new GridBagLayout();
this.jPanelPaginacionResponsables.setLayout(gridaBagLayoutPaginacionResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.EAST;
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = 0;
this.gridBagConstraintsResponsables.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionResponsables.add(this.jButtonAnterioresResponsables, this.gridBagConstraintsResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridx = iPosXAccionPaginacion++;
this.gridBagConstraintsResponsables.gridy = 0;
this.jPanelPaginacionResponsables.add(this.jButtonNuevoGuardarCambiosResponsables, this.gridBagConstraintsResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.gridx = iPosXAccionPaginacion++;
this.gridBagConstraintsResponsables.gridy = 0;
this.jPanelPaginacionResponsables.add(this.jButtonSiguientesResponsables, this.gridBagConstraintsResponsables);
iPosXAccionPaginacion=0;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = 1;
this.gridBagConstraintsResponsables.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionResponsables.add(this.jButtonNuevoResponsables, this.gridBagConstraintsResponsables);
if(!this.responsablesSessionBean.getEsGuardarRelacionado()
&& !this.conCargarMinimo) {
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = 1;
this.gridBagConstraintsResponsables.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionResponsables.add(this.jButtonGuardarCambiosTablaResponsables, this.gridBagConstraintsResponsables);
}
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = 1;
this.gridBagConstraintsResponsables.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionResponsables.add(this.jButtonDuplicarResponsables, this.gridBagConstraintsResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = 1;
this.gridBagConstraintsResponsables.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionResponsables.add(this.jButtonCopiarResponsables, this.gridBagConstraintsResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = 1;
this.gridBagConstraintsResponsables.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionResponsables.add(this.jButtonVerFormResponsables, this.gridBagConstraintsResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = 1;
this.gridBagConstraintsResponsables.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionResponsables.add(this.jButtonCerrarResponsables, this.gridBagConstraintsResponsables);
this.jButtonRecargarInformacionResponsables.setMinimumSize(new Dimension(95,25));
this.jButtonRecargarInformacionResponsables.setMaximumSize(new Dimension(95,25));
this.jButtonRecargarInformacionResponsables.setPreferredSize(new Dimension(95,25));
FuncionesSwing.setBoldButton(this.jButtonRecargarInformacionResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jComboBoxTiposArchivosReportesResponsables.setMinimumSize(new Dimension(105,20));
this.jComboBoxTiposArchivosReportesResponsables.setMaximumSize(new Dimension(105,20));
this.jComboBoxTiposArchivosReportesResponsables.setPreferredSize(new Dimension(105,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposArchivosReportesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposReportesResponsables.setMinimumSize(new Dimension(100,20));
this.jComboBoxTiposReportesResponsables.setMaximumSize(new Dimension(100,20));
this.jComboBoxTiposReportesResponsables.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposReportesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposGraficosReportesResponsables.setMinimumSize(new Dimension(80,20));
this.jComboBoxTiposGraficosReportesResponsables.setMaximumSize(new Dimension(80,20));
this.jComboBoxTiposGraficosReportesResponsables.setPreferredSize(new Dimension(80,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposGraficosReportesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposPaginacionResponsables.setMinimumSize(new Dimension(80,20));
this.jComboBoxTiposPaginacionResponsables.setMaximumSize(new Dimension(80,20));
this.jComboBoxTiposPaginacionResponsables.setPreferredSize(new Dimension(80,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposPaginacionResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposRelacionesResponsables.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposRelacionesResponsables.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposRelacionesResponsables.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposRelacionesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposAccionesResponsables.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesResponsables.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesResponsables.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposSeleccionarResponsables.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposSeleccionarResponsables.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposSeleccionarResponsables.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposSeleccionarResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jCheckBoxConAltoMaximoTablaResponsables.setMinimumSize(new Dimension(20,20));
this.jCheckBoxConAltoMaximoTablaResponsables.setMaximumSize(new Dimension(20,20));
this.jCheckBoxConAltoMaximoTablaResponsables.setPreferredSize(new Dimension(20,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxConAltoMaximoTablaResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jCheckBoxConGraficoReporteResponsables.setMinimumSize(new Dimension(60,20));
this.jCheckBoxConGraficoReporteResponsables.setMaximumSize(new Dimension(60,20));
this.jCheckBoxConGraficoReporteResponsables.setPreferredSize(new Dimension(60,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxConGraficoReporteResponsables, STIPO_TAMANIO_GENERAL,false,true,this);
this.jCheckBoxSeleccionarTodosResponsables.setMinimumSize(new Dimension(100,20));
this.jCheckBoxSeleccionarTodosResponsables.setMaximumSize(new Dimension(100,20));
this.jCheckBoxSeleccionarTodosResponsables.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxSeleccionarTodosResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jCheckBoxSeleccionadosResponsables.setMinimumSize(new Dimension(20,20));
this.jCheckBoxSeleccionadosResponsables.setMaximumSize(new Dimension(20,20));
this.jCheckBoxSeleccionadosResponsables.setPreferredSize(new Dimension(20,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxSeleccionadosResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
GridBagLayout gridaBagParametrosReportesResponsables = new GridBagLayout();
GridBagLayout gridaBagParametrosReportesAccionesResponsables = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar1Responsables = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar2Responsables = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar3Responsables = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar4Responsables = new GridBagLayout();
int iGridxParametrosReportes=0;
int iGridyParametrosReportes=0;
int iGridxParametrosAuxiliar=0;
int iGridyParametrosAuxiliar=0;
this.jPanelParametrosReportesResponsables.setLayout(gridaBagParametrosReportesResponsables);
this.jPanelParametrosReportesAccionesResponsables.setLayout(gridaBagParametrosReportesAccionesResponsables);
this.jPanelParametrosAuxiliar1Responsables.setLayout(gridaBagParametrosAuxiliar1Responsables);
this.jPanelParametrosAuxiliar2Responsables.setLayout(gridaBagParametrosAuxiliar2Responsables);
this.jPanelParametrosAuxiliar3Responsables.setLayout(gridaBagParametrosAuxiliar3Responsables);
this.jPanelParametrosAuxiliar4Responsables.setLayout(gridaBagParametrosAuxiliar4Responsables);
//this.jPanelParametrosAuxiliar5Responsables.setLayout(gridaBagParametrosAuxiliar2Responsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesResponsables.add(this.jButtonRecargarInformacionResponsables, this.gridBagConstraintsResponsables);
//PAGINACION
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar1Responsables.add(this.jComboBoxTiposPaginacionResponsables, this.gridBagConstraintsResponsables);
//CON ALTO MAXIMO TABLA
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar1Responsables.add(this.jCheckBoxConAltoMaximoTablaResponsables, this.gridBagConstraintsResponsables);
//TIPOS ARCHIVOS REPORTES
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar1Responsables.add(this.jComboBoxTiposArchivosReportesResponsables, this.gridBagConstraintsResponsables);
//USANDO AUXILIAR
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesResponsables.add(this.jPanelParametrosAuxiliar1Responsables, this.gridBagConstraintsResponsables);
//USANDO AUXILIAR FIN
//AUXILIAR4 TIPOS REPORTES Y TIPOS GRAFICOS REPORTES
iGridxParametrosAuxiliar=0;
iGridyParametrosAuxiliar=0;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar4Responsables.add(this.jComboBoxTiposReportesResponsables, this.gridBagConstraintsResponsables);
//AUXILIAR4 TIPOS REPORTES Y TIPOS GRAFICOS REPORTES
//USANDO AUXILIAR 4
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesResponsables.add(this.jPanelParametrosAuxiliar4Responsables, this.gridBagConstraintsResponsables);
//USANDO AUXILIAR 4 FIN
//TIPOS REPORTES
/*
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;//iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosReportes++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesResponsables.add(this.jComboBoxTiposReportesResponsables, this.gridBagConstraintsResponsables);
*/
//GENERAR REPORTE (jCheckBoxExportar)
/*
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesResponsables.add(this.jCheckBoxGenerarReporteResponsables, this.gridBagConstraintsResponsables);
*/
iGridxParametrosAuxiliar=0;
iGridyParametrosAuxiliar=0;
//USANDO AUXILIAR
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesResponsables.add(this.jPanelParametrosAuxiliar2Responsables, this.gridBagConstraintsResponsables);
//USANDO AUXILIAR FIN
//PARAMETROS ACCIONES
//iGridxParametrosReportes=1;
iGridxParametrosReportes=0;
iGridyParametrosReportes=1;
/*
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx =iGridxParametrosReportes++;
this.jPanelParametrosReportesResponsables.add(this.jLabelAccionesResponsables, this.gridBagConstraintsResponsables);
*/
//PARAMETROS_ACCIONES-PARAMETROS_REPORTES
//ORDER BY
if(!this.conCargarMinimo) {
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesResponsables.add(this.jButtonAbrirOrderByResponsables, this.gridBagConstraintsResponsables);
}
//PARAMETROS_ACCIONES-PARAMETROS_REPORTES
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesResponsables.add(this.jComboBoxTiposSeleccionarResponsables, this.gridBagConstraintsResponsables);
/*
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx =iGridxParametrosReportes++;
this.jPanelParametrosReportesResponsables.add(this.jCheckBoxSeleccionarTodosResponsables, this.gridBagConstraintsResponsables);
*/
iGridxParametrosAuxiliar=0;
iGridyParametrosAuxiliar=0;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar3Responsables.add(this.jCheckBoxSeleccionarTodosResponsables, this.gridBagConstraintsResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar3Responsables.add(this.jCheckBoxSeleccionadosResponsables, this.gridBagConstraintsResponsables);
//USANDO AUXILIAR3
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesResponsables.add(this.jPanelParametrosAuxiliar3Responsables, this.gridBagConstraintsResponsables);
//USANDO AUXILIAR3 FIN
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy = iGridyParametrosReportes;
this.gridBagConstraintsResponsables.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesResponsables.add(this.jComboBoxTiposAccionesResponsables, this.gridBagConstraintsResponsables);
;
//ELEMENTOS TABLAS PARAMETOS
//SUBPANELES POR CAMPO
if(!this.conCargarMinimo) {
//SUBPANELES EN PANEL CAMPOS
}
//ELEMENTOS TABLAS PARAMETOS_FIN
/*
GridBagLayout gridaBagLayoutDatosResponsables = new GridBagLayout();
this.jScrollPanelDatosResponsables.setLayout(gridaBagLayoutDatosResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = 0;
this.gridBagConstraintsResponsables.gridx = 0;
this.jScrollPanelDatosResponsables.add(this.jTableDatosResponsables, this.gridBagConstraintsResponsables);
*/
this.redimensionarTablaDatos(-1);
this.jScrollPanelDatosResponsables.setViewportView(this.jTableDatosResponsables);
this.jTableDatosResponsables.setFillsViewportHeight(true);
this.jTableDatosResponsables.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
Integer iGridXParametrosAccionesFormulario=0;
Integer iGridYParametrosAccionesFormulario=0;
GridBagLayout gridaBagLayoutAccionesResponsables= new GridBagLayout();
this.jPanelAccionesResponsables.setLayout(gridaBagLayoutAccionesResponsables);
/*
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = 0;
this.gridBagConstraintsResponsables.gridx = 0;
this.jPanelAccionesResponsables.add(this.jButtonNuevoResponsables, this.gridBagConstraintsResponsables);
*/
int iPosXAccion=0;
if(!this.conCargarMinimo) {
//BYDAN_BUSQUEDAS
GridBagLayout gridaBagLayoutBusquedaResponsablesResponsables= new GridBagLayout();
gridaBagLayoutBusquedaResponsablesResponsables.rowHeights = new int[] {1};
gridaBagLayoutBusquedaResponsablesResponsables.columnWidths = new int[] {1};
gridaBagLayoutBusquedaResponsablesResponsables.rowWeights = new double[]{0.0, 0.0, 0.0};
gridaBagLayoutBusquedaResponsablesResponsables.columnWeights = new double[]{0.0, 1.0};
jPanelBusquedaResponsablesResponsables.setLayout(gridaBagLayoutBusquedaResponsablesResponsables);
gridBagConstraintsResponsables = new GridBagConstraints();
gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
gridBagConstraintsResponsables.gridy = 0;
gridBagConstraintsResponsables.gridx = 0;
jPanelBusquedaResponsablesResponsables.add(jLabelidBusquedaResponsablesResponsables, gridBagConstraintsResponsables);
gridBagConstraintsResponsables = new GridBagConstraints();
gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
gridBagConstraintsResponsables.gridy = 0;
gridBagConstraintsResponsables.gridx = 1;
jPanelBusquedaResponsablesResponsables.add(jLabelidResponsablesBusquedaResponsables, gridBagConstraintsResponsables);
gridBagConstraintsResponsables = new GridBagConstraints();
gridBagConstraintsResponsables.anchor = GridBagConstraints.WEST;
gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
gridBagConstraintsResponsables.gridy = 1;
gridBagConstraintsResponsables.gridx =1;
jPanelBusquedaResponsablesResponsables.add(jButtonBusquedaResponsablesResponsables, gridBagConstraintsResponsables);
jTabbedPaneBusquedasResponsables.addTab("1.-Por ", jPanelBusquedaResponsablesResponsables);
jTabbedPaneBusquedasResponsables.setMnemonicAt(0, KeyEvent.VK_1);
}
//this.setJProgressBarToJPanel();
GridBagLayout gridaBagLayoutResponsables = new GridBagLayout();
this.jContentPane.setLayout(gridaBagLayoutResponsables);
if(this.parametroGeneralUsuario.getcon_botones_tool_bar() && !this.responsablesSessionBean.getEsGuardarRelacionado()) {
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy = iGridyPrincipal++;
this.gridBagConstraintsResponsables.gridx = 0;
//this.gridBagConstraintsResponsables.fill =GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.CENTER;//.CENTER;NORTH
this.gridBagConstraintsResponsables.ipadx = 100;
this.jContentPane.add(this.jTtoolBarResponsables, this.gridBagConstraintsResponsables);
}
//PROCESANDO EN OTRA PANTALLA
/*
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy = iGridyPrincipal++;
this.gridBagConstraintsResponsables.gridx = 0;
//this.gridBagConstraintsResponsables.fill =GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.CENTER;
this.gridBagConstraintsResponsables.ipadx = 100;
this.jContentPane.add(this.jPanelProgressProcess, this.gridBagConstraintsResponsables);
*/
int iGridxBusquedasParametros=0;
this.gridBagConstraintsResponsables = new GridBagConstraints();
if(!this.conCargarMinimo) {
this.gridBagConstraintsResponsables.gridy = iGridyPrincipal++;
this.gridBagConstraintsResponsables.gridx = 0;
this.gridBagConstraintsResponsables.fill =GridBagConstraints.VERTICAL;//GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.anchor = GridBagConstraints.NORTHWEST;
this.gridBagConstraintsResponsables.ipadx = 150;
if(!this.conCargarMinimo) {
this.jContentPane.add(this.jTabbedPaneBusquedasResponsables, this.gridBagConstraintsResponsables);
}
}
//PARAMETROS TABLAS PARAMETROS
if(!this.conCargarMinimo) {
}
//PARAMETROS TABLAS PARAMETROS_FIN
//PARAMETROS REPORTES
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy = iGridyPrincipal++;
this.gridBagConstraintsResponsables.gridx = 0;
this.jContentPane.add(this.jPanelParametrosReportesResponsables, this.gridBagConstraintsResponsables);
/*
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy = iGridyPrincipal++;
this.gridBagConstraintsResponsables.gridx = 0;
this.jContentPane.add(this.jPanelParametrosReportesAccionesResponsables, this.gridBagConstraintsResponsables);
*/
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy =iGridyPrincipal++;
this.gridBagConstraintsResponsables.gridx =0;
this.gridBagConstraintsResponsables.fill = GridBagConstraints.BOTH;
//this.gridBagConstraintsResponsables.ipady =150;
this.jContentPane.add(this.jScrollPanelDatosResponsables, this.gridBagConstraintsResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy = iGridyPrincipal++;
this.gridBagConstraintsResponsables.gridx = 0;
this.jContentPane.add(this.jPanelPaginacionResponsables, this.gridBagConstraintsResponsables);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
iWidthScroll=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO_RELSCROLL)+(250*1);
iHeightScroll=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO_RELSCROLL);
if(ResponsablesJInternalFrame.CON_DATOS_FRAME) {
this.jPanelBusquedasParametrosResponsables= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
int iGridyRelaciones=0;
GridBagLayout gridaBagLayoutBusquedasParametrosResponsables = new GridBagLayout();
this.jPanelBusquedasParametrosResponsables.setLayout(gridaBagLayoutBusquedasParametrosResponsables);
if(this.parametroGeneralUsuario.getcon_botones_tool_bar()) {
}
this.jScrollPanelDatosGeneralResponsables= new JScrollPane(jContentPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosGeneralResponsables.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralResponsables.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralResponsables.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.gridBagConstraintsResponsables = new GridBagConstraints();
//if(!this.conCargarMinimo) {
//}
this.conMaximoRelaciones=true;
if(this.parametroGeneralUsuario.getcon_cargar_por_parte()) {
}
Boolean tieneColumnasOcultas=false;
tieneColumnasOcultas=true;
if(!Constantes.ISDEVELOPING) {
} else {
if(tieneColumnasOcultas) {
}
}
} else {
//DISENO_DETALLE COMENTAR Y
//DISENO_DETALLE(Solo Descomentar Seccion Inferior)
//NOTA-DISENO_DETALLE(Si cambia lo de abajo, cambiar lo comentado, Al final no es lo mismo)
}
//DISENO_DETALLE-(Descomentar)
/*
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy = iGridyPrincipal++;
this.gridBagConstraintsResponsables.gridx = 0;
this.jContentPane.add(this.jPanelCamposResponsables, this.gridBagConstraintsResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy = iGridyPrincipal++;
this.gridBagConstraintsResponsables.gridx = 0;
this.jContentPane.add(this.jPanelCamposOcultosResponsables, this.gridBagConstraintsResponsables);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy =iGridyPrincipal++;
this.gridBagConstraintsResponsables.gridx =0;
this.jContentPane.add(this.jPanelAccionesResponsables, this.gridBagConstraintsResponsables);
*/
//pack();
return this.jScrollPanelDatosGeneralResponsables;//jContentPane;
}
/*
public void cargarReporteDinamicoResponsables() throws Exception {
int iWidthReporteDinamico=350;
int iHeightReporteDinamico=450;//250;400;
int iPosXReporteDinamico=0;
int iPosYReporteDinamico=0;
GridBagLayout gridaBagLayoutReporteDinamicoResponsables = new GridBagLayout();
//PANEL
this.jPanelReporteDinamicoResponsables = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelReporteDinamicoResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelReporteDinamicoResponsables.setName("jPanelReporteDinamicoResponsables");
this.jPanelReporteDinamicoResponsables.setMinimumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
this.jPanelReporteDinamicoResponsables.setMaximumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
this.jPanelReporteDinamicoResponsables.setPreferredSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
this.jPanelReporteDinamicoResponsables.setLayout(gridaBagLayoutReporteDinamicoResponsables);
this.jInternalFrameReporteDinamicoResponsables= new ReporteDinamicoJInternalFrame();
this.jScrollPanelReporteDinamicoResponsables = new JScrollPane();
//PANEL_CONTROLES
//this.jScrollColumnasSelectReporteResponsables= new JScrollPane();
//JINTERNAL FRAME
this.jInternalFrameReporteDinamicoResponsables.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameReporteDinamicoResponsables.setjInternalFrameParent(this);
this.jInternalFrameReporteDinamicoResponsables.setTitle("REPORTE DINAMICO");
this.jInternalFrameReporteDinamicoResponsables.setSize(iWidthReporteDinamico+70,iHeightReporteDinamico+100);
this.jInternalFrameReporteDinamicoResponsables.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameReporteDinamicoResponsables.setResizable(true);
this.jInternalFrameReporteDinamicoResponsables.setClosable(true);
this.jInternalFrameReporteDinamicoResponsables.setMaximizable(true);
//SCROLL PANEL
//this.jScrollPanelReporteDinamicoResponsables.setMinimumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
//this.jScrollPanelReporteDinamicoResponsables.setMaximumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
//this.jScrollPanelReporteDinamicoResponsables.setPreferredSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
//this.jScrollPanelReporteDinamicoResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Responsableses"));
//CONTROLES-ELEMENTOS
//LABEL SELECT COLUMNAS
this.jLabelColumnasSelectReporteResponsables = new JLabelMe();
this.jLabelColumnasSelectReporteResponsables.setText("Columnas Seleccion");
this.jLabelColumnasSelectReporteResponsables.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnasSelectReporteResponsables.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnasSelectReporteResponsables.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico=0;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsResponsables.gridy = iPosYReporteDinamico;
this.gridBagConstraintsResponsables.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoResponsables.add(this.jLabelColumnasSelectReporteResponsables, this.gridBagConstraintsResponsables);
//LISTA SELECT COLUMNAS
this.jListColumnasSelectReporteResponsables = new JList<Reporte>();
this.jListColumnasSelectReporteResponsables.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
this.jListColumnasSelectReporteResponsables.setToolTipText("Tipos de Seleccion");
this.jListColumnasSelectReporteResponsables.setMinimumSize(new Dimension(145,300));
this.jListColumnasSelectReporteResponsables.setMaximumSize(new Dimension(145,300));
this.jListColumnasSelectReporteResponsables.setPreferredSize(new Dimension(145,300));
//SCROLL_PANEL_CONTROL
this.jScrollColumnasSelectReporteResponsables=new JScrollPane(this.jListColumnasSelectReporteResponsables);
this.jScrollColumnasSelectReporteResponsables.setMinimumSize(new Dimension(180,150));
this.jScrollColumnasSelectReporteResponsables.setMaximumSize(new Dimension(180,150));
this.jScrollColumnasSelectReporteResponsables.setPreferredSize(new Dimension(180,150));
this.jScrollColumnasSelectReporteResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("COLUMNAS"));
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsResponsables.gridy = iPosYReporteDinamico;
this.gridBagConstraintsResponsables.gridx = iPosXReporteDinamico++;
//this.jPanelReporteDinamicoResponsables.add(this.jListColumnasSelectReporteResponsables, this.gridBagConstraintsResponsables);
this.jPanelReporteDinamicoResponsables.add(this.jScrollColumnasSelectReporteResponsables, this.gridBagConstraintsResponsables);
//LABEL SELECT RELACIONES
this.jLabelRelacionesSelectReporteResponsables = new JLabelMe();
this.jLabelRelacionesSelectReporteResponsables.setText("Relaciones Seleccion");
this.jLabelRelacionesSelectReporteResponsables.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelRelacionesSelectReporteResponsables.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelRelacionesSelectReporteResponsables.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
//LABEL SELECT RELACIONES_FIN
//LISTA SELECT RELACIONES
this.jListRelacionesSelectReporteResponsables = new JList<Reporte>();
this.jListRelacionesSelectReporteResponsables.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
this.jListRelacionesSelectReporteResponsables.setToolTipText("Tipos de Seleccion");
this.jListRelacionesSelectReporteResponsables.setMinimumSize(new Dimension(145,300));
this.jListRelacionesSelectReporteResponsables.setMaximumSize(new Dimension(145,300));
this.jListRelacionesSelectReporteResponsables.setPreferredSize(new Dimension(145,300));
//SCROLL_PANEL_CONTROL
this.jScrollRelacionesSelectReporteResponsables=new JScrollPane(this.jListRelacionesSelectReporteResponsables);
this.jScrollRelacionesSelectReporteResponsables.setMinimumSize(new Dimension(180,120));
this.jScrollRelacionesSelectReporteResponsables.setMaximumSize(new Dimension(180,120));
this.jScrollRelacionesSelectReporteResponsables.setPreferredSize(new Dimension(180,120));
this.jScrollRelacionesSelectReporteResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("RELACIONES"));
this.jCheckBoxConGraficoDinamicoResponsables = new JCheckBoxMe();
this.jComboBoxColumnaCategoriaGraficoResponsables = new JComboBoxMe();
this.jListColumnasValoresGraficoResponsables = new JList<Reporte>();
//COMBO TIPOS REPORTES
this.jComboBoxTiposReportesDinamicoResponsables = new JComboBoxMe();
this.jComboBoxTiposReportesDinamicoResponsables.setToolTipText("Tipos De Reporte");
this.jComboBoxTiposReportesDinamicoResponsables.setMinimumSize(new Dimension(100,20));
this.jComboBoxTiposReportesDinamicoResponsables.setMaximumSize(new Dimension(100,20));
this.jComboBoxTiposReportesDinamicoResponsables.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposReportesDinamicoResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
//COMBO TIPOS REPORTES
//COMBO TIPOS ARCHIVOS
this.jComboBoxTiposArchivosReportesDinamicoResponsables = new JComboBoxMe();
this.jComboBoxTiposArchivosReportesDinamicoResponsables.setToolTipText("Tipos Archivos");
this.jComboBoxTiposArchivosReportesDinamicoResponsables.setMinimumSize(new Dimension(100,20));
this.jComboBoxTiposArchivosReportesDinamicoResponsables.setMaximumSize(new Dimension(100,20));
this.jComboBoxTiposArchivosReportesDinamicoResponsables.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposArchivosReportesDinamicoResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
//COMBO TIPOS ARCHIVOS
//LABEL GENERAR EXCEL
this.jLabelGenerarExcelReporteDinamicoResponsables = new JLabelMe();
this.jLabelGenerarExcelReporteDinamicoResponsables.setText("Tipos de Reporte");
this.jLabelGenerarExcelReporteDinamicoResponsables.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelGenerarExcelReporteDinamicoResponsables.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelGenerarExcelReporteDinamicoResponsables.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsResponsables.gridy = iPosYReporteDinamico;
this.gridBagConstraintsResponsables.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoResponsables.add(this.jLabelGenerarExcelReporteDinamicoResponsables, this.gridBagConstraintsResponsables);
//BOTON GENERAR EXCEL
this.jButtonGenerarExcelReporteDinamicoResponsables = new JButtonMe();
this.jButtonGenerarExcelReporteDinamicoResponsables.setText("Generar Excel");
FuncionesSwing.addImagenButtonGeneral(this.jButtonGenerarExcelReporteDinamicoResponsables,"generar_excel_reporte_dinamico_button","Generar EXCEL");
this.jButtonGenerarExcelReporteDinamicoResponsables.setToolTipText("Generar EXCEL"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO);
//this.gridBagConstraintsResponsables = new GridBagConstraints();
//this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
//this.gridBagConstraintsResponsables.gridy = iPosYReporteDinamico;
//this.gridBagConstraintsResponsables.gridx = iPosXReporteDinamico++;
//this.jPanelReporteDinamicoResponsables.add(this.jButtonGenerarExcelReporteDinamicoResponsables, this.gridBagConstraintsResponsables);
//COMBO TIPOS REPORTES
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iPosYReporteDinamico;
this.gridBagConstraintsResponsables.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoResponsables.add(this.jComboBoxTiposReportesDinamicoResponsables, this.gridBagConstraintsResponsables);
//LABEL TIPOS DE ARCHIVO
this.jLabelTiposArchivoReporteDinamicoResponsables = new JLabelMe();
this.jLabelTiposArchivoReporteDinamicoResponsables.setText("Tipos de Archivo");
this.jLabelTiposArchivoReporteDinamicoResponsables.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelTiposArchivoReporteDinamicoResponsables.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelTiposArchivoReporteDinamicoResponsables.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsResponsables.gridy = iPosYReporteDinamico;
this.gridBagConstraintsResponsables.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoResponsables.add(this.jLabelTiposArchivoReporteDinamicoResponsables, this.gridBagConstraintsResponsables);
//COMBO TIPOS ARCHIVOS
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iPosYReporteDinamico;
this.gridBagConstraintsResponsables.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoResponsables.add(this.jComboBoxTiposArchivosReportesDinamicoResponsables, this.gridBagConstraintsResponsables);
//BOTON GENERAR
this.jButtonGenerarReporteDinamicoResponsables = new JButtonMe();
this.jButtonGenerarReporteDinamicoResponsables.setText("Generar");
FuncionesSwing.addImagenButtonGeneral(this.jButtonGenerarReporteDinamicoResponsables,"generar_reporte_dinamico_button","Generar");
this.jButtonGenerarReporteDinamicoResponsables.setToolTipText("Generar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO);
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iPosYReporteDinamico;
this.gridBagConstraintsResponsables.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoResponsables.add(this.jButtonGenerarReporteDinamicoResponsables, this.gridBagConstraintsResponsables);
//BOTON CERRAR
this.jButtonCerrarReporteDinamicoResponsables = new JButtonMe();
this.jButtonCerrarReporteDinamicoResponsables.setText("Cancelar");
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarReporteDinamicoResponsables,"cerrar_reporte_dinamico_button","Cancelar");
this.jButtonCerrarReporteDinamicoResponsables.setToolTipText("Cancelar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iPosYReporteDinamico;
this.gridBagConstraintsResponsables.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoResponsables.add(this.jButtonCerrarReporteDinamicoResponsables, this.gridBagConstraintsResponsables);
//GLOBAL AGREGAR PANELES
GridBagLayout gridaBagLayoutReporteDinamicoPrincipalResponsables = new GridBagLayout();
this.jScrollPanelReporteDinamicoResponsables= new JScrollPane(jPanelReporteDinamicoResponsables,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelReporteDinamicoResponsables.setMinimumSize(new Dimension(iWidthReporteDinamico+90,iHeightReporteDinamico+90));
this.jScrollPanelReporteDinamicoResponsables.setMaximumSize(new Dimension(iWidthReporteDinamico+90,iHeightReporteDinamico+90));
this.jScrollPanelReporteDinamicoResponsables.setPreferredSize(new Dimension(iWidthReporteDinamico+90,iHeightReporteDinamico+90));
this.jScrollPanelReporteDinamicoResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Responsableses"));
iPosXReporteDinamico=0;
iPosYReporteDinamico=0;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy =iPosYReporteDinamico;
this.gridBagConstraintsResponsables.gridx =iPosXReporteDinamico;
this.gridBagConstraintsResponsables.fill = GridBagConstraints.BOTH;
this.jInternalFrameReporteDinamicoResponsables.setContentPane(new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true));
this.jInternalFrameReporteDinamicoResponsables.getContentPane().setLayout(gridaBagLayoutReporteDinamicoPrincipalResponsables);
this.jInternalFrameReporteDinamicoResponsables.getContentPane().add(this.jScrollPanelReporteDinamicoResponsables, this.gridBagConstraintsResponsables);
}
*/
/*
public void cargarImportacionResponsables() throws Exception {
int iWidthImportacion=350;
int iHeightImportacion=250;//400;
int iPosXImportacion=0;
int iPosYImportacion=0;
GridBagLayout gridaBagLayoutImportacionResponsables = new GridBagLayout();
//PANEL
this.jPanelImportacionResponsables = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelImportacionResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelImportacionResponsables.setName("jPanelImportacionResponsables");
this.jPanelImportacionResponsables.setMinimumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jPanelImportacionResponsables.setMaximumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jPanelImportacionResponsables.setPreferredSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jPanelImportacionResponsables.setLayout(gridaBagLayoutImportacionResponsables);
this.jInternalFrameImportacionResponsables= new ImportacionJInternalFrame();
//this.jInternalFrameImportacionResponsables= new ImportacionJInternalFrame();
this.jScrollPanelImportacionResponsables = new JScrollPane();
//PANEL_CONTROLES
//this.jScrollColumnasSelectReporteResponsables= new JScrollPane();
//JINTERNAL FRAME
this.jInternalFrameImportacionResponsables.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameImportacionResponsables.setjInternalFrameParent(this);
this.jInternalFrameImportacionResponsables.setTitle("REPORTE DINAMICO");
this.jInternalFrameImportacionResponsables.setSize(iWidthImportacion+70,iHeightImportacion+100);
this.jInternalFrameImportacionResponsables.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameImportacionResponsables.setResizable(true);
this.jInternalFrameImportacionResponsables.setClosable(true);
this.jInternalFrameImportacionResponsables.setMaximizable(true);
//JINTERNAL FRAME IMPORTACION
this.jInternalFrameImportacionResponsables.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameImportacionResponsables.setjInternalFrameParent(this);
this.jInternalFrameImportacionResponsables.setTitle("IMPORTACION");
this.jInternalFrameImportacionResponsables.setSize(iWidthImportacion+70,iHeightImportacion+100);
this.jInternalFrameImportacionResponsables.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameImportacionResponsables.setResizable(true);
this.jInternalFrameImportacionResponsables.setClosable(true);
this.jInternalFrameImportacionResponsables.setMaximizable(true);
//SCROLL PANEL
this.jScrollPanelImportacionResponsables.setMinimumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jScrollPanelImportacionResponsables.setMaximumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jScrollPanelImportacionResponsables.setPreferredSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jScrollPanelImportacionResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Responsableses"));
//LABEL ARCHIVO IMPORTACION
this.jLabelArchivoImportacionResponsables = new JLabelMe();
this.jLabelArchivoImportacionResponsables.setText("ARCHIVO IMPORTACION");
this.jLabelArchivoImportacionResponsables.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelArchivoImportacionResponsables.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelArchivoImportacionResponsables.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXImportacion=0;
iPosYImportacion++;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsResponsables.gridy = iPosYImportacion;
this.gridBagConstraintsResponsables.gridx = iPosXImportacion++;
this.jPanelImportacionResponsables.add(this.jLabelArchivoImportacionResponsables, this.gridBagConstraintsResponsables);
//BOTON ABRIR IMPORTACION
this.jFileChooserImportacionResponsables = new JFileChooser();
this.jFileChooserImportacionResponsables.setToolTipText("ESCOGER ARCHIVO"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO);
this.jButtonAbrirImportacionResponsables = new JButtonMe();
this.jButtonAbrirImportacionResponsables.setText("ESCOGER");
FuncionesSwing.addImagenButtonGeneral(this.jButtonAbrirImportacionResponsables,"generar_importacion_button","ESCOGER");
this.jButtonAbrirImportacionResponsables.setToolTipText("Generar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iPosYImportacion;
this.gridBagConstraintsResponsables.gridx = iPosXImportacion++;
this.jPanelImportacionResponsables.add(this.jButtonAbrirImportacionResponsables, this.gridBagConstraintsResponsables);
//LABEL PATH IMPORTACION
this.jLabelPathArchivoImportacionResponsables = new JLabelMe();
this.jLabelPathArchivoImportacionResponsables.setText("PATH ARCHIVO");
this.jLabelPathArchivoImportacionResponsables.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelPathArchivoImportacionResponsables.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelPathArchivoImportacionResponsables.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXImportacion=0;
iPosYImportacion++;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsResponsables.gridy = iPosYImportacion;
this.gridBagConstraintsResponsables.gridx = iPosXImportacion++;
this.jPanelImportacionResponsables.add(this.jLabelPathArchivoImportacionResponsables, this.gridBagConstraintsResponsables);
//PATH IMPORTACION
this.jTextFieldPathArchivoImportacionResponsables=new JTextFieldMe();
this.jTextFieldPathArchivoImportacionResponsables.setMinimumSize(new Dimension(150,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldPathArchivoImportacionResponsables.setMaximumSize(new Dimension(150,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldPathArchivoImportacionResponsables.setPreferredSize(new Dimension(150,Constantes.ISWING_ALTO_CONTROL));
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iPosYImportacion;
this.gridBagConstraintsResponsables.gridx = iPosXImportacion++;
this.jPanelImportacionResponsables.add(this.jTextFieldPathArchivoImportacionResponsables, this.gridBagConstraintsResponsables);
//BOTON IMPORTACION
this.jButtonGenerarImportacionResponsables = new JButtonMe();
this.jButtonGenerarImportacionResponsables.setText("IMPORTAR");
FuncionesSwing.addImagenButtonGeneral(this.jButtonGenerarImportacionResponsables,"generar_importacion_button","IMPORTAR");
this.jButtonGenerarImportacionResponsables.setToolTipText("Generar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO);
iPosXImportacion=0;
iPosYImportacion++;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iPosYImportacion;
this.gridBagConstraintsResponsables.gridx = iPosXImportacion++;
this.jPanelImportacionResponsables.add(this.jButtonGenerarImportacionResponsables, this.gridBagConstraintsResponsables);
//BOTON CERRAR
this.jButtonCerrarImportacionResponsables = new JButtonMe();
this.jButtonCerrarImportacionResponsables.setText("Cancelar");
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarImportacionResponsables,"cerrar_reporte_dinamico_button","Cancelar");
this.jButtonCerrarImportacionResponsables.setToolTipText("Cancelar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO);
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iPosYImportacion;
this.gridBagConstraintsResponsables.gridx = iPosXImportacion++;
this.jPanelImportacionResponsables.add(this.jButtonCerrarImportacionResponsables, this.gridBagConstraintsResponsables);
//GLOBAL AGREGAR PANELES
GridBagLayout gridaBagLayoutImportacionPrincipalResponsables = new GridBagLayout();
this.jScrollPanelImportacionResponsables= new JScrollPane(jPanelImportacionResponsables,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
iPosXImportacion=0;
iPosYImportacion=0;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy =iPosYImportacion;
this.gridBagConstraintsResponsables.gridx =iPosXImportacion;
this.gridBagConstraintsResponsables.fill = GridBagConstraints.BOTH;
this.jInternalFrameImportacionResponsables.setContentPane(new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true));
this.jInternalFrameImportacionResponsables.getContentPane().setLayout(gridaBagLayoutImportacionPrincipalResponsables);
this.jInternalFrameImportacionResponsables.getContentPane().add(this.jScrollPanelImportacionResponsables, this.gridBagConstraintsResponsables);
}
*/
/*
public void cargarOrderByResponsables(Boolean cargaMinima) throws Exception {
String sMapKey = "";
InputMap inputMap =null;
int iWidthOrderBy=350;
int iHeightOrderBy=300;//400;
int iPosXOrderBy=0;
int iPosYOrderBy=0;
if(!cargaMinima) {
this.jButtonAbrirOrderByResponsables = new JButtonMe();
this.jButtonAbrirOrderByResponsables.setText("Orden");
this.jButtonAbrirOrderByResponsables.setToolTipText("Orden"+FuncionesSwing.getKeyMensaje("ORDEN"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonAbrirOrderByResponsables,"orden_button","Orden");
FuncionesSwing.setBoldButton(this.jButtonAbrirOrderByResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
sMapKey = "AbrirOrderByResponsables";
inputMap = this.jButtonAbrirOrderByResponsables.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ORDEN") , FuncionesSwing.getMaskKey("ORDEN")), sMapKey);
this.jButtonAbrirOrderByResponsables.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"AbrirOrderByResponsables"));
GridBagLayout gridaBagLayoutOrderByResponsables = new GridBagLayout();
//PANEL
this.jPanelOrderByResponsables = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelOrderByResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelOrderByResponsables.setName("jPanelOrderByResponsables");
this.jPanelOrderByResponsables.setMinimumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jPanelOrderByResponsables.setMaximumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jPanelOrderByResponsables.setPreferredSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
FuncionesSwing.setBoldPanel(this.jPanelOrderByResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jPanelOrderByResponsables.setLayout(gridaBagLayoutOrderByResponsables);
this.jTableDatosResponsablesOrderBy = new JTableMe();
this.jTableDatosResponsablesOrderBy.setAutoCreateRowSorter(true);
FuncionesSwing.setBoldTable(jTableDatosResponsablesOrderBy,STIPO_TAMANIO_GENERAL,false,true,this);
this.jScrollPanelDatosResponsablesOrderBy = new JScrollPane();
this.jScrollPanelDatosResponsablesOrderBy.setBorder(javax.swing.BorderFactory.createTitledBorder("Orden"));
this.jScrollPanelDatosResponsablesOrderBy.setViewportView(this.jTableDatosResponsablesOrderBy);
this.jTableDatosResponsablesOrderBy.setFillsViewportHeight(true);
this.jTableDatosResponsablesOrderBy.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
this.jInternalFrameOrderByResponsables= new OrderByJInternalFrame();
this.jInternalFrameOrderByResponsables= new OrderByJInternalFrame();
this.jScrollPanelOrderByResponsables = new JScrollPane();
//PANEL_CONTROLES
//this.jScrollColumnasSelectReporteResponsables= new JScrollPane();
//JINTERNAL FRAME OrderBy
this.jInternalFrameOrderByResponsables.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameOrderByResponsables.setjInternalFrameParent(this);
this.jInternalFrameOrderByResponsables.setTitle("Orden");
this.jInternalFrameOrderByResponsables.setSize(iWidthOrderBy+70,iHeightOrderBy+100);
this.jInternalFrameOrderByResponsables.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameOrderByResponsables.setResizable(true);
this.jInternalFrameOrderByResponsables.setClosable(true);
this.jInternalFrameOrderByResponsables.setMaximizable(true);
//FuncionesSwing.setBoldPanel(this.jInternalFrameOrderByResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
//SCROLL PANEL
this.jScrollPanelOrderByResponsables.setMinimumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jScrollPanelOrderByResponsables.setMaximumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jScrollPanelOrderByResponsables.setPreferredSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelOrderByResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jScrollPanelOrderByResponsables.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Responsableses"));
//DATOS TOTALES
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy =iPosYOrderBy++;
this.gridBagConstraintsResponsables.gridx =iPosXOrderBy;
this.gridBagConstraintsResponsables.fill = GridBagConstraints.BOTH;
//this.gridBagConstraintsResponsables.ipady =150;
this.jPanelOrderByResponsables.add(jScrollPanelDatosResponsablesOrderBy, this.gridBagConstraintsResponsables);//this.jTableDatosResponsablesTotales
//BOTON CERRAR
this.jButtonCerrarOrderByResponsables = new JButtonMe();
this.jButtonCerrarOrderByResponsables.setText("Salir");
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarOrderByResponsables,"cerrar","Salir");//cerrar_reporte_dinamico_button
this.jButtonCerrarOrderByResponsables.setToolTipText("Cancelar"+" "+ResponsablesConstantesFunciones.SCLASSWEBTITULO);
FuncionesSwing.setBoldButton(this.jButtonCerrarOrderByResponsables, STIPO_TAMANIO_GENERAL,false,true,this);;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsResponsables.gridy = iPosYOrderBy++;
this.gridBagConstraintsResponsables.gridx = iPosXOrderBy;
this.jPanelOrderByResponsables.add(this.jButtonCerrarOrderByResponsables, this.gridBagConstraintsResponsables);
//GLOBAL AGREGAR PANELES
GridBagLayout gridaBagLayoutOrderByPrincipalResponsables = new GridBagLayout();
this.jScrollPanelOrderByResponsables= new JScrollPane(jPanelOrderByResponsables,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
iPosXOrderBy=0;
iPosYOrderBy=0;
this.gridBagConstraintsResponsables = new GridBagConstraints();
this.gridBagConstraintsResponsables.gridy =iPosYOrderBy;
this.gridBagConstraintsResponsables.gridx =iPosXOrderBy;
this.gridBagConstraintsResponsables.fill = GridBagConstraints.BOTH;
this.jInternalFrameOrderByResponsables.setContentPane(new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true));
this.jInternalFrameOrderByResponsables.getContentPane().setLayout(gridaBagLayoutOrderByPrincipalResponsables);
this.jInternalFrameOrderByResponsables.getContentPane().add(this.jScrollPanelOrderByResponsables, this.gridBagConstraintsResponsables);
} else {
this.jButtonAbrirOrderByResponsables = new JButtonMe();
}
}
*/
public void redimensionarTablaDatos(int iNumFilas) {
this.redimensionarTablaDatos(iNumFilas,0);
}
public void redimensionarTablaDatos(int iNumFilas,int iTamanioFilaTabla) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int iWidthTable=screenSize.width*2;//screenSize.width - (screenSize.width/8);
int iWidthTableScroll=screenSize.width - (screenSize.width/8);
int iWidthTableCalculado=0;//3030
int iHeightTable=0;//screenSize.height/3;
int iHeightTableTotal=0;
//ANCHO COLUMNAS SIMPLES
iWidthTableCalculado+=1530;
//ANCHO COLUMNAS OCULTAS
if(Constantes.ISDEVELOPING) {
iWidthTableCalculado+=1500;
}
//ANCHO COLUMNAS RELACIONES
iWidthTableCalculado+=0;
//ESPACION PARA SELECT RELACIONES
//if(this.conMaximoRelaciones
// && this.responsablesSessionBean.getConGuardarRelaciones()
// ) {
//}
//SI CALCULADO ES MENOR QUE MAXIMO
/*
if(iWidthTableCalculado<=iWidthTable) {
iWidthTable=iWidthTableCalculado;
}
*/
//SI TABLA ES MENOR QUE SCROLL
if(iWidthTableCalculado<=iWidthTableScroll) {
iWidthTableScroll=iWidthTableCalculado;
}
//NO VALE SIEMPRE PONE TAMANIO COLUMNA 200
/*
int iTotalWidth=0;
int iWidthColumn=0;
int iCountColumns=this.jTableDatosResponsables.getColumnModel().getColumnCount();
if(iCountColumns>0) {
for(int i = 0; i < this.jTableDatosResponsables.getColumnModel().getColumnCount(); i++) {
TableColumn column = this.jTableDatosResponsables.getColumnModel().getColumn(i);
iWidthColumn=column.getWidth();
iTotalWidth+=iWidthColumn;
}
//iWidthTableCalculado=iTotalWidth;
}
*/
if(iTamanioFilaTabla<=0) {
//iTamanioFilaTabla=this.jTableDatosResponsables.getRowHeight();//ResponsablesConstantesFunciones.ITAMANIOFILATABLA;
}
if(iNumFilas>0) {
iHeightTable=(iNumFilas * iTamanioFilaTabla);
} else {
iHeightTable=iTamanioFilaTabla;
}
iHeightTableTotal=iHeightTable;
if(!this.responsablesSessionBean.getEsGuardarRelacionado()) {
if(iHeightTable > ResponsablesConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOS) { //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS) {
//SI SE SELECCIONA MAXIMO TABLA SE AMPLIA A ALTO MAXIMO DE SCROLL, PARA QUE SCROLL NO SEA TAN PEQUE?O
if(!this.jCheckBoxConAltoMaximoTablaResponsables.isSelected()) {
iHeightTable=ResponsablesConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOS; //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS;
} else {
iHeightTable=iHeightTableTotal + FuncionesSwing.getValorProporcion(iHeightTableTotal,30);
}
} else {
if(iHeightTable < ResponsablesConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOS) {//Constantes.ISWING_TAMANIOMINIMO_TABLADATOS) {
iHeightTable=ResponsablesConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOS; //Constantes.ISWING_TAMANIOMINIMO_TABLADATOS;
}
}
} else {
if(iHeightTable > ResponsablesConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOSREL) { //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS) {
//SI SE SELECCIONA MAXIMO TABLA SE AMPLIA A ALTO MAXIMO DE SCROLL, PARA QUE SCROLL NO SEA TAN PEQUE?O
if(!this.jCheckBoxConAltoMaximoTablaResponsables.isSelected()) {
iHeightTable=ResponsablesConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOSREL; //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS;
} else {
iHeightTable=iHeightTableTotal + FuncionesSwing.getValorProporcion(iHeightTableTotal,30);
}
} else {
if(iHeightTable < ResponsablesConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOSREL) {//Constantes.ISWING_TAMANIOMINIMO_TABLADATOS) {
iHeightTable=ResponsablesConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOSREL; //Constantes.ISWING_TAMANIOMINIMO_TABLADATOS;
}
}
}
//OJO:SE DESHABILITA CALCULADO
//NO SE UTILIZA CALCULADO SI POR DEFINICION
if(iWidthTableDefinicion>0) {
iWidthTableCalculado=iWidthTableDefinicion;
}
this.jTableDatosResponsables.setMinimumSize(new Dimension(iWidthTableCalculado,iHeightTableTotal));
this.jTableDatosResponsables.setMaximumSize(new Dimension(iWidthTableCalculado,iHeightTableTotal));
this.jTableDatosResponsables.setPreferredSize(new Dimension(iWidthTableCalculado,iHeightTableTotal));//iWidthTable
this.jScrollPanelDatosResponsables.setMinimumSize(new Dimension(iWidthTableScroll,iHeightTable));
this.jScrollPanelDatosResponsables.setMaximumSize(new Dimension(iWidthTableScroll,iHeightTable));
this.jScrollPanelDatosResponsables.setPreferredSize(new Dimension(iWidthTableScroll,iHeightTable));
//ORDER BY
//OrderBy
int iHeightTableOrderBy=0;
int iNumFilasOrderBy=this.arrOrderBy.size();
int iTamanioFilaTablaOrderBy=0;
if(this.jInternalFrameOrderByResponsables!=null && this.jInternalFrameOrderByResponsables.getjTableDatosOrderBy()!=null) {
//if(!this.responsablesSessionBean.getEsGuardarRelacionado()) {
iTamanioFilaTablaOrderBy=this.jInternalFrameOrderByResponsables.getjTableDatosOrderBy().getRowHeight();
if(iNumFilasOrderBy>0) {
iHeightTableOrderBy=iNumFilasOrderBy * iTamanioFilaTablaOrderBy;
} else {
iHeightTableOrderBy=iTamanioFilaTablaOrderBy;
}
this.jInternalFrameOrderByResponsables.getjTableDatosOrderBy().setMinimumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY,iHeightTableOrderBy));//iWidthTableCalculado/4
this.jInternalFrameOrderByResponsables.getjTableDatosOrderBy().setMaximumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY,iHeightTableOrderBy));
this.jInternalFrameOrderByResponsables.getjTableDatosOrderBy().setPreferredSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY,iHeightTableOrderBy));//iWidthTable
this.jInternalFrameOrderByResponsables.getjScrollPanelDatosOrderBy().setMinimumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY+30,Constantes2.ISWING_TAMANIO_ALTO_TABLADATOS_ORDERBY));//iHeightTableOrderBy,iWidthTableScroll
this.jInternalFrameOrderByResponsables.getjScrollPanelDatosOrderBy().setMaximumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY+30,Constantes2.ISWING_TAMANIO_ALTO_TABLADATOS_ORDERBY));
this.jInternalFrameOrderByResponsables.getjScrollPanelDatosOrderBy().setPreferredSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY+30,Constantes2.ISWING_TAMANIO_ALTO_TABLADATOS_ORDERBY));
}
//ORDER BY
//this.jScrollPanelDatosResponsables.setMinimumSize(new Dimension(iWidthTableScroll,iHeightTable));
//this.jScrollPanelDatosResponsables.setMaximumSize(new Dimension(iWidthTableScroll,iHeightTable));
//this.jScrollPanelDatosResponsables.setPreferredSize(new Dimension(iWidthTableScroll,iHeightTable));
//VERSION 0
/*
//SI CALCULADO ES MENOR QUE MAXIMO
if(iWidthTableCalculado<=iWidthTable) {
iWidthTable=iWidthTableCalculado;
}
//SI TABLA ES MENOR QUE SCROLL
if(iWidthTable<=iWidthTableScroll) {
iWidthTableScroll=iWidthTable;
}
*/
}
public void redimensionarTablaDatosConTamanio(int iTamanioFilaTabla) throws Exception {
int iSizeTabla=0;
//ARCHITECTURE
if(Constantes.ISUSAEJBLOGICLAYER) {
//iSizeTabla=responsablesLogic.getResponsabless().size();
} else if(Constantes.ISUSAEJBREMOTE || Constantes.ISUSAEJBHOME) {
iSizeTabla=responsabless.size();
}
//ARCHITECTURE
this.redimensionarTablaDatos(iSizeTabla,iTamanioFilaTabla);
}
//PARA REPORTES
public static List<Responsables> TraerResponsablesBeans(List<Responsables> responsabless,ArrayList<Classe> classes)throws Exception {
try {
for(Responsables responsables:responsabless) {
if(!(ResponsablesConstantesFunciones.S_TIPOREPORTE_EXTRA.equals(Constantes2.S_REPORTE_EXTRA_GROUP_GENERICO)
|| ResponsablesConstantesFunciones.S_TIPOREPORTE_EXTRA.equals(Constantes2.S_REPORTE_EXTRA_GROUP_TOTALES_GENERICO))
) {
responsables.setsDetalleGeneralEntityReporte(ResponsablesConstantesFunciones.getResponsablesDescripcion(responsables));
} else {
//responsables.setsDetalleGeneralEntityReporte(responsables.getsDetalleGeneralEntityReporte());
}
//responsablesbeans.add(responsablesbean);
}
} catch(Exception ex) {
throw ex;
}
return responsabless;
}
//PARA REPORTES FIN
}
|
risktx/risktx
|
src/main/scala/org/risktx/domain/model/messaging/TradingProfile.scala
|
<filename>src/main/scala/org/risktx/domain/model/messaging/TradingProfile.scala<gh_stars>1-10
package org.risktx.domain.model.messaging
abstract case class TradingProfile protected(
val sender: TradingParty,
val receiver: TradingParty,
val outboundSoapAction: String,
val outboundTimeoutMillis: Int
)
object TradingProfile {
def apply() = {
new TradingProfile(
TradingParty("urn:something:sender", "A Sender", "Service Provider", "http://localhost:8080/services/ams"),
TradingParty("urn:something:receiver", "A Receiver", "Service Provider", "http://localhost:8080/services/ams"),
"http://www.ACORD.org/Standards/AcordMsgSvc/Ping#PingRq",
10000) {}
}
}
|
SocraticGrid/UCS-Implementation
|
ucs-nifi-extensions/nifi-ucs-nifi-extensions-processors/src/main/java/org/socraticgrid/hl7/ucs/nifi/controller/UCSControllerServiceProxy.java
|
<reponame>SocraticGrid/UCS-Implementation
/*
* Copyright 2015 Cognitive Medical Systems, Inc (http://www.cognitivemedicine.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 org.socraticgrid.hl7.ucs.nifi.controller;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.apache.nifi.annotation.lifecycle.OnEnabled;
import org.apache.nifi.annotation.lifecycle.OnShutdown;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.controller.AbstractControllerService;
import org.apache.nifi.controller.ConfigurationContext;
import org.quartz.SchedulerException;
import org.socraticgrid.hl7.services.uc.model.Conversation;
import org.socraticgrid.hl7.services.uc.model.Message;
import org.socraticgrid.hl7.services.uc.model.QueryFilter;
import org.socraticgrid.hl7.services.uc.model.UserContactInfo;
import org.socraticgrid.hl7.ucs.nifi.common.model.Adapter;
import org.socraticgrid.hl7.ucs.nifi.common.model.ResolvedAddresses;
import org.socraticgrid.hl7.ucs.nifi.common.model.UCSStatus;
import org.socraticgrid.hl7.ucs.nifi.controller.store.MessageStoreController;
import org.socraticgrid.hl7.ucs.nifi.controller.user.UserContactInfoResolverController;
import org.socraticgrid.hl7.ucs.nifi.processor.model.MessageWithUnreachableHandlers;
import org.socraticgrid.hl7.ucs.nifi.services.TimedOutMessage;
/**
*
* @author esteban
*/
public class UCSControllerServiceProxy extends AbstractControllerService implements UCSController {
public static final PropertyDescriptor MESSAGE_STORE_IMPL = new PropertyDescriptor.Builder()
.name("MessageStoreController")
.description("The name of a concrete implementation of MessageStoreController interface")
.required(true)
.identifiesControllerService(MessageStoreController.class)
.build();
public static final PropertyDescriptor USER_CONTACT_INFO_RESOLVER_IMPL = new PropertyDescriptor.Builder()
.name("UserContactInfoController")
.description("A concrete implementation UserContactInfoResolverController interface")
.required(true)
.identifiesControllerService(UserContactInfoResolverController.class)
.build();
public static final PropertyDescriptor SERVICE_STATUS_CONTROLLER_SERVICE = new PropertyDescriptor.Builder()
.name("ServiceStatusControllerService")
.description(
"The Service Status Controller Service that this Processor uses to update the Status of this Adapter.")
.identifiesControllerService(ServiceStatusController.class)
.required(true).build();
private UCSControllerService service;
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
final List<PropertyDescriptor> descriptors = new ArrayList<>();
descriptors.add(MESSAGE_STORE_IMPL);
descriptors.add(USER_CONTACT_INFO_RESOLVER_IMPL);
descriptors.add(SERVICE_STATUS_CONTROLLER_SERVICE);
return descriptors;
}
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws Exception {
UserContactInfoResolverController userContactInfoResolver = context.getProperty(USER_CONTACT_INFO_RESOLVER_IMPL).asControllerService(UserContactInfoResolverController.class);
MessageStoreController messageStore = context.getProperty(MESSAGE_STORE_IMPL).asControllerService(MessageStoreController.class);
ServiceStatusController serviceStatusControllerService = context.getProperty(SERVICE_STATUS_CONTROLLER_SERVICE).asControllerService(ServiceStatusController.class);
this.service = new UCSControllerServiceImpl.UCSControllerServiceImplBuilder().setMessageStore(messageStore).setUserContactInfoResolver(userContactInfoResolver).setServiceStatusController(serviceStatusControllerService).build();
this.service.start();
}
@OnShutdown
public void onShutdown() throws Exception {
this.service.stop();
}
@Override
public ResolvedAddresses resolvePhysicalAddressesByServiceId(Message message) {
return this.service.resolvePhysicalAddressesByServiceId(message);
}
@Override
public UserContactInfo resolveUserContactInfo(String userId) {
return this.service.resolveUserContactInfo(userId);
}
@Override
public void start() {
//nobody is never going to call this method.
}
@Override
public void stop() {
//nobody is never going to call this method.
}
@Override
public void saveMessage(Message message) {
this.service.saveMessage(message);
}
@Override
public void updateMessage(Message message) {
this.service.updateMessage(message);
}
@Override
public Optional<Message> getMessageById(String messageId) {
return this.service.getMessageById(messageId);
}
@Override
public List<Message> listMessages() {
return this.service.listMessages();
}
@Override
public List<Message> listMessages(long from, long total) {
return this.service.listMessages(from, total);
}
@Override
public Set<Message> getRelatedMessages(String messageId) {
return this.service.getRelatedMessages(messageId);
}
@Override
public void saveMessageReference(Message message, String recipientId, String reference) {
this.service.saveMessageReference(message, recipientId, reference);
}
@Override
public Optional<Message> getMessageByReference(String reference) {
return this.service.getMessageByReference(reference);
}
@Override
public Optional<String> getRecipientIdByReference(String reference) {
return this.service.getRecipientIdByReference(reference);
}
@Override
public boolean isKnownConversation(String conversationId) {
return this.service.isKnownConversation(conversationId);
}
@Override
public String registerUCSClientCallback(URL callback) {
return this.service.registerUCSClientCallback(callback);
}
@Override
public void unregisterUCSClientCallback(String registrationId) {
this.service.unregisterUCSClientCallback(registrationId);
}
@Override
public Collection<URL> getUCSClientCallbacks() {
return this.service.getUCSClientCallbacks();
}
@Override
public void notifyAboutMessageWithUnreachableHandlers(MessageWithUnreachableHandlers message) {
this.service.notifyAboutMessageWithUnreachableHandlers(message);
}
@Override
public Set<MessageWithUnreachableHandlers> consumeMessagesWithUnreachableHandlers() {
return this.service.consumeMessagesWithUnreachableHandlers();
}
@Override
public void notifyAboutMessageWithResponseTimeout(TimedOutMessage message) {
this.service.notifyAboutMessageWithResponseTimeout(message);
}
@Override
public Set<TimedOutMessage> consumeMessagesWithResponseTimeout() {
return this.service.consumeMessagesWithResponseTimeout();
}
@Override
public void setupResponseTimeout(Message message) throws SchedulerException {
this.service.setupResponseTimeout(message);
}
@Override
public String registerUCSAlertingCallback(URL callback) {
return this.service.registerUCSAlertingCallback(callback);
}
@Override
public void unregisterUCSAlertingCallback(String registrationId) {
this.service.unregisterUCSAlertingCallback(registrationId);
}
@Override
public Collection<URL> getUCSAlertingCallbacks() {
return this.service.getUCSAlertingCallbacks();
}
@Override
public List<Adapter> getSupportedAdapters() {
return this.service.getSupportedAdapters();
}
@Override
public UCSStatus getServiceStatus() {
return this.service.getServiceStatus();
}
@Override
public void saveConversation(Conversation conversation) {
this.service.saveConversation(conversation);
}
@Override
public Optional<Conversation> getConversationById(String conversationId) {
return this.service.getConversationById(conversationId);
}
@Override
public List<Message> listMessagesByConversationId(String conversationId) {
return this.service.listMessagesByConversationId(conversationId);
}
@Override
public List<Message> listMessagesByConversationId(String conversationId, Optional<Long> from, Optional<Long> total) {
return this.service.listMessagesByConversationId(conversationId, from, total);
}
@Override
public List<Conversation> queryConversations(String query, List<QueryFilter> filters) {
return this.service.queryConversations(query, filters);
}
}
|
RadStr/DiaSynth
|
src/str/rad/synthesizer/gui/diagram/panels/port/Cable.java
|
<filename>src/str/rad/synthesizer/gui/diagram/panels/port/Cable.java<gh_stars>0
package str.rad.synthesizer.gui.diagram.panels.port;
import str.rad.synthesizer.gui.diagram.ifaces.MaxElevationGetterIFace;
import str.rad.synthesizer.gui.diagram.panels.ifaces.MovablePanelSpecificGetMethodsIFace;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
public class Cable {
public Cable(MaxElevationGetterIFace maxElevation, MovablePanelSpecificGetMethodsIFace source,
InputPort targetPort) {
MAX_ELEVATION = maxElevation;
pathAroundTargetPanel = new Path2D.Double();
absolutePath = new Path2D.Double();
relativePath = new Path2D.Double();
this.sourcePanel = source;
this.targetPort = targetPort;
}
public enum CableType {
STRAIGHT_LINE,
AISLE_ALGORITHM,
ADVANCED_ALGORITHM
}
private int pathAroundTargetPanelLen;
public int getPathAroundTargetPanelLen() {
return pathAroundTargetPanelLen;
}
private Path2D pathAroundTargetPanel;
/**
* Adds a point to the path by moving to the specified
* coordinates specified in double precision.
*
* @param x the specified X coordinate
* @param y the specified Y coordinate
*/
private void pathAroundTargetPanelMoveTo(double x, double y) {
pathAroundTargetPanel.moveTo(x, y);
pathAroundTargetPanelLen++;
}
/**
* Adds a point to the path by drawing a straight line from the
* current coordinates to the new specified coordinates
* specified in double precision.
*
* @param x the specified X coordinate
* @param y the specified Y coordinate
*/
private void pathAroundTargetPanelLineTo(double x, double y) {
pathAroundTargetPanel.lineTo(x, y);
pathAroundTargetPanelLen++;
}
public void resetPathAroundTargetPanel() {
pathAroundTargetPanel.reset();
pathAroundTargetPanelLen = 0;
}
public PathIterator getPathAroundTargetPanelIterator() {
return pathAroundTargetPanel.getPathIterator(null);
}
private double sideConnectorLastYForCollision = -Integer.MIN_VALUE;
public void setPathAroundTargetPanel() {
resetPathAroundTargetPanel();
MovablePanelSpecificGetMethodsIFace targetPanel = targetPort.getPanelWhichContainsPort();
Point relativeLocEnd = targetPanel.getRelativePosToReferencePanel();
pathAroundTargetPanelMoveTo(relativeLocEnd.x - 0.5, relativeLocEnd.y - 0.5);
pathAroundTargetPanelLineTo(relativeLocEnd.x + 0.5, relativeLocEnd.y - 0.5);
Point p = new Point();
targetPanel.getNextToLastPoint(p, targetPort);
if (p.y == -1) {
sideConnectorLastYForCollision = relativeLocEnd.y;
pathAroundTargetPanelMoveTo(relativeLocEnd.x - 0.5, relativeLocEnd.y - 0.5);
pathAroundTargetPanelLineTo(relativeLocEnd.x - 0.5, sideConnectorLastYForCollision);
}
else if (p.y == 1) {
sideConnectorLastYForCollision = relativeLocEnd.y;
pathAroundTargetPanelMoveTo(relativeLocEnd.x + 0.5, relativeLocEnd.y - 0.5);
pathAroundTargetPanelLineTo(relativeLocEnd.x + 0.5, sideConnectorLastYForCollision);
}
else {
sideConnectorLastYForCollision = Integer.MIN_VALUE;
}
}
public double getSideConnectorLastYForCollision() {
return sideConnectorLastYForCollision;
}
private CableType cableType;
public CableType getCableType() {
return cableType;
}
public void setCableType(CableType val) {
cableType = val;
}
private final MaxElevationGetterIFace MAX_ELEVATION;
private MovablePanelSpecificGetMethodsIFace sourcePanel;
public Point getSourcePanelRelativeLoc() {
return sourcePanel.getRelativePosToReferencePanel();
}
private InputPort targetPort;
public InputPort getTargetPort() {
return targetPort;
}
public Point getTargetPanelRelativeLoc() {
return targetPort.getPanelWhichContainsPort().getRelativePosToReferencePanel();
}
private Path2D absolutePath;
public Path2D getAbsolutePath() {
return absolutePath;
}
private Point lastPointBeforePort = new Point();
public Point getLastPointBeforePort() {
return lastPointBeforePort;
}
/**
* Whole number is the middle of the panel. .5 is right in the middle between the end of the panel on left and start of the panel on right.
*/
private Path2D relativePath;
private int relativePathLen = 0;
public int getRelativePathLen() {
return relativePathLen;
}
/**
* Adds a curved segment, defined by two new points, to the path by
* drawing a Quadratic curve that intersects both the current
* coordinates and the specified coordinates {@code (x2,y2)},
* using the specified point {@code (x1,y1)} as a quadratic
* parametric control point.
* All coordinates are specified in double precision.
*
* @param x1 the X coordinate of the quadratic control point
* @param y1 the Y coordinate of the quadratic control point
* @param x2 the X coordinate of the final end point
* @param y2 the Y coordinate of the final end point
*/
public void relativePathQuadTo(double x1, double y1, double x2, double y2) {
relativePath.quadTo(x1, y1, x2, y2);
relativePathLen++;
}
/**
* Adds a point to the path by moving to the specified
* coordinates specified in double precision.
*
* @param x the specified X coordinate
* @param y the specified Y coordinate
*/
public void relativePathMoveTo(double x, double y) {
relativePath.moveTo(x, y);
relativePathLen++;
}
/**
* Adds a point to the path by drawing a straight line from the
* current coordinates to the new specified coordinates
* specified in double precision.
*
* @param x the specified X coordinate
* @param y the specified Y coordinate
*/
public void relativePathLineTo(double x, double y) {
relativePath.lineTo(x, y);
relativePathLen++;
}
public PathIterator getRelativePathIterator() {
return relativePath.getPathIterator(null);
}
private final static double[] tmpArr = new double[4];
// I have to check if it is integer or not and based on that transform relative coordinates to absolute
// At first the code was quite clear, but I probably made some implementation mistake and the code got much for worse
// from there, but since it is working I won't be rewriting it
public void setAbsolutePathBasedOnRelativePath(Point referencePanelLoc, Dimension panelSize, int borderWidth, int borderHeight,
int panelSizeWithBorderWidth, int panelSizeWithBorderHeight,
int pixelsPerElevation) {
boolean endingCondition;
Point tmpPoint = new Point();
targetPort.getNextToLastPoint(tmpPoint);
boolean isConnectorOnSides = tmpPoint.y == -1 || tmpPoint.y == 1;
double[] line = new double[4];
int totalElevation = pixelsPerElevation * elevation;
int midBotReferencePanelX = referencePanelLoc.x + panelSize.width / 2;
int referencePanelEndX = referencePanelLoc.x + panelSize.width;
int referencePanelEndY = referencePanelLoc.y + panelSize.height;
double x;
double y;
absolutePath.reset();
double oldX = 0;
boolean wasLastQuad = false;
int index = 0;
for (PathIterator iterator = relativePath.getPathIterator(null); !iterator.isDone(); index++) {
if (index < 2) {
x = midBotReferencePanelX;
}
else {
x = referencePanelEndX;
}
y = referencePanelEndY;
int type = iterator.currentSegment(line);
iterator.next();
if (index == 0) {
oldX = line[0];
x += (panelSizeWithBorderWidth * line[0]);
y += (panelSizeWithBorderHeight * line[1]);
// ELEVATING START
x -= totalElevation;
y += sourcePanel.getDistanceFromRectangleBorders(totalElevation);
absolutePath.moveTo(x, y);
if (cableType == CableType.STRAIGHT_LINE) {
targetPort.getNextToLastPoint(tmpPoint);
// If it is connector from top then I will solve it now, otherwise it will be solved in the code as other cable types
if (tmpPoint.y == 0) {
// When going through panel ... we go through the mid of panel .. these 2 lines of code are copy pasted from later
Point panelLoc = targetPort.getPanelWhichContainsPort().getLocation();
y = panelLoc.y + totalElevation - borderHeight / 2;
// x is the same
absolutePath.lineTo(x, y);
setLastTwoPoints(x, y, tmpPoint);
return;
}
}
}
else {
if (type == PathIterator.SEG_QUADTO) {
double arcX = referencePanelEndX;
double arcY = referencePanelEndY;
boolean isArcToLeft;
if (line[2] < oldX) {
isArcToLeft = true;
}
else {
isArcToLeft = false;
}
arcX += getDistanceFromReferencePanel(panelSizeWithBorderWidth, borderWidth, line[0]);
arcY += getDistanceFromReferencePanel(panelSizeWithBorderHeight, borderHeight, line[1]);
arcY += totalElevation;
if ((line[1] == Math.floor(line[1]))) {
arcY -= borderHeight / 2;
}
x += getDistanceFromReferencePanel(panelSizeWithBorderWidth, borderWidth, line[2]);
y += getDistanceFromReferencePanel(panelSizeWithBorderHeight, borderHeight, line[3]);
if ((line[2] == Math.floor(line[2]))) {
if (!isArcToLeft) {
x -= panelSize.width;
}
}
if (line[0] == Math.floor(line[0])) {
if (isArcToLeft) {
x += panelSize.width / 2;
}
else {
x -= panelSize.width / 2;
}
}
else {
if (isArcToLeft) {
x -= panelSize.width / 2 - borderWidth;
}
arcX += borderWidth;
}
if (line[1] == Math.floor(line[1])) {
// EMPTY
}
else {
y -= panelSize.height / 2;
arcY += borderHeight / 2;
}
arcX -= borderWidth;
y += totalElevation;
absolutePath.quadTo(arcX, arcY, x, y);
oldX = line[2];
wasLastQuad = true;
}
else if (type == PathIterator.SEG_LINETO) {
endingCondition =
(isConnectorOnSides && (
(index >= relativePathLen - 2 && (cableType == CableType.ADVANCED_ALGORITHM) ||
cableType == CableType.STRAIGHT_LINE) ||
(index >= relativePathLen - 1 && cableType == CableType.AISLE_ALGORITHM)
)) ||
(!isConnectorOnSides && (
(index >= relativePathLen - 3 && cableType == CableType.ADVANCED_ALGORITHM) ||
(index >= relativePathLen - 2 && cableType == CableType.AISLE_ALGORITHM)
));
if (cableType == CableType.ADVANCED_ALGORITHM &&
iterator.currentSegment(tmpArr) != PathIterator.SEG_QUADTO &&
index != relativePathLen - 2 && !isConnectorOnSides) {
x = midBotReferencePanelX;
}
// When going through panel ... we go through the mid of panel
if (line[0] == Math.floor(line[0])) {
x += line[0] * panelSizeWithBorderWidth;
}
else { // When going through isle
x += getDistanceFromReferencePanel(panelSizeWithBorderWidth, borderWidth, line[0]);
}
// When going through panel ... we go through the mid of panel
if (line[1] == Math.floor(line[1])) {
y += line[1] * panelSizeWithBorderHeight;
y -= panelSize.height / 2;
}
else { // When going through isle
y += getDistanceFromReferencePanel(panelSizeWithBorderHeight, borderHeight, line[1]);
}
y += totalElevation;
// Load the one line twice, it isn't ideal, but doesn't break the program flow
double lineX = line[0];
if (iterator.currentSegment(line) == PathIterator.SEG_QUADTO) { // If the next segment is arc
boolean isArcToLeft = line[2] < line[0];
if (wasLastQuad && (isArcToLeft || (!isArcToLeft && lineX < oldX))) {
x = getNewXAfterFixForLastQuad(isArcToLeft, lineX, oldX, line[0], x, borderWidth, panelSize);
}
else {
if (line[0] == Math.floor(line[0])) {
if (isArcToLeft) { // Is line to left
x -= panelSize.width / 2;
}
else {
x += borderWidth / 2 + panelSize.width / 4;
}
}
else {
if (isArcToLeft) { // Is line to left
if (wasLastQuad && oldX - line[0] < 1) {
x -= panelSizeWithBorderWidth;
}
else {
x -= panelSize.width;
}
}
else {
// EMPTY
}
}
}
}
else {
x -= totalElevation;
}
if (endingCondition) { // Just draw the last lines and exit
setLastFewPoints(x, y, tmpPoint, totalElevation, borderWidth, borderHeight);
return;
}
else {
absolutePath.lineTo(x, y);
oldX = line[0];
wasLastQuad = false;
}
}
}
}
}
private void setLastFewPoints(double x, double y, Point tmpPoint, int totalElevation, int borderWidth, int borderHeight) {
Point panelLoc = targetPort.getPanelWhichContainsPort().getLocation();
targetPort.getNextToLastPoint(tmpPoint);
if (tmpPoint.y == 0) {
double newY = panelLoc.y + totalElevation - borderHeight / 2;
if (y != newY) {
absolutePath.lineTo(x, y);
y = newY;
absolutePath.lineTo(x, y);
}
x = tmpPoint.x;
}
else if (tmpPoint.y == -1) {
double newX = panelLoc.x - totalElevation - borderWidth / 2;
if (x != newX) {
absolutePath.lineTo(x, y);
x = newX;
absolutePath.lineTo(x, y);
}
y = tmpPoint.x;
}
else {
int targetPanelWidth = targetPort.getPanelWhichContainsPort().getSize().width;
double newX = panelLoc.x - totalElevation + targetPanelWidth + borderWidth / 2;
if (x != newX) {
absolutePath.lineTo(x, y);
x = newX;
absolutePath.lineTo(x, y);
}
y = tmpPoint.x;
}
lastPointBeforePort.x = (int) x;
lastPointBeforePort.y = (int) y;
absolutePath.lineTo(x, y);
targetPort.getLastPoint(tmpPoint);
absolutePath.lineTo(tmpPoint.x, tmpPoint.y);
}
private void setLastTwoPoints(double x, double y, Point tmpPoint) {
targetPort.getNextToLastPoint(tmpPoint);
if (tmpPoint.y == 0) {
x = tmpPoint.x;
}
else {
y = tmpPoint.x;
}
lastPointBeforePort.x = (int) x;
lastPointBeforePort.y = (int) y;
absolutePath.lineTo(x, y);
targetPort.getLastPoint(tmpPoint);
absolutePath.lineTo(tmpPoint.x, tmpPoint.y);
}
private double getNewXAfterFixForLastQuad(boolean isArcToLeft, double lineX, double oldX, double arcX, double x, int borderWidth, Dimension panelSize) {
if (isArcToLeft) { // going left - end of arc is more on left than the arc
if (lineX > oldX) { // But the line is going to right
if (arcX == Math.floor(arcX)) {
x -= borderWidth / 2 + panelSize.width / 4;
}
else {
x -= panelSize.width;
}
}
else {
if (arcX == Math.floor(arcX)) {
x -= borderWidth / 2 + panelSize.width / 4;
}
else {
x -= panelSize.width;
}
}
}
else {
if (lineX < oldX) {
if (arcX == Math.floor(arcX)) {
x += borderWidth / 2 + panelSize.width / 4;
}
}
}
return x;
}
private int getDistanceFromReferencePanel(int panelSizeWithBorder, int borderSize, double doubleVal) {
int floorVal = (int) Math.floor(doubleVal);
int dist = panelSizeWithBorder * floorVal;
if ((int) doubleVal != doubleVal) {
int modulo;
if ((int) doubleVal == 0) {
modulo = 1;
}
else {
modulo = floorVal;
if (modulo < 0 && modulo != 1) {
modulo++;
}
}
double valToAdd = borderSize * (doubleVal % modulo);
dist += Math.abs(valToAdd);
}
return dist;
}
private int elevation = 0;
public int getElevation() {
return elevation;
}
public void resetElevation() {
isElevationSet = false;
elevation = 0;
}
public void setElevationBasedOnMaxElevation(int currMaxElevation) { // Goes like 0->1->-1->2->-2 ... etc.
if (isBiggerThanCurrentlySetWithNext(currMaxElevation) || !isElevationSet) {
if (currMaxElevation == 0) {
if (MAX_ELEVATION.getMaxElevation() != 0)
elevation = 1;
else
elevation = 0;
}
else if (currMaxElevation > 0) {
elevation = -currMaxElevation;
}
else {
elevation = currMaxElevation - 1;
elevation = -elevation;
if (elevation > MAX_ELEVATION.getMaxElevation()) {
elevation = 0; // If too many cables, then just give up
}
}
isElevationSet = true;
}
}
/**
* Works with setElevationBasedOnMaxElevation so it checks if the value after the val is bigger
*
* @param val
* @return
*/
public boolean isBiggerThanCurrentlySetWithNext(int val) {
int absVal = Math.abs(val);
int absElevation = Math.abs(elevation);
return absVal >= absElevation;
}
public boolean isBiggerThanCurrentlySetWithGiven(int val) {
int absVal = Math.abs(val);
int absElevation = Math.abs(elevation);
return absVal > absElevation || (absVal == absElevation && elevation > 0 && absVal < 0);
}
public void setElevationToGivenValue(int value) {
elevation = value;
isElevationSet = true;
}
private boolean isElevationSet;
public boolean getIsElevationSet() {
return isElevationSet;
}
public void resetPaths() {
absolutePath.reset();
relativePath.reset();
relativePathLen = 0;
}
////////////////////// Board change
// Using transformations is easiest to program, but may create a lot of garbage
public void moveX(int xMovement) {
AffineTransform at = new AffineTransform();
at.translate(xMovement, 0);
absolutePath = new Path2D.Double(absolutePath, at);
lastPointBeforePort.x += xMovement;
}
public void moveY(int yMovement) {
AffineTransform at = new AffineTransform();
at.translate(0, yMovement);
absolutePath = new Path2D.Double(absolutePath, at);
lastPointBeforePort.y += yMovement;
}
public void move(int xMovement, int yMovement) {
AffineTransform at = new AffineTransform();
at.translate(xMovement, yMovement);
absolutePath = new Path2D.Double(absolutePath, at);
lastPointBeforePort.x += xMovement;
lastPointBeforePort.y += yMovement;
}
}
|
Phonemetra/TurboSQL
|
src/main/java/com/phonemetra/turbo/internal/visor/node/VisorAtomicConfiguration.java
|
<gh_stars>1-10
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.phonemetra.turbo.internal.visor.node;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import com.phonemetra.turbo.cache.CacheMode;
import com.phonemetra.turbo.configuration.AtomicConfiguration;
import com.phonemetra.turbo.internal.util.typedef.internal.S;
import com.phonemetra.turbo.internal.util.typedef.internal.U;
import com.phonemetra.turbo.internal.visor.VisorDataTransferObject;
/**
* Data transfer object for configuration of atomic data structures.
*/
public class VisorAtomicConfiguration extends VisorDataTransferObject {
/** */
private static final long serialVersionUID = 0L;
/** Atomic sequence reservation size. */
private int seqReserveSize;
/** Cache mode. */
private CacheMode cacheMode;
/** Number of backups. */
private int backups;
/**
* Default constructor.
*/
public VisorAtomicConfiguration() {
// No-op.
}
/**
* Create data transfer object for atomic configuration.
*
* @param src Atomic configuration.
*/
public VisorAtomicConfiguration(AtomicConfiguration src) {
seqReserveSize = src.getAtomicSequenceReserveSize();
cacheMode = src.getCacheMode();
backups = src.getBackups();
}
/**
* @return Atomic sequence reservation size.
*/
public int getAtomicSequenceReserveSize() {
return seqReserveSize;
}
/**
* @return Cache mode.
*/
public CacheMode getCacheMode() {
return cacheMode;
}
/**
* @return Number of backup nodes.
*/
public int getBackups() {
return backups;
}
/** {@inheritDoc} */
@Override protected void writeExternalData(ObjectOutput out) throws IOException {
out.writeInt(seqReserveSize);
U.writeEnum(out, cacheMode);
out.writeInt(backups);
}
/** {@inheritDoc} */
@Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {
seqReserveSize = in.readInt();
cacheMode = CacheMode.fromOrdinal(in.readByte());
backups = in.readInt();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(VisorAtomicConfiguration.class, this);
}
}
|
zarelaky/fuchsia
|
src/ui/lib/input_reader/tests/mock_hid_decoder.h
|
<filename>src/ui/lib/input_reader/tests/mock_hid_decoder.h
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_UI_LIB_INPUT_READER_TESTS_MOCK_HID_DECODER_H_
#define SRC_UI_LIB_INPUT_READER_TESTS_MOCK_HID_DECODER_H_
#include <lib/fit/function.h>
#include <lib/zx/event.h>
#include <queue>
#include "src/lib/fxl/memory/weak_ptr.h"
#include "src/ui/lib/input_reader/hid_decoder.h"
namespace ui_input {
// Mocks HidDecoder and allows sending arbitrary ReportDescriptors and Reports
// through |SendReportDescriptor| and |Send|.
class MockHidDecoder : public HidDecoder {
public:
MockHidDecoder() : weak_ptr_factory_(this) {}
MockHidDecoder(std::vector<uint8_t> report_descriptor) : weak_ptr_factory_(this) {
report_descriptor_ = report_descriptor;
}
MockHidDecoder(std::vector<uint8_t> report_descriptor, std::vector<uint8_t> initial_report)
: weak_ptr_factory_(this) {
report_descriptor_ = report_descriptor;
reports_.push({initial_report, 0});
}
MockHidDecoder(std::vector<uint8_t> report_descriptor, BootMode boot_mode)
: weak_ptr_factory_(this) {
boot_mode_ = boot_mode;
report_descriptor_ = report_descriptor;
}
~MockHidDecoder() override;
fxl::WeakPtr<MockHidDecoder> GetWeakPtr();
// |HidDecoder|
const std::string& name() const override;
// |HidDecoder|
bool Init() override;
// |HidDecoder|
zx::event GetEvent() override;
uint32_t GetTraceId() const override { return 0; }
// |HidDecoder|
BootMode ReadBootMode() const override;
// |HidDecoder|
const std::vector<uint8_t>& ReadReportDescriptor(int* bytes_read) override;
// |HidDecoder|
zx_status_t Read(uint8_t* data, size_t data_size, size_t* report_size,
zx_time_t* timestamp) override;
// |HidDecoder|
zx_status_t Send(ReportType type, uint8_t report_id, const std::vector<uint8_t>& report) override;
// |HidDecoder|
zx_status_t GetReport(ReportType type, uint8_t report_id, std::vector<uint8_t>* report) override;
// Emulates the Device sending a report, which will be read by |Read|.
void QueueDeviceReport(std::vector<uint8_t> bytes);
void QueueDeviceReport(std::vector<uint8_t> bytes, zx_time_t timestamp);
// Signals that the device can be read.
// Must be called after |QueueDevicereport| in order for |Read| to be called.
void SignalDeviceRead();
// Returns a copy of the last output report sent to |MockHidDecoder|.
std::vector<uint8_t> GetLastOutputReport();
// Sets the report descripter, which will be read by
// |ReadReportDescriptor|. This should only be called once at the beginning
// of setting up |MockHidDecoder|.
void SetReportDescriptor(std::vector<uint8_t> bytes);
// Sets the Boot Mode, which is read by |ReadBootMode|.
void SetBootMode(HidDecoder::BootMode boot_mode);
// Emulates removing the device. There must not be a pending report that has
// not been |Read|.
void Close();
private:
void Signal();
void ClearReport();
zx::event event_;
std::queue<std::pair<std::vector<uint8_t>, zx_time_t>> reports_;
std::vector<uint8_t> report_descriptor_;
std::vector<uint8_t> last_output_report_;
HidDecoder::BootMode boot_mode_ = HidDecoder::BootMode::NONE;
fxl::WeakPtrFactory<MockHidDecoder> weak_ptr_factory_;
};
} // namespace ui_input
#endif // SRC_UI_LIB_INPUT_READER_TESTS_MOCK_HID_DECODER_H_
|
Coobaha/reasonml-idea-plugin
|
src/com/reason/lang/dune/DuneParser.java
|
package com.reason.lang.dune;
import com.intellij.lang.*;
import com.intellij.psi.tree.*;
import com.reason.lang.*;
import org.jetbrains.annotations.*;
public class DuneParser extends CommonParser<DuneTypes> {
DuneParser() {
super(DuneTypes.INSTANCE);
}
@Override
protected void parseFile(@NotNull PsiBuilder builder, @NotNull ParserState state) {
IElementType tokenType = null;
// long parseStart = System.currentTimeMillis();
while (true) {
// long parseTime = System.currentTimeMillis();
// if (5 < parseTime - parseStart) {
// Protection: abort the parsing if too much time spent
// break;
// }
state.previousElementType1 = tokenType;
tokenType = builder.getTokenType();
if (tokenType == null) {
break;
}
if (tokenType == m_types.ATOM) {
parseAtom(state);
}
// ( ... )
else if (tokenType == m_types.LPAREN) {
parseLParen(state);
} else if (tokenType == m_types.RPAREN) {
parseRParen(state);
}
// %{ ... }
else if (tokenType == m_types.VAR_START) {
parseVarStart(state);
} else if (tokenType == m_types.VAR_END) {
parseVarEnd(state);
}
if (state.dontMove) {
state.dontMove = false;
} else {
builder.advanceLexer();
}
}
}
private void parseAtom(@NotNull ParserState state) {
if (state.is(m_types.C_STANZA)) {
state.advance().mark(m_types.C_FIELDS);
}
}
private void parseLParen(@NotNull ParserState state) {
if (state.isRoot()) {
state.markScope(m_types.C_STANZA, m_types.LPAREN);
} else if (state.is(m_types.C_FIELDS)) {
state.markScope(m_types.C_FIELD, m_types.LPAREN);
} else {
state.markScope(m_types.C_SEXPR, m_types.LPAREN);
}
}
private void parseRParen(@NotNull ParserState state) {
if (state.is(m_types.C_FIELDS)) {
state.popEnd();
}
if (state.hasScopeToken()) {
state.advance().popEnd();
} else {
state.error("Unbalanced parenthesis");
}
}
private void parseVarStart(@NotNull ParserState state) {
// |>%{<| ... }
state.markScope(m_types.C_VAR, m_types.VAR_START);
}
private void parseVarEnd(@NotNull ParserState state) {
if (state.is(m_types.C_VAR)) {
// %{ ... |>}<|
state.advance().popEnd();
}
}
}
|
wqk317/mi8_kernel_source
|
mi8/drivers/staging/qcacld-3.0/core/hdd/inc/wlan_hdd_debugfs.h
|
<gh_stars>0
/*
* Copyright (c) 2013-2018 The Linux Foundation. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef _WLAN_HDD_DEBUGFS_H
#define _WLAN_HDD_DEBUGFS_H
#ifdef WLAN_DEBUGFS
#define HDD_DEBUGFS_FILE_NAME_MAX 24
/**
* enum hdd_debugfs_file_id - Debugfs file Identifier
* @HDD_DEBUFS_FILE_ID_CONNECT_INFO: connect_info file id
* @HDD_DEBUFS_FILE_ID_ROAM_SCAN_STATS_INFO: roam_scan_stats file id
* @HDD_DEBUFS_FILE_ID_OFFLOAD_INFO: offload_info file id
* @HDD_DEBUGFS_FILE_ID_MAX: maximum id of csr debugfs file
*/
enum hdd_debugfs_file_id {
HDD_DEBUFS_FILE_ID_CONNECT_INFO = 0,
HDD_DEBUFS_FILE_ID_ROAM_SCAN_STATS_INFO = 1,
HDD_DEBUFS_FILE_ID_OFFLOAD_INFO = 2,
HDD_DEBUGFS_FILE_ID_MAX,
};
/**
* struct hdd_debugfs_file_info - Debugfs file info
* @name: name of debugfs file
* @id: id from enum hdd_debugfs_file_id used to identify file
* @buf_max_size: max size of buffer from which debugfs file is updated
* @entry: dentry pointer to debugfs file
*/
struct hdd_debugfs_file_info {
uint8_t name[HDD_DEBUGFS_FILE_NAME_MAX];
enum hdd_debugfs_file_id id;
ssize_t buf_max_size;
struct dentry *entry;
};
QDF_STATUS hdd_debugfs_init(struct hdd_adapter *adapter);
void hdd_debugfs_exit(struct hdd_adapter *adapter);
/**
* hdd_wait_for_debugfs_threads_completion() - Wait for debugfs threads
* completion before proceeding further to stop modules
*
* Return: true if there is no debugfs open
* false if there is at least one debugfs open
*/
bool hdd_wait_for_debugfs_threads_completion(void);
/**
* hdd_return_debugfs_threads_count() - Return active debugfs threads
*
* Return: total number of active debugfs threads in driver
*/
int hdd_return_debugfs_threads_count(void);
/**
* hdd_debugfs_thread_increment() - Increment debugfs thread count
*
* This function is used to increment and keep track of debugfs thread count.
* This is invoked for every file open operation.
*
* Return: None
*/
void hdd_debugfs_thread_increment(void);
/**
* hdd_debugfs_thread_decrement() - Decrement debugfs thread count
*
* This function is used to decrement and keep track of debugfs thread count.
* This is invoked for every file release operation.
*
* Return: None
*/
void hdd_debugfs_thread_decrement(void);
#else
static inline QDF_STATUS hdd_debugfs_init(struct hdd_adapter *adapter)
{
return QDF_STATUS_SUCCESS;
}
static inline void hdd_debugfs_exit(struct hdd_adapter *adapter)
{
}
/**
* hdd_wait_for_debugfs_threads_completion() - Wait for debugfs threads
* completion before proceeding further to stop modules
*
* Return: true if there is no debugfs open
* false if there is at least one debugfs open
*/
static inline
bool hdd_wait_for_debugfs_threads_completion(void)
{
return true;
}
/**
* hdd_return_debugfs_threads_count() - Return active debugfs threads
*
* Return: total number of active debugfs threads in driver
*/
static inline
int hdd_return_debugfs_threads_count(void)
{
return 0;
}
/**
* hdd_debugfs_thread_increment() - Increment debugfs thread count
*
* This function is used to increment and keep track of debugfs thread count.
* This is invoked for every file open operation.
*
* Return: None
*/
static inline
void hdd_debugfs_thread_increment(void)
{
}
/**
* hdd_debugfs_thread_decrement() - Decrement debugfs thread count
*
* This function is used to decrement and keep track of debugfs thread count.
* This is invoked for every file release operation.
*
* Return: None
*/
static inline
void hdd_debugfs_thread_decrement(void)
{
}
#endif /* #ifdef WLAN_DEBUGFS */
#endif /* #ifndef _WLAN_HDD_DEBUGFS_H */
|
medismailben/llvm-project
|
clang/test/Analysis/copypaste/not-autogenerated.cpp
|
// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=alpha.clone.CloneChecker -analyzer-config alpha.clone.CloneChecker:MinimumCloneComplexity=10 -analyzer-config alpha.clone.CloneChecker:IgnoredFilesPattern="moc_|ui_|dbus_|.*_automoc" -verify %s
void f1() {
int *p1 = new int[1];
int *p2 = new int[1];
if (p1) {
delete [] p1; // expected-note{{Similar code using 'p1' here}}
p1 = nullptr;
}
if (p2) {
delete [] p1; // expected-warning{{Potential copy-paste error; did you really mean to use 'p1' here?}}
p2 = nullptr;
}
}
|
sunwolf-swb/mark-idea
|
src/main/java/ink/markidea/note/entity/exception/PromptException.java
|
package ink.markidea.note.entity.exception;
/**
* @author hansanshi
* @date 2020/2/9
*/
public class PromptException extends RuntimeException {
public PromptException(String message) {
super(message);
}
}
|
sky5454/30daysMakeOS-Origin-ISOfiles
|
30days-Origin-ISOfiles/omake/tolsrc/go_0023s/gcc/graph.c
|
/* Output routines for graphical representation.
Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
Contributed by <NAME> <<EMAIL>>, 1998.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING. If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA. */
/* !kawai! */
#include "config.h"
#include "system.h"
/* end of !kawai! */
#include "rtl.h"
#include "flags.h"
#include "output.h"
#include "function.h"
#include "hard-reg-set.h"
#include "basic-block.h"
#include "toplev.h"
#include "graph.h"
static const char *const graph_ext[] =
{
/* no_graph */ "",
/* vcg */ ".vcg",
};
static void start_fct PARAMS ((FILE *));
static void start_bb PARAMS ((FILE *, int));
static void node_data PARAMS ((FILE *, rtx));
static void draw_edge PARAMS ((FILE *, int, int, int, int));
static void end_fct PARAMS ((FILE *));
static void end_bb PARAMS ((FILE *));
/* Output text for new basic block. */
static void
start_fct (fp)
FILE *fp;
{
switch (graph_dump_format)
{
case vcg:
fprintf (fp, "\
graph: { title: \"%s\"\nfolding: 1\nhidden: 2\nnode: { title: \"%s.0\" }\n",
current_function_name, current_function_name);
break;
case no_graph:
break;
}
}
static void
start_bb (fp, bb)
FILE *fp;
int bb;
{
switch (graph_dump_format)
{
case vcg:
fprintf (fp, "\
graph: {\ntitle: \"%s.BB%d\"\nfolding: 1\ncolor: lightblue\n\
label: \"basic block %d",
current_function_name, bb, bb);
break;
case no_graph:
break;
}
#if 0
/* FIXME Should this be printed? It makes the graph significantly larger. */
/* Print the live-at-start register list. */
fputc ('\n', fp);
EXECUTE_IF_SET_IN_REG_SET (basic_block_live_at_start[bb], 0, i,
{
fprintf (fp, " %d", i);
if (i < FIRST_PSEUDO_REGISTER)
fprintf (fp, " [%s]",
reg_names[i]);
});
#endif
switch (graph_dump_format)
{
case vcg:
fputs ("\"\n\n", fp);
break;
case no_graph:
break;
}
}
static void
node_data (fp, tmp_rtx)
FILE *fp;
rtx tmp_rtx;
{
if (PREV_INSN (tmp_rtx) == 0)
{
/* This is the first instruction. Add an edge from the starting
block. */
switch (graph_dump_format)
{
case vcg:
fprintf (fp, "\
edge: { sourcename: \"%s.0\" targetname: \"%s.%d\" }\n",
current_function_name,
current_function_name, XINT (tmp_rtx, 0));
break;
case no_graph:
break;
}
}
switch (graph_dump_format)
{
case vcg:
fprintf (fp, "node: {\n title: \"%s.%d\"\n color: %s\n \
label: \"%s %d\n",
current_function_name, XINT (tmp_rtx, 0),
GET_CODE (tmp_rtx) == NOTE ? "lightgrey"
: GET_CODE (tmp_rtx) == INSN ? "green"
: GET_CODE (tmp_rtx) == JUMP_INSN ? "darkgreen"
: GET_CODE (tmp_rtx) == CALL_INSN ? "darkgreen"
: GET_CODE (tmp_rtx) == CODE_LABEL ? "\
darkgrey\n shape: ellipse" : "white",
GET_RTX_NAME (GET_CODE (tmp_rtx)), XINT (tmp_rtx, 0));
break;
case no_graph:
break;
}
/* Print the RTL. */
if (GET_CODE (tmp_rtx) == NOTE)
{
const char *name = "";
if (NOTE_LINE_NUMBER (tmp_rtx) < 0)
name = GET_NOTE_INSN_NAME (NOTE_LINE_NUMBER (tmp_rtx));
fprintf (fp, " %s", name);
}
else if (INSN_P (tmp_rtx))
print_rtl_single (fp, PATTERN (tmp_rtx));
else
print_rtl_single (fp, tmp_rtx);
switch (graph_dump_format)
{
case vcg:
fputs ("\"\n}\n", fp);
break;
case no_graph:
break;
}
}
static void
draw_edge (fp, from, to, bb_edge, class)
FILE *fp;
int from;
int to;
int bb_edge;
int class;
{
const char * color;
switch (graph_dump_format)
{
case vcg:
color = "";
if (class == 2)
color = "color: red ";
else if (bb_edge)
color = "color: blue ";
else if (class == 3)
color = "color: green ";
fprintf (fp,
"edge: { sourcename: \"%s.%d\" targetname: \"%s.%d\" %s",
current_function_name, from,
current_function_name, to, color);
if (class)
fprintf (fp, "class: %d ", class);
fputs ("}\n", fp);
break;
case no_graph:
break;
}
}
static void
end_bb (fp)
FILE *fp;
{
switch (graph_dump_format)
{
case vcg:
fputs ("}\n", fp);
break;
case no_graph:
break;
}
}
static void
end_fct (fp)
FILE *fp;
{
switch (graph_dump_format)
{
case vcg:
fprintf (fp, "node: { title: \"%s.999999\" label: \"END\" }\n}\n",
current_function_name);
break;
case no_graph:
break;
}
}
/* Like print_rtl, but also print out live information for the start of each
basic block. */
void
print_rtl_graph_with_bb (base, suffix, rtx_first)
const char *base;
const char *suffix;
rtx rtx_first;
{
rtx tmp_rtx;
size_t namelen = strlen (base);
size_t suffixlen = strlen (suffix);
size_t extlen = strlen (graph_ext[graph_dump_format]) + 1;
char *buf = (char *) alloca (namelen + suffixlen + extlen);
FILE *fp;
if (basic_block_info == NULL)
return;
memcpy (buf, base, namelen);
memcpy (buf + namelen, suffix, suffixlen);
memcpy (buf + namelen + suffixlen, graph_ext[graph_dump_format], extlen);
fp = fopen (buf, "a");
if (fp == NULL)
return;
if (rtx_first == 0)
fprintf (fp, "(nil)\n");
else
{
int i;
enum bb_state { NOT_IN_BB, IN_ONE_BB, IN_MULTIPLE_BB };
int max_uid = get_max_uid ();
int *start = (int *) xmalloc (max_uid * sizeof (int));
int *end = (int *) xmalloc (max_uid * sizeof (int));
enum bb_state *in_bb_p = (enum bb_state *)
xmalloc (max_uid * sizeof (enum bb_state));
basic_block bb;
for (i = 0; i < max_uid; ++i)
{
start[i] = end[i] = -1;
in_bb_p[i] = NOT_IN_BB;
}
for (i = n_basic_blocks - 1; i >= 0; --i)
{
rtx x;
bb = BASIC_BLOCK (i);
start[INSN_UID (bb->head)] = i;
end[INSN_UID (bb->end)] = i;
for (x = bb->head; x != NULL_RTX; x = NEXT_INSN (x))
{
in_bb_p[INSN_UID (x)]
= (in_bb_p[INSN_UID (x)] == NOT_IN_BB)
? IN_ONE_BB : IN_MULTIPLE_BB;
if (x == bb->end)
break;
}
}
/* Tell print-rtl that we want graph output. */
dump_for_graph = 1;
/* Start new function. */
start_fct (fp);
for (tmp_rtx = NEXT_INSN (rtx_first); NULL != tmp_rtx;
tmp_rtx = NEXT_INSN (tmp_rtx))
{
int edge_printed = 0;
rtx next_insn;
if (start[INSN_UID (tmp_rtx)] < 0 && end[INSN_UID (tmp_rtx)] < 0)
{
if (GET_CODE (tmp_rtx) == BARRIER)
continue;
if (GET_CODE (tmp_rtx) == NOTE
&& (1 || in_bb_p[INSN_UID (tmp_rtx)] == NOT_IN_BB))
continue;
}
if ((i = start[INSN_UID (tmp_rtx)]) >= 0)
{
/* We start a subgraph for each basic block. */
start_bb (fp, i);
if (i == 0)
draw_edge (fp, 0, INSN_UID (tmp_rtx), 1, 0);
}
/* Print the data for this node. */
node_data (fp, tmp_rtx);
next_insn = next_nonnote_insn (tmp_rtx);
if ((i = end[INSN_UID (tmp_rtx)]) >= 0)
{
edge e;
bb = BASIC_BLOCK (i);
/* End of the basic block. */
end_bb (fp);
/* Now specify the edges to all the successors of this
basic block. */
for (e = bb->succ; e ; e = e->succ_next)
{
if (e->dest != EXIT_BLOCK_PTR)
{
rtx block_head = e->dest->head;
draw_edge (fp, INSN_UID (tmp_rtx),
INSN_UID (block_head),
next_insn != block_head,
(e->flags & EDGE_ABNORMAL ? 2 : 0));
if (block_head == next_insn)
edge_printed = 1;
}
else
{
draw_edge (fp, INSN_UID (tmp_rtx), 999999,
next_insn != 0,
(e->flags & EDGE_ABNORMAL ? 2 : 0));
if (next_insn == 0)
edge_printed = 1;
}
}
}
if (!edge_printed)
{
/* Don't print edges to barriers. */
if (next_insn == 0
|| GET_CODE (next_insn) != BARRIER)
draw_edge (fp, XINT (tmp_rtx, 0),
next_insn ? INSN_UID (next_insn) : 999999, 0, 0);
else
{
/* We draw the remaining edges in class 3. We have
to skip over the barrier since these nodes are
not printed at all. */
do
next_insn = NEXT_INSN (next_insn);
while (next_insn
&& (GET_CODE (next_insn) == NOTE
|| GET_CODE (next_insn) == BARRIER));
draw_edge (fp, XINT (tmp_rtx, 0),
next_insn ? INSN_UID (next_insn) : 999999, 0, 3);
}
}
}
dump_for_graph = 0;
end_fct (fp);
/* Clean up. */
free (start);
free (end);
free (in_bb_p);
}
fclose (fp);
}
/* Similar as clean_dump_file, but this time for graph output files. */
void
clean_graph_dump_file (base, suffix)
const char *base;
const char *suffix;
{
size_t namelen = strlen (base);
size_t suffixlen = strlen (suffix);
size_t extlen = strlen (graph_ext[graph_dump_format]) + 1;
char *buf = (char *) alloca (namelen + extlen + suffixlen);
FILE *fp;
memcpy (buf, base, namelen);
memcpy (buf + namelen, suffix, suffixlen);
memcpy (buf + namelen + suffixlen, graph_ext[graph_dump_format], extlen);
fp = fopen (buf, "w");
if (fp == NULL)
fatal_io_error ("can't open %s", buf);
switch (graph_dump_format)
{
case vcg:
fputs ("graph: {\nport_sharing: no\n", fp);
break;
case no_graph:
abort ();
}
fclose (fp);
}
/* Do final work on the graph output file. */
void
finish_graph_dump_file (base, suffix)
const char *base;
const char *suffix;
{
size_t namelen = strlen (base);
size_t suffixlen = strlen (suffix);
size_t extlen = strlen (graph_ext[graph_dump_format]) + 1;
char *buf = (char *) alloca (namelen + suffixlen + extlen);
FILE *fp;
memcpy (buf, base, namelen);
memcpy (buf + namelen, suffix, suffixlen);
memcpy (buf + namelen + suffixlen, graph_ext[graph_dump_format], extlen);
fp = fopen (buf, "a");
if (fp != NULL)
{
switch (graph_dump_format)
{
case vcg:
fputs ("}\n", fp);
break;
case no_graph:
abort ();
}
fclose (fp);
}
}
|
grzegorz103/webshop-microservices
|
product-service/src/main/java/product/service/web/api/CategoryController.java
|
<reponame>grzegorz103/webshop-microservices
package product.service.web.api;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import product.service.services.category.CategoryDTO;
import product.service.services.category.CategoryService;
import javax.validation.Valid;
@RestController
@RequestMapping(value = "${url.category}", produces = "application/json")
public class CategoryController {
private final CategoryService categoryService;
public CategoryController(CategoryService categoryService) {
this.categoryService = categoryService;
}
@GetMapping
public Page<CategoryDTO> getAll(Pageable pageable) {
return categoryService.getAll(pageable);
}
@GetMapping("/{id}")
public CategoryDTO getById(@PathVariable Long id) {
return categoryService.getById(id);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public CategoryDTO create(@RequestBody CategoryDTO category) {
return categoryService.create(category);
}
@PutMapping("/{id}")
public CategoryDTO update(@RequestBody @Valid CategoryDTO category,
@PathVariable("id") Long id) {
return categoryService.update(id, category);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable("id") Long id) {
categoryService.delete(id);
}
}
|
TianyuDu/AnnEconForecast
|
pytorch/hp_search.py
|
"""
TODO: write documents
"""
from pprint import pprint
from datetime import datetime
import sys
sys.path.extend(["./core", "./core/tools"])
import matplotlib
c = input("Use Agg as matplotlib (avoid tkinter)[y/n]: ")
if c.lower() in ["y", ""]:
matplotlib.use("agg")
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import tqdm
import torch
import lstm_controls
import nnar_controls
from param_set_generator import gen_hparam_set
import DIRS
from ProfileLoader import ProfileLoader
# For sunspot, train_size = 231, test_size = 58
LSTM_PROFILE = {
"TRAIN_SIZE": 0.8, # Include both training and validation sets.
"TEST_SIZE": 0.2,
"LAGS": [20, 32],
"VAL_RATIO": 0.2, # Validation ratio.
"BATCH_SIZE": [32, 128],
"LEARNING_RATE": [0.003, 0.001],
"NEURONS": [(2048, 1024), (1024, 2048), (2048, 4096)],
"EPOCHS": [100, 300],
"NAME": "high_complex_lstm"
}
ANN_PROFILE = {
"TRAIN_SIZE": 0.8, # Include both training and validation sets.
"TEST_SIZE": 0.2,
"LAGS": [6, 12, 20, 32],
"VAL_RATIO": 0.2, # Validation ratio.
"BATCH_SIZE": 32,
"LEARNING_RATE": [0.03, 0.01, 0.003, 0.001],
"NEURONS": [(64, 128), (128, 256), (256, 512)],
"EPOCHS": [500, 1000],
"NAME": "NNAR"
}
SRC_PROFILE = ANN_PROFILE
def df_loader() -> pd.DataFrame:
df = pd.read_csv(
"/home/ec2-user/AnnEconForecast/data/CPIAUCSL_monthly_change.csv",
index_col=0,
date_parser=lambda x: datetime.strptime(x, "%Y-%m-%d"),
engine="c"
)
# df[df[df.columns[0]] == "."] = np.nan
# df.fillna(method="ffill")
# df = df[df != "."]
# df.dropna(inplace=True)
return df
if __name__ == "__main__":
if input("Create a new experiment?[y/n] ").lower() in ["y", ""]:
profile_set = gen_hparam_set(SRC_PROFILE)
else:
path = input("Directory of profiles: ")
loader = ProfileLoader(path)
profile_set = loader.get_all()
print("Cuda avaiable: ", torch.cuda.is_available())
# Expand lstm profiles
# profile_set_expand = list()
# for p in profile_set:
# if "lstm" in p["NAME"]:
# for i in [True, False]:
# p_expand = p.copy()
# p_expand["POOLING"] = i
# profile_set_expand.append(p_expand)
# elif "nnar" in p["NAME"]:
# profile_set_expand.append(p)
# else:
# raise Exception
# Reset validation ratio to 0
# profile_set_expand = list()
# for p in profile_set:
# p_modified = p.copy()
# p_modified["VAL_RATIO"] = 0.05
# profile_set_expand.append(p_modified)
profile_set_expand = list()
for i in range(30):
p = profile_set[0].copy()
p["EPOCHS"] = (i + 1) * 50
profile_set_expand.append(p)
start = datetime.now()
raw_df = df_loader()
with tqdm.trange(len(profile_set_expand)) as prg:
for i in prg:
PROFILE = profile_set_expand[i]
prg.set_description(
f"n={PROFILE['NEURONS']};l={PROFILE['LAGS']};a={PROFILE['LEARNING_RATE']};Total")
if "lstm" in PROFILE["NAME"]:
lstm_controls.core(
**PROFILE,
profile_record=PROFILE,
raw_df=raw_df,
verbose=False
)
elif "nnar" in PROFILE["NAME"]:
nnar_controls.core(
**PROFILE,
profile_record=PROFILE,
raw_df=raw_df,
verbose=False
)
print(f"\nTotal time taken: {datetime.now() - start}")
|
liumingmusic/HadoopLearning
|
SparkSQL/src/main/scala/com/c503/sparksql/Spark_SQL_2.scala
|
<reponame>liumingmusic/HadoopLearning
package com.c503.sparksql
import com.c503.utils.SparkSqlUtils
import org.apache.spark.sql.Row
import org.apache.spark.sql.types.{StringType, StructField, StructType}
/**
* 描述 简单描述方法的作用
*
* @author liumm
* @since 2018-09-16 15:45
*/
object Spark_SQL_2 {
def main(args: Array[String]): Unit = {
SparkSqlUtils.offLogger()
}
def rddToDF_two(): Unit = {
val spark = SparkSqlUtils.newSparkSession("Spark_SQL_2")
val lines = spark.sparkContext.textFile(SparkSqlUtils.getPathByName("person.txt"))
//定义一个模式字符串
val schemaString = "name age"
//根据模式字符串生成模式
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, nullable = true))
//从上面信息可以看出,schema描述了模式信息,模式中包含name和age两个字段
//对peopleRDD 这个RDD中的每一行元素都进行解析val peopleDF = spark.read.format("json").load("examples/src/main/resources/people.json")
val schema = StructType(fields)
val rowRDD = lines.map(_.split(",")).map(attributes => Row(attributes(0), attributes(1).trim))
val peopleDF = spark.createDataFrame(rowRDD, schema)
//必须注册为临时表才能供下面查询使用
peopleDF.createOrReplaceTempView("people")
val results = spark.sql("SELECT name,age FROM people")
results.show()
}
def rddToDF_one(): Unit = {
val spark = SparkSqlUtils.newSparkSession("Spark_SQL_2")
val lines = spark.sparkContext.textFile(SparkSqlUtils.getPathByName("person.txt"))
//隐式导入
import spark.implicits._
val peopleDF = lines.map(_.split(",")).map(arr => {
Person(arr(0), arr(1).trim.toInt)
}).toDF()
//必须注册为临时表才能供下面的查询使用
peopleDF.createOrReplaceTempView("person")
spark.sql("select name, age from person where age > 20").show()
}
}
case class Person(name: String, age: Long)
|
jihwahn1018/ovirt-engine
|
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/connection/iscsibond/GetIscsiBondsByStoragePoolIdQuery.java
|
<reponame>jihwahn1018/ovirt-engine<gh_stars>100-1000
package org.ovirt.engine.core.bll.storage.connection.iscsibond;
import java.util.List;
import javax.inject.Inject;
import org.ovirt.engine.core.bll.QueriesCommandBase;
import org.ovirt.engine.core.bll.context.EngineContext;
import org.ovirt.engine.core.common.businessentities.IscsiBond;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.IscsiBondDao;
public class GetIscsiBondsByStoragePoolIdQuery <P extends IdQueryParameters> extends QueriesCommandBase<P> {
@Inject
private IscsiBondDao iscsiBondDao;
public GetIscsiBondsByStoragePoolIdQuery(P parameters, EngineContext engineContext) {
super(parameters, engineContext);
}
@Override
protected void executeQueryCommand() {
List<IscsiBond> iscsiBonds = iscsiBondDao.getAllByStoragePoolId(getParameters().getId());
for (IscsiBond iscsiBond : iscsiBonds) {
List<Guid> networkIds = iscsiBondDao.getNetworkIdsByIscsiBondId(iscsiBond.getId());
iscsiBond.setNetworkIds(networkIds);
List<String> connectionIds = iscsiBondDao.getStorageConnectionIdsByIscsiBondId(iscsiBond.getId());
iscsiBond.setStorageConnectionIds(connectionIds);
}
getQueryReturnValue().setReturnValue(iscsiBonds);
}
}
|
MaastrichtU-IDS/biosearch
|
src/main/java/cn/edu/nju/ws/biosearch/classTree/ClassGroup.java
|
<reponame>MaastrichtU-IDS/biosearch<filename>src/main/java/cn/edu/nju/ws/biosearch/classTree/ClassGroup.java<gh_stars>0
package cn.edu.nju.ws.biosearch.classTree;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Properties;
public class ClassGroup {
private static volatile ClassGroup inst = null;
private ArrayList<String> classGroups;
public static ClassGroup getInstance() {
if(inst == null) {
synchronized(ClassGroup.class) {
if(inst == null) {
inst = new ClassGroup();
}
}
}
return inst;
}
private ClassGroup() {
readClassGroups();
}
private void readClassGroups() {
classGroups = new ArrayList<String>();
Properties props = new Properties();
try {
props.load(ClassGroup.class.getClassLoader().getResourceAsStream("config/classfiltergroups.properties"));
String groups = (String) props.get("GROUPS");
if(groups == null) return;
String[] groupsArray = groups.split(";");
for(String group: groupsArray) {
classGroups.add(group);
}
} catch (IOException e) {
e.printStackTrace();
}
Collections.sort(classGroups);
}
public ArrayList<String> getClassGroups() {
return classGroups;
}
}
|
hevp/fcrepo
|
fcrepo-server/src/main/java/org/fcrepo/server/storage/ExternalContentManager.java
|
<filename>fcrepo-server/src/main/java/org/fcrepo/server/storage/ExternalContentManager.java
/* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://fedora-commons.org/license/).
*/
package org.fcrepo.server.storage;
import org.fcrepo.server.errors.ServerException;
import org.fcrepo.server.storage.types.MIMETypedStream;
/**
* Interface that provides a mechanism for retrieving external content via HTTP.
*
* @author <NAME>
* @version $Id$
*/
public interface ExternalContentManager {
/**
* Reads the contents of the specified URL and returns the
* result as a MIMETypedStream. Used as a wrapper with a default MIME type
* of "text/plain"
*
* @param params
* The context params.
* @return A MIME-typed stream.
* @throws ServerException
* If the URL connection could not be established.
*/
public MIMETypedStream getExternalContent(ContentManagerParams params)
throws ServerException;
}
|
dphrygian/zeta
|
Code/Projects/Rosa/src/Actions/wbactionrosaloadgame.h
|
<reponame>dphrygian/zeta
#ifndef WBACTIONROSALOADGAME_H
#define WBACTIONROSALOADGAME_H
#include "wbaction.h"
#include "simplestring.h"
class WBActionRosaLoadGame : public WBAction
{
public:
WBActionRosaLoadGame();
virtual ~WBActionRosaLoadGame();
DEFINE_WBACTION_FACTORY( RosaLoadGame );
virtual void InitializeFromDefinition( const SimpleString& DefinitionName );
virtual void Execute();
private:
SimpleString m_SaveSlot;
};
#endif // WBACTIONROSALOADGAME_H
|
solotzg/tiflash
|
dbms/src/Interpreters/IInterpreter.h
|
// Copyright 2022 PingCAP, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <DataStreams/BlockIO.h>
namespace DB
{
/** Interpreters interface for different queries.
*/
class IInterpreter
{
public:
/** For queries that return a result (SELECT and similar), sets in BlockIO a stream from which you can read this result.
* For queries that receive data (INSERT), sets a thread in BlockIO where you can write data.
* For queries that do not require data and return nothing, BlockIO will be empty.
*/
virtual BlockIO execute() = 0;
virtual ~IInterpreter() {}
};
} // namespace DB
|
liupangzi/codekata
|
leetcode/Algorithms/763.PartitionLabels/Solution.java
|
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> partitionLabels(String S) {
int[] map = new int[26];
for (int i = 0; i < S.length(); i++) map[S.charAt(i) - 'a'] = i;
int cursor = 0;
ArrayList<Integer> result = new ArrayList<>();
while (cursor < S.length()) {
int tmp = cursor, stop = map[S.charAt(tmp) - 'a'];
while (cursor < stop) {
stop = Math.max(stop, map[S.charAt(cursor) - 'a']);
cursor++;
}
cursor++;
result.add(cursor - tmp);
}
return result;
}
}
|
luyan1990/lifeix-football-app-android-master
|
android-client/src/main/java/io/swagger/client/model/TimeLineNews.java
|
package io.swagger.client.model;
import io.swagger.client.model.Post;
import java.util.*;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
/**
* 时间轴形式的新闻
**/
@ApiModel(description = "时间轴形式的新闻")
public class TimeLineNews {
@SerializedName("date")
private String date = null;
@SerializedName("posts")
private List<Post> posts = null;
/**
* date,时间轴上日期
**/
@ApiModelProperty(value = "date,时间轴上日期")
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
/**
* 文章
**/
@ApiModelProperty(value = "文章")
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TimeLineNews timeLineNews = (TimeLineNews) o;
return (date == null ? timeLineNews.date == null : date.equals(timeLineNews.date)) &&
(posts == null ? timeLineNews.posts == null : posts.equals(timeLineNews.posts));
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (date == null ? 0: date.hashCode());
result = 31 * result + (posts == null ? 0: posts.hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TimeLineNews {\n");
sb.append(" date: ").append(date).append("\n");
sb.append(" posts: ").append(posts).append("\n");
sb.append("}\n");
return sb.toString();
}
}
|
bingchunjin/1806_SDK
|
linux-4.14.90-dev/linux-4.14.90/arch/x86/platform/intel-mid/device_libs/platform_bcm43xx.c
|
/*
* platform_bcm43xx.c: bcm43xx platform data initilization file
*
* (C) Copyright 2016 Intel Corporation
* Author: <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License.
*/
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/fixed.h>
#include <linux/sfi.h>
#include <asm/intel-mid.h>
#define WLAN_SFI_GPIO_IRQ_NAME "WLAN-interrupt"
#define WLAN_SFI_GPIO_ENABLE_NAME "WLAN-enable"
#define WLAN_DEV_NAME "0000:00:01.3"
static struct regulator_consumer_supply bcm43xx_vmmc_supply = {
.dev_name = WLAN_DEV_NAME,
.supply = "vmmc",
};
static struct regulator_init_data bcm43xx_vmmc_data = {
.constraints = {
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = 1,
.consumer_supplies = &bcm43xx_vmmc_supply,
};
static struct fixed_voltage_config bcm43xx_vmmc = {
.supply_name = "bcm43xx-vmmc-regulator",
/*
* Announce 2.0V here to be compatible with SDIO specification. The
* real voltage and signaling are still 1.8V.
*/
.microvolts = 2000000, /* 1.8V */
.gpio = -EINVAL,
.startup_delay = 250 * 1000, /* 250ms */
.enable_high = 1, /* active high */
.enabled_at_boot = 0, /* disabled at boot */
.init_data = &bcm43xx_vmmc_data,
};
static struct platform_device bcm43xx_vmmc_regulator = {
.name = "reg-fixed-voltage",
.id = PLATFORM_DEVID_AUTO,
.dev = {
.platform_data = &bcm43xx_vmmc,
},
};
static int __init bcm43xx_regulator_register(void)
{
int ret;
bcm43xx_vmmc.gpio = get_gpio_by_name(WLAN_SFI_GPIO_ENABLE_NAME);
ret = platform_device_register(&bcm43xx_vmmc_regulator);
if (ret) {
pr_err("%s: vmmc regulator register failed\n", __func__);
return ret;
}
return 0;
}
static void __init *bcm43xx_platform_data(void *info)
{
int ret;
ret = bcm43xx_regulator_register();
if (ret)
return NULL;
pr_info("Using generic wifi platform data\n");
/* For now it's empty */
return NULL;
}
static const struct devs_id bcm43xx_clk_vmmc_dev_id __initconst = {
.name = "bcm43xx_clk_vmmc",
.type = SFI_DEV_TYPE_SD,
.get_platform_data = &bcm43xx_platform_data,
};
sfi_device(bcm43xx_clk_vmmc_dev_id);
|
brianmckenna/thredds
|
bufr/src/main/java/ucar/nc2/iosp/bufr/MessageCompressedDataReader.java
|
/*
* Copyright 1998-2013 University Corporation for Atmospheric Research/Unidata
*
* Portions of this software were developed by the Unidata Program at the
* University Corporation for Atmospheric Research.
*
* Access and use of this software shall impose the following obligations
* and understandings on the user. The user is granted the right, without
* any fee or cost, to use, copy, modify, alter, enhance and distribute
* this software, and any derivative works thereof, and its supporting
* documentation for any purpose whatsoever, provided that this entire
* notice appears in all copies of the software, derivative works and
* supporting documentation. Further, UCAR requests that the user credit
* UCAR/Unidata in any publications that result from the use of this
* software or in any product that includes this software. The names UCAR
* and/or Unidata, however, may not be used in any advertising or publicity
* to endorse or promote any products or commercial entity unless specific
* written permission is obtained from UCAR/Unidata. The user also
* understands that UCAR/Unidata is not obligated to provide the user with
* any support, consulting, training or assistance of any kind with regard
* to the use, operation and performance of this software nor to provide
* the user with any updates, revisions, new versions or "bug fixes."
*
* THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "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 UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package ucar.nc2.iosp.bufr;
import ucar.ma2.*;
import ucar.nc2.Structure;
import ucar.nc2.Sequence;
import ucar.nc2.constants.CDM;
import ucar.nc2.iosp.BitReader;
import ucar.unidata.io.RandomAccessFile;
import java.io.IOException;
import java.util.Formatter;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
/**
* Reads through the data of a message.
* Can count bits / transfer all or some data to an Array.
*
* @author caron
* @since Nov 15, 2009
*/
/*
Within one message there are n obs (datasets) and s fields in each dataset.
For compressed datasets, storage order is data(fld, obs) (obs varying fastest) :
Ro1, NBINC1, I11, I12, . . . I1n
Ro2, NBINC2, I21, I22, . . . I2n
...
Ros, NBINCs, Is1, Is2, . . . Isn
where Ro1, Ro2, . . . Ros are local reference values (number of bits as Table B) for field i.
NBINC1 . . . NBINCs contain, as 6-bit quantities, the number of bits occupied by the increments that follow.
If NBINC1 = 0, all values of element I are equal to Ro1; in such cases, the increments shall be omitted.
For character data, NBINC shall contain the number of octets occupied by the character element.
However, if the character data in all subsets are identical NBINC=0.
Iij is the increment for the ith field and the jth obs.
A replicated field (structure) takes a group of fields and replicates them.
Let C be the entire compressed block for the ith field, as above.
Ci = Roi, NBINCi, Ii1, Ii2, . . . Iin
data:
C1, (C2, C3)*r, ... Cs
where r is set in the data descriptor, and is the same for all datasets.
A delayed replicated field (sequence) takes a group of fields and replicates them, with the number of replications
in the data :
C1, dr, 6bits, (C2, C3)*dr, ... Cs
where the width (nbits) of dr is set in the data descriptor. This dr must be the same for each dataset in the message.
For some reason there is an extra 6 bits after the dr. My guess its a programming mistake that is now needed.
There is no description of this case in the spec or the guide.
--------------------------
We use an ArrayStructureMA to hold the data, and fill it sequentially as we scan the message.
Each field is held in an Array stored in the member.getDataArray().
An iterator is stored in member.getDataObject() which keeps track of where we are.
For fixed length nested Structures, we need fld(dataset, inner) but we have fld(inner, dataset) se we transpose the dimensions
before we set the iterator.
For Sequences, inner.length is the same for all datasets in the message. However, it may vary across messages. However, we
only iterate over the inner sequence, never across all messages. So the implementation can be specific to the meassage.
*/
public class MessageCompressedDataReader {
/**
* Read all datasets from a single message
* @param s outer variables
* @param proto prototype message, has been processed
* @param m read this message
* @param raf from this file
* @param f output bit count debugging info (may be null)
* @return ArrayStructure with all the data from the message in it.
* @throws IOException on read error
*/
public ArrayStructure readEntireMessage(Structure s, Message proto, Message m, RandomAccessFile raf, Formatter f) throws IOException {
// transfer info (refersTo, name) from the proto message
DataDescriptor.transferInfo(proto.getRootDataDescriptor().getSubKeys(), m.getRootDataDescriptor().getSubKeys());
// allocate ArrayStructureMA for outer structure
int n = m.getNumberDatasets();
ArrayStructureMA ama = ArrayStructureMA.factoryMA(s, new int[] {n});
setIterators(ama);
// map dkey to Member recursively
HashMap<DataDescriptor, StructureMembers.Member> map = new HashMap<>(100);
associateMessage2Members(ama.getStructureMembers(), m.getRootDataDescriptor(), map);
readData(m, raf, f, new Request(ama, map, null));
return ama;
}
/**
* Read some or all datasets from a single message
*
* @param ama place data into here in order (may be null). iterators must be already set.
* @param m read this message
* @param raf from this file
* @param r which datasets, reletive to this message. null == all.
* @param f output bit count debugging info (may be null)
* @throws IOException on read error
*/
public void readData(ArrayStructureMA ama, Message m, RandomAccessFile raf, Range r, Formatter f) throws IOException {
// map dkey to Member recursively
HashMap<DataDescriptor, StructureMembers.Member> map = null;
if (ama != null) {
map = new HashMap<>(2*ama.getMembers().size());
associateMessage2Members(ama.getStructureMembers(), m.getRootDataDescriptor(), map);
}
readData(m, raf, f, new Request(ama, map, r));
}
// manage the request
private static class Request {
ArrayStructureMA ama; // data goes here, may be null
HashMap<DataDescriptor, StructureMembers.Member> map; // map of DataDescriptor to members of ama, may be null
Range r; // requested range
DpiTracker dpiTracker; // may be null
int outerRow; // if inner process needs to know what row its on
Request(ArrayStructureMA ama, HashMap<DataDescriptor, StructureMembers.Member> map, Range r) {
this.ama = ama;
this.map = map;
this.r = r;
}
boolean wantRow(int row) {
if (ama == null) return false;
if (r == null) return true;
return r.contains(row);
}
}
// An iterator is stored in member.getDataObject() which keeps track of where we are.
// For fixed length nested Structures, we need fld(dataset, inner1, inner2, ...) but we have fld(inner1, inner2, ... , dataset)
// so we permute the dimensions
// before we set the iterator.
public static void setIterators(ArrayStructureMA ama) {
StructureMembers sms = ama.getStructureMembers();
for (StructureMembers.Member sm : sms.getMembers()) {
//System.out.printf("doin %s%n", sm.getName());
//if (sm.getName().startsWith("first"))
// System.out.println("HEY");
Array data = sm.getDataArray();
if (data instanceof ArrayStructureMA) {
setIterators( (ArrayStructureMA) data);
} else {
int[] shape = data.getShape();
if ((shape.length > 1) && (sm.getDataType() != DataType.CHAR)) {
Array datap;
if (shape.length == 2)
datap = data.transpose(0, 1);
else {
int[] pdims = new int[shape.length]; // (0,1,2,3...) -> (1,2,3...,0)
for (int i=0; i< shape.length-1; i++) pdims[i] = i+1;
datap = data.permute( pdims);
}
sm.setDataObject(datap.getIndexIterator());
} else {
sm.setDataObject(data.getIndexIterator());
}
}
}
}
private void associateMessage2Members(StructureMembers members, DataDescriptor parent, HashMap<DataDescriptor, StructureMembers.Member> map) throws IOException {
for (DataDescriptor dkey : parent.getSubKeys()) {
if (dkey.name == null) {
//System.out.printf("ass skip %s%n", dkey);
if (dkey.getSubKeys() != null)
associateMessage2Members(members, dkey, map);
continue;
}
//System.out.printf("ass %s%n", dkey.name);
StructureMembers.Member m = members.findMember(dkey.name);
if (m != null) {
map.put(dkey, m);
if (m.getDataType() == DataType.STRUCTURE) {
ArrayStructure nested = (ArrayStructure) m.getDataArray();
if (dkey.getSubKeys() != null)
associateMessage2Members(nested.getStructureMembers(), dkey, map);
}
} else {
// System.out.printf("Cant find %s%n", dkey);
if (dkey.getSubKeys() != null)
associateMessage2Members(members, dkey, map);
}
}
}
// read / count the bits in a compressed message
private int readData(Message m, RandomAccessFile raf, Formatter f, Request req) throws IOException {
BitReader reader = new BitReader(raf, m.dataSection.getDataPos() + 4);
DataDescriptor root = m.getRootDataDescriptor();
if (root.isBad) return 0;
DebugOut out = (f == null) ? null : new DebugOut(f);
BitCounterCompressed[] counterFlds = new BitCounterCompressed[root.subKeys.size()]; // one for each field LOOK why not m.counterFlds ?
readData(out, reader, counterFlds, root, 0, m.getNumberDatasets(), req);
m.msg_nbits = 0;
for (BitCounterCompressed counter : counterFlds)
if (counter != null) m.msg_nbits += counter.getTotalBits();
return m.msg_nbits;
}
/**
*
* @param out debug info; may be null
* @param reader raf wrapper for bit reading
* @param fldCounters one for each field
* @param parent parent.subkeys() holds the fields
* @param bitOffset bit offset from beginning of data
* @param ndatasets number of compressed datasets
* @param req for writing into the ArrayStructure;
* @return bitOffset
* @throws IOException on read error
*/
private int readData(DebugOut out, BitReader reader, BitCounterCompressed[] fldCounters, DataDescriptor parent, int bitOffset,
int ndatasets, Request req) throws IOException {
List<DataDescriptor> flds = parent.getSubKeys();
for (int fldidx = 0; fldidx < flds.size(); fldidx++) {
DataDescriptor dkey = flds.get(fldidx);
if (!dkey.isOkForVariable()) { // dds with no data to read
// the dpi nightmare
if ((dkey.f == 2) && (dkey.x == 36)) {
req.dpiTracker = new DpiTracker( dkey.dpi, dkey.dpi.getNfields());
//System.out.printf("HEY gotta dpiTracker %n");
}
if (out != null) out.f.format("%s %d %s (%s) %n", out.indent(), out.fldno++, dkey.name, dkey.getFxyName());
// System.out.printf("HEY skipping %s %n", dkey);
continue;
}
BitCounterCompressed counter = new BitCounterCompressed(dkey, ndatasets, bitOffset);
fldCounters[fldidx] = counter;
// sequence
if (dkey.replication == 0) {
reader.setBitOffset(bitOffset);
int count = (int) reader.bits2UInt(dkey.replicationCountSize);
bitOffset += dkey.replicationCountSize;
reader.bits2UInt(6);
// System.out.printf("EXTRA bits %d at %d %n", extra, bitOffset);
if (null != out)
out.f.format("%s--sequence %s bitOffset=%d replication=%s %n", out.indent(), dkey.getFxyName(), bitOffset, count);
bitOffset += 6; // LOOK seems to be an extra 6 bits.
counter.addNestedCounters(count);
// make an ArrayObject of ArraySequence, place it into the data array
bitOffset = makeArraySequenceCompressed(out, reader, counter, dkey, bitOffset, ndatasets, count, req);
// if (null != out) out.f.format("--back %s %d %n", dkey.getFxyName(), bitOffset);
continue;
}
// structure
if (dkey.type == 3) {
if (null != out)
out.f.format("%s--structure %s bitOffset=%d replication=%s %n", out.indent(), dkey.getFxyName(), bitOffset, dkey.replication);
// p 11 of "standard", doesnt really describe the case of replication AND compression
counter.addNestedCounters(dkey.replication);
for (int i = 0; i < dkey.replication; i++) {
BitCounterCompressed[] nested = counter.getNestedCounters(i);
req.outerRow = i;
if (null != out) {
out.f.format("%n");
out.indent.incr();
bitOffset = readData(out, reader, nested, dkey, bitOffset, ndatasets, req);
out.indent.decr();
} else {
bitOffset = readData(null, reader, nested, dkey, bitOffset, ndatasets, req);
}
}
//if (null != out) out.f.format("--back %s %d %n", dkey.getFxyName(), bitOffset);
continue;
}
// all other fields
StructureMembers.Member member;
IndexIterator iter = null;
ArrayStructure dataDpi = null; // if iter is missing - for the dpi case
if (req.map != null) {
member = req.map.get(dkey);
iter = (IndexIterator) member.getDataObject();
if (iter == null) {
//System.out.printf("HEY missing iter %s%n", dkey);
dataDpi = (ArrayStructure) member.getDataArray();
}
}
reader.setBitOffset(bitOffset); // ?? needed ??
// char data special case
if (dkey.type == 1) {
int nc = dkey.bitWidth / 8;
byte[] minValue = new byte[nc];
for (int i = 0; i < nc; i++)
minValue[i] = (byte) reader.bits2UInt(8);
int dataWidth = (int) reader.bits2UInt(6); // incremental data width in bytes
counter.setDataWidth(8*dataWidth);
int totalWidth = dkey.bitWidth + 6 + 8*dataWidth * ndatasets; // total width in bits for this compressed set of values
bitOffset += totalWidth; // bitOffset now points to the next field
if (null != out)
out.f.format("%s read %d %s (%s) bitWidth=%d defValue=%s dataWidth=%d n=%d bitOffset=%d %n",
out.indent(), out.fldno++, dkey.name, dkey.getFxyName(), dkey.bitWidth, new String(minValue, CDM.utf8Charset), dataWidth, ndatasets, bitOffset);
for (int dataset = 0; dataset < ndatasets; dataset++) {
if (dataWidth == 0) { // use the min value
if (req.wantRow(dataset))
for (int i = 0; i < nc; i++)
iter.setCharNext((char) minValue[i]); // ??
} else { // read the incremental value
int nt = Math.min(nc, dataWidth);
byte[] incValue = new byte[nc];
for (int i = 0; i < nt; i++)
incValue[i] = (byte) reader.bits2UInt(8);
for (int i = nt; i < nc; i++) // can dataWidth < n ?
incValue[i] = 0;
if (req.wantRow(dataset))
for (int i = 0; i < nc; i++) {
int cval = incValue[i];
if (cval < 32 || cval > 126) cval = 0; // printable ascii KLUDGE!
iter.setCharNext((char) cval); // ??
}
if (out != null) out.f.format(" %s,", new String(incValue, CDM.utf8Charset));
}
}
if (out != null) out.f.format("%n");
continue;
}
// numeric fields
int useBitWidth = dkey.bitWidth;
// a dpi Field needs to be substituted
boolean isDpi = ((dkey.f == 0) && (dkey.x == 31) && (dkey.y == 31));
boolean isDpiField = false;
if ((dkey.f == 2) && (dkey.x == 24) && (dkey.y == 255)) {
isDpiField = true;
DataDescriptor dpiDD = req.dpiTracker.getDpiDD(req.outerRow);
useBitWidth = dpiDD.bitWidth;
//System.out.printf("HEY gotta dpiField bitWidth=%d %n", useBitWidth);
}
long dataMin = reader.bits2UInt(useBitWidth);
int dataWidth = (int) reader.bits2UInt(6); // increment data width - always in 6 bits, so max is 2^6 = 64
if (dataWidth > useBitWidth && (null != out))
out.f.format(" BAD WIDTH ");
if (dkey.type == 1) dataWidth *= 8; // char data count is in bytes
counter.setDataWidth(dataWidth);
int totalWidth = useBitWidth + 6 + dataWidth * ndatasets; // total width in bits for this compressed set of values
bitOffset += totalWidth; // bitOffset now points to the next field
if (null != out)
out.f.format("%s read %d, %s (%s) bitWidth=%d dataMin=%d (%f) dataWidth=%d n=%d bitOffset=%d %n",
out.indent(), out.fldno++, dkey.name, dkey.getFxyName(), useBitWidth, dataMin, dkey.convert(dataMin), dataWidth, ndatasets, bitOffset);
// numeric fields
// if dataWidth == 0, just use min value, otherwise read the compressed value here
for (int dataset = 0; dataset < ndatasets; dataset++) {
long value = dataMin;
if (dataWidth > 0) {
long cv = reader.bits2UInt(dataWidth);
if ( BufrNumbers.isMissing(cv, dataWidth))
value = BufrNumbers.missingValue(useBitWidth); // set to missing value
else // add to minimum
value += cv;
}
// workaround for malformed messages
if (dataWidth > useBitWidth) {
long missingVal = BufrNumbers.missingValue(useBitWidth);
if ((value & missingVal) != value) // overflow
value = missingVal; // replace with missing value
}
if (req.wantRow(dataset)) {
if (isDpiField) {
DataDescriptor dpiDD = req.dpiTracker.getDpiDD(req.outerRow);
StructureMembers sms = dataDpi.getStructureMembers();
StructureMembers.Member m0 = sms.getMember(0);
IndexIterator iter2 = (IndexIterator) m0.getDataObject();
iter2.setObjectNext(dpiDD.getName());
StructureMembers.Member m1 = sms.getMember(1);
iter2 = (IndexIterator) m1.getDataObject();
iter2.setFloatNext(dpiDD.convert( value));
} else {
iter.setLongNext(value);
}
}
// since dpi must be the same for all datasets, just keep the first one
if (isDpi && (dataset == 0))
req.dpiTracker.setDpiValue(req.outerRow, value); // keep track of dpi values in the tracker - perhaps not expose
if ((out != null) && (dataWidth > 0)) out.f.format(" %d (%f)", value, dkey.convert(value));
}
if (out != null) out.f.format("%n");
}
return bitOffset;
}
// read in the data into an ArrayStructureMA, holding an ArrayObject() of ArraySequence
private int makeArraySequenceCompressed(DebugOut out, BitReader reader, BitCounterCompressed bitCounterNested, DataDescriptor seqdd,
int bitOffset, int ndatasets, int count, Request req) throws IOException {
// construct ArrayStructureMA and associated map
ArrayStructureMA ama = null;
StructureMembers members = null;
HashMap<DataDescriptor, StructureMembers.Member> nmap = null;
if (req.map != null) {
Sequence seq = (Sequence) seqdd.refersTo;
int[] shape = new int[]{ndatasets, count}; // seems unlikely this can handle recursion
ama = ArrayStructureMA.factoryMA(seq, shape);
setIterators(ama);
members = ama.getStructureMembers();
nmap = new HashMap<>(2*members.getMembers().size());
associateMessage2Members(members, seqdd, nmap);
}
Request nreq = new Request(ama, nmap, req.r);
// iterate over the number of replications, reading ndataset compressed values at each iteration
if (out != null) out.indent.incr();
for (int i = 0; i < count; i++) {
BitCounterCompressed[] nested = bitCounterNested.getNestedCounters(i);
nreq.outerRow = i;
bitOffset = readData(out, reader, nested, seqdd, bitOffset, ndatasets, nreq);
}
if (out != null) out.indent.decr();
// add ArraySequence to the ArrayObject in the outer structure
if (req.map != null) {
StructureMembers.Member m = req.map.get(seqdd);
ArrayObject arrObj = (ArrayObject) m.getDataArray();
// we need to break ama into separate sequences, one for each dataset
int start = 0;
for (int i = 0; i < ndatasets; i++) {
ArraySequence arrSeq = new ArraySequence(members, new SequenceIterator(start, count, ama), count);
arrObj.setObject(i, arrSeq);
start += count;
}
}
return bitOffset;
}
private static class DpiTracker {
DataDescriptorTreeConstructor.DataPresentIndicator dpi;
boolean[] isPresent;
List<DataDescriptor> dpiDD = null;
DpiTracker(DataDescriptorTreeConstructor.DataPresentIndicator dpi, int nPresentFlags) {
this.dpi = dpi;
isPresent = new boolean[nPresentFlags];
}
void setDpiValue(int fldidx, long value) {
isPresent[fldidx] = (value == 0); // present if the value is zero
}
DataDescriptor getDpiDD(int fldPresentIndex) {
if (dpiDD == null) {
dpiDD = new ArrayList<>();
for (int i=0; i<isPresent.length; i++) {
if (isPresent[i])
dpiDD.add(dpi.linear.get(i));
}
}
return dpiDD.get(fldPresentIndex);
}
boolean isDpiDDs(DataDescriptor dkey) {
return (dkey.f == 2) && (dkey.x == 24) && (dkey.y == 255);
}
boolean isDpiField(DataDescriptor dkey) {
return (dkey.f == 2) && (dkey.x == 24) && (dkey.y == 255);
}
}
}
|
lesaint/experimenting-annotation-processing
|
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_5288.java
|
<gh_stars>1-10
package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_5288 {
}
|
karthik-git-user/SAP-Stage
|
core-customize/hybris/bin/modules/integration-apis/outboundsync/src/de/hybris/platform/outboundsync/RootItemChannelCorrelationStrategy.java
|
<reponame>karthik-git-user/SAP-Stage<gh_stars>0
/*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package de.hybris.platform.outboundsync;
import de.hybris.platform.outboundsync.dto.OutboundItemDTO;
import com.google.common.base.Preconditions;
/**
* Defines a correlation strategy to be used when aggregating {@link OutboundItemDTO}s.
* It takes into account the root item PK and the channel configuration PK.
*/
public class RootItemChannelCorrelationStrategy
{
public String correlationKey(final OutboundItemDTO dto)
{
Preconditions.checkArgument(dto != null, "Cannot create correlation key with a null OutboundItemDTO");
return String.format("%d-%d", dto.getRootItemPK(), dto.getChannelConfigurationPK());
}
}
|
jezhiggins/stiX
|
c++/lib/file_open.cpp
|
#include "file_open.hpp"
#include <filesystem>
namespace fs = std::filesystem;
namespace stiX {
std::ifstream file_opener(std::string const& filename) {
return std::ifstream(filename);
} // file_opener
std::ofstream file_write_opener(std::string const& filename) {
auto path = fs::path(filename);
auto parent = path.parent_path();
if (!parent.empty())
fs::create_directories(path.parent_path());
return std::ofstream(path);
} // file_write_opener
}
|
TheStanfordDaily/loris-archives
|
data_science/apps/devise/app/static/javascript.js
|
function display_images(query, n='12') {
document.getElementById('images').innerHTML = '';
image_div = document.getElementById('images');
const query_url = '/devise/search?query='.concat(query.toLowerCase()).concat('&n=').concat(n);
fetch(query_url)
.then((resp) => resp.json())
.then(function (data) {
let image_urls = data.response;
return image_urls.map(function (image_url) {
outer_div = document.createElement('div')
outer_div.className = 'fl w-100 w-50-m w-25-ns pa3-ns';
inner_div = document.createElement('div')
inner_div.className = 'aspect-ratio aspect-ratio--1x1';
img = document.createElement('img')
img.src = image_url;
img.className = 'db bg-center cover aspect-ratio--object';
inner_div.appendChild(img);
outer_div.appendChild(inner_div);
image_div.appendChild(outer_div);
})
})
.catch(function (error) {
console.log(error);
});
}
document.getElementById("query")
.addEventListener("keypress", function (event) {
event.preventDefault();
if (event.key === 'Enter') {
document.getElementById("search_button").click();
}
});
|
thisaripatabendi/carbon-device-mgt-plugins-parent
|
components/mobile-plugins/mobile-base-plugin/org.wso2.carbon.device.mgt.mobile/src/main/java/org/wso2/carbon/device/mgt/mobile/config/MobileDeviceConfigurationManager.java
|
<gh_stars>0
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.mobile.config;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.mobile.util.MobileDeviceManagementUtil;
import org.wso2.carbon.device.mgt.mobile.config.datasource.MobileDataSourceConfig;
import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.File;
/**
* Class responsible for the mobile device manager configuration initialization.
*/
public class MobileDeviceConfigurationManager {
private static final String MOBILE_DEVICE_CONFIG_XML_NAME = "mobile-config.xml";
private static final String MOBILE_DEVICE_PLUGIN_DIRECTORY = "mobile";
private static final String DEVICE_MGT_PLUGIN_CONFIGS_DIRECTORY = "device-mgt-plugin-configs";
private MobileDeviceManagementConfig currentMobileDeviceConfig;
private static MobileDeviceConfigurationManager mobileDeviceConfigManager;
private final String mobileDeviceMgtConfigXMLPath =
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator +
DEVICE_MGT_PLUGIN_CONFIGS_DIRECTORY +
File.separator +
MOBILE_DEVICE_PLUGIN_DIRECTORY + File.separator + MOBILE_DEVICE_CONFIG_XML_NAME;
public static MobileDeviceConfigurationManager getInstance() {
if (mobileDeviceConfigManager == null) {
synchronized (MobileDeviceConfigurationManager.class) {
if (mobileDeviceConfigManager == null) {
mobileDeviceConfigManager = new MobileDeviceConfigurationManager();
}
}
}
return mobileDeviceConfigManager;
}
public synchronized void initConfig() throws DeviceManagementException {
try {
File mobileDeviceMgtConfig = new File(mobileDeviceMgtConfigXMLPath);
Document doc = MobileDeviceManagementUtil.convertToDocument(mobileDeviceMgtConfig);
JAXBContext mobileDeviceMgmtContext =
JAXBContext.newInstance(MobileDeviceManagementConfig.class);
Unmarshaller unmarshaller = mobileDeviceMgmtContext.createUnmarshaller();
this.currentMobileDeviceConfig =
(MobileDeviceManagementConfig) unmarshaller.unmarshal(doc);
} catch (Exception e) {
throw new DeviceManagementException(
"Error occurred while initializing Mobile Device Management config", e);
}
}
public MobileDeviceManagementConfig getMobileDeviceManagementConfig() {
return currentMobileDeviceConfig;
}
}
|
puyoai/puyoai
|
src/core/bit_field.h
|
<filename>src/core/bit_field.h
#ifndef CORE_BIT_FIELD_H_
#define CORE_BIT_FIELD_H_
#include <string>
#include <glog/logging.h>
#include "base/base.h"
#include "base/sse.h"
#include "core/field_bits.h"
#include "core/frame.h"
#include "core/puyo_color.h"
#include "core/rensa_result.h"
#include "core/rensa_tracker.h"
#include "core/score.h"
class PlainField;
struct Position;
// BitsField is a field implementation that uses FieldBits.
class BitField {
public:
struct SimulationContext {
explicit SimulationContext(int currentChain = 1) : currentChain(currentChain) {}
int currentChain = 1;
};
BitField();
explicit BitField(const PlainField&);
explicit BitField(const std::string&);
FieldBits bits(PuyoColor c) const;
FieldBits normalColorBits() const { return m_[2]; }
FieldBits field13Bits() const { return (m_[0] | m_[1] | m_[2]).maskedField13(); }
FieldBits differentBits(const BitField& bf) const {
return (m_[0] ^ bf.m_[0]) | (m_[1] ^ bf.m_[1]) | (m_[2] ^ bf.m_[2]);
}
PuyoColor color(int x, int y) const;
bool isColor(int x, int y, PuyoColor c) const { return bits(c).get(x, y); }
bool isNormalColor(int x, int y) const { return m_[2].get(x, y); }
bool isEmpty(int x, int y) const { return !(m_[0] | m_[1] | m_[2]).get(x, y); }
void setColor(int x, int y, PuyoColor c);
void setColorAll(FieldBits, PuyoColor);
void setColorAllIfEmpty(FieldBits, PuyoColor);
bool isZenkeshi() const { return FieldBits(m_[0] | m_[1] | m_[2]).maskedField13().isEmpty(); }
bool isConnectedPuyo(int x, int y) const { return isConnectedPuyo(x, y, color(x, y)); }
bool isConnectedPuyo(int x, int y, PuyoColor c) const;
int countConnectedPuyos(int x, int y) const { return countConnectedPuyos(x, y, color(x, y)); }
int countConnectedPuyos(int x, int y, PuyoColor c) const;
int countConnectedPuyos(int x, int y, FieldBits* checked) const { return countConnectedPuyos(x, y, color(x, y), checked); }
int countConnectedPuyos(int x, int y, PuyoColor c, FieldBits* checked) const;
int countConnectedPuyosMax4(int x, int y) const { return countConnectedPuyosMax4(x, y, color(x, y)); }
int countConnectedPuyosMax4(int x, int y, PuyoColor c) const;
bool hasEmptyNeighbor(int x, int y) const;
void countConnection(int* count2, int* count3) const;
// Returns true if there are floating puyos.
bool hasFloatingPuyo() const;
RensaResult simulate(int initialChain = 1);
template<typename Tracker> NOINLINE_UNLESS_RELEASE RensaResult simulate(SimulationContext*, Tracker*);
// Faster version of simulate(). Returns the number of chains.
template<typename Tracker> int simulateFast(Tracker*);
// Vanishes the connected puyos, and drop the puyos in the air. Score will be returned.
template<typename Tracker> NOINLINE_UNLESS_RELEASE RensaStepResult vanishDrop(SimulationContext*, Tracker*);
template<typename Tracker> bool vanishDropFast(SimulationContext*, Tracker*);
// Caution: heights must be aligned to 16.
void calculateHeight(int heights[FieldConstant::MAP_WIDTH]) const;
std::string toString(char charIfEmpty = ' ') const;
std::string toDebugString(char charIfEmpty = ' ') const;
bool rensaWillOccur() const;
// TODO(mayah): This should be removed. This is for barkward compatibility.
Position* fillSameColorPosition(int x, int y, PuyoColor c, Position* positionQueueHead, FieldBits* checked) const;
// TODO(mayah): This should be removed. This is for backward compatibility.
int fillErasingPuyoPositions(Position* eraseQueue) const;
FieldBits ignitionPuyoBits() const;
size_t hash() const;
friend bool operator==(const BitField&, const BitField&);
friend std::ostream& operator<<(std::ostream&, const BitField&);
#if defined(__AVX2__) && defined(__BMI2__)
// Faster version of simulate() that uses AVX2 instruction set.
template<typename Tracker> RensaResult NOINLINE_UNLESS_RELEASE simulateAVX2(SimulationContext*, Tracker*);
template<typename Tracker> int simulateFastAVX2(Tracker*);
template<typename Tracker> RensaStepResult NOINLINE_UNLESS_RELEASE vanishDropAVX2(SimulationContext*, Tracker*);
template<typename Tracker> bool vanishDropFastAVX2(SimulationContext*, Tracker*);
#endif
private:
BitField escapeInvisible();
void recoverInvisible(const BitField&);
// Vanishes puyos. Returns score. Erased puyos are put |erased|.
// Actually puyo won't be vanished in this method, though...
template<typename Tracker>
int vanish(int currentChain, FieldBits* erased, Tracker* tracker) const;
// Vanishes puyos. Returns true if something will be erased.
template<typename Tracker>
bool vanishFast(int currentChain, FieldBits* erased, Tracker* tracker) const;
// Drops puyos. Returns max drops.
template<typename Tracker>
int dropAfterVanish(FieldBits erased, Tracker* tracker);
template<typename Tracker>
void dropAfterVanishFast(FieldBits erased, Tracker* tracker);
#if defined(__AVX2__) && defined(__BMI2__)
template<typename Tracker>
int vanishAVX2(int currentChain, FieldBits* erased, Tracker* tracker) const;
template<typename Tracker>
bool vanishFastAVX2(int currentChain, FieldBits* erased, Tracker* tracker) const;
template<typename Tracker>
int dropAfterVanishAVX2(FieldBits erased, Tracker* tracker);
template<typename Tracker>
void dropAfterVanishFastAVX2(FieldBits erased, Tracker* tracker);
#endif
FieldBits m_[3];
};
inline
FieldBits BitField::bits(PuyoColor c) const
{
const __m128i zero = _mm_setzero_si128();
switch (c) {
case PuyoColor::EMPTY: // = 0 000
return (m_[0] | m_[1] | m_[2]) ^ _mm_cmpeq_epi8(zero, zero);
case PuyoColor::OJAMA: // = 1 001
return FieldBits(_mm_andnot_si128(m_[2].xmm(), _mm_andnot_si128(m_[1].xmm(), m_[0].xmm())));
case PuyoColor::WALL: // = 2 010
return FieldBits(_mm_andnot_si128(m_[2].xmm(), _mm_andnot_si128(m_[0].xmm(), m_[1].xmm())));
case PuyoColor::IRON: // = 3 011
return FieldBits(_mm_andnot_si128(m_[2].xmm(), _mm_and_si128(m_[1].xmm(), m_[0].xmm())));
case PuyoColor::RED: // = 4 100
return FieldBits(_mm_andnot_si128(m_[0].xmm(), _mm_andnot_si128(m_[1].xmm(), m_[2].xmm())));
case PuyoColor::BLUE: // = 5 101
return FieldBits(_mm_and_si128(m_[0].xmm(), _mm_andnot_si128(m_[1].xmm(), m_[2].xmm())));
case PuyoColor::YELLOW: // = 6 110
return FieldBits(_mm_andnot_si128(m_[0].xmm(), _mm_and_si128(m_[1].xmm(), m_[2].xmm())));
case PuyoColor::GREEN: // = 7 111
return FieldBits(_mm_and_si128(m_[0].xmm(), _mm_and_si128(m_[1].xmm(), m_[2].xmm())));
}
CHECK(false);
return FieldBits();
}
inline
BitField BitField::escapeInvisible()
{
BitField escaped;
for (int i = 0; i < 3; ++i) {
escaped.m_[i] = m_[i].notmask(FieldBits::FIELD_MASK_13);
m_[i] = m_[i].mask(FieldBits::FIELD_MASK_13);
}
return escaped;
}
inline
void BitField::recoverInvisible(const BitField& bf)
{
for (int i = 0; i < 3; ++i) {
m_[i].setAll(bf.m_[i]);
}
}
inline
PuyoColor BitField::color(int x, int y) const
{
int b0 = m_[0].get(x, y) ? 1 : 0;
int b1 = m_[1].get(x, y) ? 2 : 0;
int b2 = m_[2].get(x, y) ? 4 : 0;
return static_cast<PuyoColor>(b0 | b1 | b2);
}
inline
void BitField::setColor(int x, int y, PuyoColor c)
{
int cc = static_cast<int>(c);
for (int i = 0; i < 3; ++i) {
if (cc & (1 << i))
m_[i].set(x, y);
else
m_[i].unset(x, y);
}
}
inline
RensaResult BitField::simulate(int initialChain)
{
RensaNonTracker tracker;
SimulationContext context(initialChain);
return simulate(&context, &tracker);
}
inline
void BitField::setColorAll(FieldBits bits, PuyoColor c)
{
for (int i = 0; i < 3; ++i) {
if (static_cast<int>(c) & (1 << i)) {
m_[i].setAll(bits);
} else {
m_[i].unsetAll(bits);
}
}
}
inline
void BitField::setColorAllIfEmpty(FieldBits bits, PuyoColor c)
{
FieldBits nonEmpty = (m_[0] | m_[1] | m_[2]);
bits = bits.notmask(nonEmpty);
setColorAll(bits, c);
}
inline
bool BitField::isConnectedPuyo(int x, int y, PuyoColor c) const
{
DCHECK_EQ(c, color(x, y));
if (y > FieldConstant::HEIGHT)
return false;
FieldBits colorBits = bits(c).maskedField12();
FieldBits single(x, y);
return !single.expandEdge().mask(colorBits).notmask(single).isEmpty();
}
inline
int BitField::countConnectedPuyos(int x, int y, PuyoColor c) const
{
DCHECK_EQ(c, color(x, y));
if (y > FieldConstant::HEIGHT)
return 0;
FieldBits colorBits = bits(c).maskedField12();
return FieldBits(x, y).expand(colorBits).popcount();
}
inline
int BitField::countConnectedPuyos(int x, int y, PuyoColor c, FieldBits* checked) const
{
DCHECK_EQ(c, color(x, y));
if (y > FieldConstant::HEIGHT)
return false;
FieldBits colorBits = bits(c).maskedField12();
FieldBits connected = FieldBits(x, y).expand(colorBits);
checked->setAll(connected);
return connected.popcount();
}
inline
int BitField::countConnectedPuyosMax4(int x, int y, PuyoColor c) const
{
DCHECK_EQ(c, color(x, y));
if (y > FieldConstant::HEIGHT)
return false;
FieldBits colorBits = bits(c).maskedField12();
return FieldBits(x, y).expand4(colorBits).popcount();
}
inline
void BitField::calculateHeight(int heights[FieldConstant::MAP_WIDTH]) const
{
const __m128i zero = _mm_setzero_si128();
__m128i whole = (m_[0] | m_[1] | m_[2]).maskedField13();
__m128i count = sse::mm_popcnt_epi16(whole);
_mm_store_si128(reinterpret_cast<__m128i*>(heights), _mm_unpacklo_epi16(count, zero));
_mm_store_si128(reinterpret_cast<__m128i*>(heights + 4), _mm_unpackhi_epi16(count, zero));
}
namespace std {
template<>
struct hash<BitField>
{
size_t operator()(const BitField& bf) const
{
return bf.hash();
}
};
}
#include "bit_field_inl.h"
#if defined(__AVX2__) && defined(__BMI2__)
#include "bit_field_avx2_inl.h"
#endif
#endif // CORE_BIT_FIELD_H_
|
SjoerdKoop/vicon_control
|
robot_control/pru-cgt/lib/src/set_new.c
|
/******************************************************************************
* \ ___ / *
* / \ *
* Edison Design Group C++ Runtime - | \^/ | - *
* \ / *
* / | | \ *
* Copyright 1992-2017 Edison Design Group Inc. [_] *
* *
******************************************************************************/
/*
Redistribution and use in source and binary forms are permitted
provided that the above copyright notice and this paragraph are
duplicated in all source code forms. The name of Edison Design
Group, Inc. may not be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
Any use of this software is at the user's own risk.
*/
/*
set_new_handler routine to allow the user to affect the behavior of the
default operator new() when memory cannot be allocated.
*/
#include "basics.h"
#include "runtime.h"
#pragma hdrstop
#ifndef NULL
#define NULL 0
#endif /* ifndef NULL */
/*
If the runtime should be defined in the std namespace, open
the std namespace.
*/
#ifdef __EDG_RUNTIME_USES_NAMESPACES
namespace std {
#endif /* ifdef __EDG_RUNTIME_USES_NAMESPACES */
new_handler set_new_handler(new_handler handler) THROW_NOTHING()
/*
Set _new_handler to the new function pointer provided and return the
previous value of _new_handler.
*/
{
new_handler rr = _new_handler;
_new_handler = handler;
return rr;
} /* set_new_handler */
/*
If the runtime should be defined in the std namespace, close
the std namespace.
*/
#ifdef __EDG_RUNTIME_USES_NAMESPACES
} /* namespace std */
#endif /* ifdef __EDG_RUNTIME_USES_NAMESPACES */
/******************************************************************************
* \ ___ / *
* / \ *
* Edison Design Group C++ Runtime - | \^/ | - *
* \ / *
* / | | \ *
* Copyright 1992-2017 Edison Design Group Inc. [_] *
* *
******************************************************************************/
|
Benjoyo/distributed-tracing
|
tracingbackend/src/main/java/tracing/backend/scheduler/causal/CausalScheduler.java
|
package tracing.backend.scheduler.causal;
import tracing.backend.Target;
import tracing.backend.TraceQueue;
import tracing.backend.scheduler.EvictionService;
import tracing.backend.scheduler.QueueSpliterator;
import tracing.backend.scheduler.Scheduler;
import tracing.backend.trace.EventType;
import tracing.backend.trace.MessageEvent;
import tracing.backend.trace.TraceEvent;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Schedules an event order based on the causality of events, that is, following the happened-before relation.
*/
public class CausalScheduler implements Scheduler {
public static final int EVICTION_INTERVAL = 5000;
// all targets of the system
private Collection<Target> targets;
// maps message IDs to message events to remember send events
private final HashMap<String, MessageEvent> sendMsgMap = new HashMap<>();
// output queue
public final BlockingQueue<TraceEvent> resultQueue = new LinkedBlockingQueue<>();
// still running?
private boolean running = true;
// maps target IDs to input queues
private final Map<String, TraceQueue> queueMap = new HashMap<>();
// global sequence number assigned to events
private final AtomicLong globalSeq = new AtomicLong(0);
@Override
public void setTargets(Collection<Target> targets) {
this.targets = targets;
targets.forEach(target -> queueMap.put(target.getTargetId(), target.getTraceQueue()));
}
@Override
public void run() {
AtomicLong operations = new AtomicLong(0);
// while not stopped...
while (running) {
// try getting the oldest TraceEvent element from every trace, blocking if one trace is empty
var candidates = this.targets.stream()
.map(t -> t.getTraceQueue().blockingPeek())
.sorted(Comparator.comparing(TraceEvent::getLocalTimestamp)) // sort by local timestamps to get initial order
.collect(Collectors.toList());
// process candidates in order, breaking as soon as the first event can be processed
for (var event : candidates) {
if (event.getEventType() == EventType.SEND) {
var send = (MessageEvent) event;
// set vector clock
var clock = event.getTarget().incrementVectorClock();
event.setVectorClock(clock);
// add to send map to remember for receive event(s)
this.sendMsgMap.put(send.getMsgId(), send);
} else if (event.getEventType() == EventType.RECEIVE) {
var receiveMsg = (MessageEvent) event;
var msgId = receiveMsg.getMsgId();
var sendMsg = this.sendMsgMap.get(msgId);
if (sendMsg == null) {
System.out.println("no send event to this receive event");
continue; // don't process receive yet
}
// receive event depends on send event
event.setDependency(sendMsg.getGlobalEventId());
sendMsg.addParticipant(event.getTargetId()); // set sender
receiveMsg.addParticipant(sendMsg.getTargetId()); // add receiver
// set vector clock
var senderClock = sendMsg.getVectorClock();
var clock = event.getTarget().merge(senderClock);
event.setVectorClock(clock);
} else { // internal
// set vector clock
var clock = event.getTarget().incrementVectorClock();
event.setVectorClock(clock);
}
// remove processed event from input queue
this.queueMap.get(event.getTargetId()).remove();
// set global sequence number
event.setGlobalEventId(globalSeq.incrementAndGet());
// add to output
this.resultQueue.add(event);
// remember last event on target
event.getTarget().setLastTraceEvent(event);
if (operations.incrementAndGet() == EVICTION_INTERVAL) {
operations.set(0);
new EvictionService(targets, sendMsgMap).start();
}
// stop here, continue with next set of candidates
break;
}
}
}
public Thread start() {
var t = new Thread(this);
t.start();
return t;
}
@Override
public void stop() {
this.running = false;
}
/**
* Create result/output stream from queue.
* @return output stream
*/
@Override
public Stream<TraceEvent> resultStream() {
return StreamSupport.stream(new QueueSpliterator<>(resultQueue), false);
}
}
|
zenhack/bs
|
fs/dirent.go
|
package fs
import (
"context"
"os"
"time"
"github.com/pkg/errors"
"github.com/bobg/bs/anchor"
)
// IsDir tells whether d refers to a directory.
func (d *Dirent) IsDir() bool {
return os.FileMode(d.Mode).IsDir()
}
// Dir returns the directory referred to by d.
// It is an error to call this when !d.IsDir().
func (d *Dirent) Dir(ctx context.Context, g anchor.Getter, at time.Time) (*Dir, error) {
if !d.IsDir() {
return nil, errors.New("not a directory")
}
dref, err := g.GetAnchor(ctx, d.Item, at)
if err != nil {
return nil, errors.Wrapf(err, "getting anchor %s at %s", d.Item, at)
}
var dir Dir
err = dir.Load(ctx, g, dref)
return &dir, errors.Wrapf(err, "getting directory at %s", dref)
}
// IsLink tells whether d refers to a symlink.
// If it does, then d.Item is the target of the link.
func (d *Dirent) IsLink() bool {
return (d.Mode & uint32(os.ModeSymlink)) == uint32(os.ModeSymlink)
}
|
poppeman/Pictus
|
source/PictThumbs/codecsetup.cpp
|
#include "codecsetup.h"
#include "illa/codecmgr.h"
#include "illa/f_pcx.h"
#include "illa/f_tga.h"
#include "illa/f_wbmp.h"
#include "illa/f_psd.h"
#include "illa/f_psp.h"
#include "illa/f_tiff.h"
#include "illa/f_webp.h"
#include "illa/f_xyz.h"
void CodecManagerSetup(Img::CodecFactoryStore* cfs) {
// With the exception of JPEG, all built-in thumbnail providers are good.
// AddCodecFactory(new Img::FactoryBMP());
// AddCodecFactory(new Img::FactoryGIF());
// AddCodecFactory(new Img::FactoryJPEG());
// AddCodecFactory(new Img::FactoryPNG());
cfs->ReleaseFactories();
cfs->AddCodecFactory(new Img::FactoryPCX());
cfs->AddCodecFactory(new Img::FactoryTGA());
cfs->AddCodecFactory(new Img::FactoryWBMP());
cfs->AddCodecFactory(new Img::FactoryPSP());
// Still somewhat flaky, don't enable until it's awesome
//cfs->AddCodecFactory(new Img::FactoryTIFF());
cfs->AddCodecFactory(new Img::FactoryPSD());
cfs->AddCodecFactory(new Img::FactoryWebp());
cfs->AddCodecFactory(new Img::FactoryXYZ());
}
|
Andrewich/deadjustice
|
sgviewer/MainFrm.h
|
<reponame>Andrewich/deadjustice
// MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_MAINFRM_H__D53EDAE3_A166_11D5_BC88_0000B49545E8__INCLUDED_)
#define AFX_MAINFRM_H__D53EDAE3_A166_11D5_BC88_0000B49545E8__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <sg/Context.h>
class CMainFrame : public CFrameWnd
{
protected: // create from serialization only
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:
//{{AFX_MSG(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnDestroy();
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnEnterMenuLoop( BOOL );
afx_msg void OnExitMenuLoop( BOOL );
afx_msg void OnSysCommand( UINT nID, LPARAM lParam );
afx_msg void OnActivate( UINT state, CWnd* other, BOOL minimized );
afx_msg void OnKeyDown( UINT ch, UINT rep, UINT flags );
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MAINFRM_H__D53EDAE3_A166_11D5_BC88_0000B49545E8__INCLUDED_)
|
gcherian/reladomo
|
reladomo/src/main/java/com/gs/fw/common/mithra/list/CascadeInsertAllTransactionalCommand.java
|
<reponame>gcherian/reladomo
/*
Copyright 2016 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.gs.fw.common.mithra.list;
import com.gs.fw.common.mithra.MithraTransaction;
import com.gs.fw.common.mithra.MithraTransactionalObject;
import com.gs.fw.common.mithra.TransactionalCommand;
import java.util.List;
public class CascadeInsertAllTransactionalCommand implements TransactionalCommand
{
private List toBeInserted;
public CascadeInsertAllTransactionalCommand(List toBeInserted)
{
this.toBeInserted = toBeInserted;
}
public Object executeTransaction(MithraTransaction tx) throws Throwable
{
for(int i=0;i < toBeInserted.size();i++)
{
((MithraTransactionalObject)toBeInserted.get(i)).cascadeInsert();
}
return null;
}
}
|
leonlee/mde
|
entity-engine/src/main/java/org/blab/mde/ee/EntityEngine.java
|
package org.blab.mde.ee;
import org.blab.mde.core.CompositeEngine;
import org.blab.mde.core.CompositeEngineContext;
import org.blab.mde.core.CompositeEngineListener;
import org.blab.mde.ee.annotation.Aggregate;
import org.blab.mde.ee.annotation.Entity;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import static org.blab.mde.core.util.Guarder.requireTrue;
@Slf4j
public class EntityEngine implements CompositeEngineListener {
@Getter
private CompositeEngine compositeEngine;
@Override
public void afterStart(CompositeEngineContext context, CompositeEngine engine) {
compositeEngine = engine;
}
public <T> T createOf(Class<T> type) {
return compositeEngine.createOf(type);
}
public <T> T create(Class<?> type) {
return compositeEngine.create(type);
}
public <T> Class<T> typeOf(Class<T> originType) {
return compositeEngine.typeOf(originType);
}
public <T> Class<T> typeOf(String name) {
return compositeEngine.typeOf(name);
}
public String nameOf(Class<?> originType) {
return compositeEngine.nameOf(originType);
}
public <T> Class<T> sourceOf(String name) {
return compositeEngine.sourceOf(name);
}
public <T> T newEntity(Class<?> type) {
requireTrue(type.getAnnotation(Entity.class) != null
|| type.getAnnotation(Aggregate.class) != null, "invalid entity {}", type.getCanonicalName());
return compositeEngine.create(type);
}
}
|
desihub/qlf
|
frontend/src/screens/history/widgets/table-history/ccd-selector/ccd-selector.js
|
<filename>frontend/src/screens/history/widgets/table-history/ccd-selector/ccd-selector.js<gh_stars>1-10
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Popover from '@material-ui/core/Popover';
import QlfApi from '../../../../../containers/offline/connection/qlf-api';
const styles = theme => ({
typography: {
margin: theme.spacing.unit * 2,
cursor: 'pointer',
},
text: {
fontSize: '1.2vw',
},
});
class CCDSelector extends React.Component {
static propTypes = {
anchorEl: PropTypes.object,
classes: PropTypes.object.isRequired,
handleClose: PropTypes.func.isRequired,
openCCDViewer: PropTypes.func.isRequired,
flavor: PropTypes.string,
processId: PropTypes.number,
};
state = {
spectra: false,
ccd: false,
};
openViewer = viewer => {
this.props.handleClose();
this.props.openCCDViewer(viewer);
};
componentWillReceiveProps(nextProps) {
if (nextProps.anchorEl != null) this.checkFiles();
}
checkFiles = async () => {
const { spectra, ccd } = await QlfApi.checkViewFiles(this.props.processId);
this.setState({ spectra, ccd });
};
render() {
const { classes, anchorEl } = this.props;
return (
<Popover
open={Boolean(anchorEl)}
anchorEl={anchorEl}
onClose={this.props.handleClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'center',
}}
>
{this.state.ccd ? (
<Typography
className={classes.typography}
onClick={() => this.openViewer('ccd')}
classes={{ root: classes.text }}
>
CCD
</Typography>
) : null}
{this.props.flavor === 'science' ? (
<Typography
key="fiber"
className={classes.typography}
onClick={() => this.openViewer('fiber')}
classes={{ root: classes.text }}
>
Fibers
</Typography>
) : null}
{this.props.flavor === 'science' && this.state.spectra ? (
<Typography
key="spectra"
className={classes.typography}
onClick={() => this.openViewer('spectra')}
classes={{ root: classes.text }}
>
Spectra
</Typography>
) : null}
{/* <Typography
className={classes.typography}
onClick={() => this.openViewer('focus')}
>
Focus
</Typography>
<Typography
className={classes.typography}
onClick={() => this.openViewer('snr')}
>
SNR
</Typography> */}
</Popover>
);
}
}
export default withStyles(styles)(CCDSelector);
|
Kneelawk/SimpleCurseModpackDownloader
|
src/main/scala/org/kneelawk/simplecursemodpackdownloader/task/InterruptState.scala
|
<filename>src/main/scala/org/kneelawk/simplecursemodpackdownloader/task/InterruptState.scala
package org.kneelawk.simplecursemodpackdownloader.task
object InterruptState {
object Abort extends InterruptState
object ZombieKill extends InterruptState
}
/** An enum for different reasons to interrupt a task.
*
* There are currently two kinds of interrupt states:<br>
* Abort - a signal that the user has requested the cancelation of a task.<br>
* ZombieKill - a signal that a zombie killer has found this task to be unresponsive and is attempting to restart it.
*/
sealed trait InterruptState
case class InterruptException(state: InterruptState) extends Exception
|
wedataintelligence/vivaldi-source
|
chromium/device/bluetooth/test/test_bluetooth_adapter_observer.h
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef DEVICE_BLUETOOTH_TEST_BLUETOOTH_ADAPTER_OBSERVER_H_
#define DEVICE_BLUETOOTH_TEST_BLUETOOTH_ADAPTER_OBSERVER_H_
#include <stdint.h>
#include "base/macros.h"
#include "device/bluetooth/bluetooth_adapter.h"
namespace device {
// Test implementation of BluetoothAdapter::Observer counting method calls and
// caching last reported values.
class TestBluetoothAdapterObserver : public BluetoothAdapter::Observer {
public:
TestBluetoothAdapterObserver(scoped_refptr<BluetoothAdapter> adapter);
~TestBluetoothAdapterObserver() override;
// Reset counters and cached values.
void Reset();
// BluetoothAdapter::Observer
void AdapterPresentChanged(BluetoothAdapter* adapter, bool present) override;
void AdapterPoweredChanged(BluetoothAdapter* adapter, bool powered) override;
void AdapterDiscoverableChanged(BluetoothAdapter* adapter,
bool discoverable) override;
void AdapterDiscoveringChanged(BluetoothAdapter* adapter,
bool discovering) override;
void DeviceAdded(BluetoothAdapter* adapter, BluetoothDevice* device) override;
void DeviceChanged(BluetoothAdapter* adapter,
BluetoothDevice* device) override;
void DeviceAddressChanged(device::BluetoothAdapter* adapter,
device::BluetoothDevice* device,
const std::string& old_address) override;
void DeviceRemoved(BluetoothAdapter* adapter,
BluetoothDevice* device) override;
void GattServiceAdded(BluetoothAdapter* adapter,
BluetoothDevice* device,
BluetoothGattService* service) override;
void GattServiceRemoved(BluetoothAdapter* adapter,
BluetoothDevice* device,
BluetoothGattService* service) override;
void GattServicesDiscovered(BluetoothAdapter* adapter,
BluetoothDevice* device) override;
void GattDiscoveryCompleteForService(BluetoothAdapter* adapter,
BluetoothGattService* service) override;
void GattServiceChanged(BluetoothAdapter* adapter,
BluetoothGattService* service) override;
void GattCharacteristicAdded(
BluetoothAdapter* adapter,
BluetoothGattCharacteristic* characteristic) override;
void GattCharacteristicRemoved(
BluetoothAdapter* adapter,
BluetoothGattCharacteristic* characteristic) override;
void GattDescriptorAdded(BluetoothAdapter* adapter,
BluetoothGattDescriptor* descriptor) override;
void GattDescriptorRemoved(BluetoothAdapter* adapter,
BluetoothGattDescriptor* descriptor) override;
void GattCharacteristicValueChanged(
BluetoothAdapter* adapter,
BluetoothGattCharacteristic* characteristic,
const std::vector<uint8_t>& value) override;
void GattDescriptorValueChanged(BluetoothAdapter* adapter,
BluetoothGattDescriptor* descriptor,
const std::vector<uint8_t>& value) override;
// Adapter related:
int present_changed_count() { return present_changed_count_; }
int powered_changed_count() { return powered_changed_count_; }
int discoverable_changed_count() { return discoverable_changed_count_; }
int discovering_changed_count() { return discovering_changed_count_; }
bool last_present() { return last_present_; }
bool last_powered() { return last_powered_; }
bool last_discovering() { return last_discovering_; }
// Device related:
int device_added_count() { return device_added_count_; }
int device_changed_count() { return device_changed_count_; }
int device_address_changed_count() { return device_address_changed_count_; }
int device_removed_count() { return device_removed_count_; }
BluetoothDevice* last_device() { return last_device_; }
std::string last_device_address() { return last_device_address_; }
// GATT related:
int gatt_service_added_count() { return gatt_service_added_count_; }
int gatt_service_removed_count() { return gatt_service_removed_count_; }
int gatt_services_discovered_count() {
return gatt_services_discovered_count_;
}
int gatt_service_changed_count() { return gatt_service_changed_count_; }
int gatt_discovery_complete_count() { return gatt_discovery_complete_count_; }
int gatt_characteristic_added_count() {
return gatt_characteristic_added_count_;
}
int gatt_characteristic_removed_count() {
return gatt_characteristic_removed_count_;
}
int gatt_characteristic_value_changed_count() {
return gatt_characteristic_value_changed_count_;
}
int gatt_descriptor_added_count() { return gatt_descriptor_added_count_; }
int gatt_descriptor_removed_count() { return gatt_descriptor_removed_count_; }
int gatt_descriptor_value_changed_count() {
return gatt_descriptor_value_changed_count_;
}
std::string last_gatt_service_id() { return last_gatt_service_id_; }
BluetoothUUID last_gatt_service_uuid() { return last_gatt_service_uuid_; }
std::string last_gatt_characteristic_id() {
return last_gatt_characteristic_id_;
}
BluetoothUUID last_gatt_characteristic_uuid() {
return last_gatt_characteristic_uuid_;
}
std::vector<uint8_t> last_changed_characteristic_value() {
return last_changed_characteristic_value_;
}
std::string last_gatt_descriptor_id() { return last_gatt_descriptor_id_; }
BluetoothUUID last_gatt_descriptor_uuid() {
return last_gatt_descriptor_uuid_;
}
std::vector<uint8_t> last_changed_descriptor_value() {
return last_changed_descriptor_value_;
}
private:
// Some tests use a message loop since background processing is simulated;
// break out of those loops.
void QuitMessageLoop();
scoped_refptr<BluetoothAdapter> adapter_;
// Adapter related:
int present_changed_count_;
int powered_changed_count_;
int discoverable_changed_count_;
int discovering_changed_count_;
bool last_present_;
bool last_powered_;
bool last_discovering_;
// Device related:
int device_added_count_;
int device_changed_count_;
int device_address_changed_count_;
int device_removed_count_;
BluetoothDevice* last_device_;
std::string last_device_address_;
// GATT related:
int gatt_service_added_count_;
int gatt_service_removed_count_;
int gatt_services_discovered_count_;
int gatt_service_changed_count_;
int gatt_discovery_complete_count_;
int gatt_characteristic_added_count_;
int gatt_characteristic_removed_count_;
int gatt_characteristic_value_changed_count_;
int gatt_descriptor_added_count_;
int gatt_descriptor_removed_count_;
int gatt_descriptor_value_changed_count_;
std::string last_gatt_service_id_;
BluetoothUUID last_gatt_service_uuid_;
std::string last_gatt_characteristic_id_;
BluetoothUUID last_gatt_characteristic_uuid_;
std::vector<uint8_t> last_changed_characteristic_value_;
std::string last_gatt_descriptor_id_;
BluetoothUUID last_gatt_descriptor_uuid_;
std::vector<uint8_t> last_changed_descriptor_value_;
DISALLOW_COPY_AND_ASSIGN(TestBluetoothAdapterObserver);
};
} // namespace device
#endif // DEVICE_BLUETOOTH_TEST_BLUETOOTH_ADAPTER_OBSERVER_H_
|
XXBM/glmisWeb
|
src/main/java/com/glmis/domain/attendance/SchoolAbsence.java
|
package com.glmis.domain.attendance;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.MappedSuperclass;
/**
* Created by dell on 2017-05-23 .
*/
@MappedSuperclass
@DynamicInsert(true)
@DynamicUpdate(true)
public abstract class SchoolAbsence extends Absence {
}
|
aniskchaou/ULTRA-SHOP-CMS
|
wp-content/plugins/woocommerce-products-filter/ext/color/js/html_types/plugin_options.js
|
jQuery(function ($) {
$('.woof_toggle_colors').click(function () {
$(this).parent().find('ul.woof_color_list').toggle();
});
});
|
duanegtr/legendv3-cogs
|
modplus/modplus.py
|
from discord import user
from redbot.core import commands, Config, checks, modlog
import discord
import asyncio
import datetime
import time
from pyrate_limiter import (
BucketFullException,
Duration,
RequestRate,
Limiter,
MemoryListBucket,
MemoryQueueBucket,
)
ERROR_MESSAGES = {
'NOTIF_UNRECOGNIZED': "Notification Key was not recognized, please do `!notifs info` to get more info about the keys. List of valid keys: kick, ban, mute, jail, warn, channelperms, editchannel, deletemessages, ratelimit, adminrole, bot",
'PERM_UNRECOGNIZED': "Permission Key was not recognized, please do `!modpset perms info` to get more info about the keys. List of valid keys: kick, ban, mute, jail, warn, channelperms, editchannel, deletemessages."
}
PERM_SYS_INFO = """
**__Permission System Information__**
**Kick:** Can Kick Members (5 per hour max)
**Ban:** Can Ban Members (3 per hour max)
**Mute:** Can Mute Members
**Jail:** Can Jail Members
**Warn:** Can Warn Members
**ChannelPerms:** Can Add / Remove Members from Channels
**EditChannel:** Can Create, Rename, Enable Slowmode and Move Channels
**DeleteMessages:** Can Delete and Pin Messages. (50 per hour max)
"""
NOTIF_SYS_INFO = """
**__Notification System Information__**
You will be DMed on the events that you choose, listed below:
**Kick:** When someone is kicked
**Ban:** When someone is banned
**Mute:** When someone is muted
**Jail:** When someone is jailed
**Warn:** When someone is warned
**ChannelPerms:** When someone has been added / removed from a channel
**EditChannel:** When a channel has been created, moved or renamed
**DeleteMessages:** When messages have been deleted (note this will get spammy)
**RateLimit:** When a moderator has hit a rate limit (recommended)
**AdminRole:** When a member has been given admin or a role has been given admin (recommended)
**Bot:** When a bot has been added to the server
"""
class ModPlus(commands.Cog):
"""Ultimate Moderation Cog for RedBot"""
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 8818154, force_registration=True)
# PyRateLimit.init(redis_host="localhost", redis_port=6379)
hourly_rate5 = RequestRate(5, Duration.HOUR)
hourly_rate3 = RequestRate(3, Duration.HOUR)
self.kicklimiter = Limiter(hourly_rate5)
self.banlimiter = Limiter(hourly_rate3)
# self.kicklimit = PyRateLimit()
# self.kicklimit.create(3600, 5)
# self.banlimit = PyRateLimit()
# self.banlimit.create(3600, 3)
default_global = {
'notifs': {
'kick': [],
'ban': [],
'mute': [],
'jail': [],
'channelperms': [],
'editchannel': [],
'deletemessages': [],
'ratelimit': [],
'adminrole': [],
'bot':[],
'warn':[]
},
'notifchannels' : {
'kick': [],
'ban': [],
'mute': [],
'jail': [],
'channelperms': [],
'editchannel': [],
'deletemessages': [],
'ratelimit': [],
'adminrole': [],
'bot':[],
'warn':[]
}
}
default_guild = {
'perms': {
'kick': [],
'ban': [],
'mute': [],
'jail': [],
'channelperms': [],
'editchannel': [],
'deletemessages': [],
'warn': []
},
'roles': {
'warning1': None,
'warning2': None,
'warning3+': None,
'jailed': None,
'muted': None
}
}
self.config.register_guild(**default_guild)
self.config.register_global(**default_global)
self.permkeys = [
'kick',
'ban',
'mute',
'jail',
'channelperms',
'editchannel',
'deletemessages',
'warn'
]
self.notifkeys = [
'kick',
'ban',
'mute',
'jail',
'channelperms',
'editchannel',
'deletemessages',
'ratelimit',
'adminrole',
'bot',
'warn'
]
self.rolekeys = [
'warning1',
'warning2',
'warning3+',
'jailed',
'muted'
]
# Notifications Part
@commands.group(aliases=['notifs', 'notif']) # CHANNEL
@checks.mod()
async def adminnotifications(self, ctx):
"""Configure what notifications to get"""
pass
@adminnotifications.group(name='channel')
async def notifschannel(self, ctx):
"""Configure a channel to recieve notifications"""
pass
@adminnotifications.command(name='info')
async def notifsinfo(self, ctx):
"""Get information about notification system"""
await ctx.send(NOTIF_SYS_INFO)
@adminnotifications.command(name='add')
async def notifsadd(self, ctx, notifkey: str, user: discord.Member = None):
"""Get notified about something"""
if user is None:
user = ctx.author
notifkey = notifkey.strip().lower()
if notifkey not in self.notifkeys:
return await ctx.send(ERROR_MESSAGES['NOTIF_UNRECOGNIZED'])
data = await self.config.notifs()
if user.id in data[notifkey]:
return await ctx.send(f"{user.display_name} is already getting notified about {notifkey}")
data[notifkey].append(user.id)
await self.config.notifs.set(data)
return await ctx.send(f"{user.display_name} will now be notified on {notifkey}")
@adminnotifications.command(name='remove')
async def notifsremove(self, ctx, notifkey: str, user: discord.Member = None):
"""Stop getting notified about something"""
if user is None:
user = ctx.author
notifkey = notifkey.strip().lower()
if notifkey not in self.notifkeys:
return await ctx.send(ERROR_MESSAGES['NOTIF_UNRECOGNIZED'])
data = await self.config.notifs()
if user.id not in data[notifkey]:
return await ctx.send(f"{user.display_name} isn't currently getting notified about {notifkey}")
data[notifkey].remove(user.id)
await self.config.notifs.set(data)
return await ctx.send(f"{user.display_name} will now stop being notified about {notifkey}")
# SHOW NOTIFICATIONS
@adminnotifications.command(name='list')
async def notifslist(self, ctx, user: discord.Member = None):
"""Show which notifications you / a user has enabled"""
if user is None:
user = ctx.author
data = await self.config.notifs()
notifs = []
for notif in data:
if user.id in data[notif]:
notifs.append(notif)
await ctx.send(f'{user.display_name} is getting notified for the following: ' + ', '.join(notifs))
# Channel notifications
@notifschannel.command(name='add')
async def channelnotifsadd(self, ctx, notifkey: str, channel: discord.TextChannel):
"""Get notified about something (channel)"""
notifkey = notifkey.strip().lower()
if notifkey not in self.notifkeys:
return await ctx.send(ERROR_MESSAGES['NOTIF_UNRECOGNIZED'])
data = await self.config.notifchannels()
channeldata = [channel.guild.id, channel.id]
if channeldata in data[notifkey]:
return await ctx.send(f"{channel.name} is already getting notified about {notifkey}")
data[notifkey].append(channeldata)
await self.config.notifchannels.set(data)
return await ctx.send(f"{channel.name} will now be notified on {notifkey}")
@notifschannel.command(name='remove')
async def channelnotifsremove(self, ctx, notifkey: str, channel: discord.TextChannel):
"""Stop getting notified about something (channel)"""
notifkey = notifkey.strip().lower()
if notifkey not in self.notifkeys:
return await ctx.send(ERROR_MESSAGES['NOTIF_UNRECOGNIZED'])
data = await self.config.notifchannels()
channeldata = [channel.guild.id, channel.id]
if channeldata not in data[notifkey]:
return await ctx.send(f"{channel.name} isn't currently getting notified about {notifkey}")
data[notifkey].remove(channeldata)
await self.config.notifchannels.set(data)
return await ctx.send(f"{channel.name} will now stop being notified about {notifkey}")
@notifschannel.command(name='list')
async def channelnotifslist(self, ctx, channel: discord.TextChannel):
"""Show which notifications a channel has enabled"""
data = await self.config.notifchannels()
channeldata = [channel.guild.id, channel.id]
notifs = []
for notif in data:
if channeldata in data[notif]:
notifs.append(notif)
await ctx.send(f'{channel.name} is getting notified for the following: ' + ', '.join(notifs))
# NOTIFY FUNCTION
async def notify(self, notifkey, payload):
data = await self.config.all()
for userid in data['notifs'][notifkey]:
user: discord.User = await self.bot.fetch_user(userid)
try:
await user.send(payload)
except Exception:
pass
for channel in data['notifchannels'][notifkey]:
guild: discord.guild = self.bot.get_guild(channel[0])
if guild is not None:
txtchannel = guild.get_channel(channel[1])
try:
await txtchannel.send(payload, allowed_mentions=discord.AllowedMentions.all())
except Exception:
pass
# Admin Logging
@commands.Cog.listener(name='on_guild_role_update')
async def role_add_admin(self, old: discord.Role, new: discord.Role):
if new.permissions.administrator and not old.permissions.administrator:
await self.notify('adminrole', f'@everyone Role {new.mention}({new.id}) was updated to contain administrator permission. \n IN: {old.guild.name}({old.guild.id})')
@commands.Cog.listener(name='on_member_join')
async def join_bot(self, member: discord.Member):
"""Detect if new joining member is a bot"""
if member.bot:
await self.notify('bot', f'@everyone Role Bot {member.mention}({member.id}) was added. \n IN: {member.guild.name}({member.guild.id})')
@commands.Cog.listener(name='on_member_update')
async def member_admin(self, old: discord.Member, new: discord.Member):
new_roles = []
for role in new.roles:
if role not in old.roles:
new_roles.append(role)
for role in new_roles:
if role.permissions.administrator:
await self.notify('adminrole', f'@everyone Member{new.mention}({new.id}) was updated to contain administrator permission. \n IN: {old.guild.name}({old.guild.id})')
async def rate_limit_exceeded(self, user: discord.Member, type):
"""Called to removed all moderation roles when a mod has hit ratelimit"""
allmodroles = []
data = await self.config.guild(user.guild).perms()
for perm in data:
for role in data[perm]:
if role not in allmodroles:
allmodroles.append(role)
rm_mention = []
broken = []
issue = False
for role in user.roles:
if role.id in allmodroles:
try:
await user.remove_roles(role, reason='Rate limit exceeded.')
rm_mention.append(role.mention)
rm_mention.append('(' + str(role.id) + ')')
except Exception:
issue = True
broken.append(role.mention)
broken.append('(' + str(role.id) + ')')
if issue:
await self.notify('ratelimit', "Removing roles in the ratelimit below ended in error. The user has a role above the bot. The following roles could not be removed: " + ', '.join(broken))
payload = f"@everyone {type} ratelimit has been exceeded by {user.mention} ({user.display_name}, {user.id}). The following roles with power have been removed: " + ', '.join(rm_mention)
await self.notify('ratelimit', payload)
async def action_check(self, ctx, permkey):
if await self.bot.is_admin(ctx.author) or await self.bot.is_owner(ctx.author) or ctx.author.guild_permissions.administrator: # Admin auto-bypass
return True
data = await self.config.guild(ctx.guild).all()
canrun = False
for role in ctx.author.roles:
if role.id in data['perms'][permkey]:
canrun = True
break
if not canrun:
return False
if permkey == 'kick':
try:
self.kicklimiter.try_acquire(str(ctx.author.id))
except BucketFullException:
await self.rate_limit_exceeded(ctx.author, 'kick')
return False
elif permkey == 'ban':
try:
self.banlimiter.try_acquire(str(ctx.author.id))
except BucketFullException:
await self.rate_limit_exceeded(ctx.author, 'kick')
return False
return True
@commands.group()
@checks.admin()
async def modpset(self, ctx):
"""Configure Mod Plus"""
pass
@modpset.group(aliases=['perms', 'perm'])
async def permissions(self, ctx):
"""Configure Role Permissions"""
pass
@permissions.command(name='info')
async def permsinfo(self, ctx):
"""Get info about perms system"""
await ctx.send(PERM_SYS_INFO)
@permissions.command(name='add')
async def permsadd(self, ctx, role: discord.Role, *, permkey: str):
"""Add Perms to a Role"""
permkey = permkey.strip().lower()
if permkey not in self.permkeys:
return await ctx.send(ERROR_MESSAGES['PERM_UNRECOGNIZED'])
data = await self.config.guild(ctx.guild).get_raw("perms", permkey)
if role.id in data:
return await ctx.send(f"{role.name} already has the {permkey} permission")
data.append(role.id)
await self.config.guild(ctx.guild).set_raw("perms", permkey, value=data)
return await ctx.send(f"{role.name} was sucessfully given the {permkey} permission")
@permissions.command(name='remove')
async def permsremove(self, ctx, role: discord.Role, *, permkey: str):
"""Revoke Perms from a Role"""
permkey = permkey.strip().lower()
if permkey not in self.permkeys:
return await ctx.send(ERROR_MESSAGES['PERM_UNRECOGNIZED'])
data = await self.config.guild(ctx.guild).get_raw("perms", permkey)
if role.id not in data:
return await ctx.send(f"{role.name} doesn't have the {permkey} permission")
data.remove(role.id)
await self.config.guild(ctx.guild).set_raw("perms", permkey, value=data)
return await ctx.send(f"{role.name} has sucessfully been revoked the {permkey} permission")
@permissions.group(name='list')
async def permslist(self, ctx):
"""List Permissions"""
pass
@permslist.command(name='perm', aliases=['perms', 'permission'])
async def list_perm_by_perm(self, ctx, *, permkey):
"""List Roles which have the given perm"""
permkey = permkey.strip().lower()
if permkey not in self.permkeys:
return await ctx.send(ERROR_MESSAGES['PERM_UNRECOGNIZED'])
data = await self.config.guild(ctx.guild).get_raw("perms", permkey)
rolenames = []
for roleid in data:
role = ctx.guild.get_role(roleid)
if role is None:
continue
rolenames.append(role.mention)
output = f"Roles that have {permkey} permission: " + ', '.join(rolenames)
if len(rolenames) == 0:
output = f"No Roles have the {permkey} permission."
await ctx.send(output)
@permslist.command(name='role')
async def list_perms_by_role(self, ctx, role: discord.Role):
"""List which permissions a role has"""
data = await self.config.guild(ctx.guild).perms()
perms = []
for permkey in data:
if role.id in data[permkey]:
perms.append(permkey)
if len(perms) == 0:
await ctx.send(f"{role.name} has no permissions.")
else:
output = f"{role.name} has the following for permisssions: " + ', '.join(perms)
await ctx.send(output)
# Role Config Probably Delte
# @modpset.command(name='role')
# async def setrole(self, ctx, role: discord.Role, *, rolekey):
# """Set the coresponding role"""
# rolekey = rolekey.strip().lower()
# if rolekey not in self.rolekeys:
# return await ctx.send("Role Key was not recognized. List of valid keys: warning1, warning2, warning3+, jailed, muted")
# data = await self.config.guild(ctx.guild).roles()
# data[rolekey] = role.id
# await self.config.guild(ctx.guild).roles.set(data)
# await ctx.send(f'{rolekey} was set to {role.mention}.')
# @modpset.command(name='showroles')
# async def set_showroles(self, ctx):
# """Show which role is attributed to which key"""
# output = "__**Role Configuration:**__"
# data = await self.config.guild(ctx.guild).roles()
# for rolekey in data:
# if data[rolekey] is None:
# output += f"\n**{rolekey}**: Not Set"
# else:
# role = ctx.guild.get_role(data[rolekey])
# output += f"\n**{rolekey}**: {role.mention}"
# await ctx.send(output)
# @modpset.command()
# async def createmutedrole(self, ctx):
# """Create a muted role with all channel overrides. This will override an already set muted role"""
# async with ctx.typing():
# guild: discord.Guild = ctx.guild
# mutedrole : discord.Role = guild.create_role(name="Muted", reason="Muted Role Creation")
# for channel in guild.text_channels:
# channel.set_permissions(mutedrole, send_messages=False)
|
keerthana1502/python_practice
|
database.py
|
import pymongo
connection_url="mongodb://localhost:27017"
client = pymongo.MongoClient(connection_url)
db = client['users']
collection = db['employee']
#collection.insert_one({"name":"ocean"})
#collection.insert_many([{"name":"keerthana","number":5,"department":"CSE"},
#{"name":"kishore","number":6,"department":"IT"},
#{"name":"Ajay","number":7,"department":"ECE"},
#{"name":"shakthi","number":8,"department":"EEE"}])
query = {"name":"shakthi"}
#ret = collection.find_one(query)
#print(ret)
'''ret1=collection.find()
for i in ret1:
print(i)
newData={"$set":{"name":"shanmu"}}
collection.update_one(query,newData)
ret1=collection.find()
for i in ret1:
print(i)'''
collection.delete_one(query)
|
light1021/dynamic-application-loader-host-interface
|
libjhi/CommandInvoker.h
|
/*
Copyright 2010-2016 Intel Corporation
This software is licensed to you in accordance
with the agreement between you and Intel Corporation.
Alternatively, you can use this file in compliance
with the Apache license, Version 2.
Apache License, Version 2.0
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.
*/
/**
********************************************************************************
**
** @file CommandInvoker.h
**
** @brief Contains API for jhi commands
**
** @author <NAME>
**
********************************************************************************
*/
#ifndef _COMMAND_INVOKER_H_
#define _COMMAND_INVOKER_H_
#include "CommandsClientFactory.h"
#include "jhi.h"
#include "jhi_i.h"
#include <string_s.h>
#include "teemanagement.h"
#include "dal_tee_metadata.h"
#ifdef SCHANNEL_OVER_SOCKET //(emulation mode)
#include "jhi_sdk.h"
#endif
namespace intel_dal
{
class CommandInvoker
{
private:
ICommandsClient* client;
bool InvokeCommand(const uint8_t* inputBuffer,uint32_t inputBufferSize,uint8_t** outputBuffer,uint32_t* outputBufferSize);
// disabling copy constructor and assignment operator by declaring them as private
CommandInvoker& operator = (const CommandInvoker& other) { return *this; }
CommandInvoker(const CommandInvoker& other) { }
public:
CommandInvoker();
~CommandInvoker();
JHI_RET JhisInit();
JHI_RET JhisInstall(char* AppId, const FILECHAR* pSrcFile);
JHI_RET JhisUninstall(char* AppId);
JHI_RET JhisGetSessionsCount(char* AppId, uint32_t* pSessionCount);
JHI_RET JhisCreateSession(char* AppId, JHI_SESSION_ID* pSessionID, uint32_t flags,DATA_BUFFER* initBuffer, JHI_PROCESS_INFO* processInfo);
JHI_RET JhisCloseSession(JHI_SESSION_ID* SessionID,JHI_PROCESS_INFO* processInfo, bool force);
JHI_RET JhisGetSessionInfo(JHI_SESSION_ID* SessionID,JHI_SESSION_INFO* pSessionInfo);
JHI_RET JhisSetSessionEventHandler(JHI_SESSION_ID* SessionID, const char* handleName);
JHI_RET JhisGetEventData(JHI_SESSION_ID* SessionID,uint32_t* DataBufferSize,uint8_t** pDataBuffer,uint8_t* pDataType);
JHI_RET JhisSendAndRecv(JHI_SESSION_ID* SessionID,int32_t CommandId,const uint8_t* SendBuffer,uint32_t SendBufferSize,uint8_t* RecvBuffer,uint32_t* RecvBufferSize,int32_t* responseCode);
JHI_RET JhisGetAppletProperty(char* AppId,const uint8_t* SendBuffer,uint32_t SendBufferSize,uint8_t* RecvBuffer,uint32_t* RecvBufferSize);
JHI_RET JhisGetVersionInfo(JHI_VERSION_INFO* pVersionInfo);
// Management API
TEE_STATUS JhisOpenSDSession(IN const string& sdId, OUT SD_SESSION_HANDLE* sdHandle);
TEE_STATUS JhisCloseSDSession(IN OUT SD_SESSION_HANDLE* sdHandle);
TEE_STATUS JhisSendAdminCmdPkg(IN const SD_SESSION_HANDLE sdHandle, IN const uint8_t* package, IN uint32_t packageSize);
TEE_STATUS JhisListInstalledTAs(IN SD_SESSION_HANDLE sdHandle, OUT UUID_LIST* uuidList);
TEE_STATUS JhisListInstalledSDs(IN SD_SESSION_HANDLE sdHandle, OUT UUID_LIST* uuidList);
TEE_STATUS JhisQueryTEEMetadata(OUT dal_tee_metadata* metadata, size_t max_length);
TEE_STATUS JhisProvisionOemMasterKey(IN const tee_asym_key_material* key);
TEE_STATUS JhisSetTAEncryptionKey(IN const tee_key_material* key);
#ifdef SCHANNEL_OVER_SOCKET //(emulation mode)
JHI_RET JhisGetSessionTable(JHI_SESSIONS_DATA_TABLE** SessionDataTable);
JHI_RET JhisGetLoadedAppletsList(JHI_LOADED_APPLET_GUIDS** appGUIDs);
#endif
};
}
#endif // _COMMAND_INVOKER_H_
|
bzxy/cydia
|
iOSOpenDev/frameworks/OfficeImport.framework/Headers/ODDLayoutObjectList.h
|
<reponame>bzxy/cydia
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
*/
#import <OfficeImport/ODDLayoutObject.h>
@class NSMutableArray;
__attribute__((visibility("hidden")))
@interface ODDLayoutObjectList : ODDLayoutObject {
@private
NSMutableArray *mChildren; // 4 = 0x4
}
- (id)init; // 0x2af7b5
- (void)dealloc; // 0x2af83d
- (id)children; // 0x2af7a5
- (void)addChild:(id)child; // 0x2af819
@end
|
gcodebackups/srcdemo2
|
lib/any/jlibs/src/jlibs/core/lang/ThreadTasker.java
|
/**
* JLibs: Common Utilities for Java
* Copyright (C) 2009 <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package jlibs.core.lang;
/**
* @author <NAME>
*/
public abstract class ThreadTasker{
public abstract boolean isValid();
protected abstract void executeAndWait(Runnable runnable);
public abstract void executeLater(Runnable runnable);
public void execute(Runnable runnable){
if(isValid())
runnable.run();
else
executeAndWait(runnable);
}
public <R, E extends Exception> R execute(ThrowableTask<R, E> task) throws E{
execute(task.asRunnable());
return task.getResult();
}
public <R> R execute(Task<R> task){
execute(task.asRunnable());
return task.getResult();
}
}
|
cidneyhamilton/Composer
|
App/features/scripts/nodes/fadeEditor.js
|
<gh_stars>0
define(function(require) {
var assetDatabase = require('infrastructure/assetDatabase'),
observable = require('plugins/observable'),
NodeEditor = require('./nodeEditor'),
Editor = require('features/shared/editor');
var ctor = function() {
NodeEditor.call(this);
this.availableScope = ['FadeOutAndIn', 'FadeIn', 'FadeOut']; // Joshua Should probably have been an index to convert to an enum C# side but oh well.
};
NodeEditor.baseOn(ctor);
return ctor;
});
|
kaist-plrg/jest
|
data/generated/159.js
|
var x = 0n ; -- x ;
|
jmvezic/webcurator
|
wct-submit-to-rosetta/src/main/java/nz/govt/natlib/ndha/common/FixityUtils.java
|
<filename>wct-submit-to-rosetta/src/main/java/nz/govt/natlib/ndha/common/FixityUtils.java
/**
* nz.govt.natlib.ndha.common.Common - Software License
*
* Copyright 2007/2008 National Library of New Zealand.
* 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
*
* or the file "LICENSE.txt" included with the software.
*
* 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 nz.govt.natlib.ndha.common;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* FixityUtils is a static utility class that provides MD5 calculation methods for
* Files, and input streams.
*
* @author rossb
*/
public final class FixityUtils {
private static final int MD5_HEX_STRING_LENGTH = 32;
private static final String MD5_ALGORITHM = "MD5";
private static final char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
enum BufferSize {
TINY(1024), VERYSMALL(2048), SMALL(4096), MEDIUM(8192), LARGE(20480), HUGE(51200);
BufferSize(int bytes) {
this.size = bytes;
}
private int size;
public int getSize() {
return size;
}
}
/* Default constructor made private to stop is static utility class being instantiated */
private FixityUtils() {
}
/**
* Returns the MD5 value of the physical file represented by the File object
*
* @param theFile - The File object associated with the physical file to have
* its MD5 calculated.
* @return A String representing the MD5 value of the File.
* @throws FileNotFoundException if the file cannot be found.
* @throws RuntimeException if an internal error occurs in the MD5 calculation.
*/
public static String calculateMD5(File theFile) throws FileNotFoundException {
return calculateMD5(theFile, BufferSize.MEDIUM);
}
/**
* Returns the MD5 value of the physical file represented by the File object,
* using a read buffer of the size specified.
*
* @param theFile the File object associated with the physical file to have
* its MD5 calculated.
* @param bufferSize a BufferSize enum object identifying the size of the read buffer
* to be used. e.g. <code>FixityUtils.BufferSize.MEDIUM </code>
* @return A String representing the MD5 value of the File.
* @throws RuntimeException if an internal error occurs in the MD5 calculation.
* @throws FileNotFoundException if the file cannot be found.
*/
public static String calculateMD5(File theFile, BufferSize bufferSize) throws FileNotFoundException {
InputStream is = new FileInputStream(theFile);
return calculateMD5(is, bufferSize);
}
/**
* Returns the MD5 value of the physical file identified in the String object.
*
* @param filePath a String identifying the file (with prefix path if required) to have its
* MD5 calculated.
* @return A String representing the MD5 value of the File.
* @throws IllegalArgumentException if filePathString is null.
* @throws FileNotFoundException if the file cannot be found.
* @throws RuntimeException if an internal error occurs in the MD5 calculation.
*/
public static String calculateMD5(String filePath) throws IllegalArgumentException, FileNotFoundException {
return calculateMD5(filePath, BufferSize.MEDIUM);
}
/**
* Returns the MD5 value of the physical file identified in the String object,
* using a read buffer of the size specified.
*
* @param filePath a String identifying the file (with prefix path if required) to have its
* MD5 calculated.
* @param bufferSize a BufferSize enum object identifying the size of the read buffer
* to be used. e.g. <code>FixityUtils.BufferSize.MEDIUM </code>
* @return A String representing the MD5 value of the File.
* @throws IllegalArgumentException if filePathString is null.
* @throws FileNotFoundException if the file cannot be found.
* @throws RuntimeException if an internal error occurs in the MD5 calculation.
*/
public static String calculateMD5(String filePath, BufferSize bufferSize) throws IllegalArgumentException, FileNotFoundException {
if (null == filePath) {
throw new IllegalArgumentException("filePath String was null.");
}
return calculateMD5(new File(filePath), bufferSize);
}
/**
* Returns the MD5 value of the InputStream identified identified by is.
*
* @param is the input stream to be used in the MD5 calculation.
* @return A String representing the MD5 value of the InputStream.
* @throws RuntimeException if an internal error occurs in the MD5 calculation.
*/
public static String calculateMD5(InputStream is) {
return calculateMD5(is, BufferSize.MEDIUM);
}
/**
* Returns the MD5 value of the InputStream identified identified by is.
*
* @param is the input stream to be used in the MD5 calculation.
* @return A String representing the MD5 value of the InputStream.
* @throws RuntimeException if an internal error occurs in the MD5 calculation.
*/
public static String calculateMD5(InputStream is, BufferSize bufferSize) {
//String md5result = null;
try {
// MessageDigest digest = MessageDigest.getInstance(FixityUtils.MD5_ALGORITHM);
// byte[] buffer = new byte[bufferSize.getSize()];
// int read = 0;
// while( (read = is.read(buffer)) > 0) {
// digest.update(buffer, 0, read);
// }
// byte[] md5sum = digest.digest();
// BigInteger bigInt = new BigInteger(1, md5sum);
// md5result = bigInt.toString(16);
MessageDigest messageDigest = MessageDigest.getInstance(FixityUtils.MD5_ALGORITHM);
byte[] buffer = new byte[bufferSize.getSize()];
int read;
while ((read = is.read(buffer)) >= 0) {
messageDigest.update(buffer, 0, read);
}
byte[] digest = messageDigest.digest();
int msb;
int lsb = 0;
StringBuffer hexString = new StringBuffer(MD5_HEX_STRING_LENGTH);
for (int i = 0; i < digest.length; i++) {
msb = ((int) digest[i] & 0x000000FF) / 16;
lsb = ((int) digest[i] & 0x000000FF) % 16;
hexString.append(hexChars[msb]);
hexString.append(hexChars[lsb]);
}
return hexString.toString();
}
catch (NoSuchAlgorithmException e) { //convert to unchecked exception
throw new RuntimeException("Unable to process InputStream for MD5", e);
}
catch (IOException e) { //convert to unchecked exception
throw new RuntimeException("Unable to process InputStream for MD5", e);
}
finally {
try {
is.close();
}
catch (IOException e) { //convert to unchecked exception
throw new RuntimeException("Unable to close input stream for MD5 calculation", e);
}
}
//return md5result;
}
}
|
team-diana/nucleo-dynamixel
|
docs/html/group___t_i_m_ex___exported___functions.js
|
var group___t_i_m_ex___exported___functions =
[
[ "TIMEx_Exported_Functions_Group1", "group___t_i_m_ex___exported___functions___group1.html", null ],
[ "TIMEx_Exported_Functions_Group2", "group___t_i_m_ex___exported___functions___group2.html", null ],
[ "TIMEx_Exported_Functions_Group3", "group___t_i_m_ex___exported___functions___group3.html", null ],
[ "TIMEx_Exported_Functions_Group4", "group___t_i_m_ex___exported___functions___group4.html", null ],
[ "TIMEx_Exported_Functions_Group5", "group___t_i_m_ex___exported___functions___group5.html", null ],
[ "TIMEx_Exported_Functions_Group6", "group___t_i_m_ex___exported___functions___group6.html", null ],
[ "TIMEx_Exported_Functions_Group7", "group___t_i_m_ex___exported___functions___group7.html", null ]
];
|
zhouhp007/AndroidAll
|
language-java/jvm/jvm-sample/src/gc/PermGenOOM.java
|
package gc;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
public class PermGenOOM {
//C:\Program Files (x86)\Java\jdk1.6.0_45\bin>
//java -XX:PermSize=1m -XX:MaxPermSize=9m -Xmx16m PermGenOOM
//C:\Program Files\Java\jdk1.8.0_201
//C:\Program Files (x86)\Java\jdk1.6.0_45
//-XX:MetaspaceSize=1m -XX:MaxMetaspaceSize=9m -Xmx16m
//-XX:PermSize=1m -XX:MaxPermSize=9m -Xmx16m
private static Class klass;
public static void main(String[] args) throws Exception {
List<Object> list = new ArrayList<>();
URL url = new File(".").toURI().toURL();
URL[] urls = {url};
int count = 0;
while (true) {
try {
//System.out.println(++count);
ClassLoader loader = new URLClassLoader(urls);
//classLoaderList.add(loader);
list.add(loader.loadClass("gc.GcTest"));
list.add(loader.loadClass("gc.PermGenOOM"));
//loader.loadClass("gc.StringOomMock");
//Class clazz = loader.loadClass("gc.BigClass");
//loader.loadClass("feature.method_handle.MethodHandleTest");
//loader.loadClass("feature.method_handle.Client");
// System.out.println(clazz);
// System.out.println(klass == clazz);
//klass = clazz;
list.add(loader);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
Dilepa/micropython-async
|
v2/fast_io/fast_can_test.py
|
<gh_stars>100-1000
# fast_can_test.py Test of cancellation of tasks which call sleep
# Copyright (c) <NAME> 2019
# Released under the MIT licence
import uasyncio as asyncio
import sys
ermsg = 'This test requires the fast_io version of uasyncio V2.4 or later.'
try:
print('Uasyncio version', asyncio.version)
if not isinstance(asyncio.version, tuple):
print(ermsg)
sys.exit(0)
except AttributeError:
print(ermsg)
sys.exit(0)
# If a task times out the TimeoutError can't be trapped:
# no exception is thrown to the task
async def foo(t):
try:
print('foo started')
await asyncio.sleep(t)
print('foo ended', t)
except asyncio.CancelledError:
print('foo cancelled', t)
async def lpfoo(t):
try:
print('lpfoo started')
await asyncio.after(t)
print('lpfoo ended', t)
except asyncio.CancelledError:
print('lpfoo cancelled', t)
async def run(coro, t):
await asyncio.wait_for(coro, t)
async def bar(loop):
foo1 = foo(1)
foo5 = foo(5)
lpfoo1 = lpfoo(1)
lpfoo5 = lpfoo(5)
loop.create_task(foo1)
loop.create_task(foo5)
loop.create_task(lpfoo1)
loop.create_task(lpfoo5)
await asyncio.sleep(2)
print('Cancelling tasks')
asyncio.cancel(foo1)
asyncio.cancel(foo5)
asyncio.cancel(lpfoo1)
asyncio.cancel(lpfoo5)
await asyncio.sleep(0) # Allow cancellation to occur
print('Pausing 7s to ensure no task still running.')
await asyncio.sleep(7)
print('Launching tasks with 2s timeout')
loop.create_task(run(foo(1), 2))
loop.create_task(run(lpfoo(1), 2))
loop.create_task(run(foo(20), 2))
loop.create_task(run(lpfoo(20), 2))
print('Pausing 7s to ensure no task still running.')
await asyncio.sleep(7)
loop = asyncio.get_event_loop(ioq_len=16, lp_len=16)
loop.run_until_complete(bar(loop))
|
cleanlyer/cleanly
|
test/unit/actions/types-test.js
|
import * as types from '../../../src/actions/types'
describe('types should have', () => {
it('UPDATE_USER_LOCATION as UPDATE_USER_LOCATION', () => {
expect(types.UPDATE_USER_LOCATION).toEqual('UPDATE_USER_LOCATION')
})
it('SEND_REPORT as SEND_REPORT', () => {
expect(types.SEND_REPORT).toEqual('SEND_REPORT')
})
it('SEND_CLEAN as SEND_CLEAN', () => {
expect(types.SEND_CLEAN).toEqual('SEND_CLEAN')
})
it('UPDATE_SCORE as UPDATE_SCORE', () => {
expect(types.UPDATE_SCORE).toEqual('UPDATE_SCORE')
})
it('GET_GARBAGE as GET_GARBAGE', () => {
expect(types.GET_GARBAGE).toEqual('GET_GARBAGE')
})
it('GET_GARBAGE_OFFLINE as GET_GARBAGE_OFFLINE', () => {
expect(types.GET_GARBAGE_OFFLINE).toEqual('GET_GARBAGE_OFFLINE')
})
it('SEND_REPORT_OFFLINE as SEND_REPORT_OFFLINE', () => {
expect(types.SEND_REPORT_OFFLINE).toEqual('SEND_REPORT_OFFLINE')
})
it('SEND_CLEAN_OFFLINE as SEND_CLEAN_OFFLINE', () => {
expect(types.SEND_CLEAN_OFFLINE).toEqual('SEND_CLEAN_OFFLINE')
})
it('LOGIN as LOGIN', () => {
expect(types.LOGIN).toEqual('LOGIN')
})
})
|
cliveyao/Orienteer
|
orienteer-bpm/src/main/java/org/orienteer/bpm/camunda/handler/BatchEntityHandler.java
|
package org.orienteer.bpm.camunda.handler;
import com.orientechnologies.orient.core.metadata.schema.OType;
import org.camunda.bpm.engine.batch.BatchQuery;
import org.camunda.bpm.engine.impl.batch.BatchEntity;
import org.orienteer.bpm.camunda.OPersistenceSession;
import org.orienteer.bpm.camunda.handler.history.UserOperationLogEntryEventEntityHandler;
import org.orienteer.core.OClassDomain;
import org.orienteer.core.util.OSchemaHelper;
import java.util.List;
/**
* Created by KMukhov on 12.08.2016.
*/
public class BatchEntityHandler extends AbstractEntityHandler<BatchEntity> {
public static final String OCLASS_NAME = "BPMBatch";
public BatchEntityHandler() {
super(OCLASS_NAME);
}
@Override
public void applySchema(OSchemaHelper helper) {
super.applySchema(helper);
helper.domain(OClassDomain.SYSTEM);
helper.oProperty("type", OType.STRING, 10)
.oProperty("totalJobs", OType.INTEGER, 20)
.oProperty("jobsCreated", OType.INTEGER, 30)
.oProperty("batchJobsPerSeed", OType.INTEGER, 40)
.oProperty("invocationsPerBatchJob", OType.INTEGER, 50)
.oProperty("seedJobDefinitionId", OType.STRING, 60)
.oProperty("monitorJobDefinitionId", OType.STRING, 70)
.oProperty("batchJobDefinitionId", OType.STRING, 80)
.oProperty("configuration", OType.STRING, 90)
.oProperty("tenantId", OType.STRING, 100)
.oProperty("suspensionState", OType.INTEGER, 110)
.oProperty("userOperationLogEntryEvents", OType.LINKLIST, 120).assignVisualization("table");
}
@Override
public void applyRelationships(OSchemaHelper helper) {
super.applyRelationships(helper);
helper.setupRelationship(OCLASS_NAME, "userOperationLogEntryEvents", UserOperationLogEntryEventEntityHandler.OCLASS_NAME, "batch");
}
@Statement
public List<BatchEntity> selectBatchesByQueryCriteria(OPersistenceSession session, BatchQuery query) {
return query(session, query);
}
}
|
Waynocs/NathanWaian_cpoa
|
src/tests/dao/mysql/mysqlOrderTest.java
|
<filename>src/tests/dao/mysql/mysqlOrderTest.java
package tests.dao.mysql;
import dao.DAOFactory;
import dao.DAOFactory.Mode;
import tests.dao.OrderTest;
public class mysqlOrderTest extends OrderTest {
@Override
protected DAOFactory getFactory() {
return DAOFactory.getFactory(Mode.SQL);
}
}
|
agilecreativity/go-playground
|
structs-and-interfaces/way-to-go-11-11-reflection-02.go
|
package main
import (
"fmt"
"reflect"
)
func main() {
var x float64 = 3.4
v := reflect.ValueOf(x)
// Setting a value (will not work)
// v.SetFloat(3.1415) // panic : using unaddressable value
fmt.Println("Settability of v:", v.CanSet()) // false
v = reflect.ValueOf(&x) // Note: take the address of x
fmt.Println("Type of v:", v.Type()) // *float64
fmt.Println("Settability of v:", v.CanSet()) // false
v = v.Elem()
fmt.Println("The Elem of v is:", v)
fmt.Println("Settability of v:", v.CanSet()) // true
v.SetFloat(3.1415) // this works!
fmt.Println(v) // 3.1415
}
/* Output:
Settability of v: false
Type of v: *float64
Settability of v: false
The Elem of v is: 3.4
Settability of v: true
3.1415
*/
|
eksant/mtc
|
Amtc/src/views/Checklist/index.js
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { StyleSheet, View, ScrollView, Text } from 'react-native'
import { Actions } from 'react-native-router-flux'
import FAIcon from 'react-native-vector-icons/FontAwesome'
import { Container, Body, Header, Left, Right, Tab, Tabs, ScrollableTab, Button } from 'native-base'
import ConnectAlert from '../../components/ConnectAlert'
import { getChecklist, createCheckList } from '../../store/checklist/checklist.actions'
import BasicInfo from './BasicInfo'
import CheckKondisi from './CheckKondisi'
class Checklist extends Component {
constructor(props) {
super(props)
this.state = {
currentTab: 0,
nopol: null,
mobiltangkiId: '',
status: 'Waiting',
ritase: '',
odoKM: '',
HSSE: '',
PWSAMT: '',
TBBM: '',
remarks: '',
imgUrl: '',
itemsKondisi: [
{
name: '<NAME>',
status: 0,
reason: '',
},
{
name: '<NAME>',
status: 0,
reason: '',
},
{
name: '<NAME>',
status: 0,
reason: '',
},
{
name: '<NAME>',
status: 0,
reason: '',
},
],
itemsKondisi2: [
{
name: '<NAME>',
status: 0,
reason: '',
},
{
name: '<NAME>',
status: 0,
reason: '',
},
{
name: '<NAME>',
status: 0,
reason: '',
},
{
name: '<NAME>',
status: 0,
reason: '',
},
],
itemsKeberadaan: [
{
name: '<NAME>',
status: 0,
reason: '',
},
{
name: 'Keberadaan Surat Keur',
status: 0,
reason: '',
},
{
name: 'Keberadaan Surat Tera',
status: 0,
reason: '',
},
{
name: 'Keberadaan P3K',
status: 0,
reason: '',
},
{
name: 'Keberadaan Flame Trap',
status: 0,
reason: '',
},
],
itemsKeberadaan2: [
{
name: 'Keberadaan Ban Serep',
status: 0,
reason: '',
},
{
name: 'Keberadaan Toolkit',
status: 0,
reason: '',
},
{
name: 'Keberadaan Grounding Cable',
status: 0,
reason: '',
},
{
name: 'Keberadaan Selang Bongkar',
status: 0,
reason: '',
},
{
name: 'Keberadaan Spill Kit',
status: 0,
reason: '',
},
],
itemsMembawa: [
{
name: 'Membawa SIM',
status: 0,
reason: '',
},
{
name: 'Membawa Surat Ijin Area',
status: 0,
reason: '',
},
{
name: 'Membawa Buku Saku',
status: 0,
reason: '',
},
{
name: 'Membawa Catatan Perjalanan',
status: 0,
reason: '',
},
],
itemsMenggunakan: [
{
name: 'Menggunakan Seragam',
status: 0,
reason: '',
},
{
name: 'Menggunakan Safety Shoes',
status: 0,
reason: '',
},
{
name: 'Menggunakan Safety Helm',
status: 0,
reason: '',
},
],
itemsMenggunakan2: [
{
name: 'Menggunakan ID Card',
status: 0,
reason: '',
},
{
name: 'Menggunakan Sarung Tangan',
status: 0,
reason: '',
},
{
name: '<NAME>',
status: 0,
reason: '',
},
],
}
this.baseState = this.state
this.handleChangeStatus = this.handleChangeStatus.bind(this)
this.handleChangeReason = this.handleChangeReason.bind(this)
}
handleSubmit = () => {
const item = {
mobiltangkiId: this.state.mobiltangkiId,
status: this.state.status,
ritase: Number(this.state.ritase),
odoKM: Number(this.state.odoKM),
HSSE: this.state.HSSE,
PWSAMT: this.state.PWSAMT,
TBBM: this.state.TBBM,
remarks: this.state.remarks,
imgUrl: this.state.imgUrl,
kondisiRem: Number(this.state.itemsKondisi[0].status),
kondisiRemReason: this.state.itemsKondisi[0].reason,
kondisiBan: Number(this.state.itemsKondisi[1].status),
kondisiBanReason: this.state.itemsKondisi[1].reason,
kondisiWiper: Number(this.state.itemsKondisi[2].status),
kondisiWiperReason: this.state.itemsKondisi[2].reason,
kondisiLampu: Number(this.state.itemsKondisi[3].status),
kondisiLampuReason: this.state.itemsKondisi[3].reason,
kondisiKompartemen: Number(this.state.itemsKondisi2[0].status),
kondisiKompartemenReason: this.state.itemsKondisi2[0].reason,
kondisiApar: Number(this.state.itemsKondisi2[1].status),
kondisiAparReason: this.state.itemsKondisi2[1].reason,
kondisiOliMesin: Number(this.state.itemsKondisi2[2].status),
kondisiOliMesinReason: this.state.itemsKondisi2[2].reason,
kondisiAirRadiator: Number(this.state.itemsKondisi2[3].status),
kondisiAirRadiatorReason: this.state.itemsKondisi2[3].reason,
keberadaanSTNK: Number(this.state.itemsKeberadaan[0].status),
keberadaanSTNKReason: this.state.itemsKeberadaan[0].reason,
keberadaanSuratKeur: Number(this.state.itemsKeberadaan[1].status),
keberadaanSuratKeurReason: this.state.itemsKeberadaan[1].reason,
keberadaanSuratTera: Number(this.state.itemsKeberadaan[2].status),
keberadaanSuratTeraReason: this.state.itemsKeberadaan[2].reason,
keberadaanP3K: Number(this.state.itemsKeberadaan[3].status),
keberadaanP3KReason: this.state.itemsKeberadaan[3].reason,
keberadaanFlameTrap: Number(this.state.itemsKeberadaan[4].status),
keberadaanFlameTrapReason: this.state.itemsKeberadaan[4].reason,
keberadaanBanSerep: Number(this.state.itemsKeberadaan2[0].status),
keberadaanBanSerepReason: this.state.itemsKeberadaan2[0].reason,
keberadaanToolkit: Number(this.state.itemsKeberadaan2[1].status),
keberadaanToolKitReason: this.state.itemsKeberadaan2[1].reason,
keberadaanGroundingCable: Number(this.state.itemsKeberadaan2[2].status),
keberadaanGroundingCableReason: this.state.itemsKeberadaan2[2].reason,
keberadaanSelangBongkar: Number(this.state.itemsKeberadaan2[3].status),
keberadaanSelangBongkarReason: this.state.itemsKeberadaan2[3].reason,
keberadaanSpillKit: Number(this.state.itemsKeberadaan2[4].status),
keberadaanSpillKitReason: this.state.itemsKeberadaan2[4].reason,
membawaSIM: Number(this.state.itemsMembawa[0].status),
membawaSIMReason: this.state.itemsMembawa[0].reason,
membawaSuratIjinArea: Number(this.state.itemsMembawa[1].status),
membawaSuratIjinAreaReason: this.state.itemsMembawa[1].reason,
membawaBukuSaku: Number(this.state.itemsMembawa[2].status),
membawaBukuSakuReason: this.state.itemsMembawa[2].reason,
membawaCatatanPerjalanan: Number(this.state.itemsMembawa[3].status),
membawaCatatanPerjalananReason: this.state.itemsMembawa[3].reason,
menggunakanSeragam: Number(this.state.itemsMenggunakan[0].status),
menggunakanSeragamReason: this.state.itemsMenggunakan[0].reason,
menggunakanSafetyShoes: Number(this.state.itemsMenggunakan[1].status),
menggunakanSafetyShoesReason: this.state.itemsMenggunakan[1].reason,
menggunakanSafetyHelm: Number(this.state.itemsMenggunakan[2].status),
menggunakanSafetyHelmReason: this.state.itemsMenggunakan[2].reason,
menggunakanIDCard: Number(this.state.itemsMenggunakan2[0].status),
menggunakanIDCardReason: this.state.itemsMenggunakan2[0].reason,
menggunakanSarungTangan: Number(this.state.itemsMenggunakan2[1].status),
menggunakanSarungTanganReason: this.state.itemsMenggunakan2[1].reason,
menggunakanJasHujan: Number(this.state.itemsMenggunakan2[2].status),
menggunakanJamHujanReason: this.state.itemsMenggunakan2[2].reason,
}
// console.log('ITEM ===', item)
this.props
.createCheckList(item)
.then(async resp => {
if (resp.status === 200) {
this.props.alertWithType('success', 'Success', 'Data success to submit!')
await this.props.getChecklist()
Actions.replace('dashboard')
} else {
this.props.alertWithType('error', 'Error', resp.message)
}
})
.catch(err => {
this.props.alertWithType('error', 'Error', err)
})
}
handleClear() {
this.setState(this.baseState)
}
handleChangeStatus(index) {
const { currentTab } = this.state
if (currentTab === 1) {
let itemsKondisi = [...this.state.itemsKondisi]
let item = { ...itemsKondisi[index] }
item.status === 0 ? (item.status = 1) : (item.status = 0)
item.reason = ''
itemsKondisi[index] = item
this.setState({ itemsKondisi })
} else if (currentTab === 2) {
let itemsKondisi2 = [...this.state.itemsKondisi2]
let item = { ...itemsKondisi2[index] }
item.status === 0 ? (item.status = 1) : (item.status = 0)
item.reason = ''
itemsKondisi2[index] = item
this.setState({ itemsKondisi2 })
} else if (currentTab === 3) {
let itemsKeberadaan = [...this.state.itemsKeberadaan]
let item = { ...itemsKeberadaan[index] }
item.status === 0 ? (item.status = 1) : (item.status = 0)
item.reason = ''
itemsKeberadaan[index] = item
this.setState({ itemsKeberadaan })
} else if (currentTab === 4) {
let itemsKeberadaan2 = [...this.state.itemsKeberadaan2]
let item = { ...itemsKeberadaan2[index] }
item.status === 0 ? (item.status = 1) : (item.status = 0)
item.reason = ''
itemsKeberadaan2[index] = item
this.setState({ itemsKeberadaan2 })
} else if (currentTab === 5) {
let itemsMembawa = [...this.state.itemsMembawa]
let item = { ...itemsMembawa[index] }
item.status === 0 ? (item.status = 1) : (item.status = 0)
item.reason = ''
itemsMembawa[index] = item
this.setState({ itemsMembawa })
} else if (currentTab === 6) {
let itemsMenggunakan = [...this.state.itemsMenggunakan]
let item = { ...itemsMenggunakan[index] }
item.status === 0 ? (item.status = 1) : (item.status = 0)
item.reason = ''
itemsMenggunakan[index] = item
this.setState({ itemsMenggunakan })
} else if (currentTab === 7) {
let itemsMenggunakan2 = [...this.state.itemsMenggunakan2]
let item = { ...itemsMenggunakan2[index] }
item.status === 0 ? (item.status = 1) : (item.status = 0)
item.reason = ''
itemsMenggunakan2[index] = item
this.setState({ itemsMenggunakan2 })
}
}
handleChangeReason(index, value) {
const { currentTab } = this.state
if (currentTab === 1) {
let itemsKondisi = [...this.state.itemsKondisi]
let item = { ...itemsKondisi[index] }
item.reason = value
itemsKondisi[index] = item
this.setState({ itemsKondisi })
} else if (currentTab === 2) {
let itemsKondisi2 = [...this.state.itemsKondisi2]
let item = { ...itemsKondisi2[index] }
item.reason = value
itemsKondisi2[index] = item
this.setState({ itemsKondisi2 })
} else if (currentTab === 3) {
let itemsKeberadaan = [...this.state.itemsKeberadaan]
let item = { ...itemsKeberadaan[index] }
item.reason = value
itemsKeberadaan[index] = item
this.setState({ itemsKeberadaan })
} else if (currentTab === 4) {
let itemsKeberadaan2 = [...this.state.itemsKeberadaan2]
let item = { ...itemsKeberadaan2[index] }
item.reason = value
itemsKeberadaan2[index] = item
this.setState({ itemsKeberadaan2 })
} else if (currentTab === 5) {
let itemsMembawa = [...this.state.itemsMembawa]
let item = { ...itemsMembawa[index] }
item.reason = value
itemsMembawa[index] = item
this.setState({ itemsMembawa })
} else if (currentTab === 6) {
let itemsMenggunakan = [...this.state.itemsMenggunakan]
let item = { ...itemsMenggunakan[index] }
item.reason = value
itemsMenggunakan[index] = item
this.setState({ itemsMenggunakan })
} else if (currentTab === 7) {
let itemsMenggunakan2 = [...this.state.itemsMenggunakan2]
let item = { ...itemsMenggunakan2[index] }
item.reason = value
itemsMenggunakan2[index] = item
this.setState({ itemsMenggunakan2 })
}
}
async componentDidMount() {
const { amt } = this.props
if (amt) {
await this.setState({
nopol: amt.nopol,
mobiltangkiId: amt._id,
})
}
}
onChangeTab = ({ i }) => {
this.setState({ currentTab: i })
}
onActionBack() {
Actions.pop()
}
render() {
return (
<Container>
<Header hasTabs>
<Left style={styles.headerLeftButton}>
<Button transparent onPress={() => Actions.replace('dashboard')}>
<FAIcon name={'chevron-circle-left'} size={22} style={styles.headerIcon} />
</Button>
</Left>
<Body style={styles.headerTitleContent}>
<Text style={styles.headerTitle}>Form Checklist</Text>
</Body>
<Right style={styles.headerRightButton}>
<Button transparent onPress={() => this.handleSubmit()}>
<FAIcon name={'save'} size={22} style={styles.headerIcon} />
</Button>
<Button transparent onPress={() => this.handleClear()}>
<FAIcon name={'refresh'} size={22} style={styles.headerIcon} />
</Button>
</Right>
</Header>
<Tabs
renderTabBar={() => <ScrollableTab />}
initialPage={this.state.currentTab}
onChangeTab={this.onChangeTab}
>
<Tab heading="Basic Info" tabStyle={styles.tabStyle}>
<BasicInfo
data={this.state}
setState={p => {
this.setState(p)
}}
/>
</Tab>
<Tab heading="Cek Kondisi 1" tabStyle={styles.tabStyle}>
<CheckKondisi
data={this.state.itemsKondisi}
onChangeStatus={this.handleChangeStatus}
onChangeReason={this.handleChangeReason}
/>
</Tab>
<Tab heading="Cek Kondisi 2" tabStyle={styles.tabStyle}>
<CheckKondisi
data={this.state.itemsKondisi2}
onChangeStatus={this.handleChangeStatus}
onChangeReason={this.handleChangeReason}
/>
</Tab>
<Tab heading="Cek Keberadaan 1" tabStyle={styles.tabStyle}>
<CheckKondisi
data={this.state.itemsKeberadaan}
onChangeStatus={this.handleChangeStatus}
onChangeReason={this.handleChangeReason}
/>
</Tab>
<Tab heading="Cek Keberadaan 2" tabStyle={styles.tabStyle}>
<CheckKondisi
data={this.state.itemsKeberadaan2}
onChangeStatus={this.handleChangeStatus}
onChangeReason={this.handleChangeReason}
/>
</Tab>
<Tab heading="Cek Bawaan" tabStyle={styles.tabStyle}>
<CheckKondisi
data={this.state.itemsMembawa}
onChangeStatus={this.handleChangeStatus}
onChangeReason={this.handleChangeReason}
/>
</Tab>
<Tab heading="Cek Penggunaan 1" tabStyle={styles.tabStyle}>
<CheckKondisi
data={this.state.itemsMenggunakan}
onChangeStatus={this.handleChangeStatus}
onChangeReason={this.handleChangeReason}
/>
</Tab>
<Tab heading="Cek Penggunaan 2" tabStyle={styles.tabStyle}>
<CheckKondisi
data={this.state.itemsMenggunakan2}
onChangeStatus={this.handleChangeStatus}
onChangeReason={this.handleChangeReason}
/>
</Tab>
</Tabs>
</Container>
)
}
}
const styles = StyleSheet.create({
content: {
padding: 0,
},
header: {
borderBottomWidth: 0.5,
backgroundColor: '#4553B4',
borderBottomColor: '#CBCBCB',
},
headerLeftButton: {
flex: 1,
},
headerIcon: {
color: '#fff',
},
headerTitleContent: {
alignSelf: 'center',
},
headerTitle: {
color: '#fff',
alignItems: 'center',
},
headerRightButton: {
flex: 1,
},
tabStyle: {
backgroundColor: '#3E52D7',
},
})
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
getChecklist,
createCheckList,
},
dispatch
)
export default connect(
null,
mapDispatchToProps
)(ConnectAlert(Checklist))
|
dbajgoric/playground
|
prog-languages/javascript/samples/rest_params.js
|
<filename>prog-languages/javascript/samples/rest_params.js
/**
* Illustrates JavaScript rest parameters introduced in ES6.
*/
describe("Rest Parameters", function () {
it('illustrates rest parameters', function () {
function fnWithRestParameters(first, ...other_params) {
return other_params;
}
expect(fnWithRestParameters(-4, 3, 0, 1, 2, -5, 9)).toEqual([3, 0, 1, 2, -5, 9]);
});
it('illustrates using rest parameter to sum all function arguments', function () {
function sumVariadicRestParam(...args) {
var sum = 0;
for (var arg of args) {
sum += arg;
}
return sum;
}
expect(sumVariadicRestParam(4, 5, 1)).toEqual(10);
expect(sumVariadicRestParam(7, -5, 10, -11, -1)).toEqual(0);
});
});
|
craig-l/js-wark
|
lib/modules/map/index.js
|
<reponame>craig-l/js-wark<gh_stars>0
import { combine } from '../../'
const map = mappingFn => stream =>
combine
(([ stream ], self) => self.set(mappingFn(stream.get())))
([ stream ])
export default map
|
Daniel-Fonseca-da-Silva/Agilidade-e-TDD-um-dia-no-desenvolvimento-de-software
|
src/main/java/br/com/caelum/clines/shared/domain/Airport.java
|
<filename>src/main/java/br/com/caelum/clines/shared/domain/Airport.java<gh_stars>1-10
package br.com.caelum.clines.shared.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Getter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "airports")
public class Airport {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String code;
@NotNull
@ManyToOne
@JoinColumn(name = "location_id")
private Location location;
public Airport(String code, Location location) {
this.code = code;
this.location = location;
}
}
|
evrardjp/carrier
|
deployments/registry.go
|
<gh_stars>0
package deployments
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/avast/retry-go"
"github.com/epinio/epinio/helpers"
"github.com/epinio/epinio/helpers/kubernetes"
"github.com/epinio/epinio/helpers/termui"
"github.com/epinio/epinio/internal/auth"
"github.com/epinio/epinio/internal/duration"
"github.com/go-logr/logr"
"github.com/kyokomi/emoji"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type Registry struct {
Debug bool
Timeout time.Duration
Log logr.Logger
}
var _ kubernetes.Deployment = &Registry{}
const (
RegistryDeploymentID = "epinio-registry"
RegistryCertSecret = "epinio-registry-tls"
registryVersion = "0.1.0"
registryChartFile = "container-registry-0.1.0.tgz"
)
var registryAuthMemo *auth.PasswordAuth
func RegistryInstallAuth() (*auth.PasswordAuth, error) {
if registryAuthMemo == nil {
auth, err := auth.RandomPasswordAuth()
if err != nil {
return nil, err
}
registryAuthMemo = auth
}
return registryAuthMemo, nil
}
func (k Registry) ID() string {
return RegistryDeploymentID
}
func (k Registry) Describe() string {
return emoji.Sprintf(":cloud:Registry version: %s\n:clipboard:Registry chart: %s", registryVersion, registryChartFile)
}
func (k Registry) PreDeployCheck(ctx context.Context, c *kubernetes.Cluster, ui *termui.UI, options kubernetes.InstallationOptions) error {
return nil
}
func (k Registry) PostDeleteCheck(ctx context.Context, c *kubernetes.Cluster, ui *termui.UI) error {
err := c.WaitForNamespaceMissing(ctx, ui, RegistryDeploymentID, k.Timeout)
if err != nil {
return errors.Wrap(err, "failed to delete namespace")
}
ui.Success().Msg("Registry removed")
return nil
}
// Delete removes Registry from kubernetes cluster
func (k Registry) Delete(ctx context.Context, c *kubernetes.Cluster, ui *termui.UI) error {
ui.Note().KeeplineUnder(1).Msg("Removing Registry...")
existsAndOwned, err := c.NamespaceExistsAndOwned(ctx, RegistryDeploymentID)
if err != nil {
return errors.Wrapf(err, "failed to check if namespace '%s' is owned or not", RegistryDeploymentID)
}
if !existsAndOwned {
ui.Exclamation().Msg("Skipping Registry because namespace either doesn't exist or not owned by Epinio")
return nil
}
currentdir, err := os.Getwd()
if err != nil {
return errors.New("Failed uninstalling Registry: " + err.Error())
}
message := "Removing helm release " + RegistryDeploymentID
out, err := helpers.WaitForCommandCompletion(ui, message,
func() (string, error) {
return helpers.RunProc(currentdir, k.Debug,
"helm", "uninstall", RegistryDeploymentID, "--namespace", RegistryDeploymentID)
},
)
if err != nil {
if strings.Contains(out, "release: not found") {
ui.Exclamation().Msgf("%s helm release not found, skipping.\n", RegistryDeploymentID)
} else {
return errors.Wrapf(err, "Failed uninstalling helm release %s: %s", RegistryDeploymentID, out)
}
}
message = "Deleting Registry namespace " + RegistryDeploymentID
_, err = helpers.WaitForCommandCompletion(ui, message,
func() (string, error) {
return "", c.DeleteNamespace(ctx, RegistryDeploymentID)
},
)
if err != nil {
return errors.Wrapf(err, "Failed deleting namespace %s", RegistryDeploymentID)
}
return nil
}
func (k Registry) apply(ctx context.Context, c *kubernetes.Cluster, ui *termui.UI, options kubernetes.InstallationOptions, upgrade bool, log logr.Logger) error {
// Generate random credentials
registryAuth, err := RegistryInstallAuth()
if err != nil {
return err
}
action := "install"
if upgrade {
action = "upgrade"
}
log.Info("creating namespace", "namespace", RegistryDeploymentID)
if err := c.CreateNamespace(ctx, RegistryDeploymentID, map[string]string{
kubernetes.EpinioDeploymentLabelKey: kubernetes.EpinioDeploymentLabelValue,
}, map[string]string{"linkerd.io/inject": "enabled"}); err != nil {
return err
}
currentdir, err := os.Getwd()
if err != nil {
return err
}
log.Info("extracting chart file", "name", registryChartFile)
tarPath, err := helpers.ExtractFile(registryChartFile)
if err != nil {
return errors.New("Failed to extract embedded file: " + tarPath + " - " + err.Error())
}
defer os.Remove(tarPath)
log.Info("local transient tar archive", "name", tarPath)
htpasswd, err := registryAuth.Htpassword()
if err != nil {
return errors.Wrap(err, "Failed to hash credentials")
}
log.Info("htpasswd from credentials", "htpasswd", htpasswd)
domain, err := options.GetString("system_domain", TektonDeploymentID)
if err != nil {
return errors.Wrap(err, "Couldn't get system_domain option")
}
log.Info("system domain", "domain", domain)
if err := k.createCertificate(ctx, c, options, ui, log); err != nil {
return errors.Wrap(err, "creating Registry TLS certificate")
}
log.Info("assembling helm command")
// (**) See also `deployments/tekton.go`, func `createClusterRegistryCredsSecret`.
helmArgs := []string{
action, RegistryDeploymentID,
`--namespace`, RegistryDeploymentID,
tarPath,
`--set`, `auth.htpasswd=` + htpasswd,
`--set`, fmt.Sprintf("domain=%s.%s", RegistryDeploymentID, domain),
`--set`, fmt.Sprintf(`createNodePort=%v`, options.GetBoolNG("use-internal-registry-node-port")),
}
log.Info("assembled helm command", "command", strings.Join(append([]string{`helm`}, helmArgs...), " "))
log.Info("run helm command")
if out, err := helpers.RunProc(currentdir, k.Debug, "helm", helmArgs...); err != nil {
return errors.New("Failed installing Registry: " + out)
}
log.Info("completed helm command")
log.Info("waiting for pods to exist")
if err := c.WaitUntilPodBySelectorExist(ctx, ui, RegistryDeploymentID, "app.kubernetes.io/name=container-registry",
duration.ToPodReady()); err != nil {
return errors.Wrap(err, "failed waiting Registry deployment to come up")
}
log.Info("waiting for pods to run")
if err := c.WaitForPodBySelectorRunning(ctx, ui, RegistryDeploymentID, "app.kubernetes.io/name=container-registry",
duration.ToPodReady()); err != nil {
return errors.Wrap(err, "failed waiting Registry deployment to come up")
}
ui.Success().Msg("Registry deployed")
return nil
}
func (k Registry) GetVersion() string {
return registryVersion
}
func (k Registry) Deploy(ctx context.Context, c *kubernetes.Cluster, ui *termui.UI, options kubernetes.InstallationOptions) error {
log := k.Log.WithName("Deploy")
log.Info("start")
defer log.Info("return")
_, err := c.Kubectl.CoreV1().Namespaces().Get(
ctx,
RegistryDeploymentID,
metav1.GetOptions{},
)
if err == nil {
return errors.New("Namespace " + RegistryDeploymentID + " present already")
}
ui.Note().KeeplineUnder(1).Msg("Deploying Registry...")
err = k.apply(ctx, c, ui, options, false, log)
if err != nil {
return err
}
return nil
}
func (k Registry) createCertificate(ctx context.Context, c *kubernetes.Cluster, options kubernetes.InstallationOptions, ui *termui.UI, log logr.Logger) error {
domain, err := options.GetString("system_domain", TektonDeploymentID)
if err != nil {
return errors.Wrap(err, "Couldn't get system_domain option")
}
log.Info("create properly annotated secret")
// We need the empty certificate secret with a specific annotation
// for it to be copied into `tekton-staging` namespace
// https://cert-manager.io/docs/faq/kubed/#syncing-arbitrary-secrets-across-namespaces-using-kubed
// TODO: We won't need to create an empty secret as soon as this is resolved:
// https://github.com/jetstack/cert-manager/issues/2576
// https://github.com/jetstack/cert-manager/pull/3828
emptySecret := v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: RegistryCertSecret,
Namespace: RegistryDeploymentID,
Annotations: map[string]string{
"kubed.appscode.com/sync": fmt.Sprintf("cert-manager-tls=%s", RegistryDeploymentID),
},
},
Type: v1.SecretTypeTLS,
Data: map[string][]byte{
"ca.crt": nil,
"tls.crt": nil,
"tls.key": nil,
},
}
err = c.CreateSecret(ctx, RegistryDeploymentID, emptySecret)
if err != nil {
return err
}
// Wait for the cert manager to be present and active. It is required
log.Info("waiting for cert manager to be present and active")
issuer := options.GetStringNG("tls-issuer")
if err := waitForCertManagerReady(ctx, ui, c, issuer); err != nil {
return errors.Wrap(err, "waiting for cert manager to be ready")
}
log.Info("issue registry cert")
// Workaround for cert-manager webhook service not being immediately ready.
// More here: https://cert-manager.io/v1.2-docs/concepts/webhook/#webhook-connection-problems-shortly-after-cert-manager-installation
cert := auth.CertParam{
Namespace: RegistryDeploymentID,
Name: RegistryDeploymentID,
Issuer: issuer,
Domain: domain,
}
err = retry.Do(func() error {
return auth.CreateCertificate(ctx, c, cert, nil)
},
retry.RetryIf(func(err error) bool {
return helpers.Retryable(err.Error())
}),
retry.OnRetry(func(n uint, err error) {
ui.Note().Msgf("retrying to create the epinio cert using cert-manager")
}),
retry.Delay(5*time.Second),
retry.Attempts(10),
)
if err != nil {
return errors.Wrap(err, "failed trying to create the epinio API server cert")
}
// Wait until the cert is there before we create the Ingress
if _, err := c.WaitForSecret(ctx, RegistryDeploymentID, RegistryDeploymentID+"-tls", duration.ToSecretCopied()); err != nil {
return errors.Wrap(err, "waiting for the Registry tls certificate to be created")
}
return nil
}
func (k Registry) Upgrade(ctx context.Context, c *kubernetes.Cluster, ui *termui.UI, options kubernetes.InstallationOptions) error {
log := k.Log.WithName("Upgrade")
log.Info("start")
defer log.Info("return")
_, err := c.Kubectl.CoreV1().Namespaces().Get(
ctx,
RegistryDeploymentID,
metav1.GetOptions{},
)
if err != nil {
return errors.New("Namespace " + RegistryDeploymentID + " not present")
}
ui.Note().Msg("Upgrading Registry...")
return k.apply(ctx, c, ui, options, true, log)
}
|
ton31337/batfish
|
projects/question/src/test/java/org/batfish/question/edges/EdgesTest.java
|
package org.batfish.question.edges;
import static org.batfish.datamodel.vxlan.Layer2Vni.testBuilder;
import static org.batfish.question.edges.EdgesAnswerer.COL_INTERFACE;
import static org.batfish.question.edges.EdgesAnswerer.COL_MULTICAST_GROUP;
import static org.batfish.question.edges.EdgesAnswerer.COL_NODE;
import static org.batfish.question.edges.EdgesAnswerer.COL_REMOTE_INTERFACE;
import static org.batfish.question.edges.EdgesAnswerer.COL_REMOTE_NODE;
import static org.batfish.question.edges.EdgesAnswerer.COL_REMOTE_VLAN;
import static org.batfish.question.edges.EdgesAnswerer.COL_REMOTE_VTEP_ADDRESS;
import static org.batfish.question.edges.EdgesAnswerer.COL_UDP_PORT;
import static org.batfish.question.edges.EdgesAnswerer.COL_VLAN;
import static org.batfish.question.edges.EdgesAnswerer.COL_VNI;
import static org.batfish.question.edges.EdgesAnswerer.COL_VTEP_ADDRESS;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import javax.annotation.Nonnull;
import org.batfish.common.NetworkSnapshot;
import org.batfish.common.plugin.IBatfishTestAdapter;
import org.batfish.common.topology.Layer1Edge;
import org.batfish.common.topology.Layer1Node;
import org.batfish.common.topology.Layer1Topology;
import org.batfish.common.topology.TopologyProvider;
import org.batfish.datamodel.BumTransportMethod;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.ConfigurationFormat;
import org.batfish.datamodel.Interface;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.NetworkFactory;
import org.batfish.datamodel.Topology;
import org.batfish.datamodel.Vrf;
import org.batfish.datamodel.collections.NodeInterfacePair;
import org.batfish.datamodel.pojo.Node;
import org.batfish.datamodel.table.Row;
import org.batfish.datamodel.table.TableAnswerElement;
import org.batfish.datamodel.vxlan.Layer2Vni;
import org.batfish.identifiers.NetworkId;
import org.batfish.identifiers.SnapshotId;
import org.batfish.question.edges.EdgesQuestion.EdgeType;
import org.batfish.specifier.Location;
import org.batfish.specifier.LocationInfo;
import org.junit.Before;
import org.junit.Test;
/** End-to-end tests of {@link org.batfish.question.edges}. */
public final class EdgesTest {
private NetworkFactory _nf;
private Configuration.Builder _cb;
private Vrf.Builder _vb;
private Interface.Builder _ib;
@Before
public void setup() {
_nf = new NetworkFactory();
_cb = _nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS);
_vb = _nf.vrfBuilder().setName(Configuration.DEFAULT_VRF_NAME);
_ib = _nf.interfaceBuilder();
}
@Test
public void testAnswerLayer1() {
String c1Name = "c1";
String c2Name = "c2";
String c1a1Name = "c1a1";
String c1i1aName = "c1i1a";
String c1i1bName = "c1i1b";
String c2a1Name = "c2a1";
String c2i1aName = "c2i1a";
String c2i1bName = "c2i1b";
// A pair of physical interfaces on first node is connected to a pair of physical interfaces on
// second node. On each node, the pair is aggregated into a port-channel in the layer-1 logical
// topology.
Configuration c1 = _cb.setHostname(c1Name).build();
Vrf v1 = _vb.setOwner(c1).build();
_ib.setOwner(c1).setVrf(v1);
_ib.setName(c1i1aName).build().setChannelGroup(c1a1Name);
_ib.setName(c1i1bName).build().setChannelGroup(c1a1Name);
_ib.setName(c1a1Name).build();
Configuration c2 = _cb.setHostname(c2Name).build();
Vrf v2 = _vb.setOwner(c2).build();
_ib.setOwner(c2).setVrf(v2);
_ib.setName(c2a1Name).build();
_ib.setName(c2i1aName).build().setChannelGroup(c2a1Name);
_ib.setName(c2i1bName).build().setChannelGroup(c2a1Name);
SortedMap<String, Configuration> configurations = ImmutableSortedMap.of(c1Name, c1, c2Name, c2);
Layer1Topology layer1PhysicalTopology =
new Layer1Topology(
new Layer1Edge(new Layer1Node(c1Name, c1i1aName), new Layer1Node(c2Name, c2i1aName)),
new Layer1Edge(new Layer1Node(c2Name, c2i1aName), new Layer1Node(c1Name, c1i1aName)),
new Layer1Edge(new Layer1Node(c1Name, c1i1bName), new Layer1Node(c2Name, c2i1bName)),
new Layer1Edge(new Layer1Node(c2Name, c2i1bName), new Layer1Node(c1Name, c1i1bName)));
IBatfishTestAdapter batfish =
new IBatfishTestAdapter() {
@Override
public SortedMap<String, Configuration> loadConfigurations(NetworkSnapshot snapshot) {
return configurations;
}
@Override
public NetworkSnapshot getSnapshot() {
return new NetworkSnapshot(new NetworkId("a"), new SnapshotId("b"));
}
@Override
public Map<Location, LocationInfo> getLocationInfo(NetworkSnapshot networkSnapshot) {
return ImmutableMap.of();
}
@Override
public TopologyProvider getTopologyProvider() {
return new TopologyProviderTestAdapter(this) {
@Override
public Topology getInitialLayer3Topology(NetworkSnapshot networkSnapshot) {
return new Topology(ImmutableSortedSet.of());
}
@Override
public @Nonnull Optional<Layer1Topology> getRawLayer1PhysicalTopology(
NetworkSnapshot networkSnapshot) {
return Optional.of(layer1PhysicalTopology);
}
@Override
public @Nonnull Optional<Layer1Topology> getSynthesizedLayer1Topology(
@Nonnull NetworkSnapshot networkSnapshot) {
return Optional.of(Layer1Topology.EMPTY);
}
};
}
};
TableAnswerElement answer =
(TableAnswerElement)
new EdgesAnswerer(new EdgesQuestion(null, null, EdgeType.LAYER1, true), batfish)
.answer(batfish.getSnapshot());
// Each node should have an edge to the other node via the port-channel in the layer-1 logical
// topology.
assertThat(
answer.getRowsList(),
containsInAnyOrder(
Row.builder()
.put(COL_INTERFACE, NodeInterfacePair.of(c1Name, c1a1Name))
.put(COL_REMOTE_INTERFACE, NodeInterfacePair.of(c2Name, c2a1Name))
.build(),
Row.builder()
.put(COL_INTERFACE, NodeInterfacePair.of(c2Name, c2a1Name))
.put(COL_REMOTE_INTERFACE, NodeInterfacePair.of(c1Name, c1a1Name))
.build()));
}
@Test
public void testAnswerVxlan() {
Ip multicastGroup = Ip.parse("192.168.3.11");
String node1 = "n1";
String node2 = "n2";
Ip srcIp1 = Ip.parse("1.1.1.1");
Ip srcIp2 = Ip.parse("2.2.2.2");
int udpPort = 5555;
int vlan1 = 1;
int vlan2 = 2;
int vni = 5000;
Configuration c1 = _cb.setHostname(node1).build();
Configuration c2 = _cb.setHostname(node2).build();
Vrf v1 = _vb.setOwner(c1).build();
Vrf v2 = _vb.setOwner(c2).build();
SortedMap<String, Configuration> configurations = ImmutableSortedMap.of(node1, c1, node2, c2);
Layer2Vni.Builder vniSettingsBuilder =
testBuilder()
.setBumTransportIps(ImmutableSortedSet.of(multicastGroup))
.setBumTransportMethod(BumTransportMethod.MULTICAST_GROUP)
.setUdpPort(udpPort)
.setVni(vni);
Layer2Vni vniSettingsTail = vniSettingsBuilder.setSourceAddress(srcIp1).setVlan(vlan1).build();
v1.setLayer2Vnis(ImmutableSet.of(vniSettingsTail));
v2.setLayer2Vnis(
ImmutableSet.of(vniSettingsBuilder.setSourceAddress(srcIp2).setVlan(vlan2).build()));
IBatfishTestAdapter batfish =
new IBatfishTestAdapter() {
@Override
public SortedMap<String, Configuration> loadConfigurations(NetworkSnapshot snapshot) {
return configurations;
}
@Override
public TopologyProvider getTopologyProvider() {
return new TopologyProviderTestAdapter(this) {
@Override
public Topology getInitialLayer3Topology(NetworkSnapshot networkSnapshot) {
return new Topology(ImmutableSortedSet.of());
}
};
}
@Override
public NetworkSnapshot getSnapshot() {
return new NetworkSnapshot(new NetworkId("a"), new SnapshotId("b"));
}
@Override
public Map<Location, LocationInfo> getLocationInfo(NetworkSnapshot networkSnapshot) {
return ImmutableMap.of();
}
};
TableAnswerElement answer =
(TableAnswerElement)
new EdgesAnswerer(new EdgesQuestion(null, null, EdgeType.VXLAN, true), batfish)
.answer(batfish.getSnapshot());
assertThat(
answer.getRowsList(),
containsInAnyOrder(
Row.builder()
.put(COL_VNI, vni)
.put(COL_NODE, new Node(node1))
.put(COL_REMOTE_NODE, new Node(node2))
.put(COL_VTEP_ADDRESS, srcIp1)
.put(COL_REMOTE_VTEP_ADDRESS, srcIp2)
.put(COL_VLAN, vlan1)
.put(COL_REMOTE_VLAN, vlan2)
.put(COL_UDP_PORT, udpPort)
.put(COL_MULTICAST_GROUP, multicastGroup)
.build(),
Row.builder()
.put(COL_VNI, vni)
.put(COL_NODE, new Node(node2))
.put(COL_REMOTE_NODE, new Node(node1))
.put(COL_VTEP_ADDRESS, srcIp2)
.put(COL_REMOTE_VTEP_ADDRESS, srcIp1)
.put(COL_VLAN, vlan2)
.put(COL_REMOTE_VLAN, vlan1)
.put(COL_UDP_PORT, udpPort)
.put(COL_MULTICAST_GROUP, multicastGroup)
.build()));
}
}
|
alefherrera/gorgory
|
client/src/reducers/ui/menu.js
|
<filename>client/src/reducers/ui/menu.js
import { handleActions } from 'redux-actions';
import { OPEN_MENU, CLOSE_MENU } from '../../constants';
const initialState = {
open: false,
};
export default handleActions(
{
[OPEN_MENU]: state => ({ ...state, open: true }),
[CLOSE_MENU]: state => ({ ...state, open: false }),
},
initialState,
);
|
Akriti3011/GreenApple
|
green_apple_website/drop_a_note/views.py
|
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from drop_a_note.forms import NoteForm
from django.views.decorators.csrf import csrf_protect
from django.core.mail import EmailMessage
from validate_email import validate_email
from django.contrib import messages
def drop_note(request):
return render(request, 'drop_a_note/contact.html')
@csrf_protect
def contact_us(request):
if request.method == 'POST':
note_form = NoteForm(request.POST)
if note_form.is_valid():
notes = note_form.save(commit=False)
email_address = note_form.cleaned_data['email']
note_content = note_form.cleaned_data['note']
name = note_form.cleaned_data['name']
print(email_address + " -> " + str(name) + " -> " + str(
note_content))
notes.save()
value = validate_email(email_address, verify=True)
print(value)
if value is None:
return HttpResponse("invalid mail")
else:
email = EmailMessage('Regarding feedback',
email_address + "\n\n" + note_content,
to=['<EMAIL>',
'<EMAIL>'])
email.send()
email = EmailMessage('Regarding feedback',
"Hey " + name + ",\n\n" + "We have "
"successfully"
" recieved "
"your note!!",
to=[email_address])
email.send()
print('reached')
return HttpResponseRedirect(reverse('home:index'))
else:
print(note_form.errors)
return redirect('home/index.html')
else:
note_form = NoteForm()
return render(request, 'drop_a_note/contact.html',
{'note_form': note_form})
|
raomohan89/GATK
|
src/main/java/org/broadinstitute/hellbender/tools/funcotator/OutputRenderer.java
|
<reponame>raomohan89/GATK
package org.broadinstitute.hellbender.tools.funcotator;
import htsjdk.variant.variantcontext.VariantContext;
import java.util.LinkedHashMap;
import java.util.List;
/**
* An abstract class to allow for writing output for the Funcotator.
* Used to output Funcotations to a location of the user's choice.
* For example, writing out to a VCF file (e.g. {@link org.broadinstitute.hellbender.tools.funcotator.vcfOutput.VcfOutputRenderer}).
* It is also possible to write to a stream, or other connection (e.g. a UDP port)
* at the user's discretion.
* Created by jonn on 8/30/17.
*/
public abstract class OutputRenderer implements AutoCloseable {
//==================================================================================================================
/**
* {@link LinkedHashMap} of manually specified annotations to add to each output in addition to annotations provided
* to {@link OutputRenderer#write(VariantContext, List)}.
*/
protected LinkedHashMap<String, String> manualAnnotations;
/**
* {@link String} representation of {@link OutputRenderer#manualAnnotations} serialized to the output format of this {@link OutputRenderer}.
*/
protected String manualAnnotationSerializedString;
//==================================================================================================================
/**
* Open the {@link OutputRenderer} for writing.
*/
public abstract void open();
/**
* Close the {@link OutputRenderer}.
*/
public abstract void close();
/**
* Write the given {@code variant} and {@code funcotations} to the output file.
* @param variant {@link VariantContext} to write to the file.
* @param funcotations {@link List} of {@link Funcotation} to add to the given {@code variant} on output.
*/
public abstract void write(final VariantContext variant, final List<Funcotation> funcotations);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.