max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
435 | <filename>euroscipy-2017/videos/euroscipy-2017-pyrate-optical-raytracing-based-on-python.json
{
"copyright_text": "Creative Commons Attribution license (reuse allowed)",
"description": "Pyrate is a program for scientific optical lens design. It traces rays\nthrough an optical system and optimizes its properties, e.g. lens radii.\n\nThe merit function to be minimized during optimization can vastly vary\ndepending on the type of objective and constraints. During the design\nprocess, the merit function is changed a lot, as the system must fulfill\never more requirements when approaching production readiness.\n\nWe present a variable container, storing the variable value, its status,\nand possible constraints. The status is used to indicate whether the\nvariable shall be optimized or not. Designers often use only parts of\nthe available variables, especially in early design stages.\n\nBefore optimization, the highest hierarchy object collects all\ncontainers from its children and grandchildren, wraps them to a format\nusable by scipy.minimize and optimizes the system with the current merit\nfunction.\n\nWe show several examples of optical systems optimized with our program.",
"duration": 846,
"language": "eng",
"recorded": "2017-08-31",
"related_urls": [
{
"label": "schedule",
"url": "https://www.euroscipy.org/2017/program.html"
}
],
"speakers": [
"<NAME>",
"<NAME>"
],
"tags": [
"pyrate",
"raytracing"
],
"thumbnail_url": "https://i.ytimg.com/vi/fpX9yvIp160/maxresdefault.jpg",
"title": "Pyrate - Optical Raytracing Based on Python",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=fpX9yvIp160"
}
]
}
| 542 |
337 | public class JavaClass {
public static String getNull() {
return null;
}
public static My getMy() {
return null;
}
} | 61 |
1,200 | <gh_stars>1000+
#ifndef LEGO_MQLogger_H_
#define LEGO_MQLogger_H_
#include <string>
namespace CarreraConsumer {
typedef void (* LEGO_LOG_FUNC)(const char *);
class MQLogger
{
public:
MQLogger():func_(&DefaultOutputWrapper){}
virtual ~MQLogger(){}
void SetOutputFunction(LEGO_LOG_FUNC func);
void Print(const char *message);
void Printf(const char *message, ...);
static void DefaultOutputWrapper(const char* msg);
private:
LEGO_LOG_FUNC func_;
};
extern MQLogger mq_logger;
}
#endif // LEGO_MQLogger_H_
| 227 |
2,452 | <reponame>iyzwei4666/MyWeibo<filename>toutiao/src/main/java/com/meiji/toutiao/setting/TextSizeFragment.java
package com.meiji.toutiao.setting;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.jaygoo.widget.RangeSeekBar;
import com.meiji.toutiao.R;
import com.meiji.toutiao.module.base.BaseListFragment;
import com.meiji.toutiao.util.RxBus;
import com.meiji.toutiao.util.SettingUtil;
import java.text.DecimalFormat;
/**
* Created by Meiji on 2017/8/16.
*/
public class TextSizeFragment extends Fragment {
private RangeSeekBar seekbar;
private TextView text;
private DecimalFormat df = new DecimalFormat("0");
private int currentSize = -1;
private SettingUtil settingUtil = SettingUtil.getInstance();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting_textsize, container, false);
initView(view);
return view;
}
private void initView(View view) {
seekbar = view.findViewById(R.id.seekbar);
text = view.findViewById(R.id.text);
text.setTextSize(settingUtil.getTextSize());
seekbar.setValue(settingUtil.getTextSize() - 14);
seekbar.setLineColor(0, settingUtil.getColor());
seekbar.setOnRangeChangedListener(new RangeSeekBar.OnRangeChangedListener() {
@Override
public void onRangeChanged(RangeSeekBar view, final float min, float max, boolean isFromUser) {
if (isFromUser) {
int size = Integer.parseInt(df.format(min));
if (currentSize != size) {
setText(size);
currentSize = size;
}
}
}
@Override
public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {
}
@Override
public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
}
});
}
private void setText(int size) {
// 最小 14sp
size = 14 + size;
text.setTextSize(size);
settingUtil.setTextSize(size);
RxBus.getInstance().post(BaseListFragment.TAG, size);
}
}
| 1,067 |
333 | <filename>src/main/java/com/alipay/api/domain/AlipayOpenMiniDeploypackageQueryModel.java
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 线上拉包接口
*
* @author auto create
* @since 1.0, 2019-09-16 11:48:31
*/
public class AlipayOpenMiniDeploypackageQueryModel extends AlipayObject {
private static final long serialVersionUID = 6197782786757851683L;
/**
* 端标识
*/
@ApiField("bundle_id")
private String bundleId;
/**
* 客户端层面的渠道:CHANNEL_OFFICIAL 正式包 CHANNEL_RC 灰度包
*/
@ApiField("channel")
private String channel;
/**
* 客户端版本
*/
@ApiField("client")
private String client;
/**
* 设备号
*/
@ApiField("diu")
private String diu;
/**
* 环境:prepub 预发、线上 production)
*/
@ApiField("env")
private String env;
/**
* 本地已存在的包信息
*/
@ApiField("existed")
private String existed;
/**
* 灰度规则
*/
@ApiField("gray_rules")
private String grayRules;
/**
* 只在应用应用互保,本地应用版本信息
*/
@ApiField("local_app_info")
private String localAppInfo;
/**
* 平台标识
*/
@ApiField("platform")
private String platform;
/**
* 是否开启互保
*/
@ApiField("prefer_local")
private String preferLocal;
/**
* 协议版本号
*/
@ApiField("protocol")
private String protocol;
/**
* 拉包请求的数据
*/
@ApiField("query")
private String query;
/**
* 请求同步/异步标识
*/
@ApiField("req_mode")
private String reqMode;
/**
* 客户端sdk版本号,一般输出给多端使用
*/
@ApiField("sdk")
private String sdk;
/**
* 是否开启强大的RPC功能
*/
@ApiField("stable_rpc")
private String stableRpc;
/**
* 系统版本号
*/
@ApiField("system")
private String system;
/**
* 蚂蚁统一会员ID
*/
@ApiField("user_id")
private String userId;
public String getBundleId() {
return this.bundleId;
}
public void setBundleId(String bundleId) {
this.bundleId = bundleId;
}
public String getChannel() {
return this.channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getClient() {
return this.client;
}
public void setClient(String client) {
this.client = client;
}
public String getDiu() {
return this.diu;
}
public void setDiu(String diu) {
this.diu = diu;
}
public String getEnv() {
return this.env;
}
public void setEnv(String env) {
this.env = env;
}
public String getExisted() {
return this.existed;
}
public void setExisted(String existed) {
this.existed = existed;
}
public String getGrayRules() {
return this.grayRules;
}
public void setGrayRules(String grayRules) {
this.grayRules = grayRules;
}
public String getLocalAppInfo() {
return this.localAppInfo;
}
public void setLocalAppInfo(String localAppInfo) {
this.localAppInfo = localAppInfo;
}
public String getPlatform() {
return this.platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getPreferLocal() {
return this.preferLocal;
}
public void setPreferLocal(String preferLocal) {
this.preferLocal = preferLocal;
}
public String getProtocol() {
return this.protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getQuery() {
return this.query;
}
public void setQuery(String query) {
this.query = query;
}
public String getReqMode() {
return this.reqMode;
}
public void setReqMode(String reqMode) {
this.reqMode = reqMode;
}
public String getSdk() {
return this.sdk;
}
public void setSdk(String sdk) {
this.sdk = sdk;
}
public String getStableRpc() {
return this.stableRpc;
}
public void setStableRpc(String stableRpc) {
this.stableRpc = stableRpc;
}
public String getSystem() {
return this.system;
}
public void setSystem(String system) {
this.system = system;
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
| 1,989 |
8,805 | /*=============================================================================
Copyright (c) 2016 <NAME>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef PHOENIX_BIND_BIND_MEMBER_FUNCTION_HPP
#define PHOENIX_BIND_BIND_MEMBER_FUNCTION_HPP
#include <boost/phoenix/core/limits.hpp>
#if defined(BOOST_PHOENIX_NO_VARIADIC_BIND)
# include <boost/phoenix/bind/detail/cpp03/bind_member_function.hpp>
#else
#include <boost/phoenix/core/expression.hpp>
#include <boost/phoenix/core/reference.hpp>
#include <boost/phoenix/core/detail/function_eval.hpp>
namespace boost { namespace phoenix
{
namespace detail
{
template <typename RT, typename FP>
struct member_function_ptr
{
typedef RT result_type;
member_function_ptr(FP fp_)
: fp(fp_) {}
template <typename Class, typename... A>
result_type operator()(Class& obj, A&... a) const
{
BOOST_PROTO_USE_GET_POINTER();
typedef typename proto::detail::class_member_traits<FP>::class_type class_type;
return (BOOST_PROTO_GET_POINTER(class_type, obj)->*fp)(a...);
}
template <typename Class, typename... A>
result_type operator()(Class* obj, A&... a) const
{
return (obj->*fp)(a...);
}
bool operator==(member_function_ptr const& rhs) const
{
return fp == rhs.fp;
}
template <int M, typename RhsRT, typename RhsFP>
bool operator==(member_function_ptr<RhsRT, RhsFP> const& /*rhs*/) const
{
return false;
}
FP fp;
};
} // namespace boost::phoenix::detail
template <typename RT, typename ClassT, typename... T, typename ClassA, typename... A>
inline
typename detail::expression::function_eval<
detail::member_function_ptr<RT, RT(ClassT::*)(T...)>
, ClassA
, A...
>::type const
bind(RT (ClassT::*f)(T...), ClassA const & obj, A const&... a)
{
typedef detail::member_function_ptr<RT, RT (ClassT::*)(T...)> fp_type;
return detail::expression::function_eval<fp_type, ClassA, A...>::make(fp_type(f), obj, a...);
}
template <typename RT, typename ClassT, typename... T, typename ClassA, typename... A>
inline
typename detail::expression::function_eval<
detail::member_function_ptr<RT, RT (ClassT::*)(T...) const>
, ClassA
, A...
>::type const
bind(RT (ClassT::*f)(T...) const, ClassA const & obj, A const&... a)
{
typedef detail::member_function_ptr<RT, RT(ClassT::*)(T...) const> fp_type;
return detail::expression::function_eval<fp_type, ClassA, A...>::make(fp_type(f), obj, a...);
}
template <typename RT, typename ClassT, typename... T, typename... A>
inline
typename detail::expression::function_eval<
detail::member_function_ptr<RT, RT(ClassT::*)(T...)>
, ClassT
, A...
>::type const
bind(RT (ClassT::*f)(T...), ClassT & obj, A const&... a)
{
typedef detail::member_function_ptr<RT, RT(ClassT::*)(T...)> fp_type;
return detail::expression::function_eval<fp_type, ClassT, A...>::make(fp_type(f), obj, a...);
}
template <typename RT, typename ClassT, typename... T, typename... A>
inline
typename detail::expression::function_eval<
detail::member_function_ptr<RT, RT(ClassT::*)(T...) const>
, ClassT
, A...
>::type const
bind(RT (ClassT::*f)(T...) const, ClassT const& obj, A const&... a)
{
typedef detail::member_function_ptr<RT, RT(ClassT::*)(T...) const> fp_type;
return detail::expression::function_eval<fp_type, ClassT, A...>::make(fp_type(f), obj, a...);
}
}} // namespace boost::phoenix
#endif
#endif
| 1,917 |
1,224 | /*******************************************************************************
* Copyright (c) 2016 EclipseSource and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* EclipseSource - initial API and implementation
******************************************************************************/
package com.eclipsesource.v8;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* V8ArrayBuffers represent ArrayBuffers from V8, but are backed by a
* java.nio.ByteBuffer. This means that any data stored in a TypedArray
* can be accessed by the java.nio.ByteBuffer. This significantly improves
* performance of data access from Java to JavaScript.
*
* V8ArrayBuffers can either be constructed in Java, or returned from
* JavaScript.
*
*/
public class V8ArrayBuffer extends V8Value {
ByteBuffer byteBuffer;
/**
* Creates a new V8ArrayBuffer on a given V8Runtime with a
* given capacity.
*
* @param v8 The runtime on which to create the ArrayBuffer
* @param capacity The capacity of the buffer
*/
public V8ArrayBuffer(final V8 v8, final int capacity) {
super(v8);
initialize(v8.getV8RuntimePtr(), capacity);
byteBuffer = v8.createV8ArrayBufferBackingStore(v8.getV8RuntimePtr(), objectHandle, capacity);
byteBuffer.order(ByteOrder.nativeOrder());
}
public V8ArrayBuffer(final V8 v8, ByteBuffer byteBuffer) {
super(v8);
if (byteBuffer == null) {
byteBuffer = ByteBuffer.allocateDirect(0);
}
if (!byteBuffer.isDirect()) {
throw new IllegalArgumentException("ByteBuffer must be a allocated as a direct ByteBuffer");
}
initialize(v8.getV8RuntimePtr(), byteBuffer);
this.byteBuffer = byteBuffer;
byteBuffer.order(ByteOrder.nativeOrder());
}
@Override
protected void initialize(final long runtimePtr, final Object data) {
v8.checkThread();
if (data instanceof ByteBuffer) {
ByteBuffer buffer = (ByteBuffer) data;
int capacity = buffer.limit();
objectHandle = v8.initNewV8ArrayBuffer(v8.getV8RuntimePtr(), buffer, capacity);
} else {
int capacity = (Integer) data;
objectHandle = v8.initNewV8ArrayBuffer(v8.getV8RuntimePtr(), capacity);
}
released = false;
addObjectReference(objectHandle);
}
@Override
protected V8Value createTwin() {
return new V8ArrayBuffer(v8, byteBuffer);
}
/*
* (non-Javadoc)
* @see com.eclipsesource.v8.V8Object#twin()
*/
@Override
public V8ArrayBuffer twin() {
v8.checkThread();
checkReleased();
return (V8ArrayBuffer) super.twin();
}
/**
* Returns the buffers limit
*
* @return the buffers limit
*/
public int limit() {
v8.checkThread();
checkReleased();
return byteBuffer.limit();
}
/**
* Returns the buffers capacity
*
* @return the buffers capacity
*/
public final int capacity() {
v8.checkThread();
checkReleased();
return byteBuffer.capacity();
}
/**
*
* @return
*/
public final int position() {
v8.checkThread();
checkReleased();
return byteBuffer.position();
}
public final V8ArrayBuffer position(final int newPosition) {
v8.checkThread();
checkReleased();
byteBuffer.position(newPosition);
return this;
}
public final V8ArrayBuffer limit(final int newLimit) {
v8.checkThread();
checkReleased();
byteBuffer.limit(newLimit);
return this;
}
public final V8ArrayBuffer mark() {
v8.checkThread();
checkReleased();
byteBuffer.mark();
return this;
}
public final V8ArrayBuffer reset() {
v8.checkThread();
checkReleased();
byteBuffer.reset();
return this;
}
public final V8ArrayBuffer clear() {
v8.checkThread();
checkReleased();
byteBuffer.clear();
return this;
}
public final V8ArrayBuffer flip() {
v8.checkThread();
checkReleased();
byteBuffer.flip();
return this;
}
public final V8ArrayBuffer rewind() {
v8.checkThread();
checkReleased();
byteBuffer.rewind();
return this;
}
public final int remaining() {
v8.checkThread();
checkReleased();
return byteBuffer.remaining();
}
public final boolean hasRemaining() {
v8.checkThread();
checkReleased();
return byteBuffer.hasRemaining();
}
public boolean isReadOnly() {
v8.checkThread();
checkReleased();
return byteBuffer.isReadOnly();
}
public byte get() {
v8.checkThread();
checkReleased();
return byteBuffer.get();
}
public V8ArrayBuffer put(final byte b) {
v8.checkThread();
checkReleased();
byteBuffer.put(b);
return this;
}
public byte get(final int index) {
v8.checkThread();
checkReleased();
return byteBuffer.get(index);
}
public V8ArrayBuffer put(final int index, final byte b) {
v8.checkThread();
checkReleased();
byteBuffer.put(index, b);
return this;
}
public V8ArrayBuffer get(final byte[] dst, final int offset, final int length) {
v8.checkThread();
checkReleased();
byteBuffer.get(dst, offset, length);
return this;
}
public V8ArrayBuffer get(final byte[] dst) {
v8.checkThread();
checkReleased();
byteBuffer.get(dst);
return this;
}
public V8ArrayBuffer put(final ByteBuffer src) {
v8.checkThread();
checkReleased();
byteBuffer.put(src);
return this;
}
public V8ArrayBuffer put(final byte[] src, final int offset, final int length) {
v8.checkThread();
checkReleased();
byteBuffer.put(src, offset, length);
return this;
}
public final V8ArrayBuffer put(final byte[] src) {
v8.checkThread();
checkReleased();
byteBuffer.put(src);
return this;
}
public final boolean hasArray() {
v8.checkThread();
checkReleased();
return byteBuffer.hasArray();
}
public final byte[] array() {
v8.checkThread();
checkReleased();
return byteBuffer.array();
}
public final int arrayOffset() {
v8.checkThread();
checkReleased();
return byteBuffer.arrayOffset();
}
public V8ArrayBuffer compact() {
v8.checkThread();
checkReleased();
byteBuffer.compact();
return this;
}
public boolean isDirect() {
v8.checkThread();
checkReleased();
return byteBuffer.isDirect();
}
public final ByteOrder order() {
v8.checkThread();
checkReleased();
return byteBuffer.order();
}
public final V8ArrayBuffer order(final ByteOrder bo) {
v8.checkThread();
checkReleased();
byteBuffer.order(bo);
return this;
}
public char getChar() {
v8.checkThread();
checkReleased();
return byteBuffer.getChar();
}
public V8ArrayBuffer putChar(final char value) {
v8.checkThread();
checkReleased();
byteBuffer.putChar(value);
return this;
}
public char getChar(final int index) {
v8.checkThread();
checkReleased();
return byteBuffer.getChar(index);
}
public V8ArrayBuffer putChar(final int index, final char value) {
v8.checkThread();
checkReleased();
byteBuffer.putChar(index, value);
return this;
}
public short getShort() {
v8.checkThread();
checkReleased();
return byteBuffer.getShort();
}
public V8ArrayBuffer putShort(final short value) {
v8.checkThread();
checkReleased();
byteBuffer.putShort(value);
return this;
}
public short getShort(final int index) {
v8.checkThread();
checkReleased();
return byteBuffer.getShort(index);
}
public V8ArrayBuffer putShort(final int index, final short value) {
v8.checkThread();
checkReleased();
byteBuffer.putShort(index, value);
return this;
}
public int getInt() {
v8.checkThread();
checkReleased();
return byteBuffer.getInt();
}
public V8ArrayBuffer putInt(final int value) {
v8.checkThread();
checkReleased();
byteBuffer.putInt(value);
return this;
}
public int getInt(final int index) {
v8.checkThread();
checkReleased();
return byteBuffer.getInt(index);
}
public V8ArrayBuffer putInt(final int index, final int value) {
v8.checkThread();
checkReleased();
byteBuffer.asIntBuffer().put(index, value);
return this;
}
public long getLong() {
v8.checkThread();
checkReleased();
return byteBuffer.getLong();
}
public V8ArrayBuffer putLong(final long value) {
v8.checkThread();
checkReleased();
byteBuffer.putLong(value);
return this;
}
public long getLong(final int index) {
v8.checkThread();
checkReleased();
return byteBuffer.getLong(index);
}
public V8ArrayBuffer putLong(final int index, final long value) {
v8.checkThread();
checkReleased();
byteBuffer.putLong(index, value);
return this;
}
public float getFloat() {
v8.checkThread();
checkReleased();
return byteBuffer.getFloat();
}
public V8ArrayBuffer putFloat(final float value) {
v8.checkThread();
checkReleased();
byteBuffer.putFloat(value);
return this;
}
public float getFloat(final int index) {
v8.checkThread();
checkReleased();
return byteBuffer.getFloat(index);
}
public V8ArrayBuffer putFloat(final int index, final float value) {
v8.checkThread();
checkReleased();
byteBuffer.putFloat(index, value);
return this;
}
public double getDouble() {
v8.checkThread();
checkReleased();
return byteBuffer.getDouble();
}
public V8ArrayBuffer putDouble(final double value) {
v8.checkThread();
checkReleased();
byteBuffer.putDouble(value);
return this;
}
public double getDouble(final int index) {
v8.checkThread();
checkReleased();
return byteBuffer.getDouble(index);
}
public V8ArrayBuffer putDouble(final int index, final double value) {
v8.checkThread();
checkReleased();
byteBuffer.putDouble(index, value);
return this;
}
public int floatLimit() {
v8.checkThread();
checkReleased();
return byteBuffer.asFloatBuffer().limit();
}
public int intLimit() {
v8.checkThread();
checkReleased();
return byteBuffer.asIntBuffer().limit();
}
public int shortLimit() {
v8.checkThread();
checkReleased();
return byteBuffer.asShortBuffer().limit();
}
public int doubleLimit() {
v8.checkThread();
checkReleased();
return byteBuffer.asDoubleBuffer().limit();
}
}
| 4,912 |
997 | #ifndef PQCLEAN_SNTRUP857_CLEAN_CRYPTO_ENCODE_INT16_H
#define PQCLEAN_SNTRUP857_CLEAN_CRYPTO_ENCODE_INT16_H
#include <stdint.h>
#define PQCLEAN_SNTRUP857_CLEAN_crypto_encode_int16_STRBYTES 2
#define PQCLEAN_SNTRUP857_CLEAN_crypto_encode_int16_ITEMS 1
#define PQCLEAN_SNTRUP857_CLEAN_crypto_encode_int16_ITEMBYTES 2
void PQCLEAN_SNTRUP857_CLEAN_crypto_encode_int16(unsigned char *s, const void *x);
#endif
| 199 |
478 | <filename>source/uwp/Renderer/lib/AdaptiveShowCardActionRenderer.h
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "AdaptiveShowCardActionRenderer.g.h"
namespace winrt::AdaptiveCards::Rendering::Uwp::implementation
{
struct AdaptiveShowCardActionRenderer : AdaptiveShowCardActionRendererT<AdaptiveShowCardActionRenderer>
{
public:
winrt::UIElement Render(winrt::IAdaptiveActionElement const& action,
winrt::AdaptiveRenderContext const& renderContext,
winrt::AdaptiveRenderArgs const& renderArgs);
static winrt::UIElement BuildShowCard(winrt::AdaptiveCard const& showCard,
winrt::AdaptiveRenderContext const& renderContext,
winrt::AdaptiveRenderArgs const& renderArgs,
bool isBottomActionBar);
};
}
namespace winrt::AdaptiveCards::Rendering::Uwp::factory_implementation
{
struct AdaptiveShowCardActionRenderer
: AdaptiveShowCardActionRendererT<AdaptiveShowCardActionRenderer, implementation::AdaptiveShowCardActionRenderer>
{
};
}
| 643 |
308 | # -*- coding: utf-8 -*-
from hamcrest import *
from test.base import BaseTestCase
from amplify.agent.common.context import context
from amplify.agent.objects.plus.api import NginxApiHttpCacheObject
__author__ = "<NAME>"
__copyright__ = "Copyright (C) Nginx, Inc. All rights reserved."
__license__ = ""
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
class ApiHttpCacheCollectorTestCase(BaseTestCase):
def setup_method(self, method):
super(ApiHttpCacheCollectorTestCase, self).setup_method(method)
context.plus_cache = None
context._setup_plus_cache()
def test_gather_data(self):
cache_obj = NginxApiHttpCacheObject(local_name='http_cache', parent_local_id='nginx123', root_uuid='root123')
# Do a quick override of api_internal_url_cache
cache_obj.api_internal_url_cache = 'test_api'
# Get the cache collector
cache_collector = cache_obj.collectors[-1]
# Insert some dummy data
context.plus_cache.put('test_api', (
{
"http" : {
"caches": {
"http_cache": {
"size": 537366528,
"max_size": 536870912,
"cold": False,
"hit": {
"responses": 2096882,
"bytes": 43493401813
},
"stale": {
"responses": 0,
"bytes": 0
},
"updating": {
"responses": 0,
"bytes": 0
},
"revalidated": {
"responses": 0,
"bytes": 0
},
"miss": {
"responses": 15080961,
"bytes": 639387777964,
"responses_written": 11228030,
"bytes_written": 489040611577
},
"expired": {
"responses": 394972,
"bytes": 14639556342,
"responses_written": 384090,
"bytes_written": 14576578947
},
"bypass": {
"responses": 1324001,
"bytes": 14290938437,
"responses_written": 1323861,
"bytes_written": 14290863815
}
}
}
}
},
1
))
data = cache_collector.gather_data()
assert_that(data, not_(equal_to([])))
assert_that(data, has_length(1))
def test_collect(self):
cache_obj = NginxApiHttpCacheObject(local_name='http_cache', parent_local_id='nginx123', root_uuid='root123')
# Do a quick override of api_internal_url_cache
cache_obj.api_internal_url_cache = 'test_api'
# Get the cache collector
cache_collector = cache_obj.collectors[-1]
assert_that(cache_collector.last_collect, equal_to(None))
# Insert some dummy data
context.plus_cache.put('test_api', (
{
"http" : {
"caches": {
"http_cache": {
"size": 0,
"max_size": 0,
"cold": False,
"hit": {
"responses": 0,
"bytes": 0
},
"stale": {
"responses": 0,
"bytes": 0
},
"updating": {
"responses": 0,
"bytes": 0
},
"revalidated": {
"responses": 0,
"bytes": 0
},
"miss": {
"responses": 0,
"bytes": 0,
"responses_written": 0,
"bytes_written": 0
},
"expired": {
"responses": 0,
"bytes": 0,
"responses_written": 0,
"bytes_written": 0
},
"bypass": {
"responses": 0,
"bytes": 0,
"responses_written": 0,
"bytes_written": 0
}
}
}
}
},
1
))
context.plus_cache.put('test_api', (
{
"http" : {
"caches": {
"http_cache": {
"size": 434008064,
"max_size": 536870912,
"cold": False,
"hit": {
"responses": 54893,
"bytes": 641803539
},
"stale": {
"responses": 0,
"bytes": 0
},
"updating": {
"responses": 0,
"bytes": 0
},
"revalidated": {
"responses": 0,
"bytes": 0
},
"miss": {
"responses": 192066,
"bytes": 8238562837,
"responses_written": 113330,
"bytes_written": 3495778334
},
"expired": {
"responses": 14182,
"bytes": 470184322,
"responses_written": 12213,
"bytes_written": 452070350
},
"bypass": {
"responses": 88963,
"bytes": 674403658,
"responses_written": 88962,
"bytes_written": 674402934
}
}
}
}
},
2
))
cache_collector.collect()
assert_that(cache_collector.last_collect, equal_to(2))
assert_that(cache_obj.statsd.current, not_(has_length(0)))
assert_that(cache_obj.statsd.current, has_key('counter'))
counters = cache_obj.statsd.current['counter']
for key in (
'plus.cache.revalidated.bytes',
'plus.cache.expired',
'plus.cache.updating.bytes',
'plus.cache.miss',
'plus.cache.bypass.bytes',
'plus.cache.revalidated',
'plus.cache.updating',
'plus.cache.hit.bytes',
'plus.cache.stale',
'plus.cache.stale.bytes',
'plus.cache.hit',
'plus.cache.expired.bytes',
'plus.cache.bypass',
'plus.cache.miss.bytes'
):
assert_that(counters, has_key(key))
assert_that(counters['plus.cache.hit'][0], equal_to([2, 54893]))
assert_that(counters['plus.cache.hit.bytes'][0], equal_to([2, 641803539]))
assert_that(cache_obj.statsd.current, has_key('gauge'))
guages = cache_obj.statsd.current['gauge']
for key in (
'plus.cache.size',
'plus.cache.max_size',
):
assert_that(guages, has_key(key))
assert_that(guages['plus.cache.size'][0], equal_to((1, 0)))
assert_that(guages['plus.cache.max_size'][0], equal_to((1, 0)))
assert_that(guages['plus.cache.size'][1], equal_to((2, 434008064)))
assert_that(guages['plus.cache.max_size'][1], equal_to((2, 536870912)))
def test_missing_max_size(self):
cache_obj = NginxApiHttpCacheObject(local_name='http_cache', parent_local_id='nginx123', root_uuid='root123')
# Do a quick override of api_internal_url_cache
cache_obj.api_internal_url_cache = 'test_api'
# Get the cache collector
cache_collector = cache_obj.collectors[-1]
assert_that(cache_collector.last_collect, equal_to(None))
# Insert some dummy data
context.plus_cache.put('test_api', (
{
"http": {
"caches": {
"http_cache": {
"size": 0,
"cold": False,
"hit": {
"responses": 0,
"bytes": 0
},
"stale": {
"responses": 0,
"bytes": 0
},
"updating": {
"responses": 0,
"bytes": 0
},
"revalidated": {
"responses": 0,
"bytes": 0
},
"miss": {
"responses": 0,
"bytes": 0,
"responses_written": 0,
"bytes_written": 0
},
"expired": {
"responses": 0,
"bytes": 0,
"responses_written": 0,
"bytes_written": 0
},
"bypass": {
"responses": 0,
"bytes": 0,
"responses_written": 0,
"bytes_written": 0
}
}
}
}
},
1
))
cache_collector.collect()
assert_that(cache_collector.last_collect, equal_to(1))
assert_that(cache_obj.statsd.current, not_(has_length(0)))
assert_that(cache_obj.statsd.current, has_key('gauge'))
guages = cache_obj.statsd.current['gauge']
assert_that(guages, has_key('plus.cache.size'))
assert_that(guages, is_not(has_key('plus.cache.max_size')))
| 7,829 |
369 | <gh_stars>100-1000
// Copyright (c) 2017-2022, Mudita <NAME>.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "RT1051DriverSAI.hpp"
#include "bsp/BoardDefinitions.hpp"
#include "../fsl_drivers/fsl_sai_edma.h"
namespace drivers
{
using namespace magic_enum;
sai_edma_handle_t RT1051DriverSAI::txHandle[magic_enum::enum_count<SAIInstances>()] = {};
sai_edma_handle_t RT1051DriverSAI::rxHandle[magic_enum::enum_count<SAIInstances>()] = {};
RT1051DriverSAI::RT1051DriverSAI(const drivers::SAIInstances &inst, const drivers::DriverSAIParams ¶ms)
: DriverSAI(params)
{
switch (instances) {
case SAIInstances::SAI_1:
rxDMASource = kDmaRequestMuxSai1Rx;
txDMASource = kDmaRequestMuxSai1Tx;
base = SAI1;
IOMUXC_GPR->GPR1 |= IOMUXC_GPR_GPR1_SAI1_MCLK_DIR_MASK;
break;
case SAIInstances::SAI_2:
rxDMASource = kDmaRequestMuxSai2Rx;
txDMASource = kDmaRequestMuxSai2Tx;
base = SAI2;
IOMUXC_GPR->GPR1 |= IOMUXC_GPR_GPR1_SAI2_MCLK_DIR_MASK;
break;
case SAIInstances::SAI_3:
rxDMASource = kDmaRequestMuxSai3Rx;
txDMASource = kDmaRequestMuxSai3Tx;
base = SAI3;
IOMUXC_GPR->GPR1 |= IOMUXC_GPR_GPR1_SAI3_MCLK_DIR_MASK;
break;
}
pll = DriverInterface<DriverPLL>::Create(static_cast<PLLInstances>(BoardDefinitions::AUDIO_PLL),
DriverPLLParams{});
dmamux = DriverInterface<DriverDMAMux>::Create(
static_cast<DMAMuxInstances>(BoardDefinitions::AUDIOCODEC_DMAMUX), DriverDMAMuxParams{});
dma = DriverInterface<DriverDMA>::Create(static_cast<DMAInstances>(BoardDefinitions::AUDIOCODEC_DMA),
DriverDMAParams{});
}
RT1051DriverSAI::~RT1051DriverSAI()
{}
int32_t RT1051DriverSAI::StartInTransfer(const drivers::TransferParams &rx)
{
sai_transfer_t xfer = {0};
sai_config_t config;
sai_transfer_format_t sai_format = {0};
rxParams = rx;
dmamux->Enable(parameters.rxDMAChannel, rxDMASource);
dma->CreateHandle(parameters.rxDMAChannel);
// Initialize SAI Rx module
SAI_RxGetDefaultConfig(&config);
config.masterSlave = (parameters.masterslave == DriverSAIParams::MasterSlave::Slave) ? kSAI_Slave : kSAI_Master;
SAI_RxInit(base, &config);
/* Configure the audio format */
sai_format.bitWidth = parameters.bitWidth;
sai_format.channel = 0U;
sai_format.sampleRate_Hz = parameters.sampleRate;
sai_format.masterClockHz = parameters.masterClock;
sai_format.isFrameSyncCompact = false;
sai_format.protocol = static_cast<sai_protocol_t>(parameters.protocol);
sai_format.stereo = static_cast<sai_mono_stereo_t>(parameters.monostereo);
#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1)
sai_format.watermark = FSL_FEATURE_SAI_FIFO_COUNT / 2U;
#endif
SAI_TransferRxCreateHandleEDMA(base,
&rxHandle[enum_integer(instances)],
rxAudioCallback,
this,
reinterpret_cast<edma_handle_t *>(dma->GetHandle(parameters.rxDMAChannel)));
SAI_TransferRxSetFormatEDMA(
base, &rxHandle[enum_integer(instances)], &sai_format, parameters.masterClock, parameters.masterClock);
/* Reset SAI Rx internal logic */
SAI_RxSoftwareReset(base, kSAI_ResetTypeSoftware);
xfer.data = rx.data;
xfer.dataSize = rx.size;
SAI_TransferReceiveEDMA(base, &rxHandle[enum_integer(instances)], &xfer);
}
int32_t RT1051DriverSAI::StopInTransfer()
{
SAI_RxDisableInterrupts(base, kSAI_FIFOErrorInterruptEnable);
if (rxHandle[enum_integer(instances)].dmaHandle) {
SAI_TransferAbortReceiveEDMA(base, &rxHandle[enum_integer(instances)]);
memset(&rxHandle[enum_integer(instances)], 0, sizeof(sai_edma_handle_t));
}
}
int32_t RT1051DriverSAI::StartOutTransfer(const drivers::TransferParams &tx)
{
sai_transfer_t xfer = {0};
sai_config_t config;
sai_transfer_format_t sai_format = {0};
txParams = tx;
dmamux->Enable(parameters.txDMAChannel, txDMASource);
dma->CreateHandle(parameters.txDMAChannel);
// Initialize SAI Tx module
SAI_TxGetDefaultConfig(&config);
config.masterSlave = (parameters.masterslave == DriverSAIParams::MasterSlave::Slave) ? kSAI_Slave : kSAI_Master;
SAI_TxInit(base, &config);
/* Configure the audio format */
sai_format.bitWidth = parameters.bitWidth;
sai_format.channel = 0U;
sai_format.sampleRate_Hz = parameters.sampleRate;
sai_format.masterClockHz = parameters.masterClock;
sai_format.isFrameSyncCompact = false;
sai_format.protocol = static_cast<sai_protocol_t>(parameters.protocol);
sai_format.stereo = static_cast<sai_mono_stereo_t>(parameters.monostereo);
#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1)
sai_format.watermark = FSL_FEATURE_SAI_FIFO_COUNT / 2U;
#endif
SAI_TransferTxCreateHandleEDMA(base,
&txHandle[enum_integer(instances)],
txAudioCallback,
this,
reinterpret_cast<edma_handle_t *>(dma->GetHandle(parameters.txDMAChannel)));
SAI_TransferTxSetFormatEDMA(
base, &txHandle[enum_integer(instances)], &sai_format, parameters.masterClock, parameters.masterClock);
/* Reset SAI Tx internal logic */
SAI_TxSoftwareReset(base, kSAI_ResetTypeSoftware);
xfer.data = tx.data;
xfer.dataSize = tx.size;
SAI_TransferSendEDMA(base, &txHandle[enum_integer(instances)], &xfer);
}
int32_t RT1051DriverSAI::StopOutTransfer()
{
SAI_TxDisableInterrupts(base, kSAI_FIFOErrorInterruptEnable);
if (txHandle[enum_integer(instances)].dmaHandle) {
SAI_TransferTerminateSendEDMA(base, &txHandle[enum_integer(instances)]);
memset(&txHandle[enum_integer(instances)], 0, sizeof(sai_edma_handle_t));
}
}
int32_t RT1051DriverSAI::SetOutTransferEndCallback(std::function<int32_t()> callback)
{
txTransferEndCallback = callback;
}
int32_t RT1051DriverSAI::SetInTransferEndCallback(std::function<int32_t()> callback)
{
rxTransferEndCallback = callback;
}
void txAudioCallback(I2S_Type *base, sai_edma_handle_t *handle, status_t status, void *userData)
{
sai_transfer_t xfer = {0};
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
RT1051DriverSAI *inst = (RT1051DriverSAI *)userData;
if (inst->txTransferState == RT1051DriverSAI::TransferState::HalfTransfer) {
xfer.dataSize = inst->txParams.size;
xfer.data = inst->txParams.data + (inst->txParams.size);
SAI_TransferSendEDMA(base, &inst->txHandle[enum_integer(inst->instances)], &xfer);
inst->txTransferEndCallback();
inst->txTransferState = RT1051DriverSAI::TransferState::FullTransfer;
}
else {
xfer.dataSize = inst->txParams.size;
xfer.data = inst->txParams.data;
SAI_TransferSendEDMA(base, &inst->txHandle[enum_integer(inst->instances)], &xfer);
inst->txTransferEndCallback();
inst->txTransferState = RT1051DriverSAI::TransferState::HalfTransfer;
}
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}
void rxAudioCallback(I2S_Type *base, sai_edma_handle_t *handle, status_t status, void *userData)
{
sai_transfer_t xfer = {0};
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
RT1051DriverSAI *inst = (RT1051DriverSAI *)userData;
if (inst->txTransferState == RT1051DriverSAI::TransferState::HalfTransfer) {
xfer.dataSize = inst->txParams.size;
xfer.data = inst->txParams.data + (inst->txParams.size);
SAI_TransferReceiveEDMA(base, &inst->txHandle[enum_integer(inst->instances)], &xfer);
inst->txTransferEndCallback();
inst->txTransferState = RT1051DriverSAI::TransferState::FullTransfer;
}
else {
xfer.dataSize = inst->txParams.size;
xfer.data = inst->txParams.data;
SAI_TransferReceiveEDMA(base, &inst->txHandle[enum_integer(inst->instances)], &xfer);
inst->txTransferEndCallback();
inst->txTransferState = RT1051DriverSAI::TransferState::HalfTransfer;
}
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}
} // namespace drivers | 4,608 |
742 | <gh_stars>100-1000
#ifndef BODY_ARMOR_ARTIFACT_DATA_H
#define BODY_ARMOR_ARTIFACT_DATA_H
#include <memory>
#include <vector>
#include "ArmorArtifactData.h"
class ArmorMaterial;
enum class ArmorType;
enum class BodyPartName;
class BodyArmorArtifactData : public ArmorArtifactData
{
private:
std::unique_ptr<ArmorMaterial> armorMaterial;
BodyPartName partName;
public:
BodyArmorArtifactData(const std::string &displayName,
const std::string &flavorText, const std::vector<int> &provinceIDs,
const ArmorMaterial *armorMaterial, BodyPartName partName);
virtual ~BodyArmorArtifactData() = default;
virtual std::unique_ptr<ArtifactData> clone() const override;
BodyPartName getBodyPartName() const;
const ArmorMaterial *getArmorMaterial() const;
// The armor type is found by using the body part name.
virtual ArmorType getArmorType() const override;
};
#endif
| 311 |
360 | <filename>contrib/pgrowlocks/pgrowlocks.cpp
/*
* contrib/pgrowlocks/pgrowlocks.c
*
* Copyright (c) 2005-2006 <NAME>
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose, without fee, and without a
* written agreement is hereby granted, provided that the above
* copyright notice and this paragraph and the following two
* paragraphs appear in all copies.
*
* IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
* LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
* DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS
* IS" BASIS, AND THE AUTHOR HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE,
* SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include "postgres.h"
#include "knl/knl_variable.h"
#include "access/multixact.h"
#include "access/relscan.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "storage/buf/bufmgr.h"
#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/rel.h"
#include "utils/rel_gs.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(pgrowlocks);
extern Datum pgrowlocks(PG_FUNCTION_ARGS);
/* ----------
* pgrowlocks:
* returns tids of rows being locked
* ----------
*/
#define NCHARS 32
typedef struct {
Relation rel;
HeapScanDesc scan;
int ncolumns;
} MyData;
Datum pgrowlocks(PG_FUNCTION_ARGS)
{
FuncCallContext* funcctx = NULL;
HeapScanDesc scan;
HeapTuple tuple;
TupleDesc tupdesc;
AttInMetadata* attinmeta = NULL;
Datum result;
MyData* mydata = NULL;
Relation rel;
if (SRF_IS_FIRSTCALL()) {
text* relname = NULL;
RangeVar* relrv = NULL;
MemoryContext oldcontext;
AclResult aclresult;
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* Build a tuple descriptor for our result type */
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
elog(ERROR, "return type must be a row type");
attinmeta = TupleDescGetAttInMetadata(tupdesc);
funcctx->attinmeta = attinmeta;
relname = PG_GETARG_TEXT_P(0);
relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
rel = heap_openrv(relrv, AccessShareLock);
/* check permissions: must have SELECT on table */
aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(), ACL_SELECT);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_CLASS, RelationGetRelationName(rel));
scan = (HeapScanDesc)heap_beginscan(rel, SnapshotNow, 0, NULL);
mydata = (MyData*)palloc(sizeof(*mydata));
mydata->rel = rel;
mydata->scan = scan;
mydata->ncolumns = tupdesc->natts;
funcctx->user_fctx = mydata;
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
attinmeta = funcctx->attinmeta;
mydata = (MyData*)funcctx->user_fctx;
scan = mydata->scan;
/* scan the relation */
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL) {
/* must hold a buffer lock to call HeapTupleSatisfiesUpdate */
LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
if (HeapTupleSatisfiesUpdate(tuple->t_data, GetCurrentCommandId(false), scan->rs_cbuf) ==
HeapTupleBeingUpdated) {
char** values;
int i;
values = (char**)palloc(mydata->ncolumns * sizeof(char*));
i = 0;
values[i++] = (char*)DirectFunctionCall1(tidout, PointerGetDatum(&tuple->t_self));
if (tuple->t_data->t_infomask & HEAP_XMAX_SHARED_LOCK)
values[i++] = pstrdup("Shared");
else
values[i++] = pstrdup("Exclusive");
values[i] = (char*)palloc(NCHARS * sizeof(char));
snprintf(values[i++], NCHARS, XID_FMT, HeapTupleGetRawXmax(tuple));
if (tuple->t_data->t_infomask & HEAP_XMAX_IS_MULTI) {
TransactionId* xids = NULL;
int nxids;
int j;
int isValidXid = 0; /* any valid xid ever exists? */
values[i++] = pstrdup("true");
nxids = GetMultiXactIdMembers(HeapTupleGetRawXmax(tuple), &xids);
if (nxids == -1) {
elog(ERROR, "GetMultiXactIdMembers returns error");
}
values[i] = (char*)palloc(NCHARS * nxids);
values[i + 1] = (char*)palloc(NCHARS * nxids);
strcpy(values[i], "{");
strcpy(values[i + 1], "{");
for (j = 0; j < nxids; j++) {
char buf[NCHARS];
if (TransactionIdIsInProgress(xids[j])) {
if (isValidXid) {
strcat(values[i], ",");
strcat(values[i + 1], ",");
}
snprintf(buf, NCHARS, XID_FMT, xids[j]);
strcat(values[i], buf);
snprintf(buf, NCHARS, XID_FMT, BackendXidGetPid(xids[j]));
strcat(values[i + 1], buf);
isValidXid = 1;
}
}
strcat(values[i], "}");
strcat(values[i + 1], "}");
i++;
} else {
values[i++] = pstrdup("false");
values[i] = (char*)palloc(NCHARS * sizeof(char));
snprintf(values[i++], NCHARS, "{" XID_FMT "}", HeapTupleGetRawXmax(tuple));
values[i] = (char*)palloc(NCHARS * sizeof(char));
snprintf(values[i++], NCHARS, "{%d}", BackendXidGetPid(HeapTupleGetRawXmax(tuple)));
}
LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
/* build a tuple */
tuple = BuildTupleFromCStrings(attinmeta, values);
/* make the tuple into a datum */
result = HeapTupleGetDatum(tuple);
/* Clean up */
for (i = 0; i < mydata->ncolumns; i++)
pfree(values[i]);
pfree(values);
SRF_RETURN_NEXT(funcctx, result);
} else {
LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
}
}
heap_endscan(scan);
heap_close(mydata->rel, AccessShareLock);
SRF_RETURN_DONE(funcctx);
}
| 3,315 |
772 | package com.sksamuel.scrimage.webp;
import org.apache.commons.lang3.SystemUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
abstract class WebpHandler {
protected static Path createPlaceholder(String name) throws IOException {
return Files.createTempFile(name, "binary");
}
protected static void installBinary(Path output, String... sources) throws IOException {
for (String source : sources) {
InputStream in = WebpHandler.class.getResourceAsStream(source);
if (in != null) {
Files.copy(in, output, StandardCopyOption.REPLACE_EXISTING);
in.close();
if(!SystemUtils.IS_OS_WINDOWS) {
setExecutable(output);
}
return;
}
}
throw new IOException("Could not locate webp binary at " + Arrays.toString(sources));
}
protected static String[] getBinaryPath(String binaryName) {
String os = "linux";
if(SystemUtils.IS_OS_WINDOWS) {
os = "window";
} else if(SystemUtils.IS_OS_MAC) {
os = "mac";
}
return new String[] {
"/webp_binaries/" + binaryName,
"/webp_binaries/" + os + "/" + binaryName,
"/dist_webp_binaries/" + os + "/" + binaryName,
};
}
private static boolean setExecutable(Path output) throws IOException {
try {
return new ProcessBuilder("chmod", "+x", output.toAbsolutePath().toString())
.start()
.waitFor(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new IOException(e);
}
}
}
| 752 |
5,316 | package com.airbnb.aerosolve.core.transforms;
import com.airbnb.aerosolve.core.transforms.types.StringTransform;
import java.text.Normalizer;
import com.typesafe.config.Config;
/**
* Normalizes strings to UTF-8 NFC, NFD, NFKC or NFKD form (NFD by default)
* "field1" specifies the key of the feature
* "normalization_form" optionally specifies whether to use NFC, NFD, NFKC or NFKD form
* "output" optionally specifies the key of the output feature, if it is not given the transform
* overwrites / replaces the input feature
*/
public class NormalizeUtf8Transform extends StringTransform {
public static final Normalizer.Form DEFAULT_NORMALIZATION_FORM = Normalizer.Form.NFD;
private Normalizer.Form normalizationForm;
@Override
public void init(Config config, String key) {
String normalizationFormString = DEFAULT_NORMALIZATION_FORM.name();
if (config.hasPath(key + ".normalization_form")) {
normalizationFormString = config.getString(key + ".normalization_form");
}
if (normalizationFormString.equalsIgnoreCase("NFC")) {
normalizationForm = Normalizer.Form.NFC;
} else if (normalizationFormString.equalsIgnoreCase("NFD")) {
normalizationForm = Normalizer.Form.NFD;
} else if (normalizationFormString.equalsIgnoreCase("NFKC")) {
normalizationForm = Normalizer.Form.NFKC;
} else if (normalizationFormString.equalsIgnoreCase("NFKD")) {
normalizationForm = Normalizer.Form.NFKD;
} else {
normalizationForm = DEFAULT_NORMALIZATION_FORM;
}
}
@Override
public String processString(String rawString) {
if (rawString == null) {
return null;
}
return Normalizer.normalize(rawString, normalizationForm);
}
}
| 564 |
435 | <filename>pycon-thailand-2018/videos/teaching-and-learning-with-python.json
{
"copyright_text": "Creative Commons Attribution license (reuse allowed)",
"description": "This talk will feature discussions of how Python can be used to teach principles of computer science but it isn't limited to educators. Learning about learning is an increasingly important skill in today's world of rapidly evolving technology. I will share my experience teaching computer science and computer programming starting with being a part of the team that changed my university's Intro to Programming course from using C++ to Python. Then, I'll share tools I've used to engage students in Python programming including repl.it and Raspberry Pi and run through some of the lessons I've taught with them. I'll also discuss education best practices and how learners can apply them to their own self-education.\n\n\n\n--------\n\nI'm an educator with a background in computer science. I've worked as a firmware engineer at a large corporation and as a software developer at a small firm and taught at innovative high schools teaching mathematics and CS. I'm currently teaching at an international school in Bangkok. I am part Thai but born and raised in America in the state of Kentucky.",
"duration": 2098,
"language": "eng",
"recorded": "2018-06-16",
"related_urls": [
{
"label": "Conference schedule",
"url": "https://th.pycon.org/en/schedule/"
}
],
"speakers": [
"<NAME>"
],
"tags": [],
"thumbnail_url": "https://i.ytimg.com/vi/9-Bf3YAwedg/maxresdefault.jpg",
"title": "Teaching and Learning with Python",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=9-Bf3YAwedg"
}
]
}
| 491 |
2,151 | <filename>components/offline_pages/core/prefetch/prefetch_configuration.cc
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/offline_pages/core/prefetch/prefetch_configuration.h"
#include "components/offline_pages/core/offline_page_feature.h"
namespace offline_pages {
bool PrefetchConfiguration::IsPrefetchingEnabled() {
return IsPrefetchingOfflinePagesEnabled() && IsPrefetchingEnabledBySettings();
}
} // namespace offline_pages
| 172 |
3,269 | <reponame>Priyansh2/LeetCode-Solutions
// Time: O(|V| + |E|) = O(|E|) since graph is connected, O(|E|) >= O(|V|)
// Space: O(|V| + |E|) = O(|E|)
class Solution {
public:
int secondMinimum(int n, vector<vector<int>>& edges, int time, int change) {
vector<vector<int>> adj(n);
for (const auto& edge : edges) {
adj[edge[0] - 1].emplace_back(edge[1] - 1);
adj[edge[1] - 1].emplace_back(edge[0] - 1);
}
return calc_time(time, change, bi_bfs(adj, 0, n - 1));
}
private:
// Template:
// https://github.com/kamyu104/LeetCode-Solutions/blob/master/C++/nearest-exit-from-entrance-in-maze.cpp
int bi_bfs(const vector<vector<int>>& adj, int start, int end) {
unordered_set<int> left = {start}, right = {end}, lookup;
int result = 0, steps = 0;
while (!empty(left) && (!result || result + 2 > steps)) { // modified
for (const auto& u : left) {
lookup.emplace(u);
}
unordered_set<int> new_left;
for (const auto& u : left) {
if (right.count(u)) {
if (!result) { // modified
result = steps;
} else if (result < steps) { // modified
return result + 1;
}
}
for (const auto& v : adj[u]) {
if (lookup.count(v)) {
continue;
}
new_left.emplace(v);
}
}
left = move(new_left);
++steps;
if (size(left) > size(right)) {
swap(left, right);
}
}
return result + 2; // modified
}
int calc_time(int time, int change, int dist) {
int result = 0;
while (dist--) {
if (result / change % 2) {
result = (result / change + 1) * change;
}
result += time;
}
return result;
}
};
// Time: O(|V| + |E|) = O(|E|) since graph is connected, O(|E|) >= O(|V|)
// Space: O(|V| + |E|) = O(|E|)
class Solution2 {
public:
int secondMinimum(int n, vector<vector<int>>& edges, int time, int change) {
vector<vector<int>> adj(n);
for (const auto& edge : edges) {
adj[edge[0] - 1].emplace_back(edge[1] - 1);
adj[edge[1] - 1].emplace_back(edge[0] - 1);
}
const auto& dist_to_end = bfs(adj, 0);
const auto& dist_to_start = bfs(adj, n - 1);
int dist = dist_to_end[n - 1] + 2; // always exists
for (int i = 0; i < n; ++i) {
if (dist_to_end[i] + dist_to_start[i] == dist_to_end[n - 1]) {
continue;
}
dist = min(dist, dist_to_end[i] + dist_to_start[i]); // find second min
if (dist == dist_to_end[n - 1] + 1) {
break;
}
}
return calc_time(time, change, dist);
}
private:
vector<int> bfs(const vector<vector<int>>& adj, int start) {
static const int INF = numeric_limits<int>::max();
vector<int> q = {start};
vector<int> dist(size(adj), INF);
dist[start] = 0;
while (!empty(q)) {
vector<int> new_q;
for (const auto& u : q) {
for (const auto& v: adj[u]) {
if (dist[v] != INF) {
continue;
}
dist[v] = dist[u] + 1;
new_q.emplace_back(v);
}
}
q = move(new_q);
}
return dist;
}
int calc_time(int time, int change, int dist) {
int result = 0;
while (dist--) {
if (result / change % 2) {
result = (result / change + 1) * change;
}
result += time;
}
return result;
}
};
| 2,211 |
5,169 | {
"name": "Classes",
"version": "0.0.1",
"summary": "A short description of Classes.",
"description": "私有Pods测试\n* Markdown 格式",
"homepage": "http://EXAMPLE/Classes",
"license": "MIT",
"authors": {
"fangyuan2902": ""
},
"source": {
"git": "https://github.com/fangyuan2902/StringUtil.git"
},
"source_files": [
"Classes",
"Classes/*.{h,m}"
],
"exclude_files": "Classes/Exclude",
"requires_arc": true,
"platforms": {
"osx": null,
"ios": null,
"tvos": null,
"watchos": null
}
}
| 252 |
4,054 | <filename>readthedocs/integrations/migrations/0008_add_new_jsonfields.py<gh_stars>1000+
# Generated by Django 3.2.11 on 2022-01-31 11:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('integrations', '0007_update-provider-data'),
]
operations = [
migrations.AddField(
model_name='httpexchange',
name='request_headers_json',
field=models.JSONField(null=True, blank=True, verbose_name='Request headers'),
),
migrations.AddField(
model_name='httpexchange',
name='response_headers_json',
field=models.JSONField(null=True, blank=True, verbose_name='Request headers'),
),
migrations.AddField(
model_name='integration',
name='provider_data_json',
field=models.JSONField(null=True, blank=True, verbose_name='Provider data'),
),
]
| 420 |
488 | // t0055.cc
// member initializer where member is a templatized base class
template <class T>
class A {
public:
int f();
A(T t);
int g();
};
class B : A<int> {
public:
B() : A<int>(5) {}
};
// variant using an explicit specialization
template <>
class A<float> {};
struct D : A<float> {
D() : A<float>() {}
void f()
{
A<float> a;
}
};
| 152 |
381 | <reponame>wasauce/depthai-experiments
import cv2
import numpy as np
import depthai as dai
from time import sleep
'''
Basic demo of gen2 pipeline builder functionality where output of jpeg encoded images are sent out SPI rather than the typical XLink out interface.
Make sure you have something to handle the SPI protocol on the other end! See the included ESP32 example.
'''
def create_spi_demo_pipeline():
print("Creating SPI pipeline: ")
print("COLOR CAM -> ENCODER -> SPI OUT")
pipeline = dai.Pipeline()
cam_color = pipeline.createColorCamera()
spiout_preview = pipeline.createSPIOut()
videnc = pipeline.createVideoEncoder()
# set up color camera and link to NN node
cam_color.setPreviewSize(300, 300);
cam_color.setResolution(dai.ColorCameraProperties.SensorResolution.THE_1080_P);
cam_color.setInterleaved(False);
cam_color.setCamId(0);
cam_color.setColorOrder(dai.ColorCameraProperties.ColorOrder.BGR);
# VideoEncoder
videnc.setDefaultProfilePreset(1920, 1080, 30, dai.VideoEncoderProperties.Profile.MJPEG);
# Link plugins CAM -> ENCODER -> SPI OUT
cam_color.video.link(videnc.input);
spiout_preview.setStreamName("spipreview");
spiout_preview.setBusId(0);
videnc.bitstream.link(spiout_preview.input);
return pipeline
def test_pipeline():
pipeline = create_spi_demo_pipeline()
print("Creating DepthAI device")
if 1:
device = dai.Device(pipeline)
else: # For debug mode, with the firmware already loaded
found, device_info = dai.XLinkConnection.getFirstDevice(
dai.XLinkDeviceState.X_LINK_UNBOOTED)
if found:
device = dai.Device(pipeline, device_info)
else:
raise RuntimeError("Device not found")
print("Starting pipeline")
device.startPipeline()
print("Pipeline is running. See connected SPI device for output!")
while True:
sleep(1)
print("Closing device")
del device
test_pipeline()
| 771 |
560 | <reponame>zhanghai/Douya<gh_stars>100-1000
/*
* Copyright (c) 2018 <NAME> <<EMAIL>>
* All Rights Reserved.
*/
package me.zhanghai.android.douya.glide;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.widget.RemoteViews;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
/**
* @see com.bumptech.glide.request.target.AppWidgetTarget
*/
public class AppWidgetTarget extends SimpleTarget<Bitmap> {
private int viewId;
private RemoteViews remoteViews;
private Context context;
private ComponentName componentName;
private int[] widgetIds;
public AppWidgetTarget(int viewId) {
super(SIZE_ORIGINAL, SIZE_ORIGINAL);
this.viewId = viewId;
}
private void prepare(RemoteViews remoteViews, Context context, ComponentName componentName,
int[] widgetIds) {
this.remoteViews = remoteViews;
this.context = context;
this.componentName = componentName;
this.widgetIds = widgetIds;
}
public AppWidgetTarget prepare(RemoteViews remoteViews, Context context,
ComponentName componentName) {
prepare(remoteViews, context, componentName, null);
return this;
}
public AppWidgetTarget prepare(RemoteViews remoteViews, Context context, int[] widgetIds) {
prepare(remoteViews, context, null, widgetIds);
return this;
}
@Override
public void onResourceReady(@NonNull Bitmap resource,
@Nullable Transition<? super Bitmap> transition) {
remoteViews.setImageViewBitmap(viewId, resource);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
if (componentName != null) {
appWidgetManager.updateAppWidget(componentName, remoteViews);
} else {
appWidgetManager.updateAppWidget(widgetIds, remoteViews);
}
clear();
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
clear();
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
clear();
}
private void clear() {
remoteViews = null;
context = null;
componentName = null;
widgetIds = null;
}
}
| 991 |
713 | <reponame>t-gergely/infinispan
package org.infinispan.cloudevents.configuration;
import java.util.HashMap;
import java.util.Map;
/**
* Attribute.
*
* @author <NAME>
* @since 12
*/
public enum Attribute {
// must be first
UNKNOWN(null),
BOOTSTRAP_SERVERS("bootstrap-servers"),
ACKS("acks"),
AUDIT_TOPIC("audit-topic"),
CACHE_ENTRIES_TOPIC("cache-entries-topic"),
ENABLED("enabled"),
;
private final String name;
private Attribute(final String name) {
this.name = name;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Attribute> attributes;
static {
Map<String, Attribute> map = new HashMap<>();
for (Attribute attribute : values()) {
final String name = attribute.getLocalName();
if (name != null) {
map.put(name, attribute);
}
}
attributes = map;
}
public static Attribute forName(final String localName) {
final Attribute attribute = attributes.get(localName);
return attribute == null ? UNKNOWN : attribute;
}
}
| 459 |
927 | /* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class android_serialport_SerialPort */
#ifndef _Included_android_serialport_SerialPort
#define _Included_android_serialport_SerialPort
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: android_serialport_SerialPort
* Method: open
* Signature: (Ljava/lang/String;IIIII)Ljava/io/FileDescriptor;
*/
JNIEXPORT jobject JNICALL Java_android_serialport_SerialPort_open
(JNIEnv *, jobject, jstring, jint, jint, jint, jint, jint);
/*
* Class: android_serialport_SerialPort
* Method: close
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_android_serialport_SerialPort_close
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
/* Header for class android_serialport_SerialPort_Builder */
#ifndef _Included_android_serialport_SerialPort_Builder
#define _Included_android_serialport_SerialPort_Builder
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
| 356 |
1,338 | /*
* Copyright 2011, <NAME>, <EMAIL>.
* Distributed under the terms of the MIT License.
*/
#include "Query.h"
#include <file_systems/QueryParser.h>
#include "AttributeCookie.h"
#include "Directory.h"
#include "Index.h"
#include "Node.h"
#include "Volume.h"
// #pragma mark - QueryPolicy
struct Query::QueryPolicy {
typedef Query Context;
typedef ::Node Entry;
typedef ::Node Node;
struct Index {
Query* query;
::Index* index;
Index(Context* context)
:
query(context)
{
}
};
struct IndexIterator : ::IndexIterator {
::Index* index;
IndexIterator(::Index* index)
:
index(index)
{
}
};
static const int32 kMaxFileNameLength = B_FILE_NAME_LENGTH;
// Entry interface
static ino_t EntryGetParentID(Entry* entry)
{
return entry->Parent()->ID();
}
static Node* EntryGetNode(Entry* entry)
{
return entry;
}
static ino_t EntryGetNodeID(Entry* entry)
{
return entry->ID();
}
static ssize_t EntryGetName(Entry* entry, void* buffer, size_t bufferSize)
{
const char* name = entry->Name();
size_t nameLength = strlen(name);
if (nameLength >= bufferSize)
return B_BUFFER_OVERFLOW;
memcpy(buffer, name, nameLength + 1);
return nameLength + 1;
}
static const char* EntryGetNameNoCopy(Entry* entry, void* buffer,
size_t bufferSize)
{
return entry->Name();
}
// Index interface
static status_t IndexSetTo(Index& index, const char* attribute)
{
index.index = index.query->fVolume->FindIndex(StringKey(attribute));
return index.index != NULL ? B_OK : B_ENTRY_NOT_FOUND;
}
static void IndexUnset(Index& index)
{
index.index = NULL;
}
static int32 IndexGetWeightedScore(Index& index, int32 score)
{
// should be inversely proportional to the index size; max input score
// is 2048
static const int32 maxFactor = 1024 * 1024;
return score * (maxFactor
/ std::min(maxFactor,
std::max((int32)1, index.index->CountEntries())));
}
static type_code IndexGetType(Index& index)
{
return index.index->Type();
}
static int32 IndexGetKeySize(Index& index)
{
return index.index->KeyLength();
}
static IndexIterator* IndexCreateIterator(Index& index)
{
IndexIterator* iterator = new(std::nothrow) IndexIterator(index.index);
if (iterator == NULL)
return NULL;
if (!index.index->GetIterator(*iterator)) {
delete iterator;
return NULL;
}
return iterator;
}
// IndexIterator interface
static void IndexIteratorDelete(IndexIterator* indexIterator)
{
delete indexIterator;
}
static status_t IndexIteratorFind(IndexIterator* indexIterator,
const void* value, size_t size)
{
if (!indexIterator->index->Find(value, size, *indexIterator))
return B_ENTRY_NOT_FOUND;
return B_OK;
}
static status_t IndexIteratorGetNextEntry(IndexIterator* indexIterator,
void* value, size_t* _valueLength, size_t bufferSize, Entry** _entry)
{
Node* node = indexIterator->Next(value, _valueLength);
if (node == NULL)
return B_ENTRY_NOT_FOUND;
*_entry = node;
return B_OK;
}
static void IndexIteratorSuspend(IndexIterator* indexIterator)
{
indexIterator->Suspend();
}
static void IndexIteratorResume(IndexIterator* indexIterator)
{
indexIterator->Resume();
}
// Node interface
static const off_t NodeGetSize(Node* node)
{
return node->FileSize();
}
static time_t NodeGetLastModifiedTime(Node* node)
{
return node->ModifiedTime().tv_sec;
}
static status_t NodeGetAttribute(Node* node, const char* attribute,
void* buffer, size_t* _size, int32* _type)
{
// TODO: Creating a cookie is quite a bit of overhead.
AttributeCookie* cookie;
status_t error = node->OpenAttribute(StringKey(attribute), O_RDONLY,
cookie);
if (error != B_OK)
return error;
error = cookie->ReadAttribute(0, buffer, _size);
// also get the attribute type
if (error == B_OK) {
struct stat st;
error = cookie->ReadAttributeStat(&st);
if (error == B_OK)
*_type = st.st_type;
}
cookie->Close();
delete cookie;
return error;
}
static Entry* NodeGetFirstReferrer(Node* node)
{
return node;
}
static Entry* NodeGetNextReferrer(Node* node, Entry* entry)
{
return NULL;
}
// Volume interface
static dev_t ContextGetVolumeID(Context* context)
{
return context->fVolume->ID();
}
};
// #pragma mark - Query
Query::Query(Volume* volume)
:
fVolume(volume),
fImpl(NULL)
{
}
Query::~Query()
{
if (fImpl != NULL) {
if ((fImpl->Flags() & B_LIVE_QUERY) != 0)
fVolume->RemoveQuery(this);
delete fImpl;
}
}
/*static*/ status_t
Query::Create(Volume* volume, const char* queryString, uint32 flags,
port_id port, uint32 token, Query*& _query)
{
Query* query = new(std::nothrow) Query(volume);
if (query == NULL)
return B_NO_MEMORY;
status_t error = query->_Init(queryString, flags, port, token);
if (error != B_OK) {
delete query;
return error;
}
_query = query;
return B_OK;
}
status_t
Query::Rewind()
{
return fImpl->Rewind();
}
status_t
Query::GetNextEntry(struct dirent* entry, size_t size)
{
return fImpl->GetNextEntry(entry, size);
}
void
Query::LiveUpdate(Node* node, const char* attribute, int32 type,
const void* oldKey, size_t oldLength, const void* newKey, size_t newLength)
{
fImpl->LiveUpdate(node, node, attribute, type, (const uint8*)oldKey,
oldLength, (const uint8*)newKey, newLength);
}
status_t
Query::_Init(const char* queryString, uint32 flags, port_id port, uint32 token)
{
status_t error = QueryImpl::Create(this, queryString, flags, port, token,
fImpl);
if (error != B_OK)
return error;
if ((fImpl->Flags() & B_LIVE_QUERY) != 0)
fVolume->AddQuery(this);
return B_OK;
}
| 2,094 |
459 | <gh_stars>100-1000
/*
* This file is part of choco-solver, http://choco-solver.org/
*
* Copyright (c) 2021, IMT Atlantique. All rights reserved.
*
* Licensed under the BSD 4-clause license.
*
* See LICENSE file in the project root for full license information.
*/
package org.chocosolver.solver.search.loop.monitors;
/**
* An interface to monitor close operation of the search loop
* <br/>
*
* @author <NAME>
* @since 13/12/12
*/
public interface IMonitorClose extends ISearchMonitor {
/**
* Actions to execute before closing the search
*/
default void beforeClose(){
// nothing to do by default
}
/**
* Actions to execute after closing the search
*/
default void afterClose(){
// nothing to do by default
}
}
| 265 |
1,031 | <reponame>stjordanis/ml-cheatsheet
import torch
import torch.nn as nn
#from torch.autograd import Variable
class RNN(nn.Module):
def __init__(self, n_classes):
super().__init__()
self.hid_fc = nn.Linear(185, 128)
self.out_fc = nn.Linear(185, n_classes)
self.softmax = nn.LogSoftmax()
def forward(self, inputs, hidden):
inputs = inputs.view(1,-1)
combined = torch.cat([inputs, hidden], dim=1)
hid_out = self.hid_fc(combined)
out = self.out_fc(combined)
out = self.softmax(out)
return out, hid_out
def train(model, inputs, targets):
for i in range(len(inputs)):
target = Variable(targets[i])
name = inputs[i]
hidden = Variable(torch.zeros(1,128))
model.zero_grad()
for char in name:
input_ = Variable(torch.FloatTensor(char))
pred, hidden = model(input_, hidden)
loss = criterion(pred, target)
loss.backward()
for p in model.parameters():
p.data.add_(-.001, p.grad.data)
| 540 |
466 | package mu.nu.nullpo.gui;
public abstract class MouseInputDummy {
protected int mouseX;
protected int mouseY;
protected int[] mousePressed;
protected MouseInputDummy() {
mousePressed = new int[3];
}
public boolean isMouseClicked() {
return (mousePressed[0] == 1);
}
public boolean isMouseMiddleClicked() {
return (mousePressed[1] == 1);
}
public boolean isMouseRightClicked() {
return (mousePressed[2] == 1);
}
public boolean isMousePressed() {
return (mousePressed[0] > 0);
}
public boolean isMouseMiddlePressed() {
return (mousePressed[1] > 0);
}
public boolean isMouseRightPressed() {
return (mousePressed[2] > 0);
}
public boolean isMenuRepeatLeft() {
return (mousePressed[0] > 27 && (mousePressed[0] & 3) == 0);
}
public boolean isMenuRepeatMiddle() {
return (mousePressed[1] > 27 && (mousePressed[1] & 3) == 0);
}
public boolean isMenuRepeatRight() {
return (mousePressed[2] > 27 && (mousePressed[2] & 3) == 0);
}
public int getMouseX() {
return mouseX;
}
public int getMouseY() {
return mouseY;
}
}
| 461 |
448 | <gh_stars>100-1000
/*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "pdo/php_pdo.h"
#include "pdo/php_pdo_driver.h"
#include "php_pdo_sqlite.h"
#include "php_pdo_sqlite_int.h"
#include "zend_exceptions.h"
/* {{{ pdo_sqlite_functions[] */
static const zend_function_entry pdo_sqlite_functions[] = {
PHP_FE_END
};
/* }}} */
/* {{{ pdo_sqlite_deps
*/
static const zend_module_dep pdo_sqlite_deps[] = {
ZEND_MOD_REQUIRED("pdo")
ZEND_MOD_END
};
/* }}} */
/* {{{ pdo_sqlite_module_entry
*/
zend_module_entry pdo_sqlite_module_entry = {
STANDARD_MODULE_HEADER_EX, NULL,
pdo_sqlite_deps,
"pdo_sqlite",
pdo_sqlite_functions,
PHP_MINIT(pdo_sqlite),
PHP_MSHUTDOWN(pdo_sqlite),
NULL,
NULL,
PHP_MINFO(pdo_sqlite),
PHP_PDO_SQLITE_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#if defined(COMPILE_DL_PDO_SQLITE) || defined(COMPILE_DL_PDO_SQLITE_EXTERNAL)
ZEND_GET_MODULE(pdo_sqlite)
#endif
/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(pdo_sqlite)
{
#ifdef SQLITE_DETERMINISTIC
REGISTER_PDO_CLASS_CONST_LONG("SQLITE_DETERMINISTIC", (zend_long)SQLITE_DETERMINISTIC);
#endif
REGISTER_PDO_CLASS_CONST_LONG("SQLITE_ATTR_OPEN_FLAGS", (zend_long)PDO_SQLITE_ATTR_OPEN_FLAGS);
REGISTER_PDO_CLASS_CONST_LONG("SQLITE_OPEN_READONLY", (zend_long)SQLITE_OPEN_READONLY);
REGISTER_PDO_CLASS_CONST_LONG("SQLITE_OPEN_READWRITE", (zend_long)SQLITE_OPEN_READWRITE);
REGISTER_PDO_CLASS_CONST_LONG("SQLITE_OPEN_CREATE", (zend_long)SQLITE_OPEN_CREATE);
REGISTER_PDO_CLASS_CONST_LONG("SQLITE_ATTR_READONLY_STATEMENT", (zend_long)PDO_SQLITE_ATTR_READONLY_STATEMENT);
return php_pdo_register_driver(&pdo_sqlite_driver);
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(pdo_sqlite)
{
php_pdo_unregister_driver(&pdo_sqlite_driver);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(pdo_sqlite)
{
php_info_print_table_start();
php_info_print_table_header(2, "PDO Driver for SQLite 3.x", "enabled");
php_info_print_table_row(2, "SQLite Library", sqlite3_libversion());
php_info_print_table_end();
}
/* }}} */
| 1,405 |
777 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/blit.h"
#include <stddef.h>
#include "base/logging.h"
#include "build/build_config.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/skia/include/core/SkPixmap.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/vector2d.h"
#if defined(USE_CAIRO)
#if defined(OS_OPENBSD)
#include <cairo.h>
#elif defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
#include <cairo/cairo.h>
#endif
#endif
#if defined(OS_MACOSX)
#if defined(OS_IOS)
#include <CoreGraphics/CoreGraphics.h>
#else
#include <ApplicationServices/ApplicationServices.h>
#endif
#include "base/mac/scoped_cftyperef.h"
#endif
namespace gfx {
namespace {
// Returns true if the given canvas has any part of itself clipped out or
// any non-identity tranform.
bool HasClipOrTransform(SkCanvas& canvas) {
if (!canvas.getTotalMatrix().isIdentity())
return true;
if (!canvas.isClipRect())
return true;
// Now we know the clip is a regular rectangle, make sure it covers the
// entire canvas.
SkIRect clip_bounds;
canvas.getClipDeviceBounds(&clip_bounds);
SkImageInfo info;
size_t row_bytes;
void* pixels = canvas.accessTopLayerPixels(&info, &row_bytes);
DCHECK(pixels);
if (!pixels)
return true;
if (clip_bounds.fLeft != 0 || clip_bounds.fTop != 0 ||
clip_bounds.fRight != info.width() ||
clip_bounds.fBottom != info.height())
return true;
return false;
}
} // namespace
void ScrollCanvas(SkCanvas* canvas,
const gfx::Rect& in_clip,
const gfx::Vector2d& offset) {
DCHECK(!HasClipOrTransform(*canvas)); // Don't support special stuff.
SkPixmap pixmap;
bool success = skia::GetWritablePixels(canvas, &pixmap);
DCHECK(success);
// We expect all coords to be inside the canvas, so clip here.
gfx::Rect clip = gfx::IntersectRects(
in_clip, gfx::Rect(0, 0, pixmap.width(), pixmap.height()));
// Compute the set of pixels we'll actually end up painting.
gfx::Rect dest_rect = gfx::IntersectRects(clip + offset, clip);
if (dest_rect.size().IsEmpty())
return; // Nothing to do.
// Compute the source pixels that will map to the dest_rect
gfx::Rect src_rect = dest_rect - offset;
size_t row_bytes = dest_rect.width() * 4;
if (offset.y() > 0) {
// Data is moving down, copy from the bottom up.
for (int y = dest_rect.height() - 1; y >= 0; y--) {
memcpy(pixmap.writable_addr32(dest_rect.x(), dest_rect.y() + y),
pixmap.addr32(src_rect.x(), src_rect.y() + y),
row_bytes);
}
} else if (offset.y() < 0) {
// Data is moving up, copy from the top down.
for (int y = 0; y < dest_rect.height(); y++) {
memcpy(pixmap.writable_addr32(dest_rect.x(), dest_rect.y() + y),
pixmap.addr32(src_rect.x(), src_rect.y() + y),
row_bytes);
}
} else if (offset.x() != 0) {
// Horizontal-only scroll. We can do it in either top-to-bottom or bottom-
// to-top, but have to be careful about the order for copying each row.
// Fortunately, memmove already handles this for us.
for (int y = 0; y < dest_rect.height(); y++) {
memmove(pixmap.writable_addr32(dest_rect.x(), dest_rect.y() + y),
pixmap.addr32(src_rect.x(), src_rect.y() + y),
row_bytes);
}
}
}
} // namespace gfx
| 1,429 |
1,718 | #pragma once
#ifdef USE_CUDA
#define WARP_SIZE 32
#define MAX_THREADS_PER_BLOCK 1024
#define REDUCE_THREADS 256
#define HOST_AND_DEVICE __host__ __device__
#define FORCE_INLINE __forceinline__
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#else
#define HOST_AND_DEVICE
#define FORCE_INLINE inline
#endif // USE_CUDA
#include <cstring>
#include <iostream>
typedef enum { INFO = 0, WARNING = 1, ERROR = 2, FATAL = 3 } level_t;
const char* ToString(level_t level);
| 186 |
843 | package org.zalando.nakadi.annotations.validation;
import org.junit.Before;
import org.junit.Test;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class AnnotationValueTest {
public static class TestClass {
@Valid
@AnnotationValue
private String keyValue;
public TestClass(final String keyValue) {
this.keyValue = keyValue;
}
}
private Validator validator;
@Before
public void prepareValidator() {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
@Test
public void testLongAnnotationValue() {
final String longerAnnotation = "a".repeat(1001);
assertFalse(validator.validate(new TestClass(longerAnnotation)).isEmpty());
}
@Test
public void testNullAnnotationValue() {
assertTrue(validator.validate(new TestClass(null)).isEmpty());
}
@Test
public void testValidAnnotationValue() {
assertTrue(validator.validate(new TestClass("sdfg")).isEmpty());
assertTrue(validator.validate(new TestClass("{\"key\":\"value\"}")).isEmpty());
}
}
| 484 |
602 | <reponame>jtgrabowski/stargate<filename>testing/src/test/java/io/stargate/it/cql/AbstractCompressionTest.java<gh_stars>100-1000
package io.stargate.it.cql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.offset;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.ExecutionInfo;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import io.stargate.it.BaseOsgiIntegrationTest;
import io.stargate.it.driver.CqlSessionExtension;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(CqlSessionExtension.class)
public abstract class AbstractCompressionTest extends BaseOsgiIntegrationTest {
protected void compressionTest(CqlSession session) {
session.execute("CREATE TABLE test (k text PRIMARY KEY, t text, i int, f float)");
// Run a couple of simple test queries
ResultSet rs =
session.execute(
SimpleStatement.newInstance(
"INSERT INTO test (k, t, i, f) VALUES (?, ?, ?, ?)", "key", "foo", 42, 24.03f));
assertThat(rs.iterator().hasNext()).isFalse();
ResultSet rs1 = session.execute("SELECT * FROM test WHERE k = 'key'");
assertThat(rs1.iterator().hasNext()).isTrue();
Row row = rs1.iterator().next();
assertThat(rs1.iterator().hasNext()).isFalse();
assertThat(row.getString("k")).isEqualTo("key");
assertThat(row.getString("t")).isEqualTo("foo");
assertThat(row.getInt("i")).isEqualTo(42);
assertThat(row.getFloat("f")).isEqualTo(24.03f, offset(0.1f));
ExecutionInfo executionInfo = rs.getExecutionInfo();
// There's not much more we can check without hard-coding sizes.
// We are testing with small responses, so the compressed payload is not even guaranteed to be
// smaller.
assertThat(executionInfo.getResponseSizeInBytes()).isGreaterThan(0);
assertThat(executionInfo.getCompressedResponseSizeInBytes()).isGreaterThan(0);
}
}
| 756 |
38,047 | #include "test/jemalloc_test.h"
#define ARENA_RESET_PROF_C_
#include "arena_reset.c"
| 40 |
2,496 | <gh_stars>1000+
/*
* Copyright (C) 2005-2008 <NAME>. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.http;
import java.io.File;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.*;
import org.apache.jasper.servlet.JasperInitializer;
import org.apache.tomcat.InstanceManager;
import org.apache.tomcat.SimpleInstanceManager;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.plus.annotation.ContainerInitializer;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.ForwardedRequestCustomizer;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.WebAppLoaderFix;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.jivesoftware.openfire.Connection;
import org.jivesoftware.openfire.JMXManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.keystore.CertificateStore;
import org.jivesoftware.openfire.keystore.IdentityStore;
import org.jivesoftware.openfire.spi.*;
import org.jivesoftware.openfire.websocket.OpenfireWebSocketServlet;
import org.jivesoftware.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Responsible for making available BOSH (functionality to the outside world, using an embedded web server.
*/
public final class HttpBindManager implements CertificateEventListener {
private static final Logger Log = LoggerFactory.getLogger(HttpBindManager.class);
/**
* Enable / disable logging of BOSH requests and responses.
*/
public static final SystemProperty<Boolean> LOG_HTTPBIND_ENABLED = SystemProperty.Builder.ofType(Boolean.class)
.setKey("log.httpbind.enabled")
.setDynamic(true)
.setDefaultValue(false)
.build();
/**
* Enable / disable BOSH (HTTP Binding) functionality.
*/
public static final SystemProperty<Boolean> HTTP_BIND_ENABLED = SystemProperty.Builder.ofType(Boolean.class)
.setKey("httpbind.enabled")
.setDynamic(true)
.setDefaultValue(true)
.addListener(HttpBindManager::restart)
.build();
/**
* @deprecated Replaced with HTTP_BIND_ENABLED.getDefaultValue();
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public static final boolean HTTP_BIND_ENABLED_DEFAULT = HTTP_BIND_ENABLED.getDefaultValue();
/**
* TCP port on which the non-encrypted (HTTP) BOSH endpoint is exposed.
*/
public static final SystemProperty<Integer> HTTP_BIND_PORT = SystemProperty.Builder.ofType(Integer.class)
.setKey("httpbind.port.plain")
.setDynamic(true)
.setDefaultValue(7070)
.addListener(HttpBindManager::restart)
.build();
/**
* @deprecated Replaced with HTTP_BIND_PORT.getDefaultValue();
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public static final int HTTP_BIND_PORT_DEFAULT = HTTP_BIND_PORT.getDefaultValue();
/**
* TCP port on which the encrypted (HTTPS) BOSH endpoint is exposed.
*/
public static final SystemProperty<Integer> HTTP_BIND_SECURE_PORT = SystemProperty.Builder.ofType(Integer.class)
.setKey("httpbind.port.secure")
.setDynamic(true)
.setDefaultValue(7443)
.addListener(HttpBindManager::restart)
.build();
/**
* @deprecated Replaced with HTTP_BIND_SECURE_PORT.getDefaultValue();
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public static final int HTTP_BIND_SECURE_PORT_DEFAULT = HTTP_BIND_SECURE_PORT.getDefaultValue();
/**
* Minimum amount of threads in the thread pool to perform the network IO related to BOSH traffic.
*
* Note: Apart from the network-IO threads configured in this property, the server also uses a thread pool for
* processing the inbound data (as configured in ({@link HttpSessionManager#MAX_POOL_SIZE}). BOSH
* installations expecting heavy loads may want to allocate additional threads to this worker pool to ensure timely
* processing of data
*/
public static final SystemProperty<Integer> HTTP_BIND_THREADS_MIN = SystemProperty.Builder.ofType(Integer.class)
.setKey("httpbind.client.processing.threads-min")
.setDynamic(false) // TODO This can easily be made dynamic with <tt>.addListener(HttpBindManager.getInstance()::restartServer)</tt>. Existing implementation was not dynamic. Should it?
.setDefaultValue(8)
.setMinValue(1)
.build();
/**
* Maximum amount of threads in the thread pool to perform the network IO related to BOSH traffic.
*
* Note: Apart from the network-IO threads configured in this property, the server also uses a thread pool for
* processing the inbound data (as configured in ({@link HttpSessionManager#MAX_POOL_SIZE}). BOSH
* installations expecting heavy loads may want to allocate additional threads to this worker pool to ensure timely
* processing of data
*/
public static final SystemProperty<Integer> HTTP_BIND_THREADS = SystemProperty.Builder.ofType(Integer.class)
.setKey("httpbind.client.processing.threads")
.setDynamic(false) // TODO This can easily be made dynamic with <tt>.addListener(HttpBindManager.getInstance()::restartServer)</tt>. Existing implementation was not dynamic. Should it?
.setDefaultValue(200)
.setMinValue(1)
.build();
/**
* Amount of time after which idle, surplus threads are removed from the thread pool to perform the network IO
* related to BOSH traffic.
*
* Note: Apart from the network-IO threads configured in this property, the server also uses a thread pool for
* processing the inbound data (as configured in ({@link HttpSessionManager#INACTIVITY_TIMEOUT}). BOSH
* installations expecting heavy loads may want to allocate additional threads to this worker pool to ensure timely
* processing of data
*/
public static final SystemProperty<Duration> HTTP_BIND_THREADS_TIMEOUT = SystemProperty.Builder.ofType(Duration.class)
.setKey("httpbind.client.processing.threads-timeout")
.setDynamic(false) // TODO This can easily be made dynamic with <tt>.addListener(HttpBindManager.getInstance()::restartServer)</tt>. Existing implementation was not dynamic. Should it?
.setDefaultValue(Duration.ofSeconds(60))
.setChronoUnit(ChronoUnit.MILLIS)
.setMaxValue(Duration.ofMillis(Integer.MAX_VALUE)) // Jetty takes an int value, not a long.
.build();
/**
* @deprecated Replaced with HTTP_BIND_THREADS.getDefaultValue();
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public static final int HTTP_BIND_THREADS_DEFAULT = HTTP_BIND_THREADS.getDefaultValue();
/**
* The TLS 'mutual authentication' policy that is applied to the BOSH endpoint.
*/
// Ideally, this would be a property of the Connection.ClientAuth enum, but we need to be able to set a 'null' default value (as that will cause a dynamic default to be calculated). Using the dynamic default calculation in this SystemProperty does not work, as it throws NullPointerExceptions during server startup.
public static final SystemProperty<String> HTTP_BIND_AUTH_PER_CLIENTCERT_POLICY = SystemProperty.Builder.ofType(String.class)
.setKey("httpbind.client.cert.policy")
.setDynamic(true)
.setDefaultValue(null)
.addListener(HttpBindManager::restart)
.build();
/**
* Enable / Disable parsing a 'X-Forwarded-For' style HTTP header of BOSH requests.
*/
public static final SystemProperty<Boolean> HTTP_BIND_FORWARDED = SystemProperty.Builder.ofType(Boolean.class)
.setKey("httpbind.forwarded.enabled")
.setDynamic(false) // TODO This can easily be made dynamic with <tt>.addListener(HttpBindManager.getInstance()::restartServer)</tt>. Existing implementation was not dynamic. Should it?
.setDefaultValue(false)
.build();
/**
* The HTTP header name for 'forwarded for'
*/
public static final SystemProperty<String> HTTP_BIND_FORWARDED_FOR = SystemProperty.Builder.ofType(String.class)
.setKey("httpbind.forwarded.for.header")
.setDynamic(false) // TODO This can easily be made dynamic with <tt>.addListener(HttpBindManager.getInstance()::restartServer)</tt>. Existing implementation was not dynamic. Should it?
.setDefaultValue(HttpHeader.X_FORWARDED_FOR.toString())
.build();
/**
* The HTTP header name for 'forwarded server'.
*/
public static final SystemProperty<String> HTTP_BIND_FORWARDED_SERVER = SystemProperty.Builder.ofType(String.class)
.setKey("httpbind.forwarded.server.header")
.setDynamic(false) // TODO This can easily be made dynamic with <tt>.addListener(HttpBindManager.getInstance()::restartServer)</tt>. Existing implementation was not dynamic. Should it?
.setDefaultValue(HttpHeader.X_FORWARDED_SERVER.toString())
.build();
/**
* The HTTP header name for 'forwarded hosts'.
*/
public static final SystemProperty<String> HTTP_BIND_FORWARDED_HOST = SystemProperty.Builder.ofType(String.class)
.setKey("httpbind.forwarded.host.header")
.setDynamic(false) // TODO This can easily be made dynamic with <tt>.addListener(HttpBindManager.getInstance()::restartServer)</tt>. Existing implementation was not dynamic. Should it?
.setDefaultValue(HttpHeader.X_FORWARDED_HOST.toString())
.build();
/**
* Sets a forced valued for the host header.
*/
public static final SystemProperty<String> HTTP_BIND_FORWARDED_HOST_NAME = SystemProperty.Builder.ofType(String.class)
.setKey("httpbind.forwarded.host.name")
.setDynamic(false) // TODO This can easily be made dynamic with <tt>.addListener(HttpBindManager.getInstance()::restartServer)</tt>. Existing implementation was not dynamic. Should it?
.setDefaultValue(null)
.build();
// http binding CORS default properties
/**
* Enable / Disable support for Cross-Origin Resource Sharing (CORS) headers in the BOSH endpoint.
*/
public static final SystemProperty<Boolean> HTTP_BIND_CORS_ENABLED = SystemProperty.Builder.ofType(Boolean.class)
.setKey("httpbind.CORS.enabled")
.setDynamic(false) // TODO This can easily be made dynamic with <tt>.addListener(HttpBindManager.getInstance()::restartServer)</tt>. Existing implementation was not dynamic. Should it?
.setDefaultValue(true)
.build();
/**
* @deprecated Replaced with HTTP_BIND_CORS_ENABLED.getDefaultValue();
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public static final boolean HTTP_BIND_CORS_ENABLED_DEFAULT = HTTP_BIND_CORS_ENABLED.getDefaultValue();
/**
* The Cross-Origin Resource Sharing (CORS) header value that represents the 'allow all orgins' state.
*/
public static final String HTTP_BIND_CORS_ALLOW_ORIGIN_ALL = "*";
/**
* The domain names that are accepted as values for the CORS 'Origin' header in the BOSH endpoint.
*/
public static final SystemProperty<Set<String>> HTTP_BIND_ALLOWED_ORIGINS = SystemProperty.Builder.ofType(Set.class)
.setKey("httpbind.CORS.domains")
.setDynamic(true)
.setDefaultValue(Collections.singleton(HTTP_BIND_CORS_ALLOW_ORIGIN_ALL))
.buildSet(String.class);
/**
* The HTTP methods that are accepted in the BOSH endpoint.
*/
public static final SystemProperty<Set<String>> HTTP_BIND_CORS_ALLOW_METHODS = SystemProperty.Builder.ofType(Set.class)
.setKey("httpbind.CORS.methods")
.setDynamic(true)
.setDefaultValue(new HashSet<>(Arrays.asList("PROPFIND", "PROPPATCH", "COPY", "MOVE", "DELETE", "MKCOL", "LOCK", "UNLOCK", "PUT", "GETLIB", "VERSION-CONTROL", "CHECKIN", "CHECKOUT", "UNCHECKOUT", "REPORT", "UPDATE", "CANCELUPLOAD", "HEAD", "OPTIONS", "GET", "POST")) )
.buildSet(String.class);
/**
* @deprecated Replaced with String.join(", ", HTTP_BIND_CORS_ALLOW_METHODS.getDefaultValue())
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public static final String HTTP_BIND_CORS_ALLOW_METHODS_DEFAULT = String.join(", ", HTTP_BIND_CORS_ALLOW_METHODS.getDefaultValue());
/**
* The name of HTTP headers that are accepted in requests to the BOSH endpoint.
*/
public static final SystemProperty<Set<String>> HTTP_BIND_CORS_ALLOW_HEADERS = SystemProperty.Builder.ofType(Set.class)
.setKey("httpbind.CORS.headers")
.setDynamic(true)
.setDefaultValue(new HashSet<>(Arrays.asList("Overwrite", "Destination", "Content-Type", "Depth", "User-Agent", "X-File-Size", "X-Requested-With", "If-Modified-Since", "X-File-Name", "Cache-Control")) )
.buildSet(String.class);
/**
* @deprecated Replaced with String.join(", ", HTTP_BIND_CORS_ALLOW_HEADERS.getDefaultValue())
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public static final String HTTP_BIND_CORS_ALLOW_HEADERS_DEFAULT = String.join(", ", HTTP_BIND_CORS_ALLOW_HEADERS.getDefaultValue());;
/**
* How long the results of a preflight request (that is the information contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can be cached.
*/
public static final SystemProperty<Duration> HTTP_BIND_CORS_MAX_AGE = SystemProperty.Builder.ofType(Duration.class)
.setKey("httpbind.CORS.max_age")
.setDynamic(true)
.setDefaultValue(Duration.ofDays(1))
.setChronoUnit(ChronoUnit.SECONDS)
.build();
/**
* @deprecated Replaced with HTTP_BIND_CORS_MAX_AGE.getDefaultValue().toSeconds();
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public static final String HTTP_BIND_CORS_MAX_AGE_DEFAULT = String.valueOf(HTTP_BIND_CORS_MAX_AGE.getDefaultValue().getSeconds()); // TODO replace with 'toSeconds()' after dropping support for Java 8
/**
* the maximum size in bytes of request headers in the BOSH endpoint. Larger headers will allow for more and/or
* larger cookies plus larger form content encoded in a URL. However, larger headers consume more memory and can
* make a server more vulnerable to denial of service attacks.
*/
public static final SystemProperty<Integer> HTTP_BIND_REQUEST_HEADER_SIZE = SystemProperty.Builder.ofType(Integer.class)
.setKey("httpbind.request.header.size")
.setDynamic(true)
.setDefaultValue(32768)
.build();
/**
* @deprecated Replaced with HTTP_BIND_REQUEST_HEADER_SIZE.getDefaultValue();
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public static final int HTTP_BIND_REQUEST_HEADER_SIZE_DEFAULT = HTTP_BIND_REQUEST_HEADER_SIZE.getDefaultValue();
private static HttpBindManager instance;
private Server httpBindServer;
private final HttpSessionManager httpSessionManager;
/**
* An ordered collection of all handlers (that is created to include the #extensionHandlers).
*
* A reference to this collection is maintained outside of the Jetty server implementation ({@link #httpBindServer})
* as its lifecycle differs from that server: the server is recreated upon configuration changes, while the
* collection of handlers need not be.
*
* This collection is ordered, which ensures that:
* <ul>
* <li>The handlers providing BOSH functionality are tried first.</li>
* <li>Any handlers that are registered by external sources ({@link #extensionHandlers}) are tried in between.</li>
* <li>The 'catch-all' handler that maps to static content is tried last.</li>
* </ul>
*
* This collection should be regarded as immutable. When handlers are to be added/removed dynamically, this should
* occur in {@link #extensionHandlers}, to which a reference is stored in this list by the constructor of this class.
*/
private final HandlerList handlerList = new HandlerList();
/**
* Contains all Jetty handlers that are added as an extension.
*
* This collection is mutable. Handlers can be added and removed at runtime.
*/
private final HandlerCollection extensionHandlers = new HandlerCollection( true );
/**
* A task that, periodically, updates the 'last modified' date of all files in the Jetty 'tmp' directories. This
* prevents operating systems from removing files that are deemed unused.
*
* @see <a href="https://igniterealtime.atlassian.net/browse/OF-1534">OF-1534</a>
*/
private TempFileToucherTask tempFileToucherTask;
public static synchronized HttpBindManager getInstance() {
if (instance == null) {
instance = new HttpBindManager();
}
return instance;
}
private HttpBindManager() {
this.httpSessionManager = new HttpSessionManager();
// Setup the default handlers. Order is important here. First, evaluate if the 'standard' handlers can be used to fulfill requests.
this.handlerList.addHandler( createBoshHandler() );
this.handlerList.addHandler( createWebsocketHandler() );
// When standard handling does not apply, see if any of the handlers in the extension pool of handlers applies to the request.
this.handlerList.addHandler( this.extensionHandlers );
// When everything else fails, use the static content handler. This one should be last, as it is mapping to the root context.
// This means that it will catch everything and prevent the invocation of later handlers.
final Handler staticContentHandler = createStaticContentHandler();
if ( staticContentHandler != null )
{
this.handlerList.addHandler( staticContentHandler );
}
}
public void start() {
if (!HTTP_BIND_ENABLED.getValue()) {
return;
}
final QueuedThreadPool tp = new QueuedThreadPool(HTTP_BIND_THREADS.getValue(), HTTP_BIND_THREADS_MIN.getValue(), (int) HTTP_BIND_THREADS_TIMEOUT.getValue().toMillis());
tp.setName("Jetty-QTP-BOSH");
httpBindServer = new Server(tp);
if (JMXManager.isEnabled()) {
JMXManager jmx = JMXManager.getInstance();
httpBindServer.addBean(jmx.getContainer());
}
final Connector httpConnector = createConnector( httpBindServer );
final Connector httpsConnector = createSSLConnector( httpBindServer);
if (httpConnector == null && httpsConnector == null) {
httpBindServer = null;
return;
}
if (httpConnector != null) {
httpBindServer.addConnector(httpConnector);
}
if (httpsConnector != null) {
httpBindServer.addConnector(httpsConnector);
}
httpBindServer.setHandler( handlerList );
try {
httpBindServer.start();
if (handlerList.getHandlers() != null) {
Arrays.stream(handlerList.getHandlers()).forEach(handler -> {
try {
handler.start();
} catch (Exception e) {
Log.warn("An exception occurred while trying to start handler: {}", handler, e);
}
});
}
handlerList.start();
if ( extensionHandlers.getHandlers() != null ) {
Arrays.stream(extensionHandlers.getHandlers()).forEach(handler -> {
try {
handler.start();
} catch (Exception e) {
Log.warn("An exception occurred while trying to start extension handler: {}", handler, e);
}
});
}
extensionHandlers.start();
CertificateManager.addListener(this);
Log.info("HTTP bind service started");
}
catch (Exception e) {
Log.error("Error starting HTTP bind service", e);
}
if ( JiveGlobals.getBooleanProperty( "jetty.temp-file-toucher.enabled", true ) ) {
tempFileToucherTask = new TempFileToucherTask( httpBindServer );
final long period = JiveGlobals.getLongProperty( "jetty.temp-file-toucher.period", JiveConstants.DAY );
TaskEngine.getInstance().schedule( tempFileToucherTask, period, period );
}
}
public void stop() {
CertificateManager.removeListener(this);
if ( tempFileToucherTask != null ) {
TaskEngine.getInstance().cancelScheduledTask( tempFileToucherTask );
tempFileToucherTask = null;
}
if (httpBindServer != null) {
try {
if ( extensionHandlers.getHandlers() != null ) {
Arrays.stream(extensionHandlers.getHandlers()).forEach(handler -> {
try {
handler.stop();
} catch (Exception e) {
Log.warn("An exception occurred while trying to stop extension handler: {}", handler, e);
}
});
}
extensionHandlers.stop();
if ( handlerList.getHandlers() != null ) {
Arrays.stream(handlerList.getHandlers()).forEach(handler -> {
try {
handler.stop();
} catch (Exception e) {
Log.warn("An exception occurred while trying to stop handler: {}", handler, e);
}
});
}
handlerList.stop();
httpBindServer.stop();
Log.info("HTTP bind service stopped");
}
catch (Exception e) {
Log.error("Error stopping HTTP bind service", e);
}
httpBindServer = null;
}
}
public HttpSessionManager getSessionManager() {
return httpSessionManager;
}
private Connector createConnector( final Server httpBindServer ) {
final int port = getHttpBindUnsecurePort();
if (port > 0) {
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSendServerVersion( false );
configureProxiedConnector(httpConfig);
ServerConnector connector = new ServerConnector(httpBindServer, new HttpConnectionFactory(httpConfig));
// Listen on a specific network interface if it has been set.
connector.setHost(getBindInterface());
connector.setPort(port);
return connector;
}
else
{
return null;
}
}
private Connector createSSLConnector( final Server httpBindServer ) {
final int securePort = getHttpBindSecurePort();
try {
final IdentityStore identityStore = XMPPServer.getInstance().getCertificateStoreManager().getIdentityStore( ConnectionType.BOSH_C2S );
if (securePort > 0 && identityStore.getStore().aliases().hasMoreElements() ) {
if ( !identityStore.containsDomainCertificate( ) ) {
Log.warn("HTTP binding: Using certificates but they are not valid for the hosted domain");
}
final ConnectionManagerImpl connectionManager = ((ConnectionManagerImpl) XMPPServer.getInstance().getConnectionManager());
final ConnectionConfiguration configuration = connectionManager.getListener( ConnectionType.BOSH_C2S, true ).generateConnectionConfiguration();
final SslContextFactory sslContextFactory = new EncryptionArtifactFactory(configuration).getSslContextFactory();
final HttpConfiguration httpsConfig = new HttpConfiguration();
httpsConfig.setSecureScheme("https");
httpsConfig.setSecurePort(securePort);
configureProxiedConnector(httpsConfig);
httpsConfig.addCustomizer(new SecureRequestCustomizer());
httpsConfig.setSendServerVersion( false );
final ServerConnector sslConnector = new ServerConnector(httpBindServer, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(httpsConfig));
sslConnector.setHost(getBindInterface());
sslConnector.setPort(securePort);
return sslConnector;
}
}
catch (Exception e) {
Log.error("Error creating SSL connector for Http bind", e);
}
return null;
}
private void configureProxiedConnector(HttpConfiguration httpConfig) {
// Check to see if we are deployed behind a proxy
// Refer to http://eclipse.org/jetty/documentation/current/configuring-connectors.html
if (isXFFEnabled()) {
ForwardedRequestCustomizer customizer = new ForwardedRequestCustomizer();
// default: "X-Forwarded-For"
String forwardedForHeader = HTTP_BIND_FORWARDED_FOR.getValue();
if (forwardedForHeader != null) {
customizer.setForwardedForHeader(forwardedForHeader);
}
// default: "X-Forwarded-Server"
String forwardedServerHeader = HTTP_BIND_FORWARDED_SERVER.getValue();
if (forwardedServerHeader != null) {
customizer.setForwardedServerHeader(forwardedServerHeader);
}
// default: "X-Forwarded-Host"
String forwardedHostHeader = HTTP_BIND_FORWARDED_HOST.getValue();
if (forwardedHostHeader != null) {
customizer.setForwardedHostHeader(forwardedHostHeader);
}
// default: none
String hostName = getXFFHostName();
if (hostName != null) {
customizer.setHostHeader(hostName);
}
httpConfig.addCustomizer(customizer);
}
httpConfig.setRequestHeaderSize(HTTP_BIND_REQUEST_HEADER_SIZE.getValue());
}
private String getBindInterface() {
String interfaceName = JiveGlobals.getXMLProperty("network.interface");
String bindInterface = null;
if (interfaceName != null) {
if (interfaceName.trim().length() > 0) {
bindInterface = interfaceName;
}
}
return bindInterface;
}
/**
* Returns true if the HTTP binding server is currently enabled.
*
* @return true if the HTTP binding server is currently enabled.
*/
public boolean isHttpBindEnabled() {
return httpBindServer != null && httpBindServer.isRunning();
}
/**
* Returns true if a listener on the HTTP binding port is running.
*
* @return true if a listener on the HTTP binding port is running.
*/
public boolean isHttpBindActive()
{
if ( isHttpBindEnabled() )
{
final int configuredPort = getHttpBindUnsecurePort();
for ( final Connector connector : httpBindServer.getConnectors() )
{
if ( !( connector instanceof ServerConnector ) )
{
continue;
}
final int activePort = ( (ServerConnector) connector ).getLocalPort();
if ( activePort == configuredPort )
{
return true;
}
}
}
return false;
}
/**
* Returns true if a listener on the HTTPS binding port is running.
*
* @return true if a listener on the HTTPS binding port is running.
*/
public boolean isHttpsBindActive()
{
if ( isHttpBindEnabled() )
{
final int configuredPort = getHttpBindSecurePort();
for ( final Connector connector : httpBindServer.getConnectors() )
{
if ( !( connector instanceof ServerConnector ) )
{
continue;
}
final int activePort = ( (ServerConnector) connector ).getLocalPort();
if ( activePort == configuredPort )
{
return true;
}
}
}
return false;
}
public String getHttpBindUnsecureAddress() {
return "http://" + XMPPServer.getInstance().getServerInfo().getHostname() + ":" + getHttpBindUnsecurePort() + "/http-bind/";
}
public String getHttpBindSecureAddress() {
return "https://" + XMPPServer.getInstance().getServerInfo().getHostname() + ":" + getHttpBindSecurePort() + "/http-bind/";
}
public String getJavaScriptUrl() {
return "http://" + XMPPServer.getInstance().getServerInfo().getHostname() + ":" + getHttpBindUnsecurePort() + "/scripts/";
}
// http binding CORS support start
/**
* @deprecated Replaced by <tt>HTTP_BIND_CORS_ENABLED.getValue()</tt>
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public boolean isCORSEnabled() {
return HTTP_BIND_CORS_ENABLED.getValue();
}
/**
* @deprecated Replaced by <tt>HTTP_BIND_CORS_ENABLED.setValue()</tt>
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public void setCORSEnabled(Boolean value) {
if (value != null)
HTTP_BIND_CORS_ENABLED.setValue(value);
}
/**
* @deprecated Replaced by HTTP_BIND_ALLOWED_ORIGINS.getValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public String getCORSAllowOrigin() {
return String.join(",", HTTP_BIND_ALLOWED_ORIGINS.getValue());
}
/**
* @deprecated Replaced by HTTP_BIND_ALLOWED_ORIGINS.setValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public void setCORSAllowOrigin(String origins) {
final Set<String> update = new HashSet<>();
if (origins == null || origins.trim().length() == 0)
update.add(HTTP_BIND_CORS_ALLOW_ORIGIN_ALL);
else {
origins = origins.replaceAll("\\s+", "");
final String[] split = origins.split(",");
update.addAll(Arrays.asList(split));
}
HTTP_BIND_ALLOWED_ORIGINS.setValue(update);
}
public boolean isAllOriginsAllowed() {
return HTTP_BIND_ALLOWED_ORIGINS.getValue().contains(HTTP_BIND_CORS_ALLOW_ORIGIN_ALL);
}
public boolean isThisOriginAllowed(String origin) {
return isAllOriginsAllowed() || HTTP_BIND_ALLOWED_ORIGINS.getValue().stream().anyMatch(o -> o.equalsIgnoreCase(origin));
}
// http binding CORS support end
/**
* @deprecated Replaced by HTTP_BIND_FORWARDED.getValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public boolean isXFFEnabled() {
return HTTP_BIND_FORWARDED.getValue();
}
/**
* @deprecated Replaced by HTTP_BIND_FORWARDED.setValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public void setXFFEnabled(boolean enabled) {
HTTP_BIND_FORWARDED.setValue(enabled);
}
/**
* @deprecated Replaced by HTTP_BIND_FORWARDED_FOR.getValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public String getXFFHeader() {
return HTTP_BIND_FORWARDED_FOR.getValue();
}
/**
* @deprecated Replaced by HTTP_BIND_FORWARDED_FOR.setValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public void setXFFHeader(String header) {
if (header == null || header.trim().isEmpty()) {
HTTP_BIND_FORWARDED_FOR.setValue(null);
} else {
HTTP_BIND_FORWARDED_FOR.setValue(header);
}
}
/**
* @deprecated Replaced by HTTP_BIND_FORWARDED_SERVER.getValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public String getXFFServerHeader() {
return HTTP_BIND_FORWARDED_SERVER.getValue();
}
/**
* @deprecated Replaced by HTTP_BIND_FORWARDED_SERVER.setValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public void setXFFServerHeader(String header) {
if (header == null || header.trim().isEmpty()) {
HTTP_BIND_FORWARDED_SERVER.setValue(null);
} else {
HTTP_BIND_FORWARDED_SERVER.setValue(header);
}
}
/**
* @deprecated Replaced by HTTP_BIND_FORWARDED_HOST.getValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public String getXFFHostHeader() {
return HTTP_BIND_FORWARDED_HOST.getValue();
}
/**
* @deprecated Replaced by HTTP_BIND_FORWARDED_HOST.setValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public void setXFFHostHeader(String header) {
if (header == null || header.trim().isEmpty()) {
HTTP_BIND_FORWARDED_HOST.setValue(null);
} else {
HTTP_BIND_FORWARDED_HOST.setValue(header);
}
}
/**
* @deprecated Replaced by HTTP_BIND_FORWARDED_HOST_NAME.getValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public String getXFFHostName() {
return HTTP_BIND_FORWARDED_HOST_NAME.getValue();
}
/**
* @deprecated Replaced by HTTP_BIND_FORWARDED_HOST_NAME.setValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public void setXFFHostName(String name) {
if (name == null || name.trim().isEmpty()) {
HTTP_BIND_FORWARDED_HOST_NAME.setValue(null);
} else {
HTTP_BIND_FORWARDED_HOST_NAME.setValue(name);
}
}
/**
* Set the ports on which the HTTP binding service will be running.
*
* @param unsecurePort the unsecured connection port which clients can connect to.
* @param securePort the secured connection port which clients can connect to.
* @throws Exception when there is an error configuring the HTTP binding ports.
* @deprecated Replaced with HTTP_BIND_PORT.setValue(unsecurePort) and HTTP_BIND_SECURE_PORT.setValue(unsecurePort);
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public void setHttpBindPorts(int unsecurePort, int securePort) throws Exception {
HTTP_BIND_PORT.setValue(unsecurePort);
HTTP_BIND_SECURE_PORT.setValue(securePort);
}
/**
* Creates a Jetty context handler that can be used to expose BOSH (HTTP-Bind) functionality.
*
* Note that an invocation of this method will not register the handler (and thus make the related functionality
* available to the end user). Instead, the created handler is returned by this method, and will need to be
* registered with the embedded Jetty webserver by the caller.
*
* @return A Jetty context handler (never null).
*/
protected Handler createBoshHandler()
{
final int options;
if(isHttpCompressionEnabled()) {
options = ServletContextHandler.SESSIONS | ServletContextHandler.GZIP;
} else {
options = ServletContextHandler.SESSIONS;
}
final ServletContextHandler context = new ServletContextHandler( null, "/http-bind", options );
// Ensure the JSP engine is initialized correctly (in order to be able to cope with Tomcat/Jasper precompiled JSPs).
final List<ContainerInitializer> initializers = new ArrayList<>();
initializers.add( new ContainerInitializer( new JasperInitializer(), null ) );
context.setAttribute( "org.eclipse.jetty.containerInitializers", initializers );
context.setAttribute( InstanceManager.class.getName(), new SimpleInstanceManager() );
// Generic configuration of the context.
context.setAllowNullPathInfo( true );
// Add the functionality-providers.
context.addServlet( new ServletHolder( new HttpBindServlet() ), "/*" );
// Add compression filter when needed.
if (isHttpCompressionEnabled()) {
final GzipHandler gzipHandler = context.getGzipHandler();
gzipHandler.addIncludedPaths("/*");
gzipHandler.addIncludedMethods(HttpMethod.POST.asString());
}
return context;
}
/**
* Creates a Jetty context handler that can be used to expose Websocket functionality.
*
* Note that an invocation of this method will not register the handler (and thus make the related functionality
* available to the end user). Instead, the created handler is returned by this method, and will need to be
* registered with the embedded Jetty webserver by the caller.
*
* @return A Jetty context handler (never null).
*/
protected Handler createWebsocketHandler()
{
final ServletContextHandler context = new ServletContextHandler( null, "/ws", ServletContextHandler.SESSIONS );
context.setAllowNullPathInfo(true);
// Add the functionality-providers.
context.addServlet( new ServletHolder( new OpenfireWebSocketServlet() ), "/*" );
return context;
}
// NOTE: enabled by default
private boolean isHttpCompressionEnabled() {
final ConnectionManagerImpl connectionManager = ((ConnectionManagerImpl) XMPPServer.getInstance().getConnectionManager());
final ConnectionConfiguration configuration = connectionManager.getListener( ConnectionType.BOSH_C2S, true ).generateConnectionConfiguration();
return configuration.getCompressionPolicy() == null || configuration.getCompressionPolicy().equals( Connection.CompressionPolicy.optional );
}
/**
* Creates a Jetty context handler that can be used to expose static files.
*
* Note that an invocation of this method will not register the handler (and thus make the related functionality
* available to the end user). Instead, the created handler is returned by this method, and will need to be
* registered with the embedded Jetty webserver by the caller.
*
* @return A Jetty context handler, or null when the static content could not be accessed.
*/
protected Handler createStaticContentHandler()
{
final File spankDirectory = new File( JiveGlobals.getHomeDirectory() + File.separator + "resources" + File.separator + "spank" );
if ( spankDirectory.exists() )
{
if ( spankDirectory.canRead() )
{
final WebAppContext context = new WebAppContext( null, spankDirectory.getPath(), "/" );
context.setWelcomeFiles( new String[] { "index.html" } );
return context;
}
else
{
Log.warn( "Openfire cannot read the directory: " + spankDirectory );
}
}
return null;
}
/**
* Adds a Jetty handler to be added to the embedded web server that is used to expose BOSH (HTTP-bind)
* functionality.
*
* @param handler The handler (cannot be null).
*/
public void addJettyHandler( Handler handler )
{
if ( handler == null )
{
throw new IllegalArgumentException( "Argument 'handler' cannot be null." );
}
extensionHandlers.addHandler( handler );
if ( !handler.isStarted() && extensionHandlers.isStarted() )
{
try
{
handler.start();
}
catch ( Exception e )
{
Log.warn( "Unable to start handler {}", handler, e );
}
}
}
/**
* Removes a Jetty handler to be added to the embedded web server that is used to expose BOSH (HTTP-bind)
* functionality.
*
* Removing a handler, even when null, or non-existing, might have side-effects as introduced by the Jetty
* implementation. At the time of writing, Jetty will re
*
* @param handler The handler (should not be null).
*/
public void removeJettyHandler( Handler handler )
{
if (handler instanceof WebAppContext) {
// A work-around of the Jetty bug described at https://github.com/eclipse/jetty.project/issues/1425
// NOTE: According to some comments on WebAppLoaderFix, this may stop working on Java 9.
// Hopefully the Jetty team will have fixed the underlying bug by then
WebAppLoaderFix.checkAndClose(((WebAppContext) handler).getClassLoader());
}
extensionHandlers.removeHandler( handler );
if ( handler.isStarted() )
{
try
{
handler.stop();
}
catch ( Exception e )
{
Log.warn( "Unable to stop the handler that was removed: {}", handler, e );
}
}
}
private void doEnableHttpBind(boolean shouldEnable) {
if (shouldEnable && httpBindServer == null) {
start();
}
else if (!shouldEnable && httpBindServer != null) {
stop();
}
}
/**
* Returns the HTTP binding port which does not use SSL.
*
* @return the HTTP binding port which does not use SSL.
* @deprecated Replaced with HTTP_BIND_PORT.getValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public int getHttpBindUnsecurePort() {
return HTTP_BIND_PORT.getValue();
}
/**
* Returns the HTTP binding port which uses SSL.
*
* @return the HTTP binding port which uses SSL.
* @deprecated Replaced with HTTP_BIND_SECURE_PORT.getValue()
*/
@Deprecated // TODO drop in Openfire 4.8.0 or later.
public int getHttpBindSecurePort() {
return HTTP_BIND_SECURE_PORT.getValue();
}
/**
* Returns true if script syntax is enabled. Script syntax allows BOSH to be used in
* environments where clients may be restricted to using a particular server. Instead of using
* standard HTTP Post requests to transmit data, HTTP Get requests are used.
*
* @return true if script syntax is enabled.
* @see <a href="http://www.xmpp.org/extensions/xep-0124.html#script">BOSH: Alternative Script
* Syntax</a>
*/
public boolean isScriptSyntaxEnabled() {
return JiveGlobals.getBooleanProperty("xmpp.httpbind.scriptSyntax.enabled", false);
}
/**
* Enables or disables script syntax.
*
* @param isEnabled true to enable script syntax and false to disable it.
* @see #isScriptSyntaxEnabled()
* @see <a href="http://www.xmpp.org/extensions/xep-0124.html#script">BOSH: Alternative Script
* Syntax</a>
*/
public void setScriptSyntaxEnabled(boolean isEnabled) {
final String property = "xmpp.httpbind.scriptSyntax.enabled";
if(!isEnabled) {
JiveGlobals.deleteProperty(property);
}
else {
JiveGlobals.setProperty(property, String.valueOf(isEnabled));
}
}
/**
* Static reference for {@link #restartServer()} that can be used as a listener of a {@link SystemProperty}.
* The provided argument is ignored.
*/
public static void restart(Object ignored) {
if (getInstance() != null) {
getInstance().restartServer();
}
}
private synchronized void restartServer() {
stop();
start();
}
@Override
public void storeContentChanged( CertificateStore store )
{
restartServer();
}
}
| 17,332 |
513 | // https://www.interviewbit.com/problems/number-of-1-bits/
int Solution::numSetBits(unsigned int A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int sol = 0;
while(A/2 != 0){
if(A%2 != 0){
sol++;
}
A = A/2;
}
if(A%2 != 0){
sol++;
}
return sol;
}
| 228 |
935 | /*
* Copyright 2017-2019 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.springframework.cloud.dataflow.shell.command.support;
import org.springframework.util.Assert;
/**
* @author <NAME>
*/
public enum RoleType {
VIEW("ROLE_VIEW", "view role"),
CREATE("ROLE_CREATE", "role for create operations"),
MANAGE("ROLE_MANAGE", "role for the boot management endpoints"),
MODIFY("ROLE_MODIFY", "role for modify operations"),
DEPLOY("ROLE_DEPLOY", "role for deploy operations"),
DESTROY("ROLE_DESTROY", "role for destroy operations"),
SCHEDULE("ROLE_SCHEDULE", "role for scheduling operations");
private String key;
private String name;
/**
* Constructor.
*/
RoleType(final String key, final String name) {
this.key = key;
this.name = name;
}
/**
* Returns a Shell-specific role for the passed in role key.
*
* @param role Must not be null or empty
* @return The shell role. Never null.
*/
public static RoleType fromKey(String role) {
Assert.hasText(role, "Parameter role must not be null or empty.");
for (RoleType roleType : RoleType.values()) {
if (roleType.getKey().equals(role)) {
return roleType;
}
}
throw new IllegalArgumentException("Unable to map role " + role);
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
}
| 589 |
2,180 | /*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA 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.archive.net.chrome;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class ChromeRequest {
private final ChromeWindow window;
private final String id;
private JSONObject requestJson;
private JSONObject rawRequestHeaders;
private JSONObject responseJson;
private JSONObject rawResponseHeaders;
private String responseHeadersText;
private final long beginTime = System.currentTimeMillis();
private boolean responseFulfilledByInterception;
public ChromeRequest(ChromeWindow window, String id) {
this.window = window;
this.id = id;
}
void setRawRequestHeaders(JSONObject rawRequestHeaders) {
this.rawRequestHeaders = rawRequestHeaders;
}
void setResponseJson(JSONObject responseJson) {
this.responseJson = responseJson;
}
void setRawResponseHeaders(JSONObject headers) {
this.rawResponseHeaders = headers;
}
void setResponseHeadersText(String responseHeadersText) {
this.responseHeadersText = responseHeadersText;
}
public String getUrl() {
return requestJson.getString("url");
}
public byte[] getResponseBody() {
JSONObject reply = window.call("Network.getResponseBody", "requestId", id);
byte[] body;
if (reply.getBoolean("base64Encoded")) {
body = Base64.getDecoder().decode(reply.getString("body"));
} else {
body = reply.getString("body").getBytes(StandardCharsets.UTF_8);
}
return body;
}
public String getRequestHeader() {
if (responseJson != null && responseJson.has("requestHeadersText")) {
return responseJson.getString("requestHeadersText");
}
StringBuilder builder = new StringBuilder();
builder.append(requestJson.getString("method"));
builder.append(' ');
builder.append(getUrl());
builder.append(" HTTP/1.1\r\n");
formatHeaders(builder, requestJson.getJSONObject("headers"), rawRequestHeaders);
return builder.toString();
}
public byte[] getRequestBody() {
if (requestJson.has("postData")) {
return requestJson.getString("postData").getBytes(StandardCharsets.UTF_8);
} else {
return new byte[0];
}
}
public String getResponseHeader() {
if (responseHeadersText != null) {
return responseHeadersText;
} else if (responseJson.has("headersText")) {
return responseJson.getString("headersText");
}
StringBuilder builder = new StringBuilder();
if (responseJson.getString("protocol").equals("http/1.0")) {
builder.append("HTTP/1.0");
} else {
builder.append("HTTP/1.1");
}
builder.append(getStatus());
builder.append(" ");
builder.append(responseJson.getString("statusText"));
builder.append("\r\n");
formatHeaders(builder, responseJson.getJSONObject("headers"), rawResponseHeaders);
return builder.toString();
}
private void formatHeaders(StringBuilder builder, JSONObject headers, JSONObject rawHeaders) {
if (rawHeaders != null) {
headers = rawHeaders;
}
for (Object key : headers.keySet()) {
builder.append(key);
builder.append(": ");
builder.append(headers.getString((String) key));
builder.append("\r\n");
}
builder.append("\r\n");
}
public String getMethod() {
return requestJson.getString("method");
}
public int getStatus() {
return responseJson.getInt("status");
}
public String getResponseContentType() {
return responseJson.getString("mimeType");
}
public long getBeginTime() {
return beginTime;
}
public String getRemoteIPAddress() {
if (responseJson.has("remoteIPAddress")) {
return responseJson.getString("remoteIPAddress");
} else {
return null;
}
}
void setRequestJson(JSONObject requestJson) {
this.requestJson = requestJson;
}
void setResponseFulfilledByInterception(boolean responseFulfilledByInterception) {
this.responseFulfilledByInterception = responseFulfilledByInterception;
}
public boolean isResponseFulfilledByInterception() {
return responseFulfilledByInterception;
}
}
| 2,006 |
1,179 | <gh_stars>1000+
// SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2014-2019, Linaro Limited
*/
#include <assert.h>
#include <crypto/crypto.h>
#include <crypto/crypto_impl.h>
#include <stdlib.h>
#include <string.h>
#include <tee_api_types.h>
#include <tee/tee_cryp_utl.h>
#include <util.h>
/* From libtomcrypt doc:
* Ciphertext stealing is a method of dealing with messages
* in CBC mode which are not a multiple of the block
* length. This is accomplished by encrypting the last
* ciphertext block in ECB mode, and XOR'ing the output
* against the last partial block of plaintext. LibTomCrypt
* does not support this mode directly but it is fairly
* easy to emulate with a call to the cipher's
* ecb encrypt() callback function.
* The more sane way to deal with partial blocks is to pad
* them with zeroes, and then use CBC normally
*/
/*
* From Global Platform: CTS = CBC-CS3
*/
struct cts_ctx {
struct crypto_cipher_ctx ctx;
struct crypto_cipher_ctx *ecb;
struct crypto_cipher_ctx *cbc;
TEE_OperationMode mode;
};
static const struct crypto_cipher_ops cts_ops;
static struct cts_ctx *to_cts_ctx(struct crypto_cipher_ctx *ctx)
{
assert(ctx && ctx->ops == &cts_ops);
return container_of(ctx, struct cts_ctx, ctx);
}
static TEE_Result cts_init(struct crypto_cipher_ctx *ctx,
TEE_OperationMode mode, const uint8_t *key1,
size_t key1_len, const uint8_t *key2,
size_t key2_len, const uint8_t *iv, size_t iv_len)
{
TEE_Result res = TEE_SUCCESS;
struct cts_ctx *c = to_cts_ctx(ctx);
c->mode = mode;
res = crypto_cipher_init(c->ecb, mode, key1, key1_len, key2, key2_len,
iv, iv_len);
if (res)
return res;
return crypto_cipher_init(c->cbc, mode, key1, key1_len, key2, key2_len,
iv, iv_len);
}
/*
* From http://en.wikipedia.org/wiki/Ciphertext_stealing
* CBC ciphertext stealing encryption using a standard
* CBC interface:
* 1. Pad the last partial plaintext block with 0.
* 2. Encrypt the whole padded plaintext using the
* standard CBC mode.
* 3. Swap the last two ciphertext blocks.
* 4. Truncate the ciphertext to the length of the
* original plaintext.
*
* CBC ciphertext stealing decryption using a standard
* CBC interface
* 1. Dn = Decrypt (K, Cn-1). Decrypt the second to last
* ciphertext block.
* 2. Cn = Cn || Tail (Dn, B-M). Pad the ciphertext to the
* nearest multiple of the block size using the last
* B-M bits of block cipher decryption of the
* second-to-last ciphertext block.
* 3. Swap the last two ciphertext blocks.
* 4. Decrypt the (modified) ciphertext using the standard
* CBC mode.
* 5. Truncate the plaintext to the length of the original
* ciphertext.
*/
static TEE_Result cbc_cts_update(void *cbc_ctx, void *ecb_ctx,
TEE_OperationMode mode, bool last_block,
const uint8_t *data, size_t len, uint8_t *dst)
{
TEE_Result res = TEE_SUCCESS;
uint8_t tmp2_block[64] = { 0 };
uint8_t tmp_block[64] = { 0 };
int len_last_block = 0;
int block_size = 16;
int nb_blocks = 0;
if (!last_block)
return tee_do_cipher_update(cbc_ctx, TEE_ALG_AES_CBC_NOPAD,
mode, last_block, data, len, dst);
/* Compute the last block length and check constraints */
nb_blocks = (len + block_size - 1) / block_size;
if (nb_blocks < 2)
return TEE_ERROR_BAD_STATE;
len_last_block = len % block_size;
if (len_last_block == 0)
len_last_block = block_size;
if (mode == TEE_MODE_ENCRYPT) {
memcpy(tmp_block,
data + ((nb_blocks - 1) * block_size),
len_last_block);
memset(tmp_block + len_last_block,
0,
block_size - len_last_block);
res = tee_do_cipher_update(cbc_ctx, TEE_ALG_AES_CBC_NOPAD,
mode, 0, data,
(nb_blocks - 1) * block_size, dst);
if (res != TEE_SUCCESS)
return res;
memcpy(dst + (nb_blocks - 1) * block_size,
dst + (nb_blocks - 2) * block_size,
len_last_block);
res = tee_do_cipher_update(cbc_ctx, TEE_ALG_AES_CBC_NOPAD,
mode, 0, tmp_block, block_size,
dst + (nb_blocks - 2) * block_size);
if (res != TEE_SUCCESS)
return res;
} else {
/* 1. Decrypt the second to last ciphertext block */
res = tee_do_cipher_update(ecb_ctx, TEE_ALG_AES_ECB_NOPAD,
mode, 0,
data + (nb_blocks - 2) * block_size,
block_size, tmp2_block);
if (res != TEE_SUCCESS)
return res;
/* 2. Cn = Cn || Tail (Dn, B-M) */
memcpy(tmp_block, data + ((nb_blocks - 1) * block_size),
len_last_block);
memcpy(tmp_block + len_last_block, tmp2_block + len_last_block,
block_size - len_last_block);
/* 3. Swap the last two ciphertext blocks */
/* done by passing the correct buffers in step 4. */
/* 4. Decrypt the (modified) ciphertext */
if (nb_blocks > 2) {
res = tee_do_cipher_update(cbc_ctx,
TEE_ALG_AES_CBC_NOPAD, mode,
0, data,
(nb_blocks - 2) *
block_size, dst);
if (res != TEE_SUCCESS)
return res;
}
res = tee_do_cipher_update(cbc_ctx, TEE_ALG_AES_CBC_NOPAD,
mode, 0, tmp_block, block_size,
dst +
((nb_blocks - 2) * block_size));
if (res != TEE_SUCCESS)
return res;
res = tee_do_cipher_update(cbc_ctx, TEE_ALG_AES_CBC_NOPAD,
mode, 0, data +
((nb_blocks - 2) * block_size),
block_size, tmp_block);
if (res != TEE_SUCCESS)
return res;
/* 5. Truncate the plaintext */
memcpy(dst + (nb_blocks - 1) * block_size, tmp_block,
len_last_block);
}
return TEE_SUCCESS;
}
static TEE_Result cts_update(struct crypto_cipher_ctx *ctx, bool last_block,
const uint8_t *data, size_t len, uint8_t *dst)
{
struct cts_ctx *c = to_cts_ctx(ctx);
return cbc_cts_update(c->cbc, c->ecb, c->mode, last_block, data, len,
dst);
}
static void cts_final(struct crypto_cipher_ctx *ctx)
{
struct cts_ctx *c = to_cts_ctx(ctx);
crypto_cipher_final(c->cbc);
crypto_cipher_final(c->ecb);
}
static void cts_free_ctx(struct crypto_cipher_ctx *ctx)
{
struct cts_ctx *c = to_cts_ctx(ctx);
crypto_cipher_free_ctx(c->cbc);
crypto_cipher_free_ctx(c->ecb);
free(c);
}
static void cts_copy_state(struct crypto_cipher_ctx *dst_ctx,
struct crypto_cipher_ctx *src_ctx)
{
struct cts_ctx *src = to_cts_ctx(src_ctx);
struct cts_ctx *dst = to_cts_ctx(dst_ctx);
crypto_cipher_copy_state(dst->cbc, src->cbc);
crypto_cipher_copy_state(dst->ecb, src->ecb);
dst->mode = src->mode;
}
static const struct crypto_cipher_ops cts_ops = {
.init = cts_init,
.update = cts_update,
.final = cts_final,
.free_ctx = cts_free_ctx,
.copy_state = cts_copy_state,
};
TEE_Result crypto_aes_cts_alloc_ctx(struct crypto_cipher_ctx **ctx)
{
TEE_Result res = TEE_SUCCESS;
struct cts_ctx *c = calloc(1, sizeof(*c));
if (!c)
return TEE_ERROR_OUT_OF_MEMORY;
res = crypto_aes_ecb_alloc_ctx(&c->ecb);
if (res)
goto err;
res = crypto_aes_cbc_alloc_ctx(&c->cbc);
if (res)
goto err;
c->ctx.ops = &cts_ops;
*ctx = &c->ctx;
return TEE_SUCCESS;
err:
crypto_cipher_free_ctx(c->ecb);
free(c);
return res;
}
| 3,066 |
460 | <filename>playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java<gh_stars>100-1000
/*
* Copyright (c) Microsoft Corporation.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.playwright.impl;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.microsoft.playwright.ElementHandle;
import com.microsoft.playwright.JSHandle;
import java.util.HashMap;
import java.util.Map;
import static com.microsoft.playwright.impl.Serialization.*;
public class JSHandleImpl extends ChannelOwner implements JSHandle {
private String preview;
public JSHandleImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) {
super(parent, type, guid, initializer);
this.preview = initializer.get("preview").getAsString();
}
@Override
public ElementHandle asElement() {
return null;
}
@Override
public void dispose() {
withLogging("JSHandle.dispose", () -> sendMessage("dispose"));
}
@Override
public Object evaluate(String pageFunction, Object arg) {
return withLogging("JSHandle.evaluate", () -> {
JsonObject params = new JsonObject();
params.addProperty("expression", pageFunction);
params.addProperty("world", "main");
params.add("arg", gson().toJsonTree(serializeArgument(arg)));
JsonElement json = sendMessage("evaluateExpression", params);
SerializedValue value = gson().fromJson(json.getAsJsonObject().get("value"), SerializedValue.class);
return deserialize(value);
});
}
@Override
public JSHandle evaluateHandle(String pageFunction, Object arg) {
return withLogging("JSHandle.evaluateHandle", () -> {
JsonObject params = new JsonObject();
params.addProperty("expression", pageFunction);
params.addProperty("world", "main");
params.add("arg", gson().toJsonTree(serializeArgument(arg)));
JsonElement json = sendMessage("evaluateExpressionHandle", params);
return connection.getExistingObject(json.getAsJsonObject().getAsJsonObject("handle").get("guid").getAsString());
});
}
@Override
public Map<String, JSHandle> getProperties() {
return withLogging("JSHandle.getProperties", () -> {
JsonObject json = sendMessage("getPropertyList").getAsJsonObject();
Map<String, JSHandle> result = new HashMap<>();
for (JsonElement e : json.getAsJsonArray("properties")) {
JsonObject item = e.getAsJsonObject();
JSHandle value = connection.getExistingObject(item.getAsJsonObject("value").get("guid").getAsString());
result.put(item.get("name").getAsString(), value);
}
return result;
});
}
@Override
public JSHandle getProperty(String propertyName) {
return withLogging("JSHandle.getProperty", () -> {
JsonObject params = new JsonObject();
params.addProperty("name", propertyName);
JsonObject json = sendMessage("getProperty", params).getAsJsonObject();
return connection.getExistingObject(json.getAsJsonObject("handle").get("guid").getAsString());
});
}
@Override
public Object jsonValue() {
return withLogging("JSHandle.jsonValue", () -> {
JsonObject json = sendMessage("jsonValue").getAsJsonObject();
SerializedValue value = gson().fromJson(json.get("value"), SerializedValue.class);
return deserialize(value);
});
}
@Override
void handleEvent(String event, JsonObject parameters) {
if ("previewUpdated".equals(event)) {
preview = parameters.get("preview").getAsString();
}
super.handleEvent(event, parameters);
}
@Override
public String toString() {
return preview;
}
}
| 1,388 |
471 | <filename>examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/tests/geometry/region.cpp<gh_stars>100-1000
///////////////////////////////////////////////////////////////////////////////
// Name: tests/geometry/region.cpp
// Purpose: wxRegion unit test
// Author: <NAME>
// Created: 2011-10-12
// Copyright: (c) 2011 <NAME> <<EMAIL>>
///////////////////////////////////////////////////////////////////////////////
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "testprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/region.h"
#endif // WX_PRECOMP
#include "wx/iosfwrap.h"
// ----------------------------------------------------------------------------
// helper functions
// ----------------------------------------------------------------------------
namespace
{
// This function could be easily added to wxRegionIterator itself, where it
// could be implemented far more efficiently as all major platforms store the
// number of rectangles anyhow, but as we only use it for debugging purposes,
// just keep it here for now.
unsigned GetRectsCount(const wxRegion& rgn)
{
unsigned count = 0;
for ( wxRegionIterator iter(rgn); iter.HaveRects(); ++iter )
count++;
return count;
}
} // anonymous namespace
// this operator is needed to use CPPUNIT_ASSERT_EQUAL with wxRegions
std::ostream& operator<<(std::ostream& os, const wxRegion& rgn)
{
wxRect r = rgn.GetBox();
os << "# rects = " << GetRectsCount(rgn)
<< "; bounding box {"
<< r.x << ", " << r.y << ", " << r.width << ", " << r.height
<< "}";
return os;
}
// ----------------------------------------------------------------------------
// test class
// ----------------------------------------------------------------------------
class RegionTestCase : public CppUnit::TestCase
{
public:
RegionTestCase() { }
private:
CPPUNIT_TEST_SUITE( RegionTestCase );
CPPUNIT_TEST( Validity );
CPPUNIT_TEST( Intersect );
CPPUNIT_TEST_SUITE_END();
void Validity();
void Intersect();
wxDECLARE_NO_COPY_CLASS(RegionTestCase);
};
// register in the unnamed registry so that these tests are run by default
CPPUNIT_TEST_SUITE_REGISTRATION( RegionTestCase );
// also include in its own registry so that these tests can be run alone
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( RegionTestCase, "RegionTestCase" );
void RegionTestCase::Validity()
{
wxRegion r;
CPPUNIT_ASSERT_MESSAGE
(
"Default constructed region must be invalid",
!r.IsOk()
);
CPPUNIT_ASSERT_MESSAGE
(
"Invalid region should be empty",
r.IsEmpty()
);
// Offsetting an invalid region doesn't make sense.
WX_ASSERT_FAILS_WITH_ASSERT( r.Offset(1, 1) );
CPPUNIT_ASSERT_MESSAGE
(
"Combining with a valid region should create a valid region",
r.Union(0, 0, 10, 10)
);
CPPUNIT_ASSERT_EQUAL_MESSAGE
(
"Union() with invalid region should give the same region",
wxRegion(0, 0, 10, 10),
r
);
}
void RegionTestCase::Intersect()
{
const wxPoint points1[] = {
wxPoint(310, 392),
wxPoint(270, 392),
wxPoint(270, 421),
wxPoint(310, 421)
};
wxRegion region1(WXSIZEOF(points1), points1);
const wxPoint points2[] = {
wxPoint(54, 104),
wxPoint(85, 82),
wxPoint(68, 58),
wxPoint(37, 80)
};
wxRegion region2(4,points2);
CPPUNIT_ASSERT( region1.Intersect(region2) );
CPPUNIT_ASSERT( region1.IsEmpty() );
}
| 1,359 |
605 | <reponame>MaxLabHub/GlideBitmapPool<filename>glide-bitmap-pool/src/main/java/com/glidebitmappool/internal/SizeConfigStrategy.java
/*
* Copyright (C) 2016 <NAME>
* Copyright (C) 2011 Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glidebitmappool.internal;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
/**
* Created by amitshekhar on 17/06/16.
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public class SizeConfigStrategy implements LruPoolStrategy {
private static final int MAX_SIZE_MULTIPLE = 8;
private static final Bitmap.Config[] ARGB_8888_IN_CONFIGS =
new Bitmap.Config[]{
Bitmap.Config.ARGB_8888,
// The value returned by Bitmaps with the hidden Bitmap config.
null,
};
// We probably could allow ARGB_4444 and RGB_565 to decode into each other, but ARGB_4444 is
// deprecated and we'd rather be safe.
private static final Bitmap.Config[] RGB_565_IN_CONFIGS =
new Bitmap.Config[]{Bitmap.Config.RGB_565};
private static final Bitmap.Config[] ARGB_4444_IN_CONFIGS =
new Bitmap.Config[]{Bitmap.Config.ARGB_4444};
private static final Bitmap.Config[] ALPHA_8_IN_CONFIGS =
new Bitmap.Config[]{Bitmap.Config.ALPHA_8};
private final KeyPool keyPool = new KeyPool();
private final GroupedLinkedMap<Key, Bitmap> groupedMap = new GroupedLinkedMap<>();
private final Map<Bitmap.Config, NavigableMap<Integer, Integer>> sortedSizes = new HashMap<>();
@Override
public void put(Bitmap bitmap) {
int size = Util.getBitmapByteSize(bitmap);
Key key = keyPool.get(size, bitmap.getConfig());
groupedMap.put(key, bitmap);
NavigableMap<Integer, Integer> sizes = getSizesForConfig(bitmap.getConfig());
Integer current = sizes.get(key.size);
sizes.put(key.size, current == null ? 1 : current + 1);
}
@Override
public Bitmap get(int width, int height, Bitmap.Config config) {
int size = Util.getBitmapByteSize(width, height, config);
Key bestKey = findBestKey(size, config);
Bitmap result = groupedMap.get(bestKey);
if (result != null) {
// Decrement must be called before reconfigure.
decrementBitmapOfSize(bestKey.size, result);
result.reconfigure(width, height,
result.getConfig() != null ? result.getConfig() : Bitmap.Config.ARGB_8888);
}
return result;
}
private Key findBestKey(int size, Bitmap.Config config) {
Key result = keyPool.get(size, config);
for (Bitmap.Config possibleConfig : getInConfigs(config)) {
NavigableMap<Integer, Integer> sizesForPossibleConfig = getSizesForConfig(possibleConfig);
Integer possibleSize = sizesForPossibleConfig.ceilingKey(size);
if (possibleSize != null && possibleSize <= size * MAX_SIZE_MULTIPLE) {
if (possibleSize != size
|| (possibleConfig == null ? config != null : !possibleConfig.equals(config))) {
keyPool.offer(result);
result = keyPool.get(possibleSize, possibleConfig);
}
break;
}
}
return result;
}
@Override
public Bitmap removeLast() {
Bitmap removed = groupedMap.removeLast();
if (removed != null) {
int removedSize = Util.getBitmapByteSize(removed);
decrementBitmapOfSize(removedSize, removed);
}
return removed;
}
private void decrementBitmapOfSize(Integer size, Bitmap removed) {
Bitmap.Config config = removed.getConfig();
NavigableMap<Integer, Integer> sizes = getSizesForConfig(config);
Integer current = sizes.get(size);
if (current == null) {
throw new NullPointerException("Tried to decrement empty size"
+ ", size: " + size
+ ", removed: " + logBitmap(removed)
+ ", this: " + this);
}
if (current == 1) {
sizes.remove(size);
} else {
sizes.put(size, current - 1);
}
}
private NavigableMap<Integer, Integer> getSizesForConfig(Bitmap.Config config) {
NavigableMap<Integer, Integer> sizes = sortedSizes.get(config);
if (sizes == null) {
sizes = new TreeMap<>();
sortedSizes.put(config, sizes);
}
return sizes;
}
@Override
public String logBitmap(Bitmap bitmap) {
int size = Util.getBitmapByteSize(bitmap);
return getBitmapString(size, bitmap.getConfig());
}
@Override
public String logBitmap(int width, int height, Bitmap.Config config) {
int size = Util.getBitmapByteSize(width, height, config);
return getBitmapString(size, config);
}
@Override
public int getSize(Bitmap bitmap) {
return Util.getBitmapByteSize(bitmap);
}
@Override
public String toString() {
StringBuilder sb =
new StringBuilder()
.append("SizeConfigStrategy{groupedMap=")
.append(groupedMap)
.append(", sortedSizes=(");
for (Map.Entry<Bitmap.Config, NavigableMap<Integer, Integer>> entry : sortedSizes.entrySet()) {
sb.append(entry.getKey()).append('[').append(entry.getValue()).append("], ");
}
if (!sortedSizes.isEmpty()) {
sb.replace(sb.length() - 2, sb.length(), "");
}
return sb.append(")}").toString();
}
// Visible for testing.
static class KeyPool extends BaseKeyPool<Key> {
public Key get(int size, Bitmap.Config config) {
Key result = get();
result.init(size, config);
return result;
}
@Override
protected Key create() {
return new Key(this);
}
}
// Visible for testing.
static final class Key implements Poolable {
private final KeyPool pool;
private int size;
private Bitmap.Config config;
public Key(KeyPool pool) {
this.pool = pool;
}
// Visible for testing.
Key(KeyPool pool, int size, Bitmap.Config config) {
this(pool);
init(size, config);
}
public void init(int size, Bitmap.Config config) {
this.size = size;
this.config = config;
}
@Override
public void offer() {
pool.offer(this);
}
@Override
public String toString() {
return getBitmapString(size, config);
}
@Override
public boolean equals(Object o) {
if (o instanceof Key) {
Key other = (Key) o;
return size == other.size
&& Util.bothNullOrEqual(config, other.config);
}
return false;
}
@Override
public int hashCode() {
int result = size;
result = 31 * result + (config != null ? config.hashCode() : 0);
return result;
}
}
private static String getBitmapString(int size, Bitmap.Config config) {
return "[" + size + "](" + config + ")";
}
private static Bitmap.Config[] getInConfigs(Bitmap.Config requested) {
switch (requested) {
case ARGB_8888:
return ARGB_8888_IN_CONFIGS;
case RGB_565:
return RGB_565_IN_CONFIGS;
case ARGB_4444:
return ARGB_4444_IN_CONFIGS;
case ALPHA_8:
return ALPHA_8_IN_CONFIGS;
default:
return new Bitmap.Config[]{requested};
}
}
}
| 3,819 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-gwc8-4x3p-h96j",
"modified": "2022-05-02T00:10:05Z",
"published": "2022-05-02T00:10:05Z",
"aliases": [
"CVE-2008-4432"
],
"details": "Cross-site scripting (XSS) vulnerability in search.php in the RMSOFT MiniShop module 1.0 for Xoops allows remote attackers to inject arbitrary web script or HTML via the itemsxpag parameter.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2008-4432"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/44374"
},
{
"type": "WEB",
"url": "http://lostmon.blogspot.com/2008/08/rmsoft-minishop-module-multiple.html"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/30616"
}
],
"database_specific": {
"cwe_ids": [
"CWE-79"
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 470 |
1,144 | <filename>backend/de.metas.vertical.pharma.securpharm/src/main/java-gen/de/metas/vertical/pharma/securpharm/model/I_M_Securpharm_Log.java
package de.metas.vertical.pharma.securpharm.model;
/** Generated Interface for M_Securpharm_Log
* @author Adempiere (generated)
*/
@SuppressWarnings("javadoc")
public interface I_M_Securpharm_Log
{
/** TableName=M_Securpharm_Log */
public static final String Table_Name = "M_Securpharm_Log";
/** AD_Table_ID=541364 */
// public static final int Table_ID = org.compiere.model.MTable.getTable_ID(Table_Name);
// org.compiere.util.KeyNamePair Model = new org.compiere.util.KeyNamePair(Table_ID, Table_Name);
/** AccessLevel = 7 - System - Client - Org
*/
// java.math.BigDecimal accessLevel = java.math.BigDecimal.valueOf(7);
/** Load Meta Data */
/**
* Get Mandant.
* Mandant für diese Installation.
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getAD_Client_ID();
/** Column definition for AD_Client_ID */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, org.compiere.model.I_AD_Client> COLUMN_AD_Client_ID = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, org.compiere.model.I_AD_Client>(I_M_Securpharm_Log.class, "AD_Client_ID", org.compiere.model.I_AD_Client.class);
/** Column name AD_Client_ID */
public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/**
* Set System-Problem.
* Automatically created or manually entered System Issue
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setAD_Issue_ID (int AD_Issue_ID);
/**
* Get System-Problem.
* Automatically created or manually entered System Issue
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getAD_Issue_ID();
public org.compiere.model.I_AD_Issue getAD_Issue();
public void setAD_Issue(org.compiere.model.I_AD_Issue AD_Issue);
/** Column definition for AD_Issue_ID */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, org.compiere.model.I_AD_Issue> COLUMN_AD_Issue_ID = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, org.compiere.model.I_AD_Issue>(I_M_Securpharm_Log.class, "AD_Issue_ID", org.compiere.model.I_AD_Issue.class);
/** Column name AD_Issue_ID */
public static final String COLUMNNAME_AD_Issue_ID = "AD_Issue_ID";
/**
* Set Sektion.
* Organisatorische Einheit des Mandanten
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setAD_Org_ID (int AD_Org_ID);
/**
* Get Sektion.
* Organisatorische Einheit des Mandanten
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getAD_Org_ID();
/** Column definition for AD_Org_ID */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, org.compiere.model.I_AD_Org> COLUMN_AD_Org_ID = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, org.compiere.model.I_AD_Org>(I_M_Securpharm_Log.class, "AD_Org_ID", org.compiere.model.I_AD_Org.class);
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/**
* Get Erstellt.
* Datum, an dem dieser Eintrag erstellt wurde
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public java.sql.Timestamp getCreated();
/** Column definition for Created */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_Created = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "Created", null);
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/**
* Get Erstellt durch.
* Nutzer, der diesen Eintrag erstellt hat
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getCreatedBy();
/** Column definition for CreatedBy */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, org.compiere.model.I_AD_User> COLUMN_CreatedBy = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, org.compiere.model.I_AD_User>(I_M_Securpharm_Log.class, "CreatedBy", org.compiere.model.I_AD_User.class);
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/**
* Set Aktiv.
* Der Eintrag ist im System aktiv
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setIsActive (boolean IsActive);
/**
* Get Aktiv.
* Der Eintrag ist im System aktiv
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public boolean isActive();
/** Column definition for IsActive */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_IsActive = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "IsActive", null);
/** Column name IsActive */
public static final String COLUMNNAME_IsActive = "IsActive";
/**
* Set Fehler.
* Ein Fehler ist bei der Durchführung aufgetreten
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setIsError (boolean IsError);
/**
* Get Fehler.
* Ein Fehler ist bei der Durchführung aufgetreten
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public boolean isError();
/** Column definition for IsError */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_IsError = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "IsError", null);
/** Column name IsError */
public static final String COLUMNNAME_IsError = "IsError";
/**
* Set Securpharm Aktion Ergebnise.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setM_Securpharm_Action_Result_ID (int M_Securpharm_Action_Result_ID);
/**
* Get Securpharm Aktion Ergebnise.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getM_Securpharm_Action_Result_ID();
public de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Action_Result getM_Securpharm_Action_Result();
public void setM_Securpharm_Action_Result(de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Action_Result M_Securpharm_Action_Result);
/** Column definition for M_Securpharm_Action_Result_ID */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Action_Result> COLUMN_M_Securpharm_Action_Result_ID = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Action_Result>(I_M_Securpharm_Log.class, "M_Securpharm_Action_Result_ID", de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Action_Result.class);
/** Column name M_Securpharm_Action_Result_ID */
public static final String COLUMNNAME_M_Securpharm_Action_Result_ID = "M_Securpharm_Action_Result_ID";
/**
* Set Securpharm-Protokoll.
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setM_Securpharm_Log_ID (int M_Securpharm_Log_ID);
/**
* Get Securpharm-Protokoll.
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getM_Securpharm_Log_ID();
/** Column definition for M_Securpharm_Log_ID */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_M_Securpharm_Log_ID = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "M_Securpharm_Log_ID", null);
/** Column name M_Securpharm_Log_ID */
public static final String COLUMNNAME_M_Securpharm_Log_ID = "M_Securpharm_Log_ID";
/**
* Set Securpharm Produktdaten Ergebnise.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setM_Securpharm_Productdata_Result_ID (int M_Securpharm_Productdata_Result_ID);
/**
* Get Securpharm Produktdaten Ergebnise.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getM_Securpharm_Productdata_Result_ID();
public de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result getM_Securpharm_Productdata_Result();
public void setM_Securpharm_Productdata_Result(de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result M_Securpharm_Productdata_Result);
/** Column definition for M_Securpharm_Productdata_Result_ID */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result> COLUMN_M_Securpharm_Productdata_Result_ID = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result>(I_M_Securpharm_Log.class, "M_Securpharm_Productdata_Result_ID", de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result.class);
/** Column name M_Securpharm_Productdata_Result_ID */
public static final String COLUMNNAME_M_Securpharm_Productdata_Result_ID = "M_Securpharm_Productdata_Result_ID";
/**
* Set Anfrage Ende.
*
* <br>Type: DateTime
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setRequestEndTime (java.sql.Timestamp RequestEndTime);
/**
* Get Anfrage Ende.
*
* <br>Type: DateTime
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.sql.Timestamp getRequestEndTime();
/** Column definition for RequestEndTime */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_RequestEndTime = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "RequestEndTime", null);
/** Column name RequestEndTime */
public static final String COLUMNNAME_RequestEndTime = "RequestEndTime";
/**
* Set Request Method.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setRequestMethod (java.lang.String RequestMethod);
/**
* Get Request Method.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.lang.String getRequestMethod();
/** Column definition for RequestMethod */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_RequestMethod = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "RequestMethod", null);
/** Column name RequestMethod */
public static final String COLUMNNAME_RequestMethod = "RequestMethod";
/**
* Set Anfrage Start .
*
* <br>Type: DateTime
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setRequestStartTime (java.sql.Timestamp RequestStartTime);
/**
* Get Anfrage Start .
*
* <br>Type: DateTime
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.sql.Timestamp getRequestStartTime();
/** Column definition for RequestStartTime */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_RequestStartTime = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "RequestStartTime", null);
/** Column name RequestStartTime */
public static final String COLUMNNAME_RequestStartTime = "RequestStartTime";
/**
* Set Abfrage.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setRequestUrl (java.lang.String RequestUrl);
/**
* Get Abfrage.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.lang.String getRequestUrl();
/** Column definition for RequestUrl */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_RequestUrl = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "RequestUrl", null);
/** Column name RequestUrl */
public static final String COLUMNNAME_RequestUrl = "RequestUrl";
/**
* Set Antwort .
*
* <br>Type: Integer
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setResponseCode (int ResponseCode);
/**
* Get Antwort .
*
* <br>Type: Integer
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getResponseCode();
/** Column definition for ResponseCode */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_ResponseCode = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "ResponseCode", null);
/** Column name ResponseCode */
public static final String COLUMNNAME_ResponseCode = "ResponseCode";
/**
* Set Antwort-Text.
* Anfrage-Antworttext
*
* <br>Type: TextLong
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setResponseText (java.lang.String ResponseText);
/**
* Get Antwort-Text.
* Anfrage-Antworttext
*
* <br>Type: TextLong
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.lang.String getResponseText();
/** Column definition for ResponseText */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_ResponseText = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "ResponseText", null);
/** Column name ResponseText */
public static final String COLUMNNAME_ResponseText = "ResponseText";
/**
* Set TransaktionsID Client.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setTransactionIDClient (java.lang.String TransactionIDClient);
/**
* Get TransaktionsID Client.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.lang.String getTransactionIDClient();
/** Column definition for TransactionIDClient */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_TransactionIDClient = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "TransactionIDClient", null);
/** Column name TransactionIDClient */
public static final String COLUMNNAME_TransactionIDClient = "TransactionIDClient";
/**
* Set TransaktionsID Server.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setTransactionIDServer (java.lang.String TransactionIDServer);
/**
* Get TransaktionsID Server.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.lang.String getTransactionIDServer();
/** Column definition for TransactionIDServer */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_TransactionIDServer = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "TransactionIDServer", null);
/** Column name TransactionIDServer */
public static final String COLUMNNAME_TransactionIDServer = "TransactionIDServer";
/**
* Get Aktualisiert.
* Datum, an dem dieser Eintrag aktualisiert wurde
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public java.sql.Timestamp getUpdated();
/** Column definition for Updated */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object> COLUMN_Updated = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, Object>(I_M_Securpharm_Log.class, "Updated", null);
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/**
* Get Aktualisiert durch.
* Nutzer, der diesen Eintrag aktualisiert hat
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getUpdatedBy();
/** Column definition for UpdatedBy */
public static final org.adempiere.model.ModelColumn<I_M_Securpharm_Log, org.compiere.model.I_AD_User> COLUMN_UpdatedBy = new org.adempiere.model.ModelColumn<I_M_Securpharm_Log, org.compiere.model.I_AD_User>(I_M_Securpharm_Log.class, "UpdatedBy", org.compiere.model.I_AD_User.class);
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
}
| 6,085 |
1,319 | from paddlenlp.transformers import ErniePretrainedModel, BertPretrainedModel, RobertaPretrainedModel
from paddle import nn
import paddle
class ErnieForQuestionAnswering(ErniePretrainedModel):
def __init__(self, ernie):
super(ErnieForQuestionAnswering, self).__init__()
self.ernie = ernie # allow ernie to be config
self.classifier = nn.Linear(self.ernie.config["hidden_size"], 2)
self.classifier_cls = nn.Linear(self.ernie.config["hidden_size"], 2)
self.apply(self.init_weights)
def forward(self,
input_ids,
token_type_ids=None,
position_ids=None,
attention_mask=None):
sequence_output, pooled_output = self.ernie(
input_ids,
token_type_ids=token_type_ids,
position_ids=position_ids,
attention_mask=attention_mask)
logits = self.classifier(sequence_output)
logits = paddle.transpose(logits, perm=[2, 0, 1])
start_logits, end_logits = paddle.unstack(x=logits, axis=0)
cls_logits = self.classifier_cls(pooled_output)
return start_logits, end_logits, cls_logits
class BertForQuestionAnswering(BertPretrainedModel):
def __init__(self, bert):
super(BertForQuestionAnswering, self).__init__()
self.bert = bert # allow bert to be config
self.classifier = nn.Linear(self.bert.config["hidden_size"], 2)
self.classifier_cls = nn.Linear(self.bert.config["hidden_size"], 2)
self.apply(self.init_weights)
def forward(self,
input_ids,
token_type_ids=None,
position_ids=None,
attention_mask=None):
sequence_output, pooled_output = self.bert(
input_ids,
token_type_ids=token_type_ids,
position_ids=position_ids,
attention_mask=attention_mask)
logits = self.classifier(sequence_output)
logits = paddle.transpose(logits, perm=[2, 0, 1])
start_logits, end_logits = paddle.unstack(x=logits, axis=0)
cls_logits = self.classifier_cls(pooled_output)
return start_logits, end_logits, cls_logits
class RobertaForQuestionAnswering(RobertaPretrainedModel):
def __init__(self, roberta):
super(RobertaForQuestionAnswering, self).__init__()
self.roberta = roberta # allow roberta to be config
self.classifier = nn.Linear(self.roberta.config["hidden_size"], 2)
self.classifier_cls = nn.Linear(self.roberta.config["hidden_size"], 2)
self.apply(self.init_weights)
def forward(self,
input_ids,
token_type_ids=None,
position_ids=None,
attention_mask=None):
sequence_output, pooled_output = self.roberta(
input_ids,
token_type_ids=token_type_ids,
position_ids=position_ids,
attention_mask=attention_mask)
logits = self.classifier(sequence_output)
logits = paddle.transpose(logits, perm=[2, 0, 1])
start_logits, end_logits = paddle.unstack(x=logits, axis=0)
cls_logits = self.classifier_cls(pooled_output)
return start_logits, end_logits, cls_logits | 1,520 |
5,169 | <reponame>Gantios/Specs
{
"name": "PinFloyd",
"summary": "MapKit annotations clustering for iOS.",
"version": "1.0.4",
"homepage": "https://github.com/vadymmarkov/PinFloyd",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/vadymmarkov/PinFloyd.git",
"tag": "1.0.4"
},
"social_media_url": "https://twitter.com/vadymmarkov",
"platforms": {
"ios": "9.0",
"tvos": "9.2"
},
"requires_arc": true,
"source_files": "Sources/**/*",
"frameworks": [
"UIKit",
"MapKit"
],
"pod_target_xcconfig": {
"SWIFT_VERSION": "4.0"
}
}
| 288 |
575 | // Copyright (c) 2018 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/login/oobe_configuration.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "chrome/browser/ash/login/configuration_keys.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/oobe_configuration_client.h"
#include "ui/base/ime/chromeos/input_method_manager.h"
#include "ui/base/ime/chromeos/input_method_util.h"
namespace chromeos {
// static
OobeConfiguration* OobeConfiguration::instance = nullptr;
bool OobeConfiguration::skip_check_for_testing_ = false;
OobeConfiguration::OobeConfiguration()
: check_completed_(false),
configuration_(
std::make_unique<base::Value>(base::Value::Type::DICTIONARY)) {
DCHECK(!OobeConfiguration::Get());
OobeConfiguration::instance = this;
}
OobeConfiguration::~OobeConfiguration() {
DCHECK_EQ(instance, this);
OobeConfiguration::instance = nullptr;
}
// static
OobeConfiguration* OobeConfiguration::Get() {
return OobeConfiguration::instance;
}
void OobeConfiguration::AddAndFireObserver(Observer* observer) {
observer_list_.AddObserver(observer);
if (check_completed_) {
observer->OnOobeConfigurationChanged();
}
}
void OobeConfiguration::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
const base::Value& OobeConfiguration::GetConfiguration() const {
return *configuration_.get();
}
bool OobeConfiguration::CheckCompleted() const {
return check_completed_;
}
void OobeConfiguration::ResetConfiguration() {
configuration_ = std::make_unique<base::Value>(base::Value::Type::DICTIONARY);
if (check_completed_) {
NotifyObservers();
}
}
void OobeConfiguration::CheckConfiguration() {
if (skip_check_for_testing_)
return;
DBusThreadManager::Get()
->GetOobeConfigurationClient()
->CheckForOobeConfiguration(
base::BindOnce(&OobeConfiguration::OnConfigurationCheck,
weak_factory_.GetWeakPtr()));
}
void OobeConfiguration::OnConfigurationCheck(bool has_configuration,
const std::string& configuration) {
check_completed_ = true;
if (!has_configuration) {
NotifyObservers();
return;
}
base::JSONReader::ValueWithError parsed_json =
base::JSONReader::ReadAndReturnValueWithError(
configuration, base::JSON_ALLOW_TRAILING_COMMAS);
if (!parsed_json.value) {
LOG(ERROR) << "Error parsing OOBE configuration: "
<< parsed_json.error_message;
} else if (!chromeos::configuration::ValidateConfiguration(
*parsed_json.value)) {
LOG(ERROR) << "Invalid OOBE configuration";
} else {
configuration_ =
base::Value::ToUniquePtrValue(std::move(*parsed_json.value));
UpdateConfigurationValues();
}
NotifyObservers();
}
void OobeConfiguration::UpdateConfigurationValues() {
auto* ime_value = configuration_->FindKeyOfType(configuration::kInputMethod,
base::Value::Type::STRING);
if (ime_value) {
chromeos::input_method::InputMethodManager* imm =
chromeos::input_method::InputMethodManager::Get();
configuration_->SetKey(
configuration::kInputMethod,
base::Value(imm->GetInputMethodUtil()->MigrateInputMethod(
ime_value->GetString())));
}
}
void OobeConfiguration::NotifyObservers() {
for (auto& observer : observer_list_)
observer.OnOobeConfigurationChanged();
}
} // namespace chromeos
| 1,346 |
928 | <filename>pyportify/pkcs1/keys.py<gh_stars>100-1000
import fractions
from . import primitives
from . import exceptions
from .defaults import default_crypto_random
from .primes import get_prime, DEFAULT_ITERATION
class RsaPublicKey(object):
__slots__ = ('n', 'e', 'bit_size', 'byte_size')
def __init__(self, n, e):
self.n = n
self.e = e
self.bit_size = primitives.integer_bit_size(n)
self.byte_size = primitives.integer_byte_size(n)
def __repr__(self):
return '<RsaPublicKey n: %d e: %d bit_size: %d>' % \
(self.n, self.e, self.bit_size)
def rsavp1(self, s):
if not (0 <= s <= self.n-1):
raise exceptions.SignatureRepresentativeOutOfRange
return self.rsaep(s)
def rsaep(self, m):
if not (0 <= m <= self.n-1):
raise exceptions.MessageRepresentativeOutOfRange
return pow(m, self.e, self.n)
class RsaPrivateKey(object):
__slots__ = ('n', 'd', 'bit_size', 'byte_size')
def __init__(self, n, d):
self.n = n
self.d = d
self.bit_size = primitives.integer_bit_size(n)
self.byte_size = primitives.integer_byte_size(n)
def __repr__(self):
return '<RsaPrivateKey n: %d d: %d bit_size: %d>' % \
(self.n, self.d, self.bit_size)
def rsadp(self, c):
if not (0 <= c <= self.n-1):
raise exceptions.CiphertextRepresentativeOutOfRange
return pow(c, self.d, self.n)
def rsasp1(self, m):
if not (0 <= m <= self.n-1):
raise exceptions.MessageRepresentativeOutOfRange
return self.rsadp(m)
class MultiPrimeRsaPrivateKey(object):
__slots__ = ('primes', 'blind', 'blind_inv', 'n', 'e', 'exponents', 'crts',
'bit_size', 'byte_size')
def __init__(self, primes, e, blind=True, rnd=default_crypto_random):
self.primes = primes
self.n = primitives.product(*primes)
self.e = e
self.bit_size = primitives.integer_bit_size(self.n)
self.byte_size = primitives.integer_byte_size(self.n)
self.exponents = []
for prime in primes:
exponent, a, b = primitives.bezout(e, prime-1)
assert b == 1
if exponent < 0:
exponent += prime-1
self.exponents.append(exponent)
self.crts = [1]
R = primes[0]
for prime in primes[1:]:
crt, a, b = primitives.bezout(R, prime)
assert b == 1
R *= prime
self.crts.append(crt)
public = RsaPublicKey(self.n, self.e)
if blind:
while True:
blind_factor = rnd.getrandbits(self.bit_size-1)
self.blind = public.rsaep(blind_factor)
u, v, gcd = primitives.bezout(blind_factor, self.n)
if gcd == 1:
self.blind_inv = u if u > 0 else u + self.n
assert (blind_factor * self.blind_inv) % self.n == 1
break
else:
self.blind = None
self.blind_inv = None
def __repr__(self):
return '<RsaPrivateKey n: %d primes: %s bit_size: %d>' % \
(self.n, self.primes, self.bit_size)
def rsadp(self, c):
if not (0 <= c <= self.n-1):
raise exceptions.CiphertextRepresentativeOutOfRange
R = 1
m = 0
if self.blind:
c = (c * self.blind) % self.n
contents = zip(self.primes, self.exponents, self.crts)
for prime, exponent, crt in contents:
m_i = primitives._pow(c, exponent, prime)
h = ((m_i - m) * crt) % prime
m += R * h
R *= prime
if self.blind_inv:
m = (m * self.blind_inv) % self.n
return m
def rsasp1(self, m):
if not (0 <= m <= self.n-1):
raise exceptions.MessageRepresentativeOutOfRange
return self.rsadp(m)
def generate_key_pair(size=512, number=2, rnd=default_crypto_random,
k=DEFAULT_ITERATION, primality_algorithm=None,
strict_size=True, e=0x10001):
'''Generates an RSA key pair.
size:
the bit size of the modulus, default to 512.
number:
the number of primes to use, default to 2.
rnd:
the random number generator to use, default to SystemRandom from the
random library.
k:
the number of iteration to use for the probabilistic primality
tests.
primality_algorithm:
the primality algorithm to use.
strict_size:
whether to use size as a lower bound or a strict goal.
e:
the public key exponent.
Returns the pair (public_key, private_key).
'''
primes = []
lbda = 1
bits = size // number + 1
n = 1
while len(primes) < number:
if number - len(primes) == 1:
bits = size - primitives.integer_bit_size(n) + 1
prime = get_prime(bits, rnd, k, algorithm=primality_algorithm)
if prime in primes:
continue
if e is not None and fractions.gcd(e, lbda) != 1:
continue
if (strict_size and number - len(primes) == 1 and
primitives.integer_bit_size(n*prime) != size):
continue
primes.append(prime)
n *= prime
lbda *= prime - 1
if e is None:
e = 0x10001
while e < lbda:
if fractions.gcd(e, lbda) == 1:
break
e += 2
assert 3 <= e <= n-1
public = RsaPublicKey(n, e)
private = MultiPrimeRsaPrivateKey(primes, e, blind=True, rnd=rnd)
return public, private
| 2,849 |
1,444 | package org.mage.test.cards.single.lrw;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.player.TestPlayer;
import org.mage.test.serverside.base.CardTestPlayerBase;
/**
* @author Kranken, LevelX2
*/
public class BurrentonForgeTenderTest extends CardTestPlayerBase {
@Test
public void testPreventDamageFromStack() {
// Sacrifice Burrenton Forge-Tender: Prevent all damage a red source of your choice would deal this turn.
addCard(Zone.BATTLEFIELD, playerA, "Burrenton Forge-Tender");
addCard(Zone.BATTLEFIELD, playerA, "Soldier of the Pantheon");
addCard(Zone.HAND, playerB, "Lightning Bolt");
addCard(Zone.BATTLEFIELD, playerB, "Mountain", 1);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerB, "Lightning Bolt", "Soldier of the Pantheon");
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Sacrifice {this}: Prevent all damage a red source of your choice would deal this turn.", TestPlayer.NO_TARGET, "Cast Lightning Bolt");
playerA.addChoice("Lightning Bolt");
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertGraveyardCount(playerB, "Lightning Bolt", 1);
assertGraveyardCount(playerA, "Burrenton Forge-Tender", 1);
assertPermanentCount(playerA, "Soldier of the Pantheon", 1);
}
@Test
public void testPreventDamageFromFlametongueKavu() {
addCard(Zone.BATTLEFIELD, playerA, "Burrenton Forge-Tender");
addCard(Zone.BATTLEFIELD, playerA, "Soldier of the Pantheon");
// When Flametongue Kavu enters the battlefield, it deals 4 damage to target creature.
addCard(Zone.HAND, playerB, "Flametongue Kavu");
addCard(Zone.BATTLEFIELD, playerB, "Mountain", 4);
castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Flametongue Kavu");
addTarget(playerB, "Soldier of the Pantheon");
activateAbility(2, PhaseStep.PRECOMBAT_MAIN, playerA, "Sacrifice {this}: Prevent all damage a red source of your choice would deal this turn.",
TestPlayer.NO_TARGET, "When {this} enters the battlefield, {this} deals 4 damage to target creature.");
playerA.addChoice("Flametongue Kavu");
setStopAt(2, PhaseStep.BEGIN_COMBAT);
execute();
assertPermanentCount(playerB, "Flametongue Kavu", 1);
assertGraveyardCount(playerA, "Burrenton Forge-Tender", 1);
assertPermanentCount(playerA, "Soldier of the Pantheon", 1);
}
@Test
public void testPreventDamageFromFlametongueKavuNotAfterCloudshift() {
addCard(Zone.BATTLEFIELD, playerA, "Burrenton Forge-Tender");
addCard(Zone.BATTLEFIELD, playerA, "Soldier of the Pantheon");
// When Flametongue Kavu enters the battlefield, it deals 4 damage to target creature.
addCard(Zone.HAND, playerB, "Flametongue Kavu");
// Exile target creature you control, then return that card to the battlefield under your control.
addCard(Zone.HAND, playerB, "Cloudshift");
addCard(Zone.BATTLEFIELD, playerB, "Mountain", 1);
addCard(Zone.BATTLEFIELD, playerB, "Plains", 5);
castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Flametongue Kavu");
addTarget(playerB, "Soldier of the Pantheon");
activateAbility(2, PhaseStep.PRECOMBAT_MAIN, playerA, "Sacrifice {this}: Prevent all damage a red source of your choice would deal this turn.",
TestPlayer.NO_TARGET, "When {this} enters the battlefield, {this} deals 4 damage to target creature.");
playerA.addChoice("<NAME>");
castSpell(2, PhaseStep.POSTCOMBAT_MAIN, playerB, "Cloudshift", "Flametongue Kavu");
addTarget(playerB, "Soldier of the Pantheon"); // now the damage may not be prevented because it's a new object
setStopAt(2, PhaseStep.END_TURN);
execute();
assertPermanentCount(playerB, "<NAME>u", 1);
assertGraveyardCount(playerB, "Cloudshift", 1);
assertGraveyardCount(playerA, "Burrenton Forge-Tender", 1);
assertGraveyardCount(playerA, "Soldier of the Pantheon", 1);
}
@Test
public void testPreventDamageFromToken() {
addCard(Zone.BATTLEFIELD, playerA, "Burrenton Forge-Tender");
addCard(Zone.BATTLEFIELD, playerA, "Soldier of the Pantheon");
// Sacrifice Mogg Fanatic: Mogg Fanatic deals 1 damage to any target.
addCard(Zone.BATTLEFIELD, playerA, "Mogg Fanatic");
addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1);
addCard(Zone.BATTLEFIELD, playerA, "Plains", 1);
// Choose one - Return target creature you control and all Auras you control attached to it to their owner's hand;
// or destroy target creature and you lose life equal to its toughness;
// or return target creature card with converted mana cost 1 or less from your graveyard to the battlefield.
addCard(Zone.HAND, playerA, "Orzhov Charm");
// Kicker {5} (You may pay an additional as you cast this spell.)
// Create a tokenonto the battlefield that's a copy of target creature. If Rite of Replication was kicked, put five of those tokens onto the battlefield instead.
addCard(Zone.HAND, playerB, "Rite of Replication");
addCard(Zone.BATTLEFIELD, playerB, "Island", 4);
castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Rite of Replication", "<NAME>");
setChoice(playerB, false); // no kicker
castSpell(2, PhaseStep.BEGIN_COMBAT, playerA, "Orzhov Charm", "<NAME>");
setModeChoice(playerA, "1");
activateAbility(2, PhaseStep.END_COMBAT, playerA, "Sacrifice {this}: Prevent all damage a red source of your choice would deal this turn.");
playerA.addChoice("<NAME>");
activateAbility(2, PhaseStep.POSTCOMBAT_MAIN, playerB, "Sacrifice {this}: {this} deals 1 damage to ", "Soldier of the Pantheon");
setStopAt(2, PhaseStep.END_TURN);
execute();
assertPermanentCount(playerB, "<NAME>", 0);
assertGraveyardCount(playerA, "Orzhov Charm", 1);
assertHandCount(playerA, "<NAME>", 1);
assertGraveyardCount(playerB, "Rite of Replication", 1);
assertGraveyardCount(playerA, "Burrenton Forge-Tender", 1);
assertPermanentCount(playerA, "Soldier of the Pantheon", 1);
}
} | 2,394 |
804 | <reponame>rfscholte/jansi
/*******************************************************************************
* Copyright (C) 2017, the original author(s).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "jansi.h"
#include "jansi_structs.h"
#define CLibrary_NATIVE(func) Java_org_fusesource_jansi_internal_CLibrary_##func
#if defined(HAVE_TTYNAME)
JNIEXPORT jstring JNICALL CLibrary_NATIVE(ttyname)
(JNIEnv *env, jclass that, jint arg0)
{
jstring rc = 0;
char s[256] = { 0 };
int r = 0;
r = ttyname_r(arg0, s, 256);
if (!r) rc = (*env)->NewStringUTF(env,s);
return rc;
}
#endif
| 364 |
702 | /*
* Copyright Hyperledger Besu Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.api.util;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse;
import java.util.Optional;
public class TestJsonRpcMethodsUtil {
public static JsonRpcMethod optionalEmptyResponse() {
return new JsonRpcMethod() {
@Override
public String getName() {
return "temp_optionalEmptyResponse";
}
@Override
public JsonRpcResponse response(final JsonRpcRequestContext request) {
return new JsonRpcSuccessResponse(request.getRequest().getId(), Optional.empty());
}
};
}
public static JsonRpcMethod optionalResponseWithValue(final Object value) {
return new JsonRpcMethod() {
@Override
public String getName() {
return "temp_optionalWithValueResponse";
}
@Override
public JsonRpcResponse response(final JsonRpcRequestContext request) {
return new JsonRpcSuccessResponse(request.getRequest().getId(), Optional.of(value));
}
};
}
}
| 634 |
2,055 | # pragma once
# include <imgui.h>
namespace ax {
namespace Drawing {
enum class IconType: ImU32 { Flow, Circle, Square, Grid, RoundSquare, Diamond };
void DrawIcon(ImDrawList* drawList, const ImVec2& a, const ImVec2& b, IconType type, bool filled, ImU32 color, ImU32 innerColor);
} // namespace Drawing
} // namespace ax | 106 |
1,975 | <filename>omaha/common/ping_event.cc
// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
#include "omaha/common/ping_event.h"
#include "omaha/base/safe_format.h"
#include "omaha/base/string.h"
#include "omaha/base/xml_utils.h"
#include "omaha/common/xml_const.h"
namespace omaha {
PingEvent::PingEvent(Types type,
Results result,
int error_code,
int extra_code1)
: event_type_(type),
event_result_(result),
error_code_(error_code),
extra_code1_(extra_code1),
source_url_index_(-1),
update_check_time_ms_(0),
download_time_ms_(0),
num_bytes_downloaded_(0),
app_size_(0),
install_time_ms_(0) {
ASSERT1(EVENT_UNKNOWN != event_type_);
}
PingEvent::PingEvent(Types type,
Results result,
int error_code,
int extra_code1,
int source_url_index,
int update_check_time_ms,
int download_time_ms,
uint64 num_bytes_downloaded,
uint64 app_size,
int install_time_ms)
: event_type_(type),
event_result_(result),
error_code_(error_code),
extra_code1_(extra_code1),
source_url_index_(source_url_index),
update_check_time_ms_(update_check_time_ms),
download_time_ms_(download_time_ms),
num_bytes_downloaded_(num_bytes_downloaded),
app_size_(app_size),
install_time_ms_(install_time_ms) {
ASSERT1(EVENT_UNKNOWN != event_type_);
}
HRESULT PingEvent::ToXml(IXMLDOMNode* parent_node) const {
HRESULT hr = AddXMLAttributeNode(parent_node,
xml::kXmlNamespace,
xml::attribute::kEventType,
itostr(event_type_));
if (FAILED(hr)) {
return hr;
}
hr = AddXMLAttributeNode(parent_node,
xml::kXmlNamespace,
xml::attribute::kEventResult,
itostr(event_result_));
if (FAILED(hr)) {
return hr;
}
hr = AddXMLAttributeNode(parent_node,
xml::kXmlNamespace,
xml::attribute::kErrorCode,
itostr(error_code_));
if (FAILED(hr)) {
return hr;
}
hr = AddXMLAttributeNode(parent_node,
xml::kXmlNamespace,
xml::attribute::kExtraCode1,
itostr(extra_code1_));
if (FAILED(hr)) {
return hr;
}
if (source_url_index_ >= 0) {
hr = AddXMLAttributeNode(parent_node,
xml::kXmlNamespace,
xml::attribute::kSourceUrlIndex,
itostr(source_url_index_));
if (FAILED(hr)) {
return hr;
}
}
if (update_check_time_ms_ != 0) {
hr = AddXMLAttributeNode(parent_node,
xml::kXmlNamespace,
xml::attribute::kUpdateCheckTime,
itostr(update_check_time_ms_));
if (FAILED(hr)) {
return hr;
}
}
if (download_time_ms_ != 0) {
hr = AddXMLAttributeNode(parent_node,
xml::kXmlNamespace,
xml::attribute::kDownloadTime,
itostr(download_time_ms_));
if (FAILED(hr)) {
return hr;
}
}
if (num_bytes_downloaded_ != 0) {
hr = AddXMLAttributeNode(parent_node,
xml::kXmlNamespace,
xml::attribute::kAppBytesDownloaded,
String_Uint64ToString(num_bytes_downloaded_, 10));
if (FAILED(hr)) {
return hr;
}
}
if (app_size_ != 0) {
hr = AddXMLAttributeNode(parent_node,
xml::kXmlNamespace,
xml::attribute::kAppBytesTotal,
String_Uint64ToString(app_size_, 10));
if (FAILED(hr)) {
return hr;
}
}
if (install_time_ms_ != 0) {
hr = AddXMLAttributeNode(parent_node,
xml::kXmlNamespace,
xml::attribute::kInstallTime,
itostr(install_time_ms_));
if (FAILED(hr)) {
return hr;
}
}
return S_OK;
}
CString PingEvent::ToString() const {
CString ping_str;
SafeCStringFormat(&ping_str, _T("%s=%s, %s=%s, %s=%s, %s=%s"),
xml::attribute::kEventType, itostr(event_type_),
xml::attribute::kEventResult, itostr(event_result_),
xml::attribute::kErrorCode, itostr(error_code_),
xml::attribute::kExtraCode1, itostr(extra_code1_));
if (source_url_index_ >= 0) {
SafeCStringAppendFormat(&ping_str, _T(", %s=%s"),
xml::attribute::kSourceUrlIndex,
itostr(source_url_index_));
}
if (update_check_time_ms_ != 0) {
SafeCStringAppendFormat(&ping_str, _T(", %s=%s"),
xml::attribute::kUpdateCheckTime,
itostr(update_check_time_ms_));
}
if (app_size_ != 0) {
SafeCStringAppendFormat(&ping_str, _T(", %s=%s, %s=%s, %s=%s"),
xml::attribute::kDownloadTime,
itostr(download_time_ms_),
xml::attribute::kAppBytesDownloaded,
String_Uint64ToString(num_bytes_downloaded_, 10),
xml::attribute::kAppBytesTotal,
String_Uint64ToString(app_size_, 10));
}
if (install_time_ms_ != 0) {
SafeCStringAppendFormat(&ping_str, _T(", %s=%s"),
xml::attribute::kInstallTime,
itostr(install_time_ms_));
}
return ping_str;
}
} // namespace omaha
| 3,500 |
778 | package org.knowm.xchart.demo.charts.radar;
import org.knowm.xchart.RadarChart;
import org.knowm.xchart.RadarChartBuilder;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.demo.charts.ExampleChart;
import org.knowm.xchart.style.Styler.LegendPosition;
/**
* Radar Chart
*
* <p>Demonstrates the following:
*
* <ul>
* <li>Radar Chart
* <li>RadarChartBuilder
* <li>Tool tips
*/
public class RadarChart01 implements ExampleChart<RadarChart> {
public static void main(String[] args) {
ExampleChart<RadarChart> exampleChart = new RadarChart01();
RadarChart chart = exampleChart.getChart();
new SwingWrapper<>(chart).displayChart();
}
@Override
public RadarChart getChart() {
// Create Chart
RadarChart chart =
new RadarChartBuilder().width(800).height(600).title(getClass().getSimpleName()).build();
chart.getStyler().setToolTipsEnabled(true);
chart.getStyler().setLegendPosition(LegendPosition.InsideSW);
// Series
chart.setRadiiLabels(
new String[] {
"Sales",
"Marketing",
"Development",
"Customer Support",
"Information Technology",
"Administration"
});
chart.addSeries(
"Old System",
new double[] {0.78, 0.85, 0.80, 0.82, 0.93, 0.92},
new String[] {"Lowest varible 78%", "85%", null, null, null, null});
chart.addSeries("New System", new double[] {0.67, 0.73, 0.97, 0.95, 0.93, 0.73});
chart.addSeries("Experimental System", new double[] {0.37, 0.93, 0.57, 0.55, 0.33, 0.73});
return chart;
}
@Override
public String getExampleChartName() {
return getClass().getSimpleName() + " - Basic Radar Chart";
}
}
| 674 |
335 | {
"word": "Laboured",
"definitions": [
"Done with great effort and difficulty.",
"(especially of humour or a performance) not spontaneous or fluent."
],
"parts-of-speech": "Adjective"
} | 81 |
784 | <gh_stars>100-1000
[
{
"range": { "start": { "line": 1, "character": 11 }, "end": { "line": 1, "character": 18 } },
"severity": 1,
"source": "ts",
"message": "Argument of type '$$Props' is not assignable to parameter of type '{ exported1: string; }'.\n Types of property 'exported1' are incompatible.\n Type 'string | undefined' is not assignable to type 'string'.\n Type 'undefined' is not assignable to type 'string'.",
"code": 2345,
"tags": []
}
]
| 212 |
1,768 | package tlc2.value.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import util.Assert.TLCRuntimeException;
public class IntervalValueTest {
@Test
public void testElementAt() {
final IntervalValue iv = new IntervalValue(3, 11);
for (int i = 0; i < iv.size(); i++) {
assertEquals(IntValue.gen(i + 3), iv.elementAt(i));
}
}
@Test
public void testElementAtOutOfBoundsNegative() {
final IntervalValue iv = new IntervalValue(3, 11);
try {
iv.elementAt(-1);
} catch (TLCRuntimeException e) {
return;
}
fail();
}
@Test
public void testElementAtOutOfBoundsSize() {
final IntervalValue iv = new IntervalValue(3, 11);
try {
iv.elementAt(iv.size());
} catch (TLCRuntimeException e) {
return;
}
fail();
}
@Test
public void sizeOverflow() {
assertEquals(Integer.MAX_VALUE, new IntervalValue(1, Integer.MAX_VALUE).size());
assertEquals(Integer.MAX_VALUE, new IntervalValue(Integer.MIN_VALUE, -2).size());
try {
assertEquals(0, new IntervalValue(-989_822_976, 1_157_660_672).size());
} catch (TLCRuntimeException e) {
assertTrue(e.getMessage().contains("Size of interval value exceeds the maximum representable size (32bits)"));
return;
}
fail();
}
@Test
public void compareToOverflow1() {
final IntervalValue iv = new IntervalValue(Integer.MAX_VALUE - 1, Integer.MAX_VALUE);
assertEquals(2, iv.size());
final IntervalValue iv2 = new IntervalValue(Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 2);
assertEquals(2, iv2.size());
assertEquals(1, iv.compareTo(iv2));
}
@Test
public void testCompareExtremeIntervals() {
final IntervalValue x = new IntervalValue(Integer.MIN_VALUE, -2);
final IntervalValue y = new IntervalValue(1, Integer.MAX_VALUE);
assertEquals(x.size(), y.size());
assertTrue(x.compareTo(y) < 0);
assertTrue(y.compareTo(x) > 0);
}
@Test
public void testEmptyIntervalEquality() {
IntervalValue i1 = new IntervalValue(10, 1);
IntervalValue i2 = new IntervalValue(20, 15);
assertEquals(i1, i2);
}
@Test
public void testCompareEmptyIntervals() {
int cmp = new IntervalValue(10, 1).compareTo(new IntervalValue(20, 15));
assertEquals(0, cmp);
}
@Test
public void testSizeOfMaximumRepresentableInterval() {
final IntervalValue iv = new IntervalValue(Integer.MIN_VALUE, Integer.MAX_VALUE);
try {
iv.size();
} catch (TLCRuntimeException e) {
assertTrue(e.getMessage().contains("Size of interval value exceeds the maximum representable size (32bits)"));
return;
}
fail();
}
@Test
public void testExtremeIntervalSize() {
final IntervalValue iv1 = new IntervalValue(Integer.MAX_VALUE, Integer.MAX_VALUE);
assertEquals(1, iv1.size());
final IntervalValue iv2 = new IntervalValue(Integer.MIN_VALUE, Integer.MIN_VALUE);
assertEquals(1, iv2.size());
final IntervalValue iv3 = new IntervalValue(Integer.MAX_VALUE-10, Integer.MAX_VALUE);
assertEquals(11, iv3.size());
final IntervalValue iv4 = new IntervalValue(Integer.MIN_VALUE, Integer.MIN_VALUE+10);
assertEquals(11, iv4.size());
}
}
| 1,187 |
6,969 | ##### 7th solution
#---------------------------------------------------------
for i in range(int(input())):
s = input()
print(*[''.join(s[::2]), ''.join(s[1::2])]) | 54 |
421 | #using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
public ref class Form1: public Form
{
protected:
ListBox^ textBox1;
// <Snippet1>
private:
void PrintProductVersion()
{
textBox1->Text = "The product version is: {0}",
Application::ProductVersion;
}
// </Snippet1>
};
| 172 |
652 | <reponame>EnrikoChavez/opencbdc-tx
// Copyright (c) 2021 MIT Digital Currency Initiative,
// Federal Reserve Bank of Boston
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "ostream_serializer.hpp"
#include <cstring>
#include <vector>
namespace cbdc {
ostream_serializer::ostream_serializer(std::ostream& s)
: stream_serializer(s),
m_str(s) {}
auto ostream_serializer::end_of_buffer() const -> bool {
auto current_pos = m_str.tellp();
m_str.seekp(0, std::ios::end);
if(m_str.tellp() == current_pos) {
return true;
}
m_str.seekp(current_pos);
return false;
}
void ostream_serializer::advance_cursor(size_t len) {
m_str.seekp(static_cast<off_type>(len), std::ios::cur);
}
void ostream_serializer::reset() {
m_str.clear();
m_str.seekp(0);
}
auto ostream_serializer::write(const void* data, size_t len) -> bool {
auto write_vec = std::vector<char>(len);
std::memcpy(write_vec.data(), data, len);
return static_cast<bool>(
m_str.write(write_vec.data(), static_cast<off_type>(len)));
}
auto ostream_serializer::read(void* /* data */, size_t /* len */) -> bool {
m_str.setstate(std::ios::failbit);
return false;
}
}
| 635 |
1,024 | <filename>src/main/java/com/commafeed/backend/model/AbstractModel.java
package com.commafeed.backend.model;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.TableGenerator;
import lombok.Getter;
import lombok.Setter;
/**
* Abstract model for all entities, defining id and table generator
*
*/
@SuppressWarnings("serial")
@MappedSuperclass
@Getter
@Setter
public abstract class AbstractModel implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "gen")
@TableGenerator(
name = "gen",
table = "hibernate_sequences",
pkColumnName = "sequence_name",
valueColumnName = "sequence_next_hi_value",
allocationSize = 1000)
private Long id;
}
| 325 |
319 | <reponame>wh81752/quarkus-cxf<filename>integration-tests/src/test/java/io/quarkiverse/it/cxf/GreetingWebServiceImplTestIT.java
package io.quarkiverse.it.cxf;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.containsString;
import org.junit.jupiter.api.Test;
import io.quarkus.test.junit.NativeImageTest;
@NativeImageTest
class GreetingWebServiceImplTestIT {
@Test
void testSoapEndpoint() {
String xml = "<x:Envelope xmlns:x=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cxf=\"http://cxf.it.quarkiverse.io/\">\n"
+
" <x:Header/>\n" +
" <x:Body>\n" +
" <cxf:reply>\n" +
" <text>foo</text>\n" +
" </cxf:reply>\n" +
" </x:Body>\n" +
"</x:Envelope>";
String cnt = "";
given()
.header("Content-Type", "text/xml").and().body(xml)
.when().post("/soap/greeting")
.then()
.statusCode(200)
.body(containsString("Hello foo"));
}
@Test
void testSoap12Binding() {
given()
.when().get("/soap/greeting?wsdl")
.then()
.statusCode(200)
.body(containsString("http://schemas.xmlsoap.org/wsdl/soap12/"));
}
@Test
void testRestCxfClient() {
given()
.when().get("/rest")
.then()
.statusCode(200)
.body(containsString("Hello foo"));
}
}
| 896 |
630 | <gh_stars>100-1000
#include <hb.h>
#include <hb-ft.h>
#ifndef HB_VERSION_ATLEAST
#define HB_VERSION_ATLEAST(major,minor,micro) \
((major)*10000+(minor)*100+(micro) <= \
HB_VERSION_MAJOR*10000+HB_VERSION_MINOR*100+HB_VERSION_MICRO)
#endif
#if HB_VERSION_ATLEAST(1,1,3)
#define USE_HARFBUZZ_METRICS
#include <hb-ot.h>
#else
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_TRUETYPE_TABLES_H
#define USE_FREETYPE_METRICS
FT_Library library = NULL;
#endif
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
int get_typographic_extents (lua_State *L) {
size_t font_l;
const char * font_s = luaL_checklstring(L, 1, &font_l);
unsigned int font_index = luaL_checknumber(L, 2);
short upem;
double ascender;
double descender;
double x_height;
#ifdef USE_FREETYPE_METRICS
if (!library) FT_Init_FreeType (&library);
FT_Face ft_face = NULL;
FT_Error err = FT_New_Memory_Face (library,
(const FT_Byte *) font_s, font_l, font_index, &ft_face);
if(err) { luaL_error(L, "FT_New_Memory_Face failed"); }
upem = ft_face->units_per_EM;
ascender = ft_face->ascender / (double)upem;
descender = -ft_face->descender / (double)upem;
TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(ft_face, ft_sfnt_os2);
if (os2) {
x_height = os2->sxHeight / (double)upem;
}
FT_Done_Face(ft_face);
#else
hb_blob_t* blob = hb_blob_create (font_s, font_l, HB_MEMORY_MODE_WRITABLE, (void*)font_s, NULL);
hb_face_t* hbFace = hb_face_create (blob, font_index);
hb_font_t* hbFont = hb_font_create (hbFace);
hb_font_extents_t metrics = {0,0,0};
upem = hb_face_get_upem(hbFace);
hb_ot_font_set_funcs(hbFont);
hb_font_get_h_extents(hbFont, &metrics);
ascender = metrics.ascender / (double)upem;
descender = -metrics.descender / (double)upem;
hb_font_destroy(hbFont);
#endif
lua_newtable(L);
lua_pushstring(L, "ascender");
lua_pushnumber(L, ascender);
lua_settable(L, -3);
lua_pushstring(L, "x_height");
lua_pushnumber(L, x_height);
lua_settable(L, -3);
lua_pushstring(L, "descender");
lua_pushnumber(L, descender);
lua_settable(L, -3);
return 1;
}
int glyphwidth (lua_State* L) {
size_t font_l;
unsigned int gid = luaL_checknumber(L, 1);
const char * font_s = luaL_checklstring(L, 2, &font_l);
unsigned int font_index = luaL_checknumber(L, 3);
hb_blob_t* blob = hb_blob_create (font_s, font_l, HB_MEMORY_MODE_WRITABLE, (void*)font_s, NULL);
hb_face_t* hbFace = hb_face_create (blob, font_index);
hb_font_t* hbFont = hb_font_create (hbFace);
short upem = hb_face_get_upem(hbFace);
hb_ft_font_set_funcs(hbFont);
hb_position_t width = hb_font_get_glyph_h_advance(hbFont, gid);
lua_pushnumber(L, width / (double)upem);
return 1;
}
#if !defined LUA_VERSION_NUM
/* Lua 5.0 */
#define luaL_Reg luaL_reg
#endif
#if !defined LUA_VERSION_NUM || LUA_VERSION_NUM==501
/*
** Adapted from Lua 5.2.0
*/
void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
luaL_checkstack(L, nup+1, "too many upvalues");
for (; l->name != NULL; l++) { /* fill the table with given functions */
int i;
lua_pushstring(L, l->name);
for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -(nup+1));
lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
lua_settable(L, -(nup + 3));
}
lua_pop(L, nup); /* remove upvalues */
}
#endif
static const struct luaL_Reg lib_table [] = {
{"get_typographic_extents", get_typographic_extents},
{"glyphwidth", glyphwidth},
{NULL, NULL}
};
int luaopen_fontmetrics (lua_State *L) {
lua_newtable(L);
luaL_setfuncs(L, lib_table, 0);
return 1;
}
| 1,650 |
407 | package com.alibaba.tesla.appmanager.trait.plugin;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.tesla.appmanager.common.exception.AppErrorCode;
import com.alibaba.tesla.appmanager.common.exception.AppException;
import com.alibaba.tesla.appmanager.domain.core.WorkloadResource;
import com.alibaba.tesla.appmanager.domain.schema.TraitDefinition;
import com.alibaba.tesla.appmanager.kubernetes.KubernetesClientFactory;
import com.alibaba.tesla.appmanager.spring.util.SpringBeanUtil;
import com.alibaba.tesla.appmanager.trait.BaseTrait;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import io.fabric8.kubernetes.api.model.networking.v1beta1.Ingress;
import io.fabric8.kubernetes.api.model.networking.v1beta1.IngressBuilder;
import io.fabric8.kubernetes.api.model.networking.v1beta1.IngressSpec;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.dsl.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* Networking Ingress Trait
*
* @author <EMAIL>
*/
@Slf4j
public class NetworkingIngressTrait extends BaseTrait {
public NetworkingIngressTrait(String name, TraitDefinition traitDefinition, JSONObject spec, WorkloadResource ref) {
super(name, traitDefinition, spec, ref);
}
@Override
public void execute() {
WorkloadResource workloadResource = getWorkloadRef();
String namespace = workloadResource.getMetadata().getNamespace();
// 获取指定 cluster 的 kubernetes client
WorkloadResource workloadRef = getWorkloadRef();
KubernetesClientFactory clientFactory = SpringBeanUtil.getBean(KubernetesClientFactory.class);
String clusterId = ((JSONObject) workloadRef.getMetadata().getLabels())
.getString("labels.appmanager.oam.dev/clusterId");
if (StringUtils.isEmpty(clusterId)) {
throw new AppException(AppErrorCode.INVALID_USER_ARGS,
String.format("cannot find clusterId in workload labels|workload=%s",
JSONObject.toJSONString(workloadRef)));
}
DefaultKubernetesClient client = clientFactory.get(clusterId);
JSONArray records = getSpec().getJSONArray("ingress");
for (JSONObject record : records.toJavaList(JSONObject.class)) {
String name = record.getString("name");
JSONObject labels = new JSONObject();
if (record.getJSONObject("labels") != null) {
labels.putAll(record.getJSONObject("labels"));
}
JSONObject annotations = new JSONObject();
if (record.getJSONObject("annotations") != null) {
annotations.putAll(record.getJSONObject("annotations"));
}
JSONObject spec = record.getJSONObject("spec");
JSONObject cr = generateIngress(namespace, name, labels, annotations, spec);
// 应用到集群
try {
Resource<Ingress> resource = client.network().ingresses()
.load(new ByteArrayInputStream(cr.toJSONString().getBytes(StandardCharsets.UTF_8)));
Ingress current = client.network().ingresses().inNamespace(namespace).withName(name).get();
if (current == null) {
Ingress result = resource.create();
log.info("cr yaml has created in kubernetes|cluster={}|namespace={}|name={}|cr={}" +
"result={}", clusterId, namespace, name, cr.toJSONString(),
JSONObject.toJSONString(result));
} else {
ObjectMapper mapper = new ObjectMapper();
IngressSpec newSpec = mapper.readValue(cr.getJSONObject("spec").toJSONString(), IngressSpec.class);
final JSONObject finalLabels = labels;
final JSONObject finalAnnotations = annotations;
client.network().ingresses()
.inNamespace(namespace)
.withName(name)
.edit(s -> new IngressBuilder(s)
.editMetadata()
.withLabels(JSON.parseObject(finalLabels.toJSONString(), new TypeReference<Map<String, String>>() {}))
.withAnnotations(JSON.parseObject(finalAnnotations.toJSONString(), new TypeReference<Map<String, String>>() {}))
.endMetadata()
.withSpec(newSpec)
.build());
log.info("cr yaml has updated in kubernetes|cluster={}|namespace={}|name={}|labels={}|" +
"annotations={}|newSpec={}", clusterId, namespace, name,
JSONObject.toJSONString(labels), JSONObject.toJSONString(annotations),
JSONObject.toJSONString(newSpec));
}
} catch (Exception e) {
String errorMessage = String.format("apply cr yaml to kubernetes failed|cluster=%s|namespace=%s|" +
"exception=%s|cr=%s", clusterId, namespace, ExceptionUtils.getStackTrace(e),
cr.toJSONString());
log.error(errorMessage);
throw new AppException(AppErrorCode.INVALID_USER_ARGS, errorMessage);
}
}
}
/**
* 创建 Ingress JSON spec
*
* @param namespace 命名空间
* @param name 标识名称
* @param spec spec 定义
* @return JSONObject
*/
private JSONObject generateIngress(
String namespace, String name, Object labels, Object annotations, JSONObject spec) {
String ingressStr = JSONObject.toJSONString(ImmutableMap.of(
"apiVersion", "networking.k8s.io/v1beta1",
"kind", "Ingress",
"metadata", ImmutableMap.of(
"namespace", namespace,
"name", name,
"labels", labels,
"annotations", annotations
)
));
JSONObject ingress = JSONObject.parseObject(ingressStr);
ingress.put("spec", spec);
return ingress;
}
}
| 3,060 |
1,373 | package com.o19s.es.ltr.ranker.normalizer;
import com.o19s.es.ltr.ranker.LtrRanker;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.RamUsageEstimator;
import java.util.Map;
import java.util.Objects;
public class FeatureNormalizingRanker implements LtrRanker, Accountable {
private final LtrRanker wrapped;
private final Map<Integer, Normalizer> ftrNorms;
private static final long BASE_RAM_USED;
private static final long PER_FTR_NORM_RAM_USED = 8;
static {
BASE_RAM_USED = RamUsageEstimator.shallowSizeOfInstance(FeatureNormalizingRanker.class);
}
public FeatureNormalizingRanker(LtrRanker wrapped, Map<Integer, Normalizer> ftrNorms) {
this.wrapped = Objects.requireNonNull(wrapped);
this.ftrNorms = Objects.requireNonNull(ftrNorms);
}
public Map<Integer, Normalizer> getFtrNorms() {
return this.ftrNorms;
}
@Override
public String name() {
return wrapped.name();
}
@Override
public FeatureVector newFeatureVector(FeatureVector reuse) {
return wrapped.newFeatureVector(reuse);
}
@Override
public float score(FeatureVector point) {
for (Map.Entry<Integer, Normalizer> ordToNorm: this.ftrNorms.entrySet()) {
int ord = ordToNorm.getKey();
float origFtrScore = point.getFeatureScore(ord);
float normed = ordToNorm.getValue().normalize(origFtrScore);
point.setFeatureScore(ord, normed);
}
return wrapped.score(point);
}
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (!(other instanceof FeatureNormalizingRanker)) {
return false;
}
final FeatureNormalizingRanker that = (FeatureNormalizingRanker)(other);
if (that == null) return false;
if (!that.ftrNorms.equals(this.ftrNorms)) return false;
if (!that.wrapped.equals(this.wrapped)) return false;
return true;
}
@Override
public int hashCode() {
return this.wrapped.hashCode() +
(31 * this.ftrNorms.hashCode());
}
@Override
public long ramBytesUsed() {
long ftrNormSize = ftrNorms.size() * (PER_FTR_NORM_RAM_USED);
if (this.wrapped instanceof Accountable) {
Accountable accountable = (Accountable)this.wrapped;
return BASE_RAM_USED + accountable.ramBytesUsed() + ftrNormSize;
} else {
return BASE_RAM_USED + ftrNormSize;
}
}
} | 1,053 |
3,402 | <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.kylin.cube.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
@JsonAutoDetect(fieldVisibility = Visibility.NONE, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class
SnapshotTableDesc implements java.io.Serializable{
@JsonProperty("table_name")
private String tableName;
@JsonProperty("storage_type")
private String storageType = "metaStore";
@JsonProperty("local_cache_enable")
private boolean enableLocalCache = true;
@JsonProperty("global")
private boolean global = false;
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getStorageType() {
return storageType;
}
public void setStorageType(String storageType) {
this.storageType = storageType;
}
public boolean isGlobal() {
return global;
}
public void setGlobal(boolean global) {
this.global = global;
}
// public boolean isExtSnapshotTable() {
// return !SnapshotTable.STORAGE_TYPE_METASTORE.equals(storageType);
// }
//
// public boolean isEnableLocalCache() {
// return enableLocalCache;
// }
//
// public void setEnableLocalCache(boolean enableLocalCache) {
// this.enableLocalCache = enableLocalCache;
// }
public static SnapshotTableDesc getCopyOf(SnapshotTableDesc other) {
SnapshotTableDesc copy = new SnapshotTableDesc();
copy.tableName = other.tableName;
copy.storageType = other.storageType;
copy.enableLocalCache = other.enableLocalCache;
copy.global = other.global;
return copy;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SnapshotTableDesc that = (SnapshotTableDesc) o;
return enableLocalCache == that.enableLocalCache &&
global == that.global &&
Objects.equals(tableName, that.tableName) &&
Objects.equals(storageType, that.storageType);
}
@Override
public int hashCode() {
return Objects.hash(tableName, storageType, enableLocalCache, global);
}
}
| 1,136 |
1,657 | __author__ = "<NAME>"
__version__ = "0.0.1"
__license__ = "BSD"
import inspect
import numpy as np
import ConfigSpace
import ConfigSpace.hyperparameters as CSH
from autoPyTorch.pipeline.nodes.loss_module_selector import LossModuleSelector
from autoPyTorch.utils.configspace_wrapper import ConfigWrapper
from autoPyTorch.utils.config.config_option import ConfigOption
class LossModuleSelectorIndices(LossModuleSelector):
def fit(self, hyperparameter_config, pipeline_config, X, Y, train_indices, dataset_info):
if Y.shape[0] == dataset_info.y_shape[0]:
return super(LossModuleSelectorIndices, self).fit(hyperparameter_config, pipeline_config, X=np.zeros((Y.shape[0], 1)), Y=Y, train_indices=train_indices)
print(Y.shape[0], dataset_info.y_shape[0])
hyperparameter_config = ConfigWrapper(self.get_name(), hyperparameter_config)
loss_module_name = hyperparameter_config["loss_module"]
loss_module = self.loss_modules[loss_module_name]
loss = loss_module.module
if inspect.isclass(loss):
loss = loss()
loss_module.set_loss_function(loss)
return {'loss_function': loss_module}
| 471 |
8,095 | <reponame>radiantprism/StarCraft-2<filename>pysc2/tests/protocol_error_test.py
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Verify that we blow up if SC2 thinks we did something wrong."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import protocol
from pysc2.lib import remote_controller
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
class TestProtocolError(utils.TestCase):
"""Verify that we blow up if SC2 thinks we did something wrong."""
def test_error(self):
with run_configs.get().start(want_rgb=False) as controller:
with self.assertRaises(remote_controller.RequestError):
controller.create_game(sc_pb.RequestCreateGame()) # Missing map, etc.
with self.assertRaises(protocol.ProtocolError):
controller.join_game(sc_pb.RequestJoinGame()) # No game to join.
def test_replay_a_replay(self):
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
map_inst = maps.get("Flat64")
map_data = map_inst.data(run_config)
interface = sc_pb.InterfaceOptions(raw=True)
# Play a quick game to generate a replay.
create = sc_pb.RequestCreateGame(
local_map=sc_pb.LocalMap(
map_path=map_inst.path, map_data=map_data))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Terran,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Terran, options=interface)
controller.create_game(create)
controller.join_game(join)
controller.step(100)
obs = controller.observe()
replay_data = controller.save_replay()
# Run through the replay the first time, verifying that it finishes, but
# wasn't recording a replay.
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
map_data=map_data,
options=interface,
observed_player_id=1)
controller.start_replay(start_replay)
controller.step(1000)
obs2 = controller.observe()
self.assertEqual(obs.observation.game_loop, obs2.observation.game_loop)
with self.assertRaises(protocol.ProtocolError):
controller.save_replay()
# Run through the replay a second time, verifying that it finishes, and
# *was* recording a replay.
start_replay.record_replay = True
controller.start_replay(start_replay)
controller.step(1000)
obs2 = controller.observe()
self.assertEqual(obs.observation.game_loop, obs2.observation.game_loop)
replay_data2 = controller.save_replay()
# Make sure the replay isn't too small. Variance is fine but empty is not.
self.assertGreater(len(replay_data2), len(replay_data) * 0.8)
# Run through the replay a third time, verifying that it finishes, but
# still wasn't recording a replay.
start_replay.record_replay = False
controller.start_replay(start_replay)
controller.step(1000)
obs3 = controller.observe()
self.assertEqual(obs.observation.game_loop, obs3.observation.game_loop)
with self.assertRaises(protocol.ProtocolError):
controller.save_replay()
if __name__ == "__main__":
absltest.main()
| 1,508 |
1,581 | <filename>AppDevKit/ColorHexPresentationViewController.h<gh_stars>1000+
//
// UIColorHexPresentationViewController.h
// AppDevKit
//
// Created by <NAME> on 6/9/15.
// Copyright © 2015, Yahoo Inc.
// Licensed under the terms of the BSD License.
// Please see the LICENSE file in the project root for terms.
//
#import <UIKit/UIKit.h>
@interface ColorHexPresentationViewController : UIViewController
@end
| 137 |
1,501 | <reponame>osterwood/litex<filename>litex/compat/soc_sdram.py<gh_stars>1000+
####################################################################################################
# DISCLAIMER: Provides retro-compatibility layer for SoCSDRAM based designs.
# Will soon no longer work, please don't use in new designs.
####################################################################################################
#
# This file is part of LiteX.
#
# This file is Copyright (c) 2015 <NAME> <<EMAIL>>
# This file is Copyright (c) 2015-2019 <NAME> <<EMAIL>>
# This file is Copyright (c) 2019 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
import inspect
from migen import *
from litex.soc.integration.soc_core import *
from litex.soc.integration.soc import auto_int
__all__ = ["SoCSDRAM", "soc_sdram_args", "soc_sdram_argdict"]
# SoCSDRAM -----------------------------------------------------------------------------------------
class SoCSDRAM(SoCCore):
def __init__(self, platform, clk_freq,
l2_size = 8192,
l2_reverse = True,
min_l2_data_width = 128,
max_sdram_size = None,
**kwargs):
SoCCore.__init__(self, platform, clk_freq, **kwargs)
self.l2_size = l2_size
self.l2_reverse = l2_reverse
self.min_l2_data_width = min_l2_data_width
self.max_sdram_size = max_sdram_size
def register_sdram(self, phy, geom_settings, timing_settings, **kwargs):
class _SDRAMModule: pass
module = _SDRAMModule()
module.geom_settings = geom_settings
module.timing_settings = timing_settings
self.add_sdram("sdram",
phy = phy,
module = module,
origin = self.mem_map["main_ram"],
size = self.max_sdram_size,
l2_cache_size = self.l2_size,
l2_cache_min_data_width = self.min_l2_data_width,
l2_cache_reverse = self.l2_reverse,
**kwargs,
)
# SoCSDRAM arguments --------------------------------------------------------------------------------
def soc_sdram_args(parser):
soc_core_args(parser)
def soc_sdram_argdict(args):
r = soc_core_argdict(args)
for a in inspect.getfullargspec(SoCSDRAM.__init__).args:
if a not in ["self", "platform", "clk_freq"]:
arg = getattr(args, a, None)
if arg is not None:
r[a] = arg
return r
| 1,115 |
882 | package water.api;
import dontweave.gson.JsonObject;
import water.Job;
import water.util.Log;
import water.util.RemoveAllKeysTask;
public class RemoveAll extends JSONOnlyRequest {
@Override public RequestServer.API_VERSION[] supportedVersions() { return SUPPORTS_ONLY_V2; }
@Override protected void registered(RequestServer.API_VERSION version) { super.registered(version); }
@Override
protected Response serve() {
try {
Log.info("Removing all keys for the cluster");
// First cancel all jobs and wait for them to be done.
Log.info("Cancelling all jobs...");
for (Job job : Job.all()) {
job.cancel();
Job.waitUntilJobEnded(job.self());
}
Log.info("Finished cancelling all jobs");
RemoveAllKeysTask collector = new RemoveAllKeysTask();
collector.invokeOnAllNodes();
Log.info("Finished removing keys");
} catch( Throwable e ) {
return Response.error(e);
}
JsonObject response = new JsonObject();
return Response.done(response);
}
}
| 359 |
5,717 | <filename>samples/hmd_opencv_sandbox/opencv_process.cpp
#include "opencv_process.h"
#include "hmd_opencv_sandbox.h"
#include <opencv2/imgproc/types_c.h>
#include <opencv2/calib3d.hpp>
#include <opencv2/imgproc.hpp>
#include "common_hello.h"
#include <time.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#define NUM_DISP 96 //Max disparity.
inline double * CoPTr( const std::initializer_list<double>& d ) { return (double*)d.begin(); }
#define DO_FISHEYE 1
#define DO_PROFILE 1
#if DO_PROFILE
#define PROFILE( x ) { double Now = OGGetAbsoluteTime(); dprintf( 1, "\x1b[2K%27s: %.3fms\n", x, (Now-Start)*1000.0); Start = Now; }
#else
#define PROFILE( x )
#endif
Matrix4 Matrix4FromCVMatrix( cv::Mat matin )
{
Matrix4 out;
out.identity();
for ( int y = 0; y < matin.rows; y++ )
{
for ( int x = 0; x < matin.cols; x++ )
{
out[x + y * 4] = (float)matin.at<double>( y, x );
}
}
return out;
}
OpenCVProcess::OpenCVProcess( CameraApp * parent ) :
m_iFrameBufferLength( 0 )
, m_pFrameBuffer( 0 )
, m_pthread( 0 )
, m_parent( parent )
, m_iCurrentStereoAlgorithm( -1 )
, m_bScreenshotNext( 0 )
, m_iHasFrameForUpdate( 0 )
, m_iDoneFrameOutput( 0 )
, m_iProcFrames( 0 )
, m_iFramesSinceFPS( 0 )
, m_dTimeOfLastFPS( 0 )
, m_bQuitThread( false )
{
fNAN = nanf( "" );
}
OpenCVProcess::~OpenCVProcess()
{
m_bQuitThread = true;
if ( m_pthread )
{
m_pthread->join();
}
if ( m_iPBOids )
{
glDeleteBuffers( 2, m_iPBOids );
glDeleteFramebuffers( 1, &m_iGLfrback );
glDeleteTextures( 1, &m_iGLimback );
}
}
bool OpenCVProcess::OpenCVAppStart()
{
#define MOGRIFY_X 4
#define MOGRIFY_Y 4
#define IGNORE_EDGE_DATA_PIXELS 4
#define LAGFRAMES 4
#define DENOISE_PASSES 2
vr::EVRTrackedCameraError ce = vr::VRTrackedCamera()->AcquireVideoStreamingService( vr::k_unTrackedDeviceIndex_Hmd, &m_pCamera );
if ( ce )
{
dprintf( 0, "Error getting video streaming service. Exiting. Error: %d\n", ce );
return false;
}
vr::ETrackedPropertyError err;
m_parent->m_parent->m_pIVRSystem->GetArrayTrackedDeviceProperty( vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_CameraToHeadTransforms_Matrix34_Array, vr::k_unHmdMatrix34PropertyTag, (void *)m_headFromCamera, sizeof( vr::HmdMatrix34_t ) * 2, &err );
if ( err != vr::TrackedProp_Success )
{
dprintf( 0, "ERROR: Could not get camera to head transforms.\n" );
return false;
}
for ( int nEye = vr::Eye_Left; nEye <= vr::Eye_Right; nEye++ )
{
vr::HmdVector2_t focalLength;
vr::HmdVector2_t center;
//vr::EVRDistortionFunctionType eDistortionType;
//double fTempDistCoeffs[vr::k_unMaxDistortionFunctionParameters];
vr::EVRTrackedCameraError vrTrackedCameraError = vr::VRTrackedCamera()->GetCameraIntrinsics( vr::k_unTrackedDeviceIndex_Hmd, nEye, vr::VRTrackedCameraFrameType_Undistorted, &focalLength, ¢er );
if ( vrTrackedCameraError != vr::VRTrackedCameraError_None )
dprintf( 0, "error on GetCameraIntrinsics: %d\n", vrTrackedCameraError );
uint32_t nUndistortedWidth, nUndistortedHeight;
vrTrackedCameraError = vr::VRTrackedCamera()->GetCameraFrameSize( vr::k_unTrackedDeviceIndex_Hmd, vr::VRTrackedCameraFrameType_Undistorted, &nUndistortedWidth, &nUndistortedHeight, nullptr );
dprintf( 0, "undisorted frame size: %d %d\n", nUndistortedWidth, nUndistortedHeight );
// Currently can't get intrinsics (focal length and center) with "Distorted" type. If I get them with "Undistorted" type,
// and the undistorted size is different from the distorted size, the center will need to be corrected to account for the
// difference. Something like the below...
//
//center.v[ 0 ] -= ( ( nUndistortedWidth - m_nCameraFrameWidth ) / 2 );
//center.v[ 1 ] -= ( ( nUndistortedHeight - m_nCameraFrameHeight ) / 2 );
//
m_cameraIntrinsics[nEye].fx = focalLength.v[0]; //414, 416
m_cameraIntrinsics[nEye].cx = center.v[0]; // center.v[0]; //479, 486
m_cameraIntrinsics[nEye].fy = focalLength.v[1]; //414, 416
m_cameraIntrinsics[nEye].cy = center.v[1]; // center.v[1]; //502, 500
}
//Create Rectification Maps
double fx, cx, fy, cy;
double tmp[3][3] = { 0 };
tmp[2][2] = 1.0;
fx = m_cameraIntrinsics[0].fx;
cx = m_cameraIntrinsics[0].cx;
fy = m_cameraIntrinsics[0].fy;
cy = m_cameraIntrinsics[0].cy;
tmp[0][0] = fx;
tmp[0][2] = cx;
tmp[1][1] = fy;
tmp[1][2] = cy;
//Get coefficients... This is problematic. So, we use "undistorted" imagery from the camera.
double distortion_coefficients[vr::k_unMaxDistortionFunctionParameters * 2] = { 0 };
//double distortion_coefficients_from_steamvr[vr::k_unMaxDistortionFunctionParameters * 2];
if ( DO_FISHEYE )
{
m_parent->m_parent->m_pIVRSystem->GetArrayTrackedDeviceProperty( vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_CameraDistortionCoefficients_Float_Array, vr::k_unFloatPropertyTag,
(void*)distortion_coefficients, vr::k_unMaxDistortionFunctionParameters * 2 * sizeof( double ), 0 );
}
cv::Mat K1 = cv::Mat( cv::Size( 3, 3 ), CV_64F, &(tmp[0][0]) ).clone();
cv::Mat D1( DO_FISHEYE ? 4 : 8, 1, CV_64F, &distortion_coefficients[vr::k_unMaxDistortionFunctionParameters * 0] );
fx = m_cameraIntrinsics[1].fx;
cx = m_cameraIntrinsics[1].cx;
fy = m_cameraIntrinsics[1].fy;
cy = m_cameraIntrinsics[1].cy;
/// ROW COL
tmp[0][0] = fx;
tmp[0][2] = cx;
tmp[1][1] = fy;
tmp[1][2] = cy;
cv::Mat K2 = cv::Mat( cv::Size( 3, 3 ), CV_64F, &(tmp[0][0]) ).clone();
cv::Mat D2( DO_FISHEYE ? 4 : 8, 1, CV_64F, &distortion_coefficients[vr::k_unMaxDistortionFunctionParameters * 1] );
Matrix4 headFromLeftCamera_steamvr = ConvertSteamVRMatrixToMatrix4( m_headFromCamera[0] );
Matrix4 headFromRightCamera_steamvr = ConvertSteamVRMatrixToMatrix4( m_headFromCamera[1] );
Matrix4 RightCamerafromHead_steamvr = headFromRightCamera_steamvr.invert();
Matrix4 rotate180AroundX;
rotate180AroundX.identity();
rotate180AroundX.rotateX( 180 );
Matrix4 rightCameraFromLeftCamera_steamvr = RightCamerafromHead_steamvr * headFromLeftCamera_steamvr;
Matrix4 rightCameraFromLeftCamera_opencv = rotate180AroundX * rightCameraFromLeftCamera_steamvr * rotate180AroundX;
Vector4 RightEyeFromLeftEye = (rightCameraFromLeftCamera_steamvr * Vector4( 0, 0, 0, 1 ));
m_centerFromLeftEye = RightEyeFromLeftEye / 2;
m_CameraDistanceMeters = ( RightEyeFromLeftEye * Vector4( 1, 1, 1, 0 ) ).length();
m_centerFromLeftEye.w = 0;
double posetrans[3] = { rightCameraFromLeftCamera_opencv[12], rightCameraFromLeftCamera_opencv[13], rightCameraFromLeftCamera_opencv[14] };
rightCameraFromLeftCamera_opencv.transpose();
double posemat[9] = {
rightCameraFromLeftCamera_opencv[0], rightCameraFromLeftCamera_opencv[1], rightCameraFromLeftCamera_opencv[2],
rightCameraFromLeftCamera_opencv[4], rightCameraFromLeftCamera_opencv[5], rightCameraFromLeftCamera_opencv[6],
rightCameraFromLeftCamera_opencv[8], rightCameraFromLeftCamera_opencv[9], rightCameraFromLeftCamera_opencv[10] };
cv::Mat R( cv::Size( 3, 3 ), CV_64F, posemat /* Boy I hope the major is right */ );
cv::Mat T( 3, 1, CV_64F, posetrans );
cv::Mat R1, R2, P1, P2;
if ( DO_FISHEYE )
{
cv::fisheye::stereoRectify( K1, D1, K2, D2, cv::Size( 960, 960 ), R, T, R1, R2, P1, P2, m_cvQ, cv::CALIB_ZERO_DISPARITY, cv::Size( 960, 960 ), 0.0, 0.7 );
cv::fisheye::initUndistortRectifyMap( K1, D1, R1, P1, cv::Size( 960, 960 ), CV_16SC2, m_leftMap1, m_leftMap2 );
cv::fisheye::initUndistortRectifyMap( K2, D2, R2, P2, cv::Size( 960, 960 ), CV_16SC2, m_rightMap1, m_rightMap2 );
}
else
{
cv::stereoRectify( K1, D1, K2, D2, cv::Size( 960, 960 ), R, T, R1, R2, P1, P2, m_cvQ, cv::CALIB_ZERO_DISPARITY );
cv::initUndistortRectifyMap( K1, D1, R1, P1, cv::Size( 960, 960 ), CV_16SC2, m_leftMap1, m_leftMap2 );
cv::initUndistortRectifyMap( K2, D2, R2, P2, cv::Size( 960, 960 ), CV_16SC2, m_rightMap1, m_rightMap2 );
}
m_R1 = Matrix4FromCVMatrix( R1 );
m_R1inv = m_R1;
m_R1inv = m_R1inv.invert();
m_Q = Matrix4FromCVMatrix( m_cvQ );
uint32_t width, height;
vr::VRTextureBounds_t vtb;
dprintf( 0, "Get Cam: %lld\n", m_pCamera );
ce = vr::VRTrackedCamera()->GetVideoStreamTextureSize( vr::k_unTrackedDeviceIndex_Hmd, DO_FISHEYE ? vr::VRTrackedCameraFrameType_Distorted : vr::VRTrackedCameraFrameType_Undistorted, &vtb, &width, &height );
if ( ce )
{
dprintf( 0, "Error getting frame size (%d)\n", ce );
return false;
}
m_iFrameBufferLength = width * height * 4;
m_iFBSideWidth = width / 2;
m_iFBSideHeight = height;
m_iFBAlgoWidth = m_iFBSideWidth / MOGRIFY_X;
m_iFBAlgoHeight = m_iFBSideHeight / MOGRIFY_Y;
m_pDisparity = (uint16_t*)malloc( m_iFBAlgoWidth * m_iFBAlgoHeight * 2 );
for ( int side = 0; side < 2; side++ )
{
m_pFBSides[side] = (uint8_t*)malloc( (m_iFBAlgoWidth+ NUM_DISP)* m_iFBAlgoHeight * 1 );
m_pFBSidesColor[side] = (uint32_t*)malloc( m_iFBAlgoWidth * m_iFBAlgoHeight * 4 );
}
m_pColorOut = (uint32_t*) calloc( m_iFBAlgoWidth * m_iFBAlgoHeight, sizeof( uint32_t ) );
m_pColorOut2 = (uint32_t*) calloc( m_iFBSideWidth * m_iFBSideHeight, sizeof( uint32_t ) );
glBindTexture( GL_TEXTURE_2D, m_parent->m_iTexture );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0 ); //Always set the base and max mipmap levels of a texture.
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0 );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, m_iFBSideWidth, m_iFBSideHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_pColorOut2 );
glBindTexture( GL_TEXTURE_2D, 0 );
m_valids.resize( m_iFBAlgoHeight * m_iFBAlgoWidth );
m_valids.assign( m_valids.size(), 1 );
m_depths.resize( m_iFBAlgoHeight * m_iFBAlgoWidth );
m_pthread = new std::thread( &OpenCVProcess::Thread, this );
//Readback Buffers
//Create PBOs to allow streaming of data.
glGenBuffers( 2, m_iPBOids );
glBindBuffer( GL_PIXEL_PACK_BUFFER, m_iPBOids[0] );
glBufferData( GL_PIXEL_PACK_BUFFER, 960 * 960 * 2 * 4, 0, GL_STREAM_READ );
glBindBuffer( GL_PIXEL_PACK_BUFFER, m_iPBOids[1] );
glBufferData( GL_PIXEL_PACK_BUFFER, 960 * 960 * 2 * 4, 0, GL_STREAM_READ );
glBindBuffer( GL_PIXEL_PACK_BUFFER, 0 );
//Create target framebuffer and texture to stream camera data into.
glGenFramebuffers( 1, &m_iGLfrback );
glGenTextures( 1, &m_iGLimback );
glBindTexture( GL_TEXTURE_2D, m_iGLimback );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, m_iFBSideWidth, m_iFBSideHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0 );
glBindTexture( GL_TEXTURE_2D, 0 );
//Set up what matrices we can to prevent dynamic memory allocation.
mdisparity_expanded = cv::Mat( m_iFBAlgoHeight, m_iFBAlgoWidth + NUM_DISP, CV_16S );
return true;
}
void OpenCVProcess::Thread()
{
while ( !m_bQuitThread )
{
if ( m_iHasFrameForUpdate == 2 )
{
if( m_pFrameBuffer )
OpenCVAppUpdate();
m_iHasFrameForUpdate = 0;
}
OGUSleep( 1000 );
}
}
void OpenCVProcess::Prerender()
{
if ( m_iDoneFrameOutput )
{
m_iProcFrames++;
m_iFramesSinceFPS++;
double Start = OGGetAbsoluteTime();
if ( Start >= m_dTimeOfLastFPS + 1 )
{
if ( Start - m_dTimeOfLastFPS < 4 )
m_dTimeOfLastFPS++;
else
m_dTimeOfLastFPS = Start;
m_iFPS = m_iFramesSinceFPS;
m_iFramesSinceFPS = 0;
}
glBindTexture( GL_TEXTURE_2D, m_parent->m_iTexture );
glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, m_iFBSideWidth, m_iFBSideHeight, GL_RGBA, GL_UNSIGNED_BYTE, m_pColorOut2 ); //If you want to debug m_pColorOut, you can select that here.
glBindTexture( GL_TEXTURE_2D, 0 );
PROFILE( "[GL] Updating output texture" )
m_parent->m_geoDepthMap.TaintVerts( 0 );
m_parent->m_geoDepthMap.Check();
PROFILE( "[GL] Updating output verts" )
m_iDoneFrameOutput = 0;
}
if ( m_iHasFrameForUpdate == 1 )
{
double Start = OGGetAbsoluteTime();
glBindBuffer( GL_PIXEL_PACK_BUFFER, m_iPBOids[0] );
m_pFrameBuffer = (GLubyte*)glMapBuffer( GL_PIXEL_PACK_BUFFER, GL_READ_ONLY );
glBindBuffer( GL_PIXEL_PACK_BUFFER, 0 );
m_iHasFrameForUpdate = 2;
PROFILE( "[GL] Readback" )
}
if ( m_iHasFrameForUpdate == 0 )
{
double Start = OGGetAbsoluteTime();
#if DO_PROFILE
dprintf( 1, "\x1b[1;1f" );
dprintf( 1, "\x1b[2K\x1b[34mFrames: %5d; %3d FPS\x1b[0m\n", m_iProcFrames, m_iFPS );
dprintf( 1, "\x1b[32mGreen FG Test\x1b[0m\n" );
dprintf( 1, "\x1b[31mRed FG Test\x1b[0m\n" );
dprintf( 1, "\x1b[0m" );
#endif
//This uses OpenGL to read back the pixels. It seems to be MUCH faster than the DX alternative inside SteamVR.
vr::EVRTrackedCameraError ce = vr::VRTrackedCamera()->GetVideoStreamTextureGL( m_pCamera, DO_FISHEYE ? vr::VRTrackedCameraFrameType_Distorted : vr::VRTrackedCameraFrameType_Undistorted, &m_iGLimback, &m_lastFrameHeader, sizeof( m_lastFrameHeader ) );
m_lastFrameHeaderMatrix = ConvertSteamVRMatrixToMatrix4( m_lastFrameHeader.trackedDevicePose.mDeviceToAbsoluteTracking );
PROFILE( "[GL] GetVideoStreamTexture" )
glFinish();
PROFILE( "[GL] Flush" )
glBindFramebuffer( GL_FRAMEBUFFER, m_iGLfrback );
glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_iGLimback, 0 );
glBindBuffer( GL_PIXEL_PACK_BUFFER, m_iPBOids[0] );
if ( m_pFrameBuffer ) glUnmapBuffer( GL_PIXEL_PACK_BUFFER );
glReadPixels( 0, 0, m_lastFrameHeader.nWidth, m_lastFrameHeader.nHeight, GL_RGBA, GL_UNSIGNED_BYTE, 0 );
glBindBuffer( GL_PIXEL_PACK_BUFFER, 0 );
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
PROFILE( "[GL] PBO read is setup." )
if ( ce )
{
dprintf( 0, "Error getting frame (%d)\n", ce );
}
else
{
m_iHasFrameForUpdate = 1;
}
}
}
void OpenCVProcess::ConvertToGray( cv::InputArray src, cv::OutputArray dst )
{
//You can do this the OpenCV way, but my alternative transform seems more successful.
if ( 0 )
{
cv::cvtColor( src, dst, cv::COLOR_BGR2GRAY );
}
else
{
cv::Mat msrc( src.getMat() );
cv::Mat mdst( dst.getMat() );
int wd = mdst.cols;
int w = msrc.cols;
int h = msrc.rows;
uint32_t * indata = (uint32_t*)msrc.data;
uint8_t * outdata;
int x, y;
for ( y = 0; y < h; y++ )
{
outdata = ((uint8_t*)mdst.data) + y * wd + NUM_DISP;
for ( x = 0; x < w; x++ )
{
uint32_t inx = *(indata++);
int r = (inx >> 0) & 0xff;
int g = (inx >> 8) & 0xff;
int b = (inx >> 16) & 0xff;
//*(outdata++) = inx >> (chan * 8);
*(outdata++) = (uint8_t)((r + g + b) / 3);
}
}
}
}
Vector4 OpenCVProcess::TransformToLocalSpace( float x, float y, int disp )
{
float fDisp = ( float ) disp / 16.f; // 16-bit fixed-point disparity map (where each disparity value has 4 fractional bits)
float lz = m_Q[11] * m_CameraDistanceMeters / ( fDisp * MOGRIFY_X );
float ly = -(y * MOGRIFY_Y + m_Q[7]) / m_Q[11];
float lx = (x * MOGRIFY_X + m_Q[3]) / m_Q[11];
lx *= lz;
ly *= lz;
lz *= -1;
return m_R1inv * Vector4( lx, ly, lz, 1.0 );
}
Vector4 OpenCVProcess::TransformToWorldSpace( float x, float y, int disp )
{
Vector4 local = TransformToLocalSpace( x, y, disp );
Matrix4 mlefteye = m_lastFrameHeaderMatrix;
Vector4 placerelview( local );
Vector4 Worldview = mlefteye * (placerelview);
return Worldview;
}
void OpenCVProcess::BlurDepths()
{
//This does an actual blurring function.
#define RIGHT_EDGE_NO_TRUST 24
std::vector< float > validsback( m_iFBAlgoHeight * m_iFBAlgoWidth );
std::vector< float > depthsback( m_iFBAlgoHeight * m_iFBAlgoWidth );
//Initialize the data for this frame
for ( unsigned y = 0; y < m_iFBAlgoWidth; y++ )
{
for ( unsigned x = 0; x < m_iFBAlgoHeight; x++ )
{
int idx = y * m_iFBAlgoWidth + x;
uint16_t pxi = m_pDisparity[idx];
if ( pxi == 0 || pxi >= m_iFBAlgoWidth * 16 )
{
//If we don't know the depth, then we just discard it. We could handle that here. Additionally,
//if we wanted, we could emit fake dots where we believe the floor to be.
//Right now, we do nothing.
}
else
{
m_valids[idx] = 1.0;
m_depths[idx] = pxi;
}
//Never trust the right side of the screen.
if ( x >= m_iFBAlgoWidth - RIGHT_EDGE_NO_TRUST )
{
m_valids[idx] = 0;
m_depths[idx] = 0;
}
}
}
for ( int iter = 0; iter < 10; iter++ )
{
for ( unsigned y = 4; y < m_iFBAlgoWidth - 4; y++ )
{
for ( unsigned x = 4; x < m_iFBAlgoHeight - 4; x++ )
{
int idx = y * m_iFBAlgoWidth + x;
float tval = 0;
float tdepths = 0;
for ( int ly = -1; ly <= 1; ly++ )
for ( int lx = -1; lx <= 1; lx++ )
{
int idxx = (y+ly) * m_iFBAlgoWidth + x+lx;
tval += m_valids[idxx];
tdepths += m_depths[idxx];
}
validsback[idx] = tval / 9;
depthsback[idx] = tdepths / 9;
}
}
memcpy( &m_valids[0], &validsback[0], sizeof( float ) * validsback.size() );
memcpy( &m_depths[0], &depthsback[0], sizeof( float ) * depthsback.size() );
}
for ( unsigned y = 0; y < m_iFBAlgoHeight; y++ )
{
for ( unsigned x = 0; x < m_iFBAlgoWidth; x++ )
{
int idx = y * m_iFBAlgoWidth + x;
if ( x < 1 || x >= m_iFBAlgoWidth - 1 )
{
//Must throw out edges.
m_pDisparity[idx] = 0xfff0;
continue;
}
uint16_t pxi = m_pDisparity[idx];
if ( pxi == 0 || pxi >= m_iFBAlgoWidth * 16 )
{
if ( m_valids[idx] < .00005 )
{
m_valids[idx] = 0;
m_depths[idx] = 0;
m_pDisparity[idx] = 0xfff0;
}
else
{
m_pDisparity[idx] = (uint16_t)(m_depths[idx] / m_valids[idx]);
}
}
m_valids[idx] *= .9f;
m_depths[idx] *= .9f;
}
}
}
void OpenCVProcess::OpenCVAppUpdate()
{
double Start = OGGetAbsoluteTime();
if ( m_iCurrentStereoAlgorithm != m_parent->settings.iStereoAlg )
{
if ( m_parent->settings.iStereoAlg >= 3 ) m_parent->settings.iStereoAlg = 0;
m_iCurrentStereoAlgorithm = m_parent->settings.iStereoAlg;
if ( m_iCurrentStereoAlgorithm == 0 )
{
m_stereo = cv::StereoSGBM::create( 0, NUM_DISP, 7,
0, 0, 0,
4, 55,
25, 4,
cv::StereoSGBM::MODE_SGBM );
}
else if ( m_iCurrentStereoAlgorithm == 1 )
{
m_stereo = cv::StereoSGBM::create( 0, NUM_DISP, 2,
0, 0, 0,
4, 35,
10, 3,
cv::StereoSGBM::MODE_SGBM );
}
else if ( m_iCurrentStereoAlgorithm == 2 )
{
m_stereo = cv::StereoSGBM::create( 0, NUM_DISP, 15,
0, 0, 0,
4, 5,
200, 1,
cv::StereoSGBM::MODE_SGBM );
}
}
origStereoPair = cv::Mat( m_iFBSideHeight, m_iFBSideWidth * 2, CV_8UC4, m_pFrameBuffer );
origLeft = origStereoPair( cv::Rect( 0, 0, 960, 960 ) );
origRight = origStereoPair( cv::Rect( 960, 0, 960, 960 ) );
cv::remap( origLeft, rectLeft, m_leftMap1, m_leftMap2, CV_INTER_LINEAR, cv::BORDER_CONSTANT );
cv::remap( origRight, rectRight, m_rightMap1, m_rightMap2, CV_INTER_LINEAR, cv::BORDER_CONSTANT );
resizedLeft = cv::Mat( m_iFBAlgoHeight, m_iFBAlgoWidth, CV_8UC4, m_pFBSidesColor[0] );
resizedRight = cv::Mat( m_iFBAlgoHeight, m_iFBAlgoWidth, CV_8UC4, m_pFBSidesColor[1] );
cv::resize( rectLeft, resizedLeft, cv::Size( m_iFBAlgoWidth, m_iFBAlgoHeight ) );
cv::resize( rectRight, resizedRight, cv::Size( m_iFBAlgoWidth, m_iFBAlgoHeight ) );
resizedLeftGray = cv::Mat( m_iFBAlgoHeight, m_iFBAlgoWidth + NUM_DISP, CV_8U, m_pFBSides[0] );
resizedRightGray = cv::Mat( m_iFBAlgoHeight, m_iFBAlgoWidth + NUM_DISP, CV_8U, m_pFBSides[1] );
mdisparity = cv::Mat( m_iFBAlgoHeight, m_iFBAlgoWidth, CV_16S, m_pDisparity );
ConvertToGray( resizedLeft, resizedLeftGray );
ConvertToGray( resizedRight, resizedRightGray );
PROFILE( "[OP] Setup" )
{
m_stereo->compute( resizedLeftGray, resizedRightGray, mdisparity_expanded );
uint32_t x, y;
int wd = mdisparity.cols;
int w = mdisparity_expanded.cols;
//int h = mdisparity_expanded.rows;
for ( y = 0; y < m_iFBAlgoWidth; y++ )
{
uint16_t * indata = ((uint16_t*)mdisparity_expanded.data) + y * w + NUM_DISP;
uint16_t * outdata = ((uint16_t*)mdisparity.data) + y * wd;
for ( x = 0; x < m_iFBAlgoHeight; x++ )
{
*(outdata++) = *(indata++);
}
}
}
if ( m_bScreenshotNext )
{
TakeScreenshot();
m_bScreenshotNext = false;
}
PROFILE( "[OP] Stereo Computation")
static int rframe;
//For frame decimation
//rframe++; if ( rframe == 10 ) rframe = 0;
if ( rframe == 0 )
{
int x, y;
for ( y = 0; y < (int)m_iFBSideHeight; y++ )
{
uint32_t * pdsp = &((uint32_t*)rectLeft.data)[y*m_iFBSideWidth];
uint32_t * outlines = &m_pColorOut2[y*m_iFBSideWidth];
for ( x = 0; x < (int)m_iFBSideWidth; x++ )
{
outlines[x] = pdsp[x];// ((*(uint32_t*)(&pxdl[x * 4 + 0])) & 0xff) | ((*(uint32_t*)(&pxdr[x * 4 + 0])) & 0xff00);
}
}
}
PROFILE( "[OP] Outlines update" )
//Potentially emit dots.
if ( 1 )
{
unsigned x, y;
for ( y = 0; y < m_iFBAlgoHeight; y++ )
{
uint16_t * pxin = &m_pDisparity[y*m_iFBAlgoWidth];
for ( x = IGNORE_EDGE_DATA_PIXELS; x < m_iFBAlgoWidth - IGNORE_EDGE_DATA_PIXELS; x++ )
{
uint32_t pxc = pxin[x];
//Color
uint32_t pxo = m_pFBSidesColor[0][(x)+y * m_iFBAlgoWidth];
int pxr = ((pxo >> 0) & 0xff);
int pxg = ((pxo >> 8) & 0xff);
int pxb = ((pxo >> 16) & 0xff);
if ( pxc < 0xfff0 )
{
float frx = x + (rand() % 1000) / 1000.0f;
float fry = y + (rand() % 1000) / 1000.0f;
Vector4 Worldspace = TransformToWorldSpace( frx, fry, pxc );
if ( 1 ) //&& Worldspace.y >= 0 && Worldspace.y < 1.5 )
{
//Create debug map (this appears to the left of the window)
int dx = (int) ( -Worldspace.x * 50.0 + m_parent->m_iDebugTextureW/2 );
int dy = (int) ( Worldspace.z * 50.0 + m_parent->m_iDebugTextureH/2 );
if ( dx >= 0 && dy >= 0 && dx < m_parent->m_iDebugTextureW && dy < m_parent->m_iDebugTextureH )
{
m_parent->m_pDebugTextureData[dx + dy * m_parent->m_iDebugTextureH] = pxo | 0xff;
}
}
int emitevery = (int)(m_parent->settings.iAntEvery + m_parent->settings.fImportanceOfDist * 200 / pxc );
if ( emitevery < 1 ) emitevery = 1;
if ( 0 == (rand() % emitevery) )
m_parent->EmitDot( Worldspace.x, Worldspace.y, Worldspace.z, 1,
pxr / 255.0f, pxg / 255.0f, pxb / 255.0f, (float)((m_parent->m_frameno % m_parent->m_maxframeno) + rand()*10.0 / RAND_MAX) );
}
}
}
}
PROFILE( "[OP] Emit Dots")
if ( 1 )
{
BlurDepths( );
}
PROFILE( "[OP] Blur" )
std::vector< float > & depth_vc = m_parent->m_geoDepthMap.GetVertexArrayPtr( 0 );
if ( rframe == 0 && 1 ) //Process Output
{
uint32_t x, y;
for ( y = 0; y < m_iFBAlgoHeight; y++ )
{
uint16_t * pxin = &m_pDisparity[y*m_iFBAlgoWidth];
uint32_t * pxout = &m_pColorOut[y*m_iFBAlgoWidth];
for ( x = IGNORE_EDGE_DATA_PIXELS; x < m_iFBAlgoWidth - IGNORE_EDGE_DATA_PIXELS; x++ )
{
uint32_t pxo = pxin[x];
int idx = y * m_iFBAlgoWidth + x;
if ( pxo >= 0xfff0 )
{
pxo = 0x202020;// (x > m_iFBAlgoWidth / 2) ? 0 : 129;
depth_vc[idx * 4 + 0] = fNAN;
depth_vc[idx * 4 + 1] = fNAN;
depth_vc[idx * 4 + 2] = fNAN;
depth_vc[idx * 4 + 3] = 0;
}
else
{
//depths[x + y * m_iFBAlgoWidth] = pxin[x];
if ( 1 )
{
//Update depth geometry.
Vector4 Worldspace = TransformToWorldSpace( (float)x, (float)y, pxin[x] );
depth_vc[idx * 4 + 0] = Worldspace.x;
depth_vc[idx * 4 + 1] = Worldspace.y;
depth_vc[idx * 4 + 2] = Worldspace.z;
depth_vc[idx * 4 + 3] = m_valids[idx];
}
//OPTIONAL: Write the color buffer out.
if ( 1 )
{
pxout[x] = pxin[x];
}
}
}
}
}
m_iDoneFrameOutput = 1;
PROFILE( "[OP] Process" )
}
void OpenCVProcess::TakeScreenshot( )
{
struct tm timeinfo;
time_t rawtime;
time( &rawtime );
localtime_s( &timeinfo, &rawtime );
char timebuffer[128];
std::strftime( timebuffer, sizeof( timebuffer ), "%Y%m%d %H%M%S", &timeinfo );
std::string nowstr = timebuffer;
//Make the alpha channel of the RGB maps solid.
int sidepix = m_iFBSideWidth * m_iFBSideHeight;
for ( int i = 0; i < sidepix; i++ )
{
((uint32_t*)origStereoPair.data)[i * 2 + 1] |= 0xff000000;
((uint32_t*)origStereoPair.data)[i * 2 + 0] |= 0xff000000;
((uint32_t*)rectLeft.data)[i] |= 0xff000000;
((uint32_t*)rectRight.data)[i] |= 0xff000000;
}
stbi_write_png( (nowstr + "_Orig_RGB0.png").c_str(), m_iFBSideWidth, m_iFBSideHeight, 4, origLeft.data, m_iFBSideWidth * 8 );
stbi_write_png( (nowstr + "_Orig_RGB1.png").c_str(), m_iFBSideWidth, m_iFBSideHeight, 4, origRight.data, m_iFBSideWidth * 8 );
stbi_write_png( (nowstr + "_RGB0.png").c_str(), m_iFBSideWidth, m_iFBSideHeight, 4, rectLeft.data, m_iFBSideWidth * 4 );
stbi_write_png( (nowstr + "_RGB1.png").c_str(), m_iFBSideWidth, m_iFBSideHeight, 4, rectRight.data, m_iFBSideWidth * 4 );
stbi_write_png( (nowstr + "_Gray0.png").c_str(), m_iFBAlgoWidth, m_iFBAlgoHeight, 1, resizedLeftGray.data, m_iFBAlgoWidth );
stbi_write_png( (nowstr + "_Gray1.png").c_str(), m_iFBAlgoWidth, m_iFBAlgoHeight, 1, resizedRightGray.data, m_iFBAlgoWidth );
int pxl = m_iFBAlgoWidth * m_iFBAlgoHeight;
uint8_t * disp_px = new uint8_t[pxl];
for ( int i = 0; i < pxl; i++ )
{
disp_px[i] = (uint8_t)(((uint16_t*)(mdisparity.data))[i] / 16);
}
stbi_write_png( (nowstr + "_Disp.png").c_str(), m_iFBAlgoWidth, m_iFBAlgoHeight, 1, disp_px, m_iFBAlgoWidth );
delete[] disp_px;
}
| 11,423 |
348 | <filename>docs/data/leg-t2/062/06203351.json
{"nom":"Fouquières-lès-Lens","circ":"3ème circonscription","dpt":"Pas-de-Calais","inscrits":4559,"abs":2749,"votants":1810,"blancs":85,"nuls":56,"exp":1669,"res":[{"nuance":"FN","nom":"M. <NAME>","voix":972},{"nuance":"MDM","nom":"<NAME>","voix":697}]} | 133 |
2,338 | <filename>clang/test/SemaCXX/cxx03-aligned-allocation-unscoped-enum.cpp
// RUN: %clang_cc1 -std=c++03 -triple x86_64-pc-linux-gnu %s \
// RUN: -faligned-allocation -emit-llvm -o - -Wno-c++11-extensions | FileCheck %s
// Ensure Clang doesn't confuse std::align_val_t with the sized deallocation
// parameter when the enum type is unscoped. Libc++ does this in C++03 in order
// to support aligned allocation in that dialect.
using size_t = __decltype(sizeof(0));
namespace std {
enum align_val_t : size_t {};
}
_Static_assert(__is_same(__underlying_type(std::align_val_t), size_t), "");
// CHECK-LABEL: define{{.*}} void @_Z1fPi(
void f(int *p) {
// CHECK-NOT: call void @_ZdlPvSt11align_val_t(
// CHECK: call void @_ZdlPv(
// CHECK: ret void
delete p;
}
| 304 |
1,767 | package com.annimon.stream.operator;
import com.annimon.stream.iterator.PrimitiveIterator;
import org.jetbrains.annotations.NotNull;
public class IntLimit extends PrimitiveIterator.OfInt {
private final PrimitiveIterator.OfInt iterator;
private final long maxSize;
private long index;
public IntLimit(@NotNull PrimitiveIterator.OfInt iterator, long maxSize) {
this.iterator = iterator;
this.maxSize = maxSize;
index = 0;
}
@Override
public boolean hasNext() {
return (index < maxSize) && iterator.hasNext();
}
@Override
public int nextInt() {
index++;
return iterator.nextInt();
}
}
| 247 |
1,909 | package org.knowm.xchange.ftx.dto.account;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import org.knowm.xchange.currency.Currency;
public class FtxWalletBalanceDto {
@JsonProperty("coin")
private Currency coin;
@JsonProperty("free")
private BigDecimal free;
@JsonProperty("total")
private BigDecimal total;
public FtxWalletBalanceDto(
@JsonProperty("coin") Currency coin,
@JsonProperty("free") BigDecimal free,
@JsonProperty("total") BigDecimal total) {
this.coin = coin;
this.free = free;
this.total = total;
}
public Currency getCoin() {
return coin;
}
public BigDecimal getFree() {
return free;
}
public BigDecimal getTotal() {
return total;
}
@Override
public String toString() {
return "FtxWalletBalanceDto{" + "coin=" + coin + ", free=" + free + ", total=" + total + '}';
}
}
| 328 |
14,668 | // Copyright 2018 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 "media/audio/alsa/alsa_util.h"
#include "media/audio/alsa/mock_alsa_wrapper.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace alsa_util {
namespace {
using ::testing::_;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::Return;
} // namespace
TEST(AlsaUtilTest, FreeHwParams) {
InSequence seq;
media::MockAlsaWrapper mock_alsa_wrapper;
snd_pcm_hw_params_t* params_ptr = (snd_pcm_hw_params_t*)malloc(1);
EXPECT_CALL(mock_alsa_wrapper, PcmOpen(_, _, _, _)).WillOnce(Return(0));
EXPECT_CALL(mock_alsa_wrapper, PcmSetParams(_, _, _, _, _, _, _))
.WillOnce(Return(-1));
EXPECT_CALL(mock_alsa_wrapper, StrError(_)).WillOnce(Return("error"));
EXPECT_CALL(mock_alsa_wrapper, PcmHwParamsMalloc(_))
.WillOnce(Invoke([params_ptr](snd_pcm_hw_params_t** params) {
*params = params_ptr;
return 0;
}));
EXPECT_CALL(mock_alsa_wrapper, PcmHwParamsAny(_, _)).WillOnce(Return(-1));
EXPECT_CALL(mock_alsa_wrapper, StrError(_)).WillOnce(Return("error"));
EXPECT_CALL(mock_alsa_wrapper, PcmHwParamsFree(params_ptr));
EXPECT_CALL(mock_alsa_wrapper, PcmName(_)).WillOnce(Return("default"));
EXPECT_CALL(mock_alsa_wrapper, PcmClose(_)).WillOnce(Return(0));
snd_pcm_t* handle = OpenCaptureDevice(&mock_alsa_wrapper, "default", 2, 48000,
SND_PCM_FORMAT_S16, 40000, 10000);
EXPECT_EQ(handle, nullptr);
free(params_ptr);
}
} // namespace alsa_util
| 687 |
1,656 | """
.. module: lemur.plugins.lemur_jks.plugin
:platform: Unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import serialization
from jks import PrivateKeyEntry, KeyStore, TrustedCertEntry
from lemur.common.defaults import common_name
from lemur.common.utils import parse_certificate, parse_cert_chain, parse_private_key, check_validation
from lemur.plugins import lemur_jks as jks
from lemur.plugins.bases import ExportPlugin
def cert_chain_as_der(cert, chain):
"""Return a certificate and its chain in a list format, as expected by pyjks."""
certs = [parse_certificate(cert)]
certs.extend(parse_cert_chain(chain))
# certs (list) – A list of certificates, as byte strings. The first one should be the one belonging to the private
# key, the others the chain (in correct order).
return [cert.public_bytes(encoding=serialization.Encoding.DER) for cert in certs]
def create_truststore(cert, chain, alias, passphrase):
entries = []
for idx, cert_bytes in enumerate(cert_chain_as_der(cert, chain)):
# The original cert gets name <ALIAS>_cert, first chain element is <ALIAS>_cert_1, etc.
cert_alias = alias + "_cert" + ("_{}".format(idx) if idx else "")
entries.append(TrustedCertEntry.new(cert_alias, cert_bytes))
return KeyStore.new("jks", entries).saves(passphrase)
def create_keystore(cert, chain, key, alias, passphrase):
certs_bytes = cert_chain_as_der(cert, chain)
key_bytes = parse_private_key(key).private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
entry = PrivateKeyEntry.new(alias, certs_bytes, key_bytes)
return KeyStore.new("jks", [entry]).saves(passphrase)
class JavaTruststoreExportPlugin(ExportPlugin):
title = "Java Truststore (JKS)"
slug = "java-truststore-jks"
description = "Generates a JKS truststore"
requires_key = False
version = jks.VERSION
author = "<NAME>"
author_url = "https://github.com/intgr"
options = [
{
"name": "alias",
"type": "str",
"required": False,
"helpMessage": "Enter the alias you wish to use for the truststore.",
},
{
"name": "passphrase",
"type": "str",
"required": False,
"helpMessage": "If no passphrase is given one will be generated for you, we highly recommend this.",
"validation": check_validation(""),
},
]
def export(self, body, chain, key, options, **kwargs):
"""
Generates a Java Truststore
"""
if self.get_option("alias", options):
alias = self.get_option("alias", options)
else:
alias = common_name(parse_certificate(body))
if self.get_option("passphrase", options):
passphrase = self.get_option("passphrase", options)
else:
passphrase = Fernet.generate_key().decode("utf-8")
raw = create_truststore(body, chain, alias, passphrase)
return "jks", passphrase, raw
class JavaKeystoreExportPlugin(ExportPlugin):
title = "Java Keystore (JKS)"
slug = "java-keystore-jks"
description = "Generates a JKS keystore"
version = jks.VERSION
author = "<NAME>"
author_url = "https://github.com/intgr"
options = [
{
"name": "passphrase",
"type": "str",
"required": False,
"helpMessage": "If no passphrase is given one will be generated for you, we highly recommend this.",
"validation": check_validation(""),
},
{
"name": "alias",
"type": "str",
"required": False,
"helpMessage": "Enter the alias you wish to use for the keystore.",
},
]
def export(self, body, chain, key, options, **kwargs):
"""
Generates a Java Keystore
"""
if self.get_option("passphrase", options):
passphrase = self.get_option("passphrase", options)
else:
passphrase = <PASSWORD>.generate_key().decode("utf-8")
if self.get_option("alias", options):
alias = self.get_option("alias", options)
else:
alias = common_name(parse_certificate(body))
raw = create_keystore(body, chain, key, alias, passphrase)
return "jks", passphrase, raw
| 1,865 |
932 | <reponame>oriolmirosa/dash-recipes<filename>tabs-and-intervals.py
import dash
from dash.dependencies import Input, Output, Event, State
import dash_core_components as dcc
import dash_html_components as html
import datetime
app = dash.Dash()
app.scripts.config.serve_locally = True
app.config['suppress_callback_exceptions'] = True
app.layout = html.Div([
dcc.Tabs(
tabs=[
{'label': 'Tab {}'.format(i), 'value': i} for i in range(1, 5)
],
value=3,
id='tab'
),
html.Div(id='container'),
dcc.Interval(id='my-interval', interval=3*1000)
])
def generate_figure(selected_tab):
now = datetime.datetime.now()
return {
'data': [{'y': [1, 5, 3]}],
'layout': {
'title': 'Tab {} at {}:{}:{}'.format(
selected_tab, now.hour, now.minute, now.second
)
}
}
@app.callback(Output('container', 'children'), [Input('tab', 'value')])
def display_content(selected_tab):
return html.Div([
html.H1(selected_tab),
dcc.Graph(id='graph', figure=generate_figure(selected_tab))
])
app.callback(
Output('graph', 'figure'),
events=[Event('my-interval', 'interval')],
state=[State('tab', 'value')])(generate_figure)
if __name__ == '__main__':
app.run_server(debug=True)
| 580 |
507 | # terrascript/mysql/d.py
| 11 |
2,542 | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Common
{
class TextWriter;
class FormatOptions;
class ITextWritable
{
public:
virtual void WriteTo(TextWriter& w, FormatOptions const &) const = 0;
};
}
| 130 |
4,200 | /*
* Copyright 2018 Rundeck, Inc. (http://rundeck.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtolabs.rundeck.core.logging;
import com.dtolabs.rundeck.core.execution.workflow.ContextStack;
import java.io.IOException;
import java.util.Optional;
/**
* Stack based override of the log writer sink for the current and child threads, each child thread gets a copy of the stack
* @author greg
* @since 5/10/17
*/
public class OverridableStreamingLogWriter extends FilterStreamingLogWriter {
private final InheritableThreadLocal<ContextStack<Optional<StreamingLogWriter>>> override = new
InheritableThreadLocal<ContextStack<Optional<StreamingLogWriter>>>() {
@Override
protected ContextStack<Optional<StreamingLogWriter>> initialValue() {
return new ContextStack<>();
}
@Override
protected ContextStack<Optional<StreamingLogWriter>> childValue(
final ContextStack<Optional<StreamingLogWriter>> parentValue
)
{
return new ContextStack<>(parentValue.stack());
}
};
public OverridableStreamingLogWriter(final StreamingLogWriter writer) {
super(writer);
}
@Override
public void openStream() throws IOException {
if (getOverride() != null) {
getOverride().openStream();
return;
}
super.openStream();
}
@Override
public void addEvent(final LogEvent event) {
if (getOverride() != null) {
getOverride().addEvent(event);
return;
}
super.addEvent(event);
}
@Override
public void close() {
if (getOverride() != null) {
getOverride().close();
return;
}
super.close();
}
public StreamingLogWriter getOverride() {
if (override.get().size() > 0) {
return override.get().peek().orElse(null);
} else {
return null;
}
}
/**
* Set the writer to use
*
* @param writer writer
*/
public void setOverride(StreamingLogWriter writer) {
override.get().push(Optional.ofNullable(writer));
}
/**
* Push no value onto the stack
*/
public void pushEmpty() {
setOverride(null);
}
/**
* Remove the overriding writer, if any
*
* @return overriding writer, or null
*/
public StreamingLogWriter removeOverride() {
StreamingLogWriter previous = override.get().pop().orElse(null);
return previous;
}
}
| 1,267 |
679 | <filename>main/connectivity/source/inc/propertyids.hxx
/**************************************************************
*
* 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 _CONNECTIVITY_PROPERTYIDS_HXX_
#define _CONNECTIVITY_PROPERTYIDS_HXX_
// this define has to be set to split the names into different dll's or so's
// every dll has his own set of property names
#include <rtl/ustring.hxx>
#ifndef _MAP_
#include <map>
#endif
#include "connectivity/dbtoolsdllapi.hxx"
namespace dbtools
{
class OOO_DLLPUBLIC_DBTOOLS OPropertyMap
{
::std::map<sal_Int32 , rtl_uString*> m_aPropertyMap;
::rtl::OUString fillValue(sal_Int32 _nIndex);
public:
OPropertyMap()
{
}
~OPropertyMap();
::rtl::OUString getNameByIndex(sal_Int32 _nIndex) const;
};
}
namespace connectivity
{
namespace CONNECTIVITY_PROPERTY_NAME_SPACE
{
typedef const sal_Char* (*PVFN)();
struct OOO_DLLPUBLIC_DBTOOLS UStringDescription
{
const sal_Char* pZeroTerminatedName;
sal_Int32 nLength;
UStringDescription(PVFN _fCharFkt);
operator ::rtl::OUString() const { return ::rtl::OUString(pZeroTerminatedName,nLength,RTL_TEXTENCODING_ASCII_US); }
~UStringDescription();
private:
UStringDescription();
};
}
}
//------------------------------------------------------------------------------
#define DECL_PROP1IMPL(varname, type) \
pProperties[nPos++] = ::com::sun::star::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_##varname), PROPERTY_ID_##varname, ::getCppuType(static_cast< type*>(NULL)),
//------------------------------------------------------------------------------
#define DECL_PROP0(varname, type) \
DECL_PROP1IMPL(varname, type) 0)
//------------------------------------------------------------------------------
#define DECL_BOOL_PROP1IMPL(varname) \
pProperties[nPos++] = ::com::sun::star::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_##varname), PROPERTY_ID_##varname, ::getBooleanCppuType(),
//------------------------------------------------------------------------------
#define DECL_BOOL_PROP0(varname) \
DECL_BOOL_PROP1IMPL(varname) 0)
#define PROPERTY_ID_QUERYTIMEOUT 1
#define PROPERTY_ID_MAXFIELDSIZE 2
#define PROPERTY_ID_MAXROWS 3
#define PROPERTY_ID_CURSORNAME 4
#define PROPERTY_ID_RESULTSETCONCURRENCY 5
#define PROPERTY_ID_RESULTSETTYPE 6
#define PROPERTY_ID_FETCHDIRECTION 7
#define PROPERTY_ID_FETCHSIZE 8
#define PROPERTY_ID_ESCAPEPROCESSING 9
#define PROPERTY_ID_USEBOOKMARKS 10
// Column
#define PROPERTY_ID_NAME 11
#define PROPERTY_ID_TYPE 12
#define PROPERTY_ID_TYPENAME 13
#define PROPERTY_ID_PRECISION 14
#define PROPERTY_ID_SCALE 15
#define PROPERTY_ID_ISNULLABLE 16
#define PROPERTY_ID_ISAUTOINCREMENT 17
#define PROPERTY_ID_ISROWVERSION 18
#define PROPERTY_ID_DESCRIPTION 19
#define PROPERTY_ID_DEFAULTVALUE 20
#define PROPERTY_ID_REFERENCEDTABLE 21
#define PROPERTY_ID_UPDATERULE 22
#define PROPERTY_ID_DELETERULE 23
#define PROPERTY_ID_CATALOG 24
#define PROPERTY_ID_ISUNIQUE 25
#define PROPERTY_ID_ISPRIMARYKEYINDEX 26
#define PROPERTY_ID_ISCLUSTERED 27
#define PROPERTY_ID_ISASCENDING 28
#define PROPERTY_ID_SCHEMANAME 29
#define PROPERTY_ID_CATALOGNAME 30
#define PROPERTY_ID_COMMAND 31
#define PROPERTY_ID_CHECKOPTION 32
#define PROPERTY_ID_PASSWORD 33
#define PROPERTY_ID_RELATEDCOLUMN 34
#define PROPERTY_ID_FUNCTION 35
#define PROPERTY_ID_TABLENAME 36
#define PROPERTY_ID_REALNAME 37
#define PROPERTY_ID_DBASEPRECISIONCHANGED 38
#define PROPERTY_ID_ISCURRENCY 39
#define PROPERTY_ID_ISBOOKMARKABLE 40
#define PROPERTY_ID_INVALID_INDEX 41
#define PROPERTY_ID_HY010 43
#define PROPERTY_ID_LABEL 44
#define PROPERTY_ID_DELIMITER 45
#define PROPERTY_ID_FORMATKEY 46
#define PROPERTY_ID_LOCALE 47
#define PROPERTY_ID_IM001 48
#define PROPERTY_ID_AUTOINCREMENTCREATION 49
#define PROPERTY_ID_PRIVILEGES 50
#define PROPERTY_ID_HAVINGCLAUSE 51
#define PROPERTY_ID_ISSIGNED 52
#define PROPERTY_ID_AGGREGATEFUNCTION 53
#define PROPERTY_ID_ISSEARCHABLE 54
#define PROPERTY_ID_APPLYFILTER 55
#define PROPERTY_ID_FILTER 56
#define PROPERTY_ID_MASTERFIELDS 57
#define PROPERTY_ID_DETAILFIELDS 58
#define PROPERTY_ID_FIELDTYPE 59
#define PROPERTY_ID_VALUE 60
#define PROPERTY_ID_ACTIVE_CONNECTION 61
#endif // _CONNECTIVITY_PROPERTYIDS_HXX_
| 2,257 |
7,956 | <reponame>Earthman100/spyder
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
spyder.plugins.appearance
=========================
Appearance Plugin.
"""
| 86 |
1,141 | <filename>quokka/core/app.py
# coding: utf-8
from flask import Blueprint, Flask
from flask.helpers import _endpoint_from_view_func
class QuokkaApp(Flask):
"""
Implements customizations on Flask
- custom add_quokka_url_rule
- properties to access db and admin
"""
def add_quokka_url_rule(self, rule, endpoint=None,
view_func=None, **options):
"""Builds urls using quokka. prefix to avoid conflicts
with external modules urls."""
if endpoint is None:
endpoint = _endpoint_from_view_func(view_func)
if not endpoint.startswith('quokka.'):
endpoint = 'quokka.' + endpoint
self.add_url_rule(rule, endpoint, view_func, **options)
def register_module(self, module):
self.register_blueprint(module)
@property
def db(self):
return self.extensions['db']
@property
def admin(self):
ext = self.extensions['admin']
adm = ext[0] if isinstance(ext, list) else ext
adm.app = self # cross reference
return adm
class QuokkaModule(Blueprint):
"""Overwrite blueprint namespace to quokka.modules.name
to avoid conflicts with external Blueprints use same name"""
def __init__(self, name, *args, **kwargs):
kwargs.setdefault('import_name', name)
kwargs.setdefault('template_folder', 'templates')
super(QuokkaModule, self).__init__(name, *args, **kwargs)
| 590 |
5,169 | {
"name": "AsyncOpKit",
"version": "1.0.0",
"summary": "Generic NSOperation subclass for managing asynchronous code in Swift",
"description": "AsyncOpKit provides AsyncOp, a generic NSOperation subclass for managing\nasynchronous operations with NSOperationQueues while taking advantage of\nthe power of Swift's type system. Async Op is not compatible with Obj-C,\nhowever a legacy AsyncOperation that is Obj-C compatible is included.'",
"authors": "<NAME>",
"homepage": "https://github.com/jedlewison/AsyncOpKit",
"license": "MIT",
"source": {
"git": "https://github.com/jedlewison/AsyncOpKit.git",
"tag": "1.0.0"
},
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"source_files": "{AsyncOp.swift,AsyncOpTypes.swift,Legacy/*.swift}"
}
| 265 |
1,133 | #!/usr/bin/env python3
#
# Author: <NAME>
# Copyright 2016
#
# <NAME>: Adopted for stack processing
import argparse
import numpy as np
import os
import isce
import isceobj
import logging
import datetime
from isceobj.Location.Offset import OffsetField, Offset
from isceobj.Util.decorators import use_api
import s1a_isce_utils as ut
#logger = logging.getLogger('isce.topsinsar.rangecoreg')
def createParser():
parser = argparse.ArgumentParser( description='Estimate range misregistration using overlap bursts')
parser.add_argument('-o', '--out_range', type=str, dest='output', default='misreg.txt',
help='Output textfile with the constant range offset')
parser.add_argument('-t', '--snr_threshold', type=float, dest='offsetSNRThreshold', default=6.0,
help='SNR threshold for overlap masking')
parser.add_argument('-m','--reference', type=str, dest='reference', required=True,
help='Reference image')
parser.add_argument('-s', '--secondary',type=str, dest='secondary', required=True,
help='Secondary image')
return parser
def cmdLineParse(iargs=None):
'''
Command line parser.
'''
parser = createParser()
return parser.parse_args(args=iargs)
def runAmpcor(reference, secondary):
'''
Run one ampcor process.
'''
import isceobj
from mroipac.ampcor.Ampcor import Ampcor
mImg = isceobj.createSlcImage()
mImg.load(reference + '.xml')
mImg.setAccessMode('READ')
mImg.createImage()
sImg = isceobj.createSlcImage()
sImg.load(secondary + '.xml')
sImg.setAccessMode('READ')
sImg.createImage()
objAmpcor = Ampcor('ampcor_burst')
objAmpcor.configure()
objAmpcor.setImageDataType1('mag')
objAmpcor.setImageDataType2('mag')
if objAmpcor.acrossGrossOffset is None:
coarseAcross = 0
if objAmpcor.downGrossOffset is None:
coarseDown = 0
objAmpcor.windowSizeWidth = 64
objAmpcor.windowSizeHeight = 32
objAmpcor.searchWindowSizeWidth = 16
objAmpcor.searchWindowSizeHeight = 16
objAmpcor.oversamplingFactor = 32
xMargin = 2*objAmpcor.searchWindowSizeWidth + objAmpcor.windowSizeWidth
yMargin = 2*objAmpcor.searchWindowSizeHeight + objAmpcor.windowSizeHeight
firstAc = 1000
#####Compute image positions
offDn = objAmpcor.windowSizeHeight//2 + 1
offAc = firstAc+xMargin
offDnmax = mImg.getLength() - objAmpcor.windowSizeHeight//2 - 1
lastAc = int(mImg.width - 1000 - xMargin)
if not objAmpcor.firstSampleAcross:
objAmpcor.setFirstSampleAcross(offAc)
if not objAmpcor.lastSampleAcross:
objAmpcor.setLastSampleAcross(lastAc)
if not objAmpcor.numberLocationAcross:
objAmpcor.setNumberLocationAcross(80)
if not objAmpcor.firstSampleDown:
objAmpcor.setFirstSampleDown(offDn)
if not objAmpcor.lastSampleDown:
objAmpcor.setLastSampleDown(offDnmax)
###Since we are only dealing with overlaps
objAmpcor.setNumberLocationDown(20)
#####Override gross offsets if not provided
if not objAmpcor.acrossGrossOffset:
objAmpcor.setAcrossGrossOffset(coarseAcross)
if not objAmpcor.downGrossOffset:
objAmpcor.setDownGrossOffset(coarseDown)
objAmpcor.setImageDataType1('mag')
objAmpcor.setImageDataType2('mag')
objAmpcor.setFirstPRF(1.0)
objAmpcor.setSecondPRF(1.0)
objAmpcor.setFirstRangeSpacing(1.0)
objAmpcor.setSecondRangeSpacing(1.0)
objAmpcor(mImg, sImg)
mImg.finalizeImage()
sImg.finalizeImage()
return objAmpcor.getOffsetField()
def main(iargs=None):
inps = cmdLineParse(iargs)
'''
Estimate constant offset in range.
'''
#if not self.doESD:
# return
#catalog = isceobj.Catalog.createCatalog(self._insar.procDoc.name)
#swathList = self._insar.getValidSwathList(self.swaths)
referenceSwathList = ut.getSwathList(os.path.join(inps.reference, 'overlap'))
secondarySwathList = ut.getSwathList(os.path.join(inps.secondary, 'overlap'))
swathList = list(sorted(set(referenceSwathList+secondarySwathList)))
rangeOffsets = []
snr = []
for swath in swathList:
#if self._insar.numberOfCommonBursts[swath-1] < 2:
# print('Skipping range coreg for swath IW{0}'.format(swath))
# continue
#minBurst, maxBurst = self._insar.commonReferenceBurstLimits(swath-1)
#maxBurst = maxBurst - 1 ###For overlaps
#referenceTop = self._insar.loadProduct( os.path.join(self._insar.referenceSlcOverlapProduct, 'top_IW{0}.xml'.format(swath)))
#referenceBottom = self._insar.loadProduct( os.path.join(self._insar.referenceSlcOverlapProduct , 'bottom_IW{0}.xml'.format(swath)))
referenceTop = ut.loadProduct(os.path.join(inps.reference , 'overlap','IW{0}_top.xml'.format(swath)))
referenceBottom = ut.loadProduct(os.path.join(inps.reference ,'overlap', 'IW{0}_bottom.xml'.format(swath)))
secondaryTop = ut.loadProduct(os.path.join(inps.secondary, 'overlap', 'IW{0}_top.xml'.format(swath)))
secondaryBottom = ut.loadProduct(os.path.join(inps.secondary, 'overlap', 'IW{0}_bottom.xml'.format(swath)))
#secondaryTop = self._insar.loadProduct( os.path.join(self._insar.coregOverlapProduct , 'top_IW{0}.xml'.format(swath)))
#secondaryBottom = self._insar.loadProduct( os.path.join(self._insar.coregOverlapProduct, 'bottom_IW{0}.xml'.format(swath)))
minReference = referenceTop.bursts[0].burstNumber
maxReference = referenceTop.bursts[-1].burstNumber
minSecondary = secondaryTop.bursts[0].burstNumber
maxSecondary = secondaryTop.bursts[-1].burstNumber
minBurst = max(minSecondary, minReference)
maxBurst = min(maxSecondary, maxReference)
#maxBurst = maxBurst - 1 ###For overlaps
maxBurst = maxBurst + 1
for pair in [(referenceTop,secondaryTop), (referenceBottom,secondaryBottom)]:
for ii in range(minBurst,maxBurst):
mFile = pair[0].bursts[ii-minReference].image.filename
sFile = pair[1].bursts[ii-minSecondary].image.filename
field = runAmpcor(mFile, sFile)
for offset in field:
rangeOffsets.append(offset.dx)
snr.append(offset.snr)
###Cull
mask = np.logical_and(np.array(snr) > inps.offsetSNRThreshold, np.abs(rangeOffsets) < 1.2)
val = np.array(rangeOffsets)[mask]
medianval = np.median(val)
meanval = np.mean(val)
stdval = np.std(val)
# convert the estimations to meters
medianval = medianval * referenceTop.bursts[0].rangePixelSize
meanval = meanval * referenceTop.bursts[0].rangePixelSize
stdval = stdval * referenceTop.bursts[0].rangePixelSize
hist, bins = np.histogram(val, 50, normed=1)
center = 0.5*(bins[:-1] + bins[1:])
outputDir = os.path.dirname(inps.output)
os.makedirs(outputDir, exist_ok=True)
try:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
except:
print('Matplotlib could not be imported. Skipping debug plot ...')
debugPlot = False
debugPlot = False
if debugPlot:
try:
####Plotting
plt.figure()
plt.bar(center, hist, align='center', width = 0.7*(bins[1] - bins[0]))
plt.xlabel('Range shift in pixels')
plt.savefig( os.path.join(outputDir, 'rangeMisregistration.jpg'))
plt.show()
plt.close()
except:
print('Looks like matplotlib could not save image to JPEG, continuing .....')
print('Install Pillow to ensure debug plots for Residual range offsets are generated.')
pass
with open(inps.output, 'w') as f:
f.write('median : '+str(medianval) +'\n')
f.write('mean : '+str(meanval)+'\n')
f.write('std : '+str(stdval)+'\n')
f.write('snr threshold : '+str(inps.offsetSNRThreshold)+'\n')
f.write('mumber of coherent points : '+str(len(val))+'\n')
if __name__ == '__main__':
'''
Main driver.
'''
main()
| 3,475 |
14,668 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/chrome_cleaner/engines/controllers/engine_facade.h"
#include <utility>
#include "base/check.h"
#include "chrome/chrome_cleaner/engines/controllers/engine_cleaner.h"
#include "chrome/chrome_cleaner/engines/controllers/scanner_impl.h"
#include "sandbox/win/src/sandbox_factory.h"
#include "sandbox/win/src/target_services.h"
namespace chrome_cleaner {
EngineFacade::EngineFacade(scoped_refptr<EngineClient> engine_client)
: engine_client_(std::move(engine_client)) {
CHECK(sandbox::SandboxFactory::GetTargetServices() == nullptr);
scanner_ = std::make_unique<ScannerImpl>(engine_client_.get());
cleaner_ = std::make_unique<EngineCleaner>(engine_client_.get());
}
EngineFacade::~EngineFacade() = default;
Scanner* EngineFacade::GetScanner() {
return scanner_.get();
}
Cleaner* EngineFacade::GetCleaner() {
return cleaner_.get();
}
base::TimeDelta EngineFacade::GetScanningWatchdogTimeout() const {
return base::Seconds(engine_client_->ScanningWatchdogTimeoutInSeconds());
}
} // namespace chrome_cleaner
| 396 |
8,747 | /*
* SPDX-FileCopyrightText: 2017-2021 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Set up the SysTick interrupt
*/
void vPortSetupTimer(void);
#ifdef __cplusplus
}
#endif
| 112 |
5,169 | <filename>Specs/TFSliderView/0.1.1/TFSliderView.podspec.json<gh_stars>1000+
{
"name": "TFSliderView",
"version": "0.1.1",
"summary": "An easy to use stylish toggle switch for iOS 8+.",
"homepage": "https://github.com/tarikfayad/TFSliderView",
"description": "TFSliderView is an easy to use stylish toggle switch for iOS 8+ built on the POP animation framework. I put it together for use in an inhouse project and thought I'd share in case anyone else needed something similar.",
"screenshots": "http://i.imgur.com/o0qSWTr.gif",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"social_media_url": "http://twitter.com/tarikfayad",
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/tarikfayad/TFSliderView.git",
"tag": "0.1.1"
},
"source_files": [
"Classes",
"Classes/*.{h,m}"
],
"requires_arc": true,
"dependencies": {
"pop": [
"~> 1.0"
]
}
}
| 403 |
363 | <reponame>dingjs/javaagent
/*
* Javassist, a Java-bytecode translator toolkit.
* Copyright (C) 1999- <NAME>. All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. Alternatively, the contents of this file may be used under
* the terms of the GNU Lesser General Public License Version 2.1 or later,
* or the Apache License Version 2.0.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/
package com.wenshuo.agent.javassist.bytecode;
/**
* JVM Instruction Set.
*
* <p>This interface defines opcodes and
* array types for the NEWARRAY instruction.
*
* @see Mnemonic
*/
public interface Opcode {
/* Opcodes */
int AALOAD = 50;
int AASTORE = 83;
int ACONST_NULL = 1;
int ALOAD = 25;
int ALOAD_0 = 42;
int ALOAD_1 = 43;
int ALOAD_2 = 44;
int ALOAD_3 = 45;
int ANEWARRAY = 189;
int ARETURN = 176;
int ARRAYLENGTH = 190;
int ASTORE = 58;
int ASTORE_0 = 75;
int ASTORE_1 = 76;
int ASTORE_2 = 77;
int ASTORE_3 = 78;
int ATHROW = 191;
int BALOAD = 51;
int BASTORE = 84;
int BIPUSH = 16;
int CALOAD = 52;
int CASTORE = 85;
int CHECKCAST = 192;
int D2F = 144;
int D2I = 142;
int D2L = 143;
int DADD = 99;
int DALOAD = 49;
int DASTORE = 82;
int DCMPG = 152;
int DCMPL = 151;
int DCONST_0 = 14;
int DCONST_1 = 15;
int DDIV = 111;
int DLOAD = 24;
int DLOAD_0 = 38;
int DLOAD_1 = 39;
int DLOAD_2 = 40;
int DLOAD_3 = 41;
int DMUL = 107;
int DNEG = 119;
int DREM = 115;
int DRETURN = 175;
int DSTORE = 57;
int DSTORE_0 = 71;
int DSTORE_1 = 72;
int DSTORE_2 = 73;
int DSTORE_3 = 74;
int DSUB = 103;
int DUP = 89;
int DUP2 = 92;
int DUP2_X1 = 93;
int DUP2_X2 = 94;
int DUP_X1 = 90;
int DUP_X2 = 91;
int F2D = 141;
int F2I = 139;
int F2L = 140;
int FADD = 98;
int FALOAD = 48;
int FASTORE = 81;
int FCMPG = 150;
int FCMPL = 149;
int FCONST_0 = 11;
int FCONST_1 = 12;
int FCONST_2 = 13;
int FDIV = 110;
int FLOAD = 23;
int FLOAD_0 = 34;
int FLOAD_1 = 35;
int FLOAD_2 = 36;
int FLOAD_3 = 37;
int FMUL = 106;
int FNEG = 118;
int FREM = 114;
int FRETURN = 174;
int FSTORE = 56;
int FSTORE_0 = 67;
int FSTORE_1 = 68;
int FSTORE_2 = 69;
int FSTORE_3 = 70;
int FSUB = 102;
int GETFIELD = 180;
int GETSTATIC = 178;
int GOTO = 167;
int GOTO_W = 200;
int I2B = 145;
int I2C = 146;
int I2D = 135;
int I2F = 134;
int I2L = 133;
int I2S = 147;
int IADD = 96;
int IALOAD = 46;
int IAND = 126;
int IASTORE = 79;
int ICONST_0 = 3;
int ICONST_1 = 4;
int ICONST_2 = 5;
int ICONST_3 = 6;
int ICONST_4 = 7;
int ICONST_5 = 8;
int ICONST_M1 = 2;
int IDIV = 108;
int IFEQ = 153;
int IFGE = 156;
int IFGT = 157;
int IFLE = 158;
int IFLT = 155;
int IFNE = 154;
int IFNONNULL = 199;
int IFNULL = 198;
int IF_ACMPEQ = 165;
int IF_ACMPNE = 166;
int IF_ICMPEQ = 159;
int IF_ICMPGE = 162;
int IF_ICMPGT = 163;
int IF_ICMPLE = 164;
int IF_ICMPLT = 161;
int IF_ICMPNE = 160;
int IINC = 132;
int ILOAD = 21;
int ILOAD_0 = 26;
int ILOAD_1 = 27;
int ILOAD_2 = 28;
int ILOAD_3 = 29;
int IMUL = 104;
int INEG = 116;
int INSTANCEOF = 193;
int INVOKEDYNAMIC = 186;
int INVOKEINTERFACE = 185;
int INVOKESPECIAL = 183;
int INVOKESTATIC = 184;
int INVOKEVIRTUAL = 182;
int IOR = 128;
int IREM = 112;
int IRETURN = 172;
int ISHL = 120;
int ISHR = 122;
int ISTORE = 54;
int ISTORE_0 = 59;
int ISTORE_1 = 60;
int ISTORE_2 = 61;
int ISTORE_3 = 62;
int ISUB = 100;
int IUSHR = 124;
int IXOR = 130;
int JSR = 168;
int JSR_W = 201;
int L2D = 138;
int L2F = 137;
int L2I = 136;
int LADD = 97;
int LALOAD = 47;
int LAND = 127;
int LASTORE = 80;
int LCMP = 148;
int LCONST_0 = 9;
int LCONST_1 = 10;
int LDC = 18;
int LDC2_W = 20;
int LDC_W = 19;
int LDIV = 109;
int LLOAD = 22;
int LLOAD_0 = 30;
int LLOAD_1 = 31;
int LLOAD_2 = 32;
int LLOAD_3 = 33;
int LMUL = 105;
int LNEG = 117;
int LOOKUPSWITCH = 171;
int LOR = 129;
int LREM = 113;
int LRETURN = 173;
int LSHL = 121;
int LSHR = 123;
int LSTORE = 55;
int LSTORE_0 = 63;
int LSTORE_1 = 64;
int LSTORE_2 = 65;
int LSTORE_3 = 66;
int LSUB = 101;
int LUSHR = 125;
int LXOR = 131;
int MONITORENTER = 194;
int MONITOREXIT = 195;
int MULTIANEWARRAY = 197;
int NEW = 187;
int NEWARRAY = 188;
int NOP = 0;
int POP = 87;
int POP2 = 88;
int PUTFIELD = 181;
int PUTSTATIC = 179;
int RET = 169;
int RETURN = 177;
int SALOAD = 53;
int SASTORE = 86;
int SIPUSH = 17;
int SWAP = 95;
int TABLESWITCH = 170;
int WIDE = 196;
/* array-type code for the newarray instruction */
int T_BOOLEAN = 4;
int T_CHAR = 5;
int T_FLOAT = 6;
int T_DOUBLE = 7;
int T_BYTE = 8;
int T_SHORT = 9;
int T_INT = 10;
int T_LONG = 11;
/* how many values are pushed on the operand stack. */
int[] STACK_GROW = {
0, // nop, 0
1, // aconst_null, 1
1, // iconst_m1, 2
1, // iconst_0, 3
1, // iconst_1, 4
1, // iconst_2, 5
1, // iconst_3, 6
1, // iconst_4, 7
1, // iconst_5, 8
2, // lconst_0, 9
2, // lconst_1, 10
1, // fconst_0, 11
1, // fconst_1, 12
1, // fconst_2, 13
2, // dconst_0, 14
2, // dconst_1, 15
1, // bipush, 16
1, // sipush, 17
1, // ldc, 18
1, // ldc_w, 19
2, // ldc2_w, 20
1, // iload, 21
2, // lload, 22
1, // fload, 23
2, // dload, 24
1, // aload, 25
1, // iload_0, 26
1, // iload_1, 27
1, // iload_2, 28
1, // iload_3, 29
2, // lload_0, 30
2, // lload_1, 31
2, // lload_2, 32
2, // lload_3, 33
1, // fload_0, 34
1, // fload_1, 35
1, // fload_2, 36
1, // fload_3, 37
2, // dload_0, 38
2, // dload_1, 39
2, // dload_2, 40
2, // dload_3, 41
1, // aload_0, 42
1, // aload_1, 43
1, // aload_2, 44
1, // aload_3, 45
-1, // iaload, 46
0, // laload, 47
-1, // faload, 48
0, // daload, 49
-1, // aaload, 50
-1, // baload, 51
-1, // caload, 52
-1, // saload, 53
-1, // istore, 54
-2, // lstore, 55
-1, // fstore, 56
-2, // dstore, 57
-1, // astore, 58
-1, // istore_0, 59
-1, // istore_1, 60
-1, // istore_2, 61
-1, // istore_3, 62
-2, // lstore_0, 63
-2, // lstore_1, 64
-2, // lstore_2, 65
-2, // lstore_3, 66
-1, // fstore_0, 67
-1, // fstore_1, 68
-1, // fstore_2, 69
-1, // fstore_3, 70
-2, // dstore_0, 71
-2, // dstore_1, 72
-2, // dstore_2, 73
-2, // dstore_3, 74
-1, // astore_0, 75
-1, // astore_1, 76
-1, // astore_2, 77
-1, // astore_3, 78
-3, // iastore, 79
-4, // lastore, 80
-3, // fastore, 81
-4, // dastore, 82
-3, // aastore, 83
-3, // bastore, 84
-3, // castore, 85
-3, // sastore, 86
-1, // pop, 87
-2, // pop2, 88
1, // dup, 89
1, // dup_x1, 90
1, // dup_x2, 91
2, // dup2, 92
2, // dup2_x1, 93
2, // dup2_x2, 94
0, // swap, 95
-1, // iadd, 96
-2, // ladd, 97
-1, // fadd, 98
-2, // dadd, 99
-1, // isub, 100
-2, // lsub, 101
-1, // fsub, 102
-2, // dsub, 103
-1, // imul, 104
-2, // lmul, 105
-1, // fmul, 106
-2, // dmul, 107
-1, // idiv, 108
-2, // ldiv, 109
-1, // fdiv, 110
-2, // ddiv, 111
-1, // irem, 112
-2, // lrem, 113
-1, // frem, 114
-2, // drem, 115
0, // ineg, 116
0, // lneg, 117
0, // fneg, 118
0, // dneg, 119
-1, // ishl, 120
-1, // lshl, 121
-1, // ishr, 122
-1, // lshr, 123
-1, // iushr, 124
-1, // lushr, 125
-1, // iand, 126
-2, // land, 127
-1, // ior, 128
-2, // lor, 129
-1, // ixor, 130
-2, // lxor, 131
0, // iinc, 132
1, // i2l, 133
0, // i2f, 134
1, // i2d, 135
-1, // l2i, 136
-1, // l2f, 137
0, // l2d, 138
0, // f2i, 139
1, // f2l, 140
1, // f2d, 141
-1, // d2i, 142
0, // d2l, 143
-1, // d2f, 144
0, // i2b, 145
0, // i2c, 146
0, // i2s, 147
-3, // lcmp, 148
-1, // fcmpl, 149
-1, // fcmpg, 150
-3, // dcmpl, 151
-3, // dcmpg, 152
-1, // ifeq, 153
-1, // ifne, 154
-1, // iflt, 155
-1, // ifge, 156
-1, // ifgt, 157
-1, // ifle, 158
-2, // if_icmpeq, 159
-2, // if_icmpne, 160
-2, // if_icmplt, 161
-2, // if_icmpge, 162
-2, // if_icmpgt, 163
-2, // if_icmple, 164
-2, // if_acmpeq, 165
-2, // if_acmpne, 166
0, // goto, 167
1, // jsr, 168
0, // ret, 169
-1, // tableswitch, 170
-1, // lookupswitch, 171
-1, // ireturn, 172
-2, // lreturn, 173
-1, // freturn, 174
-2, // dreturn, 175
-1, // areturn, 176
0, // return, 177
0, // getstatic, 178 depends on the type
0, // putstatic, 179 depends on the type
0, // getfield, 180 depends on the type
0, // putfield, 181 depends on the type
0, // invokevirtual, 182 depends on the type
0, // invokespecial, 183 depends on the type
0, // invokestatic, 184 depends on the type
0, // invokeinterface, 185 depends on the type
0, // invokedynaimc, 186 depends on the type
1, // new, 187
0, // newarray, 188
0, // anewarray, 189
0, // arraylength, 190
-1, // athrow, 191 stack is cleared
0, // checkcast, 192
0, // instanceof, 193
-1, // monitorenter, 194
-1, // monitorexit, 195
0, // wide, 196 depends on the following opcode
0, // multianewarray, 197 depends on the dimensions
-1, // ifnull, 198
-1, // ifnonnull, 199
0, // goto_w, 200
1 // jsr_w, 201
};
}
| 6,211 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.j2ee.deployment.plugins.spi;
import org.netbeans.modules.j2ee.deployment.impl.ServerRegistry;
import org.netbeans.modules.j2ee.deployment.impl.ServerRegistryTestBase;
import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceCreationException;
import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
/**
*
* @author <NAME>
*/
public class UrlPatternTest extends ServerRegistryTestBase {
private static final String TEST_URL_PREFIX_PERMITTED = "permittedfooservice:";
private static final String TEST_URL_PREFIX_FORBIDDEN = "forbiddenfooservice:";
public UrlPatternTest(String name) {
super(name);
}
public void testPermittedPattern() throws InstanceCreationException {
InstanceProperties.createInstanceProperties(
TEST_URL_PREFIX_PERMITTED + "testPermitted", "test", "password", "Permitted instance");
}
public void testForbiddenPattern() throws InstanceCreationException {
try {
InstanceProperties.createInstanceProperties(
TEST_URL_PREFIX_FORBIDDEN + "testForbidden", "test", "password", "Forbidden instance");
fail("Forbidden instance registered");
} catch (InstanceCreationException ex) {
// expected
}
}
}
| 678 |
432 | <gh_stars>100-1000
/*
* Copyright (c) 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* pcap-common.h - common code for pcap and pcapng files
*/
/*
* We use the "receiver-makes-right" approach to byte order,
* because time is at a premium when we are writing the file.
* In other words, the pcap_file_header and pcap_pkthdr,
* records are written in host byte order.
* Note that the bytes of packet data are written out in the order in
* which they were received, so multi-byte fields in packets are not
* written in host byte order, they're written in whatever order the
* sending machine put them in.
*
* ntoh[ls] aren't sufficient because we might need to swap on a big-endian
* machine (if the file was written in little-end order).
*/
#define SWAPLONG(y) \
(((((u_int)(y))&0xff)<<24) | \
((((u_int)(y))&0xff00)<<8) | \
((((u_int)(y))&0xff0000)>>8) | \
((((u_int)(y))>>24)&0xff))
#define SWAPSHORT(y) \
((u_short)(((((u_int)(y))&0xff)<<8) | \
((((u_int)(y))&0xff00)>>8)))
extern int dlt_to_linktype(int dlt);
extern int linktype_to_dlt(int linktype);
extern void swap_pseudo_headers(int linktype, struct pcap_pkthdr *hdr,
u_char *data);
extern u_int max_snaplen_for_dlt(int dlt);
| 716 |
1,723 | from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.vertices = vertices
def add_edge(self, u, v):
self.graph[u].append(v)
def print_path(self, s, d, visited, path):
visited[s] = True
path.append(s)
if s == d:
print(path)
else:
for i in self.graph[s]:
if visited[i] == False:
self.print_path(i, d, visited, path)
# If path from this node does not lead to the destination, remove it
# from the path stack and mark it as not visited
path.pop()
visited[s] = False
def print_all_paths(self, s, d):
visited = [False] * self.vertices
path = []
self.print_path(s, d, visited, path)
g = Graph(4)
g.add_edge(0, 3)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(2, 0)
g.add_edge(2, 1)
s = 2
d = 3
print(f'Paths from {s} to {d} are - ')
g.print_all_paths(s, d) | 580 |
3,477 | // Copyright Microsoft and Project Verona Contributors.
// SPDX-License-Identifier: MIT
#include <ds/scramble.h>
// Simple test that perm is not preserving orders.
int main()
{
xoroshiro::p128r32 r(2);
bool failed = false;
for (size_t i = 0; i < 100; i++)
{
verona::Scramble s1;
s1.setup(r);
verona::Scramble s2;
s2.setup(r);
size_t count = 0;
for (uintptr_t p = 0; p < 1000; p++)
{
if ((s1.perm(p) < s1.perm(p + 1)) == (s2.perm(p) < s2.perm(p + 1)))
count++;
}
if (count > 550 || count < 450)
{
failed = true;
std::cout << "Count same: " << count << std::endl;
}
}
if (failed)
return 1;
else
return 0;
}
| 363 |
2,206 | <gh_stars>1000+
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.datavec.api.transform.transform.floattransform;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.datavec.api.transform.metadata.ColumnMetaData;
import org.datavec.api.transform.metadata.FloatMetaData;
import org.datavec.api.writable.FloatWritable;
import org.datavec.api.writable.Writable;
import org.datavec.api.writable.WritableType;
@NoArgsConstructor
@Data
public class ConvertToFloat extends BaseFloatTransform {
/**
* @param column Name of the column to convert to a Float column
*/
public ConvertToFloat(String column) {
super(column);
}
@Override
public FloatWritable map(Writable writable) {
if(writable.getType() == WritableType.Double){
return (FloatWritable)writable;
}
return new FloatWritable(writable.toFloat());
}
@Override
public Object map(Object input) {
if(input instanceof Number){
return ((Number) input).floatValue();
}
return Float.parseFloat(input.toString());
}
@Override
public ColumnMetaData getNewColumnMetaData(String newColumnName, ColumnMetaData oldColumnType) {
return new FloatMetaData(newColumnName);
}
@Override
public String toString() {
return "ConvertToFloat(columnName=" + columnName + ")";
}
}
| 719 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Amenoncourt","circ":"4ème circonscription","dpt":"Meurthe-et-Moselle","inscrits":70,"abs":38,"votants":32,"blancs":0,"nuls":2,"exp":30,"res":[{"nuance":"LR","nom":"<NAME>","voix":22},{"nuance":"REM","nom":"<NAME>","voix":8}]} | 116 |
2,338 | <reponame>undingen/BOLT<filename>clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vfmin.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
// REQUIRES: riscv-registered-target
// RUN: %clang_cc1 -triple riscv64 -target-feature +f -target-feature +d -target-feature +experimental-v \
// RUN: -disable-O0-optnone -emit-llvm %s -o - | opt -S -mem2reg | FileCheck --check-prefix=CHECK-RV64 %s
#include <riscv_vector.h>
//
// CHECK-RV64-LABEL: @test_vfmin_vv_f32mf2(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 1 x float> @llvm.riscv.vfmin.nxv1f32.nxv1f32.i64(<vscale x 1 x float> [[OP1:%.*]], <vscale x 1 x float> [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 1 x float> [[TMP0]]
//
vfloat32mf2_t test_vfmin_vv_f32mf2(vfloat32mf2_t op1, vfloat32mf2_t op2,
size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vf_f32mf2(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 1 x float> @llvm.riscv.vfmin.nxv1f32.f32.i64(<vscale x 1 x float> [[OP1:%.*]], float [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 1 x float> [[TMP0]]
//
vfloat32mf2_t test_vfmin_vf_f32mf2(vfloat32mf2_t op1, float op2, size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vv_f32m1(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 2 x float> @llvm.riscv.vfmin.nxv2f32.nxv2f32.i64(<vscale x 2 x float> [[OP1:%.*]], <vscale x 2 x float> [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 2 x float> [[TMP0]]
//
vfloat32m1_t test_vfmin_vv_f32m1(vfloat32m1_t op1, vfloat32m1_t op2,
size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vf_f32m1(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 2 x float> @llvm.riscv.vfmin.nxv2f32.f32.i64(<vscale x 2 x float> [[OP1:%.*]], float [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 2 x float> [[TMP0]]
//
vfloat32m1_t test_vfmin_vf_f32m1(vfloat32m1_t op1, float op2, size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vv_f32m2(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 4 x float> @llvm.riscv.vfmin.nxv4f32.nxv4f32.i64(<vscale x 4 x float> [[OP1:%.*]], <vscale x 4 x float> [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 4 x float> [[TMP0]]
//
vfloat32m2_t test_vfmin_vv_f32m2(vfloat32m2_t op1, vfloat32m2_t op2,
size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vf_f32m2(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 4 x float> @llvm.riscv.vfmin.nxv4f32.f32.i64(<vscale x 4 x float> [[OP1:%.*]], float [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 4 x float> [[TMP0]]
//
vfloat32m2_t test_vfmin_vf_f32m2(vfloat32m2_t op1, float op2, size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vv_f32m4(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 8 x float> @llvm.riscv.vfmin.nxv8f32.nxv8f32.i64(<vscale x 8 x float> [[OP1:%.*]], <vscale x 8 x float> [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 8 x float> [[TMP0]]
//
vfloat32m4_t test_vfmin_vv_f32m4(vfloat32m4_t op1, vfloat32m4_t op2,
size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vf_f32m4(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 8 x float> @llvm.riscv.vfmin.nxv8f32.f32.i64(<vscale x 8 x float> [[OP1:%.*]], float [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 8 x float> [[TMP0]]
//
vfloat32m4_t test_vfmin_vf_f32m4(vfloat32m4_t op1, float op2, size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vv_f32m8(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 16 x float> @llvm.riscv.vfmin.nxv16f32.nxv16f32.i64(<vscale x 16 x float> [[OP1:%.*]], <vscale x 16 x float> [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 16 x float> [[TMP0]]
//
vfloat32m8_t test_vfmin_vv_f32m8(vfloat32m8_t op1, vfloat32m8_t op2,
size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vf_f32m8(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 16 x float> @llvm.riscv.vfmin.nxv16f32.f32.i64(<vscale x 16 x float> [[OP1:%.*]], float [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 16 x float> [[TMP0]]
//
vfloat32m8_t test_vfmin_vf_f32m8(vfloat32m8_t op1, float op2, size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vv_f64m1(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 1 x double> @llvm.riscv.vfmin.nxv1f64.nxv1f64.i64(<vscale x 1 x double> [[OP1:%.*]], <vscale x 1 x double> [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 1 x double> [[TMP0]]
//
vfloat64m1_t test_vfmin_vv_f64m1(vfloat64m1_t op1, vfloat64m1_t op2,
size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vf_f64m1(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 1 x double> @llvm.riscv.vfmin.nxv1f64.f64.i64(<vscale x 1 x double> [[OP1:%.*]], double [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 1 x double> [[TMP0]]
//
vfloat64m1_t test_vfmin_vf_f64m1(vfloat64m1_t op1, double op2, size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vv_f64m2(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 2 x double> @llvm.riscv.vfmin.nxv2f64.nxv2f64.i64(<vscale x 2 x double> [[OP1:%.*]], <vscale x 2 x double> [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 2 x double> [[TMP0]]
//
vfloat64m2_t test_vfmin_vv_f64m2(vfloat64m2_t op1, vfloat64m2_t op2,
size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vf_f64m2(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 2 x double> @llvm.riscv.vfmin.nxv2f64.f64.i64(<vscale x 2 x double> [[OP1:%.*]], double [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 2 x double> [[TMP0]]
//
vfloat64m2_t test_vfmin_vf_f64m2(vfloat64m2_t op1, double op2, size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vv_f64m4(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 4 x double> @llvm.riscv.vfmin.nxv4f64.nxv4f64.i64(<vscale x 4 x double> [[OP1:%.*]], <vscale x 4 x double> [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 4 x double> [[TMP0]]
//
vfloat64m4_t test_vfmin_vv_f64m4(vfloat64m4_t op1, vfloat64m4_t op2,
size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vf_f64m4(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 4 x double> @llvm.riscv.vfmin.nxv4f64.f64.i64(<vscale x 4 x double> [[OP1:%.*]], double [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 4 x double> [[TMP0]]
//
vfloat64m4_t test_vfmin_vf_f64m4(vfloat64m4_t op1, double op2, size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vv_f64m8(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 8 x double> @llvm.riscv.vfmin.nxv8f64.nxv8f64.i64(<vscale x 8 x double> [[OP1:%.*]], <vscale x 8 x double> [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 8 x double> [[TMP0]]
//
vfloat64m8_t test_vfmin_vv_f64m8(vfloat64m8_t op1, vfloat64m8_t op2,
size_t vl) {
return vfmin(op1, op2, vl);
}
//
// CHECK-RV64-LABEL: @test_vfmin_vf_f64m8(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 8 x double> @llvm.riscv.vfmin.nxv8f64.f64.i64(<vscale x 8 x double> [[OP1:%.*]], double [[OP2:%.*]], i64 [[VL:%.*]])
// CHECK-RV64-NEXT: ret <vscale x 8 x double> [[TMP0]]
//
vfloat64m8_t test_vfmin_vf_f64m8(vfloat64m8_t op1, double op2, size_t vl) {
return vfmin(op1, op2, vl);
}
// CHECK-RV64-LABEL: @test_vfmin_vv_f32mf2_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 1 x float> @llvm.riscv.vfmin.mask.nxv1f32.nxv1f32.i64(<vscale x 1 x float> [[MASKEDOFF:%.*]], <vscale x 1 x float> [[OP1:%.*]], <vscale x 1 x float> [[OP2:%.*]], <vscale x 1 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 1 x float> [[TMP0]]
//
vfloat32mf2_t test_vfmin_vv_f32mf2_m(vbool64_t mask, vfloat32mf2_t maskedoff,
vfloat32mf2_t op1, vfloat32mf2_t op2,
size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vf_f32mf2_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 1 x float> @llvm.riscv.vfmin.mask.nxv1f32.f32.i64(<vscale x 1 x float> [[MASKEDOFF:%.*]], <vscale x 1 x float> [[OP1:%.*]], float [[OP2:%.*]], <vscale x 1 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 1 x float> [[TMP0]]
//
vfloat32mf2_t test_vfmin_vf_f32mf2_m(vbool64_t mask, vfloat32mf2_t maskedoff,
vfloat32mf2_t op1, float op2, size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vv_f32m1_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 2 x float> @llvm.riscv.vfmin.mask.nxv2f32.nxv2f32.i64(<vscale x 2 x float> [[MASKEDOFF:%.*]], <vscale x 2 x float> [[OP1:%.*]], <vscale x 2 x float> [[OP2:%.*]], <vscale x 2 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 2 x float> [[TMP0]]
//
vfloat32m1_t test_vfmin_vv_f32m1_m(vbool32_t mask, vfloat32m1_t maskedoff,
vfloat32m1_t op1, vfloat32m1_t op2,
size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vf_f32m1_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 2 x float> @llvm.riscv.vfmin.mask.nxv2f32.f32.i64(<vscale x 2 x float> [[MASKEDOFF:%.*]], <vscale x 2 x float> [[OP1:%.*]], float [[OP2:%.*]], <vscale x 2 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 2 x float> [[TMP0]]
//
vfloat32m1_t test_vfmin_vf_f32m1_m(vbool32_t mask, vfloat32m1_t maskedoff,
vfloat32m1_t op1, float op2, size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vv_f32m2_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 4 x float> @llvm.riscv.vfmin.mask.nxv4f32.nxv4f32.i64(<vscale x 4 x float> [[MASKEDOFF:%.*]], <vscale x 4 x float> [[OP1:%.*]], <vscale x 4 x float> [[OP2:%.*]], <vscale x 4 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 4 x float> [[TMP0]]
//
vfloat32m2_t test_vfmin_vv_f32m2_m(vbool16_t mask, vfloat32m2_t maskedoff,
vfloat32m2_t op1, vfloat32m2_t op2,
size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vf_f32m2_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 4 x float> @llvm.riscv.vfmin.mask.nxv4f32.f32.i64(<vscale x 4 x float> [[MASKEDOFF:%.*]], <vscale x 4 x float> [[OP1:%.*]], float [[OP2:%.*]], <vscale x 4 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 4 x float> [[TMP0]]
//
vfloat32m2_t test_vfmin_vf_f32m2_m(vbool16_t mask, vfloat32m2_t maskedoff,
vfloat32m2_t op1, float op2, size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vv_f32m4_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 8 x float> @llvm.riscv.vfmin.mask.nxv8f32.nxv8f32.i64(<vscale x 8 x float> [[MASKEDOFF:%.*]], <vscale x 8 x float> [[OP1:%.*]], <vscale x 8 x float> [[OP2:%.*]], <vscale x 8 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 8 x float> [[TMP0]]
//
vfloat32m4_t test_vfmin_vv_f32m4_m(vbool8_t mask, vfloat32m4_t maskedoff,
vfloat32m4_t op1, vfloat32m4_t op2,
size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vf_f32m4_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 8 x float> @llvm.riscv.vfmin.mask.nxv8f32.f32.i64(<vscale x 8 x float> [[MASKEDOFF:%.*]], <vscale x 8 x float> [[OP1:%.*]], float [[OP2:%.*]], <vscale x 8 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 8 x float> [[TMP0]]
//
vfloat32m4_t test_vfmin_vf_f32m4_m(vbool8_t mask, vfloat32m4_t maskedoff,
vfloat32m4_t op1, float op2, size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vv_f32m8_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 16 x float> @llvm.riscv.vfmin.mask.nxv16f32.nxv16f32.i64(<vscale x 16 x float> [[MASKEDOFF:%.*]], <vscale x 16 x float> [[OP1:%.*]], <vscale x 16 x float> [[OP2:%.*]], <vscale x 16 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 16 x float> [[TMP0]]
//
vfloat32m8_t test_vfmin_vv_f32m8_m(vbool4_t mask, vfloat32m8_t maskedoff,
vfloat32m8_t op1, vfloat32m8_t op2,
size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vf_f32m8_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 16 x float> @llvm.riscv.vfmin.mask.nxv16f32.f32.i64(<vscale x 16 x float> [[MASKEDOFF:%.*]], <vscale x 16 x float> [[OP1:%.*]], float [[OP2:%.*]], <vscale x 16 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 16 x float> [[TMP0]]
//
vfloat32m8_t test_vfmin_vf_f32m8_m(vbool4_t mask, vfloat32m8_t maskedoff,
vfloat32m8_t op1, float op2, size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vv_f64m1_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 1 x double> @llvm.riscv.vfmin.mask.nxv1f64.nxv1f64.i64(<vscale x 1 x double> [[MASKEDOFF:%.*]], <vscale x 1 x double> [[OP1:%.*]], <vscale x 1 x double> [[OP2:%.*]], <vscale x 1 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 1 x double> [[TMP0]]
//
vfloat64m1_t test_vfmin_vv_f64m1_m(vbool64_t mask, vfloat64m1_t maskedoff,
vfloat64m1_t op1, vfloat64m1_t op2,
size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vf_f64m1_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 1 x double> @llvm.riscv.vfmin.mask.nxv1f64.f64.i64(<vscale x 1 x double> [[MASKEDOFF:%.*]], <vscale x 1 x double> [[OP1:%.*]], double [[OP2:%.*]], <vscale x 1 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 1 x double> [[TMP0]]
//
vfloat64m1_t test_vfmin_vf_f64m1_m(vbool64_t mask, vfloat64m1_t maskedoff,
vfloat64m1_t op1, double op2, size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vv_f64m2_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 2 x double> @llvm.riscv.vfmin.mask.nxv2f64.nxv2f64.i64(<vscale x 2 x double> [[MASKEDOFF:%.*]], <vscale x 2 x double> [[OP1:%.*]], <vscale x 2 x double> [[OP2:%.*]], <vscale x 2 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 2 x double> [[TMP0]]
//
vfloat64m2_t test_vfmin_vv_f64m2_m(vbool32_t mask, vfloat64m2_t maskedoff,
vfloat64m2_t op1, vfloat64m2_t op2,
size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vf_f64m2_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 2 x double> @llvm.riscv.vfmin.mask.nxv2f64.f64.i64(<vscale x 2 x double> [[MASKEDOFF:%.*]], <vscale x 2 x double> [[OP1:%.*]], double [[OP2:%.*]], <vscale x 2 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 2 x double> [[TMP0]]
//
vfloat64m2_t test_vfmin_vf_f64m2_m(vbool32_t mask, vfloat64m2_t maskedoff,
vfloat64m2_t op1, double op2, size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vv_f64m4_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 4 x double> @llvm.riscv.vfmin.mask.nxv4f64.nxv4f64.i64(<vscale x 4 x double> [[MASKEDOFF:%.*]], <vscale x 4 x double> [[OP1:%.*]], <vscale x 4 x double> [[OP2:%.*]], <vscale x 4 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 4 x double> [[TMP0]]
//
vfloat64m4_t test_vfmin_vv_f64m4_m(vbool16_t mask, vfloat64m4_t maskedoff,
vfloat64m4_t op1, vfloat64m4_t op2,
size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vf_f64m4_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 4 x double> @llvm.riscv.vfmin.mask.nxv4f64.f64.i64(<vscale x 4 x double> [[MASKEDOFF:%.*]], <vscale x 4 x double> [[OP1:%.*]], double [[OP2:%.*]], <vscale x 4 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 4 x double> [[TMP0]]
//
vfloat64m4_t test_vfmin_vf_f64m4_m(vbool16_t mask, vfloat64m4_t maskedoff,
vfloat64m4_t op1, double op2, size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vv_f64m8_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 8 x double> @llvm.riscv.vfmin.mask.nxv8f64.nxv8f64.i64(<vscale x 8 x double> [[MASKEDOFF:%.*]], <vscale x 8 x double> [[OP1:%.*]], <vscale x 8 x double> [[OP2:%.*]], <vscale x 8 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 8 x double> [[TMP0]]
//
vfloat64m8_t test_vfmin_vv_f64m8_m(vbool8_t mask, vfloat64m8_t maskedoff,
vfloat64m8_t op1, vfloat64m8_t op2,
size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
// CHECK-RV64-LABEL: @test_vfmin_vf_f64m8_m(
// CHECK-RV64-NEXT: entry:
// CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 8 x double> @llvm.riscv.vfmin.mask.nxv8f64.f64.i64(<vscale x 8 x double> [[MASKEDOFF:%.*]], <vscale x 8 x double> [[OP1:%.*]], double [[OP2:%.*]], <vscale x 8 x i1> [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
// CHECK-RV64-NEXT: ret <vscale x 8 x double> [[TMP0]]
//
vfloat64m8_t test_vfmin_vf_f64m8_m(vbool8_t mask, vfloat64m8_t maskedoff,
vfloat64m8_t op1, double op2, size_t vl) {
return vfmin(mask, maskedoff, op1, op2, vl, VE_TAIL_AGNOSTIC);
}
| 11,335 |
852 | // Description: see header file
#include "CondFormats/DataRecord/interface/L1TCaloStage2ParamsRcd.h"
#include "FWCore/Framework/interface/eventsetuprecord_registration_macro.h"
EVENTSETUP_RECORD_REG(L1TCaloStage2ParamsRcd);
| 82 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.