max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
8,772 |
package org.apereo.cas.mongo;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.bson.BsonReader;
import org.bson.BsonTimestamp;
import org.bson.BsonWriter;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.configuration.CodecRegistry;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.time.Clock;
import java.time.ZonedDateTime;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* This is {@link ConvertersTests}.
*
* @author <NAME>
* @since 6.3.0
*/
@Tag("MongoDb")
public class ConvertersTests {
@Test
public void verifyOperation() {
assertNull(new BaseConverters.NullConverter().convert(new Object()));
assertNull(new BaseConverters.StringToZonedDateTimeConverter().convert(StringUtils.EMPTY));
assertNull(new BaseConverters.StringToPatternConverter().convert(StringUtils.EMPTY));
assertNotNull(new BaseConverters.StringToZonedDateTimeConverter().convert(ZonedDateTime.now(Clock.systemUTC()).toString()));
assertNotNull(new BaseConverters.ZonedDateTimeToStringConverter().convert(ZonedDateTime.now(Clock.systemUTC())));
assertNotNull(new BaseConverters.BsonTimestampToDateConverter().convert(new BsonTimestamp()));
assertNotNull(new BaseConverters.BsonTimestampToStringConverter().convert(new BsonTimestamp()));
assertNotNull(new BaseConverters.ZonedDateTimeTransformer().transform(ZonedDateTime.now(Clock.systemUTC())));
val codec = new BaseConverters.ZonedDateTimeCodecProvider().get(ZonedDateTime.class, mock(CodecRegistry.class));
assertNotNull(codec);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
codec.encode(mock(BsonWriter.class), ZonedDateTime.now(Clock.systemUTC()), mock(EncoderContext.class));
val r = mock(BsonReader.class);
when(r.readTimestamp()).thenReturn(new BsonTimestamp());
codec.decode(r, mock(DecoderContext.class));
}
});
assertNotNull(codec.getEncoderClass());
}
}
| 896 |
1,579 |
# You need to install pyaudio to run this example
# pip install pyaudio
# When using a microphone, the AudioSource `input` parameter would be
# initialised as a queue. The pyaudio stream would be continuosly adding
# recordings to the queue, and the websocket client would be sending the
# recordings to the speech to text service
import pyaudio
from ibm_watson import SpeechToTextV1
from ibm_watson.websocket import RecognizeCallback, AudioSource
from threading import Thread
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
try:
from Queue import Queue, Full
except ImportError:
from queue import Queue, Full
###############################################
#### Initalize queue to store the recordings ##
###############################################
CHUNK = 1024
# Note: It will discard if the websocket client can't consumme fast enough
# So, increase the max size as per your choice
BUF_MAX_SIZE = CHUNK * 10
# Buffer to store audio
q = Queue(maxsize=int(round(BUF_MAX_SIZE / CHUNK)))
# Create an instance of AudioSource
audio_source = AudioSource(q, True, True)
###############################################
#### Prepare Speech to Text Service ########
###############################################
# initialize speech to text service
authenticator = IAMAuthenticator('your_api_key')
speech_to_text = SpeechToTextV1(authenticator=authenticator)
# define callback for the speech to text service
class MyRecognizeCallback(RecognizeCallback):
def __init__(self):
RecognizeCallback.__init__(self)
def on_transcription(self, transcript):
print(transcript)
def on_connected(self):
print('Connection was successful')
def on_error(self, error):
print('Error received: {}'.format(error))
def on_inactivity_timeout(self, error):
print('Inactivity timeout: {}'.format(error))
def on_listening(self):
print('Service is listening')
def on_hypothesis(self, hypothesis):
print(hypothesis)
def on_data(self, data):
print(data)
def on_close(self):
print("Connection closed")
# this function will initiate the recognize service and pass in the AudioSource
def recognize_using_weboscket(*args):
mycallback = MyRecognizeCallback()
speech_to_text.recognize_using_websocket(audio=audio_source,
content_type='audio/l16; rate=44100',
recognize_callback=mycallback,
interim_results=True)
###############################################
#### Prepare the for recording using Pyaudio ##
###############################################
# Variables for recording the speech
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
# define callback for pyaudio to store the recording in queue
def pyaudio_callback(in_data, frame_count, time_info, status):
try:
q.put(in_data)
except Full:
pass # discard
return (None, pyaudio.paContinue)
# instantiate pyaudio
audio = pyaudio.PyAudio()
# open stream using callback
stream = audio.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
stream_callback=pyaudio_callback,
start=False
)
#########################################################################
#### Start the recording and start service to recognize the stream ######
#########################################################################
print("Enter CTRL+C to end recording...")
stream.start_stream()
try:
recognize_thread = Thread(target=recognize_using_weboscket, args=())
recognize_thread.start()
while True:
pass
except KeyboardInterrupt:
# stop recording
stream.stop_stream()
stream.close()
audio.terminate()
audio_source.completed_recording()
| 1,260 |
22,779 |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.lang.parser;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
import org.jkiss.dbeaver.lang.SCMKeyword;
import org.jkiss.dbeaver.lang.SCMKeywordToken;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class KeywordRule extends LiteralRule {
private final Map<String, SCMKeyword> keywordMap = new HashMap<>();
private final StringBuilder buffer = new StringBuilder();
public KeywordRule(SCMKeyword[] keywords) {
for (SCMKeyword keyword : keywords) {
this.keywordMap.put(keyword.name(), keyword);
}
}
@Override
public IToken evaluate(ICharacterScanner scanner) {
int c = scanner.read();
if (c != ICharacterScanner.EOF && isWordStart((char) c)) {
buffer.setLength(0);
do {
buffer.append((char)c);
c = scanner.read();
}
while (c != ICharacterScanner.EOF && isWordPart((char) c));
scanner.unread();
SCMKeyword keyword = keywordMap.get(buffer.toString().toUpperCase(Locale.ENGLISH));
if (keyword != null) {
return new SCMKeywordToken(keyword);
}
for (int i = buffer.length() - 1; i > 0; i--) {
scanner.unread();
}
}
scanner.unread();
return Token.UNDEFINED;
}
private boolean isWordStart(char c) {
return Character.isLetter(c);
}
private boolean isWordPart(char c) {
return Character.isJavaIdentifierPart(c);
}
}
| 922 |
688 |
#!/usr/bin/env python3
from .goto import Goto
| 19 |
971 |
package com.ucar.datalink.biz.utils.ddl;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.sql.dialect.postgresql.visitor.PGSchemaStatVisitor;
import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerSchemaStatVisitor;
import com.alibaba.druid.sql.visitor.SchemaStatVisitor;
import com.alibaba.druid.util.JdbcConstants;
import com.google.common.collect.Lists;
import com.ucar.datalink.domain.media.MediaSourceType;
import java.util.List;
/**
* Created by lubiao on 2017/7/12.
*/
public class DdlSqlUtils {
public static List<SQLStatementHolder> buildSQLStatement(MediaSourceType mediaSourceType, String sqls) {
return buildSQLStatement(mediaSourceType,sqls,true);
}
public static List<SQLStatementHolder> buildSQLStatement(MediaSourceType mediaSourceType, String sqls,boolean isPreHandle) {
if(isPreHandle){
sqls = preHandleBeforeCheck(sqls);
}
List<SQLStatement> list = null;
if (MediaSourceType.MYSQL.equals(mediaSourceType) || MediaSourceType.SDDL.equals(mediaSourceType)) {
list = SQLUtils.parseStatements(sqls, JdbcConstants.MYSQL);
} else if (MediaSourceType.SQLSERVER.equals(mediaSourceType)) {
list = SQLUtils.parseStatements(sqls, JdbcConstants.SQL_SERVER);
} else if (MediaSourceType.POSTGRESQL.equals(mediaSourceType)) {
list = SQLUtils.parseStatements(sqls, JdbcConstants.POSTGRESQL);
}
if (list != null && !list.isEmpty()) {
List<SQLStatementHolder> result = Lists.newArrayList();
for (SQLStatement st : list) {
SchemaStatVisitor visitor = null;
if (MediaSourceType.MYSQL.equals(mediaSourceType) || MediaSourceType.SDDL.equals(mediaSourceType)) {
visitor = new MySqlSchemaStatVisitor();
} else if (MediaSourceType.SQLSERVER.equals(mediaSourceType)) {
visitor = new SQLServerSchemaStatVisitor();
} else if (MediaSourceType.POSTGRESQL.equals(mediaSourceType)) {
visitor = new PGSchemaStatVisitor();
}
st.accept(visitor);
result.add(new SQLStatementHolder(st, visitor, mediaSourceType));
}
return result;
}
return Lists.newArrayList();
}
private static String preHandleBeforeCheck(String sqls) {
sqls = sqls.toLowerCase();
sqls = sqls.replaceAll("using\\s+btree", "");
return sqls;
}
}
| 1,152 |
353 |
<reponame>yuqi1129/chronos<filename>chronos-server/src/test/java/com/xiaomi/infra/chronos/TestChronosImplement.java
package com.xiaomi.infra.chronos;
import com.xiaomi.infra.chronos.exception.ChronosException;
import com.xiaomi.infra.chronos.exception.FatalChronosException;
import com.xiaomi.infra.chronos.zookeeper.FailoverServer;
import com.xiaomi.infra.chronos.zookeeper.HostPort;
import com.xiaomi.infra.chronos.zookeeper.ZooKeeperUtil;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.curator.test.TestingServer;
import org.apache.thrift.TException;
import org.apache.zookeeper.KeeperException;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test {@link ChronosImplement}
*/
public class TestChronosImplement {
protected final static Log LOG = LogFactory.getLog(TestChronosImplement.class);
private static TestingServer ZK_SERVER;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ZK_SERVER = new TestingServer(true);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
ZK_SERVER.close();
}
@Before
public void resetZooKeeper()
throws IOException, KeeperException, FatalChronosException, ChronosException {
ChronosImplement chronosImplement = createChronosImplement(new HostPort("127.0.0.1", 10086));
ZooKeeperUtil.deleteNodeRecursively(chronosImplement.getChronosServerWatcher(),
chronosImplement.getChronosServerWatcher().getBaseZnode());
chronosImplement.getChronosServerWatcher().close();
}
private ChronosImplement createChronosImplement(HostPort hostPort)
throws FatalChronosException, ChronosException, IOException {
Properties properties = new Properties();
properties.setProperty(FailoverServer.SERVER_HOST, hostPort.getHost());
properties.setProperty(FailoverServer.SERVER_PORT, String.valueOf(hostPort.getPort()));
properties.setProperty(FailoverServer.BASE_ZNODE, "/chronos/test-cluster");
properties.setProperty(FailoverServer.ZK_QUORUM, ZK_SERVER.getConnectString());
properties.setProperty(FailoverServer.SESSION_TIMEOUT, String.valueOf(3000));
properties.setProperty(ChronosServer.ZK_ADVANCE_TIMESTAMP, "100000");
properties.setProperty(FailoverServer.CONNECT_RETRY_TIMES, String.valueOf(10));
return new ChronosImplement(properties, new ChronosServerWatcher(properties));
}
@Test
public void testGetTimestamp()
throws FatalChronosException, ChronosException, IOException, TException {
ChronosImplement chronosImplement = createChronosImplement(new HostPort("127.0.0.1", 10086));
chronosImplement.initTimestamp();
long firstTimestamp = chronosImplement.getTimestamp();
long secondTimestamp = chronosImplement.getTimestamp();
Assert.assertTrue(firstTimestamp < secondTimestamp);
chronosImplement.getChronosServerWatcher().close();
}
}
| 1,019 |
4,465 |
<filename>bridge/bindings/qjs/qjs_patch.h
/*
* Copyright (C) 2021 Alibaba Inc. All rights reserved.
* Author: <NAME>.
*/
#ifndef KRAKENBRIDGE_QJS_PATCH_H
#define KRAKENBRIDGE_QJS_PATCH_H
#include <quickjs/list.h>
#include <quickjs/quickjs.h>
struct JSString {
JSRefCountHeader header; /* must come first, 32-bit */
uint32_t len : 31;
uint8_t is_wide_char : 1; /* 0 = 8 bits, 1 = 16 bits characters */
/* for JS_ATOM_TYPE_SYMBOL: hash = 0, atom_type = 3,
for JS_ATOM_TYPE_PRIVATE: hash = 1, atom_type = 3
XXX: could change encoding to have one more bit in hash */
uint32_t hash : 30;
uint8_t atom_type : 2; /* != 0 if atom, JS_ATOM_TYPE_x */
uint32_t hash_next; /* atom_index for JS_ATOM_TYPE_SYMBOL */
#ifdef DUMP_LEAKS
struct list_head link; /* string list */
#endif
union {
uint8_t str8[0]; /* 8 bit strings will get an extra null terminator */
uint16_t str16[0];
} u;
};
enum {
/* classid tag */ /* union usage | properties */
JS_CLASS_OBJECT = 1, /* must be first */
JS_CLASS_ARRAY, /* u.array | length */
JS_CLASS_ERROR,
JS_CLASS_NUMBER, /* u.object_data */
JS_CLASS_STRING, /* u.object_data */
JS_CLASS_BOOLEAN, /* u.object_data */
JS_CLASS_SYMBOL, /* u.object_data */
JS_CLASS_ARGUMENTS, /* u.array | length */
JS_CLASS_MAPPED_ARGUMENTS, /* | length */
JS_CLASS_DATE, /* u.object_data */
JS_CLASS_MODULE_NS,
JS_CLASS_C_FUNCTION, /* u.cfunc */
JS_CLASS_BYTECODE_FUNCTION, /* u.func */
JS_CLASS_BOUND_FUNCTION, /* u.bound_function */
JS_CLASS_C_FUNCTION_DATA, /* u.c_function_data_record */
JS_CLASS_GENERATOR_FUNCTION, /* u.func */
JS_CLASS_FOR_IN_ITERATOR, /* u.for_in_iterator */
JS_CLASS_REGEXP, /* u.regexp */
JS_CLASS_ARRAY_BUFFER, /* u.array_buffer */
JS_CLASS_SHARED_ARRAY_BUFFER, /* u.array_buffer */
JS_CLASS_UINT8C_ARRAY, /* u.array (typed_array) */
JS_CLASS_INT8_ARRAY, /* u.array (typed_array) */
JS_CLASS_UINT8_ARRAY, /* u.array (typed_array) */
JS_CLASS_INT16_ARRAY, /* u.array (typed_array) */
JS_CLASS_UINT16_ARRAY, /* u.array (typed_array) */
JS_CLASS_INT32_ARRAY, /* u.array (typed_array) */
JS_CLASS_UINT32_ARRAY, /* u.array (typed_array) */
#ifdef CONFIG_BIGNUM
JS_CLASS_BIG_INT64_ARRAY, /* u.array (typed_array) */
JS_CLASS_BIG_UINT64_ARRAY, /* u.array (typed_array) */
#endif
JS_CLASS_FLOAT32_ARRAY, /* u.array (typed_array) */
JS_CLASS_FLOAT64_ARRAY, /* u.array (typed_array) */
JS_CLASS_DATAVIEW, /* u.typed_array */
#ifdef CONFIG_BIGNUM
JS_CLASS_BIG_INT, /* u.object_data */
JS_CLASS_BIG_FLOAT, /* u.object_data */
JS_CLASS_FLOAT_ENV, /* u.float_env */
JS_CLASS_BIG_DECIMAL, /* u.object_data */
JS_CLASS_OPERATOR_SET, /* u.operator_set */
#endif
JS_CLASS_MAP, /* u.map_state */
JS_CLASS_SET, /* u.map_state */
JS_CLASS_WEAKMAP, /* u.map_state */
JS_CLASS_WEAKSET, /* u.map_state */
JS_CLASS_MAP_ITERATOR, /* u.map_iterator_data */
JS_CLASS_SET_ITERATOR, /* u.map_iterator_data */
JS_CLASS_ARRAY_ITERATOR, /* u.array_iterator_data */
JS_CLASS_STRING_ITERATOR, /* u.array_iterator_data */
JS_CLASS_REGEXP_STRING_ITERATOR, /* u.regexp_string_iterator_data */
JS_CLASS_GENERATOR, /* u.generator_data */
JS_CLASS_PROXY, /* u.proxy_data */
JS_CLASS_PROMISE, /* u.promise_data */
JS_CLASS_PROMISE_RESOLVE_FUNCTION, /* u.promise_function_data */
JS_CLASS_PROMISE_REJECT_FUNCTION, /* u.promise_function_data */
JS_CLASS_ASYNC_FUNCTION, /* u.func */
JS_CLASS_ASYNC_FUNCTION_RESOLVE, /* u.async_function_data */
JS_CLASS_ASYNC_FUNCTION_REJECT, /* u.async_function_data */
JS_CLASS_ASYNC_FROM_SYNC_ITERATOR, /* u.async_from_sync_iterator_data */
JS_CLASS_ASYNC_GENERATOR_FUNCTION, /* u.func */
JS_CLASS_ASYNC_GENERATOR, /* u.async_generator_data */
JS_CLASS_INIT_COUNT, /* last entry for predefined classes */
};
#ifdef __cplusplus
extern "C" {
#endif
uint16_t* JS_ToUnicode(JSContext* ctx, JSValueConst value, uint32_t* length);
JSValue JS_NewUnicodeString(JSRuntime* runtime, JSContext* ctx, const uint16_t* code, uint32_t length);
JSClassID JSValueGetClassId(JSValue);
bool JS_IsProxy(JSValue value);
bool JS_HasClassId(JSRuntime* runtime, JSClassID classId);
JSValue JS_GetProxyTarget(JSValue value);
#ifdef __cplusplus
}
#endif
#endif // KRAKENBRIDGE_QJS_PATCH_H
| 2,207 |
1,374 |
<filename>core-lib/es6/src/main/java/def/dom/NavigatorID.java<gh_stars>1000+
package def.dom;
import def.js.Object;
@jsweet.lang.Interface
public abstract class NavigatorID extends def.js.Object {
public java.lang.String appName;
public java.lang.String appVersion;
public java.lang.String platform;
public java.lang.String product;
public java.lang.String productSub;
public java.lang.String userAgent;
public java.lang.String vendor;
public java.lang.String vendorSub;
}
| 174 |
3,986 |
package com.xuexiang.xuidemo.fragment.expands.chart.line;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xuidemo.R;
import com.xuexiang.xuidemo.fragment.expands.chart.BaseChartFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
/**
* @author xuexiang
* @since 2019/4/14 下午1:03
*/
@Page(name = "MultiLineChart\n多组数据的折线图")
public class MultiLineChartFragment extends BaseChartFragment {
@BindView(R.id.chart1)
LineChart chart;
/**
* 布局的资源id
*
* @return
*/
@Override
protected int getLayoutId() {
return R.layout.fragment_chart_line;
}
/**
* 初始化控件
*/
@Override
protected void initViews() {
initChartStyle();
initChartLabel();
setChartData(20, 100);
}
/**
* 初始化图表的样式
*/
@Override
protected void initChartStyle() {
chart.setDrawGridBackground(false);
chart.getDescription().setEnabled(false);
chart.setDrawBorders(false);
//禁用Y轴左侧
chart.getAxisLeft().setEnabled(false);
//禁用Y轴右侧轴线
chart.getAxisRight().setDrawAxisLine(false);
//不画网格线
chart.getAxisRight().setDrawGridLines(false);
chart.getXAxis().setDrawAxisLine(false);
chart.getXAxis().setDrawGridLines(false);
// 开启手势触摸
chart.setTouchEnabled(true);
// enable scaling and dragging
chart.setDragEnabled(true);
chart.setScaleEnabled(true);
// if disabled, scaling can be done on x- and y-axis separately
chart.setPinchZoom(false);
}
/**
* 初始化图表的 标题 样式
*/
@Override
protected void initChartLabel() {
Legend l = chart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.VERTICAL);
l.setDrawInside(false);
}
/**
* 设置图表数据
*
* @param count 一组数据的数量
* @param range
*/
@Override
protected void setChartData(int count, float range) {
List<ILineDataSet> dataSets = new ArrayList<>();
//三组数据
for (int z = 0; z < 3; z++) {
List<Entry> values = new ArrayList<>();
//设置数据源
for (int i = 0; i < count; i++) {
double val = (Math.random() * range) + 3;
values.add(new Entry(i, (float) val));
}
LineDataSet d = new LineDataSet(values, "DataSet " + (z + 1));
d.setLineWidth(2.5f);
d.setCircleRadius(4f);
int color = colors[z % colors.length];
d.setColor(color);
d.setCircleColor(color);
dataSets.add(d);
}
// 设置第一组数据源为虚线
((LineDataSet) dataSets.get(0)).enableDashedLine(10, 10, 0);
((LineDataSet) dataSets.get(0)).setColors(ColorTemplate.VORDIPLOM_COLORS);
((LineDataSet) dataSets.get(0)).setCircleColors(ColorTemplate.VORDIPLOM_COLORS);
LineData data = new LineData(dataSets);
chart.setData(data);
chart.invalidate();
}
private final int[] colors = new int[] {
ColorTemplate.VORDIPLOM_COLORS[0],
ColorTemplate.VORDIPLOM_COLORS[1],
ColorTemplate.VORDIPLOM_COLORS[2]
};
}
| 1,894 |
1,418 |
package aima.core.logic.common;
/**
* A runtime exception to be used to describe Lexer exceptions. In particular it
* provides information to help in identifying where in the input character
* sequence the exception occurred.
*
* @author <NAME>
*
*/
public class LexerException extends RuntimeException {
private static final long serialVersionUID = 1L;
private int currentPositionInInput;
public LexerException(String message, int currentPositionInInput) {
super(message);
this.currentPositionInInput = currentPositionInInput;
}
public LexerException(String message, int currentPositionInInput,
Throwable cause) {
super(message, cause);
this.currentPositionInInput = currentPositionInInput;
}
/**
*
* @return the current position in the input character stream that the lexer
* was at before the exception was encountered.
*/
public int getCurrentPositionInInputExceptionThrown() {
return currentPositionInInput;
}
}
| 306 |
6,304 |
/*
* Copyright 2021 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "modules/skunicode/src/SkUnicode_icu.h"
#define SKICU_FUNC(funcname) funcname,
// ubrk_clone added as draft in ICU69 and Android API 31 (first ICU NDK).
// ubrk_safeClone deprecated in ICU69 and not exposed by Android.
template<typename...> using void_t = void;
template<typename T, typename = void>
struct SkUbrkClone {
static UBreakIterator* clone(T bi, UErrorCode* status) {
return ubrk_safeClone(bi, nullptr, nullptr, status);
}
};
template<typename T>
struct SkUbrkClone<T, void_t<decltype(ubrk_clone(std::declval<T>(), nullptr))>> {
static UBreakIterator* clone(T bi, UErrorCode* status) {
return ubrk_clone(bi, status);
}
};
std::unique_ptr<SkICULib> SkLoadICULib() {
return std::make_unique<SkICULib>(SkICULib{
SKICU_EMIT_FUNCS
&SkUbrkClone<const UBreakIterator*>::clone,
nullptr,
});
}
| 412 |
2,406 |
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <memory>
#include "ngraph/ngraph_visibility.hpp"
#include "ngraph/node.hpp"
#include "openvino/op/util/op_types.hpp"
namespace ngraph {
namespace op {
using ov::op::util::is_binary_elementwise_arithmetic;
using ov::op::util::is_binary_elementwise_comparison;
using ov::op::util::is_binary_elementwise_logical;
using ov::op::util::is_commutative;
using ov::op::util::is_constant;
using ov::op::util::is_op;
using ov::op::util::is_output;
using ov::op::util::is_parameter;
using ov::op::util::is_sink;
using ov::op::util::is_unary_elementwise_arithmetic;
using ov::op::util::supports_auto_broadcast;
} // namespace op
} // namespace ngraph
| 283 |
678 |
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/FTServices.framework/FTServices
*/
#import <FTServices/FTPushHandler.h>
#import <FTServices/APSConnectionDelegate.h>
@class APSConnection, NSData;
@interface FTEmbeddedPushHandler : FTPushHandler <APSConnectionDelegate> {
APSConnection *_apsConnection; // 16 = 0x10
NSData *_cachedPushToken; // 20 = 0x14
Class _APSConnectionClass; // 24 = 0x18
BOOL _fastUserSwitched; // 28 = 0x1c
int _cachedStatus; // 32 = 0x20
}
- (void)connection:(id)connection didChangeConnectedStatus:(BOOL)status; // 0x14285
- (void)connectionDidReconnect:(id)connection; // 0x14201
- (void)connection:(id)connection didFailToSendOutgoingMessage:(id)sendOutgoingMessage error:(id)error; // 0x141fd
- (void)connection:(id)connection didSendOutgoingMessage:(id)message; // 0x141f9
- (void)connection:(id)connection didReceiveMessageForTopic:(id)topic userInfo:(id)info; // 0x1356d
- (void)connection:(id)connection didReceivePublicToken:(id)token; // 0x132a1
- (void)_handlePendingMessagePush:(id)push; // 0x12f29
- (void)_handleGenericDataPush:(id)push; // 0x129d9
- (void)_handleGenericCommandPush:(id)push; // 0x12519
- (void)_handleEmailConfirmedPush:(id)push; // 0x12195
- (void)_handleIncomingReadReceipt:(id)receipt; // 0x11c41
- (void)_handleIncomingMessageError:(id)error; // 0x116bd
- (void)_handleIncomingDeliveryReceipt:(id)receipt; // 0x11209
- (void)_handleIncomingAttachmentMessage:(id)message; // 0x10bcd
- (void)_handleIncomingTextMessage:(id)message; // 0x10565
- (void)_handleRelayCancelPush:(id)push; // 0xfb39
- (void)_handleRelayUpdatePush:(id)push; // 0xf0c9
- (void)_handleRelayInitatePush:(id)push; // 0xe63d
- (void)_handleSendPush:(id)push; // 0xe095
- (void)_handleCancelPush:(id)push; // 0xdaed
- (void)_handleRejectPush:(id)push; // 0xd499
- (void)_handleAcceptPush:(id)push; // 0xc819
- (void)_handleReregisterPush:(id)push; // 0xc439
- (void)_handleInitatePush:(id)push; // 0xbbe9
- (void)requestKeepAlive; // 0xbba1
- (int)connectionStatus; // 0xbb5d
- (id)pushToken; // 0xbb09
- (void)systemDidFastUserSwitchIn; // 0xba81
- (void)systemDidFastUserSwitchOut; // 0xb9ed
- (void)setRegistered:(BOOL)registered; // 0xb995
- (void)_ignoreIncomingPushes; // 0xb8e5
- (void)_acceptIncomingPushes; // 0xb81d
- (void)updateTopics; // 0xb7dd
- (void)_updateTopics; // 0xb725
- (void)dealloc; // 0xb659
- (id)initWithTopics:(id)topics; // 0xb475
@end
| 968 |
1,209 |
<gh_stars>1000+
/*
u8g_pb.c
common procedures for the page buffer
Universal 8bit Graphics Library
Copyright (c) 2011, <EMAIL>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "u8g.h"
void u8g_pb_Clear(u8g_pb_t *b)
{
uint8_t *ptr = (uint8_t *)b->buf;
uint8_t *end_ptr = ptr;
end_ptr += b->width;
do
{
*ptr++ = 0;
} while( ptr != end_ptr );
}
/* the following procedure does not work. why? Can be checked with descpic */
/*
void u8g_pb_Clear(u8g_pb_t *b)
{
uint8_t *ptr = (uint8_t *)b->buf;
uint8_t cnt = b->width;
do
{
*ptr++ = 0;
cnt--;
} while( cnt != 0 );
}
*/
/*
intersection assumptions:
a1 <= a2 is always true
*/
/*
minimized version
---1----0 1 b1 <= a2 && b1 > b2
-----1--0 1 b2 >= a1 && b1 > b2
---1-1--- 1 b1 <= a2 && b2 >= a1
*/
/*
uint8_t u8g_pb8v1_IsYIntersection___Old(u8g_pb_t *b, u8g_uint_t v0, u8g_uint_t v1)
{
uint8_t c0, c1, c;
c0 = v0 <= b->p.page_y1;
c1 = v1 >= b->p.page_y0;
c = v0 > v1;
if ( c0 && c1 ) return 1;
if ( c0 && c ) return 1;
if ( c1 && c ) return 1;
return 0;
}
*/
uint8_t u8g_pb_IsYIntersection(u8g_pb_t *pb, u8g_uint_t v0, u8g_uint_t v1)
{
uint8_t c1, c2, c3, tmp;
c1 = v0 <= pb->p.page_y1;
c2 = v1 >= pb->p.page_y0;
c3 = v0 > v1;
/*
if ( c1 && c2 )
return 1;
if ( c1 && c3 )
return 1;
if ( c2 && c3 )
return 1;
return 0;
*/
tmp = c1;
c1 &= c2;
c2 &= c3;
c3 &= tmp;
c1 |= c2;
c1 |= c3;
return c1 & 1;
}
uint8_t u8g_pb_IsXIntersection(u8g_pb_t *b, u8g_uint_t v0, u8g_uint_t v1)
{
uint8_t /*c0, c1, */ c2, c3;
/*
conditions: b->p.page_y0 < b->p.page_y1
there are no restriction on v0 and v1. If v0 > v1, then warp around unsigned is assumed
*/
/*
c0 = v0 < 0;
c1 = v1 < 0;
*/
c2 = v0 > b->width;
c3 = v1 > b->width;
/*if ( c0 && c1 ) return 0;*/
if ( c2 && c3 ) return 0;
/*if ( c1 && c2 ) return 0;*/
return 1;
}
uint8_t u8g_pb_IsIntersection(u8g_pb_t *pb, u8g_dev_arg_bbx_t *bbx)
{
u8g_uint_t tmp;
tmp = bbx->y;
tmp += bbx->h;
tmp--;
if ( u8g_pb_IsYIntersection(pb, bbx->y, tmp) == 0 )
return 0;
/* maybe this one can be skiped... probability is very high to have an intersection, so it would be ok to always return 1 */
tmp = bbx->x;
tmp += bbx->w;
tmp--;
return u8g_pb_IsXIntersection(pb, bbx->x, tmp);
}
void u8g_pb_GetPageBox(u8g_pb_t *pb, u8g_box_t *box)
{
box->x0 = 0;
box->y0 = pb->p.page_y0;
box->x1 = pb->width;
box->x1--;
box->y1 = pb->p.page_y1;
}
uint8_t u8g_pb_Is8PixelVisible(u8g_pb_t *b, u8g_dev_arg_pixel_t *arg_pixel)
{
u8g_uint_t v0, v1;
v0 = arg_pixel->y;
v1 = v0;
switch( arg_pixel->dir )
{
case 0:
break;
case 1:
v1 += 8; /* this is independent from the page height */
break;
case 2:
break;
case 3:
v0 -= 8;
break;
}
return u8g_pb_IsYIntersection(b, v0, v1);
}
uint8_t u8g_pb_WriteBuffer(u8g_pb_t *b, u8g_t *u8g, u8g_dev_t *dev)
{
return u8g_WriteSequence(u8g, dev, b->width, b->buf);
}
| 2,036 |
1,346 |
from plugin.scrobbler.core.constants import IGNORED_EVENTS
import logging
log = logging.getLogger(__name__)
class Engine(object):
handlers = {}
def __init__(self):
self.handlers = self._construct_handlers(self.handlers)
def process(self, obj, events):
for key, payload in events:
result = self.process_one(obj, key, payload)
if not result:
continue
for item in result:
yield item
def process_one(self, obj, key, payload):
# Ensure the event hasn't been ignored
if key in IGNORED_EVENTS:
log.debug('Ignored %r event', key)
return
# Try find handler for event
handlers = self.handlers.get(key)
if not handlers:
raise Exception('No handlers found for %r event' % key)
# Run handlers until we get a result
result = None
for h in handlers:
if not h.is_valid_source(obj.state):
log.info('Ignoring %r event for %r, invalid state transition', key, obj)
continue
result = h.process(obj, payload)
break
if result is None:
return
for item in result:
if not item:
continue
state, data = item
# Update current state/data
self._set_attributes(obj, **data)
if state is None:
continue
# New event
obj.state = state
# Save
obj.save()
yield state, data
@staticmethod
def find_handlers(handlers, func):
result = []
for h in handlers:
if not func(h):
continue
result.append(h)
return result
@classmethod
def register(cls, kls):
key = kls.__event__
if not key:
raise Exception('Unable to register %r, missing "__key__" attribute' % kls)
if key not in cls.handlers:
cls.handlers[key] = []
cls.handlers[key].append(kls)
@staticmethod
def _construct_handlers(handlers):
result = {}
for key, classes in handlers.items():
objects = []
for kls in classes:
objects.append(kls())
result[key] = objects
return result
@staticmethod
def _set_attributes(obj, **kwargs):
for key, value in kwargs.items():
if not hasattr(obj, key):
raise Exception('Object %r is missing the attribute %r' % (obj, key))
setattr(obj, key, value)
class SessionEngine(Engine):
handlers = {}
| 1,285 |
317 |
<reponame>dinisAbranches/nwchem
/*
$Id$
*/
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "typesf2c.h"
#include "paw_atom.h"
#include "paw_sdir.h"
#include "paw_output.h"
#include "paw_basis.h"
#include "paw_scattering.h"
#include "paw_loggrid.h"
#if defined(CRAY) || defined(CRAY_T3D)
#include <fortran.h>
#if !defined(__crayx1)
#define USE_FCD
#endif
#endif
#if (defined(CRAY) || defined(WIN32)) && !defined(__crayx1) &&!defined(__MINGW32__)
#define teter_parse_ PAW_ATOM_DRIVER
#endif
void FATR paw_atom_driver_
#if defined(USE_FCD)
(Integer *debug_ptr,
Integer *lmax_ptr,
Integer *locp_ptr,
double *rlocal_ptr,
const _fcd fcd_sdir_name,
Integer *n9,
const _fcd fcd_dir_name,
Integer *n0,
const _fcd fcd_in_filename,
Integer *n1,
const _fcd fcd_out_filename,
Integer *n2,
const _fcd fcd_atom,
Integer *n3)
{
char *sdir_name = _fcdtocp(fcd_sdir_name);
char *dir_name = _fcdtocp(fcd_dir_name);
char *in_filename = _fcdtocp(fcd_in_filename);
char *out_filename = _fcdtocp(fcd_out_filename);
char *atom = _fcdtocp(fcd_atom);
#else
(debug_ptr,lmax_ptr,locp_ptr,rlocal_ptr,
sdir_name,n9,dir_name,n0,in_filename,n1,out_filename,n2,atom,n3)
Integer *debug_ptr;
Integer *lmax_ptr;
Integer *locp_ptr;
double *rlocal_ptr;
char sdir_name[];
Integer *n9;
char dir_name[];
Integer *n0;
char in_filename[];
Integer *n1;
char out_filename[];
Integer *n2;
char atom[];
Integer *n3;
{
#endif
int debug;
int lmax_out,locp_out;
double rlocal_out;
double zatom,zion; /* local psp parameters */
double over_fourpi;
int *nl;
int i,k,l,p,p1;
int Ngrid,nrl;
double *rgrid,*psi,*psp;
double *rl, *tmp, *tmp2, *sc_rho, *sc_rhol, *sc_drho, *sc_drhol,
**psil,
**pspl;
double drl,rmax;
int lmax,locp,lmaxp;
double r0,xx;
int n[10];
int pspdat,pspcode,pspxc;
double r2well,rcore[10],e99,e999;
double rchrg,fchrg,qchrg,pi;
char *w,*tc;
FILE *fp;
char comment[255];
int argc;
int m9 = ((int) (*n9));
int m0 = ((int) (*n0));
int m1 = ((int) (*n1));
int m2 = ((int) (*n2));
int m3 = ((int) (*n3));
char *infile = (char *) malloc(m9+m1+5);
char *outfile = (char *) malloc(m0+m2+5);
char *atom_out = (char *) malloc(m3+5);
char *full_filename = (char *) malloc(m9+25+5);
debug = *debug_ptr;
lmax_out = *lmax_ptr;
locp_out = *locp_ptr;
rlocal_out = *rlocal_ptr;
(void) strncpy(infile, sdir_name, m9);
infile[m9] = '\0';
strcat(infile,"/");
infile[m9+1] = '\0';
strncat(infile,in_filename,m1);
infile[m9+m1+1] = '\0';
(void) strncpy(outfile, dir_name, m0);
outfile[m0] = '\0';
(void) strcat(outfile,"/");
outfile[m0+1] = '\0';
(void) strncat(outfile,out_filename,m2);
outfile[m0+m2+1] = '\0';
(void) strncpy(atom_out, atom, m3);
atom_out[m3] = '\0';
paw_set_sdir(sdir_name,m9);
paw_set_debug(debug);
paw_init_paw_scattering_set();
if (debug) printf("\ninitializing atom parameters\n");
paw_init_atom(atom_out,infile);
if (debug) printf("\nentering the selfconsistent loop\n");
paw_solve_atom();
paw_print_atom();
paw_init_paw_atom(infile);
paw_solve_paw_atom(infile);
paw_generate_basis_file(outfile);
paw_end_paw_scattering();
paw_end_paw_basis();
paw_end_LogGrid();
}
| 1,834 |
435 |
<filename>web-services/client/src/test/java/datawave/user/DefaultAuthorizationsListTest.java
package datawave.user;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.google.common.collect.Sets;
import datawave.user.AuthorizationsListBase.SubjectIssuerDNPair;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class DefaultAuthorizationsListTest {
private DefaultAuthorizationsList dal;
// Using example dns from https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol
@SuppressWarnings("unused")
private final String stock_dn = "cn=Common Name, l=Locality, ou=Some Organizational Unit, o=Some Organization, st=CA, c=US";
private TreeSet<String> treeForTests;
private LinkedHashMap<SubjectIssuerDNPair,Set<String>> authMapForTests;
private static final String TITLE = "Effective Authorizations", EMPTY = "";
@Before
public void beforeTests() {
treeForTests = new TreeSet<String>();
treeForTests.clear(); // Default to empty treeSet
authMapForTests = new LinkedHashMap<SubjectIssuerDNPair,Set<String>>();
authMapForTests.clear(); // Default to empty LinkedHashMap
}
@SuppressWarnings("static-access")
@Test
public void testEmptyConstructor() {
dal = new DefaultAuthorizationsList();
Assert.assertTrue(dal.getAllAuths().isEmpty());
Assert.assertTrue(dal.getAuths().isEmpty());
Assert.assertEquals(EMPTY, dal.getHeadContent());
Assert.assertEquals(TITLE, dal.getTitle());
Assert.assertEquals(TITLE, dal.getPageHeader());
Set<String> auths = Sets.newHashSet("dnAuths1", "dnAuths2");
dal.addAuths("DN", "issuerDN", auths);
dal.addAuths("DN2", "issuerDN2", auths);
dal.setUserAuths("DN", "issuerDN", auths);
Assert.assertEquals(2, dal.getAllAuths().size());
Assert.assertTrue(CollectionUtils.isEqualCollection(dal.getAllAuths(), auths));
Assert.assertEquals(2, dal.getAuths().size());
Assert.assertEquals(EMPTY, dal.getHeadContent());
Assert.assertEquals(TITLE, dal.getTitle());
Assert.assertEquals(TITLE, dal.getPageHeader());
// Test getAuths()
LinkedHashMap<SubjectIssuerDNPair,Set<String>> expectedGetAuths = new LinkedHashMap<SubjectIssuerDNPair,Set<String>>();
expectedGetAuths.put(new SubjectIssuerDNPair("DN", "issuerDN"), new TreeSet<String>(auths));
expectedGetAuths.put(new SubjectIssuerDNPair("DN2", "issuerDN2"), new TreeSet<String>(auths));
Assert.assertTrue(CollectionUtils.isEqualCollection(dal.getAuths().entrySet(), expectedGetAuths.entrySet()));
// Test userAuths
Assert.assertTrue(CollectionUtils.isEqualCollection(dal.userAuths, Sets.newHashSet("dnAuths1", "dnAuths2")));
Map<String,Collection<String>> authMapping = new HashMap<String,Collection<String>>();
authMapping.put("authMapKey", auths);
authMapping.put("authMapKey2", auths);
dal.setAuthMapping(authMapping);
Assert.assertEquals(2, dal.getAuthMapping().size());
Assert.assertTrue(CollectionUtils.isEqualCollection(dal.getAuthMapping().entrySet(), authMapping.entrySet()));
// toString() matching is not a good test when the underlying data structure does not use ordered collections.
// tested individual pieces above should suffice
// String toStringExpected =
// "userAuths=[dnAuths1, dnAuths2], entityAuths=[DN<issuerDN>=[dnAuths1, dnAuths2]DN2<issuerDN2>=[dnAuths1, dnAuths2]],
// authMapping=[authMapKey->(dnAuths1,dnAuths2,), authMapKey2->(dnAuths1,dnAuths2,), ]";
// Assert.assertEquals(toStringExpected, dal.toString());
String mcExpected = "<h2>Auths for user Subject: DN (Issuer issuerDN)</h2><table><tr><td>dnAuths1</td><td>dnAuths2</td></tr></table><h2>Auths for Subject: DN2 (Issuer: issuerDN2)</h2><table><tr><td>dnAuths1</td><td>dnAuths2</td></tr></table><h2>Roles to Accumulo Auths</h2><table><tr><th>Role</th><th>Accumulo Authorizations</th></tr><tr><td>authMapKey</td><td>dnAuths1,dnAuths2</td></tr><tr class=\"highlight\"><td>authMapKey2</td><td>dnAuths1,dnAuths2</td></tr></table>";
String mainContent = dal.getMainContent();
// Testing expected string with an unordered collection doesn't always work, we'll need to parse this as we go
// Assert.assertEquals(mcExpected, mainContent);
Assert.assertEquals("<h2>Auths for user Subject: DN (Issuer issuerDN)</h2><table><tr>", mainContent.substring(0, 64));
Assert.assertTrue("<td>dnAuths1</td><td>dnAuths2</td>".equals(mainContent.substring(64, 98))
|| "<td>dnAuths2</td><td>dnAuths1</td>".equals(mainContent.substring(64, 98)));
Assert.assertEquals("</tr></table><h2>Auths for Subject: DN2 (Issuer: issuerDN2)</h2><table><tr>", mainContent.substring(98, 173));
Assert.assertTrue("<td>dnAuths1</td><td>dnAuths2</td>".equals(mainContent.substring(173, 207))
|| "<td>dnAuths2</td><td>dnAuths1</td>".equals(mainContent.substring(173, 207)));
Assert.assertEquals("</tr></table><h2>Roles to Accumulo Auths</h2><table><tr><th>Role</th><th>Accumulo Authorizations</th></tr><tr>",
mainContent.substring(207, 317));
Assert.assertTrue("<td>authMapKey</td><td>dnAuths1,dnAuths2</td>".equals(mainContent.substring(317, 362))
|| "<td>authMapKey</td><td>dnAuths2,dnAuths1</td>".equals(mainContent.substring(317, 362))
|| "<td>authMapKey2</td><td>dnAuths1,dnAuths2</td>".equals(mainContent.substring(317, 362))
|| "<td>authMapKey2</td><td>dnAuths2,dnAuths1</td>".equals(mainContent.substring(317, 362)));
Assert.assertEquals("</tr><tr class=\"highlight\">", mainContent.substring(362, 389));
Assert.assertTrue("<td>authMapKey</td><td>dnAuths1,dnAuths2</td>".equals(mainContent.substring(389, 435))
|| "<td>authMapKey</td><td>dnAuths2,dnAuths1</td>".equals(mainContent.substring(389, 435))
|| "<td>authMapKey2</td><td>dnAuths1,dnAuths2</td>".equals(mainContent.substring(389, 435))
|| "<td>authMapKey2</td><td>dnAuths2,dnAuths1</td>".equals(mainContent.substring(389, 435)));
Assert.assertEquals("</tr></table>", mainContent.substring(435));
// Tests for the SCHEMA nested class
Assert.assertNull(dal.getSchema().getFieldName(0));
Assert.assertEquals("auths", dal.getSchema().getFieldName(1));
Assert.assertEquals("authMapping", dal.getSchema().getFieldName(2));
Assert.assertEquals(0, dal.getSchema().getFieldNumber("garbage"));
Assert.assertEquals(1, dal.getSchema().getFieldNumber("auths"));
Assert.assertEquals(2, dal.getSchema().getFieldNumber("authMapping"));
Assert.assertEquals(DefaultAuthorizationsList.class, dal.getSchema().typeClass());
Assert.assertEquals(DefaultAuthorizationsList.class.getSimpleName(), dal.getSchema().messageName());
Assert.assertEquals(DefaultAuthorizationsList.class.getName(), dal.getSchema().messageFullName());
Assert.assertTrue(dal.getSchema().isInitialized(null));
Assert.assertTrue(dal.cachedSchema().isInitialized(null));
}
@Test
public void testDefaultAuthList() {
// Testing the bugfix for DefaultAuthorizationsList with mock data
String random = "ABC|DEF|GHI|JKL|MNO";
String[] splits = random.split("\\|");
Assert.assertEquals(5, splits.length);
splits = random.split("|");
Assert.assertNotEquals(5, splits.length);
}
}
| 3,440 |
575 |
// Copyright 2020 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 StackAllocatedSequence.hpp
*/
#ifndef _FASTDDS_DDS_CORE_STACKALLOCATEDSEQUENCE_HPP_
#define _FASTDDS_DDS_CORE_STACKALLOCATEDSEQUENCE_HPP_
#include <array>
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <fastdds/dds/core/LoanableArray.hpp>
#include <fastdds/dds/core/LoanableTypedCollection.hpp>
namespace eprosima {
namespace fastdds {
namespace dds {
/**
* A type-safe, ordered collection of elements allocated on the stack.
*/
template<typename T, LoanableCollection::size_type num_items>
struct StackAllocatedSequence : public LoanableTypedCollection<T>
{
using size_type = LoanableCollection::size_type;
using element_type = LoanableCollection::element_type;
StackAllocatedSequence()
{
has_ownership_ = true;
maximum_ = num_items;
length_ = 0;
elements_ = data_.buffer_for_loans();
}
~StackAllocatedSequence() = default;
// Non-copyable
StackAllocatedSequence(
const StackAllocatedSequence&) = delete;
StackAllocatedSequence& operator = (
const StackAllocatedSequence&) = delete;
// Non-moveable
StackAllocatedSequence(
StackAllocatedSequence&&) = delete;
StackAllocatedSequence& operator = (
StackAllocatedSequence&&) = delete;
protected:
using LoanableCollection::maximum_;
using LoanableCollection::length_;
using LoanableCollection::elements_;
using LoanableCollection::has_ownership_;
void resize(
LoanableCollection::size_type new_length) override
{
// This kind of collection cannot grow above its stack-allocated size
if (new_length > num_items)
{
throw std::bad_alloc();
}
}
private:
LoanableArray<T, num_items> data_;
};
} // namespace dds
} // namespace fastdds
} // namespace eprosima
#endif // _FASTDDS_DDS_CORE_STACKALLOCATEDSEQUENCE_HPP_
| 924 |
348 |
<gh_stars>100-1000
{"nom":"Campana","circ":"2ème circonscription","dpt":"Haute-Corse","inscrits":92,"abs":44,"votants":48,"blancs":1,"nuls":1,"exp":46,"res":[{"nuance":"REG","nom":"<NAME>","voix":32},{"nuance":"REM","nom":"<NAME>","voix":14}]}
| 99 |
2,032 |
# -*- coding: utf-8 -*-
# the __all__ is generated
__all__ = []
# __init__.py structure:
# common code of the package
# export interface in __all__ which contains __all__ of its sub modules
# import all from submodule em_kdata_recorder
from .em_kdata_recorder import *
from .em_kdata_recorder import __all__ as _em_kdata_recorder_all
__all__ += _em_kdata_recorder_all
| 130 |
353 |
#include <iostream>
#include <fstream>
#include "disassembly/flowgraph.hpp"
#include "disassembly/functionfeaturegenerator.hpp"
#include "searchbackend/functionsimhashfeaturedump.hpp"
// Writes a DOT file for a given graphlet.
void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB,
const Flowgraph& graphlet) {
char buf[256];
sprintf(buf, "/var/tmp/%16.16lx%16.16lx.dot", hashA, hashB);
graphlet.WriteDot(std::string(buf));
}
// Writes a JSON file for a given MnemTuple.
void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB,
const MnemTuple& tuple) {
char buf[256];
sprintf(buf, "/var/tmp/%16.16lx%16.16lx.json", hashA, hashB);
std::ofstream jsonfile;
jsonfile.open(std::string(buf));
jsonfile << "[ " << std::get<0>(tuple) << ", " << std::get<1>(tuple) << ", "
<< std::get<2>(tuple) << " ]" << std::endl;
}
// Writes an immediate that was encountered.
void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB, uint64_t
immediate) {
std::ofstream immediates;
immediates.open("/var/tmp/immediates.txt",
std::ofstream::out | std::ofstream::app);
immediates << std::hex << hashA << " " << hashB << " " << immediate
<< std::endl;
}
| 457 |
335 |
<reponame>Safal08/Hacktoberfest-1<filename>A/Acknowledgedly_adverb.json
{
"word": "Acknowledgedly",
"definitions": [
"By general, or one's own, acknowledgement; admittedly, confessedly."
],
"parts-of-speech": "Adverb"
}
| 98 |
360 |
/*
* Copyright (c) 2021 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* ckms_message.h
* Cloud KMS and IAM message is the external interface of JSON management
*
* IDENTIFICATION
* src/include/tde_key_management/ckms_message.h
*
* ---------------------------------------------------------------------------------------
*/
#ifndef SEC_CKMS_MESSAGE_H
#define SEC_CKMS_MESSAGE_H
#include "tde_key_management/data_common.h"
#include "tde_key_management/http_common.h"
#include "cipher.h"
namespace TDE {
class CKMSMessage : public BaseObject {
public:
static CKMSMessage& get_instance()
{
static CKMSMessage instance;
return instance;
}
void init();
void clear();
char* get_iam_token_json();
char* get_iam_agency_token_json();
char* get_create_dek_json(const char* cmk_id);
char* get_decrypt_dek_json(const char* cmk_id, const char* dek_cipher);
bool check_token_valid();
bool save_token(const char* token, const char* agency_token);
void load_user_info();
public:
char* tde_token;
char* tde_agency_token;
TimestampTz token_timestamp;
/* internal user B info */
TokenInfo* token_info;
/* user A info */
AgencyTokenInfo* agency_token_info;
/* KMS info */
KmsInfo* kms_info;
private:
CKMSMessage();
~CKMSMessage();
char* get_kms_json(ReplaceJsonValue input_json[], KmsHttpMsgType json_type, size_t count);
HttpErrCode traverse_jsontree_with_raplace_value(cJSON *json_tree, ReplaceJsonValue replace_rules[],
size_t rule_cnt);
cJSON *get_json_temp(KmsHttpMsgType json_tree_type);
char* read_kms_info_from_file();
void parser_json_file(char* buffer);
void fill_kms_info(cJSON* kms_json);
void fill_agency_info(cJSON* agency_json);
void fill_token_info(cJSON* internal_json);
GS_UCHAR* get_cipher_rand();
private:
MemoryContext tde_message_mem;
const int token_valid_hours = 23;
const char* token_file = "kms_iam_info.json";
const char* tde_config = "/tde_config/";
const char* key = "key_0";
};
}
#endif
| 986 |
2,576 |
<filename>modelling/src/main/java/org/axonframework/modelling/saga/metamodel/SagaMetaModelFactory.java<gh_stars>1000+
/*
* Copyright (c) 2010-2018. Axon Framework
*
* 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.axonframework.modelling.saga.metamodel;
/**
* Interface of a factory for a {@link SagaModel} for any given saga type.
*/
public interface SagaMetaModelFactory {
/**
* Create a saga meta model for the given {@code sagaType}. The meta model will inspect the capabilities and
* characteristics of the given type.
*
* @param sagaType The saga class to be inspected
* @param <T> The saga type
* @return Model describing the capabilities and characteristics of the inspected saga class
*/
<T> SagaModel<T> modelOf(Class<T> sagaType);
}
| 385 |
529 |
<reponame>PervasiveDigital/netmf-interpreter
/* crypto/aes/aes_core.c -*- mode:C; c-file-style: "eay" -*- */
/**
* rijndael-alg-fst.c
*
* @version 3.0 (December 2000)
*
* Optimised ANSI C code for the Rijndael cipher (now AES)
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*
* This code is hereby placed in the public domain.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This is experimental x86[_64] derivative. It assumes little-endian
* byte order and expects CPU to sustain unaligned memory references.
* It is used as playground for cache-time attack mitigations and
* serves as reference C implementation for x86[_64] assembler.
*
* <<EMAIL>>
*/
#ifndef AES_DEBUG
# ifndef NDEBUG
# define NDEBUG
# endif
#endif
#include <openssl/aes.h>
#include "aes_locl.h"
#ifdef OPENSSL_SYS_WINDOWS
#include <assert.h>
#include <stdlib.h>
#endif
/*
* These two parameters control which table, 256-byte or 2KB, is
* referenced in outer and respectively inner rounds.
*/
#define AES_COMPACT_IN_OUTER_ROUNDS
#ifdef AES_COMPACT_IN_OUTER_ROUNDS
/* AES_COMPACT_IN_OUTER_ROUNDS costs ~30% in performance, while
* adding AES_COMPACT_IN_INNER_ROUNDS reduces benchmark *further*
* by factor of ~2. */
# undef AES_COMPACT_IN_INNER_ROUNDS
#endif
#if 1
static void prefetch256(const void *table)
{
volatile unsigned long *t=(void *)table,ret;
unsigned long sum;
int i;
/* 32 is common least cache-line size */
for (sum=0,i=0;i<256/sizeof(t[0]);i+=32/sizeof(t[0])) sum ^= t[i];
ret = sum;
}
#else
# define prefetch256(t)
#endif
#undef GETU32
#define GETU32(p) (*((u32*)(p)))
#if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__)
typedef unsigned __int64 u64;
#define U64(C) C##UI64
#elif defined(__arch64__)
typedef unsigned long u64;
#define U64(C) C##UL
#else
typedef unsigned long long u64;
#define U64(C) C##ULL
#endif
#undef ROTATE
#if defined(_MSC_VER) || defined(__ICC)
# define ROTATE(a,n) _lrotl(a,n)
#elif defined(__GNUC__) && __GNUC__>=2
# if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)
# define ROTATE(a,n) ({ register unsigned int ret; \
asm ( \
"roll %1,%0" \
: "=r"(ret) \
: "I"(n), "0"(a) \
: "cc"); \
ret; \
})
# endif
#endif
/*
Te [x] = S [x].[02, 01, 01, 03, 02, 01, 01, 03];
Te0[x] = S [x].[02, 01, 01, 03];
Te1[x] = S [x].[03, 02, 01, 01];
Te2[x] = S [x].[01, 03, 02, 01];
Te3[x] = S [x].[01, 01, 03, 02];
*/
#define Te0 (u32)((u64*)((u8*)Te+0))
#define Te1 (u32)((u64*)((u8*)Te+3))
#define Te2 (u32)((u64*)((u8*)Te+2))
#define Te3 (u32)((u64*)((u8*)Te+1))
/*
Td [x] = Si[x].[0e, 09, 0d, 0b, 0e, 09, 0d, 0b];
Td0[x] = Si[x].[0e, 09, 0d, 0b];
Td1[x] = Si[x].[0b, 0e, 09, 0d];
Td2[x] = Si[x].[0d, 0b, 0e, 09];
Td3[x] = Si[x].[09, 0d, 0b, 0e];
Td4[x] = Si[x].[01];
*/
#define Td0 (u32)((u64*)((u8*)Td+0))
#define Td1 (u32)((u64*)((u8*)Td+3))
#define Td2 (u32)((u64*)((u8*)Td+2))
#define Td3 (u32)((u64*)((u8*)Td+1))
static const u64 Te[256] = {
U64(0xa56363c6a56363c6), U64(0x847c7cf8847c7cf8),
U64(0x997777ee997777ee), U64(0x8d7b7bf68d7b7bf6),
U64(0x0df2f2ff0df2f2ff), U64(0xbd6b6bd6bd6b6bd6),
U64(0xb16f6fdeb16f6fde), U64(0x54c5c59154c5c591),
U64(0x5030306050303060), U64(0x0301010203010102),
U64(0xa96767cea96767ce), U64(0x7d2b2b567d2b2b56),
U64(0x19fefee719fefee7), U64(0x62d7d7b562d7d7b5),
U64(0xe6abab4de6abab4d), U64(0x9a7676ec9a7676ec),
U64(0x45caca8f45caca8f), U64(0x9d82821f9d82821f),
U64(0x40c9c98940c9c989), U64(0x877d7dfa877d7dfa),
U64(0x15fafaef15fafaef), U64(0xeb5959b2eb5959b2),
U64(0xc947478ec947478e), U64(0x0bf0f0fb0bf0f0fb),
U64(0xecadad41ecadad41), U64(0x67d4d4b367d4d4b3),
U64(0xfda2a25ffda2a25f), U64(0xeaafaf45eaafaf45),
U64(0xbf9c9c23bf9c9c23), U64(0xf7a4a453f7a4a453),
U64(0x967272e4967272e4), U64(0x5bc0c09b5bc0c09b),
U64(0xc2b7b775c2b7b775), U64(0x1cfdfde11cfdfde1),
U64(0xae93933dae93933d), U64(0x6a26264c6a26264c),
U64(0x5a36366c5a36366c), U64(0x413f3f7e413f3f7e),
U64(0x02f7f7f502f7f7f5), U64(0x4fcccc834fcccc83),
U64(0x5c3434685c343468), U64(0xf4a5a551f4a5a551),
U64(0x34e5e5d134e5e5d1), U64(0x08f1f1f908f1f1f9),
U64(0x937171e2937171e2), U64(0x73d8d8ab73d8d8ab),
U64(0x5331316253313162), U64(0x3f15152a3f15152a),
U64(0x0c0404080c040408), U64(0x52c7c79552c7c795),
U64(0x6523234665232346), U64(0x5ec3c39d5ec3c39d),
U64(0x2818183028181830), U64(0xa1969637a1969637),
U64(0x0f05050a0f05050a), U64(0xb59a9a2fb59a9a2f),
U64(0x0907070e0907070e), U64(0x3612122436121224),
U64(0x9b80801b9b80801b), U64(0x3de2e2df3de2e2df),
U64(0x26ebebcd26ebebcd), U64(0x6927274e6927274e),
U64(0xcdb2b27fcdb2b27f), U64(0x9f7575ea9f7575ea),
U64(0x1b0909121b090912), U64(0x9e83831d9e83831d),
U64(0x742c2c58742c2c58), U64(0x2e1a1a342e1a1a34),
U64(0x2d1b1b362d1b1b36), U64(0xb26e6edcb26e6edc),
U64(0xee5a5ab4ee5a5ab4), U64(0xfba0a05bfba0a05b),
U64(0xf65252a4f65252a4), U64(0x4d3b3b764d3b3b76),
U64(0x61d6d6b761d6d6b7), U64(0xceb3b37dceb3b37d),
U64(0x7b2929527b292952), U64(0x3ee3e3dd3ee3e3dd),
U64(0x712f2f5e712f2f5e), U64(0x9784841397848413),
U64(0xf55353a6f55353a6), U64(0x68d1d1b968d1d1b9),
U64(0x0000000000000000), U64(0x2cededc12cededc1),
U64(0x6020204060202040), U64(0x1ffcfce31ffcfce3),
U64(0xc8b1b179c8b1b179), U64(0xed5b5bb6ed5b5bb6),
U64(0xbe6a6ad4be6a6ad4), U64(0x46cbcb8d46cbcb8d),
U64(0xd9bebe67d9bebe67), U64(0x4b3939724b393972),
U64(0xde4a4a94de4a4a94), U64(0xd44c4c98d44c4c98),
U64(0xe85858b0e85858b0), U64(0x4acfcf854acfcf85),
U64(0x6bd0d0bb6bd0d0bb), U64(0x2aefefc52aefefc5),
U64(0xe5aaaa4fe5aaaa4f), U64(0x16fbfbed16fbfbed),
U64(0xc5434386c5434386), U64(0xd74d4d9ad74d4d9a),
U64(0x5533336655333366), U64(0x9485851194858511),
U64(0xcf45458acf45458a), U64(0x10f9f9e910f9f9e9),
U64(0x0602020406020204), U64(0x817f7ffe817f7ffe),
U64(0xf05050a0f05050a0), U64(0x443c3c78443c3c78),
U64(0xba9f9f25ba9f9f25), U64(0xe3a8a84be3a8a84b),
U64(0xf35151a2f35151a2), U64(0xfea3a35dfea3a35d),
U64(0xc0404080c0404080), U64(0x8a8f8f058a8f8f05),
U64(0xad92923fad92923f), U64(0xbc9d9d21bc9d9d21),
U64(0x4838387048383870), U64(0x04f5f5f104f5f5f1),
U64(0xdfbcbc63dfbcbc63), U64(0xc1b6b677c1b6b677),
U64(0x75dadaaf75dadaaf), U64(0x6321214263212142),
U64(0x3010102030101020), U64(0x1affffe51affffe5),
U64(0x0ef3f3fd0ef3f3fd), U64(0x6dd2d2bf6dd2d2bf),
U64(0x4ccdcd814ccdcd81), U64(0x140c0c18140c0c18),
U64(0x3513132635131326), U64(0x2fececc32fececc3),
U64(0xe15f5fbee15f5fbe), U64(0xa2979735a2979735),
U64(0xcc444488cc444488), U64(0x3917172e3917172e),
U64(0x57c4c49357c4c493), U64(0xf2a7a755f2a7a755),
U64(0x827e7efc827e7efc), U64(0x473d3d7a473d3d7a),
U64(0xac6464c8ac6464c8), U64(0xe75d5dbae75d5dba),
U64(0x2b1919322b191932), U64(0x957373e6957373e6),
U64(0xa06060c0a06060c0), U64(0x9881811998818119),
U64(0xd14f4f9ed14f4f9e), U64(0x7fdcdca37fdcdca3),
U64(0x6622224466222244), U64(0x7e2a2a547e2a2a54),
U64(0xab90903bab90903b), U64(0x8388880b8388880b),
U64(0xca46468cca46468c), U64(0x29eeeec729eeeec7),
U64(0xd3b8b86bd3b8b86b), U64(0x3c1414283c141428),
U64(0x79dedea779dedea7), U64(0xe25e5ebce25e5ebc),
U64(0x1d0b0b161d0b0b16), U64(0x76dbdbad76dbdbad),
U64(0x3be0e0db3be0e0db), U64(0x5632326456323264),
U64(0x4e3a3a744e3a3a74), U64(0x1e0a0a141e0a0a14),
U64(0xdb494992db494992), U64(0x0a06060c0a06060c),
U64(0x6c2424486c242448), U64(0xe45c5cb8e45c5cb8),
U64(0x5dc2c29f5dc2c29f), U64(0x6ed3d3bd6ed3d3bd),
U64(0xefacac43efacac43), U64(0xa66262c4a66262c4),
U64(0xa8919139a8919139), U64(0xa4959531a4959531),
U64(0x37e4e4d337e4e4d3), U64(0x8b7979f28b7979f2),
U64(0x32e7e7d532e7e7d5), U64(0x43c8c88b43c8c88b),
U64(0x5937376e5937376e), U64(0xb76d6ddab76d6dda),
U64(0x8c8d8d018c8d8d01), U64(0x64d5d5b164d5d5b1),
U64(0xd24e4e9cd24e4e9c), U64(0xe0a9a949e0a9a949),
U64(0xb46c6cd8b46c6cd8), U64(0xfa5656acfa5656ac),
U64(0x07f4f4f307f4f4f3), U64(0x25eaeacf25eaeacf),
U64(0xaf6565caaf6565ca), U64(0x8e7a7af48e7a7af4),
U64(0xe9aeae47e9aeae47), U64(0x1808081018080810),
U64(0xd5baba6fd5baba6f), U64(0x887878f0887878f0),
U64(0x6f25254a6f25254a), U64(0x722e2e5c722e2e5c),
U64(0x241c1c38241c1c38), U64(0xf1a6a657f1a6a657),
U64(0xc7b4b473c7b4b473), U64(0x51c6c69751c6c697),
U64(0x23e8e8cb23e8e8cb), U64(0x7cdddda17cdddda1),
U64(0x9c7474e89c7474e8), U64(0x211f1f3e211f1f3e),
U64(0xdd4b4b96dd4b4b96), U64(0xdcbdbd61dcbdbd61),
U64(0x868b8b0d868b8b0d), U64(0x858a8a0f858a8a0f),
U64(0x907070e0907070e0), U64(0x423e3e7c423e3e7c),
U64(0xc4b5b571c4b5b571), U64(0xaa6666ccaa6666cc),
U64(0xd8484890d8484890), U64(0x0503030605030306),
U64(0x01f6f6f701f6f6f7), U64(0x120e0e1c120e0e1c),
U64(0xa36161c2a36161c2), U64(0x5f35356a5f35356a),
U64(0xf95757aef95757ae), U64(0xd0b9b969d0b9b969),
U64(0x9186861791868617), U64(0x58c1c19958c1c199),
U64(0x271d1d3a271d1d3a), U64(0xb99e9e27b99e9e27),
U64(0x38e1e1d938e1e1d9), U64(0x13f8f8eb13f8f8eb),
U64(0xb398982bb398982b), U64(0x3311112233111122),
U64(0xbb6969d2bb6969d2), U64(0x70d9d9a970d9d9a9),
U64(0x898e8e07898e8e07), U64(0xa7949433a7949433),
U64(0xb69b9b2db69b9b2d), U64(0x221e1e3c221e1e3c),
U64(0x9287871592878715), U64(0x20e9e9c920e9e9c9),
U64(0x49cece8749cece87), U64(0xff5555aaff5555aa),
U64(0x7828285078282850), U64(0x7adfdfa57adfdfa5),
U64(0x8f8c8c038f8c8c03), U64(0xf8a1a159f8a1a159),
U64(0x8089890980898909), U64(0x170d0d1a170d0d1a),
U64(0xdabfbf65dabfbf65), U64(0x31e6e6d731e6e6d7),
U64(0xc6424284c6424284), U64(0xb86868d0b86868d0),
U64(0xc3414182c3414182), U64(0xb0999929b0999929),
U64(0x772d2d5a772d2d5a), U64(0x110f0f1e110f0f1e),
U64(0xcbb0b07bcbb0b07b), U64(0xfc5454a8fc5454a8),
U64(0xd6bbbb6dd6bbbb6d), U64(0x3a16162c3a16162c)
};
static const u8 Te4[256] = {
0x63U, 0x7cU, 0x77U, 0x7bU, 0xf2U, 0x6bU, 0x6fU, 0xc5U,
0x30U, 0x01U, 0x67U, 0x2bU, 0xfeU, 0xd7U, 0xabU, 0x76U,
0xcaU, 0x82U, 0xc9U, 0x7dU, 0xfaU, 0x59U, 0x47U, 0xf0U,
0xadU, 0xd4U, 0xa2U, 0xafU, 0x9cU, 0xa4U, 0x72U, 0xc0U,
0xb7U, 0xfdU, 0x93U, 0x26U, 0x36U, 0x3fU, 0xf7U, 0xccU,
0x34U, 0xa5U, 0xe5U, 0xf1U, 0x71U, 0xd8U, 0x31U, 0x15U,
0x04U, 0xc7U, 0x23U, 0xc3U, 0x18U, 0x96U, 0x05U, 0x9aU,
0x07U, 0x12U, 0x80U, 0xe2U, 0xebU, 0x27U, 0xb2U, 0x75U,
0x09U, 0x83U, 0x2cU, 0x1aU, 0x1bU, 0x6eU, 0x5aU, 0xa0U,
0x52U, 0x3bU, 0xd6U, 0xb3U, 0x29U, 0xe3U, 0x2fU, 0x84U,
0x53U, 0xd1U, 0x00U, 0xedU, 0x20U, 0xfcU, 0xb1U, 0x5bU,
0x6aU, 0xcbU, 0xbeU, 0x39U, 0x4aU, 0x4cU, 0x58U, 0xcfU,
0xd0U, 0xefU, 0xaaU, 0xfbU, 0x43U, 0x4dU, 0x33U, 0x85U,
0x45U, 0xf9U, 0x02U, 0x7fU, 0x50U, 0x3cU, 0x9fU, 0xa8U,
0x51U, 0xa3U, 0x40U, 0x8fU, 0x92U, 0x9dU, 0x38U, 0xf5U,
0xbcU, 0xb6U, 0xdaU, 0x21U, 0x10U, 0xffU, 0xf3U, 0xd2U,
0xcdU, 0x0cU, 0x13U, 0xecU, 0x5fU, 0x97U, 0x44U, 0x17U,
0xc4U, 0xa7U, 0x7eU, 0x3dU, 0x64U, 0x5dU, 0x19U, 0x73U,
0x60U, 0x81U, 0x4fU, 0xdcU, 0x22U, 0x2aU, 0x90U, 0x88U,
0x46U, 0xeeU, 0xb8U, 0x14U, 0xdeU, 0x5eU, 0x0bU, 0xdbU,
0xe0U, 0x32U, 0x3aU, 0x0aU, 0x49U, 0x06U, 0x24U, 0x5cU,
0xc2U, 0xd3U, 0xacU, 0x62U, 0x91U, 0x95U, 0xe4U, 0x79U,
0xe7U, 0xc8U, 0x37U, 0x6dU, 0x8dU, 0xd5U, 0x4eU, 0xa9U,
0x6cU, 0x56U, 0xf4U, 0xeaU, 0x65U, 0x7aU, 0xaeU, 0x08U,
0xbaU, 0x78U, 0x25U, 0x2eU, 0x1cU, 0xa6U, 0xb4U, 0xc6U,
0xe8U, 0xddU, 0x74U, 0x1fU, 0x4bU, 0xbdU, 0x8bU, 0x8aU,
0x70U, 0x3eU, 0xb5U, 0x66U, 0x48U, 0x03U, 0xf6U, 0x0eU,
0x61U, 0x35U, 0x57U, 0xb9U, 0x86U, 0xc1U, 0x1dU, 0x9eU,
0xe1U, 0xf8U, 0x98U, 0x11U, 0x69U, 0xd9U, 0x8eU, 0x94U,
0x9bU, 0x1eU, 0x87U, 0xe9U, 0xceU, 0x55U, 0x28U, 0xdfU,
0x8cU, 0xa1U, 0x89U, 0x0dU, 0xbfU, 0xe6U, 0x42U, 0x68U,
0x41U, 0x99U, 0x2dU, 0x0fU, 0xb0U, 0x54U, 0xbbU, 0x16U
};
static const u64 Td[256] = {
U64(0x50a7f45150a7f451), U64(0x5365417e5365417e),
U64(0xc3a4171ac3a4171a), U64(0x965e273a965e273a),
U64(0xcb6bab3bcb6bab3b), U64(0xf1459d1ff1459d1f),
U64(0xab58faacab58faac), U64(0x9303e34b9303e34b),
U64(0x55fa302055fa3020), U64(0xf66d76adf66d76ad),
U64(0x9176cc889176cc88), U64(0x254c02f5254c02f5),
U64(0xfcd7e54ffcd7e54f), U64(0xd7cb2ac5d7cb2ac5),
U64(0x8044352680443526), U64(0x8fa362b58fa362b5),
U64(0x495ab1de495ab1de), U64(0x671bba25671bba25),
U64(0x980eea45980eea45), U64(0xe1c0fe5de1c0fe5d),
U64(0x02752fc302752fc3), U64(0x12f04c8112f04c81),
U64(0xa397468da397468d), U64(0xc6f9d36bc6f9d36b),
U64(0xe75f8f03e75f8f03), U64(0x959c9215959c9215),
U64(0xeb7a6dbfeb7a6dbf), U64(0xda595295da595295),
U64(0x2d83bed42d83bed4), U64(0xd3217458d3217458),
U64(0x2969e0492969e049), U64(0x44c8c98e44c8c98e),
U64(0x6a89c2756a89c275), U64(0x78798ef478798ef4),
U64(0x6b3e58996b3e5899), U64(0xdd71b927dd71b927),
U64(0xb64fe1beb64fe1be), U64(0x17ad88f017ad88f0),
U64(0x66ac20c966ac20c9), U64(0xb43ace7db43ace7d),
U64(0x184adf63184adf63), U64(0x82311ae582311ae5),
U64(0x6033519760335197), U64(0x457f5362457f5362),
U64(0xe07764b1e07764b1), U64(0x84ae6bbb84ae6bbb),
U64(0x1ca081fe1ca081fe), U64(0x942b08f9942b08f9),
U64(0x5868487058684870), U64(0x19fd458f19fd458f),
U64(0x876cde94876cde94), U64(0xb7f87b52b7f87b52),
U64(0x23d373ab23d373ab), U64(0xe2024b72e2024b72),
U64(0x578f1fe3578f1fe3), U64(0x2aab55662aab5566),
U64(0x0728ebb20728ebb2), U64(0x03c2b52f03c2b52f),
U64(0x9a7bc5869a7bc586), U64(0xa50837d3a50837d3),
U64(0xf2872830f2872830), U64(0xb2a5bf23b2a5bf23),
U64(0xba6a0302ba6a0302), U64(0x5c8216ed5c8216ed),
U64(0x2b1ccf8a2b1ccf8a), U64(0x92b479a792b479a7),
U64(0xf0f207f3f0f207f3), U64(0xa1e2694ea1e2694e),
U64(0xcdf4da65cdf4da65), U64(0xd5be0506d5be0506),
U64(0x1f6234d11f6234d1), U64(0x8afea6c48afea6c4),
U64(0x9d532e349d532e34), U64(0xa055f3a2a055f3a2),
U64(0x32e18a0532e18a05), U64(0x75ebf6a475ebf6a4),
U64(0x39ec830b39ec830b), U64(0xaaef6040aaef6040),
U64(0x069f715e069f715e), U64(0x51106ebd51106ebd),
U64(0xf98a213ef98a213e), U64(0x3d06dd963d06dd96),
U64(0xae053eddae053edd), U64(0x46bde64d46bde64d),
U64(0xb58d5491b58d5491), U64(0x055dc471055dc471),
U64(0x6fd406046fd40604), U64(0xff155060ff155060),
U64(0x24fb981924fb9819), U64(0x97e9bdd697e9bdd6),
U64(0xcc434089cc434089), U64(0x779ed967779ed967),
U64(0xbd42e8b0bd42e8b0), U64(0x888b8907888b8907),
U64(0x385b19e7385b19e7), U64(0xdbeec879dbeec879),
U64(0x470a7ca1470a7ca1), U64(0xe90f427ce90f427c),
U64(0xc91e84f8c91e84f8), U64(0x0000000000000000),
U64(0x8386800983868009), U64(0x48ed2b3248ed2b32),
U64(0xac70111eac70111e), U64(0x4e725a6c4e725a6c),
U64(0xfbff0efdfbff0efd), U64(0x5638850f5638850f),
U64(0x1ed5ae3d1ed5ae3d), U64(0x27392d3627392d36),
U64(0x64d90f0a64d90f0a), U64(0x21a65c6821a65c68),
U64(0xd1545b9bd1545b9b), U64(0x3a2e36243a2e3624),
U64(0xb1670a0cb1670a0c), U64(0x0fe757930fe75793),
U64(0xd296eeb4d296eeb4), U64(0x9e919b1b9e919b1b),
U64(0x4fc5c0804fc5c080), U64(0xa220dc61a220dc61),
U64(0x694b775a694b775a), U64(0x161a121c161a121c),
U64(0x0aba93e20aba93e2), U64(0xe52aa0c0e52aa0c0),
U64(0x43e0223c43e0223c), U64(0x1d171b121d171b12),
U64(0x0b0d090e0b0d090e), U64(0xadc78bf2adc78bf2),
U64(0xb9a8b62db9a8b62d), U64(0xc8a91e14c8a91e14),
U64(0x8519f1578519f157), U64(0x4c0775af4c0775af),
U64(0xbbdd99eebbdd99ee), U64(0xfd607fa3fd607fa3),
U64(0x9f2601f79f2601f7), U64(0xbcf5725cbcf5725c),
U64(0xc53b6644c53b6644), U64(0x347efb5b347efb5b),
U64(0x7629438b7629438b), U64(0xdcc623cbdcc623cb),
U64(0x68fcedb668fcedb6), U64(0x63f1e4b863f1e4b8),
U64(0xcadc31d7cadc31d7), U64(0x1085634210856342),
U64(0x4022971340229713), U64(0x2011c6842011c684),
U64(0x7d244a857d244a85), U64(0xf83dbbd2f83dbbd2),
U64(0x1132f9ae1132f9ae), U64(0x6da129c76da129c7),
U64(0x4b2f9e1d4b2f9e1d), U64(0xf330b2dcf330b2dc),
U64(0xec52860dec52860d), U64(0xd0e3c177d0e3c177),
U64(0x6c16b32b6c16b32b), U64(0x99b970a999b970a9),
U64(0xfa489411fa489411), U64(0x2264e9472264e947),
U64(0xc48cfca8c48cfca8), U64(0x1a3ff0a01a3ff0a0),
U64(0xd82c7d56d82c7d56), U64(0xef903322ef903322),
U64(0xc74e4987c74e4987), U64(0xc1d138d9c1d138d9),
U64(0xfea2ca8cfea2ca8c), U64(0x360bd498360bd498),
U64(0xcf81f5a6cf81f5a6), U64(0x28de7aa528de7aa5),
U64(0x268eb7da268eb7da), U64(0xa4bfad3fa4bfad3f),
U64(0xe49d3a2ce49d3a2c), U64(0x0d9278500d927850),
U64(0x9bcc5f6a9bcc5f6a), U64(0x62467e5462467e54),
U64(0xc2138df6c2138df6), U64(0xe8b8d890e8b8d890),
U64(0x5ef7392e5ef7392e), U64(0xf5afc382f5afc382),
U64(0xbe805d9fbe805d9f), U64(0x7c93d0697c93d069),
U64(0xa92dd56fa92dd56f), U64(0xb31225cfb31225cf),
U64(0x3b99acc83b99acc8), U64(0xa77d1810a77d1810),
U64(0x6e639ce86e639ce8), U64(0x7bbb3bdb7bbb3bdb),
U64(0x097826cd097826cd), U64(0xf418596ef418596e),
U64(0x01b79aec01b79aec), U64(0xa89a4f83a89a4f83),
U64(0x656e95e6656e95e6), U64(0x7ee6ffaa7ee6ffaa),
U64(0x08cfbc2108cfbc21), U64(0xe6e815efe6e815ef),
U64(0xd99be7bad99be7ba), U64(0xce366f4ace366f4a),
U64(0xd4099fead4099fea), U64(0xd67cb029d67cb029),
U64(0xafb2a431afb2a431), U64(0x31233f2a31233f2a),
U64(0x3094a5c63094a5c6), U64(0xc066a235c066a235),
U64(0x37bc4e7437bc4e74), U64(0xa6ca82fca6ca82fc),
U64(0xb0d090e0b0d090e0), U64(0x15d8a73315d8a733),
U64(0x4a9804f14a9804f1), U64(0xf7daec41f7daec41),
U64(0x0e50cd7f0e50cd7f), U64(0x2ff691172ff69117),
U64(0x8dd64d768dd64d76), U64(0x4db0ef434db0ef43),
U64(0x544daacc544daacc), U64(0xdf0496e4df0496e4),
U64(0xe3b5d19ee3b5d19e), U64(0x1b886a4c1b886a4c),
U64(0xb81f2cc1b81f2cc1), U64(0x7f5165467f516546),
U64(0x04ea5e9d04ea5e9d), U64(0x5d358c015d358c01),
U64(0x737487fa737487fa), U64(0x2e410bfb2e410bfb),
U64(0x5a1d67b35a1d67b3), U64(0x52d2db9252d2db92),
U64(0x335610e9335610e9), U64(0x1347d66d1347d66d),
U64(0x8c61d79a8c61d79a), U64(0x7a0ca1377a0ca137),
U64(0x8e14f8598e14f859), U64(0x893c13eb893c13eb),
U64(0xee27a9ceee27a9ce), U64(0x35c961b735c961b7),
U64(0xede51ce1ede51ce1), U64(0x3cb1477a3cb1477a),
U64(0x59dfd29c59dfd29c), U64(0x3f73f2553f73f255),
U64(0x79ce141879ce1418), U64(0xbf37c773bf37c773),
U64(0xeacdf753eacdf753), U64(0x5baafd5f5baafd5f),
U64(0x146f3ddf146f3ddf), U64(0x86db447886db4478),
U64(0x81f3afca81f3afca), U64(0x3ec468b93ec468b9),
U64(0x2c3424382c342438), U64(0x5f40a3c25f40a3c2),
U64(0x72c31d1672c31d16), U64(0x0c25e2bc0c25e2bc),
U64(0x8b493c288b493c28), U64(0x41950dff41950dff),
U64(0x7101a8397101a839), U64(0xdeb30c08deb30c08),
U64(0x9ce4b4d89ce4b4d8), U64(0x90c1566490c15664),
U64(0x6184cb7b6184cb7b), U64(0x70b632d570b632d5),
U64(0x745c6c48745c6c48), U64(0x4257b8d04257b8d0)
};
static const u8 Td4[256] = {
0x52U, 0x09U, 0x6aU, 0xd5U, 0x30U, 0x36U, 0xa5U, 0x38U,
0xbfU, 0x40U, 0xa3U, 0x9eU, 0x81U, 0xf3U, 0xd7U, 0xfbU,
0x7cU, 0xe3U, 0x39U, 0x82U, 0x9bU, 0x2fU, 0xffU, 0x87U,
0x34U, 0x8eU, 0x43U, 0x44U, 0xc4U, 0xdeU, 0xe9U, 0xcbU,
0x54U, 0x7bU, 0x94U, 0x32U, 0xa6U, 0xc2U, 0x23U, 0x3dU,
0xeeU, 0x4cU, 0x95U, 0x0bU, 0x42U, 0xfaU, 0xc3U, 0x4eU,
0x08U, 0x2eU, 0xa1U, 0x66U, 0x28U, 0xd9U, 0x24U, 0xb2U,
0x76U, 0x5bU, 0xa2U, 0x49U, 0x6dU, 0x8bU, 0xd1U, 0x25U,
0x72U, 0xf8U, 0xf6U, 0x64U, 0x86U, 0x68U, 0x98U, 0x16U,
0xd4U, 0xa4U, 0x5cU, 0xccU, 0x5dU, 0x65U, 0xb6U, 0x92U,
0x6cU, 0x70U, 0x48U, 0x50U, 0xfdU, 0xedU, 0xb9U, 0xdaU,
0x5eU, 0x15U, 0x46U, 0x57U, 0xa7U, 0x8dU, 0x9dU, 0x84U,
0x90U, 0xd8U, 0xabU, 0x00U, 0x8cU, 0xbcU, 0xd3U, 0x0aU,
0xf7U, 0xe4U, 0x58U, 0x05U, 0xb8U, 0xb3U, 0x45U, 0x06U,
0xd0U, 0x2cU, 0x1eU, 0x8fU, 0xcaU, 0x3fU, 0x0fU, 0x02U,
0xc1U, 0xafU, 0xbdU, 0x03U, 0x01U, 0x13U, 0x8aU, 0x6bU,
0x3aU, 0x91U, 0x11U, 0x41U, 0x4fU, 0x67U, 0xdcU, 0xeaU,
0x97U, 0xf2U, 0xcfU, 0xceU, 0xf0U, 0xb4U, 0xe6U, 0x73U,
0x96U, 0xacU, 0x74U, 0x22U, 0xe7U, 0xadU, 0x35U, 0x85U,
0xe2U, 0xf9U, 0x37U, 0xe8U, 0x1cU, 0x75U, 0xdfU, 0x6eU,
0x47U, 0xf1U, 0x1aU, 0x71U, 0x1dU, 0x29U, 0xc5U, 0x89U,
0x6fU, 0xb7U, 0x62U, 0x0eU, 0xaaU, 0x18U, 0xbeU, 0x1bU,
0xfcU, 0x56U, 0x3eU, 0x4bU, 0xc6U, 0xd2U, 0x79U, 0x20U,
0x9aU, 0xdbU, 0xc0U, 0xfeU, 0x78U, 0xcdU, 0x5aU, 0xf4U,
0x1fU, 0xddU, 0xa8U, 0x33U, 0x88U, 0x07U, 0xc7U, 0x31U,
0xb1U, 0x12U, 0x10U, 0x59U, 0x27U, 0x80U, 0xecU, 0x5fU,
0x60U, 0x51U, 0x7fU, 0xa9U, 0x19U, 0xb5U, 0x4aU, 0x0dU,
0x2dU, 0xe5U, 0x7aU, 0x9fU, 0x93U, 0xc9U, 0x9cU, 0xefU,
0xa0U, 0xe0U, 0x3bU, 0x4dU, 0xaeU, 0x2aU, 0xf5U, 0xb0U,
0xc8U, 0xebU, 0xbbU, 0x3cU, 0x83U, 0x53U, 0x99U, 0x61U,
0x17U, 0x2bU, 0x04U, 0x7eU, 0xbaU, 0x77U, 0xd6U, 0x26U,
0xe1U, 0x69U, 0x14U, 0x63U, 0x55U, 0x21U, 0x0cU, 0x7dU
};
static const u32 rcon[] = {
0x00000001U, 0x00000002U, 0x00000004U, 0x00000008U,
0x00000010U, 0x00000020U, 0x00000040U, 0x00000080U,
0x0000001bU, 0x00000036U, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */
};
/**
* Expand the cipher key into the encryption key schedule.
*/
int AES_set_encrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key) {
u32 *rk;
int i = 0;
u32 temp;
if (!userKey || !key)
return -1;
if (bits != 128 && bits != 192 && bits != 256)
return -2;
rk = key->rd_key;
if (bits==128)
key->rounds = 10;
else if (bits==192)
key->rounds = 12;
else
key->rounds = 14;
rk[0] = GETU32(userKey );
rk[1] = GETU32(userKey + 4);
rk[2] = GETU32(userKey + 8);
rk[3] = GETU32(userKey + 12);
if (bits == 128) {
while (1) {
temp = rk[3];
rk[4] = rk[0] ^
(Te4[(temp >> 8) & 0xff] ) ^
(Te4[(temp >> 16) & 0xff] << 8) ^
(Te4[(temp >> 24) ] << 16) ^
(Te4[(temp ) & 0xff] << 24) ^
rcon[i];
rk[5] = rk[1] ^ rk[4];
rk[6] = rk[2] ^ rk[5];
rk[7] = rk[3] ^ rk[6];
if (++i == 10) {
return 0;
}
rk += 4;
}
}
rk[4] = GETU32(userKey + 16);
rk[5] = GETU32(userKey + 20);
if (bits == 192) {
while (1) {
temp = rk[ 5];
rk[ 6] = rk[ 0] ^
(Te4[(temp >> 8) & 0xff] ) ^
(Te4[(temp >> 16) & 0xff] << 8) ^
(Te4[(temp >> 24) ] << 16) ^
(Te4[(temp ) & 0xff] << 24) ^
rcon[i];
rk[ 7] = rk[ 1] ^ rk[ 6];
rk[ 8] = rk[ 2] ^ rk[ 7];
rk[ 9] = rk[ 3] ^ rk[ 8];
if (++i == 8) {
return 0;
}
rk[10] = rk[ 4] ^ rk[ 9];
rk[11] = rk[ 5] ^ rk[10];
rk += 6;
}
}
rk[6] = GETU32(userKey + 24);
rk[7] = GETU32(userKey + 28);
if (bits == 256) {
while (1) {
temp = rk[ 7];
rk[ 8] = rk[ 0] ^
(Te4[(temp >> 8) & 0xff] ) ^
(Te4[(temp >> 16) & 0xff] << 8) ^
(Te4[(temp >> 24) ] << 16) ^
(Te4[(temp ) & 0xff] << 24) ^
rcon[i];
rk[ 9] = rk[ 1] ^ rk[ 8];
rk[10] = rk[ 2] ^ rk[ 9];
rk[11] = rk[ 3] ^ rk[10];
if (++i == 7) {
return 0;
}
temp = rk[11];
rk[12] = rk[ 4] ^
(Te4[(temp ) & 0xff] ) ^
(Te4[(temp >> 8) & 0xff] << 8) ^
(Te4[(temp >> 16) & 0xff] << 16) ^
(Te4[(temp >> 24) ] << 24);
rk[13] = rk[ 5] ^ rk[12];
rk[14] = rk[ 6] ^ rk[13];
rk[15] = rk[ 7] ^ rk[14];
rk += 8;
}
}
return 0;
}
/**
* Expand the cipher key into the decryption key schedule.
*/
int AES_set_decrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key) {
u32 *rk;
int i, j, status;
u32 temp;
/* first, start with an encryption schedule */
status = AES_set_encrypt_key(userKey, bits, key);
if (status < 0)
return status;
rk = key->rd_key;
/* invert the order of the round keys: */
for (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) {
temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;
temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;
temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;
temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;
}
/* apply the inverse MixColumn transform to all round keys but the first and the last: */
for (i = 1; i < (key->rounds); i++) {
rk += 4;
#if 1
for (j = 0; j < 4; j++) {
u32 tp1, tp2, tp4, tp8, tp9, tpb, tpd, tpe, m;
tp1 = rk[j];
m = tp1 & 0x80808080;
tp2 = ((tp1 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp2 & 0x80808080;
tp4 = ((tp2 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp4 & 0x80808080;
tp8 = ((tp4 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
tp9 = tp8 ^ tp1;
tpb = tp9 ^ tp2;
tpd = tp9 ^ tp4;
tpe = tp8 ^ tp4 ^ tp2;
#if defined(ROTATE)
rk[j] = tpe ^ ROTATE(tpd,16) ^
ROTATE(tp9,8) ^ ROTATE(tpb,24);
#else
rk[j] = tpe ^ (tpd >> 16) ^ (tpd << 16) ^
(tp9 >> 24) ^ (tp9 << 8) ^
(tpb >> 8) ^ (tpb << 24);
#endif
}
#else
rk[0] =
Td0[Te2[(rk[0] ) & 0xff] & 0xff] ^
Td1[Te2[(rk[0] >> 8) & 0xff] & 0xff] ^
Td2[Te2[(rk[0] >> 16) & 0xff] & 0xff] ^
Td3[Te2[(rk[0] >> 24) ] & 0xff];
rk[1] =
Td0[Te2[(rk[1] ) & 0xff] & 0xff] ^
Td1[Te2[(rk[1] >> 8) & 0xff] & 0xff] ^
Td2[Te2[(rk[1] >> 16) & 0xff] & 0xff] ^
Td3[Te2[(rk[1] >> 24) ] & 0xff];
rk[2] =
Td0[Te2[(rk[2] ) & 0xff] & 0xff] ^
Td1[Te2[(rk[2] >> 8) & 0xff] & 0xff] ^
Td2[Te2[(rk[2] >> 16) & 0xff] & 0xff] ^
Td3[Te2[(rk[2] >> 24) ] & 0xff];
rk[3] =
Td0[Te2[(rk[3] ) & 0xff] & 0xff] ^
Td1[Te2[(rk[3] >> 8) & 0xff] & 0xff] ^
Td2[Te2[(rk[3] >> 16) & 0xff] & 0xff] ^
Td3[Te2[(rk[3] >> 24) ] & 0xff];
#endif
}
return 0;
}
/*
* Encrypt a single block
* in and out can overlap
*/
void AES_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key) {
const u32 *rk;
u32 s0, s1, s2, s3, t[4];
int r;
TINYCLR_SSL_ASSERT(in && out && key);
rk = key->rd_key;
/*
* map byte array block to cipher state
* and add initial round key:
*/
s0 = GETU32(in ) ^ rk[0];
s1 = GETU32(in + 4) ^ rk[1];
s2 = GETU32(in + 8) ^ rk[2];
s3 = GETU32(in + 12) ^ rk[3];
#if defined(AES_COMPACT_IN_OUTER_ROUNDS)
prefetch256(Te4);
t[0] = Te4[(s0 ) & 0xff] ^
Te4[(s1 >> 8) & 0xff] << 8 ^
Te4[(s2 >> 16) & 0xff] << 16 ^
Te4[(s3 >> 24) ] << 24;
t[1] = Te4[(s1 ) & 0xff] ^
Te4[(s2 >> 8) & 0xff] << 8 ^
Te4[(s3 >> 16) & 0xff] << 16 ^
Te4[(s0 >> 24) ] << 24;
t[2] = Te4[(s2 ) & 0xff] ^
Te4[(s3 >> 8) & 0xff] << 8 ^
Te4[(s0 >> 16) & 0xff] << 16 ^
Te4[(s1 >> 24) ] << 24;
t[3] = Te4[(s3 ) & 0xff] ^
Te4[(s0 >> 8) & 0xff] << 8 ^
Te4[(s1 >> 16) & 0xff] << 16 ^
Te4[(s2 >> 24) ] << 24;
/* now do the linear transform using words */
{ int i;
u32 r0, r1, r2;
for (i = 0; i < 4; i++) {
r0 = t[i];
r1 = r0 & 0x80808080;
r2 = ((r0 & 0x7f7f7f7f) << 1) ^
((r1 - (r1 >> 7)) & 0x1b1b1b1b);
#if defined(ROTATE)
t[i] = r2 ^ ROTATE(r2,24) ^ ROTATE(r0,24) ^
ROTATE(r0,16) ^ ROTATE(r0,8);
#else
t[i] = r2 ^ ((r2 ^ r0) << 24) ^ ((r2 ^ r0) >> 8) ^
(r0 << 16) ^ (r0 >> 16) ^
(r0 << 8) ^ (r0 >> 24);
#endif
t[i] ^= rk[4+i];
}
}
#else
t[0] = Te0[(s0 ) & 0xff] ^
Te1[(s1 >> 8) & 0xff] ^
Te2[(s2 >> 16) & 0xff] ^
Te3[(s3 >> 24) ] ^
rk[4];
t[1] = Te0[(s1 ) & 0xff] ^
Te1[(s2 >> 8) & 0xff] ^
Te2[(s3 >> 16) & 0xff] ^
Te3[(s0 >> 24) ] ^
rk[5];
t[2] = Te0[(s2 ) & 0xff] ^
Te1[(s3 >> 8) & 0xff] ^
Te2[(s0 >> 16) & 0xff] ^
Te3[(s1 >> 24) ] ^
rk[6];
t[3] = Te0[(s3 ) & 0xff] ^
Te1[(s0 >> 8) & 0xff] ^
Te2[(s1 >> 16) & 0xff] ^
Te3[(s2 >> 24) ] ^
rk[7];
#endif
s0 = t[0]; s1 = t[1]; s2 = t[2]; s3 = t[3];
/*
* Nr - 2 full rounds:
*/
for (rk+=8,r=key->rounds-2; r>0; rk+=4,r--) {
#if defined(AES_COMPACT_IN_INNER_ROUNDS)
t[0] = Te4[(s0 ) & 0xff] ^
Te4[(s1 >> 8) & 0xff] << 8 ^
Te4[(s2 >> 16) & 0xff] << 16 ^
Te4[(s3 >> 24) ] << 24;
t[1] = Te4[(s1 ) & 0xff] ^
Te4[(s2 >> 8) & 0xff] << 8 ^
Te4[(s3 >> 16) & 0xff] << 16 ^
Te4[(s0 >> 24) ] << 24;
t[2] = Te4[(s2 ) & 0xff] ^
Te4[(s3 >> 8) & 0xff] << 8 ^
Te4[(s0 >> 16) & 0xff] << 16 ^
Te4[(s1 >> 24) ] << 24;
t[3] = Te4[(s3 ) & 0xff] ^
Te4[(s0 >> 8) & 0xff] << 8 ^
Te4[(s1 >> 16) & 0xff] << 16 ^
Te4[(s2 >> 24) ] << 24;
/* now do the linear transform using words */
{ int i;
u32 r0, r1, r2;
for (i = 0; i < 4; i++) {
r0 = t[i];
r1 = r0 & 0x80808080;
r2 = ((r0 & 0x7f7f7f7f) << 1) ^
((r1 - (r1 >> 7)) & 0x1b1b1b1b);
#if defined(ROTATE)
t[i] = r2 ^ ROTATE(r2,24) ^ ROTATE(r0,24) ^
ROTATE(r0,16) ^ ROTATE(r0,8);
#else
t[i] = r2 ^ ((r2 ^ r0) << 24) ^ ((r2 ^ r0) >> 8) ^
(r0 << 16) ^ (r0 >> 16) ^
(r0 << 8) ^ (r0 >> 24);
#endif
t[i] ^= rk[i];
}
}
#else
t[0] = Te0[(s0 ) & 0xff] ^
Te1[(s1 >> 8) & 0xff] ^
Te2[(s2 >> 16) & 0xff] ^
Te3[(s3 >> 24) ] ^
rk[0];
t[1] = Te0[(s1 ) & 0xff] ^
Te1[(s2 >> 8) & 0xff] ^
Te2[(s3 >> 16) & 0xff] ^
Te3[(s0 >> 24) ] ^
rk[1];
t[2] = Te0[(s2 ) & 0xff] ^
Te1[(s3 >> 8) & 0xff] ^
Te2[(s0 >> 16) & 0xff] ^
Te3[(s1 >> 24) ] ^
rk[2];
t[3] = Te0[(s3 ) & 0xff] ^
Te1[(s0 >> 8) & 0xff] ^
Te2[(s1 >> 16) & 0xff] ^
Te3[(s2 >> 24) ] ^
rk[3];
#endif
s0 = t[0]; s1 = t[1]; s2 = t[2]; s3 = t[3];
}
/*
* apply last round and
* map cipher state to byte array block:
*/
#if defined(AES_COMPACT_IN_OUTER_ROUNDS)
prefetch256(Te4);
*(u32*)(out+0) =
Te4[(s0 ) & 0xff] ^
Te4[(s1 >> 8) & 0xff] << 8 ^
Te4[(s2 >> 16) & 0xff] << 16 ^
Te4[(s3 >> 24) ] << 24 ^
rk[0];
*(u32*)(out+4) =
Te4[(s1 ) & 0xff] ^
Te4[(s2 >> 8) & 0xff] << 8 ^
Te4[(s3 >> 16) & 0xff] << 16 ^
Te4[(s0 >> 24) ] << 24 ^
rk[1];
*(u32*)(out+8) =
Te4[(s2 ) & 0xff] ^
Te4[(s3 >> 8) & 0xff] << 8 ^
Te4[(s0 >> 16) & 0xff] << 16 ^
Te4[(s1 >> 24) ] << 24 ^
rk[2];
*(u32*)(out+12) =
Te4[(s3 ) & 0xff] ^
Te4[(s0 >> 8) & 0xff] << 8 ^
Te4[(s1 >> 16) & 0xff] << 16 ^
Te4[(s2 >> 24) ] << 24 ^
rk[3];
#else
*(u32*)(out+0) =
(Te2[(s0 ) & 0xff] & 0x000000ffU) ^
(Te3[(s1 >> 8) & 0xff] & 0x0000ff00U) ^
(Te0[(s2 >> 16) & 0xff] & 0x00ff0000U) ^
(Te1[(s3 >> 24) ] & 0xff000000U) ^
rk[0];
*(u32*)(out+4) =
(Te2[(s1 ) & 0xff] & 0x000000ffU) ^
(Te3[(s2 >> 8) & 0xff] & 0x0000ff00U) ^
(Te0[(s3 >> 16) & 0xff] & 0x00ff0000U) ^
(Te1[(s0 >> 24) ] & 0xff000000U) ^
rk[1];
*(u32*)(out+8) =
(Te2[(s2 ) & 0xff] & 0x000000ffU) ^
(Te3[(s3 >> 8) & 0xff] & 0x0000ff00U) ^
(Te0[(s0 >> 16) & 0xff] & 0x00ff0000U) ^
(Te1[(s1 >> 24) ] & 0xff000000U) ^
rk[2];
*(u32*)(out+12) =
(Te2[(s3 ) & 0xff] & 0x000000ffU) ^
(Te3[(s0 >> 8) & 0xff] & 0x0000ff00U) ^
(Te0[(s1 >> 16) & 0xff] & 0x00ff0000U) ^
(Te1[(s2 >> 24) ] & 0xff000000U) ^
rk[3];
#endif
}
/*
* Decrypt a single block
* in and out can overlap
*/
void AES_decrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key) {
const u32 *rk;
u32 s0, s1, s2, s3, t[4];
int r;
TINYCLR_SSL_ASSERT(in && out && key);
rk = key->rd_key;
/*
* map byte array block to cipher state
* and add initial round key:
*/
s0 = GETU32(in ) ^ rk[0];
s1 = GETU32(in + 4) ^ rk[1];
s2 = GETU32(in + 8) ^ rk[2];
s3 = GETU32(in + 12) ^ rk[3];
#if defined(AES_COMPACT_IN_OUTER_ROUNDS)
prefetch256(Td4);
t[0] = Td4[(s0 ) & 0xff] ^
Td4[(s3 >> 8) & 0xff] << 8 ^
Td4[(s2 >> 16) & 0xff] << 16 ^
Td4[(s1 >> 24) ] << 24;
t[1] = Td4[(s1 ) & 0xff] ^
Td4[(s0 >> 8) & 0xff] << 8 ^
Td4[(s3 >> 16) & 0xff] << 16 ^
Td4[(s2 >> 24) ] << 24;
t[2] = Td4[(s2 ) & 0xff] ^
Td4[(s1 >> 8) & 0xff] << 8 ^
Td4[(s0 >> 16) & 0xff] << 16 ^
Td4[(s3 >> 24) ] << 24;
t[3] = Td4[(s3 ) & 0xff] ^
Td4[(s2 >> 8) & 0xff] << 8 ^
Td4[(s1 >> 16) & 0xff] << 16 ^
Td4[(s0 >> 24) ] << 24;
/* now do the linear transform using words */
{ int i;
u32 tp1, tp2, tp4, tp8, tp9, tpb, tpd, tpe, m;
for (i = 0; i < 4; i++) {
tp1 = t[i];
m = tp1 & 0x80808080;
tp2 = ((tp1 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp2 & 0x80808080;
tp4 = ((tp2 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp4 & 0x80808080;
tp8 = ((tp4 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
tp9 = tp8 ^ tp1;
tpb = tp9 ^ tp2;
tpd = tp9 ^ tp4;
tpe = tp8 ^ tp4 ^ tp2;
#if defined(ROTATE)
t[i] = tpe ^ ROTATE(tpd,16) ^
ROTATE(tp9,8) ^ ROTATE(tpb,24);
#else
t[i] = tpe ^ (tpd >> 16) ^ (tpd << 16) ^
(tp9 >> 24) ^ (tp9 << 8) ^
(tpb >> 8) ^ (tpb << 24);
#endif
t[i] ^= rk[4+i];
}
}
#else
t[0] = Td0[(s0 ) & 0xff] ^
Td1[(s3 >> 8) & 0xff] ^
Td2[(s2 >> 16) & 0xff] ^
Td3[(s1 >> 24) ] ^
rk[4];
t[1] = Td0[(s1 ) & 0xff] ^
Td1[(s0 >> 8) & 0xff] ^
Td2[(s3 >> 16) & 0xff] ^
Td3[(s2 >> 24) ] ^
rk[5];
t[2] = Td0[(s2 ) & 0xff] ^
Td1[(s1 >> 8) & 0xff] ^
Td2[(s0 >> 16) & 0xff] ^
Td3[(s3 >> 24) ] ^
rk[6];
t[3] = Td0[(s3 ) & 0xff] ^
Td1[(s2 >> 8) & 0xff] ^
Td2[(s1 >> 16) & 0xff] ^
Td3[(s0 >> 24) ] ^
rk[7];
#endif
s0 = t[0]; s1 = t[1]; s2 = t[2]; s3 = t[3];
/*
* Nr - 2 full rounds:
*/
for (rk+=8,r=key->rounds-2; r>0; rk+=4,r--) {
#if defined(AES_COMPACT_IN_INNER_ROUNDS)
t[0] = Td4[(s0 ) & 0xff] ^
Td4[(s3 >> 8) & 0xff] << 8 ^
Td4[(s2 >> 16) & 0xff] << 16 ^
Td4[(s1 >> 24) ] << 24;
t[1] = Td4[(s1 ) & 0xff] ^
Td4[(s0 >> 8) & 0xff] << 8 ^
Td4[(s3 >> 16) & 0xff] << 16 ^
Td4[(s2 >> 24) ] << 24;
t[2] = Td4[(s2 ) & 0xff] ^
Td4[(s1 >> 8) & 0xff] << 8 ^
Td4[(s0 >> 16) & 0xff] << 16 ^
Td4[(s3 >> 24) ] << 24;
t[3] = Td4[(s3 ) & 0xff] ^
Td4[(s2 >> 8) & 0xff] << 8 ^
Td4[(s1 >> 16) & 0xff] << 16 ^
Td4[(s0 >> 24) ] << 24;
/* now do the linear transform using words */
{ int i;
u32 tp1, tp2, tp4, tp8, tp9, tpb, tpd, tpe, m;
for (i = 0; i < 4; i++) {
tp1 = t[i];
m = tp1 & 0x80808080;
tp2 = ((tp1 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp2 & 0x80808080;
tp4 = ((tp2 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp4 & 0x80808080;
tp8 = ((tp4 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
tp9 = tp8 ^ tp1;
tpb = tp9 ^ tp2;
tpd = tp9 ^ tp4;
tpe = tp8 ^ tp4 ^ tp2;
#if defined(ROTATE)
t[i] = tpe ^ ROTATE(tpd,16) ^
ROTATE(tp9,8) ^ ROTATE(tpb,24);
#else
t[i] = tpe ^ (tpd >> 16) ^ (tpd << 16) ^
(tp9 >> 24) ^ (tp9 << 8) ^
(tpb >> 8) ^ (tpb << 24);
#endif
t[i] ^= rk[i];
}
}
#else
t[0] = Td0[(s0 ) & 0xff] ^
Td1[(s3 >> 8) & 0xff] ^
Td2[(s2 >> 16) & 0xff] ^
Td3[(s1 >> 24) ] ^
rk[0];
t[1] = Td0[(s1 ) & 0xff] ^
Td1[(s0 >> 8) & 0xff] ^
Td2[(s3 >> 16) & 0xff] ^
Td3[(s2 >> 24) ] ^
rk[1];
t[2] = Td0[(s2 ) & 0xff] ^
Td1[(s1 >> 8) & 0xff] ^
Td2[(s0 >> 16) & 0xff] ^
Td3[(s3 >> 24) ] ^
rk[2];
t[3] = Td0[(s3 ) & 0xff] ^
Td1[(s2 >> 8) & 0xff] ^
Td2[(s1 >> 16) & 0xff] ^
Td3[(s0 >> 24) ] ^
rk[3];
#endif
s0 = t[0]; s1 = t[1]; s2 = t[2]; s3 = t[3];
}
/*
* apply last round and
* map cipher state to byte array block:
*/
prefetch256(Td4);
*(u32*)(out+0) =
(Td4[(s0 ) & 0xff]) ^
(Td4[(s3 >> 8) & 0xff] << 8) ^
(Td4[(s2 >> 16) & 0xff] << 16) ^
(Td4[(s1 >> 24) ] << 24) ^
rk[0];
*(u32*)(out+4) =
(Td4[(s1 ) & 0xff]) ^
(Td4[(s0 >> 8) & 0xff] << 8) ^
(Td4[(s3 >> 16) & 0xff] << 16) ^
(Td4[(s2 >> 24) ] << 24) ^
rk[1];
*(u32*)(out+8) =
(Td4[(s2 ) & 0xff]) ^
(Td4[(s1 >> 8) & 0xff] << 8) ^
(Td4[(s0 >> 16) & 0xff] << 16) ^
(Td4[(s3 >> 24) ] << 24) ^
rk[2];
*(u32*)(out+12) =
(Td4[(s3 ) & 0xff]) ^
(Td4[(s2 >> 8) & 0xff] << 8) ^
(Td4[(s1 >> 16) & 0xff] << 16) ^
(Td4[(s0 >> 24) ] << 24) ^
rk[3];
}
| 24,597 |
799 |
<reponame>diCagri/content
[
{
"configuredName": "Phishing-Suspected",
"customCategory": true,
"dbCategorizedUrls": [],
"editable": true,
"id": "CUSTOM_1",
"keywordsRetainingParentCategory": [],
"type": "URL_CATEGORY",
"urls": [],
"val": 144
}
]
| 133 |
945 |
<filename>Modules/ThirdParty/VNL/src/vxl/v3p/netlib/opt/lbfgs.c<gh_stars>100-1000
/* opt/lbfgs.f -- translated by f2c (version 20050501).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "v3p_netlib.h"
#undef abs
#undef min
#undef max
#include <math.h>
#include <stdio.h>
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define min(a,b) ((a) <= (b) ? (a) : (b))
#define max(a,b) ((a) >= (b) ? (a) : (b))
/* Provide initialization function for global data argument. */
#define lb3_1 (*v3p_netlib_lbfgs_global_arg)
void
v3p_netlib_lbfgs_init(v3p_netlib_lbfgs_global_t* v3p_netlib_lbfgs_global_arg)
{
lb3_1.mp = 6;
lb3_1.lp = 6;
lb3_1.gtol = 0.9;
lb3_1.stpmin = 1e-20;
lb3_1.stpmax = 1e20;
lb3_1.stpinit = 1; /* line search default step length, added by awf */
}
/* Map persistent data. */
#define info (*v3p_netlib_lbfgs_global_arg).private_info
#define infoc (*v3p_netlib_lbfgs_global_arg).private_infoc
#define nfev (*v3p_netlib_lbfgs_global_arg).private_nfev
#define maxfev (*v3p_netlib_lbfgs_global_arg).private_maxfev
#define stp (*v3p_netlib_lbfgs_global_arg).private_stp
#define stp1 (*v3p_netlib_lbfgs_global_arg).private_stp1
#define beta (*v3p_netlib_lbfgs_global_arg).private_beta
#define ftol (*v3p_netlib_lbfgs_global_arg).private_ftol
#define gnorm (*v3p_netlib_lbfgs_global_arg).private_gnorm
#define xnorm (*v3p_netlib_lbfgs_global_arg).private_xnorm
#define inmc (*v3p_netlib_lbfgs_global_arg).private_inmc
#define iscn (*v3p_netlib_lbfgs_global_arg).private_iscn
#define iycn (*v3p_netlib_lbfgs_global_arg).private_iycn
#define iter (*v3p_netlib_lbfgs_global_arg).private_iter
#define nfun (*v3p_netlib_lbfgs_global_arg).private_nfun
#define ispt (*v3p_netlib_lbfgs_global_arg).private_ispt
#define iypt (*v3p_netlib_lbfgs_global_arg).private_iypt
#define bound (*v3p_netlib_lbfgs_global_arg).private_bound
#define point (*v3p_netlib_lbfgs_global_arg).private_point
#define finish (*v3p_netlib_lbfgs_global_arg).private_finish
#define dg (*v3p_netlib_lbfgs_global_arg).private_dg
#define fm (*v3p_netlib_lbfgs_global_arg).private_fm
#define fx (*v3p_netlib_lbfgs_global_arg).private_fx
#define fy (*v3p_netlib_lbfgs_global_arg).private_fy
#define dgm (*v3p_netlib_lbfgs_global_arg).private_dgm
#define dgx (*v3p_netlib_lbfgs_global_arg).private_dgx
#define dgy (*v3p_netlib_lbfgs_global_arg).private_dgy
#define fxm (*v3p_netlib_lbfgs_global_arg).private_fxm
#define fym (*v3p_netlib_lbfgs_global_arg).private_fym
#define stx (*v3p_netlib_lbfgs_global_arg).private_stx
#define sty (*v3p_netlib_lbfgs_global_arg).private_sty
#define dgxm (*v3p_netlib_lbfgs_global_arg).private_dgxm
#define dgym (*v3p_netlib_lbfgs_global_arg).private_dgym
#define finit (*v3p_netlib_lbfgs_global_arg).private_finit
#define width (*v3p_netlib_lbfgs_global_arg).private_width
#define stmin (*v3p_netlib_lbfgs_global_arg).private_stmin
#define stmax (*v3p_netlib_lbfgs_global_arg).private_stmax
#define stage1 (*v3p_netlib_lbfgs_global_arg).private_stage1
#define width1 (*v3p_netlib_lbfgs_global_arg).private_width1
#define ftest1 (*v3p_netlib_lbfgs_global_arg).private_ftest1
#define brackt (*v3p_netlib_lbfgs_global_arg).private_brackt
#define dginit (*v3p_netlib_lbfgs_global_arg).private_dginit
#define dgtest (*v3p_netlib_lbfgs_global_arg).private_dgtest
/* Table of constant values */
static integer c__1 = 1;
/* ---------------------------------------------------------------------- */
/* This file contains the LBFGS algorithm and supporting routines */
/* **************** */
/* LBFGS SUBROUTINE */
/* **************** */
/*< SUBROUTINE LBFGS(N,M,X,F,G,DIAGCO,DIAG,IPRINT,EPS,XTOL,W,IFLAG) >*/
/* Subroutine */ int lbfgs_(integer *n, integer *m, doublereal *x, doublereal
*f, doublereal *g, logical *diagco, doublereal *diag, integer *iprint,
doublereal *eps, doublereal *xtol, doublereal *w, integer *iflag,
v3p_netlib_lbfgs_global_t* v3p_netlib_lbfgs_global_arg)
{
/* Initialized data */
static doublereal one = 1.; /* constant */
static doublereal zero = 0.; /* constant */
/* System generated locals */
integer i__1;
doublereal d__1;
/* Builtin functions */
double sqrt(doublereal);
/* Local variables */
integer i__, cp;
doublereal sq, yr, ys=0, yy;
extern /* Subroutine */ int lb1_(
integer *iprint, integer *n, integer *m, doublereal *x, doublereal *f,
doublereal *g, v3p_netlib_lbfgs_global_t* v3p_netlib_lbfgs_global_arg);
extern doublereal ddot_(integer *, doublereal *, integer *, doublereal *,
integer *);
extern /* Subroutine */ int daxpy_(integer *, doublereal *, doublereal *,
integer *, doublereal *, integer *);
extern /* Subroutine */ int mcsrch_(integer *, doublereal *, doublereal *,
doublereal *, doublereal *,
doublereal *, doublereal *,
v3p_netlib_lbfgs_global_t*);
integer npt=0;
/*< INTEGER N,M,IPRINT(2),IFLAG >*/
/*< DOUBLE PRECISION X(N),G(N),DIAG(N),W(N*(2*M+1)+2*M) >*/
/*< DOUBLE PRECISION F,EPS,XTOL >*/
/*< LOGICAL DIAGCO >*/
/* LIMITED MEMORY BFGS METHOD FOR LARGE SCALE OPTIMIZATION */
/* <NAME> */
/* *** July 1990 *** */
/* This subroutine solves the unconstrained minimization problem */
/* min F(x), x= (x1,x2,...,xN), */
/* using the limited memory BFGS method. The routine is especially */
/* effective on problems involving a large number of variables. In */
/* a typical iteration of this method an approximation Hk to the */
/* inverse of the Hessian is obtained by applying M BFGS updates to */
/* a diagonal matrix Hk0, using information from the previous M steps. */
/* The user specifies the number M, which determines the amount of */
/* storage required by the routine. The user may also provide the */
/* diagonal matrices Hk0 if not satisfied with the default choice. */
/* The algorithm is described in "On the limited memory BFGS method */
/* for large scale optimization", by <NAME> and <NAME>, */
/* Mathematical Programming B 45 (1989) 503-528. */
/* The user is required to calculate the function value F and its */
/* gradient G. In order to allow the user complete control over */
/* these computations, reverse communication is used. The routine */
/* must be called repeatedly under the control of the parameter */
/* IFLAG. */
/* The steplength is determined at each iteration by means of the */
/* line search routine MCVSRCH, which is a slight modification of */
/* the routine CSRCH written by <NAME>. */
/* The calling statement is */
/* CALL LBFGS(N,M,X,F,G,DIAGCO,DIAG,IPRINT,EPS,XTOL,W,IFLAG) */
/* where */
/* N is an INTEGER variable that must be set by the user to the */
/* number of variables. It is not altered by the routine. */
/* Restriction: N>0. */
/* M is an INTEGER variable that must be set by the user to */
/* the number of corrections used in the BFGS update. It */
/* is not altered by the routine. Values of M less than 3 are */
/* not recommended; large values of M will result in excessive */
/* computing time. 3<= M <=7 is recommended. Restriction: M>0. */
/* X is a DOUBLE PRECISION array of length N. On initial entry */
/* it must be set by the user to the values of the initial */
/* estimate of the solution vector. On exit with IFLAG=0, it */
/* contains the values of the variables at the best point */
/* found (usually a solution). */
/* F is a DOUBLE PRECISION variable. Before initial entry and on */
/* a re-entry with IFLAG=1, it must be set by the user to */
/* contain the value of the function F at the point X. */
/* G is a DOUBLE PRECISION array of length N. Before initial */
/* entry and on a re-entry with IFLAG=1, it must be set by */
/* the user to contain the components of the gradient G at */
/* the point X. */
/* DIAGCO is a LOGICAL variable that must be set to .TRUE. if the */
/* user wishes to provide the diagonal matrix Hk0 at each */
/* iteration. Otherwise it should be set to .FALSE., in which */
/* case LBFGS will use a default value described below. If */
/* DIAGCO is set to .TRUE. the routine will return at each */
/* iteration of the algorithm with IFLAG=2, and the diagonal */
/* matrix Hk0 must be provided in the array DIAG. */
/* DIAG is a DOUBLE PRECISION array of length N. If DIAGCO=.TRUE., */
/* then on initial entry or on re-entry with IFLAG=2, DIAG */
/* it must be set by the user to contain the values of the */
/* diagonal matrix Hk0. Restriction: all elements of DIAG */
/* must be positive. */
/* IPRINT is an INTEGER array of length two which must be set by the */
/* user. */
/* IPRINT(1) specifies the frequency of the output: */
/* IPRINT(1) < 0 : no output is generated, */
/* IPRINT(1) = 0 : output only at first and last iteration, */
/* IPRINT(1) > 0 : output every IPRINT(1) iterations. */
/* IPRINT(2) specifies the type of output generated: */
/* IPRINT(2) = 0 : iteration count, number of function */
/* evaluations, function value, norm of the */
/* gradient, and steplength, */
/* IPRINT(2) = 1 : same as IPRINT(2)=0, plus vector of */
/* variables and gradient vector at the */
/* initial point, */
/* IPRINT(2) = 2 : same as IPRINT(2)=1, plus vector of */
/* variables, */
/* IPRINT(2) = 3 : same as IPRINT(2)=2, plus gradient vector. */
/* EPS is a positive DOUBLE PRECISION variable that must be set by */
/* the user, and determines the accuracy with which the solution */
/* is to be found. The subroutine terminates when */
/* ||G|| < EPS max(1,||X||), */
/* where ||.|| denotes the Euclidean norm. */
/* XTOL is a positive DOUBLE PRECISION variable that must be set by */
/* the user to an estimate of the machine precision (e.g. */
/* 10**(-16) on a SUN station 3/60). The line search routine will */
/* terminate if the relative width of the interval of uncertainty */
/* is less than XTOL. */
/* W is a DOUBLE PRECISION array of length N(2M+1)+2M used as */
/* workspace for LBFGS. This array must not be altered by the */
/* user. */
/* IFLAG is an INTEGER variable that must be set to 0 on initial entry */
/* to the subroutine. A return with IFLAG<0 indicates an error, */
/* and IFLAG=0 indicates that the routine has terminated without */
/* detecting errors. On a return with IFLAG=1, the user must */
/* evaluate the function F and gradient G. On a return with */
/* IFLAG=2, the user must provide the diagonal matrix Hk0. */
/* The following negative values of IFLAG, detecting an error, */
/* are possible: */
/* IFLAG=-1 The line search routine MCSRCH failed. The */
/* parameter INFO provides more detailed information */
/* (see also the documentation of MCSRCH): */
/* INFO = 0 IMPROPER INPUT PARAMETERS. */
/* INFO = 2 RELATIVE WIDTH OF THE INTERVAL OF */
/* UNCERTAINTY IS AT MOST XTOL. */
/* INFO = 3 MORE THAN 20 FUNCTION EVALUATIONS WERE */
/* REQUIRED AT THE PRESENT ITERATION. */
/* INFO = 4 THE STEP IS TOO SMALL. */
/* INFO = 5 THE STEP IS TOO LARGE. */
/* INFO = 6 ROUNDING ERRORS PREVENT FURTHER PROGRESS. */
/* THERE MAY NOT BE A STEP WHICH SATISFIES */
/* THE SUFFICIENT DECREASE AND CURVATURE */
/* CONDITIONS. TOLERANCES MAY BE TOO SMALL. */
/* IFLAG=-2 The i-th diagonal element of the diagonal inverse */
/* Hessian approximation, given in DIAG, is not */
/* positive. */
/* IFLAG=-3 Improper input parameters for LBFGS (N or M are */
/* not positive). */
/* ON THE DRIVER: */
/* The program that calls LBFGS must contain the declaration: */
/* COMMON: */
/* The subroutine contains one common area, which the user may wish to */
/* reference: */
/*< COMMON /LB3/MP,LP,GTOL,STPMIN,STPMAX >*/
/* MP is an INTEGER variable with default value 6. It is used as the */
/* unit number for the printing of the monitoring information */
/* controlled by IPRINT. */
/* LP is an INTEGER variable with default value 6. It is used as the */
/* unit number for the printing of error messages. This printing */
/* may be suppressed by setting LP to a non-positive value. */
/* GTOL is a DOUBLE PRECISION variable with default value 0.9, which */
/* controls the accuracy of the line search routine MCSRCH. If the */
/* function and gradient evaluations are inexpensive with respect */
/* to the cost of the iteration (which is sometimes the case when */
/* solving very large problems) it may be advantageous to set GTOL */
/* to a small value. A typical small value is 0.1. Restriction: */
/* GTOL should be greater than 1.D-04. */
/* STPMIN and STPMAX are non-negative DOUBLE PRECISION variables which */
/* specify lower and uper bounds for the step in the line search. */
/* Their default values are 1.D-20 and 1.D+20, respectively. These */
/* values need not be modified unless the exponents are too large */
/* for the machine being used, or unless the problem is extremely */
/* badly scaled (in which case the exponents should be increased). */
/* MACHINE DEPENDENCIES */
/* The only variables that are machine-dependent are XTOL, */
/* STPMIN and STPMAX. */
/* GENERAL INFORMATION */
/* Other routines called directly: DAXPY, DDOT, LB1, MCSRCH */
/* Input/Output : No input; diagnostic messages on unit MP and */
/* error messages on unit LP. */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*< >*/
/*< >*/
/*< LOGICAL FINISH >*/
/*< SAVE >*/
/*< DATA ONE,ZERO/1.0D+0,0.0D+0/ >*/
/* Parameter adjustments */
--diag;
--g;
--x;
--w;
--iprint;
/* Function Body */
/* INITIALIZE */
/* ---------- */
/*< IF(IFLAG.EQ.0) GO TO 10 >*/
if (*iflag == 0) {
goto L10;
}
/*< GO TO (172,100) IFLAG >*/
switch (*iflag) {
case 1: goto L172;
case 2: goto L100;
}
/*< 10 ITER= 0 >*/
L10:
iter = 0;
/*< IF(N.LE.0.OR.M.LE.0) GO TO 196 >*/
if (*n <= 0 || *m <= 0) {
goto L196;
}
/*< IF(GTOL.LE.1.D-04) THEN >*/
if (lb3_1.gtol <= 1e-4) {
/*< IF(LP.GT.0) WRITE(LP,245) >*/
/*
245 FORMAT(/' GTOL IS LESS THAN OR EQUAL TO 1.D-04',
. / ' IT HAS BEEN RESET TO 9.D-01')
*/
if (lb3_1.lp > 0) {
printf(" GTOL IS LESS THAN OR EQUAL TO 1.D-04");
printf(" IT HAS BEEN RESET TO 9.D-01");
}
/*< GTOL=9.D-01 >*/
lb3_1.gtol = .9;
/*< ENDIF >*/
}
/*< NFUN= 1 >*/
nfun = 1;
/*< POINT= 0 >*/
point = 0;
/*< FINISH= .FALSE. >*/
finish = FALSE_;
/*< IF(DIAGCO) THEN >*/
if (*diagco) {
/*< DO 30 I=1,N >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< 30 IF (DIAG(I).LE.ZERO) GO TO 195 >*/
/* L30: */
if (diag[i__] <= zero) {
goto L195;
}
}
/*< ELSE >*/
} else {
/*< DO 40 I=1,N >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< 40 DIAG(I)= 1.0D0 >*/
/* L40: */
diag[i__] = 1.;
}
/*< ENDIF >*/
}
/* THE WORK VECTOR W IS DIVIDED AS FOLLOWS: */
/* --------------------------------------- */
/* THE FIRST N LOCATIONS ARE USED TO STORE THE GRADIENT AND */
/* OTHER TEMPORARY INFORMATION. */
/* LOCATIONS (N+1)...(N+M) STORE THE SCALARS RHO. */
/* LOCATIONS (N+M+1)...(N+2M) STORE THE NUMBERS ALPHA USED */
/* IN THE FORMULA THAT COMPUTES H*G. */
/* LOCATIONS (N+2M+1)...(N+2M+NM) STORE THE LAST M SEARCH */
/* STEPS. */
/* LOCATIONS (N+2M+NM+1)...(N+2M+2NM) STORE THE LAST M */
/* GRADIENT DIFFERENCES. */
/* THE SEARCH STEPS AND GRADIENT DIFFERENCES ARE STORED IN A */
/* CIRCULAR ORDER CONTROLLED BY THE PARAMETER POINT. */
/*< ISPT= N+2*M >*/
ispt = *n + (*m << 1);
/*< IYPT= ISPT+N*M >*/
iypt = ispt + *n * *m;
/*< DO 50 I=1,N >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< 50 W(ISPT+I)= -G(I)*DIAG(I) >*/
/* L50: */
w[ispt + i__] = -g[i__] * diag[i__];
}
/*< GNORM= DSQRT(DDOT(N,G,1,G,1)) >*/
gnorm = sqrt(ddot_(n, &g[1], &c__1, &g[1], &c__1));
/*< STP1= ONE/GNORM >*/
stp1 = one / gnorm;
/* PARAMETERS FOR LINE SEARCH ROUTINE */
/*< FTOL= 1.0D-4 >*/
ftol = 1e-4;
/*< MAXFEV= 20 >*/
maxfev = 20;
/*< >*/
if (iprint[1] >= 0) {
lb1_(&iprint[1], n, m, &x[1], f, &g[1], v3p_netlib_lbfgs_global_arg);
}
/* -------------------- */
/* MAIN ITERATION LOOP */
/* -------------------- */
/*< 80 ITER= ITER+1 >*/
L80:
++iter;
/*< INFO=0 >*/
info = 0;
/*< BOUND=ITER-1 >*/
bound = iter - 1;
/*< IF(ITER.EQ.1) GO TO 165 >*/
if (iter == 1) {
goto L165;
}
/*< IF (ITER .GT. M)BOUND=M >*/
if (iter > *m) {
bound = *m;
}
/*< YS= DDOT(N,W(IYPT+NPT+1),1,W(ISPT+NPT+1),1) >*/
ys = ddot_(n, &w[iypt + npt + 1], &c__1, &w[ispt + npt + 1], &c__1);
/*< IF(.NOT.DIAGCO) THEN >*/
if (! (*diagco)) {
/*< YY= DDOT(N,W(IYPT+NPT+1),1,W(IYPT+NPT+1),1) >*/
yy = ddot_(n, &w[iypt + npt + 1], &c__1, &w[iypt + npt + 1], &c__1);
/*< DO 90 I=1,N >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< 90 DIAG(I)= YS/YY >*/
/* L90: */
diag[i__] = ys / yy;
}
/*< ELSE >*/
} else {
/*< IFLAG=2 >*/
*iflag = 2;
/*< RETURN >*/
return 0;
/*< ENDIF >*/
}
/*< 100 CONTINUE >*/
L100:
/*< IF(DIAGCO) THEN >*/
if (*diagco) {
/*< DO 110 I=1,N >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< 110 IF (DIAG(I).LE.ZERO) GO TO 195 >*/
/* L110: */
if (diag[i__] <= zero) {
goto L195;
}
}
/*< ENDIF >*/
}
/* COMPUTE -H*G USING THE FORMULA GIVEN IN: <NAME>. 1980, */
/* "Updating quasi-Newton matrices with limited storage", */
/* Mathematics of Computation, Vol.24, No.151, pp. 773-782. */
/* --------------------------------------------------------- */
/*< CP= POINT >*/
cp = point;
/*< IF (POINT.EQ.0) CP=M >*/
if (point == 0) {
cp = *m;
}
/*< W(N+CP)= ONE/YS >*/
w[*n + cp] = one / ys;
/*< DO 112 I=1,N >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< 112 W(I)= -G(I) >*/
/* L112: */
w[i__] = -g[i__];
}
/*< CP= POINT >*/
cp = point;
/*< DO 125 I= 1,BOUND >*/
i__1 = bound;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< CP=CP-1 >*/
--cp;
/*< IF (CP.EQ. -1)CP=M-1 >*/
if (cp == -1) {
cp = *m - 1;
}
/*< SQ= DDOT(N,W(ISPT+CP*N+1),1,W,1) >*/
sq = ddot_(n, &w[ispt + cp * *n + 1], &c__1, &w[1], &c__1);
/*< INMC=N+M+CP+1 >*/
inmc = *n + *m + cp + 1;
/*< IYCN=IYPT+CP*N >*/
iycn = iypt + cp * *n;
/*< W(INMC)= W(N+CP+1)*SQ >*/
w[inmc] = w[*n + cp + 1] * sq;
/*< CALL DAXPY(N,-W(INMC),W(IYCN+1),1,W,1) >*/
d__1 = -w[inmc];
daxpy_(n, &d__1, &w[iycn + 1], &c__1, &w[1], &c__1);
/*< 125 CONTINUE >*/
/* L125: */
}
/*< DO 130 I=1,N >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< 130 W(I)=DIAG(I)*W(I) >*/
/* L130: */
w[i__] = diag[i__] * w[i__];
}
/*< DO 145 I=1,BOUND >*/
i__1 = bound;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< YR= DDOT(N,W(IYPT+CP*N+1),1,W,1) >*/
yr = ddot_(n, &w[iypt + cp * *n + 1], &c__1, &w[1], &c__1);
/*< BETA= W(N+CP+1)*YR >*/
beta = w[*n + cp + 1] * yr;
/*< INMC=N+M+CP+1 >*/
inmc = *n + *m + cp + 1;
/*< BETA= W(INMC)-BETA >*/
beta = w[inmc] - beta;
/*< ISCN=ISPT+CP*N >*/
iscn = ispt + cp * *n;
/*< CALL DAXPY(N,BETA,W(ISCN+1),1,W,1) >*/
daxpy_(n, &beta, &w[iscn + 1], &c__1, &w[1], &c__1);
/*< CP=CP+1 >*/
++cp;
/*< IF (CP.EQ.M)CP=0 >*/
if (cp == *m) {
cp = 0;
}
/*< 145 CONTINUE >*/
/* L145: */
}
/* STORE THE NEW SEARCH DIRECTION */
/* ------------------------------ */
/*< DO 160 I=1,N >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< 160 W(ISPT+POINT*N+I)= W(I) >*/
/* L160: */
w[ispt + point * *n + i__] = w[i__];
}
/* OBTAIN THE ONE-DIMENSIONAL MINIMIZER OF THE FUNCTION */
/* BY USING THE LINE SEARCH ROUTINE MCSRCH */
/* ---------------------------------------------------- */
/*< 165 NFEV=0 >*/
L165:
nfev = 0;
/*< STP=ONE >*/
/* awf changed initial step from ONE to be parametrized. */
stp = lb3_1.stpinit;
/*< IF (ITER.EQ.1) STP=STP1 >*/
if (iter == 1) {
stp = stp1;
}
/*< DO 170 I=1,N >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< 170 W(I)=G(I) >*/
/* L170: */
w[i__] = g[i__];
}
/*< 172 CONTINUE >*/
L172:
/*< >*/
mcsrch_(n, &x[1], f, &g[1], &w[ispt + point * *n + 1], xtol,
&diag[1], v3p_netlib_lbfgs_global_arg);
/*< IF (INFO .EQ. -1) THEN >*/
if (info == -1) {
/*< IFLAG=1 >*/
*iflag = 1;
/*< RETURN >*/
return 0;
/*< ENDIF >*/
}
/*< IF (INFO .NE. 1) GO TO 190 >*/
if (info != 1) {
goto L190;
}
/*< NFUN= NFUN + NFEV >*/
nfun += nfev;
/* COMPUTE THE NEW STEP AND GRADIENT CHANGE */
/* ----------------------------------------- */
/*< NPT=POINT*N >*/
npt = point * *n;
/*< DO 175 I=1,N >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< W(ISPT+NPT+I)= STP*W(ISPT+NPT+I) >*/
w[ispt + npt + i__] = stp * w[ispt + npt + i__];
/*< 175 W(IYPT+NPT+I)= G(I)-W(I) >*/
/* L175: */
w[iypt + npt + i__] = g[i__] - w[i__];
}
/*< POINT=POINT+1 >*/
++point;
/*< IF (POINT.EQ.M)POINT=0 >*/
if (point == *m) {
point = 0;
}
/* TERMINATION TEST */
/* ---------------- */
/*< GNORM= DSQRT(DDOT(N,G,1,G,1)) >*/
gnorm = sqrt(ddot_(n, &g[1], &c__1, &g[1], &c__1));
/*< XNORM= DSQRT(DDOT(N,X,1,X,1)) >*/
xnorm = sqrt(ddot_(n, &x[1], &c__1, &x[1], &c__1));
/*< XNORM= DMAX1(1.0D0,XNORM) >*/
xnorm = max(1.,xnorm);
/*< IF (GNORM/XNORM .LE. EPS) FINISH=.TRUE. >*/
if (gnorm / xnorm <= *eps) {
finish = TRUE_;
}
/*< >*/
if (iprint[1] >= 0) {
lb1_(&iprint[1], n, m, &x[1], f, &g[1], v3p_netlib_lbfgs_global_arg);
}
/*< IF (FINISH) THEN >*/
if (finish) {
/*< IFLAG=0 >*/
*iflag = 0;
/*< RETURN >*/
return 0;
/*< ENDIF >*/
}
/*< GO TO 80 >*/
goto L80;
/* ------------------------------------------------------------ */
/* END OF MAIN ITERATION LOOP. ERROR EXITS. */
/* ------------------------------------------------------------ */
/*< 190 IFLAG=-1 >*/
L190:
*iflag = -1;
/*< IF(LP.GT.0) WRITE(LP,200) INFO >*/
/*
200 FORMAT(/' IFLAG= -1 ',/' LINE SEARCH FAILED. SEE'
. ' DOCUMENTATION OF ROUTINE MCSRCH',/' ERROR RETURN'
. ' OF LINE SEARCH: INFO= ',I2,/
. ' POSSIBLE CAUSES: FUNCTION OR GRADIENT ARE INCORRECT',/,
. ' OR INCORRECT TOLERANCES')
*/
if (lb3_1.lp > 0) {
printf(" IFLAG= -1 LINE SEARCH FAILED. SEE"
" DOCUMENTATION OF ROUTINE MCSRCH ERROR RETURN"
" OF LINE SEARCH: INFO= %ld"
" POSSIBLE CAUSES: FUNCTION OR GRADIENT ARE INCORRECT"
" OR INCORRECT TOLERANCES", info);
}
/*< RETURN >*/
return 0;
/*< 195 IFLAG=-2 >*/
L195:
*iflag = -2;
/*< IF(LP.GT.0) WRITE(LP,235) I >*/
/*
235 FORMAT(/' IFLAG= -2',/' THE',I5,'-TH DIAGONAL ELEMENT OF THE',/,
. ' INVERSE HESSIAN APPROXIMATION IS NOT POSITIVE')
*/
if (lb3_1.lp > 0) {
printf("IFLAG= -2 THE %ld-TH DIAGONAL ELEMENT OF THE"
" INVERSE HESSIAN APPROXIMATION IS NOT POSITIVE", i__);
}
/*< RETURN >*/
return 0;
/*< 196 IFLAG= -3 >*/
L196:
*iflag = -3;
/*< IF(LP.GT.0) WRITE(LP,240) >*/
/*
240 FORMAT(/' IFLAG= -3',/' IMPROPER INPUT PARAMETERS (N OR M',
. ' ARE NOT POSITIVE)')
*/
if (lb3_1.lp > 0) {
printf(" IFLAG= -3 IMPROPER INPUT PARAMETERS (N OR M"
" ARE NOT POSITIVE)");
}
/* FORMATS */
/* ------- */
/*< 2 >*/
/*< 2 >*/
/*< 2 >*/
/*< 2 >*/
/*< RETURN >*/
return 0;
/*< END >*/
} /* lbfgs_ */
/* LAST LINE OF SUBROUTINE LBFGS */
static void write50(double* v, int n)
{
int cols = 15;
double vmax = 0;
int i;
double vmaxscale;
for (i = 0; i < n; ++i)
if (fabs(v[i]) > vmax)
vmax = v[i];
vmaxscale = log(fabs(vmax)) / log(10.0);
vmaxscale = pow(10.0, ceil(vmaxscale) - 1);
if (vmaxscale != 1.0)
printf(" %e x\n", vmaxscale);
for (i = 0; i < n; ++i) {
if (i > 0 && i%cols == 0)
printf("\n");
printf(" %10.5f", v[i] / vmaxscale);
}
printf("\n");
}
/*< >*/
/* Subroutine */ int lb1_(
integer *iprint, integer *n, integer *m, doublereal *x, doublereal *f,
doublereal *g, v3p_netlib_lbfgs_global_t* v3p_netlib_lbfgs_global_arg
)
{
/* ------------------------------------------------------------- */
/* THIS ROUTINE PRINTS MONITORING INFORMATION. THE FREQUENCY AND */
/* AMOUNT OF OUTPUT ARE CONTROLLED BY IPRINT. */
/* ------------------------------------------------------------- */
/*< INTEGER IPRINT(2),ITER,NFUN,LP,MP,N,M >*/
/*< DOUBLE PRECISION X(N),G(N),F,GNORM,STP,GTOL,STPMIN,STPMAX >*/
/*< LOGICAL FINISH >*/
/*< COMMON /LB3/MP,LP,GTOL,STPMIN,STPMAX >*/
/*< IF (ITER.EQ.0)THEN >*/
/* Parameter adjustments */
--iprint;
--g;
--x;
/* Function Body */
if (iter == 0) {
/*< WRITE(MP,10) >*/
/*
10 FORMAT('*************************************************')
*/
printf("*************************************************\n");
/*< WRITE(MP,20) N,M >*/
/*
20 FORMAT(' N=',I5,' NUMBER OF CORRECTIONS=',I2,
. /, ' INITIAL VALUES')
*/
printf(" N=%ld NUMBER OF CORRECTIONS=%ld"
" INITIAL VALUES", *n, *m);
/*< WRITE(MP,30)F,GNORM >*/
/*
30 FORMAT(' F= ',1PD10.3,' GNORM= ',1PD10.3)
*/
printf(" F= %g GNORM= %g\n", *f, gnorm);
/*< IF (IPRINT(2).GE.1)THEN >*/
if (iprint[2] >= 1) {
/*< WRITE(MP,40) >*/
/*
40 FORMAT(' VECTOR X= ')
*/
printf(" VECTOR X= ");
/*< WRITE(MP,50) (X(I),I=1,N) >*/
/*
50 FORMAT(6(2X,1PD10.3))
*/
write50(x, *n);
/*< WRITE(MP,60) >*/
/*
60 FORMAT(' GRADIENT VECTOR G= ')
*/
printf(" GRADIENT VECTOR G= ");
/*< WRITE(MP,50) (G(I),I=1,N) >*/
/*
50 FORMAT(6(2X,1PD10.3))
*/
write50(g, *n);
/*< ENDIF >*/
}
/*< WRITE(MP,10) >*/
/*
10 FORMAT('*************************************************')
*/
printf("*************************************************\n");
/*< WRITE(MP,70) >*/
/*
70 FORMAT(/' I NFN',4X,'FUNC',8X,'GNORM',7X,'STEPLENGTH'/)
*/
printf(" I NFN FUNC GNORM STEPLENGTH\n");
/*< ELSE >*/
} else {
/*< IF ((IPRINT(1).EQ.0).AND.(ITER.NE.1.AND..NOT.FINISH))RETURN >*/
if (iprint[1] == 0 && (iter != 1 && ! (finish))) {
return 0;
}
/*< IF (IPRINT(1).NE.0)THEN >*/
if (iprint[1] != 0) {
/*< IF(MOD(ITER-1,IPRINT(1)).EQ.0.OR.FINISH)THEN >*/
if ((iter - 1) % iprint[1] == 0 || finish) {
/*< IF(IPRINT(2).GT.1.AND.ITER.GT.1) WRITE(MP,70) >*/
/*
70 FORMAT(/' I NFN',4X,'FUNC',8X,'GNORM',7X,'STEPLENGTH'/)
*/
if (iprint[2] > 1 && iter > 1) {
printf(" I NFN FUNC GNORM STEPLENGTH\n");
}
/*< WRITE(MP,80)ITER,NFUN,F,GNORM,STP >*/
/*
80 FORMAT(2(I4,1X),3X,3(1PD10.3,2X))
*/
printf("%4ld %4ld %10.3f %10.3f %10.3f\n", iter, nfun, *f, gnorm, stp);
/*< ELSE >*/
} else {
/*< RETURN >*/
return 0;
/*< ENDIF >*/
}
/*< ELSE >*/
} else {
/*< IF( IPRINT(2).GT.1.AND.FINISH) WRITE(MP,70) >*/
/*
70 FORMAT(/' I NFN',4X,'FUNC',8X,'GNORM',7X,'STEPLENGTH'/)
*/
if (iprint[2] > 1 && finish) {
printf(" I NFN FUNC GNORM STEPLENGTH\n");
}
/*< WRITE(MP,80)ITER,NFUN,F,GNORM,STP >*/
/*
80 FORMAT(2(I4,1X),3X,3(1PD10.3,2X))
*/
printf("%4ld %4ld %10.3f %10.3f %10.3f\n", iter, nfun, *f, gnorm, stp);
/*< ENDIF >*/
}
/*< IF (IPRINT(2).EQ.2.OR.IPRINT(2).EQ.3)THEN >*/
if (iprint[2] == 2 || iprint[2] == 3) {
/*< IF (FINISH)THEN >*/
if (finish) {
/*< WRITE(MP,90) >*/
/*
90 FORMAT(' FINAL POINT X= ')
*/
printf(" FINAL POINT X= ");
/*< ELSE >*/
} else {
/*< WRITE(MP,40) >*/
/*
40 FORMAT(' VECTOR X= ')
*/
printf(" VECTOR X= ");
/*< ENDIF >*/
}
/*< WRITE(MP,50)(X(I),I=1,N) >*/
/*
50 FORMAT(6(2X,1PD10.3))
*/
write50(x, *n);
/*< IF (IPRINT(2).EQ.3)THEN >*/
if (iprint[2] == 3) {
/*< WRITE(MP,60) >*/
/*
60 FORMAT(' GRADIENT VECTOR G= ')
*/
printf(" GRADIENT VECTOR G= ");
/*< WRITE(MP,50)(G(I),I=1,N) >*/
/*
50 FORMAT(6(2X,1PD10.3))
*/
write50(g, *n);
/*< ENDIF >*/
}
/*< ENDIF >*/
}
/*< IF (FINISH) WRITE(MP,100) >*/
/*
100 FORMAT(/' THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS.',
. /' IFLAG = 0')
*/
if (finish) {
printf(" THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS.\n");
}
/*< ENDIF >*/
}
/*< 10 FORMAT('*************************************************') >*/
/*< 2 >*/
/*< 30 FORMAT(' F= ',1PD10.3,' GNORM= ',1PD10.3) >*/
/*< 40 FORMAT(' VECTOR X= ') >*/
/*< 50 FORMAT(6(2X,1PD10.3)) >*/
/*< 60 FORMAT(' GRADIENT VECTOR G= ') >*/
/*< 70 FORMAT(/' I NFN',4X,'FUNC',8X,'GNORM',7X,'STEPLENGTH'/) >*/
/*< 80 FORMAT(2(I4,1X),3X,3(1PD10.3,2X)) >*/
/*< 90 FORMAT(' FINAL POINT X= ') >*/
/*< 1 >*/
/*< RETURN >*/
return 0;
/*< END >*/
} /* lb1_ */
/* ****** */
/* ---------------------------------------------------------- */
/* DATA */
/* ---------------------------------------------------------- */
/*< INTEGER LP,MP >*/
/*< DOUBLE PRECISION GTOL,STPMIN,STPMAX >*/
/*< COMMON /LB3/MP,LP,GTOL,STPMIN,STPMAX >*/
/*< DATA MP,LP,GTOL,STPMIN,STPMAX/6,6,9.0D-01,1.0D-20,1.0D+20/ >*/
/*< END >*/
/* ------------------------------------------------------------------ */
/* ************************** */
/* LINE SEARCH ROUTINE MCSRCH */
/* ************************** */
/*< SUBROUTINE MCSRCH(N,X,F,G,S,STP,FTOL,XTOL,MAXFEV,INFO,NFEV,WA) >*/
/* Subroutine */ int mcsrch_(
integer *n, doublereal *x, doublereal *f,
doublereal *g, doublereal *s,
doublereal *xtol, doublereal *wa,
v3p_netlib_lbfgs_global_t* v3p_netlib_lbfgs_global_arg
)
{
/* Initialized data */
static doublereal p5 = .5; /* constant */
static doublereal p66 = .66; /* constant */
static doublereal xtrapf = 4.; /* constant */
static doublereal zero = 0.; /* constant */
/* System generated locals */
integer i__1;
doublereal d__1;
/* Local variables */
integer j;
extern /* Subroutine */ int mcstep_(
doublereal *, doublereal *, doublereal *, doublereal *,
doublereal *, doublereal *, v3p_netlib_lbfgs_global_t*);
/*< INTEGER N,MAXFEV,INFO,NFEV >*/
/*< DOUBLE PRECISION F,STP,FTOL,GTOL,XTOL,STPMIN,STPMAX >*/
/*< DOUBLE PRECISION X(N),G(N),S(N),WA(N) >*/
/*< COMMON /LB3/MP,LP,GTOL,STPMIN,STPMAX >*/
/*< SAVE >*/
/* SUBROUTINE MCSRCH */
/* A slight modification of the subroutine CSRCH of More' and Thuente. */
/* The changes are to allow reverse communication, and do not affect */
/* the performance of the routine. */
/* THE PURPOSE OF MCSRCH IS TO FIND A STEP WHICH SATISFIES */
/* A SUFFICIENT DECREASE CONDITION AND A CURVATURE CONDITION. */
/* AT EACH STAGE THE SUBROUTINE UPDATES AN INTERVAL OF */
/* UNCERTAINTY WITH ENDPOINTS STX AND STY. THE INTERVAL OF */
/* UNCERTAINTY IS INITIALLY CHOSEN SO THAT IT CONTAINS A */
/* MINIMIZER OF THE MODIFIED FUNCTION */
/* F(X+STP*S) - F(X) - FTOL*STP*(GRADF(X)'S). */
/* IF A STEP IS OBTAINED FOR WHICH THE MODIFIED FUNCTION */
/* HAS A NONPOSITIVE FUNCTION VALUE AND NONNEGATIVE DERIVATIVE, */
/* THEN THE INTERVAL OF UNCERTAINTY IS CHOSEN SO THAT IT */
/* CONTAINS A MINIMIZER OF F(X+STP*S). */
/* THE ALGORITHM IS DESIGNED TO FIND A STEP WHICH SATISFIES */
/* THE SUFFICIENT DECREASE CONDITION */
/* F(X+STP*S) .LE. F(X) + FTOL*STP*(GRADF(X)'S), */
/* AND THE CURVATURE CONDITION */
/* ABS(GRADF(X+STP*S)'S)) .LE. GTOL*ABS(GRADF(X)'S). */
/* IF FTOL IS LESS THAN GTOL AND IF, FOR EXAMPLE, THE FUNCTION */
/* IS BOUNDED BELOW, THEN THERE IS ALWAYS A STEP WHICH SATISFIES */
/* BOTH CONDITIONS. IF NO STEP CAN BE FOUND WHICH SATISFIES BOTH */
/* CONDITIONS, THEN THE ALGORITHM USUALLY STOPS WHEN ROUNDING */
/* ERRORS PREVENT FURTHER PROGRESS. IN THIS CASE STP ONLY */
/* SATISFIES THE SUFFICIENT DECREASE CONDITION. */
/* THE SUBROUTINE STATEMENT IS */
/* SUBROUTINE MCSRCH(N,X,F,G,S,STP,FTOL,XTOL, MAXFEV,INFO,NFEV,WA) */
/* WHERE */
/* N IS A POSITIVE INTEGER INPUT VARIABLE SET TO THE NUMBER */
/* OF VARIABLES. */
/* X IS AN ARRAY OF LENGTH N. ON INPUT IT MUST CONTAIN THE */
/* BASE POINT FOR THE LINE SEARCH. ON OUTPUT IT CONTAINS */
/* X + STP*S. */
/* F IS A VARIABLE. ON INPUT IT MUST CONTAIN THE VALUE OF F */
/* AT X. ON OUTPUT IT CONTAINS THE VALUE OF F AT X + STP*S. */
/* G IS AN ARRAY OF LENGTH N. ON INPUT IT MUST CONTAIN THE */
/* GRADIENT OF F AT X. ON OUTPUT IT CONTAINS THE GRADIENT */
/* OF F AT X + STP*S. */
/* S IS AN INPUT ARRAY OF LENGTH N WHICH SPECIFIES THE */
/* SEARCH DIRECTION. */
/* STP IS A NONNEGATIVE VARIABLE. ON INPUT STP CONTAINS AN */
/* INITIAL ESTIMATE OF A SATISFACTORY STEP. ON OUTPUT */
/* STP CONTAINS THE FINAL ESTIMATE. */
/* FTOL AND GTOL ARE NONNEGATIVE INPUT VARIABLES. (In this reverse */
/* communication implementation GTOL is defined in a COMMON */
/* statement.) TERMINATION OCCURS WHEN THE SUFFICIENT DECREASE */
/* CONDITION AND THE DIRECTIONAL DERIVATIVE CONDITION ARE */
/* SATISFIED. */
/* XTOL IS A NONNEGATIVE INPUT VARIABLE. TERMINATION OCCURS */
/* WHEN THE RELATIVE WIDTH OF THE INTERVAL OF UNCERTAINTY */
/* IS AT MOST XTOL. */
/* STPMIN AND STPMAX ARE NONNEGATIVE INPUT VARIABLES WHICH */
/* SPECIFY LOWER AND UPPER BOUNDS FOR THE STEP. (In this reverse */
/* communication implementatin they are defined in a COMMON */
/* statement). */
/* MAXFEV IS A POSITIVE INTEGER INPUT VARIABLE. TERMINATION */
/* OCCURS WHEN THE NUMBER OF CALLS TO FCN IS AT LEAST */
/* MAXFEV BY THE END OF AN ITERATION. */
/* INFO IS AN INTEGER OUTPUT VARIABLE SET AS FOLLOWS: */
/* INFO = 0 IMPROPER INPUT PARAMETERS. */
/* INFO =-1 A RETURN IS MADE TO COMPUTE THE FUNCTION AND GRADIENT. */
/* INFO = 1 THE SUFFICIENT DECREASE CONDITION AND THE */
/* DIRECTIONAL DERIVATIVE CONDITION HOLD. */
/* INFO = 2 RELATIVE WIDTH OF THE INTERVAL OF UNCERTAINTY */
/* IS AT MOST XTOL. */
/* INFO = 3 NUMBER OF CALLS TO FCN HAS REACHED MAXFEV. */
/* INFO = 4 THE STEP IS AT THE LOWER BOUND STPMIN. */
/* INFO = 5 THE STEP IS AT THE UPPER BOUND STPMAX. */
/* INFO = 6 ROUNDING ERRORS PREVENT FURTHER PROGRESS. */
/* THERE MAY NOT BE A STEP WHICH SATISFIES THE */
/* SUFFICIENT DECREASE AND CURVATURE CONDITIONS. */
/* TOLERANCES MAY BE TOO SMALL. */
/* NFEV IS AN INTEGER OUTPUT VARIABLE SET TO THE NUMBER OF */
/* CALLS TO FCN. */
/* WA IS A WORK ARRAY OF LENGTH N. */
/* SUBPROGRAMS CALLED */
/* MCSTEP */
/* FORTRAN-SUPPLIED...ABS,MAX,MIN */
/* ARGONNE NATIONAL LABORATORY. MINPACK PROJECT. JUNE 1983 */
/* <NAME>', <NAME> */
/* ********** */
/*< INTEGER INFOC,J >*/
/*< LOGICAL BRACKT,STAGE1 >*/
/*< >*/
/*< DATA P5,P66,XTRAPF,ZERO /0.5D0,0.66D0,4.0D0,0.0D0/ >*/
/* Parameter adjustments */
--wa;
--s;
--g;
--x;
/* Function Body */
/*< IF(INFO.EQ.-1) GO TO 45 >*/
if (info == -1) {
goto L45;
}
/*< INFOC = 1 >*/
infoc = 1;
/* CHECK THE INPUT PARAMETERS FOR ERRORS. */
/*< >*/ if (*n <= 0 || stp <= zero || ftol < zero || lb3_1.gtol < zero || *xtol
< zero || lb3_1.stpmin < zero || lb3_1.stpmax < lb3_1.stpmin ||
maxfev <= 0) {
return 0;
}
/* COMPUTE THE INITIAL GRADIENT IN THE SEARCH DIRECTION */
/* AND CHECK THAT S IS A DESCENT DIRECTION. */
/*< DGINIT = ZERO >*/
dginit = zero;
/*< DO 10 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< DGINIT = DGINIT + G(J)*S(J) >*/
dginit += g[j] * s[j];
/*< 10 CONTINUE >*/
/* L10: */
}
/*< IF (DGINIT .GE. ZERO) then >*/
if (dginit >= zero) {
/*< write(LP,15) >*/
printf(" THE SEARCH DIRECTION IS NOT A DESCENT DIRECTION\n");
/*< 15 FORMAT(/' THE SEARCH DIRECTION IS NOT A DESCENT DIRECTION') >*/
/*< RETURN >*/
return 0;
/*< ENDIF >*/
}
/* INITIALIZE LOCAL VARIABLES. */
/*< BRACKT = .FALSE. >*/
brackt = FALSE_;
/*< STAGE1 = .TRUE. >*/
stage1 = TRUE_;
/*< NFEV = 0 >*/
nfev = 0;
/*< FINIT = F >*/
finit = *f;
/*< DGTEST = FTOL*DGINIT >*/
dgtest = ftol * dginit;
/*< WIDTH = STPMAX - STPMIN >*/
width = lb3_1.stpmax - lb3_1.stpmin;
/*< WIDTH1 = WIDTH/P5 >*/
width1 = width / p5;
/*< DO 20 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< WA(J) = X(J) >*/
wa[j] = x[j];
/*< 20 CONTINUE >*/
/* L20: */
}
/* THE VARIABLES STX, FX, DGX CONTAIN THE VALUES OF THE STEP, */
/* FUNCTION, AND DIRECTIONAL DERIVATIVE AT THE BEST STEP. */
/* THE VARIABLES STY, FY, DGY CONTAIN THE VALUE OF THE STEP, */
/* FUNCTION, AND DERIVATIVE AT THE OTHER ENDPOINT OF */
/* THE INTERVAL OF UNCERTAINTY. */
/* THE VARIABLES STP, F, DG CONTAIN THE VALUES OF THE STEP, */
/* FUNCTION, AND DERIVATIVE AT THE CURRENT STEP. */
/*< STX = ZERO >*/
stx = zero;
/*< FX = FINIT >*/
fx = finit;
/*< DGX = DGINIT >*/
dgx = dginit;
/*< STY = ZERO >*/
sty = zero;
/*< FY = FINIT >*/
fy = finit;
/*< DGY = DGINIT >*/
dgy = dginit;
/* START OF ITERATION. */
/*< 30 CONTINUE >*/
L30:
/* SET THE MINIMUM AND MAXIMUM STEPS TO CORRESPOND */
/* TO THE PRESENT INTERVAL OF UNCERTAINTY. */
/*< IF (BRACKT) THEN >*/
if (brackt) {
/*< STMIN = MIN(STX,STY) >*/
stmin = min(stx,sty);
/*< STMAX = MAX(STX,STY) >*/
stmax = max(stx,sty);
/*< ELSE >*/
} else {
/*< STMIN = STX >*/
stmin = stx;
/*< STMAX = STP + XTRAPF*(STP - STX) >*/
stmax = stp + xtrapf * (stp - stx);
/*< END IF >*/
}
/* FORCE THE STEP TO BE WITHIN THE BOUNDS STPMAX AND STPMIN. */
/*< STP = MAX(STP,STPMIN) >*/
stp = max(stp,lb3_1.stpmin);
/*< STP = MIN(STP,STPMAX) >*/
stp = min(stp,lb3_1.stpmax);
/* IF AN UNUSUAL TERMINATION IS TO OCCUR THEN LET */
/* STP BE THE LOWEST POINT OBTAINED SO FAR. */
/*< >*/
if ((brackt && (stp <= stmin || stp >= stmax)) || nfev >= maxfev - 1 ||
infoc == 0 || (brackt && stmax - stmin <= *xtol * stmax)) {
stp = stx;
}
/* EVALUATE THE FUNCTION AND GRADIENT AT STP */
/* AND COMPUTE THE DIRECTIONAL DERIVATIVE. */
/* We return to main program to obtain F and G. */
/*< DO 40 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< X(J) = WA(J) + STP*S(J) >*/
x[j] = wa[j] + stp * s[j];
/*< 40 CONTINUE >*/
/* L40: */
}
/*< INFO=-1 >*/
info = -1;
/*< RETURN >*/
return 0;
/*< 45 INFO=0 >*/
L45:
info = 0;
/*< NFEV = NFEV + 1 >*/
++(nfev);
/*< DG = ZERO >*/
dg = zero;
/*< DO 50 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< DG = DG + G(J)*S(J) >*/
dg += g[j] * s[j];
/*< 50 CONTINUE >*/
/* L50: */
}
/*< FTEST1 = FINIT + STP*DGTEST >*/
ftest1 = finit + stp * dgtest;
/* TEST FOR CONVERGENCE. */
/*< >*/
if ((brackt && (stp <= stmin || stp >= stmax)) || infoc == 0) {
info = 6;
}
/*< >*/
if (stp == lb3_1.stpmax && *f <= ftest1 && dg <= dgtest) {
info = 5;
}
/*< >*/
if (stp == lb3_1.stpmin && (*f > ftest1 || dg >= dgtest)) {
info = 4;
}
/*< IF (NFEV .GE. MAXFEV) INFO = 3 >*/
if (nfev >= maxfev) {
info = 3;
}
/*< IF (BRACKT .AND. STMAX-STMIN .LE. XTOL*STMAX) INFO = 2 >*/
if (brackt && stmax - stmin <= *xtol * stmax) {
info = 2;
}
/*< IF (F .LE. FTEST1 .AND. ABS(DG) .LE. GTOL*(-DGINIT)) INFO = 1 >*/
if (*f <= ftest1 && abs(dg) <= lb3_1.gtol * (-dginit)) {
info = 1;
}
/* CHECK FOR TERMINATION. */
/*< IF (INFO .NE. 0) RETURN >*/
if (info != 0) {
return 0;
}
/* IN THE FIRST STAGE WE SEEK A STEP FOR WHICH THE MODIFIED */
/* FUNCTION HAS A NONPOSITIVE VALUE AND NONNEGATIVE DERIVATIVE. */
/*< >*/
if (stage1 && *f <= ftest1 && dg >= min(ftol,lb3_1.gtol) * dginit) {
stage1 = FALSE_;
}
/* A MODIFIED FUNCTION IS USED TO PREDICT THE STEP ONLY IF */
/* WE HAVE NOT OBTAINED A STEP FOR WHICH THE MODIFIED */
/* FUNCTION HAS A NONPOSITIVE FUNCTION VALUE AND NONNEGATIVE */
/* DERIVATIVE, AND IF A LOWER FUNCTION VALUE HAS BEEN */
/* OBTAINED BUT THE DECREASE IS NOT SUFFICIENT. */
/*< IF (STAGE1 .AND. F .LE. FX .AND. F .GT. FTEST1) THEN >*/
if (stage1 && *f <= fx && *f > ftest1) {
/* DEFINE THE MODIFIED FUNCTION AND DERIVATIVE VALUES. */
/*< FM = F - STP*DGTEST >*/
fm = *f - stp * dgtest;
/*< FXM = FX - STX*DGTEST >*/
fxm = fx - stx * dgtest;
/*< FYM = FY - STY*DGTEST >*/
fym = fy - sty * dgtest;
/*< DGM = DG - DGTEST >*/
dgm = dg - dgtest;
/*< DGXM = DGX - DGTEST >*/
dgxm = dgx - dgtest;
/*< DGYM = DGY - DGTEST >*/
dgym = dgy - dgtest;
/* CALL CSTEP TO UPDATE THE INTERVAL OF UNCERTAINTY */
/* AND TO COMPUTE THE NEW STEP. */
/*< >*/
mcstep_(&dgxm, &dgym, &fm, &dgm, &stmin, &stmax,
v3p_netlib_lbfgs_global_arg);
/* RESET THE FUNCTION AND GRADIENT VALUES FOR F. */
/*< FX = FXM + STX*DGTEST >*/
fx = fxm + stx * dgtest;
/*< FY = FYM + STY*DGTEST >*/
fy = fym + sty * dgtest;
/*< DGX = DGXM + DGTEST >*/
dgx = dgxm + dgtest;
/*< DGY = DGYM + DGTEST >*/
dgy = dgym + dgtest;
/*< ELSE >*/
} else {
/* CALL MCSTEP TO UPDATE THE INTERVAL OF UNCERTAINTY */
/* AND TO COMPUTE THE NEW STEP. */
/*< >*/
mcstep_(&dgx, &dgy, f, &dg, &stmin, &stmax,
v3p_netlib_lbfgs_global_arg);
/*< END IF >*/
}
/* FORCE A SUFFICIENT DECREASE IN THE SIZE OF THE */
/* INTERVAL OF UNCERTAINTY. */
/*< IF (BRACKT) THEN >*/
if (brackt) {
/*< >*/
if ((d__1 = sty - stx, abs(d__1)) >= p66 * width1) {
stp = stx + p5 * (sty - stx);
}
/*< WIDTH1 = WIDTH >*/
width1 = width;
/*< WIDTH = ABS(STY-STX) >*/
width = (d__1 = sty - stx, abs(d__1));
/*< END IF >*/
}
/* END OF ITERATION. */
/*< GO TO 30 >*/
goto L30;
/* LAST LINE OF SUBROUTINE MCSRCH. */
/*< END >*/
} /* mcsrch_ */
/*< >*/
/* Subroutine */ int mcstep_(
doublereal *dx, doublereal *dy,
doublereal *fp, doublereal *dp,
doublereal *stpmin, doublereal *stpmax,
v3p_netlib_lbfgs_global_t* v3p_netlib_lbfgs_global_arg
)
{
/* System generated locals */
doublereal d__1, d__2, d__3;
/* Builtin functions */
double sqrt(doublereal);
/* Local variables */
doublereal p, q, r__, s, sgnd, stpc, stpf, stpq, gamma, theta;
logical mcbound;
/*< INTEGER INFOC >*/
/*< DOUBLE PRECISION STX,FX,DX,STY,FY,DY,STP,FP,DP,STPMIN,STPMAX >*/
/*< LOGICAL BRACKT,MCBOUND >*/
/* SUBROUTINE MCSTEP */
/* THE PURPOSE OF MCSTEP IS TO COMPUTE A SAFEGUARDED STEP FOR */
/* A LINESEARCH AND TO UPDATE AN INTERVAL OF UNCERTAINTY FOR */
/* A MINIMIZER OF THE FUNCTION. */
/* THE PARAMETER STX CONTAINS THE STEP WITH THE LEAST FUNCTION */
/* VALUE. THE PARAMETER STP CONTAINS THE CURRENT STEP. IT IS */
/* ASSUMED THAT THE DERIVATIVE AT STX IS NEGATIVE IN THE */
/* DIRECTION OF THE STEP. IF BRACKT IS SET TRUE THEN A */
/* MINIMIZER HAS BEEN BRACKETED IN AN INTERVAL OF UNCERTAINTY */
/* WITH ENDPOINTS STX AND STY. */
/* THE SUBROUTINE STATEMENT IS */
/* SUBROUTINE MCSTEP(STX,FX,DX,STY,FY,DY,STP,FP,DP,BRACKT, */
/* STPMIN,STPMAX,INFOC) */
/* WHERE */
/* STX, FX, AND DX ARE VARIABLES WHICH SPECIFY THE STEP, */
/* THE FUNCTION, AND THE DERIVATIVE AT THE BEST STEP OBTAINED */
/* SO FAR. THE DERIVATIVE MUST BE NEGATIVE IN THE DIRECTION */
/* OF THE STEP, THAT IS, DX AND STP-STX MUST HAVE OPPOSITE */
/* SIGNS. ON OUTPUT THESE PARAMETERS ARE UPDATED APPROPRIATELY. */
/* STY, FY, AND DY ARE VARIABLES WHICH SPECIFY THE STEP, */
/* THE FUNCTION, AND THE DERIVATIVE AT THE OTHER ENDPOINT OF */
/* THE INTERVAL OF UNCERTAINTY. ON OUTPUT THESE PARAMETERS ARE */
/* UPDATED APPROPRIATELY. */
/* STP, FP, AND DP ARE VARIABLES WHICH SPECIFY THE STEP, */
/* THE FUNCTION, AND THE DERIVATIVE AT THE CURRENT STEP. */
/* IF BRACKT IS SET TRUE THEN ON INPUT STP MUST BE */
/* BETWEEN STX AND STY. ON OUTPUT STP IS SET TO THE NEW STEP. */
/* BRACKT IS A LOGICAL VARIABLE WHICH SPECIFIES IF A MINIMIZER */
/* HAS BEEN BRACKETED. IF THE MINIMIZER HAS NOT BEEN BRACKETED */
/* THEN ON INPUT BRACKT MUST BE SET FALSE. IF THE MINIMIZER */
/* IS BRACKETED THEN ON OUTPUT BRACKT IS SET TRUE. */
/* STPMIN AND STPMAX ARE INPUT VARIABLES WHICH SPECIFY LOWER */
/* AND UPPER BOUNDS FOR THE STEP. */
/* INFOC IS AN INTEGER OUTPUT VARIABLE SET AS FOLLOWS: */
/* IF INFOC = 1,2,3,4,5, THEN THE STEP HAS BEEN COMPUTED */
/* ACCORDING TO ONE OF THE FIVE CASES BELOW. OTHERWISE */
/* INFOC = 0, AND THIS INDICATES IMPROPER INPUT PARAMETERS. */
/* SUBPROGRAMS CALLED */
/* FORTRAN-SUPPLIED ... ABS,MAX,MIN,SQRT */
/* ARGONNE NATIONAL LABORATORY. MINPACK PROJECT. JUNE 1983 */
/* <NAME>', <NAME> */
/*< DOUBLE PRECISION GAMMA,P,Q,R,S,SGND,STPC,STPF,STPQ,THETA >*/
/*< INFOC = 0 >*/
infoc = 0;
/* CHECK THE INPUT PARAMETERS FOR ERRORS. */
/*< >*/
if ((brackt && (stp <= min(stx,sty) || stp >= max(stx,sty))) || *dx *
(stp - stx) >= (float)0. || *stpmax < *stpmin) {
return 0;
}
/* DETERMINE IF THE DERIVATIVES HAVE OPPOSITE SIGN. */
/*< SGND = DP*(DX/ABS(DX)) >*/
sgnd = *dp * (*dx / abs(*dx));
/* FIRST CASE. A HIGHER FUNCTION VALUE. */
/* THE MINIMUM IS BRACKETED. IF THE CUBIC STEP IS CLOSER */
/* TO STX THAN THE QUADRATIC STEP, THE CUBIC STEP IS TAKEN, */
/* ELSE THE AVERAGE OF THE CUBIC AND QUADRATIC STEPS IS TAKEN. */
/*< IF (FP .GT. FX) THEN >*/
if (*fp > fx) {
/*< INFOC = 1 >*/
infoc = 1;
/*< MCBOUND = .TRUE. >*/
mcbound = TRUE_;
/*< THETA = 3*(FX - FP)/(STP - STX) + DX + DP >*/
theta = (fx - *fp) * 3 / (stp - stx) + *dx + *dp;
/*< S = MAX(ABS(THETA),ABS(DX),ABS(DP)) >*/
/* Computing MAX */
d__1 = abs(theta), d__2 = abs(*dx), d__1 = max(d__1,d__2), d__2 = abs(
*dp);
s = max(d__1,d__2);
/*< GAMMA = S*SQRT((THETA/S)**2 - (DX/S)*(DP/S)) >*/
/* Computing 2nd power */
d__1 = theta / s;
gamma = s * sqrt(d__1 * d__1 - *dx / s * (*dp / s));
/*< IF (STP .LT. STX) GAMMA = -GAMMA >*/
if (stp < stx) {
gamma = -gamma;
}
/*< P = (GAMMA - DX) + THETA >*/
p = gamma - *dx + theta;
/*< Q = ((GAMMA - DX) + GAMMA) + DP >*/
q = gamma - *dx + gamma + *dp;
/*< R = P/Q >*/
r__ = p / q;
/*< STPC = STX + R*(STP - STX) >*/
stpc = stx + r__ * (stp - stx);
/*< STPQ = STX + ((DX/((FX-FP)/(STP-STX)+DX))/2)*(STP - STX) >*/
stpq = stx + *dx / ((fx - *fp) / (stp - stx) + *dx) / 2 * (stp -
stx);
/*< IF (ABS(STPC-STX) .LT. ABS(STPQ-STX)) THEN >*/
if ((d__1 = stpc - stx, abs(d__1)) < (d__2 = stpq - stx, abs(d__2)))
{
/*< STPF = STPC >*/
stpf = stpc;
/*< ELSE >*/
} else {
/*< STPF = STPC + (STPQ - STPC)/2 >*/
stpf = stpc + (stpq - stpc) / 2;
/*< END IF >*/
}
/*< BRACKT = .TRUE. >*/
brackt = TRUE_;
/* SECOND CASE. A LOWER FUNCTION VALUE AND DERIVATIVES OF */
/* OPPOSITE SIGN. THE MINIMUM IS BRACKETED. IF THE CUBIC */
/* STEP IS CLOSER TO STX THAN THE QUADRATIC (SECANT) STEP, */
/* THE CUBIC STEP IS TAKEN, ELSE THE QUADRATIC STEP IS TAKEN. */
/*< ELSE IF (SGND .LT. 0.0) THEN >*/
} else if (sgnd < (float)0.) {
/*< INFOC = 2 >*/
infoc = 2;
/*< MCBOUND = .FALSE. >*/
mcbound = FALSE_;
/*< THETA = 3*(FX - FP)/(STP - STX) + DX + DP >*/
theta = (fx - *fp) * 3 / (stp - stx) + *dx + *dp;
/*< S = MAX(ABS(THETA),ABS(DX),ABS(DP)) >*/
/* Computing MAX */
d__1 = abs(theta), d__2 = abs(*dx), d__1 = max(d__1,d__2), d__2 = abs(
*dp);
s = max(d__1,d__2);
/*< GAMMA = S*SQRT((THETA/S)**2 - (DX/S)*(DP/S)) >*/
/* Computing 2nd power */
d__1 = theta / s;
gamma = s * sqrt(d__1 * d__1 - *dx / s * (*dp / s));
/*< IF (STP .GT. STX) GAMMA = -GAMMA >*/
if (stp > stx) {
gamma = -gamma;
}
/*< P = (GAMMA - DP) + THETA >*/
p = gamma - *dp + theta;
/*< Q = ((GAMMA - DP) + GAMMA) + DX >*/
q = gamma - *dp + gamma + *dx;
/*< R = P/Q >*/
r__ = p / q;
/*< STPC = STP + R*(STX - STP) >*/
stpc = stp + r__ * (stx - stp);
/*< STPQ = STP + (DP/(DP-DX))*(STX - STP) >*/
stpq = stp + *dp / (*dp - *dx) * (stx - stp);
/*< IF (ABS(STPC-STP) .GT. ABS(STPQ-STP)) THEN >*/
if ((d__1 = stpc - stp, abs(d__1)) > (d__2 = stpq - stp, abs(d__2)))
{
/*< STPF = STPC >*/
stpf = stpc;
/*< ELSE >*/
} else {
/*< STPF = STPQ >*/
stpf = stpq;
/*< END IF >*/
}
/*< BRACKT = .TRUE. >*/
brackt = TRUE_;
/* THIRD CASE. A LOWER FUNCTION VALUE, DERIVATIVES OF THE */
/* SAME SIGN, AND THE MAGNITUDE OF THE DERIVATIVE DECREASES. */
/* THE CUBIC STEP IS ONLY USED IF THE CUBIC TENDS TO INFINITY */
/* IN THE DIRECTION OF THE STEP OR IF THE MINIMUM OF THE CUBIC */
/* IS BEYOND STP. OTHERWISE THE CUBIC STEP IS DEFINED TO BE */
/* EITHER STPMIN OR STPMAX. THE QUADRATIC (SECANT) STEP IS ALSO */
/* COMPUTED AND IF THE MINIMUM IS BRACKETED THEN THE THE STEP */
/* CLOSEST TO STX IS TAKEN, ELSE THE STEP FARTHEST AWAY IS TAKEN. */
/*< ELSE IF (ABS(DP) .LT. ABS(DX)) THEN >*/
} else if (abs(*dp) < abs(*dx)) {
/*< INFOC = 3 >*/
infoc = 3;
/*< MCBOUND = .TRUE. >*/
mcbound = TRUE_;
/*< THETA = 3*(FX - FP)/(STP - STX) + DX + DP >*/
theta = (fx - *fp) * 3 / (stp - stx) + *dx + *dp;
/*< S = MAX(ABS(THETA),ABS(DX),ABS(DP)) >*/
/* Computing MAX */
d__1 = abs(theta), d__2 = abs(*dx), d__1 = max(d__1,d__2), d__2 = abs(
*dp);
s = max(d__1,d__2);
/* THE CASE GAMMA = 0 ONLY ARISES IF THE CUBIC DOES NOT TEND */
/* TO INFINITY IN THE DIRECTION OF THE STEP. */
/*< GAMMA = S*SQRT(MAX(0.0D0,(THETA/S)**2 - (DX/S)*(DP/S))) >*/
/* Computing MAX */
/* Computing 2nd power */
d__3 = theta / s;
d__1 = 0., d__2 = d__3 * d__3 - *dx / s * (*dp / s);
gamma = s * sqrt((max(d__1,d__2)));
/*< IF (STP .GT. STX) GAMMA = -GAMMA >*/
if (stp > stx) {
gamma = -gamma;
}
/*< P = (GAMMA - DP) + THETA >*/
p = gamma - *dp + theta;
/*< Q = (GAMMA + (DX - DP)) + GAMMA >*/
q = gamma + (*dx - *dp) + gamma;
/*< R = P/Q >*/
r__ = p / q;
/*< IF (R .LT. 0.0 .AND. GAMMA .NE. 0.0) THEN >*/
if (r__ < (float)0. && gamma != (float)0.) {
/*< STPC = STP + R*(STX - STP) >*/
stpc = stp + r__ * (stx - stp);
/*< ELSE IF (STP .GT. STX) THEN >*/
} else if (stp > stx) {
/*< STPC = STPMAX >*/
stpc = *stpmax;
/*< ELSE >*/
} else {
/*< STPC = STPMIN >*/
stpc = *stpmin;
/*< END IF >*/
}
/*< STPQ = STP + (DP/(DP-DX))*(STX - STP) >*/
stpq = stp + *dp / (*dp - *dx) * (stx - stp);
/*< IF (BRACKT) THEN >*/
if (brackt) {
/*< IF (ABS(STP-STPC) .LT. ABS(STP-STPQ)) THEN >*/
if ((d__1 = stp - stpc, abs(d__1)) < (d__2 = stp - stpq, abs(
d__2))) {
/*< STPF = STPC >*/
stpf = stpc;
/*< ELSE >*/
} else {
/*< STPF = STPQ >*/
stpf = stpq;
/*< END IF >*/
}
/*< ELSE >*/
} else {
/*< IF (ABS(STP-STPC) .GT. ABS(STP-STPQ)) THEN >*/
if ((d__1 = stp - stpc, abs(d__1)) > (d__2 = stp - stpq, abs(
d__2))) {
/*< STPF = STPC >*/
stpf = stpc;
/*< ELSE >*/
} else {
/*< STPF = STPQ >*/
stpf = stpq;
/*< END IF >*/
}
/*< END IF >*/
}
/* FOURTH CASE. A LOWER FUNCTION VALUE, DERIVATIVES OF THE */
/* SAME SIGN, AND THE MAGNITUDE OF THE DERIVATIVE DOES */
/* NOT DECREASE. IF THE MINIMUM IS NOT BRACKETED, THE STEP */
/* IS EITHER STPMIN OR STPMAX, ELSE THE CUBIC STEP IS TAKEN. */
/*< ELSE >*/
} else {
/*< INFOC = 4 >*/
infoc = 4;
/*< MCBOUND = .FALSE. >*/
mcbound = FALSE_;
/*< IF (BRACKT) THEN >*/
if (brackt) {
/*< THETA = 3*(FP - FY)/(STY - STP) + DY + DP >*/
theta = (*fp - fy) * 3 / (sty - stp) + *dy + *dp;
/*< S = MAX(ABS(THETA),ABS(DY),ABS(DP)) >*/
/* Computing MAX */
d__1 = abs(theta), d__2 = abs(*dy), d__1 = max(d__1,d__2), d__2 =
abs(*dp);
s = max(d__1,d__2);
/*< GAMMA = S*SQRT((THETA/S)**2 - (DY/S)*(DP/S)) >*/
/* Computing 2nd power */
d__1 = theta / s;
gamma = s * sqrt(d__1 * d__1 - *dy / s * (*dp / s));
/*< IF (STP .GT. STY) GAMMA = -GAMMA >*/
if (stp > sty) {
gamma = -gamma;
}
/*< P = (GAMMA - DP) + THETA >*/
p = gamma - *dp + theta;
/*< Q = ((GAMMA - DP) + GAMMA) + DY >*/
q = gamma - *dp + gamma + *dy;
/*< R = P/Q >*/
r__ = p / q;
/*< STPC = STP + R*(STY - STP) >*/
stpc = stp + r__ * (sty - stp);
/*< STPF = STPC >*/
stpf = stpc;
/*< ELSE IF (STP .GT. STX) THEN >*/
} else if (stp > stx) {
/*< STPF = STPMAX >*/
stpf = *stpmax;
/*< ELSE >*/
} else {
/*< STPF = STPMIN >*/
stpf = *stpmin;
/*< END IF >*/
}
/*< END IF >*/
}
/* UPDATE THE INTERVAL OF UNCERTAINTY. THIS UPDATE DOES NOT */
/* DEPEND ON THE NEW STEP OR THE CASE ANALYSIS ABOVE. */
/*< IF (FP .GT. FX) THEN >*/
if (*fp > fx) {
/*< STY = STP >*/
sty = stp;
/*< FY = FP >*/
fy = *fp;
/*< DY = DP >*/
*dy = *dp;
/*< ELSE >*/
} else {
/*< IF (SGND .LT. 0.0) THEN >*/
if (sgnd < (float)0.) {
/*< STY = STX >*/
sty = stx;
/*< FY = FX >*/
fy = fx;
/*< DY = DX >*/
*dy = *dx;
/*< END IF >*/
}
/*< STX = STP >*/
stx = stp;
/*< FX = FP >*/
fx = *fp;
/*< DX = DP >*/
*dx = *dp;
/*< END IF >*/
}
/* COMPUTE THE NEW STEP AND SAFEGUARD IT. */
/*< STPF = MIN(STPMAX,STPF) >*/
stpf = min(*stpmax,stpf);
/*< STPF = MAX(STPMIN,STPF) >*/
stpf = max(*stpmin,stpf);
/*< STP = STPF >*/
stp = stpf;
/*< IF (BRACKT .AND. MCBOUND) THEN >*/
if (brackt && mcbound) {
/*< IF (STY .GT. STX) THEN >*/
if (sty > stx) {
/*< STP = MIN(STX+0.66*(STY-STX),STP) >*/
/* Computing MIN */
d__1 = stx + (sty - stx) * (float).66;
stp = min(d__1,stp);
/*< ELSE >*/
} else {
/*< STP = MAX(STX+0.66*(STY-STX),STP) >*/
/* Computing MAX */
d__1 = stx + (sty - stx) * (float).66;
stp = max(d__1,stp);
/*< END IF >*/
}
/*< END IF >*/
}
/*< RETURN >*/
return 0;
/* LAST LINE OF SUBROUTINE MCSTEP. */
/*< END >*/
} /* mcstep_ */
#ifdef __cplusplus
}
#endif
| 32,433 |
1,290 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import os
import binascii
import hashlib
import struct
from lazagne.config.module_info import ModuleInfo
from lazagne.config.crypto.pyDes import *
from lazagne.config import homes
try:
from ConfigParser import RawConfigParser # Python 2.7
except ImportError:
from configparser import RawConfigParser # Python 3
class Opera(ModuleInfo):
def __init__(self):
ModuleInfo.__init__(self, 'opera', 'browsers')
def get_paths(self):
return homes.get(directory=u'.opera')
def run(self):
all_passwords = []
for path in self.get_paths():
# Check the use of master password
if not os.path.exists(os.path.join(path, u'operaprefs.ini')):
self.debug(u'The preference file operaprefs.ini has not been found.')
else:
if self.master_password_used(path) == '0':
self.debug(u'No master password defined.')
elif self.master_password_used(path) == '1':
self.warning(u'A master password is used.')
else:
self.warning(u'An error occurs, the use of master password is not sure.')
passwords = self.decipher_old_version(path)
if passwords:
all_passwords += self.parse_results(passwords)
else:
self.debug(u'The wand.dat seems to be empty')
return all_passwords
def decipher_old_version(self, path):
salt = '837DFC0F8EB3E86973AFFF'
# Retrieve wand.dat file
if not os.path.exists(os.path.join(path, u'wand.dat')):
self.warning(u'wand.dat file has not been found.')
return
# Read wand.dat
with open(os.path.join(path, u'wand.dat', 'rb')) as outfile:
file = outfile.read()
passwords = []
offset = 0
while offset < len(file):
offset = file.find('\x08', offset) + 1
if offset == 0:
break
tmp_block_length = offset - 8
tmp_data_len = offset + 8
block_length = struct.unpack('!i', file[tmp_block_length: tmp_block_length + 4])[0]
data_len = struct.unpack('!i', file[tmp_data_len: tmp_data_len + 4])[0]
binary_salt = binascii.unhexlify(salt)
des_key = file[offset: offset + 8]
tmp = binary_salt + des_key
md5hash1 = hashlib.md5(tmp).digest()
md5hash2 = hashlib.md5(md5hash1 + tmp).digest()
key = md5hash1 + md5hash2[0:8]
iv = md5hash2[8:]
data = file[offset + 8 + 4: offset + 8 + 4 + data_len]
des3dec = triple_des(key, CBC, iv)
try:
plaintext = des3dec.decrypt(data)
plaintext = re.sub(r'[^\x20-\x7e]', '', plaintext)
passwords.append(plaintext)
except Exception as e:
self.debug(str(e))
self.error(u'Failed to decrypt password')
offset += 8 + 4 + data_len
return passwords
def master_password_used(self, path):
# The init file is not well defined so lines have to be removed before to parse it
cp = RawConfigParser()
with open(os.path.join(path, u'operaprefs.ini', 'rb')) as outfile:
outfile.readline() # discard first line
while True:
try:
cp.readfp(outfile)
break
except Exception:
outfile.readline() # discard first line
try:
master_pass = cp.get('Security Prefs', 'Use Paranoid Mailpassword')
return master_pass
except Exception:
return False
def parse_results(self, passwords):
cpt = 0
tmp_cpt = 0
values = {}
pwd_found = []
for password in passwords:
# Date (begin of the sensitive data)
match = re.search(r'(\d+-\d+-\d+)', password)
if match:
values = {}
cpt = 0
tmp_cpt = 0
# After finding 2 urls
if cpt == 2:
tmp_cpt += 1
if tmp_cpt == 2:
values['Login'] = password
elif tmp_cpt == 4:
values['Password'] = password
pwd_found.append(values)
# URL
match = re.search(r'^http', password)
if match:
cpt += 1
if cpt == 1:
tmp_url = password
elif cpt == 2:
values['URL'] = tmp_url
return pwd_found
| 2,466 |
1,155 |
<reponame>RockyMM/intellij-swagger-icon<filename>src/main/java/org/zalando/intellij/swagger/documentation/openapi/OpenApiDocumentationProvider.java<gh_stars>1000+
package org.zalando.intellij.swagger.documentation.openapi;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import java.util.Optional;
import java.util.stream.Stream;
import org.jetbrains.annotations.Nullable;
import org.zalando.intellij.swagger.documentation.ApiDocumentProvider;
import org.zalando.intellij.swagger.file.OpenApiFileType;
import org.zalando.intellij.swagger.index.openapi.OpenApiIndexService;
import org.zalando.intellij.swagger.traversal.path.openapi.PathResolver;
import org.zalando.intellij.swagger.traversal.path.openapi.PathResolverFactory;
public class OpenApiDocumentationProvider extends ApiDocumentProvider {
@Nullable
@Override
public String getQuickNavigateInfo(
final PsiElement targetElement, final PsiElement originalElement) {
Optional<PsiFile> psiFile =
Optional.ofNullable(targetElement).map(PsiElement::getContainingFile);
final Optional<VirtualFile> maybeVirtualFile = psiFile.map(PsiFile::getVirtualFile);
final Optional<Project> maybeProject = psiFile.map(PsiFile::getProject);
return maybeVirtualFile
.flatMap(
virtualFile -> {
final Project project = maybeProject.get();
final Optional<OpenApiFileType> maybeFileType =
ServiceManager.getService(OpenApiIndexService.class)
.getFileType(project, virtualFile);
return maybeFileType.map(
openApiFileType -> {
final PathResolver pathResolver =
PathResolverFactory.fromOpenApiFileType(openApiFileType);
if (pathResolver.childOfSchema(targetElement)) {
return handleSchemaReference(targetElement, originalElement);
} else if (pathResolver.childOfResponse(targetElement)) {
return handleResponseReference(targetElement);
} else if (pathResolver.childOfParameters(targetElement)) {
return handleParameterReference(targetElement);
} else if (pathResolver.childOfExample(targetElement)) {
return handleExampleReference(targetElement);
} else if (pathResolver.childOfRequestBody(targetElement)) {
return handleRequestBodyReference(targetElement);
} else if (pathResolver.childOfHeader(targetElement)) {
return handleHeaderReference(targetElement);
} else if (pathResolver.childOfLink(targetElement)) {
return handleLinkReference(targetElement);
}
return null;
});
})
.orElse(null);
}
private String handleLinkReference(final PsiElement targetElement) {
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(description));
}
private String handleHeaderReference(final PsiElement targetElement) {
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(description));
}
private String handleRequestBodyReference(final PsiElement targetElement) {
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(description));
}
private String handleExampleReference(final PsiElement targetElement) {
final Optional<String> summary = getUnquotedFieldValue(targetElement, "summary");
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(summary, description));
}
}
| 1,558 |
1,350 |
<filename>sdk/loganalytics/azure-resourcemanager-loganalytics/src/main/java/com/azure/resourcemanager/loganalytics/implementation/SavedSearchesImpl.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.loganalytics.implementation;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.loganalytics.fluent.SavedSearchesClient;
import com.azure.resourcemanager.loganalytics.fluent.models.SavedSearchInner;
import com.azure.resourcemanager.loganalytics.fluent.models.SavedSearchesListResultInner;
import com.azure.resourcemanager.loganalytics.models.SavedSearch;
import com.azure.resourcemanager.loganalytics.models.SavedSearches;
import com.azure.resourcemanager.loganalytics.models.SavedSearchesListResult;
import com.fasterxml.jackson.annotation.JsonIgnore;
public final class SavedSearchesImpl implements SavedSearches {
@JsonIgnore private final ClientLogger logger = new ClientLogger(SavedSearchesImpl.class);
private final SavedSearchesClient innerClient;
private final com.azure.resourcemanager.loganalytics.LogAnalyticsManager serviceManager;
public SavedSearchesImpl(
SavedSearchesClient innerClient, com.azure.resourcemanager.loganalytics.LogAnalyticsManager serviceManager) {
this.innerClient = innerClient;
this.serviceManager = serviceManager;
}
public void delete(String resourceGroupName, String workspaceName, String savedSearchId) {
this.serviceClient().delete(resourceGroupName, workspaceName, savedSearchId);
}
public Response<Void> deleteWithResponse(
String resourceGroupName, String workspaceName, String savedSearchId, Context context) {
return this.serviceClient().deleteWithResponse(resourceGroupName, workspaceName, savedSearchId, context);
}
public SavedSearch get(String resourceGroupName, String workspaceName, String savedSearchId) {
SavedSearchInner inner = this.serviceClient().get(resourceGroupName, workspaceName, savedSearchId);
if (inner != null) {
return new SavedSearchImpl(inner, this.manager());
} else {
return null;
}
}
public Response<SavedSearch> getWithResponse(
String resourceGroupName, String workspaceName, String savedSearchId, Context context) {
Response<SavedSearchInner> inner =
this.serviceClient().getWithResponse(resourceGroupName, workspaceName, savedSearchId, context);
if (inner != null) {
return new SimpleResponse<>(
inner.getRequest(),
inner.getStatusCode(),
inner.getHeaders(),
new SavedSearchImpl(inner.getValue(), this.manager()));
} else {
return null;
}
}
public SavedSearchesListResult listByWorkspace(String resourceGroupName, String workspaceName) {
SavedSearchesListResultInner inner = this.serviceClient().listByWorkspace(resourceGroupName, workspaceName);
if (inner != null) {
return new SavedSearchesListResultImpl(inner, this.manager());
} else {
return null;
}
}
public Response<SavedSearchesListResult> listByWorkspaceWithResponse(
String resourceGroupName, String workspaceName, Context context) {
Response<SavedSearchesListResultInner> inner =
this.serviceClient().listByWorkspaceWithResponse(resourceGroupName, workspaceName, context);
if (inner != null) {
return new SimpleResponse<>(
inner.getRequest(),
inner.getStatusCode(),
inner.getHeaders(),
new SavedSearchesListResultImpl(inner.getValue(), this.manager()));
} else {
return null;
}
}
public SavedSearch getById(String id) {
String resourceGroupName = Utils.getValueFromIdByName(id, "resourcegroups");
if (resourceGroupName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format("The resource ID '%s' is not valid. Missing path segment 'resourcegroups'.", id)));
}
String workspaceName = Utils.getValueFromIdByName(id, "workspaces");
if (workspaceName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'workspaces'.", id)));
}
String savedSearchId = Utils.getValueFromIdByName(id, "savedSearches");
if (savedSearchId == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'savedSearches'.", id)));
}
return this.getWithResponse(resourceGroupName, workspaceName, savedSearchId, Context.NONE).getValue();
}
public Response<SavedSearch> getByIdWithResponse(String id, Context context) {
String resourceGroupName = Utils.getValueFromIdByName(id, "resourcegroups");
if (resourceGroupName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format("The resource ID '%s' is not valid. Missing path segment 'resourcegroups'.", id)));
}
String workspaceName = Utils.getValueFromIdByName(id, "workspaces");
if (workspaceName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'workspaces'.", id)));
}
String savedSearchId = Utils.getValueFromIdByName(id, "savedSearches");
if (savedSearchId == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'savedSearches'.", id)));
}
return this.getWithResponse(resourceGroupName, workspaceName, savedSearchId, context);
}
public void deleteById(String id) {
String resourceGroupName = Utils.getValueFromIdByName(id, "resourcegroups");
if (resourceGroupName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format("The resource ID '%s' is not valid. Missing path segment 'resourcegroups'.", id)));
}
String workspaceName = Utils.getValueFromIdByName(id, "workspaces");
if (workspaceName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'workspaces'.", id)));
}
String savedSearchId = Utils.getValueFromIdByName(id, "savedSearches");
if (savedSearchId == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'savedSearches'.", id)));
}
this.deleteWithResponse(resourceGroupName, workspaceName, savedSearchId, Context.NONE).getValue();
}
public Response<Void> deleteByIdWithResponse(String id, Context context) {
String resourceGroupName = Utils.getValueFromIdByName(id, "resourcegroups");
if (resourceGroupName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format("The resource ID '%s' is not valid. Missing path segment 'resourcegroups'.", id)));
}
String workspaceName = Utils.getValueFromIdByName(id, "workspaces");
if (workspaceName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'workspaces'.", id)));
}
String savedSearchId = Utils.getValueFromIdByName(id, "savedSearches");
if (savedSearchId == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'savedSearches'.", id)));
}
return this.deleteWithResponse(resourceGroupName, workspaceName, savedSearchId, context);
}
private SavedSearchesClient serviceClient() {
return this.innerClient;
}
private com.azure.resourcemanager.loganalytics.LogAnalyticsManager manager() {
return this.serviceManager;
}
public SavedSearchImpl define(String name) {
return new SavedSearchImpl(name, this.manager());
}
}
| 3,929 |
4,013 |
<gh_stars>1000+
'''
Function:
定义游戏
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import sys
import pygame
from .utils import *
from .Sprites import *
'''打砖块游戏'''
class breakoutClone():
def __init__(self, cfg, **kwargs):
pygame.init()
pygame.display.set_caption('Breakout clone —— Charles的皮卡丘')
pygame.mixer.init()
self.screen = pygame.display.set_mode((cfg.SCREENWIDTH, cfg.SCREENHEIGHT))
self.font_small = pygame.font.Font(cfg.FONTPATH, 20)
self.font_big = pygame.font.Font(cfg.FONTPATH, 30)
self.hit_sound = pygame.mixer.Sound(cfg.HITSOUNDPATH)
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.play(-1, 0.0)
self.cfg = cfg
'''运行游戏'''
def run(self):
while True:
self.__startInterface()
for idx, levelpath in enumerate(self.cfg.LEVELPATHS):
state = self.__runLevel(levelpath)
if idx == len(self.cfg.LEVELPATHS)-1:
break
if state == 'win':
self.__nextLevel()
else:
break
if state == 'fail':
self.__endInterface(False)
else:
self.__endInterface(True)
'''运行某关卡'''
def __runLevel(self, levelpath):
score = 0
num_lives = 2
# running: 游戏正在进行, fail: 游戏失败, win: 游戏成功.
state = 'running'
paddle = Paddle((self.cfg.SCREENWIDTH-self.cfg.PADDLEWIDTH)/2, self.cfg.SCREENHEIGHT-self.cfg.PADDLEHEIGHT-10, self.cfg.PADDLEWIDTH, self.cfg.PADDLEHEIGHT, self.cfg.SCREENWIDTH, self.cfg.SCREENHEIGHT)
ball = Ball(paddle.rect.centerx-self.cfg.BALLRADIUS, paddle.rect.top-self.cfg.BALLRADIUS*2, self.cfg.BALLRADIUS, self.cfg.SCREENWIDTH, self.cfg.SCREENHEIGHT)
brick_sprites = pygame.sprite.Group()
brick_positions = loadLevel(levelpath)
for bp in brick_positions:
brick_sprites.add(Brick(bp[0]*self.cfg.BRICKWIDTH, bp[1]*self.cfg.BRICKHEIGHT, self.cfg.BRICKWIDTH, self.cfg.BRICKHEIGHT))
clock = pygame.time.Clock()
while True:
if state != 'running':
return state
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(-1)
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_LEFT]:
paddle.move('left')
elif keys_pressed[pygame.K_RIGHT]:
paddle.move('right')
self.screen.fill(self.cfg.AQUA)
is_alive = ball.move()
# 判断有没有接住球
if not is_alive:
ball.reset()
paddle.reset()
num_lives -= 1
if num_lives == 0:
state = 'fail'
# 球和砖块碰撞检测
num_bricks = pygame.sprite.spritecollide(ball, brick_sprites, True)
score += len(num_bricks)
# 球和拍碰撞检测
if pygame.sprite.collide_rect(ball, paddle):
ball.change()
# 判断砖块是否已经打完
if len(brick_sprites) == 0:
state = 'win'
# 将游戏精灵绑定到屏幕
paddle.draw(self.screen, self.cfg.PURPLE)
ball.draw(self.screen, self.cfg.WHITE)
for brick in brick_sprites:
brick.draw(self.screen, self.cfg.YELLOW)
text_render = self.font_small.render('SCORE: %s, LIVES: %s' % (score, num_lives), False, self.cfg.BLUE)
self.screen.blit(text_render, (10, 10))
pygame.display.flip()
clock.tick(50)
'''关卡切换'''
def __nextLevel(self):
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(-1)
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
return
self.screen.fill(self.cfg.AQUA)
text = 'Press <Enter> to enter the next level'
text_render = self.font_big.render(text, False, self.cfg.BLUE)
self.screen.blit(text_render, ((self.cfg.SCREENWIDTH-text_render.get_rect().width)//2, (self.cfg.SCREENHEIGHT-text_render.get_rect().height)//3))
pygame.display.flip()
clock.tick(30)
'''开始界面'''
def __startInterface(self):
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
pygame.quit()
sys.exit(-1)
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
return
self.screen.fill(self.cfg.AQUA)
text1 = 'Press <Enter> to start the game'
text2 = 'Press <Esc> to quit the game'
text_render1 = self.font_big.render(text1, False, self.cfg.BLUE)
text_render2 = self.font_big.render(text2, False, self.cfg.BLUE)
self.screen.blit(text_render1, ((self.cfg.SCREENWIDTH-text_render1.get_rect().width)//2, (self.cfg.SCREENHEIGHT-text_render1.get_rect().height)//4))
self.screen.blit(text_render2, ((self.cfg.SCREENWIDTH-text_render2.get_rect().width)//2, (self.cfg.SCREENHEIGHT-text_render2.get_rect().height)//2))
pygame.display.flip()
clock.tick(30)
'''结束界面'''
def __endInterface(self, is_win):
if is_win:
text1 = 'Congratulations! You win!'
else:
text1 = 'Game Over! You fail!'
text2 = 'Press <R> to restart the game'
text3 = 'Press <Esc> to quit the game.'
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
pygame.quit()
sys.exit(-1)
if event.type == pygame.KEYDOWN and event.key == pygame.K_r:
return
self.screen.fill(self.cfg.AQUA)
text_render1 = self.font_big.render(text1, False, self.cfg.BLUE)
text_render2 = self.font_big.render(text2, False, self.cfg.BLUE)
text_render3 = self.font_big.render(text3, False, self.cfg.BLUE)
self.screen.blit(text_render1, ((self.cfg.SCREENWIDTH-text_render1.get_rect().width)//2, (self.cfg.SCREENHEIGHT-text_render1.get_rect().height)//4))
self.screen.blit(text_render2, ((self.cfg.SCREENWIDTH-text_render2.get_rect().width)//2, (self.cfg.SCREENHEIGHT-text_render2.get_rect().height)//2))
self.screen.blit(text_render3, ((self.cfg.SCREENWIDTH-text_render3.get_rect().width)//2, (self.cfg.SCREENHEIGHT-text_render2.get_rect().height)//1.5))
pygame.display.flip()
clock.tick(30)
| 3,900 |
1,121 |
/*
Copyright(c) 2016-2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//= INCLUDES =====================
#include "Spartan.h"
#include "../RHI_Fence.h"
#include "../RHI_Implementation.h"
#include "../RHI_Device.h"
//================================
namespace Spartan
{
RHI_Fence::RHI_Fence(RHI_Device* rhi_device, const char* name /*= nullptr*/)
{
m_rhi_device = rhi_device;
// Describe
VkFenceCreateInfo fence_info = {};
fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
// Create
if (!vulkan_utility::error::check(vkCreateFence(m_rhi_device->GetContextRhi()->device, &fence_info, nullptr, reinterpret_cast<VkFence*>(&m_resource))))
return;
// Name
if (name)
{
m_object_name = name;
vulkan_utility::debug::set_name(static_cast<VkFence>(m_resource), m_object_name.c_str());
}
}
RHI_Fence::~RHI_Fence()
{
if (!m_resource)
return;
// Wait in case it's still in use by the GPU
m_rhi_device->QueueWaitAll();
vkDestroyFence(m_rhi_device->GetContextRhi()->device, static_cast<VkFence>(m_resource), nullptr);
m_resource = nullptr;
}
bool RHI_Fence::IsSignaled()
{
return vkGetFenceStatus(m_rhi_device->GetContextRhi()->device, reinterpret_cast<VkFence>(m_resource)) == VK_SUCCESS;
}
bool RHI_Fence::Wait(uint64_t timeout /*= std::numeric_limits<uint64_t>::max()*/)
{
return vulkan_utility::error::check(vkWaitForFences(m_rhi_device->GetContextRhi()->device, 1, reinterpret_cast<VkFence*>(&m_resource), true, timeout));
}
bool RHI_Fence::Reset()
{
return IsSignaled() ? vulkan_utility::error::check(vkResetFences(m_rhi_device->GetContextRhi()->device, 1, reinterpret_cast<VkFence*>(&m_resource))) : true;
}
}
| 1,095 |
335 |
/*
* Copyright 2019-2020 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vividus.ui.action.search;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
public class ElementActionService
{
@Inject private Set<IElementAction> elementActions;
private Set<LocatorType> searchLocatorTypes;
private Set<LocatorType> filterLocatorTypes;
public void init()
{
this.searchLocatorTypes = collectTypesByActionClass(IElementSearchAction.class);
this.filterLocatorTypes = collectTypesByActionClass(IElementFilterAction.class);
}
@SuppressWarnings("unchecked")
public <T extends IElementAction> T find(LocatorType actionType)
{
return (T) elementActions.stream()
.filter(action -> action.getType() == actionType)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException(
"There is no mapped element action for attribute: " + actionType.getAttributeName()));
}
public Set<LocatorType> getSearchLocatorTypes()
{
return searchLocatorTypes;
}
public Set<LocatorType> getFilterLocatorTypes()
{
return filterLocatorTypes;
}
private Set<LocatorType> collectTypesByActionClass(Class<? extends IElementAction> actionClass)
{
return elementActions.stream()
.filter(t -> actionClass.isAssignableFrom(t.getClass()))
.map(IElementAction::getType)
.collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
}
}
| 859 |
575 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/arc/instance_throttle/arc_instance_throttle.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/no_destructor.h"
#include "chrome/browser/ash/arc/boot_phase_monitor/arc_boot_phase_monitor_bridge.h"
#include "chrome/browser/ash/arc/instance_throttle/arc_active_window_throttle_observer.h"
#include "chrome/browser/ash/arc/instance_throttle/arc_app_launch_throttle_observer.h"
#include "chrome/browser/ash/arc/instance_throttle/arc_boot_phase_throttle_observer.h"
#include "chrome/browser/ash/arc/instance_throttle/arc_pip_window_throttle_observer.h"
#include "components/arc/arc_browser_context_keyed_service_factory_base.h"
#include "components/arc/arc_util.h"
namespace arc {
namespace {
class DefaultDelegateImpl : public ArcInstanceThrottle::Delegate {
public:
DefaultDelegateImpl() = default;
~DefaultDelegateImpl() override = default;
void SetCpuRestriction(CpuRestrictionState cpu_restriction_state) override {
SetArcCpuRestriction(cpu_restriction_state);
}
void RecordCpuRestrictionDisabledUMA(const std::string& observer_name,
base::TimeDelta delta) override {
DVLOG(2) << "ARC throttling was disabled for "
<< delta.InMillisecondsRoundedUp()
<< " ms due to: " << observer_name;
UmaHistogramLongTimes("Arc.CpuRestrictionDisabled." + observer_name, delta);
}
private:
DISALLOW_COPY_AND_ASSIGN(DefaultDelegateImpl);
};
// Singleton factory for ArcInstanceThrottle.
class ArcInstanceThrottleFactory
: public internal::ArcBrowserContextKeyedServiceFactoryBase<
ArcInstanceThrottle,
ArcInstanceThrottleFactory> {
public:
static constexpr const char* kName = "ArcInstanceThrottleFactory";
static ArcInstanceThrottleFactory* GetInstance() {
static base::NoDestructor<ArcInstanceThrottleFactory> instance;
return instance.get();
}
private:
friend class base::NoDestructor<ArcInstanceThrottleFactory>;
ArcInstanceThrottleFactory() {
DependsOn(ArcBootPhaseMonitorBridgeFactory::GetInstance());
}
~ArcInstanceThrottleFactory() override = default;
};
} // namespace
// static
ArcInstanceThrottle* ArcInstanceThrottle::GetForBrowserContext(
content::BrowserContext* context) {
return ArcInstanceThrottleFactory::GetForBrowserContext(context);
}
// static
ArcInstanceThrottle* ArcInstanceThrottle::GetForBrowserContextForTesting(
content::BrowserContext* context) {
return ArcInstanceThrottleFactory::GetForBrowserContextForTesting(context);
}
ArcInstanceThrottle::ArcInstanceThrottle(content::BrowserContext* context,
ArcBridgeService* bridge_service)
: ThrottleService(context),
delegate_(std::make_unique<DefaultDelegateImpl>()) {
AddObserver(std::make_unique<ArcActiveWindowThrottleObserver>());
AddObserver(std::make_unique<ArcAppLaunchThrottleObserver>());
AddObserver(std::make_unique<ArcBootPhaseThrottleObserver>());
AddObserver(std::make_unique<ArcPipWindowThrottleObserver>());
StartObservers();
}
ArcInstanceThrottle::~ArcInstanceThrottle() = default;
void ArcInstanceThrottle::Shutdown() {
StopObservers();
}
void ArcInstanceThrottle::ThrottleInstance(
chromeos::ThrottleObserver::PriorityLevel level) {
switch (level) {
case chromeos::ThrottleObserver::PriorityLevel::CRITICAL:
case chromeos::ThrottleObserver::PriorityLevel::IMPORTANT:
case chromeos::ThrottleObserver::PriorityLevel::NORMAL:
delegate_->SetCpuRestriction(
CpuRestrictionState::CPU_RESTRICTION_FOREGROUND);
break;
case chromeos::ThrottleObserver::PriorityLevel::LOW:
case chromeos::ThrottleObserver::PriorityLevel::UNKNOWN:
delegate_->SetCpuRestriction(
CpuRestrictionState::CPU_RESTRICTION_BACKGROUND);
break;
}
}
void ArcInstanceThrottle::RecordCpuRestrictionDisabledUMA(
const std::string& observer_name,
base::TimeDelta delta) {
delegate_->RecordCpuRestrictionDisabledUMA(observer_name, delta);
}
} // namespace arc
| 1,486 |
18,325 |
package com.zheng.upms.server;
import com.zheng.common.base.BaseInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 系统接口
* Created by ZhangShuzheng on 2017/6/13.
*/
public class Initialize implements BaseInterface {
private static final Logger LOGGER = LoggerFactory.getLogger(Initialize.class);
@Override
public void init() {
LOGGER.info(">>>>> 系统初始化");
}
}
| 157 |
1,139 |
s = 'Hi\nHello'
print(s)
raw_s = r'Hi\nHello'
print(raw_s)
# raw string \ escapes quotes (',") but \ remains in the result
# raw string can't be single \ or end with odd numbers of \
raw_s = r'\''
print(raw_s)
raw_s = r'ab\\'
print(raw_s)
raw_s = R'\\\"' # prefix can be 'R' or 'r'
print(raw_s)
| 132 |
2,151 |
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'exe',
'type': 'executable',
'dependencies': [
'subdir2/subdir.gyp:foo',
],
},
{
'target_name': 'exe2',
'type': 'executable',
'includes': [
'test2.includes.gypi',
],
},
],
'includes': [
'test2.toplevel_includes.gypi',
],
}
| 232 |
797 |
/*
The MIT License (MIT)
Copyright (c) 2015 <NAME> and Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.intellij.lang.jsgraphql.types.validation;
import com.intellij.lang.jsgraphql.types.Internal;
import com.intellij.lang.jsgraphql.types.language.Definition;
import com.intellij.lang.jsgraphql.types.language.Document;
import com.intellij.lang.jsgraphql.types.language.FragmentDefinition;
import com.intellij.lang.jsgraphql.types.schema.*;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Internal
public class ValidationContext {
private final GraphQLSchema schema;
private final Document document;
private final TraversalContext traversalContext;
private final Map<String, FragmentDefinition> fragmentDefinitionMap = new LinkedHashMap<>();
public ValidationContext(GraphQLSchema schema, Document document) {
this.schema = schema;
this.document = document;
this.traversalContext = new TraversalContext(schema);
buildFragmentMap();
}
private void buildFragmentMap() {
for (Definition definition : document.getDefinitions()) {
if (!(definition instanceof FragmentDefinition)) continue;
FragmentDefinition fragmentDefinition = (FragmentDefinition) definition;
fragmentDefinitionMap.put(fragmentDefinition.getName(), fragmentDefinition);
}
}
public TraversalContext getTraversalContext() {
return traversalContext;
}
public GraphQLSchema getSchema() {
return schema;
}
public Document getDocument() {
return document;
}
public FragmentDefinition getFragment(String name) {
return fragmentDefinitionMap.get(name);
}
public GraphQLCompositeType getParentType() {
return traversalContext.getParentType();
}
public GraphQLInputType getInputType() {
return traversalContext.getInputType();
}
public GraphQLFieldDefinition getFieldDef() {
return traversalContext.getFieldDef();
}
public GraphQLDirective getDirective() {
return traversalContext.getDirective();
}
public GraphQLArgument getArgument() {
return traversalContext.getArgument();
}
public GraphQLOutputType getOutputType() {
return traversalContext.getOutputType();
}
public List<String> getQueryPath() {
return traversalContext.getQueryPath();
}
@Override
public String toString() {
return "ValidationContext{" + getQueryPath() + "}";
}
}
| 1,168 |
324 |
<reponame>tormath1/jclouds
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.googlecomputeengine.compute.functions;
import java.util.List;
import javax.inject.Inject;
import org.jclouds.compute.functions.GroupNamingConvention;
/**
* The convention for naming instance tags that firewall rules recognise.
*/
public final class FirewallTagNamingConvention {
public static final class Factory {
private final GroupNamingConvention.Factory namingConvention;
@Inject Factory(GroupNamingConvention.Factory namingConvention) {
this.namingConvention = namingConvention;
}
public FirewallTagNamingConvention get(String groupName) {
return new FirewallTagNamingConvention(namingConvention.create().sharedNameForGroup(groupName));
}
}
private final String sharedResourceName;
public FirewallTagNamingConvention(String sharedResourceName) {
this.sharedResourceName = sharedResourceName;
}
public String name(List<String> ports) {
final int prime = 31;
int result = 1;
for (String s : ports){
result = result * prime + s.hashCode();
// TODO(broudy): this may break between java versions! Consider a different implementation.
}
return String.format("%s-%s", sharedResourceName, Integer.toHexString(result));
}
}
| 632 |
411 |
<reponame>mmmaaaggg/pyctp_lovelylain<gh_stars>100-1000
# -*- coding: utf-8 -*-
from __future__ import absolute_import as _init
__author__ = 'lovelylain'
__version__ = '0.2.1'
__all__ = ['ApiStruct', 'MdApi', 'TraderApi']
if 0: from . import ApiStruct
class MdApi(object):
def Create(self, pszFlowPath='', bIsUsingUdp=False, bIsMulticast=False):
"""创建MdApi
@param pszFlowPath 存贮订阅信息文件的目录,默认为当前目录
@return 创建出的UserApi
modify for udp marketdata
"""
def GetApiVersion(self):
"""获取API的版本信息
@retrun 获取到的版本号
"""
return ''
def Release(self):
"""删除接口对象本身
@remark 不再使用本接口对象时,调用该函数删除接口对象
"""
def Init(self):
"""初始化
@remark 初始化运行环境,只有调用后,接口才开始工作
"""
def Join(self):
"""等待接口线程结束运行
@return 线程退出代码
"""
return 0
def GetTradingDay(self):
"""获取当前交易日
@retrun 获取到的交易日
@remark 只有登录成功后,才能得到正确的交易日
"""
return ''
def RegisterFront(self, pszFrontAddress):
"""注册前置机网络地址
@param pszFrontAddress:前置机网络地址。
@remark 网络地址的格式为:“protocol:
ipaddress:port”,如:”tcp:
127.0.0.1:17001”。
@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”17001”代表服务器端口号。
"""
def RegisterNameServer(self, pszNsAddress):
"""注册名字服务器网络地址
@param pszNsAddress:名字服务器网络地址。
@remark 网络地址的格式为:“protocol:
ipaddress:port”,如:”tcp:
127.0.0.1:12001”。
@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”12001”代表服务器端口号。
@remark RegisterNameServer优先于RegisterFront
"""
def RegisterFensUserInfo(self, pFensUserInfo):
"""注册名字服务器用户信息
@param pFensUserInfo:用户信息。
"""
def SubscribeMarketData(self, pInstrumentIDs):
"""订阅行情。
@param pInstrumentIDs 合约ID列表
@remark
"""
return 0
def UnSubscribeMarketData(self, pInstrumentIDs):
"""退订行情。
@param pInstrumentIDs 合约ID列表
@remark
"""
return 0
def SubscribeForQuoteRsp(self, pInstrumentIDs):
"""订阅询价。
@param pInstrumentIDs 合约ID列表
@remark
"""
return 0
def UnSubscribeForQuoteRsp(self, pInstrumentIDs):
"""退订询价。
@param pInstrumentIDs 合约ID列表
@remark
"""
return 0
def ReqUserLogin(self, pReqUserLogin, nRequestID):
"""用户登录请求"""
return 0
def ReqUserLogout(self, pUserLogout, nRequestID):
"""登出请求"""
return 0
def OnFrontConnected(self):
"""当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。"""
def OnFrontDisconnected(self, nReason):
"""当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。
@param nReason 错误原因
0x1001 网络读失败
0x1002 网络写失败
0x2001 接收心跳超时
0x2002 发送心跳失败
0x2003 收到错误报文
"""
def OnHeartBeatWarning(self, nTimeLapse):
"""心跳超时警告。当长时间未收到报文时,该方法被调用。
@param nTimeLapse 距离上次接收报文的时间
"""
def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):
"""登录请求响应"""
def OnRspUserLogout(self, pUserLogout, pRspInfo, nRequestID, bIsLast):
"""登出请求响应"""
def OnRspError(self, pRspInfo, nRequestID, bIsLast):
"""错误应答"""
def OnRspSubMarketData(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
"""订阅行情应答"""
def OnRspUnSubMarketData(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
"""取消订阅行情应答"""
def OnRspSubForQuoteRsp(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
"""订阅询价应答"""
def OnRspUnSubForQuoteRsp(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
"""取消订阅询价应答"""
def OnRtnDepthMarketData(self, pDepthMarketData):
"""深度行情通知"""
def OnRtnForQuoteRsp(self, pForQuoteRsp):
"""询价通知"""
class TraderApi(object):
def Create(self, pszFlowPath=''):
"""创建TraderApi
@param pszFlowPath 存贮订阅信息文件的目录,默认为当前目录
@return 创建出的UserApi
"""
def GetApiVersion(self):
"""获取API的版本信息
@retrun 获取到的版本号
"""
return ''
def Release(self):
"""删除接口对象本身
@remark 不再使用本接口对象时,调用该函数删除接口对象
"""
def Init(self):
"""初始化
@remark 初始化运行环境,只有调用后,接口才开始工作
"""
def Join(self):
"""等待接口线程结束运行
@return 线程退出代码
"""
return 0
def GetTradingDay(self):
"""获取当前交易日
@retrun 获取到的交易日
@remark 只有登录成功后,才能得到正确的交易日
"""
return ''
def RegisterFront(self, pszFrontAddress):
"""注册前置机网络地址
@param pszFrontAddress:前置机网络地址。
@remark 网络地址的格式为:“protocol:
ipaddress:port”,如:”tcp:
127.0.0.1:17001”。
@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”17001”代表服务器端口号。
"""
def RegisterNameServer(self, pszNsAddress):
"""注册名字服务器网络地址
@param pszNsAddress:名字服务器网络地址。
@remark 网络地址的格式为:“protocol:
ipaddress:port”,如:”tcp:
127.0.0.1:12001”。
@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”12001”代表服务器端口号。
@remark RegisterNameServer优先于RegisterFront
"""
def RegisterFensUserInfo(self, pFensUserInfo):
"""注册名字服务器用户信息
@param pFensUserInfo:用户信息。
"""
def SubscribePrivateTopic(self, nResumeType):
"""订阅私有流。
@param nResumeType 私有流重传方式
THOST_TERT_RESTART:从本交易日开始重传
THOST_TERT_RESUME:从上次收到的续传
THOST_TERT_QUICK:只传送登录后私有流的内容
@remark 该方法要在Init方法前调用。若不调用则不会收到私有流的数据。
"""
def SubscribePublicTopic(self, nResumeType):
"""订阅公共流。
@param nResumeType 公共流重传方式
THOST_TERT_RESTART:从本交易日开始重传
THOST_TERT_RESUME:从上次收到的续传
THOST_TERT_QUICK:只传送登录后公共流的内容
@remark 该方法要在Init方法前调用。若不调用则不会收到公共流的数据。
"""
def ReqAuthenticate(self, pReqAuthenticate, nRequestID):
"""客户端认证请求"""
return 0
def ReqUserLogin(self, pReqUserLogin, nRequestID):
"""用户登录请求"""
return 0
def ReqUserLogout(self, pUserLogout, nRequestID):
"""登出请求"""
return 0
def ReqUserPasswordUpdate(self, pUserPasswordUpdate, nRequestID):
"""用户口令更新请求"""
return 0
def ReqTradingAccountPasswordUpdate(self, pTradingAccountPasswordUpdate, nRequestID):
"""资金账户口令更新请求"""
return 0
def ReqOrderInsert(self, pInputOrder, nRequestID):
"""报单录入请求"""
return 0
def ReqParkedOrderInsert(self, pParkedOrder, nRequestID):
"""预埋单录入请求"""
return 0
def ReqParkedOrderAction(self, pParkedOrderAction, nRequestID):
"""预埋撤单录入请求"""
return 0
def ReqOrderAction(self, pInputOrderAction, nRequestID):
"""报单操作请求"""
return 0
def ReqQueryMaxOrderVolume(self, pQueryMaxOrderVolume, nRequestID):
"""查询最大报单数量请求"""
return 0
def ReqSettlementInfoConfirm(self, pSettlementInfoConfirm, nRequestID):
"""投资者结算结果确认"""
return 0
def ReqRemoveParkedOrder(self, pRemoveParkedOrder, nRequestID):
"""请求删除预埋单"""
return 0
def ReqRemoveParkedOrderAction(self, pRemoveParkedOrderAction, nRequestID):
"""请求删除预埋撤单"""
return 0
def ReqExecOrderInsert(self, pInputExecOrder, nRequestID):
"""执行宣告录入请求"""
return 0
def ReqExecOrderAction(self, pInputExecOrderAction, nRequestID):
"""执行宣告操作请求"""
return 0
def ReqForQuoteInsert(self, pInputForQuote, nRequestID):
"""询价录入请求"""
return 0
def ReqQuoteInsert(self, pInputQuote, nRequestID):
"""报价录入请求"""
return 0
def ReqQuoteAction(self, pInputQuoteAction, nRequestID):
"""报价操作请求"""
return 0
def ReqCombActionInsert(self, pInputCombAction, nRequestID):
"""申请组合录入请求"""
return 0
def ReqQryOrder(self, pQryOrder, nRequestID):
"""请求查询报单"""
return 0
def ReqQryTrade(self, pQryTrade, nRequestID):
"""请求查询成交"""
return 0
def ReqQryInvestorPosition(self, pQryInvestorPosition, nRequestID):
"""请求查询投资者持仓"""
return 0
def ReqQryTradingAccount(self, pQryTradingAccount, nRequestID):
"""请求查询资金账户"""
return 0
def ReqQryInvestor(self, pQryInvestor, nRequestID):
"""请求查询投资者"""
return 0
def ReqQryTradingCode(self, pQryTradingCode, nRequestID):
"""请求查询交易编码"""
return 0
def ReqQryInstrumentMarginRate(self, pQryInstrumentMarginRate, nRequestID):
"""请求查询合约保证金率"""
return 0
def ReqQryInstrumentCommissionRate(self, pQryInstrumentCommissionRate, nRequestID):
"""请求查询合约手续费率"""
return 0
def ReqQryExchange(self, pQryExchange, nRequestID):
"""请求查询交易所"""
return 0
def ReqQryProduct(self, pQryProduct, nRequestID):
"""请求查询产品"""
return 0
def ReqQryInstrument(self, pQryInstrument, nRequestID):
"""请求查询合约"""
return 0
def ReqQryDepthMarketData(self, pQryDepthMarketData, nRequestID):
"""请求查询行情"""
return 0
def ReqQrySettlementInfo(self, pQrySettlementInfo, nRequestID):
"""请求查询投资者结算结果"""
return 0
def ReqQryTransferBank(self, pQryTransferBank, nRequestID):
"""请求查询转帐银行"""
return 0
def ReqQryInvestorPositionDetail(self, pQryInvestorPositionDetail, nRequestID):
"""请求查询投资者持仓明细"""
return 0
def ReqQryNotice(self, pQryNotice, nRequestID):
"""请求查询客户通知"""
return 0
def ReqQrySettlementInfoConfirm(self, pQrySettlementInfoConfirm, nRequestID):
"""请求查询结算信息确认"""
return 0
def ReqQryInvestorPositionCombineDetail(self, pQryInvestorPositionCombineDetail, nRequestID):
"""请求查询投资者持仓明细"""
return 0
def ReqQryCFMMCTradingAccountKey(self, pQryCFMMCTradingAccountKey, nRequestID):
"""请求查询保证金监管系统经纪公司资金账户密钥"""
return 0
def ReqQryEWarrantOffset(self, pQryEWarrantOffset, nRequestID):
"""请求查询仓单折抵信息"""
return 0
def ReqQryInvestorProductGroupMargin(self, pQryInvestorProductGroupMargin, nRequestID):
"""请求查询投资者品种/跨品种保证金"""
return 0
def ReqQryExchangeMarginRate(self, pQryExchangeMarginRate, nRequestID):
"""请求查询交易所保证金率"""
return 0
def ReqQryExchangeMarginRateAdjust(self, pQryExchangeMarginRateAdjust, nRequestID):
"""请求查询交易所调整保证金率"""
return 0
def ReqQryExchangeRate(self, pQryExchangeRate, nRequestID):
"""请求查询汇率"""
return 0
def ReqQrySecAgentACIDMap(self, pQrySecAgentACIDMap, nRequestID):
"""请求查询二级代理操作员银期权限"""
return 0
def ReqQryProductExchRate(self, pQryProductExchRate, nRequestID):
"""请求查询产品报价汇率"""
return 0
def ReqQryOptionInstrTradeCost(self, pQryOptionInstrTradeCost, nRequestID):
"""请求查询期权交易成本"""
return 0
def ReqQryOptionInstrCommRate(self, pQryOptionInstrCommRate, nRequestID):
"""请求查询期权合约手续费"""
return 0
def ReqQryExecOrder(self, pQryExecOrder, nRequestID):
"""请求查询执行宣告"""
return 0
def ReqQryForQuote(self, pQryForQuote, nRequestID):
"""请求查询询价"""
return 0
def ReqQryQuote(self, pQryQuote, nRequestID):
"""请求查询报价"""
return 0
def ReqQryCombInstrumentGuard(self, pQryCombInstrumentGuard, nRequestID):
"""请求查询组合合约安全系数"""
return 0
def ReqQryCombAction(self, pQryCombAction, nRequestID):
"""请求查询申请组合"""
return 0
def ReqQryTransferSerial(self, pQryTransferSerial, nRequestID):
"""请求查询转帐流水"""
return 0
def ReqQryAccountregister(self, pQryAccountregister, nRequestID):
"""请求查询银期签约关系"""
return 0
def ReqQryContractBank(self, pQryContractBank, nRequestID):
"""请求查询签约银行"""
return 0
def ReqQryParkedOrder(self, pQryParkedOrder, nRequestID):
"""请求查询预埋单"""
return 0
def ReqQryParkedOrderAction(self, pQryParkedOrderAction, nRequestID):
"""请求查询预埋撤单"""
return 0
def ReqQryTradingNotice(self, pQryTradingNotice, nRequestID):
"""请求查询交易通知"""
return 0
def ReqQryBrokerTradingParams(self, pQryBrokerTradingParams, nRequestID):
"""请求查询经纪公司交易参数"""
return 0
def ReqQryBrokerTradingAlgos(self, pQryBrokerTradingAlgos, nRequestID):
"""请求查询经纪公司交易算法"""
return 0
def ReqQueryCFMMCTradingAccountToken(self, pQueryCFMMCTradingAccountToken, nRequestID):
"""请求查询监控中心用户令牌"""
return 0
def ReqFromBankToFutureByFuture(self, pReqTransfer, nRequestID):
"""期货发起银行资金转期货请求"""
return 0
def ReqFromFutureToBankByFuture(self, pReqTransfer, nRequestID):
"""期货发起期货资金转银行请求"""
return 0
def ReqQueryBankAccountMoneyByFuture(self, pReqQueryAccount, nRequestID):
"""期货发起查询银行余额请求"""
return 0
def OnFrontConnected(self):
"""当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。"""
def OnFrontDisconnected(self, nReason):
"""当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。
@param nReason 错误原因
0x1001 网络读失败
0x1002 网络写失败
0x2001 接收心跳超时
0x2002 发送心跳失败
0x2003 收到错误报文
"""
def OnHeartBeatWarning(self, nTimeLapse):
"""心跳超时警告。当长时间未收到报文时,该方法被调用。
@param nTimeLapse 距离上次接收报文的时间
"""
def OnRspAuthenticate(self, pRspAuthenticate, pRspInfo, nRequestID, bIsLast):
"""客户端认证响应"""
def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):
"""登录请求响应"""
def OnRspUserLogout(self, pUserLogout, pRspInfo, nRequestID, bIsLast):
"""登出请求响应"""
def OnRspUserPasswordUpdate(self, pUserPasswordUpdate, pRspInfo, nRequestID, bIsLast):
"""用户口令更新请求响应"""
def OnRspTradingAccountPasswordUpdate(self, pTradingAccountPasswordUpdate, pRspInfo, nRequestID, bIsLast):
"""资金账户口令更新请求响应"""
def OnRspOrderInsert(self, pInputOrder, pRspInfo, nRequestID, bIsLast):
"""报单录入请求响应"""
def OnRspParkedOrderInsert(self, pParkedOrder, pRspInfo, nRequestID, bIsLast):
"""预埋单录入请求响应"""
def OnRspParkedOrderAction(self, pParkedOrderAction, pRspInfo, nRequestID, bIsLast):
"""预埋撤单录入请求响应"""
def OnRspOrderAction(self, pInputOrderAction, pRspInfo, nRequestID, bIsLast):
"""报单操作请求响应"""
def OnRspQueryMaxOrderVolume(self, pQueryMaxOrderVolume, pRspInfo, nRequestID, bIsLast):
"""查询最大报单数量响应"""
def OnRspSettlementInfoConfirm(self, pSettlementInfoConfirm, pRspInfo, nRequestID, bIsLast):
"""投资者结算结果确认响应"""
def OnRspRemoveParkedOrder(self, pRemoveParkedOrder, pRspInfo, nRequestID, bIsLast):
"""删除预埋单响应"""
def OnRspRemoveParkedOrderAction(self, pRemoveParkedOrderAction, pRspInfo, nRequestID, bIsLast):
"""删除预埋撤单响应"""
def OnRspExecOrderInsert(self, pInputExecOrder, pRspInfo, nRequestID, bIsLast):
"""执行宣告录入请求响应"""
def OnRspExecOrderAction(self, pInputExecOrderAction, pRspInfo, nRequestID, bIsLast):
"""执行宣告操作请求响应"""
def OnRspForQuoteInsert(self, pInputForQuote, pRspInfo, nRequestID, bIsLast):
"""询价录入请求响应"""
def OnRspQuoteInsert(self, pInputQuote, pRspInfo, nRequestID, bIsLast):
"""报价录入请求响应"""
def OnRspQuoteAction(self, pInputQuoteAction, pRspInfo, nRequestID, bIsLast):
"""报价操作请求响应"""
def OnRspCombActionInsert(self, pInputCombAction, pRspInfo, nRequestID, bIsLast):
"""申请组合录入请求响应"""
def OnRspQryOrder(self, pOrder, pRspInfo, nRequestID, bIsLast):
"""请求查询报单响应"""
def OnRspQryTrade(self, pTrade, pRspInfo, nRequestID, bIsLast):
"""请求查询成交响应"""
def OnRspQryInvestorPosition(self, pInvestorPosition, pRspInfo, nRequestID, bIsLast):
"""请求查询投资者持仓响应"""
def OnRspQryTradingAccount(self, pTradingAccount, pRspInfo, nRequestID, bIsLast):
"""请求查询资金账户响应"""
def OnRspQryInvestor(self, pInvestor, pRspInfo, nRequestID, bIsLast):
"""请求查询投资者响应"""
def OnRspQryTradingCode(self, pTradingCode, pRspInfo, nRequestID, bIsLast):
"""请求查询交易编码响应"""
def OnRspQryInstrumentMarginRate(self, pInstrumentMarginRate, pRspInfo, nRequestID, bIsLast):
"""请求查询合约保证金率响应"""
def OnRspQryInstrumentCommissionRate(self, pInstrumentCommissionRate, pRspInfo, nRequestID, bIsLast):
"""请求查询合约手续费率响应"""
def OnRspQryExchange(self, pExchange, pRspInfo, nRequestID, bIsLast):
"""请求查询交易所响应"""
def OnRspQryProduct(self, pProduct, pRspInfo, nRequestID, bIsLast):
"""请求查询产品响应"""
def OnRspQryInstrument(self, pInstrument, pRspInfo, nRequestID, bIsLast):
"""请求查询合约响应"""
def OnRspQryDepthMarketData(self, pDepthMarketData, pRspInfo, nRequestID, bIsLast):
"""请求查询行情响应"""
def OnRspQrySettlementInfo(self, pSettlementInfo, pRspInfo, nRequestID, bIsLast):
"""请求查询投资者结算结果响应"""
def OnRspQryTransferBank(self, pTransferBank, pRspInfo, nRequestID, bIsLast):
"""请求查询转帐银行响应"""
def OnRspQryInvestorPositionDetail(self, pInvestorPositionDetail, pRspInfo, nRequestID, bIsLast):
"""请求查询投资者持仓明细响应"""
def OnRspQryNotice(self, pNotice, pRspInfo, nRequestID, bIsLast):
"""请求查询客户通知响应"""
def OnRspQrySettlementInfoConfirm(self, pSettlementInfoConfirm, pRspInfo, nRequestID, bIsLast):
"""请求查询结算信息确认响应"""
def OnRspQryInvestorPositionCombineDetail(self, pInvestorPositionCombineDetail, pRspInfo, nRequestID, bIsLast):
"""请求查询投资者持仓明细响应"""
def OnRspQryCFMMCTradingAccountKey(self, pCFMMCTradingAccountKey, pRspInfo, nRequestID, bIsLast):
"""查询保证金监管系统经纪公司资金账户密钥响应"""
def OnRspQryEWarrantOffset(self, pEWarrantOffset, pRspInfo, nRequestID, bIsLast):
"""请求查询仓单折抵信息响应"""
def OnRspQryInvestorProductGroupMargin(self, pInvestorProductGroupMargin, pRspInfo, nRequestID, bIsLast):
"""请求查询投资者品种/跨品种保证金响应"""
def OnRspQryExchangeMarginRate(self, pExchangeMarginRate, pRspInfo, nRequestID, bIsLast):
"""请求查询交易所保证金率响应"""
def OnRspQryExchangeMarginRateAdjust(self, pExchangeMarginRateAdjust, pRspInfo, nRequestID, bIsLast):
"""请求查询交易所调整保证金率响应"""
def OnRspQryExchangeRate(self, pExchangeRate, pRspInfo, nRequestID, bIsLast):
"""请求查询汇率响应"""
def OnRspQrySecAgentACIDMap(self, pSecAgentACIDMap, pRspInfo, nRequestID, bIsLast):
"""请求查询二级代理操作员银期权限响应"""
def OnRspQryProductExchRate(self, pProductExchRate, pRspInfo, nRequestID, bIsLast):
"""请求查询产品报价汇率"""
def OnRspQryOptionInstrTradeCost(self, pOptionInstrTradeCost, pRspInfo, nRequestID, bIsLast):
"""请求查询期权交易成本响应"""
def OnRspQryOptionInstrCommRate(self, pOptionInstrCommRate, pRspInfo, nRequestID, bIsLast):
"""请求查询期权合约手续费响应"""
def OnRspQryExecOrder(self, pExecOrder, pRspInfo, nRequestID, bIsLast):
"""请求查询执行宣告响应"""
def OnRspQryForQuote(self, pForQuote, pRspInfo, nRequestID, bIsLast):
"""请求查询询价响应"""
def OnRspQryQuote(self, pQuote, pRspInfo, nRequestID, bIsLast):
"""请求查询报价响应"""
def OnRspQryCombInstrumentGuard(self, pCombInstrumentGuard, pRspInfo, nRequestID, bIsLast):
"""请求查询组合合约安全系数响应"""
def OnRspQryCombAction(self, pCombAction, pRspInfo, nRequestID, bIsLast):
"""请求查询申请组合响应"""
def OnRspQryTransferSerial(self, pTransferSerial, pRspInfo, nRequestID, bIsLast):
"""请求查询转帐流水响应"""
def OnRspQryAccountregister(self, pAccountregister, pRspInfo, nRequestID, bIsLast):
"""请求查询银期签约关系响应"""
def OnRspError(self, pRspInfo, nRequestID, bIsLast):
"""错误应答"""
def OnRtnOrder(self, pOrder):
"""报单通知"""
def OnRtnTrade(self, pTrade):
"""成交通知"""
def OnErrRtnOrderInsert(self, pInputOrder, pRspInfo):
"""报单录入错误回报"""
def OnErrRtnOrderAction(self, pOrderAction, pRspInfo):
"""报单操作错误回报"""
def OnRtnInstrumentStatus(self, pInstrumentStatus):
"""合约交易状态通知"""
def OnRtnTradingNotice(self, pTradingNoticeInfo):
"""交易通知"""
def OnRtnErrorConditionalOrder(self, pErrorConditionalOrder):
"""提示条件单校验错误"""
def OnRtnExecOrder(self, pExecOrder):
"""执行宣告通知"""
def OnErrRtnExecOrderInsert(self, pInputExecOrder, pRspInfo):
"""执行宣告录入错误回报"""
def OnErrRtnExecOrderAction(self, pExecOrderAction, pRspInfo):
"""执行宣告操作错误回报"""
def OnErrRtnForQuoteInsert(self, pInputForQuote, pRspInfo):
"""询价录入错误回报"""
def OnRtnQuote(self, pQuote):
"""报价通知"""
def OnErrRtnQuoteInsert(self, pInputQuote, pRspInfo):
"""报价录入错误回报"""
def OnErrRtnQuoteAction(self, pQuoteAction, pRspInfo):
"""报价操作错误回报"""
def OnRtnForQuoteRsp(self, pForQuoteRsp):
"""询价通知"""
def OnRtnCFMMCTradingAccountToken(self, pCFMMCTradingAccountToken):
"""保证金监控中心用户令牌"""
def OnRtnCombAction(self, pCombAction):
"""申请组合通知"""
def OnErrRtnCombActionInsert(self, pInputCombAction, pRspInfo):
"""申请组合录入错误回报"""
def OnRspQryContractBank(self, pContractBank, pRspInfo, nRequestID, bIsLast):
"""请求查询签约银行响应"""
def OnRspQryParkedOrder(self, pParkedOrder, pRspInfo, nRequestID, bIsLast):
"""请求查询预埋单响应"""
def OnRspQryParkedOrderAction(self, pParkedOrderAction, pRspInfo, nRequestID, bIsLast):
"""请求查询预埋撤单响应"""
def OnRspQryTradingNotice(self, pTradingNotice, pRspInfo, nRequestID, bIsLast):
"""请求查询交易通知响应"""
def OnRspQryBrokerTradingParams(self, pBrokerTradingParams, pRspInfo, nRequestID, bIsLast):
"""请求查询经纪公司交易参数响应"""
def OnRspQryBrokerTradingAlgos(self, pBrokerTradingAlgos, pRspInfo, nRequestID, bIsLast):
"""请求查询经纪公司交易算法响应"""
def OnRspQueryCFMMCTradingAccountToken(self, pQueryCFMMCTradingAccountToken, pRspInfo, nRequestID, bIsLast):
"""请求查询监控中心用户令牌"""
def OnRtnFromBankToFutureByBank(self, pRspTransfer):
"""银行发起银行资金转期货通知"""
def OnRtnFromFutureToBankByBank(self, pRspTransfer):
"""银行发起期货资金转银行通知"""
def OnRtnRepealFromBankToFutureByBank(self, pRspRepeal):
"""银行发起冲正银行转期货通知"""
def OnRtnRepealFromFutureToBankByBank(self, pRspRepeal):
"""银行发起冲正期货转银行通知"""
def OnRtnFromBankToFutureByFuture(self, pRspTransfer):
"""期货发起银行资金转期货通知"""
def OnRtnFromFutureToBankByFuture(self, pRspTransfer):
"""期货发起期货资金转银行通知"""
def OnRtnRepealFromBankToFutureByFutureManual(self, pRspRepeal):
"""系统运行时期货端手工发起冲正银行转期货请求,银行处理完毕后报盘发回的通知"""
def OnRtnRepealFromFutureToBankByFutureManual(self, pRspRepeal):
"""系统运行时期货端手工发起冲正期货转银行请求,银行处理完毕后报盘发回的通知"""
def OnRtnQueryBankBalanceByFuture(self, pNotifyQueryAccount):
"""期货发起查询银行余额通知"""
def OnErrRtnBankToFutureByFuture(self, pReqTransfer, pRspInfo):
"""期货发起银行资金转期货错误回报"""
def OnErrRtnFutureToBankByFuture(self, pReqTransfer, pRspInfo):
"""期货发起期货资金转银行错误回报"""
def OnErrRtnRepealBankToFutureByFutureManual(self, pReqRepeal, pRspInfo):
"""系统运行时期货端手工发起冲正银行转期货错误回报"""
def OnErrRtnRepealFutureToBankByFutureManual(self, pReqRepeal, pRspInfo):
"""系统运行时期货端手工发起冲正期货转银行错误回报"""
def OnErrRtnQueryBankBalanceByFuture(self, pReqQueryAccount, pRspInfo):
"""期货发起查询银行余额错误回报"""
def OnRtnRepealFromBankToFutureByFuture(self, pRspRepeal):
"""期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知"""
def OnRtnRepealFromFutureToBankByFuture(self, pRspRepeal):
"""期货发起冲正期货转银行请求,银行处理完毕后报盘发回的通知"""
def OnRspFromBankToFutureByFuture(self, pReqTransfer, pRspInfo, nRequestID, bIsLast):
"""期货发起银行资金转期货应答"""
def OnRspFromFutureToBankByFuture(self, pReqTransfer, pRspInfo, nRequestID, bIsLast):
"""期货发起期货资金转银行应答"""
def OnRspQueryBankAccountMoneyByFuture(self, pReqQueryAccount, pRspInfo, nRequestID, bIsLast):
"""期货发起查询银行余额应答"""
def OnRtnOpenAccountByBank(self, pOpenAccount):
"""银行发起银期开户通知"""
def OnRtnCancelAccountByBank(self, pCancelAccount):
"""银行发起银期销户通知"""
def OnRtnChangeAccountByBank(self, pChangeAccount):
"""银行发起变更银行账号通知"""
def _init(Module, MdSpi, TraderSpi):
globals()['ApiStruct'] = __import__(__name__+'.ApiStruct', None, None, 'x')
class LazyProperty(object):
def __get__(self, obj, cls):
if obj is None: return self
value = self.fget()
name = self.fget.__name__
setattr(obj, name, value)
delattr(cls, name)
return value
def lazy_property(func):
self = LazyProperty()
setattr(Module, func.__name__, self)
self.fget = func
return self
@lazy_property
def MdApi():
from ._MdApi import _init, MdApi; _init(ApiStruct)
return type('MdApi', (MdApi,), MdSpi)
@lazy_property
def TraderApi():
from ._TraderApi import _init, TraderApi; _init(ApiStruct)
return type('TraderApi', (TraderApi,), TraderSpi)
def _init(init=_init, MdSpi=MdApi, TraderSpi=TraderApi):
import sys
from types import ModuleType, FunctionType as F
f = (lambda f:F(f.__code__,env)) if sys.version_info[0] >= 3 else (lambda f:F(f.func_code,env))
mod = sys.modules[__name__]; Module = type(mod)
if Module is ModuleType:
class Module(ModuleType): pass
mod = Module(__name__); env = mod.__dict__
env.update((k,v) for k,v in globals().items() if k.startswith('__') and k.endswith('__'))
MdSpi = dict((k,f(v)) for k,v in MdSpi.__dict__.items() if k.startswith('On'))
TraderSpi = dict((k,f(v)) for k,v in TraderSpi.__dict__.items() if k.startswith('On'))
sys.modules[__name__] = mod
else:
env = mod.__dict__
for k in ('MdApi','TraderApi','_init'): del env[k]
MdSpi = dict((k,v) for k,v in MdSpi.__dict__.items() if k.startswith('On'))
TraderSpi = dict((k,v) for k,v in TraderSpi.__dict__.items() if k.startswith('On'))
f(init)(Module, MdSpi, TraderSpi)
_init()
| 17,345 |
607 |
<filename>lib/include/timer/features/f4/Timer2GpioFeature.h<gh_stars>100-1000
/*
* This file is a part of the open source stm32plus library.
* Copyright (c) 2011 to 2014 <NAME> <www.andybrown.me.uk>
* Please see website for licensing terms.
*
* THIS IS AN AUTOMATICALLY GENERATED FILE - DO NOT EDIT!
*/
#pragma once
// ensure the MCU series is correct
#ifndef STM32PLUS_F4
#error This class can only be used with the STM32F4 series
#endif
namespace stm32plus {
struct TIM2_PinPackage_Remap_None {
typedef gpio::PA0 TIM2_ETR_Pin;
typedef gpio::PA0 TIM2_CH1_Pin;
typedef gpio::PA1 TIM2_CH2_Pin;
typedef gpio::PA2 TIM2_CH3_Pin;
typedef gpio::PA3 TIM2_CH4_Pin;
};
struct TIM2_PinPackage_Remap_Partial1 {
typedef gpio::PA15 TIM2_ETR_Pin;
typedef gpio::PA15 TIM2_CH1_Pin;
typedef gpio::PB3 TIM2_CH2_Pin;
typedef gpio::PA2 TIM2_CH3_Pin;
typedef gpio::PA3 TIM2_CH4_Pin;
};
struct TIM2_PinPackage_Remap_Partial2 {
typedef gpio::PA0 TIM2_ETR_Pin;
typedef gpio::PA0 TIM2_CH1_Pin;
typedef gpio::PA1 TIM2_CH2_Pin;
typedef gpio::PB10 TIM2_CH3_Pin;
typedef gpio::PB11 TIM2_CH4_Pin;
};
struct TIM2_PinPackage_Remap_Full {
typedef gpio::PA15 TIM2_ETR_Pin;
typedef gpio::PA15 TIM2_CH1_Pin;
typedef gpio::PB3 TIM2_CH2_Pin;
typedef gpio::PB10 TIM2_CH3_Pin;
typedef gpio::PB11 TIM2_CH4_Pin;
};
/**
* Initialise GPIO pins for this timer GPIO mode
* @tparam TPinPackage A type containing pin definitions for this timer feature
*/
template<typename TPinPackage>
struct TIM2_ETR {
TIM2_ETR() {
GpioPinInitialiser::initialise(
reinterpret_cast<GPIO_TypeDef *>(TPinPackage::TIM2_ETR_Pin::Port),
TPinPackage::TIM2_ETR_Pin::Pin,
Gpio::ALTERNATE_FUNCTION,
(GPIOSpeed_TypeDef)PeripheralTraits<PERIPHERAL_TIMER2>::GPIO_SPEED,
Gpio::PUPD_NONE,
Gpio::PUSH_PULL,
GpioAlternateFunctionMapper<PERIPHERAL_TIMER2,
TPinPackage::TIM2_ETR_Pin::Port,
TPinPackage::TIM2_ETR_Pin::Pin>::GPIO_AF);
}
};
/**
* Initialise GPIO pins for this timer GPIO mode
* @tparam TPinPackage A type containing pin definitions for this timer feature
*/
template<typename TPinPackage>
struct TIM2_CH1_IN {
TIM2_CH1_IN() {
GpioPinInitialiser::initialise(
reinterpret_cast<GPIO_TypeDef *>(TPinPackage::TIM2_CH1_Pin::Port),
TPinPackage::TIM2_CH1_Pin::Pin,
Gpio::ALTERNATE_FUNCTION,
(GPIOSpeed_TypeDef)PeripheralTraits<PERIPHERAL_TIMER2>::GPIO_SPEED,
Gpio::PUPD_NONE,
Gpio::PUSH_PULL,
GpioAlternateFunctionMapper<PERIPHERAL_TIMER2,
TPinPackage::TIM2_CH1_Pin::Port,
TPinPackage::TIM2_CH1_Pin::Pin>::GPIO_AF);
}
};
template<typename TPinPackage> using TIM2_CH1_OUT=TIM2_CH1_IN<TPinPackage>;
/**
* Initialise GPIO pins for this timer GPIO mode
* @tparam TPinPackage A type containing pin definitions for this timer feature
*/
template<typename TPinPackage>
struct TIM2_CH2_IN {
TIM2_CH2_IN() {
GpioPinInitialiser::initialise(
reinterpret_cast<GPIO_TypeDef *>(TPinPackage::TIM2_CH2_Pin::Port),
TPinPackage::TIM2_CH2_Pin::Pin,
Gpio::ALTERNATE_FUNCTION,
(GPIOSpeed_TypeDef)PeripheralTraits<PERIPHERAL_TIMER2>::GPIO_SPEED,
Gpio::PUPD_NONE,
Gpio::PUSH_PULL,
GpioAlternateFunctionMapper<PERIPHERAL_TIMER2,
TPinPackage::TIM2_CH2_Pin::Port,
TPinPackage::TIM2_CH2_Pin::Pin>::GPIO_AF);
}
};
template<typename TPinPackage> using TIM2_CH2_OUT=TIM2_CH2_IN<TPinPackage>;
/**
* Initialise GPIO pins for this timer GPIO mode
* @tparam TPinPackage A type containing pin definitions for this timer feature
*/
template<typename TPinPackage>
struct TIM2_CH3_IN {
TIM2_CH3_IN() {
GpioPinInitialiser::initialise(
reinterpret_cast<GPIO_TypeDef *>(TPinPackage::TIM2_CH3_Pin::Port),
TPinPackage::TIM2_CH3_Pin::Pin,
Gpio::ALTERNATE_FUNCTION,
(GPIOSpeed_TypeDef)PeripheralTraits<PERIPHERAL_TIMER2>::GPIO_SPEED,
Gpio::PUPD_NONE,
Gpio::PUSH_PULL,
GpioAlternateFunctionMapper<PERIPHERAL_TIMER2,
TPinPackage::TIM2_CH3_Pin::Port,
TPinPackage::TIM2_CH3_Pin::Pin>::GPIO_AF);
}
};
template<typename TPinPackage> using TIM2_CH3_OUT=TIM2_CH3_IN<TPinPackage>;
/**
* Initialise GPIO pins for this timer GPIO mode
* @tparam TPinPackage A type containing pin definitions for this timer feature
*/
template<typename TPinPackage>
struct TIM2_CH4_IN {
TIM2_CH4_IN() {
GpioPinInitialiser::initialise(
reinterpret_cast<GPIO_TypeDef *>(TPinPackage::TIM2_CH4_Pin::Port),
TPinPackage::TIM2_CH4_Pin::Pin,
Gpio::ALTERNATE_FUNCTION,
(GPIOSpeed_TypeDef)PeripheralTraits<PERIPHERAL_TIMER2>::GPIO_SPEED,
Gpio::PUPD_NONE,
Gpio::PUSH_PULL,
GpioAlternateFunctionMapper<PERIPHERAL_TIMER2,
TPinPackage::TIM2_CH4_Pin::Port,
TPinPackage::TIM2_CH4_Pin::Pin>::GPIO_AF);
}
};
template<typename TPinPackage> using TIM2_CH4_OUT=TIM2_CH4_IN<TPinPackage>;
/**
* Timer feature to enable any number of the GPIO alternate function outputs.
* All remap levels are supported. An example declaration could be:
*
* Timer2GpioFeature<TIMER_REMAP_NONE,TIM2_CH1_OUT>
*/
template<TimerGpioRemapLevel TRemapLevel,template<typename> class... Features>
struct Timer2GpioFeature;
template<template<typename> class... Features>
struct Timer2GpioFeature<TIMER_REMAP_NONE,Features...> : TimerFeatureBase,Features<TIM2_PinPackage_Remap_None>... {
Timer2GpioFeature(Timer& timer) : TimerFeatureBase(timer) {
}
};
template<template<typename> class... Features>
struct Timer2GpioFeature<TIMER_REMAP_PARTIAL1,Features...> : TimerFeatureBase,Features<TIM2_PinPackage_Remap_Partial1>... {
Timer2GpioFeature(Timer& timer) : TimerFeatureBase(timer) {
}
};
template<template<typename> class... Features>
struct Timer2GpioFeature<TIMER_REMAP_PARTIAL2,Features...> : TimerFeatureBase,Features<TIM2_PinPackage_Remap_Partial2>... {
Timer2GpioFeature(Timer& timer) : TimerFeatureBase(timer) {
}
};
template<template<typename> class... Features>
struct Timer2GpioFeature<TIMER_REMAP_FULL,Features...> : TimerFeatureBase,Features<TIM2_PinPackage_Remap_Full>... {
Timer2GpioFeature(Timer& timer) : TimerFeatureBase(timer) {
}
};
/**
* Custom structure to allow any pin mapping.
*
* e.g:
* Timer14CustomGpioFeature<TIM14_CH1_OUT<Myclass>>
* and in "MyClass" you would do a public declaration:
* typedef gpio::PF9 TIM14_CH1_Pin;
*/
template<class... Features>
struct Timer2CustomGpioFeature : TimerFeatureBase,Features... {
Timer2CustomGpioFeature(Timer& timer) : TimerFeatureBase(timer) {
}
};
}
| 3,158 |
411 |
"""Migration for the Submitty master database."""
import json
from pathlib import Path
def up(config, database, semester, course):
database.execute("CREATE TABLE IF NOT EXISTS queue(entry_id serial PRIMARY KEY, user_id VARCHAR(20) NOT NULL REFERENCES users(user_id), name VARCHAR (20) NOT NULL, time_in TIMESTAMP NOT NULL, time_helped TIMESTAMP, time_out TIMESTAMP, removed_by VARCHAR (20) REFERENCES users(user_id), status SMALLINT NOT NULL)");
database.execute("CREATE TABLE IF NOT EXISTS queue_settings(id serial PRIMARY KEY, open boolean NOT NULL, code VARCHAR (20) NOT NULL)");
course_dir = Path(config.submitty['submitty_data_dir'], 'courses', semester, course)
# add boolean to course config
config_file = Path(course_dir, 'config', 'config.json')
if config_file.is_file():
with open(config_file, 'r') as in_file:
j = json.load(in_file)
if 'queue_enabled' not in j['course_details']:
j['course_details']['queue_enabled'] = False
with open(config_file, 'w') as out_file:
json.dump(j, out_file, indent=4)
def down(config, database, semester, course):
pass
| 428 |
3,787 |
<filename>python/fate_flow/scheduling_apps/operation_app.py
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from flask import Flask, request
from fate_flow.entity.types import RetCode
from fate_flow.settings import stat_logger
from fate_flow.utils import job_utils
from fate_flow.utils.api_utils import get_json_result
from fate_arch.common import log, file_utils
manager = Flask(__name__)
@manager.errorhandler(500)
def internal_server_error(e):
stat_logger.exception(e)
return get_json_result(retcode=RetCode.EXCEPTION_ERROR, retmsg=log.exception_to_trace_string(e))
@manager.route('/job_config/get', methods=['POST'])
def get_config():
request_data = request.json
job_conf = job_utils.get_job_conf(request_data.get("job_id"), request_data.get("role"))
return get_json_result(retcode=0, retmsg='success', data=job_conf)
@manager.route('/json_conf/load', methods=['POST'])
def load_json_conf():
job_conf = file_utils.load_json_conf(request.json.get("config_path"))
return get_json_result(retcode=0, retmsg='success', data=job_conf)
| 531 |
373 |
/*-------------------------------------------------------------------------------
BARONY
File: menu.hpp
Desc: definitions and prototypes for menu.c
Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved.
See LICENSE for details.
-------------------------------------------------------------------------------*/
#pragma once
extern bool savethisgame;
// main menu code
void handleMainMenu(bool mode);
#define NUMSUBTITLES 30
extern int subtitleCurrent;
extern bool subtitleVisible;
extern Sint32 gearrot;
extern Sint32 gearsize;
extern Uint16 logoalpha;
extern int credittime;
extern int creditstage;
extern int intromovietime;
extern int intromoviestage;
extern int firstendmovietime;
extern int firstendmoviestage;
extern int secondendmovietime;
extern int secondendmoviestage;
extern int thirdendmoviestage;
extern int thirdendmovietime;
extern int fourthendmoviestage;
extern int fourthendmovietime;
extern int DLCendmovieStageAndTime[8][2];
enum NewMovieStageAndTimeIndex : int
{
MOVIE_STAGE,
MOVIE_TIME,
};
enum NewMovieCrawlTypes : int
{
MOVIE_MIDGAME_HERX_MONSTERS,
MOVIE_MIDGAME_BAPHOMET_MONSTERS,
MOVIE_MIDGAME_BAPHOMET_HUMAN_AUTOMATON,
MOVIE_CLASSIC_WIN_MONSTERS,
MOVIE_CLASSIC_WIN_BAPHOMET_MONSTERS,
MOVIE_WIN_AUTOMATON,
MOVIE_WIN_DEMONS_UNDEAD,
MOVIE_WIN_BEASTS
};
extern real_t drunkextend;
extern bool losingConnection[MAXPLAYERS];
extern int rebindaction;
// button definitions
void buttonQuitConfirm(button_t* my);
void buttonQuitNoSaveConfirm(button_t* my);
void buttonEndGameConfirm(button_t* my);
void buttonCloseAndEndGameConfirm(button_t* my);
void buttonCloseSubwindow(button_t* my);
void buttonContinue(button_t* my);
void buttonBack(button_t* my);
void buttonVideoTab(button_t* my);
void buttonAudioTab(button_t* my);
void buttonKeyboardTab(button_t* my);
void buttonMouseTab(button_t* my);
void buttonGamepadBindingsTab(button_t* my);
void buttonGamepadSettingsTab(button_t* my);
void buttonMiscTab(button_t* my);
void buttonSettingsAccept(button_t* my);
void buttonSettingsOK(button_t* my);
void buttonStartSingleplayer(button_t* my);
void buttonStartServer(button_t* my);
void buttonHostMultiplayer(button_t* my);
void buttonJoinMultiplayer(button_t* my);
void buttonHostLobby(button_t* my);
void buttonJoinLobby(button_t* my);
void buttonDisconnect(button_t* my);
void buttonScoreNext(button_t* my);
void buttonScorePrev(button_t* my);
void buttonScoreToggle(button_t* my);
void buttonDeleteCurrentScore(button_t* my);
void buttonOpenCharacterCreationWindow(button_t* my);
void buttonDeleteSavedSoloGame(button_t* my);
void buttonDeleteSavedMultiplayerGame(button_t* my);
void buttonConfirmDeleteSoloFile(button_t* my);
void buttonConfirmDeleteMultiplayerFile(button_t* my);
void buttonLoadSingleplayerGame(button_t* my);
void buttonLoadMultiplayerGame(button_t* my);
void buttonRandomCharacter(button_t* my);
void buttonReplayLastCharacter(button_t* my);
void buttonDeleteScoreWindow(button_t* my);
void buttonOpenScoresWindow(button_t* my);
void buttonRandomName(button_t* my);
void buttonGamemodsOpenDirectory(button_t* my);
void buttonGamemodsPrevDirectory(button_t* my);
void buttonGamemodsBaseDirectory(button_t* my);
void buttonGamemodsSelectDirectoryForUpload(button_t* my);
void buttonGamemodsOpenModifyExistingWindow(button_t* my);
void buttonGamemodsStartModdedGame(button_t* my);
void buttonInviteFriends(button_t* my);
#ifdef STEAMWORKS
void buttonGamemodsPrepareWorkshopItemUpload(button_t* my);
void buttonGamemodsSetWorkshopItemFields(button_t* my);
void buttonGamemodsStartUploadItem(button_t* my);
void buttonGamemodsGetSubscribedItems(button_t* my);
void buttonGamemodsOpenSubscribedWindow(button_t* my);
void buttonGamemodsOpenUploadWindow(button_t* my);
void buttonGamemodsGetMyWorkshopItems(button_t* my);
void buttonGamemodsModifyExistingWorkshopItemFields(button_t* my);
void buttonGamemodsCancelModifyFileContents(button_t* my);
void buttonSteamLobbyBrowserJoinGame(button_t* my);
void buttonSteamLobbyBrowserRefresh(button_t* my);
void buttonGamemodsSubscribeToHostsModFiles(button_t* my);
void buttonGamemodsMountHostsModFiles(button_t* my);
void* cpp_SteamMatchmaking_GetLobbyOwner(void* steamIDLobby);
void* cpp_SteamMatchmaking_GetLobbyMember(void* steamIDLobby, int index);
void openSteamLobbyWaitWindow(button_t* my);
#elif defined USE_EOS
void buttonSteamLobbyBrowserJoinGame(button_t* my);
void buttonSteamLobbyBrowserRefresh(button_t* my);
void openSteamLobbyWaitWindow(button_t* my);
#else
void windowEnterSerialPrompt();
void windowSerialResult(int success);
size_t serialHash(std::string input);
extern char serialInputText[64];
#endif
#define SLIDERFONT font12x12_bmp
// achievement window
void openAchievementsWindow();
void closeAchievementsWindow(button_t*);
extern bool achievements_window;
extern int achievements_window_page;
void buttonAchievementsUp(button_t* my);
void buttonAchievementsDown(button_t* my);
// misc functions
void openSettingsWindow();
void openFailedConnectionWindow(int mode);
void openGameoverWindow();
void openSteamLobbyBrowserWindow(button_t* my);
void openLoadGameWindow(button_t* my);
void openNewLoadGameWindow(button_t* my);
void reloadSavegamesList(bool showWindow = true);
void doSlider(int x, int y, int dots, int minvalue, int maxvalue, int increment, int* var, SDL_Surface* slider_font = SLIDERFONT, int slider_font_char_width = 16);
void doSliderF(int x, int y, int dots, real_t minvalue, real_t maxvalue, real_t increment, real_t* var);
// menu variables
extern bool settings_window;
extern int charcreation_step;
extern int loadGameSaveShowRectangle;
extern Uint32 charcreation_ticks;
extern bool playing_random_char;
extern int settings_tab;
extern int connect_window;
extern bool lobby_window;
extern int score_window;
extern Uint32 lobbyWindowSvFlags;
// gamemods window stuff
extern int gamemods_window;
extern int gamemods_window_scroll;
extern int gamemods_window_fileSelect;
extern int gamemods_uploadStatus;
extern int gamemods_numCurrentModsLoaded;
extern std::list<std::string> currentDirectoryFiles;
extern std::string directoryPath;
void gamemodsWindowClearVariables();
void gamemodsCustomContentInit();
bool gamemodsDrawClickableButton(int padx, int pady, int padw, int padh, Uint32 btnColor, std::string btnText, int action);
bool gamemodsRemovePathFromMountedFiles(std::string findStr);
bool gamemodsIsPathInMountedFiles(std::string findStr);
bool gamemodsClearAllMountedPaths();
bool gamemodsMountAllExistingPaths();
extern bool gamemods_disableSteamAchievements;
extern std::vector<std::pair<std::string, std::string>> gamemods_mountedFilepaths;
extern bool gamemods_modelsListRequiresReload;
extern bool gamemods_soundListRequiresReload;
extern bool gamemods_modPreload;
#ifdef STEAMWORKS
void gamemodsWorkshopPreloadMod(int fileID, std::string modTitle);
void gamemodsWindowUploadInit(bool creatingNewItem);
void gamemodsSubscribedItemsInit();
void gamemodsDrawWorkshopItemTagToggle(std::string tagname, int x, int y);
bool gamemodsCheckIfSubscribedAndDownloadedFileID(uint64 fileID);
bool gamemodsCheckFileIDInLoadedPaths(uint64 fileID);
bool gamemodsIsClientLoadOrderMatchingHost(std::vector<std::string> serverModList);
extern std::vector<std::pair<std::string, uint64>> gamemods_workshopLoadedFileIDMap;
extern std::unordered_set<uint64> betaPlayers;
#endif // STEAMWORKS
bool drawClickableButton(int padx, int pady, int padw, int padh, Uint32 btnColor);
extern bool scoreDisplayMultiplayer;
extern std::vector<std::tuple<int, int, int, std::string>> savegamesList; // tuple - last modified, multiplayer type, file entry, and description of save game.
extern Sint32 slidery, slidersize, oslidery;
// settings window
extern Uint32 settings_fov;
extern Uint32 settings_fps;
extern int settings_xres, settings_yres;
extern bool settings_smoothlighting;
extern int settings_fullscreen, settings_shaking, settings_bobbing;
extern bool settings_borderless;
extern real_t settings_gamma;
extern int settings_sfxvolume, settings_musvolume;
extern int settings_sfxAmbientVolume;
extern int settings_sfxEnvironmentVolume;
extern int settings_impulses[NUMIMPULSES];
extern int settings_reversemouse;
extern bool settings_smoothmouse;
extern bool settings_disablemouserotationlimit;
extern real_t settings_mousespeed;
extern bool settings_broadcast;
extern bool settings_nohud;
extern bool settings_colorblind;
extern bool settings_spawn_blood;
extern bool settings_light_flicker;
extern bool settings_vsync;
extern bool settings_status_effect_icons;
extern bool settings_minimap_ping_mute;
extern bool settings_mute_audio_on_focus_lost;
extern bool settings_mute_player_monster_sounds;
extern int settings_minimap_transparency_foreground;
extern int settings_minimap_transparency_background;
extern int settings_minimap_scale;
extern int settings_minimap_object_zoom;
extern char portnumber_char[6];
extern char connectaddress[64];
extern bool smoothmouse;
extern bool usecamerasmoothing;
extern bool disablemouserotationlimit;
extern bool broadcast;
extern bool nohud;
extern int menuselect;
extern bool colorblind;
extern bool right_click_protect;
extern bool settings_auto_hotbar_new_items;
extern bool settings_auto_hotbar_categories[NUM_HOTBAR_CATEGORIES];
extern int settings_autosort_inventory_categories[NUM_AUTOSORT_CATEGORIES];
extern bool settings_hotbar_numkey_quick_add;
extern bool settings_disable_messages;
extern bool settings_right_click_protect;
extern bool settings_auto_appraise_new_items;
extern bool settings_lock_right_sidebar;
extern bool settings_show_game_timer_always;
extern bool settings_uiscale_charactersheet;
extern bool settings_uiscale_skillspage;
extern real_t settings_uiscale_hotbar;
extern real_t settings_uiscale_playerbars;
extern real_t settings_uiscale_chatlog;
extern real_t settings_uiscale_inventory;
extern bool settings_hide_statusbar;
extern bool settings_hide_playertags;
extern bool settings_show_skill_values;
extern bool settings_disableMultithreadedSteamNetworking;
extern bool settings_disableFPSLimitOnNetworkMessages;
static const int NUM_SETTINGS_TABS = 7;
static const int SETTINGS_VIDEO_TAB = 0;
static const int SETTINGS_AUDIO_TAB = 1;
static const int SETTINGS_KEYBOARD_TAB = 2;
static const int SETTINGS_MOUSE_TAB = 3;
static const int SETTINGS_GAMEPAD_BINDINGS_TAB = 4;
static const int SETTINGS_GAMEPAD_SETTINGS_TAB = 5;
static const int SETTINGS_MISC_TAB = 6;
//Confirm resolution window stuff.
extern bool resolutionChanged;
extern bool confirmResolutionWindow;
extern int resolutionConfirmationTimer;
static const int RESOLUTION_CONFIRMATION_TIME = 10000; //Time in milliseconds before resolution reverts.
extern Sint32 oldXres;
extern Sint32 oldYres;
extern button_t* revertResolutionButton;
void applySettings();
void openConfirmResolutionWindow();
void buttonAcceptResolution(button_t* my);
void buttonRevertResolution(button_t* my);
void revertResolution();
extern std::vector<std::pair<std::string, int>> menuOptions;
void initMenuOptions();
| 3,554 |
380 |
#include "mex.h"
#include <stdlib.h>
#include <stdio.h>
/**
* Return the decision tree node corresponding to the given value set
*
* var[n]: the attribute ids for node n
* cut[n]: the threshold value for node n
* left_child[n]: the node id of the left child of node n, 0 if node n is terminal
* right_child[n]: the node id of the right child of node n, 0 if node n is terminal
* ncatsplit[c]: the number of values resulting in a left branch
* catsplit[c]: the values that would result in a left branch
* attributes: the attribute (variable) values for each feature
**/
void
treevalc(int* var, double* cut, int* left_child, int* right_child,
int* ncatsplit, double** catsplit,
double* attributes,
int* node_id) {
int currnode = 0;
int nextnode;
int currvar;
double currval;
int cid, v;
int numvals;
double* vals;
/* printf("init nodes: %d %d \n", left_child[currnode], right_child[currnode]); */
/* until reached terminal node */
while ((left_child[currnode] != 0) && (right_child[currnode] != 0)) {
/*printf("currnode: %d\n", currnode);*/
nextnode = -1;
currvar = abs(var[currnode])-1;
currval = attributes[currvar];
/* decision based on thresholded float value */
if (var[currnode] > 0) {
/*printf("currvar: %d\n", currvar);*/
/* branch left */
if (currval < cut[currnode]) {
nextnode = left_child[currnode];
}
/* branch right */
else {
nextnode = right_child[currnode];
}
}
/* decision based on discrete value */
else {
numvals = ncatsplit[(int)cut[currnode]-1];
vals = catsplit[(int)cut[currnode]-1];
for (v = 0; v < numvals; v++) {
if (currval == vals[v]) {
nextnode = left_child[currnode];
break;
}
}
if (nextnode == -1) {
nextnode = right_child[currnode];
}
}
currnode = nextnode-1;
/* printf("curr node: %d \n", currnode);*/
}
*node_id = currnode+1;
}
/**
* plhs = {var, cut, left_child, right_child, catsplit(cell array), attributes(numatt, numdata)}
*
*/
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int *var, *left_child, *right_child, *left_chil, *ncatsplit, n, nsplits,numatt, numdata, tmp_id;
double *cut, **catsplit, *all_attributes, *node_ids;
if (nrhs != 6) {
printf("Error: wrong number of input arguments: %d.\n", nlhs);
printf("Syntax: node_ids = treevalc(var, cut, left_child, right_child, catsplit, attributes)\n");
}
var = (int*)mxGetPr(prhs[0]);
cut = mxGetPr(prhs[1]);
left_child = (int*)mxGetPr(prhs[2]);
right_child = (int*)mxGetPr(prhs[3]);
/* get catsplit variables */
nsplits = mxGetNumberOfElements(prhs[4]);
ncatsplit = malloc(sizeof(int) * nsplits);
catsplit = malloc(sizeof(double*) * nsplits);
n = 0;
for (n = 0; n < nsplits; n++) {
mxArray* catsplit_cell_mx = mxGetCell(prhs[4], n);
if (catsplit_cell_mx == 0) {
printf("null cell");
}
ncatsplit[n] = mxGetNumberOfElements(catsplit_cell_mx);
catsplit[n] = (double*)mxGetPr(catsplit_cell_mx);
}
numatt = mxGetM(prhs[5]);
numdata = mxGetN(prhs[5]);
/* printf("num data = %d num att = %d\n", numdata, numatt);*/
all_attributes = mxGetPr(prhs[5]);
plhs[0] = mxCreateDoubleMatrix(numdata, 1, mxREAL);
node_ids = mxGetPr(plhs[0]);
tmp_id;
for (n = 0; n < numdata; n++) {
treevalc(var, cut, left_child, right_child, ncatsplit, catsplit,
&all_attributes[numatt*n], &tmp_id);
node_ids[n] = (double)(tmp_id);
/* printf("final node id: %d\n", tmp_id); */
}
free(catsplit);
free(ncatsplit);
}
| 1,583 |
22,688 |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
* @brief This file provides the declaration of the class `NavigationLane`.
*/
#pragma once
#include <list>
#include <memory>
#include <tuple>
#include <unordered_map>
#include <utility>
#include "modules/common/vehicle_state/proto/vehicle_state.pb.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/localization/proto/localization.pb.h"
#include "modules/map/relative_map/proto/navigation.pb.h"
#include "modules/map/relative_map/proto/relative_map_config.pb.h"
#include "modules/perception/proto/perception_obstacle.pb.h"
/**
* @namespace apollo::relative_map
* @brief apollo::relative_map
*/
namespace apollo {
namespace relative_map {
// A navigation path tuple.
//
// first element: original navigation line index of the current navigation path.
// A negative value indicates illegal.
//
// second element: half of the lateral distance to the left adjacent navigation
// path, that is, the left width of the lane generated by this navigation path.
// If the navigation path is generated based on lane markers, the value is the
// perceived left lane width. If there is no left adjacent navigation path, the
// value is "default_left_width_". A negative value indicates illegal.
//
// third element: half of the lateral distance to the right adjacent navigation
// path, that is, the right width of the lane generated by this navigation path.
// If the navigation path is generated based on lane markers, the value is the
// perceived right lane width. If there is no right adjacent navigation path,
// the value is "default_right_width_". A negative value indicates illegal.
//
// fourth element : a shared pointer of the current navigation path.
typedef std::tuple<int, double, double, std::shared_ptr<NavigationPath>>
NaviPathTuple;
// A stitching index pair.
// pair.first: the start stitching index of the current navigation line.
// pair.second: the end stitching index of the current navigation line.
typedef std::pair<int, int> StitchIndexPair;
// A projection index pair.
// pair.first: projection index of the vehicle in the current navigation line.
// pair.second: the distance between the vehicle's initial position and the
// projection position in the current navigation line.
typedef std::pair<int, double> ProjIndexPair;
/**
* @class NavigationLane
* @brief NavigationLane generates a real-time relative map based on navagation
* lines.
*
* First, several navigation lines are received from the `NavigationInfo`
* object;
*
* Second, several navigation line segments with the length of about 250 m are
* cut from the whole navigation lines and the UTM coordinates are converted
* into local coordinates with the current position of the vehicle as the
* origin;
*
* Third, the navigation line segment of the vehicle's current lane is merged
* with the perceived lane centerline.
*
* Fourth, a real-time relative map is dynamically created based on navigation
* line segments and perceived lane width;
*
* Fifth, the relative map is output as a `MapMsg` object pointer.
*/
class NavigationLane {
public:
NavigationLane() = default;
explicit NavigationLane(const NavigationLaneConfig& config);
~NavigationLane() = default;
/**
* @brief Set the configuration information required by the `NavigationLane`.
* @param config Configuration object.
* @return None.
*/
void SetConfig(const NavigationLaneConfig& config);
void SetVehicleStateProvider(
common::VehicleStateProvider* vehicle_state_provider);
/**
* @brief Update navigation line information.
* @param navigation_info Navigation line information to be updated.
* @return None.
*/
void UpdateNavigationInfo(const NavigationInfo& navigation_info);
/**
* @brief Set the default width of a lane.
* @param left_width Left half width of a lane.
* @param right_width Right half width of a lane.
* @return None.
*/
void SetDefaultWidth(const double left_width, const double right_width) {
default_left_width_ = left_width;
default_right_width_ = right_width;
}
/**
* @brief Generate a suitable path (i.e. a navigation line segment).
* @param
* @return True if a suitable path is created; false otherwise.
*/
bool GeneratePath();
/**
* @brief Update perceived lane line information.
* @param perception_obstacles Perceived lane line information to be updated.
* @return None.
*/
void UpdatePerception(
const perception::PerceptionObstacles& perception_obstacles) {
perception_obstacles_ = perception_obstacles;
}
/**
* @brief Get the generated lane segment where the vehicle is currently
* located.
* @param
* @return The generated lane segment where the vehicle is currently located.
*/
NavigationPath Path() const {
const auto& current_navi_path = std::get<3>(current_navi_path_tuple_);
if (current_navi_path) {
return *current_navi_path;
}
return NavigationPath();
}
/**
* @brief Generate a real-time relative map of approximately 250 m in length
* based on several navigation line segments and map generation configuration
* information.
* @param map_config Map generation configuration information.
* @param map_msg A pointer which outputs the real-time relative map.
* @return True if the real-time relative map is created; false otherwise.
*/
bool CreateMap(const MapGenerationParam& map_config,
MapMsg* const map_msg) const;
private:
/**
* @brief Calculate the value of a cubic polynomial according to the given
* coefficients and an independent variable.
* @param c0 Cubic polynomial coefficient.
* @param c1 Cubic polynomial coefficient.
* @param c2 Cubic polynomial coefficient.
* @param c3 Cubic polynomial coefficient.
* @param x Independent variable.
* @return Calculated value of the cubic polynomial.
*/
double EvaluateCubicPolynomial(const double c0, const double c1,
const double c2, const double c3,
const double x) const;
/**
* @brief Calculate the curvature value based on the cubic polynomial's
* coefficients and an independent variable.
* @param c1 Cubic polynomial coefficient.
* @param c2 Cubic polynomial coefficient.
* @param c3 Cubic polynomial coefficient.
* @param x Independent variable.
* @return Calculated curvature value.
*/
double GetKappa(const double c1, const double c2, const double c3,
const double x);
/**
* @brief In a navigation line segment, starting from the point given by
* `start_index`, the matched point after the distance `s` is calculated, and
* the index of the matched point is given.
* @param path The specific navigation line segment.
* @param start_index The index of the starting point.
* @param s The distance from the starting point.
* @param matched_index The pointer storing the index of the matched point.
* @return The matched point after the distance `s`.
*/
common::PathPoint GetPathPointByS(const common::Path& path,
const int start_index, const double s,
int* const matched_index);
/**
* @brief Generate a lane centerline from the perceived lane markings and
* convert it to a navigation line segment.
* @param lane_marker The perceived lane markings.
* @param path The converted navigation line segment.
* @return None.
*/
void ConvertLaneMarkerToPath(const perception::LaneMarkers& lane_marker,
common::Path* const path);
/**
* @brief A navigation line segment with the length of about 250 m are cut
* from the whole navigation lines and the UTM coordinates are converted
* into local coordinates with the current position of the vehicle as the
* origin.
* @param line_index The index of the navigation line segment vector.
* @param path The converted navigation line segment.
* @return True if a suitable path is created; false otherwise.
*/
bool ConvertNavigationLineToPath(const int line_index,
common::Path* const path);
/**
* @brief Merge the navigation line segment of the vehicle's current lane and
* the perceived lane centerline.
* @param line_index The index of the navigation line segment vector.
* @param path The merged navigation line segment.
* @return None.
*/
void MergeNavigationLineAndLaneMarker(const int line_index,
common::Path* const path);
/**
* @brief Update the index of the vehicle's current location in an entire
* navigation line.
* @param path The entire navigation line. Note that the path here refers to
* the entire navigation line stored in UTM coordinates.
* @param line_index The index of the whole navigation line vector stored in a
* `NavigationInfo` object.
* @return Updated projection index pair.
*/
ProjIndexPair UpdateProjectionIndex(const common::Path& path,
const int line_index);
/**
* @brief If an entire navigation line is a cyclic/circular
* route, the closest matching point at the starting and end positions is
* recorded so that the vehicle can drive cyclically.
* @param
* @return None.
*/
void UpdateStitchIndexInfo();
private:
// the configuration information required by the `NavigationLane`
NavigationLaneConfig config_;
// received from topic: /apollo/perception_obstacles
perception::PerceptionObstacles perception_obstacles_;
// received from topic: /apollo/navigation
NavigationInfo navigation_info_;
// navigation_path_list_ is a list of navigation paths. The internal paths
// are arranged from left to right based on the vehicle's driving direction.
// A navigation path is the combined results from perception and navigation.
std::list<NaviPathTuple> navigation_path_list_;
// the navigation path which the vehicle is currently on.
NaviPathTuple current_navi_path_tuple_;
// when invalid, left_width_ < 0
double perceived_left_width_ = -1.0;
// when invalid, right_width_ < 0
double perceived_right_width_ = -1.0;
// The standard lane width of China's expressway is 3.75 meters.
double default_left_width_ = 1.875;
double default_right_width_ = 1.875;
// key: line index,
// value: last projection index pair in the "key" line.
std::unordered_map<int, ProjIndexPair> last_project_index_map_;
// key: line index,
// value: stitching index pair in the "key" line.
std::unordered_map<int, StitchIndexPair> stitch_index_map_;
// in world coordination: ENU
localization::Pose original_pose_;
common::VehicleStateProvider* vehicle_state_provider_ = nullptr;
};
} // namespace relative_map
} // namespace apollo
| 3,486 |
6,304 |
// Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "tools/fiddle/examples.h"
// HASH=c204b38b3fc08914b0a634aa4eaec894
REG_FIDDLE(Image_bounds, 256, 128, false, 4) {
void draw(SkCanvas* canvas) {
SkIRect bounds = image->bounds();
for (int x : { 0, bounds.width() } ) {
for (int y : { 0, bounds.height() } ) {
canvas->drawImage(image, x, y);
}
}
}
} // END FIDDLE
| 209 |
348 |
{"nom":"Roissy-en-Brie","circ":"8ème circonscription","dpt":"Seine-et-Marne","inscrits":13139,"abs":7637,"votants":5502,"blancs":97,"nuls":46,"exp":5359,"res":[{"nuance":"REM","nom":"<NAME>","voix":2052},{"nuance":"FI","nom":"Mme <NAME>","voix":819},{"nuance":"LR","nom":"Mme <NAME>","voix":650},{"nuance":"FN","nom":"Mme <NAME>","voix":637},{"nuance":"SOC","nom":"<NAME>","voix":449},{"nuance":"COM","nom":"Mme <NAME>","voix":285},{"nuance":"ECO","nom":"Mme <NAME>","voix":217},{"nuance":"DLF","nom":"Mme <NAME>","voix":124},{"nuance":"DIV","nom":"<NAME>","voix":79},{"nuance":"EXG","nom":"<NAME>","voix":47},{"nuance":"DIV","nom":"M. <NAME>","voix":0}]}
| 266 |
327 |
<reponame>zhuhuaiyu/pg_travel
import numpy as np
from utils.utils import *
from hparams import HyperParams as hp
from model import Actor
def get_gae(rewards, masks, values):
rewards = torch.Tensor(rewards)
masks = torch.Tensor(masks)
returns = torch.zeros_like(rewards)
advants = torch.zeros_like(rewards)
running_returns = 0
previous_value = 0
running_advants = 0
for t in reversed(range(0, len(rewards))):
running_returns = rewards[t] + hp.gamma * running_returns * masks[t]
running_tderror = rewards[t] + hp.gamma * previous_value * masks[t] - \
values.data[t]
running_advants = running_tderror + hp.gamma * hp.lamda * \
running_advants * masks[t]
returns[t] = running_returns
previous_value = values.data[t]
advants[t] = running_advants
advants = (advants - advants.mean()) / advants.std()
return returns, advants
def surrogate_loss(actor, advants, states, old_policy, actions):
mu, std, logstd = actor(torch.Tensor(states))
new_policy = log_density(torch.Tensor(actions), mu, std, logstd)
advants = advants.unsqueeze(1)
surrogate = advants * torch.exp(new_policy - old_policy)
surrogate = surrogate.mean()
return surrogate
def train_critic(critic, states, returns, advants, critic_optim):
criterion = torch.nn.MSELoss()
n = len(states)
arr = np.arange(n)
for epoch in range(5):
np.random.shuffle(arr)
for i in range(n // hp.batch_size):
batch_index = arr[hp.batch_size * i: hp.batch_size * (i + 1)]
batch_index = torch.LongTensor(batch_index)
inputs = torch.Tensor(states)[batch_index]
target1 = returns.unsqueeze(1)[batch_index]
target2 = advants.unsqueeze(1)[batch_index]
values = critic(inputs)
loss = criterion(values, target1 + target2)
critic_optim.zero_grad()
loss.backward()
critic_optim.step()
def fisher_vector_product(actor, states, p):
p.detach()
kl = kl_divergence(new_actor=actor, old_actor=actor, states=states)
kl = kl.mean()
kl_grad = torch.autograd.grad(kl, actor.parameters(), create_graph=True)
kl_grad = flat_grad(kl_grad) # check kl_grad == 0
kl_grad_p = (kl_grad * p).sum()
kl_hessian_p = torch.autograd.grad(kl_grad_p, actor.parameters())
kl_hessian_p = flat_hessian(kl_hessian_p)
return kl_hessian_p + 0.1 * p
# from openai baseline code
# https://github.com/openai/baselines/blob/master/baselines/common/cg.py
def conjugate_gradient(actor, states, b, nsteps, residual_tol=1e-10):
x = torch.zeros(b.size())
r = b.clone()
p = b.clone()
rdotr = torch.dot(r, r)
for i in range(nsteps):
_Avp = fisher_vector_product(actor, states, p)
alpha = rdotr / torch.dot(p, _Avp)
x += alpha * p
r -= alpha * _Avp
new_rdotr = torch.dot(r, r)
betta = new_rdotr / rdotr
p = r + betta * p
rdotr = new_rdotr
if rdotr < residual_tol:
break
return x
def train_model(actor, critic, memory, actor_optim, critic_optim):
memory = np.array(memory)
states = np.vstack(memory[:, 0])
actions = list(memory[:, 1])
rewards = list(memory[:, 2])
masks = list(memory[:, 3])
values = critic(torch.Tensor(states))
# ----------------------------
# step 1: get returns and GAEs
returns, advants = get_gae(rewards, masks, values)
# ----------------------------
# step 2: train critic several steps with respect to returns
train_critic(critic, states, returns, advants, critic_optim)
# ----------------------------
# step 3: get gradient of loss and hessian of kl
mu, std, logstd = actor(torch.Tensor(states))
old_policy = log_density(torch.Tensor(actions), mu, std, logstd)
loss = surrogate_loss(actor, advants, states, old_policy.detach(), actions)
loss_grad = torch.autograd.grad(loss, actor.parameters())
loss_grad = flat_grad(loss_grad)
step_dir = conjugate_gradient(actor, states, loss_grad.data, nsteps=10)
# ----------------------------
# step 4: get step direction and step size and full step
params = flat_params(actor)
shs = 0.5 * (step_dir * fisher_vector_product(actor, states, step_dir)
).sum(0, keepdim=True)
step_size = 1 / torch.sqrt(shs / hp.max_kl)[0]
full_step = step_size * step_dir
# ----------------------------
# step 5: do backtracking line search for n times
old_actor = Actor(actor.num_inputs, actor.num_outputs)
update_model(old_actor, params)
expected_improve = (loss_grad * full_step).sum(0, keepdim=True)
flag = False
fraction = 1.0
for i in range(10):
new_params = params + fraction * full_step
update_model(actor, new_params)
new_loss = surrogate_loss(actor, advants, states, old_policy.detach(),
actions)
loss_improve = new_loss - loss
expected_improve *= fraction
kl = kl_divergence(new_actor=actor, old_actor=old_actor, states=states)
kl = kl.mean()
print('kl: {:.4f} loss improve: {:.4f} expected improve: {:.4f} '
'number of line search: {}'
.format(kl.data.numpy(), loss_improve, expected_improve[0], i))
# see https: // en.wikipedia.org / wiki / Backtracking_line_search
if kl < hp.max_kl and (loss_improve / expected_improve) > 0.5:
flag = True
break
fraction *= 0.5
if not flag:
params = flat_params(old_actor)
update_model(actor, params)
print('policy update does not impove the surrogate')
| 2,461 |
441 |
package com.alibaba.markovdemo.engine.stages;
public class RunQueryTemplate {
private String label;
private String dataId;
private String groupId;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public RunQueryTemplate(String label, String dataId, String groupId) {
super();
this.label = label;
this.dataId = dataId;
this.groupId = groupId;
}
}
| 327 |
1,290 |
<reponame>dfirpaul/Active-Directory-Exploitation-Cheat-Sheet-1<gh_stars>1000+
import fnmatch
import os
import subprocess
import re
import string
from lazagne.config.module_info import ModuleInfo
class IISAppPool(ModuleInfo):
def __init__(self):
ModuleInfo.__init__(self, name='iisapppool', category='sysadmin', registry_used=True, winapi_used=True)
def find_files(self, path, file):
"""
Try to find all files with the same name
"""
founded_files = []
for dirpath, dirnames, files in os.walk(path):
for file_name in files:
if fnmatch.fnmatch(file_name, file):
founded_files.append(dirpath + '\\' + file_name)
return founded_files
def execute_get_stdout(self, exe_file, arguments):
try:
proc = subprocess.Popen(exe_file + " " + arguments, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except:
self.debug(u'Error executing {exefile}'.format(exefile=exe_file))
return None
return proc.stdout
def run(self):
pfound = []
exe_files = self.find_files(os.environ['WINDIR'] + '\\System32\\inetsrv', 'appcmd.exe')
if len(exe_files) == 0:
self.debug(u'File not found appcmd.exe')
return
self.info(u'appcmd.exe files found: {files}'.format(files=exe_files))
output = self.execute_get_stdout(exe_files[-1], 'list apppool')
if output == None:
self.debug(u'Problems with Application Pool list')
return
app_list = []
for line in output.readlines():
app_list.append(re.findall(r'".*"', line)[0].split('"')[1])
for app in app_list:
values = {}
username = ''
password = ''
output = self.execute_get_stdout(exe_files[-1], 'list apppool ' + app + ' /text:*')
for line in output.readlines():
if re.search(r'userName:".*"', line):
username = re.findall(r'userName:".*"', line)[0].split('"')[1]
if re.search(r'password:".*"', line):
password = re.findall(r'password:".*"', line)[0].split('"')[1]
if password != '' :
values['AppPool.Name'] = app
values['Username'] = username
values['Password'] = password
pfound.append(values)
return pfound
| 1,225 |
2,338 |
<filename>clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp
//===--- SuspiciousIncludeCheck.cpp - clang-tidy --------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "SuspiciousIncludeCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/Preprocessor.h"
namespace clang {
namespace tidy {
namespace bugprone {
namespace {
class SuspiciousIncludePPCallbacks : public PPCallbacks {
public:
explicit SuspiciousIncludePPCallbacks(SuspiciousIncludeCheck &Check,
const SourceManager &SM,
Preprocessor *PP)
: Check(Check), PP(PP) {}
void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange, const FileEntry *File,
StringRef SearchPath, StringRef RelativePath,
const Module *Imported,
SrcMgr::CharacteristicKind FileType) override;
private:
SuspiciousIncludeCheck &Check;
Preprocessor *PP;
};
} // namespace
SuspiciousIncludeCheck::SuspiciousIncludeCheck(StringRef Name,
ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
RawStringHeaderFileExtensions(Options.getLocalOrGlobal(
"HeaderFileExtensions", utils::defaultHeaderFileExtensions())),
RawStringImplementationFileExtensions(Options.getLocalOrGlobal(
"ImplementationFileExtensions",
utils::defaultImplementationFileExtensions())) {
if (!utils::parseFileExtensions(RawStringImplementationFileExtensions,
ImplementationFileExtensions,
utils::defaultFileExtensionDelimiters())) {
this->configurationDiag("Invalid implementation file extension: '%0'")
<< RawStringImplementationFileExtensions;
}
if (!utils::parseFileExtensions(RawStringHeaderFileExtensions,
HeaderFileExtensions,
utils::defaultFileExtensionDelimiters())) {
this->configurationDiag("Invalid header file extension: '%0'")
<< RawStringHeaderFileExtensions;
}
}
void SuspiciousIncludeCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "ImplementationFileExtensions",
RawStringImplementationFileExtensions);
Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions);
}
void SuspiciousIncludeCheck::registerPPCallbacks(
const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
PP->addPPCallbacks(
::std::make_unique<SuspiciousIncludePPCallbacks>(*this, SM, PP));
}
void SuspiciousIncludePPCallbacks::InclusionDirective(
SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,
bool IsAngled, CharSourceRange FilenameRange, const FileEntry *File,
StringRef SearchPath, StringRef RelativePath, const Module *Imported,
SrcMgr::CharacteristicKind FileType) {
if (IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import)
return;
SourceLocation DiagLoc = FilenameRange.getBegin().getLocWithOffset(1);
const Optional<StringRef> IFE =
utils::getFileExtension(FileName, Check.ImplementationFileExtensions);
if (!IFE)
return;
Check.diag(DiagLoc, "suspicious #%0 of file with '%1' extension")
<< IncludeTok.getIdentifierInfo()->getName() << *IFE;
for (const auto &HFE : Check.HeaderFileExtensions) {
SmallString<128> GuessedFileName(FileName);
llvm::sys::path::replace_extension(GuessedFileName,
(HFE.size() ? "." : "") + HFE);
const DirectoryLookup *CurDir;
Optional<FileEntryRef> File =
PP->LookupFile(DiagLoc, GuessedFileName, IsAngled, nullptr, nullptr,
CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
if (File) {
Check.diag(DiagLoc, "did you mean to include '%0'?", DiagnosticIDs::Note)
<< GuessedFileName;
}
}
}
} // namespace bugprone
} // namespace tidy
} // namespace clang
| 1,769 |
348 |
{"nom":"<NAME>","circ":"5ème circonscription","dpt":"Côtes-d'Armor","inscrits":789,"abs":303,"votants":486,"blancs":6,"nuls":4,"exp":476,"res":[{"nuance":"REM","nom":"<NAME>","voix":192},{"nuance":"SOC","nom":"<NAME>","voix":79},{"nuance":"UDI","nom":"<NAME>","voix":61},{"nuance":"FI","nom":"Mme <NAME>","voix":53},{"nuance":"FN","nom":"Mme <NAME>","voix":35},{"nuance":"ECO","nom":"<NAME>","voix":22},{"nuance":"REG","nom":"Mme <NAME>","voix":16},{"nuance":"COM","nom":"M. <NAME>","voix":5},{"nuance":"DVD","nom":"Mme <NAME>","voix":4},{"nuance":"EXG","nom":"<NAME>","voix":4},{"nuance":"REG","nom":"<NAME>","voix":2},{"nuance":"EXG","nom":"M. <NAME>","voix":1},{"nuance":"DIV","nom":"Mme Marie-<NAME>","voix":1},{"nuance":"DIV","nom":"M. <NAME>","voix":1}]}
| 308 |
423 |
<gh_stars>100-1000
params_flatmap_lateral_medial = {
"figsize": [16, 9],
"panels": [
{
"extent": [0.000, 0.200, 1.000, 0.800],
"view": {"angle": "flatmap", "surface": "flatmap"},
},
{
"extent": [0.300, 0.000, 0.200, 0.200],
"view": {
"hemisphere": "left",
"angle": "medial_pivot",
"surface": "inflated",
},
},
{
"extent": [0.500, 0.000, 0.200, 0.200],
"view": {
"hemisphere": "right",
"angle": "medial_pivot",
"surface": "inflated",
},
},
{
"extent": [0.000, 0.000, 0.300, 0.300],
"view": {
"hemisphere": "left",
"angle": "lateral_pivot",
"surface": "inflated",
},
},
{
"extent": [0.700, 0.000, 0.300, 0.300],
"view": {
"hemisphere": "right",
"angle": "lateral_pivot",
"surface": "inflated",
},
},
],
}
params_occipital_triple_view = {
"figsize": [16, 9],
"panels": [
{
"extent": [0.260, 0.000, 0.480, 1.000],
"view": {
"angle": "flatmap",
"surface": "flatmap",
"zoom": [0.250, 0.000, 0.500, 1.000],
},
},
{
"extent": [0.000, 0.000, 0.250, 0.333],
"view": {
"hemisphere": "left",
"angle": "bottom_pivot",
"surface": "inflated",
},
},
{
"extent": [0.000, 0.333, 0.250, 0.333],
"view": {
"hemisphere": "left",
"angle": "medial_pivot",
"surface": "inflated",
},
},
{
"extent": [0.000, 0.666, 0.250, 0.333],
"view": {
"hemisphere": "left",
"angle": "lateral_pivot",
"surface": "inflated",
},
},
{
"extent": [0.750, 0.000, 0.250, 0.333],
"view": {
"hemisphere": "right",
"angle": "bottom_pivot",
"surface": "inflated",
},
},
{
"extent": [0.750, 0.333, 0.250, 0.333],
"view": {
"hemisphere": "right",
"angle": "medial_pivot",
"surface": "inflated",
},
},
{
"extent": [0.750, 0.666, 0.250, 0.333],
"view": {
"hemisphere": "right",
"angle": "lateral_pivot",
"surface": "inflated",
},
},
],
}
params_inflatedless_lateral_medial_ventral = {
"figsize": [10, 9],
"panels": [
{
"extent": [0.0, 0.0, 0.5, 1 / 3.0],
"view": {
"hemisphere": "left",
"angle": "bottom_pivot",
"surface": "inflated_less",
},
},
{
"extent": [0.000, 1 / 3.0, 0.5, 1 / 3.0],
"view": {
"hemisphere": "left",
"angle": "medial_pivot",
"surface": "inflated_less",
},
},
{
"extent": [0.000, 2 / 3.0, 0.5, 1 / 3.0],
"view": {
"hemisphere": "left",
"angle": "lateral_pivot",
"surface": "inflated_less",
},
},
{
"extent": [0.5, 0.0, 0.5, 1 / 3.0],
"view": {
"hemisphere": "right",
"angle": "bottom_pivot",
"surface": "inflated_less",
},
},
{
"extent": [0.5, 1 / 3.0, 0.5, 1 / 3.0],
"view": {
"hemisphere": "right",
"angle": "medial_pivot",
"surface": "inflated_less",
},
},
{
"extent": [0.5, 2 / 3.0, 0.5, 1 / 3.0],
"view": {
"hemisphere": "right",
"angle": "lateral_pivot",
"surface": "inflated_less",
},
},
],
}
params_inflated_dorsal_lateral_medial_ventral = {
"figsize": [10, 10],
"panels": [
{
"extent": [0.0, 0.0, 0.5, 0.20],
"view": {
"hemisphere": "left",
"angle": "bottom_pivot",
"surface": "inflated",
},
},
{
"extent": [0.000, 0.20, 0.5, 0.3],
"view": {
"hemisphere": "left",
"angle": "medial_pivot",
"surface": "inflated",
},
},
{
"extent": [0.000, 0.50, 0.5, 0.3],
"view": {
"hemisphere": "left",
"angle": "lateral_pivot",
"surface": "inflated",
},
},
{
"extent": [0.000, 0.80, 0.5, 0.20],
"view": {
"hemisphere": "left",
"angle": "top_pivot",
"surface": "inflated",
},
},
{
"extent": [0.5, 0.0, 0.5, 0.20],
"view": {
"hemisphere": "right",
"angle": "bottom_pivot",
"surface": "inflated",
},
},
{
"extent": [0.5, 0.20, 0.5, 0.30],
"view": {
"hemisphere": "right",
"angle": "medial_pivot",
"surface": "inflated",
},
},
{
"extent": [0.5, 0.50, 0.5, 0.30],
"view": {
"hemisphere": "right",
"angle": "lateral_pivot",
"surface": "inflated",
},
},
{
"extent": [0.5, 0.80, 0.5, 0.20],
"view": {
"hemisphere": "right",
"angle": "top_pivot",
"surface": "inflated",
},
},
],
}
| 4,132 |
454 |
package cn.originx.migration.restore;
import cn.originx.migration.AbstractStep;
import cn.originx.migration.MigrateStep;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.up.eon.em.Environment;
import io.vertx.up.unity.Ux;
public class RestoreAll extends AbstractStep {
private transient final MigrateStep history;
private transient final MigrateStep organize;
private transient final MigrateStep user;
private transient final MigrateStep system;
private transient final MigrateStep adjuster;
public RestoreAll(final Environment environment) {
super(environment);
this.history = new RestoreHistory(environment);
this.organize = new RestoreOrg(environment);
this.user = new RestoreUser(environment);
this.system = new RestoreSystem(environment);
this.adjuster = new AdjustNumber(environment);
}
@Override
public Future<JsonObject> procAsync(final JsonObject config) {
this.banner("003. 数据还原");
return Ux.future(config)
/* Before */
.compose(processed -> this.aspectAsync(processed, "before-restore"))
/* 组织架构还原 */
.compose(this.organize.bind(this.app)::procAsync)
/* 账号体系还原 */
.compose(this.user.bind(this.app)::procAsync)
/* 系统数据还原 */
.compose(this.system.bind(this.app)::procAsync)
/* 历史数据还原 */
.compose(this.history.bind(this.app)::procAsync)
/* 后修复 number (双重保证) */
.compose(this.adjuster.bind(this.app)::procAsync)
/* After */
.compose(processed -> this.aspectAsync(processed, "after-restore"));
}
}
| 769 |
5,169 |
<reponame>ftapp/cocoapods
{
"name": "PredicateEditor",
"version": "0.9.1",
"summary": "A visual editor for dynamically creating NSPredicates to query data in your app.",
"description": "PredicateEditor allows users of your apps to dynamically create filters (in the form of NSPredicates) using an easy-to-use GUI, that can then be used to filter data.",
"homepage": "https://github.com/arvindhsukumar/PredicateEditor",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": "<NAME>",
"source": {
"git": "https://github.com/arvindhsukumar/PredicateEditor.git",
"tag": "0.9.1"
},
"platforms": {
"ios": "9.0"
},
"source_files": "PredicateEditor/Classes/**/*",
"resource_bundles": {
"PredicateEditor": [
"PredicateEditor/Assets/*.png",
"PredicateEditor/Assets/*.xcassets"
]
},
"dependencies": {
"SnapKit": [
"~> 0.21"
],
"SeedStackViewController": [
"~> 0.2"
],
"Timepiece": [
"~> 0.4"
]
}
}
| 418 |
852 |
#!/usr/bin/env python3
from math import *
from ROOT import TFile, TObject, TTree
from array import array
from ROOT import gDirectory
import sys
import os
from __future__ import print_function
def getGTfromDQMFile(DQMfile, RunNumber, globalTagVar):
if not os.path.isfile(DQMfile):# print "Error: file", DQMfile, "not found, exit"
sys.exit(0)
thefile = TFile( DQMfile )
globalTagDir = 'DQMData/Run ' + RunNumber + '/Info/Run summary/CMSSWInfo'
if not gDirectory.GetDirectory( globalTagDir ):
# print "Warning: globalTag not found in DQM file"
sys.exit(0)
keys = gDirectory.GetDirectory( globalTagDir ).GetListOfKeys()
key = keys[0]
globalTag = ''
while key:
obj = key.ReadObj()
if globalTagVar in obj.GetName():
globalTag = obj.GetName()[len("<"+globalTagVar+">s="):-len("</"+globalTagVar+">")]
break
key = keys.After(key)
if len(globalTag) > 1:
if globalTag.find('::') >= 0:
print(globalTag[0:globalTag.find('::')])
else:
print(globalTag)
return globalTag
| 488 |
315 |
/***************************************************************************
Copyright (c) 2019, Xilinx, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#ifndef _XF_CVT_COLOR_1_HPP_
#define _XF_CVT_COLOR_1_HPP_
#ifndef __cplusplus
#error C++ is needed to compile this header !
#endif
#ifndef _XF_CVT_COLOR_HPP_
#error This file can not be included independently !
#endif
#include "xf_cvt_color_utils.hpp"
template<int SRC_T,int DST_T,int ROWS, int COLS, int NPC, int WORDWIDTH_SRC,int TC,int TCC >
void write_y(xf::Mat<SRC_T, ROWS, COLS, NPC> & src_y,xf::Mat<DST_T, ROWS, COLS, NPC> & out_y,uint16_t height,uint16_t width)
{
XF_SNAME(WORDWIDTH_SRC) tmp;
unsigned long long int idx=0;
for(int i=0;i<height;i++)
{
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
#pragma HLS LOOP_FLATTEN off
for(int j=0;j<width;j++)
{
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
tmp=src_y.read(i*width+j);
out_y.write(idx++,tmp);
}
}
}
template<int SRC_T,int UV_T,int ROWS, int COLS, int NPC, int NPC_UV,int WORDWIDTH_UV, int WORDWIDTH_DST, int TC>
void KernNv122Yuv4(xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _uv,xf::Mat<SRC_T, ROWS, COLS, NPC> & _u,xf::Mat<SRC_T, ROWS, COLS, NPC> & _v,uint16_t height,uint16_t width)
{
XF_PTNAME(XF_16UP) uv;
XF_SNAME(WORDWIDTH_DST) u, v;
XF_SNAME(WORDWIDTH_UV) uvPacked;
XF_TNAME(SRC_T,NPC) arr_u[COLS];
XF_TNAME(SRC_T,NPC) arr_v[COLS];
unsigned long long int idx=0,idx1=0;
ap_uint<13> i,j;
bool evenBlock = true;
RowLoop:
for( i = 0; i < (height>>1); i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for( j = 0; j < width; j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
if(evenBlock)
{
uv = _uv.read(idx++);
u.range(7,0) = (uint8_t)uv.range(7,0);
v.range(7,0) = (uint8_t)uv.range(15,8);
}
arr_u[j]=u;arr_v[j]=v;
_u.write(((i*2)*(_u.cols>>XF_BITSHIFT(NPC)))+j, u);
_v.write(((i*2)*(_v.cols>>XF_BITSHIFT(NPC)))+j, v);
evenBlock = evenBlock ? false : true;
}
for(int k=0;k<width;k++)
{
_u.write((((i*2)+1)*(_u.cols>>XF_BITSHIFT(NPC)))+k, arr_u[k]);
_v.write((((i*2)+1)*(_v.cols>>XF_BITSHIFT(NPC)))+k, arr_v[k]);
}
}
}
template<int SRC_T,int UV_T,int DST_T,int ROWS, int COLS, int NPC, int NPC_UV, int WORDWIDTH_Y, int WORDWIDTH_UV, int WORDWIDTH_DST>
void KernNv122Rgba(xf::Mat<SRC_T, ROWS, COLS, NPC> & _y,xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _uv,xf::Mat<DST_T, ROWS, COLS, NPC> & _rgba,uint16_t height,uint16_t width)
{
hls::stream<XF_SNAME(WORDWIDTH_UV)> uvStream;
#pragma HLS STREAM variable=&uvStream depth=COLS
XF_SNAME(WORDWIDTH_Y) yPacked;
XF_SNAME(WORDWIDTH_UV) uvPacked;
XF_SNAME(WORDWIDTH_DST) rgba;
unsigned long long int idx=0,idx1=0;
uint8_t y1, y2;
int32_t V2Rtemp, U2Gtemp, V2Gtemp, U2Btemp;
int8_t u, v;
bool evenRow = true, evenBlock = true;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
yPacked = _y.read(i*width+j);
if(evenRow)
{
if(evenBlock)
{
uvPacked = _uv.read(idx++);
uvStream.write(uvPacked);
}
}
else
{// Keep a copy of UV row data in stream to use for oddrow
if(evenBlock)
{
uvPacked = uvStream.read();
}
}
// auExtractPixels<NPC, WORDWIDTH_SRC, XF_8UP>(UVbuf, UVPacked, 0);
uint8_t t = yPacked.range(7,0);
y1 = t > 16 ? t - 16 : 0;
v = (uint8_t)uvPacked.range(15,8) - 128;
u = (uint8_t)uvPacked.range(7,0) - 128;
V2Rtemp = v * (short int)V2R;
U2Gtemp = (short int)U2G * u;
V2Gtemp = (short int)V2G * v;
U2Btemp = u * (short int)U2B;
// R = 1.164*Y + 1.596*V = Y + 0.164*Y + V + 0.596*V
// G = 1.164*Y - 0.813*V - 0.391*U = Y + 0.164*Y - 0.813*V - 0.391*U
// B = 1.164*Y + 2.018*U = Y + 0.164 + 2*U + 0.018*U
rgba.range(7,0) = CalculateR(y1, V2Rtemp, v); //R
rgba.range(15,8) = CalculateG(y1, U2Gtemp, V2Gtemp); //G
rgba.range(23,16) = CalculateB(y1, U2Btemp, u); //B
rgba.range(31,24) = 255; //A
// PackedPixels = PackRGBAPixels<WORDWIDTH_DST>(RGB);
_rgba.write(idx1++,rgba);
evenBlock = evenBlock ? false : true;
}
evenRow = evenRow ? false : true;
}
if(height & 1)
{
for(int i = 0; i < width; i++)
{
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
uvStream.read();
}
}
}
template<int SRC_T,int UV_T,int ROWS, int COLS, int NPC, int NPC_UV,int WORDWIDTH_SRC, int WORDWIDTH_DST, int TC>
void KernNv122Iyuv(xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _uv,xf::Mat<SRC_T, ROWS/4, COLS, NPC> & _u,xf::Mat<SRC_T, ROWS/4, COLS, NPC> & _v,uint16_t height,uint16_t width)
{
XF_PTNAME(XF_8UP) u, v;
XF_SNAME(WORDWIDTH_SRC) uv;
unsigned long long int idx=0;
ap_uint<13> i,j;
RowLoop:
for( i = 0; i < height>>1; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for( j = 0; j < (width>>1); j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
// u = _uv.read();
// v = _uv.read();
uv = _uv.read(i*(width>>1)+j);
_u.write(idx,uv.range(7,0));
_v.write(idx++,uv.range(15,8));
}
}
}
template<int SRC_T,int UV_T,int ROWS, int COLS, int NPC,int NPC_UV, int WORDWIDTH_VU, int WORDWIDTH_DST, int TC>
void KernNv212Yuv4(xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _vu,xf::Mat<SRC_T, ROWS, COLS, NPC> & _u,xf::Mat<SRC_T, ROWS, COLS, NPC> & _v,uint16_t height,uint16_t width)
{
XF_PTNAME(XF_16UP) uv;
XF_SNAME(WORDWIDTH_DST) u, v;
XF_SNAME(WORDWIDTH_VU) uvPacked;
XF_TNAME(SRC_T,NPC) arr_u[COLS];
XF_TNAME(SRC_T,NPC) arr_v[COLS];
unsigned long long int idx=0,idx1=0;
ap_uint<13> i,j;
bool evenBlock = true;
RowLoop:
for( i = 0; i < (height>>1); i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for( j = 0; j < width; j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
if(evenBlock)
{
uv = _vu.read(idx++);
v.range(7,0) = (uint8_t)uv.range(7,0);
u.range(7,0) = (uint8_t)uv.range(15,8);
}
arr_u[j]=u;arr_v[j]=v;
_u.write(((i*2)*(_u.cols>>XF_BITSHIFT(NPC)))+j, u);
_v.write(((i*2)*(_v.cols>>XF_BITSHIFT(NPC)))+j, v);
evenBlock = evenBlock ? false : true;
}
for(int k=0;k<width;k++)
{
_u.write((((i*2)+1)*(_u.cols>>XF_BITSHIFT(NPC)))+k, arr_u[k]);
_v.write((((i*2)+1)*(_v.cols>>XF_BITSHIFT(NPC)))+k, arr_v[k]);
}
}
}
template<int SRC_T,int UV_T,int DST_T,int ROWS, int COLS, int NPC, int NPC_UV, int WORDWIDTH_Y, int WORDWIDTH_VU, int WORDWIDTH_DST>
void KernNv212Rgba(xf::Mat<SRC_T, ROWS, COLS, NPC> & _y,xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _vu,xf::Mat<DST_T, ROWS, COLS, NPC> & _rgba,uint16_t height,uint16_t width)
{
hls::stream<XF_SNAME(WORDWIDTH_VU)> vuStream;
#pragma HLS STREAM variable=&vuStream depth=COLS
XF_SNAME(WORDWIDTH_Y) yPacked;
XF_SNAME(WORDWIDTH_VU) vuPacked;
XF_SNAME(WORDWIDTH_DST) rgba;
unsigned long long int idx=0,idx1=0;
ap_uint<13> i,j;
uint8_t y1, y2;
int32_t V2Rtemp, U2Gtemp, V2Gtemp, U2Btemp;
int8_t u, v;
bool evenRow = true, evenBlock = true;
RowLoop:
for( i = 0; i < (height); i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for( j = 0; j < width; j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
yPacked = _y.read(i*width+j);
// auExtractPixels<NPC, WORDWIDTH_SRC, XF_8UP>(Ybuf, YPacked, 0);
if(evenRow)
{
if(evenBlock)
{
vuPacked = _vu.read(idx++);
vuStream.write(vuPacked);
}
}
else
{// Keep a copy of UV row data in stream to use for oddrow
if(evenBlock)
{
vuPacked = vuStream.read();
}
}
// auExtractPixels<NPC, WORDWIDTH_SRC, XF_8UP>(UVbuf, UVPacked, 0);
uint8_t t = yPacked.range(7,0);
y1 = t > 16 ? t - 16 : 0;
u = (uint8_t)vuPacked.range(15,8) - 128;
v = (uint8_t)vuPacked.range(7,0) - 128;
V2Rtemp = v * (short int)V2R;
U2Gtemp = (short int)U2G * u;
V2Gtemp = (short int)V2G * v;
U2Btemp = u * (short int)U2B;
// R = 1.164*Y + 1.596*V = Y + 0.164*Y + V + 0.596*V
// G = 1.164*Y - 0.813*V - 0.391*U = Y + 0.164*Y - 0.813*V - 0.391*U
// B = 1.164*Y + 2.018*U = Y + 0.164 + 2*U + 0.018*U
rgba.range(7,0) = CalculateR(y1, V2Rtemp, v); //R
rgba.range(15,8) = CalculateG(y1, U2Gtemp, V2Gtemp); //G
rgba.range(23,16) = CalculateB(y1, U2Btemp, u); //B
rgba.range(31,24) = 255; //A
// PackedPixels = PackRGBAPixels<WORDWIDTH_DST>(RGB);
_rgba.write(idx1++,rgba);
evenBlock = evenBlock ? false : true;
}
evenRow = evenRow ? false : true;
}
if(height & 1)
{
for( i = 0; i < width; i++)
{
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
vuStream.read();
}
}
}
template<int SRC_T,int UV_T,int ROWS, int COLS, int NPC,int NPC_UV, int WORDWIDTH_SRC, int WORDWIDTH_DST, int TC>
void KernNv212Iyuv(xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _vu,xf::Mat<SRC_T, ROWS/4, COLS, NPC> & _u,xf::Mat<SRC_T, ROWS/4, COLS, NPC> & _v,uint16_t height,uint16_t width)
{
ap_uint<13> i,j;
XF_PTNAME(XF_8UP) u, v;
XF_SNAME(WORDWIDTH_SRC) VUPacked, UVPacked0, UVPacked1;
unsigned long long int idx=0,idx1=0;
RowLoop:
for( i = 0; i < (height>>1); i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for( j = 0; j < (width>>1); j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
VUPacked = _vu.read(idx++);
u = (uint8_t)VUPacked.range(15,8);
v = (uint8_t)VUPacked.range(7,0);
_u.write(idx1,u);
_v.write(idx1++,v);
}
}
}
template< int SRC_T,int DST_T,int ROWS, int COLS, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST, int TC>
void KernIyuv2Rgba(xf::Mat<SRC_T, ROWS, COLS, NPC> & _y, xf::Mat<SRC_T, ROWS/4, COLS, NPC> & _u,xf::Mat<SRC_T, ROWS/4, COLS, NPC> & _v,xf::Mat<DST_T, ROWS, COLS, NPC> & _rgba,uint16_t height,uint16_t width)
{
unsigned long long int idx=0,idx1=0;
ap_uint<13> i,j;
hls::stream<XF_SNAME(WORDWIDTH_SRC)> uStream, vStream;
#pragma HLS STREAM variable=&uStream depth=COLS
#pragma HLS STREAM variable=&vStream depth=COLS
XF_SNAME(WORDWIDTH_SRC) yPacked, uPacked, vPacked;
XF_SNAME(WORDWIDTH_DST) rgba;
uint8_t y1, y2;
int32_t V2Rtemp, U2Gtemp, V2Gtemp, U2Btemp;
int8_t u, v;
bool evenRow = true, evenBlock = true;
RowLoop:
for( i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for( j = 0; j < width; j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
yPacked = _y.read(i*width+j);
if(evenBlock)
{
if(evenRow)
{
uPacked = _u.read(idx);
uStream.write(uPacked);
vPacked = _v.read(idx++);
vStream.write(vPacked);
}
else
{
/* Copy of the U and V values are pushed into stream to be used for next row */
uPacked = uStream.read();
vPacked = vStream.read();
}
}
y1 = (uint8_t)yPacked.range(7,0) > 16 ? (uint8_t)yPacked.range(7,0)-16 : 0;
u = (uint8_t)uPacked.range(7,0) - 128;
v = (uint8_t)vPacked.range(7,0) - 128;
V2Rtemp = v * (short int)V2R;
U2Gtemp = (short int)U2G * u;
V2Gtemp = (short int)V2G * v;
U2Btemp = u * (short int)U2B;
// R = 1.164*Y + 1.596*V = Y + 0.164*Y + V + 0.596*V
// G = 1.164*Y - 0.813*V - 0.391*U = Y + 0.164*Y - 0.813*V - 0.391*U
// B = 1.164*Y + 2.018*U = Y + 0.164 + 2*U + 0.018*U
rgba.range(7,0) = CalculateR(y1, V2Rtemp, v); //R
rgba.range(15,8) = CalculateG(y1, U2Gtemp, V2Gtemp); //G
rgba.range(23,16) = CalculateB(y1, U2Btemp, u); //B
rgba.range(31,24) = 255; //A
_rgba.write(idx1++,rgba);
evenBlock = evenBlock ? false : true;
}
evenRow = evenRow ? false: true;
}
}
template<int SRC_T,int ROWS, int COLS, int NPC, int WORDWIDTH, int rTC, int cTC>
void KernIyuv2Yuv4( xf::Mat<SRC_T, ROWS/4, COLS, NPC> & _in_u,xf::Mat<SRC_T, ROWS/4, COLS, NPC> & _in_v, xf::Mat<SRC_T, ROWS, COLS, NPC> & _u_image,xf::Mat<SRC_T, ROWS, COLS, NPC> & _v_image,uint16_t height,uint16_t width)
{
hls::stream<XF_SNAME(WORDWIDTH)> inter_u;
#pragma HLS stream variable=inter_u depth=COLS
hls::stream<XF_SNAME(WORDWIDTH)> inter_v;
#pragma HLS stream variable=inter_v depth=COLS
XF_TNAME(SRC_T,NPC) arr_U[COLS];
XF_TNAME(SRC_T,NPC) arr_V[COLS];
XF_SNAME(WORDWIDTH) IUPacked, IVPacked;
XF_PTNAME(XF_8UP) in_u, in_v;
unsigned long long int idx=0,idx1=0,in_idx1=0,in_idx2=0;
RowLoop:
for(int i = 0; i < ((height>>2) << 1); i++)
{
#pragma HLS LOOP_FLATTEN
#pragma HLS LOOP_TRIPCOUNT min=rTC max=rTC
ColLoop:
for(int j = 0,k=0; j < (width >> 1); j++,k+=2)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=cTC max=cTC
IUPacked = _in_u.read(in_idx1++);
IVPacked = _in_v.read(in_idx2++);
_u_image.write(((i*2)*(width))+k, IUPacked);
_u_image.write(((i*2)*(width))+k+1, IUPacked);
_v_image.write(((i*2)*(width))+k, IVPacked);
_v_image.write(((i*2)*(width))+k+1, IVPacked);
inter_u.write(IUPacked);
inter_v.write(IVPacked);
inter_u.write(IUPacked);
inter_v.write(IVPacked);
}
for(int j=0;j<width;j++)
{
#pragma HLS pipeline
_u_image.write((((i*2)+1)*(width)+j), inter_u.read());
_v_image.write((((i*2)+1)*(width)+j), inter_v.read());
}
}
}
template<int SRC_T,int UV_T,int ROWS, int COLS, int NPC,int NPC_UV, int WORDWIDTH_SRC, int WORDWIDTH_UV, int rTC, int cTC>
void KernIyuv2Nv12( xf::Mat<SRC_T, ROWS/4, COLS, NPC> & _u,xf::Mat<SRC_T, ROWS/4, COLS, NPC> & _v,xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _uv,uint16_t height,uint16_t width)
{
ap_uint<13> i,j;
XF_SNAME(WORDWIDTH_SRC) u, v;
XF_SNAME(WORDWIDTH_UV) uv;
unsigned long long int idx=0;
RowLoop:
for( i = 0; i < height>>1; i++)
{
// Reading the plane interleaved U and V data from streams,
// packing them in pixel interleaved and writing out to UV stream
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=rTC max=rTC
ColLoop:
for( j = 0; j < (width>>1); j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=cTC max=cTC
u = _u.read(i*(width>>1)+j);
v = _v.read(i*(width>>1)+j);
uv.range(7,0) = u;
uv.range(15,8) = v;
_uv.write(idx++,uv);
}
}
}
template<int SRC_T, int DST_T,int ROWS, int COLS, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST>
void KernRgba2Yuv4(xf::Mat<SRC_T, ROWS, COLS, NPC> & _rgba, xf::Mat<DST_T, ROWS, COLS, NPC> & _y, xf::Mat<DST_T, ROWS, COLS, NPC> & _u, xf::Mat<DST_T, ROWS, COLS, NPC> & _v,uint16_t height,uint16_t width )
{
XF_SNAME(XF_32UW) rgba;
uint8_t y, u, v;
unsigned long long int idx=0;
RowLoop:
for(int i = 0; i < height; ++i)
{
#pragma HLS LOOP_FLATTEN OFF
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; ++j)
{
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
#pragma HLS PIPELINE
rgba = _rgba.read(i*width+j);
y = CalculateY(rgba.range(7,0),rgba.range(15,8), rgba.range(23,16));
u = CalculateU(rgba.range(7,0),rgba.range(15,8), rgba.range(23,16));
v = CalculateV(rgba.range(7,0),rgba.range(15,8), rgba.range(23,16));
_y.write(idx,y);
_u.write(idx,u);
_v.write(idx++,v);
}
}
}
template<int SRC_T,int DST_T,int ROWS, int COLS, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST,int ROWS_U,int ROWS_V>
void KernRgba2Iyuv(xf::Mat<SRC_T, ROWS, COLS, NPC> & _rgba, xf::Mat<DST_T, ROWS, COLS, NPC> & _y, xf::Mat<DST_T, ROWS/4, COLS, NPC> & _u, xf::Mat<DST_T, ROWS/4, COLS, NPC> & _v,uint16_t height,uint16_t width)
{
XF_SNAME(XF_32UW) rgba;
uint8_t y, u, v;
bool evenRow = true, evenBlock = true;
unsigned long long int idx=0,idx1=0;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
rgba = _rgba.read(i*width+j);
uint8_t r = rgba.range(7,0);
uint8_t g = rgba.range(15,8);
uint8_t b = rgba.range(23,16);
y = CalculateY(r, g, b);
if(evenRow)
{
if(evenBlock)
{
u = CalculateU(r, g, b);
v = CalculateV(r, g, b);
}
}
_y.write(idx1++,y);
if(evenRow & !evenBlock)
{
_u.write(idx,u);
_v.write(idx++,v);
}
evenBlock = evenBlock ? false : true;
}
evenRow = evenRow ? false : true;
}
}
template<int SRC_T, int Y_T, int UV_T,int ROWS, int COLS, int NPC,int NPC_UV, int WORDWIDTH_SRC, int WORDWIDTH_Y, int WORDWIDTH_UV>
void KernRgba2Nv12(xf::Mat<SRC_T, ROWS, COLS, NPC> & _rgba, xf::Mat<Y_T, ROWS, COLS, NPC> & _y, xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _uv,uint16_t height,uint16_t width)
{
// XF_SNAME(XF_32UW) rgba;
XF_TNAME(SRC_T,NPC) rgba;
ap_uint<16> val1;
uint8_t y, u, v;
unsigned long long int idx=0,idx1=0;
bool evenRow = true, evenBlock = true;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
rgba = _rgba.read(i*width+j);
uint8_t r = rgba.range(7,0);
uint8_t g = rgba.range(15,8);
uint8_t b = rgba.range(23,16);
y = CalculateY(r, g, b);
if(evenRow)
{
u = CalculateU(r, g, b);
v = CalculateV(r, g, b);
}
_y.write(idx++,y);
if(evenRow)
{
if((j & 0x01) == 0)
//{
_uv.write(idx1++,u | (uint16_t)v << 8);
//_uv.write(v);
//}
// _uv.write(u | (uint16_t)v << 8);
}
}
evenRow = evenRow ? false : true;
}
}
template<int SRC_T, int Y_T, int UV_T, int ROWS, int COLS, int NPC, int NPC_UV, int WORDWIDTH_SRC, int WORDWIDTH_Y, int WORDWIDTH_VU>
void KernRgba2Nv21(xf::Mat<SRC_T, ROWS, COLS, NPC> & _rgba, xf::Mat<Y_T, ROWS, COLS, NPC> & _y, xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _vu,uint16_t height,uint16_t width)
{
width=width>>XF_BITSHIFT(NPC);
XF_TNAME(SRC_T,NPC) rgba;
uint8_t y, u, v;
unsigned long long int idx=0,idx1=0;
bool evenRow = true, evenBlock = true;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; j++)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
rgba = _rgba.read(i*width+j);
uint8_t r = rgba.range(7,0);
uint8_t g = rgba.range(15,8);
uint8_t b = rgba.range(23,16);
y = CalculateY(r, g, b);
if(evenRow)
{
u = CalculateU(r, g, b);
v = CalculateV(r, g, b);
}
_y.write(idx++,y);
if(evenRow)
{
if((j & 0x01)==0)
_vu.write(idx1++,v | ((uint16_t)u << 8));
}
}
evenRow = evenRow ? false : true;
}
}
//Yuyv2Rgba
template<int SRC_T,int DST_T,int ROWS, int COLS, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST, int TC>
void KernYuyv2Rgba(xf::Mat<SRC_T, ROWS, COLS, NPC> & _yuyv,xf::Mat<DST_T, ROWS, COLS, NPC> & _rgba, uint16_t height, uint16_t width)
{
XF_SNAME(WORDWIDTH_DST) rgba;
XF_SNAME(WORDWIDTH_SRC) yu,yv;
XF_PTNAME(XF_8UP) r, g, b;
int8_t y1, y2, u, v;
int32_t V2Rtemp, U2Gtemp, V2Gtemp, U2Btemp;
unsigned long long int idx=0;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
#pragma HLS LOOP_FLATTEN off
ColLoop:
for(int j = 0; j < width ; j += 2)
{
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
#pragma HLS pipeline
yu = _yuyv.read(i*width+j);
yv = _yuyv.read(i*width+j+1);
u = (uint8_t)yu.range(15,8) - 128;
y1 = (yu.range(7,0) > 16) ? ((uint8_t)yu.range(7,0) - 16) : 0;
v = (uint8_t)yv.range(15,8) - 128;
y2 = (yv.range(7,0) > 16) ? ((uint8_t)yv.range(7,0) - 16) : 0;
V2Rtemp = v * (short int)V2R;
U2Gtemp = (short int)U2G * u;
V2Gtemp = (short int)V2G * v;
U2Btemp = u * (short int)U2B;
r = CalculateR(y1, V2Rtemp, v);
g = CalculateG(y1, U2Gtemp, V2Gtemp);
b = CalculateB(y1, U2Btemp, u);
rgba = ((ap_uint32_t)r) | ((ap_uint32_t)g << 8) | ((ap_uint32_t)b << 16) | (0xFF000000);
_rgba.write(idx++,rgba);
r = CalculateR(y2, V2Rtemp, v);
g = CalculateG(y2, U2Gtemp, V2Gtemp);
b = CalculateB(y2, U2Btemp, u);
rgba = ((ap_uint32_t)r) | ((ap_uint32_t)g << 8) | ((ap_uint32_t)b << 16) | (0xFF000000);
_rgba.write(idx++,rgba);
}
}
}
//Yuyv2Nv12
template<int SRC_T,int Y_T,int UV_T,int ROWS, int COLS, int NPC, int NPC_UV,int WORDWIDTH_SRC, int WORDWIDTH_Y, int WORDWIDTH_UV, int TC>
void KernYuyv2Nv12(xf::Mat<SRC_T, ROWS, COLS, NPC> & _yuyv,xf::Mat<Y_T, ROWS, COLS, NPC> & _y,xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _uv,uint16_t height, uint16_t width)
{
XF_SNAME(WORDWIDTH_SRC) yu,yv;
XF_PTNAME(XF_8UP) y1, y2;
unsigned long long int idx=0,idx1=0;
XF_SNAME(WORDWIDTH_UV) uv;
bool evenRow = true;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; j+=2)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
yu = _yuyv.read(i*width+j);
yv = _yuyv.read(i*width+j+1);
y1 = yu.range(7,0);
if(evenRow)
uv.range(7,0) = yu.range(15,8);
y2 = yv.range(7,0);
if(evenRow)
uv.range(15,8) = yv.range(15,8);
_y.write(idx++,y1);
_y.write(idx++,y2);
if(evenRow)
{
_uv.write(idx1++,uv);
}
}
evenRow = evenRow ? false : true;
}
}
//Yuyv2Nv12
template<int SRC_T,int Y_T,int UV_T,int ROWS, int COLS, int NPC, int NPC_UV,int WORDWIDTH_SRC, int WORDWIDTH_Y, int WORDWIDTH_UV, int TC>
void KernYuyv2Nv21(xf::Mat<SRC_T, ROWS, COLS, NPC> & _yuyv,xf::Mat<Y_T, ROWS, COLS, NPC> & _y,xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & _uv,uint16_t height, uint16_t width)
{
XF_SNAME(WORDWIDTH_SRC) yu,yv;
XF_PTNAME(XF_8UP) y1, y2;
unsigned long long int idx=0,idx1=0;
XF_SNAME(WORDWIDTH_UV) uv;
bool evenRow = true;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; j+=2)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
yu = _yuyv.read(i*width+j);
yv = _yuyv.read(i*width+j+1);
y1 = yu.range(7,0);
if(evenRow)
uv.range(7,0) = yv.range(15,8);
y2 = yv.range(7,0);
if(evenRow)
uv.range(15,8) = yu.range(15,8);
_y.write(idx++,y1);
_y.write(idx++,y2);
if(evenRow)
{
_uv.write(idx1++,uv);
}
}
evenRow = evenRow ? false : true;
}
}
//Yuyv2Iyuv
template<int SRC_T,int DST_T,int ROWS, int COLS, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST, int TC>
void KernYuyv2Iyuv(xf::Mat<SRC_T, ROWS, COLS, NPC> & _yuyv, xf::Mat<DST_T, ROWS, COLS, NPC> & _y, xf::Mat<DST_T, ROWS/4, COLS, NPC> & _u, xf::Mat<DST_T, ROWS/4, COLS, NPC> & _v, uint16_t height, uint16_t width)
{
XF_SNAME(WORDWIDTH_SRC) yu,yv;
unsigned long long int idx=0,idx1=0;
bool evenRow = true, evenBlock = true;
XF_PTNAME(XF_8UP) y1, y2, u, v;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; j+=2)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
yu = _yuyv.read(i*width+j);
yv = _yuyv.read(i*width+j+1);
y1 = yu.range(7,0);
y2 = yv.range(7,0);
_y.write(idx,y1);
idx++;
_y.write(idx,y2);
idx++;
if(evenRow)
u = yu.range(15,8);
if(evenRow)
v = yv.range(15,8);
if(evenRow)
{
_u.write(idx1,u);
_v.write(idx1,v);
idx1++;
}
}
evenRow = evenRow ? false : true;
}
}
template<int SRC_T,int DST_T, int ROWS, int COLS, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST, int TC>
void KernUyvy2Iyuv( xf::Mat<SRC_T, ROWS, COLS, NPC> & _uyvy,xf::Mat<DST_T, ROWS, COLS, NPC> & y_plane,xf::Mat<DST_T, ROWS/4, COLS, NPC> & u_plane,xf::Mat<DST_T, ROWS/4, COLS, NPC> & v_plane,uint16_t height, uint16_t width)
{
XF_SNAME(WORDWIDTH_SRC) uy,vy;
bool evenRow = true, evenBlock = true;
XF_PTNAME(XF_8UP) y1, y2, u, v;
unsigned long long int idx=0,idx1=0;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; j+=2)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
uy = _uyvy.read(i*width+j);
vy = _uyvy.read(i*width+j+1);
y1 = uy.range(15,8);
y_plane.write(idx1,y1);
idx1++;
if(evenRow)
u = uy.range(7,0);
y2 = vy.range(15,8);
y_plane.write(idx1,y2);
idx1++;
if(evenRow)
v = vy.range(7,0);
if(evenRow)
{
u_plane.write(idx,u);
v_plane.write(idx,v);
idx++;
}
}
evenRow = evenRow ? false : true;
}
}
//Uyvy2Nv12
template<int SRC_T,int Y_T,int UV_T,int ROWS, int COLS, int NPC, int NPC_UV,int WORDWIDTH_SRC, int WORDWIDTH_Y, int WORDWIDTH_UV, int TC>
void KernUyvy2Nv12(xf::Mat<SRC_T, ROWS, COLS, NPC> & uyvy,xf::Mat<Y_T, ROWS, COLS, NPC> & y_plane,xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & uv_plane, uint16_t height, uint16_t width)
{
XF_SNAME(WORDWIDTH_SRC) uy,vy;
XF_PTNAME(XF_8UP) y1, y2;
XF_SNAME(WORDWIDTH_UV) uv;
bool evenRow = true;
unsigned long long int idx=0,idx1=0;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; j+=2)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
uy = uyvy.read(i*width+j);
vy = uyvy.read(i*width+j+1);
y1 = uy.range(15,8);
if(evenRow)
uv.range(7,0) = uy.range(7,0);
y2 = vy.range(15,8);
if(evenRow)
uv.range(15,8) = vy.range(7,0);
y_plane.write(idx1,y1);
idx1++;
y_plane.write(idx1,y2);
idx1++;
if(evenRow)
{
uv_plane.write(idx,uv);
idx++;
}
}
evenRow = evenRow ? false : true;
}
}
//Uyvy2Nv12
template<int SRC_T,int Y_T,int UV_T,int ROWS, int COLS, int NPC, int NPC_UV,int WORDWIDTH_SRC, int WORDWIDTH_Y, int WORDWIDTH_UV, int TC>
void KernUyvy2Nv21(xf::Mat<SRC_T, ROWS, COLS, NPC> & uyvy,xf::Mat<Y_T, ROWS, COLS, NPC> & y_plane,xf::Mat<UV_T, ROWS/2, COLS/2, NPC_UV> & uv_plane, uint16_t height, uint16_t width)
{
XF_SNAME(WORDWIDTH_SRC) uy,vy;
XF_PTNAME(XF_8UP) y1, y2;
XF_SNAME(WORDWIDTH_UV) uv;
bool evenRow = true;
unsigned long long int idx=0,idx1=0;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_FLATTEN off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
ColLoop:
for(int j = 0; j < width; j+=2)
{
#pragma HLS pipeline
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
uy = uyvy.read(i*width+j);
vy = uyvy.read(i*width+j+1);
y1 = uy.range(15,8);
if(evenRow)
uv.range(7,0) = vy.range(7,0);
y2 = vy.range(15,8);
if(evenRow)
uv.range(15,8) = uy.range(7,0);
y_plane.write(idx1,y1);
idx1++;
y_plane.write(idx1,y2);
idx1++;
if(evenRow)
{
uv_plane.write(idx,uv);
idx++;
}
}
evenRow = evenRow ? false : true;
}
}
//Uyvy2Rgba
template<int SRC_T,int DST_T,int ROWS, int COLS, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST, int TC>
void KernUyvy2Rgba(xf::Mat<SRC_T, ROWS, COLS, NPC> & _uyvy,xf::Mat<DST_T, ROWS, COLS, NPC> & _rgba, uint16_t height, uint16_t width)
{
XF_SNAME(WORDWIDTH_DST) rgba;
XF_SNAME(WORDWIDTH_SRC) uyvy;
XF_SNAME(WORDWIDTH_SRC) uy;
XF_SNAME(WORDWIDTH_SRC) vy;
unsigned long long int idx=0;
XF_PTNAME(XF_8UP) r, g, b;
int8_t y1, y2, u, v;
int32_t V2Rtemp, U2Gtemp, V2Gtemp, U2Btemp;
RowLoop:
for(int i = 0; i < height; i++)
{
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
#pragma HLS LOOP_FLATTEN off
ColLoop:
for(int j = 0; j < width; j+=2)
{
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
#pragma HLS pipeline
uy = _uyvy.read(i*width+j);
vy = _uyvy.read(i*width+j+1);
u = (uint8_t)uy.range(7,0) - 128;
/* if(uyvy.range(15,8) > 16)
y1 = (uint8_t)uyvy.range(15,8) - 16;
else
y1 = 0;*/
y1 = (uy.range(15,8) > 16) ? ((uint8_t)uy.range(15,8) - 16) : 0;
v = (uint8_t)vy.range(7,0) - 128;
/* if(uyvy.range(31,24) > 16)
y2 = ((uint8_t)uyvy.range(31,24) - 16);
else
y2 = 0;*/
y2 = (vy.range(15,8) > 16) ? ((uint8_t)vy.range(15,8) - 16) : 0;
V2Rtemp = v * (short int)V2R;
U2Gtemp = (short int)U2G * u;
V2Gtemp = (short int)V2G * v;
U2Btemp = u * (short int)U2B;
r = CalculateR(y1, V2Rtemp, v);
g = CalculateG(y1, U2Gtemp, V2Gtemp);
b = CalculateB(y1, U2Btemp, u);
rgba = ((ap_uint32_t)r) | ((ap_uint32_t)g << 8) | ((ap_uint32_t)b << 16) | (0xFF000000);
_rgba.write(idx,rgba);
idx++;
r = CalculateR(y2, V2Rtemp, v);
g = CalculateG(y2, U2Gtemp, V2Gtemp);
b = CalculateB(y2, U2Btemp, u);
rgba = ((ap_uint32_t)r) | ((ap_uint32_t)g << 8) | ((ap_uint32_t)b << 16) | (0xFF000000);
_rgba.write(idx,rgba);
idx++;
}
}
}
#endif
| 16,006 |
1,168 |
// Check support for GNU's "anonymous struct" extension.
//
// This is very similar to standard C++'s anonymous unions, and Clang's AST
// models them in the same way with IndirectFieldDecls in parent scopes.
//
// (Amusingly?) this testcase crashes GCC 4.8.
union U {
struct {
//- @field defines/binding StructField
int field;
};
//- @field ref StructField
static_assert(&U::field != nullptr, "");
};
| 131 |
6,041 |
package com.koushikdutta.async.callback;
public interface ValueFunction<T> {
T getValue() throws Exception;
}
| 40 |
522 |
<reponame>pybee/briefcase
import os
import re
import subprocess
import unicodedata
from email.utils import parseaddr
from typing import Optional
from urllib.parse import urlparse
from cookiecutter import exceptions as cookiecutter_exceptions
from briefcase.config import is_valid_app_name, is_valid_bundle_identifier
from briefcase.exceptions import NetworkFailure
from .base import BaseCommand, BriefcaseCommandError
from .create import InvalidTemplateRepository
def titlecase(s):
"""Convert a string to titlecase.
Follow Chicago Manual of Style rules for capitalization (roughly).
* Capitalize *only* the first letter of each word
* ... unless the word is an acronym (e.g., URL)
* ... or the word is on the exclude list ('of', 'and', 'the)
:param s: The input string
:returns: A capitalized string.
"""
return " ".join(
word
if (
word.isupper()
or word
in {
"a",
"an",
"and",
"as",
"at",
"but",
"by",
"en",
"for",
"if",
"in",
"of",
"on",
"or",
"the",
"to",
"via",
"vs",
}
)
else word.capitalize()
for word in s.split(" ")
)
class NewCommand(BaseCommand):
cmd_line = "briefcase new"
command = "new"
platform = "all"
output_format = None
description = "Create a new briefcase project"
def bundle_path(self, app):
"""A placeholder; New command doesn't have a bundle path."""
raise NotImplementedError()
def binary_path(self, app):
"""A placeholder; New command doesn't have a binary path."""
raise NotImplementedError()
def distribution_path(self, app, packaging_format):
"""A placeholder; New command doesn't have a distribution path."""
raise NotImplementedError()
def parse_config(self, filename):
"""There is no configuration when starting a new project; this
implementation overrides the base so that no config is parsed."""
pass
def add_options(self, parser):
parser.add_argument(
"-t",
"--template",
dest="template",
help="The cookiecutter template to use for the new project",
)
def make_class_name(self, formal_name):
"""Construct a valid class name from a formal name.
:param formal_name: The formal name
:returns: The app's class name
"""
# Identifiers (including class names) can be unicode.
# https://docs.python.org/3/reference/lexical_analysis.html#identifiers
xid_start = {
"Lu", # uppercase letters
"Ll", # lowercase letters
"Lt", # titlecase letters
"Lm", # modifier letters
"Lo", # other letters
"Nl", # letter numbers
}
xid_continue = xid_start.union(
{
"Mn", # nonspacing marks
"Mc", # spacing combining marks
"Nd", # decimal number
"Pc", # connector punctuations
}
)
# Normalize to NFKC form, then remove any character that isn't
# in the allowed categories, or is the underscore character
class_name = "".join(
ch
for ch in unicodedata.normalize("NFKC", formal_name)
if unicodedata.category(ch) in xid_continue or ch in {"_"}
)
# If the first character isn't in the 'start' character set,
# and it isn't already an underscore, prepend an underscore.
if (
unicodedata.category(class_name[0]) not in xid_start
and class_name[0] != "_"
):
class_name = f"_{class_name}"
return class_name
def make_app_name(self, formal_name):
"""Construct a candidate app name from a formal name.
:param formal_name: The formal name
:returns: The candidate app name
"""
normalized = unicodedata.normalize("NFKD", formal_name)
stripped = re.sub("[^0-9a-zA-Z_]+", "", normalized).lstrip("_")
if stripped:
return stripped.lower()
else:
# If stripping removes all the content,
# use a dummy app name as the suggestion.
return "myapp"
def validate_app_name(self, candidate):
"""Determine if the app name is valid.
:param candidate: The candidate name
:returns: True. If there are any validation problems, raises ValueError
with a diagnostic message.
"""
if not is_valid_app_name(candidate):
raise ValueError(
f"{candidate!r} is not a valid app name.\n\n"
"App names must not be reserved keywords such as 'and', 'for' and 'while'.\n"
"They must also be PEP508 compliant (i.e., they can only include letters,\n"
"numbers, '-' and '_'; must start with a letter; and cannot end with '-' or '_')."
)
if (self.base_path / candidate).exists():
raise ValueError(
f"A {candidate!r} directory already exists. Select a different "
"name, move to a different parent directory, or delete the "
"existing folder."
)
return True
def make_module_name(self, app_name):
"""Construct a valid module name from an app name.
:param app_name: The app name
:returns: The app's module name.
"""
return app_name.replace("-", "_")
def validate_bundle(self, candidate):
"""Determine if the bundle identifier is valid.
:param candidate: The candidate bundle identifier
:returns: True. If there are any validation problems, raises ValueError
with a diagnostic message.
"""
if not is_valid_bundle_identifier(candidate):
raise ValueError(
f"{candidate!r} is not a valid bundle identifier.\n\n"
"The bundle should be a reversed domain name. It must contain at least 2\n"
"dot-separated sections; each section may only include letters, numbers,\n"
"and hyphens; and each section may not contain any reserved words (like\n"
"'switch', or 'while')."
)
return True
def make_domain(self, bundle):
"""Construct a candidate domain from a bundle identifier.
:param bundle: The bundle identifier
:returns: The candidate domain
"""
return ".".join(bundle.split(".")[::-1])
def make_author_email(self, author, bundle):
"""Construct a candidate email address from the authors name and the
bundle identifier.
The candidate is based on the assumption that the author's name is in
"first/last" format, or it a corporate name; the "first" part is split
off, and prepended to the domain extracted from the bundle.
It's not a perfect system, but it's better than putting up
"<EMAIL>" as a candidate default value.
:param author: The authors name.
:param bundle: The bundle identifier.
:returns: The candidate author's name
"""
return f"{author.split(' ')[0].lower()}@{self.make_domain(bundle)}"
def validate_email(self, candidate):
"""Determine if the email address is valid.
:param candidate: The candidate email address
:returns: True. If there are any validation problems, raises ValueError
with a diagnostic message.
"""
if parseaddr(candidate)[1] != candidate:
raise ValueError("Not a valid email address")
return True
def make_project_url(self, bundle, app_name):
"""Construct a candidate project URL from the bundle and app name.
It's not a perfect guess, but it's better than having
"https://example.com".
:param bundle: The bundle identifier.
:param app_name: The app name.
:returns: The candidate project URL
"""
return f"https://{self.make_domain(bundle)}/{app_name}"
def validate_url(self, candidate):
"""Determine if the URL is valid.
:param candidate: The candidate URL
:returns: True. If there are any validation problems, raises ValueError
with a diagnostic message.
"""
result = urlparse(candidate)
if not all([result.scheme, result.netloc]):
raise ValueError("Not a valid URL!")
return True
def input_text(self, intro, variable, default, validator=None):
"""Read a text answer from the user.
:param intro: An introductory paragraph explaining the question being
asked.
:param variable: The name of the variable being entered.
:param default: The default value if the user hits enter without typing
anything.
:param validator: (optional) A validator function; accepts a single
input (the candidate response), returns True if the answer is
valid, or raises ValueError() with a debugging message if the
candidate value isn't valid.
:returns: a string, guaranteed to meet the validation criteria of
``validator``.
"""
self.input.prompt(intro)
while True:
self.input.prompt()
answer = self.input.text_input(
f"{titlecase(variable)} [{default}]: ", default=default
)
if validator is None:
return answer
try:
validator(answer)
return answer
except ValueError as e:
if not self.input.enabled:
raise BriefcaseCommandError(str(e)) from e
self.input.prompt()
self.input.prompt(f"Invalid value; {e}")
def input_select(self, intro, variable, options):
"""Select one from a list of options.
The first option is assumed to be the default.
:param intro: An introductory paragraph explaining the question being
asked.
:param variable: The variable to display to the user.
:param options: A list of text strings, describing the available
options.
:returns: The string content of the selected option.
"""
self.input.prompt(intro)
index_choices = [str(key) for key in range(1, len(options) + 1)]
display_options = "\n".join(
f" [{index}] {option}" for index, option in zip(index_choices, options)
)
error_message = (
f"Invalid selection; please enter a number between 1 and {len(options)}"
)
prompt = f"""
Select one of the following:
{display_options}
{titlecase(variable)} [1]: """
selection = self.input.selection_input(
prompt=prompt,
choices=index_choices,
default="1",
error_message=error_message,
)
return options[int(selection) - 1]
def build_app_context(self):
"""Ask the user for details about the app to be created.
:returns: A context dictionary to be used in the cookiecutter project
template.
"""
formal_name = self.input_text(
intro="""
First, we need a formal name for your application. This is the name that will
be displayed to humans whenever the name of the application is displayed. It
can have spaces and punctuation if you like, and any capitalization will be
used as you type it.""",
variable="formal name",
default="Hello World",
)
# The class name can be completely derived from the formal name.
class_name = self.make_class_name(formal_name)
default_app_name = self.make_app_name(formal_name)
app_name = self.input_text(
intro=f"""
Next, we need a name that can serve as a machine-readable Python package name
for your application. This name must be PEP508-compliant - that means the name
may only contain letters, numbers, hyphens and underscores; it can't contain
spaces or punctuation, and it can't start with a hyphen or underscore.
Based on your formal name, we suggest an app name of '{default_app_name}',
but you can use another name if you want.""",
variable="app name",
default=default_app_name,
validator=self.validate_app_name,
)
# The module name can be completely derived from the app name.
module_name = self.make_module_name(app_name)
bundle = self.input_text(
intro=f"""
Now we need a bundle identifier for your application. App stores need to
protect against having multiple applications with the same name; the bundle
identifier is the namespace they use to identify applications that come from
you. The bundle identifier is usually the domain name of your company or
project, in reverse order.
For example, if you are writing an application for Example Corp, whose website
is example.com, your bundle would be ``com.example``. The bundle will be
combined with your application's machine readable name to form a complete
application identifier (e.g., com.example.{app_name}).""",
variable="bundle identifier",
default="com.example",
validator=self.validate_bundle,
)
project_name = self.input_text(
intro="""
Briefcase can manage projects that contain multiple applications, so we need a
Project name. If you're only planning to have one application in this
project, you can use the formal name as the project name.""",
variable="project name",
default=formal_name,
)
description = self.input_text(
intro="""
Now, we need a one line description for your application.""",
variable="description",
default="My first application",
)
author = self.input_text(
intro="""
Who do you want to be credited as the author of this application? This could be
your own name, or the name of your company you work for.""",
variable="author",
default="<NAME>",
)
author_email = self.input_text(
intro="""
What email address should people use to contact the developers of this
application? This might be your own email address, or a generic contact address
you set up specifically for this application.""",
variable="author's email",
default=self.make_author_email(author, bundle),
validator=self.validate_email,
)
url = self.input_text(
intro="""
What is the website URL for this application? If you don't have a website set
up yet, you can put in a dummy URL.""",
variable="application URL",
default=self.make_project_url(bundle, app_name),
validator=self.validate_url,
)
project_license = self.input_select(
intro="""
What license do you want to use for this project's code?""",
variable="project license",
options=[
"BSD license",
"MIT license",
"Apache Software License",
"GNU General Public License v2 (GPLv2)",
"GNU General Public License v2 or later (GPLv2+)",
"GNU General Public License v3 (GPLv3)",
"GNU General Public License v3 or later (GPLv3+)",
"Proprietary",
"Other",
],
)
gui_framework = self.input_select(
intro="""
What GUI toolkit do you want to use for this project?""",
variable="GUI framework",
options=[
"Toga",
"PySide2 (does not support iOS/Android deployment)",
"PySide6 (does not support iOS/Android deployment)",
"PursuedPyBear (does not support iOS/Android deployment)",
"None",
],
)
return {
"formal_name": formal_name,
"app_name": app_name,
"class_name": class_name,
"module_name": module_name,
"project_name": project_name,
"description": description,
"author": author,
"author_email": author_email,
"bundle": bundle,
"url": url,
"license": project_license,
"gui_framework": (gui_framework.split())[0],
}
def new_app(self, template: Optional[str] = None, **options):
"""Ask questions to generate a new application, and generate a stub
project from the briefcase-template."""
if template is None:
template = "https://github.com/beeware/briefcase-template"
self.input.prompt()
self.input.prompt("Let's build a new Briefcase app!")
self.input.prompt()
context = self.build_app_context()
self.logger.info()
self.logger.info(f"Generating a new application '{context['formal_name']}'")
cached_template = self.update_cookiecutter_cache(
template=template, branch="v0.3"
)
# Make extra sure we won't clobber an existing application.
if (self.base_path / context["app_name"]).exists():
raise BriefcaseCommandError(
f"A directory named '{context['app_name']}' already exists."
)
try:
# Unroll the new app template
self.cookiecutter(
str(cached_template),
no_input=True,
output_dir=os.fsdecode(self.base_path),
checkout="v0.3",
extra_context=context,
)
except subprocess.CalledProcessError as e:
# Computer is offline
# status code == 128 - certificate validation error.
raise NetworkFailure("clone template repository") from e
except cookiecutter_exceptions.RepositoryNotFound as e:
# Either the template path is invalid,
# or it isn't a cookiecutter template (i.e., no cookiecutter.json)
raise InvalidTemplateRepository(template) from e
self.logger.info(
f"""
Application '{context['formal_name']}' has been generated. To run your application, type:
cd {context['app_name']}
briefcase dev
"""
)
def verify_tools(self):
"""Verify that the tools needed to run this command exist.
Raises MissingToolException if a required system tool is
missing.
"""
self.git = self.integrations.git.verify_git_is_installed(self)
def __call__(self, template: Optional[str] = None, **options):
# Confirm all required tools are available
self.verify_tools()
return self.new_app(template=template, **options)
| 8,084 |
743 |
package pl.allegro.tech.hermes.client.metrics;
import pl.allegro.tech.hermes.client.HermesMessage;
import pl.allegro.tech.hermes.client.HermesResponse;
import pl.allegro.tech.hermes.client.MessageDeliveryListener;
import java.util.HashMap;
import java.util.Map;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
public class MetricsMessageDeliveryListener implements MessageDeliveryListener {
private final MetricsProvider metrics;
public MetricsMessageDeliveryListener(MetricsProvider metrics) {
this.metrics = metrics;
}
@Override
public void onSend(HermesResponse response, long latency) {
HermesMessage message = response.getHermesMessage();
String topic = MetricsUtils.sanitizeTopic(message.getTopic());
metrics.timerRecord(topic, "latency", latency, NANOSECONDS);
Map<String, String> tags = new HashMap<>();
tags.put("code", String.valueOf(response.getHttpStatus()));
metrics.counterIncrement(topic, "status", tags);
counterIncrementIf(topic, "publish.failure", response.isFailure());
}
@Override
public void onFailure(HermesResponse response, int attemptCount) {
String topic = MetricsUtils.sanitizeTopic(response.getHermesMessage().getTopic());
metrics.counterIncrement(topic, "failure");
}
@Override
public void onFailedRetry(HermesResponse response, int attemptCount) {
String topic = MetricsUtils.sanitizeTopic(response.getHermesMessage().getTopic());
metrics.counterIncrement(topic, "retries.count");
metrics.counterIncrement(topic, "failure");
metrics.counterIncrement(topic, "publish.retry.failure");
}
@Override
public void onSuccessfulRetry(HermesResponse response, int attemptCount) {
String topic = MetricsUtils.sanitizeTopic(response.getHermesMessage().getTopic());
metrics.counterIncrement(topic, "retries.success");
metrics.histogramUpdate(topic, "retries.attempts", attemptCount - 1);
boolean wasRetried = attemptCount > 1;
metrics.counterIncrement(topic, "publish.attempt");
counterIncrementIf(topic, "publish.retry.success", response.isSuccess() && wasRetried);
counterIncrementIf(topic, "publish.finally.success", response.isSuccess());
counterIncrementIf(topic, "publish.retry.failure", response.isFailure() && wasRetried);
counterIncrementIf(topic, "publish.finally.failure", response.isFailure());
counterIncrementIf(topic, "publish.retry.attempt", wasRetried);
}
@Override
public void onMaxRetriesExceeded(HermesResponse response, int attemptCount) {
String topic = MetricsUtils.sanitizeTopic(response.getHermesMessage().getTopic());
metrics.counterIncrement(topic, "retries.exhausted");
metrics.counterIncrement(topic, "publish.finally.failure");
metrics.counterIncrement(topic, "publish.attempt");
metrics.counterIncrement(topic, "publish.retry.attempt");
}
private void counterIncrementIf(String topic, String name, boolean condition) {
if (condition) {
metrics.counterIncrement(topic, name);
}
}
}
| 1,139 |
382 |
package rpc.turbo.util;
import io.netty.buffer.ByteBuf;
public class ByteBufUtils {
public static void writeVarInt(ByteBuf byteBuf, int value) {
if (value >>> 7 == 0) {
byteBuf.writeByte((byte) value);
return;
}
if (value >>> 14 == 0) {
int newValue = (((value & 0x7F) | 0x80) << 8) | (value >>> 7);
byteBuf.writeShort(newValue);
return;
}
if (value >>> 21 == 0) {
int newValue = (((value & 0x7F) | 0x80) << 8) | (value >>> 7 & 0xFF | 0x80);
byteBuf.writeShort(newValue);
byteBuf.writeByte((byte) (value >>> 14));
return;
}
if (value >>> 28 == 0) {
int newValue = (((value & 0x7F) | 0x80) << 24) //
| ((value >>> 7 & 0xFF | 0x80) << 16) //
| ((value >>> 14 & 0xFF | 0x80) << 8) //
| (value >>> 21);
byteBuf.writeInt(newValue);
return;
}
int newValue = (((value & 0x7F) | 0x80) << 24) //
| ((value >>> 7 & 0xFF | 0x80) << 16) //
| ((value >>> 14 & 0xFF | 0x80) << 8) //
| (value >>> 21 & 0xFF | 0x80);
byteBuf.writeInt(newValue);
byteBuf.writeByte((byte) (value >>> 28));
}
public static int readVarInt(ByteBuf byteBuf) {
int b = byteBuf.readByte();
int result = b & 0x7F;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (b & 0x7F) << 7;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (b & 0x7F) << 14;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (b & 0x7F) << 21;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (b & 0x7F) << 28;
}
}
}
}
return result;
}
// 性能提升有限,一个byte的情况性能还会下降。不推荐使用
public static int readVarIntByInt(ByteBuf byteBuf) {
int readerIndex = byteBuf.readerIndex();
int value = byteBuf.readIntLE();
int b = value;
int result = b & 0x7F;
if ((b & 0x80) == 0) {
byteBuf.readerIndex(readerIndex + 1);
return result;
}
b = (value >> 8);
result |= (b & 0x7F) << 7;
if ((b & 0x80) == 0) {
byteBuf.readerIndex(readerIndex + 2);
return result;
}
b = (value >> 16);
result |= (b & 0x7F) << 14;
if ((b & 0x80) == 0) {
byteBuf.readerIndex(readerIndex + 3);
return result;
}
b = (value >>> 24);
result |= (b & 0x7F) << 21;
if ((b & 0x80) == 0) {
return result;
}
b = byteBuf.readByte();
result |= (b & 0x7F) << 28;
return result;
}
// 性能提升有限,一个byte的情况性能还会下降。不推荐使用
public static int readVarIntByLong(ByteBuf byteBuf) {
int readerIndex = byteBuf.readerIndex();
long value = byteBuf.readLongLE();
int b = (int) value;
int result = b & 0x7F;
if ((b & 0x80) == 0) {
byteBuf.readerIndex(readerIndex + 1);
return result;
}
b = (int) (value >> 8);
result |= (b & 0x7F) << 7;
if ((b & 0x80) == 0) {
byteBuf.readerIndex(readerIndex + 2);
return result;
}
b = (int) (value >> 16);
result |= (b & 0x7F) << 14;
if ((b & 0x80) == 0) {
byteBuf.readerIndex(readerIndex + 3);
return result;
}
b = (int) (value >> 24);
result |= (b & 0x7F) << 21;
if ((b & 0x80) == 0) {
byteBuf.readerIndex(readerIndex + 4);
return result;
}
b = (int) (value >> 32);
result |= (b & 0x7F) << 28;
byteBuf.readerIndex(readerIndex + 5);
return result;
}
public static void writeVarLong(ByteBuf byteBuf, long value) {
if (value >>> 7 == 0) {
byteBuf.writeByte((byte) value);
return;
}
if (value >>> 14 == 0) {
int intValue = (int) value;
int newValue = (((intValue & 0x7F) | 0x80) << 8) | (intValue >>> 7);
byteBuf.writeShort(newValue);
return;
}
if (value >>> 21 == 0) {
int intValue = (int) value;
int newValue = (((intValue & 0x7F) | 0x80) << 8) | (intValue >>> 7 & 0xFF | 0x80);
byteBuf.writeShort(newValue);
byteBuf.writeByte((byte) (intValue >>> 14));
return;
}
if (value >>> 28 == 0) {
int intValue = (int) value;
int newValue = (((intValue & 0x7F) | 0x80) << 24) //
| ((intValue >>> 7 & 0xFF | 0x80) << 16) //
| ((intValue >>> 14 & 0xFF | 0x80) << 8) //
| (intValue >>> 21);
byteBuf.writeInt(newValue);
return;
}
if (value >>> 35 == 0) {
int intValue = (int) value;
int newValue = (((intValue & 0x7F) | 0x80) << 24) //
| ((intValue >>> 7 & 0xFF | 0x80) << 16) //
| ((intValue >>> 14 & 0xFF | 0x80) << 8) //
| (intValue >>> 21 & 0xFF | 0x80);
byteBuf.writeInt(newValue);
byteBuf.writeByte((byte) (value >>> 28));
return;
}
if (value >>> 42 == 0) {
int intValue = (int) value;
int first = (((intValue & 0x7F) | 0x80) << 24) //
| ((intValue >>> 7 & 0xFF | 0x80) << 16) //
| ((intValue >>> 14 & 0xFF | 0x80) << 8) //
| (intValue >>> 21 & 0xFF | 0x80);
byteBuf.writeInt(first);
int second = (int) (((value >>> 28 & 0xFF | 0x80) << 8) //
| (value >>> 35));
byteBuf.writeShort(second);
return;
}
if (value >>> 49 == 0) {
int intValue = (int) value;
int first = (((intValue & 0x7F) | 0x80) << 24) //
| ((intValue >>> 7 & 0xFF | 0x80) << 16) //
| ((intValue >>> 14 & 0xFF | 0x80) << 8) //
| (intValue >>> 21 & 0xFF | 0x80);
byteBuf.writeInt(first);
int second = (int) (((value >>> 28 & 0xFF | 0x80) << 8) //
| (value >>> 35 & 0xFF | 0x80));
byteBuf.writeShort(second);
byteBuf.writeByte((byte) (value >>> 42));
return;
}
if (value >>> 56 == 0) {
int intValue = (int) value;
int first = (((intValue & 0x7F) | 0x80) << 24) //
| ((intValue >>> 7 & 0xFF | 0x80) << 16) //
| ((intValue >>> 14 & 0xFF | 0x80) << 8) //
| (intValue >>> 21 & 0xFF | 0x80);
byteBuf.writeInt(first);
intValue = (int) (value >>> 28);
int second = (((intValue & 0x7F) | 0x80) << 24) //
| ((intValue >>> 7 & 0xFF | 0x80) << 16) //
| ((intValue >>> 14 & 0xFF | 0x80) << 8) //
| (intValue >>> 21);
byteBuf.writeInt(second);
return;
}
int intValue = (int) value;
int first = (((intValue & 0x7F) | 0x80) << 24) //
| ((intValue >>> 7 & 0xFF | 0x80) << 16) //
| ((intValue >>> 14 & 0xFF | 0x80) << 8) //
| (intValue >>> 21 & 0xFF | 0x80);
byteBuf.writeInt(first);
intValue = (int) (value >>> 28);
int second = (((intValue & 0x7F) | 0x80) << 24) //
| ((intValue >>> 7 & 0xFF | 0x80) << 16) //
| ((intValue >>> 14 & 0xFF | 0x80) << 8) //
| (intValue >>> 21 & 0xFF | 0x80);
byteBuf.writeInt(second);
byteBuf.writeByte((byte) (value >>> 56));
return;
}
public static long readVarLong(ByteBuf byteBuf) {
int b = byteBuf.readByte();
long result = b & 0x7F;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (b & 0x7F) << 7;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (b & 0x7F) << 14;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (b & 0x7F) << 21;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (long) (b & 0x7F) << 28;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (long) (b & 0x7F) << 35;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (long) (b & 0x7F) << 42;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (long) (b & 0x7F) << 49;
if ((b & 0x80) != 0) {
b = byteBuf.readByte();
result |= (long) b << 56;
}
}
}
}
}
}
}
}
return result;
}
}
| 3,673 |
902 |
<reponame>MrYKK/chat
package org.anychat.dao.ext;
import java.util.List;
import org.anychat.model.base.ChatGroup;
import org.anychat.model.base.ChatGroupUserCriteria;
public interface ChatGroupUserMapperExt {
List<ChatGroup> selectByExample(ChatGroupUserCriteria example);
}
| 103 |
521 |
<reponame>zai1208/fbc
/* get localized short DATE format */
#include "../fb.h"
#include "fb_private_intl.h"
int fb_DrvIntlGetDateFormat( char *buffer, size_t len )
{
char *pszName;
char achFormat[90];
char achOrder[3] = { 0 };
char achDayZero[2], *pszDayZero;
char achMonZero[2], *pszMonZero;
char achDate[2], *pszDate;
size_t i;
DBG_ASSERT(buffer!=NULL);
/* Can I use this? The problem is that it returns the date format
* with localized separators. */
pszName = fb_hGetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE,
achFormat, sizeof(achFormat) - 1 );
if( pszName!=NULL ) {
size_t uiNameSize = strlen(pszName);
if( uiNameSize < len ) {
strcpy( buffer, pszName );
return TRUE;
} else {
return FALSE;
}
}
/* Fall back for Win95 and WinNT < 4.0 */
pszDayZero = fb_hGetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_IDAYLZERO,
achDayZero, sizeof(achDayZero) );
pszMonZero = fb_hGetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_IMONLZERO,
achMonZero, sizeof(achMonZero) );
pszDate = fb_hGetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_IDATE,
achDate, sizeof(achDate) );
if( pszDate!=NULL && pszDayZero!=0 && pszMonZero!=0 ) {
switch( atoi( pszDate ) ) {
case 0:
FB_MEMCPY(achOrder, "mdy", 3);
break;
case 1:
FB_MEMCPY(achOrder, "dmy", 3);
break;
case 2:
FB_MEMCPY(achOrder, "ymd", 3);
break;
default:
break;
}
if( achOrder[0]!=0 ) {
size_t remaining = len - 1;
int day_lead_zero = atoi( pszDayZero ) != 0;
int mon_lead_zero = atoi( pszMonZero ) != 0;
for(i=0; i!=3; ++i) {
const char *pszAdd = NULL;
size_t add_len;
switch ( achOrder[i] ) {
case 'm':
if( mon_lead_zero ) {
pszAdd = "MM";
} else {
pszAdd = "M";
}
break;
case 'd':
if( day_lead_zero ) {
pszAdd = "dd";
} else {
pszAdd = "d";
}
break;
case 'y':
pszAdd = "yyyy";
break;
}
add_len = strlen(pszAdd);
if( remaining < add_len )
return FALSE;
strcpy( buffer, pszAdd );
buffer += add_len;
remaining -= add_len;
if( i!=2 ) {
if( remaining==0 )
return FALSE;
strcpy( buffer, "/" );
buffer += 1;
remaining -= 1;
}
}
return TRUE;
}
}
return FALSE;
}
| 1,933 |
626 |
<reponame>zoercai/opencensus-java
/*
* Copyright 2017, OpenCensus 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 io.opencensus.tags.unsafe;
import io.grpc.Context;
import io.opencensus.internal.Utils;
import io.opencensus.tags.Tag;
import io.opencensus.tags.TagContext;
import java.util.Collections;
import java.util.Iterator;
import javax.annotation.concurrent.Immutable;
/*>>>
import org.checkerframework.checker.nullness.qual.Nullable;
*/
/**
* Utility methods for accessing the {@link TagContext} contained in the {@link io.grpc.Context}.
*
* <p>Most code should interact with the current context via the public APIs in {@link
* io.opencensus.tags.TagContext} and avoid accessing {@link #TAG_CONTEXT_KEY} directly.
*
* @since 0.8
*/
public final class ContextUtils {
private static final TagContext EMPTY_TAG_CONTEXT = new EmptyTagContext();
private ContextUtils() {}
/**
* The {@link io.grpc.Context.Key} used to interact with the {@code TagContext} contained in the
* {@link io.grpc.Context}.
*/
private static final Context.Key</*@Nullable*/ TagContext> TAG_CONTEXT_KEY =
Context.keyWithDefault("opencensus-tag-context-key", EMPTY_TAG_CONTEXT);
/**
* Creates a new {@code Context} with the given value set.
*
* @param context the parent {@code Context}.
* @param tagContext the value to be set.
* @return a new context with the given value set.
* @since 0.21
*/
public static Context withValue(
Context context, @javax.annotation.Nullable TagContext tagContext) {
return Utils.checkNotNull(context, "context").withValue(TAG_CONTEXT_KEY, tagContext);
}
/**
* Returns the value from the specified {@code Context}.
*
* @param context the specified {@code Context}.
* @return the value from the specified {@code Context}.
* @since 0.21
*/
public static TagContext getValue(Context context) {
@javax.annotation.Nullable TagContext tags = TAG_CONTEXT_KEY.get(context);
return tags == null ? EMPTY_TAG_CONTEXT : tags;
}
@Immutable
private static final class EmptyTagContext extends TagContext {
@Override
protected Iterator<Tag> getIterator() {
return Collections.<Tag>emptySet().iterator();
}
}
}
| 864 |
439 |
<gh_stars>100-1000
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class AtbashTest {
private Atbash atbash;
@Before
public void setup() {
atbash = new Atbash();
}
@Test
public void testEncodeYes() {
assertThat(atbash.encode("yes")).isEqualTo("bvh");
}
@Ignore("Remove to run test")
@Test
public void testEncodeNo() {
assertThat(atbash.encode("no")).isEqualTo("ml");
}
@Ignore("Remove to run test")
@Test
public void testEncodeOmgInCapital() {
assertThat(atbash.encode("OMG")).isEqualTo("lnt");
}
@Ignore("Remove to run test")
@Test
public void testEncodeOmgWithSpaces() {
assertThat(atbash.encode("O M G")).isEqualTo("lnt");
}
@Ignore("Remove to run test")
@Test
public void testEncodeMindBlowingly() {
assertThat(atbash.encode("mindblowingly")).isEqualTo("nrmwy oldrm tob");
}
@Ignore("Remove to run test")
@Test
public void testEncodeNumbers() {
assertThat(atbash.encode("Testing,1 2 3, testing."))
.isEqualTo("gvhgr mt123 gvhgr mt");
}
@Ignore("Remove to run test")
@Test
public void testEncodeDeepThought() {
assertThat(atbash.encode("Truth is fiction."))
.isEqualTo("gifgs rhurx grlm");
}
@Ignore("Remove to run test")
@Test
public void testEncodeAllTheLetters() {
assertThat(atbash.encode("The quick brown fox jumps over the lazy dog."))
.isEqualTo("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt");
}
@Ignore("Remove to run test")
@Test
public void testDecodeExercism() {
assertThat(atbash.decode("vcvix rhn")).isEqualTo("exercism");
}
@Ignore("Remove to run test")
@Test
public void testDecodeASentence() {
assertThat(atbash.decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v"))
.isEqualTo("anobstacleisoftenasteppingstone");
}
@Ignore("Remove to run test")
@Test
public void testDecodeNumbers() {
assertThat(atbash.decode("gvhgr mt123 gvhgr mt"))
.isEqualTo("testing123testing");
}
@Ignore("Remove to run test")
@Test
public void testDecodeAllTheLetters() {
assertThat(atbash.decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt"))
.isEqualTo("thequickbrownfoxjumpsoverthelazydog");
}
@Ignore("Remove to run test")
@Test
public void testDecodeWithTooManySpaces() {
assertThat(atbash.decode("vc vix r hn")).isEqualTo("exercism");
}
@Ignore("Remove to run test")
@Test
public void testDecodeWithNoSpaces() {
assertThat(atbash.decode("zmlyhgzxovrhlugvmzhgvkkrmthglmv"))
.isEqualTo("anobstacleisoftenasteppingstone");
}
}
| 1,309 |
10,225 |
package io.quarkus.runtime.configuration;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import org.eclipse.microprofile.config.spi.ConfigSource;
import org.eclipse.microprofile.config.spi.ConfigSourceProvider;
public class RuntimeConfigSource implements ConfigSourceProvider {
private final String configSourceClassName;
public RuntimeConfigSource(final String configSourceClassName) {
this.configSourceClassName = configSourceClassName;
}
@Override
public Iterable<ConfigSource> getConfigSources(final ClassLoader forClassLoader) {
try {
Class<ConfigSource> configSourceClass = (Class<ConfigSource>) forClassLoader.loadClass(configSourceClassName);
ConfigSource configSource = configSourceClass.getDeclaredConstructor().newInstance();
return Collections.singleton(configSource);
} catch (ClassNotFoundException | InstantiationException | InvocationTargetException | NoSuchMethodException
| IllegalAccessException e) {
throw new ConfigurationException(e);
}
}
}
| 356 |
3,428 |
{"id":"01661","group":"easy-ham-1","checksum":{"type":"MD5","value":"1393ea887720c777d1429b07fce98ab4"},"text":"Return-Path: [email protected]\nDelivery-Date: Fri Sep 6 18:13:17 2002\nFrom: <EMAIL> (Neale Pickett)\nDate: 06 Sep 2002 10:13:17 -0700\nSubject: [Spambayes] Deployment\nIn-Reply-To: <2<EMAIL>06150<EMAIL>F<EMAIL>>\nReferences: <2<EMAIL>>\n\t<[email protected]>\n\t<2<EMAIL>>\nMessage-ID: <<EMAIL>>\n\nSo then, <NAME> <<EMAIL>> is all like:\n\n> > Basic procmail usage goes something like this:\n> > \n> > :0fw\n> > | spamassassin -P\n> > \n> > :0\n> > * ^X-Spam-Status: Yes\n> > $SPAM\n> > \n> \n> Do you feel capable of writing such a tool? It doesn't look too hard.\n\nNot to beat a dead horse, but that's exactly what my spamcan package\ndid. For those just tuning in, spamcan is a thingy I wrote before I\nknew about Tim & co's work on this crazy stuff; you can download it from\n<http://woozle.org/~neale/src/spamcan/spamcan.html>, but I'm not going\nto work on it anymore.\n\nI'm currently writing a new one based on classifier (and timtest's\nbooty-kicking tokenizer). I'll probably have something soon, like maybe\nhalf an hour, and no, it's not too hard. The hard part is storing the\ndata somewhere. I don't want to use ZODB, as I'd like something a\nperson can just drop in with a default Python install. So anydbm is\nlooking like my best option.\n\nI already have a setup like this using Xavier Leroy's SpamOracle, which\ndoes the same sort of thing. You call it from procmail, it adds a new\nheader, and then you can filter on that header. Really easy.\n\nHere's how I envision this working. Everybody gets four new mailboxes:\n\n train-eggs\n train-spam\n trained-eggs\n trained-spam\n\nYou copy all your spam and eggs* into the \"train-\" boxes as you get it.\nHow frequently you do this would be up to you, but you'd get better\nresults if you did it more often, and you'd be wise to always copy over\nanything which was misclassified. Then, every night, the spam fairy\nswoops down and reads through your folders, learning about what sorts of\nthings you think are eggs and what sorts of things are spam. After she's\ndone, she moves your mail into the \"trained-\" folders.\n\nThis would work for anybody using IMAP on a Unix box, or folks who read\ntheir mail right off the server. I've spoken with some fellows at work\nabout Exchange and they seem to beleive that Exchange exports\nappropriate functionality to implement a spam fairy as well.\n\nAdvanced users could stay ahead of the game by reprogramming their mail\nclient to bind the key \"S\" to \"move to train-spam\" and \"H\" to \"move to\ntrain-eggs\". Eventually, if enough people used this sort of thing, it'd\nstart showing up in mail clients. That's the \"delete as spam\" button\n<NAME> was talking about.\n\n* The Hormel company might not think well of using the word \"ham\" as the\n opposite of \"spam\", and they've been amazingly cool about the use of\n their product name for things thus far. So I propose we start calling\n non-spam something more innocuous (and more Monty Pythonic) such as\n \"eggs\".\n\nNeale\n"}
| 1,037 |
1,305 |
<reponame>terminux/jdk1.7.0_80
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.corba.se.impl.dynamicany;
import org.omg.CORBA.TypeCode;
import org.omg.CORBA.TCKind;
import org.omg.CORBA.Any;
import org.omg.CORBA.TypeCodePackage.BadKind;
import org.omg.CORBA.TypeCodePackage.Bounds;
import org.omg.DynamicAny.*;
import org.omg.DynamicAny.DynAnyPackage.TypeMismatch;
import org.omg.DynamicAny.DynAnyPackage.InvalidValue;
import org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode;
import com.sun.corba.se.spi.orb.ORB ;
import com.sun.corba.se.spi.logging.CORBALogDomains ;
import com.sun.corba.se.impl.logging.ORBUtilSystemException ;
public class DynStructImpl extends DynAnyComplexImpl implements DynStruct
{
//
// Constructors
//
private DynStructImpl() {
this(null, (Any)null, false);
}
protected DynStructImpl(ORB orb, Any any, boolean copyValue) {
// We can be sure that typeCode is of kind tk_struct
super(orb, any, copyValue);
// Initialize components lazily, on demand.
// This is an optimization in case the user is only interested in storing Anys.
}
protected DynStructImpl(ORB orb, TypeCode typeCode) {
// We can be sure that typeCode is of kind tk_struct
super(orb, typeCode);
// For DynStruct, the operation sets the current position to -1
// for empty exceptions and to zero for all other TypeCodes.
// The members (if any) are (recursively) initialized to their default values.
index = 0;
}
//
// Methods differing from DynValues
//
public org.omg.DynamicAny.NameValuePair[] get_members () {
if (status == STATUS_DESTROYED) {
throw wrapper.dynAnyDestroyed() ;
}
checkInitComponents();
return nameValuePairs;
}
public org.omg.DynamicAny.NameDynAnyPair[] get_members_as_dyn_any () {
if (status == STATUS_DESTROYED) {
throw wrapper.dynAnyDestroyed() ;
}
checkInitComponents();
return nameDynAnyPairs;
}
}
| 905 |
1,275 |
<gh_stars>1000+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.segment.spi.loader;
import org.apache.pinot.spi.config.table.TableConfig;
import org.apache.pinot.spi.env.PinotConfiguration;
/**
* Context for {@link SegmentDirectoryLoader}
*/
public class SegmentDirectoryLoaderContext {
private final TableConfig _tableConfig;
private final String _instanceId;
private final String _segmentName;
private final PinotConfiguration _segmentDirectoryConfigs;
public SegmentDirectoryLoaderContext(TableConfig tableConfig, String instanceId, String segmentName,
PinotConfiguration segmentDirectoryConfigs) {
_tableConfig = tableConfig;
_instanceId = instanceId;
_segmentName = segmentName;
_segmentDirectoryConfigs = segmentDirectoryConfigs;
}
public TableConfig getTableConfig() {
return _tableConfig;
}
public String getInstanceId() {
return _instanceId;
}
public String getSegmentName() {
return _segmentName;
}
public PinotConfiguration getSegmentDirectoryConfigs() {
return _segmentDirectoryConfigs;
}
}
| 515 |
565 |
<filename>numerics/cbrt.hpp
#pragma once
namespace principia {
namespace numerics {
namespace internal_cbrt {
// Computes ∛y, correctly rounded to nearest.
double Cbrt(double y);
// Specific methods, uncorrected rounding, and the corrector function exposed
// for testing.
// See documentation/cbrt.pdf, appendix F, for the naming of the methods and the
// misrounding rates of the unfaithful versions.
enum class Rounding {
Faithful,
Correct,
};
namespace method_3²ᴄZ5¹ {
template<Rounding rounding>
double Cbrt(double y);
extern template double Cbrt<Rounding::Faithful>(double y);
extern template double Cbrt<Rounding::Correct>(double y);
} // namespace method_3²ᴄZ5¹
namespace method_5²Z4¹FMA {
template<Rounding rounding>
double Cbrt(double y);
extern template double Cbrt<Rounding::Faithful>(double y);
extern template double Cbrt<Rounding::Correct>(double y);
} // namespace method_5²Z4¹FMA
// Computes one additional bit of ∛y, rounded toward 0.
// All arguments must be positive.
// a is the already-computed approximation of the cube root.
// b is the bit being computed; it must be a power of 2.
// The least significant bit of a must be greater than b.
// ∛y must lie in [a, a + 2b[.
// The result is the value of ∛y ≥ a + b, i.e., the value of the bit b in the
// binary expansion of ∛y.
bool CbrtOneBit(double y, double a, double b);
} // namespace internal_cbrt
using internal_cbrt::Cbrt;
} // namespace numerics
} // namespace principia
| 488 |
1,299 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tika.parser.wordperfect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* WordPerfect 5.x constant values used for mapping WordPerfect charsets to
* unicode equivalents when possible.
*
* @author <NAME>
*/
final class WP5Charsets {
/**
* Extended character sets used when fixed-length multi-byte functions
* with a byte value of 192 (0xC0) are found in a WordPerfect document.
* Those character set codes may be specific to WordPerfect
* file specifications and may or may not be considered standard
* outside WordPerfect. Applies to version 5.x.
*/
public static final char[][] EXTENDED_CHARSETS = new char[][]{
// WP Charset 0: ASCII (same as WP6)
WP6Charsets.EXTENDED_CHARSETS[0],
// WP Charset 1: Multinational 1 (same as WP6)
WP6Charsets.EXTENDED_CHARSETS[1],
// WP Charset 2: Multinational 2 (28 chars)
{'\u0323', '\u0324', '\u02da', '\u0325', '\u02bc', '\u032d', '\u2017', '\u005f',
'\u0138', '\u032e', '\u033e', '\u2018', '\u0020', '\u02bd', '\u02db', '\u0327',
'\u0321', '\u0322', '\u030d', '\u2019', '\u0329', '\u0020', '\u0621', '\u02be',
'\u0306', '\u0310', '\u2032', '\u2034'},
// WP Charset 3: Box Drawing (same as WP6)
WP6Charsets.EXTENDED_CHARSETS[3],
// WP Charset 4: Typographic Symbols (same as WP6)
WP6Charsets.EXTENDED_CHARSETS[4],
// WP Charset 5: Iconic Symbol (35 chars)
{'\u2665', '\u2666', '\u2663', '\u2660', '\u2642', '\u2640', '\u263c', '\u263a',
'\u263b', '\u266a', '\u266c', '\u25ac', '\u2302', '\u203c', '\u221a', '\u21a8',
'\u2310', '\u2319', '\u25d8', '\u25d9', '\u21b5', '\u261e', '\u261c', '\u2713',
'\u2610', '\u2612', '\u2639', '\u266f', '\u266d', '\u266e', '\u260e', '\u231a',
'\u231b', '\u2104', '\u23b5'},
// WP Charset 6: Math/Scientific (same as WP6)
WP6Charsets.EXTENDED_CHARSETS[6],
// WP Charset 7 Math/Scientific Extended (same as WP6)
WP6Charsets.EXTENDED_CHARSETS[7],
// WP Charset 8: Greek (210 chars)
{'\u0391', '\u03b1', '\u0392', '\u03b2', '\u0392', '\u03d0', '\u0393', '\u03b3',
'\u0394', '\u03b4', '\u0395', '\u03b5', '\u0396', '\u03b6', '\u0397', '\u03b7',
'\u0398', '\u03b8', '\u0399', '\u03b9', '\u039a', '\u03ba', '\u039b', '\u03bb',
'\u039c', '\u03bc', '\u039d', '\u03bd', '\u039e', '\u03be', '\u039f', '\u03bf',
'\u03a0', '\u03c0', '\u03a1', '\u03c1', '\u03a3', '\u03c3', '\u03f9', '\u03db',
'\u03a4', '\u03c4', '\u03a5', '\u03c5', '\u03a6', '\u03d5', '\u03a7', '\u03c7',
'\u03a8', '\u03c8', '\u03a9', '\u03c9', '\u03ac', '\u03ad', '\u03ae', '\u03af',
'\u03ca', '\u03cc', '\u03cd', '\u03cb', '\u03ce', '\u03b5', '\u03d1', '\u03f0',
'\u03d6', '\u1fe5', '\u03d2', '\u03c6', '\u03c9', '\u037e', '\u0387', '\u0384',
'\u00a8', '\u0385', '\u1fed', '\u1fef', '\u1fc0', '\u1fbd', '\u1fbf', '\u1fbe',
'\u1fce', '\u1fde', '\u1fcd', '\u1fdd', '\u1fcf', '\u1fdf', '\u0384', '\u1fef',
'\u1fc0', '\u1fbd', '\u1fbf', '\u1fce', '\u1fde', '\u1fcd', '\u1fdd', '\u1fcf',
'\u1fdf', '\u1f70', '\u1fb6', '\u1fb3', '\u1fb4', '\u1fb7', '\u1f00', '\u1f04',
'\u1f02', '\u1f06', '\u1f80', '\u1f84', '\u1f86', '\u1f01', '\u1f05', '\u1f03',
'\u1f07', '\u1f81', '\u1f85', '\u1f87', '\u1f72', '\u1f10', '\u1f14', '\u1f13',
'\u1f11', '\u1f15', '\u1f13', '\u1f74', '\u1fc6', '\u1fc3', '\u1fc4', '\u1fc2',
'\u1fc7', '\u1f20', '\u1f24', '\u1f22', '\u1f26', '\u1f90', '\u1f94', '\u1f96',
'\u1f21', '\u1f25', '\u1f23', '\u1f27', '\u1f91', '\u1f95', '\u1f97', '\u1f76',
'\u1fd6', '\u0390', '\u1fd2', '\u1f30', '\u1f34', '\u1f32', '\u1f36', '\u1f31',
'\u1f35', '\u1f33', '\u1f37', '\u1f78', '\u1f40', '\u1f44', '\u1f42', '\u1f41',
'\u1f45', '\u1f43', '\u1f7a', '\u1fe6', '\u03b0', '\u1fe3', '\u1f50', '\u1f54',
'\u1f52', '\u1f56', '\u1f51', '\u1f55', '\u1f53', '\u1f57', '\u1f7c', '\u1ff6',
'\u1ff3', '\u1ff4', '\u1ff2', '\u1ff7', '\u1f60', '\u1f64', '\u1f62', '\u1f66',
'\u1fa0', '\u1fa4', '\u1fa6', '\u1f61', '\u1f65', '\u1f63', '\u1f67', '\u1fa1',
'\u1fa5', '\u1fa7', '\u0374', '\u0375', '\u03db', '\u03dd', '\u03d9', '\u03e1',
'\u0386', '\u0388', '\u0389', '\u038a', '\u038c', '\u038e', '\u038f', '\u03aa',
'\u03ab', '\u1fe5'},
// WP Charset 9: Hebrew (119 chars)
{'\u05d0', '\u05d1', '\u05d2', '\u05d3', '\u05d4', '\u05d5', '\u05d6', '\u05d7',
'\u05d8', '\u05d9', '\u05da', '\u05db', '\u05dc', '\u05dd', '\u05de', '\u05df',
'\u05e0', '\u05e1', '\u05e2', '\u05e3', '\u05e4', '\u05e5', '\u05e6', '\u05e7',
'\u05e8', '\u05e9', '\u05ea', '\u05be', '\u05c0', '\u05c3', '\u05f3', '\u05f4',
'\u05b0', '\u05b1', '\u05b2', '\u05b3', '\u05b4', '\u05b5', '\u05b6', '\u05b7',
'\u05b8', '\u05b9', '\u05ba', '\u05bb', '\u05bc', '\u05bd', '\u05bf', '\u05b7',
'\ufbe1', '\u05f0', '\u05f1', '\u05f2', '\u0591', '\u0596', '\u05ad', '\u05a4',
'\u059a', '\u059b', '\u05a3', '\u05a5', '\u05a6', '\u05a7', '\u09aa', '\u0592',
'\u0593', '\u0594', '\u0595', '\u0597', '\u0598', '\u0599', '\u05a8', '\u059c',
'\u059d', '\u059e', '\u05a1', '\u05a9', '\u05a0', '\u059f', '\u05ab', '\u05ac',
'\u05af', '\u05c4', '\u0544', '\u05d0', '\ufb31', '\ufb32', '\ufb33', '\ufb34',
'\ufb35', '\ufb4b', '\ufb36', '\u05d7', '\ufb38', '\ufb39', '\ufb3b', '\ufb3a',
'\u05da', '\u05da', '\u05da', '\u05da', '\u05da', '\u05da', '\ufb3c', '\ufb3e',
'\ufb40', '\u05df', '\ufb41', '\ufb44', '\ufb46', '\ufb47', '\ufb2b', '\ufb2d',
'\ufb2a', '\ufb2c', '\ufb4a', '\ufb4c', '\ufb4e', '\ufb1f', '\ufb1d'},
// WP Charset 10: Cyrillic (150 chars)
{'\u0410', '\u0430', '\u0411', '\u0431', '\u0412', '\u0432', '\u0413', '\u0433',
'\u0414', '\u0434', '\u0415', '\u0435', '\u0401', '\u0451', '\u0416', '\u0436',
'\u0417', '\u0437', '\u0418', '\u0438', '\u0419', '\u0439', '\u041a', '\u043a',
'\u041b', '\u043b', '\u041c', '\u043c', '\u041d', '\u043d', '\u041e', '\u043e',
'\u041f', '\u043f', '\u0420', '\u0440', '\u0421', '\u0441', '\u0422', '\u0442',
'\u0423', '\u0443', '\u0424', '\u0444', '\u0425', '\u0445', '\u0426', '\u0446',
'\u0427', '\u0447', '\u0428', '\u0448', '\u0429', '\u0449', '\u042a', '\u044a',
'\u042b', '\u044b', '\u042c', '\u044c', '\u042d', '\u044d', '\u042e', '\u044e',
'\u042f', '\u044f', '\u0490', '\u0491', '\u0402', '\u0452', '\u0403', '\u0453',
'\u0404', '\u0454', '\u0405', '\u0455', '\u0406', '\u0456', '\u0407', '\u0457',
'\u0408', '\u0458', '\u0409', '\u0459', '\u040a', '\u045a', '\u040b', '\u045b',
'\u040c', '\u045c', '\u040e', '\u045e', '\u040f', '\u045f', '\u0462', '\u0463',
'\u0472', '\u0473', '\u0474', '\u0475', '\u046a', '\u046b', '\ua640', '\ua641',
'\u0429', '\u0449', '\u04c0', '\u04cf', '\u0466', '\u0467', '\u0000', '\u0000',
'\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000',
'\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000',
'\u0000', '\u0000', '\u0400', '\u0450', '\u0000', '\u0000', '\u040d', '\u045d',
'\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000',
'\u0000', '\u0000', '\u0000', '\u0000', '\u0301', '\u0300'},
// WP Charset 11: Japanese (185 chars)
{'\u3041', '\u3043', '\u3045', '\u3047', '\u3049', '\u3053', '\u3083', '\u3085',
'\u3087', '\u3094', '\u3095', '\u3096', '\u3042', '\u3044', '\u3046', '\u3048',
'\u304a', '\u304b', '\u304d', '\u3047', '\u3051', '\u3053', '\u304c', '\u304e',
'\u3050', '\u3052', '\u3054', '\u3055', '\u3057', '\u3059', '\u305b', '\u305d',
'\u3056', '\u3058', '\u305a', '\u305c', '\u305e', '\u305f', '\u3051', '\u3064',
'\u3066', '\u3068', '\u3060', '\u3062', '\u3065', '\u3067', '\u3069', '\u306a',
'\u306b', '\u306c', '\u306d', '\u306e', '\u306f', '\u3072', '\u3075', '\u3078',
'\u307b', '\u3070', '\u3073', '\u3076', '\u3079', '\u307c', '\u3071', '\u3074',
'\u3077', '\u307a', '\u307d', '\u307e', '\u307f', '\u3080', '\u3081', '\u3082',
'\u3084', '\u3086', '\u3088', '\u3089', '\u308a', '\u308b', '\u308c', '\u308d',
'\u308e', '\u3092', '\u3093', '\u3014', '\u3015', '\uff3b', '\uff3d', '\u300c',
'\u300d', '\u300c', '\u300d', '\u302a', '\u3002', '\u3001', '\u309d', '\u309e',
'\u3003', '\u30fc', '\u309b', '\u309c', '\u30a1', '\u30a3', '\u30a5', '\u30a7',
'\u30a9', '\u30c3', '\u30e3', '\u30e5', '\u3057', '\u30f4', '\u30f5', '\u30f6',
'\u30a2', '\u30a4', '\u30a6', '\u30a8', '\u30aa', '\u30ab', '\u30ad', '\u30af',
'\u30b1', '\u30b3', '\u30ac', '\u30ae', '\u30b0', '\u30b2', '\u30b4', '\u30b5',
'\u30c4', '\u30b9', '\u30bb', '\u30bd', '\u30b6', '\u30b8', '\u30ba', '\u30bc',
'\u30be', '\u30bf', '\u30c1', '\u30c4', '\u30c6', '\u30c8', '\u30c0', '\u30c2',
'\u30c5', '\u30c7', '\u30c9', '\u30ca', '\u30cb', '\u30cc', '\u30cd', '\u30ce',
'\u30cf', '\u30d2', '\u30d5', '\u30d8', '\u03d0', '\u30db', '\u30d3', '\u30d6',
'\u30d9', '\u30dc', '\u30d1', '\u30d4', '\u30d7', '\u30da', '\u30dd', '\u30de',
'\u30df', '\u30e0', '\u30e1', '\u30e2', '\u30e4', '\u30e6', '\u30e8', '\u30e9',
'\u30ea', '\u30ab', '\u30ec', '\u30ed', '\u30ef', '\u30f2', '\u30f3', '\u30fd',
'\u30fe'},
// WP Charset 12: User-defined (255 chars)
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}};
private static final Logger LOG = LoggerFactory.getLogger(WP5Charsets.class);
//TODO map multi-characters
/**
* Constructor.
*/
private WP5Charsets() {
}
public static void append(StringBuilder out, int charset, int charval) {
if (charset >= WP5Charsets.EXTENDED_CHARSETS.length) {
LOG.debug("Unsupported WordPerfect 5.x charset: {}", charset);
out.append(' ');
} else if (charval >= WP5Charsets.EXTENDED_CHARSETS[charset].length) {
LOG.debug("Unsupported WordPerfect 5.x charset ({}) character value: {}", charset,
charval);
out.append(' ');
} else {
out.append(WP5Charsets.EXTENDED_CHARSETS[charset][charval]);
}
}
}
| 8,559 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay<filename>docs/data/leg-t2/082/08202003.json
{"nom":"Angeville","circ":"2ème circonscription","dpt":"Tarn-et-Garonne","inscrits":178,"abs":86,"votants":92,"blancs":9,"nuls":8,"exp":75,"res":[{"nuance":"FN","nom":"<NAME>","voix":40},{"nuance":"RDG","nom":"Mme <NAME>","voix":35}]}
| 136 |
1,331 |
<gh_stars>1000+
package com.metasploit.meterpreter.stdapi;
import java.io.File;
import com.metasploit.meterpreter.CommandManager;
import com.metasploit.meterpreter.command.CommandId;
import com.metasploit.meterpreter.ExtensionLoader;
/**
* Loader class to register all the stdapi commands.
*
* @author mihi
*/
public class Loader implements ExtensionLoader {
private static File cwd;
public static File getCWD() {
if (null == cwd) {
try {
cwd = new File(".").getCanonicalFile();
}
catch (Exception e) {
cwd = null;
}
}
return cwd;
}
public static File expand(String path) {
File result = new File(path);
if (!result.isAbsolute()) {
result = new File(getCWD(), path);
}
return result;
}
public static void setCWD(File newCWD) {
cwd = newCWD;
}
public void load(CommandManager mgr) throws Exception {
mgr.registerCommand(CommandId.CORE_CHANNEL_OPEN, stdapi_channel_open.class);
mgr.registerCommand(CommandId.STDAPI_FS_CHDIR, stdapi_fs_chdir.class);
mgr.registerCommand(CommandId.STDAPI_FS_DELETE_DIR, stdapi_fs_delete_dir.class);
mgr.registerCommand(CommandId.STDAPI_FS_DELETE_FILE, stdapi_fs_delete_file.class);
mgr.registerCommand(CommandId.STDAPI_FS_FILE_EXPAND_PATH, stdapi_fs_file_expand_path.class, V1_2, V1_5); // %COMSPEC% only
mgr.registerCommand(CommandId.STDAPI_FS_FILE_MOVE, stdapi_fs_file_move.class);
mgr.registerCommand(CommandId.STDAPI_FS_FILE_COPY, stdapi_fs_file_copy.class);
mgr.registerCommand(CommandId.STDAPI_FS_GETWD, stdapi_fs_getwd.class);
mgr.registerCommand(CommandId.STDAPI_FS_LS, stdapi_fs_ls.class);
mgr.registerCommand(CommandId.STDAPI_FS_MKDIR, stdapi_fs_mkdir.class);
mgr.registerCommand(CommandId.STDAPI_FS_MD5, stdapi_fs_md5.class);
mgr.registerCommand(CommandId.STDAPI_FS_SEARCH, stdapi_fs_search.class);
mgr.registerCommand(CommandId.STDAPI_FS_SEPARATOR, stdapi_fs_separator.class);
mgr.registerCommand(CommandId.STDAPI_FS_STAT, stdapi_fs_stat.class, V1_2, V1_6);
mgr.registerCommand(CommandId.STDAPI_FS_SHA1, stdapi_fs_sha1.class);
mgr.registerCommand(CommandId.STDAPI_NET_CONFIG_GET_INTERFACES, stdapi_net_config_get_interfaces.class, V1_4, V1_6);
mgr.registerCommand(CommandId.STDAPI_NET_CONFIG_GET_ROUTES, stdapi_net_config_get_routes.class, V1_4);
mgr.registerCommand(CommandId.STDAPI_NET_SOCKET_TCP_SHUTDOWN, stdapi_net_socket_tcp_shutdown.class, V1_2, V1_3);
mgr.registerCommand(CommandId.STDAPI_NET_RESOLVE_HOST, stdapi_net_resolve_host.class);
mgr.registerCommand(CommandId.STDAPI_NET_RESOLVE_HOSTS, stdapi_net_resolve_hosts.class);
mgr.registerCommand(CommandId.STDAPI_SYS_CONFIG_GETUID, stdapi_sys_config_getuid.class);
mgr.registerCommand(CommandId.STDAPI_SYS_CONFIG_GETENV, stdapi_sys_config_getenv.class);
mgr.registerCommand(CommandId.STDAPI_SYS_CONFIG_SYSINFO, stdapi_sys_config_sysinfo.class);
mgr.registerCommand(CommandId.STDAPI_SYS_CONFIG_LOCALTIME, stdapi_sys_config_localtime.class);
mgr.registerCommand(CommandId.STDAPI_SYS_PROCESS_EXECUTE, stdapi_sys_process_execute.class, V1_2, V1_3);
mgr.registerCommand(CommandId.STDAPI_SYS_PROCESS_CLOSE, stdapi_sys_process_close.class);
mgr.registerCommand(CommandId.STDAPI_SYS_PROCESS_GET_PROCESSES, stdapi_sys_process_get_processes.class, V1_2);
mgr.registerCommand(CommandId.STDAPI_UI_DESKTOP_SCREENSHOT, stdapi_ui_desktop_screenshot.class, V1_4);
mgr.registerCommand(CommandId.STDAPI_UI_SEND_MOUSE, stdapi_ui_send_mouse.class, V1_4);
mgr.registerCommand(CommandId.STDAPI_UI_SEND_KEYEVENT, stdapi_ui_send_keyevent.class, V1_4);
mgr.registerCommand(CommandId.STDAPI_WEBCAM_AUDIO_RECORD, stdapi_webcam_audio_record.class, V1_4);
}
}
| 1,767 |
679 |
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef EVENT_TESTLISTENER_HXX
#define EVENT_TESTLISTENER_HXX
#include <sal/types.h>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>
#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/xml/dom/events/XEventTarget.hpp>
#include <com/sun/star/xml/dom/events/XEventListener.hpp>
#include <com/sun/star/xml/dom/events/XEvent.hpp>
#include <cppuhelper/implbase3.hxx>
using ::rtl::OUString;
using namespace com::sun::star::uno;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::dom::events;
namespace DOM { namespace events
{
typedef ::cppu::WeakImplHelper3
< ::com::sun::star::xml::dom::events::XEventListener
, ::com::sun::star::lang::XInitialization
, ::com::sun::star::lang::XServiceInfo
> CTestListener_Base;
class CTestListener
: public CTestListener_Base
{
private:
Reference< ::com::sun::star::lang::XMultiServiceFactory > m_factory;
Reference <XEventTarget> m_target;
OUString m_type;
sal_Bool m_capture;
OUString m_name;
public:
// static helpers for service info and component management
static const char* aImplementationName;
static const char* aSupportedServiceNames[];
static OUString _getImplementationName();
static Sequence< OUString > _getSupportedServiceNames();
static Reference< XInterface > _getInstance(
const Reference< ::com::sun::star::lang::XMultiServiceFactory >&
rSMgr);
CTestListener(
const Reference< ::com::sun::star::lang::XMultiServiceFactory >&
rSMgr)
: m_factory(rSMgr){};
virtual ~CTestListener();
// XServiceInfo
virtual OUString SAL_CALL getImplementationName()
throw (RuntimeException);
virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName)
throw (RuntimeException);
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames ()
throw (RuntimeException);
// XEventListener
virtual void SAL_CALL initialize(const Sequence< Any >& args) throw (RuntimeException);
virtual void SAL_CALL handleEvent(const Reference< XEvent >& evt) throw (RuntimeException);
};
}}
#endif
| 1,233 |
5,133 |
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.ap.test.bugs._306;
import java.util.Set;
import org.mapstruct.Mapper;
import org.mapstruct.TargetType;
import org.mapstruct.factory.Mappers;
@Mapper
public abstract class Issue306Mapper {
public static final Issue306Mapper INSTANCE = Mappers.getMapper( Issue306Mapper.class );
public abstract Source targetToSource(Target target);
protected void dummy1( Set<String> arg ) {
throw new RuntimeException();
}
protected Set<Long> dummy2( Object object, @TargetType Class<?> clazz ) {
throw new RuntimeException();
}
}
| 239 |
841 |
<reponame>brunolmfg/resteasy
package org.jboss.resteasy.test.injection.resource;
import jakarta.annotation.PostConstruct;
import jakarta.validation.constraints.Size;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
@Path("/normal")
public class PostConstructInjectionResource {
@Size(max=3)
private String s = "ab";
@Path("get")
@GET
public String get() {
return s;
}
@PostConstruct
public void postConstruct() {
s = "abcd";
}
}
| 186 |
716 |
<filename>src/utils/timer.hpp<gh_stars>100-1000
//
// Copyright (c) 2015-2019 CNRS INRIA
//
#ifndef __pinocchio_utils_timer_hpp__
#define __pinocchio_utils_timer_hpp__
#ifdef WIN32
#include <Windows.h>
#include <stdint.h> // portable: uint64_t MSVC: __int64
int gettimeofday(struct timeval* tp, struct timezone* tzp)
{
// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
// This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)
// until 00:00:00 January 1, 1970
static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
time = ((uint64_t)file_time.dwLowDateTime);
time += ((uint64_t)file_time.dwHighDateTime) << 32;
tp->tv_sec = (long)((time - EPOCH) / 10000000L);
tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
return 0;
}
#else
#include <sys/time.h>
#endif
#include <iostream>
#include <stack>
#define SMOOTH(s) for(size_t _smooth=0;_smooth<s;++_smooth)
/* Return the time spent in secs. */
inline double operator-(const struct timeval & t1,const struct timeval & t0)
{
/* TODO: double check the double conversion from long (on 64x). */
return double(t1.tv_sec - t0.tv_sec)+1e-6*double(t1.tv_usec - t0.tv_usec);
}
struct PinocchioTicToc
{
enum Unit { S = 1, MS = 1000, US = 1000000, NS = 1000000000 };
Unit DEFAULT_UNIT;
static std::string unitName(Unit u)
{
switch(u) { case S: return "s"; case MS: return "ms"; case US: return "us"; case NS: return "ns"; }
return "";
}
std::stack<struct timeval> stack;
mutable struct timeval t0;
PinocchioTicToc( Unit def = MS ) : DEFAULT_UNIT(def) {}
inline void tic() {
stack.push(t0);
gettimeofday(&(stack.top()),NULL);
}
inline double toc() { return toc(DEFAULT_UNIT); };
inline double toc(const Unit factor)
{
gettimeofday(&t0,NULL);
double dt = (t0-stack.top())*(double)factor;
stack.pop();
return dt;
}
inline void toc(std::ostream & os, double SMOOTH=1)
{
os << toc(DEFAULT_UNIT)/SMOOTH << " " << unitName(DEFAULT_UNIT) << std::endl;
}
};
#endif // ifndef __pinocchio_utils_timer_hpp__
| 927 |
14,668 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.omnibox;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.spy;
import android.app.Activity;
import android.content.Context;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.EditText;
import android.widget.LinearLayout;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowAccessibilityManager;
import org.robolectric.shadows.ShadowLog;
import org.chromium.base.Log;
import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.test.util.browser.Features;
import org.chromium.chrome.test.util.browser.Features.DisableFeatures;
import org.chromium.chrome.test.util.browser.Features.EnableFeatures;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* A robolectric test for {@link AutocompleteEditText} class.
* TODO(changwan): switch to ParameterizedRobolectricTest once crbug.com/733324 is fixed.
*/
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class AutocompleteEditTextTest {
private static final String TAG = "AutocompleteTest";
private static final boolean DEBUG = false;
// Robolectric's ShadowAccessibilityManager has a bug (crbug.com/756707). Turn this on once it's
// fixed, and you can turn this off temporarily when upgrading robolectric library.
private static final boolean TEST_ACCESSIBILITY = true;
@Rule
public TestRule mProcessor = new Features.JUnitProcessor();
private InOrder mInOrder;
private TestAutocompleteEditText mAutocomplete;
private LinearLayout mFocusPlaceHolder;
private Context mContext;
private InputConnection mInputConnection;
private Verifier mVerifier;
private ShadowAccessibilityManager mShadowAccessibilityManager;
private boolean mIsShown;
/**
* A flag to tweak test expectations to deal with an OS bug.
*
* <p>{@code EditableInputConnection}, which {@link AutocompleteEditText} internally rely on,
* has had <a href="https://issuetracker.google.com/issues/209958658">a bug</a> that it still
* returns {@code true} from {@link InputConnection#endBatchEdit()} when its internal batch edit
* count becomes {@code 0} as a result of invocation, which clearly conflicted with the spec.
* There are several tests in this file that are unfortunately affected by this bug. In order
* to abstract out such an OS issue from the actual test expectations, we will dynamically test
* if the bug still exists or not in the test execution environment or not, and set {@code true}
* to this flag if it is still there.</p>
*
* <p>Until a new version of Android OS with
* <a href="https://android-review.googlesource.com/c/platform/frameworks/base/+/1923058">the
* fix</a> and a corresponding version of Robolectric become available in Chromium, this flag is
* expected to be always {@code true}. Once they become available, you can either remove this
* flag with assuming it's always {@code false} or test two different OS behaviors at the same
* time by <a href="http://robolectric.org/configuring/">specifying multiple SDK versions</a> to
* the test runner</a>.</p>
*
* @see #testEditableInputConnectionEndBatchEditBug(Context)
* @see #assertLastBatchEdit(boolean)
*/
private boolean mHasEditableInputConnectionEndBatchEditBug;
/**
* Test if {@code EditableInputConnection} has a bug that it still returns {@code true} from
* {@link InputConnection#endBatchEdit()} when its internal batch edit count becomes {@code 0}
* as a result of invocation.
*
* <p>See https://issuetracker.google.com/issues/209958658 for details.</p>
*
* @param context The {@link Context} to be used to initialize {@link EditText}.
* @return {@code true} if the bug still exists. {@code false} otherwise.
*/
private static boolean testEditableInputConnectionEndBatchEditBug(Context context) {
EditText editText = new EditText(context);
EditorInfo editorInfo = new EditorInfo();
InputConnection editableInputConnection = editText.onCreateInputConnection(editorInfo);
editableInputConnection.beginBatchEdit();
// If this returns true, yes, the bug is still there!
return editableInputConnection.endBatchEdit();
}
/**
* A convenient helper method to assert the return value of
* {@link InputConnection#endBatchEdit()} when its internal batch edit count becomes {@code 0}.
*
* @param result The return value of {@link InputConnection#endBatchEdit()}.
*
* @see #mHasEditableInputConnectionEndBatchEditBug
* @see #testEditableInputConnectionEndBatchEditBug(Context)
*/
private void assertLastBatchEdit(boolean result) {
if (mHasEditableInputConnectionEndBatchEditBug) {
assertTrue(result);
} else {
assertFalse(result);
}
}
// Limits the target of InOrder#verify.
private static class Verifier {
public void onAutocompleteTextStateChanged(boolean updateDisplay) {
if (DEBUG) Log.i(TAG, "onAutocompleteTextStateChanged(%b)", updateDisplay);
}
public void onUpdateSelection(int selStart, int selEnd) {
if (DEBUG) Log.i(TAG, "onUpdateSelection(%d, %d)", selStart, selEnd);
}
public void onPopulateAccessibilityEvent(int eventType, String text, String beforeText,
int itemCount, int fromIndex, int toIndex, int removedCount, int addedCount) {
if (DEBUG) {
Log.i(TAG, "onPopulateAccessibilityEvent: TYP[%d] TXT[%s] BEF[%s] CNT[%d] "
+ "FROM[%d] TO[%d] REM[%d] ADD[%d]",
eventType, text, beforeText, itemCount, fromIndex, toIndex, removedCount,
addedCount);
}
}
}
private class TestAutocompleteEditText extends AutocompleteEditText {
private AtomicInteger mVerifierCallCount = new AtomicInteger();
private AtomicInteger mAccessibilityVerifierCallCount = new AtomicInteger();
private AtomicReference<String> mKeyboardPackageName = new AtomicReference<>("dummy.ime");
public TestAutocompleteEditText(Context context, AttributeSet attrs) {
super(context, attrs);
if (DEBUG) Log.i(TAG, "TestAutocompleteEditText constructor");
}
@Override
public void onAutocompleteTextStateChanged(boolean updateDisplay) {
mVerifier.onAutocompleteTextStateChanged(updateDisplay);
mVerifierCallCount.incrementAndGet();
}
@Override
public void onUpdateSelectionForTesting(int selStart, int selEnd) {
mVerifier.onUpdateSelection(selStart, selEnd);
mVerifierCallCount.incrementAndGet();
}
@Override
public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
super.onPopulateAccessibilityEvent(event);
if (TEST_ACCESSIBILITY) {
mVerifier.onPopulateAccessibilityEvent(event.getEventType(), getText(event),
getBeforeText(event), event.getItemCount(), event.getFromIndex(),
event.getToIndex(), event.getRemovedCount(), event.getAddedCount());
mAccessibilityVerifierCallCount.incrementAndGet();
}
}
private String getText(AccessibilityEvent event) {
if (event.getText() != null && event.getText().size() > 0) {
return event.getText().get(0).toString();
}
return "";
}
private String getBeforeText(AccessibilityEvent event) {
return event.getBeforeText() == null ? "" : event.getBeforeText().toString();
}
@Override
public boolean isShown() {
return mIsShown;
}
public int getAndResetVerifierCallCount() {
return mVerifierCallCount.getAndSet(0);
}
public int getAndResetAccessibilityVerifierCallCount() {
return mAccessibilityVerifierCallCount.getAndSet(0);
}
@Override
public String getKeyboardPackageName() {
return mKeyboardPackageName.get();
}
public void setKeyboardPackageName(String packageName) {
mKeyboardPackageName.set(packageName);
}
}
public AutocompleteEditTextTest() {
if (DEBUG) ShadowLog.stream = System.out;
}
private boolean isUsingSpannableModel() {
return ChromeFeatureList.isEnabled(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE);
}
@Before
public void setUp() {
if (DEBUG) Log.i(TAG, "setUp started.");
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mHasEditableInputConnectionEndBatchEditBug =
testEditableInputConnectionEndBatchEditBug(mContext);
mVerifier = spy(new Verifier());
mAutocomplete = new TestAutocompleteEditText(mContext, null);
mFocusPlaceHolder = new LinearLayout(mContext);
mFocusPlaceHolder.setFocusable(true);
mFocusPlaceHolder.addView(mAutocomplete);
assertNotNull(mAutocomplete);
// Pretend that the view is shown in the activity hierarchy, which is for accessibility
// testing.
Activity activity = Robolectric.buildActivity(Activity.class).create().get();
activity.setContentView(mFocusPlaceHolder);
assertNotNull(mFocusPlaceHolder.getParent());
mIsShown = true;
assertTrue(mAutocomplete.isShown());
// Enable accessibility.
mShadowAccessibilityManager =
Shadows.shadowOf(mAutocomplete.getAccessibilityManagerForTesting());
mShadowAccessibilityManager.setEnabled(true);
mShadowAccessibilityManager.setTouchExplorationEnabled(true);
assertTrue(mAutocomplete.getAccessibilityManagerForTesting().isEnabled());
assertTrue(mAutocomplete.getAccessibilityManagerForTesting().isTouchExplorationEnabled());
mInOrder = inOrder(mVerifier);
assertTrue(mAutocomplete.requestFocus());
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_FOCUSED, "", "", 2, -1, -1, -1, -1);
assertNotNull(mAutocomplete.onCreateInputConnection(new EditorInfo()));
mInputConnection = mAutocomplete.getInputConnection();
assertNotNull(mInputConnection);
mInOrder.verifyNoMoreInteractions();
assertVerifierCallCounts(0, 1);
// Feeder should call this at the beginning.
mAutocomplete.setIgnoreTextChangesForAutocomplete(false);
if (DEBUG) Log.i(TAG, "setUp finished.");
}
private void assertTexts(String userText, String autocompleteText) {
assertEquals(userText, mAutocomplete.getTextWithoutAutocomplete());
assertEquals(userText + autocompleteText, mAutocomplete.getTextWithAutocomplete());
assertEquals(autocompleteText.length(), mAutocomplete.getAutocompleteLength());
assertEquals(!TextUtils.isEmpty(autocompleteText), mAutocomplete.hasAutocomplete());
}
private void assertVerifierCallCounts(
int nonAccessibilityCallCount, int accessibilityCallCount) {
assertEquals(nonAccessibilityCallCount, mAutocomplete.getAndResetVerifierCallCount());
if (!TEST_ACCESSIBILITY) return;
assertEquals(
accessibilityCallCount, mAutocomplete.getAndResetAccessibilityVerifierCallCount());
}
private void verifyOnPopulateAccessibilityEvent(int eventType, String text, String beforeText,
int itemCount, int fromIndex, int toIndex, int removedCount, int addedCount) {
if (!TEST_ACCESSIBILITY) return;
mInOrder.verify(mVerifier).onPopulateAccessibilityEvent(eventType, text, beforeText,
itemCount, fromIndex, toIndex, removedCount, addedCount);
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testAppend_CommitTextWithSpannableModel() {
internalTestAppend_CommitText();
}
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testAppend_CommitTextWithoutSpannableModel() {
internalTestAppend_CommitText();
}
private void internalTestAppend_CommitText() {
// User types "h".
assertTrue(mInputConnection.commitText("h", 1));
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(1, 1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "h", "", -1, 0, -1, 0, 1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, "h", "", 1, 1, 1, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "h", "", -1, 0, -1, 0, 1);
mInOrder.verify(mVerifier).onUpdateSelection(1, 1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, "h", "", 1, 1, 1, -1, -1);
assertVerifierCallCounts(2, 2);
}
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("h", "ello world");
if (isUsingSpannableModel()) {
assertFalse(mAutocomplete.isCursorVisible());
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "h", -1, 1, -1, 0, 10);
assertVerifierCallCounts(0, 1);
} else {
// The non-spannable model changes selection in two steps.
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "h", -1, 1, -1, 0, 10);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onUpdateSelection(1, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 1, 11, -1, -1);
assertVerifierCallCounts(2, 3);
}
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// User types "he".
assertTrue(mInputConnection.commitText("e", 1));
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(2, 2);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 2, 2, -1, -1);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "he", -1, 2, -1, 0, 9);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello world", "h", -1, 1, -1, 0, 1);
mInOrder.verify(mVerifier).onUpdateSelection(2, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 2, 11, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
}
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("he", "llo world");
if (isUsingSpannableModel()) assertFalse(mAutocomplete.isCursorVisible());
mInOrder.verifyNoMoreInteractions();
assertTexts("he", "llo world");
assertTrue(mAutocomplete.shouldAutocomplete());
// User types "hello".
assertTrue(mInputConnection.commitText("llo", 1));
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 5, 5, -1, -1);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello", -1, 5, -1, 0, 6);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello",
"hello world", -1, 2, -1, 9, 3);
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
// The old model does not continue the existing autocompletion when two letters are
// typed together, which can cause a slight flicker.
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 5, 5, -1, -1);
assertVerifierCallCounts(4, 3);
}
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("hello", " world");
if (isUsingSpannableModel()) {
assertFalse(mAutocomplete.isCursorVisible());
assertVerifierCallCounts(0, 0);
} else {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello", -1, 5, -1, 0, 6);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onUpdateSelection(5, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 5, 11, -1, -1);
assertVerifierCallCounts(2, 3);
}
mInOrder.verifyNoMoreInteractions();
assertTexts("hello", " world");
assertTrue(mAutocomplete.shouldAutocomplete());
// User types a space inside a batch edit.
assertTrue(mInputConnection.beginBatchEdit());
// We should still show the intermediate autocomplete text to the user even in the middle of
// a batch edit. Otherwise, the user may see flickering of autocomplete text.
assertEquals("hello world", mAutocomplete.getText().toString());
assertTrue(mInputConnection.commitText(" ", 1));
assertEquals("hello world", mAutocomplete.getText().toString());
assertFalse(mAutocomplete.shouldAutocomplete());
assertEquals("hello world", mAutocomplete.getText().toString());
if (!isUsingSpannableModel()) {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello", -1, 5, -1, 0, 1);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 6, 11, -1, -1);
assertVerifierCallCounts(0, 2);
}
mInOrder.verifyNoMoreInteractions();
assertLastBatchEdit(mInputConnection.endBatchEdit());
// Autocomplete text gets redrawn.
assertTexts("hello ", "world");
assertTrue(mAutocomplete.shouldAutocomplete());
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(6, 6);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 6, 6, -1, -1);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello ", -1, 6, -1, 0, 5);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
mInOrder.verify(mVerifier).onUpdateSelection(6, 11);
assertVerifierCallCounts(2, 0);
}
mAutocomplete.setAutocompleteText("hello ", "world");
if (isUsingSpannableModel()) assertFalse(mAutocomplete.isCursorVisible());
assertTexts("hello ", "world");
assertVerifierCallCounts(0, 0);
mInOrder.verifyNoMoreInteractions();
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testAppend_SetComposingTextWithSpannableModel() {
internalTestAppend_SetComposingText();
}
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testAppend_SetComposingTextWithoutSpannableModel() {
internalTestAppend_SetComposingText();
}
private void internalTestAppend_SetComposingText() {
// User types "h".
assertTrue(mInputConnection.setComposingText("h", 1));
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(1, 1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "h", "", -1, 0, -1, 0, 1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, "h", "", 1, 1, 1, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "h", "", -1, 0, -1, 0, 1);
mInOrder.verify(mVerifier).onUpdateSelection(1, 1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, "h", "", 1, 1, 1, -1, -1);
assertVerifierCallCounts(2, 2);
}
mInOrder.verifyNoMoreInteractions();
// The old model does not allow autocompletion here.
assertEquals(isUsingSpannableModel(), mAutocomplete.shouldAutocomplete());
if (isUsingSpannableModel()) {
// The controller kicks in.
mAutocomplete.setAutocompleteText("h", "ello world");
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "h", -1, 1, -1, 0, 10);
assertFalse(mAutocomplete.isCursorVisible());
assertTexts("h", "ello world");
assertVerifierCallCounts(0, 1);
} else {
assertTexts("h", "");
assertVerifierCallCounts(0, 0);
}
mInOrder.verifyNoMoreInteractions();
// User types "hello".
assertTrue(mInputConnection.setComposingText("hello", 1));
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 5, 5, -1, -1);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello", -1, 5, -1, 0, 6);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "h", -1, 0, -1, 1, 5);
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 5, 5, -1, -1);
assertVerifierCallCounts(2, 2);
}
mInOrder.verifyNoMoreInteractions();
if (isUsingSpannableModel()) {
assertTexts("hello", " world");
} else {
// The old model does not work with composition.
assertTexts("hello", "");
}
// The old model does not allow autocompletion here.
assertEquals(isUsingSpannableModel(), mAutocomplete.shouldAutocomplete());
if (isUsingSpannableModel()) {
// The controller kicks in.
mAutocomplete.setAutocompleteText("hello", " world");
assertFalse(mAutocomplete.isCursorVisible());
assertTexts("hello", " world");
} else {
assertTexts("hello", "");
}
assertVerifierCallCounts(0, 0);
mInOrder.verifyNoMoreInteractions();
// User types a space.
assertTrue(mInputConnection.beginBatchEdit());
// We should still show the intermediate autocomplete text to the user even in the middle of
// a batch edit. Otherwise, the user may see flickering of autocomplete text.
if (isUsingSpannableModel()) {
assertEquals("hello world", mAutocomplete.getText().toString());
}
assertTrue(mInputConnection.finishComposingText());
if (isUsingSpannableModel()) {
assertEquals("hello world", mAutocomplete.getText().toString());
}
assertTrue(mInputConnection.commitText(" ", 1));
if (isUsingSpannableModel()) {
assertEquals("hello world", mAutocomplete.getText().toString());
assertVerifierCallCounts(0, 0);
} else {
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello ", "hello", -1, 5, -1, 0, 1);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello ", "", 6, 6, 6, -1, -1);
assertVerifierCallCounts(0, 2);
}
mInOrder.verifyNoMoreInteractions();
assertLastBatchEdit(mInputConnection.endBatchEdit());
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(6, 6);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 6, 6, -1, -1);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello ", -1, 6, -1, 0, 5);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
mInOrder.verify(mVerifier).onUpdateSelection(6, 6);
assertVerifierCallCounts(2, 0);
}
mInOrder.verifyNoMoreInteractions();
if (isUsingSpannableModel()) {
// Autocomplete text has been drawn at endBatchEdit().
assertTexts("hello ", "world");
} else {
assertTexts("hello ", "");
}
// The old model can also autocomplete now.
assertTrue(mAutocomplete.shouldAutocomplete());
mAutocomplete.setAutocompleteText("hello ", "world");
assertTexts("hello ", "world");
if (isUsingSpannableModel()) {
assertFalse(mAutocomplete.isCursorVisible());
assertVerifierCallCounts(0, 0);
} else {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello ", -1, 6, -1, 0, 5);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onUpdateSelection(6, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 6, 11, -1, -1);
assertVerifierCallCounts(2, 3);
}
mInOrder.verifyNoMoreInteractions();
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testAppend_DispatchKeyEventWithSpannableModel() {
internalTestAppend_DispatchKeyEvent();
}
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testAppend_DispatchKeyEventWithoutSpannableModel() {
internalTestAppend_DispatchKeyEvent();
}
private void internalTestAppend_DispatchKeyEvent() {
// User types "h".
mAutocomplete.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_H));
mAutocomplete.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_H));
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(1, 1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "h", "", -1, 0, -1, 0, 1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, "h", "", 1, 1, 1, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "h", "", -1, 0, -1, 0, 1);
mInOrder.verify(mVerifier).onUpdateSelection(1, 1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, "h", "", 1, 1, 1, -1, -1);
assertVerifierCallCounts(2, 2);
}
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("h", "ello world");
// The non-spannable model changes selection in two steps.
if (isUsingSpannableModel()) {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "h", -1, 1, -1, 0, 10);
assertVerifierCallCounts(0, 1);
assertFalse(mAutocomplete.isCursorVisible());
} else {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "h", -1, 1, -1, 0, 10);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onUpdateSelection(1, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 1, 11, -1, -1);
assertVerifierCallCounts(2, 3);
}
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// User types "he".
mAutocomplete.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E));
mAutocomplete.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_E));
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(2, 2);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 2, 2, -1, -1);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "he", -1, 2, -1, 0, 9);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
// The new model tries to reuse autocomplete text.
assertTexts("he", "llo world");
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "he",
"hello world", -1, 1, -1, 10, 1);
mInOrder.verify(mVerifier).onUpdateSelection(2, 2);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, "he", "", 2, 2, 2, -1, -1);
assertVerifierCallCounts(4, 3);
}
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("he", "llo world");
if (isUsingSpannableModel()) {
assertFalse(mAutocomplete.isCursorVisible());
assertVerifierCallCounts(0, 0);
} else {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "he", -1, 2, -1, 0, 9);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onUpdateSelection(2, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 2, 11, -1, -1);
assertVerifierCallCounts(2, 3);
}
mInOrder.verifyNoMoreInteractions();
assertTexts("he", "llo world");
assertTrue(mAutocomplete.shouldAutocomplete());
mInOrder.verifyNoMoreInteractions();
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testDelete_CommitTextWithSpannableModel() {
internalTestDelete_CommitText();
}
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testDelete_CommitTextWithoutSpannableModel() {
internalTestDelete_CommitText();
}
private void internalTestDelete_CommitText() {
// User types "hello".
assertTrue(mInputConnection.commitText("hello", 1));
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "", -1, 0, -1, 0, 5);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 5, 5, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "", -1, 0, -1, 0, 5);
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 5, 5, -1, -1);
assertVerifierCallCounts(2, 2);
}
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("hello", " world");
if (isUsingSpannableModel()) {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello", -1, 5, -1, 0, 6);
assertVerifierCallCounts(0, 1);
assertFalse(mAutocomplete.isCursorVisible());
} else {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello", -1, 5, -1, 0, 6);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onUpdateSelection(5, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 5, 11, -1, -1);
assertVerifierCallCounts(2, 3);
}
assertTexts("hello", " world");
mInOrder.verifyNoMoreInteractions();
// User deletes autocomplete.
if (isUsingSpannableModel()) {
assertTrue(mInputConnection.deleteSurroundingText(1, 0)); // deletes one character
} else {
assertTrue(mInputConnection.commitText("", 1)); // deletes selection.
}
if (isUsingSpannableModel()) {
// Pretend that we have deleted 'o' first.
mInOrder.verify(mVerifier).onUpdateSelection(4, 4);
// We restore 'o', and clear autocomplete text instead.
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
assertTrue(mAutocomplete.isCursorVisible());
// Autocomplete removed.
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello",
"hello world", -1, 5, -1, 6, 0);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(3, 1);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello",
"hello world", -1, 5, -1, 6, 0);
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 5, 5, -1, -1);
assertVerifierCallCounts(4, 3);
}
mInOrder.verifyNoMoreInteractions();
assertFalse(mAutocomplete.shouldAutocomplete());
assertTexts("hello", "");
// Keyboard app checks the current state.
assertEquals("hello", mInputConnection.getTextBeforeCursor(10, 0));
assertTrue(mAutocomplete.isCursorVisible());
assertVerifierCallCounts(0, 0);
mInOrder.verifyNoMoreInteractions();
assertFalse(mAutocomplete.shouldAutocomplete());
assertTexts("hello", "");
}
private boolean isComposing() {
return BaseInputConnection.getComposingSpanStart(mAutocomplete.getText())
!= BaseInputConnection.getComposingSpanEnd(mAutocomplete.getText());
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testDelete_SetComposingTextWithSpannableModel() {
// User types "hello".
assertTrue(mInputConnection.setComposingText("hello", 1));
assertTrue(isComposing());
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "", -1, 0, -1, 0, 5);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, "hello", "", 5, 5, 5, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("hello", " world");
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello world", "hello", -1, 5, -1, 0, 6);
assertFalse(mAutocomplete.isCursorVisible());
assertTexts("hello", " world");
assertVerifierCallCounts(0, 1);
mInOrder.verifyNoMoreInteractions();
// User deletes autocomplete.
assertTrue(mInputConnection.setComposingText("hell", 1));
// Pretend that we have deleted 'o'.
mInOrder.verify(mVerifier).onUpdateSelection(4, 4);
// We restore 'o', finish composition, and clear autocomplete text instead.
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
assertTrue(mAutocomplete.isCursorVisible());
assertFalse(isComposing());
// Remove autocomplete.
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "hello world", -1, 5, -1, 6, 0);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(3, 1);
mInOrder.verifyNoMoreInteractions();
assertFalse(mAutocomplete.shouldAutocomplete());
assertTexts("hello", "");
// Keyboard app checks the current state.
assertEquals("hello", mInputConnection.getTextBeforeCursor(10, 0));
assertTrue(mAutocomplete.isCursorVisible());
assertVerifierCallCounts(0, 0);
mInOrder.verifyNoMoreInteractions();
assertFalse(mAutocomplete.shouldAutocomplete());
assertTexts("hello", "");
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testDelete_SamsungKeyboardWithSpannableModel() {
mAutocomplete.setKeyboardPackageName("com.sec.android.inputmethod");
// User types "hello".
assertTrue(mInputConnection.setComposingText("hello", 1));
assertTrue(isComposing());
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("hello", " world");
assertTexts("hello", " world");
// User deletes autocomplete.
assertTrue(mInputConnection.setComposingText("hell", 1));
// Remove autocomplete.
assertFalse(mAutocomplete.shouldAutocomplete());
assertTexts("hello", "");
// Make sure that we do not finish composing text for Samsung keyboard - it does not update
// its internal states when we ask this. (crbug.com/766888).
assertTrue(isComposing());
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testDelete_SetComposingTextInBatchEditWithSpannableModel() {
// User types "hello".
assertTrue(mInputConnection.setComposingText("hello", 1));
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "", -1, 0, -1, 0, 5);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, "hello", "", 5, 5, 5, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
mInOrder.verifyNoMoreInteractions();
assertVerifierCallCounts(2, 2);
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("hello", " world");
assertFalse(mAutocomplete.isCursorVisible());
assertTexts("hello", " world");
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello world", "hello", -1, 5, -1, 0, 6);
mInOrder.verifyNoMoreInteractions();
assertVerifierCallCounts(0, 1);
// User deletes 'o' in a batch edit.
assertTrue(mInputConnection.beginBatchEdit());
assertTrue(mInputConnection.setComposingText("hell", 1));
// We restore 'o', and clear autocomplete text instead.
assertTrue(mAutocomplete.isCursorVisible());
assertFalse(mAutocomplete.shouldAutocomplete());
// The user will see "hello" even in the middle of a batch edit.
assertEquals("hello", mAutocomplete.getText().toString());
// Keyboard app checks the current state.
assertEquals("hell", mInputConnection.getTextBeforeCursor(10, 0));
assertTrue(mAutocomplete.isCursorVisible());
assertFalse(mAutocomplete.shouldAutocomplete());
mInOrder.verifyNoMoreInteractions();
assertVerifierCallCounts(0, 0);
assertLastBatchEdit(mInputConnection.endBatchEdit());
mInOrder.verify(mVerifier).onUpdateSelection(4, 4);
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "hello world", -1, 5, -1, 6, 0);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertFalse(mAutocomplete.shouldAutocomplete());
assertTexts("hello", "");
mInOrder.verifyNoMoreInteractions();
assertVerifierCallCounts(3, 1);
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testSelect_SelectAutocompleteWithSpannableModel() {
internalTestSelect_SelectAutocomplete();
}
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testSelect_SelectAutocompleteWithoutSpannableModel() {
internalTestSelect_SelectAutocomplete();
}
private void internalTestSelect_SelectAutocomplete() {
// User types "hello".
assertTrue(mInputConnection.commitText("hello", 1));
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "", -1, 0, -1, 0, 5);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 5, 5, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "", -1, 0, -1, 0, 5);
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 5, 5, -1, -1);
assertVerifierCallCounts(2, 2);
}
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("hello", " world");
assertTexts("hello", " world");
if (isUsingSpannableModel()) {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello", -1, 5, -1, 0, 6);
assertFalse(mAutocomplete.isCursorVisible());
assertVerifierCallCounts(0, 1);
} else {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello", -1, 5, -1, 0, 6);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onUpdateSelection(5, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 5, 11, -1, -1);
assertVerifierCallCounts(2, 3);
}
mInOrder.verifyNoMoreInteractions();
// User touches autocomplete text.
mAutocomplete.setSelection(7);
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(7, 7);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 7, 7, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
mInOrder.verify(mVerifier).onUpdateSelection(7, 7);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 7, 7, -1, -1);
}
assertVerifierCallCounts(2, 1);
mInOrder.verifyNoMoreInteractions();
assertFalse(mAutocomplete.shouldAutocomplete());
assertTexts("hello world", "");
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testSelect_SelectUserTextWithSpannableModel() {
internalTestSelect_SelectUserText();
}
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testSelect_SelectUserTextWithoutSpannableModel() {
internalTestSelect_SelectUserText();
}
private void internalTestSelect_SelectUserText() {
// User types "hello".
assertTrue(mInputConnection.commitText("hello", 1));
if (isUsingSpannableModel()) {
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "", -1, 0, -1, 0, 5);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 5, 5, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello", "", -1, 0, -1, 0, 5);
mInOrder.verify(mVerifier).onUpdateSelection(5, 5);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 5, 5, -1, -1);
assertVerifierCallCounts(2, 2);
}
mInOrder.verifyNoMoreInteractions();
assertTrue(mAutocomplete.shouldAutocomplete());
// The controller kicks in.
mAutocomplete.setAutocompleteText("hello", " world");
assertTexts("hello", " world");
if (isUsingSpannableModel()) {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello", -1, 5, -1, 0, 6);
assertFalse(mAutocomplete.isCursorVisible());
assertVerifierCallCounts(0, 1);
} else {
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
"hello world", "hello", -1, 5, -1, 0, 6);
mInOrder.verify(mVerifier).onUpdateSelection(11, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 11, 11, -1, -1);
mInOrder.verify(mVerifier).onUpdateSelection(5, 11);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello world", "", 11, 5, 11, -1, -1);
assertVerifierCallCounts(2, 3);
}
mInOrder.verifyNoMoreInteractions();
// User touches the user text.
mAutocomplete.setSelection(3);
if (isUsingSpannableModel()) {
assertTrue(mAutocomplete.isCursorVisible());
mInOrder.verify(mVerifier).onUpdateSelection(3, 3);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello",
"hello world", -1, 5, -1, 6, 0);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 3, 3, -1, -1);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
assertVerifierCallCounts(2, 2);
} else {
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(true);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, "hello",
"hello world", -1, 5, -1, 6, 0);
mInOrder.verify(mVerifier).onAutocompleteTextStateChanged(false);
mInOrder.verify(mVerifier).onUpdateSelection(3, 3);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
"hello", "", 5, 3, 3, -1, -1);
assertVerifierCallCounts(3, 2);
}
mInOrder.verifyNoMoreInteractions();
assertFalse(mAutocomplete.shouldAutocomplete());
// Autocomplete text is removed.
assertTexts("hello", "");
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testAppend_AfterSelectAllWithSpannableModel() {
internalTestAppend_AfterSelectAll();
}
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testAppend_AfterSelectAllWithoutSpannableModel() {
internalTestAppend_AfterSelectAll();
}
private void internalTestAppend_AfterSelectAll() {
final String url = "https://www.google.com/";
mAutocomplete.setText(url);
mAutocomplete.setSelection(0, url.length());
assertTrue(mAutocomplete.isCursorVisible());
// User types "h" - note that this is also starting character of the URL. The selection gets
// replaced by what user types.
assertTrue(mInputConnection.commitText("h", 1));
// We want to allow inline autocomplete when the user overrides an existing URL.
assertTrue(mAutocomplete.shouldAutocomplete());
assertTrue(mAutocomplete.isCursorVisible());
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testIgnoreAndGetWithSpannableModel() {
internalTestIgnoreAndGet();
}
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testIgnoreAndGetWithoutSpannableModel() {
internalTestIgnoreAndGet();
}
private void internalTestIgnoreAndGet() {
final String url = "https://www.google.com/";
mAutocomplete.setIgnoreTextChangesForAutocomplete(true);
mAutocomplete.setText(url);
mAutocomplete.setIgnoreTextChangesForAutocomplete(false);
mInputConnection.getTextBeforeCursor(1, 1);
if (isUsingSpannableModel()) {
assertTrue(mAutocomplete.isCursorVisible());
}
mInOrder.verifyNoMoreInteractions();
}
// crbug.com/760013
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testOnSaveInstanceStateDoesNotCrash() {
mInputConnection.setComposingText("h", 1);
mAutocomplete.setAutocompleteText("h", "ello world");
// On Android JB, TextView#onSaveInstanceState() calls new SpannableString(mText). This
// should not crash.
new SpannableString(mAutocomplete.getText());
}
// crbug.com/759876
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testFocusInAndSelectAllWithSpannableModel() {
internalTestFocusInAndSelectAll();
}
// crbug.com/759876
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testFocusInAndSelectAllWithoutSpannableModel() {
internalTestFocusInAndSelectAll();
}
private void internalTestFocusInAndSelectAll() {
final String url = "https://google.com";
final int len = url.length();
mAutocomplete.setIgnoreTextChangesForAutocomplete(true);
mAutocomplete.setText(url);
mAutocomplete.setIgnoreTextChangesForAutocomplete(false);
mInOrder.verifyNoMoreInteractions();
assertVerifierCallCounts(0, 0);
assertTrue(mFocusPlaceHolder.requestFocus());
mInOrder.verifyNoMoreInteractions();
assertVerifierCallCounts(0, 0);
// LocationBarLayout does this.
mAutocomplete.setSelectAllOnFocus(true);
assertTrue(mAutocomplete.requestFocus());
mInOrder.verify(mVerifier).onUpdateSelection(len, len);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, url, "", 18, 18, 18, -1, -1);
mInOrder.verify(mVerifier).onUpdateSelection(0, len);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, url, "", 18, 0, 18, -1, -1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_FOCUSED, url, "", 2, -1, -1, -1, -1);
assertVerifierCallCounts(2, 3);
mInOrder.verifyNoMoreInteractions();
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testNonMatchingBatchEditWithSpannableModel() {
internalNonMatchingBatchEdit();
}
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testNonMatchingBatchEditWithoutSpannableModel() {
internalNonMatchingBatchEdit();
}
// crbug.com/764749
private void internalNonMatchingBatchEdit() {
// beginBatchEdit() was not matched by endBatchEdit(), for some reason.
mInputConnection.beginBatchEdit();
// Restart input should reset batch edit count.
assertNotNull(mAutocomplete.onCreateInputConnection(new EditorInfo()));
mInputConnection = mAutocomplete.getInputConnection();
assertTrue(mInputConnection.commitText("a", 1));
// Works again.
assertTrue(mAutocomplete.shouldAutocomplete());
}
// crbug.com/768323
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testFocusLossHidesCursorWithSpannableModel() {
assertTrue(mAutocomplete.isFocused());
assertTrue(mAutocomplete.isCursorVisible());
// AutocompleteEditText loses focus, and this hides cursor.
assertTrue(mFocusPlaceHolder.requestFocus());
assertFalse(mAutocomplete.isFocused());
assertFalse(mAutocomplete.isCursorVisible());
// Some IME operations may arrive after focus loss, but this should never show cursor.
mInputConnection.getTextBeforeCursor(1, 0);
assertFalse(mAutocomplete.isCursorVisible());
}
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testUnsupportedKeyboardWithSpannableModel() {
mAutocomplete.setKeyboardPackageName("jp.co.sharp.android.iwnn");
// User types "h".
assertTrue(mInputConnection.commitText("h", 1));
assertFalse(mAutocomplete.shouldAutocomplete());
}
// crbug.com/783165
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testSetTextAndSelect() {
// User types "h".
assertTrue(mInputConnection.commitText("h", 1));
assertTrue(mAutocomplete.shouldAutocomplete());
mAutocomplete.setAutocompleteText("h", "ello world");
mAutocomplete.setIgnoreTextChangesForAutocomplete(true);
mAutocomplete.setText("abcde");
mAutocomplete.setIgnoreTextChangesForAutocomplete(false);
assertEquals("abcde", mAutocomplete.getText().toString());
mAutocomplete.setSelection(0);
// Check the internal states are correct.
assertEquals("abcde", mAutocomplete.getText().toString());
assertEquals("abcde", mAutocomplete.getTextWithAutocomplete());
assertEquals("abcde", mAutocomplete.getTextWithoutAutocomplete());
}
// crbug.com/810704
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testPerformEditorAction() {
// User types "goo".
assertTrue(mInputConnection.setComposingText("goo", 1));
assertTrue(mAutocomplete.shouldAutocomplete());
mAutocomplete.setAutocompleteText("goo", "gle.com");
assertEquals("google.com", mAutocomplete.getText().toString());
// User presses 'GO' key on the keyboard.
assertTrue(mInputConnection.commitText("goo", 1));
assertEquals("google.com", mAutocomplete.getText().toString());
assertTrue(mInputConnection.performEditorAction(EditorInfo.IME_ACTION_GO));
assertEquals("google.com", mAutocomplete.getText().toString());
}
// crbug.com/810704
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testPerformEditorActionInBatchEdit() {
// User types "goo".
assertTrue(mInputConnection.setComposingText("goo", 1));
assertTrue(mAutocomplete.shouldAutocomplete());
mAutocomplete.setAutocompleteText("goo", "gle.com");
assertEquals("google.com", mAutocomplete.getText().toString());
// User presses 'GO' key on the keyboard.
mInputConnection.beginBatchEdit();
assertTrue(mInputConnection.commitText("goo", 1));
assertEquals("google.com", mAutocomplete.getText().toString());
assertTrue(mInputConnection.performEditorAction(EditorInfo.IME_ACTION_GO));
assertEquals("google.com", mAutocomplete.getText().toString());
mInputConnection.endBatchEdit();
assertEquals("google.com", mAutocomplete.getText().toString());
}
// crbug.com/759876
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testTextSelectionGetsAnnouncedAgainOnFocusWithSpannableModel() {
internalTestTextSelectionGetsAnnouncedAgainOnFocus();
}
@Test
@DisableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testTextSelectionGetsAnnouncedAgainOnFocusWithoutSpannableModel() {
internalTestTextSelectionGetsAnnouncedAgainOnFocus();
}
private void internalTestTextSelectionGetsAnnouncedAgainOnFocus() {
final String text = "hello";
final int len = text.length();
assertTrue(mInputConnection.commitText(text, len));
mAutocomplete.setSelection(0, len);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, text, "", -1, 0, -1, 0, len);
verifyOnPopulateAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED,
text, "", len, len, len, -1, -1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, text, "", len, 0, len, -1, -1);
mInOrder.verifyNoMoreInteractions();
assertVerifierCallCounts(3, 3);
assertTrue(mFocusPlaceHolder.requestFocus());
mInOrder.verifyNoMoreInteractions();
assertVerifierCallCounts(0, 0);
// We left EditText with selected content. We should get the same event sent again now.
mAutocomplete.setSelectAllOnFocus(true);
assertTrue(mAutocomplete.requestFocus());
mInOrder.verify(mVerifier).onUpdateSelection(0, len);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED, text, "", len, 0, len, -1, -1);
verifyOnPopulateAccessibilityEvent(
AccessibilityEvent.TYPE_VIEW_FOCUSED, text, "", 2, -1, -1, -1, -1);
assertVerifierCallCounts(2, 3);
mInOrder.verifyNoMoreInteractions();
}
// crbug.com/759876
@Test
@EnableFeatures(ChromeFeatureList.SPANNABLE_INLINE_AUTOCOMPLETE)
public void testEndBatchEditCanReturnFalse() {
assertTrue(mInputConnection.beginBatchEdit());
assertLastBatchEdit(mInputConnection.endBatchEdit());
// Additional endBatchEdit() must continue returning false.
assertFalse(mInputConnection.endBatchEdit());
}
}
| 28,306 |
11,467 |
{"event_id":"7c9ae6e58f03442b9203bbdcf6ae904c","level":"error","timestamp":"2021-07-08T12:59:16Z","release":"db853d7","environment":"development","server_name":"MacBook.local","modules":{"rake":"13.0.3","concurrent-ruby":"1.1.9","i18n":"1.8.10","minitest":"5.14.4","thread_safe":"0.3.6","tzinfo":"1.2.9","uglifier":"4.2.0","web-console":"3.7.0"},"message":"","user":{},"tags":{"request_id":"4253dcd9-5e48-474a-89b4-0e945ab825af"},"contexts":{"os":{"name":"Darwin","version":"Darwin Kernel Version 20.5.0: Sat May 8 05:10:33 PDT 2021; root:xnu-7195.121.3~9/RELEASE_X86_64","build":"20.5.0","kernel_version":"Darwin Kernel Version 20.5.0: Sat May 8 05:10:33 PDT 2021; root:xnu-7195.121.3~9/RELEASE_X86_64"},"runtime":{"name":"ruby","version":"ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin19]"},"trace":{"trace_id":"d82b93fbc39e4d13b85762afa2e3ff36","span_id":"4a3ed8701e7f4ea4","parent_span_id":null,"description":null,"op":"rails.request","status":null}},"extra":{},"fingerprint":[],"breadcrumbs":{"values":[{"category":"start_processing.action_controller","data":{"controller":"PostsController","action":"error2","params":{"controller":"posts","action":"error2"},"format":"html","method":"GET","path":"/posts/error2","start_timestamp":1625749156.5553},"level":null,"message":"","timestamp":1625749156,"type":null},{"category":"process_action.action_controller","data":{"controller":"PostsController","action":"error2","params":{"controller":"posts","action":"error2"},"format":"html","method":"GET","path":"/posts/error2","start_timestamp":1625749156.55539,"view_runtime":null,"db_runtime":0},"level":null,"message":"","timestamp":1625749156,"type":null}]},"transaction":"PostsController#error2","platform":"ruby","sdk":{"name":"sentry.ruby.rails","version":"4.5.1"},"request":{"url":"http://localhost/posts/error2","method":"GET","headers":{},"env":{"SERVER_NAME":"localhost","SERVER_PORT":"4444"}},"exception":{"values":[{"type":"ActionView::MissingTemplate","value":"Missing template posts/error2, application/error2 with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:\n * \"/Users/developer/rails-project/app/views\"\n","module":"ActionView","thread_id":70254489510160,"stacktrace":{"frames":[{"project_root":"/Users/developer/rails-project","abs_path":"/Users/developer/.asdf/installs/ruby/2.5.1/lib/ruby/gems/2.5.0/gems/puma-3.12.6/lib/puma/thread_pool.rb","function":"block in spawn_thread","lineno":135,"in_app":false,"filename":"puma/thread_pool.rb","pre_context":[" end\n","\n"," begin\n"],"context_line":" block.call(work, *extra)\n","post_context":[" rescue Exception => e\n"," STDERR.puts \"Error reached top of thread-pool: #{e.message} (#{e.class})\"\n"," end\n"]},{"project_root":"/Users/developer/rails-project","abs_path":"/Users/developer/.asdf/installs/ruby/2.5.1/lib/ruby/gems/2.5.0/gems/puma-3.12.6/lib/puma/server.rb","function":"block in run","lineno":334,"in_app":false,"filename":"puma/server.rb","pre_context":[" client.close\n"," else\n"," if process_now\n"],"context_line":" process_client client, buffer\n","post_context":[" else\n"," client.set_timeout @first_data_timeout\n"," @reactor.add client\n"]},{"project_root":"/Users/developer/rails-project","abs_path":"/Users/developer/.asdf/installs/ruby/2.5.1/lib/ruby/gems/2.5.0/gems/actionview-5.2.6/lib/action_view/path_set.rb","function":"find","lineno":48,"in_app":false,"filename":"action_view/path_set.rb","pre_context":[" end\n","\n"," def find(*args)\n"],"context_line":" find_all(*args).first || raise(MissingTemplate.new(self, *args))\n","post_context":[" end\n","\n"," def find_file(path, prefixes = [], *args)\n"]}]}}]}}
| 1,451 |
778 |
from math import *
import numpy as np
from time import time
import matplotlib.pyplot as plt
from tqdm import tqdm
import sys
from pyevtk.hl import imageToVTK
from KratosMultiphysics.ExaquteSandboxApplication.WindGenerator.GaussianRandomField import *
from KratosMultiphysics.ExaquteSandboxApplication.WindGenerator.CovarianceKernels import VonKarmanCovariance, MannCovariance
class GenerateWind:
def __init__(self, friction_velocity, reference_height, grid_dimensions, grid_levels, seed=None, blend_num=10, **kwargs):
# Parameters taken from pg 13 of <NAME>'s dissertation
# model = 'FPDE_RDT'
model = 'Mann'
# model = 'VK'
E0 = 3.2 * friction_velocity**2 * reference_height**(-2/3)
L = 0.59 * reference_height
# L = 95 # why should the length scale depend on the reference height???????
Gamma = 3.9
# define margins and buffer
time_buffer = 3 * Gamma * L
spatial_margin = 1 * L
try:
grid_levels = [grid_levels[i].GetInt() for i in range(3)]
except:
pass
Nx = 2**grid_levels[0] + 1
Ny = 2**grid_levels[1] + 1
Nz = 2**grid_levels[2] + 1
hx = grid_dimensions[0]/Nx
hy = grid_dimensions[1]/Ny
hz = grid_dimensions[2]/Nz
n_buffer = ceil(time_buffer/hx)
n_marginy = ceil(spatial_margin/hy)
n_marginz = ceil(spatial_margin/hz)
wind_shape = [0] + [Ny] + [Nz] + [3]
if blend_num > 0:
noise_shape = [Nx + 2*n_buffer + (blend_num-1)] + [Ny + 2*n_marginy] + [Nz + 2*n_marginz] + [3]
else:
noise_shape = [Nx + 2*n_buffer] + [Ny + 2*n_marginy] + [Nz + 2*n_marginz] + [3]
new_part_shape = [Nx] + [Ny + 2*n_marginy] + [Nz + 2*n_marginz] + [3]
central_part = [slice(None, None),] * 4
new_part = central_part.copy()
central_part[0] = slice(n_buffer, -n_buffer)
central_part[1] = slice(n_marginy, -n_marginy)
central_part[2] = slice(0, -2*n_marginz)
if blend_num > 0:
new_part[0] = slice(2*n_buffer + (blend_num-1), None)
else:
new_part[0] = slice(2*n_buffer, None)
self.new_part = new_part
self.Nx = Nx
self.blend_num = blend_num
self.central_part = central_part
self.new_part_shape = new_part_shape
self.noise_shape = noise_shape
self.n_buffer = n_buffer
self.n_marginy = n_marginy
self.n_marginz = n_marginz
self.seed = seed
self.noise = None
self.total_wind = np.zeros(wind_shape)
### Random field object
if model == 'VK':
self.Covariance = VonKarmanCovariance(ndim=3, length_scale=L, E0=E0)
self.RF = VectorGaussianRandomField(**kwargs, ndim=3, grid_level=grid_levels, grid_dimensions=grid_dimensions, sampling_method='vf_fftw', grid_shape=self.noise_shape[:-1], Covariance=self.Covariance)
elif model == 'Mann':
self.Covariance = MannCovariance(ndim=3, length_scale=L, E0=E0, Gamma=Gamma)
self.RF = VectorGaussianRandomField(**kwargs, ndim=3, grid_level=grid_levels, grid_dimensions=grid_dimensions, sampling_method='vf_fftw', grid_shape=self.noise_shape[:-1], Covariance=self.Covariance)
elif model == 'FPDE_RDT':
self.Covariance = None
kwargs = {
'correlation_length' : L,
'E0' : E0
}
self.RF = VectorGaussianRandomField(**kwargs, ndim=3, grid_level=grid_levels, grid_dimensions=grid_dimensions, sampling_method='vf_rat_halfspace_rapid_distortion', grid_shape=self.noise_shape[:-1], Covariance=self.Covariance)
self.RF.reseed(self.seed)
# self.RS = np.random.RandomState(seed=self.seed)
def __call__(self):
noise_shape = self.noise_shape
central_part = self.central_part
new_part = self.new_part
new_part_shape = self.new_part_shape
Nx = self.Nx
### update noise
if self.noise is None:
noise = self.RF.sample_noise(noise_shape)
else:
noise = np.roll(self.noise, -Nx, axis=0)
noise[tuple(new_part)] = self.RF.sample_noise(new_part_shape)
self.noise = noise
t = time()
wind_block = self.RF.sample(noise)
print('block computation:', time()-t)
wind = wind_block[tuple(central_part)]
if self.blend_num > 0:
self.blend_region = wind[-self.blend_num:,...].copy()
else:
self.blend_region = None
if self.blend_num > 1:
wind = wind[:-(self.blend_num-1),...]
#NOTE: COMMENT THIS LINE TO SAVE MEMORY
# self.total_wind = np.concatenate((self.total_wind, wind), axis=0)
return wind
############################################################################
############################################################################
if __name__ == "__main__":
import matplotlib.pyplot as plt
normalize = True
friction_velocity = 2.683479938442173
reference_height = 180.0
roughness_height = 0.75
grid_dimensions = np.array([1200.0, 864.0, 576.0])
grid_levels = np.array([7, 7, 7])
seed = 9000
wind = GenerateWind(friction_velocity, reference_height, grid_dimensions, grid_levels, seed)
for _ in range(4):
wind()
wind_field = wind.total_wind
if normalize == True:
# h = np.array(grid_dimensions/wind_field.shape[0:-1])
# h = np.array(1/wind_field.shape[0],1/wind_field.shape[1],1/wind_field.shape[2])
sd = np.sqrt(np.mean(wind_field**2))
wind_field = wind_field/sd
wind_field *= 4.26 # rescale to match Mann model
# plt.imshow(wind_field[:,0,:,0])
# plt.show()
# # total_wind = wind.total_wind
# # plt.imshow(total_wind[:,0,:,0])
# # plt.show()
JCSS_law = lambda z, z_0, delta, u_ast: u_ast/0.41 * ( np.log(z/z_0+1.0) + 5.57*z/delta - 1.87*(z/delta)**2 - 1.33*(z/delta)**3 + 0.25*(z/delta)**4 )
log_law = lambda z, z_0, u_ast: u_ast * np.log(z/z_0+1.0)/0.41
z = np.linspace(0.0,grid_dimensions[2], 2**(grid_levels[2])+1)
# mean_profile_z = JCSS_law(z, roughness_height, 10.0, friction_velocity)
mean_profile_z = log_law(z, roughness_height, friction_velocity)
mean_profile = np.zeros_like(wind_field)
mean_profile[...,0] = np.tile(mean_profile_z.T, (mean_profile.shape[0], mean_profile.shape[1], 1))
# wind_field = mean_profile
wind_field += mean_profile
###################
## Export to vtk
FileName = 'OntheFlyWindField'
spacing = tuple(grid_dimensions/(2.0**grid_levels + 1))
wind_field_vtk = tuple([np.copy(wind_field[...,i], order='C') for i in range(3)])
cellData = {'grid': np.zeros_like(wind_field[...,0]), 'wind': wind_field_vtk}
imageToVTK(FileName, cellData = cellData, spacing=spacing)
| 3,246 |
742 |
from __future__ import division, absolute_import, print_function
from numpy.oldnumeric.mlab import *
import numpy.oldnumeric.mlab as nom
__all__ = nom.__all__
del nom
| 57 |
3,442 |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.sip.communicator.impl.protocol.irc;
import java.io.*;
import java.net.*;
import com.ircclouds.irc.api.*;
import com.ircclouds.irc.api.ctcp.*;
import com.ircclouds.irc.api.domain.*;
import com.ircclouds.irc.api.filters.*;
import com.ircclouds.irc.api.listeners.*;
import com.ircclouds.irc.api.state.*;
/**
* Synchronization wrapper for IRCApi.
*
* All calls are synchronized. In case of multiple operations one can manually
* block-synchronize on the instance.
*
* @author <NAME>
*/
public class SynchronizedIRCApi
implements IRCApi
{
private final IRCApi irc;
/**
* Constructor for synchronization wrapper.
*
* @param irc IRCApi instance
*/
public SynchronizedIRCApi(final IRCApi irc)
{
if (irc == null)
{
throw new IllegalArgumentException("irc instance cannot be null");
}
this.irc = irc;
}
@Override
public synchronized void connect(final IServerParameters aServerParameters,
final Callback<IIRCState> aCallback)
{
this.irc.connect(aServerParameters, aCallback);
}
@Override
public synchronized void connect(final IServerParameters aServerParameters,
final Callback<IIRCState> aCallback,
final CapabilityNegotiator negotiator)
{
this.irc.connect(aServerParameters, aCallback, negotiator);
}
@Override
public synchronized void disconnect()
{
this.irc.disconnect();
}
@Override
public synchronized void disconnect(final String aQuitMessage)
{
this.irc.disconnect(aQuitMessage);
}
@Override
public synchronized void joinChannel(final String aChannelName)
{
this.irc.joinChannel(aChannelName);
}
@Override
public synchronized void joinChannel(final String aChannelName,
final Callback<IRCChannel> aCallback)
{
this.irc.joinChannel(aChannelName, aCallback);
}
@Override
public synchronized void joinChannel(final String aChannelName,
final String aKey)
{
this.irc.joinChannel(aChannelName, aKey);
}
@Override
public synchronized void joinChannel(final String aChannelName,
final String aKey, final Callback<IRCChannel> aCallback)
{
this.irc.joinChannel(aChannelName, aKey, aCallback);
}
@Override
public synchronized void leaveChannel(final String aChannelName)
{
this.irc.leaveChannel(aChannelName);
}
@Override
public synchronized void leaveChannel(final String aChannelName,
final Callback<String> aCallback)
{
this.irc.leaveChannel(aChannelName, aCallback);
}
@Override
public synchronized void leaveChannel(final String aChannelName,
final String aPartMessage)
{
this.irc.leaveChannel(aChannelName, aPartMessage);
}
@Override
public synchronized void leaveChannel(final String aChannelName,
final String aPartMessage, final Callback<String> aCallback)
{
this.irc.leaveChannel(aChannelName, aPartMessage, aCallback);
}
@Override
public synchronized void changeNick(final String aNewNick)
{
this.irc.changeNick(aNewNick);
}
@Override
public synchronized void changeNick(final String aNewNick,
final Callback<String> aCallback)
{
this.irc.changeNick(aNewNick, aCallback);
}
@Override
public synchronized void message(final String aTarget,
final String aMessage)
{
this.irc.message(aTarget, aMessage);
}
@Override
public synchronized void message(final String aTarget,
final String aMessage, final Callback<String> aCallback)
{
this.irc.message(aTarget, aMessage, aCallback);
}
@Override
public synchronized void act(final String aTarget, final String aMessage)
{
this.irc.act(aTarget, aMessage);
}
@Override
public synchronized void act(final String aTarget, final String aMessage,
final Callback<String> aCallback)
{
this.irc.act(aTarget, aMessage, aCallback);
}
@Override
public synchronized void notice(final String aTarget, final String aMessage)
{
this.irc.notice(aTarget, aMessage);
}
@Override
public synchronized void notice(final String aTarget,
final String aMessage, final Callback<String> aCallback)
{
this.irc.notice(aTarget, aMessage, aCallback);
}
@Override
public synchronized void kick(final String aChannel, final String aNick)
{
this.irc.kick(aChannel, aNick);
}
@Override
public synchronized void kick(final String aChannel, final String aNick,
final String aKickMessage)
{
this.irc.kick(aChannel, aNick, aKickMessage);
}
@Override
public synchronized void kick(final String aChannel, final String aNick,
final Callback<String> aCallback)
{
this.irc.kick(aChannel, aNick, aCallback);
}
@Override
public synchronized void kick(final String aChannel, final String aNick,
final String aKickMessage, final Callback<String> aCallback)
{
this.irc.kick(aChannel, aNick, aKickMessage, aCallback);
}
@Override
public synchronized void changeTopic(final String aChannel,
final String aTopic)
{
this.irc.changeTopic(aChannel, aTopic);
}
@Override
public synchronized void changeMode(final String aModeString)
{
this.irc.changeMode(aModeString);
}
@Override
public synchronized void rawMessage(final String aMessage)
{
this.irc.rawMessage(aMessage);
}
@Override
public synchronized void dccSend(final String aNick, final File aFile,
final DCCSendCallback aCallback)
{
this.irc.dccSend(aNick, aFile, aCallback);
}
@Override
public synchronized void dccSend(final String aNick, final File aFile,
final Integer aTimeout, final DCCSendCallback aCallback)
{
this.irc.dccSend(aNick, aFile, aTimeout, aCallback);
}
@Override
public synchronized void dccSend(final String aNick,
final Integer aListeningPort, final File aFile,
final DCCSendCallback aCallback)
{
this.irc.dccSend(aNick, aListeningPort, aFile, aCallback);
}
@Override
public synchronized void dccSend(final String aNick, final File aFile,
final Integer aListeningPort, final Integer aTimeout,
final DCCSendCallback aCallback)
{
this.irc.dccSend(aNick, aFile, aListeningPort, aTimeout, aCallback);
}
@Override
public synchronized void dccAccept(final String aNick, final File aFile,
final Integer aPort, final Integer aResumePosition,
final DCCSendCallback aCallback)
{
this.irc.dccAccept(aNick, aFile, aPort, aResumePosition, aCallback);
}
@Override
public synchronized void dccAccept(final String aNick, final File aFile,
final Integer aPort, final Integer aResumePosition,
final Integer aTimeout, final DCCSendCallback aCallback)
{
this.irc.dccAccept(aNick, aFile, aPort, aResumePosition, aTimeout,
aCallback);
}
@Override
public synchronized void dccReceive(final File aFile, final Integer aSize,
final SocketAddress aAddress, final DCCReceiveCallback aCallback)
{
this.irc.dccReceive(aFile, aSize, aAddress, aCallback);
}
@Override
public synchronized void dccReceive(final File aFile, final Integer aSize,
final SocketAddress aAddress, final DCCReceiveCallback aCallback,
final Proxy aProxy)
{
this.irc.dccReceive(aFile, aSize, aAddress, aCallback, aProxy);
}
@Override
public synchronized void dccResume(final File aFile,
final Integer aResumePosition, final Integer aSize,
final SocketAddress aAddress, final DCCReceiveCallback aCallback)
{
this.irc.dccResume(aFile, aResumePosition, aSize, aAddress, aCallback);
}
@Override
public synchronized void dccResume(final File aFile,
final Integer aResumePosition, final Integer aSize,
final SocketAddress aAddress, final DCCReceiveCallback aCallback,
final Proxy aProxy)
{
this.irc.dccResume(aFile, aResumePosition, aSize, aAddress, aCallback,
aProxy);
}
@Override
public synchronized DCCManager getDCCManager()
{
return this.irc.getDCCManager();
}
@Override
public synchronized void addListener(final IMessageListener aListener)
{
this.irc.addListener(aListener);
}
@Override
public synchronized void deleteListener(final IMessageListener aListener)
{
this.irc.deleteListener(aListener);
}
@Override
public synchronized void setMessageFilter(final IMessageFilter aFilter)
{
this.irc.setMessageFilter(aFilter);
}
}
| 3,562 |
634 |
#pragma once
#include <Windows.h>
namespace Win32
{
namespace Registry
{
void installHooks();
void setValue(HKEY key, const char* subKey, const char* valueName, DWORD value);
void unsetValue(HKEY key, const char* subKey, const char* valueName);
}
}
| 95 |
4,098 |
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#ifndef ASSIMP_Q3BSPFILEIMPORTER_H_INC
#define ASSIMP_Q3BSPFILEIMPORTER_H_INC
#include "BaseImporter.h"
#include <map>
struct aiMesh;
struct aiNode;
struct aiFace;
struct aiMaterial;
struct aiTexture;
namespace Assimp {
namespace Q3BSP {
class Q3BSPZipArchive;
struct Q3BSPModel;
struct sQ3BSPFace;
}
// ------------------------------------------------------------------------------------------------
/** Loader to import BSP-levels from a PK3 archive or from a unpacked BSP-level.
*/
// ------------------------------------------------------------------------------------------------
class Q3BSPFileImporter : public BaseImporter {
public:
/// @brief Default constructor.
Q3BSPFileImporter();
/// @brief Destructor.
~Q3BSPFileImporter();
public:
/// @brief Returns whether the class can handle the format of the given file.
/// @remark See BaseImporter::CanRead() for details.
bool CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig ) const;
private:
typedef std::map<std::string, std::vector<Q3BSP::sQ3BSPFace*>*> FaceMap;
typedef std::map<std::string, std::vector<Q3BSP::sQ3BSPFace*>* >::iterator FaceMapIt;
typedef std::map<std::string, std::vector<Q3BSP::sQ3BSPFace*>*>::const_iterator FaceMapConstIt;
const aiImporterDesc* GetInfo () const;
void InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler);
void separateMapName( const std::string &rImportName, std::string &rArchiveName, std::string &rMapName );
bool findFirstMapInArchive( Q3BSP::Q3BSPZipArchive &rArchive, std::string &rMapName );
void CreateDataFromImport( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, Q3BSP::Q3BSPZipArchive *pArchive );
void CreateNodes( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, aiNode *pParent );
aiNode *CreateTopology( const Q3BSP::Q3BSPModel *pModel, unsigned int materialIdx,
std::vector<Q3BSP::sQ3BSPFace*> &rArray, aiMesh* pMesh );
void createTriangleTopology( const Q3BSP::Q3BSPModel *pModel, Q3BSP::sQ3BSPFace *pQ3BSPFace, aiMesh* pMesh, unsigned int &rFaceIdx,
unsigned int &rVertIdx );
void createMaterials( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, Q3BSP::Q3BSPZipArchive *pArchive );
size_t countData( const std::vector<Q3BSP::sQ3BSPFace*> &rArray ) const;
size_t countFaces( const std::vector<Q3BSP::sQ3BSPFace*> &rArray ) const;
size_t countTriangles( const std::vector<Q3BSP::sQ3BSPFace*> &rArray ) const;
void createMaterialMap( const Q3BSP::Q3BSPModel *pModel);
aiFace *getNextFace( aiMesh *pMesh, unsigned int &rFaceIdx );
bool importTextureFromArchive( const Q3BSP::Q3BSPModel *pModel, Q3BSP::Q3BSPZipArchive *pArchive, aiScene* pScene,
aiMaterial *pMatHelper, int textureId );
bool importLightmap( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, aiMaterial *pMatHelper, int lightmapId );
bool importEntities( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene );
bool expandFile( Q3BSP::Q3BSPZipArchive *pArchive, const std::string &rFilename, const std::vector<std::string> &rExtList,
std::string &rFile, std::string &rExt );
private:
aiMesh *m_pCurrentMesh;
aiFace *m_pCurrentFace;
FaceMap m_MaterialLookupMap;
std::vector<aiTexture*> mTextures;
};
// ------------------------------------------------------------------------------------------------
} // Namespace Assimp
#endif // ASSIMP_Q3BSPFILEIMPORTER_H_INC
| 1,749 |
2,151 |
<reponame>LightSun/android-study<gh_stars>1000+
// Generated from XMLParser.g4 by ANTLR 4.4
package android.databinding.parser;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ParseTreeListener;
/**
* This interface defines a complete listener for a parse tree produced by
* {@link XMLParser}.
*/
public interface XMLParserListener extends ParseTreeListener {
/**
* Enter a parse tree produced by {@link XMLParser#content}.
* @param ctx the parse tree
*/
void enterContent(@NotNull XMLParser.ContentContext ctx);
/**
* Exit a parse tree produced by {@link XMLParser#content}.
* @param ctx the parse tree
*/
void exitContent(@NotNull XMLParser.ContentContext ctx);
/**
* Enter a parse tree produced by {@link XMLParser#element}.
* @param ctx the parse tree
*/
void enterElement(@NotNull XMLParser.ElementContext ctx);
/**
* Exit a parse tree produced by {@link XMLParser#element}.
* @param ctx the parse tree
*/
void exitElement(@NotNull XMLParser.ElementContext ctx);
/**
* Enter a parse tree produced by {@link XMLParser#prolog}.
* @param ctx the parse tree
*/
void enterProlog(@NotNull XMLParser.PrologContext ctx);
/**
* Exit a parse tree produced by {@link XMLParser#prolog}.
* @param ctx the parse tree
*/
void exitProlog(@NotNull XMLParser.PrologContext ctx);
/**
* Enter a parse tree produced by {@link XMLParser#document}.
* @param ctx the parse tree
*/
void enterDocument(@NotNull XMLParser.DocumentContext ctx);
/**
* Exit a parse tree produced by {@link XMLParser#document}.
* @param ctx the parse tree
*/
void exitDocument(@NotNull XMLParser.DocumentContext ctx);
/**
* Enter a parse tree produced by {@link XMLParser#attribute}.
* @param ctx the parse tree
*/
void enterAttribute(@NotNull XMLParser.AttributeContext ctx);
/**
* Exit a parse tree produced by {@link XMLParser#attribute}.
* @param ctx the parse tree
*/
void exitAttribute(@NotNull XMLParser.AttributeContext ctx);
/**
* Enter a parse tree produced by {@link XMLParser#chardata}.
* @param ctx the parse tree
*/
void enterChardata(@NotNull XMLParser.ChardataContext ctx);
/**
* Exit a parse tree produced by {@link XMLParser#chardata}.
* @param ctx the parse tree
*/
void exitChardata(@NotNull XMLParser.ChardataContext ctx);
/**
* Enter a parse tree produced by {@link XMLParser#reference}.
* @param ctx the parse tree
*/
void enterReference(@NotNull XMLParser.ReferenceContext ctx);
/**
* Exit a parse tree produced by {@link XMLParser#reference}.
* @param ctx the parse tree
*/
void exitReference(@NotNull XMLParser.ReferenceContext ctx);
/**
* Enter a parse tree produced by {@link XMLParser#misc}.
* @param ctx the parse tree
*/
void enterMisc(@NotNull XMLParser.MiscContext ctx);
/**
* Exit a parse tree produced by {@link XMLParser#misc}.
* @param ctx the parse tree
*/
void exitMisc(@NotNull XMLParser.MiscContext ctx);
}
| 956 |
1,168 |
package cn.com.heaton.blelibrary.ble.request;
import android.bluetooth.BluetoothGattCharacteristic;
import java.util.UUID;
import cn.com.heaton.blelibrary.ble.callback.wrapper.BleWrapperCallback;
import cn.com.heaton.blelibrary.ble.callback.wrapper.ReadWrapperCallback;
import cn.com.heaton.blelibrary.ble.model.BleDevice;
import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.BleRequestImpl;
import cn.com.heaton.blelibrary.ble.annotation.Implement;
import cn.com.heaton.blelibrary.ble.callback.BleReadCallback;
/**
*
* Created by LiuLei on 2017/10/23.
*/
@Implement(ReadRequest.class)
public class ReadRequest<T extends BleDevice> implements ReadWrapperCallback<T> {
private BleReadCallback<T> bleReadCallback;
private final BleWrapperCallback<T> bleWrapperCallback = Ble.options().getBleWrapperCallback();
private final BleRequestImpl<T> bleRequest = BleRequestImpl.getBleRequest();
public boolean read(T device, BleReadCallback<T> callback){
this.bleReadCallback = callback;
return bleRequest.readCharacteristic(device.getBleAddress());
}
public boolean readByUuid(T device, UUID serviceUUID, UUID characteristicUUID, BleReadCallback<T> callback){
this.bleReadCallback = callback;
return bleRequest.readCharacteristicByUuid(device.getBleAddress(), serviceUUID, characteristicUUID);
}
@Override
public void onReadSuccess(T device, BluetoothGattCharacteristic characteristic) {
if(bleReadCallback != null){
bleReadCallback.onReadSuccess(device, characteristic);
}
if (bleWrapperCallback != null){
bleWrapperCallback.onReadSuccess(device, characteristic);
}
}
@Override
public void onReadFailed(T device, int failedCode) {
if(bleReadCallback != null){
bleReadCallback.onReadFailed(device, failedCode);
}
if (bleWrapperCallback != null){
bleWrapperCallback.onReadFailed(device, failedCode);
}
}
}
| 725 |
520 |
# Unless explicitly stated otherwise all files in this repository are licensed under the BSD-3-Clause License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2015-Present Datadog, Inc
from datadog.api.resources import (
ActionAPIResource,
CreateableAPIResource,
CustomUpdatableAPIResource,
DeletableAPIResource,
GetableAPIResource,
ListableAPIResource,
)
from datadog.api.api_client import APIClient
class Roles(
ActionAPIResource,
CreateableAPIResource,
CustomUpdatableAPIResource,
GetableAPIResource,
ListableAPIResource,
DeletableAPIResource,
):
"""
A wrapper around Tag HTTP API.
"""
_resource_name = "roles"
_api_version = "v2"
@classmethod
def update(cls, id, **body):
"""
Update a role's attributes
:param id: uuid of the role
:param body: dict with type of the input, role `id`, and modified attributes
:returns: Dictionary representing the API's JSON response
"""
params = {}
return super(Roles, cls).update("PATCH", id, params=params, **body)
@classmethod
def assign_permission(cls, id, **body):
"""
Assign permission to a role
:param id: uuid of the role to assign permission to
:param body: dict with "type": "permissions" and uuid of permission to assign
:returns: Dictionary representing the API's JSON response
"""
params = {}
path = "{resource_name}/{resource_id}/permissions".format(resource_name=cls._resource_name, resource_id=id)
api_version = getattr(cls, "_api_version", None)
return APIClient.submit("POST", path, api_version, body, **params)
@classmethod
def unassign_permission(cls, id, **body):
"""
Unassign permission from a role
:param id: uuid of the role to unassign permission from
:param body: dict with "type": "permissions" and uuid of permission to unassign
:returns: Dictionary representing the API's JSON response
"""
params = {}
path = "{resource_name}/{resource_id}/permissions".format(resource_name=cls._resource_name, resource_id=id)
api_version = getattr(cls, "_api_version", None)
return APIClient.submit("DELETE", path, api_version, body, **params)
| 914 |
3,508 |
<reponame>Luv8436/Leetcode<filename>src/main/java/com/fishercoder/solutions/_1136.java<gh_stars>1000+
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class _1136 {
public static class Solution1 {
public int minimumSemesters(int n, int[][] relations) {
Map<Integer, Set<Integer>> indegree = new HashMap<>();
for (int[] rel : relations) {
if (!indegree.containsKey(rel[1])) {
indegree.put(rel[1], new HashSet<>());
}
Set<Integer> prereqs = indegree.get(rel[1]);
prereqs.add(rel[0]);
}
Queue<Integer> queue = new LinkedList<>();
Set<Integer> taken = new HashSet<>();
for (int i = 1; i <= n; i++) {
if (!indegree.containsKey(i)) {
queue.offer(i);
taken.add(i);
}
}
int minSemesters = 0;
while (!queue.isEmpty()) {
int size = queue.size();
minSemesters++;
for (int i = 0; i < size; i++) {
Integer curr = queue.poll();
for (int key : indegree.keySet()) {
Set<Integer> prereqs = indegree.get(key);
if (prereqs.contains(curr)) {
prereqs.remove(curr);
if (prereqs.size() == 0) {
queue.offer(key);
taken.add(key);
}
}
}
}
}
return taken.size() != n ? -1 : minSemesters;
}
}
}
| 1,115 |
8,148 |
#pragma once
#include "../dxvk/dxvk_device.h"
#include "../d3d10/d3d10_view_rtv.h"
#include "d3d11_device_child.h"
#include "d3d11_view.h"
namespace dxvk {
class D3D11Device;
/**
* \brief Render target view
*/
class D3D11RenderTargetView : public D3D11DeviceChild<ID3D11RenderTargetView1> {
public:
D3D11RenderTargetView(
D3D11Device* pDevice,
ID3D11Resource* pResource,
const D3D11_RENDER_TARGET_VIEW_DESC1* pDesc);
~D3D11RenderTargetView();
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject) final;
void STDMETHODCALLTYPE GetResource(ID3D11Resource** ppResource) final;
void STDMETHODCALLTYPE GetDesc(D3D11_RENDER_TARGET_VIEW_DESC* pDesc) final;
void STDMETHODCALLTYPE GetDesc1(D3D11_RENDER_TARGET_VIEW_DESC1* pDesc) final;
const D3D11_VK_VIEW_INFO& GetViewInfo() const {
return m_info;
}
BOOL HasBindFlag(UINT Flags) const {
return m_info.BindFlags & Flags;
}
D3D11_RESOURCE_DIMENSION GetResourceType() const {
D3D11_RESOURCE_DIMENSION type;
m_resource->GetType(&type);
return type;
}
Rc<DxvkImageView> GetImageView() const {
return m_view;
}
VkImageLayout GetRenderLayout() const {
return m_view->imageInfo().tiling == VK_IMAGE_TILING_OPTIMAL
? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
: VK_IMAGE_LAYOUT_GENERAL;
}
D3D10RenderTargetView* GetD3D10Iface() {
return &m_d3d10;
}
static HRESULT GetDescFromResource(
ID3D11Resource* pResource,
D3D11_RENDER_TARGET_VIEW_DESC1* pDesc);
static D3D11_RENDER_TARGET_VIEW_DESC1 PromoteDesc(
const D3D11_RENDER_TARGET_VIEW_DESC* pDesc,
UINT Plane);
static HRESULT NormalizeDesc(
ID3D11Resource* pResource,
D3D11_RENDER_TARGET_VIEW_DESC1* pDesc);
static UINT GetPlaneSlice(
const D3D11_RENDER_TARGET_VIEW_DESC1* pDesc);
private:
ID3D11Resource* m_resource;
D3D11_RENDER_TARGET_VIEW_DESC1 m_desc;
D3D11_VK_VIEW_INFO m_info;
Rc<DxvkImageView> m_view;
D3D10RenderTargetView m_d3d10;
};
}
| 1,287 |
435 |
{
"description": "- Coding a simple malware in Python. We will create a Trojan with a\n reverse shell for Windows.\n- Connecting several trojans to a botnet network via Twitter and Gmail.\n- How can we technically defend ourselves against this attack - again\n using Python.\n",
"duration": 2915,
"language": "slk",
"recorded": "2016-03-11",
"speakers": [
"<NAME>"
],
"thumbnail_url": "https://i.ytimg.com/vi/kLAhnaEaAaI/hqdefault.jpg",
"title": "Python and Malware",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=kLAhnaEaAaI"
}
]
}
| 236 |
347 |
<reponame>hbraha/ovirt-engine
package org.ovirt.engine.core.dao;
import java.util.List;
import javax.inject.Named;
import javax.inject.Singleton;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.RoleGroupMap;
import org.ovirt.engine.core.compat.Guid;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
/**
* {@code RoleGroupMapDaoImpl} provides a concrete implementation of {@link RoleGroupMapDao}.
*/
@Named
@Singleton
public class RoleGroupMapDaoImpl extends BaseDao implements RoleGroupMapDao {
private static final RowMapper<RoleGroupMap> roleGroupMapRowMapper =(rs, rowNum) ->
new RoleGroupMap(ActionGroup.forValue(rs.getInt("action_group_id")), getGuidDefaultEmpty(rs, "role_id"));
@Override
public RoleGroupMap getByActionGroupAndRole(ActionGroup group, Guid id) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("action_group_id", group.getId()).addValue("role_id", id);
return getCallsHandler().executeRead("Get_roles_groups_By_action_group_id_And_By_role_id",
roleGroupMapRowMapper,
parameterSource);
}
@Override
public List<RoleGroupMap> getAllForRole(Guid id) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("role_id", id);
return getCallsHandler().executeReadList("Get_role_groups_By_role_id",
roleGroupMapRowMapper,
parameterSource);
}
@Override
public void save(RoleGroupMap map) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("action_group_id", map.getActionGroup().getId())
.addValue("role_id", map.getRoleId());
getCallsHandler().executeModification("Insert_roles_groups", parameterSource);
}
@Override
public void remove(ActionGroup group, Guid id) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("action_group_id", group.getId()).addValue("role_id",
id);
getCallsHandler().executeModification("Delete_roles_groups", parameterSource);
}
}
| 914 |
541 |
//
// UIViewController+JMCollectionView.h
// TableViewRefreshDemo
//
// Created by xiaozhu on 2017/6/29.
// Copyright © 2017年 xiaozhu. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIViewController (JMCollectionView)
@property (nonatomic ,strong) NSMutableArray *c_dataArray;
@end
| 111 |
920 |
<filename>dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/item/IPv4CIDRACLItem.java
/*
* The Dragonite Project
* -------------------------
* See the LICENSE file in the root directory for license information.
*/
package com.vecsight.dragonite.proxy.acl.item;
import com.vecsight.dragonite.proxy.acl.ACLItemMethod;
import com.vecsight.dragonite.proxy.acl.ACLItemType;
import com.vecsight.dragonite.proxy.exception.InvalidAddressException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPv4CIDRACLItem implements ACLItem {
private final int lowest;
private final int highest;
private final ACLItemMethod method;
public IPv4CIDRACLItem(final String string, final ACLItemMethod method) throws InvalidAddressException {
this.method = method;
if (!string.contains("/")) {
throw new InvalidAddressException(string + " is not a valid IPv4 CIDR address");
}
final String[] stringSplit = string.split("/");
if (stringSplit.length != 2) {
throw new InvalidAddressException(string + " is not a valid IPv4 CIDR address");
}
final byte[] bytes;
try {
bytes = InetAddress.getByName(stringSplit[0]).getAddress();
if (bytes.length != 4) throw new InvalidAddressException(string + " is not a valid IPv4 address");
} catch (final UnknownHostException e) {
throw new InvalidAddressException(stringSplit[0] + " is not a valid IPv4 address");
}
final int mask;
try {
final int shift = Integer.parseInt(stringSplit[1]);
if (shift < 1 || shift > 32)
throw new InvalidAddressException(string + " is not a valid IPv4 CIDR address");
mask = (-1) << (32 - shift);
} catch (final NumberFormatException e) {
throw new InvalidAddressException(string + " is not a valid IPv4 CIDR address");
}
final int addr = ipv4ToInt(bytes);
lowest = addr & mask;
highest = lowest + (~mask);
}
private int ipv4ToInt(final byte[] bytes) {
return ((bytes[0] << 24) & 0xFF000000)
| ((bytes[1] << 16) & 0xFF0000)
| ((bytes[2] << 8) & 0xFF00)
| (bytes[3] & 0xFF);
}
@Override
public ACLItemType getType() {
return ACLItemType.IPv4_CIDR;
}
@Override
public ACLItemMethod getMethod() {
return method;
}
@Override
public boolean match(final String domain) {
return false;
}
@Override
public boolean match(final byte[] address) {
if (address.length != 4) return false;
final int addr = ipv4ToInt(address);
return addr >= lowest && addr <= highest;
}
}
| 1,120 |
518 |
/*
* Copyright (c) 2010-2020 OTClient <https://github.com/edubart/otclient>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef OTMLPARSER_H
#define OTMLPARSER_H
#include "declarations.h"
class OTMLParser
{
public:
OTMLParser(OTMLDocumentPtr doc, std::istream& in);
/// Parse the entire document
void parse();
private:
/// Retrieve next line from the input stream
std::string getNextLine();
/// Counts depth of a line (every 2 spaces increments one depth)
int getLineDepth(const std::string& line, bool multilining = false);
/// Parse each line of the input stream
void parseLine(std::string line);
/// Parse nodes tag and value
void parseNode(const std::string& data);
int currentDepth;
int currentLine;
OTMLDocumentPtr doc;
OTMLNodePtr currentParent;
std::unordered_map<OTMLNodePtr, OTMLNodePtr> parentMap;
OTMLNodePtr previousNode;
std::istream& in;
};
#endif
| 592 |
1,350 |
<filename>sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/src/main/java/com/azure/resourcemanager/timeseriesinsights/implementation/EnvironmentResourceImpl.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.timeseriesinsights.implementation;
import com.azure.resourcemanager.timeseriesinsights.fluent.models.EnvironmentResourceInner;
import com.azure.resourcemanager.timeseriesinsights.models.EnvironmentResource;
import com.azure.resourcemanager.timeseriesinsights.models.Sku;
import java.util.Collections;
import java.util.Map;
public final class EnvironmentResourceImpl implements EnvironmentResource {
private EnvironmentResourceInner innerObject;
private final com.azure.resourcemanager.timeseriesinsights.TimeSeriesInsightsManager serviceManager;
EnvironmentResourceImpl(
EnvironmentResourceInner innerObject,
com.azure.resourcemanager.timeseriesinsights.TimeSeriesInsightsManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
}
public String id() {
return this.innerModel().id();
}
public String name() {
return this.innerModel().name();
}
public String type() {
return this.innerModel().type();
}
public String location() {
return this.innerModel().location();
}
public Map<String, String> tags() {
Map<String, String> inner = this.innerModel().tags();
if (inner != null) {
return Collections.unmodifiableMap(inner);
} else {
return Collections.emptyMap();
}
}
public Sku sku() {
return this.innerModel().sku();
}
public EnvironmentResourceInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.timeseriesinsights.TimeSeriesInsightsManager manager() {
return this.serviceManager;
}
}
| 677 |
310 |
<reponame>tsukoyumi/skylicht-engine
#include "pch.h"
#include "SkylichtEngine.h"
#include "SampleNoise3D.h"
#include "GridPlane/CGridPlane.h"
#include "CSphereComponent.h"
void installApplication(const std::vector<std::string>& argv)
{
SampleNoise3D *app = new SampleNoise3D();
getApplication()->registerAppEvent("SampleNoise3D", app);
}
SampleNoise3D::SampleNoise3D() :
m_scene(NULL),
m_forwardRP(NULL),
m_postProcessorRP(NULL),
m_noiseOffset(3.0f, 0.0f, 0.0f)
#if defined(USE_FREETYPE)
, m_largeFont(NULL)
#endif
{
}
SampleNoise3D::~SampleNoise3D()
{
delete m_scene;
#if defined(USE_FREETYPE)
delete m_largeFont;
#endif
delete m_forwardRP;
delete m_postProcessorRP;
}
void SampleNoise3D::onInitApp()
{
// init application
CBaseApp* app = getApplication();
// load "BuiltIn.zip" to read files inside it
app->getFileSystem()->addFileArchive(app->getBuiltInPath("BuiltIn.zip"), false, false);
#if defined(USE_FREETYPE)
// init segoeuil.ttf inside BuiltIn.zip
CGlyphFreetype *freetypeFont = CGlyphFreetype::getInstance();
freetypeFont->initFont("Segoe UI Light", "BuiltIn/Fonts/segoeui/segoeuil.ttf");
#endif
// load basic shader
CShaderManager *shaderMgr = CShaderManager::getInstance();
shaderMgr->initBasicShader();
// create a Scene
m_scene = new CScene();
// create a Zone in Scene
CZone *zone = m_scene->createZone();
// create 2D camera
CGameObject *guiCameraObject = zone->createEmptyObject();
m_guiCamera = guiCameraObject->addComponent<CCamera>();
m_guiCamera->setProjectionType(CCamera::OrthoUI);
// create 3D camera
CGameObject *camObj = zone->createEmptyObject();
camObj->addComponent<CCamera>();
camObj->addComponent<CEditorCamera>()->setMoveSpeed(2.0f);
camObj->addComponent<CFpsMoveCamera>()->setMoveSpeed(1.0f);
m_camera = camObj->getComponent<CCamera>();
m_camera->setPosition(core::vector3df(0.0f, 1.5f, 4.0f));
m_camera->lookAt(core::vector3df(0.0f, 0.0f, 0.0f), core::vector3df(0.0f, 1.0f, 0.0f));
// 3d grid
// CGameObject *grid = zone->createEmptyObject();
// grid->addComponent<CGridPlane>();
// lighting
CGameObject *lightObj = zone->createEmptyObject();
CDirectionalLight *directionalLight = lightObj->addComponent<CDirectionalLight>();
SColor c(255, 255, 244, 214);
directionalLight->setColor(SColorf(c));
CTransformEuler *lightTransform = lightObj->getTransformEuler();
lightTransform->setPosition(core::vector3df(2.0f, 2.0f, 2.0f));
core::vector3df direction = core::vector3df(0.0f, -1.5f, 2.0f);
lightTransform->setOrientation(direction, CTransform::s_oy);
// add sphere
CGameObject *sphereObj;
CSphereComponent *sphere;
sphereObj = zone->createEmptyObject();
sphere = sphereObj->addComponent<CSphereComponent>();
sphere->getMaterial()->changeShader("BuiltIn/Shader/Noise/Noise3D.xml");
sphereObj->getTransformEuler()->setPosition(core::vector3df(3.0f, 0.0f, 0.0f));
m_materials.push_back(sphere->getMaterial());
sphereObj = zone->createEmptyObject();
sphere = sphereObj->addComponent<CSphereComponent>();
sphere->getMaterial()->changeShader("BuiltIn/Shader/Noise/Electric3D.xml");
sphereObj->getTransformEuler()->setPosition(core::vector3df(0.0f, 0.0f, 0.0f));
m_materials.push_back(sphere->getMaterial());
sphereObj = zone->createEmptyObject();
sphere = sphereObj->addComponent<CSphereComponent>();
sphere->getMaterial()->changeShader("BuiltIn/Shader/Noise/StarSequence3D.xml");
sphereObj->getTransformEuler()->setPosition(core::vector3df(-3.0f, 0.0f, 0.0f));
m_materials.push_back(sphere->getMaterial());
#if defined(USE_FREETYPE)
m_largeFont = new CGlyphFont();
m_largeFont->setFont("Segoe UI Light", 50);
// create 2D Canvas
CGameObject *canvasObject = zone->createEmptyObject();
CCanvas *canvas = canvasObject->addComponent<CCanvas>();
// create UI Text in Canvas
CGUIText *textLarge = canvas->createText(m_largeFont);
textLarge->setText("SampleNoise3D");
textLarge->setTextAlign(CGUIElement::Left, CGUIElement::Top);
#endif
// rendering pipe line
u32 w = app->getWidth();
u32 h = app->getHeight();
m_forwardRP = new CForwardRP();
m_forwardRP->initRender(w, h);
m_postProcessorRP = new CPostProcessorRP();
m_postProcessorRP->enableAutoExposure(false);
m_postProcessorRP->enableBloomEffect(true);
m_postProcessorRP->enableFXAA(true);
m_postProcessorRP->initRender(w, h);
m_forwardRP->setPostProcessor(m_postProcessorRP);
}
void SampleNoise3D::onUpdate()
{
m_noiseOffset = m_noiseOffset + core::vector3df(-0.0003f, 0.0000f, 0.0003f) * getTimeStep();
float params[4];
params[0] = m_noiseOffset.X;
params[1] = m_noiseOffset.Y;
params[2] = m_noiseOffset.Z;
params[3] = 8.0f;
for (CMaterial *m : m_materials)
{
m->setUniform4("uNoiseOffset", params);
m->updateShaderParams();
}
// update application
m_scene->update();
}
void SampleNoise3D::onRender()
{
// render 3d scene
m_forwardRP->render(NULL, m_camera, m_scene->getEntityManager(), core::recti());
// render text in gui camera
CGraphics2D::getInstance()->render(m_guiCamera);
}
void SampleNoise3D::onPostRender()
{
// post render application
}
bool SampleNoise3D::onBack()
{
// on back key press
// return TRUE will run default by OS (Mobile)
// return FALSE will cancel BACK FUNCTION by OS (Mobile)
return true;
}
void SampleNoise3D::onResize(int w, int h)
{
if (m_forwardRP != NULL)
m_forwardRP->resize(w, h);
if (m_postProcessorRP != NULL)
m_postProcessorRP->resize(w, h);
}
void SampleNoise3D::onResume()
{
// resume application
}
void SampleNoise3D::onPause()
{
// pause application
}
void SampleNoise3D::onQuitApp()
{
// end application
delete this;
}
| 2,141 |
1,498 |
<reponame>cgutman/userland
/*
Copyright (c) 2012, Broadcom Europe Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file
* OpenMAX IL adaptation layer for MMAL - Parameters related functions
*/
#include "interface/vmcs_host/khronos/IL/OMX_Broadcom.h"
#include "mmalomx_util_params.h"
#include "util/mmal_util_rational.h"
/* Sanity check that OMX is defining the right int32 types */
vcos_static_assert(sizeof(OMX_U32) == 4);
MMAL_STATUS_T mmalomx_param_enum_generic(MMALOMX_PARAM_MAPPING_DIRECTION dir,
const struct MMALOMX_PARAM_TRANSLATION_T *xlat,
MMAL_PARAMETER_HEADER_T *mmal, OMX_PTR omx, MMAL_PORT_T *mmal_port);
MMAL_STATUS_T mmalomx_param_rational_generic(MMALOMX_PARAM_MAPPING_DIRECTION dir,
const struct MMALOMX_PARAM_TRANSLATION_T *xlat,
MMAL_PARAMETER_HEADER_T *mmal, OMX_PTR omx, MMAL_PORT_T *mmal_port);
MMAL_STATUS_T mmalomx_param_mapping_generic(MMALOMX_PARAM_MAPPING_DIRECTION dir,
const struct MMALOMX_PARAM_TRANSLATION_T *xlat,
MMAL_PARAMETER_HEADER_T *mmal, OMX_PTR omx, MMAL_PORT_T *mmal_port);
extern const MMALOMX_PARAM_TRANSLATION_T mmalomx_param_xlator_audio[];
extern const MMALOMX_PARAM_TRANSLATION_T mmalomx_param_xlator_video[];
extern const MMALOMX_PARAM_TRANSLATION_T mmalomx_param_xlator_camera[];
extern const MMALOMX_PARAM_TRANSLATION_T mmalomx_param_xlator_misc[];
#define MMALOMX_PARAM_ENUM_FIND(TYPE, VAR, TABLE, DIR, MMAL, OMX) \
const TYPE *VAR = TABLE; \
const TYPE *VAR##_end = VAR + MMAL_COUNTOF(TABLE); \
if (DIR == MMALOMX_PARAM_MAPPING_TO_MMAL) \
while (VAR < VAR##_end && VAR->omx != OMX) VAR++; \
else \
while (VAR < VAR##_end && VAR->mmal != MMAL) VAR++; \
do { if (VAR == VAR##_end) { \
VAR = 0; \
if (DIR == MMALOMX_PARAM_MAPPING_TO_MMAL) \
VCOS_ALERT("omx enum value %u not supported", (unsigned int)OMX); \
else \
VCOS_ALERT("mmal enum value %u not supported", (unsigned int)MMAL); \
} } while(0)
#define mmalomx_ct_assert(e) (sizeof(char[1 - 2*!(e)]))
/** List of macros used to define parameters mapping */
#define MMALOMX_PARAM_PASSTHROUGH(a,b,c,d) \
{a, (uint32_t)c, sizeof(b), sizeof(d), \
!(offsetof(d, nPortIndex) | mmalomx_ct_assert(sizeof(b)+4==sizeof(d))), \
0, MMALOMX_PARAM_TRANSLATION_TYPE_CUSTOM, {0, mmalomx_param_mapping_generic, 0, 0}, 0, 0, \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_BOOLEAN(a, b) \
MMALOMX_PARAM_PASSTHROUGH(a, MMAL_PARAMETER_BOOLEAN_T, b, OMX_CONFIG_PORTBOOLEANTYPE)
#define MMALOMX_PARAM_PASSTHROUGH_PORTLESS(a,b,c,d) \
{a, (uint32_t)c, sizeof(b), sizeof(d), \
!!(mmalomx_ct_assert(sizeof(b)==sizeof(d))), \
0, MMALOMX_PARAM_TRANSLATION_TYPE_CUSTOM, {0, mmalomx_param_mapping_generic, 0, 0}, 0, 0, \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_BOOLEAN_PORTLESS(a, b) \
MMALOMX_PARAM_PASSTHROUGH_PORTLESS(a, MMAL_PARAMETER_BOOLEAN_T, b, OMX_CONFIG_BOOLEANTYPE)
#define MMALOMX_PARAM_PASSTHROUGH_PORTLESS_DOUBLE_TRANSLATION(a,b,c,d) \
{a, (uint32_t)c, sizeof(b), sizeof(d), \
!!(mmalomx_ct_assert(sizeof(b)==sizeof(d))), \
1, MMALOMX_PARAM_TRANSLATION_TYPE_CUSTOM, {0, mmalomx_param_mapping_generic, 0, 0}, 0, 0, \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_DIRECT_PORTLESS(a,b,c,d) \
{a, (uint32_t)c, sizeof(b), sizeof(d), 1, \
0, MMALOMX_PARAM_TRANSLATION_TYPE_DIRECT, {0, 0, 0, 0}, 0, 0, \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_STRAIGHT_MAPPING(a,b,c,d,e) \
{a, (uint32_t)c, sizeof(b), sizeof(d), \
!offsetof(d, nPortIndex), \
0, MMALOMX_PARAM_TRANSLATION_TYPE_SIMPLE, {e, 0, 0, 0}, 0, 0, \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_STRAIGHT_MAPPING_PORTLESS(a,b,c,d,e) \
{a, (uint32_t)c, sizeof(b), sizeof(d), 1, \
0, MMALOMX_PARAM_TRANSLATION_TYPE_SIMPLE, {e, 0, 0, 0}, 0, 0, \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_STRAIGHT_MAPPING_DOUBLE_TRANSLATION(a,b,c,d,e) \
{a, (uint32_t)c, sizeof(b), sizeof(d), 0, \
1, MMALOMX_PARAM_TRANSLATION_TYPE_SIMPLE, {e, 0, 0, 0}, 0, 0, \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_ENUM(a,b,c,d,e) \
{a, (uint32_t)c, sizeof(b), sizeof(d), 0, \
0, MMALOMX_PARAM_TRANSLATION_TYPE_CUSTOM, {0, mmalomx_param_enum_generic, 0, 0}, e, MMAL_COUNTOF(e), \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_ENUM_PORTLESS(a,b,c,d,e) \
{a, (uint32_t)c, sizeof(b), sizeof(d), 1, \
0, MMALOMX_PARAM_TRANSLATION_TYPE_CUSTOM, {0, mmalomx_param_enum_generic, 0, 0}, e, MMAL_COUNTOF(e), \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_RATIONAL(a,b,c,d,e) \
{a, (uint32_t)c, sizeof(b), sizeof(d), 0, \
0, MMALOMX_PARAM_TRANSLATION_TYPE_CUSTOM, {0, mmalomx_param_rational_generic, 0, 0}, 0, e, \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_RATIONAL_PORTLESS(a,b,c,d,e) \
{a, (uint32_t)c, sizeof(b), sizeof(d), 1, \
0, MMALOMX_PARAM_TRANSLATION_TYPE_CUSTOM, {0, mmalomx_param_rational_generic, 0, 0}, 0, e, \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_CUSTOM(a,b,c,d,e) \
{a, (uint32_t)c, sizeof(b), sizeof(d), 0, \
0, MMALOMX_PARAM_TRANSLATION_TYPE_CUSTOM, {0, e, 0, 0}, 0, 0, \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_LIST(a,b,c,d,e,f) \
{a, (uint32_t)c, sizeof(b), sizeof(d), 0, \
0, MMALOMX_PARAM_TRANSLATION_TYPE_CUSTOM, {0, 0, f, 0}, 0, offsetof(d,e), \
MMAL_TO_STRING(a), MMAL_TO_STRING(c)}
#define MMALOMX_PARAM_TERMINATE() \
{MMAL_PARAMETER_UNUSED, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0}, 0, 0, 0, 0}
| 3,206 |
679 |
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef SD_TOOLPANEL_SCROLL_PANEL_HXX
#define SD_TOOLPANEL_SCROLL_PANEL_HXX
#include "taskpane/TaskPaneTreeNode.hxx"
#include <vcl/ctrl.hxx>
#include <vcl/scrbar.hxx>
#include <memory>
#include <vector>
namespace sd { namespace toolpanel {
class TitledControl;
/** The scroll panel shows its controls one above the other. When their
total height is larger than the height of the scroll area then only a
part of the controls is visible. Scroll bars control which part that
is.
The scroll panel registers itself as window event listener at the
controls and their title bars (conceptually; it really is the
TitledControl) to track changes of the selection and focus rectangles.
On such a change it tries to move the selected or focused part into the
visible area. At the moment this moving into view only works with
valuesets and TitleBars.
*/
class ScrollPanel
: public ::Control,
public TreeNode
{
public:
/** Create a new scroll panel which itself is the root of a TreeNode hierarchy
parent. This will usually be a child window.
*/
ScrollPanel (::Window& i_rParentWindow);
virtual ~ScrollPanel (void);
/** Add a control to the sub panel. An title bar is added above the
control.
@param rTitle
The title that will be shown in the two title bars that
belong to the control.
@param nHelpId
The help id is set at the title bar not the actual control.
@return
The new titled control that contains the given control and a new
title bar as children is returned.
*/
TitledControl* AddControl (
::std::auto_ptr<TreeNode> pControl,
const String& rTitle,
const rtl::OString& sHelpId);
/** Add a control to the sub panel without a title bar.
*/
void AddControl (::std::auto_ptr<TreeNode> pControl);
virtual void Paint (const Rectangle& rRect);
/** Initiate a rearrangement of the controls and title bars.
*/
virtual void Resize (void);
virtual void RequestResize (void);
virtual Size GetPreferredSize (void);
virtual sal_Int32 GetPreferredWidth (sal_Int32 nHeight);
virtual sal_Int32 GetPreferredHeight (sal_Int32 nWidth);
virtual bool IsResizable (void);
virtual ::Window* GetWindow (void);
virtual sal_Int32 GetMinimumWidth (void);
virtual void ExpandControl (
TreeNode* pControl,
bool bExpansionState);
bool IsVerticalScrollBarVisible (void) const;
bool IsHorizontalScrollBarVisible (void) const;
ScrollBar& GetVerticalScrollBar (void);
ScrollBar& GetHorizontalScrollBar (void);
// ::Window
virtual long Notify( NotifyEvent& rNEvt );
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible> CreateAccessibleObject (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent);
/** Scroll the given rectangle into the visible area.
@param aRectangle
The box to move into the visible area in pixel coordinates
relative to the given window.
@param pWindow
This window is used to translate the given coordinates into ones
that are relative to the scroll panel.
*/
void MakeRectangleVisible (
Rectangle& aRectangle,
::Window* pWindow);
private:
::Control maScrollWindow;
ScrollBar maVerticalScrollBar;
ScrollBar maHorizontalScrollBar;
::Window maScrollBarFiller;
::Window maScrollWindowFiller;
Point maScrollOffset;
bool mbIsRearrangePending;
bool mbIsLayoutPending;
sal_uInt32 mnChildrenWidth;
/// Border above top-most and below bottom-most control.
const int mnVerticalBorder;
/// Gap between two controls.
const int mnVerticalGap;
/// Border at the left and right of the controls.
const int mnHorizontalBorder;
/** List of horizontal stripes that is created from the gaps between
children when they are layouted. The stripes are painted in Paint()
to fill the space around the children.
*/
typedef ::std::vector< ::std::pair<int,int> > StripeList;
StripeList maStripeList;
/** Calculate position, size, and visibility of the controls.
Call this method after the list of controls, their expansion
state, or the size of the sub panel has changed.
*/
void Rearrange (void);
/** Determine the minimal size that is necessary to show the controls
one over the other. It may be smaller than the available area.
*/
Size GetRequiredSize (void);
/** Place the child windows one above the other and return the size of
the bounding box.
*/
sal_Int32 LayoutChildren (void);
/** ctor-impl
*/
void Construct();
Size SetupScrollBars (const Size& rRequiresSize);
sal_Int32 SetupVerticalScrollBar (bool bShow, sal_Int32 nRange);
sal_Int32 SetupHorizontalScrollBar (bool bShow, sal_Int32 nRange);
DECL_LINK(ScrollBarHandler, ScrollBar*);
DECL_LINK(WindowEventListener, VclSimpleEvent*);
using Window::GetWindow;
};
} } // end of namespace ::sd::toolpanel
#endif
| 2,055 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.