max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
3,680 | <filename>pxr/imaging/garch/glPlatformContextDarwin.h
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_IMAGING_GARCH_GL_PLATFORM_CONTEXT_DARWIN_H
#define PXR_IMAGING_GARCH_GL_PLATFORM_CONTEXT_DARWIN_H
#include "pxr/pxr.h"
#include <memory>
PXR_NAMESPACE_OPEN_SCOPE
class GarchNSGLContextState {
public:
/// Construct with the current state.
GarchNSGLContextState();
enum class NullState { nullstate };
GarchNSGLContextState(NullState);
/// Compare for equality.
bool operator==(const GarchNSGLContextState& rhs) const;
/// Returns a hash value for the state.
size_t GetHash() const;
/// Returns \c true if the context state is valid.
bool IsValid() const;
/// Make the context current.
void MakeCurrent();
/// Make no context current.
static void DoneCurrent();
private:
class Detail;
std::shared_ptr<Detail> _detail;
};
// Hide the platform specific type name behind a common name.
typedef GarchNSGLContextState GarchGLPlatformContextState;
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_IMAGING_GARCH_GL_PLATFORM_CONTEXT_DARWIN_H
| 667 |
3,459 | <gh_stars>1000+
/***************************************************************************
* Copyright (C) 2008 by <NAME> *
* <EMAIL> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "rateest.h"
#include <cstdlib>
void RateEst::SumQueue::push(std::ptrdiff_t const samples, usec_t const usecs) {
q_.push_back(std::make_pair(samples, usecs));
samples_ += samples;
usecs_ += usecs;
}
void RateEst::SumQueue::pop() {
std::pair<std::ptrdiff_t, usec_t> const &f = q_.front();
samples_ -= f.first;
usecs_ -= f.second;
q_.pop_front();
}
static usec_t sampleUsecs(std::ptrdiff_t samples, long rate) {
return usec_t((samples * 1000000.0f) / (rate ? rate : 1) + 0.5f);
}
static long limit(long est, long const reference) {
if (est > reference + (reference >> 6))
est = reference + (reference >> 6);
else if (est < reference - (reference >> 6))
est = reference - (reference >> 6);
return est;
}
RateEst::RateEst(long const nominalSampleRate, std::size_t const maxValidFeedPeriodSamples)
: srate_(nominalSampleRate * est_scale)
, reference_(srate_)
, maxPeriod_(sampleUsecs(maxValidFeedPeriodSamples, nominalSampleRate))
, last_(0)
, t_(6000)
, s_(nominalSampleRate * 6)
, st_(s_ * t_)
, t2_(t_ * t_)
{
}
void RateEst::feed(std::ptrdiff_t samplesIn, usec_t const now) {
usec_t usecsIn = now - last_;
if (last_ && usecsIn < maxPeriod_) {
sumq_.push(samplesIn, usecsIn);
while ((usecsIn = sumq_.usecs()) > 100000) {
samplesIn = sumq_.samples();
sumq_.pop();
long const srateIn = long(samplesIn * (1000000.0f * est_scale) / usecsIn);
if (std::abs(srateIn - reference_) < reference_ >> 1) {
s_ += samplesIn - sumq_.samples() ;
t_ += ( usecsIn - sumq_.usecs() ) * 0.001;
st_ += s_ * t_;
t2_ += t_ * t_;
long est = long(st_ * (1000.0 * est_scale) / t2_ + 0.5);
srate_ = limit((srate_ * 31 + est + 16) >> 5, reference_);
if (t_ > 8000) {
s_ *= 3.0 / 4;
t_ *= 3.0 / 4;
st_ *= 9.0 / 16;
t2_ *= 9.0 / 16;
}
}
}
}
last_ = now;
}
| 1,498 |
690 | <filename>pysts/kerasts/__init__.py
"""
The "STS for Keras" toolkit. Contains various Keras blocks that make
putting together and comfortably running neural STS models a breeze.
"""
import numpy as np
def graph_input_anssel(si0, si1, sj0, sj1, se0, se1, y, f0=None, f1=None, s0=None, s1=None, kw=None, akw=None):
""" Produce Keras task specification from vocab-vectorized sentences.
The resulting 'gr' structure is our master dataset container, as well
as something that Keras can recognize as Graph model input.
* si0, si1: Words as indices in vocab; 0 == not in vocab
* sj0, sj1: Words as indices in GloVe; 0 == not in glove
(or in vocab too, which is preferred; never si0>0 and si1>0 at once)
* se0, se1: Words as embeddings (based on sj; 0 for nonzero-si)
* y: Labels
* f0, f1: NLP flags (word class, overlaps, ...)
* s0, s1: Words as strings
* kw, akw: Scalars for auxiliary pair scoring (overlap scores in yodaqa dataset)
To get unique word indices, sum si0+sj1.
"""
gr = {'si0': si0, 'si1': si1,
'sj0': sj0, 'sj1': sj1,
'score': y}
if se0 is not None:
gr['se0'] = se0
gr['se1'] = se1
if f0 is not None:
gr['f0'] = f0
gr['f1'] = f1
if s0 is not None:
# This is useful for non-neural baselines
gr['s0'] = s0
gr['s1'] = s1
if kw is not None:
# yodaqa-specific keyword weight counters
gr['kw'] = kw
gr['akw'] = akw
return gr
def graph_nparray_anssel(gr):
""" Make sure that what should be nparray is nparray. """
for k in ['si0', 'si1', 'sj0', 'sj1', 'se0', 'se1', 'f0', 'f1', 'score', 'kw', 'akw', 'bm25']:
if k in gr:
gr[k] = np.array(gr[k])
return gr
def graph_input_sts(si0, si1, sj0, sj1, y, f0=None, f1=None, s0=None, s1=None):
""" Produce Keras task specification from vocab-vectorized sentences. """
import pysts.loader as loader
gr = {'si0': si0, 'si1': si1,
'sj0': sj0, 'sj1': sj1,
'classes': loader.sts_labels2categorical(y)}
if f0 is not None:
gr['f0'] = f0
gr['f1'] = f1
if s0 is not None:
# This is useful for non-neural baselines
gr['s0'] = s0
gr['s1'] = s1
return gr
def graph_input_slice(gr, sl):
""" Produce a slice of the original graph dataset.
Example: grs = graph_input_slice(gr, slice(500, 1000)) """
grs = dict()
for k, v in gr.items():
grs[k] = v[sl]
return grs
def graph_input_prune(gr, ypred, N, skip_oneclass=False):
""" Given a gr and a given scoring, keep only top N s1 for each s0,
and stash the others away to _x-suffixed keys (for potential recovery). """
def prune_filter(ypred, N):
""" yield (index, passed) tuples """
ys = sorted(enumerate(ypred), key=lambda yy: yy[1], reverse=True)
i = 0
for n, y in ys:
yield n, (i < N)
i += 1
# Go through (s0, s1), keeping track of the beginning of the current
# s0 block, and appending pruned versions
i = 0
grp = dict([(k, []) for k in gr.keys()] + [(k+'_x', []) for k in gr.keys()])
for j in range(len(gr['si0']) + 1):
if j < len(gr['si0']) and (j == 0 or np.all(gr['si0'][j]+gr['sj0'][j] == gr['si0'][j-1]+gr['sj0'][j-1])):
# within same-s0 block, carry on
continue
# block boundary
# possibly check if we have both classes picked (for training)
if skip_oneclass:
n_picked = 0
for n, passed in prune_filter(ypred[i:j], N):
if not passed:
break
n_picked += gr['score'][i + n] > 0
if n_picked == 0:
# only false; tough luck, prune everything for this s0
for k in gr.keys():
grp[k+'_x'] += list(gr[k][i:j])
i = j
continue
# append pruned subset
for n, passed in prune_filter(ypred[i:j], N):
for k in gr.keys():
if passed:
grp[k].append(gr[k][i + n])
else:
grp[k+'_x'].append(gr[k][i + n])
i = j
return graph_nparray_anssel(grp)
def graph_input_unprune(gro, grp, ypred, xval):
""" Reconstruct original graph gro from a pruned graph grp,
with predictions set to always False for the filtered out samples.
(xval denotes how the False is represented) """
if 'score_x' not in grp:
return grp, ypred # not actually pruned
gru = dict([(k, list(grp[k])) for k in gro.keys()])
# XXX: this will generate non-continuous s0 blocks,
# hopefully okay for all ev tools
for k in gro.keys():
gru[k] += grp[k+'_x']
ypred = list(ypred)
ypred += [xval for i in grp['score_x']]
ypred = np.array(ypred)
return graph_nparray_anssel(gru), ypred
| 2,351 |
354 | /*-------------------------------------------------------------------------
* drawElements Internal Test Module
* ---------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Seed builder tests.
*//*--------------------------------------------------------------------*/
#include "ditSeedBuilderTests.hpp"
#include "tcuTestLog.hpp"
#include "tcuVector.hpp"
#include "tcuSeedBuilder.hpp"
using tcu::IVec2;
using tcu::IVec3;
using tcu::IVec4;
using tcu::TestLog;
namespace dit
{
namespace
{
template<class T>
class SeedBuilderTest : public tcu::TestCase
{
public:
SeedBuilderTest (tcu::TestContext& testCtx, const T& value, deUint32 seed, const char* name, const char* description)
: tcu::TestCase (testCtx, name, description)
, m_value (value)
, m_seed (seed)
{
}
IterateResult iterate (void)
{
TestLog& log = m_testCtx.getLog();
tcu::SeedBuilder builder;
builder << m_value;
log << TestLog::Message << "Value: " << m_value << TestLog::EndMessage;
log << TestLog::Message << "Expected seed: " << m_seed << TestLog::EndMessage;
log << TestLog::Message << "Got seed: " << builder.get() << TestLog::EndMessage;
if (builder.get() != m_seed)
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Got invalid seed");
else
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");
return STOP;
}
private:
T m_value;
deUint32 m_seed;
};
class SeedBuilderMultipleValuesTest : public tcu::TestCase
{
public:
SeedBuilderMultipleValuesTest (tcu::TestContext& testCtx)
: tcu::TestCase(testCtx, "multiple_values", "Test that multiple values all change the seed.")
{
}
IterateResult iterate (void)
{
TestLog& log = m_testCtx.getLog();
const deUint32 a = 77740203u;
const deUint32 b = 3830824200u;
tcu::SeedBuilder builderA;
tcu::SeedBuilder builderB;
tcu::SeedBuilder builderAB;
builderA << a;
builderB << b;
builderAB << a << b;
log << TestLog::Message << "Value a: " << a << ", Seed a: " << builderA.get() << TestLog::EndMessage;
log << TestLog::Message << "Value b: " << b << ", Seed b: " << builderB.get() << TestLog::EndMessage;
log << TestLog::Message << "Seed ab: " << builderAB.get() << TestLog::EndMessage;
if (builderA.get() == builderAB.get())
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Seed seems to only depends on first value.");
else if (builderB.get() == builderAB.get())
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Seed seems to only depends on second value.");
else
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");
return STOP;
}
};
class SeedBuilderTests : public tcu::TestCaseGroup
{
public:
SeedBuilderTests (tcu::TestContext& testCtx)
: tcu::TestCaseGroup(testCtx, "seed_builder", "Seed builder tests.")
{
}
void init (void)
{
addChild(new SeedBuilderTest<bool>(m_testCtx, true, 132088003u, "bool_true", "Seed from boolean true."));
addChild(new SeedBuilderTest<bool>(m_testCtx, false, 50600761u, "bool_false", "Seed from boolean false."));
addChild(new SeedBuilderTest<deInt8>(m_testCtx, 0, 62533730u, "int8_zero", "Seed from int8 zero."));
addChild(new SeedBuilderTest<deInt8>(m_testCtx, 1, 93914869u, "int8_one", "Seed from int8 one."));
addChild(new SeedBuilderTest<deInt8>(m_testCtx, -1, 115002165u, "int8_minus_one", "Seed from int8 minus one."));
addChild(new SeedBuilderTest<deInt16>(m_testCtx, 0, 133071403u, "int16_zero", "Seed from int16 zero."));
addChild(new SeedBuilderTest<deInt16>(m_testCtx, 1, 57421642u, "int16_one", "Seed from int16 one."));
addChild(new SeedBuilderTest<deInt16>(m_testCtx, -1, 74389771u, "int16_minus_one", "Seed from int16 minus one."));
addChild(new SeedBuilderTest<deInt32>(m_testCtx, 0, 75951701u, "int32_zero", "Seed from int32 zero."));
addChild(new SeedBuilderTest<deInt32>(m_testCtx, 1, 95780822u, "int32_one", "Seed from int32 one."));
addChild(new SeedBuilderTest<deInt32>(m_testCtx, -1, 73949483u, "int32_minus_one", "Seed from int32 minus one."));
addChild(new SeedBuilderTest<deUint8>(m_testCtx, 0, 3623298u, "uint8_zero", "Seed from uint8 zero."));
addChild(new SeedBuilderTest<deUint8>(m_testCtx, 1, 102006549u, "uint8_one", "Seed from uint8 one."));
addChild(new SeedBuilderTest<deUint8>(m_testCtx, 255, 89633493u, "uint8_max", "Seed from uint8 max."));
addChild(new SeedBuilderTest<deUint16>(m_testCtx, 0, 78413740u, "uint16_zero", "Seed from uint16 zero."));
addChild(new SeedBuilderTest<deUint16>(m_testCtx, 1, 3068621u, "uint16_one", "Seed from uint16 one."));
addChild(new SeedBuilderTest<deUint16>(m_testCtx, 65535, 120448140u, "uint16_max", "Seed from uint16 max."));
addChild(new SeedBuilderTest<deUint32>(m_testCtx, 0u, 41006057u, "uint32_zero", "Seed from uint32 zero."));
addChild(new SeedBuilderTest<deUint32>(m_testCtx, 1u, 54665834u, "uint32_one", "Seed from uint32 one."));
addChild(new SeedBuilderTest<deUint32>(m_testCtx, 4294967295u, 43990167u, "uint32_max", "Seed from uint32 max."));
addChild(new SeedBuilderTest<float>(m_testCtx, 0.0f, 41165361u, "float_zero", "Seed from float zero."));
addChild(new SeedBuilderTest<float>(m_testCtx, -0.0f, 112541574u, "float_negative_zero", "Seed from float negative zero."));
addChild(new SeedBuilderTest<float>(m_testCtx, 1.0f, 44355905u, "float_one", "Seed from float one."));
addChild(new SeedBuilderTest<float>(m_testCtx, -1.0f, 107334902u, "float_negative_one", "Seed from float negative one."));
addChild(new SeedBuilderTest<double>(m_testCtx, 0.0, 133470681u, "double_zero", "Seed from double zero."));
addChild(new SeedBuilderTest<double>(m_testCtx, -0.0, 53838958u, "double_negative_zero", "Seed from double negative zero."));
addChild(new SeedBuilderTest<double>(m_testCtx, 1.0, 16975104u, "double_one", "Seed from double one."));
addChild(new SeedBuilderTest<double>(m_testCtx, -1.0, 96606391u, "double_negative_one", "Seed from double negative one."));
addChild(new SeedBuilderTest<IVec2>(m_testCtx, IVec2(0), 1111532u, "ivec2_zero", "Seed from zero vector."));
addChild(new SeedBuilderTest<IVec3>(m_testCtx, IVec3(0), 22277704u, "ivec3_zero", "Seed from zero vector."));
addChild(new SeedBuilderTest<IVec4>(m_testCtx, IVec4(0), 73989201u, "ivec4_zero", "Seed from zero vector."));
addChild(new SeedBuilderTest<IVec2>(m_testCtx, IVec2(1), 12819708u, "ivec2_one", "Seed from one vector."));
addChild(new SeedBuilderTest<IVec3>(m_testCtx, IVec3(1), 134047100u, "ivec3_one", "Seed from one vector."));
addChild(new SeedBuilderTest<IVec4>(m_testCtx, IVec4(1), 90609878u, "ivec4_one", "Seed from one vector."));
addChild(new SeedBuilderTest<IVec4>(m_testCtx, IVec4(1, 2, 3, 4), 6202236u, "ivec4_1_2_3_4", "Seed from (1, 2, 3, 4) vector."));
addChild(new SeedBuilderTest<IVec4>(m_testCtx, IVec4(4, 3, 2, 1), 26964618u, "ivec4_4_3_2_1", "Seed from (4, 3, 2, 1) vector."));
addChild(new SeedBuilderMultipleValuesTest(m_testCtx));
}
};
} // anonymous
tcu::TestCaseGroup* createSeedBuilderTests (tcu::TestContext& testCtx)
{
return new SeedBuilderTests(testCtx);
}
} // dit
| 2,998 |
3,710 | /*****************************************************************************
Copyright (c) 2011, Lab of Parallel Software and Computational Science,ICSAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. Neither the name of the ISCAS nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********************************************************************************/
#ifndef COMMON_UTEST_H_
#define COMMON_UTEST_H_
#include <CUnit/CUnit.h>
#include <common.h>
#define CHECK_EPS 0.00002
//Testcase list
void test_drot_inc_0(void);
void test_srot_inc_0(void);
void test_zdrot_inc_0(void);
void test_csrot_inc_0(void);
void test_dswap_inc_0(void);
void test_zswap_inc_0(void);
void test_sswap_inc_0(void);
void test_cswap_inc_0(void);
void test_daxpy_inc_0(void);
void test_zaxpy_inc_0(void);
void test_saxpy_inc_0(void);
void test_caxpy_inc_0(void);
void test_zdotu_n_1(void);
void test_zdotu_offset_1(void);
void test_drotmg(void);
void test_dsdot_n_1(void);
void test_samax(void);
#endif
| 763 |
310 | <filename>gear/hardware/a/a119-v3.json
{
"name": "<NAME>",
"description": "A car dash camera.",
"url": "https://www.viofo.com/en/dash-cam/143-a119-v3-with-gps-2k-25601600p-30fps-quad-hd-car-dash-cam.html"
}
| 100 |
319 | <filename>hadoop/tools/HadoopTwitterTokenTool/src/main/java/org/openimaj/hadoop/tools/twitter/HadoopLZOTest.java<gh_stars>100-1000
/**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.hadoop.tools.twitter;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.openimaj.hadoop.tools.HadoopToolsUtil;
import org.openimaj.text.nlp.TweetTokeniser;
import org.openimaj.text.nlp.TweetTokeniserException;
import org.openimaj.twitter.GeneralJSONTwitter;
import org.openimaj.twitter.USMFStatus;
/**
* @author <NAME> (<EMAIL>)
*
*/
public class HadoopLZOTest extends Configured implements Tool {
enum CounterEnum {
CHEESE, FLEES;
}
public static class CounterMapper extends Mapper<LongWritable, Text, LongWritable, Text> {
public CounterMapper() {
// TODO Auto-generated constructor stub
}
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, LongWritable, Text>.Context context)
throws java.io.IOException, InterruptedException
{
final USMFStatus status = new USMFStatus(GeneralJSONTwitter.class);
status.fillFromString(value.toString());
context.getCounter(CounterEnum.CHEESE).increment(10);
context.getCounter(CounterEnum.FLEES).increment(20);
if (status.isInvalid())
return;
try {
final TweetTokeniser tok = new TweetTokeniser(status.text);
context.write(key, new Text(StringUtils.join(tok.getTokens(), ",")));
} catch (final TweetTokeniserException e) {
}
}
}
public static class CounterReducer extends Reducer<LongWritable, Text, NullWritable, Text> {
public CounterReducer() {
// TODO Auto-generated constructor stub
}
@Override
protected void reduce(LongWritable key, Iterable<Text> values,
Reducer<LongWritable, Text, NullWritable, Text>.Context context)
{
final Counter cheeseCounter = context.getCounter(CounterEnum.CHEESE);
final Counter fleesCounter = context.getCounter(CounterEnum.FLEES);
System.out.println(cheeseCounter.getName() + ": " + cheeseCounter.getValue());
System.out.println(fleesCounter.getName() + ": " + fleesCounter.getValue());
for (final Text text : values) {
try {
context.write(NullWritable.get(), text);
} catch (final IOException e) {
} catch (final InterruptedException e) {
}
}
}
}
@SuppressWarnings("unchecked")
@Override
public int run(String[] args) throws Exception {
Class<? extends InputFormat<?, ?>> lzoClass = null;
try {
lzoClass = (Class<? extends InputFormat<?, ?>>) Class.forName("com.hadoop.mapreduce.LzoTextInputFormat");
} catch (final ClassNotFoundException nfe) {
System.err.println("LZO not installed; skipping");
return -1;
}
final Path[] paths = new Path[] { new Path(args[0]) };
final Path out = new Path(args[1]);
HadoopToolsUtil.validateOutput(args[1], true);
final Job job = new Job(this.getConf());
job.setInputFormatClass(lzoClass);
job.setOutputKeyClass(LongWritable.class);
job.setOutputValueClass(Text.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setJarByClass(this.getClass());
lzoClass.getMethod("setInputPaths", Path[].class).invoke(null, (Object[]) paths);
TextOutputFormat.setOutputPath(job, out);
job.setMapperClass(CounterMapper.class);
job.setReducerClass(CounterReducer.class);
long start, end;
start = System.currentTimeMillis();
job.waitForCompletion(true);
end = System.currentTimeMillis();
System.out.println("Took: " + (end - start) + "ms");
return 0;
}
}
| 1,891 |
1,604 | <filename>core/src/test/java/org/bouncycastle/crypto/test/CSHAKETest.java<gh_stars>1000+
package org.bouncycastle.crypto.test;
import org.bouncycastle.crypto.digests.CSHAKEDigest;
import org.bouncycastle.crypto.digests.SHAKEDigest;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.test.SimpleTest;
/**
* CSHAKE test vectors from:
*
* https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/cSHAKE_samples.pdf
*/
public class CSHAKETest
extends SimpleTest
{
public String getName()
{
return "CSHAKE";
}
public void performTest()
throws Exception
{
CSHAKEDigest cshake = new CSHAKEDigest(128, new byte[0], Strings.toByteArray("Email Signature"));
cshake.update(Hex.decode("00010203"), 0, 4);
byte[] res = new byte[32];
cshake.doOutput(res, 0, res.length);
isTrue("oops!", Arrays.areEqual(Hex.decode("c1c36925b6409a04f1b504fcbca9d82b4017277cb5ed2b2065fc1d3814d5aaf5"), res));
cshake = new CSHAKEDigest(128, new byte[0], Strings.toByteArray("Email Signature"));
cshake.update(Hex.decode(
"000102030405060708090A0B0C0D0E0F" +
"101112131415161718191A1B1C1D1E1F" +
"202122232425262728292A2B2C2D2E2F" +
"303132333435363738393A3B3C3D3E3F" +
"404142434445464748494A4B4C4D4E4F" +
"505152535455565758595A5B5C5D5E5F" +
"606162636465666768696A6B6C6D6E6F" +
"707172737475767778797A7B7C7D7E7F" +
"808182838485868788898A8B8C8D8E8F" +
"909192939495969798999A9B9C9D9E9F" +
"A0A1A2A3A4A5A6A7A8A9AAABACADAEAF" +
"B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF" +
"C0C1C2C3C4C5C6C7"), 0, 1600 / 8);
res = new byte[32];
cshake.doOutput(res, 0, res.length);
isTrue(Arrays.areEqual(Hex.decode("C5221D50E4F822D96A2E8881A961420F294B7B24FE3D2094BAED2C6524CC166B "), res));
cshake = new CSHAKEDigest(256, new byte[0], Strings.toByteArray("Email Signature"));
cshake.update(Hex.decode("00010203"), 0, 4);
res = new byte[64];
cshake.doOutput(res, 0, res.length);
isTrue(Arrays.areEqual(Hex.decode(
"D008828E2B80AC9D2218FFEE1D070C48"+
"B8E4C87BFF32C9699D5B6896EEE0EDD1"+
"64020E2BE0560858D9C00C037E34A969"+
"37C561A74C412BB4C746469527281C8C"),res));
cshake = new CSHAKEDigest(256, new byte[0], Strings.toByteArray("Email Signature"));
cshake.update(Hex.decode(
"000102030405060708090A0B0C0D0E0F" +
"101112131415161718191A1B1C1D1E1F" +
"202122232425262728292A2B2C2D2E2F" +
"303132333435363738393A3B3C3D3E3F" +
"404142434445464748494A4B4C4D4E4F" +
"505152535455565758595A5B5C5D5E5F" +
"606162636465666768696A6B6C6D6E6F" +
"707172737475767778797A7B7C7D7E7F" +
"808182838485868788898A8B8C8D8E8F" +
"909192939495969798999A9B9C9D9E9F" +
"A0A1A2A3A4A5A6A7A8A9AAABACADAEAF" +
"B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF" +
"C0C1C2C3C4C5C6C7"), 0, 1600 / 8);
res = new byte[64];
cshake.doOutput(res, 0, res.length);
isTrue(Arrays.areEqual(Hex.decode(
"07DC27B11E51FBAC75BC7B3C1D983E8B"+
"4B85FB1DEFAF218912AC864302730917"+
"27F42B17ED1DF63E8EC118F04B23633C"+
"1DFB1574C8FB55CB45DA8E25AFB092BB"), res));
doFinalTest();
longBlockTest();
checkZeroPadZ();
checkSHAKE(128, new CSHAKEDigest(128, new byte[0], new byte[0]), Hex.decode("eeaabeef"));
checkSHAKE(256, new CSHAKEDigest(256, new byte[0], null), Hex.decode("eeaabeef"));
checkSHAKE(128, new CSHAKEDigest(128, null, new byte[0]), Hex.decode("eeaabeef"));
checkSHAKE(128, new CSHAKEDigest(128, null, null), Hex.decode("eeaabeef"));
checkSHAKE(256, new CSHAKEDigest(256, null, null), Hex.decode("eeaabeef"));
}
private void checkZeroPadZ()
{
byte[] buf = new byte[20];
CSHAKEDigest cshake1 = new CSHAKEDigest(256, new byte[0], new byte[265]);
cshake1.doOutput(buf, 0, buf.length);
isTrue(areEqual(Hex.decode("6e393540387004f087c4180db008acf6825190cf"), buf));
CSHAKEDigest cshake2 = new CSHAKEDigest(128, new byte[0], new byte[329]);
cshake2.doOutput(buf, 0, buf.length);
isTrue(areEqual(Hex.decode("309bd7c285fcf8b839c9686b2cc00bd578947bee"), buf));
cshake2 = new CSHAKEDigest(128, new byte[29], new byte[300]);
cshake2.doOutput(buf, 0, buf.length);
isTrue(areEqual(Hex.decode("ff6aafd83b8d22fc3e2e9b9948b581967ed9c5e7"), buf));
}
private void doFinalTest()
{
CSHAKEDigest cshake = new CSHAKEDigest(128, new byte[0], Strings.toByteArray("Email Signature"));
cshake.update(Hex.decode("00010203"), 0, 4);
byte[] res = new byte[32];
cshake.doOutput(res, 0, res.length);
isTrue(Arrays.areEqual(Hex.decode("c1c36925b6409a04f1b504fcbca9d82b4017277cb5ed2b2065fc1d3814d5aaf5"), res));
cshake.doOutput(res, 0, res.length);
isTrue(!Arrays.areEqual(Hex.decode("c1c36925b6409a04f1b504fcbca9d82b4017277cb5ed2b2065fc1d3814d5aaf5"), res));
cshake.doFinal(res, 0, res.length);
cshake.update(Hex.decode("00010203"), 0, 4);
cshake.doFinal(res, 0, res.length);
isTrue(Arrays.areEqual(Hex.decode("<KEY>"), res));
cshake.update(Hex.decode("00010203"), 0, 4);
cshake.doOutput(res, 0, res.length);
isTrue(Arrays.areEqual(Hex.decode("<KEY>"), res));
cshake.doFinal(res, 0, res.length);
isTrue(Arrays.areEqual(Hex.decode("9cbce830079c452abdeb875366a49ebfe75b89ef17396e34898e904830b0e136"), res));
}
private void longBlockTest()
{
byte[] data = new byte[16000];
byte[] res = new byte[32];
for (int i = 0; i != data.length; i++)
{
data[i] = (byte)i;
}
byte[] hex0123 = Hex.decodeStrict("00010203");
for (int i = 10000; i != data.length; i++)
{
CSHAKEDigest cshake = new CSHAKEDigest(128, new byte[0], Arrays.copyOfRange(data, 0, i));
cshake.update(hex0123, 0, 4);
cshake.doFinal(res, 0, 16);
}
CSHAKEDigest cshake = new CSHAKEDigest(256, new byte[0], new byte[200]);
cshake.update(data, 0, 200);
cshake.doFinal(res, 0, 32);
isTrue(Arrays.areEqual(Hex.decode("4a899b5be460d85a9789215bc17f88b8f8ac049bd3b519f561e7b5d3870dafa3"), res));
}
private void checkSHAKE(int bitSize, CSHAKEDigest cshake, byte[] msg)
{
SHAKEDigest ref = new SHAKEDigest(bitSize);
ref.update(msg, 0, msg.length);
cshake.update(msg, 0, msg.length);
byte[] res1 = new byte[32];
byte[] res2 = new byte[32];
ref.doFinal(res1, 0, res1.length);
cshake.doFinal(res2, 0, res2.length);
isTrue(Arrays.areEqual(res1, res2));
}
public static void main(
String[] args)
{
runTest(new CSHAKETest());
}
}
| 4,077 |
890 | import json
from flask import g, current_app
from flask_restful import marshal, abort, reqparse, Resource
from app import db
from app.constants import API_ENVELOPE
from app.models import Preference
from app.apiv2.decorators import verify_org_location_role_schedule, \
permission_location_manager_or_self, schedule_preference_modifiable, \
permission_location_manager
from app.apiv2.marshal import preference_fields
from app.apiv2.helpers import verify_days_of_week_struct
class PreferenceApi(Resource):
@verify_org_location_role_schedule
@permission_location_manager_or_self
def get(self, org_id, location_id, role_id, schedule_id, user_id):
p = Preference.query.filter(
Preference.user_id == user_id,
Preference.schedule_id == schedule_id).first()
if p is None:
abort(404)
return {API_ENVELOPE: marshal(p, preference_fields)}
@verify_org_location_role_schedule
@permission_location_manager_or_self
@schedule_preference_modifiable
def patch(self, org_id, location_id, role_id, schedule_id, user_id):
parser = reqparse.RequestParser()
parser.add_argument("preference", type=str, required=True)
changes = parser.parse_args(strict=True)
# Filter out null values
changes = dict((k, v) for k, v in changes.iteritems() if v is not None)
p = Preference.query.filter(
Preference.user_id == user_id,
Preference.schedule_id == schedule_id).first()
if p is None:
abort(404)
if changes.get("preference") is not None:
try:
preference = json.loads(changes.get("preference"))
except:
return {"message": "Unable to parse preference json body"}, 400
if preference is None:
return {"message": "Unable to parse preference json body"}, 400
if not verify_days_of_week_struct(preference, True):
return {"message": "preference is improperly formatted"}, 400
changes["preference"] = preference
for change, value in changes.iteritems():
if change == "preference":
value = json.dumps(value)
if value is not None:
try:
setattr(p, change, value)
db.session.commit()
except Exception as exception:
db.session.rollback()
current_app.logger.exception(str(exception))
abort(400)
g.current_user.track_event("updated_preference")
return changes
@verify_org_location_role_schedule
@permission_location_manager
@schedule_preference_modifiable
def delete(self, org_id, location_id, role_id, schedule_id, user_id):
p = Preference.query.filter(
Preference.user_id == user_id,
Preference.schedule_id == schedule_id).first()
if p is None:
abort(404)
try:
db.session.delete(p)
db.session.commit()
except Exception as exception:
db.session.rollback()
current_app.logger.error(str(exception))
abort(400)
g.current_user.track_event("deleted_preference")
return {}, 204
| 1,456 |
1,428 | <reponame>PushpneetSingh/Hello-world
public class HelloFromPoland {
public static void main(String[] args) {
// Prints "Hello from Poland!" to the terminal window.
System.out.println("Hello from Poland!");
}
}
| 86 |
777 | <reponame>google-ar/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 "chrome/browser/ui/app_list/arc/arc_default_app_list.h"
#include "base/files/file_enumerator.h"
#include "base/json/json_file_value_serializer.h"
#include "base/path_service.h"
#include "base/task_runner_util.h"
#include "chrome/browser/chromeos/arc/arc_support_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/extension_system.h"
namespace {
const char kActivity[] = "activity";
const char kAppPath[] = "app_path";
const char kName[] = "name";
const char kOem[] = "oem";
const char kPackageName[] = "package_name";
// Sub-directory wher Arc apps forward declarations are stored.
const base::FilePath::CharType kArcDirectory[] = FILE_PATH_LITERAL("arc");
const base::FilePath::CharType kArcTestDirectory[] =
FILE_PATH_LITERAL("arc_default_apps");
bool use_test_apps_directory = false;
std::unique_ptr<ArcDefaultAppList::AppInfoMap>
ReadAppsFromFileThread() {
DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
std::unique_ptr<ArcDefaultAppList::AppInfoMap> apps(
new ArcDefaultAppList::AppInfoMap);
base::FilePath base_path;
if (!use_test_apps_directory) {
if (!base::PathService::Get(chrome::DIR_STANDALONE_EXTERNAL_EXTENSIONS,
&base_path))
return apps;
base_path = base_path.Append(kArcDirectory);
} else {
if (!base::PathService::Get(chrome::DIR_TEST_DATA, &base_path))
return apps;
base_path = base_path.AppendASCII(kArcTestDirectory);
}
base::FilePath::StringType extension(".json");
base::FileEnumerator json_files(
base_path,
false, // Recursive.
base::FileEnumerator::FILES);
for (base::FilePath file = json_files.Next(); !file.empty();
file = json_files.Next()) {
if (file.MatchesExtension(extension)) {
JSONFileValueDeserializer deserializer(file);
std::string error_msg;
std::unique_ptr<base::Value> app_info =
deserializer.Deserialize(nullptr, &error_msg);
if (!app_info) {
VLOG(2) << "Unable to deserialize json data: " << error_msg
<< " in file " << file.value() << ".";
continue;
}
std::unique_ptr<base::DictionaryValue> app_info_dictionary =
base::DictionaryValue::From(std::move(app_info));
CHECK(app_info_dictionary);
std::string name;
std::string package_name;
std::string activity;
std::string app_path;
bool oem = false;
app_info_dictionary->GetString(kName, &name);
app_info_dictionary->GetString(kPackageName, &package_name);
app_info_dictionary->GetString(kActivity, &activity);
app_info_dictionary->GetString(kAppPath, &app_path);
app_info_dictionary->GetBoolean(kOem, &oem);
if (name.empty() ||
package_name.empty() ||
activity.empty() ||
app_path.empty()) {
VLOG(2) << "Arc app declaration is incomplete in file "
<< file.value() << ".";
continue;
}
const std::string app_id = ArcAppListPrefs::GetAppId(
package_name, activity);
std::unique_ptr<ArcDefaultAppList::AppInfo> app(
new ArcDefaultAppList::AppInfo(name,
package_name,
activity,
oem,
base_path.Append(app_path)));
apps.get()->insert(
std::pair<std::string,
std::unique_ptr<ArcDefaultAppList::AppInfo>>(
app_id, std::move(app)));
} else {
DVLOG(1) << "Not considering: " << file.LossyDisplayName()
<< " (does not have a .json extension)";
}
}
return apps;
}
} // namespace
// static
void ArcDefaultAppList::UseTestAppsDirectory() {
use_test_apps_directory = true;
}
ArcDefaultAppList::ArcDefaultAppList(Delegate* delegate,
content::BrowserContext* context)
: delegate_(delegate), context_(context), weak_ptr_factory_(this) {
CHECK(delegate_);
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
// Once ready OnAppsReady is called.
base::PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(), FROM_HERE,
base::Bind(&ReadAppsFromFileThread),
base::Bind(&ArcDefaultAppList::OnAppsReady,
weak_ptr_factory_.GetWeakPtr()));
}
ArcDefaultAppList::~ArcDefaultAppList() {}
void ArcDefaultAppList::OnAppsReady(std::unique_ptr<AppInfoMap> apps) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
apps_.swap(*apps.get());
// Register Play Store as default app. Some services and ArcSupportHost may
// not be available in tests.
ExtensionService* service =
extensions::ExtensionSystem::Get(context_)->extension_service();
const extensions::Extension* arc_host = service ?
service->GetInstalledExtension(ArcSupportHost::kHostAppId) : nullptr;
if (arc_host) {
std::unique_ptr<ArcDefaultAppList::AppInfo> play_store_app(
new ArcDefaultAppList::AppInfo(arc_host->name(),
arc::kPlayStorePackage,
arc::kPlayStoreActivity,
false /* oem */,
base::FilePath() /* app_path */));
apps_.insert(
std::pair<std::string,
std::unique_ptr<ArcDefaultAppList::AppInfo>>(
arc::kPlayStoreAppId, std::move(play_store_app)));
}
// Initially consider packages are installed.
for (const auto& app : apps_)
packages_[app.second->package_name] = false;
delegate_->OnDefaultAppsReady();
}
const ArcDefaultAppList::AppInfo* ArcDefaultAppList::GetApp(
const std::string& app_id) const {
if (hidden_)
return nullptr;
const auto it = apps_.find(app_id);
if (it == apps_.end())
return nullptr;
// Check if its package was uninstalled.
const auto it_package = packages_.find(it->second->package_name);
DCHECK(it_package != packages_.end());
if (it_package->second)
return nullptr;
return it->second.get();
}
bool ArcDefaultAppList::HasApp(const std::string& app_id) const {
return GetApp(app_id) != nullptr;
}
bool ArcDefaultAppList::HasPackage(const std::string& package_name) const {
return packages_.count(package_name);
}
void ArcDefaultAppList::MaybeMarkPackageUninstalled(
const std::string& package_name, bool uninstalled) {
auto it = packages_.find(package_name);
if (it == packages_.end())
return;
it->second = uninstalled;
}
std::unordered_set<std::string> ArcDefaultAppList::GetActivePackages() const {
std::unordered_set<std::string> result;
for (const auto& package_info : packages_) {
if (!package_info.second)
result.insert(package_info.first);
}
return result;
}
ArcDefaultAppList::AppInfo::AppInfo(const std::string& name,
const std::string& package_name,
const std::string& activity,
bool oem,
const base::FilePath app_path)
: name(name),
package_name(package_name),
activity(activity),
oem(oem),
app_path(app_path) {}
ArcDefaultAppList::AppInfo::~AppInfo() {}
| 3,272 |
2,055 | <reponame>DarianLiu/MVVMLight-master
package com.kelin.mvvmlight.bindingadapter.image;
import android.databinding.BindingAdapter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.DrawableRes;
import android.text.TextUtils;
import android.widget.ImageView;
import com.facebook.common.executors.UiThreadImmediateExecutorService;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.kelin.mvvmlight.command.ReplyCommand;
/**
* Created by kelin on 16-3-24.
*/
public final class ViewBindingAdapter {
@BindingAdapter({"uri"})
public static void setImageUri(SimpleDraweeView simpleDraweeView, String uri) {
if (!TextUtils.isEmpty(uri)) {
simpleDraweeView.setImageURI(Uri.parse(uri));
}
}
@BindingAdapter(value = {"uri", "placeholderImageRes", "request_width", "request_height", "onSuccessCommand", "onFailureCommand"}, requireAll = false)
public static void loadImage(final ImageView imageView, String uri,
@DrawableRes int placeholderImageRes,
int width, int height,
final ReplyCommand<Bitmap> onSuccessCommand,
final ReplyCommand<DataSource<CloseableReference<CloseableImage>>> onFailureCommand) {
imageView.setImageResource(placeholderImageRes);
if (!TextUtils.isEmpty(uri)) {
ImagePipeline imagePipeline = Fresco.getImagePipeline();
ImageRequestBuilder builder = ImageRequestBuilder.newBuilderWithSource(Uri.parse(uri));
if (width > 0 && height > 0) {
builder.setResizeOptions(new ResizeOptions(width, height));
}
ImageRequest request = builder.build();
DataSource<CloseableReference<CloseableImage>>
dataSource = imagePipeline.fetchDecodedImage(request, imageView.getContext());
dataSource.subscribe(new BaseBitmapDataSubscriber() {
@Override
protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
if (onFailureCommand != null) {
onFailureCommand.execute(dataSource);
}
}
@Override
protected void onNewResultImpl(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
if (onSuccessCommand != null) {
onSuccessCommand.execute(bitmap);
}
}
}, UiThreadImmediateExecutorService.getInstance());
}
}
}
| 1,352 |
1,125 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket.composite;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public interface CompositeAggregation extends MultiBucketsAggregation {
interface Bucket extends MultiBucketsAggregation.Bucket {
Map<String, Object> getKey();
}
@Override
List<? extends CompositeAggregation.Bucket> getBuckets();
/**
* Returns the last key in this aggregation. It can be used to retrieve the buckets that are after these values.
* See {@link CompositeAggregationBuilder#aggregateAfter}.
*/
Map<String, Object> afterKey();
static XContentBuilder bucketToXContent(CompositeAggregation.Bucket bucket,
XContentBuilder builder, Params params) throws IOException {
builder.startObject();
buildCompositeMap(CommonFields.KEY.getPreferredName(), bucket.getKey(), builder);
builder.field(CommonFields.DOC_COUNT.getPreferredName(), bucket.getDocCount());
bucket.getAggregations().toXContentInternal(builder, params);
builder.endObject();
return builder;
}
static XContentBuilder toXContentFragment(CompositeAggregation aggregation, XContentBuilder builder, Params params) throws IOException {
if (aggregation.afterKey() != null) {
buildCompositeMap("after_key", aggregation.afterKey(), builder);
}
builder.startArray(CommonFields.BUCKETS.getPreferredName());
for (CompositeAggregation.Bucket bucket : aggregation.getBuckets()) {
bucketToXContent(bucket, builder, params);
}
builder.endArray();
return builder;
}
static void buildCompositeMap(String fieldName, Map<String, Object> composite, XContentBuilder builder) throws IOException {
builder.startObject(fieldName);
for (Map.Entry<String, Object> entry : composite.entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
}
}
| 975 |
561 | <reponame>leminhnguyen/NATSpeech
# rnnoise.py, requirements: ffmpeg, sox, rnnoise, python
import os
import subprocess
INSTALL_STR = """
RNNoise library not found. Please install RNNoise (https://github.com/xiph/rnnoise) to $REPO/rnnoise:
sudo apt-get install -y autoconf automake libtool ffmpeg sox
git clone https://github.com/xiph/rnnoise.git
rm -rf rnnoise/.git
cd rnnoise
./autogen.sh && ./configure && make
cd ..
"""
def rnnoise(filename, out_fn=None, verbose=False, out_sample_rate=22050):
assert os.path.exists('./rnnoise/examples/rnnoise_demo'), INSTALL_STR
if out_fn is None:
out_fn = f"{filename[:-4]}.denoised.wav"
out_48k_fn = f"{out_fn}.48000.wav"
tmp0_fn = f"{out_fn}.0.wav"
tmp1_fn = f"{out_fn}.1.wav"
tmp2_fn = f"{out_fn}.2.raw"
tmp3_fn = f"{out_fn}.3.raw"
if verbose:
print("Pre-processing audio...") # wav to pcm raw
subprocess.check_call(
f'sox "{filename}" -G -r48000 "{tmp0_fn}"', shell=True, stdin=subprocess.PIPE) # convert to raw
subprocess.check_call(
f'sox -v 0.95 "{tmp0_fn}" "{tmp1_fn}"', shell=True, stdin=subprocess.PIPE) # convert to raw
subprocess.check_call(
f'ffmpeg -y -i "{tmp1_fn}" -loglevel quiet -f s16le -ac 1 -ar 48000 "{tmp2_fn}"',
shell=True, stdin=subprocess.PIPE) # convert to raw
if verbose:
print("Applying rnnoise algorithm to audio...") # rnnoise
subprocess.check_call(
f'./rnnoise/examples/rnnoise_demo "{tmp2_fn}" "{tmp3_fn}"', shell=True)
if verbose:
print("Post-processing audio...") # pcm raw to wav
if filename == out_fn:
subprocess.check_call(f'rm -f "{out_fn}"', shell=True)
subprocess.check_call(
f'sox -t raw -r 48000 -b 16 -e signed-integer -c 1 "{tmp3_fn}" "{out_48k_fn}"', shell=True)
subprocess.check_call(f'sox "{out_48k_fn}" -G -r{out_sample_rate} "{out_fn}"', shell=True)
subprocess.check_call(f'rm -f "{tmp0_fn}" "{tmp1_fn}" "{tmp2_fn}" "{tmp3_fn}" "{out_48k_fn}"', shell=True)
if verbose:
print("Audio-filtering completed!")
| 935 |
7,158 | <filename>modules/surface_matching/samples/ppf_load_match.py
import cv2 as cv
N = 2
modelname = "parasaurolophus_6700"
scenename = "rs1_normals"
detector = cv.ppf_match_3d_PPF3DDetector(0.025, 0.05)
print('Loading model...')
pc = cv.ppf_match_3d.loadPLYSimple("data/%s.ply" % modelname, 1)
print('Training...')
detector.trainModel(pc)
print('Loading scene...')
pcTest = cv.ppf_match_3d.loadPLYSimple("data/%s.ply" % scenename, 1)
print('Matching...')
results = detector.match(pcTest, 1.0/40.0, 0.05)
print('Performing ICP...')
icp = cv.ppf_match_3d_ICP(100)
_, results = icp.registerModelToScene(pc, pcTest, results[:N])
print("Poses: ")
for i, result in enumerate(results):
#result.printPose()
print("\n-- Pose to Model Index %d: NumVotes = %d, Residual = %f\n%s\n" % (result.modelIndex, result.numVotes, result.residual, result.pose))
if i == 0:
pct = cv.ppf_match_3d.transformPCPose(pc, result.pose)
cv.ppf_match_3d.writePLY(pct, "%sPCTrans.ply" % modelname)
| 442 |
853 | #ifndef _GETLN_H____
#define _GETLN_H____
extern int getln(int, void *, long long);
#endif
| 42 |
864 | """
Mixin class containing entity versioning specific methods
To be used by OpenMetadata
"""
import logging
from typing import Generic, List, Optional, Type, TypeVar, Union
from pydantic import BaseModel
from requests.models import Response
from metadata.generated.schema.type import basic
from metadata.generated.schema.type.entityHistory import EntityVersionHistory
from metadata.ingestion.ometa.client import REST
from metadata.ingestion.ometa.utils import uuid_to_str
T = TypeVar("T", bound=BaseModel)
logger = logging.getLogger(__name__)
class OMetaVersionMixin(Generic[T]):
"""
OpenMetadata API methods related to entity versioning.
To be inherited by OpenMetadata
"""
client: REST
@staticmethod
def version_to_str(version: Union[str, float]):
"""convert float version to str
Parameters
----------
version : Union[str, float]
the version number of the entity
Returns
-------
str
the string representation of the version
"""
if isinstance(version, float):
return str(version)
return version
def get_entity_version(
self,
entity: Type[T],
entity_id: Union[str, basic.Uuid],
version: Union[str, float],
fields: Optional[List[str]] = None,
) -> Optional[T]:
"""
Get an entity at a specific version
Parameters
----------
entity: T
the entity type
entity_id: Union[str, basic.Uuid]
the ID for a specific entity
version: Union[str, float]
the specific version of the entity
fields: List
List of fields to return
"""
entity_id = uuid_to_str(entity_id)
version = self.version_to_str(version)
path = f"{entity_id}/versions/{version}"
return self._get(entity=entity, path=path, fields=fields)
def get_list_entity_versions(
self,
entity_id: Union[str, basic.Uuid],
entity: Type[T],
) -> Union[Response, EntityVersionHistory]:
"""
Retrieve the list of versions for a specific entity
Parameters
----------
entity: T
the entity type
entity_id: Union[str, basic.Uuid]
the ID for a specific entity
Returns
-------
List
lists of available versions for a specific entity
"""
path = f"{uuid_to_str(entity_id)}/versions"
resp = self.client.get(f"{self.get_suffix(entity)}/{path}")
if self._use_raw_data:
return resp
return EntityVersionHistory(**resp)
| 1,116 |
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 "core/operation/top_k.h"
#include "driver/huawei_ascend_npu/converter/converter.h"
#include "utility/debug.h"
#include "utility/logging.h"
#include "utility/modeling.h"
#include "utility/utility.h"
namespace nnadapter {
namespace huawei_ascend_npu {
int ConvertTopK(Converter* converter, hal::Operation* operation) {
TOP_K_OPERATION_EXTRACT_INPUTS_OUTPUTS
NNADAPTER_CHECK_EQ(axis,
static_cast<int>(input_operand->type.dimensions.count) - 1)
<< "HuaweiAscendNPU only support last dimsion.";
// Convert to GE operators
auto input_operator = converter->GetMappedOperator(input_operand);
if (!input_operator) {
input_operator = converter->ConvertOperand(input_operand);
}
auto k_operator = converter->GetMappedOperator(k_operand);
if (!k_operator) {
k_operator = converter->ConvertOperand(k_operand);
}
if (k_operand->type.precision == NNADAPTER_INT64) {
auto cast_op = converter->AddOperator<ge::op::Cast>(output_operand);
cast_op->set_attr_dst_type(ConvertToGEPrecision(NNADAPTER_INT32));
SET_INPUT(cast_op, x, k_operator);
k_operator = MAP_OUTPUT(cast_op, y, output_operand);
}
auto top_k_op = converter->AddOperator<ge::op::TopKV2>(output_operand);
top_k_op->set_attr_dim(axis);
top_k_op->set_attr_largest(largest);
top_k_op->set_attr_sorted(sorted);
SET_INPUT(top_k_op, x, input_operator);
SET_INPUT(top_k_op, k, k_operator);
auto output_operator = MAP_OUTPUT(top_k_op, values, output_operand);
bool need_indices_cast = false;
// ge::op::TopKV2 only support indices_type = DT_INT32, so cast to int64 if
// necessary
if (indices_operand->type.precision == NNADAPTER_INT64) {
need_indices_cast = true;
indices_operand->type.precision = NNADAPTER_INT32;
}
auto indices_operator = MAP_OUTPUT(top_k_op, indices, indices_operand);
// trick to avoid AscendNPU error
auto cast_output_op = converter->AddOperator<ge::op::Cast>(output_operand);
cast_output_op->set_attr_dst_type(
ConvertToGEPrecision(output_operand->type.precision));
SET_INPUT(cast_output_op, x, output_operator);
MAP_OUTPUT(cast_output_op, y, output_operand);
indices_operand->type.precision = NNADAPTER_INT64;
auto cast_indices_op = converter->AddOperator<ge::op::Cast>(indices_operand);
if (need_indices_cast) {
cast_indices_op->set_attr_dst_type(ConvertToGEPrecision(NNADAPTER_INT64));
} else {
cast_indices_op->set_attr_dst_type(ConvertToGEPrecision(NNADAPTER_INT32));
}
SET_INPUT(cast_indices_op, x, indices_operator);
MAP_OUTPUT(cast_indices_op, y, indices_operand);
return NNADAPTER_NO_ERROR;
}
} // namespace huawei_ascend_npu
} // namespace nnadapter
| 1,232 |
852 | #include "HLTriggerOffline/Muon/interface/L1MuonMatcherAlgo.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
L1MuonMatcherAlgo::L1MuonMatcherAlgo(const edm::ParameterSet &iConfig)
: prop_(iConfig),
preselectionCut_(iConfig.existsAs<std::string>("preselection") ? iConfig.getParameter<std::string>("preselection")
: ""),
deltaR2_(std::pow(iConfig.getParameter<double>("maxDeltaR"), 2)),
deltaPhi_(iConfig.existsAs<double>("maxDeltaPhi") ? iConfig.getParameter<double>("maxDeltaPhi") : 10),
sortByDeltaPhi_(iConfig.existsAs<bool>("sortByDeltaPhi") ? iConfig.getParameter<bool>("sortByDeltaPhi") : false) {
}
L1MuonMatcherAlgo::~L1MuonMatcherAlgo() {}
void L1MuonMatcherAlgo::init(const edm::EventSetup &iSetup) { prop_.init(iSetup); }
bool L1MuonMatcherAlgo::match(TrajectoryStateOnSurface &propagated,
const l1extra::L1MuonParticle &l1,
float &deltaR,
float &deltaPhi) const {
if (preselectionCut_(l1)) {
GlobalPoint pos = propagated.globalPosition();
double thisDeltaPhi = ::deltaPhi(double(pos.phi()), l1.phi());
double thisDeltaR2 = ::deltaR2(double(pos.eta()), double(pos.phi()), l1.eta(), l1.phi());
if ((fabs(thisDeltaPhi) < deltaPhi_) && (thisDeltaR2 < deltaR2_)) {
deltaR = std::sqrt(thisDeltaR2);
deltaPhi = thisDeltaPhi;
return true;
}
}
return false;
}
int L1MuonMatcherAlgo::match(TrajectoryStateOnSurface &propagated,
const std::vector<l1extra::L1MuonParticle> &l1s,
float &deltaR,
float &deltaPhi) const {
return matchGeneric(propagated, l1s, preselectionCut_, deltaR, deltaPhi);
/*
int match = -1;
double minDeltaPhi = deltaPhi_;
double minDeltaR2 = deltaR2_;
GlobalPoint pos = propagated.globalPosition();
for (int i = 0, n = l1s.size(); i < n; ++i) {
const l1extra::L1MuonParticle &l1 = l1s[i];
if (preselectionCut_(l1)) {
double thisDeltaPhi = ::deltaPhi(double(pos.phi()), l1.phi());
double thisDeltaR2 = ::deltaR2(double(pos.eta()),
double(pos.phi()), l1.eta(), l1.phi()); if ((fabs(thisDeltaPhi) <
deltaPhi_) && (thisDeltaR2 < deltaR2_)) { // check both if (sortByDeltaPhi_
? (fabs(thisDeltaPhi) < fabs(minDeltaPhi)) : (thisDeltaR2 < minDeltaR2)) {
// sort on one match = i; deltaR = std::sqrt(thisDeltaR2); deltaPhi =
thisDeltaPhi; if (sortByDeltaPhi_) minDeltaPhi = thisDeltaPhi; else
minDeltaR2 = thisDeltaR2;
}
}
}
}
return match;
*/
}
| 1,346 |
8,232 | <reponame>isra-fel/STL
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <synchapi.h>
// This must be as small as possible, because its contents are
// injected into the msvcprt.lib and msvcprtd.lib import libraries.
// Do not include or define anything else here.
// In particular, basic_string must not be included here.
// these declarations must be in sync with those in xthreads.h
using _Smtx_t = void*;
extern "C" {
static_assert(sizeof(_Smtx_t) == sizeof(SRWLOCK), "_Smtx_t must be the same size as SRWLOCK.");
static_assert(alignof(_Smtx_t) == alignof(SRWLOCK), "_Smtx_t must be the same alignment as SRWLOCK.");
void __cdecl _Smtx_lock_exclusive(_Smtx_t* smtx) { // lock shared mutex exclusively
AcquireSRWLockExclusive(reinterpret_cast<PSRWLOCK>(smtx));
}
void __cdecl _Smtx_lock_shared(_Smtx_t* smtx) { // lock shared mutex non-exclusively
AcquireSRWLockShared(reinterpret_cast<PSRWLOCK>(smtx));
}
int __cdecl _Smtx_try_lock_exclusive(_Smtx_t* smtx) { // try to lock shared mutex exclusively
return TryAcquireSRWLockExclusive(reinterpret_cast<PSRWLOCK>(smtx));
}
int __cdecl _Smtx_try_lock_shared(_Smtx_t* smtx) { // try to lock shared mutex non-exclusively
return TryAcquireSRWLockShared(reinterpret_cast<PSRWLOCK>(smtx));
}
void __cdecl _Smtx_unlock_exclusive(_Smtx_t* smtx) { // unlock exclusive shared mutex
ReleaseSRWLockExclusive(reinterpret_cast<PSRWLOCK>(smtx));
}
void __cdecl _Smtx_unlock_shared(_Smtx_t* smtx) { // unlock non-exclusive shared mutex
ReleaseSRWLockShared(reinterpret_cast<PSRWLOCK>(smtx));
}
}
| 622 |
331 | """
# https://stackoverflow.com/questions/547829/how-to-dynamically-load-a-python-class
"""
import importlib
def get_class_contructor(class_location):
mod_path = class_location[:class_location.rfind('.')]
class_name = class_location[class_location.rfind('.') + 1:]
module = importlib.import_module(mod_path)
# return class constructor
return getattr(module, class_name)
| 140 |
1,056 | <filename>ide/dlight.nativeexecution/src/org/netbeans/modules/nativeexecution/signals/SignalSupport.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.nativeexecution.signals;
import java.util.Collection;
import org.netbeans.modules.nativeexecution.api.ExecutionEnvironment;
import org.netbeans.modules.nativeexecution.api.util.Signal;
import org.openide.util.Lookup;
public final class SignalSupport {
public enum SIGNAL_SCOPE {
SIGNAL_PROCESS,
SIGNAL_GROUP,
SIGNAL_SESSION,
SIGNAL_BY_ENV,
SIGQUEUE_PROCESS
}
public static int signalProcess(ExecutionEnvironment env, int pid, Signal signal) {
final Collection<? extends SignalSupportImplementation> impls = Lookup.getDefault().lookupAll(SignalSupportImplementation.class);
for (SignalSupportImplementation impl : impls) {
if (impl.isSupported(env, SIGNAL_SCOPE.SIGNAL_PROCESS)) {
try {
return impl.sendSignal(env, SIGNAL_SCOPE.SIGNAL_PROCESS, pid, signal);
} catch (UnsupportedOperationException ex) {
// try next
}
}
}
throw new UnsupportedOperationException("Sending signal to a pid is not supported on " + env.getDisplayName()); // NOI18N
}
public static int signalProcessGroup(ExecutionEnvironment env, int gid, Signal signal) {
final Collection<? extends SignalSupportImplementation> impls = Lookup.getDefault().lookupAll(SignalSupportImplementation.class);
for (SignalSupportImplementation impl : impls) {
if (impl.isSupported(env, SIGNAL_SCOPE.SIGNAL_GROUP)) {
try {
return impl.sendSignal(env, SIGNAL_SCOPE.SIGNAL_GROUP, gid, signal);
} catch (UnsupportedOperationException ex) {
// try next
}
}
}
throw new UnsupportedOperationException("Sending signal to a group of processes is not supported on " + env.getDisplayName()); // NOI18N
}
public static int signalProcessSession(ExecutionEnvironment env, int psid, Signal signal) {
final Collection<? extends SignalSupportImplementation> impls = Lookup.getDefault().lookupAll(SignalSupportImplementation.class);
for (SignalSupportImplementation impl : impls) {
if (impl.isSupported(env, SIGNAL_SCOPE.SIGNAL_SESSION)) {
try {
return impl.sendSignal(env, SIGNAL_SCOPE.SIGNAL_SESSION, psid, signal);
} catch (UnsupportedOperationException ex) {
// try next
}
}
}
throw new UnsupportedOperationException("Sending signal to a session of processes is not supported on " + env.getDisplayName()); // NOI18N
}
public static int signalProcessesByEnv(ExecutionEnvironment env, String environment, Signal signal) {
final Collection<? extends SignalSupportImplementation> impls = Lookup.getDefault().lookupAll(SignalSupportImplementation.class);
for (SignalSupportImplementation impl : impls) {
if (impl.isSupported(env, SIGNAL_SCOPE.SIGNAL_BY_ENV)) {
try {
return impl.sendSignal(env, environment, signal);
} catch (UnsupportedOperationException ex) {
// try next
}
}
}
throw new UnsupportedOperationException("Sending signal to processes by env is not supported on " + env.getDisplayName()); // NOI18N
}
public static int sigqueue(ExecutionEnvironment env, int pid, Signal signal, int sigvalue) {
final Collection<? extends SignalSupportImplementation> impls = Lookup.getDefault().lookupAll(SignalSupportImplementation.class);
int result = 0;
for (SignalSupportImplementation impl : impls) {
if (impl.isSupported(env, SIGNAL_SCOPE.SIGQUEUE_PROCESS)) {
try {
result = impl.sigqueue(env, pid, signal, sigvalue);
if (result >= 0) {
return result;
}
} catch (UnsupportedOperationException ex) {
// try next
}
}
}
if (result == 0) {
throw new UnsupportedOperationException("Sigqueue is not supported on " + env.getDisplayName()); // NOI18N
}
return result;
}
}
| 2,081 |
888 | <filename>tests/system/conftest.py
import ssl
import pytest
import trustme
@pytest.fixture(scope="session")
def ca():
return trustme.CA()
@pytest.fixture(scope="session")
def localhost_cert(ca):
return ca.issue_cert("localhost")
@pytest.fixture(scope="session")
def httpserver_ssl_context(localhost_cert):
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
crt = localhost_cert.cert_chain_pems[0]
key = localhost_cert.private_key_pem
with crt.tempfile() as crt_file, key.tempfile() as key_file:
context.load_cert_chain(crt_file, key_file)
return context
| 235 |
1,738 | <reponame>jeikabu/lumberyard<filename>dev/Gems/LmbrCentral/Code/include/LmbrCentral/Shape/EditorSplineComponentBus.h
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/ComponentBus.h>
namespace LmbrCentral
{
/// Editor only listener for Spline changes.
class EditorSplineComponentNotifications
: public AZ::ComponentBus
{
public:
/// Did the type (linear/Bezier/Catmull-Rom) of the spline change.
virtual void OnSplineTypeChanged() {}
protected:
~EditorSplineComponentNotifications() = default;
};
/// Type to inherit to provide EditorPolygonPrismShapeComponentRequests
using EditorSplineComponentNotificationBus = AZ::EBus<EditorSplineComponentNotifications>;
} // namespace LmbrCentral | 390 |
385 | /**
* @file pfnc.h
* @brief Functions that communicate with the NVN function pool.
*/
#pragma once
// there's a lot of these
static void* pfnc_nvnMemoryPoolGetFlags;
static void* pfnc_nvnMemoryPoolFlushMappedRange;
static void* pfnc_nvnTexturePoolInitialize;
static void* pfnc_nvnTexturePoolSetDebugLabel;
static void* pfnc_nvnTexturePoolFinalize; | 122 |
4,392 | int main(void){return 0;}
| 9 |
605 | //======- ArmSVEToLLVMIRTranslation.cpp - Translate ArmSVE to LLVM IR -=======//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements a translation between the ArmSVE dialect and LLVM IR.
//
//===----------------------------------------------------------------------===//
#include "mlir/Target/LLVMIR/Dialect/ArmSVE/ArmSVEToLLVMIRTranslation.h"
#include "mlir/Dialect/ArmSVE/ArmSVEDialect.h"
#include "mlir/IR/Operation.h"
#include "mlir/Target/LLVMIR/ModuleTranslation.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicsAArch64.h"
using namespace mlir;
using namespace mlir::LLVM;
namespace {
/// Implementation of the dialect interface that converts operations belonging
/// to the ArmSVE dialect to LLVM IR.
class ArmSVEDialectLLVMIRTranslationInterface
: public LLVMTranslationDialectInterface {
public:
using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
/// Translates the given operation to LLVM IR using the provided IR builder
/// and saving the state in `moduleTranslation`.
LogicalResult
convertOperation(Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) const final {
Operation &opInst = *op;
#include "mlir/Dialect/ArmSVE/ArmSVEConversions.inc"
return failure();
}
};
} // namespace
void mlir::registerArmSVEDialectTranslation(DialectRegistry ®istry) {
registry.insert<arm_sve::ArmSVEDialect>();
registry.addDialectInterface<arm_sve::ArmSVEDialect,
ArmSVEDialectLLVMIRTranslationInterface>();
}
void mlir::registerArmSVEDialectTranslation(MLIRContext &context) {
DialectRegistry registry;
registerArmSVEDialectTranslation(registry);
context.appendDialectRegistry(registry);
}
| 646 |
1,023 | <reponame>AvivBenchorin/OpenSearch-Dashboards<filename>src/plugins/telemetry/opensearch_dashboards_back.json
{
"id": "telemetry",
"version": "opensearchDashboards",
"server": true,
"ui": true,
"requiredPlugins": [
"telemetryCollectionManager",
"usageCollection"
],
"extraPublicDirs": ["common/constants"],
"requiredBundles": [
"opensearchDashboardsUtils",
"opensearchDashboardsReact"
]
}
| 157 |
5,169 | <reponame>morizotter/Specs
{
"name": "NodeKittenX",
"version": "0.1.3",
"summary": "experimental GL(es) framework written in c++11",
"homepage": "https://github.com/structuresound/NodeKittenX",
"license": "MIT",
"authors": {
"structuresound": "<EMAIL>"
},
"source": {
"git": "https://github.com/structuresound/NodeKittenX.git",
"tag": "0.1.3"
},
"platforms": {
"ios": "6.0",
"osx": "10.9"
},
"source_files": [
"blocks/leif/NodeKittenX/*.{h}",
"blocks/leif/NodeKittenX/Platform/Cocoa/*.{h,mm,cpp}",
"blocks/leif/NodeKittenX/Event/*.{h,cpp}",
"blocks/leif/NodeKittenX/Node/*.{h,cpp}",
"blocks/leif/NodeKittenX/Shader/*.{h,cpp}",
"blocks/leif/NodeKittenX/Texture/*.{h,cpp}",
"blocks/leif/NodeKittenX/Types/*.{h,cpp}",
"blocks/leif/NodeKittenX/Utils/*.{h,cpp}",
"blocks/leif/NodeKittenX/View/NKView.{h,cpp}",
"blocks/leif/NodeKittenX/Examples/*.{h,cpp}"
],
"ios": {
"frameworks": "UIKit"
},
"osx": {
"frameworks": "AppKit"
},
"resources": "blocks/leif/NodeKittenX/Examples/Assets/*.{png,jpg}",
"requires_arc": true,
"xcconfig": {
"CLANG_CXX_LIBRARY": "libc++",
"GCC_OPTIMIZATION_LEVEL": "3"
},
"subspecs": [
{
"name": "picojpeg",
"source_files": "deps/leif/picojpeg/*.{h,c,cpp}"
},
{
"name": "png",
"source_files": "deps/leif/png/*.{h,c}",
"subspecs": [
{
"name": "zlib",
"source_files": "deps/leif/zlib/*.{h,c}"
}
]
}
]
}
| 783 |
1,500 | <filename>src/garage/tf/baselines/__init__.py
"""Baseline estimators for TensorFlow-based algorithms."""
from garage.tf.baselines.continuous_mlp_baseline import ContinuousMLPBaseline
from garage.tf.baselines.gaussian_cnn_baseline import GaussianCNNBaseline
from garage.tf.baselines.gaussian_mlp_baseline import GaussianMLPBaseline
__all__ = [
'ContinuousMLPBaseline',
'GaussianCNNBaseline',
'GaussianMLPBaseline',
]
| 148 |
892 | <filename>advisories/github-reviewed/2021/11/GHSA-35m5-8cvj-8783/GHSA-35m5-8cvj-8783.json
{
"schema_version": "1.2.0",
"id": "GHSA-35m5-8cvj-8783",
"modified": "2021-11-08T18:58:04Z",
"published": "2021-11-10T16:28:46Z",
"aliases": [
"CVE-2021-39182"
],
"summary": "Improper hashing in enrocrypt",
"details": "### Impact\nThe vulnerability is we used MD5 hashing Algorithm In our hashing file. If anyone who is a beginner(and doesn't know about hashes) can face problems as MD5 is considered a Insecure Hashing Algorithm. \n\n### Patches\nThe vulnerability is patched in v1.1.4 of the product, the users can upgrade to version 1.1.4.\n\n### Workarounds\nIf u specifically want a version and don't want to upgrade, you can remove the `MD5` hashing function from the file `hashing.py` and this vulnerability will be gone\n\n### References\nhttps://www.cybersecurity-help.cz/vdb/cwe/916/\nhttps://www.cybersecurity-help.cz/vdb/cwe/327/\nhttps://www.cybersecurity-help.cz/vdb/cwe/328/\nhttps://www.section.io/engineering-education/what-is-md5/\nhttps://www.johndcook.com/blog/2019/01/24/reversing-an-md5-hash/\n\n### For more information\nIf you have any questions or comments about this advisory:\n* Open an issue in [**Enrocrypt's Official Repo**](http://www.github.com/Morgan-Phoenix/EnroCrypt)\n* Create a Discussion in [**Enrocrypt's Official Repo**](http://www.github.com/Morgan-Phoenix/EnroCrypt)\n",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N"
}
],
"affected": [
{
"package": {
"ecosystem": "PyPI",
"name": "enrocrypt"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.4"
}
]
}
]
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/Morgan-Phoenix/EnroCrypt/security/advisories/GHSA-35m5-8cvj-8783"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-39182"
},
{
"type": "WEB",
"url": "https://github.com/Morgan-Phoenix/EnroCrypt/commit/e652d56ac60eadfc26489ab83927af13a9b9d8ce"
},
{
"type": "PACKAGE",
"url": "https://github.com/Morgan-Phoenix/EnroCrypt"
}
],
"database_specific": {
"cwe_ids": [
"CWE-327",
"CWE-328",
"CWE-916"
],
"severity": "HIGH",
"github_reviewed": true
}
} | 1,188 |
445 | #include "multiverso/io/local_stream.h"
#include <errno.h>
extern "C" {
#include <sys/stat.h>
}
#ifndef _MSC_VER
extern "C" {
#include <sys/types.h>
#include <dirent.h>
}
#else
#include <Windows.h>
#define stat _stat64
#endif
namespace multiverso {
LocalStream::LocalStream(const URI& uri, FileOpenMode mode) {
path_ = uri.path;
std::string mode_str;
switch (mode) {
case FileOpenMode::Read:
mode_str = "r";
break;
case FileOpenMode::Write:
mode_str = "w";
break;
case FileOpenMode::Append:
mode_str = "a";
break;
case FileOpenMode::BinaryRead:
mode_str = "rb";
break;
case FileOpenMode::BinaryWrite:
mode_str = "wb";
break;
case FileOpenMode::BinaryAppend:
mode_str = "ab";
}
#ifdef _MSC_VER
fopen_s(&fp_, uri.path.c_str(), mode_str.c_str());
#else
fp_ = fopen(uri.path.c_str(), mode_str.c_str());
#endif
if (fp_ == nullptr) {
is_good_ = false;
Log::Error("Failed to open LocalStream %s\n", uri.path.c_str());
} else {
is_good_ = true;
}
}
LocalStream::~LocalStream(void)
{
is_good_ = false;
if (fp_ != nullptr)
std::fclose(fp_);
}
/*!
* \brief write data to a file
* \param buf pointer to a memory buffer
* \param size data size
*/
void LocalStream::Write(const void *buf, size_t size) {
if (std::fwrite(buf, 1, size, fp_) != size) {
is_good_ = false;
Log::Error("LocalStream.Write incomplete\n");
}
}
/*!
* \brief read data from Stream
* \param buf pointer to a memory buffer
* \param size the size of buf
*/
size_t LocalStream::Read(void *buf, size_t size) {
return std::fread(buf, 1, size, fp_);
}
bool LocalStream::Good() { return is_good_; }
LocalStreamFactory::LocalStreamFactory(const std::string& host) {
host_ = host;
}
LocalStreamFactory::~LocalStreamFactory() {
}
/*!
* \brief create a Stream
* \param path the path of the file
* \param mode "w" - create an empty file to store data;
* "a" - open the file to append data to it
* "r" - open the file to read
* \return the Stream which is used to write or read data
*/
Stream* LocalStreamFactory::Open(const URI& uri, FileOpenMode mode) {
return new LocalStream(uri, mode);
}
void LocalStreamFactory::Close() {
///TODO
}
} | 897 |
356 | /*
* Copyright 2015-2018 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.igormaznitsa.mindmap.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.igormaznitsa.mindmap.model.parser.MindMapLexer;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.util.regex.Pattern;
import org.junit.Test;
public class TopicTest {
private MindMapLexer makeLexer(final String text) {
final MindMapLexer lexer = new MindMapLexer();
lexer.start(text, 0, text.length(), MindMapLexer.TokenType.WHITESPACE);
return lexer;
}
@Test
public void testFindMaxChildPathLength() {
final MindMap map = new MindMap(true);
final Topic t1 = new Topic(map, map.getRoot(), "t1");
final Topic t2 = new Topic(map, map.getRoot(), "t2");
final Topic t21 = new Topic(map, t2, "t21");
final Topic t22 = new Topic(map, t21, "t22");
final Topic t3 = new Topic(map, map.getRoot(), "t3");
final Topic t31 = new Topic(map, t3, "t31");
final Topic t32 = new Topic(map, t31, "t32");
final Topic t33 = new Topic(map, t32, "t33");
assertEquals(0, t1.findMaxChildPathLength());
assertEquals(2, t2.findMaxChildPathLength());
assertEquals(4, map.getRoot().findMaxChildPathLength());
}
@Test
public void test() {
final MindMap mm = new MindMap(true);
final Topic topic = new Topic(mm, null, "авы аыва вы Что то");
assertTrue(topic
.containsPattern(null, Pattern.compile(Pattern.quote("Что"), Pattern.CASE_INSENSITIVE),
true, null));
assertTrue(topic.containsPattern(null,
Pattern.compile(Pattern.quote("что"), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE),
true, null));
}
@Test
public void testParse_OnlyTopic() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Topic"));
assertEquals("Topic", topic.getText());
assertTrue(topic.getChildren().isEmpty());
}
@Test
public void testParse_OnlyTopicWithExtras() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer(
"# Topic\n- NOTE\n<pre>Some\ntext</pre>\n- LINK\n<pre>http://www.google.com</pre>\n## Topic2"));
assertEquals("Topic", topic.getText());
assertEquals(1, topic.getChildren().size());
assertEquals(2, topic.getExtras().size());
assertEquals("Some\ntext", topic.getExtras().get(Extra.ExtraType.NOTE).getValue());
assertEquals(new URI("http://www.google.com"),
((MMapURI) topic.getExtras().get(Extra.ExtraType.LINK).getValue()).asURI());
}
@Test
public void testParse_PairTopicsFirstContainsMultilineTextNoteAndMiscEOL() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer(
"# Topic\r\n- NOTE\r\n<pre> Some \r\n text \n line \r\n end \r\n </pre>\r\n- LINK\n<pre>http://www.google.com</pre>\n## Topic2"));
assertEquals("Topic", topic.getText());
assertEquals(1, topic.getChildren().size());
assertEquals(2, topic.getExtras().size());
assertEquals(" Some \r\n text \n line \r\n end \r\n ",
topic.getExtras().get(Extra.ExtraType.NOTE).getValue());
assertEquals(new URI("http://www.google.com"),
((MMapURI) topic.getExtras().get(Extra.ExtraType.LINK).getValue()).asURI());
final Topic second = topic.getFirst();
assertEquals("Topic2", second.getText());
}
@Test
public void testParse_TopicWithURLContainingSpaces() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer(
"# Topic\n- NOTE\n<pre>Some\ntext</pre>\n- LINK\n<pre> http://www.google.com </pre>\n## Topic2"));
assertEquals("Topic", topic.getText());
assertEquals(1, topic.getChildren().size());
assertEquals(2, topic.getExtras().size());
assertEquals("Some\ntext", topic.getExtras().get(Extra.ExtraType.NOTE).getValue());
assertEquals(new URI("http://www.google.com"),
((MMapURI) topic.getExtras().get(Extra.ExtraType.LINK).getValue()).asURI());
}
@Test
public void testParse_OnlyTopicWithExtrasAndAttributes() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer(
"# Topic\n- NOTE\n<pre>Some\ntext</pre>\n- LINK\n<pre>http://www.google.com</pre>\n> attr1=`hello`,attr2=``wor`ld``"));
assertEquals("Topic", topic.getText());
assertTrue(topic.getChildren().isEmpty());
assertEquals(2, topic.getExtras().size());
assertEquals("Some\ntext", topic.getExtras().get(Extra.ExtraType.NOTE).getValue());
assertEquals(new URI("http://www.google.com"),
((MMapURI) topic.getExtras().get(Extra.ExtraType.LINK).getValue()).asURI());
assertEquals(2, topic.getAttributes().size());
assertEquals("hello", topic.getAttribute("attr1"));
assertEquals("wor`ld", topic.getAttribute("attr2"));
}
@Test
public void testParse_TopicAndChild() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Topic<br>Root\n ## Child<br/>Topic"));
assertEquals("Topic\nRoot", topic.getText());
assertEquals(1, topic.getChildren().size());
final Topic child = topic.getChildren().get(0);
assertEquals("Child\nTopic", child.getText());
assertTrue(child.getChildren().isEmpty());
}
@Test
public void testParseRoot_CodeSnippetContainsThreeBackticksLine_withSpacesBefore()
throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Root\n```Java\nSystem.exit(0);\n ```\n```"));
assertEquals("System.exit(0);\n ```\n", topic.getCodeSnippet("Java"));
}
@Test
public void testParseRoot_CodeSnippetContainsThreeBackticksLine_withOneMoreBacktickAfterSpace()
throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Root\n```Java\nSystem.exit(0);\n``` `\n```"));
assertEquals("System.exit(0);\n``` `\n", topic.getCodeSnippet("Java"));
}
@Test
public void testParseRoot_CodeSnippetContainsThreeBackticksLine_manyBackticks() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Root\n```Java\nSystem.exit(0);\n`````\n```"));
assertEquals("System.exit(0);\n`````\n", topic.getCodeSnippet("Java"));
}
@Test
public void testParseRoot_CodeSnippetContainsThreeBackticksLine_threeBacktickAndChar()
throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Root\n```Java\nSystem.exit(0);\n```a\n```"));
assertEquals("System.exit(0);\n```a\n", topic.getCodeSnippet("Java"));
}
@Test
public void testParseRoot_CodeSnippetContainsThreeBackticksLine_charAndThreeBacktick()
throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Root\n```Java\nSystem.exit(0);\na```\n```"));
assertEquals("System.exit(0);\na```\n", topic.getCodeSnippet("Java"));
}
@Test
public void testParseRoot_emptyCodeSnippet() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Root\n```Java\n```"));
assertEquals("", topic.getCodeSnippet("Java"));
}
@Test
public void testParseRoot_notClosedCodeSnippet_OnlyHeader() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Root\n```Java\n"));
assertNull(topic.getCodeSnippet("Java"));
}
@Test
public void testParseRoot_notClosedCodeSnippet_NotClosed() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Root\n```Java\nSystem.out.println();\n"));
assertNull(topic.getCodeSnippet("Java"));
}
@Test
public void testParse_TopicAndTwoChildren() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# Topic\n ## Child1\n ## Child2\n"));
assertEquals("Topic", topic.getText());
assertEquals(2, topic.getChildren().size());
final Topic child1 = topic.getChildren().get(0);
assertEquals("Child1", child1.getText());
assertTrue(child1.getChildren().isEmpty());
final Topic child2 = topic.getChildren().get(1);
assertEquals("Child2", child2.getText());
assertTrue(child2.getChildren().isEmpty());
}
@Test
public void testParse_MultiLevels() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = Topic.parse(mm, makeLexer(
"# Level1\n## Level2.1\n### Level3.1\n## Level2.2\n### Level3.2\n#### Level4.2\n## Level2.3"));
assertEquals("Level1", root.getText());
assertEquals(3, root.getChildren().size());
assertEquals("Level2.1", root.getChildren().get(0).getText());
assertEquals("Level2.2", root.getChildren().get(1).getText());
assertEquals("Level2.3", root.getChildren().get(2).getText());
final Topic level32 = root.getChildren().get(1).getChildren().get(0);
assertEquals("Level3.2", level32.getText());
assertEquals("Level4.2", level32.getChildren().get(0).getText());
}
@Test
public void testParse_WriteOneLevel() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = new Topic(mm, null, "Level1");
final StringWriter writer = new StringWriter();
root.write(writer);
assertEquals("\n# Level1\n", writer.toString());
}
@Test
public void testParse_WriteOneLevelWithExtra() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = new Topic(mm, null, "Level1");
root.setExtra(new ExtraLink("http://wwww.igormaznitsa.com"));
final StringWriter writer = new StringWriter();
root.write(writer);
assertEquals("\n# Level1\n- LINK\n<pre>http://wwww.igormaznitsa.com</pre>\n",
writer.toString());
}
@Test
public void testParse_WriteOneLevelWithExtraAndTwoCodeSnippets() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = new Topic(mm, null, "Level1");
root.setCodeSnippet("Java", "System.exit();");
root.setCodeSnippet("Shell", "exit");
root.setExtra(new ExtraLink("http://wwww.igormaznitsa.com"));
final StringWriter writer = new StringWriter();
root.write(writer);
assertEquals(
"\n# Level1\n- LINK\n<pre>http://wwww.igormaznitsa.com</pre>\n```Java\nSystem.exit();\n```\n```Shell\nexit\n```\n",
writer.toString());
}
@Test
public void testParse_WriteOneLevelWithExtraAndAttribute() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = new Topic(mm, null, "Level1");
root.setAttribute("hello", "wor`ld");
root.setExtra(new ExtraLink("http://wwww.igormaznitsa.com"));
final StringWriter writer = new StringWriter();
root.write(writer);
assertEquals(
"\n# Level1\n> hello=``wor`ld``\n\n- LINK\n<pre>http://wwww.igormaznitsa.com</pre>\n",
writer.toString());
}
@Test
public void testParse_WriteOneLevelWithSpecialChars() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = new Topic(mm, null, "<Level1>\nNextText");
final StringWriter writer = new StringWriter();
root.write(writer);
assertEquals("\n# \\<Level1\\><br/>NextText\n", writer.toString());
}
@Test
public void testParse_WriteTwoLevel() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = new Topic(mm, null, "Level1");
new Topic(mm, root, "Level2");
final StringWriter writer = new StringWriter();
root.write(writer);
assertEquals("\n# Level1\n\n## Level2\n", writer.toString());
}
@Test
public void testParse_WriteThreeLevel() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = new Topic(mm, null, "Level1");
final Topic level2 = new Topic(mm, root, "Level2");
new Topic(mm, level2, "Level3");
new Topic(mm, root, "Level2.1");
final StringWriter writer = new StringWriter();
root.write(writer);
assertEquals("\n# Level1\n\n## Level2\n\n### Level3\n\n## Level2\\.1\n", writer.toString());
}
@Test
public void testParse_EmptyTextAtMiddleLevel() throws Exception {
final MindMap mm = new MindMap(true);
final Topic topic = Topic.parse(mm, makeLexer("# \n## Child\n"));
assertEquals("", topic.getText());
assertEquals(1, topic.getChildren().size());
final Topic child2 = topic.getChildren().get(0);
assertEquals("Child", child2.getText());
assertTrue(child2.getChildren().isEmpty());
}
@Test
public void testParse_topicWithTextStartsWithHash() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = new Topic(mm, null, "");
mm.setRoot(root, false);
new Topic(mm, root, "#NewTopic");
final String packedMap = mm.packToString();
final MindMap parsed = new MindMap(new StringReader(packedMap));
final Topic rootParsed = parsed.getRoot();
assertEquals(1, rootParsed.getChildren().size());
final Topic theTopic = rootParsed.getFirst();
assertEquals("#NewTopic", theTopic.getText());
assertTrue(theTopic.getExtras().isEmpty());
}
@Test
public void testWriteParse_encryptedNote() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = new Topic(mm, null, "");
mm.setRoot(root, false);
root.setText("`Root\ntopic`");
root.setExtra(new ExtraNote("Encrypted world", true, "tip"));
final StringWriter writer = new StringWriter();
final String written = mm.write(writer).toString();
assertTrue(written.contains("> extras.note.encrypted=`true`,extras.note.encrypted.hint=`tip`"));
final MindMap parsed = new MindMap(new StringReader(written));
final Topic parsedRoot = parsed.getRoot();
final ExtraNote parsedNote = (ExtraNote) parsedRoot.getExtras().get(Extra.ExtraType.NOTE);
assertTrue(parsedNote.isEncrypted());
assertEquals("tip", parsedNote.getHint());
}
@Test
public void testParse_noteContainsTicks() throws Exception {
final MindMap mm = new MindMap(true);
final Topic root = new Topic(mm, null, "");
mm.setRoot(root, false);
root.setText("`Root\ntopic`");
root.setExtra(new ExtraNote("Hello world \n <br>```Some```"));
final StringWriter writer = new StringWriter();
mm.write(writer);
final String text = writer.toString();
assertEquals("Mind Map generated by NB MindMap plugin \n"
+ "> __version__=`1.1`\n"
+ "---\n"
+ "\n# \\`Root<br/>topic\\`\n"
+ "- NOTE\n"
+ "<pre>Hello world \n"
+ " <br>```Some```</pre>\n", text);
final MindMap parsed = new MindMap(new StringReader(text));
assertEquals("`Root\ntopic`", parsed.getRoot().getText());
assertEquals("Hello world \n <br>```Some```",
((ExtraNote) parsed.getRoot().getExtras().get(Extra.ExtraType.NOTE)).getValue());
}
}
| 5,832 |
1,813 | package com.example.tools.traceur;
import com.tspoon.traceur.Traceur;
/**
* We are using an interface to initialize Traceur that gets implemented both in the debug folder and in the release folder. In the debug
* folder it starts up Traceur, while in the release folder it does nothing. This way we don't need to keep the "compile" dependency on
* Traceur, but we can replace it with a "debugCompile" dependency.
*/
public class TraceurToolImpl implements TraceurTool {
@Override
public void init() {
Traceur.enableLogging();
}
}
| 161 |
480 | {
"actions": {
"check": {
"desc": "check if crowd-pack is ready",
"for_web": "yes"
},
"crowdsource": {
"desc": "prepare experiments for crowdsourcing using mobile phones",
"for_web": "yes"
},
"request": {
"desc": "request experiment pack for mobile device",
"for_web": "yes"
},
"server": {
"desc": "start server to process tasks"
}
},
"copyright": "See CK COPYRIGHT.txt for copyright details",
"desc": "collaborative program optimization using mobile devices (such as Android mobile phones and tables)",
"developer": "<NAME>",
"developer_email": "<EMAIL>",
"developer_webpage": "http://fursin.net",
"file-mobile-request": "mobile-request",
"license": "See CK LICENSE.txt for licensing details",
"log_file_results": "log.results.txt",
"module_deps": {
"dataset": "8a7141c59cd335f5",
"env": "9b9b3208ac44b891",
"experiment": "bc0409fb61f0aa82",
"math.conditions": "d5ac649c14325bca",
"module": "032630d041b4fd8a",
"platform.os": "41e31cc4496b8a8e",
"program": "b0ac08fe1d3c2615",
"program.optimization": "27bc42ee449e880e",
"tmp": "bfc8fef73c233ce4"
},
"scenarios": [
"experiment.tune.compiler.flags.gcc.e",
"experiment.tune.compiler.flags.llvm.e"
],
"tags": [
"crowdsource-via-mobile",
"experiments",
"program optimization"
],
"tmp-server": "mobile-crowdserver-queue",
"workflow": "yes",
"workflow_type": "program crowd-optimization front-end (workflow) across mobile devices"
}
| 642 |
697 | <reponame>1634865486/AndroidTimeableView<filename>AndroidTimetableView/app/src/main/java/com/zhuangfei/android_timetableview/views/CustomWidthActivity.java
package com.zhuangfei.android_timetableview.views;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.zhuangfei.android_timetableview.R;
import com.zhuangfei.android_timetableview.custom.CustomOperater;
import com.zhuangfei.android_timetableview.model.MySubject;
import com.zhuangfei.android_timetableview.model.SubjectRepertory;
import com.zhuangfei.timetable.TimetableView;
import com.zhuangfei.timetable.listener.ISchedule;
import com.zhuangfei.timetable.listener.IWeekView;
import com.zhuangfei.timetable.listener.OnDateBuildAapter;
import com.zhuangfei.timetable.listener.OnSlideBuildAdapter;
import com.zhuangfei.timetable.listener.OnSpaceItemClickAdapter;
import com.zhuangfei.timetable.model.Schedule;
import com.zhuangfei.timetable.view.WeekView;
import java.util.List;
/**
* 基础功能演示:
* 1.周次选择栏
* 2.透明背景
* 3.点击监听
* 4.颜色分配
* 5.日期高亮
* 6.日期计算
* <p>
* <p>
* 该界面的代码注释会比较详细,建议从此处开始看起
*/
public class CustomWidthActivity extends AppCompatActivity{
private static final String TAG = "CustomWidthActivity";
//控件
TimetableView mTimetableView;
CustomOperater operater;
List<MySubject> mySubjects;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_width);
mySubjects = SubjectRepertory.loadDefaultSubjects2();
mySubjects.addAll(SubjectRepertory.loadDefaultSubjects());
initTimetableView();
}
/**
* 初始化课程控件
*/
private void initTimetableView() {
//获取控件
mTimetableView = findViewById(R.id.id_timetableView);
operater=new CustomOperater();
operater.setWidthWeights(new float[]{1,3,1,1,1,1,1});
mTimetableView.source(mySubjects)
.curWeek(1)
.maxSlideItem(10)
.monthWidthDp(30)
.operater(operater)
//旗标布局点击监听
.callback(new ISchedule.OnFlaglayoutClickListener() {
@Override
public void onFlaglayoutClick(int day, int start) {
mTimetableView.hideFlaglayout();
Toast.makeText(CustomWidthActivity.this,
"点击了旗标:周" + (day + 1) + ",第" + start + "节",
Toast.LENGTH_SHORT).show();
}
})
.callback(new OnDateBuildAapter(){
@Override
public View[] getDateViews(LayoutInflater mInflate, float monthWidth, float perWidth, int height) {
View[] views = new View[8];
views[0] = onBuildMonthLayout(mInflate, (int) monthWidth, height);
float[] weights=operater.getWeights();
float sum=0;
for(int i=0;i<weights.length;i++){
sum+=weights[i];
}
for (int i = 1; i < 8; i++) {
float rato=weights[i-1]/sum;
views[i] = onBuildDayLayout(mInflate, i, (int) (7*perWidth*rato), height);
}
return views;
}
})
.callback(new OnSpaceItemClickAdapter(){
@Override
public void onSpaceItemClick(int day, int start) {
//day:从0开始,start:从1开始
if(flagLayout==null) return;
float[] weights=operater.getWeights();
float sum=0;
for(int i=0;i<weights.length;i++){
sum+=weights[i];
}
int newItemWidth= (int) (super.itemWidth*7*weights[day]/sum);
float newMarLeft=0;
for(int i=0;i<day;i++){
newMarLeft+=(super.itemWidth*7*weights[i]/sum);
}
FrameLayout.LayoutParams lp=new FrameLayout.LayoutParams(newItemWidth-marLeft*2,itemHeight);
lp.setMargins(monthWidth+(int)newMarLeft+marLeft,(start-1)*(itemHeight+marTop)+marTop,0,0);
flagLayout.setLayoutParams(lp);
}
})
.showView();
}
/**
* 更新一下,防止因程序在后台时间过长(超过一天)而导致的日期或高亮不准确问题。
*/
@Override
protected void onStart() {
super.onStart();
mTimetableView.onDateBuildListener()
.onHighLight();
}
}
| 2,925 |
1,144 | /* SPDX-License-Identifier: GPL-2.0+ */
/*
* (C) Copyright 2005
* ARM Ltd.
* <NAME>, <<EMAIL>>
* Configuration for ARM Core Modules.
* No standalonw port yet available
* - this file is included by both integratorap.h & integratorcp.h
*/
#ifndef __ARMCOREMODULE_H
#define __ARMCOREMODULE_H
#define CM_BASE 0x10000000
/* CM registers common to all CMs */
/* Note that observed values after reboot into the ARM Boot Monitor
have been used as defaults, rather than the POR values */
#define OS_CTRL 0x0000000C
#define CMMASK_REMAP 0x00000005 /* set remap & led */
#define CMMASK_RESET 0x00000008
#define OS_LOCK 0x00000014
#define CMVAL_LOCK1 0x0000A000 /* locking value */
#define CMVAL_LOCK2 0x0000005F /* locking value */
#define CMVAL_UNLOCK 0x00000000 /* any value != CM_LOCKVAL */
#define OS_SDRAM 0x00000020
#define OS_INIT 0x00000024
#define CMMASK_MAP_SIMPLE 0xFFFDFFFF /* simple mapping */
#define CMMASK_TCRAM_DISABLE 0xFFFEFFFF /* TCRAM disabled */
#define CMMASK_LOWVEC 0x00000000 /* vectors @ 0x00000000 */
#define CMMASK_LE 0xFFFFFFF7 /* little endian */
#define CMMASK_CMxx6_COMMON 0x00000013 /* Common value for CMxx6 */
/* - observed reset value of */
/* CM926EJ-S */
/* CM1136-EJ-S */
#if defined (CONFIG_CM10200E) || defined (CONFIG_CM10220E)
#define CMMASK_INIT_102 0x00000300 /* see CM102xx ref manual */
/* - PLL test clock bypassed */
/* - bus clock ratio 2 */
/* - little endian */
/* - vectors at zero */
#endif /* CM1022xx */
/* Determine CM characteristics */
#undef CONFIG_CM_MULTIPLE_SSRAM
#undef CONFIG_CM_SPD_DETECT
#undef CONFIG_CM_REMAP
#undef CONFIG_CM_INIT
#undef CONFIG_CM_TCRAM
#if defined (CONFIG_CM946E_S) || defined (CONFIG_CM966E_S)
#define CONFIG_CM_MULTIPLE_SSRAM /* CM has multiple SSRAM mapping */
#endif
/* Excalibur core module has reduced functionality */
#ifndef CONFIG_CM922T_XA10
#define CONFIG_CM_SPD_DETECT /* CM supports SPD query */
#define OS_SPD 0x00000100 /* Address of SPD data */
#define CONFIG_CM_REMAP /* CM supports remapping */
#define CONFIG_CM_INIT /* CM has initialization reg */
#endif /* NOT EXCALIBUR */
#if defined(CONFIG_CM926EJ_S) || defined (CONFIG_CM946E_S) || \
defined(CONFIG_CM966E_S) || defined (CONFIG_CM1026EJ_S) || \
defined(CONFIG_CM1136JF_S)
#define CONFIG_CM_TCRAM /* CM has TCRAM */
#endif
#ifdef CONFIG_CM_SPD_DETECT
#define OS_SPD 0x00000100 /* The SDRAM SPD data is copied here */
#endif
#endif /* __ARMCOREMODULE_H */
| 1,098 |
850 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def hbox_grid_sample(boxes, point_num_per_line=3):
bin_w, bin_h = (boxes[:, 2] - boxes[:, 0]) / (point_num_per_line-1), (boxes[:, 3] - boxes[:, 1]) / (point_num_per_line-1)
shift_x = np.expand_dims(np.arange(0, point_num_per_line), axis=0)
shift_y = np.expand_dims(np.arange(0, point_num_per_line), axis=0)
shift_x, shift_y = np.meshgrid(shift_x, shift_y)
shift_x = np.reshape(shift_x, [-1, 1])
shift_y = np.reshape(shift_y, [-1, 1])
shifts = np.concatenate([shift_x, shift_y], axis=-1)
shifts = np.reshape(shifts, [-1, point_num_per_line**2*2])
shifts = np.array(np.tile(shifts, [boxes.shape[0], 1]).reshape([-1, point_num_per_line**2, 2]), np.float32)
bin_w = np.reshape(bin_w, [-1, 1])
bin_h = np.reshape(bin_h, [-1, 1])
shifts[:, :, 0] *= bin_w
shifts[:, :, 1] *= bin_h
shifts += boxes[:, np.newaxis, 0:2]
return shifts.reshape([-1, point_num_per_line**2*2])
def rbox_border_sample(boxes, point_num_per_line=3):
shift_x = np.arange(0, point_num_per_line-1)
shift_y = np.arange(0, point_num_per_line-1)
shift_x = np.reshape(shift_x, [-1, 1])
shift_y = np.reshape(shift_y, [-1, 1])
sample_points_list = []
for i in range(4):
width = boxes[:, (i*2+2)%8] - boxes[:, (i*2)%8]
height = boxes[:, (i*2+3)%8] - boxes[:, (i*2+1)%8]
bin_w, bin_h = width / (point_num_per_line-1), height / (point_num_per_line-1)
shifts = np.concatenate([shift_x, shift_y], axis=-1)
shifts = np.array(np.tile(shifts, [boxes.shape[0], 1]).reshape([-1, point_num_per_line-1, 2]), np.float32)
bin_w = np.reshape(bin_w, [-1, 1])
bin_h = np.reshape(bin_h, [-1, 1])
shifts[:, :, 0] *= bin_w
shifts[:, :, 1] *= bin_h
shifts += boxes[:, np.newaxis, i*2:(i*2)+2]
sample_points_list.append(shifts)
sample_points = np.concatenate(sample_points_list, axis=1)
return sample_points.reshape([-1, (point_num_per_line - 1) * 4 * 2])
if __name__ == '__main__':
# print(hbox_grid_sample(np.array([[3, 3, 12, 12], [0, 0, 4, 4]]), 3))
print(rbox_border_sample(np.array([[3, 3, 12, 3, 12, 12, 3, 12], [0, 0, 4, 0, 4, 4, 0, 4]]), 3))
| 1,125 |
5,964 | <gh_stars>1000+
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CueTimeline_h
#define CueTimeline_h
#include "core/html/track/TextTrackCue.h"
#include "core/html/track/vtt/VTTCue.h"
#include "platform/PODIntervalTree.h"
#include "platform/heap/Handle.h"
#include "wtf/Vector.h"
namespace blink {
class HTMLMediaElement;
class TextTrackCueList;
typedef PODIntervalTree<double, TextTrackCue*> CueIntervalTree;
typedef CueIntervalTree::IntervalType CueInterval;
typedef Vector<CueInterval> CueList;
// This class manages the timeline and rendering updates of cues associated
// with TextTracks. Owned by a HTMLMediaElement.
class CueTimeline : public NoBaseWillBeGarbageCollectedFinalized<CueTimeline> {
public:
CueTimeline(HTMLMediaElement&);
void addCues(TextTrack*, const TextTrackCueList*);
void addCue(TextTrack*, PassRefPtrWillBeRawPtr<TextTrackCue>);
void removeCues(TextTrack*, const TextTrackCueList*);
void removeCue(TextTrack*, PassRefPtrWillBeRawPtr<TextTrackCue>);
void hideCues(TextTrack*, const TextTrackCueList*);
void updateActiveCues(double);
bool ignoreUpdateRequests() const { return m_ignoreUpdate > 0; }
void beginIgnoringUpdateRequests();
void endIgnoringUpdateRequests();
const CueList& currentlyActiveCues() const { return m_currentlyActiveCues; }
DECLARE_TRACE();
private:
HTMLMediaElement& mediaElement() const { return *m_mediaElement; }
void addCueInternal(PassRefPtrWillBeRawPtr<TextTrackCue>);
void removeCueInternal(PassRefPtrWillBeRawPtr<TextTrackCue>);
RawPtrWillBeMember<HTMLMediaElement> m_mediaElement;
CueIntervalTree m_cueTree;
CueList m_currentlyActiveCues;
double m_lastUpdateTime;
int m_ignoreUpdate;
};
class TrackDisplayUpdateScope {
STACK_ALLOCATED();
public:
TrackDisplayUpdateScope(CueTimeline& cueTimeline)
{
m_cueTimeline = &cueTimeline;
m_cueTimeline->beginIgnoringUpdateRequests();
}
~TrackDisplayUpdateScope()
{
ASSERT(m_cueTimeline);
m_cueTimeline->endIgnoringUpdateRequests();
}
private:
RawPtrWillBeMember<CueTimeline> m_cueTimeline;
};
#ifndef NDEBUG
// Template specializations required by PodIntervalTree in debug mode.
template <>
struct ValueToString<double> {
static String string(const double value)
{
return String::number(value);
}
};
template <>
struct ValueToString<TextTrackCue*> {
static String string(TextTrackCue* const& cue)
{
return cue->toString();
}
};
#endif
} // namespace blink
#endif // CueTimeline_h
| 962 |
515 | <filename>compressai/zoo/pretrained.py
# Copyright (c) 2021-2022, InterDigital Communications, Inc
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted (subject to the limitations in the disclaimer
# below) provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of InterDigital Communications, Inc nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
# THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Dict
from torch import Tensor
def rename_key(key: str) -> str:
"""Rename state_dict key."""
# Deal with modules trained with DataParallel
if key.startswith("module."):
key = key[7:]
# ResidualBlockWithStride: 'downsample' -> 'skip'
if ".downsample." in key:
return key.replace("downsample", "skip")
# EntropyBottleneck: nn.ParameterList to nn.Parameters
if key.startswith("entropy_bottleneck."):
if key.startswith("entropy_bottleneck._biases."):
return f"entropy_bottleneck._bias{key[-1]}"
if key.startswith("entropy_bottleneck._matrices."):
return f"entropy_bottleneck._matrix{key[-1]}"
if key.startswith("entropy_bottleneck._factors."):
return f"entropy_bottleneck._factor{key[-1]}"
return key
def load_pretrained(state_dict: Dict[str, Tensor]) -> Dict[str, Tensor]:
"""Convert state_dict keys."""
state_dict = {rename_key(k): v for k, v in state_dict.items()}
return state_dict
| 904 |
839 | <reponame>kimjand/cxf<filename>tools/corba/src/main/java/org/apache/cxf/tools/corba/utils/FileOutputStreamFactory.java
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.tools.corba.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class FileOutputStreamFactory implements OutputStreamFactory {
String dirName = "";
List<String> fileNames;
FileOutputStreamFactory parent;
public FileOutputStreamFactory() {
fileNames = new LinkedList<>();
}
public FileOutputStreamFactory(String dir) {
this(dir, null);
fileNames = new LinkedList<>();
}
public FileOutputStreamFactory(String dir, FileOutputStreamFactory p) {
dirName = dir;
if (dirName == null) {
dirName = "";
}
if ((!"".equals(dirName))
&& (!".".equals(dirName))) {
if (!dirName.endsWith(File.separator)) {
dirName += File.separator;
}
File file = new File(dirName);
//create directory
file.mkdirs();
}
parent = p;
}
public String getDirectoryName() {
return dirName;
}
private void addFileName(String name) {
fileNames.add(name);
if (parent != null) {
parent.addFileName(name);
}
}
private String getClassDirectory(String packageName) {
String result = convertPackageNameToDirectory(packageName);
if (!".".equals(dirName)) {
result = dirName + result;
}
return result;
}
private String convertPackageNameToDirectory(String packageName) {
int pos1 = 0;
int pos2 = packageName.indexOf('.', pos1);
StringBuilder result = new StringBuilder("");
while (pos2 != -1) {
result.append(packageName.substring(pos1, pos2)).append(File.separator);
pos1 = pos2 + 1;
pos2 = packageName.indexOf('.', pos1);
}
result.append(packageName.substring(pos1));
return result.toString();
}
public OutputStream createFakeOutputStream(String name)
throws IOException {
addFileName(name);
return new ByteArrayOutputStream();
}
public OutputStream createFakeOutputStream(String packageName, String name)
throws IOException {
String packageDirName = convertPackageNameToDirectory(packageName);
if ((!"".equals(packageDirName)) && (!packageDirName.endsWith(File.separator))) {
packageDirName += File.separator;
}
addFileName(packageDirName + name);
return new ByteArrayOutputStream();
}
public OutputStream createOutputStream(String packageName, String name)
throws IOException {
String packageDirName = convertPackageNameToDirectory(packageName);
if ((!"".equals(packageDirName)) && (!packageDirName.endsWith(File.separator))) {
packageDirName += File.separator;
}
String dname = packageDirName;
if (!".".equals(dirName)) {
dname = dirName + packageDirName;
}
if ((!"".equals(dname)) && (!".".equals(dname))) {
File file = new File(dname);
file.mkdirs();
}
addFileName(packageDirName + name);
return Files.newOutputStream(Paths.get(dname + name));
}
public OutputStream createOutputStream(String name)
throws IOException {
addFileName(name);
String dname = name;
if (!".".equals(dirName)) {
dname = dirName + name;
}
return Files.newOutputStream(Paths.get(dname));
}
public OutputStreamFactory createSubpackageOutputStreamFactory(String name)
throws IOException {
String dname = name;
if (!".".equals(dirName)) {
dname = dirName + name;
}
return new FileOutputStreamFactory(dname, this);
}
public Iterator<String> getStreamNames() throws IOException {
return fileNames.iterator();
}
public void clearStreams() {
fileNames.clear();
if (parent != null) {
parent.clearStreams();
}
}
public boolean isOutputStreamExists(String packageName, String name) {
String dname = getClassDirectory(packageName);
if ((!"".equals(dname)) && (!dname.endsWith(File.separator))) {
dname += File.separator;
}
File file = new File(dname + name);
return file.exists();
}
}
| 2,190 |
304 | """Load transformations from URDF files.
See :doc:`transform_manager` for more information.
"""
import os
import numpy as np
from bs4 import BeautifulSoup
from .transform_manager import TransformManager
from .transformations import transform_from, concat
from .rotations import (
active_matrix_from_extrinsic_roll_pitch_yaw, matrix_from_axis_angle,
norm_vector)
class UrdfTransformManager(TransformManager):
"""Transformation manager that can load URDF files.
URDF is the `Unified Robot Description Format <http://wiki.ros.org/urdf>`_.
URDF allows to define joints between links that can be rotated about one
axis. This transformation manager allows to set the joint angles after
joints have been added or loaded from an URDF.
.. warning::
Note that this module requires the Python package beautifulsoup4.
.. note::
Joint angles must be given in radians.
Parameters
----------
strict_check : bool, optional (default: True)
Raise a ValueError if the transformation matrix is not numerically
close enough to a real transformation matrix. Otherwise we print a
warning.
check : bool, optional (default: True)
Check if transformation matrices are valid and requested nodes exist,
which might significantly slow down some operations.
"""
def __init__(self, strict_check=True, check=True):
super(UrdfTransformManager, self).__init__(strict_check, check)
self._joints = {}
self.collision_objects = []
self.visuals = []
def add_joint(self, joint_name, from_frame, to_frame, child2parent, axis,
limits=(float("-inf"), float("inf")), joint_type="revolute"):
"""Add joint.
Parameters
----------
joint_name : str
Name of the joint
from_frame : Hashable
Child link of the joint
to_frame : Hashable
Parent link of the joint
child2parent : array-like, shape (4, 4)
Transformation from child to parent
axis : array-like, shape (3,)
Rotation axis of the joint (defined in the child frame)
limits : pair of float, optional (default: (-inf, inf))
Lower and upper joint angle limit
joint_type : str, optional (default: 'revolute')
Joint type: revolute or prismatic (continuous is the same as
revolute)
"""
self.add_transform(from_frame, to_frame, child2parent)
self._joints[joint_name] = (
from_frame, to_frame, child2parent, norm_vector(axis), limits,
joint_type)
def set_joint(self, joint_name, value):
"""Set joint position.
Note that joint values are clipped to their limits.
Parameters
----------
joint_name : str
Name of the joint
value : float
Joint angle in radians in case of revolute joints or position
in case of prismatic joint.
Raises
------
KeyError
If joint_name is unknown
"""
if joint_name not in self._joints:
raise KeyError("Joint '%s' is not known" % joint_name)
from_frame, to_frame, child2parent, axis, limits, joint_type = \
self._joints[joint_name]
# this is way faster than np.clip:
value = min(max(value, limits[0]), limits[1])
if joint_type == "revolute":
joint_rotation = matrix_from_axis_angle(
np.hstack((axis, (value,))))
joint2A = transform_from(
joint_rotation, np.zeros(3), strict_check=self.strict_check)
else:
assert joint_type == "prismatic"
joint_offset = value * axis
joint2A = transform_from(
np.eye(3), joint_offset, strict_check=self.strict_check)
self.add_transform(from_frame, to_frame, concat(
joint2A, child2parent, strict_check=self.strict_check,
check=self.check))
def get_joint_limits(self, joint_name):
"""Get limits of a joint.
Parameters
----------
joint_name : str
Name of the joint
Returns
-------
limits : pair of float
Lower and upper joint angle limit
Raises
------
KeyError
If joint_name is unknown
"""
if joint_name not in self._joints:
raise KeyError("Joint '%s' is not known" % joint_name)
return self._joints[joint_name][4]
def load_urdf(self, urdf_xml, mesh_path=None, package_dir=None):
"""Load URDF file into transformation manager.
Parameters
----------
urdf_xml : str
Robot definition in URDF
mesh_path : str, optional (default: None)
Path in which we search for meshes that are defined in the URDF.
Meshes will be ignored if it is set to None and no 'package_dir'
is given.
package_dir : str, optional (default: None)
Some URDFs start file names with 'package://' to refer to the ROS
package in which these files (textures, meshes) are located. This
variable defines to which path this prefix will be resolved.
"""
robot_name, links, joints = parse_urdf(
urdf_xml, mesh_path, package_dir, self.strict_check)
initialize_urdf_transform_manager(self, robot_name, links, joints)
def plot_visuals(self, frame, ax=None, ax_s=1, wireframe=False,
convex_hull_of_mesh=True, alpha=0.3): # pragma: no cover
"""Plot all visuals in a given reference frame.
Visuals can be boxes, spheres, cylinders, or meshes. Note that visuals
that cannot be connected to the reference frame are omitted.
Parameters
----------
frame : Hashable
Reference frame
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axis will be created
ax_s : float, optional (default: 1)
Scaling of the new matplotlib 3d axis
wireframe : bool, optional (default: False)
Plot wireframe (surface otherwise)
convex_hull_of_mesh : bool, optional (default: True)
Displays convex hull of meshes instead of the original mesh. This
makes plotting a lot faster with complex meshes.
alpha : float, optional (default: 0.3)
Alpha value of the surface / wireframe that will be plotted
Returns
-------
ax : Matplotlib 3d axis
New or old axis
"""
return self._plot_objects(
self.visuals, frame, ax, ax_s, wireframe, convex_hull_of_mesh,
alpha)
def plot_collision_objects(
self, frame, ax=None, ax_s=1, wireframe=True,
convex_hull_of_mesh=True, alpha=1.0): # pragma: no cover
"""Plot all collision objects in a given reference frame.
Collision objects can be boxes, spheres, cylinders, or meshes. Note
that collision objects that cannot be connected to the reference frame
are omitted.
Parameters
----------
frame : Hashable
Reference frame
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axis will be created
ax_s : float, optional (default: 1)
Scaling of the new matplotlib 3d axis
wireframe : bool, optional (default: True)
Plot wireframe (surface otherwise)
convex_hull_of_mesh : bool, optional (default: True)
Displays convex hull of meshes instead of the original mesh. This
makes plotting a lot faster with complex meshes.
alpha : float, optional (default: 1)
Alpha value of the surface / wireframe that will be plotted
Returns
-------
ax : Matplotlib 3d axis
New or old axis
"""
return self._plot_objects(
self.collision_objects, frame, ax, ax_s, wireframe,
convex_hull_of_mesh, alpha)
def _plot_objects(self, objects, frame, ax=None, ax_s=1, wireframe=True,
convex_hull_of_mesh=True, alpha=1.0): # pragma: no cover
"""Plot all objects in a given reference frame.
Objects can be boxes, spheres, cylinders, or meshes. Note that objects
that cannot be connected to the reference frame are omitted.
Parameters
----------
objects : list
Objects that will be plotted
frame : Hashable
Reference frame
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axis will be created
ax_s : float, optional (default: 1)
Scaling of the new matplotlib 3d axis
wireframe : bool, optional (default: True)
Plot wireframe (surface otherwise)
convex_hull_of_mesh : bool, optional (default: True)
Displays convex hull of meshes instead of the original mesh. This
makes plotting a lot faster with complex meshes.
alpha : float, optional (default: 1)
Alpha value of the surface / wireframe that will be plotted
Returns
-------
ax : Matplotlib 3d axis
New or old axis
"""
if ax is None:
from .plot_utils import make_3d_axis
ax = make_3d_axis(ax_s)
for obj in objects:
ax = obj.plot(
self, frame, ax, wireframe=wireframe,
convex_hull=convex_hull_of_mesh, alpha=alpha)
return ax
def parse_urdf(urdf_xml, mesh_path=None, package_dir=None, strict_check=True):
"""Parse information from URDF file.
Parameters
----------
urdf_xml : str
Robot definition in URDF
mesh_path : str, optional (default: None)
Path in which we search for meshes that are defined in the URDF.
Meshes will be ignored if it is set to None and no 'package_dir'
is given.
package_dir : str, optional (default: None)
Some URDFs start file names with 'package://' to refer to the ROS
package in which these files (textures, meshes) are located. This
variable defines to which path this prefix will be resolved.
strict_check : bool, optional (default: True)
Raise a ValueError if the transformation matrix is not numerically
close enough to a real transformation matrix. Otherwise we print a
warning.
Returns
-------
robot_name : str
Name of the robot
links : list of Link
Links of the robot
joints : list of Joint
Joints of the robot
Raises
------
UrdfException
If URDF is not valid
"""
urdf = BeautifulSoup(urdf_xml, "xml")
# URDF XML schema:
# https://github.com/ros/urdfdom/blob/master/xsd/urdf.xsd
robot = urdf.find("robot")
if robot is None:
raise UrdfException("Robot tag is missing.")
if not robot.has_attr("name"):
raise UrdfException("Attribute 'name' is missing in robot tag.")
robot_name = robot["name"]
materials = dict([
_parse_material(material)
for material in robot.findAll("material", recursive=False)])
links = [_parse_link(link, materials, mesh_path, package_dir, strict_check)
for link in robot.findAll("link", recursive=False)]
link_names = [link.name for link in links]
joints = [_parse_joint(joint, link_names, strict_check)
for joint in robot.findAll("joint", recursive=False)]
return robot_name, links, joints
def initialize_urdf_transform_manager(tm, robot_name, links, joints):
"""Initializes transform manager from previously parsed URDF data.
Parameters
----------
tm : UrdfTransformManager
Transform manager
robot_name : str
Name of the robot
links : list of Link
Links of the robot
joints : list of Joint
Joints of the robot
"""
tm.add_transform(links[0].name, robot_name, np.eye(4))
_add_links(tm, links)
_add_joints(tm, joints)
def _parse_material(material):
"""Parse material."""
if not material.has_attr("name"):
raise UrdfException("Material name is missing.")
colors = material.findAll("color")
if len(colors) not in [0, 1]:
raise UrdfException("More than one color is not allowed.")
if len(colors) == 1:
color = _parse_color(colors[0])
else:
color = None
# TODO texture is currently ignored
return material["name"], color
def _parse_color(color):
"""Parse color."""
if not color.has_attr("rgba"):
raise UrdfException("Attribute 'rgba' of color tag is missing.")
return np.fromstring(color["rgba"], sep=" ")
def _parse_link(link, materials, mesh_path, package_dir, strict_check):
"""Create link."""
if not link.has_attr("name"):
raise UrdfException("Link name is missing.")
result = Link()
result.name = link["name"]
visuals, visual_transforms = _parse_link_children(
link, "visual", materials, mesh_path, package_dir, strict_check)
result.visuals = visuals
result.transforms.extend(visual_transforms)
collision_objects, collision_object_transforms = _parse_link_children(
link, "collision", dict(), mesh_path, package_dir, strict_check)
result.collision_objects = collision_objects
result.transforms.extend(collision_object_transforms)
inertial = link.find("inertial")
if inertial is not None:
result.inertial_frame[:, :] = _parse_origin(inertial, strict_check)
result.mass = _parse_mass(inertial)
result.inertia[:, :] = _parse_inertia(inertial)
result.transforms.append(
("inertial_frame:%s" % result.name, result.name,
result.inertial_frame))
return result
def _parse_link_children(link, child_type, materials, mesh_path, package_dir,
strict_check):
"""Parse collision objects or visuals."""
children = link.findAll(child_type)
shape_objects = []
transforms = []
for i, child in enumerate(children):
if child.has_attr("name"):
name = "%s:%s/%s" % (child_type, link["name"], child["name"])
else:
name = "%s:%s/%s" % (child_type, link["name"], i)
color = None
if child_type == "visual":
material = child.find("material")
if material is not None:
material_name, color = _parse_material(material)
if color is None and material_name in materials:
color = materials[material_name]
child2link = _parse_origin(child, strict_check)
transforms.append((name, link["name"], child2link))
shape_objects.extend(_parse_geometry(
child, name, color, mesh_path, package_dir))
return shape_objects, transforms
def _parse_geometry(child, name, color, mesh_path, package_dir):
"""Parse geometric primitives (box, cylinder, sphere) or meshes."""
geometry = child.find("geometry")
if geometry is None:
raise UrdfException("Missing geometry tag in link '%s'" % name)
result = []
for shape_type in ["box", "cylinder", "sphere", "mesh"]:
shapes = geometry.findAll(shape_type)
Cls = shape_classes[shape_type]
for shape in shapes:
shape_object = Cls(
name, mesh_path=mesh_path, package_dir=package_dir,
color=color)
shape_object.parse(shape)
result.append(shape_object)
return result
def _parse_origin(entry, strict_check):
"""Parse transformation."""
origin = entry.find("origin")
translation = np.zeros(3)
rotation = np.eye(3)
if origin is not None:
if origin.has_attr("xyz"):
translation = np.fromstring(origin["xyz"], sep=" ")
if origin.has_attr("rpy"):
roll_pitch_yaw = np.fromstring(origin["rpy"], sep=" ")
# URDF and KDL use the active convention for rotation matrices.
# For more details on how the URDF parser handles the
# conversion from Euler angles, see this blog post:
# https://orbitalstation.wordpress.com/tag/quaternion/
rotation = active_matrix_from_extrinsic_roll_pitch_yaw(
roll_pitch_yaw)
return transform_from(
rotation, translation, strict_check=strict_check)
def _parse_mass(inertial):
"""Parse link mass."""
mass = inertial.find("mass")
if mass is not None and mass.has_attr("value"):
result = float(mass["value"])
else:
result = 0.0
return result
def _parse_inertia(inertial):
"""Parse inertia matrix."""
inertia = inertial.find("inertia")
result = np.zeros((3, 3))
if inertia is None:
return result
if inertia.has_attr("ixx"):
result[0, 0] = float(inertia["ixx"])
if inertia.has_attr("ixy"):
ixy = float(inertia["ixy"])
result[0, 1] = ixy
result[1, 0] = ixy
if inertia.has_attr("ixz"):
ixz = float(inertia["ixz"])
result[0, 2] = ixz
result[2, 0] = ixz
if inertia.has_attr("iyy"):
result[1, 1] = float(inertia["iyy"])
if inertia.has_attr("iyz"):
iyz = float(inertia["iyz"])
result[1, 2] = iyz
result[2, 1] = iyz
if inertia.has_attr("izz"):
result[2, 2] = float(inertia["izz"])
return result
def _parse_joint(joint, link_names, strict_check):
"""Create joint object."""
j = Joint()
if not joint.has_attr("name"):
raise UrdfException("Joint name is missing.")
j.joint_name = joint["name"]
if not joint.has_attr("type"):
raise UrdfException("Joint type is missing in joint '%s'."
% j.joint_name)
parent = joint.find("parent")
if parent is None:
raise UrdfException("No parent specified in joint '%s'"
% j.joint_name)
if not parent.has_attr("link"):
raise UrdfException("No parent link name given in joint '%s'."
% j.joint_name)
j.parent = parent["link"]
if j.parent not in link_names:
raise UrdfException("Parent link '%s' of joint '%s' is not "
"defined." % (j.parent, j.joint_name))
child = joint.find("child")
if child is None:
raise UrdfException("No child specified in joint '%s'"
% j.joint_name)
if not child.has_attr("link"):
raise UrdfException("No child link name given in joint '%s'."
% j.joint_name)
j.child = child["link"]
if j.child not in link_names:
raise UrdfException("Child link '%s' of joint '%s' is not "
"defined." % (j.child, j.joint_name))
j.joint_type = joint["type"]
if j.joint_type in ["planar", "floating"]:
raise UrdfException("Unsupported joint type '%s'" % j.joint_type)
if j.joint_type not in ["revolute", "continuous", "prismatic",
"fixed"]:
raise UrdfException("Joint type '%s' is not allowed in a URDF "
"document." % j.joint_type)
j.child2parent = _parse_origin(joint, strict_check)
j.joint_axis = np.array([1, 0, 0])
if j.joint_type in ["revolute", "continuous", "prismatic"]:
axis = joint.find("axis")
if axis is not None and axis.has_attr("xyz"):
j.joint_axis = np.fromstring(axis["xyz"], sep=" ")
j.limits = _parse_limits(joint)
return j
def _parse_limits(joint):
"""Parse joint limits."""
limit = joint.find("limit")
lower, upper = float("-inf"), float("inf")
if limit is not None:
if limit.has_attr("lower"):
lower = float(limit["lower"])
if limit.has_attr("upper"):
upper = float(limit["upper"])
return lower, upper
def _add_links(tm, links):
"""Add previously parsed links.
Parameters
----------
tm : UrdfTransformManager
Transform manager
links : list of Link
Joint information from URDF
"""
for link in links:
tm.visuals.extend(link.visuals)
tm.collision_objects.extend(link.collision_objects)
for from_frame, to_frame, transform in link.transforms:
tm.add_transform(from_frame, to_frame, transform)
def _add_joints(tm, joints):
"""Add previously parsed joints.
Parameters
----------
tm : UrdfTransformManager
Transform manager
joints : list of Joint
Joint information from URDF
"""
for joint in joints:
if joint.joint_type in ["revolute", "continuous"]:
tm.add_joint(
joint.joint_name, joint.child, joint.parent,
joint.child2parent, joint.joint_axis, joint.limits,
"revolute")
elif joint.joint_type == "prismatic":
tm.add_joint(
joint.joint_name, joint.child, joint.parent,
joint.child2parent, joint.joint_axis, joint.limits,
"prismatic")
else:
assert joint.joint_type == "fixed"
tm.add_transform(joint.child, joint.parent, joint.child2parent)
class Link(object):
"""Link from URDF file.
This class is only required temporarily while we parse the URDF.
Attributes
----------
name : str
Link name
visuals : list of Geometry
Visual geometries
collision_objects : list of Geometry
Geometries for collision calculation
transforms : list
Transformations given as tuples: name of frame A, name of frame B,
transform A2B
inertial_frame : array, shape (4, 4)
Pose of inertial frame with respect to the link
mass : float
Mass of the link
inertia : array, shape (3, 3)
Inertia matrix
"""
def __init__(self):
self.name = None
self.visuals = []
self.collision_objects = []
self.transforms = []
self.inertial_frame = np.eye(4)
self.mass = 0.0
self.inertia = np.zeros((3, 3))
class Joint(object):
"""Joint from URDF file.
This class is only required temporarily while we parse the URDF.
Attributes
----------
child : str
Name of the child
parent : str
Name of the parent frame
child2parent : array-like, shape (4, 4)
Transformation from child to parent
joint_name : str
Name of the joint that defines the transformation
joint_axis : array-like, shape (3,)
Rotation axis of the joint (defined in the child frame)
joint_type : str
Either 'fixed' or 'revolute'
limits : pair of float
Lower and upper joint angle limit
"""
def __init__(self):
self.child = None
self.parent = None
self.child2parent = np.eye(4)
self.joint_name = None
self.joint_axis = None
self.joint_type = "fixed"
self.limits = float("-inf"), float("inf")
class Geometry(object):
"""Geometrical object."""
def __init__(self, frame, mesh_path, package_dir, color):
self.frame = frame
self.mesh_path = mesh_path
self.package_dir = package_dir
self.color = color
def parse(self, xml):
"""Parse parameters of geometry."""
def plot(self, tm, frame, ax=None, alpha=0.3, wireframe=True,
convex_hull=True):
"""Plot geometry."""
class Box(Geometry):
"""Geometrical object: box."""
def __init__(self, frame, mesh_path, package_dir, color):
super(Box, self).__init__(frame, mesh_path, package_dir, color)
self.size = np.zeros(3)
def parse(self, xml):
"""Parse box size."""
if xml.has_attr("size"):
self.size[:] = np.fromstring(xml["size"], sep=" ")
def plot(self, tm, frame, ax=None, alpha=0.3, wireframe=True,
convex_hull=True): # pragma: no cover
"""Plot box."""
A2B = tm.get_transform(self.frame, frame)
color = self.color if self.color is not None else "k"
from .plot_utils import plot_box
return plot_box(
ax, self.size, A2B, wireframe=wireframe, alpha=alpha, color=color)
class Sphere(Geometry):
"""Geometrical object: sphere."""
def __init__(self, frame, mesh_path, package_dir, color):
super(Sphere, self).__init__(frame, mesh_path, package_dir, color)
self.radius = 0.0
def parse(self, xml):
"""Parse sphere radius."""
if not xml.has_attr("radius"):
raise UrdfException("Sphere has no radius.")
self.radius = float(xml["radius"])
def plot(self, tm, frame, ax=None, alpha=0.3, wireframe=True,
convex_hull=True): # pragma: no cover
"""Plot sphere."""
center = tm.get_transform(self.frame, frame)[:3, 3]
color = self.color if self.color is not None else "k"
from .plot_utils import plot_sphere
return plot_sphere(
ax, self.radius, center, wireframe=wireframe, alpha=alpha,
color=color)
class Cylinder(Geometry):
"""Geometrical object: cylinder."""
def __init__(self, frame, mesh_path, package_dir, color):
super(Cylinder, self).__init__(frame, mesh_path, package_dir, color)
self.radius = 0.0
self.length = 0.0
def parse(self, xml):
"""Parse cylinder radius and length."""
if not xml.has_attr("radius"):
raise UrdfException("Cylinder has no radius.")
self.radius = float(xml["radius"])
if not xml.has_attr("length"):
raise UrdfException("Cylinder has no length.")
self.length = float(xml["length"])
def plot(self, tm, frame, ax=None, alpha=0.3, wireframe=True,
convex_hull=True): # pragma: no cover
"""Plot cylinder."""
A2B = tm.get_transform(self.frame, frame)
color = self.color if self.color is not None else "k"
from .plot_utils import plot_cylinder
return plot_cylinder(
ax, self.length, self.radius, 0.0, A2B, wireframe=wireframe,
alpha=alpha, color=color)
class Mesh(Geometry):
"""Geometrical object: mesh."""
def __init__(self, frame, mesh_path, package_dir, color):
super(Mesh, self).__init__(frame, mesh_path, package_dir, color)
self.filename = None
self.scale = np.ones(3)
def parse(self, xml):
"""Parse mesh filename and scale."""
if self.mesh_path is None and self.package_dir is None:
self.filename = None
else:
if not xml.has_attr("filename"):
raise UrdfException("Mesh has no filename.")
if self.mesh_path is not None:
self.filename = os.path.join(self.mesh_path, xml["filename"])
else:
assert self.package_dir is not None
self.filename = xml["filename"].replace(
"package://", self.package_dir)
if xml.has_attr("scale"):
self.scale = np.fromstring(xml["scale"], sep=" ")
def plot(self, tm, frame, ax=None, alpha=0.3, wireframe=True,
convex_hull=True): # pragma: no cover
"""Plot mesh."""
from .plot_utils import plot_mesh
A2B = tm.get_transform(self.frame, frame)
color = self.color if self.color is not None else "k"
return plot_mesh(
ax, self.filename, A2B, self.scale, wireframe=wireframe,
convex_hull=convex_hull, alpha=alpha, color=color)
shape_classes = {"box": Box,
"sphere": Sphere,
"cylinder": Cylinder,
"mesh": Mesh}
class UrdfException(Exception):
"""Exception while parsing URDF files."""
| 12,031 |
389 | <reponame>tcmoore32/sheer-madness
/*
* Copyright 2014 <NAME>, Inc.
*/
package gw.lang.reflect.gs;
import java.util.List;
public class ReloadResults {
public enum ReloadStatus {
SUCCESS,
NOT_ATTEMPTED,
PARSE_FAILURE,
REDEFINE_REJECTED,
REDEFINE_ERROR,
OTHER_ERROR
}
private ReloadStatus _status;
private List<String> _classNames;
private String _errorMessage;
public ReloadResults(ReloadStatus status, List<String> classNames, String errorMessage) {
_status = status;
_classNames = classNames;
_errorMessage = errorMessage;
}
public ReloadStatus getStatus() {
return _status;
}
public List<String> getClassNames() {
return _classNames;
}
public String getErrorMessage() {
return _errorMessage;
}
}
| 280 |
1,932 | <filename>ch18-1/ch18-1-consumer/src/main/java/cn/springcloud/book/feign/HelloFeignService.java
package cn.springcloud.book.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author: xujin
**/
@FeignClient(name = "sc-producer")
public interface HelloFeignService {
@GetMapping("/hello/")
String hello(@RequestParam(value = "name") String name);
}
| 175 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/thumbnails/thumbnail_capture_driver.h"
#include "base/check_op.h"
// static
constexpr base::TimeDelta ThumbnailCaptureDriver::kCooldownDelay;
// static
constexpr size_t ThumbnailCaptureDriver::kMaxCooldownRetries;
ThumbnailCaptureDriver::ThumbnailCaptureDriver(Client* client,
ThumbnailScheduler* scheduler)
: client_(client), scheduler_(scheduler) {
scheduler_->AddTab(this);
}
ThumbnailCaptureDriver::~ThumbnailCaptureDriver() {
scheduler_->RemoveTab(this);
}
void ThumbnailCaptureDriver::UpdatePageReadiness(PageReadiness page_readiness) {
page_readiness_ = page_readiness;
UpdateSchedulingPriority();
UpdateCaptureState();
}
void ThumbnailCaptureDriver::UpdatePageVisibility(bool page_visible) {
page_visible_ = page_visible;
UpdateSchedulingPriority();
}
void ThumbnailCaptureDriver::UpdateThumbnailVisibility(bool thumbnail_visible) {
thumbnail_visible_ = thumbnail_visible;
UpdateSchedulingPriority();
}
void ThumbnailCaptureDriver::SetCanCapture(bool can_capture) {
can_capture_ = can_capture;
UpdateCaptureState();
}
void ThumbnailCaptureDriver::GotFrame() {
if (capture_state_ == CaptureState::kCooldown)
captured_cooldown_frame_ = true;
}
void ThumbnailCaptureDriver::SetCapturePermittedByScheduler(bool scheduled) {
scheduled_ = scheduled;
UpdateCaptureState();
}
void ThumbnailCaptureDriver::UpdateCaptureState() {
// If there was a final thumbnail but the page has changed, get set up
// for a new capture.
if (page_readiness_ < PageReadiness::kReadyForFinalCapture &&
capture_state_ == CaptureState::kHaveFinalCapture) {
client_->StopCapture();
capture_state_ = CaptureState::kNoCapture;
}
// If de-scheduled, stop any ongoing capture.
if (!scheduled_) {
client_->StopCapture();
if (capture_state_ < CaptureState::kHaveFinalCapture)
capture_state_ = CaptureState::kNoCapture;
return;
}
// Request to capture if we haven't done so.
if (capture_state_ < CaptureState::kCaptureRequested) {
client_->RequestCapture();
capture_state_ = CaptureState::kCaptureRequested;
}
// Wait until our client is able to capture.
if (!can_capture_) {
// It is possible we were actively capturing and the client reported
// it can no longer capture. Reset our state to re-request capture
// later.
capture_state_ = CaptureState::kCaptureRequested;
cooldown_timer_.AbandonAndStop();
return;
}
// The client is ready so start capturing. Continue below in case the
// page is fully loaded, in which case we will wrap things up
// immediately.
if (capture_state_ == CaptureState::kCaptureRequested) {
capture_state_ = CaptureState::kCapturing;
client_->StartCapture();
}
// If the page is finalized, enter cooldown if we haven't yet.
if (page_readiness_ == PageReadiness::kReadyForFinalCapture &&
capture_state_ == CaptureState::kCapturing) {
StartCooldown();
return;
}
// If the page is finalized and we are in cooldown capture mode, we
// don't need to do anything. The cooldown timer callback will
// finalize everything.
if (page_readiness_ == PageReadiness::kReadyForFinalCapture &&
capture_state_ == CaptureState::kCooldown) {
return;
}
// If we aren't actively capturing, we should've handled this above.
DCHECK_EQ(capture_state_, CaptureState::kCapturing)
<< "page_readiness_ = " << static_cast<int>(page_readiness_);
}
void ThumbnailCaptureDriver::UpdateSchedulingPriority() {
if (page_readiness_ == PageReadiness::kNotReady) {
scheduler_->SetTabCapturePriority(
this, ThumbnailScheduler::TabCapturePriority::kNone);
return;
}
// For now don't force-load background pages, or the current page if the
// thumbnail isn't being requested. This is not ideal. We would like to grab
// frames from background pages to make hover cards and the "Mohnstrudel"
// touch/tablet tabstrip more responsive by pre-loading thumbnails from those
// pages. However, this currently results in a number of test failures and a
// possible violation of an assumption made by the renderer.
// TODO(crbug.com/1073141): Figure out how to force-render background tabs.
// This bug has detailed descriptions of steps we might take to make capture
// more flexible in this area.
if (!thumbnail_visible_) {
scheduler_->SetTabCapturePriority(
this, ThumbnailScheduler::TabCapturePriority::kNone);
return;
}
// If the page is in its final state and we already have a good
// thumbnail, don't need to anything.
if (page_readiness_ == PageReadiness::kReadyForFinalCapture &&
capture_state_ == CaptureState::kHaveFinalCapture) {
scheduler_->SetTabCapturePriority(
this, ThumbnailScheduler::TabCapturePriority::kNone);
return;
}
if (page_readiness_ == PageReadiness::kReadyForInitialCapture) {
scheduler_->SetTabCapturePriority(
this, ThumbnailScheduler::TabCapturePriority::kLow);
return;
}
DCHECK_EQ(page_readiness_, PageReadiness::kReadyForFinalCapture);
scheduler_->SetTabCapturePriority(
this, ThumbnailScheduler::TabCapturePriority::kHigh);
}
void ThumbnailCaptureDriver::StartCooldown() {
DCHECK_EQ(page_readiness_, PageReadiness::kReadyForFinalCapture);
DCHECK_EQ(capture_state_, CaptureState::kCapturing);
capture_state_ = CaptureState::kCooldown;
captured_cooldown_frame_ = false;
cooldown_retry_count_ = 0U;
if (cooldown_timer_.IsRunning()) {
cooldown_timer_.Reset();
} else {
cooldown_timer_.Start(
FROM_HERE, kCooldownDelay,
base::BindRepeating(&ThumbnailCaptureDriver::OnCooldownEnded,
weak_ptr_factory_.GetWeakPtr()));
}
}
void ThumbnailCaptureDriver::OnCooldownEnded() {
if (capture_state_ < CaptureState::kCooldown)
return;
if (!captured_cooldown_frame_ &&
cooldown_retry_count_ < kMaxCooldownRetries) {
++cooldown_retry_count_;
cooldown_timer_.Reset();
return;
}
capture_state_ = CaptureState::kHaveFinalCapture;
client_->StopCapture();
scheduler_->SetTabCapturePriority(
this, ThumbnailScheduler::TabCapturePriority::kNone);
}
| 2,091 |
903 | #include "../../../src/gui/util/qsystemtrayicon_p.h"
| 24 |
562 | #include <packio/packio.h>
#if defined(PACKIO_STANDALONE_ASIO)
namespace net = ::asio;
#else // defined(PACKIO_STANDALONE_ASIO)
namespace net = ::boost::asio;
#endif // defined(PACKIO_STANDALONE_ASIO)
int main(int, char **) {
net::io_context io;
net::ip::tcp::endpoint bind_ep{net::ip::make_address("127.0.0.1"), 0};
auto server = packio::make_server(net::ip::tcp::acceptor{io, bind_ep});
auto client = packio::make_client(net::ip::tcp::socket{io});
return 0;
}
| 195 |
639 | //
// HZSessionTask.h
// HZNetwork
//
// Created by xzh. on 15/8/17.
// Copyright (c) 2015年 xzh. All rights reserved.
//
/**************** 具体的请求任务,配置参数,输出数据 ****************/
#import <Foundation/Foundation.h>
#import "HZNetworkConfig.h"
#import "HZNetworkConst.h"
#import "HZSessionTaskDelegate.h"
@class HZSessionTask;
NS_ASSUME_NONNULL_BEGIN
typedef void(^HZSessionTaskDidCompletedBlock)(HZSessionTask *task);
typedef void(^HZSessionTaskDidSendBlock)(HZSessionTask *task);
typedef void(^HZSessionTaskDidCancelBlock)(HZSessionTask *task);
typedef void(^HZSessionTaskUploadProgressBlock)(HZSessionTask *task, NSProgress *progress);
typedef NS_ENUM(NSUInteger, HZSessionTaskState) { //The execution state of the task.
HZSessionTaskStateRunable = 0, //Runable.
HZSessionTaskStateRunning = 1, //In execution.
HZSessionTaskStateCancel = 2, //Task cancled.
HZSessionTaskStateSuccess = 3, //Task is successful.
HZSessionTaskStateFail = 4, //Task failed.
};
typedef NS_ENUM(NSUInteger, HZSessionTaskCacheImportState) { //The importing state of cache.
HZSessionTaskCacheImportStateNone = 0, //Not imported, initial state.
HZSessionTaskCacheImportStateSuccess = 1, //The cache is imported successfully.
HZSessionTaskCacheImportStateFail = 2, //The cache is imported failed. May no cache exists or already impored cache.
};
/**
HZSessionTask represents the specific request task. You can use it to config parameters for request and get response data from it.
*/
@interface HZSessionTask : NSObject
/**
Creates and returns a task.
@param method The request method, currently only GET/POST is supported.
@param path The path of URL. e.g /GeniusBrother/HZExtend
@param params The parameters for http query string.
@param delegate The task's delegate object. You can get execution state of task by it.
@param taskIdentifier The UUID of task.
@return new instance of `HZSessionTask` with specified http parameters.
*/
+ (instancetype)taskWithMethod:(NSString *)method
path:(NSString *)path
params:(nullable NSDictionary<NSString *, id> *)params
delegate:(nullable id<HZSessionTaskDelegate>)delegate
taskIdentifier:(nullable NSString *)taskIdentifier;
/**
Creates and returns a task.
@param method The request method, currently only GET/POST is supported.
@param path The path of URL. e.g /user/:uid/book/:bookId
@param delegate The task's delegate object. You can get execution state of task by it.
@param taskIdentifier The UUID of task.
@param pathValues An array consists of path parameters.
@discussion If set the pathValues not empty, the path value will be appended to path. Like URL https://example.com/user/13/book/1005
@return new instance of `HZSessionTask` with specified http parameters.
*/
+ (instancetype)taskWithMethod:(NSString *)method
path:(NSString *)path
pathValues:(nullable NSArray<NSString *> *)pathValues
delegate:(nullable id<HZSessionTaskDelegate>)delegate
taskIdentifier:(nullable NSString *)taskIdentifier;
/**
Creates and returns a task.
@param method The request method, currently only GET/POST is supported.
@param URLString The URL for http execpt query string. e.g https://github.com/GeniusBrother/HZExtend
@param delegate The task's delegate object. You can get execution state of task by it.
@param taskIdentifier The UUID of task.
@return new instance of `HZSessionTask` with specified http parameters or nil if URLString is invalid.
*/
+ (nullable instancetype)taskWithMethod:(NSString *)method
URLString:(NSString *)URLString
params:(nullable NSDictionary<NSString *, id> *)params
delegate:(nullable id<HZSessionTaskDelegate>)delegate
taskIdentifier:(NSString *)taskIdentifier;
/**
Creates and returns a upload task.
@param path The path of URL.
@param params The parameters for http query string.
@param delegate The task's delegate object. You can get execution state of task by it.
@param taskIdentifier The UUID of task.
@return new instance of `HZSessionTask` with specified http parameters.
*/
+ (instancetype)uploadTaskWithPath:(NSString *)path
params:(nullable NSDictionary<NSString *, id> *)params
delegate:(nullable id<HZSessionTaskDelegate>)delegate
taskIdentifier:(NSString *)taskIdentifier;
/** UUID */
@property(nonatomic, copy, readonly) NSString *taskIdentifier;
/** execution state. */
@property(nonatomic, assign, readonly) HZSessionTaskState state;
/** Importing state of cache. */
@property(nonatomic, assign, readonly) HZSessionTaskCacheImportState cacheImportState;
/** Boolean value that indicates whether the task is executed for the first time. */
@property(nonatomic, assign, readonly) BOOL isFirstRequest;
/** The task's delegate object. You can get execution state of task by it. */
@property(nonatomic, weak) id<HZSessionTaskDelegate> delegate;
/** A block to be executed after completion of task. */
@property(nonatomic, copy) HZSessionTaskDidCompletedBlock taskDidCompletedBlock;
/** A block to be executed after sending task. */
@property(nonatomic, copy) HZSessionTaskDidSendBlock taskDidSendBlock;
/** A block to be executed after task is cancled. */
@property(nonatomic, copy) HZSessionTaskDidCancelBlock taskDidCancelBlock;
/** A block to be executed when the upload progress is updated. */
@property(nonatomic, copy) HZSessionTaskUploadProgressBlock uploadProgressBlock;
/**
The base URL of http URL. e.g https://www.github.com
@discussion Sets the baseURL config of `HZNetworkConfig` to base URL if it not sets.
*/
@property(nullable, nonatomic, copy) NSString *baseURL;
/** The path of http URL. e.g /GeniusBrother/HZExtend */
@property(nonatomic, copy) NSString *path;
/** The parameters for http. */
@property(nonatomic, strong) NSMutableDictionary<NSString *, id> *params;
/** The parameters for file when uploading file. */
@property(nullable, nonatomic, strong) NSMutableDictionary<NSString *, id> *fileParams;
/** The method for http. */
@property(nonatomic, copy, readonly) NSString *method;
/** The http header field. */
@property(nullable, nonatomic, readonly) NSDictionary <NSString *, NSString *> *requestHeader;
/**
The patheValues will replace path parameter
*/
@property(nullable, nonatomic, strong) NSMutableArray<NSString *> *pathValues;
/**
Boolean value that indicates whether the task should cache response data.
The default value is equal to [HZNetoworkConfig sharedConfig].taskShouldCache.
*/
@property(nonatomic, assign, getter=isCached) BOOL cached;
/**
If `YES`, only import cache once when task is executed more than once or import cache everytime.
The default value is `YES`.
*/
@property(nonatomic, assign) BOOL importCacheOnce;
/** The response data from remote. */
@property(nullable, nonatomic, strong, readonly) id responseObject;
/** The error of task. */
@property(nullable, nonatomic, strong, readonly) NSError *error;
/**
The tip message for task.
You should config key path of message that in response by HZNetworkConfig. see `HZNetworkConfig` for more information.
*/
@property(nullable, nonatomic, copy, readonly) NSString *message;
/** The absoluteURL of http. */
@property(nonatomic, copy) NSString *absoluteURL;
/** The target URL for http. */
@property(nonatomic, readonly) NSString *requestPath;
/**
Sets the value of the given HTTP header field.
@param value the header field value.
@param key the header field name.
*/
- (void)setValue:(NSString *)value forHeaderField:(NSString *)key;
/**
Peforms Task.
@param completion The block to be executed after completion of task.
@param didSend The block to be executed after sending task
*/
- (void)start;
- (void)startWithCompletion:(HZSessionTaskDidCompletedBlock)completion;
- (void)startWithCompletion:(HZSessionTaskDidCompletedBlock)completion
didSend:(nullable HZSessionTaskDidSendBlock)didSend;
/**
Peforms Task with handler.
@param handler The block to be executed before peforming task. The task will be intercepted if error not nil.
*/
- (void)startWithHandler:(nullable void(^)(HZSessionTask *task, NSError * _Nullable error))handler;
/**
Cancles task.
*/
- (void)cancel;
@end
NS_ASSUME_NONNULL_END
| 2,877 |
9,724 | <filename>tests/test_sigalrm.c
// Copyright 2015 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 <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <emscripten/emscripten.h>
void alarm_handler(int dummy) {
printf("Received alarm!\n");
emscripten_force_exit(0);
}
int main() {
if (signal(SIGALRM, alarm_handler) == SIG_ERR) {
printf("Error in signal()!\n");
return 1;
}
alarm(1);
// Make sure that we keep the runtime alive long enough
// to receive the alarm.
emscripten_exit_with_live_runtime();
__builtin_unreachable();
}
| 278 |
965 | pOutlookBar->EnableInPlaceEdit(TRUE);
pOutlookBar->EnableAnimation();
pOutlookBar->EnableScrollButtons();
pOutlookBar->SetBorderSize(10);
pOutlookBar->SetPageButtonTextAlign(TA_LEFT); | 63 |
305 | /*
* Copyright (c) 2015 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 "modules/video_processing/util/denoiser_filter_sse2.h"
#include <emmintrin.h>
#include <stdlib.h>
#include <string.h>
namespace webrtc {
static void Get8x8varSse2(const uint8_t* src,
int src_stride,
const uint8_t* ref,
int ref_stride,
unsigned int* sse,
int* sum) {
const __m128i zero = _mm_setzero_si128();
__m128i vsum = _mm_setzero_si128();
__m128i vsse = _mm_setzero_si128();
for (int i = 0; i < 8; i += 2) {
const __m128i src0 = _mm_unpacklo_epi8(
_mm_loadl_epi64((const __m128i*)(src + i * src_stride)), zero);
const __m128i ref0 = _mm_unpacklo_epi8(
_mm_loadl_epi64((const __m128i*)(ref + i * ref_stride)), zero);
const __m128i diff0 = _mm_sub_epi16(src0, ref0);
const __m128i src1 = _mm_unpacklo_epi8(
_mm_loadl_epi64((const __m128i*)(src + (i + 1) * src_stride)), zero);
const __m128i ref1 = _mm_unpacklo_epi8(
_mm_loadl_epi64((const __m128i*)(ref + (i + 1) * ref_stride)), zero);
const __m128i diff1 = _mm_sub_epi16(src1, ref1);
vsum = _mm_add_epi16(vsum, diff0);
vsum = _mm_add_epi16(vsum, diff1);
vsse = _mm_add_epi32(vsse, _mm_madd_epi16(diff0, diff0));
vsse = _mm_add_epi32(vsse, _mm_madd_epi16(diff1, diff1));
}
// sum
vsum = _mm_add_epi16(vsum, _mm_srli_si128(vsum, 8));
vsum = _mm_add_epi16(vsum, _mm_srli_si128(vsum, 4));
vsum = _mm_add_epi16(vsum, _mm_srli_si128(vsum, 2));
*sum = static_cast<int16_t>(_mm_extract_epi16(vsum, 0));
// sse
vsse = _mm_add_epi32(vsse, _mm_srli_si128(vsse, 8));
vsse = _mm_add_epi32(vsse, _mm_srli_si128(vsse, 4));
*sse = _mm_cvtsi128_si32(vsse);
}
static void VarianceSSE2(const unsigned char* src,
int src_stride,
const unsigned char* ref,
int ref_stride,
int w,
int h,
uint32_t* sse,
int64_t* sum,
int block_size) {
*sse = 0;
*sum = 0;
for (int i = 0; i < h; i += block_size) {
for (int j = 0; j < w; j += block_size) {
uint32_t sse0 = 0;
int32_t sum0 = 0;
Get8x8varSse2(src + src_stride * i + j, src_stride,
ref + ref_stride * i + j, ref_stride, &sse0, &sum0);
*sse += sse0;
*sum += sum0;
}
}
}
// Compute the sum of all pixel differences of this MB.
static uint32_t AbsSumDiff16x1(__m128i acc_diff) {
const __m128i k_1 = _mm_set1_epi16(1);
const __m128i acc_diff_lo =
_mm_srai_epi16(_mm_unpacklo_epi8(acc_diff, acc_diff), 8);
const __m128i acc_diff_hi =
_mm_srai_epi16(_mm_unpackhi_epi8(acc_diff, acc_diff), 8);
const __m128i acc_diff_16 = _mm_add_epi16(acc_diff_lo, acc_diff_hi);
const __m128i hg_fe_dc_ba = _mm_madd_epi16(acc_diff_16, k_1);
const __m128i hgfe_dcba =
_mm_add_epi32(hg_fe_dc_ba, _mm_srli_si128(hg_fe_dc_ba, 8));
const __m128i hgfedcba =
_mm_add_epi32(hgfe_dcba, _mm_srli_si128(hgfe_dcba, 4));
unsigned int sum_diff = abs(_mm_cvtsi128_si32(hgfedcba));
return sum_diff;
}
// TODO(jackychen): Optimize this function using SSE2.
void DenoiserFilterSSE2::CopyMem16x16(const uint8_t* src,
int src_stride,
uint8_t* dst,
int dst_stride) {
for (int i = 0; i < 16; i++) {
memcpy(dst, src, 16);
src += src_stride;
dst += dst_stride;
}
}
uint32_t DenoiserFilterSSE2::Variance16x8(const uint8_t* src,
int src_stride,
const uint8_t* ref,
int ref_stride,
uint32_t* sse) {
int64_t sum = 0;
VarianceSSE2(src, src_stride << 1, ref, ref_stride << 1, 16, 8, sse, &sum, 8);
return *sse - ((sum * sum) >> 7);
}
DenoiserDecision DenoiserFilterSSE2::MbDenoise(const uint8_t* mc_running_avg_y,
int mc_avg_y_stride,
uint8_t* running_avg_y,
int avg_y_stride,
const uint8_t* sig,
int sig_stride,
uint8_t motion_magnitude,
int increase_denoising) {
DenoiserDecision decision = FILTER_BLOCK;
unsigned int sum_diff_thresh = 0;
int shift_inc =
(increase_denoising && motion_magnitude <= kMotionMagnitudeThreshold) ? 1
: 0;
__m128i acc_diff = _mm_setzero_si128();
const __m128i k_0 = _mm_setzero_si128();
const __m128i k_4 = _mm_set1_epi8(4 + shift_inc);
const __m128i k_8 = _mm_set1_epi8(8);
const __m128i k_16 = _mm_set1_epi8(16);
// Modify each level's adjustment according to motion_magnitude.
const __m128i l3 = _mm_set1_epi8(
(motion_magnitude <= kMotionMagnitudeThreshold) ? 7 + shift_inc : 6);
// Difference between level 3 and level 2 is 2.
const __m128i l32 = _mm_set1_epi8(2);
// Difference between level 2 and level 1 is 1.
const __m128i l21 = _mm_set1_epi8(1);
for (int r = 0; r < 16; ++r) {
// Calculate differences.
const __m128i v_sig =
_mm_loadu_si128(reinterpret_cast<const __m128i*>(&sig[0]));
const __m128i v_mc_running_avg_y =
_mm_loadu_si128(reinterpret_cast<const __m128i*>(&mc_running_avg_y[0]));
__m128i v_running_avg_y;
const __m128i pdiff = _mm_subs_epu8(v_mc_running_avg_y, v_sig);
const __m128i ndiff = _mm_subs_epu8(v_sig, v_mc_running_avg_y);
// Obtain the sign. FF if diff is negative.
const __m128i diff_sign = _mm_cmpeq_epi8(pdiff, k_0);
// Clamp absolute difference to 16 to be used to get mask. Doing this
// allows us to use _mm_cmpgt_epi8, which operates on signed byte.
const __m128i clamped_absdiff =
_mm_min_epu8(_mm_or_si128(pdiff, ndiff), k_16);
// Get masks for l2 l1 and l0 adjustments.
const __m128i mask2 = _mm_cmpgt_epi8(k_16, clamped_absdiff);
const __m128i mask1 = _mm_cmpgt_epi8(k_8, clamped_absdiff);
const __m128i mask0 = _mm_cmpgt_epi8(k_4, clamped_absdiff);
// Get adjustments for l2, l1, and l0.
__m128i adj2 = _mm_and_si128(mask2, l32);
const __m128i adj1 = _mm_and_si128(mask1, l21);
const __m128i adj0 = _mm_and_si128(mask0, clamped_absdiff);
__m128i adj, padj, nadj;
// Combine the adjustments and get absolute adjustments.
adj2 = _mm_add_epi8(adj2, adj1);
adj = _mm_sub_epi8(l3, adj2);
adj = _mm_andnot_si128(mask0, adj);
adj = _mm_or_si128(adj, adj0);
// Restore the sign and get positive and negative adjustments.
padj = _mm_andnot_si128(diff_sign, adj);
nadj = _mm_and_si128(diff_sign, adj);
// Calculate filtered value.
v_running_avg_y = _mm_adds_epu8(v_sig, padj);
v_running_avg_y = _mm_subs_epu8(v_running_avg_y, nadj);
_mm_storeu_si128(reinterpret_cast<__m128i*>(running_avg_y),
v_running_avg_y);
// Adjustments <=7, and each element in acc_diff can fit in signed
// char.
acc_diff = _mm_adds_epi8(acc_diff, padj);
acc_diff = _mm_subs_epi8(acc_diff, nadj);
// Update pointers for next iteration.
sig += sig_stride;
mc_running_avg_y += mc_avg_y_stride;
running_avg_y += avg_y_stride;
}
// Compute the sum of all pixel differences of this MB.
unsigned int abs_sum_diff = AbsSumDiff16x1(acc_diff);
sum_diff_thresh =
increase_denoising ? kSumDiffThresholdHigh : kSumDiffThreshold;
if (abs_sum_diff > sum_diff_thresh)
decision = COPY_BLOCK;
return decision;
}
} // namespace webrtc
| 4,380 |
1,914 | <reponame>PuetzD/platform<filename>src/Administration/Resources/app/administration/src/module/sw-settings-delivery-times/snippet/en-GB.json<gh_stars>1000+
{
"global": {
"error-codes": {
"DELIVERY_TIME_MIN_INVALID": "The minimum value should not be higher than the maximum value."
}
},
"sw-settings-delivery-time": {
"general": {
"mainMenuItemGeneral": "Delivery times",
"description": "Settings module for managing delivery times",
"buttonCancel": "Cancel",
"buttonCreate": "Add delivery time",
"buttonSave": "Save",
"placeholder": "Search all delivery times..."
},
"list": {
"textHeadline": "Delivery times",
"columnName": "Name",
"columnUnit": "Unit",
"columnMin": "Minimum",
"columnMax": "Maximum",
"columnUnit_day": "Day",
"columnUnit_week": "Week",
"columnUnit_month": "Month",
"columnUnit_year": "Year",
"errorLoad": "Unable to load the delivery times list."
},
"detail": {
"textHeadlineNew": "New delivery time",
"labelName": "Name",
"labelUnit": "Unit",
"labelMin": "Minimum",
"labelMax": "Maximum",
"selectionUnitDay": "Day",
"selectionUnitWeek": "Week",
"selectionUnitMonth": "Month",
"selectionUnitYear": "Year",
"errorLoad": "Unable to load the delivery time.",
"errorSave": "The delivery time could not be saved."
}
},
"sw-privileges": {
"permissions": {
"delivery_times": {
"label": "Delivery times"
}
}
}
}
| 636 |
2,110 | #ifndef __NCPP_SUBPROC_HH
#define __NCPP_SUBPROC_HH
#include <notcurses/notcurses.h>
#include "Root.hh"
#include "Plane.hh"
#include "Widget.hh"
#include "Utilities.hh"
namespace ncpp
{
class NCPP_API_EXPORT Subproc : public Widget
{
public:
static ncsubproc_options default_options;
public:
explicit Subproc (Plane* plane, const char* bin, bool use_path = true,
char* const arg[] = nullptr, char* const env[] = nullptr,
ncfdplane_callback cbfxn = nullptr, ncfdplane_done_cb donecbfxn = nullptr)
: Subproc (plane, bin, nullptr, use_path, arg, env, cbfxn, donecbfxn)
{}
explicit Subproc (Plane* plane, const char* bin, const ncsubproc_options* opts, bool use_path = true,
char* const arg[] = nullptr, char* const env[] = nullptr,
ncfdplane_callback cbfxn = nullptr, ncfdplane_done_cb donecbfxn = nullptr)
: Widget (Utilities::get_notcurses_cpp (plane))
{
ensure_valid_plane (plane);
create_subproc (*plane, bin, opts, use_path, arg, env, cbfxn, donecbfxn);
take_plane_ownership (plane);
}
explicit Subproc (Plane& plane, const char* bin, bool use_path = true,
char* const arg[] = nullptr, char* const env[] = nullptr,
ncfdplane_callback cbfxn = nullptr, ncfdplane_done_cb donecbfxn = nullptr)
: Subproc (plane, bin, nullptr, use_path, arg, env, cbfxn, donecbfxn)
{}
explicit Subproc (Plane& plane, const char* bin, const ncsubproc_options* opts, bool use_path = true,
char* const arg[] = nullptr, char* const env[] = nullptr,
ncfdplane_callback cbfxn = nullptr, ncfdplane_done_cb donecbfxn = nullptr)
: Widget (Utilities::get_notcurses_cpp (plane))
{
ensure_valid_plane (plane);
create_subproc (plane, bin, opts, use_path, arg, env, cbfxn, donecbfxn);
take_plane_ownership (plane);
}
~Subproc ()
{
if (is_notcurses_stopped ())
return;
ncsubproc_destroy (subproc);
}
Plane* get_plane () const noexcept
{
return Plane::map_plane (ncsubproc_plane (subproc));
}
private:
void create_subproc (Plane& n, const char* bin, const ncsubproc_options* opts, bool use_path,
char* const arg[], char* const env[],
ncfdplane_callback cbfxn, ncfdplane_done_cb donecbfxn)
{
if (bin == nullptr)
throw invalid_argument ("'bin' must be a valid pointer");
if (opts == nullptr)
opts = &default_options;
if (use_path) {
if (env != nullptr) {
subproc = ncsubproc_createvpe (
n, opts, bin, arg, env, cbfxn, donecbfxn
);
} else {
subproc = ncsubproc_createvp (
n, opts, bin, arg, cbfxn, donecbfxn
);
}
} else {
subproc = ncsubproc_createv (
n, opts, bin, arg, cbfxn, donecbfxn
);
}
if (subproc == nullptr)
throw init_error ("Notcurses failed to create ncsubproc instance");
}
private:
ncsubproc *subproc;
};
}
#endif // __NCPP_SUBPROC_HH
| 1,410 |
14,668 | // Copyright 2015 The Crashpad 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 "util/string/split_string.h"
#include "gtest/gtest.h"
namespace crashpad {
namespace test {
namespace {
TEST(SplitString, SplitStringFirst) {
std::string left;
std::string right;
EXPECT_FALSE(SplitStringFirst("", '=', &left, &right));
EXPECT_FALSE(SplitStringFirst("no equals", '=', &left, &right));
EXPECT_FALSE(SplitStringFirst("=", '=', &left, &right));
EXPECT_FALSE(SplitStringFirst("=beginequals", '=', &left, &right));
ASSERT_TRUE(SplitStringFirst("a=b", '=', &left, &right));
EXPECT_EQ(left, "a");
EXPECT_EQ(right, "b");
ASSERT_TRUE(SplitStringFirst("EndsEquals=", '=', &left, &right));
EXPECT_EQ(left, "EndsEquals");
EXPECT_TRUE(right.empty());
ASSERT_TRUE(SplitStringFirst("key=VALUE", '=', &left, &right));
EXPECT_EQ(left, "key");
EXPECT_EQ(right, "VALUE");
EXPECT_FALSE(SplitStringFirst("a=b", '|', &left, &right));
ASSERT_TRUE(SplitStringFirst("ls | less", '|', &left, &right));
EXPECT_EQ(left, "ls ");
EXPECT_EQ(right, " less");
ASSERT_TRUE(SplitStringFirst("when in", ' ', &left, &right));
EXPECT_EQ(left, "when");
EXPECT_EQ(right, "in");
ASSERT_TRUE(SplitStringFirst("zoo", 'o', &left, &right));
EXPECT_EQ(left, "z");
EXPECT_EQ(right, "o");
ASSERT_FALSE(SplitStringFirst("ooze", 'o', &left, &right));
}
TEST(SplitString, SplitString) {
std::vector<std::string> parts;
parts = SplitString("", '.');
EXPECT_EQ(parts.size(), 0u);
parts = SplitString(".", '.');
ASSERT_EQ(parts.size(), 2u);
EXPECT_EQ(parts[0], "");
EXPECT_EQ(parts[1], "");
parts = SplitString("a,b", ',');
ASSERT_EQ(parts.size(), 2u);
EXPECT_EQ(parts[0], "a");
EXPECT_EQ(parts[1], "b");
parts = SplitString("zoo", 'o');
ASSERT_EQ(parts.size(), 3u);
EXPECT_EQ(parts[0], "z");
EXPECT_EQ(parts[1], "");
EXPECT_EQ(parts[2], "");
parts = SplitString("0x100,0x200,0x300,0x400,0x500,0x600", ',');
ASSERT_EQ(parts.size(), 6u);
EXPECT_EQ(parts[0], "0x100");
EXPECT_EQ(parts[1], "0x200");
EXPECT_EQ(parts[2], "0x300");
EXPECT_EQ(parts[3], "0x400");
EXPECT_EQ(parts[4], "0x500");
EXPECT_EQ(parts[5], "0x600");
}
} // namespace
} // namespace test
} // namespace crashpad
| 1,088 |
6,660 | #
# This file is part of the LibreOffice project.
#
# 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/.
#
# This file incorporates work covered by the following license notice:
#
# 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 .
#
import uno
import traceback
from unohelper import systemPathToFileUrl, absolutize
from ..common.Desktop import Desktop
from ..common.SystemDialog import SystemDialog
from com.sun.star.awt import WindowDescriptor
from com.sun.star.awt import Rectangle
from com.sun.star.awt.WindowClass import TOP
from com.sun.star.task import ErrorCodeIOException
#Window Constants
com_sun_star_awt_WindowAttribute_BORDER \
= uno.getConstantByName( "com.sun.star.awt.WindowAttribute.BORDER" )
com_sun_star_awt_WindowAttribute_SIZEABLE \
= uno.getConstantByName( "com.sun.star.awt.WindowAttribute.SIZEABLE" )
com_sun_star_awt_WindowAttribute_MOVEABLE \
= uno.getConstantByName( "com.sun.star.awt.WindowAttribute.MOVEABLE" )
com_sun_star_awt_VclWindowPeerAttribute_CLIPCHILDREN \
= uno.getConstantByName(
"com.sun.star.awt.VclWindowPeerAttribute.CLIPCHILDREN" )
class OfficeDocument(object):
'''Creates a new instance of OfficeDocument '''
def __init__(self, _xMSF):
self.xMSF = _xMSF
@classmethod
def attachEventCall(self, xComponent, EventName, EventType, EventURL):
try:
oEventProperties = list(range(2))
oEventProperties[0] = uno.createUnoStruct(
'com.sun.star.beans.PropertyValue')
oEventProperties[0].Name = "EventType"
oEventProperties[0].Value = EventType
# "Service", "StarBasic"
oEventProperties[1] = uno.createUnoStruct(
'com.sun.star.beans.PropertyValue')
oEventProperties[1].Name = "Script" #"URL";
oEventProperties[1].Value = EventURL
uno.invoke(xComponent.Events, "replaceByName",
(EventName, uno.Any("[]com.sun.star.beans.PropertyValue",
tuple(oEventProperties))))
except Exception:
traceback.print_exc()
def dispose(self, xMSF, xComponent):
try:
if xComponent is not None:
xFrame = xComponent.CurrentController.Frame
if xComponent.isModified():
xComponent.setModified(False)
Desktop.dispatchURL(xMSF, ".uno:CloseDoc", xFrame)
except Exception:
traceback.print_exc()
@classmethod
def createNewFrame(self, xMSF, listener, FrameName="_blank"):
xFrame = None
if FrameName.lower() == "WIZARD_LIVE_PREVIEW".lower():
xFrame = self.createNewPreviewFrame(xMSF, listener)
else:
xF = Desktop.getDesktop(xMSF)
xFrame = xF.findFrame(FrameName, 0)
if listener is not None:
xFF = xF.getFrames()
xFF.remove(xFrame)
xF.addTerminateListener(listener)
return xFrame
@classmethod
def createNewPreviewFrame(self, xMSF, listener):
xToolkit = None
try:
xToolkit = xMSF.createInstance("com.sun.star.awt.Toolkit")
except Exception:
# TODO Auto-generated catch block
traceback.print_exc()
#describe the window and its properties
aDescriptor = WindowDescriptor()
aDescriptor.Type = TOP
aDescriptor.WindowServiceName = "window"
aDescriptor.ParentIndex = -1
aDescriptor.Parent = None
aDescriptor.Bounds = Rectangle(10, 10, 640, 480)
#Set Window Attributes
gnDefaultWindowAttributes = \
com_sun_star_awt_WindowAttribute_BORDER + \
com_sun_star_awt_WindowAttribute_MOVEABLE + \
com_sun_star_awt_WindowAttribute_SIZEABLE + \
com_sun_star_awt_VclWindowPeerAttribute_CLIPCHILDREN
aDescriptor.WindowAttributes = gnDefaultWindowAttributes
#create a new blank container window
xPeer = None
try:
xPeer = xToolkit.createWindow(aDescriptor)
except Exception:
traceback.print_exc()
#define some further properties of the frame window
#if it's needed .-)
#xPeer->setBackground(...);
#create new empty frame and set window on it
xFrame = None
try:
xFrame = xMSF.createInstance("com.sun.star.frame.Frame")
except Exception:
traceback.print_exc()
xFrame.initialize(xPeer)
#from now this frame is usable ...
#and not part of the desktop tree.
#You are alone with him .-)
if listener is not None:
Desktop.getDesktop(xMSF).addTerminateListener(listener)
return xFrame
@classmethod
def load(self, xInterface, sURL, sFrame, xValues):
xComponent = None
try:
if not sURL.startswith("file://"):
sURL = systemPathToFileUrl(sURL)
xComponent = xInterface.loadComponentFromURL(
sURL, sFrame, 0, tuple(xValues))
except Exception:
traceback.print_exc()
return xComponent
@classmethod
def store(self, xMSF, xComponent, StorePath, FilterName):
try:
if len(FilterName):
oStoreProperties = list(range(2))
oStoreProperties[0] = uno.createUnoStruct(
'com.sun.star.beans.PropertyValue')
oStoreProperties[0].Name = "FilterName"
oStoreProperties[0].Value = FilterName
oStoreProperties[1] = uno.createUnoStruct(
'com.sun.star.beans.PropertyValue')
oStoreProperties[1].Name = "InteractionHandler"
oStoreProperties[1].Value = xMSF.createInstance(
"com.sun.star.comp.uui.UUIInteractionHandler")
else:
oStoreProperties = list(range(0))
StorePath = systemPathToFileUrl(StorePath)
sPath = StorePath[:(StorePath.rfind("/") + 1)]
sFile = StorePath[(StorePath.rfind("/") + 1):]
xComponent.storeToURL(
absolutize(sPath, sFile), tuple(oStoreProperties))
return True
except ErrorCodeIOException:
#Throw this exception when trying to save a file
#which is already opened in Libreoffice
#TODO: handle it properly
return True
pass
except Exception:
traceback.print_exc()
return False
def close(self, xComponent):
bState = False
if xComponent is not None:
try:
xComponent.close(True)
bState = True
except Exception:
print ("could not close doc")
bState = False
else:
bState = True
return bState
def showMessageBox(
self, xMSF, windowServiceName, windowAttribute, MessageText):
return SystemDialog.showMessageBox(
xMSF, windowServiceName, windowAttribute, MessageText)
| 3,437 |
575 | <gh_stars>100-1000
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.tab;
import android.graphics.Bitmap;
import org.chromium.components.find_in_page.FindMatchRectsDetails;
import org.chromium.components.find_in_page.FindNotificationDetails;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.NavigationHandle;
import org.chromium.net.NetError;
import org.chromium.url.GURL;
/**
* An implementation of the {@link TabObserver} which has empty implementations of all methods.
*
* Note: Do not replace this with TabObserver with default interface methods as it inadvertently
* bloats the number of methods. See https://crbug.com/781359.
*/
public class EmptyTabObserver implements TabObserver {
@Override
public void onInitialized(Tab tab, String appId) {}
@Override
public void onShown(Tab tab, @TabSelectionType int type) {}
@Override
public void onHidden(Tab tab, @TabHidingType int reason) {}
@Override
public void onClosingStateChanged(Tab tab, boolean closing) {}
@Override
public void onDestroyed(Tab tab) {}
@Override
public void onContentChanged(Tab tab) {}
@Override
public void onLoadUrl(Tab tab, LoadUrlParams params, int loadType) {}
@Override
public void onPageLoadStarted(Tab tab, GURL url) {}
@Override
public void onPageLoadFinished(Tab tab, GURL url) {}
@Override
public void onPageLoadFailed(Tab tab, @NetError int errorCode) {}
@Override
public void onRestoreStarted(Tab tab) {}
@Override
public void onRestoreFailed(Tab tab) {}
@Override
public void onFaviconUpdated(Tab tab, Bitmap icon) {}
@Override
public void onTitleUpdated(Tab tab) {}
@Override
public void onUrlUpdated(Tab tab) {}
@Override
public void onSSLStateUpdated(Tab tab) {}
@Override
public void onCrash(Tab tab) {}
@Override
public void webContentsWillSwap(Tab tab) {}
@Override
public void onWebContentsSwapped(Tab tab, boolean didStartLoad, boolean didFinishLoad) {}
@Override
public void onContextMenuShown(Tab tab) {}
@Override
public void onCloseContents(Tab tab) {}
@Override
public void onLoadStarted(Tab tab, boolean toDifferentDocument) {}
@Override
public void onLoadStopped(Tab tab, boolean toDifferentDocument) {}
@Override
public void onLoadProgressChanged(Tab tab, float progress) {}
@Override
public void onUpdateUrl(Tab tab, GURL url) {}
@Override
public void onDidFailLoad(Tab tab, boolean isMainFrame, int errorCode, GURL failingUrl) {}
@Override
public void onDidStartNavigation(Tab tab, NavigationHandle navigationHandle) {}
@Override
public void onDidRedirectNavigation(Tab tab, NavigationHandle navigationHandle) {}
@Override
public void onDidFinishNavigation(Tab tab, NavigationHandle navigationHandle) {}
@Override
public void didFirstVisuallyNonEmptyPaint(Tab tab) {}
@Override
public void onDidChangeThemeColor(Tab tab, int color) {}
@Override
public void onBackgroundColorChanged(Tab tab, int color) {}
@Override
public void onInteractabilityChanged(Tab tab, boolean isInteractable) {}
@Override
public void onRendererResponsiveStateChanged(Tab tab, boolean isResponsive) {}
@Override
public void onNavigationEntriesDeleted(Tab tab) {}
@Override
public void onFindResultAvailable(FindNotificationDetails result) {}
@Override
public void onFindMatchRectsAvailable(FindMatchRectsDetails result) {}
@Override
public void onBrowserControlsOffsetChanged(Tab tab, int topControlsOffsetY,
int bottomControlsOffsetY, int contentOffsetY, int topControlsMinHeightOffsetY,
int bottomControlsMinHeightOffsetY) {}
@Override
public void onContentViewScrollingStateChanged(boolean scrolling) {}
}
| 1,295 |
440 | <filename>demo-rollup/package.json<gh_stars>100-1000
{
"name": "leaflet-control-geocoder-demo-rollup",
"private": true,
"scripts": {
"build": "rollup --config"
},
"dependencies": {
"leaflet": "^1.5.1",
"leaflet-control-geocoder": "^1.8.0"
},
"devDependencies": {
"rollup": "^1.14.4",
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-node-resolve": "^5.0.1"
}
}
| 195 |
347 | <filename>frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/widget/table/column/CommentColumn.java
package org.ovirt.engine.ui.webadmin.widget.table.column;
import org.ovirt.engine.core.common.businessentities.Commented;
import org.ovirt.engine.ui.common.widget.table.column.AbstractTextColumn;
/**
* Column that renders getComment() of a Commented.
*
* @param <T> row type, must implement Commented
*/
public class CommentColumn<T extends Commented> extends AbstractTextColumn<T> {
/**
* Using some row value of type T extends Commented, simply get the comment.
*
* @see com.google.gwt.user.cellview.client.Column#getValue(java.lang.Object)
*/
@Override
public String getValue(T value) {
if (value != null && value.getComment() != null && !value.getComment().isEmpty()) {
return value.getComment();
}
return null;
}
}
| 329 |
370 | <filename>src/main/java/com/vitco/app/core/data/AnimationData.java
package com.vitco.app.core.data;
import com.threed.jpct.SimpleVector;
import com.vitco.app.core.data.container.ExtendedLine;
import com.vitco.app.core.data.container.ExtendedVector;
import com.vitco.app.core.data.container.Frame;
import com.vitco.app.core.data.history.BasicActionIntent;
import com.vitco.app.core.data.history.HistoryChangeListener;
import com.vitco.app.core.data.history.HistoryManager;
import com.vitco.app.settings.VitcoSettings;
import java.util.ArrayList;
/**
* Implements all functions defined in the AnimationDataInterface
*/
public abstract class AnimationData extends GeneralData implements AnimationDataInterface {
// constructor
protected AnimationData() {
super();
// notify when the data changes
historyManagerA.addChangeListener(new HistoryChangeListener<BasicActionIntent>() {
@Override
public final void onChange(BasicActionIntent action) {
invalidateA();
}
@Override
public void onFrozenIntent(BasicActionIntent actionIntent) {
notifier.onFrozenAction();
}
@Override
public void onFrozenApply() {
notifier.onFrozenRedo();
}
@Override
public void onFrozenUnapply() {
notifier.onFrozenUndo();
}
});
}
// invalidate cache
protected final void invalidateA() {
lineBufferValid = false;
pointBufferValid = false;
frameBufferValid = false;
notifier.onAnimationDataChanged();
}
// history manager
protected final HistoryManager<BasicActionIntent> historyManagerA = new HistoryManager<BasicActionIntent>();
// ###################### PRIVATE HELPER CLASSES
// "add point" intent
private class AddPointIntent extends BasicActionIntent {
private final ExtendedVector point;
// constructor
public AddPointIntent(ExtendedVector point, boolean attach) {
super(attach);
this.point = point;
}
@Override
protected void applyAction() {
dataContainer.points.put(point.id, point);
}
@Override
protected void unapplyAction() {
dataContainer.points.remove(point.id);
dataContainer.pointsToLines.remove(point.id);
}
}
// "remove point" intent
private class RemovePointIntent extends BasicActionIntent {
private final Integer pointId;
private ExtendedVector point;
// constructor
public RemovePointIntent(Integer pointId, boolean attach) {
super(attach);
this.pointId = pointId;
}
@Override
protected void applyAction() {
if (isFirstCall()) {
// dc all lines that include this point
if ( dataContainer.pointsToLines.containsKey(pointId)) {
ExtendedLine[] lines = new ExtendedLine[ dataContainer.pointsToLines.get(pointId).size()];
dataContainer.pointsToLines.get(pointId).toArray(lines);
for (ExtendedLine line : lines) {
historyManagerA.applyIntent(new DisconnectIntent(line.point1, line.point2, true));
}
}
// delete this points in all frames
for (Integer frameId : dataContainer.frames.keySet()) {
if ( dataContainer.frames.get(frameId).getPoint(pointId) != null) {
historyManagerA.applyIntent(new RemoveFramePointIntent(pointId, frameId, true));
}
}
// store point
point = dataContainer.points.get(pointId);
}
dataContainer.pointsToLines.remove(pointId);
dataContainer.points.remove(pointId);
}
@Override
protected void unapplyAction() {
dataContainer.points.put(point.id, point);
}
}
// "move point" intent
private class MovePointIntent extends BasicActionIntent {
private final Integer pointId;
private final ExtendedVector point;
private ExtendedVector previousPoint;
// constructor
public MovePointIntent(Integer pointId, SimpleVector pos, boolean attach) {
super(attach);
this.pointId = pointId;
this.point = new ExtendedVector(pos, pointId);
}
@Override
protected void applyAction() {
if (isFirstCall()) {
previousPoint = dataContainer.points.get(pointId);
}
dataContainer.points.put(pointId, point);
}
@Override
protected void unapplyAction() {
if (previousPoint != null) {
dataContainer.points.put(pointId, previousPoint);
} else {
dataContainer.points.remove(pointId);
}
}
}
// "connect two points with a line" intent
private class ConnectIntent extends BasicActionIntent {
private final Integer pointId1;
private final Integer pointId2;
// constructor
public ConnectIntent(Integer pointId1, Integer pointId2, boolean attach) {
super(attach);
this.pointId1 = Math.min(pointId1, pointId2);
this.pointId2 = Math.max(pointId1, pointId2);
}
@Override
protected void applyAction() {
ExtendedLine line = new ExtendedLine(pointId1, pointId2);
dataContainer.lines.put(pointId1 + "_" + pointId2, line);
// make sure the pointToLines is initialized
if (! dataContainer.pointsToLines.containsKey(pointId1)) {
dataContainer.pointsToLines.put(pointId1, new ArrayList<ExtendedLine>());
}
if (! dataContainer.pointsToLines.containsKey(pointId2)) {
dataContainer.pointsToLines.put(pointId2, new ArrayList<ExtendedLine>());
}
dataContainer.pointsToLines.get(pointId1).add(line);
dataContainer.pointsToLines.get(pointId2).add(line);
}
@Override
protected void unapplyAction() {
ExtendedLine line = dataContainer.lines.get(pointId1 + "_" + pointId2);
dataContainer.lines.remove(pointId1 + "_" + pointId2);
// make sure the pointToLines is initialized
if (! dataContainer.pointsToLines.containsKey(pointId1)) {
dataContainer.pointsToLines.put(pointId1, new ArrayList<ExtendedLine>());
}
if (! dataContainer.pointsToLines.containsKey(pointId2)) {
dataContainer.pointsToLines.put(pointId2, new ArrayList<ExtendedLine>());
}
dataContainer.pointsToLines.get(pointId1).remove(line);
dataContainer.pointsToLines.get(pointId2).remove(line);
}
}
// "disconnect two points" intent
private class DisconnectIntent extends BasicActionIntent {
private final Integer pointId1;
private final Integer pointId2;
// constructor
public DisconnectIntent(Integer pointId1, Integer pointId2, boolean attach) {
super(attach);
this.pointId1 = Math.min(pointId1, pointId2);
this.pointId2 = Math.max(pointId1, pointId2);
}
@Override
protected void applyAction() {
ExtendedLine line = dataContainer.lines.get(pointId1 + "_" + pointId2);
dataContainer.lines.remove(pointId1 + "_" + pointId2);
// make sure the pointToLines is initialized
if (! dataContainer.pointsToLines.containsKey(pointId1)) {
dataContainer.pointsToLines.put(pointId1, new ArrayList<ExtendedLine>());
}
if (! dataContainer.pointsToLines.containsKey(pointId2)) {
dataContainer.pointsToLines.put(pointId2, new ArrayList<ExtendedLine>());
}
dataContainer.pointsToLines.get(pointId1).remove(line);
dataContainer.pointsToLines.get(pointId2).remove(line);
}
@Override
protected void unapplyAction() {
ExtendedLine line = new ExtendedLine(pointId1, pointId2);
dataContainer.lines.put(pointId1 + "_" + pointId2, line);
// make sure the pointToLines is initialized
if (! dataContainer.pointsToLines.containsKey(pointId1)) {
dataContainer.pointsToLines.put(pointId1, new ArrayList<ExtendedLine>());
}
if (! dataContainer.pointsToLines.containsKey(pointId2)) {
dataContainer.pointsToLines.put(pointId2, new ArrayList<ExtendedLine>());
}
dataContainer.pointsToLines.get(pointId1).add(line);
dataContainer.pointsToLines.get(pointId2).add(line);
}
}
// "clear everything (animation data)" intent
private class ClearAIntent extends BasicActionIntent {
// constructor
public ClearAIntent(boolean attach) {
super(attach);
}
@Override
protected void applyAction() {
// remove all points (attach)
if (isFirstCall()) { // delete all points of this frame
Integer[] pointIds = new Integer[ dataContainer.points.size()];
dataContainer.points.keySet().toArray(pointIds);
for (Integer pointId : pointIds) {
historyManagerA.applyIntent(new RemovePointIntent(pointId, true));
}
}
}
@Override
protected void unapplyAction() {
// nothing to do
}
}
// "create frame" intent
private class CreateFrameIntent extends BasicActionIntent {
private final Integer frameId;
private final String frameName;
// constructor
public CreateFrameIntent(Integer frameId, String frameName, boolean attach) {
super(attach);
this.frameId = frameId;
this.frameName = frameName;
}
@Override
protected void applyAction() {
dataContainer.frames.put(frameId, new Frame(frameName));
}
@Override
protected void unapplyAction() {
dataContainer.frames.remove(frameId);
}
}
// "delete frame" intent
private class DeleteFrameIntent extends BasicActionIntent {
private final Integer frameId;
private String frameName;
// constructor
public DeleteFrameIntent(Integer frameId, boolean attach) {
super(attach);
this.frameId = frameId;
}
@Override
protected void applyAction() {
if (isFirstCall()) {
// delete all points of this frame
Frame frameRef = dataContainer.frames.get(frameId);
for (Integer pointId : frameRef.getPoints()) {
historyManagerA.applyIntent(new RemoveFramePointIntent(pointId, frameId, true));
}
if ( dataContainer.activeFrame == frameId) { // make sure the frameId is still valid
historyManagerA.applyIntent(new SetActiveFrameIntent(-1, true));
}
// get the frame name
frameName = frameRef.getName();
}
dataContainer.frames.remove(frameId);
}
@Override
protected void unapplyAction() {
dataContainer.frames.put(frameId, new Frame(frameName));
}
}
// "reset frame" intent
private class ResetFrameIntent extends BasicActionIntent {
private final Integer frameId;
// constructor
public ResetFrameIntent(Integer frameId, boolean attach) {
super(attach);
this.frameId = frameId;
}
@Override
protected void applyAction() {
if (isFirstCall()) {
Frame frameRef = dataContainer.frames.get(frameId);
for (Integer pointId : frameRef.getPoints()) {
historyManagerA.applyIntent(new RemoveFramePointIntent(pointId, frameId, true));
}
}
}
@Override
protected void unapplyAction() {
// nothing to do here
}
}
// "rename frame" intent
private class RenameFrameIntent extends BasicActionIntent {
private final Integer frameId;
private final String frameName;
private String oldFrameName;
// constructor
public RenameFrameIntent(Integer frameId, String frameName, boolean attach) {
super(attach);
this.frameId = frameId;
this.frameName = frameName;
}
@Override
protected void applyAction() {
if (isFirstCall()) {
oldFrameName = dataContainer.frames.get(frameId).getName();
}
dataContainer.frames.get(frameId).setName(frameName);
}
@Override
protected void unapplyAction() {
dataContainer.frames.get(frameId).setName(oldFrameName);
}
}
// "place frame point" intent
private class PlaceFramePointIntent extends BasicActionIntent {
private final ExtendedVector point;
private final Integer frameId;
private ExtendedVector oldPoint;
// constructor
public PlaceFramePointIntent(Integer pointId, SimpleVector pos, Integer frameId, boolean attach) {
super(attach);
this.point = new ExtendedVector(pos, pointId);
this.frameId = frameId;
}
@Override
protected void applyAction() {
Frame frameRef = dataContainer.frames.get(frameId);
if (isFirstCall()) {
oldPoint = frameRef.getPoint(point.id);
}
frameRef.setPoint(point.id, point);
}
@Override
protected void unapplyAction() {
if (oldPoint != null) {
dataContainer.frames.get(frameId).setPoint(oldPoint.id, oldPoint);
} else {
dataContainer.frames.get(frameId).removePoint(point.id);
}
}
}
// "remove frame point" intent
private class RemoveFramePointIntent extends BasicActionIntent {
private final Integer pointId;
private final Integer frameId;
private ExtendedVector oldPoint;
// constructor
public RemoveFramePointIntent(Integer pointId, Integer frameId, boolean attach) {
super(attach);
this.pointId = pointId;
this.frameId = frameId;
}
@Override
protected void applyAction() {
Frame frameRef = dataContainer.frames.get(frameId);
if (isFirstCall()) {
oldPoint = frameRef.getPoint(pointId);
}
frameRef.removePoint(pointId);
}
@Override
protected void unapplyAction() {
dataContainer.frames.get(frameId).setPoint(oldPoint.id, oldPoint);
}
}
// "set active frame" intent
private class SetActiveFrameIntent extends BasicActionIntent {
private final Integer frameId;
private Integer oldFrameId;
// constructor
public SetActiveFrameIntent(Integer frameId, boolean attach) {
super(attach);
this.frameId = frameId;
}
@Override
protected void applyAction() {
if (isFirstCall()) {
oldFrameId = dataContainer.activeFrame;
}
dataContainer.activeFrame = frameId;
}
@Override
protected void unapplyAction() {
dataContainer.activeFrame = oldFrameId;
}
}
// ###################### PRIVATE HELPER FUNCTIONS
// returns a free point id
private int lastPoint = -1;
private int getFreePointId() {
do {
lastPoint++;
} while (dataContainer.points.containsKey(lastPoint));
return lastPoint;
}
// returns a free frame id
private int lastFrame = -1;
private int getFreeFrameId() {
do {
lastFrame++;
} while (dataContainer.frames.containsKey(lastFrame));
return lastFrame;
}
// =========================
// === interface methods ===
// =========================
@Override
public final boolean isValid(int pointId) {
synchronized (VitcoSettings.SYNC) {
return dataContainer.points.containsKey(pointId);
}
}
@Override
public final int addPoint(SimpleVector position) {
synchronized (VitcoSettings.SYNC) {
int pointId = getFreePointId();
ExtendedVector point = new ExtendedVector(position.x, position.y, position.z, pointId);
historyManagerA.applyIntent(new AddPointIntent(point, false));
return pointId;
}
}
@Override
public final boolean removePoint(int pointId) {
synchronized (VitcoSettings.SYNC) {
boolean result = false;
if (isValid(pointId)) {
historyManagerA.applyIntent(new RemovePointIntent(pointId, false));
result = true;
}
return result;
}
}
@Override
public final boolean movePoint(int pointId, SimpleVector pos) {
synchronized (VitcoSettings.SYNC) {
boolean result = false;
if (isValid(pointId)) {
if (dataContainer.activeFrame == -1) { // move real point
historyManagerA.applyIntent(new MovePointIntent(pointId, pos, false));
} else { // move frame point
historyManagerA.applyIntent(new PlaceFramePointIntent(pointId, pos, dataContainer.activeFrame, false));
}
result = true;
}
return result;
}
}
@Override
public final boolean areConnected(int id1, int id2) {
synchronized (VitcoSettings.SYNC) {
return dataContainer.lines.containsKey(Math.min(id1, id2) + "_" + Math.max(id1, id2));
}
}
@Override
public final boolean connect(int id1, int id2) {
synchronized (VitcoSettings.SYNC) {
boolean result = false;
if (isValid(id1) && isValid(id2) && !areConnected(id1, id2)) {
historyManagerA.applyIntent(new ConnectIntent(id1, id2, false));
result = true;
}
return result;
}
}
@Override
public final boolean clearA() {
synchronized (VitcoSettings.SYNC) {
boolean result = false;
if (dataContainer.points.size() > 0) {
historyManagerA.applyIntent(new ClearAIntent(false));
result = true;
}
return result;
}
}
@Override
public final boolean disconnect(int id1, int id2) {
synchronized (VitcoSettings.SYNC) {
boolean result = false;
if (isValid(id1) && isValid(id2) && areConnected(id1, id2)) {
historyManagerA.applyIntent(new DisconnectIntent(id1, id2, false));
result = true;
}
return result;
}
}
@Override
public final ExtendedVector getPoint(int pointId) {
synchronized (VitcoSettings.SYNC) {
if (dataContainer.activeFrame != -1) { // return frame point if defined
ExtendedVector point = dataContainer.frames.get(dataContainer.activeFrame).getPoint(pointId);
if (point != null) {
return point;
}
}
return dataContainer.points.get(pointId);
}
}
private ExtendedVector[] pointBuffer = new ExtendedVector[]{};
private boolean pointBufferValid = false;
@Override
public final ExtendedVector[] getPoints() {
synchronized (VitcoSettings.SYNC) {
if (!pointBufferValid) {
if (pointBuffer.length != dataContainer.points.size()) {
pointBuffer = new ExtendedVector[dataContainer.points.size()];
}
int i = 0;
for (int pointId : dataContainer.points.keySet()) {
pointBuffer[i++] = getPoint(pointId);
}
pointBufferValid = true;
}
return pointBuffer.clone();
}
}
private ExtendedVector[][] lineBuffer = new ExtendedVector[][]{};
private boolean lineBufferValid = false;
@Override
public final ExtendedVector[][] getLines() {
synchronized (VitcoSettings.SYNC) {
if (!lineBufferValid) {
if (lineBuffer.length != dataContainer.lines.size()) {
lineBuffer = new ExtendedVector[dataContainer.lines.size()][2];
}
int i = 0;
for (ExtendedLine line : dataContainer.lines.values()) {
lineBuffer[i][0] = getPoint(line.point1);
lineBuffer[i][1] = getPoint(line.point2);
i++;
}
lineBufferValid = true;
}
return lineBuffer.clone();
}
}
@Override
public final void undoA() {
synchronized (VitcoSettings.SYNC) {
historyManagerA.unapply();
}
}
@Override
public final void redoA() {
synchronized (VitcoSettings.SYNC) {
historyManagerA.apply();
}
}
@Override
public final boolean canUndoA() {
synchronized (VitcoSettings.SYNC) {
return historyManagerA.canUndo();
}
}
@Override
public final boolean canRedoA() {
synchronized (VitcoSettings.SYNC) {
return historyManagerA.canRedo();
}
}
@Override
public final boolean selectFrame(int frameId) {
synchronized (VitcoSettings.SYNC) {
boolean result = false;
if (dataContainer.frames.containsKey(frameId) || frameId == -1) {
historyManagerA.applyIntent(new SetActiveFrameIntent(frameId, false));
result = true;
}
return result;
}
}
@Override
public final int getSelectedFrame() {
synchronized (VitcoSettings.SYNC) {
return dataContainer.activeFrame;
}
}
@Override
public final int createFrame(String frameName) {
synchronized (VitcoSettings.SYNC) {
int frameId = getFreeFrameId();
historyManagerA.applyIntent(new CreateFrameIntent(frameId, frameName, false));
return frameId;
}
}
@Override
public final boolean deleteFrame(int frameId) {
synchronized (VitcoSettings.SYNC) {
boolean result = false;
if (dataContainer.frames.containsKey(frameId)) {
historyManagerA.applyIntent(new DeleteFrameIntent(frameId, false));
result = true;
}
return result;
}
}
@Override
public final boolean renameFrame(int frameId, String newName) {
synchronized (VitcoSettings.SYNC) {
boolean result = false;
if (dataContainer.frames.containsKey(frameId)) {
historyManagerA.applyIntent(new RenameFrameIntent(frameId, newName, false));
result = true;
}
return result;
}
}
private Integer[] frameBuffer = new Integer[]{};
private boolean frameBufferValid = false;
@Override
public final Integer[] getFrames() {
synchronized (VitcoSettings.SYNC) {
if (!frameBufferValid) {
if (frameBuffer.length != dataContainer.frames.size()) {
frameBuffer = new Integer[dataContainer.frames.size()];
}
dataContainer.frames.keySet().toArray(frameBuffer);
frameBufferValid = true;
}
return frameBuffer.clone();
}
}
@Override
public final boolean resetFrame(int frameId) {
synchronized (VitcoSettings.SYNC) {
boolean result = false;
if (dataContainer.frames.containsKey(frameId)) {
historyManagerA.applyIntent(new ResetFrameIntent(frameId, false));
result = true;
}
return result;
}
}
@Override
public final String getFrameName(int frameId) {
synchronized (VitcoSettings.SYNC) {
if (dataContainer.frames.containsKey(frameId)) {
return dataContainer.frames.get(frameId).getName();
}
return null;
}
}
} | 11,327 |
630 | package org.elasticsearch.river.mongodb.embed;
import java.io.IOException;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.config.IMongodConfig;
import de.flapdoodle.embed.process.config.IRuntimeConfig;
import de.flapdoodle.embed.process.distribution.Distribution;
import de.flapdoodle.embed.process.extract.IExtractedFileSet;
public class TokuMongodExecutable extends MongodExecutable {
public TokuMongodExecutable(Distribution distribution, IMongodConfig mongodConfig, IRuntimeConfig runtimeConfig, IExtractedFileSet files) {
super(distribution, mongodConfig, runtimeConfig, files);
}
@Override
protected MongodProcess start(Distribution distribution, IMongodConfig config, IRuntimeConfig runtime) throws IOException {
return new TokuMongodProcess(distribution, config, runtime, this);
}
}
| 302 |
3,012 | <filename>MdeModulePkg/Include/Guid/ConsoleOutDevice.h
/** @file
This GUID can be installed to the device handle to specify that the device is the console-out device.
Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef __CONSOLE_OUT_DEVICE_H__
#define __CONSOLE_OUT_DEVICE_H__
#define EFI_CONSOLE_OUT_DEVICE_GUID \
{ 0xd3b36f2c, 0xd551, 0x11d4, {0x9a, 0x46, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d } }
extern EFI_GUID gEfiConsoleOutDeviceGuid;
#endif
| 247 |
852 | #include "RecoParticleFlow/PFProducer/interface/BlockElementLinkerBase.h"
#include "DataFormats/ParticleFlowReco/interface/PFCluster.h"
#include "DataFormats/ParticleFlowReco/interface/PFBlockElementCluster.h"
#include "DataFormats/ParticleFlowReco/interface/PFBlockElementTrack.h"
#include "RecoParticleFlow/PFClusterTools/interface/LinkByRecHit.h"
class TrackAndTrackLinker : public BlockElementLinkerBase {
public:
TrackAndTrackLinker(const edm::ParameterSet& conf)
: BlockElementLinkerBase(conf),
useKDTree_(conf.getParameter<bool>("useKDTree")),
debug_(conf.getUntrackedParameter<bool>("debug", false)) {}
bool linkPrefilter(const reco::PFBlockElement*, const reco::PFBlockElement*) const override;
double testLink(const reco::PFBlockElement*, const reco::PFBlockElement*) const override;
private:
bool useKDTree_, debug_;
};
DEFINE_EDM_PLUGIN(BlockElementLinkerFactory, TrackAndTrackLinker, "TrackAndTrackLinker");
bool TrackAndTrackLinker::linkPrefilter(const reco::PFBlockElement* e1, const reco::PFBlockElement* e2) const {
return (e1->isLinkedToDisplacedVertex() || e2->isLinkedToDisplacedVertex());
}
double TrackAndTrackLinker::testLink(const reco::PFBlockElement* elem1, const reco::PFBlockElement* elem2) const {
constexpr reco::PFBlockElement::TrackType T_TO_DISP = reco::PFBlockElement::T_TO_DISP;
constexpr reco::PFBlockElement::TrackType T_FROM_DISP = reco::PFBlockElement::T_FROM_DISP;
double dist = -1.0;
const reco::PFDisplacedTrackerVertexRef& ni1_TO_DISP = elem1->displacedVertexRef(T_TO_DISP);
const reco::PFDisplacedTrackerVertexRef& ni2_TO_DISP = elem2->displacedVertexRef(T_TO_DISP);
const reco::PFDisplacedTrackerVertexRef& ni1_FROM_DISP = elem1->displacedVertexRef(T_FROM_DISP);
const reco::PFDisplacedTrackerVertexRef& ni2_FROM_DISP = elem2->displacedVertexRef(T_FROM_DISP);
if (ni1_TO_DISP.isNonnull() && ni2_FROM_DISP.isNonnull())
if (ni1_TO_DISP == ni2_FROM_DISP) {
dist = 1.0;
}
if (ni1_FROM_DISP.isNonnull() && ni2_TO_DISP.isNonnull())
if (ni1_FROM_DISP == ni2_TO_DISP) {
dist = 1.0;
}
if (ni1_FROM_DISP.isNonnull() && ni2_FROM_DISP.isNonnull())
if (ni1_FROM_DISP == ni2_FROM_DISP) {
dist = 1.0;
}
if (elem1->trackType(reco::PFBlockElement::T_FROM_GAMMACONV) &&
elem2->trackType(reco::PFBlockElement::T_FROM_GAMMACONV)) {
for (const auto& conv1 : elem1->convRefs()) {
for (const auto& conv2 : elem2->convRefs()) {
if (conv1.isNonnull() && conv2.isNonnull() && conv1 == conv2) {
dist = 1.0;
break;
}
}
}
}
if (elem1->trackType(reco::PFBlockElement::T_FROM_V0) && elem2->trackType(reco::PFBlockElement::T_FROM_V0)) {
if (elem1->V0Ref().isNonnull() && elem2->V0Ref().isNonnull()) {
if (elem1->V0Ref() == elem2->V0Ref()) {
dist = 1.0;
}
}
}
return dist;
}
| 1,220 |
311 | <reponame>ProgPassion/the-c-programming-language-exercise-answers
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include "lookup.h"
#define LEN 1000
static struct item *htable[LEN];
static char *strdup2(char *s) {
char *p = (char *) malloc(strlen(s) + 1);
if (p != NULL) {
strcpy(p, s);
}
return p;
}
static unsigned hash(char *name) {
unsigned val;
for(val = 0; *name != '\0'; name++) {
val = *name + 31 * val;
}
return val % LEN;
}
struct item *lookup(char *name) {
unsigned hashval = hash(name);
struct item *itemp;
for (itemp = htable[hashval]; itemp != NULL; itemp = itemp->next) {
if (strcmp(name, itemp->name) == 0) {
return itemp;
}
}
return NULL;
}
struct item *install(char *name, char *value) {
struct item *itemp;
if ((itemp = lookup(name)) == NULL) {
itemp = (struct item *) malloc(sizeof(struct item));
if (itemp == NULL) {
return NULL;
}
if ((itemp->name = strdup2(name)) == NULL) {
free((void *) itemp);
return NULL;
}
unsigned hashval = hash(name);
itemp->next = htable[hashval];
htable[hashval] = itemp;
} else {
free((void *) itemp->value);
}
if ((itemp->value = strdup2(value)) == NULL) {
return NULL;
}
return itemp;
}
void undef(char *name) {
unsigned hashval = hash(name);
struct item *itemp;
struct item *previtemp;
for (itemp = htable[hashval]; itemp != NULL; previtemp = itemp, itemp = itemp->next) {
if (strcmp(name, itemp->name) == 0) {
if (previtemp == NULL) {
htable[hashval] = itemp->next;
} else {
previtemp->next = itemp->next;
}
free(itemp->name);
free(itemp->value);
free(itemp);
}
}
}
| 756 |
19,628 | package com.didichuxing.foundation.net.rpc.http;
import com.didichuxing.doraemonkit.DoKit;
import com.didichuxing.doraemonkit.constant.DoKitModule;
import com.didichuxing.doraemonkit.kit.core.DoKitManager;
import com.didichuxing.doraemonkit.kit.core.DokitAbility;
import com.didichuxing.doraemonkit.kit.network.rpc.AbsDoKitRpcInterceptor;
import com.didichuxing.doraemonkit.kit.network.rpc.RpcCapInterceptor;
import com.didichuxing.doraemonkit.kit.network.rpc.RpcMockInterceptor;
import com.didichuxing.doraemonkit.kit.network.rpc.RpcWeakNetworkInterceptor;
import com.didichuxing.doraemonkit.util.ReflectUtils;
import java.util.ArrayList;
import java.util.List;
import didihttp.DidiHttpClient;
import didihttp.Interceptor;
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2019-12-13-10:40
* 描 述:用来通过ASM在编译器进行hook
* 修订历史:
* ================================================
*/
public class DidiHttpHook {
/**
* 添加 didi 的拦截器 通过字节码插入
*/
public static void addRpcIntercept(DidiHttpClient client) {
if (!DoKit.isInit()) {
return;
}
try {
List<Interceptor> interceptors = new ArrayList<>(client.interceptors());
List<Interceptor> networkInterceptors = new ArrayList<>(client.networkInterceptors());
DokitAbility.DokitModuleProcessor processor = DoKitManager.INSTANCE.getModuleProcessor(DoKitModule.MODULE_RPC_MC);
if (processor != null) {
Object interceptor = processor.values().get("rpc_interceptor");
if (interceptor instanceof AbsDoKitRpcInterceptor) {
noDuplicateAdd(interceptors, (AbsDoKitRpcInterceptor) interceptor);
}
}
noDuplicateAdd(interceptors, new RpcMockInterceptor());
noDuplicateAdd(interceptors, new RpcCapInterceptor());
noDuplicateAdd(networkInterceptors, new RpcWeakNetworkInterceptor());
//需要用反射重新赋值 因为源码中创建了一个不可变的list
ReflectUtils.reflect(client).field("interceptors", interceptors);
ReflectUtils.reflect(client).field("networkInterceptors", networkInterceptors);
} catch (Exception e) {
e.printStackTrace();
}
}
//list判断是否重复添加
private static void noDuplicateAdd(List<Interceptor> interceptors, AbsDoKitRpcInterceptor interceptor) {
boolean hasInterceptor = false;
for (Interceptor i : interceptors) {
if (i instanceof AbsDoKitRpcInterceptor) {
if (((AbsDoKitRpcInterceptor) i).getTAG().equals(interceptor.getTAG())) {
hasInterceptor = true;
break;
}
}
}
if (!hasInterceptor) {
interceptors.add(interceptor);
}
}
}
| 1,364 |
32,544 | <reponame>DBatOWL/tutorials
package com.baeldung.networking.cookies;
import java.net.*;
public class ProxyAcceptCookiePolicy implements CookiePolicy {
String acceptedProxy;
public ProxyAcceptCookiePolicy(String acceptedProxy) {
this.acceptedProxy = acceptedProxy;
}
public boolean shouldAccept(URI uri, HttpCookie cookie) {
String host;
try {
host = InetAddress.getByName(uri.getHost()).getCanonicalHostName();
} catch (UnknownHostException e) {
host = uri.getHost();
}
if (HttpCookie.domainMatches(acceptedProxy, host)) {
return true;
}
return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);
}
}
| 303 |
6,424 | <reponame>vmoens/tutorials
"""
`Introduction <introyt1_tutorial.html>`_ ||
`Tensors <tensors_deeper_tutorial.html>`_ ||
`Autograd <autogradyt_tutorial.html>`_ ||
`Building Models <modelsyt_tutorial.html>`_ ||
`TensorBoard Support <tensorboardyt_tutorial.html>`_ ||
**Training Models** ||
`Model Understanding <captumyt.html>`_
Training with PyTorch
=====================
Follow along with the video below or on `youtube <https://www.youtube.com/watch?v=jF43_wj_DCQ>`__.
.. raw:: html
<div style="margin-top:10px; margin-bottom:10px;">
<iframe width="560" height="315" src="https://www.youtube.com/embed/jF43_wj_DCQ" frameborder="0" allow="accelerometer; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
Introduction
------------
In past videos, we’ve discussed and demonstrated:
- Building models with the neural network layers and functions of the torch.nn module
- The mechanics of automated gradient computation, which is central to
gradient-based model training
- Using TensorBoard to visualize training progress and other activities
In this video, we’ll be adding some new tools to your inventory:
- We’ll get familiar with the dataset and dataloader abstractions, and how
they ease the process of feeding data to your model during a training loop
- We’ll discuss specific loss functions and when to use them
- We’ll look at PyTorch optimizers, which implement algorithms to adjust
model weights based on the outcome of a loss function
Finally, we’ll pull all of these together and see a full PyTorch
training loop in action.
Dataset and DataLoader
----------------------
The ``Dataset`` and ``DataLoader`` classes encapsulate the process of
pulling your data from storage and exposing it to your training loop in
batches.
The ``Dataset`` is responsible for accessing and processing single
instances of data.
The ``DataLoader`` pulls instances of data from the ``Dataset`` (either
automatically or with a sampler that you define), collects them in
batches, and returns them for consumption by your training loop. The
``DataLoader`` works with all kinds of datasets, regardless of the type
of data they contain.
For this tutorial, we’ll be using the Fashion-MNIST dataset provided by
TorchVision. We use ``torchvision.transforms.Normalize()`` to
zero-center and normalize the distribution of the image tile content,
and download both training and validation data splits.
"""
import torch
import torchvision
import torchvision.transforms as transforms
# PyTorch TensorBoard support
from torch.utils.tensorboard import SummaryWriter
from datetime import datetime
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# Create datasets for training & validation, download if necessary
training_set = torchvision.datasets.FashionMNIST('./data', train=True, transform=transform, download=True)
validation_set = torchvision.datasets.FashionMNIST('./data', train=False, transform=transform, download=True)
# Create data loaders for our datasets; shuffle for training, not for validation
training_loader = torch.utils.data.DataLoader(training_set, batch_size=4, shuffle=True, num_workers=2)
validation_loader = torch.utils.data.DataLoader(validation_set, batch_size=4, shuffle=False, num_workers=2)
# Class labels
classes = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot')
# Report split sizes
print('Training set has {} instances'.format(len(training_set)))
print('Validation set has {} instances'.format(len(validation_set)))
######################################################################
# As always, let’s visualize the data as a sanity check:
#
import matplotlib.pyplot as plt
import numpy as np
# Helper function for inline image display
def matplotlib_imshow(img, one_channel=False):
if one_channel:
img = img.mean(dim=0)
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
if one_channel:
plt.imshow(npimg, cmap="Greys")
else:
plt.imshow(np.transpose(npimg, (1, 2, 0)))
dataiter = iter(training_loader)
images, labels = dataiter.next()
# Create a grid from the images and show them
img_grid = torchvision.utils.make_grid(images)
matplotlib_imshow(img_grid, one_channel=True)
print(' '.join(classes[labels[j]] for j in range(4)))
#########################################################################
# The Model
# ---------
#
# The model we’ll use in this example is a variant of LeNet-5 - it should
# be familiar if you’ve watched the previous videos in this series.
#
import torch.nn as nn
import torch.nn.functional as F
# PyTorch models inherit from torch.nn.Module
class GarmentClassifier(nn.Module):
def __init__(self):
super(GarmentClassifier, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 4 * 4, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 4 * 4)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
model = GarmentClassifier()
##########################################################################
# Loss Function
# -------------
#
# For this example, we’ll be using a cross-entropy loss. For demonstration
# purposes, we’ll create batches of dummy output and label values, run
# them through the loss function, and examine the result.
#
loss_fn = torch.nn.CrossEntropyLoss()
# NB: Loss functions expect data in batches, so we're creating batches of 4
# Represents the model's confidence in each of the 10 classes for a given input
dummy_outputs = torch.rand(4, 10)
# Represents the correct class among the 10 being tested
dummy_labels = torch.tensor([1, 5, 3, 7])
print(dummy_outputs)
print(dummy_labels)
loss = loss_fn(dummy_outputs, dummy_labels)
print('Total loss for this batch: {}'.format(loss.item()))
#################################################################################
# Optimizer
# ---------
#
# For this example, we’ll be using simple `stochastic gradient
# descent <https://pytorch.org/docs/stable/optim.html>`__ with momentum.
#
# It can be instructive to try some variations on this optimization
# scheme:
#
# - Learning rate determines the size of the steps the optimizer
# takes. What does a different learning rate do to the your training
# results, in terms of accuracy and convergence time?
# - Momentum nudges the optimizer in the direction of strongest gradient over
# multiple steps. What does changing this value do to your results?
# - Try some different optimization algorithms, such as averaged SGD, Adagrad, or
# Adam. How do your results differ?
#
# Optimizers specified in the torch.optim package
optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
#######################################################################################
# The Training Loop
# -----------------
#
# Below, we have a function that performs one training epoch. It
# enumerates data from the DataLoader, and on each pass of the loop does
# the following:
#
# - Gets a batch of training data from the DataLoader
# - Zeros the optimizer’s gradients
# - Performs an inference - that is, gets predictions from the model for an input batch
# - Calculates the loss for that set of predictions vs. the labels on the dataset
# - Calculates the backward gradients over the learning weights
# - Tells the optimizer to perform one learning step - that is, adjust the model’s
# learning weights based on the observed gradients for this batch, according to the
# optimization algorithm we chose
# - It reports on the loss for every 1000 batches.
# - Finally, it reports the average per-batch loss for the last
# 1000 batches, for comparison with a validation run
#
def train_one_epoch(epoch_index, tb_writer):
running_loss = 0.
last_loss = 0.
# Here, we use enumerate(training_loader) instead of
# iter(training_loader) so that we can track the batch
# index and do some intra-epoch reporting
for i, data in enumerate(training_loader):
# Every data instance is an input + label pair
inputs, labels = data
# Zero your gradients for every batch!
optimizer.zero_grad()
# Make predictions for this batch
outputs = model(inputs)
# Compute the loss and its gradients
loss = loss_fn(outputs, labels)
loss.backward()
# Adjust learning weights
optimizer.step()
# Gather data and report
running_loss += loss.item()
if i % 1000 == 999:
last_loss = running_loss / 1000 # loss per batch
print(' batch {} loss: {}'.format(i + 1, last_loss))
tb_x = epoch_index * len(training_loader) + i + 1
tb_writer.add_scalar('Loss/train', last_loss, tb_x)
running_loss = 0.
return last_loss
##################################################################################
# Per-Epoch Activity
# ~~~~~~~~~~~~~~~~~~
#
# There are a couple of things we’ll want to do once per epoch:
#
# - Perform validation by checking our relative loss on a set of data that was not
# used for training, and report this
# - Save a copy of the model
#
# Here, we’ll do our reporting in TensorBoard. This will require going to
# the command line to start TensorBoard, and opening it in another browser
# tab.
#
# Initializing in a separate cell so we can easily add more epochs to the same run
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
writer = SummaryWriter('runs/fashion_trainer_{}'.format(timestamp))
epoch_number = 0
EPOCHS = 5
best_vloss = 1_000_000.
for epoch in range(EPOCHS):
print('EPOCH {}:'.format(epoch_number + 1))
# Make sure gradient tracking is on, and do a pass over the data
model.train(True)
avg_loss = train_one_epoch(epoch_number, writer)
# We don't need gradients on to do reporting
model.train(False)
running_vloss = 0.0
for i, vdata in enumerate(validation_loader):
vinputs, vlabels = vdata
voutputs = model(vinputs)
vloss = loss_fn(voutputs, vlabels)
running_vloss += vloss
avg_vloss = running_vloss / (i + 1)
print('LOSS train {} valid {}'.format(avg_loss, avg_vloss))
# Log the running loss averaged per batch
# for both training and validation
writer.add_scalars('Training vs. Validation Loss',
{ 'Training' : avg_loss, 'Validation' : avg_vloss },
epoch_number + 1)
writer.flush()
# Track best performance, and save the model's state
if avg_vloss < best_vloss:
best_vloss = avg_vloss
model_path = 'model_{}_{}'.format(timestamp, epoch_number)
torch.save(model.state_dict(), model_path)
epoch_number += 1
#########################################################################
# To load a saved version of the model:
#
# ::
#
# saved_model = GarmentClassifier()
# saved_model.load_state_dict(torch.load(PATH))
#
# Once you’ve loaded the model, it’s ready for whatever you need it for -
# more training, inference, or analysis.
#
# Note that if your model has constructor parameters that affect model
# structure, you’ll need to provide them and configure the model
# identically to the state in which it was saved.
#
# Other Resources
# ---------------
#
# - Docs on the `data
# utilities <https://pytorch.org/docs/stable/data.html>`__, including
# Dataset and DataLoader, at pytorch.org
# - A `note on the use of pinned
# memory <https://pytorch.org/docs/stable/notes/cuda.html#cuda-memory-pinning>`__
# for GPU training
# - Documentation on the datasets available in
# `TorchVision <https://pytorch.org/vision/stable/datasets.html>`__,
# `TorchText <https://pytorch.org/text/stable/datasets.html>`__, and
# `TorchAudio <https://pytorch.org/audio/stable/datasets.html>`__
# - Documentation on the `loss
# functions <https://pytorch.org/docs/stable/nn.html#loss-functions>`__
# available in PyTorch
# - Documentation on the `torch.optim
# package <https://pytorch.org/docs/stable/optim.html>`__, which
# includes optimizers and related tools, such as learning rate
# scheduling
# - A detailed `tutorial on saving and loading
# models <https://pytorch.org/tutorials/beginner/saving_loading_models.html>`__
# - The `Tutorials section of
# pytorch.org <https://pytorch.org/tutorials/>`__ contains tutorials on
# a broad variety of training tasks, including classification in
# different domains, generative adversarial networks, reinforcement
# learning, and more
#
| 4,377 |
1,160 | /**
* Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/adc.h"
int main() {
stdio_init_all();
adc_init();
// Make sure GPIO is high-impedance, no pullups etc
adc_gpio_init(26);
adc_gpio_init(27);
while (1) {
adc_select_input(0);
uint adc_x_raw = adc_read();
adc_select_input(1);
uint adc_y_raw = adc_read();
// Display the joystick position something like this:
// X: [ o ] Y: [ o ]
const uint bar_width = 40;
const uint adc_max = (1 << 12) - 1;
uint bar_x_pos = adc_x_raw * bar_width / adc_max;
uint bar_y_pos = adc_y_raw * bar_width / adc_max;
printf("\rX: [");
for (int i = 0; i < bar_width; ++i)
putchar( i == bar_x_pos ? 'o' : ' ');
printf("] Y: [");
for (int i = 0; i < bar_width; ++i)
putchar( i == bar_y_pos ? 'o' : ' ');
printf("]");
sleep_ms(50);
}
}
| 585 |
7,076 | /*
* Copyright (C) 2021. <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.uber.debug.broadcast.core;
import com.uber.debug.broadcast.core.DebugBroadcastReceiver.Handler;
/*
* Simple example handler for responding to 'ACK' command requests.
*/
public class AckDebugBroadcastHandler implements Handler<String> {
static final String COMMAND_ACK = "ACK";
public AckDebugBroadcastHandler() {}
@Override
public boolean canHandle(DebugBroadcastRequest request) {
return request.isCommand(COMMAND_ACK);
}
@Override
public void handle(DebugBroadcastRequest request) {
request.respond("Hello");
}
}
| 317 |
190,993 | <reponame>EricRemmerswaal/tensorflow
# Copyright 2018 The TensorFlow 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.
# ==============================================================================
"""Functions related to Python memory management."""
# TODO(b/115366440): Delete this function when a custom OrderedDict is added
def dismantle_ordered_dict(ordered_dict):
"""Remove reference cycle in OrderedDict `ordered_dict`.
Helpful for making sure the garbage collector doesn't need to run after
using an OrderedDict.
Args:
ordered_dict: A `OrderedDict` object to destroy. This object is unusable
after this function runs.
"""
# OrderedDict, makes a simple reference loop
# and hides it in an __attribute in some Python versions. We don't need to
# throw an error if we can't find it, but if we do find it we can break the
# loop to avoid creating work for the garbage collector.
problematic_cycle = ordered_dict.__dict__.get("_OrderedDict__root", None) # pylint: disable=protected-access
if problematic_cycle:
try:
del problematic_cycle[0][:]
except TypeError:
# This is probably not one of the problematic Python versions. Continue
# with the rest of our cleanup.
pass
| 489 |
322 | package com.imooc.imooc_voice.view.discory.radio;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import com.imooc.imooc_voice.api.RequestCenter;
import com.imooc.imooc_voice.model.newapi.dj.DjTopListBean;
import com.imooc.lib_common_ui.delegate.NeteaseDelegate;
import com.imooc.lib_network.listener.DisposeDataListener;
import java.util.List;
public class RadioRankDelegate extends NeteaseDelegate {
/**
* 主播电台排行榜
* 主播榜 24小时榜 新人榜 最热主播
* 节目榜(默认)
* 电台榜
*/
@Override
public Object setLayout() {
return null;
}
@Override
public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View view) throws Exception {
}
}
| 325 |
964 | <gh_stars>100-1000
[
{
"queryName": "Sagemaker Endpoint Configuration Encryption Disabled",
"severity": "HIGH",
"line": 1,
"fileName": "positive.tf"
}
]
| 72 |
1,444 | <filename>Mage.Tests/src/test/java/org/mage/test/cards/triggers/BecomesBlockedTest.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.mage.test.cards.triggers;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestPlayerBase;
/**
*
* @author escplan9 (<NAME> - dmontur1 at gmail dot com)
*/
public class BecomesBlockedTest extends CardTestPlayerBase {
/**
* Reported bug:
* There's something wrong with how Rabid Elephant is getting his +2/+2 bonus,
* it doesn't last until end of turn, but seems to be removed right after the blockers step.
*/
@Test
public void testRabidElephant() {
// {4}{G}
// Whenever Rabid Elephant becomes blocked, it gets +2/+2 until end of turn for each creature blocking it.
addCard(Zone.BATTLEFIELD, playerA, "Rabid Elephant", 1); // 3/4
addCard(Zone.BATTLEFIELD, playerB, "Savannah Lions", 1); // 2/1
addCard(Zone.BATTLEFIELD, playerB, "Hill Giant", 1); // 3/3
attack(1, playerA, "Rabid Elephant");
block(1, playerB, "Savannah Lions", "Rabid Elephant");
block(1, playerB, "Hill Giant", "Rabid Elephant");
// test passes if PhaseStep ends at DECLARE_BLOCKERS
//setStopAt(1, PhaseStep.DECLARE_BLOCKERS);
setStopAt(1, PhaseStep.COMBAT_DAMAGE);
execute();
// blocked by 2 creatures, so gets +2/+2 twice, making it 7/8
assertPowerToughness(playerA, "Rabid Elephant", 7, 8);
}
}
| 670 |
2,151 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.autofill.keyboard_accessory;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ViewStub;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.modelutil.LazyViewBinderAdapter;
import org.chromium.chrome.browser.modelutil.PropertyModelChangeProcessor;
/**
* Creates and owns all elements which are part of the accessory sheet component.
* It's part of the controller but will mainly forward events (like showing the sheet) and handle
* communication with the {@link ManualFillingCoordinator} (e.g. add a tab to trigger the sheet).
* to the {@link AccessorySheetMediator}.
*/
public class AccessorySheetCoordinator {
private final AccessorySheetMediator mMediator;
/**
* Creates the sheet component by instantiating Model, View and Controller before wiring these
* parts up.
* @param viewStub The view stub that can be inflated into the accessory layout.
*/
public AccessorySheetCoordinator(ViewStub viewStub) {
LazyViewBinderAdapter.StubHolder<ViewPager> stubHolder =
new LazyViewBinderAdapter.StubHolder<>(viewStub);
AccessorySheetModel model = new AccessorySheetModel();
model.addObserver(new PropertyModelChangeProcessor<>(
model, stubHolder, new LazyViewBinderAdapter<>(new AccessorySheetViewBinder())));
mMediator = new AccessorySheetMediator(model);
}
/**
* Creates the {@link PagerAdapter} for the newly inflated {@link ViewPager}.
* If any ListModelChangeProcessor<> is needed, it would be created here. Currently, connecting
* the model.getTabList() to the tabViewBinder would have no effect as only the change of
* ACTIVE_TAB affects the view.
* @param model The model containing the list of tabs to be displayed.
* @return A fully initialized {@link PagerAdapter}.
*/
static PagerAdapter createTabViewAdapter(AccessorySheetModel model) {
return new AccessoryPagerAdapter(model.getTabList());
}
/**
* Adds the contents of a given {@link KeyboardAccessoryData.Tab} to the accessory sheet. If it
* is the first Tab, it automatically becomes the active Tab.
* Careful, if you want to show this tab as icon in the KeyboardAccessory, use the method
* {@link ManualFillingCoordinator#addTab(KeyboardAccessoryData.Tab)} instead.
* @param tab The tab which should be added to the AccessorySheet.
*/
void addTab(KeyboardAccessoryData.Tab tab) {
mMediator.addTab(tab);
}
/**
* Returns a {@link KeyboardAccessoryData.Tab} object that is used to display this bottom sheet.
* @return Returns a {@link KeyboardAccessoryData.Tab}.
*/
@Nullable
public KeyboardAccessoryData.Tab getTab() {
return mMediator.getTab();
}
@VisibleForTesting
AccessorySheetMediator getMediatorForTesting() {
return mMediator;
}
} | 1,054 |
5,411 | // 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 <stdint.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <vector>
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/memory/unsafe_shared_memory_region.h"
#include "base/process/process_handle.h"
#include "build/build_config.h"
#include "mojo/core/test/mojo_test_base.h"
#include "mojo/public/c/system/platform_handle.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_WIN)
#include <windows.h>
#include "base/win/scoped_handle.h"
#elif defined(OS_MACOSX) && !defined(OS_IOS)
#include "base/mac/scoped_mach_port.h"
#endif
#if defined(OS_WIN)
#define SIMPLE_PLATFORM_HANDLE_TYPE MOJO_PLATFORM_HANDLE_TYPE_WINDOWS_HANDLE
#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
#define SIMPLE_PLATFORM_HANDLE_TYPE MOJO_PLATFORM_HANDLE_TYPE_FILE_DESCRIPTOR
#endif
#if defined(OS_FUCHSIA)
#define SHARED_BUFFER_PLATFORM_HANDLE_TYPE \
MOJO_PLATFORM_HANDLE_TYPE_FUCHSIA_HANDLE
#elif defined(OS_MACOSX) && !defined(OS_IOS)
#define SHARED_BUFFER_PLATFORM_HANDLE_TYPE MOJO_PLATFORM_HANDLE_TYPE_MACH_PORT
#elif defined(OS_WIN) || defined(OS_POSIX)
#define SHARED_BUFFER_PLATFORM_HANDLE_TYPE SIMPLE_PLATFORM_HANDLE_TYPE
#endif
uint64_t PlatformHandleValueFromPlatformFile(base::PlatformFile file) {
#if defined(OS_WIN)
return reinterpret_cast<uint64_t>(file);
#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
return static_cast<uint64_t>(file);
#endif
}
base::PlatformFile PlatformFileFromPlatformHandleValue(uint64_t value) {
#if defined(OS_WIN)
return reinterpret_cast<base::PlatformFile>(value);
#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
return static_cast<base::PlatformFile>(value);
#endif
}
namespace mojo {
namespace core {
namespace {
using PlatformWrapperTest = test::MojoTestBase;
TEST_F(PlatformWrapperTest, WrapPlatformHandle) {
// Create a temporary file and write a message to it.
base::FilePath temp_file_path;
ASSERT_TRUE(base::CreateTemporaryFile(&temp_file_path));
const std::string kMessage = "Hello, world!";
EXPECT_EQ(base::WriteFile(temp_file_path, kMessage.data(),
static_cast<int>(kMessage.size())),
static_cast<int>(kMessage.size()));
RunTestClient("ReadPlatformFile", [&](MojoHandle h) {
// Open the temporary file for reading, wrap its handle, and send it to
// the child along with the expected message to be read.
base::File file(temp_file_path,
base::File::FLAG_OPEN | base::File::FLAG_READ);
EXPECT_TRUE(file.IsValid());
MojoHandle wrapped_handle;
MojoPlatformHandle os_file;
os_file.struct_size = sizeof(MojoPlatformHandle);
os_file.type = SIMPLE_PLATFORM_HANDLE_TYPE;
os_file.value =
PlatformHandleValueFromPlatformFile(file.TakePlatformFile());
EXPECT_EQ(MOJO_RESULT_OK,
MojoWrapPlatformHandle(&os_file, nullptr, &wrapped_handle));
WriteMessageWithHandles(h, kMessage, &wrapped_handle, 1);
});
base::DeleteFile(temp_file_path, false);
}
DEFINE_TEST_CLIENT_TEST_WITH_PIPE(ReadPlatformFile, PlatformWrapperTest, h) {
// Read a message and a wrapped file handle; unwrap the handle.
MojoHandle wrapped_handle;
std::string message = ReadMessageWithHandles(h, &wrapped_handle, 1);
MojoPlatformHandle platform_handle;
platform_handle.struct_size = sizeof(MojoPlatformHandle);
ASSERT_EQ(MOJO_RESULT_OK, MojoUnwrapPlatformHandle(wrapped_handle, nullptr,
&platform_handle));
EXPECT_EQ(SIMPLE_PLATFORM_HANDLE_TYPE, platform_handle.type);
base::File file(PlatformFileFromPlatformHandleValue(platform_handle.value));
// Expect to read the same message from the file.
std::vector<char> data(message.size());
EXPECT_EQ(file.ReadAtCurrentPos(data.data(), static_cast<int>(data.size())),
static_cast<int>(data.size()));
EXPECT_TRUE(std::equal(message.begin(), message.end(), data.begin()));
}
TEST_F(PlatformWrapperTest, WrapPlatformSharedMemoryRegion) {
// Allocate a new platform shared buffer and write a message into it.
const std::string kMessage = "Hello, world!";
auto region = base::UnsafeSharedMemoryRegion::Create(kMessage.size());
base::WritableSharedMemoryMapping buffer = region.Map();
CHECK(buffer.IsValid());
memcpy(buffer.memory(), kMessage.data(), kMessage.size());
RunTestClient("ReadPlatformSharedBuffer", [&](MojoHandle h) {
// Wrap the shared memory handle and send it to the child along with the
// expected message.
base::subtle::PlatformSharedMemoryRegion platform_region =
base::UnsafeSharedMemoryRegion::TakeHandleForSerialization(
region.Duplicate());
MojoPlatformHandle os_buffer;
os_buffer.struct_size = sizeof(MojoPlatformHandle);
os_buffer.type = SHARED_BUFFER_PLATFORM_HANDLE_TYPE;
#if defined(OS_WIN)
os_buffer.value =
reinterpret_cast<uint64_t>(platform_region.PassPlatformHandle().Take());
#elif defined(OS_MACOSX) && !defined(OS_IOS) || defined(OS_FUCHSIA) || \
defined(OS_ANDROID)
os_buffer.value =
static_cast<uint64_t>(platform_region.PassPlatformHandle().release());
#elif defined(OS_POSIX)
os_buffer.value = static_cast<uint64_t>(
platform_region.PassPlatformHandle().fd.release());
#else
#error Unsupported platform
#endif
MojoSharedBufferGuid mojo_guid;
base::UnguessableToken guid = platform_region.GetGUID();
mojo_guid.high = guid.GetHighForSerialization();
mojo_guid.low = guid.GetLowForSerialization();
MojoHandle wrapped_handle;
ASSERT_EQ(MOJO_RESULT_OK,
MojoWrapPlatformSharedMemoryRegion(
&os_buffer, 1, kMessage.size(), &mojo_guid,
MOJO_PLATFORM_SHARED_MEMORY_REGION_ACCESS_MODE_UNSAFE,
nullptr, &wrapped_handle));
WriteMessageWithHandles(h, kMessage, &wrapped_handle, 1);
// As a sanity check, send the GUID explicitly in a second message. We'll
// verify that the deserialized buffer handle holds the same GUID on the
// receiving end.
WriteMessageRaw(MessagePipeHandle(h), &mojo_guid, sizeof(mojo_guid),
nullptr, 0, MOJO_WRITE_MESSAGE_FLAG_NONE);
});
}
DEFINE_TEST_CLIENT_TEST_WITH_PIPE(ReadPlatformSharedBuffer,
PlatformWrapperTest,
h) {
// Read a message and a wrapped shared buffer handle.
MojoHandle wrapped_handle;
std::string message = ReadMessageWithHandles(h, &wrapped_handle, 1);
// Check the message in the buffer
ExpectBufferContents(wrapped_handle, 0, message);
// Now unwrap the buffer and verify that the
// base::subtle::PlatformSharedMemoryRegion also works as expected.
MojoPlatformHandle os_buffer;
os_buffer.struct_size = sizeof(MojoPlatformHandle);
uint32_t num_handles = 1;
uint64_t size;
MojoSharedBufferGuid mojo_guid;
MojoPlatformSharedMemoryRegionAccessMode access_mode;
ASSERT_EQ(MOJO_RESULT_OK, MojoUnwrapPlatformSharedMemoryRegion(
wrapped_handle, nullptr, &os_buffer,
&num_handles, &size, &mojo_guid, &access_mode));
EXPECT_EQ(MOJO_PLATFORM_SHARED_MEMORY_REGION_ACCESS_MODE_UNSAFE, access_mode);
auto mode = base::subtle::PlatformSharedMemoryRegion::Mode::kUnsafe;
base::UnguessableToken guid =
base::UnguessableToken::Deserialize(mojo_guid.high, mojo_guid.low);
#if defined(OS_WIN)
ASSERT_EQ(MOJO_PLATFORM_HANDLE_TYPE_WINDOWS_HANDLE, os_buffer.type);
auto platform_handle =
base::win::ScopedHandle(reinterpret_cast<HANDLE>(os_buffer.value));
#elif defined(OS_FUCHSIA)
ASSERT_EQ(MOJO_PLATFORM_HANDLE_TYPE_FUCHSIA_HANDLE, os_buffer.type);
auto platform_handle = zx::vmo(static_cast<zx_handle_t>(os_buffer.value));
#elif defined(OS_MACOSX) && !defined(OS_IOS)
ASSERT_EQ(MOJO_PLATFORM_HANDLE_TYPE_MACH_PORT, os_buffer.type);
auto platform_handle =
base::mac::ScopedMachSendRight(static_cast<mach_port_t>(os_buffer.value));
#elif defined(OS_POSIX)
ASSERT_EQ(MOJO_PLATFORM_HANDLE_TYPE_FILE_DESCRIPTOR, os_buffer.type);
auto platform_handle = base::ScopedFD(static_cast<int>(os_buffer.value));
#endif
base::subtle::PlatformSharedMemoryRegion platform_region =
base::subtle::PlatformSharedMemoryRegion::Take(std::move(platform_handle),
mode, size, guid);
base::UnsafeSharedMemoryRegion region =
base::UnsafeSharedMemoryRegion::Deserialize(std::move(platform_region));
ASSERT_TRUE(region.IsValid());
base::WritableSharedMemoryMapping mapping = region.Map();
ASSERT_TRUE(mapping.memory());
EXPECT_TRUE(std::equal(message.begin(), message.end(),
static_cast<const char*>(mapping.memory())));
// Verify that the received buffer's internal GUID was preserved in transit.
EXPECT_EQ(MOJO_RESULT_OK, WaitForSignals(h, MOJO_HANDLE_SIGNAL_READABLE));
std::vector<uint8_t> guid_bytes;
EXPECT_EQ(MOJO_RESULT_OK,
ReadMessageRaw(MessagePipeHandle(h), &guid_bytes, nullptr,
MOJO_READ_MESSAGE_FLAG_NONE));
EXPECT_EQ(sizeof(MojoSharedBufferGuid), guid_bytes.size());
auto* expected_guid =
reinterpret_cast<MojoSharedBufferGuid*>(guid_bytes.data());
EXPECT_EQ(expected_guid->high, mojo_guid.high);
EXPECT_EQ(expected_guid->low, mojo_guid.low);
}
TEST_F(PlatformWrapperTest, InvalidHandle) {
// Wrap an invalid platform handle and expect to unwrap the same.
MojoHandle wrapped_handle;
MojoPlatformHandle invalid_handle;
invalid_handle.struct_size = sizeof(MojoPlatformHandle);
invalid_handle.type = MOJO_PLATFORM_HANDLE_TYPE_INVALID;
EXPECT_EQ(MOJO_RESULT_OK,
MojoWrapPlatformHandle(&invalid_handle, nullptr, &wrapped_handle));
EXPECT_EQ(MOJO_RESULT_OK,
MojoUnwrapPlatformHandle(wrapped_handle, nullptr, &invalid_handle));
EXPECT_EQ(MOJO_PLATFORM_HANDLE_TYPE_INVALID, invalid_handle.type);
}
TEST_F(PlatformWrapperTest, InvalidArgument) {
// Try to wrap an invalid MojoPlatformHandle struct and expect an error.
MojoHandle wrapped_handle;
MojoPlatformHandle platform_handle;
platform_handle.struct_size = 0;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoWrapPlatformHandle(&platform_handle, nullptr, &wrapped_handle));
}
} // namespace
} // namespace core
} // namespace mojo
| 4,183 |
369 | /*
* Copyright © 2017 <NAME>, 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.
*/
package io.cdap.cdap.messaging.store.cache;
import io.cdap.cdap.messaging.cache.MessageCache;
import io.cdap.cdap.messaging.store.MessageTable;
/**
* A {@link MessageCache.Weigher} for the {@link MessageTable.Entry}.
*/
final class MessageTableEntryWeigher implements MessageCache.Weigher<MessageTable.Entry> {
@Override
public int weight(MessageTable.Entry entry) {
// Some fixed overhead for the primitive and reference fields
int weight = 40;
byte[] payload = entry.getPayload();
weight += payload == null ? 0 : payload.length;
return weight;
}
}
| 340 |
528 | <reponame>mahimadubey/leetcode-python<gh_stars>100-1000
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def minDepth(self, root):
if root is None:
return 0
# BFS
queue1 = []
queue2 = []
queue1.append(root)
queue2.append(1)
while queue1:
root = queue1.pop(0)
depth = queue2.pop(0)
if root.left is None and root.right is None:
return depth
if root.left is not None:
queue1.append(root.left)
queue2.append(depth + 1)
if root.right is not None:
queue1.append(root.right)
queue2.append(depth + 1)
| 468 |
5,169 | <reponame>Gantios/Specs
{
"name": "XLsn0wAliPaySDK",
"version": "15.1.6.2016.08.02",
"summary": "XLsn0w Create The XLsn0wAliPaySDK CocoaPod Sync Alipay Official SDK",
"description": "XLsn0w Create The XLsn0wAliPaySDK CocoaPod Sync ANT Financial Official AlipaySDK",
"license": "MIT",
"authors": {
"XLsn0w": "<EMAIL>"
},
"homepage": "https://github.com/XLsn0w/XLsn0wAlipaySDK",
"source": {
"git": "https://github.com/XLsn0w/XLsn0wAlipaySDK.git",
"tag": "15.1.6.2016.08.02"
},
"platforms": {
"ios": "7.0"
},
"requires_arc": true,
"vendored_libraries": [
"libcrypto/libcrypto.a",
"libssl/libssl.a"
],
"frameworks": [
"CoreMotion",
"CoreTelephony",
"SystemConfiguration",
"CFNetwork"
],
"libraries": [
"z",
"c++"
],
"vendored_frameworks": "AlipaySDKFramework/AlipaySDK.framework",
"resources": "AlipaySDKBundle/AlipaySDK.bundle"
}
| 422 |
8,586 | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#include <gtest/gtest.h>
#include "graph/context/QueryContext.h"
#include "graph/executor/query/DataCollectExecutor.h"
#include "graph/planner/plan/Query.h"
namespace nebula {
namespace graph {
class DataCollectTest : public testing::Test {
protected:
void SetUp() override {
qctx_ = std::make_unique<QueryContext>();
{
DataSet ds1;
ds1.colNames = {
kVid, "_stats", "_tag:tag1:prop1:prop2", "_edge:+edge1:prop1:prop2:_dst:_rank", "_expr"};
for (auto i = 0; i < 10; ++i) {
Row row;
// _vid
row.values.emplace_back(folly::to<std::string>(i));
// _stats = empty
row.values.emplace_back(Value());
// tag
List tag;
tag.values.emplace_back(0);
tag.values.emplace_back(1);
row.values.emplace_back(Value(tag));
// edges
List edges;
for (auto j = 0; j < 2; ++j) {
List edge;
for (auto k = 0; k < 2; ++k) {
edge.values.emplace_back(k);
}
edge.values.emplace_back("2");
edge.values.emplace_back(j);
edges.values.emplace_back(std::move(edge));
}
row.values.emplace_back(edges);
// _expr = empty
row.values.emplace_back(Value());
ds1.rows.emplace_back(std::move(row));
}
DataSet ds2;
ds2.colNames = {
kVid, "_stats", "_tag:tag2:prop1:prop2", "_edge:-edge2:prop1:prop2:_dst:_rank", "_expr"};
for (auto i = 10; i < 20; ++i) {
Row row;
// _vid
row.values.emplace_back(folly::to<std::string>(i));
// _stats = empty
row.values.emplace_back(Value());
// tag
List tag;
tag.values.emplace_back(0);
tag.values.emplace_back(1);
row.values.emplace_back(Value(tag));
// edges
List edges;
for (auto j = 0; j < 2; ++j) {
List edge;
for (auto k = 0; k < 2; ++k) {
edge.values.emplace_back(k);
}
edge.values.emplace_back("2");
edge.values.emplace_back(j);
edges.values.emplace_back(std::move(edge));
}
row.values.emplace_back(edges);
// _expr = empty
row.values.emplace_back(Value());
ds2.rows.emplace_back(std::move(row));
}
List datasets;
datasets.values.emplace_back(std::move(ds1));
ResultBuilder builder;
builder.value(Value(std::move(datasets))).iter(Iterator::Kind::kGetNeighbors);
qctx_->symTable()->newVariable("input_datasets");
qctx_->ectx()->setResult("input_datasets", builder.build());
qctx_->ectx()->setResult(
"input_datasets",
ResultBuilder().value(Value(std::move(ds2))).iter(Iterator::Kind::kGetNeighbors).build());
}
{
DataSet ds;
ds.colNames = {"col1", "col2"};
for (auto i = 0; i < 9; ++i) {
Row row;
row.values.emplace_back(i);
row.values.emplace_back(i);
ds.rows.emplace_back(std::move(row));
}
qctx_->symTable()->newVariable("input_sequential");
qctx_->ectx()->setResult("input_sequential",
ResultBuilder().value(Value(std::move(ds))).build());
}
{
DataSet ds;
ds.colNames = {
kVid, "_stats", "_tag:tag1:prop1:prop2", "_edge:+edge1:prop1:prop2:_dst:_rank", "_expr"};
qctx_->symTable()->newVariable("empty_get_neighbors");
qctx_->ectx()->setResult(
"empty_get_neighbors",
ResultBuilder().value(Value(ds)).iter(Iterator::Kind::kGetNeighbors).build());
qctx_->ectx()->setResult(
"empty_get_neighbors",
ResultBuilder().value(Value(std::move(ds))).iter(Iterator::Kind::kGetNeighbors).build());
}
{
// for path with prop
// <("0")-[:like]->("1")>
DataSet vertices;
vertices.colNames = {kVid, "player.name", "player.age"};
for (auto i = 0; i < 2; ++i) {
Row row;
row.values.emplace_back(folly::to<std::string>(i));
row.values.emplace_back(folly::to<std::string>(i));
row.values.emplace_back(i + 20);
vertices.rows.emplace_back(std::move(row));
}
qctx_->symTable()->newVariable("vertices");
qctx_->ectx()->setResult(
"vertices",
ResultBuilder().value(Value(std::move(vertices))).iter(Iterator::Kind::kProp).build());
DataSet edges;
edges.colNames = {"like._src", "like._dst", "like._rank", "like._type", "like.likeness"};
Row edge;
edge.values.emplace_back("0");
edge.values.emplace_back("1");
edge.values.emplace_back(0);
edge.values.emplace_back(15);
edge.values.emplace_back(90);
edges.rows.emplace_back(std::move(edge));
qctx_->symTable()->newVariable("edges");
qctx_->ectx()->setResult(
"edges",
ResultBuilder().value(Value(std::move(edges))).iter(Iterator::Kind::kProp).build());
DataSet paths;
paths.colNames = {"paths"};
Vertex src("0", {});
Vertex dst("1", {});
Step step(std::move(dst), 15, "like", 0, {});
Path path(std::move(src), {step});
Row row;
row.values.emplace_back(std::move(path));
paths.rows.emplace_back(std::move(row));
qctx_->symTable()->newVariable("paths");
qctx_->ectx()->setResult("paths", ResultBuilder().value(Value(std::move(paths))).build());
}
}
protected:
std::unique_ptr<QueryContext> qctx_;
};
TEST_F(DataCollectTest, CollectSubgraph) {
auto* dc = DataCollect::make(qctx_.get(), DataCollect::DCKind::kSubgraph);
dc->setInputVars({"input_datasets"});
dc->setColNames(std::vector<std::string>{"_vertices", "_edges"});
auto dcExe = std::make_unique<DataCollectExecutor>(dc, qctx_.get());
auto future = dcExe->execute();
auto status = std::move(future).get();
EXPECT_TRUE(status.ok());
auto& result = qctx_->ectx()->getResult(dc->outputVar());
DataSet expected;
expected.colNames = {"_vertices", "_edges"};
auto& hist = qctx_->ectx()->getHistory("input_datasets");
auto iter = hist[0].iter();
auto* gNIter = static_cast<GetNeighborsIter*>(iter.get());
Row row;
std::unordered_set<Value> vids;
std::unordered_set<std::tuple<Value, int64_t, int64_t, Value>> edgeKeys;
List vertices;
List edges;
auto originVertices = gNIter->getVertices();
for (auto& v : originVertices.values) {
if (!v.isVertex()) {
continue;
}
if (vids.emplace(v.getVertex().vid).second) {
vertices.emplace_back(std::move(v));
}
}
auto originEdges = gNIter->getEdges();
for (auto& e : originEdges.values) {
if (!e.isEdge()) {
continue;
}
auto edgeKey =
std::make_tuple(e.getEdge().src, e.getEdge().type, e.getEdge().ranking, e.getEdge().dst);
if (edgeKeys.emplace(std::move(edgeKey)).second) {
edges.emplace_back(std::move(e));
}
}
row.values.emplace_back(std::move(vertices));
row.values.emplace_back(std::move(edges));
expected.rows.emplace_back(std::move(row));
EXPECT_EQ(result.value().getDataSet(), expected);
EXPECT_EQ(result.state(), Result::State::kSuccess);
}
TEST_F(DataCollectTest, RowBasedMove) {
auto* dc = DataCollect::make(qctx_.get(), DataCollect::DCKind::kRowBasedMove);
dc->setInputVars({"input_sequential"});
dc->setColNames(std::vector<std::string>{"col1", "col2"});
DataSet expected;
auto& input = qctx_->ectx()->getResult("input_sequential");
expected = input.value().getDataSet();
auto dcExe = std::make_unique<DataCollectExecutor>(dc, qctx_.get());
auto future = dcExe->execute();
auto status = std::move(future).get();
EXPECT_TRUE(status.ok());
auto& result = qctx_->ectx()->getResult(dc->outputVar());
EXPECT_EQ(result.value().getDataSet(), expected);
EXPECT_EQ(result.state(), Result::State::kSuccess);
}
TEST_F(DataCollectTest, EmptyResult) {
auto* dc = DataCollect::make(qctx_.get(), DataCollect::DCKind::kSubgraph);
dc->setInputVars({"empty_get_neighbors"});
dc->setColNames(std::vector<std::string>{"_vertices", "_edges"});
auto dcExe = std::make_unique<DataCollectExecutor>(dc, qctx_.get());
auto future = dcExe->execute();
auto status = std::move(future).get();
EXPECT_TRUE(status.ok());
auto& result = qctx_->ectx()->getResult(dc->outputVar());
DataSet expected;
expected.colNames = {"_vertices", "_edges"};
Row row;
row.values.emplace_back(Value(List()));
row.values.emplace_back(Value(List()));
expected.rows.emplace_back(std::move(row));
EXPECT_EQ(result.value().getDataSet(), expected);
EXPECT_EQ(result.state(), Result::State::kSuccess);
}
TEST_F(DataCollectTest, PathWithProp) {
auto* dc = DataCollect::make(qctx_.get(), DataCollect::DCKind::kPathProp);
dc->setInputVars({"vertices", "edges", "paths"});
dc->setColNames({"paths"});
auto dcExe = std::make_unique<DataCollectExecutor>(dc, qctx_.get());
auto future = dcExe->execute();
auto status = std::move(future).get();
EXPECT_TRUE(status.ok());
auto& result = qctx_->ectx()->getResult(dc->outputVar());
DataSet expected;
expected.colNames = {"paths"};
Vertex src("0", {Tag("player", {{"age", Value(20)}, {"name", Value("0")}})});
Vertex dst("1", {Tag("player", {{"age", Value(21)}, {"name", Value("1")}})});
Step step(std::move(dst), 15, "like", 0, {{"likeness", 90}});
Path path(std::move(src), {std::move(step)});
Row row;
row.values.emplace_back(std::move(path));
expected.rows.emplace_back(std::move(row));
EXPECT_EQ(result.value().getDataSet(), expected);
EXPECT_EQ(result.state(), Result::State::kSuccess);
}
} // namespace graph
} // namespace nebula
| 4,273 |
940 | <filename>BasiliskII/src/slirp/slirp.h
#ifndef __COMMON_H__
#define __COMMON_H__
#define CONFIG_QEMU
#define DEBUG 1
#ifndef CONFIG_QEMU
#include "version.h"
#endif
#include "config.h"
#include "slirp_config.h"
#ifdef _WIN32
# include <inttypes.h>
typedef uint8_t u_int8_t;
typedef uint16_t u_int16_t;
typedef uint32_t u_int32_t;
typedef uint64_t u_int64_t;
typedef char *caddr_t;
typedef int socklen_t;
typedef unsigned long ioctlsockopt_t;
# include <winsock2.h>
# include <WS2tcpip.h>
# include <sys/timeb.h>
# include <iphlpapi.h>
# define USE_FIONBIO 1
/* Basilisk II Router defines those */
# define udp_read_completion slirp_udp_read_completion
# define write_udp slirp_write_udp
# define init_udp slirp_init_udp
# define final_udp slirp_final_udp
#else
# define WSAGetLastError() (int)(errno)
# define WSASetLastError(e) (void)(errno = (e))
# define WSAEWOULDBLOCK EWOULDBLOCK
# define WSAEINPROGRESS EINPROGRESS
# define WSAENOTCONN ENOTCONN
# define WSAEHOSTUNREACH EHOSTUNREACH
# define WSAENETUNREACH ENETUNREACH
# define WSAECONNREFUSED ECONNREFUSED
typedef int ioctlsockopt_t;
# define ioctlsocket ioctl
# define closesocket(s) close(s)
# define O_BINARY 0
#endif
#include <sys/types.h>
#ifdef HAVE_SYS_BITYPES_H
# include <sys/bitypes.h>
#endif
#ifdef HAVE_STDINT_H
# include <stdint.h>
#endif
#ifndef _WIN32
#include <sys/time.h>
#endif
#ifdef NEED_TYPEDEFS
typedef char int8_t;
typedef unsigned char u_int8_t;
# if SIZEOF_SHORT == 2
typedef short int16_t;
typedef unsigned short u_int16_t;
# else
# if SIZEOF_INT == 2
typedef int int16_t;
typedef unsigned int u_int16_t;
# else
#error Cannot find a type with sizeof() == 2
# endif
# endif
# if SIZEOF_SHORT == 4
typedef short int32_t;
typedef unsigned short u_int32_t;
# else
# if SIZEOF_INT == 4
typedef int int32_t;
typedef unsigned int u_int32_t;
# else
#error Cannot find a type with sizeof() == 4
# endif
# endif
#endif /* NEED_TYPEDEFS */
/* Basilisk II types glue */
typedef u_int8_t uint8;
typedef u_int16_t uint16;
typedef u_int32_t uint32;
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_STDLIB_H
# include <stdlib.h>
#endif
#include <stdio.h>
#include <errno.h>
#ifndef HAVE_MEMMOVE
#define memmove(x, y, z) bcopy(y, x, z)
#endif
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#ifdef HAVE_STRING_H
# include <string.h>
#else
# include <strings.h>
#endif
#ifndef _WIN32
#include <sys/uio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#ifdef GETTIMEOFDAY_ONE_ARG
#define gettimeofday(x, y) gettimeofday(x)
#endif
/* Systems lacking strdup() definition in <string.h>. */
#if defined(ultrix)
char *strdup(const char *);
#endif
/* Systems lacking malloc() definition in <stdlib.h>. */
#if defined(ultrix) || defined(hcx)
void *malloc(size_t arg);
void free(void *ptr);
#endif
#ifndef HAVE_INET_ATON
int inet_aton(const char *cp, struct in_addr *ia);
#endif
#include <fcntl.h>
#ifdef _WIN32
#include <io.h>
#endif
#ifndef NO_UNIX_SOCKETS
#include <sys/un.h>
#endif
#include <signal.h>
#ifdef HAVE_SYS_SIGNAL_H
# include <sys/signal.h>
#endif
#ifndef _WIN32
#include <sys/socket.h>
#endif
#if defined(HAVE_SYS_IOCTL_H)
# include <sys/ioctl.h>
#endif
#ifdef HAVE_SYS_SELECT_H
# include <sys/select.h>
#endif
#ifdef HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#ifdef HAVE_SYS_FILIO_H
# include <sys/filio.h>
#endif
#ifdef USE_PPP
#include <ppp/slirppp.h>
#endif
#include <stdarg.h>
#include <sys/stat.h>
/* Avoid conflicting with the libc insque() and remque(), which
have different prototypes. */
#define insque slirp_insque
#define remque slirp_remque
#ifdef HAVE_SYS_STROPTS_H
#include <sys/stropts.h>
#endif
#include "debug.h"
#if defined __GNUC__
#define PACKED__ __attribute__ ((packed))
#elif defined _MSC_VER
#define PRAGMA_PACK_SUPPORTED 1
#define PACK_RESET
#define PACKED__
#elif defined __sgi
#define PRAGMA_PACK_SUPPORTED 1
#define PACK_RESET 0
#define PACKED__
#else
#error "Packed attribute or pragma shall be supported"
#endif
#include "ip.h"
#include "tcp.h"
#include "tcp_timer.h"
#include "tcp_var.h"
#include "tcpip.h"
#include "udp.h"
#include "icmp_var.h"
#include "mbuf.h"
#include "sbuf.h"
#include "socket.h"
#include "if.h"
#include "main.h"
#include "misc.h"
#include "ctl.h"
#ifdef USE_PPP
#include "ppp/pppd.h"
#include "ppp/ppp.h"
#endif
#include "bootp.h"
#include "tftp.h"
#include "libslirp.h"
extern struct ttys *ttys_unit[MAX_INTERFACES];
#ifndef NULL
#define NULL (void *)0
#endif
#ifndef FULL_BOLT
void if_start(void);
#else
void if_start(struct ttys *);
#endif
#ifdef BAD_SPRINTF
# define vsprintf vsprintf_len
# define sprintf sprintf_len
extern int vsprintf_len(char *, const char *, va_list);
extern int sprintf_len(char *, const char *, ...);
#endif
#ifdef DECLARE_SPRINTF
# ifndef BAD_SPRINTF
extern int vsprintf(char *, const char *, va_list);
# endif
extern int vfprintf(FILE *, const char *, va_list);
#endif
#ifndef HAVE_STRERROR
extern char *strerror(int error);
#endif
#ifndef HAVE_INDEX
char *index(const char *, int);
#endif
#ifndef HAVE_GETHOSTID
long gethostid(void);
#endif
void lprint(const char *, ...);
extern int do_echo;
#if SIZEOF_CHAR_P == 4
# define insque_32 insque
# define remque_32 remque
#else
extern inline void insque_32(void *, void *);
extern inline void remque_32(void *);
#endif
#ifndef _WIN32
#include <netdb.h>
#endif
#define DEFAULT_BAUD 115200
/* cksum.c */
int cksum(struct mbuf *m, int len);
/* if.c */
void if_init(void);
void if_output(struct socket *, struct mbuf *);
/* ip_input.c */
void ip_init(void);
void ip_input(struct mbuf *);
struct ip * ip_reass(register struct ipasfrag *, register struct ipq *);
void ip_freef(struct ipq *);
void ip_enq(register struct ipasfrag *, register struct ipasfrag *);
void ip_deq(register struct ipasfrag *);
void ip_slowtimo(void);
void ip_stripoptions(register struct mbuf *, struct mbuf *);
/* ip_output.c */
int ip_output(struct socket *, struct mbuf *);
/* tcp_input.c */
int tcp_reass(register struct tcpcb *, register struct tcpiphdr *, struct mbuf *);
void tcp_input(register struct mbuf *, int, struct socket *);
void tcp_dooptions(struct tcpcb *, u_char *, int, struct tcpiphdr *);
void tcp_xmit_timer(register struct tcpcb *, int);
u_int tcp_mss(register struct tcpcb *, u_int);
/* tcp_output.c */
int tcp_output(register struct tcpcb *);
void tcp_setpersist(register struct tcpcb *);
/* tcp_subr.c */
void tcp_init(void);
void tcp_template(struct tcpcb *);
void tcp_respond(struct tcpcb *, register struct tcpiphdr *, register struct mbuf *, tcp_seq, tcp_seq, int);
struct tcpcb * tcp_newtcpcb(struct socket *);
struct tcpcb * tcp_close(register struct tcpcb *);
void tcp_drain(void);
void tcp_sockclosed(struct tcpcb *);
int tcp_fconnect(struct socket *);
void tcp_connect(struct socket *);
int tcp_attach(struct socket *);
u_int8_t tcp_tos(struct socket *);
int tcp_emu(struct socket *, struct mbuf *);
int tcp_ctl(struct socket *);
struct tcpcb *tcp_drop(struct tcpcb *tp, int err);
#ifdef USE_PPP
#define MIN_MRU MINMRU
#define MAX_MRU MAXMRU
#else
#define MIN_MRU 128
#define MAX_MRU 16384
#endif
#ifndef _WIN32
#define min(x,y) ((x) < (y) ? (x) : (y))
#define max(x,y) ((x) > (y) ? (x) : (y))
#endif
#endif
| 3,082 |
1,299 | /*
* Copyright 2015 Netflix, 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.
*
*/
package io.reactivex.netty.protocol.http.ws.server;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.util.internal.StringUtil;
import io.reactivex.netty.protocol.http.server.HttpServerRequest;
import io.reactivex.netty.protocol.http.server.HttpServerResponse;
import rx.Observable;
import rx.Subscriber;
import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpHeaderValues.*;
/**
* The websocket handshaker for sending handshake response back to the client.
*
* The defaults chosen by the handshaker can be altered by using the various methods here.
*/
public abstract class WebSocketHandshaker extends Observable<Void> {
public static final int DEFAULT_MAX_FRAME_PAYLOAD_LENGTH = 65536;
public static final boolean DEFAULT_ALLOW_EXTENSIONS = true;
protected WebSocketHandshaker(OnSubscribe<Void> f) {
super(f);
}
public abstract WebSocketHandshaker subprotocol(String... subprotocols);
public abstract WebSocketHandshaker allowExtensions(boolean allowExtensions);
public abstract WebSocketHandshaker location(String webSocketLocation);
public abstract WebSocketHandshaker maxFramePayloadLength(int maxFramePayloadLength);
public static WebSocketHandshaker newHandshaker(HttpServerRequest<?> request,
HttpServerResponse<?> upgradeResponse, WebSocketHandler handler) {
final WebSocketVersion wsVersion = getWsVersion(request);
return V7to13Handshaker.createNew(wsVersion, request, upgradeResponse, handler);
}
public static WebSocketHandshaker newErrorHandshaker(Throwable error) {
return new ErrorWebSocketHandshaker(error);
}
/**
* <b>This is copied from {@link WebSocketServerHandshaker}</b>
*
* Selects the first matching supported sub protocol
*
* @param requestedSubprotocols CSV of protocols to be supported. e.g. "chat, superchat"
* @return First matching supported sub protocol. Null if not found.
*/
protected static String selectSubprotocol(String requestedSubprotocols, String[] supportedSubProtocols) {
if (requestedSubprotocols == null || supportedSubProtocols.length == 0) {
return null;
}
String[] requestedSubprotocolArray = requestedSubprotocols.split(",");
for (String p: requestedSubprotocolArray) {
String requestedSubprotocol = p.trim();
for (String supportedSubprotocol: supportedSubProtocols) {
if (WebSocketServerHandshaker.SUB_PROTOCOL_WILDCARD.equals(supportedSubprotocol)
|| requestedSubprotocol.equals(supportedSubprotocol)) {
return requestedSubprotocol;
}
}
}
// No match found
return null;
}
public static boolean isUpgradeRequested(HttpServerRequest<?> upgradeRequest) {
return null != upgradeRequest && upgradeRequest.containsHeader(HttpHeaderNames.UPGRADE)
&& WEBSOCKET.contentEqualsIgnoreCase(upgradeRequest.getHeader(HttpHeaderNames.UPGRADE));
}
public static boolean isUpgradeRequested(HttpRequest upgradeRequest) {
return null != upgradeRequest && upgradeRequest.headers().contains(HttpHeaderNames.UPGRADE)
&& WEBSOCKET.contentEqualsIgnoreCase(upgradeRequest.headers()
.get(HttpHeaderNames.UPGRADE));
}
private static WebSocketVersion getWsVersion(HttpServerRequest<?> request) {
String version = request.getHeader(SEC_WEBSOCKET_VERSION);
switch (version) {
case "0":
return WebSocketVersion.V00;
case "7":
return WebSocketVersion.V07;
case "8":
return WebSocketVersion.V08;
case "13":
return WebSocketVersion.V13;
default:
return WebSocketVersion.UNKNOWN;
}
}
private static class ErrorWebSocketHandshaker extends WebSocketHandshaker {
public ErrorWebSocketHandshaker(final Throwable error) {
super(new OnSubscribe<Void>() {
@Override
public void call(Subscriber<? super Void> subscriber) {
subscriber.onError(error);
}
});
}
@Override
public WebSocketHandshaker subprotocol(String... subprotocols) {
return this;
}
@Override
public WebSocketHandshaker allowExtensions(boolean allowExtensions) {
return this;
}
@Override
public WebSocketHandshaker location(String webSocketLocation) {
return this;
}
@Override
public WebSocketHandshaker maxFramePayloadLength(int maxFramePayloadLength) {
return this;
}
}
}
| 2,246 |
2,032 | # -*- coding: utf-8 -*-
from sqlalchemy import Column, String, Float
from sqlalchemy.orm import declarative_base
from zvt.contract import Portfolio, PortfolioStockHistory
from zvt.contract.register import register_schema, register_entity
IndexMetaBase = declarative_base()
# 指数
@register_entity(entity_type="index")
class Index(IndexMetaBase, Portfolio):
__tablename__ = "index"
# 发布商
publisher = Column(String(length=64))
# 类别
# see IndexCategory
category = Column(String(length=64))
# 基准点数
base_point = Column(Float)
class IndexStock(IndexMetaBase, PortfolioStockHistory):
__tablename__ = "index_stock"
register_schema(providers=["exchange"], db_name="index_meta", schema_base=IndexMetaBase)
# the __all__ is generated
__all__ = ["Index", "IndexStock"]
| 293 |
457 | <gh_stars>100-1000
from PIL import Image
im = Image.open('indoor1.jpg')
imBackground = im.resize((875, 587)) #700 470 840 564
imBackground.save('indoor1_resize.jpg')
| 65 |
348 | <filename>docs/data/leg-t2/064/06404404.json<gh_stars>100-1000
{"nom":"Montory","circ":"4ème circonscription","dpt":"Pyrénées-Atlantiques","inscrits":299,"abs":136,"votants":163,"blancs":12,"nuls":4,"exp":147,"res":[{"nuance":"DVD","nom":"<NAME>","voix":81},{"nuance":"REM","nom":"<NAME>","voix":66}]} | 124 |
455 | #pragma once
#include "../../defines.h"
namespace star
{
struct pos
{
float32 x, y;
lay l;
pos();
explicit pos(const vec2 & vec, lay layer = LAYER_DEF);
pos(float64 X, float64 Y, lay layer = LAYER_DEF);
pos(float32 X, float32 Y, lay layer = LAYER_DEF);
pos(int32 X, int32 Y, lay layer = LAYER_DEF);
pos(int64 X, int64 Y, lay layer = LAYER_DEF);
pos(const pos & yRef);
pos(pos && yRef);
bool operator==(const pos & yRef) const;
bool operator==(const vec2 & yRef) const;
bool operator!=(const pos & yRef) const;
bool operator!=(const vec2 & yRef) const;
pos & operator=(const pos & yRef);
pos & operator=(pos && yRef);
pos & operator=(const vec2 & yRef);
pos & operator+=(const pos & yRef);
pos & operator+=(const vec2 & yRef);
pos & operator-=(const pos & yRef);
pos & operator-=(const vec2 & yRef);
pos operator+(const pos & yRef) const;
pos operator+(const vec2 & yRef) const;
pos operator-(const pos & yRef) const;
pos operator-(const vec2 & yRef) const;
pos & operator*=(uint32 n);
pos & operator*=(uint64 n);
pos & operator*=(int32 n);
pos & operator*=(int64 n);
pos & operator*=(float32 n);
pos & operator*=(float64 n);
pos & operator/=(uint32 n);
pos & operator/=(uint64 n);
pos & operator/=(int32 n);
pos & operator/=(int64 n);
pos & operator/=(float32 n);
pos & operator/=(float64 n);
pos operator*(uint32 n);
pos operator*(uint64 n);
pos operator*(int32 n);
pos operator*(int64 n);
pos operator*(float32 n);
pos operator*(float64 n);
pos operator/(uint32 n);
pos operator/(uint64 n);
pos operator/(int32 n);
pos operator/(int64 n);
pos operator/(float32 n);
pos operator/(float64 n);
vec2 pos2D() const;
vec3 pos3D() const;
float32 length() const;
friend pos operator*(uint32 n, const pos & yRef);
friend pos operator*(uint64 n, const pos & yRef);
friend pos operator*(int32 n, const pos & yRef);
friend pos operator*(int64 n, const pos & yRef);
friend pos operator*(float32 n, const pos & yRef);
friend pos operator*(float64 n, const pos & yRef);
friend pos operator*(const vec2 & v, const pos & yRef);
friend pos operator/(uint32 n, const pos & yRef);
friend pos operator/(uint64 n, const pos & yRef);
friend pos operator/(int32 n, const pos & yRef);
friend pos operator/(int64 n, const pos & yRef);
friend pos operator/(float32 n, const pos & yRef);
friend pos operator/(float64 n, const pos & yRef);
friend pos operator/(const vec2 & v, const pos & yRef);
friend bool operator==(const vec2 & lRef, const pos & rRef);
friend bool operator!=(const vec2 & lRef, const pos & rRef);
};
}
| 1,105 |
5,169 | <reponame>Gantios/Specs
{
"name": "ScanditOCR",
"version": "6.9.2",
"homepage": "https://www.scandit.com",
"documentation_url": "https://docs.scandit.com/data-capture-sdk/ios/",
"license": {
"text": "Copyright 2020- Scandit",
"type": "Commercial"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"summary": "ScanditOCR provides core OCR functionality for other modules of the Scandit Data Capture SDK",
"platforms": {
"ios": "11.0"
},
"source": {
"http": "https://ssl.scandit.com/sdk/download/scandit-datacapture-ios-ocr-6.9.2.zip"
},
"requires_arc": true,
"pod_target_xcconfig": {
"EXCLUDED_ARCHS[sdk=iphonesimulator*]": "arm64"
},
"user_target_xcconfig": {
"EXCLUDED_ARCHS[sdk=iphonesimulator*]": "arm64"
},
"module_name": "ScanditOCR",
"vendored_frameworks": "ScanditOCR.framework"
}
| 369 |
2,151 | <reponame>zipated/src
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/html/forms/text_control_element.h"
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/position.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_text_area_element.h"
#include "third_party/blink/renderer/core/loader/empty_clients.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
namespace blink {
class TextControlElementTest : public testing::Test {
protected:
void SetUp() override;
DummyPageHolder& Page() const { return *dummy_page_holder_; }
Document& GetDocument() const { return *document_; }
TextControlElement& TextControl() const { return *text_control_; }
HTMLInputElement& Input() const { return *input_; }
private:
std::unique_ptr<DummyPageHolder> dummy_page_holder_;
Persistent<Document> document_;
Persistent<TextControlElement> text_control_;
Persistent<HTMLInputElement> input_;
};
void TextControlElementTest::SetUp() {
Page::PageClients page_clients;
FillWithEmptyClients(page_clients);
dummy_page_holder_ =
DummyPageHolder::Create(IntSize(800, 600), &page_clients);
document_ = &dummy_page_holder_->GetDocument();
document_->documentElement()->SetInnerHTMLFromString(
"<body><textarea id=textarea></textarea><input id=input /></body>");
document_->View()->UpdateAllLifecyclePhases();
text_control_ = ToTextControl(document_->getElementById("textarea"));
text_control_->focus();
input_ = ToHTMLInputElement(document_->getElementById("input"));
}
TEST_F(TextControlElementTest, SetSelectionRange) {
EXPECT_EQ(0u, TextControl().selectionStart());
EXPECT_EQ(0u, TextControl().selectionEnd());
TextControl().SetInnerEditorValue("Hello, text form.");
EXPECT_EQ(0u, TextControl().selectionStart());
EXPECT_EQ(0u, TextControl().selectionEnd());
TextControl().SetSelectionRange(1, 3);
EXPECT_EQ(1u, TextControl().selectionStart());
EXPECT_EQ(3u, TextControl().selectionEnd());
}
TEST_F(TextControlElementTest, SetSelectionRangeDoesNotCauseLayout) {
Input().focus();
Input().setValue("Hello, input form.");
Input().SetSelectionRange(1, 1);
// Force layout if document().updateStyleAndLayoutIgnorePendingStylesheets()
// is called.
GetDocument().body()->AppendChild(GetDocument().createTextNode("foo"));
const int start_layout_count = Page().GetFrameView().LayoutCount();
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
Input().SetSelectionRange(2, 2);
EXPECT_EQ(start_layout_count, Page().GetFrameView().LayoutCount());
}
TEST_F(TextControlElementTest, IndexForPosition) {
Input().setValue("Hello");
HTMLElement* inner_editor = Input().InnerEditorElement();
EXPECT_EQ(5u, TextControlElement::IndexForPosition(
inner_editor,
Position(inner_editor, PositionAnchorType::kAfterAnchor)));
}
TEST_F(TextControlElementTest, ReadOnlyAttributeChangeEditability) {
Input().setAttribute(HTMLNames::styleAttr, "all:initial");
Input().setAttribute(HTMLNames::readonlyAttr, "");
GetDocument().View()->UpdateAllLifecyclePhases();
EXPECT_EQ(EUserModify::kReadOnly,
Input().InnerEditorElement()->GetComputedStyle()->UserModify());
Input().removeAttribute(HTMLNames::readonlyAttr);
GetDocument().View()->UpdateAllLifecyclePhases();
EXPECT_EQ(EUserModify::kReadWritePlaintextOnly,
Input().InnerEditorElement()->GetComputedStyle()->UserModify());
}
TEST_F(TextControlElementTest, DisabledAttributeChangeEditability) {
Input().setAttribute(HTMLNames::styleAttr, "all:initial");
Input().setAttribute(HTMLNames::disabledAttr, "");
GetDocument().View()->UpdateAllLifecyclePhases();
EXPECT_EQ(EUserModify::kReadOnly,
Input().InnerEditorElement()->GetComputedStyle()->UserModify());
Input().removeAttribute(HTMLNames::disabledAttr);
GetDocument().View()->UpdateAllLifecyclePhases();
EXPECT_EQ(EUserModify::kReadWritePlaintextOnly,
Input().InnerEditorElement()->GetComputedStyle()->UserModify());
}
} // namespace blink
| 1,602 |
2,322 | GET_TEAMS_DATA = [
{
"id": "PQ9K7I8",
"type": "team",
"summary": "Engineering",
"self": "https://api.pagerduty.com/teams/PQ9K7I8",
"html_url": "https://subdomain.pagerduty.com/teams/PQ9K7I8",
"name": "Engineering",
"description": "All engineering",
},
]
| 169 |
826 | <reponame>dartartem/eventuate-tram-sagas
package io.eventuate.tram.sagas.eventsourcingsupport;
import io.eventuate.DispatchedEvent;
import io.eventuate.Event;
import io.eventuate.SubscriberOptions;
import io.eventuate.sync.EventuateAggregateStore;
import io.eventuate.tram.commands.common.CommandMessageHeaders;
import io.eventuate.tram.commands.consumer.CommandHandlerReplyBuilder;
import io.eventuate.tram.messaging.common.ChannelMapping;
import io.eventuate.tram.messaging.common.Message;
import io.eventuate.tram.messaging.producer.MessageBuilder;
import io.eventuate.tram.messaging.producer.MessageProducer;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toMap;
public class SagaReplyRequestedEventSubscriber {
@Autowired
private MessageProducer messageProducer;
@Autowired
private EventuateAggregateStore aggregateStore;
private String subscriberId;
private Set<String> aggregateTypes;
public SagaReplyRequestedEventSubscriber(String subscriberId, Set<String> aggregateTypes) {
this.subscriberId = subscriberId;
this.aggregateTypes = aggregateTypes;
}
@PostConstruct
public void subscribe() {
Map<String, Set<String>> aggregatesAndEvents =
aggregateTypes.stream().collect(toMap(Function.identity(), x -> singleton(SagaReplyRequestedEvent.class.getName())));
aggregateStore.subscribe(subscriberId,
aggregatesAndEvents,
SubscriberOptions.DEFAULTS,
this::sendReply);
}
public CompletableFuture<Object> sendReply(DispatchedEvent<Event> de) {
SagaReplyRequestedEvent event = (SagaReplyRequestedEvent) de.getEvent();
Message reply = CommandHandlerReplyBuilder.withSuccess();
messageProducer.send(event.getCorrelationHeaders().get(CommandMessageHeaders.inReply(CommandMessageHeaders.REPLY_TO)),
MessageBuilder
.withMessage(reply)
.withExtraHeaders("", event.getCorrelationHeaders())
.build());
return CompletableFuture.completedFuture(null);
}
}
| 791 |
849 | <filename>lte/gateway/python/magma/policydb/servicers/policy_servicer.py
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import logging
from typing import List
import grpc
from lte.protos.policydb_pb2 import (
DisableStaticRuleRequest,
EnableStaticRuleRequest,
)
from lte.protos.policydb_pb2_grpc import (
PolicyAssignmentControllerStub,
PolicyDBServicer,
add_PolicyDBServicer_to_server,
)
from lte.protos.session_manager_pb2 import (
PolicyReAuthRequest,
StaticRuleInstall,
)
from magma.policydb.basename_store import BaseNameDict
from magma.policydb.reauth_handler import ReAuthHandler
from orc8r.protos.common_pb2 import Void
class PolicyRpcServicer(PolicyDBServicer):
"""
gRPC based server for PolicyDB service.
This will act as a bare-bones local PCRF and OCS.
In current implementation, it is only used for enabling the Captive Portal
feature.
"""
def __init__(
self,
reauth_handler: ReAuthHandler,
rules_by_basename: BaseNameDict,
subscriberdb_stub: PolicyAssignmentControllerStub,
):
self._reauth_handler = reauth_handler
self._rules_by_basename = rules_by_basename
self._subscriberdb_stub = subscriberdb_stub
def add_to_server(self, server):
""" Add the servicer to a gRPC server """
add_PolicyDBServicer_to_server(
self, server,
)
def EnableStaticRules(
self,
request: EnableStaticRuleRequest,
context,
) -> Void:
"""
Associate the static rules with the specified subscriber.
Also send a RAR to sessiond to install the specified rules for the
subscriber.
"""
try:
self._subscriberdb_stub.EnableStaticRules(request)
except grpc.RpcError:
logging.error(
'Unable to enable rules for subscriber %s. ',
request.imsi,
)
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Failed to update rule assignments in orc8r')
return Void()
rules_to_install = self._get_rules(
request.rule_ids, request.base_names,
)
rar = PolicyReAuthRequest(
# Leave session id empty, re-auth for all sessions
imsi=request.imsi,
rules_to_install=[
StaticRuleInstall(rule_id=rule_id)
for rule_id in rules_to_install
],
)
success = self._reauth_handler.handle_policy_re_auth(rar)
if not success:
context.set_code(grpc.StatusCode.UNKNOWN)
context.set_details(
'Failed to enable all static rules for '
'subscriber. Partial update may have succeeded',
)
return Void()
def DisableStaticRules(
self,
request: DisableStaticRuleRequest,
context,
) -> Void:
"""
Unassociate the static rules with the specified subscriber.
Also send a RAR to sessiond to uninstall the specified rules for the
subscriber.
"""
try:
self._subscriberdb_stub.DisableStaticRules(request)
except grpc.RpcError:
logging.error(
'Unable to disable rules for subscriber %s. ',
request.imsi,
)
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Failed to update rule assignments in orc8r')
return Void()
rar = PolicyReAuthRequest(
# Leave session id empty, re-auth for all sessions
imsi=request.imsi,
rules_to_remove=self._get_rules(
request.rule_ids,
request.base_names,
),
)
success = self._reauth_handler.handle_policy_re_auth(rar)
if not success:
context.set_code(grpc.StatusCode.UNKNOWN)
context.set_details(
'Failed to enable all static rules for '
'subscriber. Partial update may have succeeded',
)
return Void()
def _get_rules(
self,
rule_ids: List[str],
basenames: List[str],
) -> List[str]:
rules = set(rule_ids)
for basename in basenames:
if basename in self._rules_by_basename:
rules.update(self._rules_by_basename[basename].RuleNames)
return list(rules)
| 2,146 |
892 | <filename>advisories/github-reviewed/2022/01/GHSA-99p8-9p2c-49j4/GHSA-99p8-9p2c-49j4.json<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-99p8-9p2c-49j4",
"modified": "2022-01-19T19:40:50Z",
"published": "2022-01-21T23:20:16Z",
"aliases": [
"CVE-2022-21695"
],
"summary": "Improper Access Control in Onionshare",
"details": "Between September 26, 2021 and October 8, 2021, [Radically Open Security](https://www.radicallyopensecurity.com/) conducted a penetration test of OnionShare 2.4, funded by the Open Technology Fund's [Red Team lab](https://www.opentech.fund/labs/red-team-lab/). This is an issue from that penetration test.\n\n- Vulnerability ID: OTF-009\n- Vulnerability type: Improper Access Control\n- Threat level: Low\n\n## Description:\n\nAuthenticated users (or unauthenticated in public mode) can send messages without being visible in the list of chat participants.\n\n## Technical description:\n\nPrerequisites:\n\n- Existing chatroom\n- Access to the chatroom (Public or known Private Key)\n- Either a modified frontend client or manual requests from burp/curl\n\nIf a user opens the chatroom without emitting the join message he will not be present in session.users[x] list. Therefore there is no listing in the frontend and no chat participant knows another party joined the chat. It is still possible to send messages in the chatroom.\n\nIf a user decides to abuse OTF-003 (page 22) he can impersonate messages from existing users; others would not be able to distinguish original and faked messages. This is also a prerequisite for OTF-004 (page 19).\n\n## Impact:\n\nAn adversary with access to the chat environment can send messages to the chat without being visible in the list of chat participants.\n\n## Recommendation:\n\n- Allow chat access only after emission of the join event.\n- Implement proper session handling.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:N/A:N"
}
],
"affected": [
{
"package": {
"ecosystem": "PyPI",
"name": "onionshare-cli"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "0"
},
{
"fixed": "2.5"
}
]
}
]
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/onionshare/onionshare/security/advisories/GHSA-99p8-9p2c-49j4"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21695"
},
{
"type": "WEB",
"url": "https://github.com/onionshare/onionshare/releases/tag/v2.5"
},
{
"type": "PACKAGE",
"url": "https://github.com/onionshare/onionshare"
}
],
"database_specific": {
"cwe_ids": [
"CWE-287"
],
"severity": "MODERATE",
"github_reviewed": true
}
} | 1,199 |
14,668 | <gh_stars>1000+
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WIDGET_WIDGET_BASE_CLIENT_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WIDGET_WIDGET_BASE_CLIENT_H_
#include <vector>
#include "base/time/time.h"
#include "cc/metrics/begin_main_frame_metrics.h"
#include "cc/metrics/frame_sequence_tracker_collection.h"
#include "cc/metrics/web_vital_metrics.h"
#include "cc/paint/element_id.h"
#include "cc/trees/layer_tree_host_client.h"
#include "third_party/blink/public/common/metrics/document_update_reason.h"
#include "third_party/blink/public/platform/web_input_event_result.h"
#include "third_party/blink/public/platform/web_text_input_type.h"
#include "third_party/blink/public/web/web_lifecycle_update.h"
#include "third_party/blink/renderer/platform/widget/input/input_handler_proxy.h"
#include "ui/display/mojom/screen_orientation.mojom-blink.h"
namespace cc {
class LayerTreeFrameSink;
struct BeginMainFrameMetrics;
struct WebVitalMetrics;
} // namespace cc
namespace blink {
class FrameWidget;
class WebGestureEvent;
class WebMouseEvent;
// This class is part of the foundation of all widgets. It provides
// callbacks from the compositing infrastructure that the individual widgets
// will need to implement.
class WidgetBaseClient {
public:
// Called to record the time taken to dispatch rAF aligned input.
virtual void RecordDispatchRafAlignedInputTime(
base::TimeTicks raf_aligned_input_start_time) {}
// Called to update the document lifecycle, advance the state of animations
// and dispatch rAF.
virtual void BeginMainFrame(base::TimeTicks frame_time) = 0;
// Requests that the lifecycle of the widget be updated.
virtual void UpdateLifecycle(WebLifecycleUpdate requested_update,
DocumentUpdateReason reason) = 0;
// TODO(crbug.com/704763): Remove the need for this.
virtual void SetSuppressFrameRequestsWorkaroundFor704763Only(bool) {}
// Called when main frame metrics are desired. The local frame's UKM
// aggregator must be informed that collection is starting for the
// frame.
virtual void RecordStartOfFrameMetrics() {}
// Called when a main frame time metric should be emitted, along with
// any metrics that depend upon the main frame total time.
virtual void RecordEndOfFrameMetrics(
base::TimeTicks frame_begin_time,
cc::ActiveFrameSequenceTrackers trackers) {}
// Return metrics information for the stages of BeginMainFrame. This is
// ultimately implemented by Blink's LocalFrameUKMAggregator. It must be a
// distinct call from the FrameMetrics above because the BeginMainFrameMetrics
// for compositor latency must be gathered before the layer tree is
// committed to the compositor, which is before the call to
// RecordEndOfFrameMetrics.
virtual std::unique_ptr<cc::BeginMainFrameMetrics>
GetBeginMainFrameMetrics() {
return nullptr;
}
virtual std::unique_ptr<cc::WebVitalMetrics> GetWebVitalMetrics() {
return nullptr;
}
// Methods called to mark the beginning and end of the
// LayerTreeHost::UpdateLayers method. Only called when gathering main frame
// UMA and UKM. That is, when RecordStartOfFrameMetrics has been called, and
// before RecordEndOfFrameMetrics has been called.
virtual void BeginUpdateLayers() {}
virtual void EndUpdateLayers() {}
// Methods called to mark the beginning and end of a commit to the impl
// thread for a frame. Only called when gathering main frame
// UMA and UKM. That is, when RecordStartOfFrameMetrics has been called, and
// before RecordEndOfFrameMetrics has been called.
virtual void BeginCommitCompositorFrame() {}
virtual void EndCommitCompositorFrame(base::TimeTicks commit_start_time,
base::TimeTicks commit_finish_time) {}
// Applies viewport related properties during a commit from the compositor
// thread.
virtual void ApplyViewportChanges(const cc::ApplyViewportChangesArgs& args) {}
virtual void UpdateCompositorScrollState(
const cc::CompositorCommitData& commit_data) {}
// Notifies that the layer tree host has completed a call to
// RequestMainFrameUpdate in response to a BeginMainFrame.
virtual void DidBeginMainFrame() {}
virtual void DidCommitAndDrawCompositorFrame() {}
virtual void DidObserveFirstScrollDelay(
base::TimeDelta first_scroll_delay,
base::TimeTicks first_scroll_timestamp) {}
virtual void WillBeginMainFrame() {}
virtual void DidCompletePageScaleAnimation() {}
// Allocates a LayerTreeFrameSink to submit CompositorFrames to. Only
// override this method if you wish to provide your own implementation
// of LayerTreeFrameSinks (usually for tests). If this method returns null
// a frame sink will be requested from the browser process (ie. default flow)
virtual std::unique_ptr<cc::LayerTreeFrameSink>
AllocateNewLayerTreeFrameSink() = 0;
virtual void FocusChangeComplete() {}
virtual WebInputEventResult DispatchBufferedTouchEvents() = 0;
virtual WebInputEventResult HandleInputEvent(
const WebCoalescedInputEvent&) = 0;
virtual bool SupportsBufferedTouchEvents() = 0;
virtual void DidHandleKeyEvent() {}
virtual void WillHandleGestureEvent(const WebGestureEvent& event,
bool* suppress) = 0;
virtual void WillHandleMouseEvent(const WebMouseEvent& event) = 0;
virtual void ObserveGestureEventAndResult(
const WebGestureEvent& gesture_event,
const gfx::Vector2dF& unused_delta,
const cc::OverscrollBehavior& overscroll_behavior,
bool event_processed) = 0;
virtual WebTextInputType GetTextInputType() {
return WebTextInputType::kWebTextInputTypeNone;
}
// Called to inform the Widget of the mouse cursor's visibility.
virtual void SetCursorVisibilityState(bool is_visible) {}
// The FrameWidget interface if this is a FrameWidget.
virtual blink::FrameWidget* FrameWidget() { return nullptr; }
// Called to inform the Widget that it has gained or lost keyboard focus.
virtual void FocusChanged(bool) {}
// Call to request an animation frame from the compositor.
virtual void ScheduleAnimation() {}
// TODO(bokan): Temporary to unblock synthetic gesture events running under
// VR. https://crbug.com/940063
virtual bool ShouldAckSyntheticInputImmediately() { return false; }
// Apply the visual properties.
virtual void UpdateVisualProperties(
const VisualProperties& visual_properties) = 0;
// A callback to apply the updated screen rects, return true if it
// was handled. If not handled WidgetBase will apply the screen
// rects as the new values.
virtual bool UpdateScreenRects(const gfx::Rect& widget_screen_rect,
const gfx::Rect& window_screen_rect) {
return false;
}
// Convert screen coordinates to device emulated coordinates (scaled
// coordinates when devtools is used). This occurs for popups where their
// window bounds are emulated.
virtual void ScreenRectToEmulated(gfx::Rect& screen_rect) {}
virtual void EmulatedToScreenRect(gfx::Rect& screen_rect) {}
// Signal the orientation has changed.
virtual void OrientationChanged() {}
// Return the original (non-emulated) screen infos.
virtual const display::ScreenInfos& GetOriginalScreenInfos() = 0;
// Indication that the surface and screen were updated.
virtual void DidUpdateSurfaceAndScreen(
const display::ScreenInfos& previous_original_screen_infos) {}
// Return the viewport visible rect.
virtual gfx::Rect ViewportVisibleRect() = 0;
// The screen orientation override.
virtual absl::optional<display::mojom::blink::ScreenOrientation>
ScreenOrientationOverride() {
return absl::nullopt;
}
// Return the overridden device scale factor for testing.
virtual float GetTestingDeviceScaleFactorOverride() { return 0.f; }
// Test-specific methods below this point.
virtual void ScheduleAnimationForWebTests() {}
// Inform the widget that it was hidden.
virtual void WasHidden() {}
// Inform the widget that it was shown.
virtual void WasShown(bool was_evicted) {}
virtual void RunPaintBenchmark(int repeat_count,
cc::PaintBenchmarkResult& result) {}
// Called to indicate a synthetic event was queued.
virtual void WillQueueSyntheticEvent(const WebCoalescedInputEvent& event) {}
// When the WebWidget is part of a frame tree, returns the active url for
// main frame of that tree, if the main frame is local in that tree. When
// the WebWidget is of a different kind (e.g. a popup) it returns the active
// url for the main frame of the frame tree that spawned the WebWidget, if
// the main frame is local in that tree. When the relevant main frame is
// remote in that frame tree, then the url is not known, and an empty url is
// returned.
virtual KURL GetURLForDebugTrace() = 0;
// In EventTiming, we count the events invoked by user interactions. Some
// touchstarts will be dropped before they get sent to the main thread.
// Meanwhile, the corresponding pointerdown will not be fired. The following
// pointerup will be captured in pointer_event_manager. The following touchend
// will not be dispatched because there's no target which is always set by
// touchstart. But we still want to count those touchstart, pointerdown and
// touchend.
virtual void CountDroppedPointerDownForEventTiming(unsigned count) {}
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WIDGET_WIDGET_BASE_CLIENT_H_
| 2,927 |
1,127 | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <ie_compound_blob.h>
#include <gtest/gtest.h>
#include <random>
#include <chrono>
using namespace ::testing;
using namespace std;
using namespace InferenceEngine;
class CompoundBlobTests : public ::testing::Test {
protected:
Blob::Ptr _test_blob;
using BlobPtrs = std::vector<Blob::Ptr>;
using MemoryBlobPtrs = std::vector<MemoryBlob::Ptr>;
public:
void verifyCompoundBlob(const Blob::Ptr& blob) {
// verify basic assumptions about a compound blob
ASSERT_NE(nullptr, blob);
ASSERT_TRUE(blob->is<CompoundBlob>());
CompoundBlob::Ptr compound_blob = as<CompoundBlob>(blob);
ASSERT_NE(nullptr, compound_blob);
EXPECT_EQ(compound_blob.get(), blob->as<CompoundBlob>()); // shared object == raw ptr
EXPECT_EQ(0, compound_blob->element_size());
EXPECT_EQ(nullptr, compound_blob->buffer());
EXPECT_EQ(nullptr, compound_blob->cbuffer());
EXPECT_GT(compound_blob->size(), 0);
EXPECT_NE(nullptr, compound_blob->getBlob(0));
}
void verifyCompoundBlob(Blob::Ptr blob, const BlobPtrs& underlying_blobs) {
verifyCompoundBlob(blob);
// check that the compound blob contains a vector of provided underlying blobs
CompoundBlob::Ptr compound_blob = as<CompoundBlob>(blob);
EXPECT_EQ(compound_blob.get(), blob->as<CompoundBlob>()); // shared object == raw ptr
ASSERT_EQ(underlying_blobs.size(), compound_blob->size());
for (size_t i = 0; i < underlying_blobs.size(); ++i) {
EXPECT_EQ(underlying_blobs[i], compound_blob->getBlob(i));
}
}
};
class NV12BlobTests : public CompoundBlobTests {};
class I420BlobTests : public CompoundBlobTests {};
TEST(BlobConversionTests, canWorkWithMemoryBlob) {
Blob::Ptr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 3, 4, 4}, NCHW));
ASSERT_TRUE(blob->is<MemoryBlob>());
ASSERT_FALSE(blob->is<CompoundBlob>());
ASSERT_NE(nullptr, as<MemoryBlob>(blob));
ASSERT_EQ(nullptr, as<CompoundBlob>(blob));
ASSERT_EQ(as<MemoryBlob>(blob).get(), blob->as<MemoryBlob>());
ASSERT_EQ(as<CompoundBlob>(blob).get(), blob->as<CompoundBlob>());
}
TEST(BlobConversionTests, canWorkWithConstMemoryBlob) {
Blob::CPtr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 3, 4, 4}, NCHW));
ASSERT_TRUE(blob->is<MemoryBlob>());
ASSERT_FALSE(blob->is<CompoundBlob>());
ASSERT_NE(nullptr, as<MemoryBlob>(blob));
ASSERT_EQ(nullptr, as<CompoundBlob>(blob));
ASSERT_EQ(as<MemoryBlob>(blob).get(), blob->as<MemoryBlob>());
ASSERT_EQ(as<CompoundBlob>(blob).get(), blob->as<CompoundBlob>());
}
TEST(BlobConversionTests, canWorkWithTBlob) {
Blob::Ptr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 3, 4, 4}, NCHW));
ASSERT_TRUE(blob->is<TBlob<uint8_t>>());
ASSERT_FALSE(blob->is<TBlob<float>>());
ASSERT_FALSE(blob->is<CompoundBlob>());
ASSERT_NE(nullptr, as<TBlob<uint8_t>>(blob));
ASSERT_EQ(nullptr, as<TBlob<float>>(blob));
ASSERT_EQ(nullptr, as<CompoundBlob>(blob));
ASSERT_EQ(as<TBlob<uint8_t>>(blob).get(), blob->as<TBlob<uint8_t>>());
ASSERT_EQ(as<TBlob<float>>(blob).get(), blob->as<TBlob<float>>());
ASSERT_EQ(as<CompoundBlob>(blob).get(), blob->as<CompoundBlob>());
}
TEST(BlobConversionTests, canWorkWithConstTBlob) {
Blob::CPtr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 3, 4, 4}, NCHW));
ASSERT_TRUE(blob->is<TBlob<uint8_t>>());
ASSERT_FALSE(blob->is<TBlob<float>>());
ASSERT_FALSE(blob->is<CompoundBlob>());
ASSERT_NE(nullptr, as<TBlob<uint8_t>>(blob));
ASSERT_EQ(nullptr, as<TBlob<float>>(blob));
ASSERT_EQ(nullptr, as<CompoundBlob>(blob));
ASSERT_EQ(as<TBlob<uint8_t>>(blob).get(), blob->as<TBlob<uint8_t>>());
ASSERT_EQ(as<TBlob<float>>(blob).get(), blob->as<TBlob<float>>());
ASSERT_EQ(as<CompoundBlob>(blob).get(), blob->as<CompoundBlob>());
}
TEST(BlobConversionTests, canWorkWithCompoundBlob) {
Blob::Ptr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 3, 4, 4}, NCHW));
Blob::Ptr cblob = make_shared_blob<CompoundBlob>(std::vector<Blob::Ptr>({blob}));
ASSERT_TRUE(cblob->is<CompoundBlob>());
ASSERT_FALSE(cblob->is<MemoryBlob>());
ASSERT_NE(nullptr, as<CompoundBlob>(cblob));
ASSERT_EQ(nullptr, as<MemoryBlob>(cblob));
ASSERT_EQ(as<CompoundBlob>(cblob).get(), cblob->as<CompoundBlob>());
ASSERT_EQ(as<MemoryBlob>(cblob).get(), cblob->as<MemoryBlob>());
}
TEST(BlobConversionTests, canWorkWithConstCompoundBlob) {
Blob::Ptr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 3, 4, 4}, NCHW));
Blob::CPtr cblob = make_shared_blob<CompoundBlob>(std::vector<Blob::Ptr>({blob}));
ASSERT_TRUE(cblob->is<CompoundBlob>());
ASSERT_FALSE(cblob->is<MemoryBlob>());
ASSERT_NE(nullptr, as<CompoundBlob>(cblob));
ASSERT_EQ(nullptr, as<MemoryBlob>(cblob));
ASSERT_EQ(as<CompoundBlob>(cblob).get(), cblob->as<CompoundBlob>());
ASSERT_EQ(as<MemoryBlob>(cblob).get(), cblob->as<MemoryBlob>());
}
TEST(BlobConversionTests, blobSharesOwnershipOnCast) {
static constexpr const uint8_t stored_value = 123;
TBlob<uint8_t>::Ptr tblob;
{
Blob::Ptr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1}, HW));
ASSERT_EQ(1, blob.use_count());
ASSERT_TRUE(blob->is<TBlob<uint8_t>>());
tblob = as<TBlob<uint8_t>>(blob);
ASSERT_NE(nullptr, tblob);
ASSERT_EQ(2, blob.use_count());
ASSERT_EQ(2, tblob.use_count());
tblob->allocate();
tblob->data()[0] = stored_value;
ASSERT_EQ(stored_value, tblob->data()[0]);
}
ASSERT_EQ(1, tblob.use_count());
ASSERT_NE(nullptr, tblob);
ASSERT_EQ(stored_value, tblob->data()[0]);
}
TEST_F(CompoundBlobTests, cannotCreateCompoundBlobFromNullptr) {
Blob::Ptr valid = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 3, 4, 4}, NCHW));
EXPECT_THROW(make_shared_blob<CompoundBlob>(std::vector<Blob::Ptr>({valid, nullptr})),
InferenceEngine::Exception);
}
TEST_F(CompoundBlobTests, canCreateEmptyCompoundBlob) {
_test_blob = make_shared_blob<CompoundBlob>(std::vector<Blob::Ptr>());
ASSERT_NE(nullptr, _test_blob);
EXPECT_EQ(0, _test_blob->element_size());
EXPECT_EQ(nullptr, _test_blob->buffer());
EXPECT_EQ(nullptr, _test_blob->cbuffer());
ASSERT_TRUE(_test_blob->is<CompoundBlob>());
CompoundBlob::Ptr compound_blob = as<CompoundBlob>(_test_blob);
ASSERT_NE(nullptr, compound_blob);
EXPECT_EQ(0, compound_blob->size());
EXPECT_EQ(nullptr, compound_blob->getBlob(0));
}
TEST_F(CompoundBlobTests, canCreateCompoundBlob) {
// Create a blob with NCHW layout and pass it to compound for test
Blob::Ptr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 3, 4, 4}, NCHW));
BlobPtrs blobs = {blob};
_test_blob = make_shared_blob<CompoundBlob>(blobs);
verifyCompoundBlob(_test_blob, blobs);
}
TEST_F(CompoundBlobTests, cannotCreateCompoundBlobFromCompoundBlob) {
// Create a blob with NCHW layout and pass it to compound for test. The created compound blob
// cannot be used to construct another compound blob. Recursive behavior is rejected
Blob::Ptr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 3, 4, 4}, NCHW));
_test_blob = make_shared_blob<CompoundBlob>(std::vector<Blob::Ptr>({blob}));
verifyCompoundBlob(_test_blob);
EXPECT_THROW(make_shared_blob<CompoundBlob>(std::vector<Blob::Ptr>({blob, _test_blob})),
InferenceEngine::Exception);
}
TEST_F(CompoundBlobTests, compoundBlobHoldsCorrectDataInCorrectOrder) {
// Create a vector of blobs with HW layout and pass it to a compound blob to test if the vector
// is stored correctly
static constexpr const uint8_t MAGIC_NUMBER = 23;
BlobPtrs blobs(5);
for (size_t i = 0; i < blobs.size(); ++i) {
blobs[i] = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1}, HW));
blobs[i]->allocate();
MemoryBlob::Ptr mb = as<MemoryBlob>(blobs[i]);
auto lm = mb->rwmap();
lm.as<uint8_t*>()[0] = static_cast<uint8_t>(i + MAGIC_NUMBER);
}
_test_blob = make_shared_blob<CompoundBlob>(blobs);
verifyCompoundBlob(_test_blob, blobs);
CompoundBlob::Ptr compound_blob = as<CompoundBlob>(_test_blob);
EXPECT_EQ(blobs.size(), compound_blob->size());
for (size_t i = 0; i < compound_blob->size(); ++i) {
auto blob = compound_blob->getBlob(i);
ASSERT_NE(nullptr, blob);
MemoryBlob::Ptr mb = as<MemoryBlob>(blob);
ASSERT_NE(nullptr, mb);
auto lm = mb->rwmap();
EXPECT_EQ(static_cast<uint8_t>(i + MAGIC_NUMBER), lm.as<uint8_t *>()[0]);
}
}
TEST_F(CompoundBlobTests, compoundBlobHoldsReferencesToBlobs) {
// Create a blob with HW layout and pass it to a compound blob to check that the compound blob
// holds references to the blob and not a copy of it
MemoryBlob::Ptr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1}, HW));
blob->allocate();
// here is quite self to dereference address since LockedMemory would be destroyed only after assignemnt
blob->rwmap().as<uint8_t*>()[0] = 12;
_test_blob = make_shared_blob<CompoundBlob>(std::vector<Blob::Ptr>({blob}));
verifyCompoundBlob(_test_blob);
CompoundBlob::Ptr compound_blob = as<CompoundBlob>(_test_blob);
Blob::Ptr b0 = compound_blob->getBlob(0);
MemoryBlob::CPtr mb0 = as<MemoryBlob>(b0);
EXPECT_EQ(12, mb0->rmap().as<const uint8_t *>()[0]);
blob->rwmap().as<uint8_t*>()[0] = 34;
EXPECT_EQ(34, mb0->rmap().as<const uint8_t *>()[0]);
}
TEST_F(CompoundBlobTests, compoundBlobHoldsValidDataWhenUnderlyingBlobIsDestroyed) {
// Create a scoped blob with HW layout, pass it to compound, and destroy the original scoped
// blob. Check that the compound blob, which holds a reference to the destroyed blob, still has
// a valid object
static constexpr const uint8_t stored_value = 123;
{
MemoryBlob::Ptr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1}, HW));
blob->allocate();
blob->rwmap().as<uint8_t*>()[0] = stored_value;
_test_blob = make_shared_blob<CompoundBlob>(std::vector<Blob::Ptr>({blob}));
}
verifyCompoundBlob(_test_blob);
CompoundBlob::Ptr compound_blob = as<CompoundBlob>(_test_blob);
ASSERT_NE(nullptr, compound_blob->getBlob(0));
MemoryBlob::CPtr mb0 = as<MemoryBlob>(compound_blob->getBlob(0));
ASSERT_NE(nullptr, mb0);
EXPECT_EQ(stored_value, mb0->rmap().as<const uint8_t *>()[0]);
}
TEST_F(NV12BlobTests, cannotCreateNV12BlobFromNullptrBlobs) {
Blob::Ptr valid = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 4, 4}, NHWC));
EXPECT_THROW(make_shared_blob<NV12Blob>(valid, nullptr),
InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<NV12Blob>(nullptr, valid),
InferenceEngine::Exception);
}
TEST_F(NV12BlobTests, cannotCreateNV12BlobFromCompoundBlobs) {
Blob::Ptr blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 4, 4}, NHWC));
auto cblob = make_shared_blob<CompoundBlob>(std::vector<Blob::Ptr>({blob}));
EXPECT_THROW(make_shared_blob<NV12Blob>(cblob, blob),
InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<NV12Blob>(blob, cblob),
InferenceEngine::Exception);
}
TEST_F(NV12BlobTests, cannotCreateNV12BlobFromPlanesWithDifferentElementSize) {
Blob::Ptr blob_u8 = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 4, 4}, NHWC));
Blob::Ptr blob_float = make_shared_blob<float>(TensorDesc(Precision::FP32, {1, 2, 2, 2}, NHWC));
EXPECT_THROW(make_shared_blob<NV12Blob>(blob_u8, blob_float),
InferenceEngine::Exception);
}
TEST_F(NV12BlobTests, cannotCreateNV12BlobFromPlanesWithNonU8Precision) {
Blob::Ptr float_y_blob = make_shared_blob<float>(TensorDesc(Precision::FP32, {1, 1, 4, 4}, NHWC));
Blob::Ptr float_uv_blob = make_shared_blob<float>(TensorDesc(Precision::FP32, {1, 2, 2, 2}, NHWC));
EXPECT_THROW(make_shared_blob<NV12Blob>(float_y_blob, float_uv_blob),
InferenceEngine::Exception);
}
TEST_F(NV12BlobTests, cannotCreateNV12BlobFromPlanesWithInconsistentBatchSize) {
Blob::Ptr y = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 4, 4}, NHWC));
Blob::Ptr uv = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {2, 2, 2, 2}, NHWC));
EXPECT_THROW(make_shared_blob<NV12Blob>(y, uv), InferenceEngine::Exception);
}
TEST_F(NV12BlobTests, cannotCreateNV12BlobFromPlanesWithWrongChannelNumber) {
Blob::Ptr y = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 4, 4}, NHWC));
Blob::Ptr uv = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 2, 2}, NHWC));
EXPECT_THROW(make_shared_blob<NV12Blob>(y, y), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<NV12Blob>(uv, uv), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<NV12Blob>(uv, y), InferenceEngine::Exception);
}
TEST_F(NV12BlobTests, cannotCreateNV12BlobFromPlanesWithWrongWidthRatio) {
Blob::Ptr y = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 6}, NHWC));
Blob::Ptr uv0 = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 1, 3}, NHWC));
Blob::Ptr uv1 = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 5, 3}, NHWC));
Blob::Ptr uv2 = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 6, 3}, NHWC));
Blob::Ptr uv3 = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 8, 3}, NHWC));
EXPECT_THROW(make_shared_blob<NV12Blob>(y, uv0), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<NV12Blob>(y, uv1), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<NV12Blob>(y, uv2), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<NV12Blob>(y, uv3), InferenceEngine::Exception);
}
TEST_F(NV12BlobTests, cannotCreateNV12BlobFromPlanesWithWrongHeightRatio) {
Blob::Ptr y = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 6}, NHWC));
Blob::Ptr uv0 = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 3, 1}, NHWC));
Blob::Ptr uv1 = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 3, 5}, NHWC));
Blob::Ptr uv2 = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 3, 6}, NHWC));
Blob::Ptr uv3 = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 3, 8}, NHWC));
EXPECT_THROW(make_shared_blob<NV12Blob>(y, uv0), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<NV12Blob>(y, uv1), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<NV12Blob>(y, uv2), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<NV12Blob>(y, uv3), InferenceEngine::Exception);
}
TEST_F(NV12BlobTests, canCreateNV12BlobFromTwoPlanes) {
Blob::Ptr y_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 8}, NHWC));
Blob::Ptr uv_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 3, 4}, NHWC));
NV12Blob::Ptr nv12_blob = make_shared_blob<NV12Blob>(y_blob, uv_blob);
verifyCompoundBlob(nv12_blob, {y_blob, uv_blob});
EXPECT_EQ(y_blob, nv12_blob->y());
EXPECT_EQ(uv_blob, nv12_blob->uv());
}
TEST_F(NV12BlobTests, canCreateNV12BlobFromTwoMovedPlanes) {
NV12Blob::Ptr nv12_blob = make_shared_blob<NV12Blob>(
make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 8}, NHWC)),
make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 3, 4}, NHWC)));
verifyCompoundBlob(nv12_blob);
}
TEST_F(I420BlobTests, canCreateI420BlobFromThreePlanes) {
Blob::Ptr y_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 8}, NHWC));
Blob::Ptr u_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 4}, NHWC));
Blob::Ptr v_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 4}, NHWC));
I420Blob::Ptr i420_blob = make_shared_blob<I420Blob>(y_blob, u_blob, v_blob);
verifyCompoundBlob(i420_blob, {y_blob, u_blob, v_blob});
EXPECT_EQ(y_blob, i420_blob->y());
EXPECT_EQ(u_blob, i420_blob->u());
EXPECT_EQ(v_blob, i420_blob->v());
}
TEST_F(I420BlobTests, canCreateI420BlobFromThreeMovedPlanes) {
I420Blob::Ptr i420_blob = make_shared_blob<I420Blob>(
make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 8}, NHWC)),
make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 4}, NHWC)),
make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 4}, NHWC)));
verifyCompoundBlob(i420_blob);
}
TEST_F(I420BlobTests, cannotCreateI420BlobFromNullptrBlobs) {
Blob::Ptr valid = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 4, 4}, NHWC));
EXPECT_THROW(make_shared_blob<I420Blob>(valid, nullptr, nullptr), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<I420Blob>(nullptr, valid, nullptr), InferenceEngine::Exception);
}
TEST_F(I420BlobTests, cannotCreateI420BlobFromCompoundBlobs) {
Blob::Ptr y_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 8}, NHWC));
Blob::Ptr u_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 4}, NHWC));
Blob::Ptr v_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 4}, NHWC));
auto make_cblob = [](Blob::Ptr const& b){
return make_shared_blob<CompoundBlob>(std::vector<Blob::Ptr>({b}));
};
auto c_y_blob = make_cblob(y_blob);
auto c_u_blob = make_cblob(u_blob);
auto c_v_blob = make_cblob(v_blob);
using ie_exception_t = InferenceEngine::Exception;
EXPECT_THROW(make_shared_blob<I420Blob>(c_y_blob, u_blob, v_blob), ie_exception_t);
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob, c_u_blob, v_blob), ie_exception_t);
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob, u_blob, c_v_blob), ie_exception_t);
}
TEST_F(I420BlobTests, cannotCreateI420BlobFromPlanesWithDifferentElementSize) {
Blob::Ptr y_blob_u8 = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 4, 4}, NHWC));
Blob::Ptr u_blob_float = make_shared_blob<float>(TensorDesc(Precision::FP32, {1, 1, 2, 2}, NHWC));
Blob::Ptr v_blob_float = make_shared_blob<float>(TensorDesc(Precision::FP32, {1, 1, 2, 2}, NHWC));
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob_u8, u_blob_float, v_blob_float), InferenceEngine::Exception);
}
TEST_F(I420BlobTests, cannotCreateI420BlobFromPlanesWithNonU8Precision) {
Blob::Ptr y_blob_float = make_shared_blob<float>(TensorDesc(Precision::FP32, {1, 1, 4, 4}, NHWC));
Blob::Ptr u_blob_float = make_shared_blob<float>(TensorDesc(Precision::FP32, {1, 1, 2, 2}, NHWC));
Blob::Ptr v_blob_float = make_shared_blob<float>(TensorDesc(Precision::FP32, {1, 1, 2, 2}, NHWC));
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob_float, u_blob_float, v_blob_float), InferenceEngine::Exception);
}
TEST_F(I420BlobTests, cannotCreateI420BlobFromPlanesWithInconsistentBatchSize) {
Blob::Ptr y_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 8}, NHWC));
Blob::Ptr u_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {2, 1, 3, 4}, NHWC));
Blob::Ptr v_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 4}, NHWC));
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob, u_blob, v_blob), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob, v_blob, u_blob), InferenceEngine::Exception);
}
TEST_F(I420BlobTests, cannotCreateI420BlobFromPlanesWithWrongChannelNumber) {
Blob::Ptr y_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 8}, NHWC));
Blob::Ptr u_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 2, 3, 4}, NHWC));
Blob::Ptr v_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 4}, NHWC));
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob, u_blob, v_blob), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob, v_blob, u_blob), InferenceEngine::Exception);
}
TEST_F(I420BlobTests, cannotCreateI420BlobFromPlanesWithWrongWidthRatio) {
Blob::Ptr y_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 8}, NHWC));
Blob::Ptr u_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 2}, NHWC));
Blob::Ptr v_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 4}, NHWC));
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob, u_blob, v_blob), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob, v_blob, u_blob), InferenceEngine::Exception);
}
TEST_F(I420BlobTests, cannotCreateI420BlobFromPlanesWithWrongHeightRatio) {
Blob::Ptr y_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 6, 8}, NHWC));
Blob::Ptr u_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 2, 4}, NHWC));
Blob::Ptr v_blob = make_shared_blob<uint8_t>(TensorDesc(Precision::U8, {1, 1, 3, 4}, NHWC));
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob, u_blob, v_blob), InferenceEngine::Exception);
EXPECT_THROW(make_shared_blob<I420Blob>(y_blob, v_blob, u_blob), InferenceEngine::Exception);
}
| 9,686 |
355 | <reponame>Pasquy007/gvdb-voxels
// -------------------------------------------------------------
// cuDPP -- CUDA Data Parallel Primitives library
// -------------------------------------------------------------
// This source code is distributed under the terms of license.txt in
// the root directory of this source distribution.
// -------------------------------------------------------------
/**
* @file
* ppm.h
*
* @brief functions to find files and directories
*/
#ifndef _PPM_H_
#define _PPM_H_
namespace cudpp_app {
//////////////////////////////////////////////////////////////////////////////
//! Load PGM or PPM file
//! @note if data == NULL then the necessary memory is allocated in the
//! function and w and h are initialized to the size of the image
//! @return true if the file loading succeeded, otherwise false
//! @param file name of the file to load
//! @param data handle to the memory for the image file data
//! @param w width of the image
//! @param h height of the image
//! @param channels number of channels in image
//////////////////////////////////////////////////////////////////////////////
bool loadPPM( const char* file, unsigned char** data,
unsigned int *w, unsigned int *h, unsigned int *channels );
}
#ifdef CUDPP_APP_COMMON_IMPL
#include "ppm.inl"
#endif
#endif // _PPM_H_ | 424 |
392 | package com.platform.dao;
import com.platform.entity.AdVo;
/**
*
*
* @author lipengjun
* @email <EMAIL>
* @date 2017-08-11 09:14:25
*/
public interface ApiAdMapper extends BaseDao<AdVo> {
}
| 82 |
637 | <reponame>1st/jenkins<filename>core/src/main/java/hudson/cli/EnablePluginCommand.java<gh_stars>100-1000
/*
* The MIT License
*
* Copyright (c) 2018 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.cli;
import hudson.Extension;
import hudson.PluginManager;
import hudson.PluginWrapper;
import jenkins.model.Jenkins;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import java.io.IOException;
import java.util.List;
/**
* Enables one or more installed plugins. The listed plugins must already be installed along with its dependencies.
* Any listed plugin with disabled dependencies will have its dependencies enabled transitively. Note that enabling an
* already enabled plugin does nothing.
*
* @since 2.136
*/
@Extension
public class EnablePluginCommand extends CLICommand {
@Argument(required = true, usage = "Enables the plugins with the given short names and their dependencies.")
private List<String> pluginNames;
@Option(name = "-restart", usage = "Restart Jenkins after enabling plugins.")
private boolean restart;
@Override
public String getShortDescription() {
return Messages.EnablePluginCommand_ShortDescription();
}
@Override
protected int run() throws Exception {
Jenkins jenkins = Jenkins.get();
jenkins.checkPermission(Jenkins.ADMINISTER);
PluginManager manager = jenkins.getPluginManager();
boolean enabledAnyPlugins = false;
for (String pluginName : pluginNames) {
enabledAnyPlugins |= enablePlugin(manager, pluginName);
}
if (restart && enabledAnyPlugins) {
jenkins.safeRestart();
}
return 0;
}
private boolean enablePlugin(PluginManager manager, String shortName) throws IOException {
PluginWrapper plugin = manager.getPlugin(shortName);
if (plugin == null) {
throw new IllegalArgumentException(Messages.EnablePluginCommand_NoSuchPlugin(shortName));
}
if (plugin.isEnabled()) {
return false;
}
stdout.println(String.format("Enabling plugin `%s' (%s)", plugin.getShortName(), plugin.getVersion()));
enableDependencies(manager, plugin);
plugin.enable();
stdout.println(String.format("Plugin `%s' was enabled.", plugin.getShortName()));
return true;
}
private void enableDependencies(PluginManager manager, PluginWrapper plugin) throws IOException {
for (PluginWrapper.Dependency dep : plugin.getDependencies()) {
PluginWrapper dependency = manager.getPlugin(dep.shortName);
if (dependency == null) {
throw new IllegalArgumentException(Messages.EnablePluginCommand_MissingDependencies(plugin.getShortName(), dep));
}
if (!dependency.isEnabled()) {
enableDependencies(manager, dependency);
stdout.println(String.format("Enabling plugin dependency `%s' (%s) for `%s'", dependency.getShortName(), dependency.getVersion(), plugin.getShortName()));
dependency.enable();
}
}
}
}
| 1,402 |
468 | /*=============================================================================
GLIntercept - OpenGL intercept/debugging tool
Copyright (C) 2005 <NAME>
Licensed under the MIT license - See Docs\license.txt for details.
=============================================================================*/
#include "GLCore1_1.h"
#include "BuiltInFunction.h"
//Function prototypes. Only use in core override files.
#include "GLFunctions.h"
//
// Core OpenGL 1.1 function handlers
//
USING_ERRORLOG
//The driver to log calls by
extern GLDriver glDriver;
//The version of the OpenGL functions that the builtin wrappers call
// (Functions in this table may be over-ridden/replaced)
extern GLCoreDriver GLV_Builtin;
//A dummy value to pass to the logger
static int glcDummyValue=0xBAADF00D;
///////////////////////////////////////////////////////////////////////////////
//
GL_FUNCTION_WRAPPER_HEADER(glBegin, (GLenum mode), (mode))
{
PRE_FUNCTION(glBegin,(mode),mode);
//Test for existing glBegin mode
if(glDriver.GetBeginEndState())
{
LOGERR(("glBegin called while previous glBegin was not closed"));
}
else
{
//Flag that we are now in a Begin/End section
glDriver.SetBeginEndState(true);
}
GLV_Builtin.glBegin (mode);
POST_FUNCTION(glBegin)
}
///////////////////////////////////////////////////////////////////////////////
//
GL_FUNCTION_WRAPPER_HEADER(glEnd, (), ())
{
PRE_FUNCTION(glEnd,(),glcDummyValue);
GLV_Builtin.glEnd();
//Test for existing glBegin mode
if(!glDriver.GetBeginEndState())
{
LOGERR(("glEnd called whithout a glBegin"));
}
else
{
//Flag that we are out of the Begin/End section
glDriver.SetBeginEndState(false);
}
POST_FUNCTION(glEnd)
}
///////////////////////////////////////////////////////////////////////////////
//
GL_FUNCTION_WRAPPER_HEADER(glNewList, (GLuint list, GLenum mode), (list, mode))
{
PRE_FUNCTION(glNewList,(list, mode),list);
//Test for existing glNewList mode
if(glDriver.GetNewListState())
{
LOGERR(("glNewList called while previous glNewList was not closed"));
}
else
{
//Flag that we are now in a glNewList/glEndList section
glDriver.SetNewListState(true);
}
GLV_Builtin.glNewList (list,mode);
POST_FUNCTION(glNewList)
}
///////////////////////////////////////////////////////////////////////////////
//
GL_FUNCTION_WRAPPER_HEADER(glEndList, (), ())
{
PRE_FUNCTION(glEndList,(),glcDummyValue);
GLV_Builtin.glEndList();
//Test for existing glNewList mode
if(!glDriver.GetNewListState())
{
LOGERR(("glEndList called whithout a glNewList"));
}
else
{
//Flag that we are out of the glNewList/glEndList section
glDriver.SetNewListState(false);
}
POST_FUNCTION(glEndList)
}
///////////////////////////////////////////////////////////////////////////////
//
GL_FUNCTION_WRAPPER_HEADER_RET(glGetError, (), (), GLenum)
{
PRE_FUNCTION(glGetError,(),glcDummyValue);
//Get the cached value from the driver
GLenum retValue = glDriver.GetCachedErrorCode();
//If the cached value is "no-error" call and return the correct error
if(retValue == GL_NO_ERROR)
{
retValue = GLV_Builtin.glGetError();
}
else
{
//Reset the cached error code (so further calls do not get the same error)
glDriver.ResetCachedErrorCode();
}
POST_FUNCTION_RET(glGetError,retValue)
return retValue;
}
//Generated built in wrappers
GL_FUNCTION_WRAPPER(glClearIndex,(GLfloat c), (c), c);
GL_FUNCTION_WRAPPER(glClearColor,(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glClear,(GLbitfield mask), (mask), mask);
GL_FUNCTION_WRAPPER(glIndexMask,(GLuint mask), (mask), mask);
GL_FUNCTION_WRAPPER(glColorMask,(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glAlphaFunc,(GLenum func, GLfloat ref), (func, ref), func);
GL_FUNCTION_WRAPPER(glBlendFunc,(GLenum sfactor, GLenum dfactor), (sfactor, dfactor), sfactor);
GL_FUNCTION_WRAPPER(glLogicOp,(GLenum opcode), (opcode), opcode);
GL_FUNCTION_WRAPPER(glCullFace,(GLenum mode), (mode), mode);
GL_FUNCTION_WRAPPER(glFrontFace,(GLenum mode), (mode), mode);
GL_FUNCTION_WRAPPER(glPointSize,(GLfloat size), (size), size);
GL_FUNCTION_WRAPPER(glLineWidth,(GLfloat width), (width), width);
GL_FUNCTION_WRAPPER(glLineStipple,(GLint factor, GLushort pattern), (factor, pattern), factor);
GL_FUNCTION_WRAPPER(glPolygonMode,(GLenum face, GLenum mode), (face, mode), face);
GL_FUNCTION_WRAPPER(glPolygonOffset,(GLfloat factor, GLfloat units), (factor, units), factor);
GL_FUNCTION_WRAPPER(glPolygonStipple,(const GLubyte *mask), (mask), mask);
GL_FUNCTION_WRAPPER(glGetPolygonStipple,(GLubyte *mask), (mask), mask);
GL_FUNCTION_WRAPPER(glEdgeFlag,(GLboolean flag), (flag), flag);
GL_FUNCTION_WRAPPER(glEdgeFlagv,(const GLboolean *flag), (flag), flag);
GL_FUNCTION_WRAPPER(glScissor,(GLint x, GLint y, GLsizei width, GLsizei height), (x, y, width, height), x);
GL_FUNCTION_WRAPPER(glClipPlane,(GLenum plane, const GLdouble *equation), (plane, equation), plane);
GL_FUNCTION_WRAPPER(glGetClipPlane,(GLenum plane, GLdouble *equation), (plane, equation), plane);
GL_FUNCTION_WRAPPER(glDrawBuffer,(GLenum mode), (mode), mode);
GL_FUNCTION_WRAPPER(glReadBuffer,(GLenum mode), (mode), mode);
GL_FUNCTION_WRAPPER(glEnable,(GLenum cap), (cap), cap);
GL_FUNCTION_WRAPPER(glDisable,(GLenum cap), (cap), cap);
GL_FUNCTION_WRAPPER_RET(glIsEnabled,(GLenum cap), (cap), cap, GLboolean);
GL_FUNCTION_WRAPPER(glEnableClientState,(GLenum cap), (cap), cap);
GL_FUNCTION_WRAPPER(glDisableClientState,(GLenum cap), (cap), cap);
GL_FUNCTION_WRAPPER(glGetBooleanv,(GLenum pname, GLboolean *params), (pname, params), pname);
GL_FUNCTION_WRAPPER(glGetDoublev,(GLenum pname, GLdouble *params), (pname, params), pname);
GL_FUNCTION_WRAPPER(glGetFloatv,(GLenum pname, GLfloat *params), (pname, params), pname);
GL_FUNCTION_WRAPPER(glGetIntegerv,(GLenum pname, GLint *params), (pname, params), pname);
GL_FUNCTION_WRAPPER(glPushAttrib,(GLbitfield mask), (mask), mask);
GL_FUNCTION_WRAPPER(glPopAttrib,(), (), glcDummyValue);
GL_FUNCTION_WRAPPER(glPushClientAttrib,(GLbitfield mask), (mask), mask);
GL_FUNCTION_WRAPPER(glPopClientAttrib,(), (), glcDummyValue);
GL_FUNCTION_WRAPPER_RET(glRenderMode,(GLenum mode), (mode), mode, GLint);
//GL_FUNCTION_WRAPPER_RET(glGetError,(GLvoid ), (), glcDummyValue, GLenum);
GL_FUNCTION_WRAPPER_RET(glGetString,(GLenum name), (name), name, const GLubyte *);
GL_FUNCTION_WRAPPER(glFinish,(), (), glcDummyValue);
GL_FUNCTION_WRAPPER(glFlush,(), (), glcDummyValue);
GL_FUNCTION_WRAPPER(glHint,(GLenum target, GLenum mode), (target, mode), target);
GL_FUNCTION_WRAPPER(glClearDepth,(GLdouble depth), (depth), depth);
GL_FUNCTION_WRAPPER(glDepthFunc,(GLenum func), (func), func);
GL_FUNCTION_WRAPPER(glDepthMask,(GLboolean flag), (flag), flag);
GL_FUNCTION_WRAPPER(glDepthRange,(GLdouble near_val, GLdouble far_val), (near_val, far_val), near_val);
GL_FUNCTION_WRAPPER(glClearAccum,(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glAccum,(GLenum op, GLfloat value), (op, value), op);
GL_FUNCTION_WRAPPER(glMatrixMode,(GLenum mode), (mode), mode);
GL_FUNCTION_WRAPPER(glOrtho,(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val), (left, right, bottom, top, near_val, far_val), left);
GL_FUNCTION_WRAPPER(glFrustum,(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val), (left, right, bottom, top, near_val, far_val), left);
GL_FUNCTION_WRAPPER(glViewport,(GLint x, GLint y, GLsizei width, GLsizei height), (x, y, width, height), x);
GL_FUNCTION_WRAPPER(glPushMatrix,(), (), glcDummyValue);
GL_FUNCTION_WRAPPER(glPopMatrix,(), (), glcDummyValue);
GL_FUNCTION_WRAPPER(glLoadIdentity,(), (), glcDummyValue);
GL_FUNCTION_WRAPPER(glLoadMatrixd,(const GLdouble *m), (m), m);
GL_FUNCTION_WRAPPER(glLoadMatrixf,(const GLfloat *m), (m), m);
GL_FUNCTION_WRAPPER(glMultMatrixd,(const GLdouble *m), (m), m);
GL_FUNCTION_WRAPPER(glMultMatrixf,(const GLfloat *m), (m), m);
GL_FUNCTION_WRAPPER(glRotated,(GLdouble angle, GLdouble x, GLdouble y, GLdouble z), (angle, x, y, z), angle);
GL_FUNCTION_WRAPPER(glRotatef,(GLfloat angle, GLfloat x, GLfloat y, GLfloat z), (angle, x, y, z), angle);
GL_FUNCTION_WRAPPER(glScaled,(GLdouble x, GLdouble y, GLdouble z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glScalef,(GLfloat x, GLfloat y, GLfloat z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glTranslated,(GLdouble x, GLdouble y, GLdouble z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glTranslatef,(GLfloat x, GLfloat y, GLfloat z), (x, y, z), x);
GL_FUNCTION_WRAPPER_RET(glIsList,(GLuint list), (list), list, GLboolean);
GL_FUNCTION_WRAPPER(glDeleteLists,(GLuint list, GLsizei range), (list, range), list);
GL_FUNCTION_WRAPPER_RET(glGenLists,(GLsizei range), (range), range, GLuint);
//GL_FUNCTION_WRAPPER(glNewList,(GLuint list, GLenum mode), (list, mode), list);
//GL_FUNCTION_WRAPPER(glEndList,(GLvoid ), (), glcDummyValue);
GL_FUNCTION_WRAPPER(glCallList,(GLuint list), (list), list);
GL_FUNCTION_WRAPPER(glCallLists,(GLsizei n, GLenum type, const GLvoid *lists), (n, type, lists), n);
GL_FUNCTION_WRAPPER(glListBase,(GLuint base), (base), base);
//GL_FUNCTION_WRAPPER(glBegin,(GLenum mode), (mode), mode);
//GL_FUNCTION_WRAPPER(glEnd,(GLvoid ), (), glcDummyValue);
GL_FUNCTION_WRAPPER(glVertex2d,(GLdouble x, GLdouble y), (x, y), x);
GL_FUNCTION_WRAPPER(glVertex2f,(GLfloat x, GLfloat y), (x, y), x);
GL_FUNCTION_WRAPPER(glVertex2i,(GLint x, GLint y), (x, y), x);
GL_FUNCTION_WRAPPER(glVertex2s,(GLshort x, GLshort y), (x, y), x);
GL_FUNCTION_WRAPPER(glVertex3d,(GLdouble x, GLdouble y, GLdouble z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glVertex3f,(GLfloat x, GLfloat y, GLfloat z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glVertex3i,(GLint x, GLint y, GLint z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glVertex3s,(GLshort x, GLshort y, GLshort z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glVertex4d,(GLdouble x, GLdouble y, GLdouble z, GLdouble w), (x, y, z, w), x);
GL_FUNCTION_WRAPPER(glVertex4f,(GLfloat x, GLfloat y, GLfloat z, GLfloat w), (x, y, z, w), x);
GL_FUNCTION_WRAPPER(glVertex4i,(GLint x, GLint y, GLint z, GLint w), (x, y, z, w), x);
GL_FUNCTION_WRAPPER(glVertex4s,(GLshort x, GLshort y, GLshort z, GLshort w), (x, y, z, w), x);
GL_FUNCTION_WRAPPER(glVertex2dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex2fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex2iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex2sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex3dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex3fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex3iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex3sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex4dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex4fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex4iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glVertex4sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glNormal3b,(GLbyte nx, GLbyte ny, GLbyte nz), (nx, ny, nz), nx);
GL_FUNCTION_WRAPPER(glNormal3d,(GLdouble nx, GLdouble ny, GLdouble nz), (nx, ny, nz), nx);
GL_FUNCTION_WRAPPER(glNormal3f,(GLfloat nx, GLfloat ny, GLfloat nz), (nx, ny, nz), nx);
GL_FUNCTION_WRAPPER(glNormal3i,(GLint nx, GLint ny, GLint nz), (nx, ny, nz), nx);
GL_FUNCTION_WRAPPER(glNormal3s,(GLshort nx, GLshort ny, GLshort nz), (nx, ny, nz), nx);
GL_FUNCTION_WRAPPER(glNormal3bv,(const GLbyte *v), (v), v);
GL_FUNCTION_WRAPPER(glNormal3dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glNormal3fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glNormal3iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glNormal3sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glIndexd,(GLdouble c), (c), c);
GL_FUNCTION_WRAPPER(glIndexf,(GLfloat c), (c), c);
GL_FUNCTION_WRAPPER(glIndexi,(GLint c), (c), c);
GL_FUNCTION_WRAPPER(glIndexs,(GLshort c), (c), c);
GL_FUNCTION_WRAPPER(glIndexub,(GLubyte c), (c), c);
GL_FUNCTION_WRAPPER(glIndexdv,(const GLdouble *c), (c), c);
GL_FUNCTION_WRAPPER(glIndexfv,(const GLfloat *c), (c), c);
GL_FUNCTION_WRAPPER(glIndexiv,(const GLint *c), (c), c);
GL_FUNCTION_WRAPPER(glIndexsv,(const GLshort *c), (c), c);
GL_FUNCTION_WRAPPER(glIndexubv,(const GLubyte *c), (c), c);
GL_FUNCTION_WRAPPER(glColor3b,(GLbyte red, GLbyte green, GLbyte blue), (red, green, blue), red);
GL_FUNCTION_WRAPPER(glColor3d,(GLdouble red, GLdouble green, GLdouble blue), (red, green, blue), red);
GL_FUNCTION_WRAPPER(glColor3f,(GLfloat red, GLfloat green, GLfloat blue), (red, green, blue), red);
GL_FUNCTION_WRAPPER(glColor3i,(GLint red, GLint green, GLint blue), (red, green, blue), red);
GL_FUNCTION_WRAPPER(glColor3s,(GLshort red, GLshort green, GLshort blue), (red, green, blue), red);
GL_FUNCTION_WRAPPER(glColor3ub,(GLubyte red, GLubyte green, GLubyte blue), (red, green, blue), red);
GL_FUNCTION_WRAPPER(glColor3ui,(GLuint red, GLuint green, GLuint blue), (red, green, blue), red);
GL_FUNCTION_WRAPPER(glColor3us,(GLushort red, GLushort green, GLushort blue), (red, green, blue), red);
GL_FUNCTION_WRAPPER(glColor4b,(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glColor4d,(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glColor4f,(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glColor4i,(GLint red, GLint green, GLint blue, GLint alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glColor4s,(GLshort red, GLshort green, GLshort blue, GLshort alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glColor4ub,(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glColor4ui,(GLuint red, GLuint green, GLuint blue, GLuint alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glColor4us,(GLushort red, GLushort green, GLushort blue, GLushort alpha), (red, green, blue, alpha), red);
GL_FUNCTION_WRAPPER(glColor3bv,(const GLbyte *v), (v), v);
GL_FUNCTION_WRAPPER(glColor3dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glColor3fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glColor3iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glColor3sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glColor3ubv,(const GLubyte *v), (v), v);
GL_FUNCTION_WRAPPER(glColor3uiv,(const GLuint *v), (v), v);
GL_FUNCTION_WRAPPER(glColor3usv,(const GLushort *v), (v), v);
GL_FUNCTION_WRAPPER(glColor4bv,(const GLbyte *v), (v), v);
GL_FUNCTION_WRAPPER(glColor4dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glColor4fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glColor4iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glColor4sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glColor4ubv,(const GLubyte *v), (v), v);
GL_FUNCTION_WRAPPER(glColor4uiv,(const GLuint *v), (v), v);
GL_FUNCTION_WRAPPER(glColor4usv,(const GLushort *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord1d,(GLdouble s), (s), s);
GL_FUNCTION_WRAPPER(glTexCoord1f,(GLfloat s), (s), s);
GL_FUNCTION_WRAPPER(glTexCoord1i,(GLint s), (s), s);
GL_FUNCTION_WRAPPER(glTexCoord1s,(GLshort s), (s), s);
GL_FUNCTION_WRAPPER(glTexCoord2d,(GLdouble s, GLdouble t), (s, t), s);
GL_FUNCTION_WRAPPER(glTexCoord2f,(GLfloat s, GLfloat t), (s, t), s);
GL_FUNCTION_WRAPPER(glTexCoord2i,(GLint s, GLint t), (s, t), s);
GL_FUNCTION_WRAPPER(glTexCoord2s,(GLshort s, GLshort t), (s, t), s);
GL_FUNCTION_WRAPPER(glTexCoord3d,(GLdouble s, GLdouble t, GLdouble r), (s, t, r), s);
GL_FUNCTION_WRAPPER(glTexCoord3f,(GLfloat s, GLfloat t, GLfloat r), (s, t, r), s);
GL_FUNCTION_WRAPPER(glTexCoord3i,(GLint s, GLint t, GLint r), (s, t, r), s);
GL_FUNCTION_WRAPPER(glTexCoord3s,(GLshort s, GLshort t, GLshort r), (s, t, r), s);
GL_FUNCTION_WRAPPER(glTexCoord4d,(GLdouble s, GLdouble t, GLdouble r, GLdouble q), (s, t, r, q), s);
GL_FUNCTION_WRAPPER(glTexCoord4f,(GLfloat s, GLfloat t, GLfloat r, GLfloat q), (s, t, r, q), s);
GL_FUNCTION_WRAPPER(glTexCoord4i,(GLint s, GLint t, GLint r, GLint q), (s, t, r, q), s);
GL_FUNCTION_WRAPPER(glTexCoord4s,(GLshort s, GLshort t, GLshort r, GLshort q), (s, t, r, q), s);
GL_FUNCTION_WRAPPER(glTexCoord1dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord1fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord1iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord1sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord2dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord2fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord2iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord2sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord3dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord3fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord3iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord3sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord4dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord4fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord4iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glTexCoord4sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos2d,(GLdouble x, GLdouble y), (x, y), x);
GL_FUNCTION_WRAPPER(glRasterPos2f,(GLfloat x, GLfloat y), (x, y), x);
GL_FUNCTION_WRAPPER(glRasterPos2i,(GLint x, GLint y), (x, y), x);
GL_FUNCTION_WRAPPER(glRasterPos2s,(GLshort x, GLshort y), (x, y), x);
GL_FUNCTION_WRAPPER(glRasterPos3d,(GLdouble x, GLdouble y, GLdouble z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glRasterPos3f,(GLfloat x, GLfloat y, GLfloat z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glRasterPos3i,(GLint x, GLint y, GLint z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glRasterPos3s,(GLshort x, GLshort y, GLshort z), (x, y, z), x);
GL_FUNCTION_WRAPPER(glRasterPos4d,(GLdouble x, GLdouble y, GLdouble z, GLdouble w), (x, y, z, w), x);
GL_FUNCTION_WRAPPER(glRasterPos4f,(GLfloat x, GLfloat y, GLfloat z, GLfloat w), (x, y, z, w), x);
GL_FUNCTION_WRAPPER(glRasterPos4i,(GLint x, GLint y, GLint z, GLint w), (x, y, z, w), x);
GL_FUNCTION_WRAPPER(glRasterPos4s,(GLshort x, GLshort y, GLshort z, GLshort w), (x, y, z, w), x);
GL_FUNCTION_WRAPPER(glRasterPos2dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos2fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos2iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos2sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos3dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos3fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos3iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos3sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos4dv,(const GLdouble *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos4fv,(const GLfloat *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos4iv,(const GLint *v), (v), v);
GL_FUNCTION_WRAPPER(glRasterPos4sv,(const GLshort *v), (v), v);
GL_FUNCTION_WRAPPER(glRectd,(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2), (x1, y1, x2, y2), x1);
GL_FUNCTION_WRAPPER(glRectf,(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2), (x1, y1, x2, y2), x1);
GL_FUNCTION_WRAPPER(glRecti,(GLint x1, GLint y1, GLint x2, GLint y2), (x1, y1, x2, y2), x1);
GL_FUNCTION_WRAPPER(glRects,(GLshort x1, GLshort y1, GLshort x2, GLshort y2), (x1, y1, x2, y2), x1);
GL_FUNCTION_WRAPPER(glRectdv,(const GLdouble *v1, const GLdouble *v2), (v1, v2), v1);
GL_FUNCTION_WRAPPER(glRectfv,(const GLfloat *v1, const GLfloat *v2), (v1, v2), v1);
GL_FUNCTION_WRAPPER(glRectiv,(const GLint *v1, const GLint *v2), (v1, v2), v1);
GL_FUNCTION_WRAPPER(glRectsv,(const GLshort *v1, const GLshort *v2), (v1, v2), v1);
GL_FUNCTION_WRAPPER(glVertexPointer,(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr), (size, type, stride, ptr), size);
GL_FUNCTION_WRAPPER(glNormalPointer,(GLenum type, GLsizei stride,const GLvoid *ptr), (type, stride, ptr), type);
GL_FUNCTION_WRAPPER(glColorPointer,(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr), (size, type, stride, ptr), size);
GL_FUNCTION_WRAPPER(glIndexPointer,(GLenum type, GLsizei stride, const GLvoid *ptr), (type, stride, ptr), type);
GL_FUNCTION_WRAPPER(glTexCoordPointer,(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr), (size, type, stride, ptr), size);
GL_FUNCTION_WRAPPER(glEdgeFlagPointer,(GLsizei stride, const GLvoid *ptr), (stride, ptr), stride);
GL_FUNCTION_WRAPPER(glGetPointerv,(GLenum pname, GLvoid **params), (pname, params), pname);
GL_FUNCTION_WRAPPER(glArrayElement,(GLint i), (i), i);
GL_FUNCTION_WRAPPER(glDrawArrays,(GLenum mode, GLint first, GLsizei count), (mode, first, count), mode);
GL_FUNCTION_WRAPPER(glDrawElements,(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices), (mode, count, type, indices), mode);
GL_FUNCTION_WRAPPER(glInterleavedArrays,(GLenum format, GLsizei stride, const GLvoid *pointer), (format, stride, pointer), format);
GL_FUNCTION_WRAPPER(glShadeModel,(GLenum mode), (mode), mode);
GL_FUNCTION_WRAPPER(glLightf,(GLenum light, GLenum pname, GLfloat param), (light, pname, param), light);
GL_FUNCTION_WRAPPER(glLighti,(GLenum light, GLenum pname, GLint param), (light, pname, param), light);
GL_FUNCTION_WRAPPER(glLightfv,(GLenum light, GLenum pname, const GLfloat *params), (light, pname, params), light);
GL_FUNCTION_WRAPPER(glLightiv,(GLenum light, GLenum pname, const GLint *params), (light, pname, params), light);
GL_FUNCTION_WRAPPER(glGetLightfv,(GLenum light, GLenum pname, GLfloat *params), (light, pname, params), light);
GL_FUNCTION_WRAPPER(glGetLightiv,(GLenum light, GLenum pname, GLint *params), (light, pname, params), light);
GL_FUNCTION_WRAPPER(glLightModelf,(GLenum pname, GLfloat param), (pname, param), pname);
GL_FUNCTION_WRAPPER(glLightModeli,(GLenum pname, GLint param), (pname, param), pname);
GL_FUNCTION_WRAPPER(glLightModelfv,(GLenum pname, const GLfloat *params), (pname, params), pname);
GL_FUNCTION_WRAPPER(glLightModeliv,(GLenum pname, const GLint *params), (pname, params), pname);
GL_FUNCTION_WRAPPER(glMaterialf,(GLenum face, GLenum pname, GLfloat param), (face, pname, param), face);
GL_FUNCTION_WRAPPER(glMateriali,(GLenum face, GLenum pname, GLint param), (face, pname, param), face);
GL_FUNCTION_WRAPPER(glMaterialfv,(GLenum face, GLenum pname, const GLfloat *params), (face, pname, params), face);
GL_FUNCTION_WRAPPER(glMaterialiv,(GLenum face, GLenum pname, const GLint *params), (face, pname, params), face);
GL_FUNCTION_WRAPPER(glGetMaterialfv,(GLenum face, GLenum pname, GLfloat *params), (face, pname, params), face);
GL_FUNCTION_WRAPPER(glGetMaterialiv,(GLenum face, GLenum pname, GLint *params), (face, pname, params), face);
GL_FUNCTION_WRAPPER(glColorMaterial,(GLenum face, GLenum mode), (face, mode), face);
GL_FUNCTION_WRAPPER(glPixelZoom,(GLfloat xfactor, GLfloat yfactor), (xfactor, yfactor), xfactor);
GL_FUNCTION_WRAPPER(glPixelStoref,(GLenum pname, GLfloat param), (pname, param), pname);
GL_FUNCTION_WRAPPER(glPixelStorei,(GLenum pname, GLint param), (pname, param), pname);
GL_FUNCTION_WRAPPER(glPixelTransferf,(GLenum pname, GLfloat param), (pname, param), pname);
GL_FUNCTION_WRAPPER(glPixelTransferi,(GLenum pname, GLint param), (pname, param), pname);
GL_FUNCTION_WRAPPER(glPixelMapfv,(GLenum map, GLsizei mapsize, const GLfloat *values), (map, mapsize, values), map);
GL_FUNCTION_WRAPPER(glPixelMapuiv,(GLenum map, GLsizei mapsize, const GLuint *values), (map, mapsize, values), map);
GL_FUNCTION_WRAPPER(glPixelMapusv,(GLenum map, GLsizei mapsize, const GLushort *values), (map, mapsize, values), map);
GL_FUNCTION_WRAPPER(glGetPixelMapfv,(GLenum map, GLfloat *values), (map, values), map);
GL_FUNCTION_WRAPPER(glGetPixelMapuiv,(GLenum map, GLuint *values), (map, values), map);
GL_FUNCTION_WRAPPER(glGetPixelMapusv,(GLenum map, GLushort *values), (map, values), map);
GL_FUNCTION_WRAPPER(glBitmap,(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap), (width, height, xorig, yorig, xmove, ymove, bitmap), width);
GL_FUNCTION_WRAPPER(glReadPixels,(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels), (x, y, width, height, format, type, pixels), x);
GL_FUNCTION_WRAPPER(glDrawPixels,(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels), (width, height, format, type, pixels), width);
GL_FUNCTION_WRAPPER(glCopyPixels,(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type), (x, y, width, height, type), x);
GL_FUNCTION_WRAPPER(glStencilFunc,(GLenum func, GLint ref, GLuint mask), (func, ref, mask), func);
GL_FUNCTION_WRAPPER(glStencilMask,(GLuint mask), (mask), mask);
GL_FUNCTION_WRAPPER(glStencilOp,(GLenum fail, GLenum zfail, GLenum zpass), (fail, zfail, zpass), fail);
GL_FUNCTION_WRAPPER(glClearStencil,(GLint s), (s), s);
GL_FUNCTION_WRAPPER(glTexGend,(GLenum coord, GLenum pname, GLdouble param), (coord, pname, param), coord);
GL_FUNCTION_WRAPPER(glTexGenf,(GLenum coord, GLenum pname, GLfloat param), (coord, pname, param), coord);
GL_FUNCTION_WRAPPER(glTexGeni,(GLenum coord, GLenum pname, GLint param), (coord, pname, param), coord);
GL_FUNCTION_WRAPPER(glTexGendv,(GLenum coord, GLenum pname, const GLdouble *params), (coord, pname, params), coord);
GL_FUNCTION_WRAPPER(glTexGenfv,(GLenum coord, GLenum pname, const GLfloat *params), (coord, pname, params), coord);
GL_FUNCTION_WRAPPER(glTexGeniv,(GLenum coord, GLenum pname, const GLint *params), (coord, pname, params), coord);
GL_FUNCTION_WRAPPER(glGetTexGendv,(GLenum coord, GLenum pname, GLdouble *params), (coord, pname, params), coord);
GL_FUNCTION_WRAPPER(glGetTexGenfv,(GLenum coord, GLenum pname, GLfloat *params), (coord, pname, params), coord);
GL_FUNCTION_WRAPPER(glGetTexGeniv,(GLenum coord, GLenum pname, GLint *params), (coord, pname, params), coord);
GL_FUNCTION_WRAPPER(glTexEnvf,(GLenum target, GLenum pname, GLfloat param), (target, pname, param), target);
GL_FUNCTION_WRAPPER(glTexEnvi,(GLenum target, GLenum pname, GLint param), (target, pname, param), target);
GL_FUNCTION_WRAPPER(glTexEnvfv,(GLenum target, GLenum pname, const GLfloat *params), (target, pname, params), target);
GL_FUNCTION_WRAPPER(glTexEnviv,(GLenum target, GLenum pname, const GLint *params), (target, pname, params), target);
GL_FUNCTION_WRAPPER(glGetTexEnvfv,(GLenum target, GLenum pname, GLfloat *params), (target, pname, params), target);
GL_FUNCTION_WRAPPER(glGetTexEnviv,(GLenum target, GLenum pname, GLint *params), (target, pname, params), target);
GL_FUNCTION_WRAPPER(glTexParameterf,(GLenum target, GLenum pname, GLfloat param), (target, pname, param), target);
GL_FUNCTION_WRAPPER(glTexParameteri,(GLenum target, GLenum pname, GLint param), (target, pname, param), target);
GL_FUNCTION_WRAPPER(glTexParameterfv,(GLenum target, GLenum pname, const GLfloat *params), (target, pname, params), target);
GL_FUNCTION_WRAPPER(glTexParameteriv,(GLenum target, GLenum pname, const GLint *params), (target, pname, params), target);
GL_FUNCTION_WRAPPER(glGetTexParameterfv,(GLenum target, GLenum pname, GLfloat *params), (target, pname, params), target);
GL_FUNCTION_WRAPPER(glGetTexParameteriv,(GLenum target, GLenum pname, GLint *params), (target, pname, params), target);
GL_FUNCTION_WRAPPER(glGetTexLevelParameterfv,(GLenum target, GLint level, GLenum pname, GLfloat *params), (target, level, pname, params), target);
GL_FUNCTION_WRAPPER(glGetTexLevelParameteriv,(GLenum target, GLint level, GLenum pname, GLint *params), (target, level, pname, params), target);
GL_FUNCTION_WRAPPER(glTexImage1D,(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels), (target, level, internalFormat, width, border, format, type, pixels), target);
GL_FUNCTION_WRAPPER(glTexImage2D,(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels), (target, level, internalFormat, width, height, border, format, type, pixels), target);
GL_FUNCTION_WRAPPER(glGetTexImage,(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels), (target, level, format, type, pixels), target);
GL_FUNCTION_WRAPPER(glGenTextures,(GLsizei n, GLuint *textures), (n, textures), n);
GL_FUNCTION_WRAPPER(glDeleteTextures,(GLsizei n, const GLuint *textures), (n, textures), n);
GL_FUNCTION_WRAPPER(glBindTexture,(GLenum target, GLuint texture), (target, texture), target);
GL_FUNCTION_WRAPPER(glPrioritizeTextures,(GLsizei n, const GLuint *textures, const GLfloat *priorities), (n, textures, priorities), n);
GL_FUNCTION_WRAPPER_RET(glAreTexturesResident,(GLsizei n, const GLuint *textures, GLboolean *residences), (n, textures, residences), n, GLboolean);
GL_FUNCTION_WRAPPER_RET(glIsTexture,(GLuint texture), (texture), texture, GLboolean);
GL_FUNCTION_WRAPPER(glTexSubImage1D,(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels), (target, level, xoffset, width, format, type, pixels), target);
GL_FUNCTION_WRAPPER(glTexSubImage2D,(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels), (target, level, xoffset, yoffset, width, height, format, type, pixels), target);
GL_FUNCTION_WRAPPER(glCopyTexImage1D,(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border), (target, level, internalformat, x, y, width, border), target);
GL_FUNCTION_WRAPPER(glCopyTexImage2D,(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border), (target, level, internalformat, x, y, width, height, border), target);
GL_FUNCTION_WRAPPER(glCopyTexSubImage1D,(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width), (target, level, xoffset, x, y, width), target);
GL_FUNCTION_WRAPPER(glCopyTexSubImage2D,(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height), (target, level, xoffset, yoffset, x, y, width, height), target);
GL_FUNCTION_WRAPPER(glMap1d,(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points), (target, u1, u2, stride, order, points), target);
GL_FUNCTION_WRAPPER(glMap1f,(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points), (target, u1, u2, stride, order, points), target);
GL_FUNCTION_WRAPPER(glMap2d,(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points), (target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points), target);
GL_FUNCTION_WRAPPER(glMap2f,(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points), (target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points), target);
GL_FUNCTION_WRAPPER(glGetMapdv,(GLenum target, GLenum query, GLdouble *v), (target, query, v), target);
GL_FUNCTION_WRAPPER(glGetMapfv,(GLenum target, GLenum query, GLfloat *v), (target, query, v), target);
GL_FUNCTION_WRAPPER(glGetMapiv,(GLenum target, GLenum query, GLint *v), (target, query, v), target);
GL_FUNCTION_WRAPPER(glEvalCoord1d,(GLdouble u), (u), u);
GL_FUNCTION_WRAPPER(glEvalCoord1f,(GLfloat u), (u), u);
GL_FUNCTION_WRAPPER(glEvalCoord1dv,(const GLdouble *u), (u), u);
GL_FUNCTION_WRAPPER(glEvalCoord1fv,(const GLfloat *u), (u), u);
GL_FUNCTION_WRAPPER(glEvalCoord2d,(GLdouble u, GLdouble v), (u, v), u);
GL_FUNCTION_WRAPPER(glEvalCoord2f,(GLfloat u, GLfloat v), (u, v), u);
GL_FUNCTION_WRAPPER(glEvalCoord2dv,(const GLdouble *u), (u), u);
GL_FUNCTION_WRAPPER(glEvalCoord2fv,(const GLfloat *u), (u), u);
GL_FUNCTION_WRAPPER(glMapGrid1d,(GLint un, GLdouble u1, GLdouble u2), (un, u1, u2), un);
GL_FUNCTION_WRAPPER(glMapGrid1f,(GLint un, GLfloat u1, GLfloat u2), (un, u1, u2), un);
GL_FUNCTION_WRAPPER(glMapGrid2d,(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2), (un, u1, u2, vn, v1, v2), un);
GL_FUNCTION_WRAPPER(glMapGrid2f,(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2), (un, u1, u2, vn, v1, v2), un);
GL_FUNCTION_WRAPPER(glEvalPoint1,(GLint i), (i), i);
GL_FUNCTION_WRAPPER(glEvalPoint2,(GLint i, GLint j), (i, j), i);
GL_FUNCTION_WRAPPER(glEvalMesh1,(GLenum mode, GLint i1, GLint i2), (mode, i1, i2), mode);
GL_FUNCTION_WRAPPER(glEvalMesh2,(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2), (mode, i1, i2, j1, j2), mode);
GL_FUNCTION_WRAPPER(glFogf,(GLenum pname, GLfloat param), (pname, param), pname);
GL_FUNCTION_WRAPPER(glFogi,(GLenum pname, GLint param), (pname, param), pname);
GL_FUNCTION_WRAPPER(glFogfv,(GLenum pname, const GLfloat *params), (pname, params), pname);
GL_FUNCTION_WRAPPER(glFogiv,(GLenum pname, const GLint *params), (pname, params), pname);
GL_FUNCTION_WRAPPER(glFeedbackBuffer,(GLsizei size, GLenum type, GLfloat *buffer), (size, type, buffer), size);
GL_FUNCTION_WRAPPER(glPassThrough,(GLfloat token), (token), token);
GL_FUNCTION_WRAPPER(glSelectBuffer,(GLsizei size, GLuint *buffer), (size, buffer), size);
GL_FUNCTION_WRAPPER(glInitNames,(), (), glcDummyValue);
GL_FUNCTION_WRAPPER(glLoadName,(GLuint name), (name), name);
GL_FUNCTION_WRAPPER(glPushName,(GLuint name), (name), name);
GL_FUNCTION_WRAPPER(glPopName,(), (), glcDummyValue);
| 13,976 |
2,313 | /*
* Copyright (c) 2020-2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "arm_compute/runtime/NEON/functions/NEGEMMConv2d.h"
#include "arm_compute/core/utils/misc/ShapeCalculator.h"
#include "arm_compute/runtime/Tensor.h"
#include "src/core/helpers/MemoryHelpers.h"
#include "src/runtime/cpu/operators/CpuGemmDirectConv2d.h"
namespace arm_compute
{
using OperatorType = cpu::CpuGemmDirectConv2d;
using namespace arm_compute::experimental;
struct NEGEMMConv2d::Impl
{
const ITensor *weights{ nullptr };
std::unique_ptr<OperatorType> op{ nullptr };
ITensorPack run_pack{};
ITensorPack prep_pack{};
WorkspaceData<Tensor> workspace{};
MemoryGroup memory_group{};
bool is_prepared{ false };
experimental::MemoryRequirements aux_mem_req{};
};
NEGEMMConv2d::NEGEMMConv2d(const std::shared_ptr<IMemoryManager> &memory_manager)
: _impl(std::make_unique<Impl>())
{
_impl->memory_group = MemoryGroup(memory_manager);
}
NEGEMMConv2d::~NEGEMMConv2d() = default;
void NEGEMMConv2d::configure(ITensor *input, const ITensor *weights, const ITensor *biases, ITensor *output, const Conv2dInfo &info)
{
ARM_COMPUTE_ERROR_ON_NULLPTR(input, weights, output);
_impl->weights = weights;
_impl->is_prepared = false;
_impl->op = std::make_unique<OperatorType>();
_impl->op->configure(input->info(), weights->info(), biases != nullptr ? biases->info() : nullptr, output->info(), info);
_impl->aux_mem_req = _impl->op->workspace();
_impl->run_pack = { { TensorType::ACL_SRC_0, input }, { TensorType::ACL_SRC_2, biases }, { TensorType::ACL_DST, output } };
_impl->prep_pack = { { TensorType::ACL_SRC_1, weights }, { TensorType::ACL_SRC_2, biases } };
_impl->workspace = manage_workspace<Tensor>(_impl->op->workspace(), _impl->memory_group, _impl->run_pack, _impl->prep_pack);
}
Status NEGEMMConv2d::validate(const ITensorInfo *input, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *output, const Conv2dInfo &info)
{
return OperatorType::validate(input, weights, biases, output, info);
}
void NEGEMMConv2d::run()
{
prepare();
MemoryGroupResourceScope scope_mg(_impl->memory_group);
_impl->op->run(_impl->run_pack);
}
void NEGEMMConv2d::prepare()
{
if(!_impl->is_prepared)
{
_impl->op->prepare(_impl->prep_pack);
auto has_reshape = std::find_if(_impl->aux_mem_req.begin(),
_impl->aux_mem_req.end(),
[](const MemoryInfo & m) -> bool { return m.lifetime == MemoryLifetime::Persistent; });
if(has_reshape != std::end(_impl->aux_mem_req))
{
_impl->weights->mark_as_unused();
}
else
{
_impl->run_pack.add_const_tensor(ACL_SRC_1, _impl->weights);
}
// Release temporary tensors that are only used in prepare stage
release_temporaries<Tensor>(_impl->aux_mem_req, _impl->workspace);
_impl->is_prepared = true;
}
}
} // namespace arm_compute
| 1,706 |
3,102 | // RUN: %clang_cc1 -triple x86_64-pc-linux -mrelocation-model static -O1 -fno-experimental-new-pass-manager -emit-llvm %s -o - | FileCheck --check-prefix=STATIC %s
// RUN: %clang_cc1 -triple x86_64-pc-linux -mrelocation-model static -fno-plt -O1 -fno-experimental-new-pass-manager -emit-llvm %s -o - | FileCheck --check-prefix=NOPLT %s
// RUN: %clang_cc1 -triple x86_64-w64-mingw32 -O1 -fno-experimental-new-pass-manager -emit-llvm %s -o - | FileCheck --check-prefix=MINGW %s
// STATIC-DAG: @_ZTV1C = linkonce_odr dso_local unnamed_addr constant
// STATIC-DAG: @_ZTS1C = linkonce_odr dso_local constant
// STATIC-DAG: @_ZTI1C = linkonce_odr dso_local constant
// STATIC-DAG: @_ZZ14useStaticLocalvE3obj = linkonce_odr dso_local global
// STATIC-DAG: @_ZGVZN5guard1gEvE1a = linkonce_odr dso_local global
// STATIC-DAG: define dso_local void @_ZN1CC2Ev(
// STATIC-DAG: define dso_local void @_ZN1CC1Ev(
// STATIC-DAG: define linkonce_odr dso_local void @_ZN1C3fooEv(
// NOPLT-DAG: @_ZTV1C = linkonce_odr dso_local unnamed_addr constant
// NOPLT-DAG: @_ZTS1C = linkonce_odr dso_local constant
// NOPLT-DAG: @_ZTI1C = linkonce_odr dso_local constant
// NOPLT-DAG: @_ZZ14useStaticLocalvE3obj = linkonce_odr dso_local global
// NOPLT-DAG: @_ZGVZN5guard1gEvE1a = linkonce_odr dso_local global
// NOPLT-DAG: define dso_local void @_ZN1CC2Ev(
// NOPLT-DAG: define dso_local void @_ZN1CC1Ev(
// NOPLT-DAG: define linkonce_odr dso_local void @_ZN1C3fooEv(
// MINGW-DAG: @_ZTV1C = linkonce_odr dso_local unnamed_addr constant
// MINGW-DAG: @_ZTS1C = linkonce_odr dso_local constant
// MINGW-DAG: @_ZTI1C = linkonce_odr dso_local constant
// MINGW-DAG: @_ZZ14useStaticLocalvE3obj = linkonce_odr dso_local global
// MINGW-DAG: @_ZGVZN5guard1gEvE1a = linkonce_odr dso_local global
// MINGW-DAG: define dso_local void @_ZN1CC2Ev(
// MINGW-DAG: define dso_local void @_ZN1CC1Ev(
// MINGW-DAG: define linkonce_odr dso_local void @_ZN1C3fooEv(
struct C {
C();
virtual void foo() {}
};
C::C() {}
struct HasVTable {
virtual void f();
};
inline HasVTable &useStaticLocal() {
static HasVTable obj;
return obj;
}
void useit() {
useStaticLocal();
}
namespace guard {
int f();
inline int g() {
static int a = f();
return a;
}
int h() {
return g();
}
} // namespace guard
// STATIC-DAG: @_ZN5test23barIiE1xE = available_externally dso_local constant i32
// STATIC-DAG: define available_externally dso_local void @_ZN5test23barIcEC1Ev(
// NOPLT-DAG: @_ZN5test23barIiE1xE = available_externally dso_local constant i32
// NOPLT-DAG: define available_externally void @_ZN5test23barIcEC1Ev(
// MINGW-DAG: @_ZN5test23barIiE1xE = available_externally constant i32
// MINGW-DAG: define available_externally dso_local void @_ZN5test23barIcEC1Ev(
namespace test2 {
void foo();
template <typename T>
struct bar {
virtual void zed();
static const int x = 42;
bar() { foo(); }
};
extern template class bar<char>;
bar<char> abc;
const int *getX() {
return &bar<int>::x;
}
} // namespace test2
| 1,284 |
465 | /*
* Copyright (c) 2018 Uber Technologies, Inc.
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package com.uber.marmaray.common.retry;
import com.google.common.base.Optional;
import com.uber.marmaray.common.configuration.Configuration;
import com.uber.marmaray.common.configuration.RetryStrategyConfiguration;
import com.uber.marmaray.common.configuration.SimpleRetryStrategyConfiguration;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.io.File;
import lombok.NonNull;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
class MockRetryableFunction<T,R> extends RetryableFunction<T,R> {
private int count = 0;
public MockRetryableFunction(IFunctionThrowsException<T,R> func,
IRetryStrategy retryStrategy) {
super(func,spy(retryStrategy));
when(super.retryStrategy.shouldRetry()).thenCallRealMethod();
when(super.retryStrategy.retryMessage()).thenCallRealMethod();
}
@Override
protected IFunctionThrowsException<T, R> getUserFunction() {
this.count++;
return super.getUserFunction();
}
public void verifyRetry(int numFuncApply, int numShouldRetry) {
Assert.assertEquals(count, numFuncApply);
Mockito.verify(this.retryStrategy, times(numShouldRetry)).shouldRetry();
}
}
public class TestRetryableFunction {
private final static String CONFIG_YAML = "src/test/resources/config.yaml";
private final static Configuration conf = new Configuration(new File(CONFIG_YAML), Optional.absent());
private final static int maxRetries = new SimpleRetryStrategyConfiguration(conf).getNumRetries();
private static int counter = 0;
private Integer divide(@NonNull final Integer divisor) {
counter++;
if (divisor == 0) {
throw new IllegalArgumentException("The divisor is 0.");
} else {
if (counter < maxRetries)
throw new RuntimeException("Failing for all attempts except last one");
return (100 / divisor);
}
}
@Test
public void testGoodRetryableFunction() throws Exception {
counter = 0;
final MockRetryableFunction<Integer, Integer> divideBy = new MockRetryableFunction<>(
this::divide,
new RetryStrategyConfiguration(conf).getRetryStrategy());
assertEquals(new Integer(50), divideBy.apply(2));
divideBy.verifyRetry(maxRetries, maxRetries-1);
}
@Test(expected = IllegalArgumentException.class)
public void testBadRetryableTask() throws Exception {
counter = 0;
final MockRetryableFunction<Integer, Integer> divideBy = new MockRetryableFunction<>(
this::divide,
new RetryStrategyConfiguration(conf).getRetryStrategy());
try {
divideBy.apply(0);
}
finally {
divideBy.verifyRetry(maxRetries, maxRetries);
}
}
}
| 1,462 |
1,126 | <filename>integration-tests/src/test/java/org/mvndaemon/mvnd/it/MaxHeapNativeIT.java<gh_stars>1000+
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.mvndaemon.mvnd.it;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import javax.inject.Inject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mvndaemon.mvnd.assertj.TestClientOutput;
import org.mvndaemon.mvnd.client.Client;
import org.mvndaemon.mvnd.junit.MvndNativeTest;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class MaxHeapNativeIT {
static class BaseTest {
@Inject
Client client;
static ListAppender<ILoggingEvent> appender = new ListAppender<>();
@BeforeAll
static void setup() {
Logger logger = (Logger) LoggerFactory.getLogger("org.mvndaemon.mvnd.client.DaemonConnector");
logger.setLevel(Level.DEBUG);
logger.addAppender(appender);
appender.start();
}
@AfterAll
static void tearDown() {
Logger logger = (Logger) LoggerFactory.getLogger("org.mvndaemon.mvnd.client.DaemonConnector");
logger.detachAppender(appender);
}
static String getDaemonArgs() {
return appender.list.stream()
.filter(e -> e.getMessage().contains("Starting daemon process"))
.map(e -> e.getArgumentArray()[2].toString())
.findAny().orElseThrow();
}
@BeforeEach
void unitSetup() {
appender.list.clear();
}
}
@MvndNativeTest(projectDir = "src/test/projects/max-heap/default-heap")
static class DefaultConfig extends BaseTest {
@Test
void noXmxPassedByDefault() throws InterruptedException {
final TestClientOutput output = new TestClientOutput();
client.execute(output, "-Dmvnd.log.level=DEBUG", "org.codehaus.gmaven:groovy-maven-plugin:2.1.1:execute",
"-Dsource=System.out.println(java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments())")
.assertSuccess();
String daemonArgs = getDaemonArgs();
assertTrue(!daemonArgs.contains("-Xmx") && !daemonArgs.contains("mvnd.maxHeapSize"),
"Args must not contain -Xmx or mvnd.maxHeapSize but is:\n" + daemonArgs);
}
}
@MvndNativeTest(projectDir = "src/test/projects/max-heap/jvm-heap")
static class JvmConfig extends BaseTest {
@Test
void xmxFromJvmConfig() throws InterruptedException {
final TestClientOutput output = new TestClientOutput();
client.execute(output, "-Dmvnd.log.level=DEBUG", "org.codehaus.gmaven:groovy-maven-plugin:2.1.1:execute",
"-Dsource=System.out.println(java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments())")
.assertSuccess();
String daemonArgs = getDaemonArgs();
assertTrue(!daemonArgs.contains("-Xmx") && !daemonArgs.contains("mvnd.maxHeapSize"),
"Args must not contain -Xmx or mvnd.maxHeapSize but is:\n" + daemonArgs);
}
}
@MvndNativeTest(projectDir = "src/test/projects/max-heap/mvnd-props")
static class MvndProps extends BaseTest {
@Test
void xmxFromMvndProperties() throws InterruptedException {
final TestClientOutput output = new TestClientOutput();
client.execute(output, "-Dmvnd.log.level=DEBUG", "org.codehaus.gmaven:groovy-maven-plugin:2.1.1:execute",
"-Dsource=System.out.println(java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments())")
.assertSuccess();
String daemonArgs = getDaemonArgs();
assertTrue(daemonArgs.contains("-Xmx130M") && daemonArgs.contains("mvnd.maxHeapSize=130M"),
"Args must contain -Xmx130M or mvnd.maxHeapSize=130M but is:\n" + daemonArgs);
}
}
}
| 2,037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.