max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,062 | <reponame>larkov/MailTrackerBlocker<filename>MailHeaders/Catalina/MailFW/MFSearchableIndexBasicQueryResultProcessor.h
//
// Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <objc/NSObject.h>
#import <MailFW/MFSearchableIndexQueryResultProcessor-Protocol.h>
@class NSString;
@protocol MFSearchableIndexQueryResultProcessorDelegate;
@interface MFSearchableIndexBasicQueryResultProcessor : NSObject <MFSearchableIndexQueryResultProcessor>
{
BOOL _cancelled; // 8 = 0x8
id <MFSearchableIndexQueryResultProcessorDelegate> _delegate; // 16 = 0x10
}
@property(getter=isCancelled) BOOL cancelled; // @synthesize cancelled=_cancelled;
@property(nonatomic) __weak id <MFSearchableIndexQueryResultProcessorDelegate> delegate; // @synthesize delegate=_delegate;
// - (void).cxx_destruct; // IMP=0x00000000001fad9f
- (void)cancel; // IMP=0x00000000001fad4c
- (void)provider:(id)arg1 foundResults:(id)arg2; // IMP=0x00000000001fa73d
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 434 |
537 | <gh_stars>100-1000
import pytest
from turbodbc import connect
from helpers import for_one_database, get_credentials
"""
Test optional features mentioned in PEP-249 "behave" as specified
"""
@for_one_database
def test_callproc_unsupported(dsn, configuration):
cursor = connect(dsn, **get_credentials(configuration)).cursor()
with pytest.raises(AttributeError):
cursor.callproc()
@for_one_database
def test_nextset_unsupported(dsn, configuration):
cursor = connect(dsn, **get_credentials(configuration)).cursor()
with pytest.raises(AttributeError):
cursor.nextset()
| 207 |
1,799 | // Copyright (c) 2019 PaddlePaddle 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.
#include "driver/huawei_ascend_npu/optimizer/fix_op_constraints.h"
#include <cmath>
#include <vector>
#include "core/operation/expand.h"
#include "core/operation/range.h"
#include "core/operation/reduce.h"
#include "utility/debug.h"
#include "utility/logging.h"
#include "utility/modeling.h"
#include "utility/utility.h"
namespace nnadapter {
namespace huawei_ascend_npu {
/*
* ReduceMeanAsModelOutputFixScalarOutput:
* In the following cases need add op trans scalar to 1D tensor with shape[1]:
* 1. keep_dim == false && reduce_all
* 2. output operand is model output operand.
*/
static int ReduceMeanAsModelOutputFixScalarOutput(hal::Model* model,
hal::Operation* operation) {
NNADAPTER_VLOG(5) << "Enter ReduceMeanAsModelOutputFixScalarOutput";
REDUCE_OPERATION_EXTRACT_INPUTS_OUTPUTS
auto reduce_all = axes_size == input_operand->type.dimensions.count;
if (!keep_dim && reduce_all && IsModelOutputOperand(output_operand)) {
AddDummyOperation(model, output_operand);
}
return NNADAPTER_NO_ERROR;
}
static int RangeCheckAllInputsAreConstantOperands(hal::Operation* operation) {
NNADAPTER_VLOG(5) << "Enter RangeCheckAllInputsAreConstantOperands";
if (!IsOperationWithAllInputConstantOperands(operation)) {
NNADAPTER_LOG(ERROR) << "Range input operands only support constant!";
return NNADAPTER_INVALID_PARAMETER;
}
return NNADAPTER_NO_ERROR;
}
static int ExpandCheckShapeIsConstantOperand(hal::Operation* operation) {
NNADAPTER_VLOG(5) << "Enter ExpandCheckShapeIsConstantOperand";
EXPAND_OPERATION_EXTRACT_INPUTS_OUTPUTS
if (!IsConstantOperand(shape_operand)) {
NNADAPTER_LOG(ERROR) << "Expand shape operand only support constant!";
return NNADAPTER_INVALID_PARAMETER;
}
return NNADAPTER_NO_ERROR;
}
int FixOpConstraints(hal::Model* model) {
std::vector<hal::Operation*> operations =
SortOperationsInTopologicalOrder(model);
NNADAPTER_VLOG(5) << "Enter FixOpConstraints";
for (auto operation : operations) {
switch (operation->type) {
case NNADAPTER_EXPAND: {
NNADAPTER_CHECK_EQ(ExpandCheckShapeIsConstantOperand(operation),
NNADAPTER_NO_ERROR);
} break;
case NNADAPTER_RANGE: {
NNADAPTER_CHECK_EQ(RangeCheckAllInputsAreConstantOperands(operation),
NNADAPTER_NO_ERROR);
} break;
case NNADAPTER_REDUCE_MEAN: {
NNADAPTER_CHECK_EQ(
ReduceMeanAsModelOutputFixScalarOutput(model, operation),
NNADAPTER_NO_ERROR);
} break;
default:
break;
}
}
return NNADAPTER_NO_ERROR;
}
} // namespace huawei_ascend_npu
} // namespace nnadapter
| 1,277 |
27,074 | <reponame>luzhongqiu/d2l-zh<filename>static/post_latex/main.py
import os
import re
import regex
import sys
def _unnumber_chaps_and_secs(lines):
def _startswith_unnumbered(l):
UNNUMBERED = {'\\section{Summary',
'\\section{Exercise',
'\\section{Exercises'
'\\subsection{Summary',
'\\subsection{Exercise',
'\\subsection{Exercises'}
for unnum in UNNUMBERED:
if l.startswith(unnum):
return True
return False
# Preface, Installation, and Notation are unnumbered chapters
NUM_UNNUMBERED_CHAPS = 3
# Prelimilaries
TOC2_START_CHAP_NO = 5
preface_reached = False
ch2_reached = False
num_chaps = 0
for i, l in enumerate(lines):
if l.startswith('\\chapter{'):
num_chaps += 1
# Unnumber unnumbered chapters
if num_chaps <= NUM_UNNUMBERED_CHAPS:
chap_name = re.split('{|}', l)[1]
lines[i] = ('\\chapter*{' + chap_name
+ '}\\addcontentsline{toc}{chapter}{'
+ chap_name + '}\n')
# Set tocdepth to 2 after Chap 1
elif num_chaps == TOC2_START_CHAP_NO:
lines[i] = ('\\addtocontents{toc}{\\protect\\setcounter{tocdepth}{2}}\n'
+ lines[i])
# Unnumber all sections in unnumbered chapters
elif 1 <= num_chaps <= NUM_UNNUMBERED_CHAPS:
if (l.startswith('\\section') or l.startswith('\\subsection')
or l.startswith('\\subsubsection')):
lines[i] = l.replace('section{', 'section*{')
# Unnumber summary, references, exercises, qr code in numbered chapters
elif _startswith_unnumbered(l):
lines[i] = l.replace('section{', 'section*{')
# Since we inserted '\n' in some lines[i], re-build the list
lines = '\n'.join(lines).split('\n')
# If label is of chap*/index.md title, its numref is Chapter X instead of Section X
def _sec_to_chap(lines):
for i, l in enumerate(lines):
# e.g., {Section \ref{\detokenize{chapter_dlc/index:chap-dlc}}} matches
# {Section \ref{\detokenize{chapter_prelim/nd:sec-nd}}} does not match
# Note that there can be multiple {Section } in one line
longest_balanced_braces = regex.findall('\{(?>[^{}]|(?R))*\}', l)
for src in longest_balanced_braces:
if src.startswith('{Section \\ref') and 'index:' in src:
tgt = src.replace('Section \\ref', 'Chapter \\ref')
lines[i] = lines[i].replace(src, tgt)
# Remove date
def _edit_titlepage(pdf_dir):
smanual = os.path.join(pdf_dir, 'sphinxmanual.cls')
with open(smanual, 'r') as f:
lines = f.read().split('\n')
for i, l in enumerate(lines):
lines[i] = lines[i].replace('\\@date', '')
with open(smanual, 'w') as f:
f.write('\n'.join(lines))
def delete_lines(lines, deletes):
return [line for i, line in enumerate(lines) if i not in deletes]
def _delete_discussions_title(lines):
deletes = []
to_delete = False
for i, l in enumerate(lines):
if 'section*{Discussion' in l or 'section{Discussion' in l:
to_delete = True
elif to_delete and '\\sphinxincludegraphics' in l:
to_delete = False
if to_delete:
deletes.append(i)
return delete_lines(lines, deletes)
def main():
tex_file = sys.argv[1]
with open(tex_file, 'r') as f:
lines = f.read().split('\n')
_unnumber_chaps_and_secs(lines)
_sec_to_chap(lines)
#lines = _delete_discussions_title(lines)
with open(tex_file, 'w') as f:
f.write('\n'.join(lines))
pdf_dir = os.path.dirname(tex_file)
#_edit_titlepage(pdf_dir)
if __name__ == "__main__":
main()
| 1,883 |
556 | <gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.plc4x.java.bacnetip;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.messages.PlcSubscriptionResponse;
import org.apache.plc4x.java.spi.values.PlcStruct;
import org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent;
public class PassiveBacNetIpDriverManual {
public static void main(String[] args) throws Exception {
final BacNetIpDriver driver = new BacNetIpDriver();
final PlcConnection connection = driver.getConnection(
"bacnet-ip:pcap:///Users/christofer.dutz/Projects/Apache/PLC4X-Documents/BacNET/Merck/Captures/BACnet.pcapng?ede-directory-path=/Users/christofer.dutz/Projects/Apache/PLC4X-Documents/BacNET/Merck/EDE-Files");
connection.connect();
final PlcSubscriptionResponse subscriptionResponse = connection.subscriptionRequestBuilder().addEventField(
"Hurz", "*/*/*").build().execute().get();
subscriptionResponse.getSubscriptionHandle("Hurz").register(plcSubscriptionEvent -> {
PlcStruct plcStruct = (PlcStruct)
((DefaultPlcSubscriptionEvent) plcSubscriptionEvent).getValues().get("event").getValue();
System.out.println(plcStruct);
});
}
}
| 686 |
9,782 | <filename>presto-main/src/main/java/com/facebook/presto/cost/UnnestStatsRule.java
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.cost;
import com.facebook.presto.Session;
import com.facebook.presto.cost.ComposableStatsCalculator.Rule;
import com.facebook.presto.matching.Pattern;
import com.facebook.presto.spi.relation.VariableReferenceExpression;
import com.facebook.presto.sql.planner.TypeProvider;
import com.facebook.presto.sql.planner.iterative.Lookup;
import com.facebook.presto.sql.planner.plan.UnnestNode;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static com.facebook.presto.sql.planner.plan.Patterns.unnest;
public class UnnestStatsRule
implements Rule<UnnestNode>
{
private static final int UPPER_BOUND_ROW_COUNT_FOR_ESTIMATION = 1;
@Override
public Pattern<UnnestNode> getPattern()
{
return unnest();
}
@Override
public Optional<PlanNodeStatsEstimate> calculate(UnnestNode node, StatsProvider statsProvider, Lookup lookup, Session session, TypeProvider types)
{
PlanNodeStatsEstimate sourceStats = statsProvider.getStats(node.getSource());
PlanNodeStatsEstimate.Builder calculatedStats = PlanNodeStatsEstimate.builder();
if (sourceStats.getOutputRowCount() > UPPER_BOUND_ROW_COUNT_FOR_ESTIMATION) {
return Optional.empty();
}
// Since we don't have stats for cardinality about the unnest column, we cannot estimate the row count.
// However, when the source row count is low, the error would not matter much in query optimization.
// Thus we'd still populate the inaccurate numbers just so stats are populated to enable optimization
// potential.
calculatedStats.setOutputRowCount(sourceStats.getOutputRowCount());
for (VariableReferenceExpression variable : node.getReplicateVariables()) {
calculatedStats.addVariableStatistics(variable, sourceStats.getVariableStatistics(variable));
}
for (Map.Entry<VariableReferenceExpression, List<VariableReferenceExpression>> entry : node.getUnnestVariables().entrySet()) {
List<VariableReferenceExpression> unnestToVariables = entry.getValue();
VariableStatsEstimate stats = sourceStats.getVariableStatistics(entry.getKey());
for (VariableReferenceExpression variable : unnestToVariables) {
// This is a very conservative way on estimating stats after unnest. We assume each symbol
// after unnest would have as much data as the symbol before unnest. This would over
// estimate, which are more likely to mean we'd loose an optimization opportunity, but at
// least it won't cause false optimizations.
calculatedStats.addVariableStatistics(
variable,
VariableStatsEstimate.builder()
.setAverageRowSize(stats.getAverageRowSize())
.build());
}
}
if (node.getOrdinalityVariable().isPresent()) {
calculatedStats.addVariableStatistics(
node.getOrdinalityVariable().get(),
VariableStatsEstimate.builder()
.setLowValue(0)
.setNullsFraction(0)
.build());
}
return Optional.of(calculatedStats.build());
}
}
| 1,481 |
739 | <reponame>Vertver/Crinkler
#pragma once
#include <vector>
#include <string>
#include "../Compressor/ModelList.h"
#include "Hunk.h"
#include "HunkList.h"
#include "ExplicitHunkSorter.h"
enum ReuseType {
REUSE_OFF, REUSE_WRITE, REUSE_IMPROVE, REUSE_STABLE
};
static const char *ReuseTypeName(ReuseType mode) {
switch (mode) {
case REUSE_OFF:
return "OFF";
case REUSE_WRITE:
return "WRITE";
case REUSE_IMPROVE:
return "IMPROVE";
case REUSE_STABLE:
return "STABLE";
}
return "";
}
class Reuse {
ModelList4k *m_code_models;
ModelList4k *m_data_models;
std::vector<std::string> m_code_hunk_ids;
std::vector<std::string> m_data_hunk_ids;
std::vector<std::string> m_bss_hunk_ids;
int m_hashsize;
friend Reuse* LoadReuseFile(const char *filename);
friend void ExplicitHunkSorter::SortHunkList(HunkList* hunklist, Reuse *reuse);
public:
Reuse();
Reuse(const ModelList4k& code_models, const ModelList4k& data_models, const HunkList& hl, int hashsize);
const ModelList4k* GetCodeModels() const { return m_code_models; }
const ModelList4k* GetDataModels() const { return m_data_models; }
int GetHashSize() const { return m_hashsize; }
void Save(const char* filename) const;
};
Reuse* LoadReuseFile(const char *filename);
| 562 |
25,151 | <reponame>TamsilAmani/selenium
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.support.decorators;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.testing.UnitTests;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
@Category(UnitTests.class)
public class DecoratedTimeoutsTest {
private static class Fixture {
WebDriver originalDriver;
WebDriver decoratedDriver;
WebDriver.Options originalOptions;
WebDriver.Timeouts original;
WebDriver.Timeouts decorated;
public Fixture() {
original = mock(WebDriver.Timeouts.class);
originalOptions = mock(WebDriver.Options.class);
originalDriver = mock(WebDriver.class);
when(originalOptions.timeouts()).thenReturn(original);
when(originalDriver.manage()).thenReturn(originalOptions);
decoratedDriver = new WebDriverDecorator().decorate(originalDriver);
decorated = decoratedDriver.manage().timeouts();
}
}
private void verifyFunction(Consumer<WebDriver.Timeouts> f) {
Fixture fixture = new Fixture();
f.accept(fixture.decorated);
f.accept(verify(fixture.original, times(1)));
verifyNoMoreInteractions(fixture.original);
}
@Test
public void implicitlyWaitLegacy() {
verifyFunction($ -> $.implicitlyWait(10, TimeUnit.SECONDS));
}
@Test
public void implicitlyWait() {
verifyFunction($ -> $.implicitlyWait(Duration.ofSeconds(10)));
}
@Test
public void setScriptTimeoutLegacy() {
verifyFunction($ -> $.setScriptTimeout(10, TimeUnit.SECONDS));
}
@Test
public void setScriptTimeout() {
verifyFunction($ -> $.setScriptTimeout(Duration.ofSeconds(10)));
}
@Test
public void pageLoadTimeoutLegacy() {
verifyFunction($ -> $.pageLoadTimeout(10, TimeUnit.SECONDS));
}
@Test
public void pageLoadTimeout() {
verifyFunction($ -> $.pageLoadTimeout(Duration.ofSeconds(10)));
}
}
| 948 |
1,442 | #ifndef LIBA_ALLOCA_H
#define LIBA_ALLOCA_H
#define alloca(size) __builtin_alloca(size)
#endif
| 46 |
1,072 | /*
* Copyright 2016 Freelander
*
* 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.jun.elephant.ui.topic.reply;
import com.jun.elephant.entity.topic.TopicReplyEntity;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
/**
* Created by Jun on 2016/10/15.
*/
public class TopicReplyPresenter extends TopicReplyContract.Presenter {
private Observer<TopicReplyEntity> mReplyObserver = new Observer<TopicReplyEntity>() {
@Override
public void onCompleted() {
mView.onRequestEnd();
}
@Override
public void onError(Throwable e) {
mView.onRequestError(e.toString());
mView.onInternetError();
}
@Override
public void onNext(TopicReplyEntity topicReplyEntity) {
mView.replySuccess(topicReplyEntity);
}
};
@Override
public void reply(int topicId, String body) {
mRxManager.add(mModel.reply(topicId, body)
.doOnSubscribe(new Action0() {
@Override
public void call() {
mView.onRequestStart();
}
})
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(mReplyObserver));
}
}
| 795 |
2,706 | /* Copyright (c) 2013-2016 <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 "OverrideView.h"
#include <QPushButton>
#include "ConfigController.h"
#include "CoreController.h"
#ifdef M_CORE_GBA
#include "GBAOverride.h"
#include <mgba/internal/gba/gba.h>
#endif
#ifdef M_CORE_GB
#include "GBOverride.h"
#include <mgba/internal/gb/gb.h>
#endif
using namespace QGBA;
#ifdef M_CORE_GB
QList<enum GBModel> OverrideView::s_gbModelList;
QList<enum GBMemoryBankControllerType> OverrideView::s_mbcList;
#endif
OverrideView::OverrideView(ConfigController* config, QWidget* parent)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint)
, m_config(config)
{
#ifdef M_CORE_GB
if (s_mbcList.isEmpty()) {
// NB: Keep in sync with OverrideView.ui
s_mbcList.append(GB_MBC_AUTODETECT);
s_mbcList.append(GB_MBC_NONE);
s_mbcList.append(GB_MBC1);
s_mbcList.append(GB_MBC2);
s_mbcList.append(GB_MBC3);
s_mbcList.append(GB_MBC3_RTC);
s_mbcList.append(GB_MBC5);
s_mbcList.append(GB_MBC5_RUMBLE);
s_mbcList.append(GB_MBC7);
s_mbcList.append(GB_POCKETCAM);
s_mbcList.append(GB_TAMA5);
s_mbcList.append(GB_HuC3);
}
if (s_gbModelList.isEmpty()) {
// NB: Keep in sync with OverrideView.ui
s_gbModelList.append(GB_MODEL_AUTODETECT);
s_gbModelList.append(GB_MODEL_DMG);
s_gbModelList.append(GB_MODEL_SGB);
s_gbModelList.append(GB_MODEL_CGB);
s_gbModelList.append(GB_MODEL_AGB);
}
#endif
m_ui.setupUi(this);
connect(m_ui.hwAutodetect, &QAbstractButton::toggled, [this] (bool enabled) {
m_ui.hwRTC->setEnabled(!enabled);
m_ui.hwGyro->setEnabled(!enabled);
m_ui.hwLight->setEnabled(!enabled);
m_ui.hwTilt->setEnabled(!enabled);
m_ui.hwRumble->setEnabled(!enabled);
});
m_colorPickers[0] = ColorPicker(m_ui.color0, QColor(0xF8, 0xF8, 0xF8));
m_colorPickers[1] = ColorPicker(m_ui.color1, QColor(0xA8, 0xA8, 0xA8));
m_colorPickers[2] = ColorPicker(m_ui.color2, QColor(0x50, 0x50, 0x50));
m_colorPickers[3] = ColorPicker(m_ui.color3, QColor(0x00, 0x00, 0x00));
m_colorPickers[4] = ColorPicker(m_ui.color4, QColor(0xF8, 0xF8, 0xF8));
m_colorPickers[5] = ColorPicker(m_ui.color5, QColor(0xA8, 0xA8, 0xA8));
m_colorPickers[6] = ColorPicker(m_ui.color6, QColor(0x50, 0x50, 0x50));
m_colorPickers[7] = ColorPicker(m_ui.color7, QColor(0x00, 0x00, 0x00));
m_colorPickers[8] = ColorPicker(m_ui.color8, QColor(0xF8, 0xF8, 0xF8));
m_colorPickers[9] = ColorPicker(m_ui.color9, QColor(0xA8, 0xA8, 0xA8));
m_colorPickers[10] = ColorPicker(m_ui.color10, QColor(0x50, 0x50, 0x50));
m_colorPickers[11] = ColorPicker(m_ui.color11, QColor(0x00, 0x00, 0x00));
for (int colorId = 0; colorId < 12; ++colorId) {
connect(&m_colorPickers[colorId], &ColorPicker::colorChanged, this, [this, colorId](const QColor& color) {
m_gbColors[colorId] = color.rgb() | 0xFF000000;
});
}
#ifndef M_CORE_GBA
m_ui.tabWidget->removeTab(m_ui.tabWidget->indexOf(m_ui.tabGBA));
#endif
#ifndef M_CORE_GB
m_ui.tabWidget->removeTab(m_ui.tabWidget->indexOf(m_ui.tabGB));
#endif
connect(m_ui.buttonBox, &QDialogButtonBox::accepted, this, &OverrideView::saveOverride);
connect(m_ui.buttonBox, &QDialogButtonBox::rejected, this, &QWidget::close);
m_recheck.setInterval(200);
connect(&m_recheck, &QTimer::timeout, this, &OverrideView::recheck);
}
void OverrideView::setController(std::shared_ptr<CoreController> controller) {
m_controller = controller;
connect(controller.get(), &CoreController::started, this, &OverrideView::gameStarted);
connect(controller.get(), &CoreController::stopping, this, &OverrideView::gameStopped);
recheck();
}
void OverrideView::saveOverride() {
if (!m_controller) {
m_savePending = true;
return;
}
Override* override = m_controller->override();
if (!override) {
return;
}
m_config->saveOverride(*override);
}
void OverrideView::recheck() {
if (!m_controller) {
return;
}
if (m_controller->hasStarted()) {
gameStarted();
} else {
updateOverrides();
}
}
void OverrideView::updateOverrides() {
if (!m_controller) {
return;
}
#ifdef M_CORE_GBA
if (m_ui.tabWidget->currentWidget() == m_ui.tabGBA) {
std::unique_ptr<GBAOverride> gba(new GBAOverride);
memset(gba->override.id, 0, 4);
gba->override.savetype = static_cast<SavedataType>(m_ui.savetype->currentIndex() - 1);
gba->override.hardware = HW_NO_OVERRIDE;
gba->override.idleLoop = IDLE_LOOP_NONE;
gba->override.mirroring = false;
if (!m_ui.hwAutodetect->isChecked()) {
gba->override.hardware = HW_NONE;
if (m_ui.hwRTC->isChecked()) {
gba->override.hardware |= HW_RTC;
}
if (m_ui.hwGyro->isChecked()) {
gba->override.hardware |= HW_GYRO;
}
if (m_ui.hwLight->isChecked()) {
gba->override.hardware |= HW_LIGHT_SENSOR;
}
if (m_ui.hwTilt->isChecked()) {
gba->override.hardware |= HW_TILT;
}
if (m_ui.hwRumble->isChecked()) {
gba->override.hardware |= HW_RUMBLE;
}
}
if (m_ui.hwGBPlayer->isChecked()) {
gba->override.hardware |= HW_GB_PLAYER_DETECTION;
}
bool ok;
uint32_t parsedIdleLoop = m_ui.idleLoop->text().toInt(&ok, 16);
if (ok) {
gba->override.idleLoop = parsedIdleLoop;
}
if (gba->override.savetype != SAVEDATA_AUTODETECT || gba->override.hardware != HW_NO_OVERRIDE ||
gba->override.idleLoop != IDLE_LOOP_NONE) {
m_controller->setOverride(std::move(gba));
} else {
m_controller->clearOverride();
}
}
#endif
#ifdef M_CORE_GB
if (m_ui.tabWidget->currentWidget() == m_ui.tabGB) {
std::unique_ptr<GBOverride> gb(new GBOverride);
gb->override.mbc = s_mbcList[m_ui.mbc->currentIndex()];
gb->override.model = s_gbModelList[m_ui.gbModel->currentIndex()];
bool hasColor = false;
for (int i = 0; i < 12; ++i) {
gb->override.gbColors[i] = m_gbColors[i];
hasColor = hasColor || (m_gbColors[i] & 0xFF000000);
}
bool hasOverride = gb->override.mbc != GB_MBC_AUTODETECT || gb->override.model != GB_MODEL_AUTODETECT;
hasOverride = hasOverride || hasColor;
if (hasOverride) {
m_controller->setOverride(std::move(gb));
} else {
m_controller->clearOverride();
}
}
#endif
}
void OverrideView::gameStarted() {
CoreController::Interrupter interrupter(m_controller);
mCoreThread* thread = m_controller->thread();
m_ui.tabWidget->setEnabled(false);
m_recheck.start();
switch (thread->core->platform(thread->core)) {
#ifdef M_CORE_GBA
case PLATFORM_GBA: {
m_ui.tabWidget->setCurrentWidget(m_ui.tabGBA);
GBA* gba = static_cast<GBA*>(thread->core->board);
m_ui.savetype->setCurrentIndex(gba->memory.savedata.type + 1);
m_ui.hwRTC->setChecked(gba->memory.hw.devices & HW_RTC);
m_ui.hwGyro->setChecked(gba->memory.hw.devices & HW_GYRO);
m_ui.hwLight->setChecked(gba->memory.hw.devices & HW_LIGHT_SENSOR);
m_ui.hwTilt->setChecked(gba->memory.hw.devices & HW_TILT);
m_ui.hwRumble->setChecked(gba->memory.hw.devices & HW_RUMBLE);
m_ui.hwGBPlayer->setChecked(gba->memory.hw.devices & HW_GB_PLAYER_DETECTION);
if (gba->idleLoop != IDLE_LOOP_NONE) {
m_ui.idleLoop->setText(QString::number(gba->idleLoop, 16));
} else {
m_ui.idleLoop->clear();
}
break;
}
#endif
#ifdef M_CORE_GB
case PLATFORM_GB: {
m_ui.tabWidget->setCurrentWidget(m_ui.tabGB);
GB* gb = static_cast<GB*>(thread->core->board);
int mbc = s_mbcList.indexOf(gb->memory.mbcType);
if (mbc >= 0) {
m_ui.mbc->setCurrentIndex(mbc);
} else {
m_ui.mbc->setCurrentIndex(0);
}
int model = s_gbModelList.indexOf(gb->model);
if (model >= 0) {
m_ui.gbModel->setCurrentIndex(model);
} else {
m_ui.gbModel->setCurrentIndex(0);
}
break;
}
#endif
case PLATFORM_NONE:
break;
}
if (m_savePending) {
m_savePending = false;
saveOverride();
}
}
void OverrideView::gameStopped() {
m_recheck.stop();
m_controller.reset();
m_ui.tabWidget->setEnabled(true);
m_ui.savetype->setCurrentIndex(0);
m_ui.idleLoop->clear();
m_ui.mbc->setCurrentIndex(0);
m_ui.gbModel->setCurrentIndex(0);
}
| 3,617 |
22,688 | /******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include "modules/canbus/proto/chassis_detail.pb.h"
#include "modules/drivers/canbus/can_comm/protocol_data.h"
namespace apollo {
namespace canbus {
namespace neolix_edu {
class Vcuvehicleinforesponse502
: public ::apollo::drivers::canbus::ProtocolData<
::apollo::canbus::ChassisDetail> {
public:
static const int32_t ID;
Vcuvehicleinforesponse502();
void Parse(const std::uint8_t* bytes, int32_t length,
ChassisDetail* chassis) const override;
private:
// config detail: {'name': 'Vehicle_Softwareversion_Indicati', 'offset': 0.0,
// 'precision': 1.0, 'len': 24, 'is_signed_var': False, 'physical_range':
// '[0|16777215]', 'bit': 7, 'type': 'int', 'order': 'motorola',
// 'physical_unit': ''}
int vehicle_softwareversion_indicati(const std::uint8_t* bytes,
const int32_t length) const;
// config detail: {'name': 'Project', 'offset': 0.0, 'precision': 1.0, 'len':
// 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 27, 'type':
// 'int', 'order': 'motorola', 'physical_unit': ''}
int project(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'Manufacturer', 'offset': 0.0, 'precision': 1.0,
// 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 31,
// 'type': 'int', 'order': 'motorola', 'physical_unit': ''}
int manufacturer(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'Year', 'offset': 0.0, 'precision': 1.0, 'len': 8,
// 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 39, 'type':
// 'int', 'order': 'motorola', 'physical_unit': ''}
int year(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'Month', 'offset': 0.0, 'precision': 1.0, 'len': 4,
// 'is_signed_var': False, 'physical_range': '[1|12]', 'bit': 47, 'type':
// 'int', 'order': 'motorola', 'physical_unit': ''}
int month(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'Day', 'offset': 0.0, 'precision': 1.0, 'len': 5,
// 'is_signed_var': False, 'physical_range': '[1|31]', 'bit': 43, 'type':
// 'int', 'order': 'motorola', 'physical_unit': ''}
int day(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'Vehicle_Serial_Number', 'offset': 0.0,
// 'precision': 1.0, 'len': 15, 'is_signed_var': False, 'physical_range':
// '[0|32767]', 'bit': 54, 'type': 'int', 'order': 'motorola',
// 'physical_unit': ''}
int vehicle_serial_number(const std::uint8_t* bytes,
const int32_t length) const;
};
} // namespace neolix_edu
} // namespace canbus
} // namespace apollo
| 1,253 |
445 | #ifndef MULTIVERSO_KV_TABLE_H_
#define MULTIVERSO_KV_TABLE_H_
#include <unordered_map>
#include <vector>
#include "multiverso/multiverso.h"
#include "multiverso/table_interface.h"
#include "multiverso/util/log.h"
namespace multiverso {
template <typename Key, typename Val>
struct KVTableOption;
// A distributed shared std::unordered_map<Key, Val> table
// Key, Val should be the basic type
template <typename Key, typename Val>
class KVWorkerTable : public WorkerTable {
public:
explicit KVWorkerTable(const KVTableOption<Key, Val>&) {}
void Get(Key key) { WorkerTable::Get(Blob(&key, sizeof(Key))); }
void Get(std::vector<Key>& keys) {
WorkerTable::Get(Blob(&keys[0], sizeof(Key) * keys.size()));
}
void Add(Key key, Val value) {
WorkerTable::Add(Blob(&key, sizeof(Key)), Blob(&value, sizeof(Val)));
}
void Add(std::vector<Key>& keys, std::vector<Val>& vals) {
CHECK(keys.size() == vals.size());
Blob keys_blob(&keys[0], sizeof(Key) * keys.size());
Blob vals_blob(&vals[0], sizeof(Val) * vals.size());
WorkerTable::Add(keys_blob, vals_blob);
}
std::unordered_map<Key, Val>& raw() { return table_; }
int Partition(const std::vector<Blob>& kv,
MsgType, std::unordered_map<int, std::vector<Blob> >* out) override {
CHECK(kv.size() == 1 || kv.size() == 2);
CHECK_NOTNULL(out);
std::unordered_map<int, int> counts;
Blob keys = kv[0];
for (int i = 0; i < keys.size<Key>(); ++i) { // iterate as type Key
int dst = static_cast<int>(keys.As<Key>(i) % MV_NumServers());
++counts[dst];
}
for (auto& it : counts) { // Allocate memory
std::vector<Blob>& vec = (*out)[it.first];
vec.push_back(Blob(it.second * sizeof(Key)));
if (kv.size() == 2) vec.push_back(Blob(it.second * sizeof(Val)));
}
counts.clear();
for (int i = 0; i < keys.size<Key>(); ++i) {
int dst = static_cast<int>(keys.As<Key>(i) % MV_NumServers());
(*out)[dst][0].As<Key>(counts[dst]) = keys.As<Key>(i);
if (kv.size() == 2)
(*out)[dst][1].As<Val>(counts[dst]) = kv[1].As<Val>(i);
++counts[dst];
}
return static_cast<int>(out->size());
}
void ProcessReplyGet(std::vector<Blob>& data) override {
CHECK(data.size() == 2);
Blob keys = data[0], vals = data[1];
CHECK(keys.size<Key>() == vals.size<Val>());
for (int i = 0; i < keys.size<Key>(); ++i) {
table_[keys.As<Key>(i)] = vals.As<Val>(i);
}
}
private:
std::unordered_map<Key, Val> table_;
};
template <typename Key, typename Val>
class KVServerTable : public ServerTable {
public:
explicit KVServerTable(const KVTableOption<Key, Val>&) {}
void ProcessGet(const std::vector<Blob>& data,
std::vector<Blob>* result) override {
CHECK(data.size() == 1);
CHECK_NOTNULL(result);
Blob keys = data[0];
result->push_back(keys); // also push the key
result->push_back(Blob(keys.size<Key>() * sizeof(Val)));
Blob& vals = (*result)[1];
for (int i = 0; i < keys.size<Key>(); ++i) {
vals.As<Val>(i) = table_[keys.As<Key>(i)];
}
}
void ProcessAdd(const std::vector<Blob>& data) override {
CHECK(data.size() == 2);
Blob keys = data[0], vals = data[1];
CHECK(keys.size<Key>() == vals.size<Val>());
for (int i = 0; i < keys.size<Key>(); ++i) {
table_[keys.As<Key>(i)] += vals.As<Val>(i);
}
}
void Store(Stream*) override {
Log::Fatal("Not implemented yet\n");
}
void Load(Stream*) override {
Log::Fatal("Not implemented yet\n");
}
private:
std::unordered_map<Key, Val> table_;
};
template <typename Key, typename Val>
struct KVTableOption {
typedef KVWorkerTable<Key, Val> WorkerTableType;
typedef KVServerTable<Key, Val> ServerTableType;
};
} // namespace multiverso
#endif // MULTIVERSO_KV_TABLE_H_
| 1,631 |
1,194 | package ca.uhn.fhir.cql.dstu3.evaluation;
/*-
* #%L
* HAPI FHIR JPA Server - Clinical Quality Language
* %%
* Copyright (C) 2014 - 2022 Smile CDR, 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.
* #L%
*/
import ca.uhn.fhir.i18n.Msg;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.cql.common.provider.EvaluationProviderFactory;
import ca.uhn.fhir.cql.common.retrieve.JpaFhirRetrieveProvider;
import ca.uhn.fhir.jpa.api.dao.DaoRegistry;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import org.opencds.cqf.cql.engine.data.CompositeDataProvider;
import org.opencds.cqf.cql.engine.data.DataProvider;
import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver;
import org.opencds.cqf.cql.engine.model.ModelResolver;
import org.opencds.cqf.cql.engine.terminology.TerminologyProvider;
import org.opencds.cqf.cql.evaluator.engine.terminology.PrivateCachingTerminologyProviderDecorator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
// This class is a relatively dumb factory for data providers. It supports only
// creating JPA providers for FHIR and only basic auth for terminology
@Component
public class ProviderFactory implements EvaluationProviderFactory {
private final DaoRegistry registry;
private final TerminologyProvider defaultTerminologyProvider;
private final FhirContext fhirContext;
private final ModelResolver fhirModelResolver;
@Autowired
public ProviderFactory(FhirContext fhirContext, DaoRegistry registry,
TerminologyProvider defaultTerminologyProvider, ModelResolver fhirModelResolver) {
this.defaultTerminologyProvider = defaultTerminologyProvider;
this.registry = registry;
this.fhirContext = fhirContext;
this.fhirModelResolver = fhirModelResolver;
}
public DataProvider createDataProvider(String model, String version, RequestDetails theRequestDetails) {
return this.createDataProvider(model, version, null, null, null, theRequestDetails);
}
public DataProvider createDataProvider(String model, String version, String url, String user, String pass, RequestDetails theRequestDetails) {
TerminologyProvider terminologyProvider = this.createTerminologyProvider(model, version, url, user, pass);
return this.createDataProvider(model, version, terminologyProvider, theRequestDetails);
}
public DataProvider createDataProvider(String model, String version, TerminologyProvider terminologyProvider, RequestDetails theRequestDetails) {
if (model.equals("FHIR") && version.startsWith("3")) {
JpaFhirRetrieveProvider retrieveProvider = new JpaFhirRetrieveProvider(this.registry,
new SearchParameterResolver(this.fhirContext), theRequestDetails);
retrieveProvider.setTerminologyProvider(terminologyProvider);
retrieveProvider.setExpandValueSets(true);
return new CompositeDataProvider(this.fhirModelResolver, retrieveProvider);
}
throw new IllegalArgumentException(Msg.code(1650) + String.format("Can't construct a data provider for model %s version %s", model, version));
}
public TerminologyProvider createTerminologyProvider(String model, String version, String url, String user,
String pass) {
TerminologyProvider terminologyProvider = null;
terminologyProvider = this.defaultTerminologyProvider;
return new PrivateCachingTerminologyProviderDecorator(terminologyProvider);
}
}
| 1,185 |
3,294 | // This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#pragma once
#include "IconComboBox.h"
/////////////////////////////////////////////////////////////////////////////
// CDesktopAlertDemoDlg dialog
class CDesktopAlertDemoDlg : public CDialogEx
{
// Construction
public:
CDesktopAlertDemoDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
// <snippet2>
enum { IDD = IDD_ALERT_DIALOG };
CSliderCtrl m_wndAutoCloseTime;
CEdit m_wndText;
CEdit m_wndLink;
CStatic m_wndLabel3;
CStatic m_wndLabel2;
CStatic m_wndLabel1;
CIconComboBox m_wndIcons;
CSliderCtrl m_wndTransparency;
CSliderCtrl m_wndANimationSpeed;
int m_nVisualMngr;
int m_nAnimation;
int m_nAnimationSpeed;
CString m_strAnimSpeed;
int m_nTransparency;
CString m_strTransparency;
BOOL m_bSmallCaption;
int m_nPopupSource;
int m_nIcon;
CString m_strLink;
CString m_strText;
int m_nAutoCloseTime;
CString m_strAutoClose;
BOOL m_bAutoClose;
// </snippet2>
// ClassWizard generated virtual function overrides
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
CMenu m_menuPopup;
CPoint m_ptPopup;
CMFCToolBarImages m_Icons;
CMFCToolBarImages m_IconsSmall;
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnShow();
afx_msg void OnSelchangeVisualMngr();
afx_msg void OnSelchangeAnimation();
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnSmallCaption();
afx_msg void OnPopupSource();
afx_msg void OnAutoClose();
afx_msg LRESULT OnClosePopup(WPARAM,LPARAM);
DECLARE_MESSAGE_MAP()
void EnableControls (BOOL bEnable = TRUE);
void EnableSourceControls ();
};
| 791 |
1,576 | package org.commonmark.internal.inline;
import org.commonmark.node.SourceSpan;
import org.commonmark.parser.SourceLine;
import org.commonmark.parser.SourceLines;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.Assert.*;
public class ScannerTest {
@Test
public void testNext() {
Scanner scanner = new Scanner(Collections.singletonList(
SourceLine.of("foo bar", null)),
0, 4);
assertEquals('b', scanner.peek());
scanner.next();
assertEquals('a', scanner.peek());
scanner.next();
assertEquals('r', scanner.peek());
scanner.next();
assertEquals('\0', scanner.peek());
}
@Test
public void testMultipleLines() {
Scanner scanner = new Scanner(Arrays.asList(
SourceLine.of("ab", null),
SourceLine.of("cde", null)),
0, 0);
assertTrue(scanner.hasNext());
assertEquals('\0', scanner.peekPreviousCodePoint());
assertEquals('a', scanner.peek());
scanner.next();
assertTrue(scanner.hasNext());
assertEquals('a', scanner.peekPreviousCodePoint());
assertEquals('b', scanner.peek());
scanner.next();
assertTrue(scanner.hasNext());
assertEquals('b', scanner.peekPreviousCodePoint());
assertEquals('\n', scanner.peek());
scanner.next();
assertTrue(scanner.hasNext());
assertEquals('\n', scanner.peekPreviousCodePoint());
assertEquals('c', scanner.peek());
scanner.next();
assertTrue(scanner.hasNext());
assertEquals('c', scanner.peekPreviousCodePoint());
assertEquals('d', scanner.peek());
scanner.next();
assertTrue(scanner.hasNext());
assertEquals('d', scanner.peekPreviousCodePoint());
assertEquals('e', scanner.peek());
scanner.next();
assertFalse(scanner.hasNext());
assertEquals('e', scanner.peekPreviousCodePoint());
assertEquals('\0', scanner.peek());
}
@Test
public void testCodePoints() {
Scanner scanner = new Scanner(Arrays.asList(SourceLine.of("\uD83D\uDE0A", null)), 0, 0);
assertTrue(scanner.hasNext());
assertEquals('\0', scanner.peekPreviousCodePoint());
assertEquals(128522, scanner.peekCodePoint());
scanner.next();
// This jumps chars, not code points. So jump two here
scanner.next();
assertFalse(scanner.hasNext());
assertEquals(128522, scanner.peekPreviousCodePoint());
assertEquals('\0', scanner.peekCodePoint());
}
@Test
public void testTextBetween() {
Scanner scanner = new Scanner(Arrays.asList(
SourceLine.of("ab", SourceSpan.of(10, 3, 2)),
SourceLine.of("cde", SourceSpan.of(11, 4, 3))),
0, 0);
Position start = scanner.position();
scanner.next();
assertSourceLines(scanner.getSource(start, scanner.position()),
"a",
SourceSpan.of(10, 3, 1));
Position afterA = scanner.position();
scanner.next();
assertSourceLines(scanner.getSource(start, scanner.position()),
"ab",
SourceSpan.of(10, 3, 2));
Position afterB = scanner.position();
scanner.next();
assertSourceLines(scanner.getSource(start, scanner.position()),
"ab\n",
SourceSpan.of(10, 3, 2));
scanner.next();
assertSourceLines(scanner.getSource(start, scanner.position()),
"ab\nc",
SourceSpan.of(10, 3, 2),
SourceSpan.of(11, 4, 1));
scanner.next();
assertSourceLines(scanner.getSource(start, scanner.position()),
"ab\ncd",
SourceSpan.of(10, 3, 2),
SourceSpan.of(11, 4, 2));
scanner.next();
assertSourceLines(scanner.getSource(start, scanner.position()),
"ab\ncde",
SourceSpan.of(10, 3, 2),
SourceSpan.of(11, 4, 3));
assertSourceLines(scanner.getSource(afterA, scanner.position()),
"b\ncde",
SourceSpan.of(10, 4, 1),
SourceSpan.of(11, 4, 3));
assertSourceLines(scanner.getSource(afterB, scanner.position()),
"\ncde",
SourceSpan.of(11, 4, 3));
}
private void assertSourceLines(SourceLines sourceLines, String expectedContent, SourceSpan... expectedSourceSpans) {
assertEquals(expectedContent, sourceLines.getContent());
assertEquals(Arrays.asList(expectedSourceSpans), sourceLines.getSourceSpans());
}
@Test
public void nextString() {
Scanner scanner = Scanner.of(SourceLines.of(Arrays.asList(
SourceLine.of("hey ya", null),
SourceLine.of("hi", null))));
assertFalse(scanner.next("hoy"));
assertTrue(scanner.next("hey"));
assertTrue(scanner.next(' '));
assertFalse(scanner.next("yo"));
assertTrue(scanner.next("ya"));
assertFalse(scanner.next(" "));
}
}
| 2,412 |
396 | package com.mapbox.turf;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.GeoJson;
import com.mapbox.geojson.Point;
/**
* Also called Assertions, these methods enforce expectations of a certain type or calculate various
* shapes from given points.
*
* @see <a href="http://turfjs.org/docs/">Turf documentation</a>
* @since 1.2.0
*/
public final class TurfAssertions {
private TurfAssertions() {
// Private constructor preventing initialization of this class
}
/**
* Unwrap a coordinate {@link Point} from a Feature with a Point geometry.
*
* @param obj any value
* @return a coordinate
* @see <a href="http://turfjs.org/docs/#getcoord">Turf getCoord documentation</a>
* @since 1.2.0
* @deprecated use {@link TurfMeta#getCoord(Feature)}
*/
@Deprecated
public static Point getCoord(Feature obj) {
return TurfMeta.getCoord(obj);
}
/**
* Enforce expectations about types of GeoJson objects for Turf.
*
* @param value any GeoJson object
* @param type expected GeoJson type
* @param name name of calling function
* @see <a href="http://turfjs.org/docs/#geojsontype">Turf geojsonType documentation</a>
* @since 1.2.0
*/
public static void geojsonType(GeoJson value, String type, String name) {
if (type == null || type.length() == 0 || name == null || name.length() == 0) {
throw new TurfException("Type and name required");
}
if (value == null || !value.type().equals(type)) {
throw new TurfException("Invalid input to " + name + ": must be a " + type
+ ", given " + (value != null ? value.type() : " null"));
}
}
/**
* Enforce expectations about types of {@link Feature} inputs for Turf. Internally this uses
* {@link Feature#type()} to judge geometry types.
*
* @param feature with an expected geometry type
* @param type type expected GeoJson type
* @param name name of calling function
* @see <a href="http://turfjs.org/docs/#featureof">Turf featureOf documentation</a>
* @since 1.2.0
*/
public static void featureOf(Feature feature, String type, String name) {
if (name == null || name.length() == 0) {
throw new TurfException(".featureOf() requires a name");
}
if (feature == null || !feature.type().equals("Feature") || feature.geometry() == null) {
throw new TurfException(String.format(
"Invalid input to %s, Feature with geometry required", name));
}
if (feature.geometry() == null || !feature.geometry().type().equals(type)) {
throw new TurfException(String.format(
"Invalid input to %s: must be a %s, given %s", name, type, feature.geometry().type()));
}
}
/**
* Enforce expectations about types of {@link FeatureCollection} inputs for Turf. Internally
* this uses {@link Feature#type()}} to judge geometry types.
*
* @param featureCollection for which features will be judged
* @param type expected GeoJson type
* @param name name of calling function
* @see <a href="http://turfjs.org/docs/#collectionof">Turf collectionOf documentation</a>
* @since 1.2.0
*/
public static void collectionOf(FeatureCollection featureCollection, String type, String name) {
if (name == null || name.length() == 0) {
throw new TurfException("collectionOf() requires a name");
}
if (featureCollection == null || !featureCollection.type().equals("FeatureCollection")
|| featureCollection.features() == null) {
throw new TurfException(String.format(
"Invalid input to %s, FeatureCollection required", name));
}
for (Feature feature : featureCollection.features()) {
if (feature == null || !feature.type().equals("Feature") || feature.geometry() == null) {
throw new TurfException(String.format(
"Invalid input to %s, Feature with geometry required", name));
}
if (feature.geometry() == null || !feature.geometry().type().equals(type)) {
throw new TurfException(String.format(
"Invalid input to %s: must be a %s, given %s", name, type, feature.geometry().type()));
}
}
}
}
| 1,448 |
322 | <gh_stars>100-1000
#pragma once
#include <database.h>
#include <widgets.h>
#include <QSettings>
/** Settings UI namespace. */
/*namespace Ui {
class Settings;
}*/
/** Settings class.
* Class to handle the settings section of the launcher
*/
class Settings : public QWidget
{
Q_OBJECT
public:
explicit Settings(QWidget* parent, QSettings* p);
~Settings();
public slots:
void rerunGameWizard();
void clearDatabase();
void setLightAccent();
void setMediumAccent();
void setDarkAccent();
void resetAccents();
void updateAccent(int accent, QColor color);
private:
QPushButton* accentButton_1;
QPushButton* accentButton_2;
QPushButton* accentButton_3;
QPushButton* textColourButton_1;
QPushButton* textColourButton_2;
QPushButton* textColourButton_3;
};
| 297 |
1,694 | <gh_stars>1000+
//
// 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>
#import "IRemoteControlCheckExt-Protocol.h"
@interface MMMusicPlayerSessionMgr : NSObject <IRemoteControlCheckExt>
{
}
+ (id)sharedMusicPlayerSessionMgr;
- (void)iRemoteControlCheckShouldPrevTrack;
- (void)iRemoteControlCheckShouldNextTrack;
- (void)iRemoteControlCheckPluginOff;
- (void)iRemoteControlCheckShouldStop;
- (void)iRemoteControlCheckShouldPlayOrPause;
- (void)iRemoteControlCheckShouldPause;
- (void)iRemoteControlCheckShouldPlay;
- (void)notifyNewPlayStateChange:(id)arg1;
- (void)endNewMusicPlayerAudioSession:(id)arg1;
- (void)beginNewMusicPlayerAudioSession:(id)arg1;
- (void)notifyPlayStateChange:(id)arg1;
- (void)endMusicPlayerAudioSession:(id)arg1;
- (void)beginMusicPlayerAudioSession:(id)arg1;
- (void)dealloc;
- (id)init;
@end
| 349 |
359 | // Copyright Xilinx, Inc 2014-2016
// Author: <NAME>
// Register definition for the APPMGMT
#ifndef __AWSMGMT_CW_H__
#define __AWSMGMT_CW_H__
#define OCL_CTLR_OFFSET 0x000000
#define AXI_GATE_OFFSET 0x030000
#define AXI_GATE_OFFSET_READ 0x030008
#define FEATURE_ID 0x031000
#define GENERAL_STATUS 0x032000
#define OCL_CLKWIZ_OFFSET 0x050000
#define OCL_CLKWIZ_BASEADDR 0x050000
#define OCL_CLKWIZ_BASEADDR2 0x051000
#define OCL_CLKWIZ_SYSCLOCK 0x052000
#define OCL_CLKWIZ_STATUS_OFFSET 0x4
#define OCL_CLKWIZ_CONFIG_OFFSET(n) (0x200 + 4 * (n))
// These are kept only for backwards compatipility. These macros should
// not be used anymore.
#define OCL_CLKWIZ_STATUS (OCL_CLKWIZ_BASEADDR + OCL_CLKWIZ_STATUS_OFFSET)
#define OCL_CLKWIZ_CONFIG(n) (OCL_CLKWIZ_BASEADDR + OCL_CLKWIZ_CONFIG_OFFSET(n))
/************************** Constant Definitions ****************************/
/* Input frequency */
#define AMAZON_INPUT_FREQ 250
#define OCL_CU_CTRL_RANGE 0x1000
#define APPMGMT_7V3_CLKWIZ_CONFIG0 0x04000a01
#define APPMGMT_KU3_CLKWIZ_CONFIG0 0x04000a01
#endif
| 584 |
1,174 | <reponame>RANGERERIC2/EMV-NFC-Paycard-Enrollment<gh_stars>1000+
package com.github.devnied.emvnfccard.utils;
import java.text.SimpleDateFormat;
import org.fest.assertions.Assertions;
import org.junit.Test;
import com.github.devnied.emvnfccard.model.EmvTrack1;
import com.github.devnied.emvnfccard.model.EmvTrack2;
import com.github.devnied.emvnfccard.model.enums.ServiceCode1Enum;
import com.github.devnied.emvnfccard.model.enums.ServiceCode2Enum;
import com.github.devnied.emvnfccard.model.enums.ServiceCode3Enum;
import fr.devnied.bitlib.BytesUtils;
public class TrackUtilsTest {
@Test
public void track1Test() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42343131313131313131313131313131313F305E202F5E31373032323031313030333F313030313030303030303030303030303F"));
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("28/02/2017");
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
@Test
public void track1NameTest() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42343131313131313131313131313131313F305E446F652F4A6F686E5E31373032323031313030333F313030313030303030303030303030303F"));
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("28/02/2017");
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getHolderFirstname()).isEqualTo("John");
Assertions.assertThat(track1.getHolderLastname()).isEqualTo("Doe");
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
@Test
public void track1FormatTest() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42353231313131313131313131313131315E202F2020202020202020202020202020202020202020202020205E31363038323032303030303030303030303030312020303030202020202030"));
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getCardNumber()).isEqualTo("5211111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("31/08/2016");
Assertions.assertThat(track1.getHolderFirstname()).isNull();
Assertions.assertThat(track1.getHolderLastname()).isNull();
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.GOODS_SERVICES);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
@Test
public void track1FormatNullUser() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42353231313131313131313131313131315E22202020202020202020202020202020202020202020202020205E31363038323032303030303030303030303030312020303030202020202030"));
Assertions.assertThat(track1.getCardNumber()).isEqualTo("5211111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("31/08/2016 00:00:00");
Assertions.assertThat(track1.getHolderFirstname()).isNull();
Assertions.assertThat(track1.getHolderLastname()).isNull();
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.GOODS_SERVICES);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
@Test
public void track2EquivalentTest() {
EmvTrack2 track2 = TrackUtils.extractTrack2EquivalentData(BytesUtils.fromString("55 66 88 77 66 55 66 77 D1 50 62 01 69 28 07 65 90 00 0F"));
Assertions.assertThat(track2).isNotNull();
Assertions.assertThat(track2.getCardNumber()).isEqualTo("5566887766556677");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Assertions.assertThat(sdf.format(track2.getExpireDate())).isEqualTo("30/06/2015");
Assertions.assertThat(track2.getService()).isNotNull();
Assertions.assertThat(track2.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track2.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track2.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track2.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track2.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track2.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(track2.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track2.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
@Test
public void track2EquivalentTest2() {
EmvTrack2 track2 = TrackUtils.extractTrack2EquivalentData(BytesUtils.fromString("55 55 55 66 88 77 66 55 66 7D 11 05 62 01 69 28 07 65 90 00 0F"));
Assertions.assertThat(track2).isNotNull();
Assertions.assertThat(track2.getCardNumber()).isEqualTo("5555556688776655667");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Assertions.assertThat(sdf.format(track2.getExpireDate())).isEqualTo("31/05/2011");
Assertions.assertThat(track2.getService()).isNotNull();
Assertions.assertThat(track2.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.NATIONAL_ICC);
Assertions.assertThat(track2.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.BY_ISSUER);
Assertions.assertThat(track2.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION_PIN_REQUIRED);
}
@Test
public void track2EquivalentTestNullService() {
EmvTrack2 track2 = TrackUtils.extractTrack2EquivalentData(BytesUtils.fromString("55 55 55 66 88 77 66 55 66 7D 11 05 FF F1 69 28 07 65 90 00 0F"));
Assertions.assertThat(track2).isNotNull();
Assertions.assertThat(track2.getCardNumber()).isEqualTo("5555556688776655667");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Assertions.assertThat(sdf.format(track2.getExpireDate())).isEqualTo("31/05/2011");
Assertions.assertThat(track2.getService()).isNotNull();
Assertions.assertThat(track2.getService().getServiceCode1()).isNull();
Assertions.assertThat(track2.getService().getServiceCode2()).isNull();
Assertions.assertThat(track2.getService().getServiceCode3()).isNull();
}
@Test
public void track2EquivalentTestNull() {
EmvTrack2 card = TrackUtils.extractTrack2EquivalentData(BytesUtils.fromString("00"));
Assertions.assertThat(card).isNull();
}
}
| 3,626 |
574 | <reponame>virtualpathum/collect
package org.odk.collect.android.adapters;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import org.odk.collect.android.fragments.BlankFormListFragment;
import org.odk.collect.android.fragments.SavedFormListFragment;
public class DeleteFormsTabsAdapter extends FragmentStateAdapter {
private final boolean matchExactlyEnabled;
public DeleteFormsTabsAdapter(FragmentActivity fa, boolean matchExactlyEnabled) {
super(fa);
this.matchExactlyEnabled = matchExactlyEnabled;
}
@NonNull
@Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new SavedFormListFragment();
case 1:
return new BlankFormListFragment();
default:
// should never reach here
throw new IllegalArgumentException("Fragment position out of bounds");
}
}
@Override
public int getItemCount() {
if (matchExactlyEnabled) {
return 1;
} else {
return 2;
}
}
} | 501 |
5,207 | <reponame>radekg/kratos<gh_stars>1000+
{
"keys": [
{
"use": "sig",
"kty": "RSA",
"kid": "a2aa9739-d753-4a0d-87ee-61f101050277",
"alg": "RS256",
"n": "<KEY>",
"e": "AQAB",
"d": "<KEY>",
"p": "<KEY>",
"q": "<KEY>",
"dp": "<KEY>",
"dq": "<KEY>",
"qi": "<KEY>"
}
]
}
| 219 |
14,668 | <reponame>zealoussnow/chromium
// Copyright 2016 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 <utility>
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/test_support/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/rrect_f.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/gfx/mojom/accelerated_widget_mojom_traits.h"
#include "ui/gfx/mojom/buffer_types_mojom_traits.h"
#include "ui/gfx/mojom/presentation_feedback.mojom.h"
#include "ui/gfx/mojom/presentation_feedback_mojom_traits.h"
#include "ui/gfx/mojom/traits_test_service.mojom.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/selection_bound.h"
namespace gfx {
namespace {
gfx::AcceleratedWidget CastToAcceleratedWidget(int i) {
#if defined(USE_OZONE) || defined(OS_APPLE)
return static_cast<gfx::AcceleratedWidget>(i);
#else
return reinterpret_cast<gfx::AcceleratedWidget>(i);
#endif
}
class StructTraitsTest : public testing::Test, public mojom::TraitsTestService {
public:
StructTraitsTest() {}
StructTraitsTest(const StructTraitsTest&) = delete;
StructTraitsTest& operator=(const StructTraitsTest&) = delete;
protected:
mojo::Remote<mojom::TraitsTestService> GetTraitsTestRemote() {
mojo::Remote<mojom::TraitsTestService> remote;
traits_test_receivers_.Add(this, remote.BindNewPipeAndPassReceiver());
return remote;
}
private:
// TraitsTestService:
void EchoSelectionBound(const SelectionBound& s,
EchoSelectionBoundCallback callback) override {
std::move(callback).Run(s);
}
void EchoTransform(const Transform& t,
EchoTransformCallback callback) override {
std::move(callback).Run(t);
}
void EchoGpuMemoryBufferHandle(
GpuMemoryBufferHandle handle,
EchoGpuMemoryBufferHandleCallback callback) override {
std::move(callback).Run(std::move(handle));
}
void EchoRRectF(const RRectF& r, EchoRRectFCallback callback) override {
std::move(callback).Run(r);
}
base::test::TaskEnvironment task_environment_;
mojo::ReceiverSet<TraitsTestService> traits_test_receivers_;
};
} // namespace
TEST_F(StructTraitsTest, SelectionBound) {
const gfx::SelectionBound::Type type = gfx::SelectionBound::CENTER;
const gfx::PointF edge_start(1234.5f, 5678.6f);
const gfx::PointF edge_end(910112.5f, 13141516.6f);
const bool visible = true;
gfx::SelectionBound input;
input.set_type(type);
input.SetEdge(edge_start, edge_end);
input.set_visible(visible);
mojo::Remote<mojom::TraitsTestService> remote = GetTraitsTestRemote();
gfx::SelectionBound output;
remote->EchoSelectionBound(input, &output);
EXPECT_EQ(type, output.type());
EXPECT_EQ(edge_start, output.edge_start());
EXPECT_EQ(edge_end, output.edge_end());
EXPECT_EQ(input.edge_start_rounded(), output.edge_start_rounded());
EXPECT_EQ(input.edge_end_rounded(), output.edge_end_rounded());
EXPECT_EQ(visible, output.visible());
}
TEST_F(StructTraitsTest, Transform) {
const float col1row1 = 1.f;
const float col2row1 = 2.f;
const float col3row1 = 3.f;
const float col4row1 = 4.f;
const float col1row2 = 5.f;
const float col2row2 = 6.f;
const float col3row2 = 7.f;
const float col4row2 = 8.f;
const float col1row3 = 9.f;
const float col2row3 = 10.f;
const float col3row3 = 11.f;
const float col4row3 = 12.f;
const float col1row4 = 13.f;
const float col2row4 = 14.f;
const float col3row4 = 15.f;
const float col4row4 = 16.f;
gfx::Transform input(col1row1, col2row1, col3row1, col4row1, col1row2,
col2row2, col3row2, col4row2, col1row3, col2row3,
col3row3, col4row3, col1row4, col2row4, col3row4,
col4row4);
mojo::Remote<mojom::TraitsTestService> remote = GetTraitsTestRemote();
gfx::Transform output;
remote->EchoTransform(input, &output);
EXPECT_EQ(col1row1, output.matrix().get(0, 0));
EXPECT_EQ(col2row1, output.matrix().get(0, 1));
EXPECT_EQ(col3row1, output.matrix().get(0, 2));
EXPECT_EQ(col4row1, output.matrix().get(0, 3));
EXPECT_EQ(col1row2, output.matrix().get(1, 0));
EXPECT_EQ(col2row2, output.matrix().get(1, 1));
EXPECT_EQ(col3row2, output.matrix().get(1, 2));
EXPECT_EQ(col4row2, output.matrix().get(1, 3));
EXPECT_EQ(col1row3, output.matrix().get(2, 0));
EXPECT_EQ(col2row3, output.matrix().get(2, 1));
EXPECT_EQ(col3row3, output.matrix().get(2, 2));
EXPECT_EQ(col4row3, output.matrix().get(2, 3));
EXPECT_EQ(col1row4, output.matrix().get(3, 0));
EXPECT_EQ(col2row4, output.matrix().get(3, 1));
EXPECT_EQ(col3row4, output.matrix().get(3, 2));
EXPECT_EQ(col4row4, output.matrix().get(3, 3));
}
TEST_F(StructTraitsTest, AcceleratedWidget) {
gfx::AcceleratedWidget input(CastToAcceleratedWidget(1001));
gfx::AcceleratedWidget output;
mojo::test::SerializeAndDeserialize<gfx::mojom::AcceleratedWidget>(input,
output);
EXPECT_EQ(input, output);
}
TEST_F(StructTraitsTest, GpuMemoryBufferHandle) {
const gfx::GpuMemoryBufferId kId(99);
const uint32_t kOffset = 126;
const int32_t kStride = 256;
base::UnsafeSharedMemoryRegion shared_memory_region =
base::UnsafeSharedMemoryRegion::Create(1024);
ASSERT_TRUE(shared_memory_region.IsValid());
ASSERT_TRUE(shared_memory_region.Map().IsValid());
gfx::GpuMemoryBufferHandle handle;
handle.type = gfx::SHARED_MEMORY_BUFFER;
handle.id = kId;
handle.region = shared_memory_region.Duplicate();
handle.offset = kOffset;
handle.stride = kStride;
mojo::Remote<mojom::TraitsTestService> remote = GetTraitsTestRemote();
gfx::GpuMemoryBufferHandle output;
remote->EchoGpuMemoryBufferHandle(std::move(handle), &output);
EXPECT_EQ(gfx::SHARED_MEMORY_BUFFER, output.type);
EXPECT_EQ(kId, output.id);
EXPECT_EQ(kOffset, output.offset);
EXPECT_EQ(kStride, output.stride);
base::UnsafeSharedMemoryRegion output_memory = std::move(output.region);
EXPECT_TRUE(output_memory.Map().IsValid());
#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(USE_OZONE)
gfx::GpuMemoryBufferHandle handle2;
const uint64_t kSize = kOffset + kStride;
handle2.type = gfx::NATIVE_PIXMAP;
handle2.id = kId;
handle2.offset = kOffset;
handle2.stride = kStride;
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
const uint64_t kModifier = 2;
base::ScopedFD buffer_handle;
handle2.native_pixmap_handle.modifier = kModifier;
#elif defined(OS_FUCHSIA)
zx::vmo buffer_handle;
handle2.native_pixmap_handle.buffer_collection_id =
gfx::SysmemBufferCollectionId::Create();
handle2.native_pixmap_handle.buffer_index = 4;
handle2.native_pixmap_handle.ram_coherency = true;
#endif
handle2.native_pixmap_handle.planes.emplace_back(kOffset, kStride, kSize,
std::move(buffer_handle));
remote->EchoGpuMemoryBufferHandle(std::move(handle2), &output);
EXPECT_EQ(gfx::NATIVE_PIXMAP, output.type);
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
EXPECT_EQ(kModifier, output.native_pixmap_handle.modifier);
#elif defined(OS_FUCHSIA)
EXPECT_EQ(handle2.native_pixmap_handle.buffer_collection_id,
output.native_pixmap_handle.buffer_collection_id);
EXPECT_EQ(handle2.native_pixmap_handle.buffer_index,
output.native_pixmap_handle.buffer_index);
EXPECT_EQ(handle2.native_pixmap_handle.ram_coherency,
output.native_pixmap_handle.ram_coherency);
#endif
ASSERT_EQ(1u, output.native_pixmap_handle.planes.size());
EXPECT_EQ(kSize, output.native_pixmap_handle.planes.back().size);
#endif
}
TEST_F(StructTraitsTest, NullGpuMemoryBufferHandle) {
mojo::Remote<mojom::TraitsTestService> remote = GetTraitsTestRemote();
GpuMemoryBufferHandle output;
remote->EchoGpuMemoryBufferHandle(GpuMemoryBufferHandle(), &output);
EXPECT_TRUE(output.is_null());
}
TEST_F(StructTraitsTest, BufferFormat) {
using BufferFormatTraits =
mojo::EnumTraits<gfx::mojom::BufferFormat, gfx::BufferFormat>;
BufferFormat output;
mojo::Remote<mojom::TraitsTestService> remote = GetTraitsTestRemote();
for (int i = 0; i <= static_cast<int>(BufferFormat::LAST); ++i) {
BufferFormat input = static_cast<BufferFormat>(i);
BufferFormatTraits::FromMojom(BufferFormatTraits::ToMojom(input), &output);
EXPECT_EQ(output, input);
}
}
TEST_F(StructTraitsTest, BufferUsage) {
using BufferUsageTraits =
mojo::EnumTraits<gfx::mojom::BufferUsage, gfx::BufferUsage>;
BufferUsage output;
mojo::Remote<mojom::TraitsTestService> remote = GetTraitsTestRemote();
for (int i = 0; i <= static_cast<int>(BufferUsage::LAST); ++i) {
BufferUsage input = static_cast<BufferUsage>(i);
BufferUsageTraits::FromMojom(BufferUsageTraits::ToMojom(input), &output);
EXPECT_EQ(output, input);
}
}
TEST_F(StructTraitsTest, PresentationFeedback) {
base::TimeTicks timestamp = base::TimeTicks() + base::Seconds(12);
base::TimeDelta interval = base::Milliseconds(23);
uint32_t flags =
PresentationFeedback::kVSync | PresentationFeedback::kZeroCopy;
PresentationFeedback input{timestamp, interval, flags};
input.available_timestamp = base::TimeTicks() + base::Milliseconds(20);
input.ready_timestamp = base::TimeTicks() + base::Milliseconds(21);
input.latch_timestamp = base::TimeTicks() + base::Milliseconds(22);
PresentationFeedback output;
mojo::test::SerializeAndDeserialize<gfx::mojom::PresentationFeedback>(input,
output);
EXPECT_EQ(timestamp, output.timestamp);
EXPECT_EQ(interval, output.interval);
EXPECT_EQ(flags, output.flags);
EXPECT_EQ(input.available_timestamp, output.available_timestamp);
EXPECT_EQ(input.ready_timestamp, output.ready_timestamp);
EXPECT_EQ(input.latch_timestamp, output.latch_timestamp);
}
TEST_F(StructTraitsTest, RRectF) {
gfx::RRectF input(40, 50, 60, 70, 1, 2);
input.SetCornerRadii(RRectF::Corner::kUpperRight, 3, 4);
input.SetCornerRadii(RRectF::Corner::kLowerRight, 5, 6);
input.SetCornerRadii(RRectF::Corner::kLowerLeft, 7, 8);
EXPECT_EQ(input.GetType(), RRectF::Type::kComplex);
mojo::Remote<mojom::TraitsTestService> remote = GetTraitsTestRemote();
gfx::RRectF output;
remote->EchoRRectF(input, &output);
EXPECT_EQ(input, output);
input = gfx::RRectF(40, 50, 0, 70, 0);
EXPECT_EQ(input.GetType(), RRectF::Type::kEmpty);
remote->EchoRRectF(input, &output);
EXPECT_EQ(input, output);
input = RRectF(40, 50, 60, 70, 0);
EXPECT_EQ(input.GetType(), RRectF::Type::kRect);
remote->EchoRRectF(input, &output);
EXPECT_EQ(input, output);
input = RRectF(40, 50, 60, 70, 5);
EXPECT_EQ(input.GetType(), RRectF::Type::kSingle);
remote->EchoRRectF(input, &output);
EXPECT_EQ(input, output);
input = RRectF(40, 50, 60, 70, 6, 3);
EXPECT_EQ(input.GetType(), RRectF::Type::kSimple);
remote->EchoRRectF(input, &output);
EXPECT_EQ(input, output);
input = RRectF(40, 50, 60, 70, 30, 35);
EXPECT_EQ(input.GetType(), RRectF::Type::kOval);
remote->EchoRRectF(input, &output);
EXPECT_EQ(input, output);
input.SetCornerRadii(RRectF::Corner::kUpperLeft, 50, 50);
input.SetCornerRadii(RRectF::Corner::kUpperRight, 20, 20);
input.SetCornerRadii(RRectF::Corner::kLowerRight, 0, 0);
input.SetCornerRadii(RRectF::Corner::kLowerLeft, 0, 0);
remote->EchoRRectF(input, &output);
EXPECT_EQ(input, output);
}
} // namespace gfx
| 4,757 |
1,083 | /*
* 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.carbondata.index.secondary;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.carbondata.core.index.dev.IndexModel;
import org.apache.hadoop.conf.Configuration;
/**
* Secondary Index Model. it is used to initialize the Secondary Index Coarse Grain Index
*/
public class SecondaryIndexModel extends IndexModel {
private final String indexName; // Secondary Index name
private final String currentSegmentId; // Segment Id to prune
private final List<String> validSegmentIds; // Valid segment Ids for Secondary Index pruning
private final PositionReferenceInfo positionReferenceInfo; // Position reference information
public SecondaryIndexModel(String indexName, String currentSegmentId,
List<String> validSegmentIds, PositionReferenceInfo positionReferenceInfo,
Configuration configuration) {
super(null, configuration);
this.indexName = indexName;
this.currentSegmentId = currentSegmentId;
this.validSegmentIds = validSegmentIds;
this.positionReferenceInfo = positionReferenceInfo;
}
public String getIndexName() {
return indexName;
}
public String getCurrentSegmentId() {
return currentSegmentId;
}
public List<String> getValidSegmentIds() {
return validSegmentIds;
}
public PositionReferenceInfo getPositionReferenceInfo() {
return positionReferenceInfo;
}
/**
* Position Reference information. One instance of position reference information is shared across
* all the {@link SecondaryIndex} instances for the particular query pruning with the given index
* filter. This ensures to run a single sql query to get position references from the valid
* segments of the given secondary index table with given index filter and populate them in map.
* First secondary index segment prune in the query will run the sql query for position
* references and store them in map. And subsequent segments prune in the same query can avoid
* the individual sql for position references within the respective segment and return position
* references from the map directly
*/
public static class PositionReferenceInfo {
/**
* Indicates whether position references are available or not. Initially it is false. It is set
* to true during the first secondary index segment prune after sql query for position
* references from the valid segments (passed in the {@link SecondaryIndexModel}) of the
* secondary index table. Those obtained position references are used to populate
* {@link #segmentToPosReferences} map
*/
private boolean fetched;
/**
* Map of Segment Id to set of position references within that segment. First secondary index
* segment prune populates this map and the subsequent segment prune will return the position
* references for the respective segment from this map directly without further sql query for
* position references in the segment
*/
private final Map<String, Set<String>> segmentToPosReferences = new HashMap<>();
public boolean isFetched() {
return fetched;
}
public void setFetched(boolean fetched) {
this.fetched = fetched;
}
public Map<String, Set<String>> getSegmentToPosReferences() {
return segmentToPosReferences;
}
}
}
| 1,105 |
544 | <filename>examples/tween_example.py
import pygame as pg
from itertools import cycle
import pytweening as tween
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
LIGHTGREY = (40, 40, 40)
tween_func = cycle([tween.easeInSine, tween.easeOutSine, tween.easeInOutSine,
tween.easeInCirc, tween.easeOutCirc, tween.easeInOutCirc,
tween.easeInQuart, tween.easeOutQuart, tween.easeInOutQuart,
tween.easeInQuint, tween.easeOutQuint, tween.easeInOutQuint,
tween.easeInExpo, tween.easeOutExpo, tween.easeInOutExpo,
tween.easeInElastic, tween.easeOutElastic, tween.easeInOutElastic,
tween.easeInBounce, tween.easeOutBounce, tween.easeInOutBounce])
def draw_text(text, size, color, x, y, align="nw"):
font_name = pg.font.match_font('hack')
font = pg.font.Font(font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
if align == "nw":
text_rect.topleft = (x, y)
if align == "ne":
text_rect.topright = (x, y)
if align == "sw":
text_rect.bottomleft = (x, y)
if align == "se":
text_rect.bottomright = (x, y)
if align == "n":
text_rect.midtop = (x, y)
if align == "s":
text_rect.midbottom = (x, y)
if align == "e":
text_rect.midright = (x, y)
if align == "w":
text_rect.midleft = (x, y)
if align == "center":
text_rect.center = (x, y)
screen.blit(text_surface, text_rect)
pg.init()
screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()
class Box(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((20, 20))
self.image.fill((255, 255, 0))
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
self.iter = 0
def update(self, dt):
self.rect.x = 750 * tween.linear(self.iter / ITERATIONS)
self.rect.y = 10 + 550 * func(self.iter / ITERATIONS)
self.iter += 1
if self.iter > ITERATIONS:
self.iter = 0
ITERATIONS = 400
factor = 0
func = next(tween_func)
draw_text("Func: {}".format(func.__name__), 22, WHITE, 795, 5, align="ne")
b = Box()
running = True
while running:
dt = clock.tick(60) / 1000
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
running = False
if event.key == pg.K_SPACE:
func = next(tween_func)
screen.fill((0, 0, 0))
draw_text("Func: {}".format(func.__name__), 22, WHITE, 795, 5, align="ne")
b = Box()
b.update(dt)
# screen.fill((0, 0, 0))
screen.blit(b.image, b.rect)
pg.display.flip()
pg.quit()
| 1,500 |
10,225 | package io.quarkus.it.mongodb.rest.data.panache;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@ApplicationScoped
@Path("/test")
public class TestResource {
@Inject
BookRepository bookRepository;
@POST
@Path("/authors")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Author createAuthor(Author author) {
author.persist();
return author;
}
@DELETE
@Path("/authors")
public void deleteAllAuthors() {
Author.deleteAll();
}
@POST
@Path("/books")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Book createBook(Book book) {
bookRepository.persist(book);
return book;
}
@DELETE
@Path("/books")
public void deleteAllBooks() {
bookRepository.deleteAll();
}
}
| 452 |
686 | <filename>green/test/test_junit.py
from __future__ import unicode_literals
from green.config import default_args
from green.output import GreenStream
from green.junit import JUnitXML, JUnitDialect, Verdict
from green.result import GreenTestResult, BaseTestResult, ProtoTest, proto_error
from io import StringIO
from sys import exc_info
from unittest import TestCase
from xml.etree.ElementTree import fromstring as from_xml, tostring as to_xml
def test(module, class_name, method_name):
test = ProtoTest()
test.module = module
test.class_name = class_name
test.method_name = method_name
return test
class JUnitXMLReportIsGenerated(TestCase):
def setUp(self):
self._destination = StringIO()
self._test_results = GreenTestResult(default_args, GreenStream(StringIO()))
self._test_results.timeTaken = 4.06
self._adapter = JUnitXML()
self._test = ProtoTest()
self._test.module = "my_module"
self._test.class_name = "MyClass"
self._test.method_name = "my_method"
self._test.test_time = "0.005"
def test_when_the_results_contain_only_one_successful_test(self):
self._test_results.addSuccess(self._test)
self._adapter.save_as(self._test_results, self._destination)
self._assert_report_is(
{"my_module.MyClass": {"tests": {"my_method": {"verdict": Verdict.PASSED}}}}
)
def test_when_the_results_contain_tests_with_various_verdict(self):
self._test_results.addSuccess(test("my.module", "MyClass", "test_method1"))
self._test_results.addSuccess(test("my.module", "MyClass", "test_method2"))
self._record_failure(test("my.module", "MyClass", "test_method3"))
self._record_failure(test("my.module", "MyClass", "test_method4"))
self._record_error(test("my.module", "MyClass", "test_method5"))
self._test_results.addSkip(
test("my.module", "MyClass", "test_method6"), "Take too long"
)
self._adapter.save_as(self._test_results, self._destination)
self._assert_report_is(
{
"my.module.MyClass": {
"#tests": "6",
"#failures": "2",
"#errors": "1",
"#skipped": "1",
"tests": {
"test_method1": {"verdict": Verdict.PASSED},
"test_method2": {"verdict": Verdict.PASSED},
"test_method3": {"verdict": Verdict.FAILED},
"test_method4": {"verdict": Verdict.FAILED},
"test_method5": {"verdict": Verdict.ERROR},
"test_method6": {"verdict": Verdict.SKIPPED},
},
},
}
)
def _record_failure(self, test):
try:
raise ValueError("Wrong value")
except:
error = proto_error(exc_info())
self._test_results.addFailure(test, error)
def _record_error(self, test):
try:
raise ValueError("Wrong value")
except:
error = proto_error(exc_info())
self._test_results.addError(test, error)
def test_when_the_results_contain_only_one_test_with_output(self):
output = "This is the output of the test"
self._test_results.recordStdout(self._test, output)
self._test_results.addSuccess(self._test)
self._adapter.save_as(self._test_results, self._destination)
self._assert_report_is(
{
"my_module.MyClass": {
"tests": {
"my_method": {"verdict": Verdict.PASSED, "stdout": output}
}
}
}
)
def test_when_the_results_contain_only_one_test_with_errput(self):
errput = "This is the errput of the test"
self._test_results.recordStderr(self._test, errput)
self._test_results.addSuccess(self._test)
self._adapter.save_as(self._test_results, self._destination)
self._assert_report_is(
{
"my_module.MyClass": {
"tests": {
"my_method": {"verdict": Verdict.PASSED, "stderr": errput}
}
}
}
)
def test_when_the_results_contain_only_one_failed_test(self):
self._record_failure(test("my_module", "MyClass", "my_method"))
self._adapter.save_as(self._test_results, self._destination)
self._assert_report_is(
{"my_module.MyClass": {"tests": {"my_method": {"verdict": Verdict.FAILED}}}}
)
def test_when_the_results_contain_only_one_erroneous_test(self):
self._record_error(test("my_module", "MyClass", "my_method"))
self._adapter.save_as(self._test_results, self._destination)
self._assert_report_is(
{"my_module.MyClass": {"tests": {"my_method": {"verdict": Verdict.ERROR}}}}
)
def test_when_the_results_contain_only_one_skipped_test(self):
self._test_results.addSkip(self._test, "reason for skipping")
self._adapter.save_as(self._test_results, self._destination)
self._assert_report_is(
{
"my_module.MyClass": {
"tests": {"my_method": {"verdict": Verdict.SKIPPED}}
}
}
)
def test_convert_test_will_record_time_for_test(self):
xml_test_result = self._adapter._convert_test(
self._test_results, Verdict.PASSED, self._test
)
self.assertEqual(
xml_test_result.attrib,
{"name": "my_method", "classname": "MyClass", "time": "0.005"},
)
def test_suite_time(self):
test1 = test("my.module", "MyClass", "test_method1")
test1.test_time = "0.01"
test2 = test("my.module", "MyClass", "test_method2")
test2.test_time = "0.5"
test3 = test("my.module", "MyClass", "test_method3")
test3.test_time = "1.0"
suite_time = self._adapter._suite_time([(2, test1), (0, test2), (0, test3)])
self.assertEqual(suite_time, 1.51)
def _assert_report_is(self, report):
"""
Verify the structure of the generated XML text against the given
'report' structure.
"""
root = from_xml(self._destination.getvalue())
test_suites = root.findall(JUnitDialect.TEST_SUITE)
self.assertEqual(len(report), len(test_suites))
for each_suite in test_suites:
self._assert_suite(report, each_suite)
def _assert_suite(self, expected_report, suite):
"""
Verify that the given 'suite' matches one in the expected test report.
"""
name = suite.get(JUnitDialect.NAME)
self.assertIsNotNone(name)
self.assertIn(name, expected_report)
expected_suite = expected_report[name]
# Check the count of tests
if "#tests" in expected_suite:
self.assertEqual(
expected_suite["#tests"], suite.get(JUnitDialect.TEST_COUNT)
)
# Check the count of failures
if "#failures" in expected_suite:
self.assertEqual(
expected_suite["#failures"], suite.get(JUnitDialect.FAILURE_COUNT)
)
# Check the count of errors
if "#errors" in expected_suite:
self.assertEqual(
expected_suite["#errors"], suite.get(JUnitDialect.ERROR_COUNT)
)
# Check the count of skipped tests
if "#skipped" in expected_suite:
self.assertEqual(
expected_suite["#skipped"], suite.get(JUnitDialect.SKIPPED_COUNT)
)
# Check the time of each test
if "time" in expected_suite:
self.assertEqual(expected_suite["time"], suite.get(JUnitDialect.TEST_TIME))
# Check the time of total test run
if "totaltesttime" in expected_suite:
self.assertEqual(
expected_suite["totaltesttime"], suite.get(JUnitDialect.TEST_TIME)
)
# Check individual test reports
self.assertEqual(len(expected_suite["tests"]), len(suite))
for each_test in suite:
self._assert_test(expected_suite["tests"], each_test)
def _assert_test(self, expected_suite, test):
"""
Verify that the given 'test' matches one in the expected test suite.
"""
name = test.get(JUnitDialect.NAME)
self.assertIsNotNone(test)
self.assertIn(name, expected_suite)
expected_test = expected_suite[name]
test_passed = True
for key, expected in expected_test.items():
if key == "verdict":
self._assert_verdict(expected, test)
elif key == "stdout":
system_out = test.find(JUnitDialect.SYSTEM_OUT)
self.assertIsNotNone(system_out)
self.assertEqual(expected, system_out.text)
elif key == "stderr":
system_err = test.find(JUnitDialect.SYSTEM_ERR)
self.assertIsNotNone(system_err)
self.assertEqual(expected, system_err.text)
def _assert_verdict(self, expected_verdict, test):
failure = test.find(JUnitDialect.FAILURE)
error = test.find(JUnitDialect.ERROR)
skipped = test.find(JUnitDialect.SKIPPED)
if expected_verdict == Verdict.FAILED:
self.assertIsNotNone(failure)
self.assertIsNone(error)
self.assertIsNone(skipped)
elif expected_verdict == Verdict.ERROR:
self.assertIsNone(failure)
self.assertIsNotNone(error)
self.assertIsNone(skipped)
elif expected_verdict == Verdict.SKIPPED:
self.assertIsNone(failure)
self.assertIsNone(error)
self.assertIsNotNone(skipped)
else: # Verdict == PASSED
self.assertIsNone(failure)
self.assertIsNone(error)
self.assertIsNone(skipped)
| 4,864 |
12,718 | /* NSObjCRuntime.h
Copyright (c) 1994-2012, Apple Inc. All rights reserved.
*/
#ifndef _OBJC_NSOBJCRUNTIME_H_
#define _OBJC_NSOBJCRUNTIME_H_
#include <TargetConditionals.h>
#include <objc/objc.h>
#if __LP64__ || 0 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
#define NSIntegerMax LONG_MAX
#define NSIntegerMin LONG_MIN
#define NSUIntegerMax ULONG_MAX
#define NSINTEGER_DEFINED 1
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
#endif | 289 |
502 | <reponame>thliang01/arena
package com.github.kubeflow.arena.model.nodes;
import com.alibaba.fastjson.JSON;
public class GPUShareNodeDevice {
private String id;
private double allocatedGPUMemory;
private double totalGPUMemory;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getTotalGPUMemory() {
return totalGPUMemory;
}
public void setTotalGPUMemory(double totalGPUMemory) {
this.totalGPUMemory = totalGPUMemory;
}
public double getAllocatedGPUMemory() {
return allocatedGPUMemory;
}
public void setAllocatedGPUMemory(double allocatedGPUMemory) {
this.allocatedGPUMemory = allocatedGPUMemory;
}
@Override
public String toString() {
return JSON.toJSONString(this,true);
}
}
| 325 |
1,652 | package com.ctrip.xpipe.redis.console.service.impl;
import com.ctrip.xpipe.endpoint.HostPort;
import com.ctrip.xpipe.redis.checker.healthcheck.actions.ping.PingService;
import com.google.common.collect.Maps;
import java.util.Map;
/**
* @author lishanglin
* date 2021/3/17
*/
public class ConsoleCachedPingService implements PingService {
Map<HostPort, Boolean> redisAlives = Maps.newConcurrentMap();
@Override
public void updateRedisAlives(Map<HostPort, Boolean> redisAlives) {
this.redisAlives.putAll(redisAlives);
}
@Override
public boolean isRedisAlive(HostPort hostPort) {
return redisAlives.containsKey(hostPort) && redisAlives.get(hostPort);
}
@Override
public Map<HostPort, Boolean> getAllRedisAlives() {
return redisAlives;
}
}
| 306 |
334 | // Pedra, Papel, Tesoura, Lagarto e Spock
/* Pedra-papel-tesoura-lagarto-Spock é uma expansão do clássico método de
seleção em jogo de pedra-papel-tesoura. Atua sob o mesmo princípio básico,
mas inclui outras duas armas adicionais: o lagarto (formado pela mão igual a
uma boca de fantoche) e Spock (formada pela saudação dos vulcanos em Star Trek).
Isso reduz as chances de uma rodada terminar em um empate. O jogo foi
inventado por <NAME> e <NAME>, como "Rock Paper Scissors Lizard Spock".
As regras de vantagem são as seguintes:
• Tesoura corta papel
• Papel cobre pedra
• Pedra derruba lagarto
• Lagarto adormece Spock
• Spock derrete tesoura
• Tesoura prende lagarto
• Lagarto come papel
• Papel refuta Spock
• Spock vaporiza pedra
• Pedra quebra tesoura
Um dia, duas amigas, Fernanda e Marcia, decidiram apostar quem pagaria um
almoço para o outro, com esta brincadeira. Sua missão será fazer um algoritmo
que, baseado no que eles escolherem, informe quem irá ganhar ou se dará empate.
- Entrada
Haverá diversos casos de teste. O primeiro número a ser lido será um inteiro,
representando a quantidade de casos de teste. Cada caso de teste tem duas
palavras, representando a escolha de Fernanda e de Marcia, respectivamente.
- Saída
Para cada caso de teste, imprima quem venceu, ou se houve empate. */
import java.util.*;
public class PedraPapelTesouraLagartoSpock {
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
int casos = scr.nextInt();
scr.nextLine();
List<Regra> regras = new ArrayList<>();
regras.add(new Regra("tesoura", "papel"));
regras.add(new Regra("papel", "pedra"));
regras.add(new Regra("pedra", "lagarto"));
regras.add(new Regra("lagarto", "spock"));
regras.add(new Regra("spock", "tesoura"));
regras.add(new Regra("tesoura", "lagarto"));
regras.add(new Regra("lagarto", "papel"));
regras.add(new Regra("papel", "spock"));
regras.add(new Regra("spock", "pedra"));
regras.add(new Regra("pedra", "tesoura"));
for (int i = 0; i < casos; i++) {
List<String> palavras = Arrays.asList(scr.nextLine().split(" "));
if(palavras.get(0).equals(palavras.get(1))){
System.out.println("empate");
} else {
boolean primeiro = false;
for (Regra r : regras) {
if (r.getVence().equals(palavras.get(0)) && r.getPerde().equals(palavras.get(1))) {
primeiro = true;
break;
}
}
if(primeiro) {
System.out.println("fernanda");
} else {
System.out.println("marcia");
}
}
}
}
public static class Regra {
private String vence;
private String perde;
public Regra(String vence,
String perde) {
this.vence = vence;
this.perde = perde;
}
public String getVence() {
return vence;
}
public void setVence(String vence) {
this.vence = vence;
}
public String getPerde() {
return perde;
}
public void setPerde(String perde) {
this.perde = perde;
}
}
} | 1,751 |
679 | <reponame>Grosskopf/openoffice
/**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// System - Includes -----------------------------------------------------
#include <sot/formats.hxx>
#include <sfx2/app.hxx>
#include <sfx2/linkmgr.hxx>
#include "servobj.hxx"
#include "docsh.hxx"
#include "impex.hxx"
#include "brdcst.hxx"
#include "rangenam.hxx"
#include "sc.hrc" // SC_HINT_AREAS_CHANGED
// -----------------------------------------------------------------------
sal_Bool lcl_FillRangeFromName( ScRange& rRange, ScDocShell* pDocSh, const String& rName )
{
if (pDocSh)
{
ScDocument* pDoc = pDocSh->GetDocument();
ScRangeName* pNames = pDoc->GetRangeName();
if (pNames)
{
sal_uInt16 nPos;
if( pNames->SearchName( rName, nPos ) )
{
ScRangeData* pData = (*pNames)[ nPos ];
if ( pData->IsValidReference( rRange ) )
return sal_True;
}
}
}
return sal_False;
}
ScServerObjectSvtListenerForwarder::ScServerObjectSvtListenerForwarder(
ScServerObject* pObjP)
: pObj(pObjP)
{
}
ScServerObjectSvtListenerForwarder::~ScServerObjectSvtListenerForwarder()
{
//! do NOT access pObj
}
void ScServerObjectSvtListenerForwarder::Notify( SvtBroadcaster& /* rBC */, const SfxHint& rHint)
{
pObj->Notify( aBroadcaster, rHint);
}
ScServerObject::ScServerObject( ScDocShell* pShell, const String& rItem ) :
aForwarder( this ),
pDocSh( pShell ),
bRefreshListener( sal_False )
{
// parse item string
if ( lcl_FillRangeFromName( aRange, pDocSh, rItem ) )
{
aItemStr = rItem; // must be parsed again on ref update
}
else
{
// parse ref
ScDocument* pDoc = pDocSh->GetDocument();
SCTAB nTab = pDocSh->GetCurTab();
aRange.aStart.SetTab( nTab );
if ( aRange.Parse( rItem, pDoc ) & SCA_VALID )
{
// area reference
}
else if ( aRange.aStart.Parse( rItem, pDoc, pDoc->GetAddressConvention() ) & SCA_VALID )
{
// cell reference
aRange.aEnd = aRange.aStart;
}
else
{
DBG_ERROR("ScServerObject: invalid item");
}
}
pDocSh->GetDocument()->GetLinkManager()->InsertServer( this );
pDocSh->GetDocument()->StartListeningArea( aRange, &aForwarder );
StartListening(*pDocSh); // um mitzubekommen, wenn die DocShell geloescht wird
StartListening(*SFX_APP()); // for SC_HINT_AREAS_CHANGED
}
__EXPORT ScServerObject::~ScServerObject()
{
Clear();
}
void ScServerObject::Clear()
{
if (pDocSh)
{
ScDocShell* pTemp = pDocSh;
pDocSh = NULL;
pTemp->GetDocument()->EndListeningArea( aRange, &aForwarder );
pTemp->GetDocument()->GetLinkManager()->RemoveServer( this );
EndListening(*pTemp);
EndListening(*SFX_APP());
}
}
void ScServerObject::EndListeningAll()
{
aForwarder.EndListeningAll();
SfxListener::EndListeningAll();
}
sal_Bool __EXPORT ScServerObject::GetData(
::com::sun::star::uno::Any & rData /*out param*/,
const String & rMimeType, sal_Bool /* bSynchron */ )
{
if (!pDocSh)
return sal_False;
// named ranges may have changed -> update aRange
if ( aItemStr.Len() )
{
ScRange aNew;
if ( lcl_FillRangeFromName( aNew, pDocSh, aItemStr ) && aNew != aRange )
{
aRange = aNew;
bRefreshListener = sal_True;
}
}
if ( bRefreshListener )
{
// refresh the listeners now (this is called from a timer)
EndListeningAll();
pDocSh->GetDocument()->StartListeningArea( aRange, &aForwarder );
StartListening(*pDocSh);
StartListening(*SFX_APP());
bRefreshListener = sal_False;
}
String aDdeTextFmt = pDocSh->GetDdeTextFmt();
ScDocument* pDoc = pDocSh->GetDocument();
if( FORMAT_STRING == SotExchange::GetFormatIdFromMimeType( rMimeType ))
{
ScImportExport aObj( pDoc, aRange );
if( aDdeTextFmt.GetChar(0) == 'F' )
aObj.SetFormulas( sal_True );
if( aDdeTextFmt.EqualsAscii( "SYLK" ) ||
aDdeTextFmt.EqualsAscii( "FSYLK" ) )
{
ByteString aByteData;
if( aObj.ExportByteString( aByteData, gsl_getSystemTextEncoding(), SOT_FORMATSTR_ID_SYLK ) )
{
rData <<= ::com::sun::star::uno::Sequence< sal_Int8 >(
(sal_Int8*)aByteData.GetBuffer(),
aByteData.Len() + 1 );
return 1;
}
return 0;
}
if( aDdeTextFmt.EqualsAscii( "CSV" ) ||
aDdeTextFmt.EqualsAscii( "FCSV" ) )
aObj.SetSeparator( ',' );
aObj.SetExportTextOptions( ScExportTextOptions( ScExportTextOptions::ToSpace, ' ', false ) );
return aObj.ExportData( rMimeType, rData ) ? 1 : 0;
}
ScImportExport aObj( pDoc, aRange );
aObj.SetExportTextOptions( ScExportTextOptions( ScExportTextOptions::ToSpace, ' ', false ) );
if( aObj.IsRef() )
return aObj.ExportData( rMimeType, rData ) ? 1 : 0;
return 0;
}
void __EXPORT ScServerObject::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
sal_Bool bDataChanged = sal_False;
// DocShell can't be tested via type info, because SFX_HINT_DYING comes from the dtor
if ( &rBC == pDocSh )
{
// from DocShell, only SFX_HINT_DYING is interesting
if ( rHint.ISA(SfxSimpleHint) && ((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING )
{
pDocSh = NULL;
EndListening(*SFX_APP());
// don't access DocShell anymore for EndListening etc.
}
}
else if (rBC.ISA(SfxApplication))
{
if ( aItemStr.Len() && rHint.ISA(SfxSimpleHint) &&
((const SfxSimpleHint&)rHint).GetId() == SC_HINT_AREAS_CHANGED )
{
// check if named range was modified
ScRange aNew;
if ( lcl_FillRangeFromName( aNew, pDocSh, aItemStr ) && aNew != aRange )
bDataChanged = sal_True;
}
}
else
{
// must be from Area broadcasters
const ScHint* pScHint = PTR_CAST( ScHint, &rHint );
if( pScHint && (pScHint->GetId() & (SC_HINT_DATACHANGED | SC_HINT_DYING)) )
bDataChanged = sal_True;
else if (rHint.ISA(ScAreaChangedHint)) // position of broadcaster changed
{
ScRange aNewRange = ((const ScAreaChangedHint&)rHint).GetRange();
if ( aRange != aNewRange )
{
bRefreshListener = sal_True;
bDataChanged = sal_True;
}
}
else if (rHint.ISA(SfxSimpleHint))
{
sal_uLong nId = ((const SfxSimpleHint&)rHint).GetId();
if (nId == SFX_HINT_DYING)
{
// If the range is being deleted, listening must be restarted
// after the deletion is complete (done in GetData)
bRefreshListener = sal_True;
bDataChanged = sal_True;
}
}
}
if ( bDataChanged && HasDataLinks() )
SvLinkSource::NotifyDataChanged();
}
| 2,889 |
1,144 | package de.metas.invoicecandidate.api.impl;
/*
* #%L
* de.metas.swat.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.adempiere.util.lang.ObjectUtils;
import de.metas.invoicecandidate.model.I_C_InvoiceCandidate_InOutLine;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import de.metas.invoicecandidate.api.IInvoiceLineAggregationRequest;
import de.metas.invoicecandidate.api.IInvoiceLineAttribute;
import de.metas.invoicecandidate.model.I_C_Invoice_Candidate;
import de.metas.util.Check;
/**
* Default immutable implementation of {@link IInvoiceLineAggregationRequest}.
*
* @author tsa
*
*/
/* package */final class InvoiceLineAggregationRequest implements IInvoiceLineAggregationRequest
{
public static final Builder builder()
{
return new Builder();
}
private final I_C_Invoice_Candidate invoiceCandidate;
private final I_C_InvoiceCandidate_InOutLine iciol;
private final ImmutableList<Object> aggregationKeyElements;
private final ImmutableSet<IInvoiceLineAttribute> invoiceLineAttributes;
private final boolean allocateRemainingQty;
private InvoiceLineAggregationRequest(final Builder builder)
{
super();
Check.assumeNotNull(builder, "builder not null");
this.invoiceCandidate = builder.invoiceCandidate;
Check.assumeNotNull(invoiceCandidate, "invoiceCandidate not null");
this.iciol = builder.iciol;
if (iciol != null && iciol.getC_Invoice_Candidate_ID() != invoiceCandidate.getC_Invoice_Candidate_ID())
{
throw new IllegalArgumentException("Invalid " + iciol + ". C_Invoice_Candidate_ID shall match."
+ "\n Expected invoice candidate: " + invoiceCandidate);
}
this.aggregationKeyElements = ImmutableList.copyOf(builder.aggregationKeyElements);
this.invoiceLineAttributes = ImmutableSet.copyOf(builder.invoiceLineAttributes);
this.allocateRemainingQty = builder.allocateRemainingQty;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public I_C_Invoice_Candidate getC_Invoice_Candidate()
{
return invoiceCandidate;
}
@Override
public I_C_InvoiceCandidate_InOutLine getC_InvoiceCandidate_InOutLine()
{
return iciol;
}
@Override
public List<Object> getLineAggregationKeyElements()
{
return aggregationKeyElements;
}
@Override
public Set<IInvoiceLineAttribute> getInvoiceLineAttributes()
{
return invoiceLineAttributes;
}
@Override
public boolean isAllocateRemainingQty()
{
return this.allocateRemainingQty;
}
/**
* {@link InvoiceLineAggregationRequest} builder.
*
* @author tsa
*/
public static class Builder
{
private I_C_Invoice_Candidate invoiceCandidate;
private I_C_InvoiceCandidate_InOutLine iciol;
private final List<Object> aggregationKeyElements = new ArrayList<>();
private final Set<IInvoiceLineAttribute> invoiceLineAttributes = new LinkedHashSet<>();
private boolean allocateRemainingQty = false;
public InvoiceLineAggregationRequest build()
{
return new InvoiceLineAggregationRequest(this);
}
private Builder()
{
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
public Builder setC_Invoice_Candidate(final I_C_Invoice_Candidate invoiceCandidate)
{
this.invoiceCandidate = invoiceCandidate;
return this;
}
public Builder setC_InvoiceCandidate_InOutLine(final I_C_InvoiceCandidate_InOutLine iciol)
{
this.iciol = iciol;
return this;
}
/**
* Adds an additional element to be considered part of the line aggregation key.
*
* NOTE: basically this shall be always empty because everything which is related to line aggregation
* shall be configured from aggregation definition,
* but we are also leaving this door open in case we need to implement some quick/hot fixes.
*
* @param aggregationKeyElement
* @deprecated This method will be removed because we shall go entirely with standard aggregation definition.
*/
@Deprecated
public Builder addLineAggregationKeyElement(final Object aggregationKeyElement)
{
aggregationKeyElements.add(aggregationKeyElement);
return this;
}
public Builder addInvoiceLineAttributes(final Collection<IInvoiceLineAttribute> invoiceLineAttributes)
{
this.invoiceLineAttributes.addAll(invoiceLineAttributes);
return this;
}
public Builder setAllocateRemainingQty(boolean allocateRemainingQty)
{
this.allocateRemainingQty = allocateRemainingQty;
return this;
}
}
}
| 1,693 |
7,089 | from setuptools import setup
setup(
name="requires_requires_capitalized",
version="1.0",
install_requires=["requires_Capitalized==0.1"],
)
| 54 |
2,338 | // RUN: %check_clang_tidy %s bugprone-not-null-terminated-result %t -- \
// RUN: -- -std=c11 -I %S/Inputs/bugprone-not-null-terminated-result
#include "not-null-terminated-result-c.h"
#define __STDC_LIB_EXT1__ 1
#define __STDC_WANT_LIB_EXT1__ 1
//===----------------------------------------------------------------------===//
// memcpy() - destination array tests
//===----------------------------------------------------------------------===//
void bad_memcpy_not_just_char_dest(const char *src) {
unsigned char dest00[13];
memcpy(dest00, src, strlen(src));
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 'memcpy' is not null-terminated [bugprone-not-null-terminated-result]
// CHECK-FIXES: unsigned char dest00[14];
// CHECK-FIXES-NEXT: strcpy_s((char *)dest00, 14, src);
}
void good_memcpy_not_just_char_dest(const char *src) {
unsigned char dst00[14];
strcpy_s((char *)dst00, 14, src);
}
void bad_memcpy_known_dest(const char *src) {
char dest01[13];
memcpy(dest01, src, strlen(src));
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 'memcpy' is not null-terminated [bugprone-not-null-terminated-result]
// CHECK-FIXES: char dest01[14];
// CHECK-FIXES: strcpy_s(dest01, 14, src);
}
void good_memcpy_known_dest(const char *src) {
char dst01[14];
strcpy_s(dst01, 14, src);
}
//===----------------------------------------------------------------------===//
// memcpy() - length tests
//===----------------------------------------------------------------------===//
void bad_memcpy_full_source_length(const char *src) {
char dest20[13];
memcpy(dest20, src, strlen(src));
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 'memcpy' is not null-terminated [bugprone-not-null-terminated-result]
// CHECK-FIXES: char dest20[14];
// CHECK-FIXES-NEXT: strcpy_s(dest20, 14, src);
}
void good_memcpy_full_source_length(const char *src) {
char dst20[14];
strcpy_s(dst20, 14, src);
}
void bad_memcpy_partial_source_length(const char *src) {
char dest21[13];
memcpy(dest21, src, strlen(src) - 1);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 'memcpy' is not null-terminated [bugprone-not-null-terminated-result]
// CHECK-FIXES: char dest21[14];
// CHECK-FIXES-NEXT: strncpy_s(dest21, 14, src, strlen(src) - 1);
}
void good__memcpy_partial_source_length(const char *src) {
char dst21[14];
strncpy_s(dst21, 14, src, strlen(src) - 1);
}
//===----------------------------------------------------------------------===//
// memcpy_s() - destination array tests
//===----------------------------------------------------------------------===//
void bad_memcpy_s_unknown_dest(char *dest40, const char *src) {
memcpy_s(dest40, 13, src, strlen(src));
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 'memcpy_s' is not null-terminated [bugprone-not-null-terminated-result]
// CHECK-FIXES: strcpy_s(dest40, 13, src);
}
void good_memcpy_s_unknown_dest(char *dst40, const char *src) {
strcpy_s(dst40, 13, src);
}
void bad_memcpy_s_known_dest(const char *src) {
char dest41[13];
memcpy_s(dest41, 13, src, strlen(src));
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 'memcpy_s' is not null-terminated [bugprone-not-null-terminated-result]
// CHECK-FIXES: char dest41[14];
// CHECK-FIXES-NEXT: strcpy_s(dest41, 14, src);
}
void good_memcpy_s_known_dest(const char *src) {
char dst41[14];
strcpy_s(dst41, 14, src);
}
//===----------------------------------------------------------------------===//
// memcpy_s() - length tests
//===----------------------------------------------------------------------===//
void bad_memcpy_s_full_source_length(const char *src) {
char dest60[13];
memcpy_s(dest60, 13, src, strlen(src));
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 'memcpy_s' is not null-terminated [bugprone-not-null-terminated-result]
// CHECK-FIXES: char dest60[14];
// CHECK-FIXES-NEXT: strcpy_s(dest60, 14, src);
}
void good_memcpy_s_full_source_length(const char *src) {
char dst60[14];
strcpy_s(dst60, 14, src);
}
void bad_memcpy_s_partial_source_length(const char *src) {
char dest61[13];
memcpy_s(dest61, 13, src, strlen(src) - 1);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 'memcpy_s' is not null-terminated [bugprone-not-null-terminated-result]
// CHECK-FIXES: char dest61[14];
// CHECK-FIXES-NEXT: strncpy_s(dest61, 14, src, strlen(src) - 1);
}
void good_memcpy_s_partial_source_length(const char *src) {
char dst61[14];
strncpy_s(dst61, 14, src, strlen(src) - 1);
}
| 1,739 |
7,073 | <filename>atest/testdata/keywords/library/with/dots/in/name/__init__.py
class name:
def get_keyword_names(self):
return ['No dots in keyword name in library with dots in name',
'Dots.in.name.in.a.library.with.dots.in.name',
'Multiple...dots . . in . a............row.in.a.library.with.dots.in.name',
'Ending with a dot. In a library with dots in name.',
'Conflict']
def run_keyword(self, name, args):
print("Running keyword '%s'." % name)
return '-'.join(args)
| 256 |
5,169 | {
"name": "KQNetworkManager",
"version": "0.1.1",
"summary": "KQNetworkManager is for network calls.",
"description": "'KQNetworkManager is for network calls.'",
"homepage": "https://github.com/MKQasim/KQNetworkManager.git",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME> <NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/MKQasim/KQNetworkManager.git",
"tag": "0.1.1"
},
"platforms": {
"ios": "12.0"
},
"source_files": "Classes/Utility/**/*",
"swift_versions": "5.0",
"requires_arc": true,
"swift_version": "5.0"
}
| 260 |
4,868 | package com.cf.chat.service;
import com.cf.chat.domain.CfUserMessage;
import com.cf.chat.domain.CfUserMessageVo;
import com.cf.chat.domain.Message;
import com.cf.framework.domain.ucenter.ext.UserBasicInfo;
import io.netty.channel.Channel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 请在此填写描述
*
* @ClassName CfUserMessageService
* @Author 隔壁小王子 <EMAIL>
* @Date 2019/12/15/015 12:44
* @Version 1.0
**/
public interface CfUserMessageService {
/**
* 发送用户消息
* @param cfUserMessage
* @return
*/
public CfUserMessage sendMessage(CfUserMessage cfUserMessage);
/**
* 给通道塞入消息
* @param cfUserMessage
*/
public void sendMessageByChannel(CfUserMessage cfUserMessage);
/**
* 通知发送者消息发送结果
*
* @param cfUserMessage
*/
public void sendMessageResultByChannel(CfUserMessage cfUserMessage);
/**
* 改变消息状态
* @param uid
* @param messageId
* @param status
* @return
*/
public Long updateStatus(String uid, String messageId, Integer status);
/**
* 检查token是否合法
* @param jwtString
* @return
*/
public String checkToken(String jwtString);
/**
* 获取指定用的未读消息(支持分页获取)
* @param uid
* @param page
* @param limit
* @return
*/
public List<CfUserMessage> selectNotReadMessageListByToUid(String uid, Integer page, Integer limit);
/**
* 根据消息id组查询消息数据
* @param ids
* @return
*/
public List<CfUserMessage> selectListByIds(String[] ids);
/**
* 根据token获取用户基本信息
* @param token
* @return
*/
public UserBasicInfo getBaseUserInfoByToken(String token);
/**
* 获取离线消息
* @param uid
*/
public void getNotReadMessage(String uid);
/**
* 批量更新消息状态
* @param cfUserMessages
*/
public void batchUpdateStatusByIds(List<CfUserMessage> cfUserMessages);
}
| 1,003 |
386 | package com.github.unclecatmyself.bootstrap.channel.protocol;
import java.util.Map;
/**
* 消息返回
* Created by MySelf on 2018/11/23.
*/
public interface Response {
/**
* 登录成功返回信息
* @return {@link Map} Json
*/
Map<String,String> loginSuccess();
/**
* 登录失败返回信息
* @return {@link Map} Json
*/
Map<String,String> loginError();
/**
* 发送给自己
* @param value {@link String} 通讯消息
* @return {@link Map} Json
*/
Map<String,String> sendMe(String value);
/**
* 发送给某人的信息,返回给自己
* @param otherOne {@link String} 某人Token
* @param value {@link String} 通讯消息
* @return {@link Map} Json
*/
Map<String,String> sendBack(String otherOne, String value);
/**
* 某人接收到他人发送给他的消息
* @param me {@link String} 发送人的标签
* @param value {@link String} 通讯消息
* @return
*/
Map<String,String> getMessage(String me, String value);
/**
* 发送消息到群里
* @param me {@link String} 发送人的标签
* @param value {@link String} 通讯消息
* @param groupId {@link String} 群聊Id
* @return
*/
Map<String,String> sendGroup(String me,String value,String groupId);
}
| 677 |
319 | import torch
from torch import nn
from typing import Dict, List, Tuple
from ptgnn.neuralmodels.gnn.messagepassing.abstractmessagepassing import AbstractMessagePassingLayer
class _ResidualOriginLayer(AbstractMessagePassingLayer):
def __init__(self, input_dim: int, target_layer):
super().__init__()
self.__target_layer = target_layer
self.__input_dim = input_dim
@property
def input_state_dimension(self) -> int:
return self.__input_dim
@property
def output_state_dimension(self) -> int:
return self.__input_dim
def forward(
self,
node_states: torch.Tensor,
adjacency_lists: List[Tuple[torch.Tensor, torch.Tensor]],
node_to_graph_idx: torch.Tensor,
reference_node_ids: Dict[str, torch.Tensor],
reference_node_graph_idx: Dict[str, torch.Tensor],
edge_features: List[torch.Tensor],
) -> torch.Tensor:
self.__target_layer._original_input = node_states
return node_states
class MeanResidualLayer(AbstractMessagePassingLayer):
def __init__(self, input_dim: int):
super().__init__()
self._original_input = None
self.__input_dim = input_dim
def pass_through_dummy_layer(self) -> _ResidualOriginLayer:
return _ResidualOriginLayer(self.__input_dim, target_layer=self)
def forward(
self,
node_states: torch.Tensor,
adjacency_lists: List[Tuple[torch.Tensor, torch.Tensor]],
node_to_graph_idx: torch.Tensor,
reference_node_ids: Dict[str, torch.Tensor],
reference_node_graph_idx: Dict[str, torch.Tensor],
edge_features: List[torch.Tensor],
) -> torch.Tensor:
assert self._original_input is not None, "Initial Pass Through Layer was not used."
out = torch.stack((self._original_input, node_states), dim=-1).mean(dim=-1)
self._original_input = None # Reset
return out
@property
def input_state_dimension(self) -> int:
return self.__input_dim
@property
def output_state_dimension(self) -> int:
return self.__input_dim
class ConcatResidualLayer(AbstractMessagePassingLayer):
def __init__(self, input_dim: int):
super().__init__()
self._original_input = None
self.__input_dim = input_dim
def pass_through_dummy_layer(self) -> _ResidualOriginLayer:
return _ResidualOriginLayer(self.__input_dim, target_layer=self)
def forward(
self,
node_states: torch.Tensor,
adjacency_lists: List[Tuple[torch.Tensor, torch.Tensor]],
node_to_graph_idx: torch.Tensor,
reference_node_ids: Dict[str, torch.Tensor],
reference_node_graph_idx: Dict[str, torch.Tensor],
edge_features: List[torch.Tensor],
) -> torch.Tensor:
assert self._original_input is not None, "Initial Pass Through Layer was not used."
out = torch.cat((self._original_input, node_states), dim=-1)
self._original_input = None # Reset
return out
@property
def input_state_dimension(self) -> int:
return self.__input_dim
@property
def output_state_dimension(self) -> int:
return 2 * self.__input_dim
class LinearResidualLayer(AbstractMessagePassingLayer):
def __init__(
self,
state_dimension1: int,
state_dimension2: int,
target_state_size: int,
dropout_rate: float = 0.0,
):
super().__init__()
self.__input_dim1 = state_dimension1
self.__input_dim2 = state_dimension2
self.__linear_combination = nn.Linear(
in_features=state_dimension1 + state_dimension2,
out_features=target_state_size,
bias=False,
)
self._original_input = None
self.__dropout = nn.Dropout(p=dropout_rate)
def pass_through_dummy_layer(self) -> _ResidualOriginLayer:
return _ResidualOriginLayer(self.__input_dim1, target_layer=self)
def forward(
self,
node_states: torch.Tensor,
adjacency_lists: List[Tuple[torch.Tensor, torch.Tensor]],
node_to_graph_idx: torch.Tensor,
reference_node_ids: Dict[str, torch.Tensor],
reference_node_graph_idx: Dict[str, torch.Tensor],
edge_features: List[torch.Tensor],
) -> torch.Tensor:
assert self._original_input is not None, "Initial Pass Through Layer was not used."
out = self.__linear_combination(torch.cat((self._original_input, node_states), axis=-1))
self._original_input = None # Reset
return self.__dropout(out)
@property
def input_state_dimension(self) -> int:
return self.__input_dim2
@property
def output_state_dimension(self) -> int:
return self.__linear_combination.out_features
| 2,035 |
314 | //
// ZJStarsView.h
// ZJCommitListDemo
//
// Created by 邓志坚 on 2017/12/10.
// Copyright © 2017年 邓志坚. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ZJStarsView : UIView
// 星级分数
@property(nonatomic, copy) NSString *starCount;
@end
| 123 |
2,828 | <filename>curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaBuilder.java<gh_stars>1000+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.framework.schema;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
public class SchemaBuilder
{
private final Pattern pathRegex;
private final String path;
private String name = UUID.randomUUID().toString();
private String documentation = "";
private SchemaValidator schemaValidator = new DefaultSchemaValidator();
private Schema.Allowance ephemeral = Schema.Allowance.CAN;
private Schema.Allowance sequential = Schema.Allowance.CAN;
private Schema.Allowance watched = Schema.Allowance.CAN;
private boolean canBeDeleted = true;
private Map<String, String> metadata = ImmutableMap.of();
/**
* Build a new schema from the currently set values
*
* @return new schema
*/
public Schema build()
{
return new Schema(name, pathRegex, path, documentation, schemaValidator, ephemeral, sequential, watched, canBeDeleted, metadata);
}
/**
* @param name unique name for this schema
* @return this for chaining
*/
public SchemaBuilder name(String name)
{
this.name = Preconditions.checkNotNull(name, "name cannot be null");
return this;
}
/**
* @param documentation user displayable documentation for the schema
* @return this for chaining
*/
public SchemaBuilder documentation(String documentation)
{
this.documentation = Preconditions.checkNotNull(documentation, "documentation cannot be null");
return this;
}
/**
* @param schemaValidator a data validator - will be used to validate data set for the znode
* @return this for chaining
*/
public SchemaBuilder dataValidator(SchemaValidator schemaValidator)
{
this.schemaValidator = Preconditions.checkNotNull(schemaValidator, "dataValidator cannot be null");
return this;
}
/**
* @param ephemeral whether can, must or cannot be ephemeral
* @return this for chaining
*/
public SchemaBuilder ephemeral(Schema.Allowance ephemeral)
{
this.ephemeral = Preconditions.checkNotNull(ephemeral, "ephemeral cannot be null");
return this;
}
/**
* @param sequential whether can, must or cannot be sequential
* @return this for chaining
*/
public SchemaBuilder sequential(Schema.Allowance sequential)
{
this.sequential = Preconditions.checkNotNull(sequential, "sequential cannot be null");
return this;
}
/**
* @param watched whether can, must or cannot be watched
* @return this for chaining
*/
public SchemaBuilder watched(Schema.Allowance watched)
{
this.watched = watched;
return this;
}
/**
* @param canBeDeleted true if znode can be deleted
* @return this for chaining
*/
public SchemaBuilder canBeDeleted(boolean canBeDeleted)
{
this.canBeDeleted = canBeDeleted;
return this;
}
/**
* @param metadata any field -> value you want
* @return this for chaining
*/
public SchemaBuilder metadata(Map<String, String> metadata)
{
this.metadata = ImmutableMap.copyOf(metadata);
return this;
}
SchemaBuilder(Pattern pathRegex, String path)
{
this.pathRegex = pathRegex;
this.path = path;
}
}
| 1,493 |
348 | <reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000
{"nom":"Brétigny","circ":"6ème circonscription","dpt":"Oise","inscrits":278,"abs":141,"votants":137,"blancs":5,"nuls":3,"exp":129,"res":[{"nuance":"FN","nom":"<NAME>","voix":70},{"nuance":"REM","nom":"<NAME>","voix":59}]} | 116 |
4,129 | package com.didiglobal.booster.instrument;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class ShadowExecutors {
/**
* The minimum pool size, {@link ScheduledThreadPoolExecutor} with core pool size 0 cause high processor load.
* This is a bug of JDK that has been fixed in Java 9
*
* @see <a href="https://bugs.openjdk.java.net/browse/JDK-8129861">JDK-8129861</a>
* @see <a href="https://bugs.openjdk.java.net/browse/JDK-8022642>JDK-8022642/a>
*/
private static final int MIN_POOL_SIZE = 1;
private static final int NCPU = Runtime.getRuntime().availableProcessors();
/**
* The maximum pool size
*/
private static final int MAX_POOL_SIZE = (NCPU << 1) + 1;
/**
* The default keep alive time for idle threads
*/
private static final long DEFAULT_KEEP_ALIVE = 30000L;
public static ThreadFactory defaultThreadFactory(final String name) {
return new NamedThreadFactory(name);
}
// <editor-fold desc="- named fixed thread pool">
public static ExecutorService newFixedThreadPool(final int nThreads, final String name) {
return Executors.newFixedThreadPool(nThreads, new NamedThreadFactory(name));
}
public static ExecutorService newFixedThreadPool(final int nThreads, final ThreadFactory factory, final String name) {
return Executors.newFixedThreadPool(nThreads, new NamedThreadFactory(factory, name));
}
// </editor-fold>
// <editor-fold desc="- named single thread executor">
public static ExecutorService newSingleThreadExecutor(final String name) {
return Executors.newSingleThreadExecutor(new NamedThreadFactory(name));
}
public static ExecutorService newSingleThreadExecutor(final ThreadFactory factory, final String name) {
return Executors.newSingleThreadExecutor(new NamedThreadFactory(factory, name));
}
// </editor-fold>
// <editor-fold desc="- named cached thread pool">
public static ExecutorService newCachedThreadPool(final String name) {
return Executors.newCachedThreadPool(new NamedThreadFactory(name));
}
public static ExecutorService newCachedThreadPool(final ThreadFactory factory, final String name) {
return Executors.newCachedThreadPool(new NamedThreadFactory(factory, name));
}
// </editor-fold>
// <editor-fold desc="- named single thread scheduled executor">
public static ScheduledExecutorService newSingleThreadScheduledExecutor(final String name) {
return Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(name));
}
public static ScheduledExecutorService newSingleThreadScheduledExecutor(final ThreadFactory factory, final String name) {
return Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(factory, name));
}
// </editor-fold>
// <editor-fold desc="- named scheduled thread pool">
public static ScheduledExecutorService newScheduledThreadPool(final int corePoolSize, final String name) {
return Executors.newScheduledThreadPool(corePoolSize, new NamedThreadFactory(name));
}
public static ScheduledExecutorService newScheduledThreadPool(final int corePoolSize, final ThreadFactory factory, final String name) {
return Executors.newScheduledThreadPool(corePoolSize, new NamedThreadFactory(factory, name));
}
// </editor-fold>
// <editor-fold desc="- named work stealing pool">
public static ExecutorService newWorkStealingPool(final String name) {
return new ForkJoinPool(Runtime.getRuntime().availableProcessors(), new NamedForkJoinWorkerThreadFactory(name), null, true);
}
public static ExecutorService newWorkStealingPool(final int parallelism, final String name) {
return new ForkJoinPool(parallelism, new NamedForkJoinWorkerThreadFactory(name), null, true);
}
// </editor-fold>
// <editor-fold desc="- optimized fixed thread pool">
public static ExecutorService newOptimizedFixedThreadPool(final int nThreads, final String name) {
return Executors.newFixedThreadPool(nThreads, new NamedThreadFactory(name));
}
public static ExecutorService newOptimizedFixedThreadPool(final int nThreads, final ThreadFactory factory, final String name) {
return Executors.newFixedThreadPool(nThreads, new NamedThreadFactory(factory, name));
}
// </editor-fold>
// <editor-fold desc="* optimized single thread scheduled executor">
public static ScheduledExecutorService newOptimizedSingleThreadScheduledExecutor(final String name) {
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory(name));
executor.setKeepAliveTime(DEFAULT_KEEP_ALIVE, TimeUnit.MILLISECONDS);
executor.allowCoreThreadTimeOut(true);
return executor;
}
public static ScheduledExecutorService newOptimizedSingleThreadScheduledExecutor(final ThreadFactory factory, final String name) {
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory(factory, name));
executor.setKeepAliveTime(DEFAULT_KEEP_ALIVE, TimeUnit.MILLISECONDS);
executor.allowCoreThreadTimeOut(true);
return executor;
}
// </editor-fold>
// <editor-fold desc="* optimized scheduled thread pool">
public static ScheduledExecutorService newOptimizedScheduledThreadPool(final int corePoolSize, final String name) {
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(min(max(1, corePoolSize), MAX_POOL_SIZE), new NamedThreadFactory(name));
executor.setKeepAliveTime(DEFAULT_KEEP_ALIVE, TimeUnit.MILLISECONDS);
executor.allowCoreThreadTimeOut(true);
return executor;
}
public static ScheduledExecutorService newOptimizedScheduledThreadPool(final int corePoolSize, final ThreadFactory factory, final String name) {
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(min(max(1, corePoolSize), MAX_POOL_SIZE), new NamedThreadFactory(factory, name));
executor.setKeepAliveTime(DEFAULT_KEEP_ALIVE, TimeUnit.MILLISECONDS);
executor.allowCoreThreadTimeOut(true);
return executor;
}
// </editor-fold>
// <editor-fold desc="* optimized single thread executor">
public static ExecutorService newOptimizedSingleThreadExecutor(final String name) {
final ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 1, DEFAULT_KEEP_ALIVE, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(name));
executor.allowCoreThreadTimeOut(true);
return new FinalizableDelegatedExecutorService(executor);
}
public static ExecutorService newOptimizedSingleThreadExecutor(final ThreadFactory factory, final String name) {
final ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 1, DEFAULT_KEEP_ALIVE, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(factory, name));
executor.allowCoreThreadTimeOut(true);
return new FinalizableDelegatedExecutorService(executor);
}
// </editor-fold>
//<editor-fold desc="* optimized cached thread pool">
public static ExecutorService newOptimizedCachedThreadPool(final String name) {
final ThreadPoolExecutor executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory(name));
executor.allowCoreThreadTimeOut(true);
return executor;
}
public static ExecutorService newOptimizedCachedThreadPool(final ThreadFactory factory, final String name) {
final ThreadPoolExecutor executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory(factory, name));
executor.allowCoreThreadTimeOut(true);
return executor;
}
//</editor-fold>
// <editor-fold desc="* optimized work stealing pool">
public static ExecutorService newOptimizedWorkStealingPool(final String name) {
return new ForkJoinPool(Runtime.getRuntime().availableProcessors(), new NamedForkJoinWorkerThreadFactory(name), null, true);
}
public static ExecutorService newOptimizedWorkStealingPool(final int parallelism, final String name) {
return new ForkJoinPool(parallelism, new NamedForkJoinWorkerThreadFactory(name), null, true);
}
// </editor-fold>
private static class DelegatedExecutorService extends AbstractExecutorService {
private final ExecutorService executor;
DelegatedExecutorService(final ExecutorService executor) {
this.executor = executor;
}
@Override
public void execute(final Runnable command) {
this.executor.execute(command);
}
@Override
public void shutdown() {
this.executor.shutdown();
}
@Override
public List<Runnable> shutdownNow() {
return this.executor.shutdownNow();
}
@Override
public boolean isShutdown() {
return this.executor.isShutdown();
}
@Override
public boolean isTerminated() {
return this.executor.isTerminated();
}
@Override
public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {
return this.executor.awaitTermination(timeout, unit);
}
@Override
public Future<?> submit(final Runnable task) {
return this.executor.submit(task);
}
@Override
public <T> Future<T> submit(final Callable<T> task) {
return this.executor.submit(task);
}
@Override
public <T> Future<T> submit(final Runnable task, final T result) {
return this.executor.submit(task, result);
}
@Override
public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks) throws InterruptedException {
return this.executor.invokeAll(tasks);
}
@Override
public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit) throws InterruptedException {
return this.executor.invokeAll(tasks, timeout, unit);
}
@Override
public <T> T invokeAny(final Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
return this.executor.invokeAny(tasks);
}
@Override
public <T> T invokeAny(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return this.executor.invokeAny(tasks, timeout, unit);
}
}
private static final class FinalizableDelegatedExecutorService extends DelegatedExecutorService {
FinalizableDelegatedExecutorService(final ExecutorService executor) {
super(executor);
}
@Override
protected void finalize() {
super.shutdown();
}
}
}
| 4,160 |
3,765 | <filename>pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleMapper.java
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* A mapper from rule class names to rule instances for cached rules.
*
* @deprecated This is internal API, will be hidden with 7.0.0
*/
@Deprecated
@InternalApi
public class CachedRuleMapper {
private final Map<String, Rule> cachedRulesInstances = new HashMap<>();
/**
* Finds a rule instance for the given rule class name, name and target language
* @param className The name of the rule class that generated the cache entry
* @param ruleName The name of the rule that generated the cache entry
* @param languageName The terse name of the language for which the rule applies
* @return The requested rule
*/
public Rule getRuleForClass(final String className, final String ruleName, final String languageName) {
return cachedRulesInstances.get(getRuleKey(className, ruleName, languageName));
}
/**
* Initialize the mapper with the given rulesets.
* @param rs The rulesets from which to retrieve rules.
*/
public void initialize(final RuleSets rs) {
for (final Rule r : rs.getAllRules()) {
cachedRulesInstances.put(getRuleKey(r.getRuleClass(), r.getName(), r.getLanguage().getTerseName()), r);
}
}
private String getRuleKey(final String className, final String ruleName, final String languageName) {
return className + "$$" + ruleName + "$$" + languageName;
}
}
| 589 |
332 | /*
* Copyright 2013-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.xd.integration.test;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.springframework.xd.test.fixtures.FilePollHdfsJob;
import org.springframework.xd.test.fixtures.SimpleFileSource;
/**
* Runs a basic suite of FilePollHdfs tests on an XD Cluster instance.
*
* @author <NAME>
*/
public class FilePollHdfsTest extends AbstractJobTest {
public final static String DEFAULT_NAMES = "data";
/**
* Clears out the test directory
*
* @throws Exception
*/
@Before
public void initialize() throws Exception {
if (hadoopUtil.fileExists(FilePollHdfsJob.DEFAULT_DIRECTORY)) {
hadoopUtil.fileRemove(FilePollHdfsJob.DEFAULT_DIRECTORY);
}
}
/**
* Verifies that FilePollHdfs Job has written the test data to the hdfs.
*
*/
@Test
public void testFilePollHdfsJob() {
String data = UUID.randomUUID().toString();
String jobName = "tfphj" + UUID.randomUUID().toString();
String sourceFileName = UUID.randomUUID().toString() + ".out";
String sourceDir = "/tmp/xd/" + FilePollHdfsJob.DEFAULT_FILE_NAME;
SimpleFileSource fileSource = sources.file(sourceDir, sourceFileName).mode(SimpleFileSource.Mode.REF);
job(jobName, jobs.filePollHdfsJob(DEFAULT_NAMES).toDSL(), true);
stream(fileSource + XD_TAP_DELIMITER + " queue:job:" + jobName);
//Since the job may be on a different container you will have to copy the file to the job's container.
setupDataFiles(getContainerHostForJob(jobName), sourceDir, sourceFileName, data);
//Copy file to source container instance.
setupSourceDataFiles(sourceDir, sourceFileName, data);
waitForJobToComplete(jobName);
assertValidHdfs(data, FilePollHdfsJob.DEFAULT_DIRECTORY + "/" + FilePollHdfsJob.DEFAULT_FILE_NAME + "-0.csv");
}
}
| 771 |
6,989 | #pragma once
#include <catboost/libs/data/data_provider.h>
#include <catboost/private/libs/options/restrictions.h>
#include <util/generic/fwd.h>
#include <util/generic/vector.h>
class TFold;
struct TSplitNode;
struct TNonSymmetricTreeStructure;
class TOnlineCtrBase;
namespace NPar {
class ILocalExecutor;
}
void UpdateIndicesWithSplit(
const TSplitNode& node,
const NCB::TTrainingDataProviders& trainingData,
const NCB::TIndexedSubset<ui32>& docsSubset,
const TFold& fold,
NPar::ILocalExecutor* localExecutor,
TArrayRef<TIndexType> indices,
NCB::TIndexedSubset<ui32>* leftIndices,
NCB::TIndexedSubset<ui32>* rightIndices
);
void UpdateIndices(
const TSplitNode& node,
const NCB::TTrainingDataProviders& trainingData,
const NCB::TIndexedSubset<ui32>& docsSubset,
const TFold& fold,
NPar::ILocalExecutor* localExecutor,
TArrayRef<TIndexType> indices
);
void BuildIndicesForDataset(
const TNonSymmetricTreeStructure& tree,
const NCB::TTrainingDataProviders& trainingData,
const TFold& fold,
ui32 sampleCount,
const TVector<const TOnlineCtrBase*>& onlineCtrs,
ui32 objectSubsetIdx, // 0 - learn, 1+ - test (subtract 1 for testIndex)
NPar::ILocalExecutor* localExecutor,
TIndexType* indices);
| 508 |
851 | /*
* Copyright (c) 2018 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdlib>
#include <string>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "modules/congestion_controller/pcc/bitrate_controller.h"
namespace webrtc {
namespace pcc {
PccBitrateController::PccBitrateController(double initial_conversion_factor,
double initial_dynamic_boundary,
double dynamic_boundary_increment,
double rtt_gradient_coefficient,
double loss_coefficient,
double throughput_coefficient,
double throughput_power,
double rtt_gradient_threshold,
double delay_gradient_negative_bound)
: PccBitrateController(initial_conversion_factor,
initial_dynamic_boundary,
dynamic_boundary_increment,
absl::make_unique<ModifiedVivaceUtilityFunction>(
rtt_gradient_coefficient,
loss_coefficient,
throughput_coefficient,
throughput_power,
rtt_gradient_threshold,
delay_gradient_negative_bound)) {}
PccBitrateController::PccBitrateController(
double initial_conversion_factor,
double initial_dynamic_boundary,
double dynamic_boundary_increment,
std::unique_ptr<PccUtilityFunctionInterface> utility_function)
: consecutive_boundary_adjustments_number_(0),
initial_dynamic_boundary_(initial_dynamic_boundary),
dynamic_boundary_increment_(dynamic_boundary_increment),
utility_function_(std::move(utility_function)),
step_size_adjustments_number_(0),
initial_conversion_factor_(initial_conversion_factor) {}
PccBitrateController::~PccBitrateController() = default;
double PccBitrateController::ComputeStepSize(double utility_gradient) {
// Computes number of consecutive step size adjustments.
if (utility_gradient > 0) {
step_size_adjustments_number_ =
std::max<int64_t>(step_size_adjustments_number_ + 1, 1);
} else if (utility_gradient < 0) {
step_size_adjustments_number_ =
std::min<int64_t>(step_size_adjustments_number_ - 1, -1);
} else {
step_size_adjustments_number_ = 0;
}
// Computes step size amplifier.
int64_t step_size_amplifier = 1;
if (std::abs(step_size_adjustments_number_) <= 3) {
step_size_amplifier =
std::max<int64_t>(std::abs(step_size_adjustments_number_), 1);
} else {
step_size_amplifier = 2 * std::abs(step_size_adjustments_number_) - 3;
}
return step_size_amplifier * initial_conversion_factor_;
}
double PccBitrateController::ApplyDynamicBoundary(double rate_change,
double bitrate) {
double rate_change_abs = std::abs(rate_change);
int64_t rate_change_sign = (rate_change > 0) ? 1 : -1;
if (consecutive_boundary_adjustments_number_ * rate_change_sign < 0) {
consecutive_boundary_adjustments_number_ = 0;
}
double dynamic_change_boundary =
initial_dynamic_boundary_ +
std::abs(consecutive_boundary_adjustments_number_) *
dynamic_boundary_increment_;
double boundary = bitrate * dynamic_change_boundary;
if (rate_change_abs > boundary) {
consecutive_boundary_adjustments_number_ += rate_change_sign;
return boundary * rate_change_sign;
}
// Rate change smaller than boundary. Reset boundary to the smallest possible
// that would allow the change.
while (rate_change_abs <= boundary &&
consecutive_boundary_adjustments_number_ * rate_change_sign > 0) {
consecutive_boundary_adjustments_number_ -= rate_change_sign;
dynamic_change_boundary =
initial_dynamic_boundary_ +
std::abs(consecutive_boundary_adjustments_number_) *
dynamic_boundary_increment_;
boundary = bitrate * dynamic_change_boundary;
}
consecutive_boundary_adjustments_number_ += rate_change_sign;
return rate_change;
}
absl::optional<DataRate>
PccBitrateController::ComputeRateUpdateForSlowStartMode(
const PccMonitorInterval& monitor_interval) {
double utility_value = utility_function_->Compute(monitor_interval);
if (previous_utility_.has_value() && utility_value <= previous_utility_) {
return absl::nullopt;
}
previous_utility_ = utility_value;
return monitor_interval.GetTargetSendingRate();
}
DataRate PccBitrateController::ComputeRateUpdateForOnlineLearningMode(
const std::vector<PccMonitorInterval>& intervals,
DataRate bandwith_estimate) {
double first_utility = utility_function_->Compute(intervals[0]);
double second_utility = utility_function_->Compute(intervals[1]);
double first_bitrate_bps = intervals[0].GetTargetSendingRate().bps();
double second_bitrate_bps = intervals[1].GetTargetSendingRate().bps();
double gradient = (first_utility - second_utility) /
(first_bitrate_bps - second_bitrate_bps);
double rate_change_bps = gradient * ComputeStepSize(gradient); // delta_r
rate_change_bps =
ApplyDynamicBoundary(rate_change_bps, bandwith_estimate.bps());
return DataRate::bps(
std::max(0.0, bandwith_estimate.bps() + rate_change_bps));
}
} // namespace pcc
} // namespace webrtc
| 2,457 |
381 | from rpython.conftest import option
from rpython.flowspace.objspace import build_flow
from rpython.flowspace.model import Variable
from rpython.flowspace.generator import (
make_generator_entry_graph, get_variable_names)
from rpython.translator.simplify import join_blocks
# ____________________________________________________________
def f_gen(n):
i = 0
while i < n:
yield i
i += 1
class GeneratorIterator(object):
def __init__(self, entry):
self.current = entry
def next(self):
e = self.current
self.current = None
if isinstance(e, Yield1):
n = e.n_0
i = e.i_0
i += 1
else:
n = e.n_0
i = 0
if i < n:
e = Yield1()
e.n_0 = n
e.i_0 = i
self.current = e
return i
raise StopIteration
def __iter__(self):
return self
class AbstractPosition(object):
_immutable_ = True
class Entry1(AbstractPosition):
_immutable_ = True
class Yield1(AbstractPosition):
_immutable_ = True
def f_explicit(n):
e = Entry1()
e.n_0 = n
return GeneratorIterator(e)
def test_explicit():
assert list(f_gen(10)) == list(f_explicit(10))
def test_get_variable_names():
lst = get_variable_names([Variable('a'), Variable('b_'), Variable('a')])
assert lst == ['g_a', 'g_b', 'g_a_']
# ____________________________________________________________
class TestGenerator:
def test_replace_graph_with_bootstrap(self):
def func(n, x, y, z):
yield n
yield n
#
graph = make_generator_entry_graph(func)
if option.view:
graph.show()
block = graph.startblock
ops = block.operations
assert ops[0].opname == 'simple_call' # e = Entry1()
assert ops[1].opname == 'setattr' # e.g_n = n
assert ops[1].args[1].value == 'g_n'
assert ops[2].opname == 'setattr' # e.g_x = x
assert ops[2].args[1].value == 'g_x'
assert ops[3].opname == 'setattr' # e.g_y = y
assert ops[3].args[1].value == 'g_y'
assert ops[4].opname == 'setattr' # e.g_z = z
assert ops[4].args[1].value == 'g_z'
assert ops[5].opname == 'simple_call' # g = GeneratorIterator(e)
assert ops[5].args[1] == ops[0].result
assert len(ops) == 6
assert len(block.exits) == 1
assert block.exits[0].target is graph.returnblock
def test_tweak_generator_graph(self):
def f(n, x, y, z):
z *= 10
yield n + 1
z -= 10
#
graph = make_generator_entry_graph(f)
func1 = graph._tweaked_func
if option.view:
graph.show()
GeneratorIterator = graph._tweaked_func._generator_next_method_of_
assert hasattr(GeneratorIterator, 'next')
#
graph_next = build_flow(GeneratorIterator.next.im_func)
join_blocks(graph_next)
if option.view:
graph_next.show()
#
graph1 = build_flow(func1)
if option.view:
graph1.show()
def test_automatic(self):
def f(n, x, y, z):
z *= 10
yield n + 1
z -= 10
#
graph = build_flow(f)
if option.view:
graph.show()
block = graph.startblock
assert len(block.exits) == 1
assert block.exits[0].target is graph.returnblock
| 1,694 |
313 | //
// YBLBriberyItemCell.h
// 手机云采
//
// Created by 乔同新 on 2017/7/25.
// Copyright © 2017年 乔同新. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "YBLBriberyItemView.h"
@interface YBLBriberyItemCell : UITableViewCell
@property (nonatomic, strong) YBLBriberyItemView *briberyMoenyView;
@end
| 143 |
416 | <filename>src/main/java/com/tencentcloudapi/pds/v20210701/PdsErrorCode.java
package com.tencentcloudapi.pds.v20210701;
public enum PdsErrorCode {
// 内部错误。
INTERNALERROR("InternalError"),
// 服务超时。
INTERNALERROR_SERVICETIMEOUT("InternalError.ServiceTimeout"),
// 参数错误。
INVALIDPARAMETER("InvalidParameter"),
// 参数取值错误。
INVALIDPARAMETERVALUE("InvalidParameterValue"),
// 超过配额限制。
LIMITEXCEEDED("LimitExceeded"),
// 重放攻击。
LIMITEXCEEDED_REPLAYATTACK("LimitExceeded.ReplayAttack"),
// 缺少参数错误。
MISSINGPARAMETER("MissingParameter"),
// 请求的次数超过了频率限制。
REQUESTLIMITEXCEEDED("RequestLimitExceeded"),
// 资源不足。
RESOURCEINSUFFICIENT("ResourceInsufficient"),
// 资源不存在。
RESOURCENOTFOUND("ResourceNotFound"),
// 未授权操作。
UNAUTHORIZEDOPERATION("UnauthorizedOperation");
private String value;
private PdsErrorCode (String value){
this.value = value;
}
/**
* @return errorcode value
*/
public String getValue() {
return value;
}
}
| 625 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-vp74-83h5-6967",
"modified": "2022-04-29T03:00:54Z",
"published": "2022-04-29T03:00:54Z",
"aliases": [
"CVE-2004-2154"
],
"details": "CUPS before 1.1.21rc1 treats a Location directive in cupsd.conf as case sensitive, which allows attackers to bypass intended ACLs via a printer name containing uppercase or lowercase letters that are different from what is specified in the directive.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2004-2154"
},
{
"type": "WEB",
"url": "https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=162405"
},
{
"type": "WEB",
"url": "https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=163274"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A9940"
},
{
"type": "WEB",
"url": "http://www.cups.org/str.php?L700"
},
{
"type": "WEB",
"url": "http://www.novell.com/linux/security/advisories/2005_18_sr.html"
},
{
"type": "WEB",
"url": "http://www.redhat.com/support/errata/RHSA-2005-571.html"
},
{
"type": "WEB",
"url": "http://www.ubuntu.com/usn/usn-185-1"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 695 |
342 | """Functions reused within command-line implementations."""
import logging
import sys
from skgenome import tabio
from .cnary import CopyNumArray as CNA
def read_cna(infile, sample_id=None, meta=None):
"""Read a CNVkit file (.cnn, .cnr, .cns) to create a CopyNumArray object."""
return tabio.read(infile, into=CNA, sample_id=sample_id, meta=meta)
def load_het_snps(vcf_fname, sample_id=None, normal_id=None,
min_variant_depth=20, zygosity_freq=None, tumor_boost=False):
if vcf_fname is None:
return None
varr = tabio.read(vcf_fname, 'vcf',
sample_id=sample_id,
normal_id=normal_id,
min_depth=min_variant_depth,
skip_somatic=True)
if (zygosity_freq is None and 'n_zygosity' in varr and
not varr['n_zygosity'].any()):
# Mutect2 sets all normal genotypes to 0/0 -- work around it
logging.warning("VCF normal sample's genotypes are all 0/0 or missing; "
"inferring genotypes from allele frequency instead")
zygosity_freq = 0.25
if zygosity_freq is not None:
varr = varr.zygosity_from_freq(zygosity_freq, 1 - zygosity_freq)
if 'n_zygosity' in varr:
# Infer & drop (more) somatic loci based on genotype
somatic_idx = (varr['zygosity'] != 0.0) & (varr['n_zygosity'] == 0.0)
if somatic_idx.any() and not somatic_idx.all():
logging.info("Skipping %d additional somatic records based on "
"T/N genotypes", somatic_idx.sum())
varr = varr[~somatic_idx]
orig_len = len(varr)
varr = varr.heterozygous()
logging.info("Kept %d heterozygous of %d VCF records",
len(varr), orig_len)
# TODO use/explore tumor_boost option
if tumor_boost:
varr['alt_freq'] = varr.tumor_boost()
return varr
def verify_sample_sex(cnarr, sex_arg, is_male_reference):
is_sample_female = cnarr.guess_xx(is_male_reference, verbose=False)
if sex_arg:
is_sample_female_given = (sex_arg.lower() not in ['y', 'm', 'male'])
if is_sample_female != is_sample_female_given:
logging.warning("Sample sex specified as %s "
"but chromosomal X/Y ploidy looks like %s",
"female" if is_sample_female_given else "male",
"female" if is_sample_female else "male")
is_sample_female = is_sample_female_given
logging.info("Treating sample %s as %s",
cnarr.sample_id or '',
"female" if is_sample_female else "male")
return is_sample_female
def write_tsv(outfname, rows, colnames=None):
"""Write rows, with optional column header, to tabular file."""
with tabio.safe_write(outfname or sys.stdout) as handle:
if colnames:
header = '\t'.join(colnames) + '\n'
handle.write(header)
handle.writelines('\t'.join(map(str, row)) + '\n'
for row in rows)
def write_text(outfname, text, *more_texts):
"""Write one or more strings (blocks of text) to a file."""
with tabio.safe_write(outfname or sys.stdout) as handle:
handle.write(text)
if more_texts:
for mtext in more_texts:
handle.write(mtext)
def write_dataframe(outfname, dframe, header=True):
"""Write a pandas.DataFrame to a tabular file."""
with tabio.safe_write(outfname or sys.stdout) as handle:
dframe.to_csv(handle, header=header,
index=False, sep='\t', float_format='%.6g')
| 1,715 |
1,131 | // 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.cloudstack.storage.configdrive;
public class ConfigDrive {
public final static String CONFIGDRIVEDIR = "configdrive";
public static final String cloudStackConfigDriveName = "/cloudstack/";
public static final String openStackConfigDriveName = "/openstack/latest/";
/**
* Creates the path to ISO file relative to mount point.
* The config driver path will have the following format: {@link #CONFIGDRIVEDIR} + / + instanceName + ".iso"
*
* @return config drive ISO file path
*/
public static String createConfigDrivePath(String instanceName) {
return ConfigDrive.CONFIGDRIVEDIR + "/" + configIsoFileName(instanceName);
}
/**
* Config Drive iso file name for an instance name
* @param instanceName
* @return
*/
public static String configIsoFileName(String instanceName) {
return instanceName + ".iso";
}
} | 492 |
724 | from . import image_cls, rand
| 10 |
19,046 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <atomic>
#include <thread>
#include <vector>
#include <folly/experimental/ReadMostlySharedPtr.h>
#include <folly/portability/GTest.h>
using folly::ReadMostlyMainPtr;
class ReadMostlySharedPtrStressTest : public ::testing::Test {};
TEST_F(ReadMostlySharedPtrStressTest, ReaderWriter) {
struct alignas(64) Data {
std::atomic<int> lastValue{};
};
const static int kNumReaders = 4;
const static int kNumIters = 100 * 1000;
Data writerDone;
writerDone.lastValue.store(0, std::memory_order_relaxed);
// How the readers tell the writer to proceed.
std::array<Data, kNumReaders> readerDone;
for (auto& data : readerDone) {
data.lastValue.store(0, std::memory_order_relaxed);
}
ReadMostlyMainPtr<int> rmmp(std::make_shared<int>(0));
std::vector<std::thread> readers(kNumReaders);
for (int threadId = 0; threadId < kNumReaders; ++threadId) {
readers[threadId] = std::thread([&, threadId] {
for (int i = 1; i < kNumIters; ++i) {
while (writerDone.lastValue.load(std::memory_order_acquire) != i) {
// Spin until the write has completed.
}
auto rmsp = rmmp.getShared();
readerDone[threadId].lastValue.store(i, std::memory_order_release);
}
});
}
for (int i = 1; i < kNumIters; ++i) {
auto sp = rmmp.getStdShared();
rmmp.reset(std::make_shared<int>(i));
writerDone.lastValue.store(i, std::memory_order_release);
for (int threadId = 0; threadId < kNumReaders; ++threadId) {
auto& myReaderDone = readerDone[threadId];
while (myReaderDone.lastValue.load(std::memory_order_acquire) != i) {
// Spin until reader has completed.
}
}
}
for (auto& thread : readers) {
thread.join();
}
}
| 850 |
1,302 | /* Copyright (c) 2019 The node-webrtc project authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE.md file in the root of the source tree. All contributing
* project authors may be found in the AUTHORS file in the root of the source
* tree.
*/
#include "src/interfaces/media_stream_track.h"
#include <webrtc/api/peer_connection_interface.h>
#include <webrtc/rtc_base/helpers.h>
#include "src/converters.h"
#include "src/converters/interfaces.h"
#include "src/enums/webrtc/track_state.h"
#include "src/interfaces/rtc_peer_connection/peer_connection_factory.h"
namespace node_webrtc {
Napi::FunctionReference& MediaStreamTrack::constructor() {
static Napi::FunctionReference constructor;
return constructor;
}
MediaStreamTrack::MediaStreamTrack(const Napi::CallbackInfo& info)
: AsyncObjectWrapWithLoop<MediaStreamTrack>("MediaStreamTrack", *this, info) {
auto env = info.Env();
if (info.Length() != 2 || !info[0].IsObject() || !info[1].IsExternal()) {
Napi::TypeError::New(env, "You cannot construct a MediaStreamTrack").ThrowAsJavaScriptException();
return;
}
// FIXME(mroberts): There is a safer conversion here.
auto factory = PeerConnectionFactory::Unwrap(info[0].ToObject());
auto track = *info[1].As<Napi::External<rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>>>().Data();
_factory = factory;
_factory->Ref();
_track = std::move(track);
_track->RegisterObserver(this);
// NOTE(mroberts): This doesn't actually matter yet.
_enabled = false;
}
MediaStreamTrack::~MediaStreamTrack() {
_track = nullptr;
Napi::HandleScope scope(PeerConnectionFactory::constructor().Env());
_factory->Unref();
_factory = nullptr;
wrap()->Release(this);
} // NOLINT
void MediaStreamTrack::Stop() {
_track->UnregisterObserver(this);
_ended = true;
_enabled = _track->enabled();
AsyncObjectWrapWithLoop<MediaStreamTrack>::Stop();
}
void MediaStreamTrack::OnChanged() {
if (_track->state() == webrtc::MediaStreamTrackInterface::TrackState::kEnded) {
Stop();
}
}
void MediaStreamTrack::OnPeerConnectionClosed() {
Stop();
}
Napi::Value MediaStreamTrack::GetEnabled(const Napi::CallbackInfo& info) {
CONVERT_OR_THROW_AND_RETURN_NAPI(info.Env(), _ended ? _enabled : _track->enabled(), result, Napi::Value)
return result;
}
void MediaStreamTrack::SetEnabled(const Napi::CallbackInfo& info, const Napi::Value& value) {
auto maybeEnabled = From<bool>(value);
if (maybeEnabled.IsInvalid()) {
Napi::TypeError::New(info.Env(), maybeEnabled.ToErrors()[0]).ThrowAsJavaScriptException();
return;
}
auto enabled = maybeEnabled.UnsafeFromValid();
if (_ended) {
_enabled = enabled;
} else {
_track->set_enabled(enabled);
}
}
Napi::Value MediaStreamTrack::GetId(const Napi::CallbackInfo& info) {
CONVERT_OR_THROW_AND_RETURN_NAPI(info.Env(), _track->id(), result, Napi::Value)
return result;
}
Napi::Value MediaStreamTrack::GetKind(const Napi::CallbackInfo& info) {
CONVERT_OR_THROW_AND_RETURN_NAPI(info.Env(), _track->kind(), result, Napi::Value)
return result;
}
Napi::Value MediaStreamTrack::GetReadyState(const Napi::CallbackInfo& info) {
auto state = _ended
? webrtc::MediaStreamTrackInterface::TrackState::kEnded
: _track->state();
CONVERT_OR_THROW_AND_RETURN_NAPI(info.Env(), state, result, Napi::Value)
return result;
}
Napi::Value MediaStreamTrack::GetMuted(const Napi::CallbackInfo& info) {
CONVERT_OR_THROW_AND_RETURN_NAPI(info.Env(), false, result, Napi::Value)
return result;
}
Napi::Value MediaStreamTrack::Clone(const Napi::CallbackInfo&) {
auto label = rtc::CreateRandomUuid();
rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> clonedTrack = nullptr;
if (_track->kind() == _track->kAudioKind) {
auto audioTrack = static_cast<webrtc::AudioTrackInterface*>(_track.get());
clonedTrack = _factory->factory()->CreateAudioTrack(label, audioTrack->GetSource());
} else {
auto videoTrack = static_cast<webrtc::VideoTrackInterface*>(_track.get());
clonedTrack = _factory->factory()->CreateVideoTrack(label, videoTrack->GetSource());
}
auto clonedMediaStreamTrack = wrap()->GetOrCreate(_factory, clonedTrack);
if (_ended) {
clonedMediaStreamTrack->Stop();
}
return clonedMediaStreamTrack->Value();
}
Napi::Value MediaStreamTrack::JsStop(const Napi::CallbackInfo& info) {
Stop();
return info.Env().Undefined();
}
Wrap <
MediaStreamTrack*,
rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>,
PeerConnectionFactory*
> * MediaStreamTrack::wrap() {
static auto wrap = new node_webrtc::Wrap <
MediaStreamTrack*,
rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>,
PeerConnectionFactory*
> (MediaStreamTrack::Create);
return wrap;
}
MediaStreamTrack* MediaStreamTrack::Create(
PeerConnectionFactory* factory,
rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track) {
auto env = constructor().Env();
Napi::HandleScope scope(env);
auto mediaStreamTrack = constructor().New({
factory->Value(),
Napi::External<rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>>::New(env, &track)
});
return Unwrap(mediaStreamTrack);
}
void MediaStreamTrack::Init(Napi::Env env, Napi::Object exports) {
auto func = DefineClass(env, "MediaStreamTrack", {
InstanceAccessor("enabled", &MediaStreamTrack::GetEnabled, &MediaStreamTrack::SetEnabled),
InstanceAccessor("id", &MediaStreamTrack::GetId, nullptr),
InstanceAccessor("kind", &MediaStreamTrack::GetKind, nullptr),
InstanceAccessor("readyState", &MediaStreamTrack::GetReadyState, nullptr),
InstanceAccessor("muted", &MediaStreamTrack::GetMuted, nullptr),
InstanceMethod("clone", &MediaStreamTrack::Clone),
InstanceMethod("stop", &MediaStreamTrack::JsStop)
});
constructor() = Napi::Persistent(func);
constructor().SuppressDestruct();
exports.Set("MediaStreamTrack", func);
}
CONVERTER_IMPL(MediaStreamTrack*, rtc::scoped_refptr<webrtc::AudioTrackInterface>, mediaStreamTrack) {
auto track = mediaStreamTrack->track();
if (track->kind() != webrtc::MediaStreamTrackInterface::kAudioKind) {
return Validation<rtc::scoped_refptr<webrtc::AudioTrackInterface>>::Invalid(
"Expected an audio MediaStreamTrack");
}
rtc::scoped_refptr<webrtc::AudioTrackInterface> audioTrack(static_cast<webrtc::AudioTrackInterface*>(track.get()));
return Pure(audioTrack);
}
CONVERTER_IMPL(MediaStreamTrack*, rtc::scoped_refptr<webrtc::VideoTrackInterface>, mediaStreamTrack) {
auto track = mediaStreamTrack->track();
if (track->kind() != webrtc::MediaStreamTrackInterface::kVideoKind) {
return Validation<rtc::scoped_refptr<webrtc::VideoTrackInterface>>::Invalid(
"Expected a video MediaStreamTrack");
}
rtc::scoped_refptr<webrtc::VideoTrackInterface> videoTrack(static_cast<webrtc::VideoTrackInterface*>(track.get()));
return Pure(videoTrack);
}
CONVERT_INTERFACE_TO_AND_FROM_NAPI(MediaStreamTrack, "MediaStreamTrack")
CONVERT_VIA(Napi::Value, MediaStreamTrack*, rtc::scoped_refptr<webrtc::AudioTrackInterface>)
CONVERT_VIA(Napi::Value, MediaStreamTrack*, rtc::scoped_refptr<webrtc::VideoTrackInterface>)
} // namespace node_webrtc
| 2,455 |
660 | package quick.pager.shop.service.impl;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import quick.pager.shop.constants.ResponseStatus;
import quick.pager.shop.goods.dto.UploadDTO;
import quick.pager.shop.goods.enums.GoodsPublishStatusEnum;
import quick.pager.shop.goods.enums.GoodsTypeEnum;
import quick.pager.shop.mapper.GoodsClassMapper;
import quick.pager.shop.mapper.GoodsMapper;
import quick.pager.shop.mapper.GoodsSkuImageMapper;
import quick.pager.shop.mapper.GoodsSkuMapper;
import quick.pager.shop.mapper.GoodsSkuStockMapper;
import quick.pager.shop.mapper.GoodsSpuMapper;
import quick.pager.shop.model.Goods;
import quick.pager.shop.model.GoodsClass;
import quick.pager.shop.goods.request.GoodsPageRequest;
import quick.pager.shop.goods.request.GoodsSaveRequest;
import quick.pager.shop.goods.response.GoodsResponse;
import quick.pager.shop.model.GoodsSku;
import quick.pager.shop.model.GoodsSkuImage;
import quick.pager.shop.model.GoodsSkuStock;
import quick.pager.shop.model.GoodsSpu;
import quick.pager.shop.service.GoodsService;
import quick.pager.shop.user.response.Response;
import quick.pager.shop.utils.DateUtils;
/**
* GoodsServiceImpl
*
* @author siguiyang
*/
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
@Autowired
private GoodsClassMapper goodsClassMapper;
@Autowired
private GoodsSkuMapper goodsSkuMapper;
@Autowired
private GoodsSpuMapper goodsSpuMapper;
@Autowired
private GoodsSkuImageMapper goodsSkuImageMapper;
@Autowired
private GoodsSkuStockMapper goodsSkuStockMapper;
private static final String SKU_PREFIX = "SKU";
@Override
public Response<List<GoodsResponse>> queryPage(GoodsPageRequest request) {
LambdaQueryWrapper<Goods> wrapper = new LambdaQueryWrapper<>();
// 检索sku名称
if (StringUtils.isNotBlank(request.getKeyword())) {
List<GoodsSku> skus = this.goodsSkuMapper.selectList(new LambdaQueryWrapper<GoodsSku>()
.like(GoodsSku::getSkuName, request.getKeyword())
.select(GoodsSku::getGoodsId));
// 商品集
wrapper.in(Goods::getId, skus.stream().map(GoodsSku::getGoodsId).collect(Collectors.toList()));
}
// 商品状态
if (Objects.nonNull(request.getState())) {
List<GoodsSku> skus = this.goodsSkuMapper.selectList(new LambdaQueryWrapper<GoodsSku>()
.eq(GoodsSku::getState, request.getState())
.select(GoodsSku::getGoodsId));
if (CollectionUtils.isEmpty(skus)) {
return Response.toResponse();
}
// 商品集
wrapper.in(Goods::getId, skus.stream().map(GoodsSku::getGoodsId).collect(Collectors.toList()));
}
// 分类
if (Objects.nonNull(request.getGoodsClassId())) {
wrapper.eq(Goods::getGoodsClassId, request.getGoodsClassId());
}
// 审核状态
if (Objects.nonNull(request.getPublishStatus())) {
wrapper.eq(Goods::getPublishStatus, request.getPublishStatus());
}
// 推荐
if (Objects.nonNull(request.getRecommend())) {
wrapper.eq(Goods::getRecommend, request.getRecommend());
}
// 新品
if (Objects.nonNull(request.getGoodsState())) {
wrapper.eq(Goods::getGoodsState, request.getGoodsState());
}
Response<List<Goods>> page = this.toPage(request.getPage(), request.getPageSize(), wrapper);
return Response.toResponse(page.getData().stream().map(this::convert).collect(Collectors.toList())
, page.getTotal());
}
@Override
@Transactional(rollbackFor = Exception.class)
public Response<Long> create(final GoodsSaveRequest request) {
// 1. 创建商品主表
Goods goods = this.convert(request);
goods.setPublishStatus(GoodsPublishStatusEnum.NONE_SHELF.getCode());
goods.setCreateTime(DateUtils.dateTime());
goods.setUpdateTime(DateUtils.dateTime());
goods.setDeleteStatus(Boolean.FALSE);
this.baseMapper.insert(goods);
// 2. 创建sku
GoodsSku sku = this.convertSku(request);
sku.setState(Boolean.FALSE);
sku.setGoodsId(goods.getId());
sku.setSkuCode(SKU_PREFIX + IdUtil.createSnowflake(1L, 5L).nextId());
sku.setCreateTime(DateUtils.dateTime());
sku.setUpdateTime(DateUtils.dateTime());
sku.setDeleteStatus(Boolean.FALSE);
this.goodsSkuMapper.insert(sku);
// 3. 插入sku 图片
GoodsSkuImage skuImage = this.convertImage(request);
skuImage.setGoodsId(goods.getId());
skuImage.setSkuId(sku.getId());
skuImage.setCreateTime(DateUtils.dateTime());
skuImage.setUpdateTime(DateUtils.dateTime());
skuImage.setDeleteStatus(Boolean.FALSE);
this.goodsSkuImageMapper.insert(skuImage);
// 4. 插入入库量
GoodsSkuStock stock = this.convertStock(request);
stock.setGoodsId(goods.getId());
stock.setSkuId(sku.getId());
stock.setCreateTime(DateUtils.dateTime());
stock.setUpdateTime(DateUtils.dateTime());
stock.setDeleteStatus(Boolean.FALSE);
this.goodsSkuStockMapper.insert(stock);
return Response.toResponse(goods.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public Response<Long> modify(final GoodsSaveRequest request) {
// 1. 更新商品主表
Goods goods = this.convert(request);
goods.setId(request.getId());
goods.setUpdateTime(DateUtils.dateTime());
this.baseMapper.updateById(goods);
// 2. 更新sku
GoodsSku sku = this.convertSku(request);
sku.setUpdateTime(DateUtils.dateTime());
this.goodsSkuMapper.update(sku, new LambdaQueryWrapper<GoodsSku>()
.eq(GoodsSku::getGoodsId, goods.getId()));
// 3. 更新sku 图片
GoodsSkuImage skuImage = this.convertImage(request);
skuImage.setUpdateTime(DateUtils.dateTime());
this.goodsSkuImageMapper.update(skuImage, new LambdaQueryWrapper<GoodsSkuImage>()
.eq(GoodsSkuImage::getGoodsId, goods.getId()));
// 4. 更新入库量
GoodsSkuStock stock = this.convertStock(request);
stock.setUpdateTime(DateUtils.dateTime());
this.goodsSkuStockMapper.update(stock, new LambdaQueryWrapper<GoodsSkuStock>()
.eq(GoodsSkuStock::getGoodsId, goods.getId()));
return Response.toResponse(goods.getId());
}
@Override
public Response<Long> state(final Long skuId) {
GoodsSku sku = this.goodsSkuMapper.selectById(skuId);
if (Objects.isNull(sku)) {
return Response.toError(ResponseStatus.Code.FAIL_CODE, "商品不存在");
}
GoodsSku updateGoodsSku = new GoodsSku();
updateGoodsSku.setId(skuId);
updateGoodsSku.setUpdateTime(DateUtils.dateTime());
updateGoodsSku.setState(!sku.getState());
this.goodsSkuMapper.updateById(updateGoodsSku);
return Response.toResponse(skuId);
}
@Override
public Response<GoodsResponse> detail(final Long id) {
Goods goods = this.baseMapper.selectById(id);
return Response.toResponse(this.convertDetail(goods));
}
@Override
@Transactional(rollbackFor = Exception.class)
public Response<Long> delete(final Long id) {
Goods goods = this.baseMapper.selectById(id);
if (Objects.isNull(goods)) {
return Response.toError(ResponseStatus.Code.FAIL_CODE, "商品主信息不存在");
}
GoodsSku sku = this.goodsSkuMapper.selectOne(new LambdaQueryWrapper<GoodsSku>().eq(GoodsSku::getGoodsId, id));
if (Objects.isNull(sku)) {
return Response.toError(ResponseStatus.Code.FAIL_CODE, "商品不存在");
}
this.baseMapper.deleteById(id);
this.goodsSkuMapper.deleteById(sku.getId());
// sku主图
GoodsSkuImage skuImage = this.goodsSkuImageMapper.selectOne(new LambdaQueryWrapper<GoodsSkuImage>()
.eq(GoodsSkuImage::getSkuId, sku.getId()));
if (Objects.nonNull(skuImage)) {
this.goodsSkuImageMapper.deleteById(skuImage.getId());
}
// 商品库存
GoodsSkuStock stock = this.goodsSkuStockMapper.selectOne(new LambdaQueryWrapper<GoodsSkuStock>()
.eq(GoodsSkuStock::getStock, sku.getId()));
if (Objects.nonNull(stock)) {
this.goodsSkuStockMapper.deleteById(stock.getId());
}
return Response.toResponse(id);
}
/**
* GoodsSaveRequest -> Goods
*
* @param request 参数
* @return goods
*/
private Goods convert(final GoodsSaveRequest request) {
Goods goods = new Goods();
goods.setGoodsType(request.getGoodsType());
goods.setRecommend(request.getRecommend());
goods.setGoodsState(request.getGoodsState());
goods.setBeginTime(request.getBeginTime());
goods.setEndTime(request.getEndTime());
goods.setGoodsClassId(request.getGoodsClassId());
goods.setUnit(request.getUnit());
goods.setUpdateUser(request.getUpdateUser());
goods.setCreateUser(request.getCreateUser());
return goods;
}
/**
* GoodsSaveRequest -> GoodsSku
*
* @param request 参数
* @return goods
*/
private GoodsSku convertSku(final GoodsSaveRequest request) {
GoodsSku sku = new GoodsSku();
sku.setSkuName(request.getSkuName());
sku.setDescription(request.getDescription());
sku.setWeight(request.getWeight());
sku.setSkuAmount(request.getSkuAmount());
sku.setDiscountAmount(request.getDiscountAmount());
sku.setUpdateUser(request.getUpdateUser());
sku.setCreateUser(request.getCreateUser());
return sku;
}
/**
* GoodsSaveRequest -> GoodsSkuImage
*
* @param request 参数
* @return goods
*/
private GoodsSkuImage convertImage(final GoodsSaveRequest request) {
GoodsSkuImage skuImage = new GoodsSkuImage();
skuImage.setImages(JSON.toJSONString(request.getImages()));
skuImage.setUpdateUser(request.getUpdateUser());
skuImage.setCreateUser(request.getCreateUser());
return skuImage;
}
/**
* GoodsSaveRequest -> GoodsSkuStock
*
* @param request 参数
* @return goods
*/
private GoodsSkuStock convertStock(final GoodsSaveRequest request) {
GoodsSkuStock stock = new GoodsSkuStock();
stock.setStock(request.getStock());
stock.setUpdateUser(request.getUpdateUser());
stock.setCreateUser(request.getCreateUser());
return stock;
}
/**
* Goods -> GoodsResponse
*
* @param goods 商品主信息
* @return 数据响应
*/
private GoodsResponse convert(final Goods goods) {
GoodsResponse response = new GoodsResponse();
response.setId(goods.getId());
response.setUnit(goods.getUnit());
response.setGoodsState(goods.getGoodsState());
response.setRecommend(goods.getRecommend());
response.setUpdateTime(goods.getUpdateTime());
response.setUpdateUser(goods.getUpdateUser());
GoodsTypeEnum typeEnum = GoodsTypeEnum.parse(goods.getGoodsType());
response.setGoodsType(goods.getGoodsType());
response.setGoodsTypeName(null != typeEnum ? typeEnum.getName() : null);
// 商品状态
GoodsPublishStatusEnum statusEnum = GoodsPublishStatusEnum.parse(goods.getPublishStatus());
response.setPublishStatus(goods.getPublishStatus());
response.setPublishStatusName(null != statusEnum ? statusEnum.getDesc() : null);
this.convert(response, goods, false);
return response;
}
/**
* Goods -> GoodsResponse
*
* @param goods 商品主信息
* @return 数据响应
*/
private GoodsResponse convertDetail(final Goods goods) {
GoodsResponse response = new GoodsResponse();
response.setId(goods.getId());
response.setUnit(goods.getUnit());
response.setGoodsState(goods.getGoodsState());
response.setRecommend(goods.getRecommend());
response.setBeginTime(goods.getBeginTime());
response.setEndTime(goods.getEndTime());
response.setGoodsType(goods.getGoodsType());
// 商品状态
response.setPublishStatus(goods.getPublishStatus());
this.convert(response, goods, true);
return response;
}
/**
* 数据转换
*
* @param response 返回对象
* @param goods 商品
*/
private void convert(final GoodsResponse response, final Goods goods, final boolean detail) {
// sku 名称
GoodsSku sku = this.goodsSkuMapper.selectOne(new LambdaQueryWrapper<GoodsSku>()
.eq(GoodsSku::getGoodsId, goods.getId()));
response.setSkuId(sku.getId());
response.setSkuName(sku.getSkuName());
response.setWeight(sku.getWeight());
response.setState(sku.getState());
response.setSkuAmount(sku.getSkuAmount());
response.setDiscountAmount(sku.getDiscountAmount());
response.setSkuCode(sku.getSkuCode());
if (detail) {
response.setDescription(sku.getDescription());
}
// spu 分类
if (Objects.nonNull(goods.getGoodsClassId())) {
GoodsClass goodsClass = this.goodsClassMapper.selectById(goods.getGoodsClassId());
GoodsSpu spu = this.goodsSpuMapper.selectOne(new LambdaQueryWrapper<GoodsSpu>()
.eq(GoodsSpu::getId, goodsClass.getSpuId())
.select(GoodsSpu::getId, GoodsSpu::getSpuName));
response.setSpuName(spu.getSpuName().concat(" / ").concat(goodsClass.getClassName()));
response.setGoodsClassId(Stream.of(spu.getId(), goodsClass.getId()).collect(Collectors.toList()));
}
// 商品图片集
GoodsSkuImage skuImage = this.goodsSkuImageMapper.selectOne(new LambdaQueryWrapper<GoodsSkuImage>()
.eq(GoodsSkuImage::getGoodsId, goods.getId())
.select(GoodsSkuImage::getImages));
response.setImages(JSON.parseArray(skuImage.getImages(), UploadDTO.class));
// 商品库存
GoodsSkuStock stock = this.goodsSkuStockMapper.selectOne(new LambdaQueryWrapper<GoodsSkuStock>()
.eq(GoodsSkuStock::getGoodsId, goods.getId())
.select(GoodsSkuStock::getStock));
response.setStock(stock.getStock());
}
}
| 6,791 |
1,703 | <reponame>giuliolovisotto/YOLOv3_TensorFlow
# coding: utf-8
# This script is used to remove the optimizer parameters in the saved checkpoint files.
# These parameters are useless in the forward process.
# Removing them will shrink the checkpoint size a lot.
import sys
sys.path.append('..')
import os
import tensorflow as tf
from model import yolov3
# params
ckpt_path = ''
class_num = 20
save_dir = 'shrinked_ckpt'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
image = tf.placeholder(tf.float32, [1, 416, 416, 3])
yolo_model = yolov3(class_num, None)
with tf.variable_scope('yolov3'):
pred_feature_maps = yolo_model.forward(image)
saver_to_restore = tf.train.Saver()
saver_to_save = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver_to_restore.restore(sess, ckpt_path)
saver_to_save.save(sess, save_dir + '/shrinked') | 347 |
1,575 | <reponame>mfkiwl/mujoco
# Copyright 2022 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""Tests for ast_nodes.py."""
from absl.testing import absltest
from google3.third_party.mujoco.introspect import ast_nodes
class AstNodesTest(absltest.TestCase):
def test_value_type(self):
value_type = ast_nodes.ValueType('int')
self.assertEqual(str(value_type), 'int')
self.assertEqual(value_type.decl('var'), 'int var')
const_value_type = ast_nodes.ValueType('double', is_const=True)
self.assertEqual(str(const_value_type), 'const double')
self.assertEqual(const_value_type.decl('var2'), 'const double var2')
def test_pointer_type(self):
pointer_type = ast_nodes.PointerType(ast_nodes.ValueType('int'))
self.assertEqual(str(pointer_type), 'int *')
self.assertEqual(pointer_type.decl('var'), 'int * var')
const_pointer_type = ast_nodes.PointerType(
ast_nodes.ValueType('double'), is_const=True)
self.assertEqual(str(const_pointer_type), 'double * const')
self.assertEqual(const_pointer_type.decl('var2'), 'double * const var2')
pointer_to_const_type = ast_nodes.PointerType(
ast_nodes.ValueType('float', is_const=True))
self.assertEqual(str(pointer_to_const_type), 'const float *')
self.assertEqual(pointer_to_const_type.decl('var3'), 'const float * var3')
restrict_volatile_pointer_to_const_type = ast_nodes.PointerType(
ast_nodes.ValueType('char', is_const=True),
is_volatile=True, is_restrict=True)
self.assertEqual(str(restrict_volatile_pointer_to_const_type),
'const char * volatile restrict')
self.assertEqual(
restrict_volatile_pointer_to_const_type.decl('var4'),
'const char * volatile restrict var4')
pointer_to_array_type = ast_nodes.PointerType(
ast_nodes.ArrayType(ast_nodes.ValueType('long'), (3,)))
self.assertEqual(str(pointer_to_array_type), 'long (*)[3]')
self.assertEqual(pointer_to_array_type.decl('var5'), 'long (* var5)[3]')
const_pointer_to_array_type = ast_nodes.PointerType(
ast_nodes.ArrayType(ast_nodes.ValueType('unsigned int'), (4,)),
is_const=True)
self.assertEqual(
str(const_pointer_to_array_type), 'unsigned int (* const)[4]')
self.assertEqual(
const_pointer_to_array_type.decl('var6'),
'unsigned int (* const var6)[4]')
def test_array_type(self):
array_type = ast_nodes.ArrayType(ast_nodes.ValueType('int'), (4,))
self.assertEqual(str(array_type), 'int [4]')
self.assertEqual(array_type.decl('var'), 'int var[4]')
array_2d_type = ast_nodes.ArrayType(
ast_nodes.ValueType('double', is_const=True), (2, 3))
self.assertEqual(str(array_2d_type), 'const double [2][3]')
self.assertEqual(array_2d_type.decl('var2'), 'const double var2[2][3]')
array_to_pointer_type = ast_nodes.ArrayType(
ast_nodes.PointerType(ast_nodes.ValueType('char', is_const=True)), (5,))
self.assertEqual(str(array_to_pointer_type), 'const char * [5]')
self.assertEqual(array_to_pointer_type.decl('var3'), 'const char * var3[5]')
array_to_const_pointer_type = ast_nodes.ArrayType(
ast_nodes.PointerType(ast_nodes.ValueType('float'), is_const=True),
(7,))
self.assertEqual(str(array_to_const_pointer_type), 'float * const [7]')
self.assertEqual(
array_to_const_pointer_type.decl('var4'), 'float * const var4[7]')
def test_complex_type(self):
complex_type = ast_nodes.ArrayType(
extents=[9],
inner_type=ast_nodes.PointerType(
ast_nodes.PointerType(
is_const=True,
inner_type=ast_nodes.ArrayType(
extents=[7],
inner_type=ast_nodes.PointerType(
is_const=True,
inner_type=ast_nodes.PointerType(
ast_nodes.ArrayType(
extents=(3, 4),
inner_type=ast_nodes.ValueType(
'unsigned int', is_const=True)
)
)
)
)
)
)
)
self.assertEqual(str(complex_type),
'const unsigned int (* * const (* const * [9])[7])[3][4]')
self.assertEqual(
complex_type.decl('var'),
'const unsigned int (* * const (* const * var[9])[7])[3][4]')
if __name__ == '__main__':
absltest.main()
| 2,259 |
1,751 | <filename>rapidoid-http-server/src/main/java/org/rapidoid/http/impl/lowlevel/HttpIO.java
/*-
* #%L
* rapidoid-http-server
* %%
* Copyright (C) 2014 - 2020 <NAME> and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.rapidoid.http.impl.lowlevel;
import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.buffer.Buf;
import org.rapidoid.data.BufRange;
import org.rapidoid.http.HttpStatus;
import org.rapidoid.http.MediaType;
import org.rapidoid.http.Req;
import org.rapidoid.http.RespBody;
import org.rapidoid.http.impl.MaybeReq;
import org.rapidoid.log.LogLevel;
import org.rapidoid.net.AsyncLogic;
import org.rapidoid.net.abstracts.Channel;
import java.io.ByteArrayOutputStream;
import java.util.Map;
@Authors("<NAME>")
@Since("5.1.0")
public class HttpIO extends RapidoidThing {
public static final HttpIO INSTANCE = new HttpIO();
private final LowLevelHttpIO impl = new LowLevelHttpIO();
public void removeTrailingSlash(Buf buf, BufRange range) {
impl.removeTrailingSlash(buf, range);
}
public void writeResponse(MaybeReq req, Channel ctx, boolean isKeepAlive, int code, MediaType contentTypeHeader, byte[] content) {
impl.writeResponse(req, ctx, isKeepAlive, code, contentTypeHeader, content);
}
public void write200(MaybeReq req, Channel ctx, boolean isKeepAlive, MediaType contentTypeHeader, byte[] content) {
impl.write200(req, ctx, isKeepAlive, contentTypeHeader, content);
}
public void error(Req req, Throwable error, LogLevel logLevel) {
impl.error(req, error, logLevel);
}
public HttpStatus errorAndDone(Req req, Throwable error, LogLevel logLevel) {
return impl.errorAndDone(req, error, logLevel);
}
public void writeContentLengthAndBody(MaybeReq req, Channel ctx, ByteArrayOutputStream body) {
impl.writeContentLengthAndBody(req, ctx, body);
}
public void writeContentLengthHeader(Channel ctx, int len) {
impl.writeContentLengthHeader(ctx, len);
}
public void writeHttpResp(MaybeReq req, Channel ctx, boolean isKeepAlive, int code, MediaType contentType, Object value) {
impl.writeHttpResp(req, ctx, isKeepAlive, code, contentType, value);
}
public void done(Req req) {
impl.done(req);
}
public void resume(MaybeReq maybeReq, Channel channel, AsyncLogic logic) {
impl.resume(maybeReq, channel, logic);
}
public void writeBadRequest(Channel channel) {
impl.writeBadRequest(channel);
}
public void respond(MaybeReq maybeReq, Channel channel, long connId, long handle,
int code, boolean isKeepAlive, MediaType contentType,
RespBody body, Map<String, String> headers, Map<String, String> cookies) {
impl.respond(maybeReq, channel, connId, handle, code, isKeepAlive, contentType, body, headers, cookies);
}
public void closeHeaders(MaybeReq req, Buf out) {
impl.closeHeaders(req, out);
}
}
| 1,280 |
474 | <filename>javacord-core/src/main/java/org/javacord/core/interaction/InteractionImmediateResponseBuilderImpl.java<gh_stars>100-1000
package org.javacord.core.interaction;
import org.javacord.api.interaction.InteractionBase;
import org.javacord.api.interaction.callback.InteractionImmediateResponseBuilder;
import org.javacord.api.interaction.callback.InteractionOriginalResponseUpdater;
import java.util.concurrent.CompletableFuture;
public class InteractionImmediateResponseBuilderImpl
extends ExtendedInteractionMessageBuilderBaseImpl<InteractionImmediateResponseBuilder>
implements InteractionImmediateResponseBuilder {
private final InteractionImpl interaction;
/**
* Class constructor.
*
* @param interaction The interaction to use.
*/
public InteractionImmediateResponseBuilderImpl(InteractionBase interaction) {
super(InteractionImmediateResponseBuilder.class);
this.interaction = (InteractionImpl) interaction;
}
@Override
public CompletableFuture<InteractionOriginalResponseUpdater> respond() {
CompletableFuture<InteractionOriginalResponseUpdater> future = new CompletableFuture<>();
CompletableFuture<Void> job = delegate.sendInitialResponse(interaction)
.thenRun(() -> {
future.complete(new InteractionOriginalResponseUpdaterImpl(interaction, delegate));
})
.exceptionally(e -> {
future.completeExceptionally(e);
return null;
});
return future;
}
}
| 580 |
9,724 | <reponame>albertobarri/idk<gh_stars>1000+
/*
* Copyright 2020 The Emscripten Authors. All rights reserved.
* Emscripten is available under two separate licenses, the MIT license and the
* University of Illinois/NCSA Open Source License. Both these licenses can be
* found in the LICENSE file.
*/
#include <tmmintrin.h>
#include "benchmark_sse.h"
int main()
{
printf ("{ \"workload\": %u, \"results\": [\n", N);
float *src_flt = alloc_float_buffer();
float *src2_flt = alloc_float_buffer();
float *dst_flt = alloc_float_buffer();
for(int i = 0; i < N; ++i) src_flt[i] = (float)(1.0 + (double)rand() / RAND_MAX);
for(int i = 0; i < N; ++i) src2_flt[i] = (float)(1.0 + (double)rand() / RAND_MAX);
double *src_dbl = alloc_double_buffer();
double *src2_dbl = alloc_double_buffer();
double *dst_dbl = alloc_double_buffer();
for(int i = 0; i < N; ++i) src_dbl[i] = 1.0 + (double)rand() / RAND_MAX;
for(int i = 0; i < N; ++i) src2_dbl[i] = 1.0 + (double)rand() / RAND_MAX;
int *src_int = alloc_int_buffer();
int *src2_int = alloc_int_buffer();
int *dst_int = alloc_int_buffer();
for(int i = 0; i < N; ++i) src_int[i] = rand();
for(int i = 0; i < N; ++i) src2_int[i] = rand();
float scalarTime = 0.f;
// Benchmarks start:
SETCHART("abs");
UNARYOP_I_I("_mm_abs_epi8", _mm_abs_epi8, _mm_load_si128((__m128i*)src_int));
UNARYOP_I_I("_mm_abs_epi16", _mm_abs_epi16, _mm_load_si128((__m128i*)src_int));
UNARYOP_I_I("_mm_abs_epi32", _mm_abs_epi32, _mm_load_si128((__m128i*)src_int));
// TODO _mm_alignr_epi8
SETCHART("horizontal add");
BINARYOP_I_II("_mm_hadd_epi16", _mm_hadd_epi16, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
BINARYOP_I_II("_mm_hadd_epi32", _mm_hadd_epi32, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
BINARYOP_I_II("_mm_hadds_epi16", _mm_hadds_epi16, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
SETCHART("horizontal sub");
BINARYOP_I_II("_mm_hsub_epi16", _mm_hsub_epi16, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
BINARYOP_I_II("_mm_hsub_epi32", _mm_hsub_epi32, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
BINARYOP_I_II("_mm_hsubs_epi16", _mm_hsubs_epi16, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
SETCHART("mul & shuffle");
BINARYOP_I_II("_mm_maddubs_epi16", _mm_maddubs_epi16, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
BINARYOP_I_II("_mm_mulhrs_epi16", _mm_mulhrs_epi16, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
BINARYOP_I_II("_mm_shuffle_epi8", _mm_shuffle_epi8, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
SETCHART("sign");
BINARYOP_I_II("_mm_sign_epi8", _mm_sign_epi8, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
BINARYOP_I_II("_mm_sign_epi16", _mm_sign_epi16, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
BINARYOP_I_II("_mm_sign_epi32", _mm_sign_epi32, _mm_load_si128((__m128i*)src_int), _mm_load_si128((__m128i*)src2_int));
// Benchmarks end:
printf("]}\n");
}
| 1,512 |
5,937 | <reponame>txlos/wpf
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//+----------------------------------------------------------------------------
//
//
// Abstract:
// Definitions of class CAssembleContext and its derivatives.
//
//-----------------------------------------------------------------------------
#pragma once
class COperator;
class CVarState;
class CMapper;
//+-----------------------------------------------------------------------------
//
// Class:
// CAssembleContext
//
// Synopsis:
// Hooks program context to low level code generator.
// Serves as an argument of COperator::Assemble() so that
// the latter can access current operator and CCoder86.
//
// CAssembleContext is abstract: virtual Emit() members
// declared in CCoder86 are not defined. They are defined
// in two CAssembleContext derivatives, CAssemblePass1 and
// CAssemblePass2. Pass 1 is idle: Emit() calls do not
// store the code but during this pass we can accumulate
// labes offsets and get to know final size of binary code.
// Pass 2 executes real job.
//
// Usage pattern:
// See CProgram::Assemble()
//
//-----------------------------------------------------------------------------
class CAssembleContext : public CCoder86
{
public:
CAssembleContext(CMapper const & mapper, bool fUseNegativeStackOffsets);
void AssemblePrologue(
__in UINT32 uFrameSize,
__in UINT32 uFrameAlignment
);
#if DBG_DUMP
void AssembleProgram(CProgram * pProgram, bool fDumpEnabled);
#else
void AssembleProgram(CProgram * pProgram);
#endif //DBG_DUMP
UINT32 GetOperatorFlags() const
{
return m_uOperatorFlags;
}
memptr FramePtr(UINT32 nDisplacement) const
{
return memptr(gsp, (INT32)(nDisplacement - m_uEspOffset));
}
virtual void* Place(void* pData, UINT32 dataType) = 0;
UINT32 GetOffset(UINT32 uVarID) const;
UINT32 GetEspOffset() const { return m_uEspOffset; }
public:
// Offset from ebp to 1st argument, see AssemblePrologue().
#if WPFGFX_FXJIT_X86
// 8 = 4 bytes for saved ebp + 4 bytes for ret adds.
static const int sc_uArgOffset = 8;
#else //_AMD64_
// 16 = 8 bytes for saved rbp + 8 bytes for ret adds.
static const int sc_uArgOffset = 16;
#endif
CMapper const & m_mapper;
protected:
// Offset from stack frame bottom to the position pointed by esp/rsp register.
// This offset is used to reduce code size by involving negative displacement values.
UINT32 m_uEspOffset;
private:
COperator *m_pCurrentOperator;
UINT32 m_uOperatorFlags;
};
//+-----------------------------------------------------------------------------
//
// Class:
// CAssemblePass1
//
// Synopsis:
// Idle implementation of CAssembleContext.
// Contains Emit() functions that do not store data
// but calculate amount of storage needed for binary code.
//
//-----------------------------------------------------------------------------
class CAssemblePass1 : public CAssembleContext
{
public:
CAssemblePass1(CMapper const & mapper, bool fUseNegativeStackOffsets) : CAssembleContext(mapper, fUseNegativeStackOffsets) {}
void Emit(UINT32 /*data*/) {m_uCount++;}
void Emit4(UINT32 /*data*/) {m_uCount += 4;}
void EmitOpcode(UINT32 opcode)
{
UINT32 uDelta = (opcode & OpcSize) >> OpcShiftSize;
#if WPFGFX_FXJIT_X86
#else // _AMD64_
if (opcode & OpcREX)
{
uDelta++;
}
#endif
m_uCount += uDelta;
}
UINT_PTR GetBase() const {return 0;}
void* Place(void* pData, UINT32 /*dataType*/) {return pData;}
};
//+-----------------------------------------------------------------------------
//
// Class:
// CAssemblePass2
//
// Synopsis:
// Final pass implementation of CAssembleContext.
// Contains Emit() functions that store binary code into the
// given memory.
//
//-----------------------------------------------------------------------------
class CAssemblePass2 : public CAssembleContext
{
public:
CAssemblePass2(
CMapper const & mapper,
bool fUseNegativeStackOffsets,
UINT8 * pData,
INT_PTR uStatic4Offset,
INT_PTR uStatic8Offset,
INT_PTR uStatic16Offset
);
void Emit(UINT32 data) {m_pData[m_uCount++] = static_cast<UINT8>(data);}
void Emit4(UINT32 data)
{
m_pData[m_uCount ] = static_cast<UINT8>(data );
m_pData[m_uCount + 1] = static_cast<UINT8>(data >> 8);
m_pData[m_uCount + 2] = static_cast<UINT8>(data >> 16);
m_pData[m_uCount + 3] = static_cast<UINT8>(data >> 24);
m_uCount += 4;
}
void EmitOpcode(UINT32 opcode)
{
#if DBG
UINT32 uNextCount = m_uCount + ((opcode & OpcSize) >> OpcShiftSize);
#endif
C_ASSERT(Prefix_None == 0 && Prefix_F20F == 1 && Prefix_F30F == 2 && Prefix_660F == 3);
static const UINT32 prefixes[4] = { 0, 0xF20F, 0xF30F, 0x660F };
UINT32 prefix = prefixes[(opcode & OpcPrefix) >> OpcShiftPrefix];
if (prefix)
{
m_pData[m_uCount++] = static_cast<UINT8>(prefix >> 8);
}
#if WPFGFX_FXJIT_X86
#else // _AMD64_
if (opcode & OpcREX)
{
#if DBG
uNextCount++;
#endif
m_pData[m_uCount++] = static_cast<UINT8>( ( (opcode & OpcREX) >> OpcShiftREX) | 0x40);
}
#endif
if (prefix)
{
m_pData[m_uCount++] = static_cast<UINT8>(prefix);
}
if (opcode & OpcIsLong)
{
m_pData[m_uCount++] = static_cast<UINT8>( (opcode & OpcByte1) >> OpcShiftByte1);
}
m_pData[m_uCount++] = static_cast<UINT8>( (opcode & OpcByte2) >> OpcShiftByte2);
WarpAssert(m_uCount == uNextCount);
}
UINT_PTR GetBase() const
{
return reinterpret_cast<UINT_PTR>(m_pData);
}
void* Place(void* pData, UINT32 dataType);
private:
UINT8* const m_pData;
INT_PTR const m_uStatic4Offset;
INT_PTR const m_uStatic8Offset;
INT_PTR const m_uStatic16Offset;
};
| 2,476 |
918 | /*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* Copyright (c) 2009 <NAME>
* Copyright (c) 2012 <NAME>
* Copyright (c) 2014 <NAME>
*/
/*!
* \file atomic/detail/ops_windows.hpp
*
* This header contains implementation of the \c operations template.
*
* This implementation is the most basic version for Windows. It should
* work for any non-MSVC-like compilers as long as there are Interlocked WinAPI
* functions available. This version is also used for WinCE.
*
* Notably, this implementation is not as efficient as other
* versions based on compiler intrinsics.
*/
#ifndef BOOST_ATOMIC_DETAIL_OPS_WINDOWS_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_OPS_WINDOWS_HPP_INCLUDED_
#include <cstddef>
#include <boost/memory_order.hpp>
#include <boost/atomic/detail/config.hpp>
#include <boost/atomic/detail/interlocked.hpp>
#include <boost/atomic/detail/storage_type.hpp>
#include <boost/atomic/detail/operations_fwd.hpp>
#include <boost/atomic/detail/type_traits/make_signed.hpp>
#include <boost/atomic/capabilities.hpp>
#include <boost/atomic/detail/ops_msvc_common.hpp>
#include <boost/atomic/detail/ops_extending_cas_based.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
namespace boost {
namespace atomics {
namespace detail {
struct windows_operations_base
{
static BOOST_CONSTEXPR_OR_CONST bool is_always_lock_free = true;
static BOOST_FORCEINLINE void hardware_full_fence() BOOST_NOEXCEPT
{
long tmp;
BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&tmp, 0);
}
static BOOST_FORCEINLINE void fence_before(memory_order) BOOST_NOEXCEPT
{
BOOST_ATOMIC_DETAIL_COMPILER_BARRIER();
}
static BOOST_FORCEINLINE void fence_after(memory_order) BOOST_NOEXCEPT
{
BOOST_ATOMIC_DETAIL_COMPILER_BARRIER();
}
};
template< typename T, typename Derived >
struct windows_operations :
public windows_operations_base
{
typedef T storage_type;
static BOOST_FORCEINLINE void store(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
{
Derived::exchange(storage, v, order);
}
static BOOST_FORCEINLINE storage_type load(storage_type const volatile& storage, memory_order order) BOOST_NOEXCEPT
{
return Derived::fetch_add(const_cast< storage_type volatile& >(storage), (storage_type)0, order);
}
static BOOST_FORCEINLINE storage_type fetch_sub(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
{
typedef typename boost::atomics::detail::make_signed< storage_type >::type signed_storage_type;
return Derived::fetch_add(storage, static_cast< storage_type >(-static_cast< signed_storage_type >(v)), order);
}
static BOOST_FORCEINLINE bool compare_exchange_weak(
storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order success_order, memory_order failure_order) BOOST_NOEXCEPT
{
return Derived::compare_exchange_strong(storage, expected, desired, success_order, failure_order);
}
static BOOST_FORCEINLINE bool test_and_set(storage_type volatile& storage, memory_order order) BOOST_NOEXCEPT
{
return !!Derived::exchange(storage, (storage_type)1, order);
}
static BOOST_FORCEINLINE void clear(storage_type volatile& storage, memory_order order) BOOST_NOEXCEPT
{
store(storage, (storage_type)0, order);
}
};
template< bool Signed >
struct operations< 4u, Signed > :
public windows_operations< typename make_storage_type< 4u, Signed >::type, operations< 4u, Signed > >
{
typedef windows_operations< typename make_storage_type< 4u, Signed >::type, operations< 4u, Signed > > base_type;
typedef typename base_type::storage_type storage_type;
typedef typename make_storage_type< 4u, Signed >::aligned aligned_storage_type;
static BOOST_CONSTEXPR_OR_CONST std::size_t storage_size = 4u;
static BOOST_CONSTEXPR_OR_CONST bool is_signed = Signed;
static BOOST_FORCEINLINE storage_type fetch_add(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
{
base_type::fence_before(order);
v = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD(&storage, v));
base_type::fence_after(order);
return v;
}
static BOOST_FORCEINLINE storage_type exchange(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
{
base_type::fence_before(order);
v = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&storage, v));
base_type::fence_after(order);
return v;
}
static BOOST_FORCEINLINE bool compare_exchange_strong(
storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order success_order, memory_order failure_order) BOOST_NOEXCEPT
{
storage_type previous = expected;
base_type::fence_before(success_order);
storage_type old_val = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(&storage, desired, previous));
expected = old_val;
// The success and failure fences are the same anyway
base_type::fence_after(success_order);
return (previous == old_val);
}
static BOOST_FORCEINLINE storage_type fetch_and(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
{
#if defined(BOOST_ATOMIC_INTERLOCKED_AND)
base_type::fence_before(order);
v = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_AND(&storage, v));
base_type::fence_after(order);
return v;
#else
storage_type res = storage;
while (!compare_exchange_strong(storage, res, res & v, order, memory_order_relaxed)) {}
return res;
#endif
}
static BOOST_FORCEINLINE storage_type fetch_or(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
{
#if defined(BOOST_ATOMIC_INTERLOCKED_OR)
base_type::fence_before(order);
v = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_OR(&storage, v));
base_type::fence_after(order);
return v;
#else
storage_type res = storage;
while (!compare_exchange_strong(storage, res, res | v, order, memory_order_relaxed)) {}
return res;
#endif
}
static BOOST_FORCEINLINE storage_type fetch_xor(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
{
#if defined(BOOST_ATOMIC_INTERLOCKED_XOR)
base_type::fence_before(order);
v = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_XOR(&storage, v));
base_type::fence_after(order);
return v;
#else
storage_type res = storage;
while (!compare_exchange_strong(storage, res, res ^ v, order, memory_order_relaxed)) {}
return res;
#endif
}
};
template< bool Signed >
struct operations< 1u, Signed > :
public extending_cas_based_operations< operations< 4u, Signed >, 1u, Signed >
{
};
template< bool Signed >
struct operations< 2u, Signed > :
public extending_cas_based_operations< operations< 4u, Signed >, 2u, Signed >
{
};
BOOST_FORCEINLINE void thread_fence(memory_order order) BOOST_NOEXCEPT
{
BOOST_ATOMIC_DETAIL_COMPILER_BARRIER();
if (order == memory_order_seq_cst)
windows_operations_base::hardware_full_fence();
BOOST_ATOMIC_DETAIL_COMPILER_BARRIER();
}
BOOST_FORCEINLINE void signal_fence(memory_order order) BOOST_NOEXCEPT
{
if (order != memory_order_relaxed)
BOOST_ATOMIC_DETAIL_COMPILER_BARRIER();
}
} // namespace detail
} // namespace atomics
} // namespace boost
#endif // BOOST_ATOMIC_DETAIL_OPS_WINDOWS_HPP_INCLUDED_
| 3,055 |
990 | #
# 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.
#
from pyspark.ml.param import *
from ai.h2o.sparkling.ml.params.H2OTypeConverters import H2OTypeConverters
class HasGamCols(Params):
gamCols = Param(
Params._dummy(),
"gamCols",
"Arrays of predictor column names for gam for smoothers using single or multiple predictors "
"like {{'c1'},{'c2','c3'},{'c4'},...}",
H2OTypeConverters.toNullableListListString())
def getGamCols(self):
return self.getOrDefault(self.gamCols)
def setGamCols(self, value):
return self._set(gamCols=self._convertGamCols(value))
def _toStringArray(self, value):
if isinstance(value, list):
return value
else:
return [str(value)]
def _convertGamCols(self, value):
if isinstance(value, list):
return [self._toStringArray(item) for item in value]
else:
return value
def _updateInitKwargs(self, kwargs):
if 'gamCols' in kwargs:
kwargs['gamCols'] = self._convertGamCols(kwargs['gamCols'])
return kwargs
| 683 |
9,681 | from django.shortcuts import render, HttpResponse
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D
from django.contrib.gis.db.models.functions import Distance
from django.contrib.gis.db.models import Union
from .models import Collection, Collection2
# Create your views here.
def vuln(request):
query = request.GET.get('q', default=0.05)
qs = Collection.objects.annotate(
d=Distance(
Point(0.01, 0.01, srid=4326),
Point(0.01, 0.01, srid=4326),
tolerance=query,
),
).filter(d=D(m=1)).values('name')
return HttpResponse(qs)
def vuln2(request):
query = request.GET.get('q')
qs = Collection2.objects.aggregate(
Union('point', tolerance=query),
).values()
return HttpResponse(qs) | 335 |
1,338 | #include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
uint8_t sector[512];
int main(int argc, char **argv)
{
int fd, i;
uint16_t sum;
uint8_t *p = sector;
fd = open(argv[1], O_RDWR);
if (fd < 0) {
return 1;
}
if (read(fd, sector, 512-2) < 512-2) {
perror("read");
return 1;
}
for (sum = 0, i = 0; i < (512-2)/2; i++) {
uint16_t v;
v = *p++ << 8;
v += *p++;
sum += v;
}
sum = 0x1234 - sum /*+ 1*/;
//sum = 0xaa55;
// big endian
*p++ = (uint8_t)(sum >> 8);
*p++ = (uint8_t)sum;
//lseek(fd, 0LL, SEEK_SET);
write(fd, §or[512-2], 2);
close(fd);
return 0;
}
| 329 |
6,989 | <filename>contrib/libs/linuxvdso/interface.cpp
#include "interface.h"
#include "original/vdso_support.h"
#ifdef HAVE_VDSO_SUPPORT
size_t NVdso::Enumerate(TSymbol* s, size_t len) {
if (!len) {
return 0;
}
base::VDSOSupport vdso;
if (!vdso.IsPresent()) {
return 0;
}
size_t n = 0;
for (base::VDSOSupport::SymbolIterator it = vdso.begin(); it != vdso.end(); ++it) {
*s++ = TSymbol(it->name, (void*)it->address);
++n;
if (!--len) {
break;
}
}
return n;
}
void* NVdso::Function(const char* name, const char* version) {
base::VDSOSupport::SymbolInfo info;
// Have to cast away the `const` to make this reinterpret_cast-able to a function pointer.
return base::VDSOSupport().LookupSymbol(name, version, STT_FUNC, &info) ? (void*) info.address : nullptr;
}
#else
size_t NVdso::Enumerate(TSymbol*, size_t) {
return 0;
}
void* NVdso::Function(const char*, const char*) {
return nullptr;
}
#endif
| 457 |
4,013 | from checkov.terraform.checks.data.base_registry import Registry
data_registry = Registry()
| 28 |
369 | #
#
#
from __future__ import absolute_import, division, print_function, \
unicode_literals
from os import path
from os.path import dirname, isfile
from unittest import TestCase
from octodns.provider.etc_hosts import EtcHostsProvider
from octodns.provider.plan import Plan
from octodns.record import Record
from octodns.zone import Zone
from helpers import TemporaryDirectory
class TestEtcHostsProvider(TestCase):
def test_provider(self):
source = EtcHostsProvider('test', path.join(dirname(__file__),
'config'))
zone = Zone('unit.tests.', [])
# We never populate anything, when acting as a source
source.populate(zone, target=source)
self.assertEquals(0, len(zone.records))
# Same if we're acting as a target
source.populate(zone)
self.assertEquals(0, len(zone.records))
record = Record.new(zone, '', {
'ttl': 60,
'type': 'ALIAS',
'value': 'www.unit.tests.'
})
zone.add_record(record)
record = Record.new(zone, 'www', {
'ttl': 60,
'type': 'AAAA',
'value': 'fc00:db20:35b:7399::5',
})
zone.add_record(record)
record = Record.new(zone, 'www', {
'ttl': 60,
'type': 'A',
'values': ['1.1.1.1', '2.2.2.2'],
})
zone.add_record(record)
record = record.new(zone, 'v6', {
'ttl': 60,
'type': 'AAAA',
'value': 'fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b',
})
zone.add_record(record)
record = record.new(zone, 'start', {
'ttl': 60,
'type': 'CNAME',
'value': 'middle.unit.tests.',
})
zone.add_record(record)
record = record.new(zone, 'middle', {
'ttl': 60,
'type': 'CNAME',
'value': 'unit.tests.',
})
zone.add_record(record)
record = record.new(zone, 'ext', {
'ttl': 60,
'type': 'CNAME',
'value': 'github.com.',
})
zone.add_record(record)
record = record.new(zone, '*', {
'ttl': 60,
'type': 'A',
'value': '3.3.3.3',
})
zone.add_record(record)
with TemporaryDirectory() as td:
# Add some subdirs to make sure that it can create them
directory = path.join(td.dirname, 'sub', 'dir')
hosts_file = path.join(directory, 'unit.tests.hosts')
target = EtcHostsProvider('test', directory)
# We add everything
plan = target.plan(zone)
self.assertEquals(len(zone.records), len(plan.changes))
self.assertFalse(isfile(hosts_file))
# Now actually do it
self.assertEquals(len(zone.records), target.apply(plan))
self.assertTrue(isfile(hosts_file))
with open(hosts_file) as fh:
data = fh.read()
# v6
self.assertTrue('2001:4860:4860::8844\tv6.unit.tests' in data)
# www
self.assertTrue('1.1.1.1\twww.unit.tests' in data)
# root ALIAS
self.assertTrue('# unit.tests -> www.unit.tests' in data)
self.assertTrue('1.1.1.1\tunit.tests' in data)
self.assertTrue('# start.unit.tests -> middle.unit.tests' in
data)
self.assertTrue('# middle.unit.tests -> unit.tests' in data)
self.assertTrue('# unit.tests -> www.unit.tests' in data)
self.assertTrue('1.1.1.1 start.unit.tests' in data)
# second empty run that won't create dirs and overwrites file
plan = Plan(zone, zone, [], True)
self.assertEquals(0, target.apply(plan))
def test_cname_loop(self):
source = EtcHostsProvider('test', path.join(dirname(__file__),
'config'))
zone = Zone('unit.tests.', [])
# We never populate anything, when acting as a source
source.populate(zone, target=source)
self.assertEquals(0, len(zone.records))
# Same if we're acting as a target
source.populate(zone)
self.assertEquals(0, len(zone.records))
record = Record.new(zone, 'start', {
'ttl': 60,
'type': 'CNAME',
'value': 'middle.unit.tests.',
})
zone.add_record(record)
record = Record.new(zone, 'middle', {
'ttl': 60,
'type': 'CNAME',
'value': 'loop.unit.tests.',
})
zone.add_record(record)
record = Record.new(zone, 'loop', {
'ttl': 60,
'type': 'CNAME',
'value': 'start.unit.tests.',
})
zone.add_record(record)
with TemporaryDirectory() as td:
# Add some subdirs to make sure that it can create them
directory = path.join(td.dirname, 'sub', 'dir')
hosts_file = path.join(directory, 'unit.tests.hosts')
target = EtcHostsProvider('test', directory)
# We add everything
plan = target.plan(zone)
self.assertEquals(len(zone.records), len(plan.changes))
self.assertFalse(isfile(hosts_file))
# Now actually do it
self.assertEquals(len(zone.records), target.apply(plan))
self.assertTrue(isfile(hosts_file))
with open(hosts_file) as fh:
data = fh.read()
self.assertTrue('# loop.unit.tests -> start.unit.tests '
'**loop**' in data)
self.assertTrue('# middle.unit.tests -> loop.unit.tests '
'**loop**' in data)
self.assertTrue('# start.unit.tests -> middle.unit.tests '
'**loop**' in data)
| 3,139 |
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 EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX
#define EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX
#include <rtl/ustring.hxx>
#include "abptypes.hxx"
#include <com/sun/star/uno/Reference.hxx>
#include "addresssettings.hxx"
namespace com { namespace sun { namespace star {
namespace lang {
class XMultiServiceFactory;
}
namespace beans {
class XPropertySet;
}
} } }
class Window;
//.........................................................................
namespace abp
{
//.........................................................................
//.....................................................................
namespace fieldmapping
{
//.....................................................................
//-----------------------------------------------------------------
/** invokes the field mapping dialog
@param _rxORB
service factory to use for creating UNO services
@param _pParent
window to use as parent for the dialog and error messages
@param _rSettings
current settings. Upon return, the field mapping member of this
structure will be filled with the settings the user did in the
field mapping dialog.
*/
sal_Bool invokeDialog(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
class Window* _pParent,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDataSource,
AddressSettings& _rSettings
) SAL_THROW ( ( ) );
//-----------------------------------------------------------------
/** creates a default field mapping for usage with the address book SDBC driver
<p>The column names as used by the SDBC driver for address books is stored in the configuration,
and this function creates a mapping which uses this configuration information.</p>
*/
void defaultMapping(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
MapString2String& /* [out] */ _rFieldAssignment
) SAL_THROW ( ( ) );
//-----------------------------------------------------------------
/** writes a field mapping for the template document address source
*/
void writeTemplateAddressFieldMapping(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
const MapString2String& _rFieldAssignment
) SAL_THROW ( ( ) );
//.....................................................................
} // namespace fieldmapping
//.....................................................................
//.....................................................................
namespace addressconfig
{
//.....................................................................
//-----------------------------------------------------------------
/** writes the data source / table name given into the configuration, to where the template documents
expect it.
*/
void writeTemplateAddressSource(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
const ::rtl::OUString& _rDataSourceName,
const ::rtl::OUString& _rTableName
) SAL_THROW ( ( ) );
/** writes the configuration entry which states the pilot has been completed successfully
*/
void markPilotSuccess(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
) SAL_THROW ( ( ) );
//.....................................................................
} // namespace addressconfig
//.....................................................................
//.........................................................................
} // namespace abp
//.........................................................................
#endif // EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX
| 1,223 |
839 | #include "Polycode.h"
#include "PolycodeView.h"
#include "PolycodeLinuxPlayer.h"
int main(int argc, char *argv[]) {
PolycodeView *view = new PolycodeView("Polycode Player");
if(argc < 2) {
printf("Filename required!\n");
return 1;
}
PolycodeLinuxPlayer *player = new PolycodeLinuxPlayer(view, argv[1], false, true);
player->runPlayer();
while(player->Update()) {}
delete player;
return 0;
}
| 147 |
1,615 | <filename>MLN-Android/mmui/src/main/jni/bridge/mmui_vm_auto_fill.c
/**
* Created by MomoLuaNative.
* Copyright (c) 2020, Momo Group. All rights reserved.
*
* This source code is licensed under the MIT.
* For the full copyright and license information,please view the LICENSE file in the root directory of this source tree.
*/
//
// Created by MOMO on 2020/8/20.
//
#include <jni.h>
#include <lua_include/lapi.h>
#include <jfunction.h>
#include <lua_include/lauxlib.h>
extern jclass LuaValue;
#if defined(J_API_INFO)
/// 为了在开发阶段调用 luaTableKeyPathTrackCode 代码里的
/// lua函数:getAllKeyPath,并且获取全局变量:KeyPathMap。
/// 此时栈顶是全局变量 KeyPathMap
/// \param LS lua 虚拟机指针
/// \param erridx 从lua虚拟机中获取的 getErrorFunctionIndex
void getOriginKeyPath(lua_State *LS, int erridx) {
lua_pushvalue(LS, -1);
lua_getglobal(LS, "getAllKeyPath");
lua_insert(LS, -2);
lua_pcall(LS, 1, 0, erridx);
lua_getglobal(LS, "KeyPathMap");
}
#endif
JNIEXPORT jobjectArray JNICALL
Java_com_immomo_mmui_MMUIAutoFillCApi__1autoFill(JNIEnv *env, jclass clazz, jlong L,
jstring function, jboolean compareSwitch, jobjectArray params,
jint rc) {
lua_State *LS = (lua_State *) L;
lua_lock(LS);
int erridx = getErrorFunctionIndex(LS);
int oldTop = lua_gettop(LS);
const char *_function = GetString(env, function);
int res = luaL_loadstring(LS, _function);
if (res != 0) { // error occur
throwJavaError(env, LS);
lua_pop(LS, 1);
lua_unlock(LS);
return NULL;
}
lua_pcall(LS, 0, -1, erridx); // 先返回真正的function,此时在栈顶
int len = pushJavaArray(env, LS, params);
int ret = lua_pcall(LS, len, (int) rc, erridx);
if (ret != 0) {
throwJavaError(env, LS);
lua_settop(LS, oldTop);
lua_unlock(LS);
return NULL;
}
#if defined(J_API_INFO)
if (compareSwitch) {
getOriginKeyPath(LS, erridx);
}
#endif
int returnCount = lua_gettop(LS) - oldTop;
if (returnCount == 0) {
lua_settop(LS, oldTop);
// lua_pop(LS, 1);
lua_unlock(LS);
return NULL;
}
int i;
jobjectArray r = (*env)->NewObjectArray(env, returnCount, LuaValue, NULL);
for (i = returnCount - 1; i >= 0; i--) {
jobject v = toJavaValue(env, LS, oldTop + i + 1);
(*env)->SetObjectArrayElement(env, r, i, v);
FREE(env, v);
}
lua_settop(LS, oldTop);
lua_unlock(LS);
return r;
} | 1,279 |
346 | <filename>src/game/Utils/Multi_Language_Graphic_Utils.h<gh_stars>100-1000
#include "GameRes.h"
| 39 |
778 | <reponame>lkusch/Kratos
//
// Project Name: KratosConstitutiveModelsApplication $
// Created by: $Author: JMCarbonell $
// Last modified by: $Co-Author: $
// Date: $Date: April 2017 $
// Revision: $Revision: 0.0 $
//
//
// System includes
// External includes
// Project includes
#include "custom_models/plasticity_models/hardening_rules/simo_linear_hardening_rule.hpp"
namespace Kratos
{
//*******************************CONSTRUCTOR******************************************
//************************************************************************************
SimoLinearHardeningRule::SimoLinearHardeningRule()
:SimoExponentialHardeningRule()
{
}
//*******************************ASSIGMENT OPERATOR***********************************
//************************************************************************************
SimoLinearHardeningRule& SimoLinearHardeningRule::operator=(SimoLinearHardeningRule const& rOther)
{
SimoExponentialHardeningRule::operator=(rOther);
return *this;
}
//*******************************COPY CONSTRUCTOR*************************************
//************************************************************************************
SimoLinearHardeningRule::SimoLinearHardeningRule(SimoLinearHardeningRule const& rOther)
:SimoExponentialHardeningRule(rOther)
{
}
//********************************CLONE***********************************************
//************************************************************************************
HardeningRule::Pointer SimoLinearHardeningRule::Clone() const
{
return Kratos::make_shared<SimoLinearHardeningRule>(*this);
}
//********************************DESTRUCTOR******************************************
//************************************************************************************
SimoLinearHardeningRule::~SimoLinearHardeningRule()
{
}
/// Operations.
//*******************************CALCULATE ISOTROPIC HARDENING************************
//************************************************************************************
double& SimoLinearHardeningRule::CalculateAndAddIsotropicHardening(const PlasticDataType& rVariables, double& rIsotropicHardening)
{
KRATOS_TRY
const ModelDataType& rModelData = rVariables.GetModelData();
//get values
const double& rEquivalentPlasticStrain = rVariables.GetInternalVariables()[0];
//linear hardening properties
const Properties& rProperties = rModelData.GetProperties();
const double& YieldStress = rProperties[YIELD_STRESS];
const double& KinematicHardeningConstant = rProperties[KINEMATIC_HARDENING_MODULUS];
//Linear Hardening rule: (mTheta = 0)
rIsotropicHardening += YieldStress + (1.0 - mTheta) * KinematicHardeningConstant * rEquivalentPlasticStrain;
return rIsotropicHardening;
KRATOS_CATCH(" ")
}
//*******************************CALCULATE HARDENING DERIVATIVE***********************
//************************************************************************************
double& SimoLinearHardeningRule::CalculateDeltaHardening(const PlasticDataType& rVariables, double& rDeltaHardening)
{
KRATOS_TRY
const ModelDataType& rModelData = rVariables.GetModelData();
//linear hardening properties
const double& KinematicHardeningConstant = rModelData.GetProperties()[KINEMATIC_HARDENING_MODULUS];
//Linear Hardening rule: (mTheta = 0)
rDeltaHardening = (1.0 - mTheta) * KinematicHardeningConstant;
return rDeltaHardening;
KRATOS_CATCH(" ")
}
//***************************CALCULATE ISOTROPIC HARDENING DERIVATIVE*****************
//************************************************************************************
double& SimoLinearHardeningRule::CalculateAndAddDeltaIsotropicHardening(const PlasticDataType& rVariables, double& rDeltaIsotropicHardening)
{
KRATOS_TRY
const ModelDataType& rModelData = rVariables.GetModelData();
//linear hardening properties
const double& KinematicHardeningConstant = rModelData.GetProperties()[KINEMATIC_HARDENING_MODULUS];
//Linear Hardening rule: (mTheta = 0)
rDeltaIsotropicHardening += mTheta * KinematicHardeningConstant;
return rDeltaIsotropicHardening;
KRATOS_CATCH(" ")
}
} // namespace Kratos.
| 1,399 |
460 | <filename>trunk/win/Source/Includes/QtIncludes/src/3rdparty/webkit/WebCore/ForwardingHeaders/wtf/FastMalloc.h
#ifndef WebCore_FWD_FastMalloc_h
#define WebCore_FWD_FastMalloc_h
#include <JavaScriptCore/FastMalloc.h>
#endif
| 92 |
476 | <filename>presto-spi/src/main/java/io/prestosql/spi/expression/FieldDereference.java
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.spi.expression;
import io.prestosql.spi.type.Type;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
public class FieldDereference
extends ConnectorExpression
{
private final ConnectorExpression target;
private final int field;
public FieldDereference(Type type, ConnectorExpression target, int field)
{
super(type);
this.target = requireNonNull(target, "target is null");
this.field = field;
}
public ConnectorExpression getTarget()
{
return target;
}
public int getField()
{
return field;
}
@Override
public String toString()
{
return format("(%s).#%s", target, field);
}
}
| 474 |
2,210 | /*
* Copyright 2020-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration;
import java.util.function.Supplier;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.endsWith;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Tests for {@link RegisterMissingBeanPostProcessor}.
*
* @author <NAME>
*/
public class RegisterMissingBeanPostProcessorTests {
private final RegisterMissingBeanPostProcessor postProcessor = new RegisterMissingBeanPostProcessor();
@Test
public void postProcessBeanDefinitionRegistryWhenClassAddedThenRegisteredWithClass() {
this.postProcessor.addBeanDefinition(SimpleBean.class, null);
this.postProcessor.setBeanFactory(new DefaultListableBeanFactory());
BeanDefinitionRegistry beanDefinitionRegistry = mock(BeanDefinitionRegistry.class);
this.postProcessor.postProcessBeanDefinitionRegistry(beanDefinitionRegistry);
ArgumentCaptor<BeanDefinition> beanDefinitionCaptor = ArgumentCaptor.forClass(BeanDefinition.class);
verify(beanDefinitionRegistry).registerBeanDefinition(endsWith("SimpleBean"), beanDefinitionCaptor.capture());
RootBeanDefinition beanDefinition = (RootBeanDefinition) beanDefinitionCaptor.getValue();
assertThat(beanDefinition.getBeanClass()).isEqualTo(SimpleBean.class);
assertThat(beanDefinition.getInstanceSupplier()).isNull();
}
@Test
public void postProcessBeanDefinitionRegistryWhenSupplierAddedThenRegisteredWithSupplier() {
Supplier<SimpleBean> beanSupplier = () -> new SimpleBean("string");
this.postProcessor.addBeanDefinition(SimpleBean.class, beanSupplier);
this.postProcessor.setBeanFactory(new DefaultListableBeanFactory());
BeanDefinitionRegistry beanDefinitionRegistry = mock(BeanDefinitionRegistry.class);
this.postProcessor.postProcessBeanDefinitionRegistry(beanDefinitionRegistry);
ArgumentCaptor<BeanDefinition> beanDefinitionCaptor = ArgumentCaptor.forClass(BeanDefinition.class);
verify(beanDefinitionRegistry).registerBeanDefinition(endsWith("SimpleBean"), beanDefinitionCaptor.capture());
RootBeanDefinition beanDefinition = (RootBeanDefinition) beanDefinitionCaptor.getValue();
assertThat(beanDefinition.getBeanClass()).isEqualTo(SimpleBean.class);
assertThat(beanDefinition.getInstanceSupplier()).isEqualTo(beanSupplier);
}
@Test
public void postProcessBeanDefinitionRegistryWhenNoBeanDefinitionsAddedThenNoneRegistered() {
this.postProcessor.setBeanFactory(new DefaultListableBeanFactory());
BeanDefinitionRegistry beanDefinitionRegistry = mock(BeanDefinitionRegistry.class);
this.postProcessor.postProcessBeanDefinitionRegistry(beanDefinitionRegistry);
verifyNoInteractions(beanDefinitionRegistry);
}
@Test
public void postProcessBeanDefinitionRegistryWhenBeanDefinitionAlreadyExistsThenNoneRegistered() {
this.postProcessor.addBeanDefinition(SimpleBean.class, null);
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerBeanDefinition("simpleBean", new RootBeanDefinition(SimpleBean.class));
this.postProcessor.setBeanFactory(beanFactory);
BeanDefinitionRegistry beanDefinitionRegistry = mock(BeanDefinitionRegistry.class);
this.postProcessor.postProcessBeanDefinitionRegistry(beanDefinitionRegistry);
verifyNoInteractions(beanDefinitionRegistry);
}
private static final class SimpleBean {
private final String field;
private SimpleBean(String field) {
this.field = field;
}
private String getField() {
return field;
}
}
}
| 1,327 |
302 | /*
Simple DirectMedia Layer
Copyright (C) 1997-2020 <NAME> <<EMAIL>>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "./SDL_internal.h"
/* Simple error handling in SDL */
#include "SDL_log.h"
#include "SDL_error.h"
#include "SDL_error_c.h"
#define SDL_ERRBUFIZE 1024
/* Private functions */
static const char *
SDL_LookupString(const char *key)
{
/* FIXME: Add code to lookup key in language string hash-table */
return key;
}
/* Public functions */
static char *SDL_GetErrorMsg(char *errstr, int maxlen);
int
SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{
va_list ap;
SDL_error *error;
/* Ignore call if invalid format pointer was passed */
if (fmt == NULL) return -1;
/* Copy in the key, mark error as valid */
error = SDL_GetErrBuf();
error->error = 1;
SDL_strlcpy((char *) error->key, fmt, sizeof(error->key));
va_start(ap, fmt);
error->argc = 0;
while (*fmt) {
if (*fmt++ == '%') {
while (*fmt == '.' || (*fmt >= '0' && *fmt <= '9')) {
++fmt;
}
switch (*fmt++) {
case 0: /* Malformed format string.. */
--fmt;
break;
case 'l':
switch (*fmt++) {
case 0: /* Malformed format string.. */
--fmt;
break;
case 'i': case 'd': case 'u': case 'x': case 'X':
error->args[error->argc++].value_l = va_arg(ap, long);
break;
}
break;
case 'c':
case 'i':
case 'd':
case 'u':
case 'o':
case 'x':
case 'X':
error->args[error->argc++].value_i = va_arg(ap, int);
break;
case 'f':
error->args[error->argc++].value_f = va_arg(ap, double);
break;
case 'p':
error->args[error->argc++].value_ptr = va_arg(ap, void *);
break;
case 's':
{
int i = error->argc;
const char *str = va_arg(ap, const char *);
if (str == NULL)
str = "(null)";
SDL_strlcpy((char *) error->args[i].buf, str,
ERR_MAX_STRLEN);
error->argc++;
}
break;
default:
break;
}
if (error->argc >= ERR_MAX_ARGS) {
break;
}
}
}
va_end(ap);
if (SDL_LogGetPriority(SDL_LOG_CATEGORY_ERROR) <= SDL_LOG_PRIORITY_DEBUG) {
/* If we are in debug mode, print out an error message
* Avoid stomping on the static buffer in GetError, just
* in case this is called while processing a ShowMessageBox to
* show an error already in that static buffer.
*/
char errmsg[SDL_ERRBUFIZE];
SDL_GetErrorMsg(errmsg, sizeof(errmsg));
SDL_LogDebug(SDL_LOG_CATEGORY_ERROR, "%s", errmsg);
}
return -1;
}
/* Available for backwards compatibility */
const char *
SDL_GetError(void)
{
static char errmsg[SDL_ERRBUFIZE];
return SDL_GetErrorMsg(errmsg, SDL_ERRBUFIZE);
}
void
SDL_ClearError(void)
{
SDL_error *error;
error = SDL_GetErrBuf();
error->error = 0;
}
/* Very common errors go here */
int
SDL_Error(SDL_errorcode code)
{
switch (code) {
case SDL_ENOMEM:
return SDL_SetError("Out of memory");
case SDL_EFREAD:
return SDL_SetError("Error reading from datastream");
case SDL_EFWRITE:
return SDL_SetError("Error writing to datastream");
case SDL_EFSEEK:
return SDL_SetError("Error seeking in datastream");
case SDL_UNSUPPORTED:
return SDL_SetError("That operation is not supported");
default:
return SDL_SetError("Unknown SDL error");
}
}
#ifdef TEST_ERROR
int
main(int argc, char *argv[])
{
char buffer[BUFSIZ + 1];
SDL_SetError("Hi there!");
printf("Error 1: %s\n", SDL_GetError());
SDL_ClearError();
SDL_memset(buffer, '1', BUFSIZ);
buffer[BUFSIZ] = 0;
SDL_SetError("This is the error: %s (%f)", buffer, 1.0);
printf("Error 2: %s\n", SDL_GetError());
exit(0);
}
#endif
/* keep this at the end of the file so it works with GCC builds that don't
support "#pragma GCC diagnostic push" ... we'll just leave the warning
disabled after this. */
/* this pragma arrived in GCC 4.2 and causes a warning on older GCCs! Sigh. */
#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 2))))
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
#endif
/* This function has a bit more overhead than most error functions
so that it supports internationalization and thread-safe errors.
*/
static char *
SDL_GetErrorMsg(char *errstr, int maxlen)
{
SDL_error *error;
/* Clear the error string */
*errstr = '\0';
--maxlen;
/* Get the thread-safe error, and print it out */
error = SDL_GetErrBuf();
if (error->error) {
const char *fmt;
char *msg = errstr;
int len;
int argi;
fmt = SDL_LookupString(error->key);
argi = 0;
while (*fmt && (maxlen > 0)) {
if (*fmt == '%') {
char tmp[32], *spot = tmp;
*spot++ = *fmt++;
while ((*fmt == '.' || (*fmt >= '0' && *fmt <= '9'))
&& spot < (tmp + SDL_arraysize(tmp) - 2)) {
*spot++ = *fmt++;
}
if (*fmt == 'l') {
*spot++ = *fmt++;
*spot++ = *fmt++;
*spot++ = '\0';
switch (spot[-2]) {
case 'i': case 'd': case 'u': case 'x': case 'X':
len = SDL_snprintf(msg, maxlen, tmp,
error->args[argi++].value_l);
if (len > 0) {
msg += len;
maxlen -= len;
}
break;
}
continue;
}
*spot++ = *fmt++;
*spot++ = '\0';
switch (spot[-2]) {
case '%':
*msg++ = '%';
maxlen -= 1;
break;
case 'c':
case 'i':
case 'd':
case 'u':
case 'o':
case 'x':
case 'X':
len =
SDL_snprintf(msg, maxlen, tmp,
error->args[argi++].value_i);
if (len > 0) {
msg += len;
maxlen -= len;
}
break;
case 'f':
len =
SDL_snprintf(msg, maxlen, tmp,
error->args[argi++].value_f);
if (len > 0) {
msg += len;
maxlen -= len;
}
break;
case 'p':
len =
SDL_snprintf(msg, maxlen, tmp,
error->args[argi++].value_ptr);
if (len > 0) {
msg += len;
maxlen -= len;
}
break;
case 's':
len =
SDL_snprintf(msg, maxlen, tmp,
SDL_LookupString(error->args[argi++].
buf));
if (len > 0) {
msg += len;
maxlen -= len;
}
break;
}
} else {
*msg++ = *fmt++;
maxlen -= 1;
}
}
/* slide back if we've overshot the end of our buffer. */
if (maxlen < 0) {
msg -= (-maxlen) + 1;
}
*msg = 0; /* NULL terminate the string */
}
return (errstr);
}
/* vi: set ts=4 sw=4 expandtab: */
| 5,071 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.editor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.JTextComponent;
import javax.swing.text.BadLocationException;
import org.netbeans.api.editor.NavigationHistory;
import org.openide.modules.PatchedPublic;
import org.openide.util.WeakListeners;
/**
* The list of marked positions in text components.
*
* @author <NAME>
* @version 1.01
*/
public final class JumpList {
private static final Logger LOG = Logger.getLogger(JumpList.class.getName());
private static final WeakPropertyChangeSupport support = new WeakPropertyChangeSupport();
private static PropertyChangeListener listener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
support.firePropertyChange(JumpList.class, null, null, null);
}
};
static {
NavigationHistory.getNavigations().addPropertyChangeListener(
WeakListeners.propertyChange(listener, NavigationHistory.getNavigations()));
}
static void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
/**
* Adds the caret position of the active <code>JTextComponent</code> to the
* list. If the active component can't be determined this method does nothing.
*
* <p class="nonormative">The active <code>JTextComponent</code> is obtained
* from the system by tracking components that gain focus as a users uses them.
* In Netbeans IDE the active component is usually the component selected in
* the IDE's editor area.
*
* @see #addEntry(JTextComponent, int)
*/
public static void checkAddEntry() {
JTextComponent c = Utilities.getLastActiveComponent();
if (c != null) {
addEntry(c, c.getCaret().getDot());
}
}
/**
* Adds the caret position of the provided <code>JTextComponent</code> to the
* list.
*
* @param c The offset of this component's caret will be added to the list.
*
* @see #addEntry(JTextComponent, int)
*/
public static void checkAddEntry(JTextComponent c) {
addEntry(c, c.getCaret().getDot());
}
/**
* The same as {@link #addEntry(JTextComponent, int)}.
*
* @deprecated Use {@link #addEntry(JTextComponent, int)} instead.
*/
public static void checkAddEntry(JTextComponent c, int pos) {
addEntry(c, pos);
}
/**
* Adds a new entry to the list. If the component and the position passed
* in are the same as those from the last entry in the list, nothing
* will be added.
*
* @param c The component to add to the list.
* @param pos The offset of the component's caret to add to the list.
*/
public static void addEntry(JTextComponent c, int pos) {
try {
NavigationHistory.getNavigations().markWaypoint(c, pos, false, false);
} catch (BadLocationException e) {
LOG.log(Level.WARNING, "Can't add position to the navigation history.", e); //NOI18N
}
}
/**
* Navigates to the component and position from the previous entry in the list.
* It will skip all entries with the same component and position as the
* current caret position in the component passed in.
*
* <p class="nonnormative">This method will try to move focus to the component
* stored in the list and set its caret position.
*
* @param c The component to check for the current position.
*/
public static void jumpPrev(JTextComponent c) {
NavigationHistory.Waypoint wpt = NavigationHistory.getNavigations().navigateBack();
show(wpt);
}
/**
* Navigates to the component and position from the previous entry in the list.
* It will skip all entries with the same component as the one passed in, but
* it does not perform any checks on the positions.
*
* <p class="nonnormative">This method will try to move focus to the component
* stored in the list and set its caret position.
*
* @param c The component to check for the current position.
*/
public static void jumpPrevComponent(JTextComponent c) {
List<NavigationHistory.Waypoint> list = NavigationHistory.getNavigations().getPreviousWaypoints();
for(NavigationHistory.Waypoint wpt : list) {
JTextComponent wptComp = wpt.getComponent();
if (wptComp != null && wptComp != c) {
show(wpt);
return;
}
}
}
/**
* Checks if there is the previous entry in the list.
*
* @return <code>true</code> if there is a previous entry in the list and it
* is possible to use {@link #jumpPrev(JTextComponent)} or {@link #jumpPrevComponent(JTextComponent)}
* for navigation. Otherwise <code>false</code>.
*/
public static boolean hasPrev() {
return NavigationHistory.getNavigations().hasPreviousWaypoints();
}
/**
* Navigates to the component and position from the next entry in the list.
* It will skip all entries with the same component and position as the
* current caret position in the component passed in.
*
* <p class="nonnormative">This method will try to move focus to the component
* stored in the list and set its caret position.
*
* @param c The component to check for the current position.
*/
public static void jumpNext(JTextComponent c) {
NavigationHistory.Waypoint wpt = NavigationHistory.getNavigations().navigateForward();
show(wpt);
}
/**
* Navigates to the component and position from the next entry in the list.
* It will skip all entries with the same component as the one passed in, but
* it does not perform any checks on the positions.
*
* <p class="nonnormative">This method will try to move focus to the component
* stored in the list and set its caret position.
*
* @param c The component to check for the current position.
*/
public static void jumpNextComponent(JTextComponent c) {
List<NavigationHistory.Waypoint> list = NavigationHistory.getNavigations().getNextWaypoints();
for(NavigationHistory.Waypoint wpt : list) {
JTextComponent wptComp = wpt.getComponent();
if (wptComp != null && wptComp != c) {
show(wpt);
return;
}
}
}
/**
* Checks if there is the next entry in the list.
*
* @return <code>true</code> if there is a previous entry in the list and it
* is possible to use {@link #jumpPrev(JTextComponent)} or {@link #jumpPrevComponent(JTextComponent)}
* for navigation. Otherwise <code>false</code>.
*/
public static boolean hasNext() {
return NavigationHistory.getNavigations().hasNextWaypoints();
}
/**
* @return Unspecified string.
* @deprecate Should have never been public.
*/
public static String dump() {
StringBuilder sb = new StringBuilder();
sb.append("Previous waypoints: {\n"); //NOI18N
List<NavigationHistory.Waypoint> prev = NavigationHistory.getNavigations().getPreviousWaypoints();
for(NavigationHistory.Waypoint wpt : prev) {
URL url = wpt.getUrl();
sb.append(" ").append(url.toString()).append("\n"); //NOI18N
}
sb.append("}\n"); //NOI18N
sb.append("Next waypoints: {\n"); //NOI18N
List<NavigationHistory.Waypoint> next = NavigationHistory.getNavigations().getNextWaypoints();
for(NavigationHistory.Waypoint wpt : next) {
URL url = wpt.getUrl();
sb.append(" ").append(url.toString()).append("\n"); //NOI18N
}
sb.append("}\n"); //NOI18N
return sb.toString();
}
/** Just to prevent instantialization. */
@PatchedPublic
private JumpList() {
}
private static void show(NavigationHistory.Waypoint wpt) {
JTextComponent c = wpt == null ? null : wpt.getComponent();
if (c != null) {
if (Utilities.getLastActiveComponent() != c) {
Utilities.requestFocus(c); // possibly request for the component
}
int offset = wpt.getOffset();
if (offset >= 0 && offset <= c.getDocument().getLength()) {
c.getCaret().setDot(offset); // set the dot
}
}
}
/**
* An entry in the list with <code>JTextComponent</code> and a position in
* its <code>Document</code>.
*/
public static final class Entry {
private Entry(JTextComponent component, int offset, Entry last) throws BadLocationException {
}
/**
* Gets the offset of the position maintaind by this entry.
*
* @return An offset within this entry's component's document or -1 if
* this entry is not valid anymore.
*/
public int getPosition() {
return -1;
}
/**
* Gets the component maintained by this entry.
*
* @return The component or <code>null</code> if this entry is not valid
* anymore.
*/
public JTextComponent getComponent() {
return null;
}
/**
* Navigates to the component and position maintained by this entry.
*
* <p class="nonnormative">This method will try to move focus to the component
* stored in this entry and set its caret to the position maintained by this entry.
*
* @return <code>true</code> if the navigation was successful, <code>false</code>
* otherwise.
*/
public boolean setDot() {
return false;
}
} // End of Entry class
}
| 4,072 |
879 | <reponame>qianfei11/zstack
package org.zstack.header.identity.role;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@StaticMetamodel(SystemRoleVO.class)
public class SystemRoleVO_ extends RoleVO_ {
public static SingularAttribute<SystemRoleVO, SystemRoleType> systemRoleType;
}
| 118 |
1,772 | import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.db.models.deletion import RestrictedError
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.contrib.admin.utils import NestedObjects
from django.db import DEFAULT_DB_ALIAS
from dojo.authorization.roles_permissions import Permissions
from dojo.authorization.authorization import user_has_permission
from dojo.authorization.authorization_decorators import user_is_authorized
from dojo.filters import GroupFilter
from dojo.forms import DojoGroupForm, DeleteGroupForm, Add_Product_Group_GroupForm, \
Add_Product_Type_Group_GroupForm, Add_Group_MemberForm, Edit_Group_MemberForm, \
Delete_Group_MemberForm, GlobalRoleForm
from dojo.models import Dojo_Group, Product_Group, Product_Type_Group, Dojo_Group_Member, Role
from dojo.utils import get_page_items, add_breadcrumb, is_title_in_breadcrumbs
from dojo.group.queries import get_authorized_groups, get_product_groups_for_group, \
get_product_type_groups_for_group, get_group_members_for_group
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def group(request):
groups = get_authorized_groups(Permissions.Group_View)
groups = GroupFilter(request.GET, queryset=groups)
paged_groups = get_page_items(request, groups.qs, 25)
add_breadcrumb(title="All Groups", top_level=True, request=request)
return render(request, 'dojo/groups.html', {
'groups': paged_groups,
'filtered': groups,
'name': 'All Groups'
})
@user_is_authorized(Dojo_Group, Permissions.Group_View, 'gid')
def view_group(request, gid):
group = get_object_or_404(Dojo_Group, id=gid)
products = get_product_groups_for_group(group)
product_types = get_product_type_groups_for_group(group)
group_members = get_group_members_for_group(group)
add_breadcrumb(title="View Group", top_level=False, request=request)
return render(request, 'dojo/view_group.html', {
'group': group,
'products': products,
'product_types': product_types,
'group_members': group_members
})
@user_is_authorized(Dojo_Group, Permissions.Group_Edit, 'gid')
def edit_group(request, gid):
group = get_object_or_404(Dojo_Group, id=gid)
form = DojoGroupForm(instance=group)
global_role = group.global_role if hasattr(group, 'global_role') else None
if global_role is None:
previous_global_role = None
global_role_form = GlobalRoleForm()
else:
previous_global_role = global_role.role
global_role_form = GlobalRoleForm(instance=global_role)
if request.method == 'POST':
form = DojoGroupForm(request.POST, instance=group)
if global_role is None:
global_role_form = GlobalRoleForm(request.POST)
else:
global_role_form = GlobalRoleForm(request.POST, instance=global_role)
if form.is_valid() and global_role_form.is_valid():
if global_role_form.cleaned_data['role'] != previous_global_role and not request.user.is_superuser:
messages.add_message(request,
messages.WARNING,
'Only superusers are allowed to change the global role.',
extra_tags='alert-warning')
else:
form.save()
global_role = global_role_form.save(commit=False)
global_role.group = group
global_role.save()
messages.add_message(request,
messages.SUCCESS,
'Group saved successfully.',
extra_tags='alert-success')
else:
messages.add_message(request,
messages.ERROR,
'Group was not saved successfully.',
extra_tags='alert_danger')
add_breadcrumb(title="Edit Group", top_level=False, request=request)
return render(request, "dojo/add_group.html", {
'form': form,
'global_role_form': global_role_form,
})
@user_is_authorized(Dojo_Group, Permissions.Group_Delete, 'gid')
def delete_group(request, gid):
group = get_object_or_404(Dojo_Group, id=gid)
form = DeleteGroupForm(instance=group)
if request.method == 'POST':
if 'id' in request.POST and str(group.id) == request.POST['id']:
form = DeleteGroupForm(request.POST, instance=group)
if form.is_valid():
try:
group.delete()
messages.add_message(request,
messages.SUCCESS,
'Group and relationships successfully removed.',
extra_tags='alert-success')
except RestrictedError as err:
messages.add_message(request,
messages.WARNING,
'Group cannot be deleted: {}'.format(err),
extra_tags='alert-warning')
return HttpResponseRedirect(reverse('groups'))
collector = NestedObjects(using=DEFAULT_DB_ALIAS)
collector.collect([group])
rels = collector.nested()
add_breadcrumb(title="Delete Group", top_level=False, request=request)
return render(request, 'dojo/delete_group.html', {
'to_delete': group,
'form': form,
'rels': rels
})
@user_passes_test(lambda u: u.is_staff)
def add_group(request):
form = DojoGroupForm
global_role_form = GlobalRoleForm()
group = None
if request.method == 'POST':
form = DojoGroupForm(request.POST)
global_role_form = GlobalRoleForm(request.POST)
if form.is_valid() and global_role_form.is_valid():
if global_role_form.cleaned_data['role'] is not None and not request.user.is_superuser:
messages.add_message(request, messages.ERROR,
'Only superusers are allowed to set global role.',
extra_tags='alert-warning')
else:
group = form.save(commit=False)
group.save()
global_role = global_role_form.save(commit=False)
global_role.group = group
global_role.save()
member = Dojo_Group_Member()
member.user = request.user
member.group = group
member.role = Role.objects.get(is_owner=True)
member.save()
messages.add_message(request,
messages.SUCCESS,
'Group was added successfully.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('view_group', args=(group.id,)))
else:
messages.add_message(request, messages.ERROR,
'Group was not added successfully.',
extra_tags='alert-danger')
add_breadcrumb(title="Add Group", top_level=False, request=request)
return render(request, "dojo/add_group.html", {
'form': form,
'global_role_form': global_role_form,
})
@user_is_authorized(Dojo_Group, Permissions.Group_Manage_Members, 'gid')
def add_group_member(request, gid):
group = get_object_or_404(Dojo_Group, id=gid)
groupform = Add_Group_MemberForm(initial={'group': group.id})
if request.method == 'POST':
groupform = Add_Group_MemberForm(request.POST, initial={'group': group.id})
if groupform.is_valid():
if groupform.cleaned_data['role'].is_owner and not user_has_permission(request.user, group, Permissions.Group_Add_Owner):
messages.add_message(request,
messages.WARNING,
'You are not permitted to add users as owners.',
extra_tags='alert-warning')
else:
if 'users' in groupform.cleaned_data and len(groupform.cleaned_data['users']) > 0:
for user in groupform.cleaned_data['users']:
existing_users = Dojo_Group_Member.objects.filter(group=group, user=user)
if existing_users.count() == 0:
group_member = Dojo_Group_Member()
group_member.group = group
group_member.user = user
group_member.role = groupform.cleaned_data['role']
group_member.save()
messages.add_message(request,
messages.SUCCESS,
'Group members added successfully.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('view_group', args=(gid, )))
add_breadcrumb(title="Add Group Member", top_level=False, request=request)
return render(request, 'dojo/new_group_member.html', {
'group': group,
'form': groupform
})
@user_is_authorized(Dojo_Group_Member, Permissions.Group_Manage_Members, 'mid')
def edit_group_member(request, mid):
member = get_object_or_404(Dojo_Group_Member, pk=mid)
memberform = Edit_Group_MemberForm(instance=member)
if request.method == 'POST':
memberform = Edit_Group_MemberForm(request.POST, instance=member)
if memberform.is_valid():
if not member.role.is_owner:
owners = Dojo_Group_Member.objects.filter(group=member.group, role__is_owner=True).exclude(id=member.id).count()
if owners < 1:
messages.add_message(request,
messages.WARNING,
'There must be at least one owner for group {}.'.format(member.group.name),
extra_tags='alert-warning')
if is_title_in_breadcrumbs('View User'):
return HttpResponseRedirect(reverse('view_user', args=(member.user.id, )))
else:
return HttpResponseRedirect(reverse('view_group', args=(member.group.id, )))
if member.role.is_owner and not user_has_permission(request.user, member.group, Permissions.Group_Add_Owner):
messages.add_message(request,
messages.WARNING,
'You are not permitted to make users owners.',
extra_tags='alert-warning')
else:
memberform.save()
messages.add_message(request,
messages.SUCCESS,
'Group member updated successfully',
extra_tags='alert-success')
if is_title_in_breadcrumbs('View User'):
return HttpResponseRedirect(reverse('view_user', args=(member.user.id, )))
else:
return HttpResponseRedirect(reverse('view_group', args=(member.group.id, )))
add_breadcrumb(title="Edit a Group Member", top_level=False, request=request)
return render(request, 'dojo/edit_group_member.html', {
'memberid': mid,
'form': memberform
})
@user_is_authorized(Dojo_Group_Member, Permissions.Group_Member_Delete, 'mid')
def delete_group_member(request, mid):
member = get_object_or_404(Dojo_Group_Member, pk=mid)
memberform = Delete_Group_MemberForm(instance=member)
if request.method == 'POST':
memberform = Delete_Group_MemberForm(request.POST, instance=member)
member = memberform.instance
if member.role.is_owner:
owners = Dojo_Group_Member.objects.filter(group=member.group, role__is_owner=True).count()
if owners <= 1:
messages.add_message(request,
messages.WARNING,
'There must be at least one owner for group {}.'.format(member.group.name),
extra_tags='alert-warning')
if is_title_in_breadcrumbs('View User'):
return HttpResponseRedirect(reverse('view_user', args=(member.user.id, )))
else:
return HttpResponseRedirect(reverse('view_group', args=(member.group.id, )))
user = member.user
member.delete()
messages.add_message(request,
messages.SUCCESS,
'Group member deleted successfully.',
extra_tags='alert-success')
if is_title_in_breadcrumbs('View User'):
return HttpResponseRedirect(reverse('view_user', args=(member.user.id, )))
else:
if user == request.user:
return HttpResponseRedirect(reverse('groups'))
else:
return HttpResponseRedirect(reverse('view_group', args=(member.group.id, )))
add_breadcrumb("Delete a group member", top_level=False, request=request)
return render(request, 'dojo/delete_group_member.html', {
'memberid': mid,
'form': memberform
})
@user_passes_test(lambda u: u.is_superuser)
def add_product_group(request, gid):
group = get_object_or_404(Dojo_Group, id=gid)
group_form = Add_Product_Group_GroupForm(initial={'group': group.id})
if request.method == 'POST':
group_form = Add_Product_Group_GroupForm(request.POST, initial={'group': group.id})
if group_form.is_valid():
if 'products' in group_form.cleaned_data and len(group_form.cleaned_data['products']) > 0:
for product in group_form.cleaned_data['products']:
existing_groups = Product_Group.objects.filter(product=product, group=group)
if existing_groups.count() == 0:
product_group = Product_Group()
product_group.product = product
product_group.group = group
product_group.role = group_form.cleaned_data['role']
product_group.save()
messages.add_message(request,
messages.SUCCESS,
'Product groups added successfully.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('view_group', args=(gid, )))
add_breadcrumb(title="Add Product Group", top_level=False, request=request)
return render(request, 'dojo/new_product_group_group.html', {
'group': group,
'form': group_form
})
@user_passes_test(lambda u: u.is_superuser)
def add_product_type_group(request, gid):
group = get_object_or_404(Dojo_Group, id=gid)
group_form = Add_Product_Type_Group_GroupForm(initial={'group': group.id})
if request.method == 'POST':
group_form = Add_Product_Type_Group_GroupForm(request.POST, initial={'group': group.id})
if group_form.is_valid():
if 'product_types' in group_form.cleaned_data and len(group_form.cleaned_data['product_types']) > 0:
for product_type in group_form.cleaned_data['product_types']:
existing_groups = Product_Type_Group.objects.filter(product_type=product_type)
if existing_groups.count() == 0:
product_type_group = Product_Type_Group()
product_type_group.product_type = product_type
product_type_group.group = group
product_type_group.role = group_form.cleaned_data['role']
product_type_group.save()
messages.add_message(request,
messages.SUCCESS,
'Product type groups added successfully.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('view_group', args=(gid, )))
add_breadcrumb(title="Add Product Type Group", top_level=False, request=request)
return render(request, 'dojo/new_product_type_group_group.html', {
'group': group,
'form': group_form,
})
| 8,035 |
10,225 | <reponame>Markus-Schwer/quarkus
package io.quarkus.it.kafka.codecs;
import java.util.ArrayList;
import java.util.List;
import io.quarkus.kafka.client.serialization.JsonbDeserializer;
public class PersonListDeserializer extends JsonbDeserializer<List<Person>> {
public PersonListDeserializer() {
super(new ArrayList<Person>() {
}.getClass().getGenericSuperclass());
}
}
| 153 |
556 | <gh_stars>100-1000
/*
* Hacker Disassembler Engine 64 C
* Copyright (c) 2008-2009, <NAME>.
* All rights reserved.
*
*/
#include "stdafx.h"
#if defined(_M_X64) || defined(__x86_64__)
#pragma warning(push, 0)
#pragma warning(disable: 4701 4706 26451)
#include "hde64.h"
#include "table64.h"
unsigned int hde64_disasm(const void *code, hde64s *hs)
{
uint8_t x, c, *p = (uint8_t *)code, cflags, opcode, pref = 0;
uint8_t *ht = hde64_table, m_mod, m_reg, m_rm, disp_size = 0;
uint8_t op64 = 0;
// Avoid using memset to reduce the footprint.
memset(hs, 0, sizeof(hde64s));
for (x = 16; x; x--)
switch (c = *p++) {
case 0xf3:
hs->p_rep = c;
pref |= PRE_F3;
break;
case 0xf2:
hs->p_rep = c;
pref |= PRE_F2;
break;
case 0xf0:
hs->p_lock = c;
pref |= PRE_LOCK;
break;
case 0x26: case 0x2e: case 0x36:
case 0x3e: case 0x64: case 0x65:
hs->p_seg = c;
pref |= PRE_SEG;
break;
case 0x66:
hs->p_66 = c;
pref |= PRE_66;
break;
case 0x67:
hs->p_67 = c;
pref |= PRE_67;
break;
default:
goto pref_done;
}
pref_done:
hs->flags = (uint32_t)pref << 23;
if (!pref)
pref |= PRE_NONE;
if ((c & 0xf0) == 0x40) {
hs->flags |= F_PREFIX_REX;
if ((hs->rex_w = (c & 0xf) >> 3) && (*p & 0xf8) == 0xb8)
op64++;
hs->rex_r = (c & 7) >> 2;
hs->rex_x = (c & 3) >> 1;
hs->rex_b = c & 1;
if (((c = *p++) & 0xf0) == 0x40) {
opcode = c;
goto error_opcode;
}
}
if ((hs->opcode = c) == 0x0f) {
hs->opcode2 = c = *p++;
ht += DELTA_OPCODES;
} else if (c >= 0xa0 && c <= 0xa3) {
op64++;
if (pref & PRE_67)
pref |= PRE_66;
else
pref &= ~PRE_66;
}
opcode = c;
cflags = ht[ht[opcode / 4] + (opcode % 4)];
if (cflags == C_ERROR) {
error_opcode:
hs->flags |= F_ERROR | F_ERROR_OPCODE;
cflags = 0;
if ((opcode & -3) == 0x24)
cflags++;
}
x = 0;
if (cflags & C_GROUP) {
uint16_t t;
t = *(uint16_t *)(ht + (cflags & 0x7f));
cflags = (uint8_t)t;
x = (uint8_t)(t >> 8);
}
if (hs->opcode2) {
ht = hde64_table + DELTA_PREFIXES;
if (ht[ht[opcode / 4] + (opcode % 4)] & pref)
hs->flags |= F_ERROR | F_ERROR_OPCODE;
}
if (cflags & C_MODRM) {
hs->flags |= F_MODRM;
hs->modrm = c = *p++;
hs->modrm_mod = m_mod = c >> 6;
hs->modrm_rm = m_rm = c & 7;
hs->modrm_reg = m_reg = (c & 0x3f) >> 3;
if (x && ((x << m_reg) & 0x80))
hs->flags |= F_ERROR | F_ERROR_OPCODE;
if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) {
uint8_t t = opcode - 0xd9;
if (m_mod == 3) {
ht = hde64_table + DELTA_FPU_MODRM + t*8;
t = ht[m_reg] << m_rm;
} else {
ht = hde64_table + DELTA_FPU_REG;
t = ht[t] << m_reg;
}
if (t & 0x80)
hs->flags |= F_ERROR | F_ERROR_OPCODE;
}
if (pref & PRE_LOCK) {
if (m_mod == 3) {
hs->flags |= F_ERROR | F_ERROR_LOCK;
} else {
uint8_t *table_end, op = opcode;
if (hs->opcode2) {
ht = hde64_table + DELTA_OP2_LOCK_OK;
table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK;
} else {
ht = hde64_table + DELTA_OP_LOCK_OK;
table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK;
op &= -2;
}
for (; ht != table_end; ht++)
if (*ht++ == op) {
if (!((*ht << m_reg) & 0x80))
goto no_lock_error;
else
break;
}
hs->flags |= F_ERROR | F_ERROR_LOCK;
no_lock_error:
;
}
}
if (hs->opcode2) {
switch (opcode) {
case 0x20: case 0x22:
m_mod = 3;
if (m_reg > 4 || m_reg == 1)
goto error_operand;
else
goto no_error_operand;
case 0x21: case 0x23:
m_mod = 3;
if (m_reg == 4 || m_reg == 5)
goto error_operand;
else
goto no_error_operand;
}
} else {
switch (opcode) {
case 0x8c:
if (m_reg > 5)
goto error_operand;
else
goto no_error_operand;
case 0x8e:
if (m_reg == 1 || m_reg > 5)
goto error_operand;
else
goto no_error_operand;
}
}
if (m_mod == 3) {
uint8_t *table_end;
if (hs->opcode2) {
ht = hde64_table + DELTA_OP2_ONLY_MEM;
table_end = ht + sizeof(hde64_table) - DELTA_OP2_ONLY_MEM;
} else {
ht = hde64_table + DELTA_OP_ONLY_MEM;
table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM;
}
for (; ht != table_end; ht += 2)
if (*ht++ == opcode) {
if (*ht++ & pref && !((*ht << m_reg) & 0x80))
goto error_operand;
else
break;
}
goto no_error_operand;
} else if (hs->opcode2) {
switch (opcode) {
case 0x50: case 0xd7: case 0xf7:
if (pref & (PRE_NONE | PRE_66))
goto error_operand;
break;
case 0xd6:
if (pref & (PRE_F2 | PRE_F3))
goto error_operand;
break;
case 0xc5:
goto error_operand;
}
goto no_error_operand;
} else
goto no_error_operand;
error_operand:
hs->flags |= F_ERROR | F_ERROR_OPERAND;
no_error_operand:
c = *p++;
if (m_reg <= 1) {
if (opcode == 0xf6)
cflags |= C_IMM8;
else if (opcode == 0xf7)
cflags |= C_IMM_P66;
}
switch (m_mod) {
case 0:
if (pref & PRE_67) {
if (m_rm == 6)
disp_size = 2;
} else
if (m_rm == 5)
disp_size = 4;
break;
case 1:
disp_size = 1;
break;
case 2:
disp_size = 2;
if (!(pref & PRE_67))
disp_size <<= 1;
}
if (m_mod != 3 && m_rm == 4) {
hs->flags |= F_SIB;
p++;
hs->sib = c;
hs->sib_scale = c >> 6;
hs->sib_index = (c & 0x3f) >> 3;
if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1))
disp_size = 4;
}
p--;
switch (disp_size) {
case 1:
hs->flags |= F_DISP8;
hs->disp.disp8 = *p;
break;
case 2:
hs->flags |= F_DISP16;
hs->disp.disp16 = *(uint16_t *)p;
break;
case 4:
hs->flags |= F_DISP32;
hs->disp.disp32 = *(uint32_t *)p;
}
p += disp_size;
} else if (pref & PRE_LOCK)
hs->flags |= F_ERROR | F_ERROR_LOCK;
if (cflags & C_IMM_P66) {
if (cflags & C_REL32) {
if (pref & PRE_66) {
hs->flags |= F_IMM16 | F_RELATIVE;
hs->imm.imm16 = *(uint16_t *)p;
p += 2;
goto disasm_done;
}
goto rel32_ok;
}
if (op64) {
hs->flags |= F_IMM64;
hs->imm.imm64 = *(uint64_t *)p;
p += 8;
} else if (!(pref & PRE_66)) {
hs->flags |= F_IMM32;
hs->imm.imm32 = *(uint32_t *)p;
p += 4;
} else
goto imm16_ok;
}
if (cflags & C_IMM16) {
imm16_ok:
hs->flags |= F_IMM16;
hs->imm.imm16 = *(uint16_t *)p;
p += 2;
}
if (cflags & C_IMM8) {
hs->flags |= F_IMM8;
hs->imm.imm8 = *p++;
}
if (cflags & C_REL32) {
rel32_ok:
hs->flags |= F_IMM32 | F_RELATIVE;
hs->imm.imm32 = *(uint32_t *)p;
p += 4;
} else if (cflags & C_REL8) {
hs->flags |= F_IMM8 | F_RELATIVE;
hs->imm.imm8 = *p++;
}
disasm_done:
if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) {
hs->flags |= F_ERROR | F_ERROR_LENGTH;
hs->len = 15;
}
return (unsigned int)hs->len;
}
#pragma warning(pop)
#endif // defined(_M_X64) || defined(__x86_64__)
| 6,317 |
1,882 | """
widget.py
-------------
A widget which can visualize trimesh.Scene objects in a glooey window.
Check out an example in `examples/widget.py`
"""
import glooey
import numpy as np
import pyglet
from pyglet import gl
from .. import rendering
from .trackball import Trackball
from .windowed import geometry_hash
from .windowed import SceneViewer
class SceneGroup(pyglet.graphics.Group):
def __init__(
self,
rect,
scene,
background=None,
pixel_per_point=(1, 1),
parent=None,
):
super().__init__(parent)
self.rect = rect
self.scene = scene
if background is None:
background = [.99, .99, .99, 1.0]
self._background = background
self._pixel_per_point = pixel_per_point
def _set_view(self):
left = int(self._pixel_per_point[0] * self.rect.left)
bottom = int(self._pixel_per_point[1] * self.rect.bottom)
width = int(self._pixel_per_point[0] * self.rect.width)
height = int(self._pixel_per_point[1] * self.rect.height)
gl.glPushAttrib(gl.GL_ENABLE_BIT)
gl.glEnable(gl.GL_SCISSOR_TEST)
gl.glScissor(left, bottom, width, height)
self._mode = (gl.GLint)()
gl.glGetIntegerv(gl.GL_MATRIX_MODE, self._mode)
self._viewport = (gl.GLint * 4)()
gl.glGetIntegerv(gl.GL_VIEWPORT, self._viewport)
gl.glViewport(left, bottom, width, height)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPushMatrix()
gl.glLoadIdentity()
near = 0.01
far = 1000.
gl.gluPerspective(self.scene.camera.fov[1], width / height, near, far)
gl.glMatrixMode(gl.GL_MODELVIEW)
def _unset_view(self):
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPopMatrix()
gl.glMatrixMode(self._mode.value)
gl.glViewport(
self._viewport[0],
self._viewport[1],
self._viewport[2],
self._viewport[3],
)
gl.glPopAttrib()
def set_state(self):
self._set_view()
SceneViewer._gl_set_background(self._background)
SceneViewer._gl_enable_depth(self.scene.camera)
SceneViewer._gl_enable_color_material()
SceneViewer._gl_enable_blending()
SceneViewer._gl_enable_smooth_lines()
SceneViewer._gl_enable_lighting(self.scene)
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glMultMatrixf(
rendering.matrix_to_gl(np.linalg.inv(self.scene.camera_transform)))
def unset_state(self):
gl.glPopMatrix()
SceneViewer._gl_unset_background()
self._unset_view()
class MeshGroup(pyglet.graphics.Group):
def __init__(self, transform=None, texture=None, parent=None):
super().__init__(parent)
if transform is None:
transform = np.eye(4)
self.transform = transform
self.texture = texture
def set_state(self):
gl.glPushMatrix()
gl.glMultMatrixf(rendering.matrix_to_gl(self.transform))
if self.texture:
gl.glEnable(self.texture.target)
gl.glBindTexture(self.texture.target, self.texture.id)
def unset_state(self):
if self.texture:
gl.glDisable(self.texture.target)
gl.glPopMatrix()
class SceneWidget(glooey.Widget):
def __init__(self, scene, **kwargs):
super().__init__()
self.scene = scene
self._scene_group = None
# key is node_name
self.mesh_group = {}
# key is geometry_name
self.vertex_list = {}
self.vertex_list_hash = {}
self.textures = {}
self._initial_camera_transform = self.scene.camera_transform.copy()
self.reset_view()
self._background = kwargs.pop('background', None)
self._smooth = kwargs.pop('smooth', True)
if kwargs:
raise TypeError('unexpected kwargs: {}'.format(kwargs))
@property
def scene_group(self):
if self._scene_group is None:
pixel_per_point = (np.array(self.window.get_viewport_size()) /
np.array(self.window.get_size()))
self._scene_group = SceneGroup(
rect=self.rect,
scene=self.scene,
background=self._background,
pixel_per_point=pixel_per_point,
parent=self.group,
)
return self._scene_group
def clear(self):
self._scene_group = None
self.mesh_group = {}
while self.vertex_list:
_, vertex = self.vertex_list.popitem()
vertex.delete()
self.vertex_list_hash = {}
self.textures = {}
def reset_view(self):
self.view = {
'ball': Trackball(
pose=self._initial_camera_transform,
size=self.scene.camera.resolution,
scale=self.scene.scale,
target=self.scene.centroid)}
self.scene.camera_transform[...] = self.view['ball'].pose
def do_claim(self):
return 0, 0
def do_regroup(self):
if not self.vertex_list:
return
node_names = self.scene.graph.nodes_geometry
for node_name in node_names:
transform, geometry_name = self.scene.graph[node_name]
if geometry_name not in self.vertex_list:
continue
vertex_list = self.vertex_list[geometry_name]
if node_name in self.mesh_group:
mesh_group = self.mesh_group[node_name]
else:
mesh_group = MeshGroup(
transform=transform,
texture=self.textures.get(geometry_name),
parent=self.scene_group)
self.mesh_group[node_name] = mesh_group
self.batch.migrate(
vertex_list,
gl.GL_TRIANGLES,
mesh_group,
self.batch)
def do_draw(self):
resolution = (self.rect.width, self.rect.height)
if not (resolution == self.scene.camera.resolution).all():
self.scene.camera.resolution = resolution
node_names = self.scene.graph.nodes_geometry
for node_name in node_names:
transform, geometry_name = self.scene.graph[node_name]
geometry = self.scene.geometry[geometry_name]
self._update_node(node_name, geometry_name, geometry, transform)
def do_undraw(self):
if not self.vertex_list:
return
for vertex_list in self.vertex_list.values():
vertex_list.delete()
self._scene_group = None
self.mesh_group = {}
self.vertex_list = {}
self.vertex_list_hash = {}
self.textures = {}
def on_mouse_press(self, x, y, buttons, modifiers):
SceneViewer.on_mouse_press(self, x, y, buttons, modifiers)
self._draw()
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
# detect a drag across widgets
x_prev = x - dx
y_prev = y - dy
left, bottom = self.rect.left, self.rect.bottom
width, height = self.rect.width, self.rect.height
if not (left < x_prev <= left + width) or \
not (bottom < y_prev <= bottom + height):
self.view['ball'].down(np.array([x, y]))
SceneViewer.on_mouse_drag(self, x, y, dx, dy, buttons, modifiers)
self._draw()
def on_mouse_scroll(self, x, y, dx, dy):
SceneViewer.on_mouse_scroll(self, x, y, dx, dy)
self._draw()
def _update_node(self, node_name, geometry_name, geometry, transform):
geometry_hash_new = geometry_hash(geometry)
if self.vertex_list_hash.get(geometry_name) != geometry_hash_new:
# if geometry has texture defined convert it to opengl form
if hasattr(geometry, 'visual') and hasattr(
geometry.visual, 'material'):
tex = rendering.material_to_texture(geometry.visual.material)
if tex is not None:
self.textures[geometry_name] = tex
if node_name in self.mesh_group:
mesh_group = self.mesh_group[node_name]
mesh_group.transform = transform
mesh_group.texture = self.textures.get(geometry_name)
else:
mesh_group = MeshGroup(
transform=transform,
texture=self.textures.get(geometry_name),
parent=self.scene_group)
self.mesh_group[node_name] = mesh_group
if self.vertex_list_hash.get(geometry_name) != geometry_hash_new:
if geometry_name in self.vertex_list:
self.vertex_list[geometry_name].delete()
# convert geometry to constructor args
args = rendering.convert_to_vertexlist(
geometry,
group=mesh_group,
smooth=self._smooth)
# create the indexed vertex list
self.vertex_list[geometry_name] = self.batch.add_indexed(*args)
# save the MD5 of the geometry
self.vertex_list_hash[geometry_name] = geometry_hash_new
| 4,454 |
679 | <filename>main/package/qa/storages/RegressionTest_125919.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 complex.storages;
import java.lang.Integer;
import com.sun.star.uno.XInterface;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XSingleServiceFactory;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import com.sun.star.io.XStream;
import com.sun.star.io.XInputStream;
import com.sun.star.embed.*;
import share.LogWriter;
import complex.storages.TestHelper;
import complex.storages.StorageTest;
import complex.storages.BorderedStream;
public class RegressionTest_125919 implements StorageTest {
XMultiServiceFactory m_xMSF;
XSingleServiceFactory m_xStorageFactory;
TestHelper m_aTestHelper;
int nMinTestLen = 0;
int nMaxTestLen = 60000;
public RegressionTest_125919( XMultiServiceFactory xMSF, XSingleServiceFactory xStorageFactory, LogWriter aLogWriter )
{
m_xMSF = xMSF;
m_xStorageFactory = xStorageFactory;
m_aTestHelper = new TestHelper( aLogWriter, "RegressionTest_125919: " );
}
public boolean test()
{
try
{
byte[] pBytes0 = new byte[0];
byte[] pBytes18 = new byte[18000];
byte[] pBytes36 = new byte[36000];
for ( int nInitInd = 0; nInitInd < 36000; nInitInd++ )
{
pBytes36[nInitInd] = ( new Integer( nInitInd >> ( ( nInitInd % 2 ) * 8 ) ) ).byteValue();
if ( nInitInd < 18000 )
pBytes18[nInitInd] = ( new Integer( 256 - pBytes36[nInitInd] ) ).byteValue();
}
System.out.println( "This test can take up to some hours. The file size currently is about 50000." );
System.out.println( "Progress: " );
for ( int nAvailableBytes = nMinTestLen; nAvailableBytes < nMaxTestLen; nAvailableBytes++ )
{
Object oBStream = new BorderedStream( nAvailableBytes );
XStream xBorderedStream = (XStream)UnoRuntime.queryInterface( XStream.class, oBStream );
if ( xBorderedStream == null )
{
m_aTestHelper.Error( "Can't create bordered stream!" );
return false;
}
// create storage based on the temporary stream
Object pArgs[] = new Object[2];
pArgs[0] = (Object) xBorderedStream;
pArgs[1] = new Integer( ElementModes.WRITE );
Object oTempStorage = m_xStorageFactory.createInstanceWithArguments( pArgs );
XStorage xTempStorage = (XStorage) UnoRuntime.queryInterface( XStorage.class, oTempStorage );
if ( xTempStorage == null )
{
m_aTestHelper.Error( "Can't create temporary storage representation!" );
return false;
}
XTransactedObject xTransact = (XTransactedObject) UnoRuntime.queryInterface( XTransactedObject.class, xTempStorage );
if ( xTransact == null )
{
m_aTestHelper.Error( "This test is designed for storages in transacted mode!" );
return false;
}
if ( !m_aTestHelper.WriteBytesToSubstream( xTempStorage, "SubStream" + 0, "MediaType1", true, pBytes0 ) )
return false;
if ( !m_aTestHelper.WriteBytesToSubstream( xTempStorage, "SubStream" + 18, "MediaType2", true, pBytes18 ) )
return false;
if ( !m_aTestHelper.WriteBytesToSubstream( xTempStorage, "SubStream" + 36, "MediaType3", true, pBytes36 ) )
return false;
if ( nAvailableBytes > 0 && nAvailableBytes % 100 == 0 )
System.out.println( " " + nAvailableBytes );
if ( nAvailableBytes > 0 && nAvailableBytes % 2 == 1 )
System.out.print( "#" );
try
{
xTransact.commit();
System.out.println( "" );
if ( !m_aTestHelper.disposeStorage( xTempStorage ) )
return false;
// SUCCESS
return true;
}
catch( UseBackupException aExc )
{
// when there is not enough place in the target location and the target file is empty
// the direct writing will fail and must throw this exception with empty URL
if ( aExc.TemporaryFileURL.length() != 0 )
return false;
}
catch( Exception e )
{
System.out.println( "" );
m_aTestHelper.Error( "Unexpected exception: " + e + "\nnAvailableBytes = " + nAvailableBytes );
return false;
}
}
return false;
}
catch( Exception e )
{
m_aTestHelper.Error( "Exception: " + e );
return false;
}
}
}
| 1,822 |
822 | package com.zlm.hp.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* @Description: 设置开关按钮
* @Param:
* @Return:
* @Author: zhangliangming
* @Date: 2017/7/21 21:51
* @Throws:
*/
public class SetupBGButton extends RelativeLayout {
private boolean isLoadColor = false;
private boolean isSelect = false;
private boolean isPressed = false;
public SetupBGButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public SetupBGButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public SetupBGButton(Context context) {
super(context);
init(context);
}
private void init(Context context) {
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (!isLoadColor) {
int strokeWidth = 2; // 3dp 边框宽度
int strokeColor = parserColor("#555555,60");// 边框颜色
int fillColor = Color.TRANSPARENT;
if (isPressed || isSelect) {
strokeColor = parserColor("#31afff,130");
fillColor = parserColor("#31afff,40");
invalidateChild(parserColor("#31afff"));
} else {
invalidateChild(parserColor("#555555"));
}
GradientDrawable gd = new GradientDrawable();// 创建drawable
gd.setColor(fillColor);
gd.setStroke(strokeWidth, strokeColor);
gd.setShape(GradientDrawable.OVAL);
setBackgroundDrawable(gd);
isLoadColor = true;
}
super.dispatchDraw(canvas);
}
@Override
public void setPressed(boolean pressed) {
isLoadColor = false;
isPressed = pressed;
invalidate();
super.setPressed(pressed);
}
public void setSelect(boolean select) {
isLoadColor = false;
isSelect = select;
invalidate();
}
public boolean isSelect() {
return isSelect;
}
private void invalidateChild(int textColor) {
int count = getChildCount();
for (int i = 0; i < count; i++) {
View v = getChildAt(i);
if (v instanceof TextView) {
TextView temp = (TextView) v;
temp.setTextColor(textColor);
}
}
}
/**
* 解析颜色字符串
*
* @param value
* 颜色字符串 #edf8fc,255
* @return
*/
private int parserColor(String value) {
String regularExpression = ",";
if (value.contains(regularExpression)) {
String[] temp = value.split(regularExpression);
int color = Color.parseColor(temp[0]);
int alpha = Integer.valueOf(temp[1]);
int red = (color & 0xff0000) >> 16;
int green = (color & 0x00ff00) >> 8;
int blue = (color & 0x0000ff);
return Color.argb(alpha, red, green, blue);
}
return Color.parseColor(value);
}
}
| 1,093 |
416 | //
// UNNotificationContent.h
// UserNotifications
//
// Copyright © 2015 Apple Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
@class UNNotificationAttachment;
@class UNNotificationSound;
NS_ASSUME_NONNULL_BEGIN
__IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0)
@interface UNNotificationContent : NSObject <NSCopying, NSMutableCopying, NSSecureCoding>
// Optional array of attachments.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSArray <UNNotificationAttachment *> *attachments __TVOS_PROHIBITED;
// The application badge number.
@property (NS_NONATOMIC_IOSONLY, readonly, copy, nullable) NSNumber *badge;
// The body of the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *body __TVOS_PROHIBITED;
// The identifier for a registered UNNotificationCategory that will be used to determine the appropriate actions to display for the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *categoryIdentifier __TVOS_PROHIBITED;
// The launch image that will be used when the app is opened from the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *launchImageName __TVOS_PROHIBITED;
// The sound that will be played for the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy, nullable) UNNotificationSound *sound __TVOS_PROHIBITED;
// The subtitle of the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *subtitle __TVOS_PROHIBITED;
// The unique identifier for the thread or conversation related to this notification request. It will be used to visually group notifications together.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *threadIdentifier __TVOS_PROHIBITED;
// The title of the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *title __TVOS_PROHIBITED;
// Apps can set the userInfo for locally scheduled notification requests. The contents of the push payload will be set as the userInfo for remote notifications.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSDictionary *userInfo __TVOS_PROHIBITED;
@end
__IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0)
@interface UNMutableNotificationContent : UNNotificationContent
// Optional array of attachments.
@property (NS_NONATOMIC_IOSONLY, copy) NSArray <UNNotificationAttachment *> *attachments __TVOS_PROHIBITED;
// The application badge number. nil means no change. 0 to hide.
@property (NS_NONATOMIC_IOSONLY, copy, nullable) NSNumber *badge;
// The body of the notification. Use -[NSString localizedUserNotificationStringForKey:arguments:] to provide a string that will be localized at the time that the notification is presented.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *body __TVOS_PROHIBITED;
// The identifier for a registered UNNotificationCategory that will be used to determine the appropriate actions to display for the notification.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *categoryIdentifier __TVOS_PROHIBITED;
// The launch image that will be used when the app is opened from the notification.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *launchImageName __TVOS_PROHIBITED;
// The sound that will be played for the notification.
@property (NS_NONATOMIC_IOSONLY, copy, nullable) UNNotificationSound *sound __TVOS_PROHIBITED;
// The subtitle of the notification. Use -[NSString localizedUserNotificationStringForKey:arguments:] to provide a string that will be localized at the time that the notification is presented.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *subtitle __TVOS_PROHIBITED;
// The unique identifier for the thread or conversation related to this notification request. It will be used to visually group notifications together.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *threadIdentifier __TVOS_PROHIBITED;
// The title of the notification. Use -[NSString localizedUserNotificationStringForKey:arguments:] to provide a string that will be localized at the time that the notification is presented.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *title __TVOS_PROHIBITED;
// Apps can set the userInfo for locally scheduled notification requests. The contents of the push payload will be set as the userInfo for remote notifications.
@property (NS_NONATOMIC_IOSONLY, copy) NSDictionary *userInfo;
@end
NS_ASSUME_NONNULL_END
| 1,353 |
369 | //*******************************************************************************
// Provides Functions to Initialize the UCS/FLL and clock sources
// File: hal_ucs.c
//
// Texas Instruments
//
// Version 1.2
// 11/24/09
//
// V1.0 Initial Version
// V1.1 Added timeout function
// V1.1 Added parameter for XTDrive
//*******************************************************************************
#ifndef __hal_UCS
#define __hal_UCS
#include <stdint.h>
#include "hal_macros.h"
/*************************************************************************
* MACROS
**************************************************************************/
/* Select source for FLLREF e.g. SELECT_FLLREF(SELREF__XT1CLK) */
#define SELECT_FLLREF(source) st(UCSCTL3 = (UCSCTL3 & ~(SELREF_7)) | (source);)
/* Select source for ACLK e.g. SELECT_ACLK(SELA__XT1CLK) */
#define SELECT_ACLK(source) st(UCSCTL4 = (UCSCTL4 & ~(SELA_7)) | (source);)
/* Select source for MCLK e.g. SELECT_MCLK(SELM__XT2CLK) */
#define SELECT_MCLK(source) st(UCSCTL4 = (UCSCTL4 & ~(SELM_7)) | (source);)
/* Select source for SMCLK e.g. SELECT_SMCLK(SELS__XT2CLK) */
#define SELECT_SMCLK(source) st(UCSCTL4 = (UCSCTL4 & ~(SELS_7)) | (source);)
/* Select source for MCLK and SMCLK e.g. SELECT_MCLK_SMCLK(SELM__DCOCLK + SELS__DCOCLK) */
#define SELECT_MCLK_SMCLK(sources) st(UCSCTL4 = (UCSCTL4 & ~(SELM_7 + SELS_7)) | (sources);)
/* set ACLK/x */
#define ACLK_DIV(x) st(UCSCTL5 = (UCSCTL5 & ~(DIVA_7)) | (DIVA__##x);)
/* set MCLK/x */
#define MCLK_DIV(x) st(UCSCTL5 = (UCSCTL5 & ~(DIVM_7)) | (DIVM__##x);)
/* set SMCLK/x */
#define SMCLK_DIV(x) st(UCSCTL5 = (UCSCTL5 & ~(DIVS_7)) | (DIVS__##x);)
/* Select divider for FLLREF e.g. SELECT_FLLREFDIV(2) */
#define SELECT_FLLREFDIV(x) st(UCSCTL3 = (UCSCTL3 & ~(FLLREFDIV_7))|(FLLREFDIV__##x);)
//************************************************************************
// Defines
//************************************************************************
#define UCS_STATUS_OK 0
#define UCS_STATUS_ERROR 1
//====================================================================
/**
* Startup routine for 32kHz Cristal on LFXT1
*
* \param xtdrive: Bits defining the LFXT drive mode after startup
*
*/
extern void LFXT_Start(uint16_t xtdrive);
//====================================================================
/**
* Startup routine for 32kHz Cristal on LFXT1 with timeout counter
*
* \param xtdrive: Bits defining the LFXT drive mode after startup
* \param timeout: value for the timeout counter
*
*/
extern uint16_t LFXT_Start_Timeout(uint16_t xtdrive, uint16_t timeout);
//====================================================================
/**
* Startup routine for XT1
*
* \param xtdrive: Bits defining the XT drive mode
*
*/
extern void XT1_Start(uint16_t xtdrive);
//====================================================================
/**
* Startup routine for XT1 with timeout counter
*
* \param xtdrive: Bits defining the XT drive mode
* \param timeout: value for the timeout counter
*
*/
extern uint16_t XT1_Start_Timeout(uint16_t xtdrive, uint16_t timeout);
//====================================================================
/**
* Use XT1 in Bypasss mode
*
*/
extern void XT1_Bypass(void);
//====================================================================
/**
* Startup routine for XT2
*
* \param xtdrive: Bits defining the XT drive mode
*
*/
extern void XT2_Start(uint16_t xtdrive);
//====================================================================
/**
* Startup routine for XT2 with timeout counter
*
* \param xtdrive: Bits defining the XT drive mode
* \param timeout: value for the timeout counter
*
*/
extern uint16_t XT2_Start_Timeout(uint16_t xtdrive, uint16_t timeout);
//====================================================================
/**
* Use XT2 in Bypasss mode for MCLK
*
*/
extern void XT2_Bypass(void);
//====================================================================
/**
* Initializes FLL of the UCS and wait till settled
*
* \param fsystem required system frequency (MCLK) in kHz
* \param ratio ratio between fsystem and FLLREFCLK
*/
extern void Init_FLL_Settle(uint16_t fsystem, uint16_t ratio);
//====================================================================
/**
* Initializes FLL of the UCS
*
* \param fsystem required system frequency (MCLK) in kHz
* \param ratio ratio between fsystem and FLLREFCLK
*/
static void Init_FLL(uint16_t fsystem, uint16_t ratio);
#endif /* __hal_UCS */
| 1,521 |
348 | <gh_stars>100-1000
{"nom":"Caluire-et-Cuire","circ":"5ème circonscription","dpt":"Rhône","inscrits":31732,"abs":15534,"votants":16198,"blancs":95,"nuls":21,"exp":16082,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":6969},{"nuance":"LR","nom":"<NAME>","voix":4564},{"nuance":"FI","nom":"Mme <NAME>","voix":1487},{"nuance":"ECO","nom":"M. <NAME>","voix":1136},{"nuance":"FN","nom":"Mme <NAME>","voix":947},{"nuance":"COM","nom":"Mme <NAME>","voix":277},{"nuance":"DIV","nom":"Mme <NAME>","voix":171},{"nuance":"DIV","nom":"Mme <NAME>","voix":170},{"nuance":"DLF","nom":"Mme <NAME>","voix":136},{"nuance":"DVD","nom":"<NAME>","voix":86},{"nuance":"EXG","nom":"<NAME>","voix":68},{"nuance":"DIV","nom":"<NAME>","voix":65},{"nuance":"DIV","nom":"M. <NAME>","voix":6}]} | 310 |
455 | <gh_stars>100-1000
#pragma once
#include <vector>
#include <typeinfo>
#include "../Entity.h"
#include "../Logger.h"
#include "../Context.h"
#include "../Components/TransformComponent.h"
#include "../AI/Pathfinding/PathFindManager.h"
#include "../Helpers/HashTag.h"
#include "../Graphics/Color.h"
namespace star
{
class BaseComponent;
class PathFindNodeComponent;
class BaseScene;
class Action;
class Object : public Entity
{
public:
Object();
explicit Object(const tstring & name);
Object(
const tstring & name,
const tstring & groupTag
);
virtual ~Object(void);
void Destroy();
Object* GetParent() const;
void BaseInitialize();
void BaseAfterInitialized();
void BaseUpdate(const Context& context);
void BaseDraw();
void BaseDrawWithCulling(
float32 left,
float32 right,
float32 top,
float32 bottom
);
const tstring& GetPhysicsTag() const;
void SetPhysicsTag(const tstring& tag);
bool ComparePhysicsTag(const tstring & tag);
const tstring& GetGroupTag() const;
void SetGroupTag(const tstring& tag);
bool CompareGroupTag(const tstring & tag);
void AddComponent(BaseComponent* pComponent);
virtual void AddChild(Object* pObject);
void RemoveChild(const Object* pObject);
void RemoveChild(const tstring & name);
const std::vector<Object*>& GetChildren() const;
void SetChildFrozen(const tstring & name, bool freeze);
void SetChildDisabled(const tstring & name, bool disabled);
void SetChildVisible(const tstring & name, bool visible);
void SetChildrenFrozen(bool freeze);
void SetChildrenDisabled(bool disable);
void SetChildrenVisible(bool visible);
void AddAction(Action * pAction);
void RemoveAction(Action *pAction);
void RemoveAction(const tstring & name);
void RestartAction(const tstring & name);
void PauseAction(const tstring & name);
void ResumeAction(const tstring & name);
void RemoveComponent(BaseComponent * pComponent);
template <typename T>
T * GetChildByName(const tstring & name);
virtual void SetVisible(bool visible);
bool IsVisible() const;
virtual void Freeze(bool freeze);
bool IsFrozen() const;
bool IsChildNameAlreadyInUse(const tstring & name) const;
bool IsActionNameAlreadyInUse(const tstring & name) const;
virtual void SetDisabled(bool disabled);
virtual bool IsDisabled() const;
bool IsInitialized() const;
void SetScene(BaseScene * pScene);
void UnsetScene();
virtual void Reset();
TransformComponent * GetTransform() const;
BaseScene * GetScene() const;
template <typename T>
void RemoveComponent();
template <typename T>
T* GetComponent(bool searchChildren = false) const;
const std::vector<BaseComponent*>& GetComponents() const;
template <typename T>
T* GetChild() const;
template <typename T>
T* GetChild(const tstring & name) const;
template <typename T>
bool HasComponent(BaseComponent * component) const;
void RecalculateDimensions();
protected:
enum class GarbageType : byte
{
ComponentType = 0,
ObjectType = 1,
ActionType = 2
};
struct GarbageInfo
{
GarbageInfo(
Entity* pEntity,
GarbageType type
);
Entity *element;
GarbageType type;
};
void DestroyGarbageElement(const GarbageInfo & info);
virtual void Initialize();
virtual void AfterInitialized();
virtual void Update(const Context & context);
virtual void Draw();
bool BaseCheckCulling(
float32 left, float32 right, float32 top, float32 bottom
);
virtual bool CheckCulling(
float32 left,
float32 right,
float32 top,
float32 bottom
);
bool m_bIsInitialized;
bool m_IsVisible;
bool m_IsFrozen;
Object* m_pParentGameObject;
PathFindNodeComponent* m_pPathFindComp;
BaseScene *m_pScene;
std::vector<GarbageInfo> m_pGarbageContainer;
std::vector<BaseComponent*> m_pComponents;
std::vector<Object*> m_pChildren;
std::vector<Action*> m_pActions;
HashTag m_GroupTag, m_PhysicsTag;
private:
void CollectGarbage();
Object(const Object& t);
Object(Object&& t);
Object& operator=(const Object& t);
Object& operator=(Object&& t);
};
}
#include "Object.inl"
| 1,671 |
5,651 | <gh_stars>1000+
import sys
import collections
Result = collections.namedtuple('Result', 'total average')
def adder():
total = 0
count = 0
while True:
term = yield
try:
term = float(term)
except (ValueError, TypeError):
break
else:
total += term
count += 1
return Result(total, total/count)
def process_args(coro, args):
for arg in args:
coro.send(arg)
try:
next(coro)
except StopIteration as exc:
return exc.value
def prompt(coro):
while True:
term = input('+> ')
try:
coro.send(term)
except StopIteration as exc:
return exc.value
def main():
coro = adder()
next(coro) # prime it
if len(sys.argv) > 1:
res = process_args(coro, sys.argv[1:])
else:
res = prompt(coro)
print(res)
main()
| 448 |
808 | <reponame>stjordanis/symengine
#include <iostream>
#include <chrono>
#include <cstdlib>
#include <iomanip>
#include "symengine/ntheory.h"
#include <symengine/mul.h>
#include <symengine/integer.h>
#include <symengine/basic.h>
#include "symengine/constants.h"
#include <symengine/add.h>
#include <symengine/pow.h>
#include <symengine/symbol.h>
using SymEngine::add;
using SymEngine::Basic;
using SymEngine::div;
using SymEngine::factorial;
using SymEngine::gcd;
using SymEngine::Integer;
using SymEngine::integer;
using SymEngine::Number;
using SymEngine::one;
using SymEngine::pow;
using SymEngine::RCP;
using SymEngine::rcp_static_cast;
using SymEngine::symbol;
double A()
{
auto t1 = std::chrono::high_resolution_clock::now();
for (int i = 1; i <= 100; i++) {
div(factorial(1000 + i), factorial(900 + i));
}
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double B()
{
RCP<const Number> s = integer(0);
auto t1 = std::chrono::high_resolution_clock::now();
for (int i = 1; i <= 1000; i++) {
s = s->add(*one->div(*integer(i)));
}
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double C()
{
RCP<const Integer> x = integer(13 * 17 * 31);
RCP<const Integer> y = integer(13 * 19 * 29);
auto t1 = std::chrono::high_resolution_clock::now();
for (int i = 1; i <= 200; i++) {
gcd(*rcp_static_cast<const Integer>(pow(x, integer(300 + i % 181))),
*rcp_static_cast<const Integer>(pow(y, integer(200 + i % 183))));
}
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double D()
{
RCP<const Basic> s = integer(0);
RCP<const Basic> y = symbol("y");
RCP<const Basic> t = symbol("t");
auto t1 = std::chrono::high_resolution_clock::now();
for (int i = 1; i <= 10; i++) {
s = add(s, div(mul(integer(i), mul(y, pow(t, integer(i)))),
pow(add(y, mul(integer(i), t)), integer(i))));
}
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double E()
{
RCP<const Basic> s = integer(0);
RCP<const Basic> y = symbol("y");
RCP<const Basic> t = symbol("t");
auto t1 = std::chrono::high_resolution_clock::now();
for (int i = 1; i <= 10; i++) {
s = add(s, div(mul(integer(i), mul(y, pow(t, integer(i)))),
pow(add(y, mul(integer(abs(5 - i)), t)), integer(i))));
}
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
int main(int argc, char *argv[])
{
SymEngine::print_stack_on_segfault();
std::cout << "Time for A : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << A() << std::endl;
std::cout << "Time for B : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << B() << std::endl;
std::cout << "Time for C : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << C() << std::endl;
std::cout << "Time for D : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << D() << std::endl;
std::cout << "Time for E : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << E() << std::endl;
return 0;
}
| 1,501 |
591 | <reponame>turesnake/tprPixelGames
/*
* ======================= BoolBitMap.h =======================
* -- tpr --
* CREATE -- 2019.02.03
* MODIFY --
* ----------------------------------------------------------
* each bit mean a bool_flag
* ----------------------------
*/
#ifndef TPR_BOOL_BIT_MAP_H
#define TPR_BOOL_BIT_MAP_H
//-------------------- CPP --------------------//
#include <cmath>
#include <vector>
//-------------------- Engine --------------------//
#include "tprAssert.h"
#include "tprCast.h"
//- each bit:
// 0: false
// 1: true
class BoolBitMap{
public:
BoolBitMap() = default;
inline void resize( size_t w_, size_t h_=1 )noexcept{
this->wLen = w_;
this->hLen = h_;
this->totalNum = w_ * h_;
//--
size_t bytes = cast_2_size_t( ceil( static_cast<double>(this->totalNum) /
static_cast<double>(BoolBitMap::BITS_PER_BYTE) ) );
bitMap.resize( bytes );
}
inline void clear_all()noexcept{
for( auto &i : bitMap ){
i = 0; //- all false
}
}
inline void signUp( size_t w_, size_t h_ )noexcept{
tprAssert( (w_<this->wLen) && (h_<this->hLen) );
size_t idx = h_ * this->wLen + w_;
//---
tprAssert( (idx/BoolBitMap::BITS_PER_BYTE) < bitMap.size() );
uint8_t &bitRef = bitMap.at( idx/BoolBitMap::BITS_PER_BYTE );
bitRef = bitRef | static_cast<uint8_t>(1 << (idx%BoolBitMap::BITS_PER_BYTE));
}
inline void signUp( size_t idx_ )noexcept{
tprAssert( idx_ < this->totalNum );
//---
tprAssert( (idx_/BoolBitMap::BITS_PER_BYTE) < bitMap.size() );
uint8_t &bitRef = bitMap.at( idx_/BoolBitMap::BITS_PER_BYTE );
bitRef = bitRef | static_cast<uint8_t>(1 << (idx_%BoolBitMap::BITS_PER_BYTE));
}
inline bool check( size_t w_, size_t h_ )noexcept{
tprAssert( (w_<this->wLen) && (h_<this->hLen) );
size_t idx = h_ * this->wLen + w_;
//---
tprAssert( (idx/BoolBitMap::BITS_PER_BYTE) < bitMap.size() );
const uint8_t &bitRef = bitMap.at( idx/BoolBitMap::BITS_PER_BYTE );
return ( ((bitRef>>(idx%BoolBitMap::BITS_PER_BYTE)) & 1)==1 );
}
inline bool check( size_t idx_ )noexcept{
tprAssert( idx_ < this->totalNum );
//---
tprAssert( (idx_/BoolBitMap::BITS_PER_BYTE) < bitMap.size() );
const uint8_t &bitRef = bitMap.at( idx_/BoolBitMap::BITS_PER_BYTE );
return ( ((bitRef>>(idx_%BoolBitMap::BITS_PER_BYTE)) & 1)==1 );
}
private:
std::vector<uint8_t> bitMap {};
size_t wLen {};
size_t hLen {};
size_t totalNum {};
//======== static ========//
static size_t BITS_PER_BYTE;
};
#endif
| 1,419 |
388 | // -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
add(new JScrollPane(new JTextArea()));
add(new StatusBar(), BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class StatusBar extends JPanel {
protected StatusBar() {
super(new BorderLayout());
add(new BottomRightCornerLabel(), BorderLayout.EAST);
setOpaque(false);
}
}
class BottomRightCornerLabel extends JLabel {
private transient MouseInputListener handler;
protected BottomRightCornerLabel() {
super(new BottomRightCornerIcon());
}
@Override public void updateUI() {
removeMouseListener(handler);
removeMouseMotionListener(handler);
super.updateUI();
handler = new ResizeWindowListener();
addMouseListener(handler);
addMouseMotionListener(handler);
setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
}
}
class ResizeWindowListener extends MouseInputAdapter {
private final Rectangle rect = new Rectangle();
private final Point startPt = new Point();
@Override public void mousePressed(MouseEvent e) {
Component p = SwingUtilities.getRoot(e.getComponent());
if (p instanceof Window) {
startPt.setLocation(e.getPoint());
rect.setBounds(p.getBounds());
}
}
@Override public void mouseDragged(MouseEvent e) {
Component p = SwingUtilities.getRoot(e.getComponent());
if (!rect.isEmpty() && p instanceof Window) {
Point pt = e.getPoint();
rect.width += pt.x - startPt.x;
rect.height += pt.y - startPt.y;
p.setBounds(rect);
}
}
}
// https://web.archive.org/web/20050609021916/http://today.java.net/pub/a/today/2005/06/07/pixelpushing.html
class BottomRightCornerIcon implements Icon {
private static final Color SQUARE_COLOR = new Color(160, 160, 160, 160);
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
int diff = 3;
Graphics2D g2 = (Graphics2D) g.create();
g2.translate(getIconWidth() - diff * 3 - 1, getIconHeight() - diff * 3 - 1);
int firstRow = 0;
int secondRow = firstRow + diff;
int thirdRow = secondRow + diff;
int firstColumn = 0;
drawSquare(g2, firstColumn, thirdRow);
int secondColumn = firstColumn + diff;
drawSquare(g2, secondColumn, secondRow);
drawSquare(g2, secondColumn, thirdRow);
int thirdColumn = secondColumn + diff;
drawSquare(g2, thirdColumn, firstRow);
drawSquare(g2, thirdColumn, secondRow);
drawSquare(g2, thirdColumn, thirdRow);
g2.dispose();
}
@Override public int getIconWidth() {
return 16;
}
@Override public int getIconHeight() {
return 20;
}
private void drawSquare(Graphics g, int x, int y) {
g.setColor(SQUARE_COLOR);
g.fillRect(x, y, 2, 2);
}
}
| 1,328 |
396 | package me.everything.providers.sample.fragments;
import android.widget.TextView;
import me.everything.providers.android.media.Artist;
import me.everything.providers.android.media.MediaProvider;
import me.everything.providers.core.Data;
import me.everything.providers.sample.base.GetCursorTask;
/**
* Created by sromku
*/
public class ArtistsFragment extends MediaFragment<Artist> {
@Override
protected String getTitle() {
return "Artists";
}
@Override
protected void bindEntity(Artist artist, TextView title, TextView details) {
title.setText(artist.artist);
details.setText(artist.id + "");
}
@Override
protected GetCursorTask.DataFetcher<Artist> getFetcher() {
return new GetCursorTask.DataFetcher<Artist>() {
@Override
public Data<Artist> getData() {
MediaProvider provider = new MediaProvider(getApplicationContext());
return provider.getArtists(isExternal ?
MediaProvider.Storage.EXTERNAL :
MediaProvider.Storage.INTERNAL);
}
};
}
}
| 454 |
1,040 | <reponame>titanomachy/flight
/*
* Integrates the 3d stereo data (from LCM) and the IMU data (from LCM)
* and generates an obstacle map. Then uses that map with a trajectory
* library for control.
*
* Author: <NAME>, <<EMAIL>> 2013-2015
*
*/
#include "stereo-imu-obstacles.hpp"
#define PUBLISH_MAP_TO_STEREO_AT_EVERY_FRAME
using Eigen::Matrix3d;
using Eigen::Vector3d;
using namespace std;
using namespace octomap;
lcm_t * lcm;
char *lcm_out = NULL;
int numFrames = 0;
unsigned long totalTime = 0;
bool disable_filtering = false;
int64_t currentOctreeTimestamp, buildingOctreeTimestamp;
// global trajectory library
TrajectoryLibrary trajlib;
bot_lcmgl_t* lcmgl;
// globals for subscription functions, so we can unsubscribe in the control-c handler
lcmt_stereo_subscription_t * stereo_sub;
void stereo_handler(const lcm_recv_buf_t *rbuf, const char* channel, const lcmt_stereo *msg, void *user) {
// start the rate clock
struct timeval start, now;
unsigned long elapsed;
gettimeofday( &start, NULL );
StereoHandlerData *data = (StereoHandlerData*)user;
StereoOctomap *octomap = data->octomap;
StereoFilter *filter = data->filter;
lcmt_stereo *filtered_msg;
// filter the stereo message
if (disable_filtering == false) {
filtered_msg = filter->ProcessMessage(msg);
} else {
filtered_msg = lcmt_stereo_copy(msg);
}
//cout << "Number of points: " << msg->number_of_points << " --> " << filtered_msg->number_of_points << endl;
octomap->ProcessStereoMessage(filtered_msg);
if (numFrames%15 == 0) {
octomap->PublishOctomap(lcm);
}
#ifdef PUBLISH_MAP_TO_STEREO_AT_EVERY_FRAME
octomap->PublishToStereo(lcm, msg->frame_number, msg->video_number);
#endif
// search the trajectory library for the best trajectory
/*
Trajectory* farthestTraj = trajlib.FindFarthestTrajectory(currentOctree, &bodyToLocal, lcmgl);
// publish the farthest trajectory number over LCM for visualization
lcmt_trajectory_number trajNumMsg;
trajNumMsg.timestamp = getTimestampNow();
trajNumMsg.trajNum = farthestTraj->GetTrajectoryNumber();
lcmt_trajectory_number_publish(lcm, "trajectory_number", &trajNumMsg);
// only publish every so often since it swamps the viewer
if (numFrames%30 == 0)
{
PublishOctomap();
}
*/
numFrames ++;
delete filtered_msg;
// compute framerate
gettimeofday( &now, NULL );
elapsed = (now.tv_usec / 1000 + now.tv_sec * 1000) - (start.tv_usec / 1000 + start.tv_sec * 1000);
totalTime += elapsed;
printf("\r%d frames | %f ms/frame", numFrames, (float)totalTime/numFrames);
fflush(stdout);
}
int main(int argc,char** argv) {
bool ttl_one = false;
string config_file = "";
string trajectory_dir = "";
ConciseArgs parser(argc, argv);
parser.add(ttl_one, "t", "ttl-one", "Pass to set LCM TTL=1");
parser.add(disable_filtering, "f", "disable-filtering", "Disable filtering.");
parser.add(config_file, "c", "config", "Configuration file containing camera GUIDs, etc.", true);
parser.add(trajectory_dir, "d", "trajectory-dir" "Directory containing CSV files with trajectories.");
parser.parse();
if (disable_filtering) {
cout << "WARNING: you have disabled filtering with the -f flag." << endl;
}
OpenCvStereoConfig stereo_config;
// parse the config file
if (ParseConfigFile(config_file, &stereo_config) != true)
{
fprintf(stderr, "Failed to parse configuration file, quitting.\n");
return 1;
}
// load calibration
OpenCvStereoCalibration stereo_calibration;
if (LoadCalibration(stereo_config.calibrationDir, &stereo_calibration) != true)
{
cerr << "Error: failed to read calibration files. Quitting." << endl;
return 1;
}
if (trajectory_dir != "") {
// load a trajectory library
if (!trajlib.LoadLibrary(trajectory_dir)) {
cerr << "Error: failed to load trajectory library. Quitting." << endl;
return 1;
}
//trajlib.Print();
}
if (ttl_one) {
lcm = lcm_create ("udpm://192.168.127.12:7667?ttl=1");
} else {
lcm = lcm_create ("udpm://192.168.127.12:7667?ttl=0");
}
if (!lcm)
{
fprintf(stderr, "lcm_create for recieve failed. Quitting.\n");
return 1;
}
// init frames
BotParam *param = bot_param_new_from_server(lcm, 0);
BotFrames *bot_frames = bot_frames_new(lcm, param);
// init octomap
StereoOctomap octomap(bot_frames);
octomap.SetStereoConfig(stereo_config, stereo_calibration);
StereoFilter filter(0.1);
StereoHandlerData user_data;
user_data.octomap = &octomap;
user_data.filter = &filter;
char *stereo_channel;
if (bot_param_get_str(param, "lcm_channels.stereo", &stereo_channel) >= 0) {
stereo_sub = lcmt_stereo_subscribe(lcm, stereo_channel, &stereo_handler, &user_data);
}
lcmgl = bot_lcmgl_init(lcm, "lcmgl-stereo-transformed");
bot_lcmgl_enable(lcmgl, GL_BLEND);
// control-c handler
signal(SIGINT,sighandler);
printf("Receiving LCM:\n\tStereo: %s\n", stereo_channel);
while (true)
{
// read the LCM channel
lcm_handle (lcm);
}
return 0;
}
void sighandler(int dum)
{
printf("\n\nclosing... ");
lcmt_stereo_unsubscribe(lcm, stereo_sub);
lcm_destroy (lcm);
printf("done.\n");
exit(0);
}
| 2,252 |
21,274 | <filename>tools/deploy/torchscript_mask_rcnn.cpp
// Copyright (c) Facebook, Inc. and its affiliates.
// @lint-ignore-every CLANGTIDY
// This is an example code that demonstrates how to run inference
// with a torchscript format Mask R-CNN model exported by ./export_model.py
// using export method=tracing, caffe2_tracing & scripting.
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <c10/cuda/CUDAStream.h>
#include <torch/csrc/autograd/grad_mode.h>
#include <torch/csrc/jit/runtime/graph_executor.h>
#include <torch/script.h>
// only needed for export_method=tracing
#include <torchvision/vision.h> // @oss-only
// @fb-only: #include <torchvision/csrc/vision.h>
using namespace std;
c10::IValue get_caffe2_tracing_inputs(cv::Mat& img, c10::Device device) {
const int height = img.rows;
const int width = img.cols;
// FPN models require divisibility of 32.
// Tracing mode does padding inside the graph, but caffe2_tracing does not.
assert(height % 32 == 0 && width % 32 == 0);
const int channels = 3;
auto input =
torch::from_blob(img.data, {1, height, width, channels}, torch::kUInt8);
// NHWC to NCHW
input = input.to(device, torch::kFloat).permute({0, 3, 1, 2}).contiguous();
std::array<float, 3> im_info_data{height * 1.0f, width * 1.0f, 1.0f};
auto im_info =
torch::from_blob(im_info_data.data(), {1, 3}).clone().to(device);
return std::make_tuple(input, im_info);
}
c10::IValue get_tracing_inputs(cv::Mat& img, c10::Device device) {
const int height = img.rows;
const int width = img.cols;
const int channels = 3;
auto input =
torch::from_blob(img.data, {height, width, channels}, torch::kUInt8);
// HWC to CHW
input = input.to(device, torch::kFloat).permute({2, 0, 1}).contiguous();
return input;
}
// create a Tuple[Dict[str, Tensor]] which is the input type of scripted model
c10::IValue get_scripting_inputs(cv::Mat& img, c10::Device device) {
const int height = img.rows;
const int width = img.cols;
const int channels = 3;
auto img_tensor =
torch::from_blob(img.data, {height, width, channels}, torch::kUInt8);
// HWC to CHW
img_tensor =
img_tensor.to(device, torch::kFloat).permute({2, 0, 1}).contiguous();
auto dic = c10::Dict<std::string, torch::Tensor>();
dic.insert("image", img_tensor);
return std::make_tuple(dic);
}
c10::IValue
get_inputs(std::string export_method, cv::Mat& img, c10::Device device) {
// Given an image, create inputs in the format required by the model.
if (export_method == "tracing")
return get_tracing_inputs(img, device);
if (export_method == "caffe2_tracing")
return get_caffe2_tracing_inputs(img, device);
if (export_method == "scripting")
return get_scripting_inputs(img, device);
abort();
}
struct MaskRCNNOutputs {
at::Tensor pred_boxes, pred_classes, pred_masks, scores;
int num_instances() const {
return pred_boxes.sizes()[0];
}
};
MaskRCNNOutputs get_outputs(std::string export_method, c10::IValue outputs) {
// Given outputs of the model, extract tensors from it to turn into a
// common MaskRCNNOutputs format.
if (export_method == "tracing") {
auto out_tuple = outputs.toTuple()->elements();
// They are ordered alphabetically by their field name in Instances
return MaskRCNNOutputs{
out_tuple[0].toTensor(),
out_tuple[1].toTensor(),
out_tuple[2].toTensor(),
out_tuple[3].toTensor()};
}
if (export_method == "caffe2_tracing") {
auto out_tuple = outputs.toTuple()->elements();
// A legacy order used by caffe2 models
return MaskRCNNOutputs{
out_tuple[0].toTensor(),
out_tuple[2].toTensor(),
out_tuple[3].toTensor(),
out_tuple[1].toTensor()};
}
if (export_method == "scripting") {
// With the ScriptableAdapter defined in export_model.py, the output is
// List[Dict[str, Any]].
auto out_dict = outputs.toList().get(0).toGenericDict();
return MaskRCNNOutputs{
out_dict.at("pred_boxes").toTensor(),
out_dict.at("pred_classes").toTensor(),
out_dict.at("pred_masks").toTensor(),
out_dict.at("scores").toTensor()};
}
abort();
}
int main(int argc, const char* argv[]) {
if (argc != 4) {
cerr << R"xx(
Usage:
./torchscript_mask_rcnn model.ts input.jpg EXPORT_METHOD
EXPORT_METHOD can be "tracing", "caffe2_tracing" or "scripting".
)xx";
return 1;
}
std::string image_file = argv[2];
std::string export_method = argv[3];
assert(
export_method == "caffe2_tracing" || export_method == "tracing" ||
export_method == "scripting");
torch::jit::getBailoutDepth() = 1;
torch::autograd::AutoGradMode guard(false);
auto module = torch::jit::load(argv[1]);
assert(module.buffers().size() > 0);
// Assume that the entire model is on the same device.
// We just put input to this device.
auto device = (*begin(module.buffers())).device();
cv::Mat input_img = cv::imread(image_file, cv::IMREAD_COLOR);
auto inputs = get_inputs(export_method, input_img, device);
// Run the network
auto output = module.forward({inputs});
if (device.is_cuda())
c10::cuda::getCurrentCUDAStream().synchronize();
// run 3 more times to benchmark
int N_benchmark = 3, N_warmup = 1;
auto start_time = chrono::high_resolution_clock::now();
for (int i = 0; i < N_benchmark + N_warmup; ++i) {
if (i == N_warmup)
start_time = chrono::high_resolution_clock::now();
output = module.forward({inputs});
if (device.is_cuda())
c10::cuda::getCurrentCUDAStream().synchronize();
}
auto end_time = chrono::high_resolution_clock::now();
auto ms = chrono::duration_cast<chrono::microseconds>(end_time - start_time)
.count();
cout << "Latency (should vary with different inputs): "
<< ms * 1.0 / 1e6 / N_benchmark << " seconds" << endl;
// Parse Mask R-CNN outputs
auto rcnn_outputs = get_outputs(export_method, output);
cout << "Number of detected objects: " << rcnn_outputs.num_instances()
<< endl;
cout << "pred_boxes: " << rcnn_outputs.pred_boxes.toString() << " "
<< rcnn_outputs.pred_boxes.sizes() << endl;
cout << "scores: " << rcnn_outputs.scores.toString() << " "
<< rcnn_outputs.scores.sizes() << endl;
cout << "pred_classes: " << rcnn_outputs.pred_classes.toString() << " "
<< rcnn_outputs.pred_classes.sizes() << endl;
cout << "pred_masks: " << rcnn_outputs.pred_masks.toString() << " "
<< rcnn_outputs.pred_masks.sizes() << endl;
cout << rcnn_outputs.pred_boxes << endl;
return 0;
}
| 2,556 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.