max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,338 | <reponame>Kirishikesan/haiku
/*
* Copyright 2008-2010, <NAME>, <EMAIL>.
* Copyright 2011, <NAME>, <EMAIL>.
* Copyright 2014 Haiku, Inc. All rights reserved.
*
* Distributed under the terms of the MIT License.
*
* Authors:
* <NAME>, <EMAIL>
* <NAME>, <EMAIL>
* <NAME>, <EMAIL>
*/
#ifndef VOLUME_H
#define VOLUME_H
#include <lock.h>
#include <string.h>
#include <StorageDefs.h>
#include "exfat.h"
#include "SplayTree.h"
struct node_key {
cluster_t cluster;
uint32 offset;
};
struct node {
struct node_key key;
ino_t ino;
ino_t parent;
SplayTreeLink<struct node> nodeTreeLink;
SplayTreeLink<struct node> inoTreeLink;
};
struct NodeTreeDefinition {
typedef struct node_key KeyType;
typedef struct node NodeType;
static KeyType GetKey(const NodeType* node)
{
return node->key;
}
static SplayTreeLink<NodeType>* GetLink(NodeType* node)
{
return &node->nodeTreeLink;
}
static int Compare(KeyType key, const NodeType* node)
{
if (key.cluster == node->key.cluster) {
if (key.offset == node->key.offset)
return 0;
return key.offset < node->key.offset ? -1 : 1;
}
return key.cluster < node->key.cluster ? -1 : 1;
}
};
struct InoTreeDefinition {
typedef ino_t KeyType;
typedef struct node NodeType;
static KeyType GetKey(const NodeType* node)
{
return node->ino;
}
static SplayTreeLink<NodeType>* GetLink(NodeType* node)
{
return &node->inoTreeLink;
}
static int Compare(KeyType key, const NodeType* node)
{
if (key != node->ino)
return key < node->ino ? -1 : 1;
return 0;
}
};
typedef SplayTree<NodeTreeDefinition> NodeTree;
typedef SplayTree<InoTreeDefinition> InoTree;
class Inode;
struct InodesInoTreeDefinition;
typedef IteratableSplayTree<InodesInoTreeDefinition> InodesInoTree;
struct InodesClusterTreeDefinition;
typedef IteratableSplayTree<InodesClusterTreeDefinition> InodesClusterTree;
enum volume_flags {
VOLUME_READ_ONLY = 0x0001
};
class Volume {
public:
Volume(fs_volume* volume);
~Volume();
status_t Mount(const char* device, uint32 flags);
status_t Unmount();
bool IsValidSuperBlock();
bool IsReadOnly() const
{ return (fFlags & VOLUME_READ_ONLY) != 0; }
Inode* RootNode() const { return fRootNode; }
int Device() const { return fDevice; }
dev_t ID() const
{ return fFSVolume ? fFSVolume->id : -1; }
fs_volume* FSVolume() const { return fFSVolume; }
const char* Name() const;
void SetName(const char* name)
{ strlcpy(fName, name, sizeof(fName)); }
uint32 BlockSize() const { return fBlockSize; }
uint32 EntriesPerBlock() const
{ return fEntriesPerBlock; }
uint32 EntriesPerCluster()
{ return fEntriesPerBlock
<< SuperBlock().BlocksPerClusterShift(); }
size_t ClusterSize() { return fBlockSize
<< SuperBlock().BlocksPerClusterShift(); }
exfat_super_block& SuperBlock() { return fSuperBlock; }
status_t LoadSuperBlock();
// cache access
void* BlockCache() { return fBlockCache; }
static status_t Identify(int fd, exfat_super_block* superBlock);
status_t ClusterToBlock(cluster_t cluster,
fsblock_t &block);
Inode * FindInode(ino_t id);
Inode * FindInode(cluster_t cluster);
cluster_t NextCluster(cluster_t cluster);
ino_t GetIno(cluster_t cluster, uint32 offset,
ino_t parent);
struct node_key* GetNode(ino_t ino, ino_t &parent);
private:
ino_t _NextID() { return fNextId++; }
mutex fLock;
fs_volume* fFSVolume;
int fDevice;
exfat_super_block fSuperBlock;
char fName[B_FILE_NAME_LENGTH];
uint16 fFlags;
uint32 fBlockSize;
uint32 fEntriesPerBlock;
Inode* fRootNode;
ino_t fNextId;
void* fBlockCache;
InodesInoTree* fInodesInoTree;
InodesClusterTree* fInodesClusterTree;
NodeTree fNodeTree;
InoTree fInoTree;
};
#endif // VOLUME_H
| 1,701 |
3,428 | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef STDLIB_RANDOM_BASE_MINSTD_H
#define STDLIB_RANDOM_BASE_MINSTD_H
// Note: keep project includes in alphabetical order...
#include <stdint.h>
#include "stdlib/random/base.h"
/*
* If C++, prevent name mangling so that the compiler emits a binary file having undecorated names, thus mirroring the behavior of a C compiler.
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* Declare an opaque type definition for the PRNG state.
*/
typedef struct {
uint32_t seed;
uint32_t state;
} stdlib_base_random_minstd_state_t;
/**
* Returns a pointer to a dynamically allocated PRNG.
*/
struct BasePRNGObject * stdlib_base_random_minstd_allocate( const int32_t seed );
/**
* Frees a PRNG's allocated memory.
*/
void stdlib_base_random_minstd_free( struct BasePRNGObject *obj );
/**
* Returns a PRNG seed.
*/
int8_t stdlib_base_random_minstd_seed( const struct BasePRNGObject *obj, int32_t *out );
/**
* Returns a copy of the current PRNG state.
*/
void * stdlib_base_random_minstd_state( const struct BasePRNGObject *obj );
/**
* Sets the PRNG state.
*/
int8_t stdlib_base_random_minstd_set( struct BasePRNGObject *obj, const void *state );
#ifdef __cplusplus
}
#endif
#endif // !STDLIB_RANDOM_BASE_MINSTD_H
| 605 |
396 | package com.mapbox.api.directionsrefresh.v1;
import com.google.gson.TypeAdapterFactory;
import com.ryanharter.auto.value.gson.GsonTypeAdapterFactory;
/**
* Required so that AutoValue can generate specific type adapters when needed inside the direction
* packages.
*/
@GsonTypeAdapterFactory
public abstract class DirectionsRefreshAdapterFactory implements TypeAdapterFactory {
/**
* Creates a TypeAdapter that AutoValues uses to generate specific type adapters when needed
* inside the direction package classes.
*/
public static TypeAdapterFactory create() {
return new AutoValueGson_DirectionsRefreshAdapterFactory();
}
}
| 169 |
1,538 | <reponame>attilabukor/kudu
// 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.
#include "kudu/master/location_cache.h"
#include <cstdint>
#include <ostream>
#include <string>
#include <thread>
#include <vector>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "kudu/gutil/ref_counted.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/util/metrics.h"
#include "kudu/util/path_util.h"
#include "kudu/util/status.h"
#include "kudu/util/test_macros.h"
#include "kudu/util/test_util.h"
METRIC_DECLARE_counter(location_mapping_cache_hits);
METRIC_DECLARE_counter(location_mapping_cache_queries);
using std::string;
using std::thread;
using std::vector;
using strings::Substitute;
namespace kudu {
namespace master {
// Targeted test for LocationCache.
class LocationCacheTest : public KuduTest {
protected:
void SetUp() override {
KuduTest::SetUp();
metric_entity_ = METRIC_ENTITY_server.Instantiate(&metric_registry_,
"LocationCacheTest");
}
void CheckMetrics(int64_t expected_queries, int64_t expected_hits) {
scoped_refptr<Counter> cache_queries(metric_entity_->FindOrCreateCounter(
&METRIC_location_mapping_cache_queries));
ASSERT_NE(nullptr, cache_queries.get());
ASSERT_EQ(expected_queries, cache_queries->value());
scoped_refptr<Counter> cache_hits(metric_entity_->FindOrCreateCounter(
&METRIC_location_mapping_cache_hits));
ASSERT_NE(nullptr, cache_hits.get());
ASSERT_EQ(expected_hits, cache_hits->value());
}
MetricRegistry metric_registry_;
scoped_refptr<MetricEntity> metric_entity_;
};
TEST_F(LocationCacheTest, EmptyMappingCommand) {
LocationCache cache(" ", metric_entity_.get());
string location;
auto s = cache.GetLocation("na", &location);
ASSERT_TRUE(s.IsRuntimeError()) << s.ToString();
ASSERT_STR_CONTAINS(
s.ToString(), "invalid empty location mapping command");
NO_FATALS(CheckMetrics(1, 0));
}
TEST_F(LocationCacheTest, MappingCommandNotFound) {
LocationCache cache("./notfound.sh", metric_entity_.get());
string location;
auto s = cache.GetLocation("na", &location);
ASSERT_TRUE(s.IsRuntimeError()) << s.ToString();
ASSERT_STR_CONTAINS(
s.ToString(), "failed to run location mapping command: ");
}
TEST_F(LocationCacheTest, MappingCommandFailureExitStatus) {
LocationCache cache("/sbin/nologin", metric_entity_.get());
string location;
auto s = cache.GetLocation("na", &location);
ASSERT_TRUE(s.IsRuntimeError()) << s.ToString();
ASSERT_STR_CONTAINS(
s.ToString(), "failed to run location mapping command: ");
NO_FATALS(CheckMetrics(1, 0));
}
TEST_F(LocationCacheTest, MappingCommandEmptyOutput) {
LocationCache cache("/bin/cat", metric_entity_.get());
string location;
auto s = cache.GetLocation("/dev/null", &location);
ASSERT_TRUE(s.IsRuntimeError()) << s.ToString();
ASSERT_STR_CONTAINS(
s.ToString(), "location mapping command returned invalid empty location");
NO_FATALS(CheckMetrics(1, 0));
}
// Bad cases where the script returns locations with disallowed characters or
// in the wrong format.
TEST_F(LocationCacheTest, MappingCommandReturnsInvalidLocation) {
const vector<string> bad_locations = {
"\"\"", // Empty (doesn't begin with /).
"foo", // Doesn't begin with /.
"/foo$", // Contains the illegal character '$'.
"\"/foo /bar\"", // Contains the illegal character ' '.
};
for (const auto& l : bad_locations) {
SCOPED_TRACE(Substitute("location '$0'", l));
const string cmd_path = JoinPathSegments(GetTestExecutableDirectory(),
"testdata/first_argument.sh");
const string location_mapping_cmd = Substitute("$0 $1", cmd_path, l);
LocationCache cache(location_mapping_cmd, metric_entity_.get());
string location;
auto s = cache.GetLocation("na", &location);
ASSERT_TRUE(s.IsRuntimeError()) << s.ToString();
ASSERT_STR_CONTAINS(
s.ToString(), "location mapping command returned invalid location");
}
NO_FATALS(CheckMetrics(bad_locations.size(), 0));
}
TEST_F(LocationCacheTest, HappyPath) {
const string kRefLocation = "/ref_location";
const string cmd_path = JoinPathSegments(GetTestExecutableDirectory(),
"testdata/first_argument.sh");
const string location_mapping_cmd = Substitute("$0 $1",
cmd_path, kRefLocation);
LocationCache cache(location_mapping_cmd, metric_entity_.get());
NO_FATALS(CheckMetrics(0, 0));
string location;
auto s = cache.GetLocation("key_0", &location);
ASSERT_TRUE(s.ok()) << s.ToString();
ASSERT_EQ(kRefLocation, location);
NO_FATALS(CheckMetrics(1, 0));
s = cache.GetLocation("key_1", &location);
ASSERT_TRUE(s.ok()) << s.ToString();
ASSERT_EQ(kRefLocation, location);
NO_FATALS(CheckMetrics(2, 0));
s = cache.GetLocation("key_1", &location);
ASSERT_TRUE(s.ok()) << s.ToString();
ASSERT_EQ(kRefLocation, location);
NO_FATALS(CheckMetrics(3, 1));
s = cache.GetLocation("key_0", &location);
ASSERT_TRUE(s.ok()) << s.ToString();
ASSERT_EQ(kRefLocation, location);
NO_FATALS(CheckMetrics(4, 2));
}
TEST_F(LocationCacheTest, ConcurrentRequests) {
static constexpr auto kNumThreads = 32;
const string kRefLocation = "/ref_location";
const string cmd_path = JoinPathSegments(GetTestExecutableDirectory(),
"testdata/first_argument.sh");
const string location_mapping_cmd = Substitute("$0 $1",
cmd_path, kRefLocation);
LocationCache cache(location_mapping_cmd, metric_entity_.get());
NO_FATALS(CheckMetrics(0, 0));
for (auto iter = 0; iter < 2; ++iter) {
vector<thread> threads;
threads.reserve(kNumThreads);
for (auto idx = 0; idx < kNumThreads; ++idx) {
threads.emplace_back([&cache, &kRefLocation, idx]() {
string location;
auto s = cache.GetLocation(Substitute("key_$0", idx), &location);
CHECK(s.ok()) << s.ToString();
CHECK_EQ(kRefLocation, location);
});
}
for (auto& t : threads) {
t.join();
}
// Expecting to account for every query, and the follow-up iteration
// should result in every query hitting the cache.
NO_FATALS(CheckMetrics(kNumThreads * (iter + 1),
kNumThreads * iter));
}
}
} // namespace master
} // namespace kudu
| 2,787 |
348 | {"nom":"<NAME>","circ":"5ème circonscription","dpt":"Sarthe","inscrits":1584,"abs":804,"votants":780,"blancs":31,"nuls":6,"exp":743,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":227},{"nuance":"LR","nom":"<NAME>","voix":183},{"nuance":"FN","nom":"M. <NAME>","voix":128},{"nuance":"FI","nom":"M. <NAME>","voix":85},{"nuance":"ECO","nom":"Mme <NAME>","voix":38},{"nuance":"SOC","nom":"M. <NAME>","voix":30},{"nuance":"DLF","nom":"Mme <NAME>","voix":15},{"nuance":"COM","nom":"M. <NAME>","voix":9},{"nuance":"EXD","nom":"Mme <NAME>","voix":8},{"nuance":"DIV","nom":"M. <NAME>","voix":8},{"nuance":"EXG","nom":"Mme <NAME>","voix":6},{"nuance":"DIV","nom":"M. <NAME>","voix":6},{"nuance":"EXD","nom":"Mme <NAME>","voix":0}]} | 297 |
8,772 | package org.apereo.cas.config;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.ticket.BaseTicketCatalogConfigurer;
import org.apereo.cas.ticket.DefaultSecurityTokenTicket;
import org.apereo.cas.ticket.SecurityTokenTicket;
import org.apereo.cas.ticket.TicketCatalog;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
/**
* This is {@link CasWsSecurityTokenTicketCatalogConfiguration}.
*
* @author <NAME>
* @since 5.1.0
*/
@Configuration(value = "casWsSecurityTokenTicketCatalogConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
@Slf4j
public class CasWsSecurityTokenTicketCatalogConfiguration extends BaseTicketCatalogConfigurer {
@Override
public void configureTicketCatalog(final TicketCatalog plan,
final CasConfigurationProperties casProperties) {
LOGGER.debug("Registering core WS security token ticket definitions...");
val definition = buildTicketDefinition(plan, SecurityTokenTicket.PREFIX, DefaultSecurityTokenTicket.class, Ordered.HIGHEST_PRECEDENCE);
val properties = definition.getProperties();
properties.setStorageName("wsSecurityTokenTicketsCache");
properties.setStorageTimeout(casProperties.getTicket().getTgt().getPrimary().getMaxTimeToLiveInSeconds());
registerTicketDefinition(plan, definition);
}
}
| 514 |
591 | <reponame>zhiqiang-hu/apollo-DuerOS
/******************************************************************************
* Copyright 2017 The Baidu Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
package com.baidu.carlifevehicle.view;
import com.baidu.carlifevehicle.CommonParams;
import com.baidu.carlifevehicle.R;
import com.baidu.carlifevehicle.util.LogUtil;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
public class SettingAboutWindow implements OnClickListener {
public static final String TAG = "SettingAboutWindow";
private static SettingAboutWindow mInstance = null;
private ViewGroup mRootView = null;
private Context mContext = null;
private PopupWindow mFullWindow = null;
private View mFullWindowLayout = null;
private ImageButton mExitBtn = null;
private TextView mTvVersionCode;
private static String mPackageName;
private static String mVersionName;
private static int mVersionCode = -1;
private SettingAboutWindow() {
}
public static SettingAboutWindow getInstance() {
if (null == mInstance) {
synchronized (SettingAboutWindow.class) {
if (null == mInstance) {
mInstance = new SettingAboutWindow();
}
}
}
return mInstance;
}
public void init(Context context, ViewGroup parent) {
try {
mContext = context;
mRootView = parent;
mFullWindowLayout = LayoutInflater.from(mContext).inflate(R.layout.frag_setting_about, null);
mFullWindow = new PopupWindow(mFullWindowLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mExitBtn = (ImageButton) mFullWindowLayout.findViewById(R.id.exit_img_btn);
mExitBtn.setOnClickListener(this);
mTvVersionCode = (TextView) mFullWindowLayout.findViewById(R.id.about_tv_version_code);
PackageInfo pi = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
mPackageName = pi.packageName;
mVersionName = pi.versionName;
mVersionCode = pi.versionCode;
String temp = mContext.getString(R.string.version_code_prefix)
+ mVersionName;
if (!"".equals(CommonParams.BUILD_NUMBER)) {
temp += " (" + CommonParams.BUILD_NUMBER + ")";
}
mTvVersionCode.setText(temp);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void displayWindow() {
LogUtil.d(TAG, "----displayWindow()----");
mFullWindow.setFocusable(true);
mFullWindow.showAtLocation(mRootView, Gravity.CENTER, 0, 0);
}
public void closeWindow() {
LogUtil.d(TAG, "----closeWindow()----");
if (mFullWindow != null && mFullWindow.isShowing()) {
mFullWindow.dismiss();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.exit_img_btn:
closeWindow();
break;
default:
break;
}
}
}
| 1,699 |
3,940 | <reponame>tonyping/Open-Shell-Menu
// Classic Shell (c) 2009-2017, <NAME>
// Open-Shell (c) 2017-2018, The Open-Shell Team
// Confidential information of Ivo Beltchev. Not for disclosure or distribution without prior written consent from the author
// Accessibility.cpp - contains the accessibility class CMenuAccessible, used by CMenuContainer
#include "stdafx.h"
#include "Accessibility.h"
#include "MenuContainer.h"
#include "Translations.h"
CMenuAccessible::CMenuAccessible( CMenuContainer *pOwner )
{
m_RefCount=0;
m_pOwner=pOwner;
CreateStdAccessibleObject(pOwner->m_hWnd,OBJID_CLIENT,IID_IAccessible,(void**)&m_pStdAccessible);
}
CMenuAccessible::~CMenuAccessible( void )
{
}
void CMenuAccessible::Reset( void )
{
m_pOwner=NULL;
m_pStdAccessible=NULL;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accParent( IDispatch **ppdispParent )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
if (m_pStdAccessible)
return m_pStdAccessible->get_accParent(ppdispParent);
*ppdispParent=NULL;
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accChildCount( long *pcountChildren )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
*pcountChildren=(long)m_pOwner->m_Items.size();
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accChild( VARIANT varChild, IDispatch **ppdispChild )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
*ppdispChild=NULL; // no child IAccessibles
if (varChild.vt!=VT_I4) return E_INVALIDARG;
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accName( VARIANT varChild, BSTR *pszName )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
*pszName=NULL;
if (varChild.vt!=VT_I4) return S_FALSE;
if (varChild.lVal==CHILDID_SELF) return S_FALSE;
int index=varChild.lVal-1;
if (index<0 || index>=(int)m_pOwner->m_Items.size()) return S_FALSE;
if (m_pOwner->m_Items[index].id==MENU_SEPARATOR) return S_FALSE;
wchar_t text[256];
Strcpy(text,_countof(text),m_pOwner->m_Items[index].name);
for (wchar_t *c1=text,*c2=text;;c1++)
{
if (*c1!='&')
*c2++=*c1;
if (*c1==0) break;
}
*pszName=SysAllocString(text);
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accDescription( VARIANT varChild, BSTR *pszDescription )
{
return get_accName(varChild,pszDescription);
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accRole( VARIANT varChild, VARIANT *pvarRole )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
pvarRole->vt=VT_EMPTY;
if (varChild.vt!=VT_I4) return E_INVALIDARG;
if (varChild.lVal==CHILDID_SELF)
{
pvarRole->vt=VT_I4;
pvarRole->lVal=ROLE_SYSTEM_MENUPOPUP;
return S_OK;
}
int index=varChild.lVal-1;
if (index<0 || index>=(int)m_pOwner->m_Items.size()) return E_INVALIDARG;
pvarRole->vt=VT_I4;
pvarRole->lVal=m_pOwner->m_Items[index].id==MENU_SEPARATOR?ROLE_SYSTEM_SEPARATOR:ROLE_SYSTEM_MENUITEM;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accState( VARIANT varChild, VARIANT *pvarState )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
pvarState->vt=VT_EMPTY;
if (varChild.vt!=VT_I4) return E_INVALIDARG;
int flags=STATE_SYSTEM_FOCUSABLE;
int index=varChild.lVal-1;
if (index>=0 && index<(int)m_pOwner->m_Items.size())
{
const CMenuContainer::MenuItem &item=m_pOwner->m_Items[index];
if (m_pOwner->m_HotItem==index)
flags|=STATE_SYSTEM_FOCUSED;
if (item.bFolder)
flags|=STATE_SYSTEM_HASPOPUP;
if (item.id==MENU_SEPARATOR)
flags=0;
RECT rc;
if (!m_pOwner->GetItemRect(index,rc))
flags|=STATE_SYSTEM_INVISIBLE;
}
pvarState->vt=VT_I4;
pvarState->lVal=flags;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accKeyboardShortcut( VARIANT varChild, BSTR *pszKeyboardShortcut )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
*pszKeyboardShortcut=NULL;
if (varChild.vt!=VT_I4) return E_INVALIDARG;
int flags=0;
int index=varChild.lVal-1;
if (index<0 || index>=(int)m_pOwner->m_Items.size())
return S_FALSE;
const CMenuContainer::MenuItem &item=m_pOwner->m_Items[index];
wchar_t str[2]={item.accelerator,0};
*pszKeyboardShortcut=SysAllocString(str);
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accFocus( VARIANT *pvarChild )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
HWND focus=GetFocus();
pvarChild->vt=VT_EMPTY;
if (m_pOwner->m_hWnd==focus && m_pOwner->m_HotItem>=0)
{
pvarChild->vt=VT_I4;
pvarChild->lVal=m_pOwner->m_HotItem+1;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accSelection( VARIANT *pvarChildren )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
pvarChildren->vt=VT_EMPTY;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::get_accDefaultAction( VARIANT varChild, BSTR *pszDefaultAction )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
*pszDefaultAction=NULL;
if (varChild.vt!=VT_I4) return E_INVALIDARG;
if (varChild.lVal==CHILDID_SELF)
{
*pszDefaultAction=SysAllocString(FindTranslation(L"Menu.ActionClose",L"Close"));
return S_OK;
}
int index=varChild.lVal-1;
if (index<0 || index>=(int)m_pOwner->m_Items.size())
return S_FALSE;
const CMenuContainer::MenuItem &item=m_pOwner->m_Items[index];
if (item.id!=MENU_SEPARATOR && item.id!=MENU_EMPTY && item.id!=MENU_EMPTY_TOP)
*pszDefaultAction=SysAllocString(item.bFolder?FindTranslation(L"Menu.ActionOpen",L"Open"):FindTranslation(L"Menu.ActionExecute",L"Execute"));
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::accSelect( long flagsSelect, VARIANT varChild )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
if (varChild.vt!=VT_I4) return E_INVALIDARG;
if (flagsSelect&SELFLAG_TAKEFOCUS)
{
int index=varChild.lVal-1;
if (index<0 || index>=(int)m_pOwner->m_Items.size())
return S_FALSE;
m_pOwner->ActivateItem(index,CMenuContainer::ACTIVATE_SELECT,NULL);
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::accLocation( long *pxLeft, long *pyTop, long *pcxWidth, long *pcyHeight, VARIANT varChild )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
if (varChild.vt!=VT_I4) return E_INVALIDARG;
RECT rc;
if (varChild.lVal==CHILDID_SELF)
{
m_pOwner->GetWindowRect(&rc);
}
else
{
int index=varChild.lVal-1;
if (index<0 || index>=(int)m_pOwner->m_Items.size())
return S_FALSE;
m_pOwner->GetItemRect(index,rc);
m_pOwner->MapWindowPoints(NULL,&rc);
}
*pxLeft=rc.left;
*pyTop=rc.top;
*pcxWidth=rc.right-rc.left;
*pcyHeight=rc.bottom-rc.top;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::accNavigate( long navDir, VARIANT varStart, VARIANT *pvarEndUpAt )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
pvarEndUpAt->vt=VT_EMPTY;
if (varStart.vt!=VT_I4) return E_INVALIDARG;
switch (navDir)
{
case NAVDIR_FIRSTCHILD:
if (varStart.lVal!=CHILDID_SELF) return S_FALSE;
pvarEndUpAt->vt=VT_I4;
pvarEndUpAt->lVal=1;
break;
case NAVDIR_LASTCHILD:
if (varStart.lVal!=CHILDID_SELF) return S_FALSE;
pvarEndUpAt->vt=VT_I4;
pvarEndUpAt->lVal=(int)m_pOwner->m_Items.size();
break;
case NAVDIR_NEXT:
case NAVDIR_DOWN:
if (varStart.lVal==CHILDID_SELF)
{
if (m_pStdAccessible)
return m_pStdAccessible->accNavigate(navDir,varStart,pvarEndUpAt);
return S_FALSE;
}
if (varStart.lVal>=(int)m_pOwner->m_Items.size())
pvarEndUpAt->vt=VT_EMPTY;
else
{
pvarEndUpAt->vt=VT_I4;
pvarEndUpAt->lVal=varStart.lVal+1;
}
break;
case NAVDIR_PREVIOUS:
case NAVDIR_UP:
if (varStart.lVal==CHILDID_SELF)
{
if (m_pStdAccessible)
return m_pStdAccessible->accNavigate(navDir,varStart,pvarEndUpAt);
return S_FALSE;
}
if (varStart.lVal<1)
pvarEndUpAt->vt=VT_EMPTY;
else
{
pvarEndUpAt->vt=VT_I4;
pvarEndUpAt->lVal=varStart.lVal-1;
}
break;
// Unsupported directions.
case NAVDIR_LEFT:
case NAVDIR_RIGHT:
if (varStart.lVal==CHILDID_SELF)
{
if (m_pStdAccessible)
return m_pStdAccessible->accNavigate(navDir,varStart,pvarEndUpAt);
}
return S_FALSE;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::accHitTest( long xLeft, long yTop, VARIANT *pvarChild )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
POINT pt={xLeft,yTop};
RECT rc;
m_pOwner->GetWindowRect(&rc);
if (!PtInRect(&rc,pt))
{
pvarChild->vt=VT_EMPTY;
return S_FALSE;
}
POINT pt2=pt;
m_pOwner->ScreenToClient(&pt2);
int index=m_pOwner->HitTest(pt2,NULL);
if (index>=0)
{
pvarChild->vt=VT_I4;
pvarChild->lVal=index+1;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CMenuAccessible::accDoDefaultAction( VARIANT varChild )
{
if (!m_pOwner) return RPC_E_DISCONNECTED;
if (varChild.vt!=VT_I4) return E_INVALIDARG;
if (varChild.lVal==CHILDID_SELF)
{
// close
for (std::vector<CMenuContainer*>::reverse_iterator it=CMenuContainer::s_Menus.rbegin();*it!=m_pOwner;++it)
(*it)->PostMessage(WM_CLOSE);
m_pOwner->PostMessage(WM_CLOSE);
return S_OK;
}
int index=varChild.lVal-1;
if (index<0 || index>=(int)m_pOwner->m_Items.size())
return S_FALSE;
// open or execute
const CMenuContainer::MenuItem &item=m_pOwner->m_Items[index];
if (item.id!=MENU_SEPARATOR && item.id!=MENU_EMPTY && item.id!=MENU_EMPTY_TOP)
m_pOwner->ActivateItem(index,item.bFolder?CMenuContainer::ACTIVATE_OPEN:CMenuContainer::ACTIVATE_EXECUTE,NULL,NULL);
return S_OK;
}
| 4,106 |
1,483 | <filename>lealone-common/src/main/java/org/lealone/server/protocol/dt/DTransactionPreparedUpdateAck.java
/*
* Copyright Lealone Database Group.
* Licensed under the Server Side Public License, v 1.
* Initial Developer: zhh
*/
package org.lealone.server.protocol.dt;
import java.io.IOException;
import org.lealone.net.NetInputStream;
import org.lealone.net.NetOutputStream;
import org.lealone.server.protocol.AckPacket;
import org.lealone.server.protocol.PacketDecoder;
import org.lealone.server.protocol.PacketType;
public class DTransactionPreparedUpdateAck implements AckPacket {
public final int updateCount;
public DTransactionPreparedUpdateAck(int updateCount) {
this.updateCount = updateCount;
}
@Override
public PacketType getType() {
return PacketType.DISTRIBUTED_TRANSACTION_PREPARED_UPDATE_ACK;
}
@Override
public void encode(NetOutputStream out, int version) throws IOException {
out.writeInt(updateCount);
}
public static final Decoder decoder = new Decoder();
private static class Decoder implements PacketDecoder<DTransactionPreparedUpdateAck> {
@Override
public DTransactionPreparedUpdateAck decode(NetInputStream in, int version) throws IOException {
return new DTransactionPreparedUpdateAck(in.readInt());
}
}
}
| 455 |
30,023 | <filename>homeassistant/components/broadlink/config_flow.py
"""Config flow for Broadlink devices."""
import errno
from functools import partial
import logging
import socket
import broadlink as blk
from broadlink.exceptions import (
AuthenticationError,
BroadlinkException,
NetworkTimeoutError,
)
import voluptuous as vol
from homeassistant import config_entries, data_entry_flow
from homeassistant.components import dhcp
from homeassistant.const import CONF_HOST, CONF_MAC, CONF_NAME, CONF_TIMEOUT, CONF_TYPE
from homeassistant.helpers import config_validation as cv
from .const import DEFAULT_PORT, DEFAULT_TIMEOUT, DEVICE_TYPES, DOMAIN
from .helpers import format_mac
_LOGGER = logging.getLogger(__name__)
class BroadlinkFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a Broadlink config flow."""
VERSION = 1
def __init__(self):
"""Initialize the Broadlink flow."""
self.device = None
async def async_set_device(self, device, raise_on_progress=True):
"""Define a device for the config flow."""
if device.type not in DEVICE_TYPES:
_LOGGER.error(
"Unsupported device: %s. If it worked before, please open "
"an issue at https://github.com/home-assistant/core/issues",
hex(device.devtype),
)
raise data_entry_flow.AbortFlow("not_supported")
await self.async_set_unique_id(
device.mac.hex(), raise_on_progress=raise_on_progress
)
self.device = device
self.context["title_placeholders"] = {
"name": device.name,
"model": device.model,
"host": device.host[0],
}
async def async_step_dhcp(
self, discovery_info: dhcp.DhcpServiceInfo
) -> data_entry_flow.FlowResult:
"""Handle dhcp discovery."""
host = discovery_info.ip
unique_id = discovery_info.macaddress.lower().replace(":", "")
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured(updates={CONF_HOST: host})
try:
device = await self.hass.async_add_executor_job(blk.hello, host)
except NetworkTimeoutError:
return self.async_abort(reason="cannot_connect")
except OSError as err:
if err.errno == errno.ENETUNREACH:
return self.async_abort(reason="cannot_connect")
return self.async_abort(reason="unknown")
if device.type not in DEVICE_TYPES:
return self.async_abort(reason="not_supported")
await self.async_set_device(device)
return await self.async_step_auth()
async def async_step_user(self, user_input=None):
"""Handle a flow initiated by the user."""
errors = {}
if user_input is not None:
host = user_input[CONF_HOST]
timeout = user_input.get(CONF_TIMEOUT, DEFAULT_TIMEOUT)
try:
hello = partial(blk.hello, host, timeout=timeout)
device = await self.hass.async_add_executor_job(hello)
except NetworkTimeoutError:
errors["base"] = "cannot_connect"
err_msg = "Device not found"
except OSError as err:
if err.errno in {errno.EINVAL, socket.EAI_NONAME}:
errors["base"] = "invalid_host"
err_msg = "Invalid hostname or IP address"
elif err.errno == errno.ENETUNREACH:
errors["base"] = "cannot_connect"
err_msg = str(err)
else:
errors["base"] = "unknown"
err_msg = str(err)
else:
device.timeout = timeout
if self.source != config_entries.SOURCE_REAUTH:
await self.async_set_device(device)
self._abort_if_unique_id_configured(
updates={CONF_HOST: device.host[0], CONF_TIMEOUT: timeout}
)
return await self.async_step_auth()
if device.mac == self.device.mac:
await self.async_set_device(device, raise_on_progress=False)
return await self.async_step_auth()
errors["base"] = "invalid_host"
err_msg = (
"This is not the device you are looking for. The MAC "
f"address must be {format_mac(self.device.mac)}"
)
_LOGGER.error("Failed to connect to the device at %s: %s", host, err_msg)
if self.source == config_entries.SOURCE_IMPORT:
return self.async_abort(reason=errors["base"])
data_schema = {
vol.Required(CONF_HOST): str,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
}
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(data_schema),
errors=errors,
)
async def async_step_auth(self):
"""Authenticate to the device."""
device = self.device
errors = {}
try:
await self.hass.async_add_executor_job(device.auth)
except AuthenticationError:
errors["base"] = "invalid_auth"
await self.async_set_unique_id(device.mac.hex())
return await self.async_step_reset(errors=errors)
except NetworkTimeoutError as err:
errors["base"] = "cannot_connect"
err_msg = str(err)
except BroadlinkException as err:
errors["base"] = "unknown"
err_msg = str(err)
except OSError as err:
if err.errno == errno.ENETUNREACH:
errors["base"] = "cannot_connect"
err_msg = str(err)
else:
errors["base"] = "unknown"
err_msg = str(err)
else:
await self.async_set_unique_id(device.mac.hex())
if self.source == config_entries.SOURCE_IMPORT:
_LOGGER.warning(
"%s (%s at %s) is ready to be configured. Click "
"Configuration in the sidebar, click Integrations and "
"click Configure on the device to complete the setup",
device.name,
device.model,
device.host[0],
)
if device.is_locked:
return await self.async_step_unlock()
return await self.async_step_finish()
await self.async_set_unique_id(device.mac.hex())
_LOGGER.error(
"Failed to authenticate to the device at %s: %s", device.host[0], err_msg
)
return self.async_show_form(step_id="auth", errors=errors)
async def async_step_reset(self, user_input=None, errors=None):
"""Guide the user to unlock the device manually.
We are unable to authenticate because the device is locked.
The user needs to open the Broadlink app and unlock the device.
"""
device = self.device
if user_input is None:
return self.async_show_form(
step_id="reset",
errors=errors,
description_placeholders={
"name": device.name,
"model": device.model,
"host": device.host[0],
},
)
return await self.async_step_user(
{CONF_HOST: device.host[0], CONF_TIMEOUT: device.timeout}
)
async def async_step_unlock(self, user_input=None):
"""Unlock the device.
The authentication succeeded, but the device is locked.
We can offer an unlock to prevent authorization errors.
"""
device = self.device
errors = {}
if user_input is None:
pass
elif user_input["unlock"]:
try:
await self.hass.async_add_executor_job(device.set_lock, False)
except NetworkTimeoutError as err:
errors["base"] = "cannot_connect"
err_msg = str(err)
except BroadlinkException as err:
errors["base"] = "unknown"
err_msg = str(err)
except OSError as err:
if err.errno == errno.ENETUNREACH:
errors["base"] = "cannot_connect"
err_msg = str(err)
else:
errors["base"] = "unknown"
err_msg = str(err)
else:
return await self.async_step_finish()
_LOGGER.error(
"Failed to unlock the device at %s: %s", device.host[0], err_msg
)
else:
return await self.async_step_finish()
data_schema = {vol.Required("unlock", default=False): bool}
return self.async_show_form(
step_id="unlock",
errors=errors,
data_schema=vol.Schema(data_schema),
description_placeholders={
"name": device.name,
"model": device.model,
"host": device.host[0],
},
)
async def async_step_finish(self, user_input=None):
"""Choose a name for the device and create config entry."""
device = self.device
errors = {}
# Abort reauthentication flow.
self._abort_if_unique_id_configured(
updates={CONF_HOST: device.host[0], CONF_TIMEOUT: device.timeout}
)
if user_input is not None:
return self.async_create_entry(
title=user_input[CONF_NAME],
data={
CONF_HOST: device.host[0],
CONF_MAC: device.mac.hex(),
CONF_TYPE: device.devtype,
CONF_TIMEOUT: device.timeout,
},
)
data_schema = {vol.Required(CONF_NAME, default=device.name): str}
return self.async_show_form(
step_id="finish", data_schema=vol.Schema(data_schema), errors=errors
)
async def async_step_import(self, import_info):
"""Import a device."""
self._async_abort_entries_match({CONF_HOST: import_info[CONF_HOST]})
return await self.async_step_user(import_info)
async def async_step_reauth(self, data):
"""Reauthenticate to the device."""
device = blk.gendevice(
data[CONF_TYPE],
(data[CONF_HOST], DEFAULT_PORT),
bytes.fromhex(data[CONF_MAC]),
name=data[CONF_NAME],
)
device.timeout = data[CONF_TIMEOUT]
await self.async_set_device(device)
return await self.async_step_reset()
| 5,382 |
1,418 | // http://oeis.org/A056971
#include "uint.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <unordered_map>
UnsignedInt combination(int N, int M)
{
// printf("Choose N=%d M=%d\n", N, M);
assert(0 <= M && M <= N);
if (M > N/2)
M = N - M;
UnsignedInt result(1);
for (int i = 1; i <= M; ++i)
{
result.multiply(N - i + 1);
int r = result.devide(i);
assert(r == 0);
if (r != 0)
abort();
}
return result;
}
std::unordered_map<int, UnsignedInt> table = {
{ 0, 1 },
{ 1, 1 },
};
const UnsignedInt& num_heaps(int N)
{
UnsignedInt& result = table[N];
if (result.isZero())
{
int h = log2(N);
int left = std::min(pow(2, h)-1, N - pow(2,h-1));
result = combination(N-1, left);
result.multiply(num_heaps(left));
int right = N - 1 - left;
result.multiply(num_heaps(right));
}
else
{
// printf("hit %d\n", N);
}
return result;
}
int main(int argc, char* argv[])
{
if (argc > 1)
{
UnsignedInt result = num_heaps(atoi(argv[1]));
printf("%s\n", result.toDec().c_str());
}
else
{
printf("Usage: %s N\n", argv[0]);
printf("Number of binary heaps on N elements.\n");
}
}
| 566 |
2,151 | <reponame>rhencke/engine
//
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DXTSRGBCompressedTextureTestData.inl
// Data for sRGB DXT texture tests (DXTSRGBCompressedTextureTest.cpp)
//
static constexpr size_t kMaxCompressedSize = 64;
static constexpr size_t kMaxDecompressedSize = 256;
struct TestCase
{
GLsizei width;
GLsizei height;
GLsizei dataSize;
uint8_t data[kMaxCompressedSize];
uint8_t expected[kMaxDecompressedSize];
};
static const std::map<GLenum, TestCase> kTests = {
{
GL_COMPRESSED_SRGB_S3TC_DXT1_EXT,
{
8, 8, 32,
{
0x08, 0xba, 0xe8, 0x45, 0x44, 0x45, 0x40, 0x55, 0xe8, 0xbd, 0x17, 0x42, 0x44, 0x45, 0x40, 0x55,
0x17, 0xba, 0xe8, 0x45, 0x11, 0x10, 0x15, 0x00, 0xf7, 0x45, 0x17, 0x42, 0x11, 0x10, 0x15, 0x00,
},
{
0x82, 0x0d, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x82, 0x0d, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x82, 0x83, 0x0d, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
}
}
},
{
GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,
{
8, 8, 32,
{
0xa8, 0x4d, 0x48, 0xb2, 0x13, 0x10, 0x15, 0x00, 0xe8, 0xbd, 0x17, 0x42, 0x44, 0x45, 0x40, 0x55,
0x17, 0xba, 0xe8, 0x45, 0x11, 0x10, 0x15, 0x00, 0xf7, 0x45, 0x17, 0x42, 0x11, 0x10, 0x15, 0x00,
},
{
0x00, 0x00, 0x00, 0x00, 0x11, 0x77, 0x0d, 0xff, 0x74, 0x11, 0x0d, 0xff, 0x11, 0x77, 0x0d, 0xff,
0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x11, 0x77, 0x0d, 0xff, 0x11, 0x77, 0x0d, 0xff, 0x74, 0x11, 0x0d, 0xff, 0x11, 0x77, 0x0d, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x74, 0x11, 0x0d, 0xff, 0x74, 0x11, 0x0d, 0xff, 0x74, 0x11, 0x0d, 0xff, 0x11, 0x77, 0x0d, 0xff,
0x82, 0x83, 0x0d, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x11, 0x77, 0x0d, 0xff, 0x11, 0x77, 0x0d, 0xff, 0x11, 0x77, 0x0d, 0xff, 0x11, 0x77, 0x0d, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
}
}
},
{
GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,
{
8, 8, 64,
{
0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x08, 0xba, 0xe8, 0x45, 0x44, 0x45, 0x40, 0x55,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe8, 0xbd, 0x17, 0x42, 0x44, 0x45, 0x40, 0x55,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x17, 0xba, 0xe8, 0x45, 0x11, 0x10, 0x15, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf7, 0x45, 0x17, 0x42, 0x11, 0x10, 0x15, 0x00,
},
{
0x82, 0x0d, 0x0d, 0x77, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x82, 0x0d, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x82, 0x83, 0x0d, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
}
}
},
{
GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT,
{
8, 8, 64,
{
0xff, 0x7f, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0xba, 0xe8, 0x45, 0x44, 0x45, 0x40, 0x55,
0xff, 0xff, 0x49, 0x92, 0x24, 0x49, 0x92, 0x24, 0xe8, 0xbd, 0x17, 0x42, 0x44, 0x45, 0x40, 0x55,
0xff, 0xff, 0x49, 0x92, 0x24, 0x49, 0x92, 0x24, 0x17, 0xba, 0xe8, 0x45, 0x11, 0x10, 0x15, 0x00,
0xff, 0xff, 0x49, 0x92, 0x24, 0x49, 0x92, 0x24, 0xf7, 0x45, 0x17, 0x42, 0x11, 0x10, 0x15, 0x00,
},
{
0x82, 0x0d, 0x0d, 0x7f, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x82, 0x0d, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x82, 0x0d, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x82, 0x83, 0x0d, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x82, 0x83, 0x0d, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x0d, 0x83, 0x0d, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x0d, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff, 0x82, 0x0d, 0x82, 0xff,
0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff, 0x0d, 0x83, 0x82, 0xff,
}
}
},
};
| 6,918 |
709 | <reponame>lazear/mlton
/* Copyright (C) 2019 <NAME>.
* Copyright (C) 1999-2008 <NAME>, <NAME>, Suresh
* Jagannathan, and <NAME>.
* Copyright (C) 1997-2000 NEC Research Institute.
*
* MLton is released under a HPND-style license.
* See the file MLton-LICENSE for details.
*/
void GC_share (GC_state s, pointer object) {
size_t bytesExamined;
size_t bytesHashConsed;
struct GC_markState markState;
if (not isPointer (object))
return;
enter (s); /* update stack in heap, in case it is reached */
if (DEBUG_SHARE)
fprintf (stderr, "GC_share "FMTPTR"\n", (uintptr_t)object);
if (DEBUG_SHARE or s->controls.messages)
s->lastMajorStatistics.bytesHashConsed = 0;
// Don't hash cons during the first round of marking.
markState.mode = MARK_MODE;
markState.size = 0;
markState.shouldHashCons = FALSE;
markState.shouldLinkWeaks = FALSE;
dfsMark (s, object, &markState);
bytesExamined = markState.size;
s->objectHashTable = allocHashTable (s);
// Hash cons during the second round of (un)marking.
markState.mode = UNMARK_MODE;
markState.size = 0;
markState.shouldHashCons = TRUE;
dfsMark (s, object, &markState);
freeHashTable (s->objectHashTable);
bytesHashConsed = s->lastMajorStatistics.bytesHashConsed;
s->cumulativeStatistics.bytesHashConsed += bytesHashConsed;
if (DEBUG_SHARE or s->controls.messages)
printBytesHashConsedMessage (bytesHashConsed, bytesExamined);
leave (s);
}
| 504 |
559 | <filename>gaps/progress_bar.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
import sys
def print_progress(iteration, total, prefix="", suffix="", decimals=1, bar_length=50):
""" Call in a loop to create terminal progress bar"""
str_format = "{0:." + str(decimals) + "f}"
percents = str_format.format(100 * (iteration / float(total)))
filled_length = int(round(bar_length * iteration / float(total)))
bar = "\033[32m█\033[0m" * filled_length + "\033[31m-\033[0m" * (bar_length - filled_length)
sys.stdout.write("\r{0: <16} {1} {2}{3} {4}".format(prefix, bar, percents, "%", suffix))
if iteration == total:
sys.stdout.write("\n")
sys.stdout.flush()
| 280 |
14,668 | <gh_stars>1000+
# 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.
import os
import sys
_HEADERS = """ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: DYN (Shared object file)
Machine: ARM
Version: 0x1
Entry point address: 0x0
Start of program headers: 52 (bytes into file)
Start of section headers: 628588000 (bytes into file)
Flags: 0x5000200, Version5 EABI, soft-float ABI
Size of this header: 52 (bytes)
Size of program headers: 32 (bytes)
Number of program headers: 9
Size of section headers: 40 (bytes)
Number of section headers: 40
Section header string table index: 39
"""
_SECTIONS = """There are 40 section headers, starting at offset 0x25777de0:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
[ 1] .interp PROGBITS 00000154 000154 000013 00 A 0 0 1
[ 2] .note.gnu.build-id NOTE 00000168 000168 000024 00 A 0 0 4
[ 3] .dynsym DYNSYM 0000018c 00018c 001960 10 A 4 1 4
[ 4] .dynstr STRTAB 00001b0c 001b0c 000fb9 00 A 0 0 1
[ 5] .hash HASH 00002ad4 002ad4 000a7c 04 A 3 0 4
[ 6] .gnu.version VERSYM 00003558 003558 00032c 02 A 3 0 2
[ 7] .gnu.version_d VERDEF 00003888 003888 00001c 00 A 4 1 4
[ 8] .gnu.version_r VERNEED 000038a4 0038a4 000060 00 A 4 3 4
[ 9] .rel.dyn REL 00003904 003904 288498 08 A 3 0 4
[10] .rel.plt REL 0029fbec 29fbec 000b00 08 A 3 0 4
[11] .plt PROGBITS 002a06ec 2a06ec 001094 00 AX 0 0 4
[12] .text PROGBITS 0028d900 28d900 2250ba8 00 AX 0 0 64
[13] .rodata PROGBITS 0266e5f0 000084 5a72e4 00 A 0 0 256
[14] .ARM.exidx ARM_EXIDX 02bd3d10 2bd3d10 1771c8 08 AL 12 0 4
[15] .ARM.extab PROGBITS 02bd5858 2bd5858 02cd50 00 A 0 0 4
[16] .data.rel.ro.local PROGBITS 02c176f0 2c166f0 0c0e08 00 WA 0 0 16
[17] .data.rel.ro PROGBITS 02cd8500 2cd8500 104108 00 WA 0 0 16
[18] .init_array INIT_ARRAY 02ddc608 2ddc608 000008 00 WA 0 0 4
[19] .fini_array FINI_ARRAY 02ddc6f4 2ddc6f4 000008 00 WA 0 0 4
[20] .dynamic DYNAMIC 02ddc6fc 2ddc6fc 000130 08 WA 4 0 4
[21] .got PROGBITS 02ddc834 2ddc834 00a7cc 00 WA 0 0 4
[22] .data PROGBITS 02de7000 2de7000 018d88 00 WA 0 0 32
[23] .bss NOBITS 02dffda0 2dffda0 13d7e8 00 WA 0 0 32
[35] .note.gnu.gold-version NOTE 00000000 22700c98 00001c 00 0 0 4
[36] .ARM.attributes ARM_ATTRIBUTES 00000000 22700cb4 00003c 00 0 0 1
[37] .symtab SYMTAB 00000000 22700cf0 105ef20 10 38 901679 4
[38] .strtab STRTAB 00000000 234c4950 213a4fe 00 0 0 1
[39] .shstrtab STRTAB 00000000 257b46da 0001b4 00 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
"""
_NOTES = """
Displaying notes found at file offset 0x00000168 with length 0x00000024:
Owner Data size\tDescription
GNU 0x00000014\tNT_GNU_BUILD_ID (unique build ID bitstring)
Build ID: WhatAnAmazingBuildId
Displaying notes found at file offset 0x226c41e8 with length 0x0000001c:
Owner Data size\tDescription
GNU 0x00000009\tNT_GNU_GOLD_VERSION (gold version)
"""
_OBJECT_OUTPUTS = {
'obj/third_party/icu/icuuc/ucnv_ext.o': """\
There are 71 section headers, starting at offset 0x3114:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
[ 1] .strtab STRTAB 00000000 0029ac 000765 00 0 0 1
[ 2] .text PROGBITS 00000000 000034 000000 00 AX 0 0 4
[ 3] .text.ucnv_extIni PROGBITS 00000000 000034 0000c6 00 AX 0 0 2
[ 4] .rel.text.ucnv_ex REL 00000000 0023f4 000010 08 70 3 4
[ 5] .ARM.exidx.text.u ARM_EXIDX 00000000 0000fc 000008 00 AL 3 0 4
[60] .rodata.str1.1 PROGBITS 00000000 000015 000015 01 AMS 0 0 1
[56] .debug_str PROGBITS 00000000 000c50 0003c5 01 MS 0 0 1
[57] .debug_abbrev PROGBITS 00000000 001015 0000a1 00 0 0 1
[58] .debug_info PROGBITS 00000000 0010b6 000151 00 0 0 1
[59] .rel.debug_info REL 00000000 002544 0001e8 08 70 58 4
[60] .debug_ranges PROGBITS 00000000 001207 0000b0 00 0 0 1
[61] .rel.debug_ranges REL 00000000 00272c 000130 08 70 60 4
[62] .debug_macinfo PROGBITS 00000000 0012b7 000001 00 0 0 1
[63] .comment PROGBITS 00000000 0012b8 000024 01 MS 0 0 1
[64] .note.GNU-stack PROGBITS 00000000 0012dc 000000 00 0 0 1
[65] .ARM.attributes ARM_ATTRIBUTES 00000000 0012dc 00003c 00 0 0 1
[66] .debug_frame PROGBITS 00000000 001318 0001e4 00 0 0 4
[67] .rel.debug_frame REL 00000000 00285c 0000e0 08 70 66 4
[68] .debug_line PROGBITS 00000000 0014fc 000965 00 0 0 1
[69] .rel.debug_line REL 00000000 00293c 000070 08 70 68 4
[70] .symtab SYMTAB 00000000 001e64 000590 10 1 74 4
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
""",
'obj/third_party/WebKit.a': """\
File: obj/third_party/WebKit.a(PaintChunker.o)
There are 68 section headers, starting at offset 0x5650:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
File: obj/third_party/WebKit.a(ContiguousContainer.o)
There are 68 section headers, starting at offset 0x5650:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
""",
'obj/base/base/page_allocator.o': """\
There are 68 section headers, starting at offset 0x5650:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
[ 1] .rodata.str1.1 PROGBITS 00000000 000015 000005 01 AMS 0 0 1
""",
'obj/third_party/ffmpeg/libffmpeg_internal.a': """\
File: obj/third_party/ffmpeg/libffmpeg_internal.a(fft_float.o)
There are 68 section headers, starting at offset 0x5650:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
[ 1] .rodata.str1.1 PROGBITS 00000000 000015 000005 01 AMS 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
File: obj/third_party/ffmpeg/libffmpeg_internal.a(fft_fixed.o)
There are 68 section headers, starting at offset 0x5650:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
""",
'../../third_party/gvr-android-sdk/libgvr_shim_static_arm.a': """\
File: ../../third_party/gvr-android-sdk/libgvr_shim_static_arm.a(\
libcontroller_api_impl.a_controller_api_impl.o)
There are 68 section headers, starting at offset 0x5650:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
File: ../../third_party/gvr-android-sdk/libgvr_shim_static_arm.a(\
libport_android_jni.a_jni_utils.o)
There are 68 section headers, starting at offset 0x5650:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
""",
}
def _PrintHeader(path):
sys.stdout.write('\n')
sys.stdout.write('File: ' + path + '\n')
def _PrintOutput(path):
payload = _OBJECT_OUTPUTS.get(os.path.normpath(path))
assert payload, 'No mock_nm.py entry for: ' + path
sys.stdout.write(payload)
sys.stdout.write('\n')
def main():
paths = [p for p in sys.argv[1:] if not p.startswith('-')]
if paths[0].endswith('.o') or paths[0].endswith('.a'):
if len(paths) > 1:
for path in paths:
_PrintHeader(path)
_PrintOutput(path)
else:
_PrintOutput(paths[0])
elif sys.argv[1] == '-h':
sys.stdout.write(_HEADERS)
elif sys.argv[1] == '-S':
sys.stdout.write(_SECTIONS)
elif sys.argv[1] == '-n':
sys.stdout.write(_NOTES)
else:
assert False, 'Invalid args: %s' % sys.argv
if __name__ == '__main__':
main()
| 5,591 |
839 | <filename>tools/wsdlto/misc/src/main/java/org/apache/cxf/tools/misc/WSDLToService.java
/**
* 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.cxf.tools.misc;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import org.apache.cxf.common.i18n.Message;
import org.apache.cxf.tools.common.AbstractCXFToolContainer;
import org.apache.cxf.tools.common.CommandInterfaceUtils;
import org.apache.cxf.tools.common.ToolConstants;
import org.apache.cxf.tools.common.ToolContext;
import org.apache.cxf.tools.common.ToolException;
import org.apache.cxf.tools.common.toolspec.ToolRunner;
import org.apache.cxf.tools.common.toolspec.ToolSpec;
import org.apache.cxf.tools.common.toolspec.parser.BadUsageException;
import org.apache.cxf.tools.common.toolspec.parser.CommandDocument;
import org.apache.cxf.tools.common.toolspec.parser.ErrorVisitor;
import org.apache.cxf.tools.misc.processor.WSDLToServiceProcessor;
public class WSDLToService extends AbstractCXFToolContainer {
static final String TOOL_NAME = "wsdl2service";
public WSDLToService(ToolSpec toolspec) throws Exception {
super(TOOL_NAME, toolspec);
}
private Set<String> getArrayKeys() {
return new HashSet<>();
}
public void execute(boolean exitOnFinish) {
WSDLToServiceProcessor processor = new WSDLToServiceProcessor();
try {
super.execute(exitOnFinish);
if (!hasInfoOption()) {
ToolContext env = new ToolContext();
env.setParameters(getParametersMap(getArrayKeys()));
if (isVerboseOn()) {
env.put(ToolConstants.CFG_VERBOSE, Boolean.TRUE);
}
env.put(ToolConstants.CFG_CMD_ARG, getArgument());
validate(env);
processor.setEnvironment(env);
processor.process();
}
} catch (ToolException ex) {
if (ex.getCause() instanceof BadUsageException) {
printUsageException(TOOL_NAME, (BadUsageException)ex.getCause());
}
err.println();
err.println("WSDLToService Error : " + ex.getMessage());
if (isVerboseOn()) {
ex.printStackTrace(err);
}
} catch (Exception ex) {
err.println();
err.println("WSDLToService Error : " + ex.getMessage());
if (isVerboseOn()) {
ex.printStackTrace(err);
}
} finally {
tearDown();
}
}
private void validate(ToolContext env) throws ToolException {
String outdir = (String)env.get(ToolConstants.CFG_OUTPUTDIR);
if (outdir != null) {
File dir = new File(outdir);
if (!dir.exists() && !dir.mkdirs()) {
Message msg = new Message("DIRECTORY_COULD_NOT_BE_CREATED", LOG, outdir);
throw new ToolException(msg);
}
if (!dir.isDirectory()) {
Message msg = new Message("NOT_A_DIRECTORY", LOG, outdir);
throw new ToolException(msg);
}
}
}
public static void main(String[] pargs) {
CommandInterfaceUtils.commandCommonMain();
try {
ToolRunner.runTool(WSDLToService.class, WSDLToService.class
.getResourceAsStream("wsdl2service.xml"), false, pargs);
} catch (Exception ex) {
System.err.println("Error : " + ex.getMessage());
System.err.println();
ex.printStackTrace();
}
}
public void checkParams(ErrorVisitor errors) throws ToolException {
CommandDocument doc = super.getCommandDocument();
if (!doc.hasParameter("wsdlurl")) {
errors.add(new ErrorVisitor.UserError("WSDL/SCHEMA URL has to be specified"));
}
if (errors.getErrors().size() > 0) {
Message msg = new Message("PARAMETER_MISSING", LOG);
throw new ToolException(msg, new BadUsageException(getUsage(), errors));
}
}
}
| 1,998 |
636 | <gh_stars>100-1000
aa_dict = {
'A' : 'ala',
'C' : 'cys',
'D' : 'asp',
'E' : 'glu',
'F' : 'phe',
'G' : 'gly',
'H' : 'his',
'I' : 'ile',
'K' : 'lys',
'L' : 'leu',
'M' : 'met',
'N' : 'asn',
'P' : 'pro',
'Q' : 'gln',
'R' : 'arg',
'S' : 'ser',
'T' : 'thr',
'V' : 'val',
'W' : 'trp',
'Y' : 'tyr',
}
from pymol import editor
from pymol import cmd
def build(object_name, sequence, first_residue = "1"):
if len(sequence):
code = sequence[0]
cmd.fragment(aa_dict[code],object_name)
cmd.alter(object_name,'resi="%s"'%first_residue)
cmd.edit(object_name+" and name C")
for code in sequence[1:]:
editor.attach_amino_acid("pk1",aa_dict[code])
cmd.edit()
build("poly_ala","ACDEFGHIKLMNPQRSTVWY")
cmd.zoom()
| 443 |
3,897 | <gh_stars>1000+
/*
* Copyright (c) 2013-2017, Pelion and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef UDP_H_
#define UDP_H_
extern void udp_checksum_write(buffer_t *buf);
extern buffer_t *udp_down(buffer_t *buf);
extern buffer_t *udp_up(buffer_t *buf);
/* The network stack has some inbuilt special behaviour for these known ports */
#define UDP_PORT_ECHO 7 /* Echo Protocol - RFC 862 */
#define UDP_PORT_PANA 716 /* Protocol for carrying Authentication for Network Access - RFC 5191 */
#define UDP_PORT_MLE 19788 /* Mesh Link Establishment - draft */
#endif /* UDP_H_ */
| 399 |
6,224 | <reponame>Trifunik/zephyr
/*
* Copyright (c) 2021 IP-Logix Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
#define DT_DRV_COMPAT atmel_sam_mdio
#include <errno.h>
#include <device.h>
#include <init.h>
#include <soc.h>
#include <drivers/mdio.h>
#include <logging/log.h>
LOG_MODULE_REGISTER(mdio_sam, CONFIG_MDIO_LOG_LEVEL);
/* GMAC */
#ifdef CONFIG_SOC_FAMILY_SAM0
#define GMAC_MAN MAN.reg
#define GMAC_NSR NSR.reg
#define GMAC_NCR NCR.reg
#endif
struct mdio_sam_dev_data {
struct k_sem sem;
};
struct mdio_sam_dev_config {
Gmac * const regs;
int protocol;
};
#define DEV_NAME(dev) ((dev)->name)
#define DEV_DATA(dev) ((struct mdio_sam_dev_data *const)(dev)->data)
#define DEV_CFG(dev) \
((const struct mdio_sam_dev_config *const)(dev)->config)
static int mdio_transfer(const struct device *dev, uint8_t prtad, uint8_t devad,
uint8_t rw, uint16_t data_in, uint16_t *data_out)
{
const struct mdio_sam_dev_config *const cfg = DEV_CFG(dev);
struct mdio_sam_dev_data *const data = DEV_DATA(dev);
int timeout = 50;
k_sem_take(&data->sem, K_FOREVER);
/* Write mdio transaction */
if (cfg->protocol == CLAUSE_45) {
cfg->regs->GMAC_MAN = (GMAC_MAN_OP(rw ? 0x2 : 0x3))
| GMAC_MAN_WTN(0x02)
| GMAC_MAN_PHYA(prtad)
| GMAC_MAN_REGA(devad)
| GMAC_MAN_DATA(data_in);
} else if (cfg->protocol == CLAUSE_22) {
cfg->regs->GMAC_MAN = GMAC_MAN_CLTTO
| (GMAC_MAN_OP(rw ? 0x2 : 0x1))
| GMAC_MAN_WTN(0x02)
| GMAC_MAN_PHYA(prtad)
| GMAC_MAN_REGA(devad)
| GMAC_MAN_DATA(data_in);
} else {
LOG_ERR("Unsupported protocol");
}
/* Wait until done */
while (!(cfg->regs->GMAC_NSR & GMAC_NSR_IDLE)) {
if (timeout-- == 0U) {
LOG_ERR("transfer timedout %s", DEV_NAME(dev));
k_sem_give(&data->sem);
return -ETIMEDOUT;
}
k_sleep(K_MSEC(5));
}
if (data_out) {
*data_out = cfg->regs->GMAC_MAN & GMAC_MAN_DATA_Msk;
}
k_sem_give(&data->sem);
return 0;
}
static int mdio_sam_read(const struct device *dev, uint8_t prtad, uint8_t devad,
uint16_t *data)
{
return mdio_transfer(dev, prtad, devad, 1, 0, data);
}
static int mdio_sam_write(const struct device *dev, uint8_t prtad,
uint8_t devad, uint16_t data)
{
return mdio_transfer(dev, prtad, devad, 0, data, NULL);
}
static void mdio_sam_bus_enable(const struct device *dev)
{
const struct mdio_sam_dev_config *const cfg = DEV_CFG(dev);
cfg->regs->GMAC_NCR |= GMAC_NCR_MPE;
}
static void mdio_sam_bus_disable(const struct device *dev)
{
const struct mdio_sam_dev_config *const cfg = DEV_CFG(dev);
cfg->regs->GMAC_NCR &= ~GMAC_NCR_MPE;
}
static int mdio_sam_initialize(const struct device *dev)
{
struct mdio_sam_dev_data *const data = DEV_DATA(dev);
k_sem_init(&data->sem, 1, 1);
return 0;
}
static const struct mdio_driver_api mdio_sam_driver_api = {
.read = mdio_sam_read,
.write = mdio_sam_write,
.bus_enable = mdio_sam_bus_enable,
.bus_disable = mdio_sam_bus_disable,
};
#define MDIO_SAM_CONFIG(n) \
static const struct mdio_sam_dev_config mdio_sam_dev_config_##n = { \
.regs = (Gmac *)DT_REG_ADDR(DT_INST_PARENT(n)), \
.protocol = DT_INST_ENUM_IDX(n, protocol), \
};
#define MDIO_SAM_DEVICE(n) \
MDIO_SAM_CONFIG(n); \
static struct mdio_sam_dev_data mdio_sam_dev_data##n; \
DEVICE_DT_INST_DEFINE(n, \
&mdio_sam_initialize, \
NULL, \
&mdio_sam_dev_data##n, \
&mdio_sam_dev_config_##n, POST_KERNEL, \
CONFIG_MDIO_INIT_PRIORITY, \
&mdio_sam_driver_api);
DT_INST_FOREACH_STATUS_OKAY(MDIO_SAM_DEVICE)
| 1,748 |
474 | package org.javacord.core.event.connection;
import org.javacord.api.DiscordApi;
import org.javacord.api.event.connection.LostConnectionEvent;
import org.javacord.core.event.EventImpl;
/**
* The implementation of {@link LostConnectionEvent}.
*/
public class LostConnectionEventImpl extends EventImpl implements LostConnectionEvent {
/**
* Creates a new lost connection event.
*
* @param api The api instance of the event.
*/
public LostConnectionEventImpl(DiscordApi api) {
super(api);
}
}
| 183 |
1,694 | <reponame>CrackerCat/iWeChat<filename>header6.6.1/KSNewAudioPlayerManager.h
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
@class KSAudioPlayer, LZFileCacheManager;
@protocol KSAudioLogProtocol, OS_dispatch_queue;
@interface KSNewAudioPlayerManager : NSObject
{
NSObject<OS_dispatch_queue> *_audioProcessingQueue;
void *_lzAudioMgrQueueKey;
LZFileCacheManager *_fileCacheMgr;
id <KSAudioLogProtocol> _logObj;
KSAudioPlayer *_curAudioPlayer;
}
+ (id)cachePath;
+ (void)setCachePath:(id)arg1;
+ (id)sharedInstance;
+ (void)initialize;
@property(nonatomic) __weak KSAudioPlayer *curAudioPlayer; // @synthesize curAudioPlayer=_curAudioPlayer;
@property(retain) id <KSAudioLogProtocol> logObj; // @synthesize logObj=_logObj;
- (void).cxx_destruct;
- (void)log:(long long)arg1 file:(const char *)arg2 func:(const char *)arg3 line:(int)arg4 EFDict:(id)arg5 msg:(id)arg6;
- (void)setLogProtocol:(id)arg1;
- (void)audioRouteChangeListenerCallback:(id)arg1;
- (void)interruption:(id)arg1;
- (void)setupAudioSession;
- (id)localCachePath:(id)arg1;
- (_Bool)cacheLocalFile:(id)arg1 fileVid:(id)arg2 fileExt:(id)arg3 removeSrc:(_Bool)arg4;
- (_Bool)isFileAlreadCachedByUrl:(id)arg1;
- (_Bool)isFileAlreadCachedByVid:(id)arg1;
- (_Bool)isFileAlreadCachedByVid:(id)arg1 fileExt:(id)arg2;
- (void)cleanCacheDir:(CDUnknownBlockType)arg1;
- (void)setDefaultCleanFilter:(CDUnknownBlockType)arg1;
- (id)curPlayer;
- (void *)contextKey;
- (id)createAudioPlayer:(id)arg1;
- (id)fileCacheMgr;
- (void)dealloc;
- (id)initInner;
- (id)init;
@end
| 688 |
619 | <gh_stars>100-1000
/*
* Author: <NAME> <<EMAIL>>
* Copyright (c) 2015 Intel Corporation.
*
* This program and the accompanying materials are made available under the
* terms of the The MIT License which is available at
* https://opensource.org/licenses/MIT.
*
* SPDX-License-Identifier: MIT
*/
//NOT TESTED!!!
public class DS1307_Example {
static private void printTime(upm_ds1307.DS1307 rtc) {
System.out.print("The time is: " + rtc.getMonth() + "/" + rtc.getDayOfMonth() + "/"
+ rtc.getYear() + " " + rtc.getHours() + ":" + rtc.getMinutes() + ":"
+ rtc.getSeconds());
if (rtc.getAmPmMode()) {
if (rtc.getAmPmMode())
System.out.print(" PM");
else
System.out.print(" AM");
}
System.out.println();
if (rtc.getAmPmMode())
System.out.println("Clock is in AM/PM mode");
else
System.out.println("Clock is in 24h mode");
}
public static void main(String[] args) throws InterruptedException {
// ! [Interesting]
// Instantiate a DS1037 on I2C bus 0
upm_ds1307.DS1307 rtc = new upm_ds1307.DS1307(0);
// always do this first
System.out.println("Loading the current time...");
if (!rtc.loadTime()) {
System.err.println("rtc->loadTime() failed.");
System.exit(-1);
}
printTime(rtc);
// set the year as an example
System.out.println("setting the year to 50");
rtc.setYear(50);
rtc.setTime();
// reload the time and print it
rtc.loadTime();
printTime(rtc);
// ! [Interesting]
}
} | 575 |
1,162 | package io.digdag.server;
import com.google.inject.Inject;
import org.weakref.jmx.Managed;
import io.digdag.core.ErrorReporter;
import java.util.concurrent.atomic.AtomicInteger;
public class JmxErrorReporter
implements ErrorReporter
{
private final AtomicInteger uncaughtErrorCount = new AtomicInteger(0);
@Inject
public JmxErrorReporter()
{ }
@Override
public void reportUncaughtError(Throwable error)
{
uncaughtErrorCount.incrementAndGet();
}
@Managed
public int getUncaughtErrorCount()
{
return uncaughtErrorCount.get();
}
}
| 225 |
456 | <reponame>pafri/DJV
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2020 <NAME>
// All rights reserved.
#pragma once
#include <djvUI/Widget.h>
class Media;
class DrawerWidget : public djv::UI::Widget
{
DJV_NON_COPYABLE(DrawerWidget);
protected:
void _init(
const std::shared_ptr<Media>&,
const std::shared_ptr<djv::System::Context>&);
DrawerWidget();
public:
~DrawerWidget() override;
static std::shared_ptr<DrawerWidget> create(
const std::shared_ptr<Media>&,
const std::shared_ptr<djv::System::Context>&);
protected:
void _preLayoutEvent(djv::System::Event::PreLayout&) override;
void _layoutEvent(djv::System::Event::Layout&) override;
private:
DJV_PRIVATE();
}; | 307 |
1,668 | package org.elixir_lang.code_insight.lookup.element_renderer;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.psi.PsiElement;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import org.elixir_lang.psi.call.Call;
import org.jetbrains.annotations.NotNull;
public class CallDefinitionClauseTest extends LightPlatformCodeInsightFixtureTestCase {
/*
* Tests
*/
public void testIssue457ShorterName() {
String name = "fo";
LookupElement lookupElement = lookupElement(name);
LookupElementPresentation lookupElementPresentation = new LookupElementPresentation();
lookupElement.renderElement(lookupElementPresentation);
assertEquals(name, lookupElementPresentation.getItemText());
}
public void testIssue457EqualName() {
String name = "foo";
LookupElement lookupElement = lookupElement(name);
LookupElementPresentation lookupElementPresentation = new LookupElementPresentation();
lookupElement.renderElement(lookupElementPresentation);
assertEquals(name, lookupElementPresentation.getItemText());
}
public void testIssue457LongerNameIssue503() {
String name = "fooo";
LookupElement lookupElement = lookupElement(name);
LookupElementPresentation lookupElementPresentation = new LookupElementPresentation();
lookupElement.renderElement(lookupElementPresentation);
assertEquals(name, lookupElementPresentation.getItemText());
}
/*
* Protected Instance Methods
*/
@Override
protected String getTestDataPath() {
return "testData/org/elixir_lang/code_insight/lookup/element_renderer/call_definition_clause";
}
/*
* Private Instance Methods
*/
private LookupElement lookupElement(@NotNull String name) {
myFixture.configureByFile("issue_457.ex");
PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
assertNotNull(elementAtCaret);
PsiElement maybeDefElement = elementAtCaret.getParent().getParent();
assertInstanceOf(maybeDefElement, Call.class);
Call maybeDefCall = (Call) maybeDefElement;
assertTrue(org.elixir_lang.psi.CallDefinitionClause.is(maybeDefCall));
return org.elixir_lang.code_insight.lookup.element.CallDefinitionClause.createWithSmartPointer(
name,
maybeDefElement
);
}
}
| 922 |
848 | /*
* Copyright 2019 Xilinx 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 <iostream>
#include "vitis/ai/parse_value.hpp"
#include "vitis/ai/profiling.hpp"
#include "xir/dpu_controller.hpp"
using namespace std;
int main(int argc, char* argv[]) {
auto dpu = xir::DpuController::get_instance();
auto num = dpu->get_num_of_dpus();
for (auto i = 0u; i < num; ++i) {
auto core_id = dpu->get_core_id(i);
auto device_id = dpu->get_device_id(i);
auto device_core_id = i;
auto fingerprint = dpu->get_fingerprint(i);
auto batch = dpu->get_batch_size(i);
cout << "device_core_id=" << device_core_id << " " //
<< "device= " << device_id //
<< " core = " << core_id //
<< " fingerprint = " << std::hex << "0x" << fingerprint << std::dec //
<< " batch = " << batch //
<< " full_cu_name=" << dpu->get_full_name(device_core_id) << "\n";
}
cout << endl;
}
| 684 |
436 | package org.qiyi.basecore.taskmanager.threadpool;
import android.os.Handler;
import org.qiyi.basecore.taskmanager.TM;
import org.qiyi.basecore.taskmanager.TaskWrapper;
import org.qiyi.basecore.taskmanager.other.TMLog;
public class PendingTaskQueue implements ITaskQueue {
private TaskBlockingQueue rejectedQueue = new TaskBlockingQueue();
private Handler workHandler;
public PendingTaskQueue(Handler handler) {
workHandler = handler;
}
@Override
public Runnable dequeue(int priority) {
return rejectedQueue.pollFirst();
}
@Override
public int size() {
return rejectedQueue.size();
}
@Override
public int getQueueState() {
int size = rejectedQueue.size();
if (size < 1) {
return IDLE;
} else if (size < 3) {
return AVERAGE;
} else if (size > 100) {
return HEAVY;
} else {
return BUSY;
}
}
@Override
public void offer(final TaskWrapper wrapper, final int taskPriority) {
rejectedQueue.addLast(wrapper, taskPriority);
workHandler.post(new Runnable() {
@Override
public void run() {
synchronized (PendingTaskQueue.this) {
PendingTaskQueue.this.notify();
}
}
});
}
@Override
public boolean removeTaskById(int taskId) {
return rejectedQueue.removeTaskById(taskId);
}
@Override
public boolean removeTaskByToken(Object token) {
return rejectedQueue.removeTaskByToken(token);
}
@Override
public void printTasks() {
rejectedQueue.printTasks();
}
}
| 729 |
6,969 | <gh_stars>1000+
#include<iostream>
using namespace std;
const int R=4, C=4;
void printSpiral(int mat[R][C], int R, int C)
{
int top=0, left=0, bottom=R-1, right=C-1;
while(top <= bottom && left <= right)
{
for(int i=left; i<=right; i++)
cout<<mat[top][i]<<" ";
cout<<endl;
top++;
for(int i=top; i<=bottom; i++)
cout<<mat[i][right]<<" ";
cout<<endl;
right--;
if(top <= bottom)
{
for(int i=right; i>=left; i--)
cout<<mat[bottom][i]<<" ";
cout<<endl;
bottom--;
}
if(left <= right)
{
for(int i=bottom; i>=top; i--)
cout<<mat[i][left]<<" ";
cout<<endl;
left++;
}
}
}
int main()
{
cout<<"Spiral Matrix Traversal = \n";
int R=4, C=4;
int mat[4][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
printSpiral(mat, R, C);
cout<<endl;
} | 654 |
739 | <filename>pyjswidgets/pyjamas/dnd/DragEvent.ie6.py
class DragEvent:
def setTarget(self, target=None):
if target is not None:
self.srcElement = target
#self.target = target
else:
self.srcElement = DOM.eventGetTarget(self.evt)
#self.target = target | 149 |
3,710 |
#include "tw/stringtable.h"
// #include "tw/message.h"
//#include "tfilepath.h"
#include "tfilepath_io.h"
#include "tenv.h"
//#include "texception.h"
#include "tsystem.h"
#include "tstream.h"
#include "tconvert.h"
namespace {
//-------------------------------------------------------------------
class TStringTableImp final : public TStringTable {
public:
bool m_initialized;
std::map<std::string, Item> m_table;
std::pair<std::string, int> m_defaultFontNameAndSize;
std::string m_defaultMacFontName;
TStringTableImp();
~TStringTableImp();
void init();
void load(const TFilePath &);
void loadCoded(const TFilePath &);
void saveCoded(const TFilePath &);
const Item *getItem(std::string name) const override;
std::pair<std::string, int> getDefaultFontNameAndSize() const override {
return m_defaultFontNameAndSize;
}
std::string getDefaultMacFontName() const override;
};
//-------------------------------------------------------------------
TStringTableImp::TStringTableImp()
: m_initialized(false)
, m_defaultFontNameAndSize("", 0)
, m_defaultMacFontName("") {}
//-------------------------------------------------------------------
TStringTableImp::~TStringTableImp() {}
//-------------------------------------------------------------------
void TStringTableImp::init() {
if (m_initialized) return;
m_initialized = true;
TFilePath plainFp = TEnv::getConfigDir() + "current.txt";
try {
load(plainFp);
} catch (...) {
}
}
//-------------------------------------------------------------------
std::string TStringTableImp::getDefaultMacFontName() const {
return m_defaultMacFontName;
}
//-------------------------------------------------------------------
void writeShort(Tofstream &os, int x) {
os.put(x & 0xff);
os.put((x >> 8) & 0xff);
}
//-------------------------------------------------------------------
int readShort(Tifstream &is) {
char hi = 0, lo = 0;
is.get(lo);
is.get(hi);
return (unsigned char)hi << 8 | (unsigned char)lo;
}
//-------------------------------------------------------------------
void writeString(Tofstream &os, std::string s) {
int len = s.length();
writeShort(os, len);
os.write(s.c_str(), len);
if (len & 0x3) {
os.write("____", 4 - (len & 0x3));
}
}
//-------------------------------------------------------------------
std::string readString(Tifstream &is) {
int len = readShort(is);
int len2 = len;
if (len2 & 0x3) len2 += 4 - (len2 & 0x3);
char buffer[1204];
assert(len2 <= (int)(sizeof(buffer)));
is.read(buffer, len2);
return std::string(buffer, len);
}
//-------------------------------------------------------------------
void writeStringW(Tofstream &os, std::wstring s) {
int len = s.length();
writeShort(os, len);
os.write(reinterpret_cast<const char *>(s.c_str()), sizeof(wchar_t) * len);
}
//-------------------------------------------------------------------
std::wstring readStringW(Tifstream &is) {
int len = readShort(is);
wchar_t buffer[1204];
assert(len <= (int)(sizeof(buffer)));
is.read(reinterpret_cast<char *>(buffer), sizeof(wchar_t) * len);
return std::wstring(buffer, len);
}
//-------------------------------------------------------------------
#ifdef MACOSX
class TMagic // singleton
{
public:
std::string m_magic;
private:
TMagic() : m_magic("stab.001") {}
public:
static TMagic *instance() {
static TMagic inst;
;
return &inst;
}
};
#else
const std::string magic = "stab.001";
#endif
void TStringTableImp::loadCoded(const TFilePath &fp) {
try {
Tifstream is(fp);
char buffer[1024];
#ifdef MACOSX
is.read(buffer, TMagic::instance()->m_magic.length());
#else
is.read(buffer, magic.length());
#endif
m_defaultFontNameAndSize.first = readString(is);
m_defaultFontNameAndSize.second = readShort(is);
int count = readShort(is);
for (int i = 0; i < count; i++) {
int m = readShort(is);
assert(1 <= m && m <= 3);
std::string id = readString(is);
Item &item = m_table[id];
item.m_name = readStringW(is);
if (m >= 2) {
item.m_help = readStringW(is);
if (m == 3) item.m_tip = readStringW(is);
}
}
int check = readShort(is);
assert(check == 12345);
// if(check != 12345)
// throw;
} catch (...) {
// TMessage::error("Error reading StringTable file: ", fp);
}
}
//-------------------------------------------------------------------
/*
void TStringTableImp::saveCoded(const TFilePath &fp)
{
try {
Tofstream os(fp);
#ifdef MACOSX
os.write(TMagic::instance()->m_magic.c_str(),
TMagic::instance()->m_magic.length());
#else
os.write(magic.c_str(), magic.length());
#endif
writeString(os, m_defaultFontNameAndSize.first);
writeShort(os, m_defaultFontNameAndSize.second);
writeShort(os, m_table.size());
for(std::map<std::string, Item>::iterator it = m_table.begin();
it != m_table.end(); ++it)
{
Item &item = it->second;
int m = 1;
if(item.m_tip != L"") m = 3;
else if(item.m_help != L"") m = 2;
writeShort(os, m);
writeString(os, it->first);
writeStringW(os, item.m_name);
if(m>=2)
{
writeStringW(os, item.m_help);
if(m==3)
writeStringW(os, item.m_tip);
}
}
writeShort(os, 12345);
} catch(...) {
TMessage::error("Unable to save StringTable file: ", fp);
}
}
*/
//-------------------------------------------------------------------
void TStringTableImp::load(const TFilePath &fp) {
if (!TFileStatus(fp).doesExist()) throw TException("file not found");
TIStream is(fp);
if (!is) throw TException("can't read string table ");
std::string tagName;
if (!is.matchTag(tagName) || tagName != "stringtable")
throw TException("not a string table file");
while (!is.matchEndTag()) {
if (!is.matchTag(tagName)) throw TException("expected tag");
if (tagName == "item") {
std::string id, name, help, tip;
is >> id >> name;
if (!is.matchEndTag()) {
is >> help;
if (!is.matchEndTag()) {
is >> tip;
if (!is.matchEndTag()) throw TException("Expected end tag");
}
}
Item &item = m_table[id];
item.m_name = ::to_wstring(name);
item.m_help = ::to_wstring(help);
item.m_tip = ::to_wstring(tip);
} else if (tagName == "defaultFont") {
std::string fontName;
int fontSize = 0;
is >> fontName >> fontSize;
if (!is.matchEndTag()) throw TException("Expected end tag");
m_defaultFontNameAndSize = std::make_pair(fontName, fontSize);
} else if (tagName == "defaultMacFont") {
std::string macFontName;
is >> macFontName;
if (!is.matchEndTag()) throw TException("Expected end tag");
m_defaultMacFontName = macFontName;
} else
throw TException("unexpected tag /" + tagName + "/");
}
// m_valid =true;
}
//-------------------------------------------------------------------
const TStringTable::Item *TStringTableImp::getItem(std::string name) const {
std::map<std::string, Item>::const_iterator it;
it = m_table.find(name);
if (it == m_table.end())
return 0;
else
return &(it->second);
}
//-------------------------------------------------------------------
} // namespace
//-------------------------------------------------------------------
TStringTable::TStringTable() {}
//-------------------------------------------------------------------
TStringTable::~TStringTable() {}
//-------------------------------------------------------------------
std::wstring TStringTable::translate(std::string name) {
const TStringTable::Item *item = instance()->getItem(name);
if (item)
return item->m_name;
else
return ::to_wstring(name);
}
//-------------------------------------------------------------------
const TStringTable *TStringTable::instance() {
// may hurt MacOsX
static TStringTableImp *instance = 0;
if (!instance) instance = new TStringTableImp;
instance->init();
return instance;
}
| 2,894 |
1,553 | from plex.interfaces.core.base import Interface
class PluginInterface(Interface):
path = ':/plugins'
def reload_services(self, plugin_id):
response = self.http.get(plugin_id, 'services/reload')
return response.status_code == 200
def restart(self, plugin_id):
response = self.http.get(plugin_id, 'restart')
return response.status_code == 200
| 141 |
3,200 | <gh_stars>1000+
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
""" test nn ops """
import numpy as np
import pytest
import mindspore
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor, Parameter
from mindspore.common.initializer import initializer
from mindspore.ops import composite as C
from mindspore.ops import operations as P
from mindspore.ops import functional as F
from mindspore.ops.operations import _grad_ops as G
from mindspore.ops import prim_attr_register, PrimitiveWithInfer
from mindspore._c_expression import security
from tests.security_utils import security_off_wrap
from ..ut_filter import non_graph_engine
from ....mindspore_test_framework.mindspore_test import mindspore_test
from ....mindspore_test_framework.pipeline.forward.compile_forward \
import pipeline_for_compile_forward_ge_graph_for_case_by_case_config
from ....mindspore_test_framework.pipeline.forward.verify_exception \
import pipeline_for_verify_exception_for_case_by_case_config
context.set_context(mode=context.GRAPH_MODE)
def conv3x3(in_channels, out_channels, stride=1, padding=1):
"""3x3 convolution """
return nn.Conv2d(in_channels, out_channels,
kernel_size=3, stride=stride, padding=padding)
def conv1x1(in_channels, out_channels, stride=1, padding=0):
"""1x1 convolution"""
return nn.Conv2d(in_channels, out_channels,
kernel_size=1, stride=stride, padding=padding)
grad = C.GradOperation()
grad_all_with_sens = C.GradOperation(get_all=True, sens_param=True)
class ResidualBlock(nn.Cell):
"""
residual Block
"""
expansion = 4
def __init__(self,
in_channels,
out_channels,
stride=1,
down_sample=False):
super(ResidualBlock, self).__init__()
out_chls = out_channels // self.expansion
self.conv1 = conv1x1(in_channels, out_chls, stride=1, padding=0)
self.bn1 = nn.BatchNorm2d(out_chls)
self.conv2 = conv3x3(out_chls, out_chls, stride=stride, padding=0)
self.bn2 = nn.BatchNorm2d(out_chls)
self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
self.bn3 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU()
self.downsample = down_sample
self.conv_down_sample = conv1x1(in_channels, out_channels,
stride=stride, padding=0)
self.bn_down_sample = nn.BatchNorm2d(out_channels)
self.add = P.Add()
def construct(self, x):
"""
:param x:
:return:
"""
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample:
identity = self.conv_down_sample(identity)
identity = self.bn_down_sample(identity)
out = self.add(out, identity)
out = self.relu(out)
return out
class VirtualLossGrad(PrimitiveWithInfer):
""" VirtualLossGrad definition """
@prim_attr_register
def __init__(self):
"""init VirtualLossGrad"""
def __call__(self, x, out, dout):
raise NotImplementedError
def infer_shape(self, x_shape, out_shape, dout_shape):
return x_shape
def infer_dtype(self, x_dtype, out_dtype, dout_dtype):
return x_dtype
class VirtualLoss(PrimitiveWithInfer):
""" VirtualLoss definition """
@prim_attr_register
def __init__(self):
"""init VirtualLoss"""
def __call__(self, x):
raise NotImplementedError
def get_bprop(self):
loss_grad = VirtualLossGrad()
def bprop(x, out, dout):
# pylint: disable=unused-argument
dx = loss_grad(x, out, dout)
return (dx,)
return bprop
def infer_shape(self, x_shape):
return []
def infer_dtype(self, x_dtype):
return x_dtype
class VirtualNetWithLoss(nn.Cell):
""" VirtualNetWithLoss definition """
def __init__(self, network):
super(VirtualNetWithLoss, self).__init__()
self.loss = VirtualLoss()
self.network = network
def construct(self, x):
predict = self.network(x)
return self.loss(predict)
class SoftMaxGrad(nn.Cell):
""" SoftMaxGrad definition """
def __init__(self, network):
super(SoftMaxGrad, self).__init__()
self.network = network
def construct(self, x):
return grad(self.network)(x)
class DropoutGrad(nn.Cell):
""" DropoutGrad definition """
def __init__(self, network):
super(DropoutGrad, self).__init__()
self.network = network
def construct(self, x):
return grad(self.network)(x)
class ScalarSummaryNet(nn.Cell):
""" ScalarSummaryNet definition """
def __init__(self):
super(ScalarSummaryNet, self).__init__()
self.summary = P.ScalarSummary()
def construct(self, scalar):
string_in = "bias_value"
out = self.summary(string_in, scalar)
return out
class L2NormalizeNet(nn.Cell):
""" L2NormalizeNet definition """
def __init__(self):
super(L2NormalizeNet, self).__init__()
self.l2_normalize = P.L2Normalize()
def construct(self, x):
out = self.l2_normalize(x)
return out
class HistogramSummaryNet(nn.Cell):
"""HistogramSummaryNet definition"""
def __init__(self):
super(HistogramSummaryNet, self).__init__()
self.summary = P.HistogramSummary()
def construct(self, tensor):
string_in = "wight_value"
out = self.summary(string_in, tensor)
return out
class FusedBatchNormGrad(nn.Cell):
""" FusedBatchNormGrad definition """
def __init__(self, network):
super(FusedBatchNormGrad, self).__init__()
self.grad = C.GradOperation(get_all=True, sens_param=True)
self.network = network
def construct(self, inp, output_grad):
return self.grad(self.network)(inp, output_grad)
class NetWithLoss(nn.Cell):
""" NetWithLoss definition """
def __init__(self, network):
super(NetWithLoss, self).__init__()
self.loss = P.SmoothL1Loss()
self.network = network
def construct(self, x, label):
predict = self.network(x)
return self.loss(predict, label)
class Grad(nn.Cell):
""" GradWrap definition """
def __init__(self, network):
super(Grad, self).__init__()
self.network = network
self.network.set_train()
def construct(self, x, label):
return grad(self.network)(x, label)
class BatchnormNet(nn.Cell):
""" BatchnormNet definition """
def __init__(self):
super(BatchnormNet, self).__init__()
self.conv1 = nn.Conv2d(3, 4, kernel_size=8, stride=2, pad_mode="pad", padding=3)
self.bn1 = nn.BatchNorm2d(4)
self.flatten = P.Flatten()
self.weight = Parameter(Tensor(np.ones([64, 10], np.float32)), name="weight")
self.bias = Parameter(Tensor(np.ones([10], np.float32)), name="bias")
self.fc = P.MatMul()
self.biasAdd = P.BiasAdd()
def construct(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.flatten(x)
x = self.biasAdd(self.fc(x, self.weight), self.bias)
return x
class NetWithLossClass(nn.Cell):
""" NetWithLossClass definition """
def __init__(self, network):
super(NetWithLossClass, self).__init__(auto_prefix=False)
self.loss = nn.SoftmaxCrossEntropyWithLogits()
self.network = network
def construct(self, x, label):
predict = self.network(x)
return self.loss(predict, label)
class BlockNet(nn.Cell):
""" BlockNet definition """
def __init__(self):
super(BlockNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, pad_mode="pad", padding=3)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU()
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2)
self.block_down_sample = ResidualBlock(
64, 256, stride=1, down_sample=True
)
self.flatten = P.Flatten()
self.weight = Parameter(Tensor(np.ones([1024, 10]).astype(np.float32)), name="weight")
self.bias = Parameter(Tensor(np.ones([10]).astype((np.float32))), name="bias")
self.fc = P.MatMul()
self.biasAdd = P.BiasAdd()
def construct(self, x):
x = self.conv1(x)
return x
class Conv2dWithBiasNet(nn.Cell):
""" Conv2dWithBiasNet definition """
def __init__(self):
super(Conv2dWithBiasNet, self).__init__()
self.conv = nn.Conv2d(3, 10, 1, bias_init='zeros')
self.flatten = P.Flatten()
def construct(self, input_x):
return self.flatten(self.conv(input_x))
class Conv2dNativeNet(nn.Cell):
""" Conv2dNativeNet definition """
def __init__(self):
super(Conv2dNativeNet, self).__init__()
self.conv = P.DepthwiseConv2dNative(channel_multiplier=3, kernel_size=(3, 3))
self.flatten = P.Flatten()
channel_multipliers = 1
in_channels = 3
kernel_size = (3, 3)
self.weight = Parameter(initializer(
Tensor(np.ones([channel_multipliers, in_channels, *kernel_size], dtype=np.float32)),
[channel_multipliers, in_channels, *kernel_size]), name='weight')
def construct(self, input_x):
return self.flatten(self.conv(input_x, self.weight))
class StateNet(nn.Cell):
""" StateTestTensor definition """
def __init__(self):
super(StateNet, self).__init__()
weight = Tensor(np.ones([2, 1, 2, 2], np.float32))
self.s1 = Parameter(weight, name="s1")
self.s2 = Parameter(weight, name="s2")
self.sub = P.Sub()
self.loss = nn.SoftmaxCrossEntropyWithLogits()
self.assign = P.Assign()
def construct(self, x):
x = F.depend(x, self.assign(self.s1, x + self.s1))
self.s1 = self.sub(self.s1, x)
self.s2 = self.sub(self.s2, x)
return x
def test_conv2d_same_primitive():
class Conv2DSameNet(nn.Cell):
def __init__(self):
super(Conv2DSameNet, self).__init__()
self.conv1 = nn.Conv2d(16, 64, (1, 41), (1, 4), "same", 0, 1, has_bias=True)
self.conv2 = nn.Conv2d(16, 64, (1, 41), (1, 4), "same", 0, 1, has_bias=True)
def construct(self, x, y):
r1 = self.conv1(x)
r2 = self.conv2(y)
return (r1, r2)
t1 = Tensor(np.ones([1, 16, 1, 1918]).astype(np.float32))
t2 = Tensor(np.ones([1, 16, 1, 3840]).astype(np.float32))
net = Conv2DSameNet()
net(t1, t2)
class ComparisonNet(nn.Cell):
def __init__(self):
""" ComparisonNet definition """
super(ComparisonNet, self).__init__()
def construct(self, x, y):
ret = x <= y
return ret
def test_max_pool_with_arg_max():
class NetMaxPoolWithArgMax(nn.Cell):
def __init__(self):
""" ComparisonNet definition """
super(NetMaxPoolWithArgMax, self).__init__()
self.max_pool_with_arg_max = P.MaxPoolWithArgmax(pad_mode="valid", kernel_size=2, strides=1)
def construct(self, x):
ret = self.max_pool_with_arg_max(x)
return ret
x = Tensor(np.ones([1, 1, 3, 3], np.float32))
net = NetMaxPoolWithArgMax()
context.set_context(mode=context.GRAPH_MODE)
ret = net(x)
print(ret)
class GradWrapUnfold(nn.Cell):
""" GradWrapUnfold definition """
def __init__(self, network):
super(GradWrapUnfold, self).__init__()
self.network = network
self.sens = Tensor(np.ones([1, 4, 2, 2], np.float32))
def construct(self, x):
return grad_all_with_sens(self.network)(x, self.sens)
class UnfoldNetValid(nn.Cell):
""" UnfoldNetValid definition """
def __init__(self):
super(UnfoldNetValid, self).__init__()
self.unfold = nn.Unfold(ksizes=[1, 2, 2, 1],
strides=[1, 1, 1, 1],
rates=[1, 1, 1, 1],
padding='VALID')
def construct(self, x):
return self.unfold(x)
class UnfoldNetSame(nn.Cell):
""" UnfoldNetSame definition """
def __init__(self):
super(UnfoldNetSame, self).__init__()
self.unfold = nn.Unfold(ksizes=[1, 2, 2, 1],
strides=[1, 1, 1, 1],
rates=[1, 1, 1, 1],
padding='SAME')
def construct(self, x):
return self.unfold(x)
class FlattenNet(nn.Cell):
""" FlattenNet definition """
def __init__(self):
super(FlattenNet, self).__init__()
self.flatten = P.Flatten()
def construct(self, x):
return self.flatten(x)
class PReLUNet(nn.Cell):
""" PReLUNet definition """
def __init__(self):
super(PReLUNet, self).__init__()
self.prelu = P.PReLU()
self.w = Tensor(np.ones(3, np.float32))
def construct(self, x):
return self.prelu(x, self.w)
class PReLUGradNet(nn.Cell):
""" PReLUGradNet definition """
def __init__(self):
super(PReLUGradNet, self).__init__()
self.prelu_grad = G.PReLUGrad()
def construct(self, dout, x, w):
return self.prelu_grad(dout, x, w)
class LRNNet(nn.Cell):
""" LRNNet definition """
def __init__(self):
super(LRNNet, self).__init__()
self.lrn = P.LRN()
def construct(self, x):
return self.lrn(x)
class LRNGradNet(nn.Cell):
""" LRNGradNet definition """
def __init__(self):
super(LRNGradNet, self).__init__()
self.lrn_grad = G.LRNGrad()
def construct(self, dout, x, out):
return self.lrn_grad(dout, x, out)
test_cases = [
('SoftMaxGrad', {
'block': SoftMaxGrad(VirtualNetWithLoss(P.Softmax())),
'desc_inputs': [[128, 32, 32, 64]],
'desc_bprop': [[128, 32, 32, 64]],
}),
('DropoutGrad', {
'block': DropoutGrad(VirtualNetWithLoss(nn.Dropout())),
'desc_inputs': [[128, 32, 32, 64]],
'desc_bprop': [[128, 32, 32, 64]],
}),
('L2Normalize', {
'block': L2NormalizeNet(),
'desc_inputs': [Tensor(np.array([[1.0, 2, 3], [4.0, 5, 6], [7.0, 8, 9]]), mindspore.float32)],
}),
('FusedBatchNormGrad', {
'block': FusedBatchNormGrad(nn.BatchNorm2d(num_features=512, eps=1e-5, momentum=0.1)),
'desc_inputs': [[64, 512, 7, 7], [64, 512, 7, 7]],
'desc_bprop': [[64, 512, 7, 7]],
}),
('BatchnormGrad', {
'block': Grad(NetWithLoss(BatchnormNet())),
'desc_inputs': [Tensor(np.ones([1, 3, 8, 8], np.float32)), Tensor(np.zeros([1, 10], np.float32))],
}),
('BlockGrad', {
'block': Grad(NetWithLossClass(BlockNet())),
'desc_inputs': [Tensor(np.ones([1, 3, 8, 8], np.float32)), Tensor(np.zeros([1, 64, 4, 4], np.float32))],
}),
('Conv2dWithBiasGrad', {
'block': Grad(NetWithLossClass(Conv2dWithBiasNet())),
'desc_inputs': [Tensor(np.ones([1, 3, 16, 16], np.float32)), Tensor(np.zeros([1, 2560], np.float32))],
}),
('Conv2dNativeGrad', {
'block': Grad(NetWithLossClass(Conv2dNativeNet())),
'desc_inputs': [Tensor(np.ones([1, 3, 16, 16], np.float32)), Tensor(np.zeros([1, 1764], np.float32))],
}),
('StateTest', {
'block': StateNet(),
'desc_inputs': [Tensor(np.ones([2, 1, 2, 2]).astype(np.float32))],
}),
('StateGrad', {
'block': Grad(NetWithLossClass(StateNet())),
'desc_inputs': [Tensor(np.ones([2, 1, 2, 2], np.float32)), Tensor(np.ones([2, 1, 2, 2], np.float32))],
}),
('ComparisonTest', {
'block': ComparisonNet(),
'desc_inputs': [Tensor(np.ones([6, 9, 10], np.int32)), Tensor(np.ones([6, 9, 10], np.int32))],
}),
('UnfoldValid', {
'block': UnfoldNetValid(),
'desc_inputs': [Tensor(np.ones([1, 1, 3, 3], np.float32))],
'desc_bprop': [Tensor(np.ones([1, 4, 2, 2], np.float32))],
'skip': ['backward']}),
('UnfoldSame', {
'block': UnfoldNetSame(),
'desc_inputs': [Tensor(np.ones([1, 1, 3, 3], np.float32))],
'desc_bprop': [Tensor(np.ones([1, 4, 3, 3], np.float32))],
'skip': ['backward']}),
('UnfoldGrad', {
'block': GradWrapUnfold(UnfoldNetValid()),
'desc_inputs': [Tensor(np.ones([1, 1, 3, 3], np.float32))],
'desc_bprop': [Tensor(np.ones([1, 4, 2, 2], np.float32))],
'skip': ['backward']}),
('LogSigmoid', {
'block': nn.LogSigmoid(),
'desc_inputs': [Tensor(np.array([1, 2, 3, 4]).astype(np.float32))],
'desc_bprop': [Tensor(np.array([1, 2, 3, 4]).astype(np.float32))],
'skip': ['backward']}),
('ReduceLogSumExp', {
'block': nn.ReduceLogSumExp((0,), False),
'desc_inputs': [Tensor(np.array([3, 4, 5, 6]).astype(np.float32))],
'skip': ['backward']}),
('LGamma', {
'block': nn.LGamma(),
'desc_inputs': [Tensor(np.array([3, 4, 5, 6]).astype(np.float32))],
'skip': ['backward']}),
('IGamma', {
'block': nn.IGamma(),
'desc_inputs': [Tensor(np.array([3, 4, 5, 6]).astype(np.float32)),
Tensor(np.array([3, 4, 5, 6]).astype(np.float32))],
'skip': ['backward']}),
('DiGamma', {
'block': nn.DiGamma(),
'desc_inputs': [Tensor(np.array([3, 4, 5, 6]).astype(np.float32))],
'skip': ['backward']}),
('LBeta', {
'block': nn.LBeta(),
'desc_inputs': [Tensor(np.array([3, 4, 5, 6]).astype(np.float32)),
Tensor(np.array([3, 4, 5, 6]).astype(np.float32))],
'skip': ['backward']}),
('FlattenNet', {
'block': FlattenNet(),
'desc_inputs': [Tensor(np.ones([1, 2, 3, 4], np.float32))],
}),
('PReLUNet', {
'block': PReLUNet(),
'desc_inputs': [Tensor(np.ones([1, 3, 4, 4], np.float32))],
}),
('PReLUGradNet', {
'block': PReLUGradNet(),
'desc_inputs': [Tensor(np.ones([1, 3, 4, 4], np.float32)),
Tensor(np.ones([1, 3, 4, 4], np.float32)),
Tensor(np.ones(3, np.float32))],
}),
('MatrixDiag', {
'block': nn.MatrixDiag(),
'desc_inputs': [Tensor(np.array([1, 2, 3]).astype(np.float32))],
'skip': ['backward']
}),
('MatrixDiagPart', {
'block': nn.MatrixDiagPart(),
'desc_inputs': [Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32))],
'skip': ['backward']
}),
('MatrixSetDiag', {
'block': nn.MatrixSetDiag(),
'desc_inputs': [Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)),
Tensor(np.array([1, 2]).astype(np.float32))],
'skip': ['backward']
}),
('MatInverse', {
'block': nn.MatInverse(),
'desc_inputs': [Tensor(np.array([[4, 12, -16], [12, 37, -43], [-16, -43, 98]]).astype(np.float32))],
'skip': ['backward']
}),
('MatDet', {
'block': nn.MatDet(),
'desc_inputs': [Tensor(np.array([[4, 12, -16], [12, 37, -43], [-16, -43, 98]]).astype(np.float32))],
'skip': ['backward']
}),
('LRNNet', {
'block': LRNNet(),
'desc_inputs': [Tensor(np.ones([1, 5, 4, 4], np.float32))],
}),
('LRNGradNet', {
'block': LRNGradNet(),
'desc_inputs': [Tensor(np.ones([1, 5, 4, 4], np.float32)),
Tensor(np.ones([1, 5, 4, 4], np.float32)),
Tensor(np.ones([1, 5, 4, 4], np.float32))],
}),
]
test_cases_for_verify_exception = [
('ApplyMomentum_Error', {
'block': (P.ApplyMomentum(), {'exception': TypeError}),
'desc_inputs': [[2], [128, 32, 32, 64], [128, 32, 32, 64], [128, 32, 32, 64], [128, 32, 32, 64]],
'desc_bprop': [[128, 32, 32, 64]],
'skip': ['backward']
}),
('Conv2d_ValueError_1', {
'block': (lambda _: P.Conv2D(3, 4, mode=-2.0), {'exception': TypeError}),
'desc_inputs': [0],
}),
('Conv2d_ValueError_2', {
'block': (lambda _: P.Conv2D(3, 4, mode=-2), {'exception': ValueError}),
'desc_inputs': [0],
}),
('MaxPoolWithArgmax_ValueError_1', {
'block': (lambda _: P.MaxPoolWithArgmax(pad_mode='sane'), {'exception': ValueError}),
'desc_inputs': [0],
}),
('MaxPoolWithArgmax_ValueError_2', {
'block': (lambda _: P.MaxPoolWithArgmax(kernel_size='1'), {'exception': TypeError}),
'desc_inputs': [0],
}),
('MaxPoolWithArgmax_ValueError_3', {
'block': (lambda _: P.MaxPoolWithArgmax(kernel_size=-2), {'exception': ValueError}),
'desc_inputs': [0],
}),
('MaxPoolWithArgmax_ValueError_4', {
'block': (lambda _: P.MaxPoolWithArgmax(strides=-1), {'exception': ValueError}),
'desc_inputs': [0],
}),
('Softmax_ValueError_1', {
'block': (lambda _: P.Softmax("1"), {'exception': TypeError}),
'desc_inputs': [0],
}),
('Softmax_ValueError_2', {
'block': (lambda _: P.Softmax(1.1), {'exception': TypeError}),
'desc_inputs': [0],
}),
('Softmax_ValueError_3', {
'block': (lambda _: P.Softmax(axis="1"), {'exception': TypeError}),
'desc_inputs': [0],
}),
('DropoutGenMask_ValueError_1', {
'block': (lambda _: P.DropoutGenMask(Seed0="seed0"), {'exception': TypeError}),
'desc_inputs': [0],
}),
('DropoutGenMask_ValueError_2', {
'block': (lambda _: P.DropoutGenMask(Seed0=1.0), {'exception': TypeError}),
'desc_inputs': [0],
}),
('DropoutGenMask_ValueError_3', {
'block': (lambda _: P.DropoutGenMask(Seed1="seed1"), {'exception': TypeError}),
'desc_inputs': [0],
}),
('DropoutGenMask_ValueError_4', {
'block': (lambda _: P.DropoutGenMask(Seed1=2.0), {'exception': TypeError}),
'desc_inputs': [0],
}),
('MaxPool2d_ValueError_1', {
'block': (nn.MaxPool2d(kernel_size=120, stride=1, pad_mode="valid"), {'exception': ValueError}),
'desc_inputs': [Tensor(np.random.randn(32, 3, 112, 112).astype(np.float32).transpose(0, 3, 1, 2))],
}),
('MaxPool2d_ValueError_2', {
'block': (
lambda _: nn.MaxPool2d(kernel_size=120, stride=True, pad_mode="valid"),
{'exception': TypeError},
),
'desc_inputs': [Tensor(np.random.randn(32, 3, 112, 112).astype(np.float32).transpose(0, 3, 1, 2))],
}),
('MaxPool2d_ValueError_3', {
'block': (
lambda _: nn.MaxPool2d(kernel_size=3, stride=True, pad_mode="valid"),
{'exception': TypeError},
),
'desc_inputs': [Tensor(np.random.randn(32, 3, 112, 112).astype(np.float32).transpose(0, 3, 1, 2))],
}),
('ReduceLogsumexp_TypeError_1', {
'block': (
lambda _: nn.ReduceLogSumExp(axis=(0,), keep_dims=2),
{'exception': TypeError},
),
'desc_inputs': [Tensor(np.array([3, 4, 5, 6]).astype(np.float32))],
}),
('ReduceLogsumexp_TypeError_2', {
'block': (
lambda _: nn.ReduceLogSumExp(axis=1.2, keep_dims=True),
{'exception': TypeError},
),
'desc_inputs': [Tensor(np.array([3, 4, 5, 6]).astype(np.float32))],
}),
]
@security_off_wrap
@non_graph_engine
@mindspore_test(pipeline_for_verify_exception_for_case_by_case_config)
def test_summary_nn_ops():
if security.enable_security():
return []
test_cases_for_summary_ops = [
('ScalarSummary', {
'block': ScalarSummaryNet(),
'desc_inputs': [Tensor(2.2)],
}),
('HistogramSummary', {
'block': HistogramSummaryNet(),
'desc_inputs': [[1, 2, 3]],
}),
]
context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
return test_cases_for_summary_ops
def test_summary_nn_ops_security_on():
if security.enable_security():
with pytest.raises(ValueError) as exc:
ScalarSummaryNet()
assert str(exc.value) == 'The Summary is not supported, please without `-s on` and recompile source.'
@non_graph_engine
@mindspore_test(pipeline_for_compile_forward_ge_graph_for_case_by_case_config)
def test_compile():
context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
return test_cases
@mindspore_test(pipeline_for_verify_exception_for_case_by_case_config)
def test_check_exception():
return test_cases_for_verify_exception
| 12,033 |
451 | <gh_stars>100-1000
#include "include/MMVII_all.h"
#include "include/MMVII_2Include_Serial_Tpl.h"
#include "LearnDM.h"
//#include "include/MMVII_Tpl_Images.h"
namespace MMVII
{
cPyr1ImLearnMatch::cPyr1ImLearnMatch
(
const cBox2di & aBox,
const cBox2di & aBoxOut,
const std::string & aName,
const cAppliLearningMatch & anAppli,
const cFilterPCar& aFPC,
bool initRand
) :
mBox (aBox),
mNameIm (aName),
mAppli (anAppli),
mGP (mBox.Sz(),mAppli.NbOct(),mAppli.NbLevByOct(),mAppli.NbOverLapByO(),&mAppli,false),
mPyr (nullptr),
mImF (cPt2di(1,1))
{
mGP.mFPC = aFPC;
mPyr = tPyr::Alloc(mGP,mNameIm,mBox,aBoxOut);
if (initRand)
mPyr->ImTop().DIm().InitRandom(0.0,100.0);
else
mPyr->ImTop().Read(cDataFileIm2D::Create(mNameIm,true),mBox.P0());
mPyr->ComputGaussianFilter();
// Compute the filtered images used for having "invariant" gray level
// Filter to have a local average
mImF = mPyr->ImTop().Dup();
float aFact = 50.0;
ExpFilterOfStdDev(mImF.DIm(),5,aFact);
// make a ratio image
{
tDataImF &aDIF = mImF.DIm();
tDataImF &aDI0 = mPyr->ImTop().DIm();
for (const auto & aP : aDIF)
{
aDIF.SetV(aP,(1+NormalisedRatioPos(aDI0.GetV(aP),aDIF.GetV(aP))) / 2.0);
}
}
}
void cPyr1ImLearnMatch::SaveImFiltered() const
{
std::string aName = "FILTRED-" + mNameIm;
const tDataImF &aDIF = mImF.DIm();
cIm2D<tU_INT1> aImS(aDIF.Sz());
for (const auto & aP : aDIF)
{
int aVal = round_ni(aDIF.GetV(aP)*255.0);
aImS.DIm().SetV(aP,aVal);
}
aImS.DIm().ToFile(aName); // Ok
}
double cPyr1ImLearnMatch::MulScale() const {return mPyr->MulScale();}
const cPyr1ImLearnMatch::tDataImF & cPyr1ImLearnMatch::ImInit() const {return mPyr->ImTop().DIm();}
const cPyr1ImLearnMatch::tDataImF & cPyr1ImLearnMatch::ImFiltered() const {return mImF.DIm();}
// const tDataImF & ImFiltered() const;
bool cPyr1ImLearnMatch::CalculAimeDesc(const cPt2dr & aPt)
{
{
cPt2dr aSzV(mAppli.SzMaxStdNeigh(),mAppli.SzMaxStdNeigh());
cPt2dr aP1 = aPt - aSzV;
cPt2dr aP2 = aPt + aSzV;
tDataImF & aImPyr = mPyr->ImTop().DIm();
if (!(aImPyr.InsideBL(aP1) && aImPyr.InsideBL(aP2)))
return false;
tDataImF & aDImF = mImF.DIm();
if (!(aDImF.InsideBL(aP1) && aDImF.InsideBL(aP2)))
return false;
}
cProtoAimeTieP<tREAL4> aPAT(mPyr->GPImTop(),aPt);
if (! aPAT.FillAPC(mGP.mFPC,mPC,true))
return false;
aPAT.FillAPC(mGP.mFPC,mPC,false);
return true;
}
cAimePCar cPyr1ImLearnMatch::DupLPIm() const { return mPC.DupLPIm(); }
};
| 1,466 |
1,909 | package org.knowm.xchange.bitso.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Collection;
import java.util.Map;
import si.mazi.rescu.HttpStatusExceptionSupport;
public class BitsoException extends HttpStatusExceptionSupport {
private Map<String, Collection<String>> errors;
public BitsoException(@JsonProperty("error") Object error) {
super(getMessage(error));
if (error instanceof Map) {
try {
errors = (Map<String, Collection<String>>) error;
} catch (Exception ignore) {
}
}
}
private static String getMessage(Object errors) {
if (errors instanceof Map) {
try {
Map<String, Iterable> map = (Map<String, Iterable>) errors;
final StringBuilder sb = new StringBuilder();
for (String key : map.keySet()) {
for (Object msg : map.get(key)) {
if (sb.length() > 0) {
sb.append(" -- ");
}
sb.append(msg);
}
}
return sb.toString();
} catch (Exception ignore) {
}
}
return String.valueOf(errors);
}
public Map<String, Collection<String>> getErrors() {
return errors;
}
public Collection<String> getErrors(String key) {
return errors.get(key);
}
}
| 518 |
1,041 | package org.tests.rawsql;
import io.ebean.annotation.Sql;
import javax.persistence.Entity;
@Entity
@Sql
public class A2Customer {
private long custId;
private String customerName;
public long getCustId() {
return custId;
}
public void setCustId(long custId) {
this.custId = custId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
| 166 |
699 | [{"name":"gson-support","description":null,"location":"gson-support/index.html","searchKeys":["gson-support"]},{"name":"com.chibatching.kotpref.gsonpref","description":null,"location":"gson-support/com.chibatching.kotpref.gsonpref/index.html","searchKeys":["com.chibatching.kotpref.gsonpref"]},{"name":"gson","description":null,"location":"gson-support/com.chibatching.kotpref.gsonpref/gson.html","searchKeys":["gson"]},{"name":"GsonNullablePref","description":null,"location":"gson-support/com.chibatching.kotpref.gsonpref/-gson-nullable-pref/index.html","searchKeys":["GsonNullablePref"]},{"name":"gsonNullablePref","description":null,"location":"gson-support/com.chibatching.kotpref.gsonpref/gson-nullable-pref.html","searchKeys":["gsonNullablePref"]},{"name":"GsonPref","description":null,"location":"gson-support/com.chibatching.kotpref.gsonpref/-gson-pref/index.html","searchKeys":["GsonPref"]},{"name":"gsonPref","description":null,"location":"gson-support/com.chibatching.kotpref.gsonpref/gson-pref.html","searchKeys":["gsonPref"]}]
| 362 |
577 | <gh_stars>100-1000
/*-------------------------------------------------------------------------
*
* pglogical_fe.h
* pglogical replication plugin
*
* Copyright (c) 2015, PostgreSQL Global Development Group
*
* IDENTIFICATION
* pglogical_fe.h
*
*-------------------------------------------------------------------------
*/
#ifndef PGLOGICAL_FE_H
#define PGLOGICAL_FE_H
extern int find_other_exec_version(const char *argv0, const char *target,
uint32 *version, char *retpath);
extern char *pgl_get_connstr(char *connstr, char *dbname, char *options, char **errmsg);
#endif /* PGLOGICAL_FE_H */
| 214 |
317 | //
// This file is distributed under the MIT License. See LICENSE for details.
//
#ifndef UTILS_INITIALIZEPASSES_H
#define UTILS_INITIALIZEPASSES_H
#include "llvm/InitializePasses.h"
namespace llvm {
void initializeDevirtualizePass(PassRegistry &Registry);
} // end namespace llvm
#endif // UTILS_INITIALIZEPASSES_H
| 114 |
14,668 | <gh_stars>1000+
// 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/safe_browsing/core/browser/db/allowlist_checker_client.h"
#include <memory>
#include "base/bind.h"
namespace safe_browsing {
namespace {
// Number of milliseconds to wait for the response from the Safe Browsing
// database manager before proceeding with the timeout behavior.
const int kLookupTimeoutMS = 5000;
} // namespace
// static
void AllowlistCheckerClient::StartCheckCsdAllowlist(
scoped_refptr<SafeBrowsingDatabaseManager> database_manager,
const GURL& url,
base::OnceCallback<void(bool)> callback_for_result) {
// On timeout or if the list is unavailable, report match.
const bool kDefaultDoesMatchAllowlist = true;
std::unique_ptr<AllowlistCheckerClient> client = GetAllowlistCheckerClient(
database_manager, url, &callback_for_result, kDefaultDoesMatchAllowlist);
if (!client) {
std::move(callback_for_result).Run(kDefaultDoesMatchAllowlist);
return;
}
AsyncMatch match = database_manager->CheckCsdAllowlistUrl(url, client.get());
InvokeCallbackOrRelease(match, std::move(client));
}
// static
std::unique_ptr<AllowlistCheckerClient>
AllowlistCheckerClient::GetAllowlistCheckerClient(
scoped_refptr<SafeBrowsingDatabaseManager> database_manager,
const GURL& url,
base::OnceCallback<void(bool)>* callback_for_result,
bool default_does_match_allowlist) {
if (!url.is_valid() || !database_manager ||
!database_manager->CanCheckUrl(url)) {
return nullptr;
}
// Make a client for each request. The caller could have several in
// flight at once.
return std::make_unique<AllowlistCheckerClient>(
std::move(*callback_for_result), database_manager,
default_does_match_allowlist);
}
// static
void AllowlistCheckerClient::InvokeCallbackOrRelease(
AsyncMatch match,
std::unique_ptr<AllowlistCheckerClient> client) {
switch (match) {
case AsyncMatch::MATCH:
std::move(client->callback_for_result_)
.Run(true /* did_match_allowlist */);
break;
case AsyncMatch::NO_MATCH:
std::move(client->callback_for_result_)
.Run(false /* did_match_allowlist */);
break;
case AsyncMatch::ASYNC:
// Client is now self-owned. When it gets called back with the result,
// it will delete itself.
client.release();
break;
}
}
AllowlistCheckerClient::AllowlistCheckerClient(
base::OnceCallback<void(bool)> callback_for_result,
scoped_refptr<SafeBrowsingDatabaseManager> database_manager,
bool default_does_match_allowlist)
: callback_for_result_(std::move(callback_for_result)),
database_manager_(database_manager),
default_does_match_allowlist_(default_does_match_allowlist) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Set a timer to fail open, i.e. call it "allowlisted", if the full
// check takes too long.
auto timeout_callback = base::BindOnce(&AllowlistCheckerClient::OnTimeout,
weak_factory_.GetWeakPtr());
timer_.Start(FROM_HERE, base::Milliseconds(kLookupTimeoutMS),
std::move(timeout_callback));
}
AllowlistCheckerClient::~AllowlistCheckerClient() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
// SafeBrowsingDatabaseMananger::Client impl
void AllowlistCheckerClient::OnCheckAllowlistUrlResult(
bool did_match_allowlist) {
OnCheckUrlResult(did_match_allowlist);
}
void AllowlistCheckerClient::OnCheckUrlForHighConfidenceAllowlist(
bool did_match_allowlist) {
OnCheckUrlResult(did_match_allowlist);
}
void AllowlistCheckerClient::OnCheckUrlResult(bool did_match_allowlist) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
timer_.Stop();
// The callback can only be invoked by other code paths if this object is not
// self-owned. Because this method is only invoked when we're self-owned, we
// know the callback must still be valid, and it must be safe to delete
// |this|.
DCHECK(callback_for_result_);
std::move(callback_for_result_).Run(did_match_allowlist);
delete this;
}
void AllowlistCheckerClient::OnTimeout() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
database_manager_->CancelCheck(this);
OnCheckUrlResult(default_does_match_allowlist_);
}
} // namespace safe_browsing
| 1,541 |
3,055 | /*
Fontname: -B&H-LucidaBright-DemiBold-I-Normal--20-140-100-100-P-119-ISO10646-1
Copyright: Copyright Bigelow & Holmes 1986, 1985.
Glyphs: 95/723
BBX Build Mode: 0
*/
const uint8_t u8g2_font_lubBI14_tr[2369] U8G2_FONT_SECTION("u8g2_font_lubBI14_tr") =
"_\0\4\3\5\5\4\5\6\26\24\377\374\17\374\17\374\2\316\6<\11$ \6\0`\64\1!\21\346"
"%,g\311\314\66B\212\242\342\1Hf\0\42\21\307pNa\302\204F\42F\42F\42&\2\0#"
"$\354)l/DL$.&L$.&\346\200(&.DL$.&\350\200&\231\210XL\230"
"\210\30\0$!K\252k/\356\206Dd\42Dd\42Dd\42\216!;\262\220\251\20%!J\42d"
"\16#\343\0%+\357)|\205NbBJDdFd\211\214\22)\211\11\61\22i\11:\11\21)"
"\11\31!\21\31MF\204DT\211H\310\315\0&'\357%|\255RdndndnDpB\222"
"Rb\244BdfbfDdfDd\250f\210jh\314\202\4\0'\14\303l.\341@B\42$"
"\2\0(\23g*;-*JH\225\320\220\320~\245,.\6\0)\21g\42;),L\225\216v"
"$\64\244*\63\0*\21\350,NI&$\204\42B\211\314\212\221\64\0+\20\254%dMT\64\66"
"\253\203\252\330L\225\1,\13\4%+c'!*D\0-\7%\350\65\241\0.\11d$,\343`"
"\2\0/\25n\42SY\70\261pb\341\304\302\211\205S\7\7\313\12\3\60\37\354)l\213NdH"
"\215\324\304\324\304\224\231\325\325\304\324\304\324\304\320\214\220\320\210X\25\0\61\17\350-l\305j\321\324\256"
"\244vDr\20\62\31\354%l\311Jf(j&jrpR\241dhR\311\203\221\203\21\0\63\27"
"\353)l\307Jf&hp\241\234\230!\341\26R\42B#G\0\64\35\353)lq\216\214.B,"
"D*d(f&H&J\344\340A\330\240\244\234\5\0\65\30\354)l\347@\346 (T\64\266t"
"\313%R#B\63BBf\0\66 \354)l\315H\215T\214\344\344A\14\315\10\321\304\324\304\324\304"
"\324\304\320\214\220\320\310\30\25\0\67\23\353-l\343`\342`\62KA\205\203\12\327\15\16\2\70!\354"
")l\253jFHhdhdH\210B\312\354H\244D\210bjbjbJfF\252\12\0\71!"
"\354)l\213lDhHFjbjbjbjb\210d\204\210bRrDJFH\310\14\0:"
"\13e%,e{\320\221%\0;\16\346!+g\311<\302\231!\65\212\0<\17\255%d\71tp"
"\217g\207\327\16\207\0=\14\315\344d\343\240\36\273\203\12\0>\17\255!d%xvx\355\360\340\236"
"\6\3\77\23\351-T\303&\306hlL]\230\262\365\200cc\0@\60\361)\214\317RJL\62("
"h*D&F&$FMDP\220\314\214\314LD\214\242\210\30\221\31\211\30\11\22\221\240\221\251x"
"\20\251\330B\0A \357!|Sx\230\264\64b\62d\62d\60hLh\354@Jj*N(p"
"Dp\202\312\0B\42\355%l\347@jfhfHhHhf\321\310\224\335\310\224\320\314\320\314\320"
"\314\320\314\222\203\31\0C\27\356)|\355 h\315\230\310\134\214\354\322\331mi\207\247\244\216\0D\42"
"\360%\204\347`n\210j\263!\271\231\271\231\271\231\271\231\271\231\261\231\271\231\261\241\251EC\7c\0"
"E\33\355%l\347`hHhHhrt\215\324\331L\230\350VAC\42\7$\0F\27\355%d"
"\347`hHhHhrt\215\324\331L\230\350\16\355\0G\37\356)\204\355 h\315\230\310\134\314\350"
"\354\350\354\324\201\330\310\330\310\330\314\324\320\220\330\21\0H\25\362%\214\307\321\330~\65\266\331A\331\256"
"\306\366#\33\33\0I\17\351%<\307hl\253\261]\215md\3J\24LbS\315\216pr\341\344"
"\36Nn$\62%\42V\7K\42\357%|\307\204h*l(N(n&pB\262\324RbRd"
"n\204lflhj\210\304\5\0L\25\354%d\307\216pr!\341\344\206\204\223S\42S\7\26\0"
"M-\364%\234\207\260\210n\214\257\42\246$fB\304$f\42\306BFB\306BFB\306bh\246"
"d\206\304d\226\5\11\215\205\16\225\331\0N+\361%\204\207\252h.\214,\214J,bHJb("
"Ld&,f&,hB,hBJ\212L\212,n,n\250L\10\0O\35\357)\214\257nh"
"\231\314\334\210\340\304\340\304\240\245\303\211\301\211\271\231\251\241uf\0P\26\356!l\347@lh\277!"
"\22\332f\352n\224tv\345\35\0Q*q*\213\257rHnLjnHpfpfpdrd"
"rd\220dpf\216h\212j\210\360 Z\36B\36b\36\302\0R\35\356%t\347`j\206h\337"
"\320\14\315L\35\204M\314\215L\315L\15\355j\302\210\0S\34\354%d\313hHFJd*f\222"
"\262\260\222r\222$jDjDh\310\12\0T\24\356-t\341\201\320\14\315P\330\354\246\263;\235\235"
"<\3U$\357-\204\341\246dLfNfNf.h.h.f\60fNf.h.h.h"
",l(\320\16\0V!\357-|\301\212bP\204.h,j,j*lH\214&p$r$r"
"\42\264vXZ\22\0W\62\363)\224\241H\210bJ\311\320T\314\320\220\314\14Q\320L\204\214\320H"
"\210L\324H\210\62\11\221\211\70\211\230:\211\30\302!\302\241I\251I)A\0X\42\360!l\307\206"
"\210*nHnFrBt\42\226z\230VbRdPh.jJ\214\206\310\4\0Y\34\356)l"
"\301\210\202LfJh*\212&n$p\42\224tv\224tv\345\31\0Z\31\356%t\347\200Fj"
"H\210\222\351(%\323\245\224T\62c\42\7\64\0[\24h&;\211fjJL\325*\61U\253\304"
"T\255\252\1\134\21f.S!,*\263\250\254\244r\26\225Y\0]\23h\42;\247j\225\230\252U"
"b\252V\211\251ZC\4^\32\254\245d\61T\345d\204\134\210\230LXP\224\220\214\224L\134\210\34"
"\241\0_\10(\244S\341 \0`\11d<gaDF\0a\34l%l\353(hDjDhd"
"hD\210b\210b&bI\304H\311\314L\1b\37\354)l\243r\341\344\314\222\222\211\220\21\232\11"
"\242\11\42\221\241\221!\31\251\30\232\240+\0c\22j)T\253F\211\220\304\220\204\334\16\207bL\0"
"d\42\355%l\261trt\354*h(jFhfhFjd\210d&bd$b\246dh\246"
"\2\0e\30j)\134\213HdDfbfBfbd\344fnpH\304\4\0f\27\213&C\255"
"JDHFHp\354 jnpw\203\273\33\134\10g#\354%k\315HfFhdHFhd"
"hd\206d$bd\242\246b\206dr$LfF\252\14\0h\37\353)l\243Pp\223\231\211\22"
"\11\211\25!\23\64\23\63#\63#B\23C\23C\23C\4i\17\346)\64g\263\232\65\62\273\221\231"
"\251\0j\25k\36Cq{\210\302u\203\273\33\134($#$\42U\6k\34\353)l\243pPp"
"\315\310\314\310\32\221\31+\253\211\241\211!\231\221\31\212!\2l\20\346)\64\243fFf\67\62\273\221"
"\231\251\0m#r)\234\241f\213\222\26\23\22#\22!%\23\64\64\23C\63#C\63#BK\204"
"V\14\255\30\232)n\35k)l\241df\242DBbE\310\4\315\304\314\310\314\210\320\304\320\304\320"
"\304\20\1o\30k)d\213JF\321\304\320\304\220\225\225\304\320\304\220\314\210\24\25\0p\37\354%k"
"\243df\244d\42d\204f\204fdhDhdhdHfF\310LrK\0q\37\354%k\353"
"(hDjDhdhD\210b\210b&bI\304H\311\314\312\205\223\63\0r\25j)T\241F"
"dbfbd\42\212\214lnln\35\0s\24i%T\251d&d&d\214\263\11\231\11\231\221"
"\32\0t\20\307)<Gh\311\305\320n\206\266\210!\1u\34k)l\201\206bhbhbHd"
"fdfb\206b$b\205\222\212\231\221\2v\31l%d\201\210bjdhdHfFj$l"
"\42\216\220pR\16\0w$p)\204\201(hb(hDfFfdFf\202&h\42b\42\252"
"\242l\204NfPH\60*\14\0x\30k%\134\203f\215\314\210\324D\30\241\134\225\304\220\314\210\320"
"\310\20\1y\31\356!c\205\210\206hGRCq#\201\23\221\225\244\263\302i'I\1z\24k%"
"\134\345@Df&\206n\357\210B\206$\16D\0{\23g*;ifHh\217d\304\24-\22\332"
"j\6\0|\22e&+G\233\240\30m\202\322h\23\24\243\15\0}\23g&;gjh\233\241!"
"\61\65B{$\64\63\4~\21\254\344de,\42DJH\225HD\330\10\0\0\0\0\4\377\377\0"
"";
| 3,778 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Montselgues","circ":"3ème circonscription","dpt":"Ardèche","inscrits":85,"abs":35,"votants":50,"blancs":13,"nuls":4,"exp":33,"res":[{"nuance":"REM","nom":"<NAME>","voix":21},{"nuance":"LR","nom":"<NAME>","voix":12}]} | 110 |
861 | <gh_stars>100-1000
package cn.springcloud.gray.communication.http;
import cn.springcloud.gray.http.HttpParams;
import cn.springcloud.gray.http.HttpRequest;
import cn.springcloud.gray.http.HttpResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.util.*;
/**
* @author saleson
* @date 2020-02-04 22:43
*/
public class RestTemplateAgent implements HttpAgent {
private final String baseUrl;
private RestTemplate rest;
public RestTemplateAgent(String baseUrl) {
this(baseUrl, new RestTemplate());
}
public RestTemplateAgent(String baseUrl, int timeout) {
this.baseUrl = baseUrl;
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout((int) timeout);
requestFactory.setReadTimeout((int) timeout);
this.rest = new RestTemplate(requestFactory);
}
public RestTemplateAgent(String baseUrl, RestTemplate rest) {
this.baseUrl = baseUrl;
this.rest = rest;
}
@Override
public HttpResult request(HttpRequest request) {
// String url = getCompleteUrl(request.getPath(), request.getParamValues(), request.getEncoding());
// String url = getCompleteUrl(request.getPath(), request.getParamValues(), null);
Map<String, String> params = getParams(request.getParamValues());
String url = getExtendUrl(request.getPath(), params);
org.springframework.http.HttpHeaders httpHeaders = new org.springframework.http.HttpHeaders();
if (Objects.nonNull(request.getHeaders())) {
httpHeaders.putAll(request.getHeaders().toMap());
}
HttpEntity<String> httpEntity = new HttpEntity<>(request.getBody(), httpHeaders);
ResponseEntity<String> responseEntity = rest.exchange(
url, HttpMethod.resolve(request.getMethod().name()), httpEntity, String.class, params);
return toHttpResult(responseEntity);
}
private HttpResult toHttpResult(ResponseEntity<String> responseEntity) {
HttpResult httpResult = new HttpResult();
httpResult.setCode(responseEntity.getStatusCode().value());
httpResult.setHeaders(responseEntity.getHeaders());
httpResult.setContent(responseEntity.getBody());
return httpResult;
}
private String getExtendUrl(String path, Map<String, ?> params) {
String fullPath = baseUrl + path;
List<String> querys = new ArrayList<>(params.size());
params.forEach((k, v) -> {
StringBuilder query = new StringBuilder();
query.append(k).append("={").append(k).append("}");
querys.add(query.toString());
});
String queryString = StringUtils.join(querys, "&");
if (StringUtils.indexOf(fullPath, "?") > -1) {
return fullPath + "&" + queryString;
}
return fullPath + "?" + queryString;
}
private Map<String, String> getParams(HttpParams paramValues) {
if (Objects.isNull(paramValues)) {
return Collections.emptyMap();
}
return paramValues.toValueMap();
}
private String getCompleteUrl(String path, HttpParams paramValues, String encoding) {
StringBuilder url = new StringBuilder();
url.append(baseUrl).append(path);
if (Objects.nonNull(paramValues)) {
String queryString = StringUtils.isEmpty(encoding) ? paramValues.toQueryString() : paramValues.encodingParams(encoding);
url.append("?").append(queryString);
}
return url.toString();
}
}
| 1,430 |
2,706 | /* Copyright (c) 2013-2015 <NAME>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "imagemagick-gif-encoder.h"
#include <mgba/internal/gba/gba.h>
#include <mgba/internal/gba/video.h>
#include <mgba-util/string.h>
static void _magickPostVideoFrame(struct mAVStream*, const color_t* pixels, size_t stride);
static void _magickVideoDimensionsChanged(struct mAVStream*, unsigned width, unsigned height);
void ImageMagickGIFEncoderInit(struct ImageMagickGIFEncoder* encoder) {
encoder->wand = 0;
encoder->d.videoDimensionsChanged = _magickVideoDimensionsChanged;
encoder->d.postVideoFrame = _magickPostVideoFrame;
encoder->d.postAudioFrame = 0;
encoder->d.postAudioBuffer = 0;
encoder->frameskip = 2;
encoder->delayMs = -1;
encoder->iwidth = VIDEO_HORIZONTAL_PIXELS;
encoder->iheight = VIDEO_VERTICAL_PIXELS;
}
void ImageMagickGIFEncoderSetParams(struct ImageMagickGIFEncoder* encoder, int frameskip, int delayMs) {
if (ImageMagickGIFEncoderIsOpen(encoder)) {
return;
}
encoder->frameskip = frameskip;
encoder->delayMs = delayMs;
}
bool ImageMagickGIFEncoderOpen(struct ImageMagickGIFEncoder* encoder, const char* outfile) {
MagickWandGenesis();
encoder->wand = NewMagickWand();
MagickSetImageFormat(encoder->wand, "GIF");
MagickSetImageDispose(encoder->wand, PreviousDispose);
encoder->outfile = strdup(outfile);
encoder->frame = malloc(encoder->iwidth * encoder->iheight * 4);
encoder->currentFrame = 0;
return true;
}
bool ImageMagickGIFEncoderClose(struct ImageMagickGIFEncoder* encoder) {
if (!encoder->wand) {
return false;
}
MagickBooleanType success = MagickWriteImages(encoder->wand, encoder->outfile, MagickTrue);
DestroyMagickWand(encoder->wand);
encoder->wand = 0;
free(encoder->outfile);
free(encoder->frame);
MagickWandTerminus();
return success == MagickTrue;
}
bool ImageMagickGIFEncoderIsOpen(struct ImageMagickGIFEncoder* encoder) {
return !!encoder->wand;
}
static void _magickPostVideoFrame(struct mAVStream* stream, const color_t* pixels, size_t stride) {
struct ImageMagickGIFEncoder* encoder = (struct ImageMagickGIFEncoder*) stream;
if (encoder->currentFrame % (encoder->frameskip + 1)) {
++encoder->currentFrame;
return;
}
const uint8_t* p8 = (const uint8_t*) pixels;
size_t row;
for (row = 0; row < encoder->iheight; ++row) {
memcpy(&encoder->frame[row * encoder->iwidth], &p8[row * 4 * stride], encoder->iwidth * 4);
}
MagickConstituteImage(encoder->wand, encoder->iwidth, encoder->iheight, "RGBP", CharPixel, encoder->frame);
uint64_t ts = encoder->currentFrame;
uint64_t nts = encoder->currentFrame + encoder->frameskip + 1;
if (encoder->delayMs >= 0) {
ts *= encoder->delayMs;
nts *= encoder->delayMs;
ts /= 10;
nts /= 10;
} else {
ts *= VIDEO_TOTAL_LENGTH * 100;
nts *= VIDEO_TOTAL_LENGTH * 100;
ts /= GBA_ARM7TDMI_FREQUENCY;
nts /= GBA_ARM7TDMI_FREQUENCY;
}
MagickSetImageDelay(encoder->wand, nts - ts);
++encoder->currentFrame;
}
static void _magickVideoDimensionsChanged(struct mAVStream* stream, unsigned width, unsigned height) {
struct ImageMagickGIFEncoder* encoder = (struct ImageMagickGIFEncoder*) stream;
encoder->iwidth = width;
encoder->iheight = height;
}
| 1,259 |
404 | // Copyright (c) 2013-2019 K Team. All Rights Reserved.
package org.kframework.backend.java.kil;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.lang3.tuple.Pair;
import org.kframework.attributes.Att;
import org.kframework.backend.java.symbolic.Transformer;
import org.kframework.backend.java.symbolic.Visitor;
import org.kframework.utils.errorsystem.KEMException;
import scala.collection.Seq;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* A KLabel constant.
*
* @author AndreiS
*/
public class KLabelConstant extends KLabel implements org.kframework.kore.KLabel {
private static final ConcurrentMap<Pair<Set<SortSignature>, Att>,
ConcurrentMap<String, KLabelConstant>> cache = new ConcurrentHashMap<>();
/**
* see {@link #ordinal()}
*/
public static final AtomicInteger maxOrdinal = new AtomicInteger(0);
/* un-escaped label */
private final String label;
private final Seq<org.kframework.kore.Sort> params;
/**
* see {@link #ordinal()}
*/
private final int ordinal;
/* the sort signatures of the productions generating this {@code KLabelConstant} */
private final Set<SortSignature> signatures;
/* the attributes associated with the productions generating this {@code KLabelConstant}
* (attributes are assumed to be identical for all productions) */
private final Att productionAttributes;
/*
* boolean flag set iff a production tagged with "function" or "predicate"
* generates this {@code KLabelConstant}
*/
private final boolean isFunction;
/*
* boolean flag set iff a production tagged with "pattern" generates
* this {@code KLabelConstant}
*/
private final boolean isPattern;
private final boolean isSortPredicate;
private final Sort predicateSort;
private final String smtlib;
private final boolean isImpure;
private final List<Integer> projectionAtt;
private KLabelConstant(
String label,
Seq<org.kframework.kore.Sort> params,
int ordinal,
Set<SortSignature> signatures,
Set<Sort> allSorts,
Att productionAttributes) {
this.label = label;
this.params = params;
this.ordinal = ordinal;
this.signatures = signatures;
this.productionAttributes = productionAttributes;
// TODO(YilongL): urgent; how to detect KLabel clash?
boolean isFunction;
boolean isPattern = false;
String smtlib = null;
List<Integer> projectionAtt = null;
// there are labels which are just predicates, but are not obligated to be sort membership predicates
if (!productionAttributes.contains(Att.PREDICATE(), org.kframework.kore.Sort.class)) {
predicateSort = null;
isFunction = productionAttributes.contains(Att.FUNCTION());
isPattern = productionAttributes.contains(Att.PATTERN());
smtlib = productionAttributes.getOptional(Att.SMTLIB())
.orElse(productionAttributes.getOptional(Att.SMT_HOOK())
.orElse(null));
projectionAtt = getProjectionAtt(productionAttributes);
} else {
/* a KLabel beginning with "is" represents a sort membership predicate */
isFunction = true;
predicateSort = Sort.of(productionAttributes.get(Att.PREDICATE(), org.kframework.kore.Sort.class));
}
this.isSortPredicate = predicateSort != null;
this.isFunction = isFunction;
this.projectionAtt = projectionAtt;
this.isPattern = isPattern;
this.smtlib = smtlib;
this.isImpure = productionAttributes.contains(Att.IMPURE());
}
/**
* Returns a {@code KLabelConstant} representation of label. The {@code KLabelConstant}
* instances are cached to ensure uniqueness (subsequent invocations
* of this method with the same label return the same {@code KLabelConstant} object).
*
* @param label string representation of the KLabel; must not be '`' escaped;
* @return AST term representation the the KLabel;
*/
public static KLabelConstant of(org.kframework.kore.KLabel label, Definition definition) {
return cache.computeIfAbsent(Pair.of(definition.signaturesOf(label.name()), definition.kLabelAttributesOf(label)), p -> new ConcurrentHashMap<>())
.computeIfAbsent(label.toString(), l -> new KLabelConstant(
label.name(),
label.params(),
maxOrdinal.getAndIncrement(),
definition.signaturesOf(label.name()),
definition.allSorts(),
definition.kLabelAttributesOf(label)));
}
/*
* [proj(A,B,C)] => (A,B,C)
* [proj] => (0,1,2) // by default
*/
private List<Integer> getProjectionAtt(Att productionAttributes) {
Optional<String> proj = productionAttributes.getOptional(Att.PROJ());
if (proj.isPresent()) {
String projAtt = proj.get();
if (projAtt.isEmpty()) {
return Arrays.asList(0,1,2);
} else {
return Arrays.stream(proj.get().split(",")).map(s -> Integer.valueOf(s.trim())).collect(Collectors.toList());
}
} else {
return null;
}
}
public List<Integer> getProjectionAtt() {
return projectionAtt;
}
/**
* Returns true iff no production tagged with "function" or "predicate" or "pattern"
* generates this {@code KLabelConstant}.
*/
@Override
public boolean isConstructor() {
return !isFunction;
}
/**
* Returns true iff a production tagged with "function" or "predicate" generates this {@code
* KLabelConstant}.
*/
@Override
public boolean isFunction() {
return isFunction;
}
@Override
public boolean isProjection() {
return projectionAtt != null;
}
/**
* Returns true iff a production tagged with "pattern" generates
* this {@code KLabelConstant}.
*/
@Override
public boolean isPattern() {
return isPattern;
}
/**
* Returns true if this {@code KLabelConstant} is a sort membership
* predicate; otherwise, false.
*/
public boolean isSortPredicate() {
return isSortPredicate;
}
/**
* Returns the predicate sort if this {@code KLabelConstant} represents a
* sort membership predicate; otherwise, {@code null}.
*/
public Sort getPredicateSort() {
assert isSortPredicate();
return predicateSort;
}
public String label() {
return label;
}
/**
* @return an unique integer representing the KLabel -- used by {@link org.kframework.backend.java.symbolic.FastRuleMatcher}
*/
public int ordinal() {
return ordinal;
}
/**
* Returns a list of productions generating this {@code KLabelConstant}.
*/
public Set<SortSignature> signatures() {
return signatures;
}
/**
* @return the SMTLIB name of this KLabel
*/
public String smtlib() {
return smtlib;
}
public boolean isImpure() {
return isImpure;
}
@Override
public String name() {
return label;
}
@Override
public Seq<org.kframework.kore.Sort> params() { return params; }
@Override
public boolean equals(Object object) {
/* {@code KLabelConstant} objects are cached to ensure uniqueness */
return this == object;
}
@Override
protected int computeHash() {
return label.hashCode();
}
@Override
public String toString() {
return label;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@Override
public JavaSymbolicObject accept(Transformer transformer) {
return transformer.transform(this);
}
/**
* Returns the cached instance rather than the de-serialized instance if there is a cached
* instance.
*/
private Object readResolve() {
Map<String, KLabelConstant> localCache = cache.computeIfAbsent(
Pair.of(signatures, productionAttributes),
p -> new ConcurrentHashMap<>());
if (localCache.containsKey(label) && localCache.get(label).ordinal != this.ordinal) {
throw KEMException.criticalError("The ordinal for klabel: " + label + " is " + localCache.get(label).ordinal +
" in the cache and " + this.ordinal + " serialized.");
}
// TODO: fix bug: ordinals from deserialized objects may overlap with those of newly created objects
return localCache.computeIfAbsent(label, l -> this);
}
public String getAttr(String attribute) {
return productionAttributes.getOptional(attribute).orElse(null);
}
public boolean isMetaBinder() {
return getAttr("metabinder") != null;
}
public boolean isBinder() {
return getAttr("binder") != null;
}
/**
* Searches for and retrieves (if found) a binder map for this label
* See {@link org.kframework.kil.Production#getBinderMap()}
*
* @return the binder map for this label (or {@code null} if no binder map was defined.
*/
public Multimap<Integer, Integer> getBinderMap() {
if (isBinder()) {
Multimap<Integer, Integer> binder = productionAttributes.getOptional("binder", Multimap.class).orElse(null);
assert signatures.stream().map(s -> s.parameters().size()).distinct().count() == 1;
return binder == null ? ImmutableMultimap.of(0, signatures.iterator().next().parameters().size() - 1) : binder;
} else {
return null;
}
}
/**
* Searches for and retrieves (if found) a meta binder map for this label
* See {@link org.kframework.kil.Production#getBinderMap()}
*
* @return the binder map for this label (or {@code null} if no meta binder map was defined.
*/
public Multimap<Integer, Integer> getMetaBinderMap() {
if (isMetaBinder()) {
return productionAttributes.get("metabinder", Multimap.class);
} else {
return null;
}
}
}
| 4,196 |
2,175 | /*
* Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.qiyi.video.svg.dispatcher;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import org.qiyi.video.svg.cursor.DispatcherCursor;
import org.qiyi.video.svg.log.Logger;
/**
* Created by wangallen on 2018/3/19.
*/
public class DispatcherProvider extends ContentProvider {
public static final String PROJECTION_MAIN[] = {"main"};
//public static final Uri URI = Uri.parse("content://org.qiyi.video.svg.dispatcher/main");
public static final String URI_SUFFIX="qiyi.svg.dispatcher";
@Override
public boolean onCreate() {
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Logger.d("DispatcherProvider-->query,uri:" + uri.getAuthority());
return DispatcherCursor.generateCursor(Dispatcher.getInstance().asBinder());
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
| 1,023 |
325 |
#pragma once
#include <string>
#include "jet/live/IEvent.hpp"
namespace jet
{
class FileChangedEvent : public IEvent
{
public:
FileChangedEvent(const std::string& filepath)
: IEvent(EventType::kFileChanged)
, m_filepath(filepath)
{
}
const std::string& getFilepath() const { return m_filepath; }
int getPriority() const override { return 20; }
private:
std::string m_filepath;
};
}
| 215 |
898 |
#include "editor-support/cocostudio/WidgetReader/NodeReaderDefine.h"
| 26 |
368 | /*
Plugin-SDK (Grand Theft Auto San Andreas) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "PluginBase.h"
namespace plugin {
CTOR_META_BEGIN(CAnimBlendAssociation)
static int address;
static int global_address;
static const int id = 0x4CE9B0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CE9B0, 0, 0, 0, 0, 0>;
// total references count: 10us (0), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<>;
using def_t = CAnimBlendAssociation *(CAnimBlendAssociation *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *>, 0>;
META_END
META_BEGIN(CAnimBlendAssociation::AllocateAnimBlendNodeArray)
static int address;
static int global_address;
static const int id = 0x4CE9F0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CE9F0, 0, 0, 0, 0, 0>;
// total references count: 10us (3), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4CED70, GAME_10US_COMPACT, H_CALL, 0x4CED50, 1,
0x4CEE75, GAME_10US_COMPACT, H_CALL, 0x4CEE40, 1,
0x4CEEF5, GAME_10US_COMPACT, H_CALL, 0x4CEEC0, 1>;
using def_t = void(CAnimBlendAssociation *, int);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,int>, 0,1>;
META_END
META_BEGIN(CAnimBlendAssociation::FreeAnimBlendNodeArray)
static int address;
static int global_address;
static const int id = 0x4CEA40;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEA40, 0, 0, 0, 0, 0>;
// total references count: 10us (0), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<>;
using def_t = void(CAnimBlendAssociation *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *>, 0>;
META_END
META_BEGIN(CAnimBlendAssociation::ReferenceAnimBlock)
static int address;
static int global_address;
static const int id = 0x4CEA50;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEA50, 0, 0, 0, 0, 0>;
// total references count: 10us (2), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4D438D, GAME_10US_COMPACT, H_CALL, 0x4D4330, 1,
0x4D4568, GAME_10US_COMPACT, H_CALL, 0x4D4410, 1>;
using def_t = void(CAnimBlendAssociation *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *>, 0>;
META_END
META_BEGIN(CAnimBlendAssociation::SetCurrentTime)
static int address;
static int global_address;
static const int id = 0x4CEA80;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEA80, 0, 0, 0, 0, 0>;
// total references count: 10us (59), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x45B55C, GAME_10US_COMPACT, H_CALL, 0x45B4D0, 1,
0x45B636, GAME_10US_COMPACT, H_CALL, 0x45B4D0, 2,
0x45B703, GAME_10US_COMPACT, H_CALL, 0x45B4D0, 3,
0x470CE8, GAME_10US_COMPACT, H_CALL, 0x470A90, 1,
0x491863, GAME_10US_COMPACT, H_CALL, 0x490DB0, 1,
0x4C0517, GAME_10US_COMPACT, H_CALL, 0x4C0170, 1,
0x4C054C, GAME_10US_COMPACT, H_CALL, 0x4C0170, 2,
0x4CEB57, GAME_10US_COMPACT, H_CALL, 0x4CEB40, 1,
0x4CEB74, GAME_10US_COMPACT, H_JUMP, 0x4CEB70, 1,
0x533E86, GAME_10US_COMPACT, H_CALL, 0x533D30, 1,
0x5B03D5, GAME_10US_COMPACT, H_CALL, 0x5B0390, 1,
0x60AA7B, GAME_10US_COMPACT, H_CALL, 0x60A9C0, 1,
0x60AA88, GAME_10US_COMPACT, H_CALL, 0x60A9C0, 2,
0x60AA99, GAME_10US_COMPACT, H_CALL, 0x60A9C0, 3,
0x60AEF4, GAME_10US_COMPACT, H_CALL, 0x60A9C0, 4,
0x60AF01, GAME_10US_COMPACT, H_CALL, 0x60A9C0, 5,
0x61BD21, GAME_10US_COMPACT, H_CALL, 0x61BCB0, 1,
0x61E5B5, GAME_10US_COMPACT, H_CALL, 0x61E3F0, 1,
0x61E5C1, GAME_10US_COMPACT, H_CALL, 0x61E3F0, 2,
0x61E5CD, GAME_10US_COMPACT, H_CALL, 0x61E3F0, 3,
0x61E5D9, GAME_10US_COMPACT, H_CALL, 0x61E3F0, 4,
0x61E920, GAME_10US_COMPACT, H_CALL, 0x61E8E0, 1,
0x61FD72, GAME_10US_COMPACT, H_CALL, 0x61FD20, 1,
0x62005A, GAME_10US_COMPACT, H_CALL, 0x61FF40, 1,
0x62025C, GAME_10US_COMPACT, H_CALL, 0x61FF40, 2,
0x6209E4, GAME_10US_COMPACT, H_CALL, 0x620910, 1,
0x623BD4, GAME_10US_COMPACT, H_CALL, 0x623B10, 1,
0x6250B8, GAME_10US_COMPACT, H_CALL, 0x624F30, 1,
0x627C52, GAME_10US_COMPACT, H_CALL, 0x627B20, 1,
0x629D68, GAME_10US_COMPACT, H_CALL, 0x629920, 1,
0x629F8C, GAME_10US_COMPACT, H_CALL, 0x629920, 2,
0x62A8CB, GAME_10US_COMPACT, H_CALL, 0x62A380, 1,
0x62AB00, GAME_10US_COMPACT, H_CALL, 0x62A380, 2,
0x62AB7B, GAME_10US_COMPACT, H_CALL, 0x62A380, 3,
0x62ABCF, GAME_10US_COMPACT, H_CALL, 0x62A380, 4,
0x62ABE6, GAME_10US_COMPACT, H_CALL, 0x62A380, 5,
0x62D6FE, GAME_10US_COMPACT, H_CALL, 0x62D3B0, 1,
0x62D789, GAME_10US_COMPACT, H_CALL, 0x62D3B0, 2,
0x62D7BE, GAME_10US_COMPACT, H_CALL, 0x62D3B0, 3,
0x65F05E, GAME_10US_COMPACT, H_CALL, 0x65EF80, 1,
0x65F06B, GAME_10US_COMPACT, H_CALL, 0x65EF80, 2,
0x65F078, GAME_10US_COMPACT, H_CALL, 0x65EF80, 3,
0x65F107, GAME_10US_COMPACT, H_CALL, 0x65EF80, 4,
0x65F114, GAME_10US_COMPACT, H_CALL, 0x65EF80, 5,
0x678609, GAME_10US_COMPACT, H_CALL, 0x6784C0, 1,
0x67CABE, GAME_10US_COMPACT, H_CALL, 0x67CA40, 1,
0x67CB3D, GAME_10US_COMPACT, H_CALL, 0x67CA40, 2,
0x67D3DC, GAME_10US_COMPACT, H_CALL, 0x67D380, 1,
0x6B7DD0, GAME_10US_COMPACT, H_CALL, 0x6B7280, 1,
0x6B7DFA, GAME_10US_COMPACT, H_CALL, 0x6B7280, 2,
0x6B7E6C, GAME_10US_COMPACT, H_CALL, 0x6B7280, 3,
0x6B7E96, GAME_10US_COMPACT, H_CALL, 0x6B7280, 4,
0x6BFFEC, GAME_10US_COMPACT, H_CALL, 0x6BFB50, 1,
0x6C064B, GAME_10US_COMPACT, H_CALL, 0x6C0590, 1,
0x6C0787, GAME_10US_COMPACT, H_CALL, 0x6C0590, 2,
0x6C07D2, GAME_10US_COMPACT, H_CALL, 0x6C0590, 3,
0x7363BD, GAME_10US_COMPACT, H_CALL, 0x7360D0, 1,
0x73A657, GAME_10US_COMPACT, H_CALL, 0x73A530, 1,
0x73A7A4, GAME_10US_COMPACT, H_CALL, 0x73A530, 2>;
using def_t = void(CAnimBlendAssociation *, float);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,float>, 0,1>;
META_END
META_BEGIN(CAnimBlendAssociation::SyncAnimation)
static int address;
static int global_address;
static const int id = 0x4CEB40;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEB40, 0, 0, 0, 0, 0>;
// total references count: 10us (3), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4D3B1E, GAME_10US_COMPACT, H_CALL, 0x4D3AA0, 1,
0x4D3B71, GAME_10US_COMPACT, H_CALL, 0x4D3B30, 1,
0x4D4402, GAME_10US_COMPACT, H_CALL, 0x4D4330, 1>;
using def_t = void(CAnimBlendAssociation *, CAnimBlendAssociation *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,CAnimBlendAssociation *>, 0,1>;
META_END
META_BEGIN(CAnimBlendAssociation::GetNode)
static int address;
static int global_address;
static const int id = 0x4CEB60;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEB60, 0, 0, 0, 0, 0>;
// total references count: 10us (2), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4D3561, GAME_10US_COMPACT, H_CALL, 0x4D34F0, 1,
0x61AAAA, GAME_10US_COMPACT, H_CALL, 0x61AAA0, 1>;
using def_t = CAnimBlendNode *(CAnimBlendAssociation *, int);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,int>, 0,1>;
META_END
META_BEGIN(CAnimBlendAssociation::Start)
static int address;
static int global_address;
static const int id = 0x4CEB70;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEB70, 0, 0, 0, 0, 0>;
// total references count: 10us (9), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4D3AF8, GAME_10US_COMPACT, H_CALL, 0x4D3AA0, 1,
0x4D3B80, GAME_10US_COMPACT, H_CALL, 0x4D3B30, 1,
0x4D43CD, GAME_10US_COMPACT, H_CALL, 0x4D4330, 1,
0x4D4595, GAME_10US_COMPACT, H_CALL, 0x4D4410, 1,
0x4D45E3, GAME_10US_COMPACT, H_CALL, 0x4D4410, 2,
0x4D47D5, GAME_10US_COMPACT, H_CALL, 0x4D4610, 1,
0x4D67BE, GAME_10US_COMPACT, H_CALL, 0x4D6790, 1,
0x62516E, GAME_10US_COMPACT, H_CALL, 0x624F30, 1,
0x689EF6, GAME_10US_COMPACT, H_CALL, 0x6899F0, 1>;
using def_t = void(CAnimBlendAssociation *, float);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,float>, 0,1>;
META_END
META_BEGIN(CAnimBlendAssociation::SetBlendTo)
static int address;
static int global_address;
static const int id = 0x4CEB80;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEB80, 0, 0, 0, 0, 0>;
// total references count: 10us (0), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<>;
using def_t = void(CAnimBlendAssociation *, float, float);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,float,float>, 0,1,2>;
META_END
META_BEGIN(CAnimBlendAssociation::SetBlend)
static int address;
static int global_address;
static const int id = 0x4CEBA0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEBA0, 0, 0, 0, 0, 0>;
// total references count: 10us (2), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x45B582, GAME_10US_COMPACT, H_CALL, 0x45B4D0, 1,
0x45B64E, GAME_10US_COMPACT, H_CALL, 0x45B4D0, 2>;
using def_t = void(CAnimBlendAssociation *, float, float);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,float,float>, 0,1,2>;
META_END
META_BEGIN(CAnimBlendAssociation::SetDeleteCallback)
static int address;
static int global_address;
static const int id = 0x4CEBC0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEBC0, 0, 0, 0, 0, 0>;
// total references count: 10us (67), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4D1512, GAME_10US_COMPACT, H_CALL, 0x4D1490, 1,
0x60B13E, GAME_10US_COMPACT, H_CALL, 0x60A9C0, 1,
0x60B164, GAME_10US_COMPACT, H_CALL, 0x60A9C0, 2,
0x61AAE1, GAME_10US_COMPACT, H_CALL, 0x61AAA0, 1,
0x61AC7A, GAME_10US_COMPACT, H_CALL, 0x61AC50, 1,
0x61BB89, GAME_10US_COMPACT, H_CALL, 0x61BB10, 1,
0x61C579, GAME_10US_COMPACT, H_CALL, 0x61C530, 1,
0x61C58C, GAME_10US_COMPACT, H_CALL, 0x61C530, 2,
0x61DF79, GAME_10US_COMPACT, H_CALL, 0x61DF30, 1,
0x61E1CF, GAME_10US_COMPACT, H_CALL, 0x61E190, 1,
0x621920, GAME_10US_COMPACT, H_CALL, 0x6218C0, 1,
0x6226C9, GAME_10US_COMPACT, H_CALL, 0x622680, 1,
0x622714, GAME_10US_COMPACT, H_CALL, 0x6226F0, 1,
0x622770, GAME_10US_COMPACT, H_CALL, 0x6226F0, 2,
0x623A53, GAME_10US_COMPACT, H_CALL, 0x6239F0, 1,
0x623A71, GAME_10US_COMPACT, H_CALL, 0x6239F0, 2,
0x623B2D, GAME_10US_COMPACT, H_CALL, 0x623B10, 1,
0x623D6C, GAME_10US_COMPACT, H_CALL, 0x623B10, 2,
0x623EAC, GAME_10US_COMPACT, H_CALL, 0x623B10, 3,
0x624E9B, GAME_10US_COMPACT, H_CALL, 0x624E30, 1,
0x624F9C, GAME_10US_COMPACT, H_CALL, 0x624F30, 1,
0x627BE8, GAME_10US_COMPACT, H_CALL, 0x627B20, 1,
0x627C1E, GAME_10US_COMPACT, H_CALL, 0x627B20, 2,
0x62993D, GAME_10US_COMPACT, H_CALL, 0x629920, 1,
0x629B7B, GAME_10US_COMPACT, H_CALL, 0x629920, 2,
0x629DB2, GAME_10US_COMPACT, H_CALL, 0x629920, 3,
0x62A5F1, GAME_10US_COMPACT, H_CALL, 0x62A380, 1,
0x62D389, GAME_10US_COMPACT, H_CALL, 0x62D290, 1,
0x661079, GAME_10US_COMPACT, H_CALL, 0x661030, 1,
0x661132, GAME_10US_COMPACT, H_CALL, 0x661110, 1,
0x664953, GAME_10US_COMPACT, H_CALL, 0x6648C0, 1,
0x6649F6, GAME_10US_COMPACT, H_CALL, 0x6648C0, 2,
0x675CC9, GAME_10US_COMPACT, H_CALL, 0x675C90, 1,
0x675DA7, GAME_10US_COMPACT, H_CALL, 0x675D60, 1,
0x675EC9, GAME_10US_COMPACT, H_CALL, 0x675E90, 1,
0x675F82, GAME_10US_COMPACT, H_CALL, 0x675F60, 1,
0x6760B9, GAME_10US_COMPACT, H_CALL, 0x676080, 1,
0x676172, GAME_10US_COMPACT, H_CALL, 0x676150, 1,
0x676DC8, GAME_10US_COMPACT, H_CALL, 0x676D30, 1,
0x67701C, GAME_10US_COMPACT, H_CALL, 0x676D30, 2,
0x677384, GAME_10US_COMPACT, H_CALL, 0x6772E0, 1,
0x6775C3, GAME_10US_COMPACT, H_CALL, 0x6772E0, 2,
0x677794, GAME_10US_COMPACT, H_CALL, 0x677780, 1,
0x677892, GAME_10US_COMPACT, H_CALL, 0x677880, 1,
0x677A10, GAME_10US_COMPACT, H_CALL, 0x677920, 1,
0x677C17, GAME_10US_COMPACT, H_CALL, 0x677920, 2,
0x678D89, GAME_10US_COMPACT, H_CALL, 0x678D50, 1,
0x678F78, GAME_10US_COMPACT, H_CALL, 0x678F40, 1,
0x67A219, GAME_10US_COMPACT, H_CALL, 0x67A1D0, 1,
0x67A2D2, GAME_10US_COMPACT, H_CALL, 0x67A280, 1,
0x67DC0D, GAME_10US_COMPACT, H_CALL, 0x67DBE0, 1,
0x67DC92, GAME_10US_COMPACT, H_CALL, 0x67DBE0, 2,
0x67DCCA, GAME_10US_COMPACT, H_CALL, 0x67DBE0, 3,
0x67DCF0, GAME_10US_COMPACT, H_CALL, 0x67DBE0, 4,
0x67DD65, GAME_10US_COMPACT, H_CALL, 0x67DBE0, 5,
0x67DDAA, GAME_10US_COMPACT, H_CALL, 0x67DBE0, 6,
0x680780, GAME_10US_COMPACT, H_CALL, 0x680600, 1,
0x680802, GAME_10US_COMPACT, H_CALL, 0x680600, 2,
0x680BB9, GAME_10US_COMPACT, H_CALL, 0x680600, 3,
0x680BDE, GAME_10US_COMPACT, H_CALL, 0x680600, 4,
0x68B810, GAME_10US_COMPACT, H_CALL, 0x68B7E0, 1,
0x692E26, GAME_10US_COMPACT, H_CALL, 0x692DF0, 1,
0x6930E1, GAME_10US_COMPACT, H_CALL, 0x692FF0, 1,
0x693ACB, GAME_10US_COMPACT, H_CALL, 0x6939F0, 1,
0x693B46, GAME_10US_COMPACT, H_CALL, 0x6939F0, 2,
0x694545, GAME_10US_COMPACT, H_CALL, 0x694390, 1,
0x694672, GAME_10US_COMPACT, H_CALL, 0x694640, 1>;
using def_t = void(CAnimBlendAssociation *, void(*)(CAnimBlendAssociation *, void *), void *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,void(*)(CAnimBlendAssociation *, void *),void *>, 0,1,2>;
META_END
META_BEGIN(CAnimBlendAssociation::SetFinishCallback)
static int address;
static int global_address;
static const int id = 0x4CEBE0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEBE0, 0, 0, 0, 0, 0>;
// total references count: 10us (150), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4543F8, GAME_10US_COMPACT, H_CALL, 0x454340, 1,
0x45473A, GAME_10US_COMPACT, H_CALL, 0x454340, 2,
0x4D1475, GAME_10US_COMPACT, H_CALL, 0x4D13D0, 1,
0x4D1525, GAME_10US_COMPACT, H_CALL, 0x4D1490, 1,
0x61A729, GAME_10US_COMPACT, H_CALL, 0x61A6F0, 1,
0x61A87C, GAME_10US_COMPACT, H_CALL, 0x61A790, 1,
0x61A97A, GAME_10US_COMPACT, H_CALL, 0x61A950, 1,
0x61AE39, GAME_10US_COMPACT, H_CALL, 0x61ADF0, 1,
0x61B003, GAME_10US_COMPACT, H_CALL, 0x61AF60, 1,
0x61B1B4, GAME_10US_COMPACT, H_CALL, 0x61AF60, 2,
0x61BB65, GAME_10US_COMPACT, H_CALL, 0x61BB10, 1,
0x61BBA3, GAME_10US_COMPACT, H_CALL, 0x61BB10, 2,
0x61C0AC, GAME_10US_COMPACT, H_CALL, 0x61BF20, 1,
0x61F739, GAME_10US_COMPACT, H_CALL, 0x61F700, 1,
0x61F798, GAME_10US_COMPACT, H_CALL, 0x61F780, 1,
0x61F7EB, GAME_10US_COMPACT, H_CALL, 0x61F780, 2,
0x61FC93, GAME_10US_COMPACT, H_CALL, 0x61FC50, 1,
0x61FCFA, GAME_10US_COMPACT, H_CALL, 0x61FCC0, 1,
0x61FDEE, GAME_10US_COMPACT, H_CALL, 0x61FD20, 1,
0x61FEB3, GAME_10US_COMPACT, H_CALL, 0x61FE70, 1,
0x61FF1A, GAME_10US_COMPACT, H_CALL, 0x61FEE0, 1,
0x620278, GAME_10US_COMPACT, H_CALL, 0x61FF40, 1,
0x6203B3, GAME_10US_COMPACT, H_CALL, 0x620370, 1,
0x620420, GAME_10US_COMPACT, H_CALL, 0x6203F0, 1,
0x620462, GAME_10US_COMPACT, H_CALL, 0x6203F0, 2,
0x620572, GAME_10US_COMPACT, H_CALL, 0x620490, 1,
0x6205BA, GAME_10US_COMPACT, H_CALL, 0x620490, 2,
0x6205DF, GAME_10US_COMPACT, H_CALL, 0x620490, 3,
0x6206BA, GAME_10US_COMPACT, H_CALL, 0x620660, 1,
0x6206E3, GAME_10US_COMPACT, H_CALL, 0x620660, 2,
0x620853, GAME_10US_COMPACT, H_CALL, 0x620810, 1,
0x6208E2, GAME_10US_COMPACT, H_CALL, 0x620890, 1,
0x6209F6, GAME_10US_COMPACT, H_CALL, 0x620910, 1,
0x623BA2, GAME_10US_COMPACT, H_CALL, 0x623B10, 1,
0x623EE1, GAME_10US_COMPACT, H_CALL, 0x623B10, 2,
0x623F52, GAME_10US_COMPACT, H_CALL, 0x623B10, 3,
0x6250CD, GAME_10US_COMPACT, H_CALL, 0x624F30, 1,
0x62517C, GAME_10US_COMPACT, H_CALL, 0x624F30, 2,
0x6251EF, GAME_10US_COMPACT, H_CALL, 0x624F30, 3,
0x625B4F, GAME_10US_COMPACT, H_CALL, 0x6259E0, 1,
0x62987D, GAME_10US_COMPACT, H_CALL, 0x6296D0, 1,
0x62FB79, GAME_10US_COMPACT, H_CALL, 0x62FB40, 1,
0x6310A9, GAME_10US_COMPACT, H_CALL, 0x631070, 1,
0x6310F4, GAME_10US_COMPACT, H_CALL, 0x6310D0, 1,
0x631119, GAME_10US_COMPACT, H_CALL, 0x6310D0, 2,
0x631202, GAME_10US_COMPACT, H_CALL, 0x6311E0, 1,
0x631359, GAME_10US_COMPACT, H_CALL, 0x631320, 1,
0x6313A4, GAME_10US_COMPACT, H_CALL, 0x631380, 1,
0x6313C9, GAME_10US_COMPACT, H_CALL, 0x631380, 2,
0x631452, GAME_10US_COMPACT, H_CALL, 0x631410, 1,
0x631D39, GAME_10US_COMPACT, H_CALL, 0x631D00, 1,
0x637562, GAME_10US_COMPACT, H_CALL, 0x637520, 1,
0x637A32, GAME_10US_COMPACT, H_CALL, 0x6379F0, 1,
0x63800A, GAME_10US_COMPACT, H_CALL, 0x637FE0, 1,
0x6399E1, GAME_10US_COMPACT, H_CALL, 0x639990, 1,
0x63C4CC, GAME_10US_COMPACT, H_CALL, 0x63C460, 1,
0x64274E, GAME_10US_COMPACT, H_CALL, 0x642700, 1,
0x645C29, GAME_10US_COMPACT, H_CALL, 0x645BE0, 1,
0x645F29, GAME_10US_COMPACT, H_CALL, 0x645EE0, 1,
0x646139, GAME_10US_COMPACT, H_CALL, 0x6460F0, 1,
0x646279, GAME_10US_COMPACT, H_CALL, 0x646230, 1,
0x6463C9, GAME_10US_COMPACT, H_CALL, 0x646380, 1,
0x6465B9, GAME_10US_COMPACT, H_CALL, 0x646570, 1,
0x646759, GAME_10US_COMPACT, H_CALL, 0x646710, 1,
0x6468D9, GAME_10US_COMPACT, H_CALL, 0x646890, 1,
0x6472A9, GAME_10US_COMPACT, H_CALL, 0x647260, 1,
0x6474D9, GAME_10US_COMPACT, H_CALL, 0x647490, 1,
0x6480B9, GAME_10US_COMPACT, H_CALL, 0x648070, 1,
0x648309, GAME_10US_COMPACT, H_CALL, 0x6482C0, 1,
0x648CB2, GAME_10US_COMPACT, H_CALL, 0x648C40, 1,
0x64ACCB, GAME_10US_COMPACT, H_CALL, 0x64AC00, 1,
0x64ADD1, GAME_10US_COMPACT, H_CALL, 0x64AD90, 1,
0x64AE5F, GAME_10US_COMPACT, H_CALL, 0x64AE00, 1,
0x64AF26, GAME_10US_COMPACT, H_CALL, 0x64AE90, 1,
0x64AFF1, GAME_10US_COMPACT, H_CALL, 0x64AFB0, 1,
0x64B2A0, GAME_10US_COMPACT, H_CALL, 0x64B080, 1,
0x64B38F, GAME_10US_COMPACT, H_CALL, 0x64B2D0, 1,
0x64B42F, GAME_10US_COMPACT, H_CALL, 0x64B3E0, 1,
0x64BE29, GAME_10US_COMPACT, H_CALL, 0x64BDE0, 1,
0x64BF41, GAME_10US_COMPACT, H_CALL, 0x64BF00, 1,
0x64C051, GAME_10US_COMPACT, H_CALL, 0x64C010, 1,
0x64C1D9, GAME_10US_COMPACT, H_CALL, 0x64C190, 1,
0x64CBAE, GAME_10US_COMPACT, H_CALL, 0x64C970, 1,
0x64CC83, GAME_10US_COMPACT, H_CALL, 0x64CC60, 1,
0x64CD49, GAME_10US_COMPACT, H_CALL, 0x64CCE0, 1,
0x6530C9, GAME_10US_COMPACT, H_CALL, 0x653090, 1,
0x65312D, GAME_10US_COMPACT, H_CALL, 0x6530F0, 1,
0x653209, GAME_10US_COMPACT, H_CALL, 0x6531D0, 1,
0x65326F, GAME_10US_COMPACT, H_CALL, 0x653240, 1,
0x653619, GAME_10US_COMPACT, H_CALL, 0x6535D0, 1,
0x655E77, GAME_10US_COMPACT, H_CALL, 0x655E50, 1,
0x655ECC, GAME_10US_COMPACT, H_CALL, 0x655EA0, 1,
0x655F5E, GAME_10US_COMPACT, H_CALL, 0x655F20, 1,
0x657A4B, GAME_10US_COMPACT, H_CALL, 0x657A10, 1,
0x6588D9, GAME_10US_COMPACT, H_CALL, 0x6588A0, 1,
0x658A7E, GAME_10US_COMPACT, H_CALL, 0x6589B0, 1,
0x659E5A, GAME_10US_COMPACT, H_CALL, 0x659E30, 1,
0x65A81A, GAME_10US_COMPACT, H_CALL, 0x65A7C0, 1,
0x664A1E, GAME_10US_COMPACT, H_CALL, 0x6648C0, 1,
0x676DF0, GAME_10US_COMPACT, H_CALL, 0x676D30, 1,
0x676E7D, GAME_10US_COMPACT, H_CALL, 0x676D30, 2,
0x676EAD, GAME_10US_COMPACT, H_CALL, 0x676D30, 3,
0x676EFB, GAME_10US_COMPACT, H_CALL, 0x676D30, 4,
0x677044, GAME_10US_COMPACT, H_CALL, 0x676D30, 5,
0x6773AE, GAME_10US_COMPACT, H_CALL, 0x6772E0, 1,
0x67745F, GAME_10US_COMPACT, H_CALL, 0x6772E0, 2,
0x6775ED, GAME_10US_COMPACT, H_CALL, 0x6772E0, 3,
0x677860, GAME_10US_COMPACT, H_CALL, 0x677780, 1,
0x677909, GAME_10US_COMPACT, H_CALL, 0x677880, 1,
0x677A38, GAME_10US_COMPACT, H_CALL, 0x677920, 1,
0x677AC1, GAME_10US_COMPACT, H_CALL, 0x677920, 2,
0x677C3F, GAME_10US_COMPACT, H_CALL, 0x677920, 3,
0x677FB9, GAME_10US_COMPACT, H_CALL, 0x677F80, 1,
0x6780BE, GAME_10US_COMPACT, H_CALL, 0x677FE0, 1,
0x678349, GAME_10US_COMPACT, H_CALL, 0x678310, 1,
0x67847D, GAME_10US_COMPACT, H_CALL, 0x678370, 1,
0x678E29, GAME_10US_COMPACT, H_CALL, 0x678DC0, 1,
0x678F19, GAME_10US_COMPACT, H_CALL, 0x678EE0, 1,
0x678F69, GAME_10US_COMPACT, H_CALL, 0x678F40, 1,
0x679B29, GAME_10US_COMPACT, H_CALL, 0x679AF0, 1,
0x67C9D5, GAME_10US_COMPACT, H_CALL, 0x67C770, 1,
0x67CA9A, GAME_10US_COMPACT, H_CALL, 0x67CA40, 1,
0x67CAEE, GAME_10US_COMPACT, H_CALL, 0x67CA40, 2,
0x67CB2A, GAME_10US_COMPACT, H_CALL, 0x67CA40, 3,
0x67CD1A, GAME_10US_COMPACT, H_CALL, 0x67CCB0, 1,
0x67D42A, GAME_10US_COMPACT, H_CALL, 0x67D380, 1,
0x67D947, GAME_10US_COMPACT, H_CALL, 0x67D7A0, 1,
0x680C30, GAME_10US_COMPACT, H_CALL, 0x680600, 1,
0x68B6CA, GAME_10US_COMPACT, H_CALL, 0x68B690, 1,
0x68B762, GAME_10US_COMPACT, H_CALL, 0x68B740, 1,
0x690BE9, GAME_10US_COMPACT, H_CALL, 0x690BB0, 1,
0x690C4D, GAME_10US_COMPACT, H_CALL, 0x690C10, 1,
0x69169A, GAME_10US_COMPACT, H_CALL, 0x691630, 1,
0x692069, GAME_10US_COMPACT, H_CALL, 0x692030, 1,
0x6920B0, GAME_10US_COMPACT, H_CALL, 0x692030, 2,
0x692156, GAME_10US_COMPACT, H_CALL, 0x692100, 1,
0x692176, GAME_10US_COMPACT, H_CALL, 0x692100, 2,
0x69228E, GAME_10US_COMPACT, H_CALL, 0x692100, 3,
0x6922F3, GAME_10US_COMPACT, H_CALL, 0x692100, 4,
0x692351, GAME_10US_COMPACT, H_CALL, 0x692340, 1,
0x692375, GAME_10US_COMPACT, H_CALL, 0x692340, 2,
0x692747, GAME_10US_COMPACT, H_CALL, 0x692700, 1,
0x692761, GAME_10US_COMPACT, H_CALL, 0x692700, 2,
0x6930C2, GAME_10US_COMPACT, H_CALL, 0x692FF0, 1,
0x693A29, GAME_10US_COMPACT, H_CALL, 0x6939F0, 1,
0x693A70, GAME_10US_COMPACT, H_CALL, 0x6939F0, 2,
0x693AA2, GAME_10US_COMPACT, H_CALL, 0x6939F0, 3,
0x693B1D, GAME_10US_COMPACT, H_CALL, 0x6939F0, 4,
0x693C0D, GAME_10US_COMPACT, H_CALL, 0x693BD0, 1,
0x6C07EB, GAME_10US_COMPACT, H_CALL, 0x6C0590, 1>;
using def_t = void(CAnimBlendAssociation *, void(*)(CAnimBlendAssociation *, void *), void *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,void(*)(CAnimBlendAssociation *, void *),void *>, 0,1,2>;
META_END
DTOR_META_BEGIN(CAnimBlendAssociation)
static int address;
static int global_address;
static const int id = 0x4CECF0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CECF0, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4CEFA3, GAME_10US_COMPACT, H_CALL, 0x4CEFA0, 1>;
using def_t = void(CAnimBlendAssociation *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *>, 0>;
META_END
META_BEGIN_OVERLOADED(CAnimBlendAssociation::Init, void (CAnimBlendAssociation::*)(RpClump *, CAnimBlendHierarchy *))
static int address;
static int global_address;
static const int id = 0x4CED50;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CED50, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4CF006, GAME_10US_COMPACT, H_CALL, 0x4CEFC0, 1>;
using def_t = void(CAnimBlendAssociation *, RpClump *, CAnimBlendHierarchy *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,RpClump *,CAnimBlendHierarchy *>, 0,1,2>;
META_END
META_BEGIN_OVERLOADED(CAnimBlendAssociation::Init, void (CAnimBlendAssociation::*)(CAnimBlendAssociation &))
static int address;
static int global_address;
static const int id = 0x4CEE40;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEE40, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4CF052, GAME_10US_COMPACT, H_CALL, 0x4CF020, 1>;
using def_t = void(CAnimBlendAssociation *, CAnimBlendAssociation &);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,CAnimBlendAssociation &>, 0,1>;
META_END
META_BEGIN_OVERLOADED(CAnimBlendAssociation::Init, void (CAnimBlendAssociation::*)(CAnimBlendStaticAssociation &))
static int address;
static int global_address;
static const int id = 0x4CEEC0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEEC0, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4CF0B2, GAME_10US_COMPACT, H_CALL, 0x4CF080, 1>;
using def_t = void(CAnimBlendAssociation *, CAnimBlendStaticAssociation &);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,CAnimBlendStaticAssociation &>, 0,1>;
META_END
DEL_DTOR_META_BEGIN(CAnimBlendAssociation)
static int address;
static int global_address;
static const int id = 0x4CEFA0;
static const bool is_virtual = true;
static const int vtable_index = 0;
using mv_addresses_t = MvAddresses<0x4CEFA0, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x85C6D0, GAME_10US_COMPACT, H_CALLBACK, 0x85C6D0, 1>;
using def_t = void(CAnimBlendAssociation *, unsigned char);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,unsigned char>, 0,1>;
META_END
CTOR_META_BEGIN_OVERLOADED(CAnimBlendAssociation, void(RpClump *, CAnimBlendHierarchy *))
static int address;
static int global_address;
static const int id = 0x4CEFC0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CEFC0, 0, 0, 0, 0, 0>;
// total references count: 10us (2), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4D436F, GAME_10US_COMPACT, H_CALL, 0x4D4330, 1,
0x4D4546, GAME_10US_COMPACT, H_CALL, 0x4D4410, 1>;
using def_t = CAnimBlendAssociation *(CAnimBlendAssociation *, RpClump *, CAnimBlendHierarchy *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,RpClump *,CAnimBlendHierarchy *>, 0,1,2>;
META_END
CTOR_META_BEGIN_OVERLOADED(CAnimBlendAssociation, void(CAnimBlendAssociation &))
static int address;
static int global_address;
static const int id = 0x4CF020;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CF020, 0, 0, 0, 0, 0>;
// total references count: 10us (0), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<>;
using def_t = CAnimBlendAssociation *(CAnimBlendAssociation *, CAnimBlendAssociation &);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,CAnimBlendAssociation &>, 0,1>;
META_END
CTOR_META_BEGIN_OVERLOADED(CAnimBlendAssociation, void(CAnimBlendHierarchy &))
static int address;
static int global_address;
static const int id = 0x4CF080;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4CF080, 0, 0, 0, 0, 0>;
// total references count: 10us (2), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4CE0FC, GAME_10US_COMPACT, H_CALL, 0x4CE0B0, 1,
0x4CE182, GAME_10US_COMPACT, H_CALL, 0x4CE130, 1>;
using def_t = CAnimBlendAssociation *(CAnimBlendAssociation *, CAnimBlendHierarchy &);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,CAnimBlendHierarchy &>, 0,1>;
META_END
META_BEGIN(CAnimBlendAssociation::UpdateTimeStep)
static int address;
static int global_address;
static const int id = 0x4D13A0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4D13A0, 0, 0, 0, 0, 0>;
// total references count: 10us (0), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<>;
using def_t = void(CAnimBlendAssociation *, float, float);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,float,float>, 0,1,2>;
META_END
META_BEGIN(CAnimBlendAssociation::UpdateTime)
static int address;
static int global_address;
static const int id = 0x4D13D0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4D13D0, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4D3751, GAME_10US_COMPACT, H_CALL, 0x4D34F0, 1>;
using def_t = bool(CAnimBlendAssociation *, float, float);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,float,float>, 0,1,2>;
META_END
META_BEGIN(CAnimBlendAssociation::UpdateBlend)
static int address;
static int global_address;
static const int id = 0x4D1490;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4D1490, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4D353C, GAME_10US_COMPACT, H_CALL, 0x4D34F0, 1>;
using def_t = bool(CAnimBlendAssociation *, float);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CAnimBlendAssociation *,float>, 0,1>;
META_END
template<>
struct stack_object<CAnimBlendAssociation> : stack_object_no_default<CAnimBlendAssociation> {
SUPPORTED_10US stack_object() {
plugin::CallMethodDynGlobal<CAnimBlendAssociation *>(ctor_gaddr(CAnimBlendAssociation), reinterpret_cast<CAnimBlendAssociation *>(objBuff));
}
SUPPORTED_10US stack_object(CAnimBlendHierarchy &rhs) {
plugin::CallMethodDynGlobal<CAnimBlendAssociation *, CAnimBlendHierarchy &>(ctor_gaddr_o(CAnimBlendAssociation, void(CAnimBlendHierarchy &)), reinterpret_cast<CAnimBlendAssociation *>(objBuff), rhs);
}
SUPPORTED_10US stack_object(RpClump *clump, CAnimBlendHierarchy *hier) {
plugin::CallMethodDynGlobal<CAnimBlendAssociation *, RpClump *, CAnimBlendHierarchy *>(ctor_gaddr_o(CAnimBlendAssociation, void(RpClump *, CAnimBlendHierarchy *)), reinterpret_cast<CAnimBlendAssociation *>(objBuff), clump, hier);
}
SUPPORTED_10US stack_object(CAnimBlendAssociation &rhs) {
plugin::CallMethodDynGlobal<CAnimBlendAssociation *, CAnimBlendAssociation &>(ctor_gaddr_o(CAnimBlendAssociation, void(CAnimBlendAssociation &)), reinterpret_cast<CAnimBlendAssociation *>(objBuff), rhs);
}
SUPPORTED_10US ~stack_object() {
plugin::CallMethodDynGlobal<CAnimBlendAssociation *>(dtor_gaddr(CAnimBlendAssociation), reinterpret_cast<CAnimBlendAssociation *>(objBuff));
}
};
template <>
SUPPORTED_10US inline CAnimBlendAssociation *operator_new<CAnimBlendAssociation>() {
void *objData = operator new(sizeof(CAnimBlendAssociation));
CAnimBlendAssociation *obj = reinterpret_cast<CAnimBlendAssociation *>(objData);
plugin::CallMethodDynGlobal<CAnimBlendAssociation *>(ctor_gaddr(CAnimBlendAssociation), obj);
return obj;
}
template <>
SUPPORTED_10US inline CAnimBlendAssociation *operator_new_array<CAnimBlendAssociation>(unsigned int objCount) {
void *objData = operator new(sizeof(CAnimBlendAssociation) * objCount + 4);
*reinterpret_cast<unsigned int *>(objData) = objCount;
CAnimBlendAssociation *objArray = reinterpret_cast<CAnimBlendAssociation *>(reinterpret_cast<unsigned int>(objData) + 4);
for (unsigned int i = 0; i < objCount; i++)
plugin::CallMethodDynGlobal<CAnimBlendAssociation *>(ctor_gaddr(CAnimBlendAssociation), &objArray[i]);
return objArray;
}
template <>
SUPPORTED_10US inline CAnimBlendAssociation *operator_new<CAnimBlendAssociation>(CAnimBlendHierarchy &rhs) {
void *objData = operator new(sizeof(CAnimBlendAssociation));
CAnimBlendAssociation *obj = reinterpret_cast<CAnimBlendAssociation *>(objData);
plugin::CallMethodDynGlobal<CAnimBlendAssociation *, CAnimBlendHierarchy &>(ctor_gaddr_o(CAnimBlendAssociation, void(CAnimBlendHierarchy &)), obj, rhs);
return obj;
}
template <>
SUPPORTED_10US inline CAnimBlendAssociation *operator_new<CAnimBlendAssociation>(RpClump *clump, CAnimBlendHierarchy *hier) {
void *objData = operator new(sizeof(CAnimBlendAssociation));
CAnimBlendAssociation *obj = reinterpret_cast<CAnimBlendAssociation *>(objData);
plugin::CallMethodDynGlobal<CAnimBlendAssociation *, RpClump *, CAnimBlendHierarchy *>(ctor_gaddr_o(CAnimBlendAssociation, void(RpClump *, CAnimBlendHierarchy *)), obj, clump, hier);
return obj;
}
template <>
SUPPORTED_10US inline CAnimBlendAssociation *operator_new<CAnimBlendAssociation>(CAnimBlendAssociation &rhs) {
void *objData = operator new(sizeof(CAnimBlendAssociation));
CAnimBlendAssociation *obj = reinterpret_cast<CAnimBlendAssociation *>(objData);
plugin::CallMethodDynGlobal<CAnimBlendAssociation *, CAnimBlendAssociation &>(ctor_gaddr_o(CAnimBlendAssociation, void(CAnimBlendAssociation &)), obj, rhs);
return obj;
}
template <>
SUPPORTED_10US inline void operator_delete<CAnimBlendAssociation>(CAnimBlendAssociation *obj) {
if (obj == nullptr) return;
plugin::CallVirtualMethod<0, CAnimBlendAssociation *, unsigned char>(obj, 1);
}
template <>
SUPPORTED_10US inline void operator_delete_array<CAnimBlendAssociation>(CAnimBlendAssociation *objArray) {
if (objArray == nullptr) return;
void *objData = reinterpret_cast<void *>(reinterpret_cast<char *>(objArray) - 4);
unsigned int arraySize = *reinterpret_cast<unsigned int *>(objData);
for (unsigned int i = 0; i < arraySize; i++)
plugin::CallVirtualMethod<0, CAnimBlendAssociation *, unsigned char>(&objArray[i], 1);
operator delete(objData);
}
}
| 19,691 |
5,169 | <reponame>Gantios/Specs
{
"name": "OpenMultitouchSupport",
"version": "1.0",
"summary": "This enables you easily to observe global multitouch events on the trackpad. [macOS] [MultitouchSupport.framework]",
"description": "This enables you easily to observe global multitouch events on the trackpad (Built-In only).\nI created this framework to make MultitouchSupport.framework (Private Framework) easy to use.\nThis framework refers to M5MultitouchSupport.framework very much. This project includes a demo.",
"homepage": "https://github.com/Kyome22/OpenMultitouchSupport",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"social_media_url": "https://twitter.com/Kyomesuke",
"platforms": {
"osx": "10.12"
},
"requires_arc": true,
"source": {
"git": "https://github.com/Kyome22/OpenMultitouchSupport.git",
"tag": "1.0"
},
"xcconfig": {
"FRAMEWORK_SEARCH_PATHS": "/System/Library/PrivateFrameworks/"
},
"frameworks": [
"Cocoa",
"MultitouchSupport"
],
"source_files": "OpenMultitouchSupport/*.{h,m}",
"private_header_files": "OpenMultitouchSupport/*Internal.h"
}
| 424 |
23,901 | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model constructor for Tensorflow Japan prefecture-level models.
This is the Japan prefecture-level model constructor. It is adapted from the
US-county-level model constructor.
1. For now, this constructor does not have ICU and Ventilator compartments and
their related state (compartment) and rate variables.
2. For now, this constructor does not have reconciliation between different
geographic resolutions. We will revisit this if such data becomes available.
"""
from typing import Dict, List
import numpy as np
import tensorflow as tf
from covid_epidemiology.src import constants
from covid_epidemiology.src.models import generic_seir_model_constructor
from covid_epidemiology.src.models import losses
from covid_epidemiology.src.models.shared import model_utils
class JapanPrefectureModelConstructor(
generic_seir_model_constructor.ModelConstructor):
"""Constructs a Japan Prefecture Tensorflow model, to be used in tf_seir."""
def __init__(self, model_spec, random_seed=0):
super(JapanPrefectureModelConstructor,
self).__init__(model_spec, random_seed)
self.num_states = 15
def gt_scaler(self, ground_truth_timeseries, num_known_time_steps):
"""Get min/max values of each covariate."""
(_, gt_list, _, _, _) = ground_truth_timeseries
confirmed_scaler = {
"min": np.min(gt_list["confirmed"][:num_known_time_steps]),
"max": np.max(gt_list["confirmed"][:num_known_time_steps])
}
death_scaler = {
"min": np.min(gt_list["death"][:num_known_time_steps]),
"max": np.max(gt_list["death"][:num_known_time_steps])
}
return {"confirmed": confirmed_scaler, "death": death_scaler}
def extract_prediction(self, all_states):
"""Extract the death and confirmed predictions."""
confirmed_all = list()
death_all = list()
for curr_state in all_states:
(exposed_t, infected_d_t, infected_ud_t, recovered_d_t, recovered_ud_t,
hospitalized_t, hospitalized_cumulative_t, hospitalized_increase_t,
death_t, population_t, reinfectable_d_t, reinfectable_ud_t,
reinfectable_vaccine_t, vaccine_immuned_t,
infected_ud_increase_t) = tf.unstack(curr_state)
del exposed_t, infected_ud_t, recovered_ud_t, hospitalized_cumulative_t
del hospitalized_increase_t, population_t, reinfectable_ud_t
del reinfectable_vaccine_t, vaccine_immuned_t, infected_ud_increase_t
confirmed_t = (
infected_d_t + recovered_d_t + hospitalized_t + death_t +
reinfectable_d_t)
confirmed_all.append(confirmed_t)
death_all.append(death_t)
return {"confirmed": confirmed_all, "death": death_all}
def compute_coef(self,
ground_truth_timeseries,
ground_truth_state,
num_train_steps,
num_known_steps,
power=2.0):
"""Compute train/valid coefficients for loss computation.
Args:
ground_truth_timeseries: ground truth compartments
ground_truth_state: ground truth state level compartments
num_train_steps: number of timesteps for training
num_known_steps: number of known timesteps
power: 2 for MSE and 1 for MAE
Returns:
train_coefs: training coeffcients for each compartment
valid_coefs: valid coeffcients for each compartment
"""
(_, gt_list, gt_indicator, _, _) = ground_truth_timeseries
def _compartment_base(compartment_name):
return model_utils.compartment_base(gt_list[compartment_name],
gt_indicator[compartment_name],
num_train_steps, num_known_steps)
# Coefficients.
recovered_train, recovered_valid = _compartment_base("recovered")
death_train, death_valid = _compartment_base("death")
confirmed_train, confirmed_valid = _compartment_base("confirmed")
hospitalized_train, hospitalized_valid = _compartment_base("hospitalized")
hospitalized_cumulative_train, hospitalized_cumulative_valid = _compartment_base(
"hospitalized_cumulative")
train_coefs = [
1,
(death_train / recovered_train)**power,
1,
(death_train / confirmed_train)**power,
(death_train / hospitalized_train)**power,
(death_train / hospitalized_cumulative_train)**power,
]
valid_coefs = [
1,
(death_valid / recovered_valid)**power,
1,
(death_valid / confirmed_valid)**power,
(death_valid / hospitalized_valid)**power,
(death_valid / hospitalized_cumulative_valid)**power,
]
train_coefs = np.nan_to_num(train_coefs).tolist()
valid_coefs = np.nan_to_num(valid_coefs).tolist()
return train_coefs, valid_coefs
def seir_dynamics(self, current_state, seir_variables):
"""Model dynamics."""
(first_dose_vaccine_ratio_per_day, second_dose_vaccine_ratio_per_day,
average_contact_id, average_contact_iud, reinfectable_rate, alpha,
diagnosis_rate, recovery_rate_id, recovery_rate_iud, recovery_rate_h,
hospitalization_rate, death_rate_id, death_rate_h) = seir_variables
(exposed_t, infected_d_t, infected_ud_t, recovered_d_t, recovered_ud_t,
hospitalized_t, hospitalized_cumulative_t, hospitalized_increase_t,
death_t, population_t, reinfectable_d_t, reinfectable_ud_t,
reinfectable_vaccine_t, vaccine_immuned_t,
infected_ud_increase_t) = tf.unstack(current_state)
del hospitalized_cumulative_t, reinfectable_d_t, reinfectable_ud_t
# Setting the susceptible so that the population adds up to a constant.
normalized_susceptible_t = 1.0 - (exposed_t + infected_d_t + infected_ud_t +
recovered_d_t + recovered_ud_t +
hospitalized_t + death_t +
vaccine_immuned_t) / population_t
normalized_susceptible_t = tf.nn.relu(normalized_susceptible_t)
# Differential change on vaccinated.
d_vaccine_immuned_dt = (
first_dose_vaccine_ratio_per_day * population_t +
second_dose_vaccine_ratio_per_day * population_t -
reinfectable_vaccine_t - vaccine_immuned_t)
# Differential change on reinfectable after vaccination.
d_reinfectable_vaccine_dt = vaccine_immuned_t * 1.0 / constants.VACCINE_IMMUNITY_DURATION
# Differential change on exposed
d_exposed_dt = (
(average_contact_id * infected_d_t +
average_contact_iud * infected_ud_t) * normalized_susceptible_t -
alpha * exposed_t)
# Differential change on infected, documented and undocumented
d_infected_d_dt = (
diagnosis_rate * infected_ud_t - recovery_rate_id * infected_d_t -
death_rate_id * infected_d_t - hospitalization_rate * infected_d_t -
hospitalization_rate * diagnosis_rate * infected_ud_t)
d_infected_ud_dt = (
alpha * exposed_t - diagnosis_rate * infected_ud_t -
recovery_rate_iud * infected_ud_t)
d_infected_ud_increase_dt = alpha * exposed_t - infected_ud_increase_t
# Differential change on recovered, documented and undocumented
d_recovered_d_dt = (
recovery_rate_id * infected_d_t + recovery_rate_h * hospitalized_t -
reinfectable_rate * recovered_d_t)
d_recovered_ud_dt = (
recovery_rate_iud * infected_ud_t - reinfectable_rate * recovered_ud_t)
# Differential change on hospitalized
d_hospitalized_d_dt = (
hospitalization_rate * (infected_d_t +
(diagnosis_rate * infected_ud_t)) -
(death_rate_h + recovery_rate_h) * hospitalized_t)
d_hospitalized_cumulative_d_dt = (
hospitalization_rate * (infected_d_t + diagnosis_rate * infected_ud_t))
d_hospitalized_increase_d_dt = (
hospitalization_rate * (infected_d_t + diagnosis_rate * infected_ud_t) -
hospitalized_increase_t)
# Differential change on death, documented
d_death_d_dt = (
death_rate_id * infected_d_t + death_rate_h * hospitalized_t)
# Differential change on recovered, who may get the disease again.
d_reinfectable_d_dt = reinfectable_rate * recovered_d_t
d_reinfectable_ud_dt = reinfectable_rate * recovered_ud_t
all_state_derivatives = [
d_exposed_dt, d_infected_d_dt, d_infected_ud_dt, d_recovered_d_dt,
d_recovered_ud_dt, d_hospitalized_d_dt, d_hospitalized_cumulative_d_dt,
d_hospitalized_increase_d_dt, d_death_d_dt, -d_death_d_dt,
d_reinfectable_d_dt, d_reinfectable_ud_dt, d_reinfectable_vaccine_dt,
d_vaccine_immuned_dt, d_infected_ud_increase_dt
]
return tf.stack(all_state_derivatives)
def compute_losses(self,
hparams,
train_coefs,
valid_coefs,
propagated_states,
ground_truth_timeseries,
r_eff,
train_start_index,
train_end_index,
valid_start_index,
valid_end_index,
num_forecast_steps,
quantiles=None):
train_loss_coefs = hparams["train_loss_coefs"]
valid_loss_coefs = hparams["valid_loss_coefs"]
time_scale_weight = hparams["time_scale_weight"]
width_coef_train = hparams["width_coef_train"]
width_coef_valid = hparams["width_coef_valid"]
quantile_cum_viol_coef = hparams["quantile_cum_viol_coef"]
increment_loss_weight = hparams["increment_loss_weight"]
train_crps_weight = hparams["train_crps_weight"]
valid_crps_weight = hparams["valid_crps_weight"]
(_, gt_list, gt_indicator, _, _) = ground_truth_timeseries
unstacked_propagated_states = tf.unstack(propagated_states, axis=1)
pred_infected = unstacked_propagated_states[1]
pred_recovered = unstacked_propagated_states[3]
pred_hospitalized = unstacked_propagated_states[5]
pred_hospitalized_cumulative = unstacked_propagated_states[6]
pred_death = unstacked_propagated_states[8]
pred_reinfected = unstacked_propagated_states[10]
pred_confirmed = (
pred_infected + pred_recovered + pred_death + pred_hospitalized +
pred_reinfected)
# Convert these values to tensors so that tf.function calls don't get
# recompiled for different values.
train_start_index = tf.identity(train_start_index)
train_end_index = tf.identity(train_end_index)
valid_start_index = tf.identity(valid_start_index)
valid_end_index = tf.identity(valid_end_index)
if quantiles is not None:
quantiles = tf.constant(quantiles, dtype=tf.float32)
# Use quantile loss if the value of quantiles are given
def loss(pred_states,
gt_list,
gt_indicator,
train_start_index,
train_end_index,
valid_start_index,
valid_end_index,
time_scale_weight=0,
is_training=True):
if quantiles is not None:
if is_training:
train_loss = losses.weighted_interval_loss(
quantile_pred_states=pred_states,
tau_list=quantiles,
gt_list=gt_list,
gt_indicator=gt_indicator,
begin_timestep=train_start_index,
end_timestep=train_end_index,
time_scale_weight=time_scale_weight,
width_coef=width_coef_train)
valid_loss = losses.weighted_interval_loss(
quantile_pred_states=pred_states,
tau_list=quantiles,
gt_list=gt_list,
gt_indicator=gt_indicator,
begin_timestep=valid_start_index,
end_timestep=valid_end_index,
time_scale_weight=time_scale_weight,
width_coef=width_coef_train)
else:
train_loss = losses.weighted_interval_loss(
quantile_pred_states=pred_states,
tau_list=quantiles,
gt_list=gt_list,
gt_indicator=gt_indicator,
begin_timestep=train_start_index,
end_timestep=train_end_index,
time_scale_weight=time_scale_weight,
width_coef=width_coef_valid)
valid_loss = losses.weighted_interval_loss(
quantile_pred_states=pred_states,
tau_list=quantiles,
gt_list=gt_list,
gt_indicator=gt_indicator,
begin_timestep=valid_start_index,
end_timestep=valid_end_index,
time_scale_weight=time_scale_weight,
width_coef=width_coef_valid)
train_loss += train_crps_weight * losses.crps_loss(
quantile_pred_states=pred_states,
tau_list=quantiles,
gt_list=gt_list,
gt_indicator=gt_indicator,
begin_timestep=train_start_index,
end_timestep=train_end_index,
time_scale_weight=time_scale_weight)
valid_loss += valid_crps_weight * losses.crps_loss(
quantile_pred_states=pred_states,
tau_list=quantiles,
gt_list=gt_list,
gt_indicator=gt_indicator,
begin_timestep=valid_start_index,
end_timestep=valid_end_index,
time_scale_weight=time_scale_weight)
else:
train_loss = losses.state_estimation_loss(
pred_states=pred_states,
gt_list=gt_list,
gt_indicator=gt_indicator,
begin_timestep=train_start_index,
end_timestep=train_end_index,
time_scale_weight=time_scale_weight,
increment_loss_weight=increment_loss_weight,
num_forecast_steps=num_forecast_steps)
valid_loss = losses.state_estimation_loss(
pred_states=pred_states,
gt_list=gt_list,
gt_indicator=gt_indicator,
begin_timestep=valid_start_index,
end_timestep=valid_end_index,
time_scale_weight=time_scale_weight,
increment_loss_weight=increment_loss_weight,
num_forecast_steps=num_forecast_steps)
return train_loss, valid_loss
gt_list_infected = tf.nn.relu(gt_list["confirmed"] - gt_list["recovered"] -
gt_list["hospitalized"] - gt_list["death"])
gt_indicator_infected = (
gt_indicator["confirmed"] * gt_indicator["recovered"] *
gt_indicator["hospitalized"] * gt_indicator["death"])
infected_doc_train_loss, infected_doc_valid_loss = loss(
pred_infected,
gt_list_infected,
gt_indicator_infected,
train_start_index,
train_end_index,
valid_start_index,
valid_end_index,
time_scale_weight=time_scale_weight)
death_train_loss, death_valid_loss = loss(
pred_death,
gt_list["death"],
gt_indicator["death"],
train_start_index,
train_end_index,
valid_start_index,
valid_end_index,
time_scale_weight=time_scale_weight)
recovered_doc_train_loss, recovered_doc_valid_loss = loss(
pred_recovered + pred_reinfected,
gt_list["recovered"],
gt_indicator["recovered"],
train_start_index,
train_end_index,
valid_start_index,
valid_end_index,
time_scale_weight=time_scale_weight)
hospitalized_train_loss, hospitalized_valid_loss = loss(
pred_hospitalized,
gt_list["hospitalized"],
gt_indicator["hospitalized"],
train_start_index,
train_end_index,
valid_start_index,
valid_end_index,
time_scale_weight=time_scale_weight)
hospitalized_cumulative_train_loss, hospitalized_cumulative_valid_loss = loss(
pred_hospitalized_cumulative,
gt_list["hospitalized_cumulative"],
gt_indicator["hospitalized_cumulative"],
train_start_index,
train_end_index,
valid_start_index,
valid_end_index,
time_scale_weight=time_scale_weight)
confirmed_train_loss, confirmed_valid_loss = loss(
pred_confirmed,
gt_list["confirmed"],
gt_indicator["confirmed"],
train_start_index,
train_end_index,
valid_start_index,
valid_end_index,
time_scale_weight=time_scale_weight)
train_loss_overall = (
train_coefs[0] * train_loss_coefs[0] * infected_doc_train_loss +
train_coefs[1] * train_loss_coefs[1] * recovered_doc_train_loss +
train_coefs[2] * train_loss_coefs[2] * death_train_loss +
train_coefs[3] * train_loss_coefs[3] * confirmed_train_loss +
train_coefs[4] * train_loss_coefs[4] * hospitalized_train_loss +
train_coefs[5] * train_loss_coefs[5] *
hospitalized_cumulative_train_loss)
valid_loss_overall = (
valid_coefs[0] * valid_loss_coefs[0] * infected_doc_valid_loss +
valid_coefs[1] * valid_loss_coefs[1] * recovered_doc_valid_loss +
valid_coefs[2] * valid_loss_coefs[2] * death_valid_loss +
valid_coefs[3] * valid_loss_coefs[3] * confirmed_valid_loss +
valid_coefs[4] * valid_loss_coefs[4] * hospitalized_valid_loss +
valid_coefs[5] * valid_loss_coefs[5] *
hospitalized_cumulative_valid_loss)
if quantiles is None:
if r_eff is not None:
train_loss_overall += (
hparams["r_eff_penalty_coef"] * tf.math.reduce_mean(
tf.math.softplus(r_eff - hparams["r_eff_penalty_cutoff"])))
# Calculate acceleration
train_loss_overall += (
hparams["acceleration_death_coef"] *
self.acceleration_loss(pred_death, 3))
train_loss_overall += (
hparams["acceleration_confirm_coef"] *
self.acceleration_loss(pred_confirmed, 3))
train_loss_overall += (
hparams["acceleration_hospital_coef"] *
self.acceleration_loss(pred_hospitalized, 3))
else:
# Quantile cumulative violation penalty
forecasting_horizon = valid_end_index - valid_start_index
train_violation_confirmed = losses.quantile_viol_loss(
forecasting_horizon, train_end_index, forecasting_horizon,
gt_indicator["confirmed"], gt_list["confirmed"], pred_confirmed)
train_violation_death = losses.quantile_viol_loss(
forecasting_horizon, train_end_index, forecasting_horizon,
gt_indicator["death"], gt_list["death"], pred_death)
train_loss_overall += quantile_cum_viol_coef * tf.reduce_mean(
train_violation_confirmed)
train_loss_overall += quantile_cum_viol_coef * tf.reduce_mean(
train_violation_death)
valid_violation_confirmed = losses.quantile_viol_loss(
valid_start_index, valid_end_index, forecasting_horizon,
gt_indicator["confirmed"], gt_list["confirmed"], pred_confirmed)
valid_violation_death = losses.quantile_viol_loss(
valid_start_index, valid_end_index, forecasting_horizon,
gt_indicator["death"], gt_list["death"], pred_death)
valid_loss_overall += quantile_cum_viol_coef * tf.reduce_mean(
valid_violation_confirmed)
valid_loss_overall += quantile_cum_viol_coef * tf.reduce_mean(
valid_violation_death)
return train_loss_overall, valid_loss_overall
def unpack_states(self,
chosen_location_list,
ground_truth_timeseries,
propagated_states,
propagated_variables,
num_forecast_steps,
quantile_regression=False):
# Assign in the desired dictionary form.
susceptible_f_all_locations = {}
exposed_f_all_locations = {}
infected_d_f_all_locations = {}
infected_ud_f_all_locations = {}
recovered_d_f_all_locations = {}
recovered_ud_f_all_locations = {}
death_d_f_all_locations = {}
death_horizon_ahead_d_f_all_locations = {}
confirmed_f_all_locations = {}
confirmed_horizon_ahead_d_f_all_locations = {}
hospitalized_f_all_locations = {}
hospitalized_increase_f_all_locations = {}
reinfectable_d_f_all_locations = {}
reinfectable_ud_f_all_locations = {}
reinfectable_vaccine_f_all_locations = {}
vaccine_immuned_f_all_locations = {}
population_f_all_locations = {}
infected_ud_increase_f_all_locations = {}
for location_index, location in enumerate(chosen_location_list):
exposed_f_all_locations[
location] = propagated_states[:, 0, location_index].numpy()
infected_d_f_all_locations[
location] = propagated_states[:, 1, location_index].numpy()
infected_ud_f_all_locations[
location] = propagated_states[:, 2, location_index].numpy()
recovered_d_f_all_locations[location] = (
propagated_states[:, 3, location_index].numpy())
recovered_ud_f_all_locations[location] = (
propagated_states[:, 4, location_index].numpy())
hospitalized_f_all_locations[location] = (
propagated_states[:, 5, location_index].numpy())
hospitalized_increase_f_all_locations[
location] = propagated_states[:, 7, location_index].numpy()
death_d_f_all_locations[
location] = propagated_states[:, 8, location_index].numpy()
death_horizon_ahead_d_f_all_locations[location] = (
propagated_states[num_forecast_steps - 1:, 8, location_index].numpy()
- propagated_states[:-num_forecast_steps + 1, 8,
location_index].numpy())
population_f_all_locations[
location] = propagated_states[:, 9, location_index].numpy()
reinfectable_d_f_all_locations[
location] = propagated_states[:, 10, location_index].numpy()
reinfectable_ud_f_all_locations[
location] = propagated_states[:, 11, location_index].numpy()
reinfectable_vaccine_f_all_locations[
location] = propagated_states[:, 12, location_index].numpy()
vaccine_immuned_f_all_locations[
location] = propagated_states[:, 13, location_index].numpy()
infected_ud_increase_f_all_locations[
location] = propagated_states[:, 14, location_index].numpy()
confirmed_f_all_locations[location] = (
infected_d_f_all_locations[location] +
recovered_d_f_all_locations[location] +
death_d_f_all_locations[location] +
hospitalized_f_all_locations[location])
confirmed_horizon_ahead_d_f_all_locations[location] = (
confirmed_f_all_locations[location][num_forecast_steps - 1:, :] -
confirmed_f_all_locations[location][:-num_forecast_steps + 1, :])
susceptible_f_all_locations[location] = np.maximum(
0, (population_f_all_locations[location] -
confirmed_f_all_locations[location] -
exposed_f_all_locations[location] -
recovered_ud_f_all_locations[location] -
infected_ud_f_all_locations[location] -
vaccine_immuned_f_all_locations[location]))
recovered_d_f_all_locations[location] = (
recovered_d_f_all_locations[location] +
reinfectable_d_f_all_locations[location])
recovered_ud_f_all_locations[location] = (
recovered_ud_f_all_locations[location] +
reinfectable_ud_f_all_locations[location])
confirmed_f_all_locations[location] = (
confirmed_f_all_locations[location] +
reinfectable_d_f_all_locations[location])
# Lower bound of the cumulative quantiles are the last values
if quantile_regression:
(_, gt_list, _, _, _) = ground_truth_timeseries
death_d_f_all_locations = self.lowerbound_postprocessing(
death_d_f_all_locations, gt_list["death"][:, location_index],
location, num_forecast_steps)
confirmed_f_all_locations = self.lowerbound_postprocessing(
confirmed_f_all_locations, gt_list["confirmed"][:, location_index],
location, num_forecast_steps)
recovered_d_f_all_locations = self.lowerbound_postprocessing(
recovered_d_f_all_locations, gt_list["recovered"][:,
location_index],
location, num_forecast_steps)
recovered_ud_f_all_locations = self.lowerbound_postprocessing(
recovered_ud_f_all_locations, None, location, num_forecast_steps)
reinfectable_d_f_all_locations = self.lowerbound_postprocessing(
reinfectable_d_f_all_locations, None, location, num_forecast_steps)
reinfectable_ud_f_all_locations = self.lowerbound_postprocessing(
reinfectable_ud_f_all_locations, None, location, num_forecast_steps)
rates = self.extract_rates(propagated_variables, chosen_location_list)
return (susceptible_f_all_locations, exposed_f_all_locations,
infected_d_f_all_locations, infected_ud_f_all_locations,
recovered_d_f_all_locations, recovered_ud_f_all_locations,
death_d_f_all_locations, death_horizon_ahead_d_f_all_locations,
confirmed_f_all_locations,
confirmed_horizon_ahead_d_f_all_locations,
hospitalized_f_all_locations, hospitalized_increase_f_all_locations,
infected_ud_increase_f_all_locations, rates)
def pack_compartments(self, states, ground_truth_timeseries,
num_forecast_steps):
"""Packs predictions into compartments with associated ground truth."""
(susceptible_f_all_locations, exposed_f_all_locations,
infected_d_f_all_locations, infected_ud_f_all_locations,
recovered_d_f_all_locations, recovered_ud_f_all_locations,
death_d_f_all_locations, death_horizon_ahead_d_f_all_locations,
confirmed_f_all_locations, confirmed_horizon_ahead_d_f_all_locations,
hospitalized_f_all_locations, hospitalized_increase_f_all_locations,
infected_ud_increase_f_all_locations, rates) = states
(_, _, _, _, orig_gt) = ground_truth_timeseries
# pack all results in a list of compartment dataclasses.
susceptible_compartment = generic_seir_model_constructor.Compartment(
name=constants.SUSCEPTIBLE,
predictions=susceptible_f_all_locations,
num_forecast_steps=num_forecast_steps)
exposed_compartment = generic_seir_model_constructor.Compartment(
name=constants.EXPOSED,
predictions=exposed_f_all_locations,
num_forecast_steps=num_forecast_steps)
infected_d_compartment = generic_seir_model_constructor.Compartment(
name=constants.INFECTED_DOC,
predictions=infected_d_f_all_locations,
num_forecast_steps=num_forecast_steps,
ground_truth=orig_gt["infected"])
infected_ud_compartment = generic_seir_model_constructor.Compartment(
name=constants.INFECTED_UNDOC,
predictions=infected_ud_f_all_locations,
num_forecast_steps=num_forecast_steps)
infected_ud_increase_compartment = generic_seir_model_constructor.Compartment(
name=constants.INFECTED_UNDOC_INCREASE,
predictions=infected_ud_increase_f_all_locations,
num_forecast_steps=num_forecast_steps)
recovered_d_compartment = generic_seir_model_constructor.Compartment(
name=constants.RECOVERED_DOC,
predictions=recovered_d_f_all_locations,
num_forecast_steps=num_forecast_steps,
ground_truth=orig_gt["recovered"])
recovered_ud_compartment = generic_seir_model_constructor.Compartment(
name=constants.RECOVERED_UNDOC,
predictions=recovered_ud_f_all_locations,
num_forecast_steps=num_forecast_steps)
death_d_compartment = generic_seir_model_constructor.Compartment(
name=constants.DEATH,
predictions=death_d_f_all_locations,
num_forecast_steps=num_forecast_steps,
ground_truth=orig_gt["death"])
confirmed_compartment = generic_seir_model_constructor.Compartment(
name=constants.CONFIRMED,
predictions=confirmed_f_all_locations,
num_forecast_steps=num_forecast_steps,
ground_truth=orig_gt["confirmed"])
hospitalized_compartment = generic_seir_model_constructor.Compartment(
name=constants.HOSPITALIZED,
predictions=hospitalized_f_all_locations,
num_forecast_steps=num_forecast_steps,
ground_truth=orig_gt["hospitalized"])
hospitalized_increase_compartment = (
generic_seir_model_constructor.Compartment(
name=constants.HOSPITALIZED_INCREASE,
predictions=hospitalized_increase_f_all_locations,
num_forecast_steps=num_forecast_steps))
def create_horizon_ahead_gt(gt):
"""Creates incremental (1-day) ground truth values."""
horizon_ahead_gt = {}
for location in gt:
horizon_ahead_gt[location] = (
gt[location][num_forecast_steps - 1:] -
gt[location][:-num_forecast_steps + 1])
return horizon_ahead_gt
death_horizon_ahead_d_compartment = (
generic_seir_model_constructor.Compartment(
name=constants.HORIZON_AHEAD_DEATH,
predictions=death_horizon_ahead_d_f_all_locations,
num_forecast_steps=1,
ground_truth=create_horizon_ahead_gt(orig_gt["death"])))
confirmed_horizon_ahead_d_compartment = (
generic_seir_model_constructor.Compartment(
name=constants.HORIZON_AHEAD_CONFIRMED,
predictions=confirmed_horizon_ahead_d_f_all_locations,
num_forecast_steps=1,
ground_truth=create_horizon_ahead_gt(orig_gt["confirmed"])))
rates_compartments = []
for name, predictions in rates.items():
rates_compartments.append(
generic_seir_model_constructor.Compartment(
name=name,
predictions=predictions,
num_forecast_steps=num_forecast_steps,
use_quantiles=False))
compartments = [
susceptible_compartment, exposed_compartment, infected_d_compartment,
infected_ud_compartment, recovered_d_compartment,
recovered_ud_compartment, death_d_compartment,
death_horizon_ahead_d_compartment, confirmed_compartment,
confirmed_horizon_ahead_d_compartment, hospitalized_compartment,
hospitalized_increase_compartment, infected_ud_increase_compartment
]
compartments += rates_compartments
return compartments
def apply_quantile_transform(self,
hparams,
propagated_states,
quantile_kernel,
quantile_biases,
ground_truth_timeseries,
num_train_steps,
num_forecast_steps,
num_quantiles=23,
epsilon=1e-8,
is_training=True,
initial_quantile_step=0):
"""Transforms predictions into vector representing different quantiles.
Args:
hparams: Hyperparameters.
propagated_states: single value predictions, its dimensions represent
timestep * states * location.
quantile_kernel: Quantile mapping kernel.
quantile_biases: Biases for quantiles.
ground_truth_timeseries: Ground truth time series.
num_train_steps: number of train steps
num_forecast_steps: number of forecasting steps
num_quantiles: Number of quantiles
epsilon: A small number to avoid 0 division issues.
is_training: Whether the phase is training or inference.
initial_quantile_step: start index for quantile training
Returns:
Vector value predictions of size
timestep * states * location * num_quantiles
"""
(_, gt_list, gt_indicator, _, _) = ground_truth_timeseries
unstacked_propagated_states = tf.unstack(propagated_states, axis=1)
pred_infected = unstacked_propagated_states[1]
pred_recovered = unstacked_propagated_states[3]
pred_hospitalized = unstacked_propagated_states[5]
pred_death = unstacked_propagated_states[8]
pred_reinfected = unstacked_propagated_states[10]
pred_confirmed = (
pred_infected + pred_recovered + pred_death + pred_hospitalized +
pred_reinfected)
quantile_encoding_window = hparams["quantile_encoding_window"]
smooth_coef = hparams["quantile_smooth_coef"]
partial_mean_interval = hparams["partial_mean_interval"]
quantile_mapping_kernel = tf.math.softplus(
tf.expand_dims(quantile_kernel, 2))
quantile_biases = tf.math.softplus(tf.expand_dims(quantile_biases, 1))
propagated_states_quantiles = []
state_quantiles_multiplier_prev = tf.ones_like(
tf.expand_dims(propagated_states[0, :, :], 2))
def gt_ratio_feature(gt_values,
predicted):
"""Creates the GT ratio feature."""
# This uses the imputed values when the values are not valid.
ratio_pred = (1 - (predicted[:num_train_steps, :] /
(epsilon + gt_values[:num_train_steps])))
# Add 0 at the beginning
ratio_pred = tf.concat([
0 * ratio_pred[:(quantile_encoding_window + num_forecast_steps), :],
ratio_pred
],
axis=0)
ratio_pred = tf.expand_dims(ratio_pred, 1)
ratio_pred = tf.tile(ratio_pred, [1, self.num_states, 1])
return ratio_pred
def indicator_feature(gt_indicator):
"""Creates the indicator feature."""
indicator = 1 - gt_indicator
# Add 0 at the beginning
indicator = tf.concat([
0 * indicator[:(quantile_encoding_window + num_forecast_steps), :],
indicator
],
axis=0)
indicator = tf.expand_dims(indicator, 1)
indicator = tf.tile(indicator, [1, self.num_states, 1])
return indicator
# Propagated states features
temp_propagated_states = tf.concat([
0 * propagated_states[:quantile_encoding_window, :, :],
propagated_states
],
axis=0)
# GT ratio features
death_gt_ratio_feature = gt_ratio_feature(gt_list["death"], pred_death)
confirmed_gt_ratio_feature = gt_ratio_feature(gt_list["confirmed"],
pred_confirmed)
hospitalized_gt_ratio_feature = gt_ratio_feature(gt_list["hospitalized"],
pred_hospitalized)
# Indicator features
death_indicator_feature = indicator_feature(gt_indicator["death"])
confirmed_indicator_feature = indicator_feature(gt_indicator["confirmed"])
hospitalized_indicator_feature = indicator_feature(
gt_indicator["hospitalized"])
for ti in range(initial_quantile_step,
num_train_steps + num_forecast_steps):
if ti < num_train_steps:
state_quantiles_multiplier = tf.ones_like(
tf.expand_dims(propagated_states[0, :, :], 2))
state_quantiles_multiplier = tf.tile(state_quantiles_multiplier,
[1, 1, num_quantiles])
else:
# Construct the input features to be used for quantile estimation.
encoding_input = []
# Features coming from the trend of the estimated.
encoding_input.append(1 - (
temp_propagated_states[ti:(ti + quantile_encoding_window), :, :] /
(epsilon +
temp_propagated_states[ti + quantile_encoding_window, :, :])))
# Features coming from the ground truth ratio of death.
encoding_input.append(
death_gt_ratio_feature[ti:(ti + quantile_encoding_window), :, :])
# Features coming from the ground truth ratio of confirmed.
encoding_input.append(
confirmed_gt_ratio_feature[ti:(ti +
quantile_encoding_window), :, :])
# Features coming from the ground truth ratio of hospitalized.
encoding_input.append(
hospitalized_gt_ratio_feature[ti:(ti +
quantile_encoding_window), :, :])
# Features coming from death indicator.
encoding_input.append(
death_indicator_feature[ti:(ti + quantile_encoding_window), :, :])
# Features coming from confirmed indicator.
encoding_input.append(
confirmed_indicator_feature[ti:(ti +
quantile_encoding_window), :, :])
# Features coming from hospitalized indicator.
encoding_input.append(
hospitalized_indicator_feature[ti:(ti +
quantile_encoding_window), :, :])
encoding_input_t = tf.expand_dims(tf.concat(encoding_input, axis=0), 3)
# Limit the range of features.
encoding_input_t = model_utils.apply_relu_bounds(
encoding_input_t,
lower_bound=0.0,
upper_bound=2.0,
replace_nan=True)
# Estimate the multipliers of quantiles
state_quantiles_multiplier = quantile_biases + tf.math.reduce_mean(
tf.multiply(encoding_input_t, quantile_mapping_kernel), 0)
# Consider accumulation to guarantee monotonicity
state_quantiles_multiplier = tf.math.cumsum(
state_quantiles_multiplier, axis=-1)
if partial_mean_interval == 0:
# Normalize to match the median to point forecasts
state_quantiles_multiplier /= (
epsilon + tf.expand_dims(
state_quantiles_multiplier[:, :,
(num_quantiles - 1) // 2], -1))
else:
# Normalize with major densities to approximate point forecast (mean)
median_idx = (num_quantiles - 1) // 2
normalize_start = median_idx - partial_mean_interval
normalize_end = median_idx + partial_mean_interval
normalizer = tf.reduce_mean(
0.5 *
(state_quantiles_multiplier[:, :, normalize_start:normalize_end] +
state_quantiles_multiplier[:, :, normalize_start +
1:normalize_end + 1]),
axis=2,
keepdims=True)
state_quantiles_multiplier /= (epsilon + normalizer)
state_quantiles_multiplier = (
smooth_coef * state_quantiles_multiplier_prev +
(1 - smooth_coef) * state_quantiles_multiplier)
state_quantiles_multiplier_prev = state_quantiles_multiplier
# Return the estimated quantiles
propagated_states_quantiles_timestep = tf.multiply(
tf.expand_dims(propagated_states[ti, :, :], 2),
state_quantiles_multiplier)
propagated_states_quantiles.append(propagated_states_quantiles_timestep)
return tf.stack(propagated_states_quantiles)
def extract_rate_list(self):
"""Return list of rates that correspond to 'propagated_variables' tensor.
Args: None.
Returns:
List of rate names.
"""
return constants.HOSPITAL_RATE_LIST
def calculate_r_eff(self,
rates = None,
propagated_variables = None,
epsilon = 1e-8):
"""Calculate Basic Reproduction Number R_eff over time and locations.
Args:
rates: rate name->tensor maps.
propagated_variables: single tensor of variables indexed by
(time)x(variables)x(locations) (used in the training).
epsilon: epsilon for avoiding numerical error.
Returns:
R_eff tensor.
"""
if rates is not None and propagated_variables is not None:
raise ValueError("Only rates or seir_variables can be used.")
elif rates is None and propagated_variables is None:
raise ValueError("Have to specify one argument.")
elif rates is not None:
beta_d, beta_ud = rates["average_contact_id_rate"], rates[
"average_contact_iud_rate"]
rho_id, rho_iud = rates["recovery_id_rate"], rates["recovery_iud_rate"]
gamma, h = rates["diagnosis_rate"], rates["hospitalization_rate"]
kappa_id = rates["death_id_rate"]
# equation is same as that for state.
# If you are changing any of the parameters below, please make sure to
# update the Next Generation Matrix derivation and parameters too.
# LINT.IfChange
r_eff = (beta_d * gamma + beta_ud *
(rho_id + kappa_id + h)) / ((gamma + rho_iud) *
(rho_id + kappa_id + h) + epsilon)
return r_eff
else:
propagated_variables_list = tf.unstack(propagated_variables, axis=1)
average_contact_id = propagated_variables_list[2]
average_contact_iud = propagated_variables_list[3]
diagnosis_rate = propagated_variables_list[6]
recovery_rate_id = propagated_variables_list[7]
recovery_rate_iud = propagated_variables_list[8]
hospitalization_rate = propagated_variables_list[10]
death_rate_id = propagated_variables_list[11]
beta_d = average_contact_id
beta_ud = average_contact_iud
rho_id = recovery_rate_id
rho_iud = recovery_rate_iud
gamma = diagnosis_rate
h = hospitalization_rate
kappa_id = death_rate_id
r_eff = (beta_d * gamma + beta_ud *
(rho_id + kappa_id + h)) / ((gamma + rho_iud) *
(rho_id + kappa_id + h) + epsilon)
return r_eff
| 18,882 |
335 | {
"word": "Rotation",
"definitions": [
"The action of rotating about an axis or centre.",
"The conceptual operation of turning a system about an axis.",
"The passing of a privilege or responsibility to each member of a group in a regularly recurring order.",
"The growing of different crops in succession on a piece of land to avoid exhausting the soil and to control weeds, pests, and diseases.",
"The cycle of growth and felling or cutting of trees.",
"A tour of duty, especially by a medical practitioner in training."
],
"parts-of-speech": "Noun"
} | 189 |
3,287 | # --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import os
from azure.cli.testsdk import ScenarioTest
from azure.cli.testsdk import ResourceGroupPreparer
from .example_steps import step_device_create
from .example_steps import step_device_delete
from .example_steps import step_order_create
from .example_steps import step_order_show
from .example_steps import step_order_list
from .example_steps import step_order_delete
from .. import (
try_manual,
raise_if,
calc_coverage
)
TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..'))
# Env setup_scenario
@try_manual
def setup_scenario(test, rg):
step_device_create(test, rg)
# Env cleanup_scenario
@try_manual
def cleanup_scenario(test, rg):
step_device_delete(test, rg)
# Testcase: Scenario
@try_manual
def call_scenario(test, rg):
setup_scenario(test, rg)
step_order_create(test, rg, checks=[
test.check("contactInformation.companyName", "Microsoft", case_sensitive=False),
test.check("contactInformation.contactPerson", "<NAME>", case_sensitive=False),
test.check("shippingAddress.country", "United States", case_sensitive=False),
])
step_order_show(test, rg, checks=[
test.check("contactInformation.companyName", "Microsoft", case_sensitive=False),
test.check("contactInformation.contactPerson", "<NAME>", case_sensitive=False),
test.check("shippingAddress.country", "United States", case_sensitive=False),
])
step_order_list(test, rg, checks=[
test.check('length(@)', 1),
])
step_order_delete(test, rg, checks=[])
step_order_list(test, rg, checks=[
test.check('length(@)', 0),
])
cleanup_scenario(test, rg)
# Test class for Scenario
@try_manual
class OrderScenarioTest(ScenarioTest):
@ResourceGroupPreparer(name_prefix='clitestdataboxedge_GroupForEdgeAutomation'[:7], key='rg', parameter_name='rg')
def test_order_Scenario(self, rg):
self.kwargs.update({
'myDevice': 'testedgedevice',
})
call_scenario(self, rg)
calc_coverage(__file__)
raise_if()
| 862 |
749 | import numpy as np
import roboticstoolbox as rtb
from spatialmath.base import *
from spatialmath import SE3, Twist3
puma = rtb.models.DH.Puma560()
# print(puma)
# #puma.plot(puma.qz)
# q = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
# T = puma.fkine(q)
# q = puma.ikine(T)[0]
# print(q)
# # q = puma.ikine_sym(T)
# puma.maniplty(q)
# J = puma.jacob0(q)
# print(J)
# rtb.tools.models()
# import roboticstoolbox.ETS3 as ETS
# ets = ETS.tx() * ETS.rx() * ETS.tx() * …
# robot = Robot(ets)
# np.set_printoptions(
# linewidth=100, formatter={
# 'float': lambda x: f"{x:8.4g}" if x > 1e-10 else f"{0:8.4g}"})
q = puma.qn
qd = np.zeros((6,))
qdd = np.zeros((6,))
tau = np.zeros((6,))
qdd = puma.accel(q, qd, tau)
print(qdd)
# M = puma.inertia(q)
# print(M)
# C = puma.coriolis(q, qd)
# print(C)
# g = puma.gravload(q)
# print(g)
# links = [
# ELink(name=“l1”, parent=“base”, joint=“rx”, jindex=0, transform=SE3(
# RevoluteDH
# robot = DHRobot(…
# a = SE2
# a
# b = SO3
# b
# a * b
# skew([1, 2, 3])
# skewa([1, 2, 3, 4, 5, 6])
# T = SE3.Rand()
# tw = Twist3(T)
# tw
# tw.v
# tw.w
# tw.pitch()
# tw.pole()
# tw.exp(0)
# tw.exp(1)
# tw.exp([0, 1])
# Twist3.R([1, 0, 0], [0, 0, 0])
# Twist3.P([0, 1, 0])
# line = tw.line()
# type(line)
# sm.geom3.plotvol([-5 5 -5 5 -5 5])
# line.plot('k:')
# S,T0 = puma.twists()
# qn = np.random.rand((7,))
# S.exp(puma.qn)
# S.exp(qn).prod() * T0
# puma.fkine(qn)
# axisLines = tw.line()
# print(axisLines)
# puma.plot(qn)
# axisLines.plot('k:')
| 803 |
315 | <reponame>pxeger/C-Macro-Collections
/**
* Copyright (c) 2019 <NAME>
*
* This file is part of the C Macro Collections Libray.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* ext_sac_list.h
*
* Creation Date: 06/10/2020
*
* Authors:
* <NAME> (https://github.com/LeoVen)
*
*/
#ifndef CMC_EXT_SAC_LIST_H
#define CMC_EXT_SAC_LIST_H
#include "cor_core.h"
/**
* All the EXT parts of SAC List.
*/
#define CMC_EXT_SAC_LIST_PARTS PLACEHOLDER
#define CMC_EXT_SAC_LIST_PLACEHOLDER(ACCESS, FILE, PARAMS) \
CMC_(CMC_(CMC_EXT_SAC_LIST_PLACEHOLDER_, ACCESS), CMC_(_, FILE))(PARAMS)
#define CMC_EXT_SAC_LIST_PLACEHOLDER_PUBLIC_HEADER(PARAMS)
#define CMC_EXT_SAC_LIST_PLACEHOLDER_PUBLIC_SOURCE(PARAMS)
#define CMC_EXT_SAC_LIST_PLACEHOLDER_PRIVATE_HEADER(PARAMS)
#define CMC_EXT_SAC_LIST_PLACEHOLDER_PRIVATE_SOURCE(PARAMS)
#endif /* CMC_EXT_SAC_LIST_H */
| 649 |
4,695 | {
"operation_chart_host_os_chart": "按操作系统类型统计",
"operation_chart_host_biz_chart": "按业务统计",
"operation_chart_host_cloud_chart": "按云区域统计",
"operation_chart_host_change_biz_chart": "主机数量变化趋势",
"operation_chart_model_inst_chart": "实例数量统计",
"operation_chart_model_inst_change_chart": "实例变更统计",
"": ""
} | 204 |
775 | # Copyright (C) 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions
# and limitations under the License.
import os
import pytest
from ote_sdk.entities.model_template import parse_model_template
from ote_sdk.test_suite.e2e_test_system import e2e_pytest_component
from ote_cli.registry import Registry
templates = Registry('external', experimental=True).templates
paths = [os.path.relpath(template.model_template_path) for template in templates]
ids = [os.path.relpath(template.model_template_id) for template in templates]
class TestTemplates:
@e2e_pytest_component
@pytest.mark.parametrize("path", paths, ids=ids)
def test_template(self, path):
template = parse_model_template(path)
assert template.hyper_parameters.data
| 374 |
38,047 | <reponame>Mu-L/jemalloc<filename>include/jemalloc/internal/ckh.h
#ifndef JEMALLOC_INTERNAL_CKH_H
#define JEMALLOC_INTERNAL_CKH_H
#include "jemalloc/internal/tsd.h"
/* Cuckoo hashing implementation. Skip to the end for the interface. */
/******************************************************************************/
/* INTERNAL DEFINITIONS -- IGNORE */
/******************************************************************************/
/* Maintain counters used to get an idea of performance. */
/* #define CKH_COUNT */
/* Print counter values in ckh_delete() (requires CKH_COUNT). */
/* #define CKH_VERBOSE */
/*
* There are 2^LG_CKH_BUCKET_CELLS cells in each hash table bucket. Try to fit
* one bucket per L1 cache line.
*/
#define LG_CKH_BUCKET_CELLS (LG_CACHELINE - LG_SIZEOF_PTR - 1)
/* Typedefs to allow easy function pointer passing. */
typedef void ckh_hash_t (const void *, size_t[2]);
typedef bool ckh_keycomp_t (const void *, const void *);
/* Hash table cell. */
typedef struct {
const void *key;
const void *data;
} ckhc_t;
/* The hash table itself. */
typedef struct {
#ifdef CKH_COUNT
/* Counters used to get an idea of performance. */
uint64_t ngrows;
uint64_t nshrinks;
uint64_t nshrinkfails;
uint64_t ninserts;
uint64_t nrelocs;
#endif
/* Used for pseudo-random number generation. */
uint64_t prng_state;
/* Total number of items. */
size_t count;
/*
* Minimum and current number of hash table buckets. There are
* 2^LG_CKH_BUCKET_CELLS cells per bucket.
*/
unsigned lg_minbuckets;
unsigned lg_curbuckets;
/* Hash and comparison functions. */
ckh_hash_t *hash;
ckh_keycomp_t *keycomp;
/* Hash table with 2^lg_curbuckets buckets. */
ckhc_t *tab;
} ckh_t;
/******************************************************************************/
/* BEGIN PUBLIC API */
/******************************************************************************/
/* Lifetime management. Minitems is the initial capacity. */
bool ckh_new(tsd_t *tsd, ckh_t *ckh, size_t minitems, ckh_hash_t *hash,
ckh_keycomp_t *keycomp);
void ckh_delete(tsd_t *tsd, ckh_t *ckh);
/* Get the number of elements in the set. */
size_t ckh_count(ckh_t *ckh);
/*
* To iterate over the elements in the table, initialize *tabind to 0 and call
* this function until it returns true. Each call that returns false will
* update *key and *data to the next element in the table, assuming the pointers
* are non-NULL.
*/
bool ckh_iter(ckh_t *ckh, size_t *tabind, void **key, void **data);
/*
* Basic hash table operations -- insert, removal, lookup. For ckh_remove and
* ckh_search, key or data can be NULL. The hash-table only stores pointers to
* the key and value, and doesn't do any lifetime management.
*/
bool ckh_insert(tsd_t *tsd, ckh_t *ckh, const void *key, const void *data);
bool ckh_remove(tsd_t *tsd, ckh_t *ckh, const void *searchkey, void **key,
void **data);
bool ckh_search(ckh_t *ckh, const void *searchkey, void **key, void **data);
/* Some useful hash and comparison functions for strings and pointers. */
void ckh_string_hash(const void *key, size_t r_hash[2]);
bool ckh_string_keycomp(const void *k1, const void *k2);
void ckh_pointer_hash(const void *key, size_t r_hash[2]);
bool ckh_pointer_keycomp(const void *k1, const void *k2);
#endif /* JEMALLOC_INTERNAL_CKH_H */
| 1,153 |
505 | <reponame>Manny27nyc/BitcoinArmory<gh_stars>100-1000
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (C) 2016, goatpig. //
// Distributed under the MIT license //
// See LICENSE-MIT or https://opensource.org/licenses/MIT //
// //
////////////////////////////////////////////////////////////////////////////////
#include "SocketObject.h"
#include <cstring>
#include <stdexcept>
///////////////////////////////////////////////////////////////////////////////
//
// BinarySocket
//
///////////////////////////////////////////////////////////////////////////////
BinarySocket::BinarySocket(const string& addr, const string& port) :
addr_(addr), port_(port)
{
//resolve address
struct addrinfo hints;
struct addrinfo *result;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
#ifdef _WIN32
//somehow getaddrinfo doesnt handle localhost on Windows
string addrstr = addr;
if(addr == "localhost")
addrstr = "127.0.0.1";
#else
auto& addrstr = addr;
#endif
getaddrinfo(addrstr.c_str(), port.c_str(), &hints, &result);
for (auto ptr = result; ptr != nullptr; ptr = ptr->ai_next)
{
if (ptr->ai_family == AF_INET)
{
memcpy(&serv_addr_, ptr->ai_addr, sizeof(sockaddr_in));
memcpy(&serv_addr_.sa_data, &ptr->ai_addr->sa_data, 14);
break;
}
throw runtime_error("unsupported remote address format");
}
freeaddrinfo(result);
}
///////////////////////////////////////////////////////////////////////////////
SOCKET BinarySocket::openSocket(bool blocking)
{
SOCKET sockfd = SOCK_MAX;
try
{
sockfd = socket(serv_addr_.sa_family, SOCK_STREAM, 0);
if (sockfd < 0)
throw SocketError("failed to create socket");
auto result = connect(sockfd, &serv_addr_, sizeof(serv_addr_));
if (result < 0)
{
closeSocket(sockfd);
throw SocketError("failed to connect to server");
}
setBlocking(sockfd, blocking);
}
catch (SocketError &)
{
closeSocket(sockfd);
sockfd = SOCK_MAX;
}
return sockfd;
}
///////////////////////////////////////////////////////////////////////////////
void BinarySocket::closeSocket(SOCKET& sockfd)
{
if (sockfd == SOCK_MAX)
return;
#ifdef WIN32
closesocket(sockfd);
#else
close(sockfd);
#endif
sockfd = SOCK_MAX;
}
////////////////////////////////////////////////////////////////////////////////
void BinarySocket::writeToSocket(SOCKET sockfd, void* data, size_t size)
{
//don't return we have written and are write ready
struct pollfd pfd;
bool haveWritten = false;
pfd.fd = sockfd;
pfd.events = POLLOUT;
size_t total_send = 0;
while (1)
{
#ifdef _WIN32
auto status = WSAPoll(&pfd, 1, 60000);
#else
auto status = poll(&pfd, 1, 60000);
#endif
if (status == 0)
continue;
else if (status == -1)
{
#ifdef _WIN32
auto errornum = WSAGetLastError();
#else
auto errornum = errno;
#endif
stringstream ss;
ss << "poll() error in writeToSocket: " << errornum;
LOGERR << ss.str();
throw SocketError(ss.str());
}
//exceptions
if (pfd.revents & POLLERR)
{
//break out of poll loop
LOGERR << "POLLERR in writeToSocket";
throw SocketError("POLLERR in writeToSocket");
}
if (pfd.revents & POLLNVAL)
{
//LOGERR << "POLLNVAL in writeToSocket";
throw SocketError("POLLNVAL in writeToSocket");
}
if (pfd.revents & POLLOUT)
{
if (!haveWritten)
{
auto bytessent = send(
sockfd, (char*)data + total_send, size - total_send, 0);
if (bytessent == 0)
throw SocketError("failed to send data");
total_send += bytessent;
if (total_send >= size)
haveWritten = true;
}
else
{
//write ready
break;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
bool BinarySocket::testConnection(void)
{
try
{
auto sockfd = openSocket(true);
if (sockfd == SOCK_MAX)
return false;
closeSocket(sockfd);
return true;
}
catch (runtime_error&)
{
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
void BinarySocket::setBlocking(SOCKET sock, bool setblocking)
{
if (sock < 0)
throw SocketError("invalid socket");
#ifdef WIN32
unsigned long mode = (unsigned long)!setblocking;
if (ioctlsocket(sock, FIONBIO, &mode) != 0)
throw SocketError("failed to set blocking mode on socket");
#else
int flags = fcntl(sock, F_GETFL, 0);
if (flags < 0) return;
flags = setblocking ? (flags&~O_NONBLOCK) : (flags | O_NONBLOCK);
int rt = fcntl(sock, F_SETFL, flags);
if (rt != 0)
{
auto thiserrno = errno;
cout << "fcntl returned " << rt << endl;
cout << "error: " << strerror(errno);
throw SocketError("failed to set blocking mode on socket");
}
#endif
}
///////////////////////////////////////////////////////////////////////////////
void BinarySocket::readFromSocket(SOCKET sockfd, ReadCallback callback)
{
exception_ptr exceptptr = nullptr;
auto readLambda = [sockfd, callback, this](void)->void
{
try
{
readFromSocketThread(sockfd, callback);
}
catch (...)
{
}
};
thread readThr(readLambda);
if (readThr.joinable())
readThr.detach();
}
///////////////////////////////////////////////////////////////////////////////
void BinarySocket::readFromSocketThread(SOCKET sockfd, ReadCallback callback)
{
size_t readIncrement = 8192;
stringstream errorss;
exception_ptr exceptptr = nullptr;
struct pollfd pfd;
pfd.fd = sockfd;
pfd.events = POLLIN;
try
{
while (1)
{
#ifdef _WIN32
auto status = WSAPoll(&pfd, 1, 60000);
#else
auto status = poll(&pfd, 1, 60000);
#endif
if (status == 0)
continue;
if (status == -1)
{
//select error, process and exit loop
#ifdef _WIN32
auto errornum = WSAGetLastError();
#else
auto errornum = errno;
#endif
errorss << "poll() error in readFromSocketThread: " << errornum;
LOGERR << errorss.str();
throw SocketError(errorss.str());
}
if (pfd.revents & POLLNVAL)
{
#ifndef _WIN32
/*int error = 0;
socklen_t errlen = sizeof(error);
getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&error, &errlen);
LOGERR << "readFromSocketThread poll returned POLLNVAL, errnum: " <<
error << ", errmsg: " << strerror(error);*/
#endif
throw SocketError("POLLNVAL in readFromSocketThread");
}
//exceptions
if (pfd.revents & POLLERR)
{
//TODO: grab socket error code, pass error to callback
//break out of poll loop
errorss << "POLLERR error in readFromSocketThread";
LOGERR << errorss.str();
throw SocketError(errorss.str());
}
if (pfd.revents & POLLRDBAND)
{
//we dont use OOB data, just grab and dump
vector<uint8_t> readdata;
readdata.resize(1024);
int readAmt;
size_t totalread = 0;
while (readAmt =
recv(sockfd, (char*)&readdata[0] + totalread, 1024, MSG_OOB))
{
if (readAmt < 0)
break;
totalread += readAmt;
if (readAmt < 1024)
break;
readdata.resize(totalread + 1024);
}
}
if (pfd.revents & POLLIN)
{
//read socket
vector<uint8_t> readdata;
readdata.resize(readIncrement);
size_t totalread = 0;
int readAmt;
while ((readAmt =
recv(sockfd, (char*)&readdata[0] + totalread , readIncrement, 0))
!= 0)
{
if (readAmt < 0)
{
#ifdef _WIN32
auto errornum = WSAGetLastError();
if(errornum == WSAEWOULDBLOCK)
break;
#else
auto errornum = errno;
if (errornum == EAGAIN || errornum == EWOULDBLOCK)
break;
#endif
errorss << "recv error: " << errornum;
throw SocketError(errorss.str());
break;
}
totalread += readAmt;
if (readAmt < readIncrement)
break;
readdata.resize(totalread + readIncrement);
}
if (readAmt == 0)
{
LOGINFO << "POLLIN recv return 0";
break;
}
if (totalread > 0)
{
readdata.resize(totalread);
//callback with the new data, exit poll loop on true
if (callback(move(readdata), nullptr))
break;
}
}
//socket was closed
if (pfd.revents & POLLHUP)
break;
}
}
catch (...)
{
exceptptr = current_exception();
}
//cleanup
closeSocket(sockfd);
//mark read as completed
callback(vector<uint8_t>(), exceptptr);
}
///////////////////////////////////////////////////////////////////////////////
void BinarySocket::writeAndRead(
SOCKET sockfd, uint8_t* data, size_t len, SequentialReadCallback callback)
{
size_t readIncrement = 8192;
stringstream errorss;
bool haveWritten = false;
exception_ptr exceptptr = nullptr;
struct pollfd pfd;
pfd.fd = sockfd;
pfd.events = POLLOUT;
size_t total_send = 0;
while (1)
{
#ifdef _WIN32
auto status = WSAPoll(&pfd, 1, 60000);
#else
auto status = poll(&pfd, 1, 60000);
#endif
if (status == 0)
continue;
if (status == -1)
{
//select error, process and exit loop
#ifdef _WIN32
auto errornum = WSAGetLastError();
#else
auto errornum = errno;
#endif
errorss << "poll() error in readAndWrite: " << errornum;
if (verbose_)
LOGERR << errorss.str();
throw SocketError(errorss.str());
}
if (pfd.revents & POLLNVAL)
{
#ifndef _WIN32
/*int error = 0;
socklen_t errlen = sizeof(error);
getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&error, &errlen);
LOGERR << "readFromSocketThread poll returned POLLNVAL, errnum: " <<
error << ", errmsg: " << strerror(error);*/
#endif
throw SocketError("POLLNVAL in readAndWrite");
}
//exceptions
if (pfd.revents & POLLERR)
{
//TODO: grab socket error code, pass error to callback
//break out of poll loop
errorss << "POLLERR error in readAndWrite";
if (verbose_)
LOGERR << errorss.str();
throw SocketError(errorss.str());
}
if (pfd.revents & POLLOUT)
{
if (!haveWritten)
{
auto bytessent = send(
sockfd, (char*)data + total_send, len - total_send, 0);
if (bytessent == 0)
throw SocketError("failed to send data");
total_send += bytessent;
if (total_send >= len)
{
haveWritten = true;
pfd.events = POLLIN;
}
}
}
if (pfd.revents & POLLRDBAND)
{
//we dont use OOB data, just grab and dump
vector<uint8_t> readdata;
readdata.resize(1024);
int readAmt;
size_t totalread = 0;
while (readAmt =
recv(sockfd, (char*)&readdata[0] + totalread, 1024, MSG_OOB))
{
if (readAmt < 0)
break;
totalread += readAmt;
if (readAmt < 1024)
break;
readdata.resize(totalread + 1024);
}
}
if (pfd.revents & POLLIN)
{
//read socket
vector<uint8_t> readdata;
readdata.resize(readIncrement);
size_t totalread = 0;
int readAmt;
while ((readAmt =
recv(sockfd, (char*)&readdata[0] + totalread, readIncrement, 0))
!= 0)
{
if (readAmt < 0)
{
#ifdef _WIN32
auto errornum = WSAGetLastError();
if (errornum == WSAEWOULDBLOCK)
break;
#else
auto errornum = errno;
if (errornum == EAGAIN || errornum == EWOULDBLOCK)
break;
#endif
errorss << "recv error: " << errornum;
throw SocketError(errorss.str());
break;
}
totalread += readAmt;
if (readAmt < readIncrement)
break;
readdata.resize(totalread + readIncrement);
}
if (readAmt == 0)
{
if (!callback(readdata))
{
if (verbose_)
LOGINFO << "POLLIN recv return 0";
}
break;
}
if (totalread > 0)
{
readdata.resize(totalread);
//callback with the new data, exit poll loop on true
if (callback(readdata))
break;
}
}
//socket was closed
if (pfd.revents & POLLHUP)
break;
}
//cleanup
closeSocket(sockfd);
}
///////////////////////////////////////////////////////////////////////////////
void BinarySocket::listen(AcceptCallback callback)
{
SOCKET sockfd = SOCK_MAX;
try
{
sockfd = socket(serv_addr_.sa_family, SOCK_STREAM, 0);
if (sockfd < 0)
throw SocketError("failed to create socket");
if (::bind(sockfd, &serv_addr_, sizeof(serv_addr_)) < 0)
{
closeSocket(sockfd);
throw SocketError("failed to bind socket");
}
if (::listen(sockfd, 10) < 0)
{
closeSocket(sockfd);
throw SocketError("failed to listen to socket");
}
}
catch (SocketError &)
{
closeSocket(sockfd);
return;
}
stringstream errorss;
exception_ptr exceptptr = nullptr;
struct pollfd pfd;
pfd.fd = sockfd;
pfd.events = POLLIN;
try
{
while (1)
{
#ifdef _WIN32
auto status = WSAPoll(&pfd, 1, 60000);
#else
auto status = poll(&pfd, 1, 60000);
#endif
if (status == 0)
continue;
if (status == -1)
{
//select error, process and exit loop
#ifdef _WIN32
auto errornum = WSAGetLastError();
#else
auto errornum = errno;
#endif
errorss << "poll() error in readFromSocketThread: " << errornum;
LOGERR << errorss.str();
throw SocketError(errorss.str());
}
if (pfd.revents & POLLNVAL)
{
#ifndef _WIN32
/*int error = 0;
socklen_t errlen = sizeof(error);
getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&error, &errlen);
LOGERR << "readFromSocketThread poll returned POLLNVAL, errnum: " <<
error << ", errmsg: " << strerror(error);*/
#endif
throw SocketError("POLLNVAL in readFromSocketThread");
}
//exceptions
if (pfd.revents & POLLERR)
{
//TODO: grab socket error code, pass error to callback
//break out of poll loop
errorss << "POLLERR error in readFromSocketThread";
LOGERR << errorss.str();
throw SocketError(errorss.str());
}
if (pfd.revents & POLLIN)
{
//accept socket and trigger callback
AcceptStruct astruct;
astruct.sockfd_ = accept(sockfd, &astruct.saddr_, &astruct.addrlen_);
callback(move(astruct));
}
}
}
catch (...)
{
exceptptr = current_exception();
}
//cleanup
closeSocket(sockfd);
}
///////////////////////////////////////////////////////////////////////////////
ListenServer::ListenServer(const string& addr, const string& port)
{
listenSocket_ = make_unique<DedicatedBinarySocket>(addr, port);
listenSocket_->verbose_ = false;
}
///////////////////////////////////////////////////////////////////////////////
void ListenServer::start(ReadCallback callback)
{
auto listenlbd = [this](ReadCallback clbk)->void
{
this->listenThread(clbk);
};
listenThread_ = thread(listenlbd, callback);
}
///////////////////////////////////////////////////////////////////////////////
void ListenServer::join()
{
if (listenThread_.joinable())
listenThread_.join();
}
///////////////////////////////////////////////////////////////////////////////
void ListenServer::listenThread(ReadCallback callback)
{
auto acceptldb = [callback, this](AcceptStruct astruct)->void
{
astruct.readCallback_ = callback;
this->acceptProcess(move(astruct));
};
listenSocket_->listen(acceptldb);
}
///////////////////////////////////////////////////////////////////////////////
void ListenServer::acceptProcess(AcceptStruct aStruct)
{
unique_lock<mutex> lock(mu_);
auto readldb = [this](
shared_ptr<DedicatedBinarySocket> sock, ReadCallback callback)->void
{
sock->readFromSocket(callback);
auto sockfd = sock->sockfd_;
this->cleanUpStack_.push_back(move(sockfd));
};
auto ss = make_unique<SocketStruct>();
//create BinarySocket object from sockfd
ss->sock_ = make_shared<DedicatedBinarySocket>(aStruct.sockfd_);
ss->sock_->verbose_ = false;
//start read lambda thread
ss->thr_ = thread(readldb, ss->sock_, aStruct.readCallback_);
//record thread id and socket ptr in socketStruct, add to acceptMap_
acceptMap_.insert(make_pair(aStruct.sockfd_, move(ss)));
//run through clean up stack, removing flagged entries from acceptMap_
try
{
while (1)
{
auto&& sock = cleanUpStack_.pop_front();
auto iter = acceptMap_.find(sock);
if (iter != acceptMap_.end())
{
auto ssptr = move(iter->second);
acceptMap_.erase(iter);
if (ssptr->thr_.joinable())
ssptr->thr_.join();
}
}
}
catch (IsEmpty&)
{
}
}
///////////////////////////////////////////////////////////////////////////////
void ListenServer::stop()
{
listenSocket_->closeSocket();
if (listenThread_.joinable())
listenThread_.join();
for (auto& sockPair : acceptMap_)
{
auto& sockstruct = sockPair.second;
sockstruct->sock_->closeSocket();
if (sockstruct->thr_.joinable())
sockstruct->thr_.join();
}
}
| 9,149 |
655 | #include "embeddedr.h"
/* Helper variable to store R's status
*/
const unsigned int const RPY_R_INITIALIZED = 0x01;
const unsigned int const RPY_R_BUSY = 0x02;
/* Initial status is 0 */
static unsigned int embeddedR_status = 0;
/* An environment to keep R objects preserved by rpy2 */
static SEXP RPY_R_PreciousEnv = NULL;
static PyObject *Rpy_R_Precious;
static inline void embeddedR_setlock(void) {
embeddedR_status = embeddedR_status | RPY_R_BUSY;
}
static inline void embeddedR_freelock(void) {
embeddedR_status = embeddedR_status ^ RPY_R_BUSY;
}
static inline unsigned int rpy_has_status(unsigned int status) {
return (embeddedR_status & status) == status;
}
/*FIXME: this is not thread safe (calls to R not using
locking). Can this is be a source of errors ?
*/
static void SexpObject_clear(SexpObject *sexpobj)
{
if (sexpobj->pycount <= 0) {
printf("Warning: clearing an R object with a refcount <= zero.\n");
}
if ((sexpobj->sexp) != R_NilValue) {
/* R objects that needs to be preserved from garbage collection */
if (RPY_R_PreciousEnv == NULL) {
/* Use the R "precious list" */
R_ReleaseObject(sexpobj->sexp);
} else {
/* Use the environment */
static char *name_buf;
if (name_buf == NULL) {
/* Initialize with the number of characters required for an hexadecimal
representation of a pointer*/
name_buf = (char *)calloc(sizeof(name_buf)*2+2+1, sizeof(char)) ;
}
sprintf(name_buf, "%p", (void *)(sexpobj->sexp));
SEXP res = rpy2_remove(Rf_mkString(name_buf),
RPY_R_PreciousEnv,
Rf_ScalarLogical(FALSE));
//Rf_defineVar(name_r, sexpobj->sexp, RPY_R_PreciousEnv);
}
PyMem_Free(sexpobj);
}
/* sexpobj->count--; */
/* #ifdef RPY_VERBOSE */
/* printf("R:%p -- sexp count is %i...", */
/* sexpobj->sexp, sexpobj->count); */
/* #endif */
/* if (((*sexpobj).count == 0) && (*sexpobj).sexp) { */
/* #ifdef RPY_VERBOSE */
/* printf("freeing SEXP resources..."); */
/* #endif */
/* /\* if (sexpobj->sexp != R_NilValue) { *\/ */
/* /\* #ifdef RPY_DEBUG_PRESERVE *\/ */
/* /\* printf(" PRESERVE -- Sexp_clear: R_ReleaseObject -- %p ", *\/ */
/* /\* sexpobj->sexp); *\/ */
/* /\* preserved_robjects -= 1; *\/ */
/* /\* printf("-- %i\n", preserved_robjects); *\/ */
/* /\* #endif *\/ */
/* /\* int preserve_status = Rpy_ReleaseObject(sexpobj->sexp); *\/ */
/* /\* if (preserve_status == -1) { *\/ */
/* /\* PyErr_Print(); *\/ */
/* /\* PyErr_Clear(); *\/ */
/* /\* } *\/ */
/* /\* } *\/ */
/* /\* self->ob_type->tp_free((PyObject*)self); *\/ */
/* #ifdef RPY_VERBOSE */
/* printf("done.\n"); */
/* #endif */
/* } */
}
static void SexpObject_CObject_destroy(PyObject *rpycapsule)
{
SexpObject *sexpobj_ptr = (SexpObject *)(PyCapsule_GetPointer(rpycapsule,
"rpy2.rinterface._rinterface.SEXPOBJ_C_API"));
SexpObject_clear(sexpobj_ptr);
}
/* Keep track of R objects preserved by rpy2
Return NULL on failure (a Python exception being set)
*/
static SexpObject* Rpy_PreserveObject(SEXP object) {
/* PyDict can be confused if an error has been raised.
We put aside the exception if the case, to restore it at the end.
FIXME: this situation can occur because of presumed shortcomings
in the overall design of rpy2.
*/
int reset_error_state = 0;
PyObject *ptype, *pvalue, *ptraceback;
if (PyErr_Occurred()) {
reset_error_state = 1;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
}
PyObject *key = PyLong_FromVoidPtr((void *)object);
PyObject *capsule = PyDict_GetItem(Rpy_R_Precious, key);
SexpObject *sexpobj_ptr;
/* capsule is a borrowed reference */
if (capsule == NULL) {
/* The R object is not yet tracked by rpy2 so we:
- create a new SexpObject.
- create a capsule for it
- put the capsule in the tracking dictionary
*/
sexpobj_ptr = (SexpObject *)PyMem_Malloc(1 * sizeof(SexpObject));
if (! sexpobj_ptr) {
PyErr_NoMemory();
return NULL;
}
sexpobj_ptr->pycount = 1;
sexpobj_ptr->sexp = object;
capsule = PyCapsule_New((void *)(sexpobj_ptr),
"rpy2.rinterface._rinterface.SEXPOBJ_C_API",
SexpObject_CObject_destroy);
if (PyDict_SetItem(Rpy_R_Precious, key, capsule) == -1) {
Py_DECREF(key);
Py_DECREF(capsule);
return NULL;
}
Py_DECREF(capsule);
if (object != R_NilValue) {
/* R objects that needs to be preserved from garbage collection */
if (RPY_R_PreciousEnv == NULL) {
/* Use the R "precious list" */
R_PreserveObject(object);
} else {
/* Use an enclosing environment instead of R's "precious list"
to protect the object from garbage collection */
static char *name_buf;
if (name_buf == NULL) {
/* Initialize with the number of characters required for an hexadecimal
representation of a pointer*/
name_buf = (char *)calloc(sizeof(name_buf)*2+2+1, sizeof(char)) ;
}
sprintf(name_buf, "%p", (void *)object);
SEXP name_r = Rf_install(name_buf);
Rf_defineVar(name_r, object, RPY_R_PreciousEnv);
}
}
} else {
/* Reminder: capsule is a borrowed reference */
sexpobj_ptr = (SexpObject *)(PyCapsule_GetPointer(capsule,
"rpy2.rinterface._rinterface.SEXPOBJ_C_API"));
if (sexpobj_ptr != NULL) {
sexpobj_ptr->pycount++;
}
}
Py_DECREF(key);
if (reset_error_state) {
if (PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
}
PyErr_Restore(ptype, pvalue, ptraceback);
}
return sexpobj_ptr;
}
/* static int Rpy_PreserveObject(SEXP object) { */
/* R_ReleaseObject(RPY_R_Precious); */
/* PROTECT(RPY_R_Precious); */
/* RPY_R_Precious = CONS(object, RPY_R_Precious); */
/* UNPROTECT(1); */
/* R_PreserveObject(RPY_R_Precious); */
/* } */
static int Rpy_ReleaseObject(SEXP object) {
/* PyDict can be confused if an error has been raised.
We put aside the exception if the case, to restore it at the end.
FIXME: this situation can occur because of presumed shortcomings
in the overall design of rpy2.
*/
int reset_error_state = 0;
PyObject *ptype, *pvalue, *ptraceback;
if (PyErr_Occurred()) {
reset_error_state = 1;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
}
PyObject *key = PyLong_FromVoidPtr((void *)object);
PyObject *capsule = PyDict_GetItem(Rpy_R_Precious, key);
/* capsule is a borrowed reference */
if (capsule == NULL) {
/* FIXME: should all rpy2 proxy objects have an associated capsule ?
* If yes, why are we here ?
*/
printf("Warning: the rpy2 object we are trying to release has no associated capsule.\n");
if (reset_error_state) {
PyErr_Restore(ptype, pvalue, ptraceback);
printf("Restoring an earlier exception.\n");
printf("Error:Trying to release object ID %ld while not preserved\n",
PyLong_AsLong(key));
} else {
PyErr_Format(PyExc_KeyError,
"Trying to release object ID %ld while not preserved\n",
PyLong_AsLong(key));
}
Py_DECREF(key);
return -1;
}
SexpObject *sexpobj_ptr = (SexpObject *)(PyCapsule_GetPointer(capsule,
"rpy2.rinterface._rinterface.SEXPOBJ_C_API"));
if (sexpobj_ptr == NULL) {
if (reset_error_state) {
if (PyErr_Occurred()) {
PyErr_Print();
}
PyErr_Restore(ptype, pvalue, ptraceback);
}
Py_DECREF(key);
return -1;
}
int res = 0;
switch (sexpobj_ptr->pycount) {
case 0:
if (object != R_NilValue) {
res = -1;
PyErr_Format(PyExc_ValueError,
"Preserved object ID %ld with a count of zero\n",
PyLong_AsLong(key));
Py_DECREF(key);
return res;
}
break;
case 1:
/* By deleting the capsule from the dictionary, the count of the SexpObject
will go down by one, reach zero, and the release of the R object
will be performed. */
if (object == R_NilValue) {
sexpobj_ptr->pycount--;
} else {
res = PyDict_DelItem(Rpy_R_Precious, key);
if (res == -1)
PyErr_Format(PyExc_ValueError,
"Occured while deleting preserved object ID %ld\n",
PyLong_AsLong(key));
}
break;
case 2:
/* When the refcount is exactly 2, we could have the following possible
* situations:
* A- 1 PySexpObject, 1 SexpObject in a capsule
* B- 2 SexpObject in a capsule
* C- 2 PySexObject
* Only A is effectively possible because each PySexpObject has
* an associated capsule (rules out C) and each capsule is unique
* for a given SEXP (rules out B).
* In addition to that, the reference counting in rpy2 is independent
* from Python's reference counting. This is means that in the situation A/
* above we can have n pointers to the PySexpObject and m pointers
* to the SexpObject.
*/
// ob_refcnt;
/* if (PyLong_AsLong(key) == 0) { */
/* printf("Count 2 for: 0\n"); */
/* break; */
/* } */
sexpobj_ptr->pycount--;
/* if (object == R_NilValue) { */
/* sexpobj_ptr->count--; */
/* } else { */
/* //printf("-->use to delete %ld here\n", PyLong_AsLong(key)); */
/* res = PyDict_DelItem(Rpy_R_Precious, key); */
/* if (res == -1) */
/* PyErr_Format(PyExc_ValueError, */
/* "Occured while deleting preserved object ID %ld\n", */
/* PyLong_AsLong(key)); */
/* } */
break;
default:
sexpobj_ptr->pycount--;
break;
}
Py_DECREF(key);
if (reset_error_state) {
if (PyErr_Occurred()) {
PyErr_Print();
}
PyErr_Restore(ptype, pvalue, ptraceback);
}
return res;
}
/* SEXP parentnode, node; */
/* Py_ssize_t res = -1; */
/* if (isNull(RPY_R_Precious)) { */
/* return res; */
/* } */
/* res++; */
/* if (object == CAR(RPY_R_Precious)) { */
/* RPY_R_Precious = CDR(RPY_R_Precious); */
/* return res; */
/* } */
/* parentnode = RPY_R_Precious; */
/* node = CDR(RPY_R_Precious); */
/* while (!isNull(node)) { */
/* res++; */
/* if (object == CAR(node)) { */
/* SETCDR(parentnode, CDR(node)); */
/* return res; */
/* } */
/* parentnode = node; */
/* node = CDR(node); */
/* } */
PyDoc_STRVAR(Rpy_ProtectedIDs_doc,
"Return a tuple of pairs with each: \n"
"- an R ID for the objects protected from R's garbage collection by rpy2\n"
"- the number of rpy2 objects protecting that R object from collection.\n\n"
"The R ID is a memory pointer for the R-defined C-structure "
"containing all information about the R object. It is available "
"from an rpy2 object through the read-only attribute `rid`.");
/* Return a tuple with IDs of R objects protected by rpy2 and counts */
static PyObject* Rpy_ProtectedIDs(PyObject *self) {
PyObject *key, *capsule;
Py_ssize_t pos = 0;
PyObject *ids = PyTuple_New(PyDict_Size(Rpy_R_Precious));
Py_ssize_t pos_ids = 0;
PyObject *id_count;
SexpObject *sexpobject_ptr;
while (PyDict_Next(Rpy_R_Precious, &pos, &key, &capsule)) {
id_count = PyTuple_New(2);
Py_INCREF(key);
PyTuple_SET_ITEM(id_count, 0, key);
sexpobject_ptr = (SexpObject *)(PyCapsule_GetPointer(capsule,
"rpy2.rinterface._rinterface.SEXPOBJ_C_API"));
PyTuple_SET_ITEM(id_count, 1, PyLong_FromLong(sexpobject_ptr->pycount));
PyTuple_SET_ITEM(ids, pos_ids, id_count);
pos_ids++;
}
return ids;
}
/* return 0 on success, -1 on failure (and set an exception) */
static inline int Rpy_ReplaceSexp(PySexpObject *pso, SEXP rObj) {
SexpObject *sexpobj_ptr = Rpy_PreserveObject(rObj);
//printf("target: %zd\n", sexpobj_ptr->count);
if (sexpobj_ptr == NULL) {
return -1;
}
//printf("orig: %zd\n", pso->sObj->count);
SEXP sexp = pso->sObj->sexp;
pso->sObj = sexpobj_ptr;
int res = Rpy_ReleaseObject(sexp);
return res;
}
PyDoc_STRVAR(EmbeddedR_isInitialized_doc,
"is_initialized() -> bool\n"
""
"Return whether R is initialized.");
static PyObject*
EmbeddedR_isInitialized(void) {
if (rpy2_isinitialized()) {
Py_INCREF(Py_True);
return Py_True;
} else {
Py_INCREF(Py_False);
return Py_False;
}
}
| 5,122 |
18,636 | import os
from .base import DataView
class Source(DataView):
"""Information on a "simple" Python package index.
This could be PyPI, or a self-hosted index server, etc. The server
specified by the `url` attribute is expected to provide the "simple"
package API.
"""
__SCHEMA__ = {
"name": {"type": "string", "required": True},
"url": {"type": "string", "required": True},
"verify_ssl": {"type": "boolean", "required": True},
}
@property
def name(self):
return self._data["name"]
@name.setter
def name(self, value):
self._data["name"] = value
@property
def url(self):
return self._data["url"]
@url.setter
def url(self, value):
self._data["url"] = value
@property
def verify_ssl(self):
return self._data["verify_ssl"]
@verify_ssl.setter
def verify_ssl(self, value):
self._data["verify_ssl"] = value
@property
def url_expanded(self):
return os.path.expandvars(self._data["url"])
| 428 |
1,085 | <gh_stars>1000+
"""
Migration script to change the 'value' column of 'user_preference' table from varchar to text.
"""
import logging
from sqlalchemy import MetaData, Table, Text
log = logging.getLogger(__name__)
metadata = MetaData()
def upgrade(migrate_engine):
metadata.bind = migrate_engine
print(__doc__)
metadata.reflect()
t = Table("user_preference", metadata, autoload=True)
t.c.value.alter(type=Text)
def downgrade(migrate_engine):
metadata.bind = migrate_engine
metadata.reflect()
# Pass, since we don't want to potentially truncate data.
| 198 |
852 | <reponame>Purva-Chaudhari/cmssw
#ifndef CRackTrajectoryBuilder_h
#define CRackTrajectoryBuilder_h
//
// Package: RecoTracker/SingleTrackPattern
// Class: CRackTrajectoryBuilder
// Original Author: <NAME>-INFN perugia
#include <string>
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ConsumesCollector.h"
#include "DataFormats/TrajectorySeed/interface/TrajectorySeedCollection.h"
#include "DataFormats/TrackerRecHit2D/interface/SiPixelRecHitCollection.h"
#include "DataFormats/TrackerRecHit2D/interface/SiStripMatchedRecHit2DCollection.h"
#include "DataFormats/TrackerRecHit2D/interface/SiStripRecHit2DCollection.h"
#include "DataFormats/TrackCandidate/interface/TrackCandidateCollection.h"
#include "TrackingTools/PatternTools/interface/Trajectory.h"
#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
#include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h"
#include "TrackingTools/GeomPropagators/interface/AnalyticalPropagator.h"
#include "TrackingTools/KalmanUpdators/interface/KFUpdator.h"
#include "TrackingTools/KalmanUpdators/interface/Chi2MeasurementEstimator.h"
#include "MagneticField/Engine/interface/MagneticField.h"
#include "DataFormats/GeometryVector/interface/GlobalPoint.h"
#include "RecoTracker/TkDetLayers/interface/GeometricSearchTracker.h"
#include "RecoTracker/Record/interface/TrackerRecoGeometryRecord.h"
#include "TrackingTools/TransientTrackingRecHit/interface/TransientTrackingRecHitBuilder.h"
#include "TrackingTools/Records/interface/TransientRecHitRecord.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/TrackReco/interface/TrackExtra.h"
#include "TrackingTools/TrackFitters/interface/KFTrajectoryFitter.h"
#include "TrackingTools/TrackFitters/interface/KFTrajectorySmoother.h"
#include "TrackingTools/MeasurementDet/interface/LayerMeasurements.h"
#include "RecoTracker/MeasurementDet/interface/MeasurementTracker.h"
#include "TrackingTools/MaterialEffects/interface/PropagatorWithMaterial.h"
//to sort hits by the det position
class CompareDetY_plus {
public:
CompareDetY_plus(const TrackerGeometry& tracker) : _tracker(tracker) {}
bool operator()(const TrackingRecHit* rh1, const TrackingRecHit* rh2) {
const GeomDet* detPos1 = _tracker.idToDet(rh1->geographicalId());
const GeomDet* detPos2 = _tracker.idToDet(rh2->geographicalId());
const GlobalPoint& gp1 = detPos1->position();
const GlobalPoint& gp2 = detPos2->position();
if (gp1.y() > gp2.y())
return true;
if (gp1.y() < gp2.y())
return false;
// if (gp1.y()== gp2.y())
//
return (rh1->geographicalId() < rh2->geographicalId());
};
private:
// edm::ESHandle<TrackerGeometry> _tracker;
const TrackerGeometry& _tracker;
};
class CompareDetY_minus {
public:
CompareDetY_minus(const TrackerGeometry& tracker) : _tracker(tracker) {}
bool operator()(const TrackingRecHit* rh1, const TrackingRecHit* rh2) {
const GeomDet* detPos1 = _tracker.idToDet(rh1->geographicalId());
const GeomDet* detPos2 = _tracker.idToDet(rh2->geographicalId());
const GlobalPoint& gp1 = detPos1->position();
const GlobalPoint& gp2 = detPos2->position();
if (gp1.y() < gp2.y())
return true;
if (gp1.y() > gp2.y())
return false;
// if (gp1.y()== gp2.y())
//
return (rh1->geographicalId() < rh2->geographicalId());
};
private:
// edm::ESHandle<TrackerGeometry> _tracker;
const TrackerGeometry& _tracker;
};
#ifndef TrajectoryBuilder_CompareHitY
#define TrajectoryBuilder_CompareHitY
class CompareHitY {
public:
CompareHitY(const TrackerGeometry& tracker) : _tracker(tracker) {}
bool operator()(const TrackingRecHit* rh1, const TrackingRecHit* rh2) {
GlobalPoint gp1 = _tracker.idToDet(rh1->geographicalId())->surface().toGlobal(rh1->localPosition());
GlobalPoint gp2 = _tracker.idToDet(rh2->geographicalId())->surface().toGlobal(rh2->localPosition());
return gp1.y() < gp2.y();
};
private:
// edm::ESHandle<TrackerGeometry> _tracker;
const TrackerGeometry& _tracker;
};
class CompareHitY_plus {
public:
CompareHitY_plus(const TrackerGeometry& tracker) : _tracker(tracker) {}
bool operator()(const TrackingRecHit* rh1, const TrackingRecHit* rh2) {
GlobalPoint gp1 = _tracker.idToDet(rh1->geographicalId())->surface().toGlobal(rh1->localPosition());
GlobalPoint gp2 = _tracker.idToDet(rh2->geographicalId())->surface().toGlobal(rh2->localPosition());
return gp1.y() > gp2.y();
};
private:
// edm::ESHandle<TrackerGeometry> _tracker;
const TrackerGeometry& _tracker;
};
#endif
class CRackTrajectoryBuilder {
// using namespace std;
typedef TrajectoryStateOnSurface TSOS;
typedef TrajectoryMeasurement TM;
typedef std::vector<const TrackingRecHit*>::iterator TrackingRecHitIterator;
typedef std::pair<TrackingRecHitIterator, TrackingRecHitIterator> TrackingRecHitRange;
typedef std::vector<TrackingRecHitRange>::iterator TrackingRecHitRangeIterator;
// typedef std::pair<TrackingRecHitIterator, TSOS> PairTrackingRecHitTsos;
typedef std::pair<TrackingRecHitRangeIterator, TSOS> PairTrackingRecHitTsos;
public:
class CompareDetByTraj;
friend class CompareDetByTraj;
class CompareDetByTraj {
public:
CompareDetByTraj(const TSOS& tSos) : _tSos(tSos){};
bool operator()(const std::pair<TrackingRecHitRangeIterator, TSOS> rh1,
const std::pair<TrackingRecHitRangeIterator, TSOS> rh2) {
GlobalPoint gp1 = rh1.second.globalPosition();
GlobalPoint gp2 = rh2.second.globalPosition();
GlobalPoint gpT = _tSos.globalPosition();
GlobalVector gpDiff1 = gp1 - gpT;
GlobalVector gpDiff2 = gp2 - gpT;
//this might have a better performance ...
// float dist1 = ( gp1.x()-gpT.x() ) * ( gp1.x()-gpT.x() ) + ( gp1.y()-gpT.y() ) * ( gp1.y()-gpT.y() ) + ( gp1.z()-gpT.z() ) * ( gp1.z()-gpT.z() );
// float dist2 = ( gp2.x()-gpT.x() ) * ( gp2.x()-gpT.x() ) + ( gp2.y()-gpT.y() ) * ( gp2.y()-gpT.y() ) + ( gp2.z()-gpT.z() ) * ( gp2.z()-gpT.z() );
//if ( dist1<dist2 )
// if ( gpDiff1.mag2() < gpDiff2.mag2() )
float dist1 = gpDiff1 * _tSos.globalDirection();
float dist2 = gpDiff2 * _tSos.globalDirection();
if (dist1 < 0)
return false;
if (dist1 < dist2)
return true;
return false;
};
private:
const TrajectoryStateOnSurface& _tSos;
};
public:
CRackTrajectoryBuilder(const edm::ParameterSet& conf, edm::ConsumesCollector iC);
~CRackTrajectoryBuilder();
/// Runs the algorithm
void run(const TrajectorySeedCollection& collseed,
const SiStripRecHit2DCollection& collstereo,
const SiStripRecHit2DCollection& collrphi,
const SiStripMatchedRecHit2DCollection& collmatched,
const SiPixelRecHitCollection& collpixel,
const edm::EventSetup& es,
edm::Event& e,
std::vector<Trajectory>& trajoutput);
void init(const edm::EventSetup& es, bool);
Trajectory createStartingTrajectory(const TrajectorySeed& seed) const;
const TransientTrackingRecHitBuilder* hitBuilder() const { return RHBuilder; }
private:
std::vector<TrajectoryMeasurement> seedMeasurements(const TrajectorySeed& seed) const;
std::vector<const TrackingRecHit*> SortHits(const SiStripRecHit2DCollection& collstereo,
const SiStripRecHit2DCollection& collrphi,
const SiStripMatchedRecHit2DCollection& collmatched,
const SiPixelRecHitCollection& collpixel,
const TrajectorySeed& seed,
const bool bAddSeedHits);
// std::vector<TrackingRecHitRange> SortByTrajectory (const std::vector<TrackingRecHitRange>& inputHits);
TSOS startingTSOS(const TrajectorySeed& seed) const;
void updateTrajectory(Trajectory& traj, const TM& tm, const TransientTrackingRecHit& hit) const;
void AddHit(Trajectory& traj, const std::vector<const TrackingRecHit*>& Hits, Propagator* currPropagator);
// edm::OwnVector<TransientTrackingRecHit> hits);
bool qualityFilter(const Trajectory& traj);
bool isDifferentStripReHit2D(const SiStripRecHit2D& hitA, const SiStripRecHit2D& hitB);
std::pair<TrajectoryStateOnSurface, const GeomDet*> innerState(const Trajectory& traj) const;
private:
const edm::ESGetToken<MagneticField, IdealMagneticFieldRecord> magfieldToken_;
const edm::ESGetToken<TrackerGeometry, TrackerDigiGeometryRecord> trackerToken_;
const edm::ESGetToken<TransientTrackingRecHitBuilder, TransientRecHitRecord> builderToken_;
const MagneticField* magfield;
const TrackerGeometry* tracker;
PropagatorWithMaterial* thePropagator;
PropagatorWithMaterial* thePropagatorOp;
// AnalyticalPropagator *thePropagator;
// AnalyticalPropagator *thePropagatorOp;
KFUpdator* theUpdator;
Chi2MeasurementEstimator* theEstimator;
const TransientTrackingRecHitBuilder* RHBuilder;
const KFTrajectorySmoother* theSmoother;
const KFTrajectoryFitter* theFitter;
// const KFTrajectoryFitter * theFitterOp;
bool debug_info;
bool fastPropagation;
bool useMatchedHits;
int theMinHits;
double chi2cut;
std::vector<Trajectory> trajFit;
//RC edm::OwnVector<const TransientTrackingRecHit> hits;
TransientTrackingRecHit::RecHitContainer hits;
bool seed_plus;
std::string geometry;
// TransientInitialStateEstimator* theInitialState;
};
#endif
| 3,690 |
2,863 | # Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Classes representing observables."""
import abc
import functools
from dm_env import specs
import numpy as np
def _make_aggregator(np_reducer_func, bounds_preserving):
result = functools.partial(np_reducer_func, axis=0)
setattr(result, 'bounds_reserving', bounds_preserving)
return result
AGGREGATORS = {
'min': _make_aggregator(np.min, True),
'max': _make_aggregator(np.max, True),
'mean': _make_aggregator(np.mean, True),
'median': _make_aggregator(np.median, True),
'sum': _make_aggregator(np.sum, False),
}
def _get_aggregator(name_or_callable):
"""Returns aggregator from predefined set by name, else returns callable."""
if name_or_callable is None:
return None
elif not callable(name_or_callable):
try:
return AGGREGATORS[name_or_callable]
except KeyError:
raise KeyError('Unrecognized aggregator name: {!r}. Valid names: {}.'
.format(name_or_callable, AGGREGATORS.keys()))
else:
return name_or_callable
class Observable(metaclass=abc.ABCMeta):
"""Abstract base class for an observable."""
def __init__(self, update_interval, buffer_size, delay,
aggregator, corruptor):
self._update_interval = update_interval
self._buffer_size = buffer_size
self._delay = delay
self._aggregator = _get_aggregator(aggregator)
self._corruptor = corruptor
self._enabled = False
@property
def update_interval(self):
return self._update_interval
@update_interval.setter
def update_interval(self, value):
self._update_interval = value
@property
def buffer_size(self):
return self._buffer_size
@buffer_size.setter
def buffer_size(self, value):
self._buffer_size = value
@property
def delay(self):
return self._delay
@delay.setter
def delay(self, value):
self._delay = value
@property
def aggregator(self):
return self._aggregator
@aggregator.setter
def aggregator(self, value):
self._aggregator = _get_aggregator(value)
@property
def corruptor(self):
return self._corruptor
@corruptor.setter
def corruptor(self, value):
self._corruptor = value
@property
def enabled(self):
return self._enabled
@enabled.setter
def enabled(self, value):
self._enabled = value
@property
def array_spec(self):
"""The `ArraySpec` which describes observation arrays from this observable.
If this property is `None`, then the specification should be inferred by
actually retrieving an observation from this observable.
"""
return None
@abc.abstractmethod
def _callable(self, physics):
pass
def observation_callable(self, physics, random_state=None):
"""A callable which returns a (potentially corrupted) observation."""
raw_callable = self._callable(physics)
if self._corruptor:
def _corrupted():
return self._corruptor(raw_callable(), random_state=random_state)
return _corrupted
else:
return raw_callable
def __call__(self, physics, random_state=None):
"""Convenience function to just call an observable."""
return self.observation_callable(physics, random_state)()
def configure(self, **kwargs):
"""Sets multiple attributes of this observable.
Args:
**kwargs: The keyword argument names correspond to the attributes
being modified.
Raises:
AttributeError: If kwargs contained an attribute not in the observable.
"""
for key, value in kwargs.items():
if not hasattr(self, key):
raise AttributeError('Cannot add attribute %s in configure.' % key)
self.__setattr__(key, value)
class Generic(Observable):
"""A generic observable defined via a callable."""
def __init__(self, raw_observation_callable, update_interval=1,
buffer_size=None, delay=None,
aggregator=None, corruptor=None):
"""Initializes this observable.
Args:
raw_observation_callable: A callable which accepts a single argument of
type `control.base.Physics` and returns the observation value.
update_interval: (optional) An integer, number of simulation steps between
successive updates to the value of this observable.
buffer_size: (optional) The maximum size of the returned buffer.
This option is only relevant when used in conjunction with an
`observation.Updater`. If None, `observation.DEFAULT_BUFFER_SIZE` will
be used.
delay: (optional) Number of additional simulation steps that must be
taken before an observation is returned. This option is only relevant
when used in conjunction with an`observation.Updater`. If None,
`observation.DEFAULT_DELAY` will be used.
aggregator: (optional) Name of an item in `AGGREGATORS` or a callable that
performs a reduction operation over the first dimension of the buffered
observation before it is returned. A value of `None` means that no
aggregation will be performed and the whole buffer will be returned.
corruptor: (optional) A callable which takes a single observation as
an argument, modifies it, and returns it. An example use case for this
is to add random noise to the observation. When used in a
`BufferedWrapper`, the corruptor is applied to the observation before
it is added to the buffer. In particular, this means that the aggregator
operates on corrupted observations.
"""
self._raw_callable = raw_observation_callable
super().__init__(update_interval, buffer_size, delay, aggregator, corruptor)
def _callable(self, physics):
return lambda: self._raw_callable(physics)
class MujocoFeature(Observable):
"""An observable corresponding to a named MuJoCo feature."""
def __init__(self, kind, feature_name, update_interval=1,
buffer_size=None, delay=None,
aggregator=None, corruptor=None):
"""Initializes this observable.
Args:
kind: A string corresponding to a field name in MuJoCo's mjData struct.
feature_name: A string, or list of strings, or a callable returning
either, corresponding to the name(s) of an entity in the
MuJoCo XML model.
update_interval: (optional) An integer, number of simulation steps between
successive updates to the value of this observable.
buffer_size: (optional) The maximum size of the returned buffer.
This option is only relevant when used in conjunction with an
`observation.Updater`. If None, `observation.DEFAULT_BUFFER_SIZE` will
be used.
delay: (optional) Number of additional simulation steps that must be
taken before an observation is returned. This option is only relevant
when used in conjunction with an`observation.Updater`. If None,
`observation.DEFAULT_DELAY` will be used.
aggregator: (optional) Name of an item in `AGGREGATORS` or a callable that
performs a reduction operation over the first dimension of the buffered
observation before it is returned. A value of `None` means that no
aggregation will be performed and the whole buffer will be returned.
corruptor: (optional) A callable which takes a single observation as
an argument, modifies it, and returns it. An example use case for this
is to add random noise to the observation. When used in a
`BufferedWrapper`, the corruptor is applied to the observation before
it is added to the buffer. In particular, this means that the aggregator
operates on corrupted observations.
"""
self._kind = kind
self._feature_name = feature_name
super().__init__(update_interval, buffer_size, delay, aggregator, corruptor)
def _callable(self, physics):
named_indexer_for_kind = physics.named.data.__getattribute__(self._kind)
if callable(self._feature_name):
return lambda: named_indexer_for_kind[self._feature_name()]
else:
return lambda: named_indexer_for_kind[self._feature_name]
class MujocoCamera(Observable):
"""An observable corresponding to a MuJoCo camera."""
def __init__(self, camera_name, height=240, width=320, update_interval=1,
buffer_size=None, delay=None,
aggregator=None, corruptor=None, depth=False):
"""Initializes this observable.
Args:
camera_name: A string corresponding to the name of a camera in the
MuJoCo XML model.
height: (optional) An integer, the height of the rendered image.
width: (optional) An integer, the width of the rendered image.
update_interval: (optional) An integer, number of simulation steps between
successive updates to the value of this observable.
buffer_size: (optional) The maximum size of the returned buffer.
This option is only relevant when used in conjunction with an
`observation.Updater`. If None, `observation.DEFAULT_BUFFER_SIZE` will
be used.
delay: (optional) Number of additional simulation steps that must be
taken before an observation is returned. This option is only relevant
when used in conjunction with an`observation.Updater`. If None,
`observation.DEFAULT_DELAY` will be used.
aggregator: (optional) Name of an item in `AGGREGATORS` or a callable that
performs a reduction operation over the first dimension of the buffered
observation before it is returned. A value of `None` means that no
aggregation will be performed and the whole buffer will be returned.
corruptor: (optional) A callable which takes a single observation as
an argument, modifies it, and returns it. An example use case for this
is to add random noise to the observation. When used in a
`BufferedWrapper`, the corruptor is applied to the observation before
it is added to the buffer. In particular, this means that the aggregator
operates on corrupted observations.
depth: (optional) A boolean. If `True`, renders a depth image (1-channel)
instead of RGB (3-channel).
"""
self._camera_name = camera_name
self._height = height
self._width = width
self._n_channels = 1 if depth else 3
self._dtype = np.float32 if depth else np.uint8
self._depth = depth
super().__init__(update_interval, buffer_size, delay, aggregator, corruptor)
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def array_spec(self):
return specs.Array(
shape=(self._height, self._width, self._n_channels), dtype=self._dtype)
def _callable(self, physics):
return lambda: physics.render( # pylint: disable=g-long-lambda
self._height, self._width, self._camera_name, depth=self._depth)
| 3,924 |
7,482 | <gh_stars>1000+
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2015-04-29 ArdaFu first version
*/
#ifndef __HW_TIMER0_H__
#define __HW_TIMER0_H__
////////////////////////////////////////////////////////////////////////////////
#include "stdint.h"
extern void hw_timer0_init(void);
////////////////////////////////////////////////////////////////////////////////
#endif /* __HW_TIMER0_H__ */
| 176 |
1,070 | /*
* Copyright (c) 2014 <NAME> <<EMAIL>>
* Copyright (c) 2014 <NAME> <<EMAIL>>
*
* 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.gnucash.android.ui.util;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.model.Money;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import java.lang.ref.WeakReference;
/**
* An asynchronous task for computing the account balance of an account.
* This is done asynchronously because in cases of deeply nested accounts,
* it can take some time and would block the UI thread otherwise.
*/
public class AccountBalanceTask extends AsyncTask<String, Void, Money> {
public static final String LOG_TAG = AccountBalanceTask.class.getName();
private final WeakReference<TextView> accountBalanceTextViewReference;
private final AccountsDbAdapter accountsDbAdapter;
public AccountBalanceTask(TextView balanceTextView){
accountBalanceTextViewReference = new WeakReference<>(balanceTextView);
accountsDbAdapter = AccountsDbAdapter.getInstance();
}
@Override
protected Money doInBackground(String... params) {
//if the view for which we are doing this job is dead, kill the job as well
if (accountBalanceTextViewReference.get() == null){
cancel(true);
return Money.getZeroInstance();
}
Money balance = Money.getZeroInstance();
try {
balance = accountsDbAdapter.getAccountBalance(params[0], -1, -1);
} catch (Exception ex) {
Log.e(LOG_TAG, "Error computing account balance ", ex);
Crashlytics.logException(ex);
}
return balance;
}
@Override
protected void onPostExecute(Money balance) {
if (accountBalanceTextViewReference.get() != null && balance != null){
final TextView balanceTextView = accountBalanceTextViewReference.get();
if (balanceTextView != null){
TransactionsActivity.displayBalance(balanceTextView, balance);
}
}
}
}
| 891 |
652 | <filename>src/version.h
#pragma once
#define REDISAI_VERSION_MAJOR 99
#define REDISAI_VERSION_MINOR 99
#define REDISAI_VERSION_PATCH 99
#define REDISAI_MODULE_VERSION \
(REDISAI_VERSION_MAJOR * 10000 + REDISAI_VERSION_MINOR * 100 + REDISAI_VERSION_PATCH)
/* API versions. */
#define REDISAI_LLAPI_VERSION 1
static const long long REDISAI_ENC_VER = 4;
| 206 |
592 | /*
* Copyright 2016 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.gradle.python.tasks;
import com.linkedin.gradle.python.extension.PythonDetails;
import com.linkedin.gradle.python.tasks.action.ProbeVenvInfoAction;
import com.linkedin.gradle.python.tasks.provides.ProvidesVenv;
import com.linkedin.gradle.python.wheel.EditablePythonAbiContainer;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
/**
* Get supported wheel tags from previously probed virtual environment.
*
* <p>When virtual environment creation task is up-to-date,
* then ABI container does not get populated, remains empty, and
* no cached wheels can match any tags. This task ensures that
* the container does get populated, regardless of virtual environment
* creation task outcome.</p>
*/
public class GetProbedTagsTask extends DefaultTask implements ProvidesVenv {
private PythonDetails pythonDetails;
private EditablePythonAbiContainer editablePythonAbiContainer;
@TaskAction
public void getProbedTags() {
ProbeVenvInfoAction.getProbedTags(getProject(), pythonDetails, editablePythonAbiContainer);
}
@Override
public void setEditablePythonAbiContainer(EditablePythonAbiContainer editablePythonAbiContainer) {
this.editablePythonAbiContainer = editablePythonAbiContainer;
}
public PythonDetails getPythonDetails() {
return pythonDetails;
}
public void setPythonDetails(PythonDetails pythonDetails) {
this.pythonDetails = pythonDetails;
}
}
| 599 |
775 | <filename>run_pe/src/pe_hdrs_helper.cpp
#include "pe_hdrs_helper.h"
IMAGE_NT_HEADERS32* get_nt_hrds32(BYTE *pe_buffer)
{
if (pe_buffer == NULL) return NULL;
IMAGE_DOS_HEADER *idh = (IMAGE_DOS_HEADER*)pe_buffer;
if (idh->e_magic != IMAGE_DOS_SIGNATURE) {
return NULL;
}
const LONG kMaxOffset = 1024;
LONG pe_offset = idh->e_lfanew;
if (pe_offset > kMaxOffset) return NULL;
IMAGE_NT_HEADERS32 *inh = (IMAGE_NT_HEADERS32 *)((BYTE*)pe_buffer + pe_offset);
return inh;
}
IMAGE_DATA_DIRECTORY* get_pe_directory32(PVOID pe_buffer, DWORD dir_id)
{
if (dir_id >= IMAGE_NUMBEROF_DIRECTORY_ENTRIES) return NULL;
//fetch relocation table from current image:
PIMAGE_NT_HEADERS32 nt_headers = get_nt_hrds32((BYTE*) pe_buffer);
if (nt_headers == NULL) return NULL;
IMAGE_DATA_DIRECTORY* peDir = &(nt_headers->OptionalHeader.DataDirectory[dir_id]);
if (peDir->VirtualAddress == NULL) {
return NULL;
}
return peDir;
}
| 434 |
2,329 | package invokevirtual;
public class ZZ extends YY {
}
| 18 |
1,253 | /**
* Created by aubdira on 10/30/17.
* BogoSort is an ineffective sorting algorithm. The algorithm
* generates permutations of its input until it finds one that is sorted.
*/
public class BogoSort {
public static void main(String[] args) {
//Enter array to be sorted here
int[] arr = {12, 43, 5, -5, 0, 13};
BogoSort now = new BogoSort();
System.out.print("Unsorted: ");
now.printArray(arr);
now.bogo(arr);
System.out.print("Sorted: ");
now.printArray(arr);
}
private void bogo(int[] arr) {
while (!isSorted(arr)) {
shuffle(arr);
}
}
/**
* Use Fisher-Yates shuffle algorithm to shuffle the array
*
* @param arr input array
*/
private void shuffle(int[] arr) {
int i = arr.length - 1;
while (i > 0) {
swap(arr, i--, (int) (Math.random() * i));
}
}
private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private boolean isSorted(int[] arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) {
return false;
}
}
return true;
}
private void printArray(int[] arr) {
for (int anArr : arr) {
System.out.print(anArr + " ");
}
System.out.println();
}
}
| 693 |
622 | <reponame>Sam-Gao-Xin/Courses-
# -*- coding: utf-8 -*-
"""
@author: salimt
"""
def is_palindrome_v1(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v1('noon')
True
>>> is_palindrome_v1('racecar')
True
>>> is_palindrome_v1('dented')
False
"""
return s[:] == s[::-1]
#print(is_palindrome_v1('racecar'), is_palindrome_v1('dented'))
def is_palindrome_v2(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v1('noon')
True
>>> is_palindrome_v1('racecar')
True
>>> is_palindrome_v1('dented')
False
"""
n = len(s)
return s[:n//2] == s[n-1:n-n//2-1:-1]
#print(is_palindrome_v2('racecar'), is_palindrome_v2('dented'))
def is_palindrome_v3(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v1('noon')
True
>>> is_palindrome_v1('racecar')
True
>>> is_palindrome_v1('dented')
False
"""
counter = 0
for ch in range(len(s)):
if s[ch] == s[-ch-1]:
counter += 1
return counter == len(s)
#i = 0
#j = len(s) - 1
# while i < j and s[i] == s[j]:
# i += 1
# j -= 1
# return j <= i
#print(is_palindrome_v3('racecar'), is_palindrome_v3('dented')) | 755 |
5,079 | print "*** test_pak imported"
state = []
def setup():
# print "SETUP CALLED", state, id(state)
state.append('test_pak.setup')
def teardown():
# print "TEARDOWN CALLED", state, id(state)
state.append('test_pak.teardown')
| 92 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-535g-qhh4-m728",
"modified": "2022-05-13T01:11:13Z",
"published": "2022-05-13T01:11:13Z",
"aliases": [
"CVE-2019-6504"
],
"details": "Insufficient output sanitization in the Automic Web Interface (AWI), in CA Automic Workload Automation 12.0 to 12.2, allow attackers to potentially conduct persistent cross site scripting (XSS) attacks via a crafted object.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2019-6504"
},
{
"type": "WEB",
"url": "https://communities.ca.com/community/product-vulnerability-response/blog/2019/01/24/ca20190124-01-security-notice-for-ca-automic-workload-automation"
},
{
"type": "WEB",
"url": "https://marc.info/?l=bugtraq&m=154874504200510&w=2"
},
{
"type": "WEB",
"url": "https://packetstormsecurity.com/files/151325/CA-Automic-Workload-Automation-12.x-Cross-Site-Scripting.html"
},
{
"type": "WEB",
"url": "https://sec-consult.com/en/blog/advisories/cross-site-scripting-in-ca-automic-workload-automation-web-interface-formerly-automic-automation-engine/"
},
{
"type": "WEB",
"url": "https://seclists.org/fulldisclosure/2019/Jan/61"
},
{
"type": "WEB",
"url": "https://support.ca.com/us/product-content/recommended-reading/security-notices/CA20190124-01-security-notice-for-ca-automic-workload-automation.html"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/106755"
}
],
"database_specific": {
"cwe_ids": [
"CWE-79"
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 862 |
3,200 | <gh_stars>1000+
/**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include "utils/ms_utils.h"
#include "gtest/gtest.h"
#include "utils/log_adapter.h"
#include "minddata/mindrecord/include/shard_segment.h"
#include "ut_common.h"
using mindspore::LogStream;
using mindspore::ExceptionType::NoExceptionType;
using mindspore::MsLogLevel::INFO;
namespace mindspore {
namespace mindrecord {
class TestShardSegment : public UT::Common {
public:
TestShardSegment() {}
void SetUp() override { ShardWriterImageNet(); }
void TearDown() override {
for (int i = 1; i <= 4; i++) {
string filename = std::string("./imagenet.shard0") + std::to_string(i);
string db_name = std::string("./imagenet.shard0") + std::to_string(i) + ".db";
remove(common::SafeCStr(filename));
remove(common::SafeCStr(db_name));
}
}
};
TEST_F(TestShardSegment, TestShardSegment) {
MS_LOG(INFO) << FormatInfo("Test Shard Segment");
std::string file_name = "./imagenet.shard01";
ShardSegment dataset;
dataset.Open({file_name}, true, 4);
auto fields_ptr = std::make_shared<vector<std::string>>();
auto status = dataset.GetCategoryFields(&fields_ptr);
for (const auto &fields : *fields_ptr) {
MS_LOG(INFO) << "Get category field: " << fields;
}
status = dataset.SetCategoryField("label");
EXPECT_TRUE(status.IsOk());
status = dataset.SetCategoryField("laabel_0");
EXPECT_FALSE(status.IsOk());
std::shared_ptr<std::string> category_ptr;
status = dataset.ReadCategoryInfo(&category_ptr);
EXPECT_TRUE(status.IsOk());
MS_LOG(INFO) << "Read category info: " << *category_ptr;
auto pages_ptr = std::make_shared<std::vector<std::vector<uint8_t>>>();
status = dataset.ReadAtPageByName("822", 0, 10, &pages_ptr);
EXPECT_TRUE(status.IsOk());
MS_LOG(INFO) << "category field: 822, images count: " << pages_ptr->size() << ", image[0] size: " << ((*pages_ptr)[0]).size();
auto pages_ptr_1 = std::make_shared<std::vector<std::vector<uint8_t>>>();
status = dataset.ReadAtPageByName("823", 0, 10, &pages_ptr_1);
MS_LOG(INFO) << "category field: 823, images count: " << pages_ptr_1->size();
auto pages_ptr_2 = std::make_shared<std::vector<std::vector<uint8_t>>>();
status = dataset.ReadAtPageById(1, 0, 10, &pages_ptr_2);
EXPECT_TRUE(status.IsOk());
MS_LOG(INFO) << "category id: 1, images count: " << pages_ptr_2->size() << ", image[0] size: " << ((*pages_ptr_2)[0]).size();
auto pages_ptr_3 = std::make_shared<PAGES>();
status = dataset.ReadAllAtPageByName("822", 0, 10, &pages_ptr_3);
MS_LOG(INFO) << "category field: 822, images count: " << pages_ptr_3->size();
auto pages_ptr_4 = std::make_shared<PAGES>();
status = dataset.ReadAllAtPageById(1, 0, 10, &pages_ptr_4);
MS_LOG(INFO) << "category id: 1, images count: " << pages_ptr_4->size();
}
TEST_F(TestShardSegment, TestReadAtPageByNameOfCategoryName) {
MS_LOG(INFO) << FormatInfo("Test ReadAtPageByName of error category_name and category_field");
std::string file_name = "./imagenet.shard01";
ShardSegment dataset;
dataset.Open({file_name}, true, 4);
auto fields_ptr = std::make_shared<vector<std::string>>();
auto status = dataset.GetCategoryFields(&fields_ptr);
for (const auto &fields : *fields_ptr) {
MS_LOG(INFO) << "Get category field: " << fields;
}
string category_name = "82Cus";
string category_field = "laabel_0";
status = dataset.SetCategoryField("label");
EXPECT_TRUE(status.IsOk());
status = dataset.SetCategoryField(category_field);
EXPECT_FALSE(status.IsOk());
std::shared_ptr<std::string> category_ptr;
status = dataset.ReadCategoryInfo(&category_ptr);
EXPECT_TRUE(status.IsOk());
MS_LOG(INFO) << "Read category info: " << *category_ptr;
auto pages_ptr = std::make_shared<std::vector<std::vector<uint8_t>>>();
status = dataset.ReadAtPageByName(category_name, 0, 10, &pages_ptr);
EXPECT_FALSE(status.IsOk());
}
TEST_F(TestShardSegment, TestReadAtPageByIdOfCategoryId) {
MS_LOG(INFO) << FormatInfo("Test ReadAtPageById of error categoryId");
std::string file_name = "./imagenet.shard01";
ShardSegment dataset;
dataset.Open({file_name}, true, 4);
auto fields_ptr = std::make_shared<vector<std::string>>();
auto status = dataset.GetCategoryFields(&fields_ptr);
for (const auto &fields : *fields_ptr) {
MS_LOG(INFO) << "Get category field: " << fields;
}
int64_t categoryId = 2251799813685247;
MS_LOG(INFO) << "Input category id: " << categoryId;
status = dataset.SetCategoryField("label");
EXPECT_TRUE(status.IsOk());
std::shared_ptr<std::string> category_ptr;
status = dataset.ReadCategoryInfo(&category_ptr);
EXPECT_TRUE(status.IsOk());
MS_LOG(INFO) << "Read category info: " << *category_ptr;
auto pages_ptr = std::make_shared<std::vector<std::vector<uint8_t>>>();
status = dataset.ReadAtPageById(categoryId, 0, 10, &pages_ptr);
EXPECT_FALSE(status.IsOk());
}
TEST_F(TestShardSegment, TestReadAtPageByIdOfPageNo) {
MS_LOG(INFO) << FormatInfo("Test ReadAtPageById of error page_no");
std::string file_name = "./imagenet.shard01";
ShardSegment dataset;
dataset.Open({file_name}, true, 4);
auto fields_ptr = std::make_shared<vector<std::string>>();
auto status = dataset.GetCategoryFields(&fields_ptr);
for (const auto &fields : *fields_ptr) {
MS_LOG(INFO) << "Get category field: " << fields;
}
int64_t page_no = 2251799813685247;
MS_LOG(INFO) << "Input page no: " << page_no;
status = dataset.SetCategoryField("label");
EXPECT_TRUE(status.IsOk());
std::shared_ptr<std::string> category_ptr;
status = dataset.ReadCategoryInfo(&category_ptr);
EXPECT_TRUE(status.IsOk());
MS_LOG(INFO) << "Read category info: " << *category_ptr;
auto pages_ptr = std::make_shared<std::vector<std::vector<uint8_t>>>();
status = dataset.ReadAtPageById(1, page_no, 10, &pages_ptr);
EXPECT_FALSE(status.IsOk());
}
TEST_F(TestShardSegment, TestReadAtPageByIdOfPageRows) {
MS_LOG(INFO) << FormatInfo("Test ReadAtPageById of error pageRows");
std::string file_name = "./imagenet.shard01";
ShardSegment dataset;
dataset.Open({file_name}, true, 4);
auto fields_ptr = std::make_shared<vector<std::string>>();
auto status = dataset.GetCategoryFields(&fields_ptr);
for (const auto &fields : *fields_ptr) {
MS_LOG(INFO) << "Get category field: " << fields;
}
int64_t pageRows = 0;
MS_LOG(INFO) << "Input page rows: " << pageRows;
status = dataset.SetCategoryField("label");
EXPECT_TRUE(status.IsOk());
std::shared_ptr<std::string> category_ptr;
status = dataset.ReadCategoryInfo(&category_ptr);
EXPECT_TRUE(status.IsOk());
MS_LOG(INFO) << "Read category info: " << *category_ptr;
auto pages_ptr = std::make_shared<std::vector<std::vector<uint8_t>>>();
status = dataset.ReadAtPageById(1, 0, pageRows, &pages_ptr);
EXPECT_FALSE(status.IsOk());
}
} // namespace mindrecord
} // namespace mindspore
| 2,716 |
14,668 | <reponame>zealoussnow/chromium
// 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 "media/base/supported_types.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_ANDROID)
#include "base/android/build_info.h"
#endif
namespace media {
#if BUILDFLAG(USE_PROPRIETARY_CODECS)
const bool kPropCodecsEnabled = true;
#else
const bool kPropCodecsEnabled = false;
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH) && BUILDFLAG(USE_PROPRIETARY_CODECS)
const bool kMpeg4Supported = true;
#else
const bool kMpeg4Supported = false;
#endif
TEST(SupportedTypesTest, IsSupportedVideoTypeBasics) {
// Default to common 709.
const VideoColorSpace kColorSpace = VideoColorSpace::REC709();
// Some codecs do not have a notion of level.
const int kUnspecifiedLevel = 0;
// Expect support for baseline configuration of known codecs.
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP8, VP8PROFILE_ANY, kUnspecifiedLevel, kColorSpace}));
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP9, VP9PROFILE_PROFILE0, kUnspecifiedLevel, kColorSpace}));
EXPECT_TRUE(
IsSupportedVideoType({VideoCodec::kTheora, VIDEO_CODEC_PROFILE_UNKNOWN,
kUnspecifiedLevel, kColorSpace}));
// Expect non-support for the following.
EXPECT_FALSE(
IsSupportedVideoType({VideoCodec::kUnknown, VIDEO_CODEC_PROFILE_UNKNOWN,
kUnspecifiedLevel, kColorSpace}));
EXPECT_FALSE(
IsSupportedVideoType({VideoCodec::kVC1, VIDEO_CODEC_PROFILE_UNKNOWN,
kUnspecifiedLevel, kColorSpace}));
EXPECT_FALSE(
IsSupportedVideoType({VideoCodec::kMPEG2, VIDEO_CODEC_PROFILE_UNKNOWN,
kUnspecifiedLevel, kColorSpace}));
EXPECT_FALSE(
IsSupportedVideoType({VideoCodec::kHEVC, VIDEO_CODEC_PROFILE_UNKNOWN,
kUnspecifiedLevel, kColorSpace}));
// Expect conditional support for the following.
EXPECT_EQ(kPropCodecsEnabled,
IsSupportedVideoType(
{VideoCodec::kH264, H264PROFILE_BASELINE, 1, kColorSpace}));
EXPECT_EQ(
kMpeg4Supported,
IsSupportedVideoType({VideoCodec::kMPEG4, VIDEO_CODEC_PROFILE_UNKNOWN,
kUnspecifiedLevel, kColorSpace}));
}
TEST(SupportedTypesTest, IsSupportedVideoType_VP9TransferFunctions) {
size_t num_found = 0;
// TODO(hubbe): Verify support for HDR codecs when color management enabled.
const std::set<VideoColorSpace::TransferID> kSupportedTransfers = {
VideoColorSpace::TransferID::GAMMA22,
VideoColorSpace::TransferID::UNSPECIFIED,
VideoColorSpace::TransferID::BT709,
VideoColorSpace::TransferID::SMPTE170M,
VideoColorSpace::TransferID::BT2020_10,
VideoColorSpace::TransferID::BT2020_12,
VideoColorSpace::TransferID::IEC61966_2_1,
VideoColorSpace::TransferID::GAMMA28,
VideoColorSpace::TransferID::SMPTE240M,
VideoColorSpace::TransferID::LINEAR,
VideoColorSpace::TransferID::LOG,
VideoColorSpace::TransferID::LOG_SQRT,
VideoColorSpace::TransferID::BT1361_ECG,
VideoColorSpace::TransferID::SMPTEST2084,
VideoColorSpace::TransferID::IEC61966_2_4,
VideoColorSpace::TransferID::SMPTEST428_1,
VideoColorSpace::TransferID::ARIB_STD_B67,
};
for (int i = 0; i <= (1 << (8 * sizeof(VideoColorSpace::TransferID))); i++) {
VideoColorSpace color_space = VideoColorSpace::REC709();
color_space.transfer = VideoColorSpace::GetTransferID(i);
bool found = kSupportedTransfers.find(color_space.transfer) !=
kSupportedTransfers.end();
if (found)
num_found++;
EXPECT_EQ(found,
IsSupportedVideoType(
{VideoCodec::kVP9, VP9PROFILE_PROFILE0, 1, color_space}));
}
EXPECT_EQ(kSupportedTransfers.size(), num_found);
}
TEST(SupportedTypesTest, IsSupportedVideoType_VP9Primaries) {
size_t num_found = 0;
// TODO(hubbe): Verify support for HDR codecs when color management enabled.
const std::set<VideoColorSpace::PrimaryID> kSupportedPrimaries = {
VideoColorSpace::PrimaryID::BT709,
VideoColorSpace::PrimaryID::UNSPECIFIED,
VideoColorSpace::PrimaryID::BT470M,
VideoColorSpace::PrimaryID::BT470BG,
VideoColorSpace::PrimaryID::SMPTE170M,
VideoColorSpace::PrimaryID::SMPTE240M,
VideoColorSpace::PrimaryID::FILM,
VideoColorSpace::PrimaryID::BT2020,
VideoColorSpace::PrimaryID::SMPTEST428_1,
VideoColorSpace::PrimaryID::SMPTEST431_2,
VideoColorSpace::PrimaryID::SMPTEST432_1,
};
for (int i = 0; i <= (1 << (8 * sizeof(VideoColorSpace::PrimaryID))); i++) {
VideoColorSpace color_space = VideoColorSpace::REC709();
color_space.primaries = VideoColorSpace::GetPrimaryID(i);
bool found = kSupportedPrimaries.find(color_space.primaries) !=
kSupportedPrimaries.end();
if (found)
num_found++;
EXPECT_EQ(found,
IsSupportedVideoType(
{VideoCodec::kVP9, VP9PROFILE_PROFILE0, 1, color_space}));
}
EXPECT_EQ(kSupportedPrimaries.size(), num_found);
}
TEST(SupportedTypesTest, IsSupportedVideoType_VP9Matrix) {
size_t num_found = 0;
// TODO(hubbe): Verify support for HDR codecs when color management enabled.
const std::set<VideoColorSpace::MatrixID> kSupportedMatrix = {
VideoColorSpace::MatrixID::BT709,
VideoColorSpace::MatrixID::UNSPECIFIED,
VideoColorSpace::MatrixID::BT470BG,
VideoColorSpace::MatrixID::SMPTE170M,
VideoColorSpace::MatrixID::BT2020_NCL,
VideoColorSpace::MatrixID::RGB,
VideoColorSpace::MatrixID::FCC,
VideoColorSpace::MatrixID::SMPTE240M,
VideoColorSpace::MatrixID::YCOCG,
VideoColorSpace::MatrixID::YDZDX,
VideoColorSpace::MatrixID::BT2020_CL,
};
for (int i = 0; i <= (1 << (8 * sizeof(VideoColorSpace::MatrixID))); i++) {
VideoColorSpace color_space = VideoColorSpace::REC709();
color_space.matrix = VideoColorSpace::GetMatrixID(i);
bool found =
kSupportedMatrix.find(color_space.matrix) != kSupportedMatrix.end();
if (found)
num_found++;
EXPECT_EQ(found,
IsSupportedVideoType(
{VideoCodec::kVP9, VP9PROFILE_PROFILE0, 1, color_space}));
}
EXPECT_EQ(kSupportedMatrix.size(), num_found);
}
TEST(SupportedTypesTest, IsSupportedVideoType_VP9Profiles) {
// Default to common 709.
const VideoColorSpace kColorSpace = VideoColorSpace::REC709();
// Some codecs do not have a notion of level.
const int kUnspecifiedLevel = 0;
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP9, VP9PROFILE_PROFILE0, kUnspecifiedLevel, kColorSpace}));
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP9, VP9PROFILE_PROFILE1, kUnspecifiedLevel, kColorSpace}));
// VP9 Profile2 are supported on x86, ChromeOS on ARM and Mac/Win on ARM64.
// See third_party/libvpx/BUILD.gn.
#if defined(ARCH_CPU_X86_FAMILY) || \
(defined(ARCH_CPU_ARM_FAMILY) && BUILDFLAG(IS_CHROMEOS_ASH)) || \
(defined(ARCH_CPU_ARM64) && (defined(OS_MAC) || defined(OS_WIN)))
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP9, VP9PROFILE_PROFILE2, kUnspecifiedLevel, kColorSpace}));
#endif
}
TEST(SupportedTypesTest, IsSupportedAudioTypeWithSpatialRenderingBasics) {
const bool is_spatial_rendering = true;
// Dolby Atmos = E-AC3 (Dolby Digital Plus) + spatialRendering. Currently not
// supported.
EXPECT_FALSE(IsSupportedAudioType(
{AudioCodec::kEAC3, AudioCodecProfile::kUnknown, is_spatial_rendering}));
// Expect non-support for codecs with which there is no spatial audio format.
EXPECT_FALSE(IsSupportedAudioType(
{AudioCodec::kAAC, AudioCodecProfile::kUnknown, is_spatial_rendering}));
EXPECT_FALSE(IsSupportedAudioType(
{AudioCodec::kMP3, AudioCodecProfile::kUnknown, is_spatial_rendering}));
EXPECT_FALSE(IsSupportedAudioType(
{AudioCodec::kPCM, AudioCodecProfile::kUnknown, is_spatial_rendering}));
EXPECT_FALSE(
IsSupportedAudioType({AudioCodec::kVorbis, AudioCodecProfile::kUnknown,
is_spatial_rendering}));
EXPECT_FALSE(IsSupportedAudioType(
{AudioCodec::kFLAC, AudioCodecProfile::kUnknown, is_spatial_rendering}));
EXPECT_FALSE(
IsSupportedAudioType({AudioCodec::kAMR_NB, AudioCodecProfile::kUnknown,
is_spatial_rendering}));
EXPECT_FALSE(
IsSupportedAudioType({AudioCodec::kAMR_WB, AudioCodecProfile::kUnknown,
is_spatial_rendering}));
EXPECT_FALSE(
IsSupportedAudioType({AudioCodec::kPCM_MULAW, AudioCodecProfile::kUnknown,
is_spatial_rendering}));
EXPECT_FALSE(
IsSupportedAudioType({AudioCodec::kGSM_MS, AudioCodecProfile::kUnknown,
is_spatial_rendering}));
EXPECT_FALSE(
IsSupportedAudioType({AudioCodec::kPCM_S16BE, AudioCodecProfile::kUnknown,
is_spatial_rendering}));
EXPECT_FALSE(
IsSupportedAudioType({AudioCodec::kPCM_S24BE, AudioCodecProfile::kUnknown,
is_spatial_rendering}));
EXPECT_FALSE(IsSupportedAudioType(
{AudioCodec::kOpus, AudioCodecProfile::kUnknown, is_spatial_rendering}));
EXPECT_FALSE(
IsSupportedAudioType({AudioCodec::kPCM_ALAW, AudioCodecProfile::kUnknown,
is_spatial_rendering}));
EXPECT_FALSE(IsSupportedAudioType(
{AudioCodec::kALAC, AudioCodecProfile::kUnknown, is_spatial_rendering}));
EXPECT_FALSE(IsSupportedAudioType(
{AudioCodec::kAC3, AudioCodecProfile::kUnknown, is_spatial_rendering}));
EXPECT_FALSE(IsSupportedAudioType({AudioCodec::kMpegHAudio,
AudioCodecProfile::kUnknown,
is_spatial_rendering}));
EXPECT_FALSE(
IsSupportedAudioType({AudioCodec::kUnknown, AudioCodecProfile::kUnknown,
is_spatial_rendering}));
}
TEST(SupportedTypesTest, XHE_AACSupportedOnAndroidOnly) {
// TODO(dalecurtis): Update this test if we ever have support elsewhere.
#if defined(OS_ANDROID)
const bool is_supported =
kPropCodecsEnabled &&
base::android::BuildInfo::GetInstance()->sdk_int() >=
base::android::SDK_VERSION_P;
EXPECT_EQ(is_supported,
IsSupportedAudioType(
{AudioCodec::kAAC, AudioCodecProfile::kXHE_AAC, false}));
#else
EXPECT_FALSE(IsSupportedAudioType(
{AudioCodec::kAAC, AudioCodecProfile::kXHE_AAC, false}));
#endif
}
TEST(SupportedTypesTest, IsSupportedVideoTypeWithHdrMetadataBasics) {
// Default to common 709.
VideoColorSpace color_space = VideoColorSpace::REC709();
// Some codecs do not have a notion of level.
const int kUnspecifiedLevel = 0;
// Expect support for baseline configuration of known codecs.
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP8, VP8PROFILE_ANY, kUnspecifiedLevel, color_space}));
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP9, VP9PROFILE_PROFILE0, kUnspecifiedLevel, color_space}));
EXPECT_TRUE(
IsSupportedVideoType({VideoCodec::kTheora, VIDEO_CODEC_PROFILE_UNKNOWN,
kUnspecifiedLevel, color_space}));
// All combinations of combinations of color gamuts and transfer functions
// should be supported.
color_space.primaries = VideoColorSpace::PrimaryID::SMPTEST431_2;
color_space.transfer = VideoColorSpace::TransferID::SMPTEST2084;
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP8, VP8PROFILE_ANY, kUnspecifiedLevel, color_space}));
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP9, VP9PROFILE_PROFILE0, kUnspecifiedLevel, color_space}));
EXPECT_TRUE(
IsSupportedVideoType({VideoCodec::kTheora, VIDEO_CODEC_PROFILE_UNKNOWN,
kUnspecifiedLevel, color_space}));
color_space.primaries = VideoColorSpace::PrimaryID::BT2020;
color_space.transfer = VideoColorSpace::TransferID::ARIB_STD_B67;
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP8, VP8PROFILE_ANY, kUnspecifiedLevel, color_space}));
EXPECT_TRUE(IsSupportedVideoType(
{VideoCodec::kVP9, VP9PROFILE_PROFILE0, kUnspecifiedLevel, color_space}));
EXPECT_TRUE(
IsSupportedVideoType({VideoCodec::kTheora, VIDEO_CODEC_PROFILE_UNKNOWN,
kUnspecifiedLevel, color_space}));
// No HDR metadata types are supported.
EXPECT_FALSE(
IsSupportedVideoType({VideoCodec::kVP8, VP8PROFILE_ANY, kUnspecifiedLevel,
color_space, gfx::HdrMetadataType::kSmpteSt2086}));
EXPECT_FALSE(IsSupportedVideoType({VideoCodec::kVP8, VP8PROFILE_ANY,
kUnspecifiedLevel, color_space,
gfx::HdrMetadataType::kSmpteSt2094_10}));
EXPECT_FALSE(IsSupportedVideoType({VideoCodec::kVP8, VP8PROFILE_ANY,
kUnspecifiedLevel, color_space,
gfx::HdrMetadataType::kSmpteSt2094_40}));
}
} // namespace media
| 5,532 |
1,644 | <gh_stars>1000+
// Copyright 2019 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject;
import google.registry.model.replay.EntityTest.EntityForTesting;
import google.registry.persistence.transaction.JpaTestExtensions;
import google.registry.persistence.transaction.JpaTestExtensions.JpaUnitTestExtension;
import google.registry.testing.FakeClock;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.joda.time.DateTime;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link CreateAutoTimestampConverter}. */
public class CreateAutoTimestampConverterTest {
private final FakeClock fakeClock = new FakeClock();
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestExtensions.Builder()
.withClock(fakeClock)
.withEntityClass(TestEntity.class)
.buildUnitTestExtension();
@Test
void testTypeConversion() {
CreateAutoTimestamp ts = CreateAutoTimestamp.create(DateTime.parse("2019-09-9T11:39:00Z"));
TestEntity ent = new TestEntity("myinst", ts);
insertInDb(ent);
TestEntity result =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "myinst"));
assertThat(result).isEqualTo(new TestEntity("myinst", ts));
}
@Test
void testAutoInitialization() {
CreateAutoTimestamp ts = CreateAutoTimestamp.create(null);
TestEntity ent = new TestEntity("autoinit", ts);
insertInDb(ent);
TestEntity result =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "autoinit"));
assertThat(result.cat.getTimestamp()).isEqualTo(fakeClock.nowUtc());
}
@Entity(name = "TestEntity") // Override entity name to avoid the nested class reference.
@EntityForTesting
public static class TestEntity extends ImmutableObject {
@Id String name;
CreateAutoTimestamp cat;
public TestEntity() {}
TestEntity(String name, CreateAutoTimestamp cat) {
this.name = name;
this.cat = cat;
}
}
}
| 944 |
852 | import FWCore.ParameterSet.Config as cms
from Configuration.EventContent.EventContent_cff import *
from JetMETAnalysis.METSkims.sumET_EventContent_cff import *
FEVTSIMSumETEventContent = cms.PSet(
outputCommands = cms.untracked.vstring()
)
FEVTSIMSumETEventContent.outputCommands.extend(FEVTSIMEventContent.outputCommands)
FEVTSIMSumETEventContent.outputCommands.extend(sumETEventContent.outputCommands)
| 137 |
716 | /*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
/* clang-format off */
/* srand3f.c - Implements LIB3F srand subprogram. */
#include <stdlib.h>
#include "ent3f.h"
/* srand48 is not currently available on win64 */
#if defined(WIN64) || defined(WIN32)
void ENT3F(SRAND1, srand1)(int *iseed) { srand(*iseed); }
void ENT3F(SRAND2, srand2)(float *rseed)
{
int iseed;
iseed = (int)(*rseed);
srand(iseed);
}
#else
void ENT3F(SRAND, srand)(int *iseed) { srand48(*iseed); }
#endif
| 263 |
850 | <filename>centaur/src/main/resources/standardTestCases/standard_output_paths_colliding_prevented/options.json
{
"final_workflow_outputs_dir": "/tmp/outputs/standard_output_paths_colliding_prevented",
"use_relative_output_paths": false,
"read_from_cache": false
}
| 96 |
619 | /*
* Author: <NAME> <<EMAIL>>
* Author: <NAME> (@deadprogram)
* Author: <NAME> (@JustInDevelopment)
* Copyright (c) 2016 Intel Corporation.
*
* This program and the accompanying materials are made available under the
* terms of the The MIT License which is available at
* https://opensource.org/licenses/MIT.
*
* SPDX-License-Identifier: MIT
*/
#include <iostream>
#include <string>
#include <string.h>
#include <stdexcept>
#include <unistd.h>
#include <stdlib.h>
#include "curieimu.hpp"
using namespace upm;
static CurieImu* awaitingReponse;
CurieImu::CurieImu (int subplatformoffset)
{
m_firmata = mraa_firmata_init(FIRMATA_CURIE_IMU);
if (m_firmata == NULL) {
throw std::invalid_argument(std::string(__FUNCTION__) +
": mraa_firmata_init() failed");
return;
}
if (pthread_mutex_init(&m_responseLock, NULL)) {
throw std::runtime_error(std::string(__FUNCTION__) +
": pthread_mutex_init(m_responseLock) failed");
return;
}
if (pthread_cond_init(&m_responseCond, NULL)) {
throw std::runtime_error(std::string(__FUNCTION__) +
": pthread_cond_init(m_responseCond) failed");
return;
}
}
CurieImu::~CurieImu()
{
pthread_mutex_destroy(&m_responseLock);
pthread_cond_destroy(&m_responseCond);
}
void
CurieImu::lock()
{
pthread_mutex_lock(&m_responseLock);
}
void
CurieImu::unlock()
{
pthread_mutex_unlock(&m_responseLock);
}
void
CurieImu::waitForResponse()
{
awaitingReponse = this;
pthread_cond_wait(&m_responseCond, &m_responseLock);
}
void
CurieImu::proceed()
{
pthread_cond_broadcast(&m_responseCond);
}
void
CurieImu::setResults(uint8_t* buf, int length)
{
m_results = new char(length);
memcpy((void*)m_results, (void*)buf, length);
}
/*
* Handles a single syncronous response being returned from Firmata
*
* @param buffer the data beinig returned from Firmata
* @param length length of results buffer
*/
static void
handleSyncResponse(uint8_t* buf, int length)
{
awaitingReponse->setResults(buf, length);
awaitingReponse->proceed();
}
/*
* Handles asyncronous responses being returned from Firmata
*
* @param buffer the data beinig returned from Firmata
* @param length length of results buffer
*/
static void
handleAsyncResponses(uint8_t* buf, int length)
{
awaitingReponse->setResults(buf, length);
awaitingReponse->processResponse();
}
void
CurieImu::processResponse()
{
switch(m_results[2]) {
case FIRMATA_CURIE_IMU_SHOCK_DETECT:
{
IMUDataItem* item = new IMUDataItem();
item->axis = m_results[3];
item->direction = m_results[4];
m_shockData.push(item);
break;
}
case FIRMATA_CURIE_IMU_STEP_COUNTER:
{
int count = ((m_results[3] & 0x7f) | ((m_results[4] & 0x7f) << 7));
m_stepData.push(count);
break;
}
case FIRMATA_CURIE_IMU_TAP_DETECT:
{
IMUDataItem* item = new IMUDataItem();
item->axis = m_results[3];
item->direction = m_results[4];
m_tapData.push(item);
break;
}
}
return;
}
int16_t*
CurieImu::getAccel()
{
return &m_accel[0];
}
int16_t
CurieImu::getAccelX()
{
return m_accel[X];
}
int16_t
CurieImu::getAccelY()
{
return m_accel[Y];
}
int16_t
CurieImu::getAccelZ()
{
return m_accel[Z];
}
int16_t*
CurieImu::getGyro()
{
return &m_gyro[0];
}
int16_t
CurieImu::getGyroX()
{
return m_gyro[X];
}
int16_t
CurieImu::getGyroY()
{
return m_gyro[Y];
}
int16_t
CurieImu::getGyroZ()
{
return m_gyro[Z];
}
int16_t*
CurieImu::getMotion()
{
return &m_motion[0];
}
void
CurieImu::updateAccel()
{
char message[4];
message[0] = FIRMATA_START_SYSEX;
message[1] = FIRMATA_CURIE_IMU;
message[2] = FIRMATA_CURIE_IMU_READ_ACCEL;
message[3] = FIRMATA_END_SYSEX;
lock();
mraa_firmata_response_stop(m_firmata);
mraa_firmata_response(m_firmata, handleSyncResponse);
mraa_firmata_write_sysex(m_firmata, &message[0], 4);
waitForResponse();
m_accel[0] = ((m_results[3] & 0x7f) | ((m_results[4] & 0x7f) << 7));
m_accel[1] = ((m_results[5] & 0x7f) | ((m_results[6] & 0x7f) << 7));
m_accel[2] = ((m_results[7] & 0x7f) | ((m_results[8] & 0x7f) << 7));
delete m_results;
unlock();
return;
}
void
CurieImu::updateGyro()
{
char message[4];
message[0] = FIRMATA_START_SYSEX;
message[1] = FIRMATA_CURIE_IMU;
message[2] = FIRMATA_CURIE_IMU_READ_GYRO;
message[3] = FIRMATA_END_SYSEX;
lock();
mraa_firmata_response_stop(m_firmata);
mraa_firmata_response(m_firmata, handleSyncResponse);
mraa_firmata_write_sysex(m_firmata, &message[0], 4);
waitForResponse();
m_gyro[0] = ((m_results[3] & 0x7f) | ((m_results[4] & 0x7f) << 7));
m_gyro[1] = ((m_results[5] & 0x7f) | ((m_results[6] & 0x7f) << 7));
m_gyro[2] = ((m_results[7] & 0x7f) | ((m_results[8] & 0x7f) << 7));
delete m_results;
unlock();
return;
}
void
CurieImu::updateMotion()
{
char message[4];
message[0] = FIRMATA_START_SYSEX;
message[1] = FIRMATA_CURIE_IMU;
message[2] = FIRMATA_CURIE_IMU_READ_MOTION;
message[3] = FIRMATA_END_SYSEX;
lock();
mraa_firmata_response_stop(m_firmata);
mraa_firmata_response(m_firmata, handleSyncResponse);
mraa_firmata_write_sysex(m_firmata, &message[0], 4);
waitForResponse();
m_motion[0] = ((m_results[3] & 0x7f) | ((m_results[4] & 0x7f) << 7));
m_motion[1] = ((m_results[5] & 0x7f) | ((m_results[6] & 0x7f) << 7));
m_motion[2] = ((m_results[7] & 0x7f) | ((m_results[8] & 0x7f) << 7));
m_motion[3] = ((m_results[9] & 0x7f) | ((m_results[10] & 0x7f) << 7));
m_motion[4] = ((m_results[11] & 0x7f) | ((m_results[12] & 0x7f) << 7));
m_motion[5] = ((m_results[13] & 0x7f) | ((m_results[13] & 0x7f) << 7));
for (int i=0; i<3; i++)
m_accel[i] = m_motion[i];
for (int i=0; i<3; i++)
m_gyro[i] = m_motion[i+3];
delete m_results;
unlock();
return;
}
int16_t
CurieImu::getTemperature()
{
char message[4];
message[0] = FIRMATA_START_SYSEX;
message[1] = FIRMATA_CURIE_IMU;
message[2] = FIRMATA_CURIE_IMU_READ_TEMP;
message[3] = FIRMATA_END_SYSEX;
lock();
mraa_firmata_response_stop(m_firmata);
mraa_firmata_response(m_firmata, handleSyncResponse);
mraa_firmata_write_sysex(m_firmata, &message[0], 4);
waitForResponse();
int16_t result;
result = ((m_results[3] & 0x7f) | ((m_results[4] & 0x7f) << 7));
result += ((m_results[5] & 0x7f) | ((m_results[6] & 0x7f) << 7)) << 8;
delete m_results;
unlock();
return result;
}
int16_t
CurieImu::getAxis()
{
return m_axis;
}
int16_t
CurieImu::getDirection()
{
return m_direction;
}
void
CurieImu::enableShockDetection(bool enable)
{
char message[5];
message[0] = FIRMATA_START_SYSEX;
message[1] = FIRMATA_CURIE_IMU;
message[2] = FIRMATA_CURIE_IMU_SHOCK_DETECT;
message[3] = enable;
message[4] = FIRMATA_END_SYSEX;
lock();
mraa_firmata_response_stop(m_firmata);
mraa_firmata_response(m_firmata, handleAsyncResponses);
mraa_firmata_write_sysex(m_firmata, &message[0], 5);
awaitingReponse = this;
unlock();
return;
}
bool
CurieImu::isShockDetected()
{
return (m_shockData.size() > 0);
}
void
CurieImu::getNextShock()
{
if (m_shockData.size() > 0) {
IMUDataItem* item = m_shockData.front();
m_axis = item->axis;
m_direction = item->direction;
m_shockData.pop();
delete item;
}
}
void
CurieImu::enableStepCounter(bool enable)
{
char message[5];
message[0] = FIRMATA_START_SYSEX;
message[1] = FIRMATA_CURIE_IMU;
message[2] = FIRMATA_CURIE_IMU_STEP_COUNTER;
message[3] = enable;
message[4] = FIRMATA_END_SYSEX;
lock();
mraa_firmata_response_stop(m_firmata);
mraa_firmata_response(m_firmata, handleAsyncResponses);
mraa_firmata_write_sysex(m_firmata, &message[0], 5);
awaitingReponse = this;
unlock();
return;
}
bool
CurieImu::isStepDetected()
{
return (m_stepData.size() > 0);
}
int16_t
CurieImu::getStepCount()
{
int16_t count = 0;
if (m_stepData.size() > 0) {
count = m_stepData.front();
m_stepData.pop();
}
return count;
}
void
CurieImu::enableTapDetection(bool enable)
{
char message[5];
message[0] = FIRMATA_START_SYSEX;
message[1] = FIRMATA_CURIE_IMU;
message[2] = FIRMATA_CURIE_IMU_TAP_DETECT;
message[3] = enable;
message[4] = FIRMATA_END_SYSEX;
lock();
mraa_firmata_response_stop(m_firmata);
mraa_firmata_response(m_firmata, handleAsyncResponses);
mraa_firmata_write_sysex(m_firmata, &message[0], 5);
awaitingReponse = this;
unlock();
return;
}
bool
CurieImu::isTapDetected()
{
return (m_tapData.size() > 0);
}
void
CurieImu::getNextTap()
{
if (m_tapData.size() > 0) {
IMUDataItem* item = m_tapData.front();
m_axis = item->axis;
m_direction = item->direction;
m_tapData.pop();
delete item;
}
}
| 4,460 |
402 | <reponame>urosporo/flow
/*
* Copyright 2000-2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.client.flow;
import com.vaadin.client.WidgetUtil;
import com.vaadin.client.flow.collection.JsArray;
import com.vaadin.client.flow.collection.JsCollections;
import com.vaadin.client.flow.collection.JsSet;
import com.vaadin.client.flow.nodefeature.MapProperty;
import com.vaadin.client.flow.nodefeature.NodeList;
import com.vaadin.client.flow.nodefeature.NodeMap;
import com.vaadin.client.flow.util.ClientJsonCodec;
import com.vaadin.flow.shared.JsonConstants;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
/**
* Updates a state tree based on changes in JSON format.
*
* @author <NAME>
* @since 1.0
*/
public class TreeChangeProcessor {
private TreeChangeProcessor() {
// Only static helpers here
}
/**
* Update a state tree based on a JSON array of changes.
*
* @param tree
* the tree to update
* @param changes
* the JSON array of changes
* @return a set of updated nodes addressed by the {@code changes}
*/
public static JsSet<StateNode> processChanges(StateTree tree,
JsonArray changes) {
assert !tree.isUpdateInProgress()
: "Previous tree change processing has not completed";
try {
tree.setUpdateInProgress(true);
// Attach all nodes before doing anything else
JsSet<StateNode> nodes = processAttachChanges(tree, changes);
// Then process all non-attach changes
int length = changes.length();
for (int i = 0; i < length; i++) {
JsonObject change = changes.getObject(i);
if (!isAttach(change)) {
nodes.add(processChange(tree, change));
}
}
return nodes;
} finally {
tree.setUpdateInProgress(false);
}
}
private static JsSet<StateNode> processAttachChanges(StateTree tree,
JsonArray changes) {
JsSet<StateNode> nodes = JsCollections.set();
int length = changes.length();
for (int i = 0; i < length; i++) {
JsonObject change = changes.getObject(i);
if (isAttach(change)) {
int nodeId = (int) change.getNumber(JsonConstants.CHANGE_NODE);
if (nodeId != tree.getRootNode().getId()) {
StateNode node = new StateNode(nodeId, tree);
tree.registerNode(node);
nodes.add(node);
}
}
}
return nodes;
}
private static boolean isAttach(JsonObject change) {
return JsonConstants.CHANGE_TYPE_ATTACH
.equals(change.getString(JsonConstants.CHANGE_TYPE));
}
/**
* Update a state tree based on a JSON change. This method is public for
* testing purposes.
*
* @param tree
* the tree to update
* @param change
* the JSON change
* @return the updated node addressed by the provided {@code change}
*/
public static StateNode processChange(StateTree tree, JsonObject change) {
String type = change.getString(JsonConstants.CHANGE_TYPE);
int nodeId = (int) change.getNumber(JsonConstants.CHANGE_NODE);
StateNode node = tree.getNode(nodeId);
assert node != null;
switch (type) {
case JsonConstants.CHANGE_TYPE_NOOP:
populateFeature(change, node);
break;
case JsonConstants.CHANGE_TYPE_SPLICE:
processSpliceChange(change, node);
break;
case JsonConstants.CHANGE_TYPE_PUT:
processPutChange(change, node);
break;
case JsonConstants.CHANGE_TYPE_REMOVE:
processRemoveChange(change, node);
break;
case JsonConstants.CHANGE_TYPE_DETACH:
processDetachChange(node);
break;
case JsonConstants.CHANGE_TYPE_CLEAR:
processClearChange(change, node);
break;
default:
assert false : "Unsupported change type: " + type;
}
return node;
}
private static void processDetachChange(StateNode node) {
node.getTree().unregisterNode(node);
node.setParent(null);
}
private static void populateFeature(JsonObject change, StateNode node) {
assert change.hasKey(JsonConstants.CHANGE_FEATURE_TYPE)
: "Change doesn't contain feature type. Don't know how to populate feature";
int featureId = (int) change.getNumber(JsonConstants.CHANGE_FEATURE);
if (change.getBoolean(JsonConstants.CHANGE_FEATURE_TYPE)) {
// list feature
node.getList(featureId);
} else {
node.getMap(featureId);
}
}
private static void processPutChange(JsonObject change, StateNode node) {
MapProperty property = findProperty(change, node);
if (change.hasKey(JsonConstants.CHANGE_PUT_VALUE)) {
JsonValue jsonValue = change.get(JsonConstants.CHANGE_PUT_VALUE);
Object value = ClientJsonCodec.decodeWithoutTypeInfo(jsonValue);
property.setValue(value);
} else if (change.hasKey(JsonConstants.CHANGE_PUT_NODE_VALUE)) {
int childId = (int) change
.getNumber(JsonConstants.CHANGE_PUT_NODE_VALUE);
StateNode child = node.getTree().getNode(childId);
assert child != null;
child.setParent(node);
property.setValue(child);
} else {
assert false
: "Change should have either value or nodeValue property: "
+ WidgetUtil.stringify(change);
}
}
private static void processRemoveChange(JsonObject change, StateNode node) {
MapProperty property = findProperty(change, node);
property.removeValue();
}
private static MapProperty findProperty(JsonObject change, StateNode node) {
int nsId = (int) change.getNumber(JsonConstants.CHANGE_FEATURE);
NodeMap map = node.getMap(nsId);
String key = change.getString(JsonConstants.CHANGE_MAP_KEY);
return map.getProperty(key);
}
private static void processSpliceChange(JsonObject change, StateNode node) {
int nsId = (int) change.getNumber(JsonConstants.CHANGE_FEATURE);
NodeList list = node.getList(nsId);
int index = (int) change.getNumber(JsonConstants.CHANGE_SPLICE_INDEX);
int remove;
if (change.hasKey(JsonConstants.CHANGE_SPLICE_REMOVE)) {
remove = (int) change.getNumber(JsonConstants.CHANGE_SPLICE_REMOVE);
} else {
remove = 0;
}
if (change.hasKey(JsonConstants.CHANGE_SPLICE_ADD)) {
JsonArray addJson = change
.getArray(JsonConstants.CHANGE_SPLICE_ADD);
JsArray<Object> add = ClientJsonCodec.jsonArrayAsJsArray(addJson);
list.splice(index, remove, add);
} else if (change.hasKey(JsonConstants.CHANGE_SPLICE_ADD_NODES)) {
JsonArray addNodes = change
.getArray(JsonConstants.CHANGE_SPLICE_ADD_NODES);
int length = addNodes.length();
JsArray<StateNode> add = JsCollections.array();
StateTree tree = node.getTree();
for (int i = 0; i < length; i++) {
int childId = (int) addNodes.getNumber(i);
StateNode child = tree.getNode(childId);
assert child != null : "No child node found with id " + childId;
child.setParent(node);
add.set(i, child);
}
list.splice(index, remove, add);
} else {
list.splice(index, remove);
}
}
private static void processClearChange(JsonObject change, StateNode node) {
int nsId = (int) change.getNumber(JsonConstants.CHANGE_FEATURE);
NodeList list = node.getList(nsId);
list.clear();
}
}
| 3,799 |
769 | <filename>include/circt/Support/FieldRef.h
//===- FieldRef.h - Field References ---------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This header file defines FieldRefs and helpers for them.
//
//===----------------------------------------------------------------------===//
#ifndef CIRCT_SUPPORT_FIELDREF_H
#define CIRCT_SUPPORT_FIELDREF_H
#include "circt/Support/LLVM.h"
#include "mlir/IR/Value.h"
#include "llvm/ADT/DenseMapInfo.h"
namespace circt {
/// This class represents a reference to a specific field or element of an
/// aggregate value. Typically, the user will assign a unique field ID to each
/// field in an aggregate type by visiting them in a depth-first pre-order.
///
/// This can be used as the key in a hashtable to store field specific
/// information.
class FieldRef {
public:
/// Get a null FieldRef.
FieldRef() {}
/// Get a FieldRef location for the specified value.
FieldRef(Value value, unsigned id) : value(value), id(id) {}
/// Get the Value which created this location.
Value getValue() const { return value; }
/// Get the operation which defines this field.
Operation *getDefiningOp() const;
/// Get the field ID of this FieldRef, which is a unique identifier mapped to
/// a specific field in a bundle.
unsigned getFieldID() const { return id; }
/// Get a reference to a subfield.
FieldRef getSubField(unsigned subFieldID) const {
return FieldRef(value, id + subFieldID);
}
bool operator==(const FieldRef &other) const {
return value == other.value && id == other.id;
}
bool operator<(const FieldRef &other) const {
if (value.getImpl() < other.value.getImpl())
return true;
if (value.getImpl() > other.value.getImpl())
return false;
return id < other.id;
}
operator bool() const { return bool(value); }
private:
/// A pointer to the value which created this.
Value value;
/// A unique field ID.
unsigned id = 0;
};
/// Get a hash code for a FieldRef.
inline ::llvm::hash_code hash_value(const FieldRef &fieldRef) {
return llvm::hash_combine(fieldRef.getValue(), fieldRef.getFieldID());
}
} // namespace circt
namespace llvm {
/// Allow using FieldRef with DenseMaps. This hash is based on the Value
/// identity and field ID.
template <>
struct DenseMapInfo<circt::FieldRef> {
static inline circt::FieldRef getEmptyKey() {
return circt::FieldRef(DenseMapInfo<mlir::Value>::getEmptyKey(), 0);
}
static inline circt::FieldRef getTombstoneKey() {
return circt::FieldRef(DenseMapInfo<mlir::Value>::getTombstoneKey(), 0);
}
static unsigned getHashValue(const circt::FieldRef &val) {
return circt::hash_value(val);
}
static bool isEqual(const circt::FieldRef &lhs, const circt::FieldRef &rhs) {
return lhs == rhs;
}
};
} // namespace llvm
#endif // CIRCT_SUPPORT_FIELDREF_H
| 971 |
5,659 | from django.core.management.base import CommandError
from cms.utils.check import FileOutputWrapper, check
from .base import SubcommandsCommand
class CheckInstallation(SubcommandsCommand):
help_string = 'Checks your settings and environment'
command_name = 'check'
def handle(self, *args, **options):
if not check(FileOutputWrapper(self.stdout, self.stderr)):
raise CommandError()
| 137 |
596 | /*
* Yet Another UserAgent Analyzer
* Copyright (C) 2013-2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 nl.example.logging.log4j;
import nl.basjes.parse.useragent.UserAgentAnalyzerDirect;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
class TestFailingOverBadLoggingDependencies {
@Test
void failOverMissingLoggingUsage() {
// Since Log4j is used immediately in the UserAgentAnalyzerDirect class this
// test fails before the actual check code is run. So no clean error message.
assertThrows(NoClassDefFoundError.class,
() -> UserAgentAnalyzerDirect.newBuilder().delayInitialization().build());
}
}
| 374 |
428 | /*
** 2011 April 5
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
*/
package info.ata4.bsplib.struct;
/**
* A simple class to store RGBA values.
*
* @author <NAME> <barracuda415 at yahoo.de>
*/
public class Color32 {
public final int r;
public final int g;
public final int b;
public final int a;
public final int rgba;
/**
* Creates a new RGBA value with the given colors
*
* @param red red value, 0-255
* @param green green value, 0-255
* @param blue blue value, 0-255
* @param alpha alpha value, 0-255
*/
public Color32(int red, int green, int blue, int alpha) {
r = red & 0xFF;
g = green & 0xFF;
b = blue & 0xFF;
a = alpha & 0xFF;
rgba = (((((a << 8) + b) << 8) + g) << 8) + r;
}
/**
* Creates a new RGBA value with the given integer
*
* @param value RGBA integer
*/
public Color32(int value) {
r = value & 0xFF;
g = (value >> 8) & 0xFF;
b = (value >> 16) & 0xFF;
a = (value >> 24) & 0xFF;
rgba = value;
}
}
| 614 |
852 | import FWCore.ParameterSet.Config as cms
# This modifier is for activating displacedGeneralStep step for phase1 tracking
displacedTracking = cms.Modifier()
| 42 |
303 | <reponame>mr-c/LightZone<filename>lightcrafts/src/com/lightcrafts/ui/region/curves/Linear.java<gh_stars>100-1000
/* Copyright (C) 2005-2011 <NAME> */
package com.lightcrafts.ui.region.curves;
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
class Linear extends Polynomial {
private double a, b; // a + b*t
// Define a Linear by its real root:
static Linear createFactored(double z0) {
return new Linear(-z0, 1.);
}
Linear(double a, double b) {
super(a, b);
this.a = a;
this.b = b;
}
Polynomial translate(double x) {
return new Linear(a + b * x, b);
}
// Infer a Line2D (control points) from two Linears (polynomial
// coefficients). See Line2D.fillEqn().
static Shape createShape(Polynomial x, Polynomial y) {
if ((x.getDegree() != 1) || (y.getDegree() != 1)) {
throw new IllegalArgumentException("Expected degree 1");
}
double xa = x.getCoeff(0);
double xb = x.getCoeff(1);
double ya = y.getCoeff(0);
double yb = y.getCoeff(1);
Point2D c1 = new Point2D.Double(xa, ya);
Point2D c2 = new Point2D.Double(xa + xb, ya + yb);
return new Line2D.Double(
c1.getX(), c1.getY(),
c2.getX(), c2.getY()
);
}
}
| 647 |
1,056 | <reponame>timfel/netbeans
/*
* 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.libs.git;
import java.net.URISyntaxException;
import org.eclipse.jgit.transport.URIish;
/**
* Representation of a supported Git URI, that denotes a remote repository and
* is used mainly in Git commands connecting to remote repositories.
* An instance of this class is immutable meaning any setter method constructs
* a new instance but does not modify the original instance.
* @author <NAME>
*/
public final class GitURI {
private URIish uri;
private GitURI() {}
// a private constructor with URIish uri causes:
// cannot access org.eclipse.jgit.transport.URIish
// class file for org.eclipse.jgit.transport.URIish not found
private GitURI create(URIish uri) {
GitURI u = new GitURI();
u.uri = uri;
return u;
}
/**
* Constructor creating an instance of a Git URI. In case the given uri string
* has an unsupported format a URISyntaxException is thrown.
* @param uriString string representation of a Git URI.
* @throws URISyntaxException if the given string has unsupported format
*/
public GitURI(String uriString) throws URISyntaxException {
this.uri = new URIish(uriString);
// WORKAROUND:
// new URIish("https://foo.bar").getHost() returns null
// new URIish("https://foo.bar").getPath() returns foo.bar
// it should work instead like
// new URIish("https://foo.bar/").getHost() returns foo.bar
// new URIish("https://foo.bar/").getPath() returns null
String scheme = uri.getScheme();
if(scheme != null &&
!scheme.startsWith("file:") &&
uri.getHost() == null &&
!uriString.endsWith("/"))
{
uri = new URIish(uriString + "/");
}
}
/**
* Returns string representation that contains also username and password as plaintext.
* @return full form (along with user credentials) of the Git URI
*/
public String toPrivateString() {
return uri.toPrivateString();
}
/**
* Constructs a new instance with the given user name.
* @param user user name
* @return new instance that contains user as part of the credential area.
*/
public GitURI setUser (String user) {
return create(uri.setUser(user));
}
/**
* Constructs a new instance with the given user name.
* @param scheme new scheme
* @return a duplicate instance of this with modified scheme part
*/
public GitURI setScheme (String scheme) {
return create(uri.setScheme(scheme));
}
/**
* Constructs a new instance with the given port number.
* @param port port number
* @return a duplicate instance of this with modified port number.
*/
public GitURI setPort (int port) {
return create(uri.setPort(port));
}
/**
* Constructs a new instance with the given path.
* @param path path to a resource
* @return a duplicate instance of this with modified path to a resource.
*/
public GitURI setPath (String path) {
return create(uri.setPath(path));
}
/**
* Creates a new instance with the given new password.
* @param password new password
* @return a duplicate instance of this with a new password
*/
public GitURI setPass (String password) {
return create(uri.setPass(password));
}
/**
* Creates a new instance with the given new host name.
* @param host new host name
* @return a duplicate instance of this with a new host name
*/
public GitURI setHost (String host) {
return create(uri.setHost(host));
}
/**
* Returns <code>true</code> if this URI references a repository on another system.
*/
public boolean isRemote() {
return uri.isRemote();
}
/**
* Returns the username part of the URI's credentials part.
*/
public String getUser() {
return uri.getUser();
}
/**
* Returns the URI's scheme as a string.
*/
public String getScheme() {
return uri.getScheme();
}
/**
* Returns the port number specified by the URI.
*/
public int getPort() {
return uri.getPort();
}
/**
* Returns the path on the host to the resource denoted by the URI.
*/
public String getPath() {
return uri.getPath();
}
/**
* Returns the password part of the URI's credentials part.
*/
public String getPass() {
return uri.getPass();
}
/**
* Returns the URI's host.
*/
public String getHost() {
return uri.getHost();
}
/**
* Returns string representation if the URI without the credentials part
* @return readable representation of the URI with empty credentials.
*/
@Override
public String toString() {
return uri.toString();
}
@Override
public boolean equals(Object o) {
if (o instanceof GitURI) {
return uri.equals(((GitURI) o).uri);
} else {
return false;
}
}
@Override
public int hashCode() {
return uri.hashCode();
}
}
| 2,178 |
679 | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef OOX_VML_VMLDRAWING_HXX
#define OOX_VML_VMLDRAWING_HXX
#include <map>
#include <memory>
#include <vector>
#include "oox/ole/oleobjecthelper.hxx"
namespace com { namespace sun { namespace star {
namespace awt { struct Rectangle; }
namespace awt { class XControlModel; }
namespace drawing { class XDrawPage; }
namespace drawing { class XShape; }
namespace drawing { class XShapes; }
} } }
namespace oox {
namespace core { class XmlFilterBase; }
namespace ole { class EmbeddedControl; }
namespace ole { class EmbeddedForm; }
}
namespace oox {
namespace vml {
class ShapeBase;
class ShapeContainer;
struct ClientData;
// ============================================================================
/** Enumerates different types of VML drawings. */
enum DrawingType
{
VMLDRAWING_WORD, /// Word: One shape per drawing.
VMLDRAWING_EXCEL, /// Excel: OLE objects are part of VML.
VMLDRAWING_POWERPOINT /// PowerPoint: OLE objects are part of DrawingML.
};
// ============================================================================
/** Contains information about an OLE object embedded in a draw page. */
struct OleObjectInfo : public ::oox::ole::OleObjectInfo
{
::rtl::OUString maShapeId; /// Shape identifier for shape lookup.
::rtl::OUString maName; /// Programmatical name of the OLE object.
bool mbAutoLoad;
const bool mbDmlShape; /// True = DrawingML shape (PowerPoint), false = VML shape (Excel/Word).
explicit OleObjectInfo( bool bDmlShape = false );
/** Sets the string representation of the passed numeric shape identifier. */
void setShapeId( sal_Int32 nShapeId );
};
// ============================================================================
/** Contains information about a form control embedded in a draw page. */
struct ControlInfo
{
::rtl::OUString maShapeId; /// Shape identifier for shape lookup.
::rtl::OUString maFragmentPath; /// Path to the fragment describing the form control properties.
::rtl::OUString maName; /// Programmatical name of the form control.
explicit ControlInfo();
/** Sets the string representation of the passed numeric shape identifier. */
void setShapeId( sal_Int32 nShapeId );
};
// ============================================================================
/** Represents the collection of VML shapes for a complete draw page. */
class Drawing
{
public:
explicit Drawing(
::oox::core::XmlFilterBase& rFilter,
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& rxDrawPage,
DrawingType eType );
virtual ~Drawing();
/** Returns the filter object that imports/exports this VML drawing. */
inline ::oox::core::XmlFilterBase& getFilter() const { return mrFilter; }
/** Returns the application type containing the drawing. */
inline DrawingType getType() const { return meType; }
/** Returns read/write access to the container of shapes and templates. */
inline ShapeContainer& getShapes() { return *mxShapes; }
/** Returns read access to the container of shapes and templates. */
inline const ShapeContainer& getShapes() const { return *mxShapes; }
/** Returns the form object used to process ActiveX form controls. */
::oox::ole::EmbeddedForm& getControlForm() const;
/** Registers a block of shape identifiers reserved by this drawing. Block
size is 1024, shape identifiers are one-based (block 1 => 1025-2048). */
void registerBlockId( sal_Int32 nBlockId );
/** Registers the passed embedded OLE object. The related shape will then
load the OLE object data from the specified fragment. */
void registerOleObject( const OleObjectInfo& rOleObject );
/** Registers the passed embedded form control. The related shape will then
load the control properties from the specified fragment. */
void registerControl( const ControlInfo& rControl );
/** Final processing after import of the fragment. */
void finalizeFragmentImport();
/** Creates and inserts all UNO shapes into the draw page. The virtual
function notifyXShapeInserted() will be called for each new shape. */
void convertAndInsert() const;
/** Returns the local shape index from the passed global shape identifier. */
sal_Int32 getLocalShapeIndex( const ::rtl::OUString& rShapeId ) const;
/** Returns the registered info structure for an OLE object, if extant. */
const OleObjectInfo* getOleObjectInfo( const ::rtl::OUString& rShapeId ) const;
/** Returns the registered info structure for a form control, if extant. */
const ControlInfo* getControlInfo( const ::rtl::OUString& rShapeId ) const;
/** Creates a new UNO shape object, inserts it into the passed UNO shape
container, and sets the shape position and size. */
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >
createAndInsertXShape(
const ::rtl::OUString& rService,
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& rxShapes,
const ::com::sun::star::awt::Rectangle& rShapeRect ) const;
/** Creates a new UNO shape object for a form control, inserts the control
model into the form, and the shape into the passed UNO shape container. */
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >
createAndInsertXControlShape(
const ::oox::ole::EmbeddedControl& rControl,
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& rxShapes,
const ::com::sun::star::awt::Rectangle& rShapeRect,
sal_Int32& rnCtrlIndex ) const;
/** Derived classes may disable conversion of specific shapes. */
virtual bool isShapeSupported( const ShapeBase& rShape ) const;
/** Derived classes may return additional base names for automatic shape
name creation. */
virtual ::rtl::OUString getShapeBaseName( const ShapeBase& rShape ) const;
/** Derived classes may calculate the shape rectangle from a non-standard
anchor information string. */
virtual bool convertClientAnchor(
::com::sun::star::awt::Rectangle& orShapeRect,
const ::rtl::OUString& rShapeAnchor ) const;
/** Derived classes create a UNO shape according to the passed shape model.
Called for shape models that specify being under host control. */
virtual ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >
createAndInsertClientXShape(
const ShapeBase& rShape,
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& rxShapes,
const ::com::sun::star::awt::Rectangle& rShapeRect ) const;
/** Derived classes may want to know that a UNO shape has been inserted.
Will be called from the convertAndInsert() implementation.
@param bGroupChild True = inserted into a group shape,
false = inserted directly into this drawing. */
virtual void notifyXShapeInserted(
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rxShape,
const ::com::sun::star::awt::Rectangle& rShapeRect,
const ShapeBase& rShape, bool bGroupChild );
private:
typedef ::std::vector< sal_Int32 > BlockIdVector;
typedef ::std::auto_ptr< ::oox::ole::EmbeddedForm > EmbeddedFormPtr;
typedef ::std::auto_ptr< ShapeContainer > ShapeContainerPtr;
typedef ::std::map< ::rtl::OUString, OleObjectInfo > OleObjectInfoMap;
typedef ::std::map< ::rtl::OUString, ControlInfo > ControlInfoMap;
::oox::core::XmlFilterBase& mrFilter; /// Filter object that imports/exports the VML drawing.
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >
mxDrawPage; /// UNO draw page used to insert the shapes.
mutable EmbeddedFormPtr mxCtrlForm; /// The control form used to process embedded controls.
mutable BlockIdVector maBlockIds; /// Block identifiers used by this drawing.
ShapeContainerPtr mxShapes; /// All shapes and shape templates.
OleObjectInfoMap maOleObjects; /// Info about all embedded OLE objects, mapped by shape id.
ControlInfoMap maControls; /// Info about all embedded form controls, mapped by control name.
const DrawingType meType; /// Application type containing the drawing.
};
// ============================================================================
} // namespace vml
} // namespace oox
#endif
| 3,689 |
1,403 | <reponame>Valkatraz/scons
class Empty {
}
interface Listener {
public void execute();
}
public
class
Test {
class Inner {
void go() {
use(new Listener() {
public void execute() {
System.out.println("In Inner");
}
});
}
String s1 = "class A";
String s2 = "new Listener() { }";
/* class B */
/* new Listener() { } */
}
public static void main(String[] args) {
new Test().run();
}
void run() {
use(new Listener() {
public void execute() {
use(new Listener( ) {
public void execute() {
System.out.println("Inside execute()");
}
});
}
});
new Inner().go();
}
void use(Listener l) {
l.execute();
}
}
class Private {
void run() {
new Listener() {
public void execute() {
}
};
}
}
| 390 |
509 | <reponame>NEUQ-League/wechat_sender
# coding: utf-8
from __future__ import unicode_literals
from __future__ import absolute_import
import copy
import functools
import json
import os
import time
import datetime
import psutil
import logging
import sys
import tornado.web
from wechat_sender.objects import WxBot, Message, Global
from wechat_sender.utils import StatusWrapperMixin, STATUS_BOT_EXCEPTION, STATUS_PERMISSION_DENIED, \
STATUS_TORNADO_EXCEPTION, DEFAULT_REMIND_TIME, STATUS_ERROR, DEFAULT_REPORT_TIME, DELAY_TASK, PERIODIC_TASK, \
MESSAGE_REPORT_COMMAND, SYSTEM_TASK, MESSAGE_STATUS_COMMAND
glb = None
_logger = logging.getLogger(__name__)
class Application(tornado.web.Application):
"""
tornado app 初始化
"""
def __init__(self):
handlers = [
(r"/message", MessageHandle),
(r"/delay_message", DelayMessageHandle),
(r"/periodic_message", PeriodicMessageHandle),
(r"/send_to_message", UserMessageHandle),
]
settings = dict(
static_path=os.path.join(os.path.dirname(__file__), "static"),
)
super(Application, self).__init__(handlers, **settings)
class MessageHandle(StatusWrapperMixin, tornado.web.RequestHandler):
"""
普通消息处理 handle
"""
def post(self, *args, **kwargs):
message = self.get_argument('content', None)
token = self.get_argument('token', None)
receivers = self.get_argument('receivers', None)
if not message:
self.status_code = STATUS_ERROR
self.write('Content is required')
return
if glb.token:
if glb.token != token:
self.status_code = STATUS_PERMISSION_DENIED
self.write('Token is missing')
return
try:
msg = Message(message, receivers=receivers)
glb.wxbot.send_msg(msg)
self.write('Success')
except Exception as e:
_logger.exception(e)
self.status_code = STATUS_BOT_EXCEPTION
self.write(e.message)
class DelayMessageHandle(StatusWrapperMixin, tornado.web.RequestHandler):
"""
延时消息处理 handle
"""
def __init__(self, application, request, *args, **kwargs):
self.ioloop = tornado.ioloop.IOLoop.instance()
super(DelayMessageHandle, self).__init__(application, request, *args, **kwargs)
def post(self, *args, **kwargs):
content = self.get_argument('content', '')
title = self.get_argument('title', '')
task_time = self.get_argument('time', None)
remind = int(self.get_argument('remind', DEFAULT_REMIND_TIME))
token = self.get_argument('token', None)
receivers = self.get_argument('receivers', None)
if glb.token:
if glb.token != token:
self.status_code = STATUS_PERMISSION_DENIED
self.write('Token is missing')
return
if task_time:
try:
task_time = datetime.datetime.strptime(task_time, '%Y-%m-%d %H:%M:%S')
timestamp = time.mktime(
(task_time - datetime.timedelta(
seconds=remind)).timetuple())
except ValueError as e:
self.status_code = STATUS_ERROR
self.write(e.message)
_logger.exception(e)
return
else:
task_time = datetime.datetime.now()
timestamp = int(time.mktime(task_time.timetuple()))
try:
message = Message(content, title, task_time, datetime.timedelta(seconds=remind), receivers=receivers)
self.ioloop.call_at(timestamp, self.delay_task, DELAY_TASK, message)
self.write('Success')
except Exception as e:
self.status_code = STATUS_TORNADO_EXCEPTION
self.write(e.message)
_logger.exception(e)
@staticmethod
def delay_task(task_type, message):
# try:
glb.wxbot.send_msg(message)
_logger.info(
'{0} Send delay message {1} at {2:%Y-%m-%d %H:%M:%S}'.format(task_type, message, datetime.datetime.now()))
# except Exception as e:
class PeriodicMessageHandle(StatusWrapperMixin, tornado.web.RequestHandler):
"""
周期消息处理 handle
"""
def __init__(self, application, request, *args, **kwargs):
self.ioloop = tornado.ioloop.IOLoop.instance()
super(PeriodicMessageHandle, self).__init__(application, request, *args, **kwargs)
def post(self, *args, **kwargs):
content = self.get_argument('content', '')
title = self.get_argument('title', '')
interval = self.get_argument('interval', None)
token = self.get_argument('token', None)
receivers = self.get_argument('receivers', None)
if glb.token:
if glb.token != token:
self.status_code = STATUS_PERMISSION_DENIED
self.write('Token is missing')
return
if not interval:
self.status_code = STATUS_ERROR
self.write('interval is required')
return
try:
interval = int(interval)
except Exception as e:
self.status_code = STATUS_ERROR
self.write('interval must be a integer')
try:
message = Message(content, title=title, interval=datetime.timedelta(seconds=interval), receivers=receivers)
user_periodic = tornado.ioloop.PeriodicCallback(
functools.partial(self.periodic_task, PERIODIC_TASK, message),
interval * 1000, self.ioloop)
glb.periodic_list.append(user_periodic)
user_periodic.start()
self.write('Success')
except Exception as e:
self.status_code = STATUS_TORNADO_EXCEPTION
self.write(e.message)
_logger.exception(e)
@staticmethod
def periodic_task(task_type, message):
glb.wxbot.send_msg(message)
_logger.info('{0} Send periodic message {1} at {2:%Y-%m-%d %H:%M:%S}'.format(task_type, message,
datetime.datetime.now()))
class UserMessageHandle(StatusWrapperMixin, tornado.web.RequestHandler):
"""
指定消息接收处理 handle
"""
def post(self, *args, **kwargs):
from wxpy import ensure_one
content = self.get_argument('content', '')
search = self.get_argument('search', '')
token = self.get_argument('token', None)
default_receiver = self.get_argument('receivers', None)
if glb.token:
if glb.token != token:
self.status_code = STATUS_PERMISSION_DENIED
self.write('Token is missing')
return
try:
search = json.loads(search)
except ValueError:
search = search
try:
if isinstance(search, dict):
receiver = ensure_one(glb.wxbot.bot.search(**search))
else:
receiver = ensure_one(glb.wxbot.bot.search(search))
except ValueError:
receiver = None
if receiver:
receiver.send_msg(content)
else:
msg = '消息发送失败,没有找到接收者。\n[搜索条件]: {0}\n[消息内容]:{1}'.format(search, content)
message = Message(msg, receivers=default_receiver)
glb.wxbot.send_msg(message)
_logger.info(msg)
self.write('Success')
def generate_run_info():
"""
获取当前运行状态
"""
uptime = datetime.datetime.now() - datetime.datetime.fromtimestamp(glb.run_info.create_time())
memory_usage = glb.run_info.memory_info().rss
msg = '[当前时间] {now:%H:%M:%S}\n[运行时间] {uptime}\n[内存占用] {memory}\n[发送消息] {messages}'.format(
now=datetime.datetime.now(),
uptime=str(uptime).split('.')[0],
memory='{:.2f} MB'.format(memory_usage / 1024 ** 2),
messages=len(glb.wxbot.bot.messages)
)
return msg
def check_bot(task_type=SYSTEM_TASK):
"""
wxpy bot 健康检查任务
"""
if glb.wxbot.bot.alive:
msg = generate_run_info()
message = Message(content=msg, receivers='status')
glb.wxbot.send_msg(message)
_logger.info(
'{0} Send status message {1} at {2:%Y-%m-%d %H:%M:%S}'.format(task_type, msg, datetime.datetime.now()))
else:
# todo
pass
def timeout_message_report():
"""
周期/延时 消息报告
"""
timeout_list = glb.ioloop._timeouts
delay_task = []
for timeout in timeout_list:
if not timeout.callback:
continue
if len(timeout.callback.args) == 2:
task_type, message = timeout.callback.args
delay_task.append(message)
msg = '当前已注册延时消息共有{0}条'.format(len(delay_task))
for i, itm in enumerate(delay_task):
msg = '{pre}\n[ID (序号) ]:D{index}\n[消息接收]:{receiver}\n[发送时间]:{remind}\n[消息时间]:{time}\n[消息标题]:{message}\n'.format(
pre=msg, index=i, remind=itm.remind, time=itm.time, message=itm.title or itm.content, receiver=itm.receiver)
interval_task = [(periodic.callback.args[1], periodic.is_running()) for periodic in glb.periodic_list if
len(periodic.callback.args) == 2 and periodic.callback.args[0] == PERIODIC_TASK]
msg = '{0}\n当前已注册周期消息共有{1}条'.format(msg, len(interval_task))
for i, itm in enumerate(interval_task):
msg = '{pre}\n[ID (序号) ]:P{index}\n[消息接收]:{receiver}\n[运行状态]:{status}\n[发送周期]:{interval}\n[消息标题]:{message}\n'.format(
pre=msg, index=i, interval=itm[0].interval, status='已激活' if itm[1] else '未激活',
message=itm[0].title or itm[0].content, receiver=itm[0].receiver)
return msg
def register_listener_handle(wxbot):
"""
wechat_sender 向 wxpy 注册控制消息 handler
"""
from wxpy import TEXT
@wxbot.bot.register(wxbot.default_receiver, TEXT, except_self=False)
def sender_command_handle(msg):
command_dict = {MESSAGE_REPORT_COMMAND: timeout_message_report(),
MESSAGE_STATUS_COMMAND: generate_run_info()}
message = command_dict.get(msg.text, None)
if message:
return message
myself = wxbot.bot.registered.get_config(msg)
registered_copy = copy.copy(wxbot.bot.registered)
registered_copy.remove(myself)
pre_conf = registered_copy.get_config(msg)
if pre_conf:
my_name = sys._getframe().f_code.co_name
if my_name != pre_conf.func.__name__:
pre_conf.func(msg)
def listen(bot, receivers=None, token=None, port=10245, status_report=False, status_receiver=None,
status_interval=DEFAULT_REPORT_TIME):
"""
传入 bot 实例并启动 wechat_sender 服务
:param bot: (必填|Bot对象) - wxpy 的 Bot 对象实例
:param receivers: (选填|wxpy.Chat 对象|Chat 对象列表) - 消息接收者,wxpy 的 Chat 对象实例, 或 Chat 对象列表,如果为 list 第一个 Chat 为默认接收者。如果为 Chat 对象,则默认接收者也是此对象。 不填为当前 bot 对象的文件接收者
:param token: (选填|str) - 信令,防止 receiver 被非法滥用,建议加上 token 防止非法使用,如果使用 token 请在初始化 `Sender()` 时也使用统一 token,否则无法发送。token 建议为 32 位及以上的无规律字符串
:param port: (选填|int) - 监听端口, 监听端口默认为 10245 ,如有冲突或特殊需要请自行指定,需要和 `Sender()` 统一
:param status_report: (选填|bool) - 是否开启状态报告,如果开启,wechat_sender 将会定时发送状态信息到 status_receiver
:param status_receiver: (选填|Chat 对象) - 指定 status_receiver,不填将会发送状态消息给默认接收者
:param status_interval: (选填|int|datetime.timedelta) - 指定状态报告发送间隔时间,为 integer 时代表毫秒
"""
global glb
periodic_list = []
app = Application()
wxbot = WxBot(bot, receivers, status_receiver)
register_listener_handle(wxbot)
process = psutil.Process()
app.listen(port)
if status_report:
if isinstance(status_interval, datetime.timedelta):
status_interval = status_interval.seconds * 1000
check_periodic = tornado.ioloop.PeriodicCallback(functools.partial(check_bot, SYSTEM_TASK), status_interval)
check_periodic.start()
periodic_list.append(check_periodic)
glb = Global(wxbot=wxbot, run_info=process, periodic_list=periodic_list, ioloop=tornado.ioloop.IOLoop.instance(),
token=token)
tornado.ioloop.IOLoop.current().start()
| 6,501 |
769 | <gh_stars>100-1000
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import List, Optional, Sequence, Tuple, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from typing_extensions import Literal
from torchmetrics.functional.image.ssim import _ssim_compute, _ssim_update
def _get_normalized_sim_and_cs(
preds: Tensor,
target: Tensor,
kernel_size: Sequence[int] = (11, 11),
sigma: Sequence[float] = (1.5, 1.5),
reduction: str = "elementwise_mean",
data_range: Optional[float] = None,
k1: float = 0.01,
k2: float = 0.03,
normalize: Optional[Literal["relu", "simple"]] = None,
) -> Tuple[Tensor, Tensor]:
sim, contrast_sensitivity = _ssim_compute(
preds, target, kernel_size, sigma, reduction, data_range, k1, k2, return_contrast_sensitivity=True
)
if normalize == "relu":
sim = torch.relu(sim)
contrast_sensitivity = torch.relu(contrast_sensitivity)
return sim, contrast_sensitivity
def _multiscale_ssim_compute(
preds: Tensor,
target: Tensor,
kernel_size: Sequence[int] = (11, 11),
sigma: Sequence[float] = (1.5, 1.5),
reduction: str = "elementwise_mean",
data_range: Optional[float] = None,
k1: float = 0.01,
k2: float = 0.03,
betas: Union[Tuple[float, float, float, float, float], Tuple[float, ...]] = (
0.0448,
0.2856,
0.3001,
0.2363,
0.1333,
),
normalize: Optional[Literal["relu", "simple"]] = None,
) -> Tensor:
"""Computes Multi-Scale Structual Similarity Index Measure. Adapted from: https://github.com/jorge-
pessoa/pytorch-msssim/blob/master/pytorch_msssim/__init__.py.
Args:
preds: estimated image
target: ground truth image
kernel_size: size of the gaussian kernel (default: (11, 11))
sigma: Standard deviation of the gaussian kernel (default: (1.5, 1.5))
reduction: a method to reduce metric score over labels.
- ``'elementwise_mean'``: takes the mean (default)
- ``'sum'``: takes the sum
- ``'none'``: no reduction will be applied
data_range: Range of the image. If ``None``, it is determined from the image (max - min)
k1: Parameter of structural similarity index measure.
k2: Parameter of structural similarity index measure.
betas: Exponent parameters for individual similarities and contrastive sensitivies returned by different image
resolutions.
normalize: When MultiScaleSSIM loss is used for training, it is desirable to use normalizes to improve the
training stability. This `normalize` argument is out of scope of the original implementation [1], and it is
adapted from https://github.com/jorge-pessoa/pytorch-msssim instead.
Raises:
ValueError:
If the image height or width is smaller then ``2 ** len(betas)``.
ValueError:
If the image height is smaller than ``(kernel_size[0] - 1) * max(1, (len(betas) - 1)) ** 2``.
ValueError:
If the image width is smaller than ``(kernel_size[0] - 1) * max(1, (len(betas) - 1)) ** 2``.
"""
sim_list: List[Tensor] = []
cs_list: List[Tensor] = []
if preds.size()[-1] < 2 ** len(betas) or preds.size()[-2] < 2 ** len(betas):
raise ValueError(
f"For a given number of `betas` parameters {len(betas)}, the image height and width dimensions must be"
f" larger than or equal to {2 ** len(betas)}."
)
_betas_div = max(1, (len(betas) - 1)) ** 2
if preds.size()[-2] // _betas_div <= kernel_size[0] - 1:
raise ValueError(
f"For a given number of `betas` parameters {len(betas)} and kernel size {kernel_size[0]},"
f" the image height must be larger than {(kernel_size[0] - 1) * _betas_div}."
)
if preds.size()[-1] // _betas_div <= kernel_size[1] - 1:
raise ValueError(
f"For a given number of `betas` parameters {len(betas)} and kernel size {kernel_size[1]},"
f" the image width must be larger than {(kernel_size[1] - 1) * _betas_div}."
)
for _ in range(len(betas)):
sim, contrast_sensitivity = _get_normalized_sim_and_cs(
preds, target, kernel_size, sigma, reduction, data_range, k1, k2, normalize
)
sim_list.append(sim)
cs_list.append(contrast_sensitivity)
preds = F.avg_pool2d(preds, (2, 2))
target = F.avg_pool2d(target, (2, 2))
sim_stack = torch.stack(sim_list)
cs_stack = torch.stack(cs_list)
if normalize == "simple":
sim_stack = (sim_stack + 1) / 2
cs_stack = (cs_stack + 1) / 2
sim_stack = sim_stack ** torch.tensor(betas, device=sim_stack.device)
cs_stack = cs_stack ** torch.tensor(betas, device=cs_stack.device)
return torch.prod(cs_stack[:-1]) * sim_stack[-1]
def multiscale_structural_similarity_index_measure(
preds: Tensor,
target: Tensor,
kernel_size: Sequence[int] = (11, 11),
sigma: Sequence[float] = (1.5, 1.5),
reduction: str = "elementwise_mean",
data_range: Optional[float] = None,
k1: float = 0.01,
k2: float = 0.03,
betas: Tuple[float, ...] = (0.0448, 0.2856, 0.3001, 0.2363, 0.1333),
normalize: Optional[Literal["relu", "simple"]] = None,
) -> Tensor:
"""Computes `MultiScaleSSIM`_, Multi-scale Structual Similarity Index Measure, which is a generalization of
Structual Similarity Index Measure by incorporating image details at different resolution scores.
Args:
preds: Predictions from model of shape `[N, C, H, W]`
target: Ground truth values of shape `[N, C, H, W]`
kernel_size: size of the gaussian kernel (default: (11, 11))
sigma: Standard deviation of the gaussian kernel (default: (1.5, 1.5))
reduction: a method to reduce metric score over labels.
- ``'elementwise_mean'``: takes the mean (default)
- ``'sum'``: takes the sum
- ``'none'``: no reduction will be applied
data_range: Range of the image. If ``None``, it is determined from the image (max - min)
k1: Parameter of structural similarity index measure.
k2: Parameter of structural similarity index measure.
betas: Exponent parameters for individual similarities and contrastive sensitivies returned by different image
resolutions.
normalize: When MultiScaleSSIM loss is used for training, it is desirable to use normalizes to improve the
training stability. This `normalize` argument is out of scope of the original implementation [1], and it is
adapted from https://github.com/jorge-pessoa/pytorch-msssim instead.
Return:
Tensor with Multi-Scale SSIM score
Raises:
TypeError:
If ``preds`` and ``target`` don't have the same data type.
ValueError:
If ``preds`` and ``target`` don't have ``BxCxHxW shape``.
ValueError:
If the length of ``kernel_size`` or ``sigma`` is not ``2``.
ValueError:
If one of the elements of ``kernel_size`` is not an ``odd positive number``.
ValueError:
If one of the elements of ``sigma`` is not a ``positive number``.
Example:
>>> from torchmetrics.functional import multiscale_structural_similarity_index_measure
>>> preds = torch.rand([1, 1, 256, 256], generator=torch.manual_seed(42))
>>> target = preds * 0.75
>>> multiscale_structural_similarity_index_measure(preds, target)
tensor(0.9558)
References:
[1] Multi-Scale Structural Similarity For Image Quality Assessment by <NAME>, <NAME> and <NAME> `MultiScaleSSIM`_
"""
if not isinstance(betas, tuple):
raise ValueError("Argument `betas` is expected to be of a type tuple.")
if isinstance(betas, tuple) and not all(isinstance(beta, float) for beta in betas):
raise ValueError("Argument `betas` is expected to be a tuple of floats.")
if normalize and normalize not in ("relu", "simple"):
raise ValueError("Argument `normalize` to be expected either `None` or one of 'relu' or 'simple'")
preds, target = _ssim_update(preds, target)
return _multiscale_ssim_compute(preds, target, kernel_size, sigma, reduction, data_range, k1, k2, betas, normalize)
| 3,523 |
1,210 | <filename>snippets/vector/sample.cpp
// Follow the Style Guide while submitting code PR.
// Style Guide => https://github.com/Bhupesh-V/30-Seconds-Of-STL/blob/master/CONTRIBUTING.md/#Style Guide
/*
Author : this must be your name ;)
Date : Date format dd/mm/yyyy
Time : Time format hh:mm
Description : description should be small & one liner.
*/
| 123 |
623 | <reponame>RADarkflow/zap-extensions<filename>addOns/pscanrulesAlpha/src/main/java/org/zaproxy/zap/extension/pscanrulesAlpha/PermissionsPolicyScanRule.java
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2019 The ZAP Development Team
*
* 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.zaproxy.zap.extension.pscanrulesAlpha;
import java.util.List;
import java.util.Map;
import net.htmlparser.jericho.Source;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.core.scanner.Plugin.AlertThreshold;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpStatusCode;
import org.zaproxy.addon.commonlib.CommonAlertTag;
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;
/**
* Permissions Policy Header Missing passive scan rule
* https://github.com/zaproxy/zaproxy/issues/4885
*/
public class PermissionsPolicyScanRule extends PluginPassiveScanner {
private static final String PERMISSIONS_POLICY_HEADER = "Permissions-Policy";
private static final String DEPRECATED_HEADER = "Feature-Policy";
private static final String MESSAGE_PREFIX = "pscanalpha.permissionspolicymissing.";
private static final Logger LOGGER = LogManager.getLogger(PermissionsPolicyScanRule.class);
private static final Map<String, String> ALERT_TAGS =
CommonAlertTag.toMap(
CommonAlertTag.OWASP_2021_A01_BROKEN_AC,
CommonAlertTag.OWASP_2017_A05_BROKEN_AC);
private static final int PLUGIN_ID = 10063;
@Override
public void scanHttpRequestSend(HttpMessage httpMessage, int id) {
// Only checking the response for this scan rule
}
@Override
public void scanHttpResponseReceive(HttpMessage httpMessage, int id, Source source) {
long start = System.currentTimeMillis();
if (!httpMessage.getResponseHeader().isHtml()
&& !httpMessage.getResponseHeader().isJavaScript()) {
return;
}
if (HttpStatusCode.isRedirection(httpMessage.getResponseHeader().getStatusCode())
&& !AlertThreshold.LOW.equals(this.getAlertThreshold())) {
return;
}
// Feature-Policy is supported by Chrome 60+, Firefox 65+, Opera 47+, but not by Internet
// Exploder or Safari
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy#Browser_compatibility
List<String> featurePolicyOptions =
httpMessage.getResponseHeader().getHeaderValues(DEPRECATED_HEADER);
List<String> permissionPolicyOptions =
httpMessage.getResponseHeader().getHeaderValues(PERMISSIONS_POLICY_HEADER);
if (!featurePolicyOptions.isEmpty()) {
newAlert()
.setRisk(Alert.RISK_LOW)
.setConfidence(Alert.CONFIDENCE_MEDIUM)
.setName(getAlertAttribute("deprecated.name"))
.setDescription(getAlertAttribute("deprecated.desc"))
.setSolution(getAlertAttribute("deprecated.soln"))
.setReference(getAlertAttribute("deprecated.refs"))
.setEvidence(DEPRECATED_HEADER)
.setCweId(16) // CWE-16: Configuration
.setWascId(15) // WASC-15: Application Misconfiguration
.raise();
} else if (permissionPolicyOptions.isEmpty()) {
newAlert()
.setRisk(Alert.RISK_LOW)
.setConfidence(Alert.CONFIDENCE_MEDIUM)
.setDescription(getAlertAttribute("desc"))
.setSolution(getAlertAttribute("soln"))
.setReference(getAlertAttribute("refs"))
.setCweId(693) // CWE-693: Protection Mechanism Failure
.setWascId(15) // WASC-15: Application Misconfiguration
.raise();
}
LOGGER.debug("\tScan of record {} took {} ms", id, System.currentTimeMillis() - start);
}
@Override
public void setParent(PassiveScanThread passiveScanThread) {
// Nothing to do.
}
@Override
public int getPluginId() {
return PLUGIN_ID;
}
@Override
public String getName() {
return Constant.messages.getString(MESSAGE_PREFIX + "name");
}
@Override
public Map<String, String> getAlertTags() {
return ALERT_TAGS;
}
private static String getAlertAttribute(String key) {
return Constant.messages.getString(MESSAGE_PREFIX + key);
}
}
| 2,138 |
4,054 | <filename>document/src/vespa/document/select/parsing_failed_exception.h
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include <vespa/vespalib/util/exception.h>
namespace document::select {
VESPA_DEFINE_EXCEPTION(ParsingFailedException, vespalib::Exception);
}
| 113 |
5,169 | {
"name": "ZGPicturePickerManager",
"version": "3.0.0",
"summary": "从相册选择图片,包含图片裁剪功能",
"description": "select photo with clip function",
"homepage": "https://github.com/MR-Zong/ZGPicturePickerManager",
"license": {
"type": "MIT",
"file": "FILE_LICENSE"
},
"authors": {
"ZongGenXu": "<EMAIL>"
},
"social_media_url": "https://github.com/MR-Zong",
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/MR-Zong/ZGPicturePickerManager.git",
"tag": "3.0.0"
},
"source_files": "ZGPicturePickerManager/Classes/ZGPicturePickerManager/**/*.{h,m}",
"requires_arc": true
}
| 304 |
1,248 | #
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 <NAME> and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free Software Foundation in version 3 of the License.
#
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
# this file, see <https://pretix.eu/about/en/license>.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
#
from django.conf import settings
from django.http import StreamingHttpResponse
class ChunkBasedFileResponse(StreamingHttpResponse):
block_size = 4096
def __init__(self, streaming_content=(), *args, **kwargs):
filelike = streaming_content
streaming_content = streaming_content.chunks(self.block_size)
super().__init__(streaming_content, *args, **kwargs)
self['Content-Length'] = filelike.size
def get_client_ip(request):
ip = request.META.get('REMOTE_ADDR')
if settings.TRUST_X_FORWARDED_FOR:
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
return ip
| 577 |
5,166 | <reponame>iconara/aws-doc-sdk-examples
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Stub functions that are used by the Amazon EMR unit tests.
When tests are run against an actual AWS account, the stubber class does not
set up stubs and passes all calls through to the Boto3 client.
"""
from test_tools.example_stubber import ExampleStubber
class EmrStubber(ExampleStubber):
"""
A class that implements a variety of stub functions that are used by the
Amazon EMR unit tests.
The stubbed functions all expect certain parameters to be passed to them as
part of the tests, and will raise errors when the actual parameters differ from
the expected.
"""
def __init__(self, client, use_stubs=True):
"""
Initializes the object with a specific client and configures it for
stubbing or AWS passthrough.
:param client: A Boto3 EMR client.
:param use_stubs: When True, use stubs to intercept requests. Otherwise,
pass requests through to AWS.
"""
super().__init__(client, use_stubs)
def stub_run_job_flow(
self, name, log_uri, release, instance_type, instance_count, keep_alive,
steps, applications, job_flow_role_name, service_role_name, security_groups,
cluster_id, error_code=None):
expected_params = {
'Name': name,
'LogUri': log_uri,
'ReleaseLabel': release,
'Instances': {
'MasterInstanceType': instance_type,
'SlaveInstanceType': instance_type,
'InstanceCount': instance_count,
'KeepJobFlowAliveWhenNoSteps': keep_alive,
'EmrManagedMasterSecurityGroup': security_groups['manager'].id,
'EmrManagedSlaveSecurityGroup': security_groups['worker'].id,
},
'Steps': [{
'Name': step['name'],
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 'command-runner.jar',
'Args': ['spark-submit', '--deploy-mode', 'cluster',
step['script_uri'], *step['script_args']]
}
} for step in steps],
'Applications': [{
'Name': app
} for app in applications],
'JobFlowRole': job_flow_role_name,
'ServiceRole': service_role_name,
'EbsRootVolumeSize': 10,
'VisibleToAllUsers': True
}
response = {'JobFlowId': cluster_id}
self._stub_bifurcator(
'run_job_flow', expected_params, response, error_code=error_code)
def stub_describe_cluster(self, cluster_id, cluster, error_code=None):
expected_params = {'ClusterId': cluster_id}
response = {'Cluster': cluster}
self._stub_bifurcator(
'describe_cluster', expected_params, response, error_code=error_code)
def stub_terminate_job_flows(self, cluster_ids, error_code=None):
expected_params = {'JobFlowIds': cluster_ids}
self._stub_bifurcator(
'terminate_job_flows', expected_params, error_code=error_code)
def stub_list_steps(self, cluster_id, steps, error_code=None):
expected_params = {'ClusterId': cluster_id}
response = {'Steps': steps}
self._stub_bifurcator(
'list_steps', expected_params, response, error_code=error_code)
def stub_add_job_flow_steps(self, cluster_id, steps, step_ids, error_code=None):
expected_params = {
'JobFlowId': cluster_id,
'Steps': []
}
for step in steps:
if step['type'] == 'emrfs':
expected_params['Steps'].append({
'Name': step['name'],
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 'command-runner.jar',
'Args': ['/usr/bin/emrfs', step['command'], step['bucket_url']]
}
})
elif step['type'] == 'spark':
expected_params['Steps'].append({
'Name': step['name'],
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 'command-runner.jar',
'Args': ['spark-submit', '--deploy-mode', 'cluster',
step['script_uri'], *step['script_args']]
}
})
response = {'StepIds': step_ids}
self._stub_bifurcator(
'add_job_flow_steps', expected_params, response, error_code=error_code)
def stub_describe_step(self, cluster_id, step, error_code=None):
expected_params = {'ClusterId': cluster_id, 'StepId': step['Id']}
response = {'Step': step}
self._stub_bifurcator(
'describe_step', expected_params, response, error_code=error_code)
def stub_list_instances(self, cluster_id, types, instance_ids, error_code=None):
expected_params = {'ClusterId': cluster_id, 'InstanceGroupTypes': types}
response = {'Instances': [{
'Ec2InstanceId': inst_id
} for inst_id in instance_ids]}
self._stub_bifurcator(
'list_instances', expected_params, response, error_code=error_code)
| 2,595 |
2,550 | <reponame>erkekin/tuist<filename>projects/tuist/fixtures/ios_app_with_sdk/Modules/StaticFramework/Sources/MyObjcppClass.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MyObjcppClass : NSObject
- (void)hello;
@end
NS_ASSUME_NONNULL_END
| 105 |
5,169 | <filename>Specs/2/d/b/AssetImportKit/1.0.8/AssetImportKit.podspec.json
{
"name": "AssetImportKit",
"version": "1.0.8",
"summary": "Swifty cross platform library (macOS, iOS) that converts Assimp supported models to SceneKit scenes.",
"description": "AssetImportKit allows you to import Assimp supported file formats directly in SceneKit at runtime. The library supports: geometry, materials (with color, embedded textures and external textures), cameras, skeletal animations, serialization to .scn format.",
"homepage": "https://github.com/eugenebokhan/AssetImportKit",
"screenshots": [
"https://github.com/eugenebokhan/AssetImportKit/raw/master/Media/AssetImportKit_Demonstration.png",
"https://github.com/eugenebokhan/AssetImportKit/raw/master/SceneKitAssetImport/Media/SceneKitAssetImport_HowToUse.png"
],
"license": {
"type": "BSD 3-Clause",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"social_media_url": "http://twitter.com/eugenebokhan",
"platforms": {
"ios": "10.3",
"osx": "10.12"
},
"swift_version": "4.2",
"source": {
"git": "https://github.com/eugenebokhan/AssetImportKit.git",
"tag": "1.0.8"
},
"source_files": "AssetImportKit/**/*.{swift}",
"preserve_paths": [
"AssetImportKit/AssetImportKit/Dependencies/**/*",
"AssetImportKit/AssetImportKit/module.modulemap"
],
"ios": {
"vendored_libraries": [
"AssetImportKit/AssetImportKit/Dependencies/Assimp/lib/iOS/libassimp-iOS.a",
"AssetImportKit/AssetImportKit/Dependencies/Assimp/lib/iOS/libIrrXML-iOS.a"
],
"libraries": [
"assimp-iOS",
"IrrXML-iOS"
],
"xcconfig": {
"SWIFT_INCLUDE_PATHS": "$(PROJECT_DIR)/AssetImportKit/AssetImportKit/AssetImportKit/",
"HEADER_SEARCH_PATHS": "$(PROJECT_DIR)/AssetImportKit/Dependencies/Assimp/include",
"ENABLE_BITCODE": "NO",
"OTHER_LDFLAGS": "-ObjC -all_load -lz -lstdc++"
}
},
"osx": {
"vendored_libraries": [
"AssetImportKit/AssetImportKit/Dependencies/Assimp/lib/macOS/libassimp-macOS.a",
"AssetImportKit/AssetImportKit/Dependencies/Assimp/lib/macOS/libIrrXML-macOS.a"
],
"libraries": [
"assimp-macOS",
"IrrXML-macOS"
],
"xcconfig": {
"SWIFT_INCLUDE_PATHS": "$(PROJECT_DIR)/AssetImportKit/AssetImportKit/AssetImportKit/",
"HEADER_SEARCH_PATHS": "$(PROJECT_DIR)/AssetImportKit/Dependencies/Assimp/include",
"ENABLE_BITCODE": "NO",
"OTHER_LDFLAGS": "-ObjC -all_load -lz -lstdc++",
"EXPANDED_CODE_SIGN_IDENTITY": "-",
"EXPANDED_CODE_SIGN_IDENTITY_NAME": "-"
}
}
}
| 1,102 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.