max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
713 |
<reponame>franz1981/infinispan
package org.infinispan.cache.impl;
import java.util.function.UnaryOperator;
import org.infinispan.commons.util.InjectiveFunction;
/**
* This is a marker interface to signal that this function may perform an encoding of the provided value. The returned
* value therefore will always be equivalent to the provided value, but may be in a slightly different form (whether
* due to unwrapping, encoding or transcoding. This may allow certain optimizations knowing that the value is
* equivalent to what it was before.
* @author wburns
* @since 10.1
*/
public interface EncodingFunction<T> extends UnaryOperator<T>, InjectiveFunction<T, T> {
}
| 185 |
921 |
<filename>test/test_fcl_math.cpp
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011-2014, <NAME>, Inc.
* Copyright (c) 2014-2016, Open Source Robotics Foundation
* Copyright (c) 2016, Toyota Research Institute
* 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 Open Source Robotics Foundation 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.
*/
#include <gtest/gtest.h>
#include "fcl/broadphase/detail/morton.h"
#include "fcl/config.h"
#include "fcl/math/bv/AABB.h"
#include "fcl/math/bv/RSS.h"
#include "fcl/math/bv/utility.h"
#include "fcl/math/constants.h"
using namespace fcl;
template <typename S>
void test_vec_test_basic_vector()
{
Vector3<S> v1(1.0, 2.0, 3.0);
EXPECT_TRUE(v1[0] == (S)1.0);
EXPECT_TRUE(v1[1] == (S)2.0);
EXPECT_TRUE(v1[2] == (S)3.0);
Vector3<S> v2 = v1;
Vector3<S> v3(3.3, 4.3, 5.3);
v1 += v3;
EXPECT_TRUE(v1.isApprox(v2 + v3));
v1 -= v3;
EXPECT_TRUE(v1.isApprox(v2));
v1 -= v3;
EXPECT_TRUE(v1.isApprox(v2 - v3));
v1 += v3;
v1.array() *= v3.array();
EXPECT_TRUE(v1.array().isApprox(v2.array() * v3.array()));
v1.array() /= v3.array();
EXPECT_TRUE(v1.isApprox(v2));
v1.array() /= v3.array();
EXPECT_TRUE(v1.array().isApprox(v2.array() / v3.array()));
v1.array() *= v3.array();
v1 *= 2.0;
EXPECT_TRUE(v1.isApprox(v2 * 2.0));
v1 /= 2.0;
EXPECT_TRUE(v1.isApprox(v2));
v1 /= 2.0;
EXPECT_TRUE(v1.isApprox(v2 / 2.0));
v1 *= 2.0;
v1.array() += 2.0;
EXPECT_TRUE(v1.array().isApprox(v2.array() + 2.0));
v1.array() -= 2.0;
EXPECT_TRUE(v1.isApprox(v2));
v1.array() -= 2.0;
EXPECT_TRUE(v1.array().isApprox(v2.array() - 2.0));
v1.array() += 2.0;
EXPECT_TRUE((-Vector3<S>(1.0, 2.0, 3.0)) == (Vector3<S>(-1.0, -2.0, -3.0)));
v1 = Vector3<S>(1.0, 2.0, 3.0);
v2 = Vector3<S>(3.0, 4.0, 5.0);
EXPECT_TRUE((v1.cross(v2)).isApprox(Vector3<S>(-2.0, 4.0, -2.0)));
EXPECT_TRUE(std::abs(v1.dot(v2) - 26) < 1e-5);
v1 = Vector3<S>(3.0, 4.0, 5.0);
EXPECT_TRUE(std::abs(v1.squaredNorm() - 50.0) < 1e-5);
EXPECT_TRUE(std::abs(v1.norm() - sqrt(50.0)) < 1e-5);
EXPECT_TRUE(v1.normalized().isApprox(v1 / v1.norm()));
v1 = Vector3<S>(1.0, 2.0, 3.0);
v2 = Vector3<S>(3.0, 4.0, 5.0);
EXPECT_TRUE((v1.cross(v2)).isApprox(Vector3<S>(-2.0, 4.0, -2.0)));
EXPECT_TRUE(v1.dot(v2) == 26);
}
GTEST_TEST(FCL_MATH, vec_test_basic_vector3)
{
// test_vec_test_basic_vector<float>();
test_vec_test_basic_vector<double>();
}
template <typename S>
void test_morton()
{
AABB<S> bbox(Vector3<S>(0, 0, 0), Vector3<S>(1000, 1000, 1000));
detail::morton_functor<S, std::bitset<30>> F1(bbox);
detail::morton_functor<S, std::bitset<60>> F2(bbox);
detail::morton_functor<S, uint64> F3(bbox); // 60 bits
detail::morton_functor<S, uint32> F4(bbox); // 30 bits
Vector3<S> p(254, 873, 674);
EXPECT_TRUE(F1(p).to_ulong() == F4(p));
EXPECT_TRUE(F2(p).to_ullong() == F3(p));
}
GTEST_TEST(FCL_MATH, morton)
{
// test_morton<float>();
test_morton<double>();
}
// Test fitting an RSS to various number of points
template <typename S>
void test_rss_fit()
{
const S epsilon = constants<S>::eps_78();
RSS<S> rss;
Vector3<S> pn[8];
pn[0] << 0, 0, 0;
pn[1] << 1, 0, 0;
// Check fitting 1 point
fit(pn, 1, rss);
EXPECT_EQ(rss.center(), pn[0]);
EXPECT_EQ(rss.width(), 0.0);
EXPECT_EQ(rss.height(), 0.0);
EXPECT_EQ(rss.depth(), 0.0);
EXPECT_TRUE(rss.axis.isApprox(Matrix3<S>::Identity()));
// Check fitting 2 points for each axis
fit(pn, 2, rss);
EXPECT_TRUE(rss.center().isApprox(Vector3<S>(0.5, 0, 0)));
EXPECT_EQ(rss.width(), 1.0);
EXPECT_EQ(rss.height(), 0.0);
EXPECT_EQ(rss.depth(), 0.0);
EXPECT_TRUE(rss.axis.col(0).isApprox(Vector3<S>(1, 0, 0)) ||
rss.axis.col(0).isApprox(Vector3<S>(-1, 0, 0)));
pn[1] << 0, 1, 0;
fit(pn, 2, rss);
EXPECT_TRUE(rss.center().isApprox(Vector3<S>(0, 0.5, 0)));
EXPECT_EQ(rss.width(), 1.0);
EXPECT_EQ(rss.height(), 0.0);
EXPECT_EQ(rss.depth(), 0.0);
EXPECT_TRUE(rss.axis.col(0).isApprox(Vector3<S>(0, 1, 0)) ||
rss.axis.col(0).isApprox(Vector3<S>(0, -1, 0)));
pn[1] << 0, 0, 1;
fit(pn, 2, rss);
EXPECT_TRUE(rss.center().isApprox(Vector3<S>(0, 0, 0.5)));
EXPECT_EQ(rss.width(), 1.0);
EXPECT_EQ(rss.height(), 0.0);
EXPECT_EQ(rss.depth(), 0.0);
EXPECT_TRUE(rss.axis.col(0).isApprox(Vector3<S>(0, 0, 1)) ||
rss.axis.col(0).isApprox(Vector3<S>(0, 0, -1)));
// Check fitting 2 in opposite order
pn[0] << 0, 0, 1;
pn[1] << 0, 0, 0;
fit(pn, 2, rss);
EXPECT_TRUE(rss.center().isApprox(Vector3<S>(0, 0, 0.5)));
EXPECT_EQ(rss.width(), 1.0);
EXPECT_EQ(rss.height(), 0.0);
EXPECT_EQ(rss.depth(), 0.0);
EXPECT_TRUE(rss.axis.col(0).isApprox(Vector3<S>(0, 0, 1)) ||
rss.axis.col(0).isApprox(Vector3<S>(0, 0, -1)));
// Check fitting 2 not along an axis
pn[0] << -1, 1, 0;
pn[1] << 0, 0, 0;
fit(pn, 2, rss);
EXPECT_TRUE(rss.center().isApprox(Vector3<S>(-0.5, 0.5, 0)));
EXPECT_NEAR(rss.width(), sqrt(2.0), epsilon);
EXPECT_EQ(rss.height(), 0.0);
EXPECT_EQ(rss.depth(), 0.0);
EXPECT_TRUE(
rss.axis.col(0).isApprox(Vector3<S>(-sqrt(2.0)/2.0, sqrt(2.0)/2.0, 0)) ||
rss.axis.col(0).isApprox(Vector3<S>(sqrt(2.0)/2.0, -sqrt(2.0)/2.0, 0)));
// Check fitting 3
pn[0] << 0, 0, 0;
pn[1] << 1, 0, 0;
pn[2] << 0, 1, 0;
fit(pn, 3, rss);
Vector3<S> c3(0.25, 0.25, 0);
EXPECT_TRUE(c3.isApprox(rss.center()));
EXPECT_NEAR(rss.width(), sqrt(2.0), epsilon);
EXPECT_NEAR(rss.height(), sqrt(2.0) / 2.0, epsilon);
EXPECT_EQ(rss.depth(), 0.0);
// Check fitting 8
pn[3] << 0, 0, 1;
pn[4] << 1, 0, 0;
pn[5] << 1, 0, 1;
pn[6] << 1, 1, 0;
pn[7] << 1, 1, 1;
fit(pn, 8, rss);
EXPECT_GE(rss.depth(), 0.5);
}
// Test convert RSS to other bounding volumes
template <typename S>
void test_rss_conversion()
{
const S epsilon = constants<S>::eps_78();
RSS<S> rss;
Vector3<S> pn[8];
AABB<S> aabb;
OBB<S> obb;
pn[0] << 0, 0, 0;
pn[1] << 1, 0, 0;
pn[2] << 0, 1, 0;
pn[3] << 0, 0, 1;
pn[4] << 1, 0, 0;
pn[5] << 1, 0, 1;
pn[6] << 1, 1, 0;
pn[7] << 1, 1, 1;
fit(pn, 8, rss);
convertBV(rss, Transform3<S>::Identity(), aabb);
EXPECT_GE(aabb.width(), rss.width());
EXPECT_GE(aabb.height(), rss.height());
EXPECT_GE(aabb.depth(), rss.depth());
EXPECT_TRUE(aabb.center().isApprox(rss.center()));
convertBV(aabb, Transform3<S>::Identity(), rss);
// The resulting RSS must be bigger than the AABB for it to contain it
EXPECT_GE(rss.width() - rss.depth() + epsilon, aabb.width());
EXPECT_GE(rss.height() - rss.depth() + epsilon, aabb.height());
EXPECT_GE(rss.depth(), aabb.depth());
EXPECT_TRUE(aabb.center().isApprox(rss.center()));
convertBV(rss, Transform3<S>::Identity(), obb);
EXPECT_GE(obb.width(), rss.width());
EXPECT_GE(obb.height(), rss.height());
EXPECT_GE(obb.depth(), rss.depth());
EXPECT_TRUE(obb.center().isApprox(rss.center()));
}
// Test RSS to RSS distance function
template <typename S>
void test_rss_distance()
{
const S epsilon = constants<S>::eps_78();
Vector3<S> p0[3];
Vector3<S> p1[3];
RSS<S> rss;
RSS<S> rss2;
// Test RSS to RSS distance for correctness
p0[0] << 1, 1, 1;
p0[1] << 1, 1, -1;
p0[2] << 0, 1, -1;
p1[0] << 1, -1, 1;
p1[1] << 1, -1, -1;
p1[2] << 0, -1, -1;
fit(p0, 3, rss);
fit(p1, 3, rss2);
EXPECT_NEAR(rss.distance(rss2), 2.0, epsilon);
rss.To << 0, 0, 0.5;
rss.axis = Matrix3<S>::Identity();
rss.l[0] = 1;
rss.l[1] = 1;
rss.r = 0.5;
rss2.To << -1, -1, 2.5;
rss2.axis = Matrix3<S>::Identity();
rss2.l[0] = 1;
rss2.l[1] = 1;
rss2.r = 0.5;
EXPECT_NEAR(rss.distance(rss2), 1.0, epsilon);
rss2.axis << -1, 0, 0,
0, -1, 0,
0, 0, -1;
EXPECT_NEAR(rss.distance(rss2), sqrt(6) - 1.0, epsilon);
rss2.To << 0, 0, 2.5;
EXPECT_NEAR(rss.distance(rss2), 1.0, epsilon);
}
// Test setting RSS position
template <typename S>
void test_rss_position()
{
// Verify setting To via the center works correctly.
RSS<S> rss;
rss.l[0] = 1;
rss.l[1] = 1;
rss.r = 0.5;
rss.axis = Matrix3<S>::Identity();
rss.setToFromCenter(Vector3<S>(0.5, 0.5, 0.5));
EXPECT_TRUE(rss.To.isApprox(Vector3<S>(0.0, 0.0, 0.5)));
rss.axis *= -1.0;
rss.setToFromCenter(Vector3<S>(-0.5, -0.5, 2.5));
EXPECT_TRUE(rss.To.isApprox(Vector3<S>(0.0, 0.0, 2.5)));
}
GTEST_TEST(FCL_MATH, rss_fit)
{
test_rss_fit<double>();
}
GTEST_TEST(FCL_MATH, rss_conversion)
{
test_rss_conversion<double>();
}
GTEST_TEST(FCL_MATH, rss_distance)
{
test_rss_distance<double>();
}
GTEST_TEST(FCL_MATH, rss_position)
{
test_rss_position<double>();
}
// TODO test overlap
// TODO test contain
// TODO test operator+
// TODO test size
//==============================================================================
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 4,869 |
1,383 |
<filename>src/chrono_vehicle/output/ChVehicleOutputHDF5.h
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: <NAME>
// =============================================================================
//
// ASCII text vehicle output database.
//
// =============================================================================
#ifndef CH_VEHICLE_OUTPUT_HDF5_H
#define CH_VEHICLE_OUTPUT_HDF5_H
#include <string>
#include <fstream>
#include "chrono_vehicle/ChVehicleOutput.h"
#include "H5Cpp.h"
namespace chrono {
namespace vehicle {
/// @addtogroup vehicle
/// @{
/// HDF5 vehicle output database.
class CH_VEHICLE_API ChVehicleOutputHDF5 : public ChVehicleOutput {
public:
ChVehicleOutputHDF5(const std::string& filename);
~ChVehicleOutputHDF5();
private:
virtual void WriteTime(int frame, double time) override;
virtual void WriteSection(const std::string& name) override;
virtual void WriteBodies(const std::vector<std::shared_ptr<ChBody>>& bodies) override;
virtual void WriteAuxRefBodies(const std::vector<std::shared_ptr<ChBodyAuxRef>>& bodies) override;
virtual void WriteMarkers(const std::vector<std::shared_ptr<ChMarker>>& markers) override;
virtual void WriteShafts(const std::vector<std::shared_ptr<ChShaft>>& shafts) override;
virtual void WriteJoints(const std::vector<std::shared_ptr<ChLink>>& joints) override;
virtual void WriteCouples(const std::vector<std::shared_ptr<ChShaftsCouple>>& couples) override;
virtual void WriteLinSprings(const std::vector<std::shared_ptr<ChLinkTSDA>>& springs) override;
virtual void WriteRotSprings(const std::vector<std::shared_ptr<ChLinkRSDA>>& springs) override;
virtual void WriteBodyLoads(const std::vector<std::shared_ptr<ChLoadBodyBody>>& loads) override;
H5::H5File* m_fileHDF5;
H5::Group* m_frame_group;
H5::Group* m_section_group;
static H5::CompType* m_body_type;
static H5::CompType* m_bodyaux_type;
static H5::CompType* m_shaft_type;
static H5::CompType* m_marker_type;
static H5::CompType* m_joint_type;
static H5::CompType* m_couple_type;
static H5::CompType* m_linspring_type;
static H5::CompType* m_rotspring_type;
static H5::CompType* m_bodyload_type;
static const H5::CompType& getBodyType();
static const H5::CompType& getBodyAuxType();
static const H5::CompType& getShaftType();
static const H5::CompType& getMarkerType();
static const H5::CompType& getJointType();
static const H5::CompType& getCoupleType();
static const H5::CompType& getLinSpringType();
static const H5::CompType& getRotSpringType();
static const H5::CompType& getBodyLoadType();
};
/// @} vehicle
} // end namespace vehicle
} // end namespace chrono
#endif
| 1,042 |
694 |
msg = "hello"
print(msg)
| 12 |
575 |
<filename>third_party/blink/tools/blinkpy/tool/commands/help_command.py
# Copyright (c) 2016 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * 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 Google Inc. 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.
import optparse
from blinkpy.tool.commands.command import Command
class HelpCommand(Command):
name = 'help'
help_text = 'Display information about this program or its subcommands'
argument_names = '[COMMAND]'
def __init__(self, tool=None):
options = [
optparse.make_option(
'-a',
'--all-commands',
action='store_true',
dest='show_all_commands',
help='Print all available commands'),
]
super(HelpCommand, self).__init__(options)
# A hack used to pass --all-commands to help_epilog even though it's called by the OptionParser.
self.show_all_commands = False
# self._tool is used in help_epilog, so it's passed in the initializer rather than set in the execute method.
self._tool = tool
def help_epilog(self):
# Only show commands which are relevant to this checkout's SCM system. Might this be confusing to some users?
if self.show_all_commands:
epilog = 'All %prog commands:\n'
relevant_commands = self._tool.commands[:]
else:
epilog = 'Common %prog commands:\n'
relevant_commands = filter(self._tool.should_show_in_main_help,
self._tool.commands)
longest_name_length = max(
len(command.name) for command in relevant_commands)
relevant_commands.sort(lambda a, b: cmp(a.name, b.name))
command_help_texts = [
' %s %s\n' % (command.name.ljust(longest_name_length),
command.help_text)
for command in relevant_commands
]
epilog += '%s\n' % ''.join(command_help_texts)
epilog += "See '%prog help --all-commands' to list all commands.\n"
epilog += "See '%prog help COMMAND' for more information on a specific command.\n"
# Use of %prog here mimics OptionParser.expand_prog_name().
return epilog.replace('%prog', self._tool.name())
# FIXME: This is a hack so that we don't show --all-commands as a global option:
def _remove_help_options(self):
for option in self.options:
self.option_parser.remove_option(option.get_opt_string())
def execute(self, options, args, tool):
if args:
command = self._tool.command_by_name(args[0])
if command:
print command.standalone_help()
return 0
self.show_all_commands = options.show_all_commands
self._remove_help_options()
self.option_parser.print_help()
return 0
| 1,648 |
320 |
<reponame>strangestroad/interview-techdev-guide
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
void insertHead(Node **head, int item);
void deleteNodeatPosition(Node **head, int position);
void insertAfter(Node **prev_node, int item);
void insertEnd(Node **head, int item);
void PrintAll(Node *head);
void InsertinPosition(int item, int position);
void Reverse(Node **head);
// ! Global Variable
Node *head = NULL;
int main()
{
insertHead(&head, 5);
insertAfter(&head, 22);
insertEnd(&head, 54);
InsertinPosition(3, 2);
InsertinPosition(4, 3);
deleteNodeatPosition(&head, 3);
PrintAll(head);
cout << "After Reversing the Linked List" << endl;
Reverse(&head);
return 0;
}
void insertHead(Node **head, int item)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = item;
newNode->next = *head;
*head = newNode;
cout << " Inserted at Head " << newNode->data << endl;
}
void insertAfter(Node **prev_node, int item)
{
Node *temp = *prev_node;
if (temp == NULL)
{
cout << "Error ! Previous Node Cannot be NULL" << endl;
}
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = item;
newNode->next = temp->next;
temp->next = newNode;
cout << "Inserted " << item << "before " << temp->data << endl;
}
void insertEnd(Node **head, int item)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = item;
newNode->next = NULL;
if (*head == NULL)
{
*head = newNode;
}
Node *last = *head;
while (last->next != NULL)
{
last = last->next;
}
last->next = newNode;
cout << "Inserted " << item << " at end " << endl;
}
void PrintAll(Node *head)
{
while (head != NULL)
{
cout << head->data << endl;
head = head->next;
}
}
void InsertinPosition(int item, int position)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = item;
newNode->next = NULL;
if (position == 1)
{
newNode->next = head;
head = newNode;
}
else
{
Node *temp = head;
for (int i = 0; i < position - 2; i++)
{
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
}
void deleteNodeatPosition(Node **head, int position)
{
Node *temp1 = *head;
if (position == 1)
{
*head = temp1->next;
free(temp1);
}
else
{
Node *temp2 = temp1->next;
for (int i = 0; i < position - 2; i++)
{
temp1 = temp1->next;
}
temp1->next = temp2->next;
free(temp2);
}
}
void Reverse(Node **head)
{
Node *current = *head;
Node *prev = NULL, *next = NULL;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
PrintAll(*head);
}
| 1,309 |
411 |
<filename>documents4j-transformer-msoffice/documents4j-transformer-msoffice-powerpoint/src/test/java/com/documents4j/conversion/msoffice/MicrosoftPowerpointInaccessibilityTest.java
package com.documents4j.conversion.msoffice;
import com.documents4j.api.DocumentType;
import org.junit.BeforeClass;
public class MicrosoftPowerpointInaccessibilityTest extends AbstractMicrosoftOfficeInaccessibilityTest {
public MicrosoftPowerpointInaccessibilityTest() {
super(new DocumentTypeProvider(MicrosoftPowerpointPresentation.PPTX_VALID,
MicrosoftPowerpointPresentation.PPTX_CORRUPT,
MicrosoftPowerpointPresentation.PPTX_INEXISTENT,
DocumentType.PPTX,
DocumentType.PDF,
"pdf",
true));
}
@BeforeClass
public static void setUpConverter() throws Exception {
setUp(MicrosoftPowerpointBridge.class, MicrosoftPowerpointScript.ASSERTION, MicrosoftPowerpointScript.SHUTDOWN);
}
}
| 377 |
852 |
#ifndef DQM_SiStripCommissioningSummary_OptoScanSummaryFactory_H
#define DQM_SiStripCommissioningSummary_OptoScanSummaryFactory_H
#include "DQM/SiStripCommissioningSummary/interface/CommissioningSummaryFactory.h"
class OptoScanSummaryFactory : public SummaryPlotFactory<CommissioningAnalysis*> {
protected:
void extract(Iterator) override;
void format() override;
};
#endif // DQM_SiStripCommissioningSummary_OptoScanSummaryFactory_H
| 134 |
492 |
<filename>losses/blend_loss.py
import torch
import PIL
import os
from losses import masked_lpips
class BlendLossBuilder(torch.nn.Module):
def __init__(self, opt):
super(BlendLossBuilder, self).__init__()
self.opt = opt
self.parsed_loss = [[1.0, 'face'], [1.0, 'hair']]
if opt.device == 'cuda':
use_gpu = True
else:
use_gpu = False
self.face_percept = masked_lpips.PerceptualLoss(
model="net-lin", net="vgg", vgg_blocks=['1', '2', '3'], use_gpu=use_gpu
)
self.face_percept.eval()
self.hair_percept = masked_lpips.PerceptualLoss(
model="net-lin", net="vgg", vgg_blocks=['1', '2', '3'], use_gpu=use_gpu
)
self.hair_percept.eval()
def _loss_face_percept(self, gen_im, ref_im, mask, **kwargs):
return self.face_percept(gen_im, ref_im, mask=mask)
def _loss_hair_percept(self, gen_im, ref_im, mask, **kwargs):
return self.hair_percept(gen_im, ref_im, mask=mask)
def forward(self, gen_im, im_1, im_3, mask_face, mask_hair):
loss = 0
loss_fun_dict = {
'face': self._loss_face_percept,
'hair': self._loss_hair_percept,
}
losses = {}
for weight, loss_type in self.parsed_loss:
if loss_type == 'face':
var_dict = {
'gen_im': gen_im,
'ref_im': im_1,
'mask': mask_face
}
elif loss_type == 'hair':
var_dict = {
'gen_im': gen_im,
'ref_im': im_3,
'mask': mask_hair
}
tmp_loss = loss_fun_dict[loss_type](**var_dict)
losses[loss_type] = tmp_loss
loss += weight*tmp_loss
return loss, losses
| 1,013 |
14,668 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_CHROME_CLEANER_TEST_TEST_SCOPED_SERVICE_HANDLE_H_
#define CHROME_CHROME_CLEANER_TEST_TEST_SCOPED_SERVICE_HANDLE_H_
#include <string>
#include "chrome/chrome_cleaner/os/scoped_service_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chrome_cleaner {
// Offers the basic methods for using a service in the context of a test, such
// as installing, starting and closing the service that is defined by the
// ScopedServiceHandle class.
class TestScopedServiceHandle : public ScopedServiceHandle {
public:
~TestScopedServiceHandle();
::testing::AssertionResult InstallService();
::testing::AssertionResult StartService();
::testing::AssertionResult StopAndDelete();
void Close();
const wchar_t* service_name() const { return service_name_.c_str(); }
private:
std::wstring service_name_;
};
// Returns a random string that is not an existing service name. This is a
// best-effort check as a service with that name could be created before the
// function returns.
std::wstring RandomUnusedServiceNameForTesting();
// Tries to stop any copies of the test service executable that are running.
// Returns false if an executable remains running.
::testing::AssertionResult EnsureNoTestServicesRunning();
} // namespace chrome_cleaner
#endif // CHROME_CHROME_CLEANER_TEST_TEST_SCOPED_SERVICE_HANDLE_H_
| 458 |
1,351 |
/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
1 test_Cache.cc + X distributed with this work for additional information regarding copyright ownership. The ASF licenses this
file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "main.h"
#include "CacheTestHandler.h"
TestContChain::TestContChain() : Continuation(new_ProxyMutex()) {}
CacheTestHandler::CacheTestHandler(size_t size, const char *url)
{
this->_wt = new CacheWriteTest(size, this, url);
this->_rt = new CacheReadTest(size, this, url);
this->_wt->mutex = this->mutex;
this->_rt->mutex = this->mutex;
SET_HANDLER(&CacheTestHandler::start_test);
}
void
CacheTestHandler::handle_cache_event(int event, CacheTestBase *base)
{
REQUIRE(base != nullptr);
switch (event) {
case CACHE_EVENT_OPEN_READ:
base->do_io_read();
break;
case CACHE_EVENT_OPEN_WRITE:
base->do_io_write();
break;
case VC_EVENT_READ_READY:
case VC_EVENT_WRITE_READY:
REQUIRE(base->vc != nullptr);
REQUIRE(base->vio != nullptr);
base->reenable();
break;
case VC_EVENT_WRITE_COMPLETE:
this_ethread()->schedule_imm(this->_rt);
base->close();
break;
case VC_EVENT_READ_COMPLETE:
base->close();
delete this;
break;
default:
REQUIRE(false);
base->close();
delete this;
break;
}
return;
}
int
CacheTestHandler::start_test(int event, void *e)
{
this_ethread()->schedule_imm(this->_wt);
return 0;
}
| 702 |
3,371 |
package com.beloo.chipslayoutmanager.sample.ui;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity;
import com.beloo.chipslayoutmanager.sample.ui.adapter.ChipsAdapter;
import com.beloo.widget.chipslayoutmanager.SpacingItemDecoration;
import java.util.List;
import com.beloo.chipslayoutmanager.sample.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
*/
public class BottomSheetFragment extends Fragment {
public BottomSheetFragment() {
// Required empty public constructor
}
public static BottomSheetFragment newInstance() {
Bundle args = new Bundle();
BottomSheetFragment fragment = new BottomSheetFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_bottom_sheet, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
}
@OnClick(R.id.btnShowSheet)
void onShowSheetClicked(View view) {
BottomSheetDialogFragment fragment = BottomSheetDialogFragment.newInstance();
fragment.show(getChildFragmentManager(), fragment.getTag());
}
}
| 668 |
655 |
/* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Projecting Op
#include <stdio.h>
#include <cfloat>
#include <math.h>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
using namespace tensorflow;
typedef Eigen::ThreadPoolDevice CPUDevice;
REGISTER_OP("Project")
.Attr("T: {float, double}")
.Attr("kernel_size: int")
.Attr("threshold: float")
.Input("bottom_data: T")
.Input("bottom_depth: T")
.Input("bottom_meta_data: T")
.Output("top_data: T");
REGISTER_OP("ProjectGrad")
.Attr("T: {float, double}")
.Attr("kernel_size: int")
.Attr("threshold: float")
.Input("bottom_data: T")
.Input("bottom_depth: T")
.Input("bottom_meta_data: T")
.Input("grad: T")
.Output("output: T");
template <typename Device, typename T>
class ProjectOp : public OpKernel {
public:
explicit ProjectOp(OpKernelConstruction* context) : OpKernel(context) {
// Get the kernel size
OP_REQUIRES_OK(context,
context->GetAttr("kernel_size", &kernel_size_));
// Check that kernel size is positive
OP_REQUIRES(context, kernel_size_ >= 0,
errors::InvalidArgument("Need kernel_size >= 0, got ", kernel_size_));
// Get the threshold
OP_REQUIRES_OK(context,
context->GetAttr("threshold", &threshold_));
// Check that threshold is positive
OP_REQUIRES(context, threshold_ >= 0,
errors::InvalidArgument("Need threshold >= 0, got ", threshold_));
}
// bottom_data: (batch_size, grid_size, grid_size, grid_size, channels)
void Compute(OpKernelContext* context) override
{
// Grab the input tensor
const Tensor& bottom_data = context->input(0);
auto bottom_data_flat = bottom_data.flat<T>();
const Tensor& bottom_depth = context->input(1);
auto im_depth = bottom_depth.flat<T>();
// format of the meta_data
// intrinsic matrix: meta_data[0 ~ 8]
// inverse intrinsic matrix: meta_data[9 ~ 17]
// pose_world2live: meta_data[18 ~ 29]
// pose_live2world: meta_data[30 ~ 41]
// voxel step size: meta_data[42, 43, 44]
// voxel min value: meta_data[45, 46, 47]
const Tensor& bottom_meta_data = context->input(2);
auto meta_data = bottom_meta_data.flat<T>();
// data should have 4 dimensions.
OP_REQUIRES(context, bottom_data.dims() == 5,
errors::InvalidArgument("data must be 5-dimensional"));
OP_REQUIRES(context, bottom_depth.dims() == 4,
errors::InvalidArgument("depth must be 4-dimensional"));
OP_REQUIRES(context, bottom_meta_data.dims() == 4,
errors::InvalidArgument("meta data must be 4-dimensional"));
// batch size
int batch_size = bottom_data.dim_size(0);
// grid size
int grid_size = bottom_data.dim_size(1);
// number of channels
int num_channels = bottom_data.dim_size(4);
// height
int height = bottom_depth.dim_size(1);
// width
int width = bottom_depth.dim_size(2);
// number of meta data
int num_meta_data = bottom_meta_data.dim_size(3);
// Create output tensors
// top_data
int dims[4];
dims[0] = batch_size;
dims[1] = height;
dims[2] = width;
dims[3] = num_channels;
TensorShape output_shape;
TensorShapeUtils::MakeShape(dims, 4, &output_shape);
Tensor* top_data_tensor = NULL;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &top_data_tensor));
auto top_data = top_data_tensor->template flat<T>();
int index_meta_data = 0;
for(int n = 0; n < batch_size; n++)
{
for(int h = 0; h < height; h++)
{
for(int w = 0; w < width; w++)
{
int index_pixel = n * height * width + h * width + w;
T depth = im_depth(index_pixel);
// find the voxel for this pixel
// backproject the pixel to 3D
// format of the meta_data
// intrinsic matrix: meta_data[0 ~ 8]
// inverse intrinsic matrix: meta_data[9 ~ 17]
// pose_world2live: meta_data[18 ~ 29]
// pose_live2world: meta_data[30 ~ 41]
// voxel step size: meta_data[42, 43, 44]
// voxel min value: meta_data[45, 46, 47]
// apply the inverse intrinsic matrix
int offset = n * num_meta_data + 9;
T RX = meta_data(offset + 0) * w + meta_data(offset + 1) * h + meta_data(offset + 2);
T RY = meta_data(offset + 3) * w + meta_data(offset + 4) * h + meta_data(offset + 5);
T RZ = meta_data(offset + 6) * w + meta_data(offset + 7) * h + meta_data(offset + 8);
// compute the 3D points in camera's coordinate system
T X = depth * RX;
T Y = depth * RY;
T Z = depth * RZ;
// apply pose_live2world
offset = n * num_meta_data;
T X1 = meta_data(offset + 30) * X + meta_data(offset + 31) * Y + meta_data(offset + 32) * Z + meta_data(offset + 33);
T Y1 = meta_data(offset + 34) * X + meta_data(offset + 35) * Y + meta_data(offset + 36) * Z + meta_data(offset + 37);
T Z1 = meta_data(offset + 38) * X + meta_data(offset + 39) * Y + meta_data(offset + 40) * Z + meta_data(offset + 41);
// voxel location in 3D
int vd = round((X1 - meta_data(offset + 45)) / meta_data(offset + 42));
int vh = round((Y1 - meta_data(offset + 46)) / meta_data(offset + 43));
int vw = round((Z1 - meta_data(offset + 47)) / meta_data(offset + 44));
// get the data
if (vd >= 0 && vd < grid_size && vh >= 0 && vh < grid_size && vw >= 0 && vw < grid_size)
{
for(int c = 0; c < num_channels; c++)
top_data(index_pixel * num_channels + c) = bottom_data_flat((n * grid_size * grid_size * grid_size + vd * grid_size * grid_size + vh * grid_size + vw) * num_channels + c);
}
else
{
for(int c = 0; c < num_channels; c++)
top_data(index_pixel * num_channels + c) = 0;
}
}
}
}
}
private:
int kernel_size_;
float threshold_;
};
REGISTER_KERNEL_BUILDER(Name("Project").Device(DEVICE_CPU).TypeConstraint<float>("T"), ProjectOp<CPUDevice, float>);
REGISTER_KERNEL_BUILDER(Name("Project").Device(DEVICE_CPU).TypeConstraint<double>("T"), ProjectOp<CPUDevice, double>);
bool ProjectForwardLaucher(
const float* bottom_data, const float* bottom_depth, const float* bottom_meta_data,
const int batch_size, const int height, const int width, const int channels, const int num_meta_data,
const int grid_size, float* top_data, const Eigen::GpuDevice& d);
static void ProjectingKernel(
OpKernelContext* context, const Tensor* bottom_data, const Tensor* bottom_depth, const Tensor* bottom_meta_data,
const int batch_size, const int height, const int width, const int channels, const int num_meta_data,
const int grid_size, const TensorShape& tensor_output_shape)
{
Tensor* top_data = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, tensor_output_shape, &top_data));
if (!context->status().ok()) {
return;
}
ProjectForwardLaucher(
bottom_data->flat<float>().data(), bottom_depth->flat<float>().data(), bottom_meta_data->flat<float>().data(),
batch_size, height, width, channels, num_meta_data, grid_size,
top_data->flat<float>().data(), context->eigen_device<Eigen::GpuDevice>());
}
template <class T>
class ProjectOp<Eigen::GpuDevice, T> : public OpKernel {
public:
typedef Eigen::GpuDevice Device;
explicit ProjectOp(OpKernelConstruction* context) : OpKernel(context) {
// Get the kernel size
OP_REQUIRES_OK(context,
context->GetAttr("kernel_size", &kernel_size_));
// Check that kernel size is positive
OP_REQUIRES(context, kernel_size_ >= 0,
errors::InvalidArgument("Need kernel_size >= 0, got ", kernel_size_));
// Get the threshold
OP_REQUIRES_OK(context,
context->GetAttr("threshold", &threshold_));
// Check that threshold is positive
OP_REQUIRES(context, threshold_ >= 0,
errors::InvalidArgument("Need threshold >= 0, got ", threshold_));
}
void Compute(OpKernelContext* context) override
{
// Grab the input tensor
const Tensor& bottom_data = context->input(0);
const Tensor& bottom_depth = context->input(1);
const Tensor& bottom_meta_data = context->input(2);
// data should have 5 dimensions.
OP_REQUIRES(context, bottom_data.dims() == 5,
errors::InvalidArgument("data must be 5-dimensional"));
OP_REQUIRES(context, bottom_depth.dims() == 4,
errors::InvalidArgument("depth must be 4-dimensional"));
OP_REQUIRES(context, bottom_meta_data.dims() == 4,
errors::InvalidArgument("meta data must be 4-dimensional"));
// batch size
int batch_size = bottom_data.dim_size(0);
// grid size
int grid_size = bottom_data.dim_size(1);
// number of channels
int num_channels = bottom_data.dim_size(4);
// height
int height = bottom_depth.dim_size(1);
// width
int width = bottom_depth.dim_size(2);
// number of meta data
int num_meta_data = bottom_meta_data.dim_size(3);
// Create output tensors
// top_data
int dims[4];
dims[0] = batch_size;
dims[1] = height;
dims[2] = width;
dims[3] = num_channels;
TensorShape output_shape;
TensorShapeUtils::MakeShape(dims, 4, &output_shape);
ProjectingKernel(context, &bottom_data, &bottom_depth, &bottom_meta_data, batch_size, height,
width, num_channels, num_meta_data, grid_size, output_shape);
}
private:
int kernel_size_;
float threshold_;
};
REGISTER_KERNEL_BUILDER(Name("Project").Device(DEVICE_GPU).TypeConstraint<float>("T"), ProjectOp<Eigen::GpuDevice, float>);
bool ProjectBackwardLaucher(const float* top_diff, const float* bottom_depth, const float* bottom_meta_data, const int batch_size,
const int height, const int width, const int channels, const int num_meta_data, const int grid_size, const int kernel_size, const float threshold,
float* bottom_diff, const Eigen::GpuDevice& d);
static void ProjectingGradKernel(
OpKernelContext* context, const Tensor* bottom_depth, const Tensor* bottom_meta_data, const Tensor* out_backprop,
const int batch_size, const int height, const int width, const int channels, const int num_meta_data,
const int grid_size, const int kernel_size, const float threshold,
const TensorShape& tensor_output_shape)
{
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, tensor_output_shape, &output));
if (!context->status().ok()) {
return;
}
ProjectBackwardLaucher(
out_backprop->flat<float>().data(), bottom_depth->flat<float>().data(), bottom_meta_data->flat<float>().data(),
batch_size, height, width, channels, num_meta_data, grid_size, kernel_size, threshold, output->flat<float>().data(), context->eigen_device<Eigen::GpuDevice>());
}
// compute gradient
template <class Device, class T>
class ProjectGradOp : public OpKernel {
public:
explicit ProjectGradOp(OpKernelConstruction* context) : OpKernel(context) {
// Get the kernel size
OP_REQUIRES_OK(context,
context->GetAttr("kernel_size", &kernel_size_));
// Check that kernel size is positive
OP_REQUIRES(context, kernel_size_ >= 0,
errors::InvalidArgument("Need kernel_size >= 0, got ", kernel_size_));
// Get the threshold
OP_REQUIRES_OK(context,
context->GetAttr("threshold", &threshold_));
// Check that threshold is positive
OP_REQUIRES(context, threshold_ >= 0,
errors::InvalidArgument("Need threshold >= 0, got ", threshold_));
}
void Compute(OpKernelContext* context) override
{
// Grab the input tensor
const Tensor& bottom_data = context->input(0);
const Tensor& bottom_depth = context->input(1);
const Tensor& bottom_meta_data = context->input(2);
const Tensor& out_backprop = context->input(3);
// data should have 5 dimensions.
OP_REQUIRES(context, bottom_data.dims() == 5,
errors::InvalidArgument("data must be 5-dimensional"));
OP_REQUIRES(context, bottom_depth.dims() == 4,
errors::InvalidArgument("depth must be 4-dimensional"));
OP_REQUIRES(context, bottom_meta_data.dims() == 4,
errors::InvalidArgument("meta data must be 4-dimensional"));
// batch size
int batch_size = bottom_data.dim_size(0);
// grid size
int grid_size = bottom_data.dim_size(1);
// number of channels
int num_channels = bottom_data.dim_size(4);
// height
int height = bottom_depth.dim_size(1);
// width
int width = bottom_depth.dim_size(2);
// number of meta data
int num_meta_data = bottom_meta_data.dim_size(3);
// construct the output shape
TensorShape output_shape = bottom_data.shape();
ProjectingGradKernel(
context, &bottom_depth, &bottom_meta_data, &out_backprop,
batch_size, height, width, num_channels, num_meta_data, grid_size, kernel_size_, threshold_, output_shape);
}
private:
int kernel_size_;
float threshold_;
};
REGISTER_KERNEL_BUILDER(Name("ProjectGrad").Device(DEVICE_GPU).TypeConstraint<float>("T"), ProjectGradOp<Eigen::GpuDevice, float>);
| 5,554 |
333 |
/**
* Copyright 2016 Red Hat, Inc.
*
* Red Hat 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 io.fabric8.maven.core.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author roland
* @since 24/07/16
*/
public class ProcessorConfigTest {
List<String> includes = Arrays.asList("i1", "i2", "i3");
Set<String> excludes = new HashSet<>(Arrays.asList("e1"));
Map <String, TreeMap> config = Collections.singletonMap("k1", new TreeMap(Collections.singletonMap("i1","v1")));
@Test
public void incAndExc() {
ProcessorConfig pConfig = new ProcessorConfig(includes, excludes, config);
List<TestNamed> filtered = pConfig.prepareProcessors(getAllTestData(), "test");
assertTrue(contains(filtered, "i2"));
assertFalse(contains(filtered, "e1"));
assertFalse(contains(filtered, "n1"));
}
@Test
public void inc() {
ProcessorConfig pConfig = new ProcessorConfig(includes, null, config);
List<TestNamed> filtered = pConfig.prepareProcessors(getAllTestData(), "test");
assertTrue(contains(filtered, "i2"));
assertFalse(contains(filtered, "e1"));
assertFalse(contains(filtered, "n1"));
}
@Test
public void exc() {
ProcessorConfig pConfig = new ProcessorConfig(null, excludes, config);
List<TestNamed> filtered = pConfig.prepareProcessors(getAllTestData(), "test");
assertFalse(contains(filtered, "i2"));
assertFalse(contains(filtered, "e1"));
assertFalse(contains(filtered, "n1"));
}
@Test
public void empty() {
ProcessorConfig pConfig = new ProcessorConfig(Collections.<String>emptyList(), null, config);
List<TestNamed> filtered = pConfig.prepareProcessors(getAllTestData(), "test");
assertFalse(contains(filtered, "i2"));
assertFalse(contains(filtered, "e1"));
assertFalse(contains(filtered, "n1"));
}
@Test
public void config() {
ProcessorConfig pConfig = new ProcessorConfig(null, null, config);
assertEquals("v1", pConfig.getConfig("k1", "i1"));
assertNull(pConfig.getConfig("k2", "i1"));
assertNull(pConfig.getConfig("k1", "i2"));
}
@Test
public void order() {
List<TestNamed> data = Arrays.asList(
new TestNamed("t1"),
new TestNamed("t2"),
new TestNamed("t3"),
new TestNamed("t4"));
List<String> inc = Arrays.asList("t4", "t2");
ProcessorConfig pConfig = new ProcessorConfig(inc, null, null);
List<TestNamed> result = pConfig.prepareProcessors(data, "test");
assertEquals(2,result.size());
assertEquals("t4", result.get(0).getName());
assertEquals("t2", result.get(1).getName());
}
@Test
public void orderWithInvalidInc() {
List<TestNamed> data = Arrays.asList(new TestNamed("t1"));
List<String> inc = Arrays.asList("t3", "t1");
ProcessorConfig pConfig = new ProcessorConfig(inc, null, null);
try {
pConfig.prepareProcessors(data, "bla");
fail();
} catch (IllegalArgumentException exp) {
assertTrue(exp.getMessage().contains("bla"));
}
}
@Test
public void merge() {
Yaml yaml = new Yaml();
List<Map> data = (List<Map>) yaml.load(getClass().getResourceAsStream("/fabric8/config/ProcessorConfigTest.yml"));
for (Map entry : data) {
List<Map> inputs = (List<Map>) entry.get("input");
ArrayList<ProcessorConfig> processorConfigs = new ArrayList<>();
for (Map input : inputs) {
processorConfigs.add(extractProcessorConfig(input));
}
ProcessorConfig merged = ProcessorConfig.mergeProcessorConfigs(processorConfigs.toArray(new ProcessorConfig[0]));
ProcessorConfig expected = extractProcessorConfig((Map) entry.get("merged"));
assertEquals(expected.includes, merged.includes);
assertEquals(expected.excludes, merged.excludes);
assertEquals(expected.config.keySet(), merged.config.keySet());
for (Map.Entry<String, TreeMap> configEntry : merged.config.entrySet()) {
TreeMap<String, String> expectedValues = expected.config.get(configEntry.getKey());
TreeMap<String, String> mergedValues = configEntry.getValue();
assertEquals(expectedValues.size(),mergedValues.size());
for (Map.Entry<String, String> valEntry : mergedValues.entrySet()) {
assertEquals(expectedValues.get(valEntry.getKey()), valEntry.getValue());
}
}
}
}
// =================================================================================
private ProcessorConfig extractProcessorConfig(Map input) {
List<String> i = (List<String>) input.get("includes");
List<String> eL = (List<String>) input.get("excludes");
Set<String> e = eL != null ? new HashSet(eL) : null;
Map<String,Map> cV = (Map<String, Map>) input.get("config");
Map<String, TreeMap> c = null;
if (cV != null) {
c = new HashMap<>();
for (Map.Entry<String, Map> el : cV.entrySet()) {
c.put(el.getKey(), new TreeMap(el.getValue()));
}
}
return new ProcessorConfig(i, e, c);
}
private boolean contains(List<TestNamed> list, String element) {
return list.contains(new TestNamed(element));
}
private List<TestNamed> getAllTestData() {
return Arrays.asList(new TestNamed("i2"), new TestNamed("i1"), new TestNamed("i3"), new TestNamed("e1"));
}
private class TestNamed implements Named {
private String name;
@Override
public String getName() {
return name;
}
public TestNamed(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestNamed testNamed = (TestNamed) o;
if (name != null ? !name.equals(testNamed.name) : testNamed.name != null) return false;
return true;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
}
}
| 3,039 |
1,435 |
from libcloud.container.types import Provider
from libcloud.container.providers import get_driver
driver = get_driver(Provider.RANCHER)
connection = driver("MYRANCHERACCESSKEY", "MYRANCHERSECRETKEY",
host="172.30.0.100", port=8080, secure=False)
new_stack = connection.ex_deploy_stack(name="GhostBlog",
description="Contains services for the"
"ghost blog.")
id_of_new_stack = new_stack['id']
| 240 |
1,602 |
//===-- Passes.h - Target independent code generation passes ----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code generation
// passes provided by the LLVM backend.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CODEGEN_PASSES_H
#define LLVM_CODEGEN_PASSES_H
#include "llvm/Support/CodeGen.h"
#include <functional>
#include <string>
namespace llvm {
class FunctionPass;
class MachineFunction;
class MachineFunctionPass;
class MemoryBuffer;
class ModulePass;
class Pass;
class TargetMachine;
class TargetRegisterClass;
class raw_ostream;
} // End llvm namespace
/// List of target independent CodeGen pass IDs.
namespace llvm {
FunctionPass *createAtomicExpandPass();
/// createUnreachableBlockEliminationPass - The LLVM code generator does not
/// work well with unreachable basic blocks (what live ranges make sense for a
/// block that cannot be reached?). As such, a code generator should either
/// not instruction select unreachable blocks, or run this pass as its
/// last LLVM modifying pass to clean up blocks that are not reachable from
/// the entry block.
FunctionPass *createUnreachableBlockEliminationPass();
/// createBBSectionsPrepare Pass - This pass assigns sections to machine basic
/// blocks and is enabled with -fbasic-block-sections.
/// Buf is a memory buffer that contains the list of functions and basic
/// block ids to selectively enable basic block sections.
MachineFunctionPass *createBBSectionsPreparePass(const MemoryBuffer *Buf);
/// MachineFunctionPrinter pass - This pass prints out the machine function to
/// the given stream as a debugging tool.
MachineFunctionPass *
createMachineFunctionPrinterPass(raw_ostream &OS,
const std::string &Banner ="");
/// MIRPrinting pass - this pass prints out the LLVM IR into the given stream
/// using the MIR serialization format.
MachineFunctionPass *createPrintMIRPass(raw_ostream &OS);
/// This pass resets a MachineFunction when it has the FailedISel property
/// as if it was just created.
/// If EmitFallbackDiag is true, the pass will emit a
/// DiagnosticInfoISelFallback for every MachineFunction it resets.
/// If AbortOnFailedISel is true, abort compilation instead of resetting.
MachineFunctionPass *createResetMachineFunctionPass(bool EmitFallbackDiag,
bool AbortOnFailedISel);
/// createCodeGenPreparePass - Transform the code to expose more pattern
/// matching during instruction selection.
FunctionPass *createCodeGenPreparePass();
/// createScalarizeMaskedMemIntrinPass - Replace masked load, store, gather
/// and scatter intrinsics with scalar code when target doesn't support them.
FunctionPass *createScalarizeMaskedMemIntrinPass();
/// AtomicExpandID -- Lowers atomic operations in terms of either cmpxchg
/// load-linked/store-conditional loops.
extern char &AtomicExpandID;
/// MachineLoopInfo - This pass is a loop analysis pass.
extern char &MachineLoopInfoID;
/// MachineDominators - This pass is a machine dominators analysis pass.
extern char &MachineDominatorsID;
/// MachineDominanaceFrontier - This pass is a machine dominators analysis pass.
extern char &MachineDominanceFrontierID;
/// MachineRegionInfo - This pass computes SESE regions for machine functions.
extern char &MachineRegionInfoPassID;
/// EdgeBundles analysis - Bundle machine CFG edges.
extern char &EdgeBundlesID;
/// LiveVariables pass - This pass computes the set of blocks in which each
/// variable is life and sets machine operand kill flags.
extern char &LiveVariablesID;
/// PHIElimination - This pass eliminates machine instruction PHI nodes
/// by inserting copy instructions. This destroys SSA information, but is the
/// desired input for some register allocators. This pass is "required" by
/// these register allocator like this: AU.addRequiredID(PHIEliminationID);
extern char &PHIEliminationID;
/// LiveIntervals - This analysis keeps track of the live ranges of virtual
/// and physical registers.
extern char &LiveIntervalsID;
/// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
extern char &LiveStacksID;
/// TwoAddressInstruction - This pass reduces two-address instructions to
/// use two operands. This destroys SSA information but it is desired by
/// register allocators.
extern char &TwoAddressInstructionPassID;
/// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
extern char &ProcessImplicitDefsID;
/// RegisterCoalescer - This pass merges live ranges to eliminate copies.
extern char &RegisterCoalescerID;
/// MachineScheduler - This pass schedules machine instructions.
extern char &MachineSchedulerID;
/// PostMachineScheduler - This pass schedules machine instructions postRA.
extern char &PostMachineSchedulerID;
/// SpillPlacement analysis. Suggest optimal placement of spill code between
/// basic blocks.
extern char &SpillPlacementID;
/// ShrinkWrap pass. Look for the best place to insert save and restore
// instruction and update the MachineFunctionInfo with that information.
extern char &ShrinkWrapID;
/// LiveRangeShrink pass. Move instruction close to its definition to shrink
/// the definition's live range.
extern char &LiveRangeShrinkID;
/// Greedy register allocator.
extern char &RAGreedyID;
/// Basic register allocator.
extern char &RABasicID;
/// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
/// assigned in VirtRegMap.
extern char &VirtRegRewriterID;
/// UnreachableMachineBlockElimination - This pass removes unreachable
/// machine basic blocks.
extern char &UnreachableMachineBlockElimID;
/// DeadMachineInstructionElim - This pass removes dead machine instructions.
extern char &DeadMachineInstructionElimID;
/// This pass adds dead/undef flags after analyzing subregister lanes.
extern char &DetectDeadLanesID;
/// This pass perform post-ra machine sink for COPY instructions.
extern char &PostRAMachineSinkingID;
/// FastRegisterAllocation Pass - This pass register allocates as fast as
/// possible. It is best suited for debug code where live ranges are short.
///
FunctionPass *createFastRegisterAllocator();
/// BasicRegisterAllocation Pass - This pass implements a degenerate global
/// register allocator using the basic regalloc framework.
///
FunctionPass *createBasicRegisterAllocator();
/// Greedy register allocation pass - This pass implements a global register
/// allocator for optimized builds.
///
FunctionPass *createGreedyRegisterAllocator();
/// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
/// Quadratic Prograaming (PBQP) based register allocator.
///
FunctionPass *createDefaultPBQPRegisterAllocator();
/// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
/// and eliminates abstract frame references.
extern char &PrologEpilogCodeInserterID;
MachineFunctionPass *createPrologEpilogInserterPass();
/// ExpandPostRAPseudos - This pass expands pseudo instructions after
/// register allocation.
extern char &ExpandPostRAPseudosID;
/// PostRAHazardRecognizer - This pass runs the post-ra hazard
/// recognizer.
extern char &PostRAHazardRecognizerID;
/// PostRAScheduler - This pass performs post register allocation
/// scheduling.
extern char &PostRASchedulerID;
/// BranchFolding - This pass performs machine code CFG based
/// optimizations to delete branches to branches, eliminate branches to
/// successor blocks (creating fall throughs), and eliminating branches over
/// branches.
extern char &BranchFolderPassID;
/// BranchRelaxation - This pass replaces branches that need to jump further
/// than is supported by a branch instruction.
extern char &BranchRelaxationPassID;
/// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
extern char &MachineFunctionPrinterPassID;
/// MIRPrintingPass - this pass prints out the LLVM IR using the MIR
/// serialization format.
extern char &MIRPrintingPassID;
/// TailDuplicate - Duplicate blocks with unconditional branches
/// into tails of their predecessors.
extern char &TailDuplicateID;
/// Duplicate blocks with unconditional branches into tails of their
/// predecessors. Variant that works before register allocation.
extern char &EarlyTailDuplicateID;
/// MachineTraceMetrics - This pass computes critical path and CPU resource
/// usage in an ensemble of traces.
extern char &MachineTraceMetricsID;
/// EarlyIfConverter - This pass performs if-conversion on SSA form by
/// inserting cmov instructions.
extern char &EarlyIfConverterID;
/// EarlyIfPredicator - This pass performs if-conversion on SSA form by
/// predicating if/else block and insert select at the join point.
extern char &EarlyIfPredicatorID;
/// This pass performs instruction combining using trace metrics to estimate
/// critical-path and resource depth.
extern char &MachineCombinerID;
/// StackSlotColoring - This pass performs stack coloring and merging.
/// It merges disjoint allocas to reduce the stack size.
extern char &StackColoringID;
/// IfConverter - This pass performs machine code if conversion.
extern char &IfConverterID;
FunctionPass *createIfConverter(
std::function<bool(const MachineFunction &)> Ftor);
/// MachineBlockPlacement - This pass places basic blocks based on branch
/// probabilities.
extern char &MachineBlockPlacementID;
/// MachineBlockPlacementStats - This pass collects statistics about the
/// basic block placement using branch probabilities and block frequency
/// information.
extern char &MachineBlockPlacementStatsID;
/// GCLowering Pass - Used by gc.root to perform its default lowering
/// operations.
FunctionPass *createGCLoweringPass();
/// ShadowStackGCLowering - Implements the custom lowering mechanism
/// used by the shadow stack GC. Only runs on functions which opt in to
/// the shadow stack collector.
FunctionPass *createShadowStackGCLoweringPass();
/// GCMachineCodeAnalysis - Target-independent pass to mark safe points
/// in machine code. Must be added very late during code generation, just
/// prior to output, and importantly after all CFG transformations (such as
/// branch folding).
extern char &GCMachineCodeAnalysisID;
/// Creates a pass to print GC metadata.
///
FunctionPass *createGCInfoPrinter(raw_ostream &OS);
/// MachineCSE - This pass performs global CSE on machine instructions.
extern char &MachineCSEID;
/// MIRCanonicalizer - This pass canonicalizes MIR by renaming vregs
/// according to the semantics of the instruction as well as hoists
/// code.
extern char &MIRCanonicalizerID;
/// ImplicitNullChecks - This pass folds null pointer checks into nearby
/// memory operations.
extern char &ImplicitNullChecksID;
/// This pass performs loop invariant code motion on machine instructions.
extern char &MachineLICMID;
/// This pass performs loop invariant code motion on machine instructions.
/// This variant works before register allocation. \see MachineLICMID.
extern char &EarlyMachineLICMID;
/// MachineSinking - This pass performs sinking on machine instructions.
extern char &MachineSinkingID;
/// MachineCopyPropagation - This pass performs copy propagation on
/// machine instructions.
extern char &MachineCopyPropagationID;
/// PeepholeOptimizer - This pass performs peephole optimizations -
/// like extension and comparison eliminations.
extern char &PeepholeOptimizerID;
/// OptimizePHIs - This pass optimizes machine instruction PHIs
/// to take advantage of opportunities created during DAG legalization.
extern char &OptimizePHIsID;
/// StackSlotColoring - This pass performs stack slot coloring.
extern char &StackSlotColoringID;
/// This pass lays out funclets contiguously.
extern char &FuncletLayoutID;
/// This pass inserts the XRay instrumentation sleds if they are supported by
/// the target platform.
extern char &XRayInstrumentationID;
/// This pass inserts FEntry calls
extern char &FEntryInserterID;
/// This pass implements the "patchable-function" attribute.
extern char &PatchableFunctionID;
/// createStackProtectorPass - This pass adds stack protectors to functions.
///
FunctionPass *createStackProtectorPass();
/// createMachineVerifierPass - This pass verifies cenerated machine code
/// instructions for correctness.
///
FunctionPass *createMachineVerifierPass(const std::string& Banner);
/// createDwarfEHPass - This pass mulches exception handling code into a form
/// adapted to code generation. Required if using dwarf exception handling.
FunctionPass *createDwarfEHPass(CodeGenOpt::Level OptLevel);
/// createWinEHPass - Prepares personality functions used by MSVC on Windows,
/// in addition to the Itanium LSDA based personalities.
FunctionPass *createWinEHPass(bool DemoteCatchSwitchPHIOnly = false);
/// createSjLjEHPreparePass - This pass adapts exception handling code to use
/// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
///
FunctionPass *createSjLjEHPreparePass(const TargetMachine *TM);
/// createWasmEHPass - This pass adapts exception handling code to use
/// WebAssembly's exception handling scheme.
FunctionPass *createWasmEHPass();
/// LocalStackSlotAllocation - This pass assigns local frame indices to stack
/// slots relative to one another and allocates base registers to access them
/// when it is estimated by the target to be out of range of normal frame
/// pointer or stack pointer index addressing.
extern char &LocalStackSlotAllocationID;
/// This pass expands pseudo-instructions, reserves registers and adjusts
/// machine frame information.
extern char &FinalizeISelID;
/// UnpackMachineBundles - This pass unpack machine instruction bundles.
extern char &UnpackMachineBundlesID;
FunctionPass *
createUnpackMachineBundles(std::function<bool(const MachineFunction &)> Ftor);
/// FinalizeMachineBundles - This pass finalize machine instruction
/// bundles (created earlier, e.g. during pre-RA scheduling).
extern char &FinalizeMachineBundlesID;
/// StackMapLiveness - This pass analyses the register live-out set of
/// stackmap/patchpoint intrinsics and attaches the calculated information to
/// the intrinsic for later emission to the StackMap.
extern char &StackMapLivenessID;
/// LiveDebugValues pass
extern char &LiveDebugValuesID;
/// createJumpInstrTables - This pass creates jump-instruction tables.
ModulePass *createJumpInstrTablesPass();
/// createForwardControlFlowIntegrityPass - This pass adds control-flow
/// integrity.
ModulePass *createForwardControlFlowIntegrityPass();
/// InterleavedAccess Pass - This pass identifies and matches interleaved
/// memory accesses to target specific intrinsics.
///
FunctionPass *createInterleavedAccessPass();
/// InterleavedLoadCombines Pass - This pass identifies interleaved loads and
/// combines them into wide loads detectable by InterleavedAccessPass
///
FunctionPass *createInterleavedLoadCombinePass();
/// LowerEmuTLS - This pass generates __emutls_[vt].xyz variables for all
/// TLS variables for the emulated TLS model.
///
ModulePass *createLowerEmuTLSPass();
/// This pass lowers the \@llvm.load.relative and \@llvm.objc.* intrinsics to
/// instructions. This is unsafe to do earlier because a pass may combine the
/// constant initializer into the load, which may result in an overflowing
/// evaluation.
ModulePass *createPreISelIntrinsicLoweringPass();
/// GlobalMerge - This pass merges internal (by default) globals into structs
/// to enable reuse of a base pointer by indexed addressing modes.
/// It can also be configured to focus on size optimizations only.
///
Pass *createGlobalMergePass(const TargetMachine *TM, unsigned MaximalOffset,
bool OnlyOptimizeForSize = false,
bool MergeExternalByDefault = false);
/// This pass splits the stack into a safe stack and an unsafe stack to
/// protect against stack-based overflow vulnerabilities.
FunctionPass *createSafeStackPass();
/// This pass detects subregister lanes in a virtual register that are used
/// independently of other lanes and splits them into separate virtual
/// registers.
extern char &RenameIndependentSubregsID;
/// This pass is executed POST-RA to collect which physical registers are
/// preserved by given machine function.
FunctionPass *createRegUsageInfoCollector();
/// Return a MachineFunction pass that identifies call sites
/// and propagates register usage information of callee to caller
/// if available with PysicalRegisterUsageInfo pass.
FunctionPass *createRegUsageInfoPropPass();
/// This pass performs software pipelining on machine instructions.
extern char &MachinePipelinerID;
/// This pass frees the memory occupied by the MachineFunction.
FunctionPass *createFreeMachineFunctionPass();
/// This pass performs outlining on machine instructions directly before
/// printing assembly.
ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions = true);
/// This pass expands the experimental reduction intrinsics into sequences of
/// shuffles.
FunctionPass *createExpandReductionsPass();
// This pass expands memcmp() to load/stores.
FunctionPass *createExpandMemCmpPass();
/// Creates Break False Dependencies pass. \see BreakFalseDeps.cpp
FunctionPass *createBreakFalseDeps();
// This pass expands indirectbr instructions.
FunctionPass *createIndirectBrExpandPass();
/// Creates CFI Instruction Inserter pass. \see CFIInstrInserter.cpp
FunctionPass *createCFIInstrInserter();
/// Creates CFGuard longjmp target identification pass.
/// \see CFGuardLongjmp.cpp
FunctionPass *createCFGuardLongjmpPass();
/// Create Hardware Loop pass. \see HardwareLoops.cpp
FunctionPass *createHardwareLoopsPass();
/// Create IR Type Promotion pass. \see TypePromotion.cpp
FunctionPass *createTypePromotionPass();
/// Creates MIR Debugify pass. \see MachineDebugify.cpp
ModulePass *createDebugifyMachineModulePass();
/// Creates MIR Strip Debug pass. \see MachineStripDebug.cpp
/// If OnlyDebugified is true then it will only strip debug info if it was
/// added by a Debugify pass. The module will be left unchanged if the debug
/// info was generated by another source such as clang.
ModulePass *createStripDebugMachineModulePass(bool OnlyDebugified);
/// The pass fixups statepoint machine instruction to replace usage of
/// caller saved registers with stack slots.
extern char &FixupStatepointCallerSavedID;
} // End llvm namespace
#endif
| 5,149 |
1,338 |
/*
* Copyright 2007-2010 Haiku, Inc. All rights reserved.
* Distributed under the terms of the MIT license.
*
* Authors:
* <NAME>
*/
#include "accelerant.h"
#include <errno.h>
#include <string.h>
#include <unistd.h>
AccelerantInfo gInfo; // global data used by various source files of
// accelerant.
static status_t
InitCommon(int fileDesc)
{
// Initialization function used by primary and cloned accelerants.
gInfo.deviceFileDesc = fileDesc;
// Get area ID of shared data from driver.
area_id sharedArea;
status_t result = ioctl(gInfo.deviceFileDesc, TDFX_GET_SHARED_DATA,
&sharedArea, sizeof(sharedArea));
if (result != B_OK)
return result;
gInfo.sharedInfoArea = clone_area("3DFX shared info",
(void**)&(gInfo.sharedInfo), B_ANY_ADDRESS, B_READ_AREA | B_WRITE_AREA,
sharedArea);
if (gInfo.sharedInfoArea < 0)
return gInfo.sharedInfoArea; // sharedInfoArea has error code
gInfo.regsArea = clone_area("3DFX regs area", (void**)&(gInfo.regs),
B_ANY_ADDRESS, B_READ_AREA | B_WRITE_AREA, gInfo.sharedInfo->regsArea);
if (gInfo.regsArea < 0) {
delete_area(gInfo.sharedInfoArea);
return gInfo.regsArea; // regsArea has error code
}
return B_OK;
}
static void
UninitCommon(void)
{
// This function is used by both primary and cloned accelerants.
delete_area(gInfo.regsArea);
gInfo.regs = 0;
delete_area(gInfo.sharedInfoArea);
gInfo.sharedInfo = 0;
}
status_t
InitAccelerant(int fileDesc)
{
// Initialize the accelerant. fileDesc is the file handle of the device
// (in /dev/graphics) that has been opened by the app_server.
TRACE("Enter InitAccelerant()\n");
gInfo.bAccelerantIsClone = false; // indicate this is primary accelerant
status_t result = InitCommon(fileDesc);
if (result == B_OK) {
SharedInfo& si = *gInfo.sharedInfo;
TRACE("Vendor ID: 0x%X, Device ID: 0x%X\n", si.vendorID, si.deviceID);
// Ensure that InitAccelerant is executed just once (copies should be clones)
if (si.bAccelerantInUse) {
result = B_NOT_ALLOWED;
} else {
result = TDFX_Init(); // perform init related to current chip
if (result == B_OK) {
result = si.engineLock.Init("3DFX engine lock");
if (result == B_OK)
result = si.overlayLock.Init("3DFX overlay lock");
if (result == B_OK) {
TDFX_ShowCursor(false);
// ensure that this function won't be executed again
// (copies should be clones)
si.bAccelerantInUse = true;
}
}
}
if (result != B_OK)
UninitCommon();
}
TRACE("Leave InitAccelerant(), result: 0x%X\n", result);
return result;
}
ssize_t
AccelerantCloneInfoSize(void)
{
// Return the number of bytes required to hold the information required
// to clone the device. The information is merely the name of the device;
// thus, return the size of the name buffer.
return B_OS_NAME_LENGTH;
}
void
GetAccelerantCloneInfo(void* data)
{
// Return the info required to clone the device. Argument data points to
// a buffer which is the size returned by AccelerantCloneInfoSize().
ioctl(gInfo.deviceFileDesc, TDFX_DEVICE_NAME, data, B_OS_NAME_LENGTH);
}
status_t
CloneAccelerant(void* data)
{
// Initialize a copy of the accelerant as a clone. Argument data points to
// a copy of the data which was returned by GetAccelerantCloneInfo().
TRACE("Enter CloneAccelerant()\n");
char path[MAXPATHLEN] = "/dev/";
strcat(path, (const char*)data);
gInfo.deviceFileDesc = open(path, B_READ_WRITE); // open the device
if (gInfo.deviceFileDesc < 0)
return errno;
gInfo.bAccelerantIsClone = true;
status_t result = InitCommon(gInfo.deviceFileDesc);
if (result != B_OK) {
close(gInfo.deviceFileDesc);
return result;
}
result = gInfo.modeListArea = clone_area("3DFX cloned display_modes",
(void**) &gInfo.modeList, B_ANY_ADDRESS, B_READ_AREA,
gInfo.sharedInfo->modeArea);
if (result < 0) {
UninitCommon();
close(gInfo.deviceFileDesc);
return result;
}
TRACE("Leave CloneAccelerant()\n");
return B_OK;
}
void
UninitAccelerant(void)
{
delete_area(gInfo.modeListArea);
gInfo.modeList = NULL;
UninitCommon();
if (gInfo.bAccelerantIsClone)
close(gInfo.deviceFileDesc);
}
status_t
GetAccelerantDeviceInfo(accelerant_device_info* adi)
{
// Get info about the device.
SharedInfo& si = *gInfo.sharedInfo;
adi->version = 1;
strcpy(adi->name, "3dfx chipset");
strcpy(adi->chipset, si.chipName);
strcpy(adi->serial_no, "unknown");
adi->memory = si.maxFrameBufferSize;
adi->dac_speed = 270;
return B_OK;
}
| 1,711 |
335 |
{
"word": "Tell",
"definitions": [
"Communicate information to someone in spoken or written words.",
"Order or advise someone to do something.",
"Relate (a story)",
"Reveal (information) to someone in a non-verbal way.",
"Divulge confidential or private information.",
"Inform someone of the misdemeanours of.",
"Decide or determine correctly or with certainty.",
"Perceive (the difference between one person or thing and another)",
"(of an experience or period of time) have a noticeable, typically harmful, effect on someone.",
"(of a particular factor) play a part in the success or otherwise of someone or something.",
"Count (the members of a group)"
],
"parts-of-speech": "Verb"
}
| 266 |
1,695 |
/*
* 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.trino.plugin.prometheus;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.ByteSource;
import com.google.common.io.CountingInputStream;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.trino.spi.TrinoException;
import io.trino.spi.block.Block;
import io.trino.spi.block.BlockBuilder;
import io.trino.spi.connector.RecordCursor;
import io.trino.spi.type.ArrayType;
import io.trino.spi.type.MapType;
import io.trino.spi.type.Type;
import io.trino.spi.type.TypeUtils;
import io.trino.spi.type.VarcharType;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Instant;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static io.trino.plugin.prometheus.PrometheusClient.TIMESTAMP_COLUMN_TYPE;
import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.BooleanType.BOOLEAN;
import static io.trino.spi.type.DateTimeEncoding.packDateTimeWithZone;
import static io.trino.spi.type.DoubleType.DOUBLE;
import static io.trino.spi.type.IntegerType.INTEGER;
import static io.trino.spi.type.SmallintType.SMALLINT;
import static io.trino.spi.type.TinyintType.TINYINT;
import static io.trino.spi.type.VarcharType.createUnboundedVarcharType;
import static java.util.Objects.requireNonNull;
public class PrometheusRecordCursor
implements RecordCursor
{
private final List<PrometheusColumnHandle> columnHandles;
private final int[] fieldToColumnIndex;
private final Iterator<PrometheusStandardizedRow> metricsItr;
private final long totalBytes;
private PrometheusStandardizedRow fields;
public PrometheusRecordCursor(List<PrometheusColumnHandle> columnHandles, ByteSource byteSource)
{
this.columnHandles = columnHandles;
fieldToColumnIndex = new int[columnHandles.size()];
for (int i = 0; i < columnHandles.size(); i++) {
PrometheusColumnHandle columnHandle = columnHandles.get(i);
fieldToColumnIndex[i] = columnHandle.getOrdinalPosition();
}
try (CountingInputStream input = new CountingInputStream(byteSource.openStream())) {
metricsItr = prometheusResultsInStandardizedForm(new PrometheusQueryResponseParse(input).getResults()).iterator();
totalBytes = input.getCount();
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public long getCompletedBytes()
{
return totalBytes;
}
@Override
public long getReadTimeNanos()
{
return 0;
}
@Override
public Type getType(int field)
{
checkArgument(field < columnHandles.size(), "Invalid field index");
return columnHandles.get(field).getColumnType();
}
@Override
public boolean advanceNextPosition()
{
if (!metricsItr.hasNext()) {
return false;
}
fields = metricsItr.next();
return true;
}
private Object getFieldValue(int field)
{
checkState(fields != null, "Cursor has not been advanced yet");
int columnIndex = fieldToColumnIndex[field];
switch (columnIndex) {
case 0:
return fields.getLabels();
case 1:
return fields.getTimestamp();
case 2:
return fields.getValue();
}
return null;
}
@Override
public boolean getBoolean(int field)
{
return true;
}
@Override
public long getLong(int field)
{
Type type = getType(field);
if (type.equals(TIMESTAMP_COLUMN_TYPE)) {
Instant dateTime = (Instant) requireNonNull(getFieldValue(field));
// render with the fixed offset of the Trino server
int offsetMinutes = dateTime.atZone(ZoneId.systemDefault()).getOffset().getTotalSeconds() / 60;
return packDateTimeWithZone(dateTime.toEpochMilli(), offsetMinutes);
}
else {
throw new TrinoException(NOT_SUPPORTED, "Unsupported type " + getType(field));
}
}
@Override
public double getDouble(int field)
{
checkFieldType(field, DOUBLE);
return (double) requireNonNull(getFieldValue(field));
}
@Override
public Slice getSlice(int field)
{
checkFieldType(field, createUnboundedVarcharType());
return Slices.utf8Slice((String) requireNonNull(getFieldValue(field)));
}
@Override
public Object getObject(int field)
{
return getFieldValue(field);
}
@Override
public boolean isNull(int field)
{
checkArgument(field < columnHandles.size(), "Invalid field index");
return getFieldValue(field) == null;
}
private void checkFieldType(int field, Type expected)
{
Type actual = getType(field);
checkArgument(actual.equals(expected), "Expected field %s to be type %s but is %s", field, expected, actual);
}
private List<PrometheusStandardizedRow> prometheusResultsInStandardizedForm(List<PrometheusMetricResult> results)
{
return results.stream().map(result ->
result.getTimeSeriesValues().getValues().stream().map(prometheusTimeSeriesValue -> new PrometheusStandardizedRow(
getBlockFromMap(columnHandles.get(0).getColumnType(), ImmutableMap.copyOf(result.getMetricHeader())),
prometheusTimeSeriesValue.getTimestamp(),
Double.parseDouble(prometheusTimeSeriesValue.getValue())))
.collect(Collectors.toList()))
.flatMap(List::stream)
.collect(Collectors.toList());
}
static Block getBlockFromMap(Type mapType, Map<?, ?> map)
{
// on functions like COUNT() the Type won't be a MapType
if (!(mapType instanceof MapType)) {
return null;
}
Type keyType = mapType.getTypeParameters().get(0);
Type valueType = mapType.getTypeParameters().get(1);
BlockBuilder mapBlockBuilder = mapType.createBlockBuilder(null, 1);
BlockBuilder builder = mapBlockBuilder.beginBlockEntry();
for (Map.Entry<?, ?> entry : map.entrySet()) {
writeObject(builder, keyType, entry.getKey());
writeObject(builder, valueType, entry.getValue());
}
mapBlockBuilder.closeEntry();
return (Block) mapType.getObject(mapBlockBuilder, 0);
}
static Map<Object, Object> getMapFromBlock(Type type, Block block)
{
MapType mapType = (MapType) type;
Type keyType = mapType.getKeyType();
Type valueType = mapType.getValueType();
Map<Object, Object> map = new HashMap<>(block.getPositionCount() / 2);
for (int i = 0; i < block.getPositionCount(); i += 2) {
map.put(readObject(keyType, block, i), readObject(valueType, block, i + 1));
}
return map;
}
private static void writeObject(BlockBuilder builder, Type type, Object obj)
{
if (type instanceof ArrayType) {
Type elementType = ((ArrayType) type).getElementType();
BlockBuilder arrayBuilder = builder.beginBlockEntry();
for (Object item : (List<?>) obj) {
writeObject(arrayBuilder, elementType, item);
}
builder.closeEntry();
}
else if (type instanceof MapType) {
MapType mapType = (MapType) type;
BlockBuilder mapBlockBuilder = builder.beginBlockEntry();
for (Map.Entry<?, ?> entry : ((Map<?, ?>) obj).entrySet()) {
writeObject(mapBlockBuilder, mapType.getKeyType(), entry.getKey());
writeObject(mapBlockBuilder, mapType.getValueType(), entry.getValue());
}
builder.closeEntry();
}
else {
if (BOOLEAN.equals(type)
|| TINYINT.equals(type)
|| SMALLINT.equals(type)
|| INTEGER.equals(type)
|| BIGINT.equals(type)
|| DOUBLE.equals(type)
|| type instanceof VarcharType) {
TypeUtils.writeNativeValue(type, builder, obj);
}
}
}
private static Object readObject(Type type, Block block, int position)
{
if (type instanceof ArrayType) {
Type elementType = ((ArrayType) type).getElementType();
return getArrayFromBlock(elementType, block.getObject(position, Block.class));
}
else if (type instanceof MapType) {
return getMapFromBlock(type, block.getObject(position, Block.class));
}
else {
if (type.getJavaType() == Slice.class) {
Slice slice = (Slice) requireNonNull(TypeUtils.readNativeValue(type, block, position));
return (type instanceof VarcharType) ? slice.toStringUtf8() : slice.getBytes();
}
return TypeUtils.readNativeValue(type, block, position);
}
}
private static List<Object> getArrayFromBlock(Type elementType, Block block)
{
ImmutableList.Builder<Object> arrayBuilder = ImmutableList.builder();
for (int i = 0; i < block.getPositionCount(); ++i) {
arrayBuilder.add(readObject(elementType, block, i));
}
return arrayBuilder.build();
}
@Override
public void close() {}
}
| 4,226 |
1,575 |
<reponame>senliontec/mujoco
// Copyright 2021 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef MUJOCO_SRC_ENGINE_ENGINE_SOLVER_H_
#define MUJOCO_SRC_ENGINE_ENGINE_SOLVER_H_
#include <mujoco/mjdata.h>
#include <mujoco/mjmodel.h>
// PGS solver
void mj_solPGS(const mjModel* m, mjData* d, int maxiter);
// No Slip solver (modified PGS)
void mj_solNoSlip(const mjModel* m, mjData* d, int maxiter);
// CG solver
void mj_solCG(const mjModel* m, mjData* d, int maxiter);
// Newton solver
void mj_solNewton(const mjModel* m, mjData* d, int maxiter);
#endif // MUJOCO_SRC_ENGINE_ENGINE_SOLVER_H_
| 403 |
354 |
from typing import Literal
class Foo:
@property
def foo() -> Literal["hi"]:
"hi"
return "hi"
| 54 |
667 |
#import <UIKit/UIKit.h>
#import "LoginViewController.h"
#import "HomeViewController.h"
#import "ErrorViewController.h"
#import "AFHTTPRequestOperation.h"
#import "JASidePanelController.h"
#import "NarrowOperators.h"
@interface ZulipAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate>
@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) UITabBarController *tabBarController;
@property (nonatomic, retain) UINavigationController *navController;
@property (nonatomic, retain) JASidePanelController *sidePanelController;
@property (nonatomic, retain) LoginViewController *loginViewController;
@property (nonatomic, retain) HomeViewController *homeViewController;
@property (nonatomic, retain) ErrorViewController *errorViewController;
// Push notifications
@property (nonatomic, assign) BOOL wakingFromBackground;
// List of NSNumber * Message IDs that were included in the push notification update
@property (nonatomic, retain) NSArray *notifiedWithMessages;
// Core Data bits
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void) showErrorScreen:(NSString *)errorMessage;
- (void) dismissErrorScreen;
- (void) dismissLoginScreen;
- (void) showAboutScreen;
// Narrowing
- (void) narrowWithOperators:(NarrowOperators *)narrow;
- (void) narrowWithOperators:(NarrowOperators *)narrow thenDisplayId:(long)messageId;
- (BOOL) isNarrowed;
- (NarrowOperators *)currentNarrow;
- (void) clearNarrowWithAnimation:(BOOL)animation;
- (void) reloadCoreData;
@end
| 506 |
640 |
<filename>client/tp_assist_win/msocketx.cpp
#include "stdafx.h"
#include "msocketx.h"
#ifdef _WIN32
#pragma warning(disable:4244)
#endif
msocketx::msocketx()
{
m_sock = INVALID_SOCKET;
}
msocketx::~msocketx()
{
close();
}
int msocketx::getsockname(unsigned int& uiip, unsigned short& usport)
{
sockaddr_in addr;
socklen_t ilen = sizeof(addr);
int nret = ::getsockname(m_sock, (sockaddr*)&addr, &ilen);
if (nret != SOCKET_ERROR)
{
uiip = addr.sin_addr.s_addr;
usport = ntohs(addr.sin_port);
}
return nret;
}
int msocketx::shutdown(int ihow)
{
return ::shutdown(m_sock, ihow);
}
int msocketx::closesocket()
{
#ifdef _WIN32
return ::closesocket(m_sock);
#else
return ::close(m_sock);
#endif
}
void msocketx::close()
{
if (isvalid())
{
shutdown(0);
closesocket();
m_sock = INVALID_SOCKET;
}
}
bool msocketx::startup()
{
#ifdef _WIN32
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
return false;
#endif
return true;
}
bool msocketx::clearup()
{
#ifdef _WIN32
return WSACleanup() == 0;
#endif
return true;
}
int msocketx::getlasterror()
{
#ifdef _WIN32
return WSAGetLastError();
#else
return errno;
#endif
}
void msocketx::attach(SOCKET sock)
{
if (sock == INVALID_SOCKET)
return;
m_sock = sock;
}
bool msocketx::isvalid()
{
return m_sock != INVALID_SOCKET;
}
bool msocketx::setsockbuff(unsigned int uirecvlen /* = 4 * 1024 * 1024 */,
unsigned int uisendlen /* = 4 * 1024 * 1024 */)
{
return (setsockopt(m_sock, SOL_SOCKET, SO_SNDBUF, (char*)&uisendlen, sizeof(uisendlen)) == 0) &&
(setsockopt(m_sock, SOL_SOCKET, SO_RCVBUF, (char*)&uirecvlen, sizeof(uirecvlen)) == 0);
}
bool msocketx::setsocknagle(bool benable /* = true */)
{
socklen_t iflag = (benable ? 0 : 1);
return setsockopt(m_sock, IPPROTO_TCP, TCP_NODELAY, (char*)&iflag, sizeof(iflag)) == 0;
}
bool msocketx::setsocktime(unsigned int uimillisecond /* = 500 */)
{
#ifdef _WIN32
return (setsockopt(m_sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&uimillisecond, sizeof(uimillisecond)) == 0) &&
(setsockopt(m_sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&uimillisecond, sizeof(uimillisecond)) == 0);
#else
struct timeval timeout;
timeout.tv_sec = uimillisecond / 1000;
timeout.tv_usec = (uimillisecond % 1000) * 1000;
return (setsockopt(m_sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout)) == 0) &&
(setsockopt(m_sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)) == 0);
#endif
}
bool msocketx::setsock()
{
return setsockbuff() && setsocktime();
}
bool msocketx::setblock(bool bblock /* = false */)
{
#ifdef _WIN32
u_long b = bblock ? 0 : 1;
return ioctlsocket(m_sock, FIONBIO, &b) == 0;
#else
int flags = fcntl(m_sock, F_GETFL, 0);
if (bblock)
flags |= O_NONBLOCK;
else
flags &= (~O_NONBLOCK);
return fcntl(m_sock, F_SETFL, flags) != -1;
#endif
}
bool msocketx::create(int itype, int iprotocol)
{
if (isvalid())
return true;
m_sock = socket(AF_INET, itype, iprotocol);
return isvalid();
}
bool msocketx::bind(unsigned short usport, const char* pstrip /* = NULL */)
{
sockaddr_in addr = { 0 };
unsigned long nResult = 0;
addr.sin_family = AF_INET;
if (pstrip == NULL)
addr.sin_addr.s_addr = htonl(INADDR_ANY);
else
{
nResult = inet_addr(pstrip);
if (nResult == INADDR_NONE)
return false;
addr.sin_addr.s_addr = nResult;
}
addr.sin_port = htons(usport);
return ::bind(m_sock, (sockaddr*)&addr, sizeof(addr)) == 0;
}
int msocketx::sendto(const void* pbuf, unsigned int ilen, unsigned int uiip, unsigned short usport, int iflags)
{
if (pbuf == NULL)
return -1;
sockaddr_in addr = { 0 };
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = uiip;
addr.sin_port = htons(usport);
return ::sendto(m_sock, (char*)pbuf, ilen, iflags, (sockaddr*)&addr, sizeof(addr));
}
int msocketx::sendto(const void* pbuf, unsigned int ilen, const char* pszip, unsigned short usport, int iflags)
{
if (pbuf == NULL)
return -1;
return sendto(pbuf, ilen, inet_addr(pszip), usport, iflags);
}
int msocketx::recvfrom(void* pbuf, unsigned int ilen, unsigned int& uiip, unsigned short& usport, int iflags)
{
if (pbuf == NULL)
return -1;
sockaddr_in srcaddr = { 0 };
socklen_t iaddrlen = sizeof(srcaddr);
int nret = ::recvfrom(m_sock, (char*)pbuf, ilen, iflags, (sockaddr*)&srcaddr, &iaddrlen);
if (nret != SOCKET_ERROR)
{
usport = htons(srcaddr.sin_port);
uiip = srcaddr.sin_addr.s_addr;
}
return nret;
}
int msocketx::send(const void* pbuf, unsigned int ilen, int iflags)
{
if (pbuf == NULL)
return -1;
return ::send(m_sock, (char*)pbuf, ilen, iflags);
}
int msocketx::recv(void* pbuf, unsigned int ilen, int iflags)
{
if (pbuf == NULL)
return -1;
return ::recv(m_sock, (char*)pbuf, ilen, iflags);
}
bool msocketx::listen(int ibacklog)
{
return ::listen(m_sock, ibacklog) == 0;
}
bool msocketx::accept(SOCKET& sock, sockaddr* peeraddr, socklen_t* addrlen)
{
sock = ::accept(m_sock, peeraddr, addrlen);
return sock != INVALID_SOCKET;
}
bool msocketx::accept(msocketx& sock, sockaddr* peeraddr, socklen_t* addrlen)
{
SOCKET socktmp = ::accept(m_sock, peeraddr, addrlen);
sock.m_sock = socktmp;
return socktmp != INVALID_SOCKET;
}
int msocketx::connect(const char* pszip, unsigned short usport, bool bblock)
{
if (pszip == NULL)
return -1;
if (!isvalid())
{
if (!create(SOCK_STREAM, 0))
return -1;
}
setblock(bblock);
sockaddr_in addr = { 0 };
addr.sin_port = htons(usport);
addr.sin_addr.s_addr = inet_addr(pszip);
addr.sin_family = AF_INET;
return ::connect(m_sock, (sockaddr*)&addr, sizeof(addr));
}
int msocketx::wait(unsigned int uimilli, int iflagx)
{
timeval timeout;
timeout.tv_sec = uimilli / 1000;
timeout.tv_usec = (uimilli % 1000) * 1000;
fd_set *prfds = NULL, *pwfds = NULL, *pefds = NULL;
int iret = 0;
if ((iflagx & CAN_CONNECTX) == CAN_CONNECTX)
{
pwfds = new(std::nothrow) fd_set;
if (pwfds == NULL)
return -1;
pefds = new(std::nothrow) fd_set;
if (pefds == NULL)
{
if (pwfds)
delete pwfds;
return -1;
}
FD_ZERO(pwfds);
FD_ZERO(pefds);
FD_SET(m_sock, pwfds);
FD_SET(m_sock, pefds);
iret = ::select(m_sock + 1, NULL, pwfds, pefds, &timeout);
if (iret > 0)
{
if (FD_ISSET(m_sock, pwfds) || FD_ISSET(m_sock, pefds))
{
int iopt = 0;
socklen_t ioptlen = sizeof(iopt);
if (getsockopt(m_sock, SOL_SOCKET, SO_ERROR, (char*)&iopt, &ioptlen) == 0)
{
if (iopt == 0)
iret = CAN_CONNECTX;
else
iret = SOCKET_ERROR;
}
else
iret = SOCKET_ERROR;
}
}
if (pwfds)
delete pwfds;
if (pefds)
delete pefds;
return iret;
}
if ((iflagx & CAN_READX) == CAN_READX || (iflagx & CAN_ACCEPTX) == CAN_ACCEPTX)
{
prfds = new(std::nothrow) fd_set;
if (prfds == NULL)
return -1;
FD_ZERO(prfds);
FD_SET(m_sock, prfds);
}
if ((iflagx & CAN_WRITEX) == CAN_WRITEX)
{
pwfds = new(std::nothrow) fd_set;
if (pwfds == NULL)
{
if (prfds)
delete prfds;
return -1;
}
FD_ZERO(pwfds);
FD_SET(m_sock, pwfds);
}
iret = ::select(m_sock + 1, prfds, pwfds, NULL, &timeout);
if (iret > 0)
{
int itmp = 0;
if (prfds)
if (FD_ISSET(m_sock, prfds))
itmp |= CAN_READX;
if (pwfds)
if (FD_ISSET(m_sock, pwfds))
itmp |= CAN_WRITEX;
iret = itmp;
}
if (pwfds)
delete pwfds;
if (prfds)
delete prfds;
return iret;
}
| 3,469 |
9,136 |
"""Base class for simulation client."""
import enum
from typing import Text
GRAY = (0.3, 0.3, 0.3, 1)
class ClientType(enum.Enum):
"""Type of client."""
BULLET = "pybullet"
class ClientMode(enum.Enum):
"""Client running mode."""
# Client is being initialized, object is being loaded, teleported, etc.
CONFIGURATION = 1
# Client is in a mode that simulate motion according to physics and control.
SIMULATION = 2
class WrongClientModeError(Exception):
"""Client mode does not meet expectation (e.g. load object in sim mode)."""
class BaseClient(object):
"""Base class for simulation client."""
def __init__(self, client_type: Text = ""):
self._client_type = client_type
# Default to configuration mode.
self._client_mode = ClientMode.CONFIGURATION
@property
def client_type(self) -> ClientType:
return self._client_type
def switch_mode(self, mode: ClientMode) -> bool:
"""Switches running mode of simulation client and return if mode changed."""
if mode not in (ClientMode.CONFIGURATION, ClientMode.SIMULATION):
raise ValueError(f"Invalid client mode {mode}.")
if mode == self._client_mode:
return False
self._client_mode = mode
return True
@property
def client_mode(self) -> ClientMode:
"""Returns current client mode."""
return self._client_mode
def _assert_in_configuration_mode(self, operation: Text = "this operation"):
"""Raises exception if client is not in configuration mode."""
if self._client_mode != ClientMode.CONFIGURATION:
raise WrongClientModeError(
f"Sim client is expected to be in configuration mode for "
f"{operation}.")
| 539 |
1,202 |
<filename>test/pkgs_signed/Signed Package/pkg.json
{"license":"","file_hash":null,"name":"Package","version":"1.0.0","description":"original package","group":"","keywords":null,"dependencies":[],"contents":"","engine_version":"2.1.0.7840","engine":"dynamo","engine_metadata":"","site_url":"","repository_url":"","contains_binaries":true,"node_libraries":["SignedPackage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"]}
| 129 |
777 |
<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.
#include "ui/events/latency_info.h"
#include <stddef.h>
#include <algorithm>
#include <string>
#include <utility>
#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/macros.h"
#include "base/strings/stringprintf.h"
#include "base/trace_event/trace_event.h"
namespace {
const size_t kMaxLatencyInfoNumber = 100;
const char* GetComponentName(ui::LatencyComponentType type) {
#define CASE_TYPE(t) case ui::t: return #t
switch (type) {
CASE_TYPE(INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT);
CASE_TYPE(LATENCY_BEGIN_SCROLL_LISTENER_UPDATE_MAIN_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_FIRST_SCROLL_UPDATE_ORIGINAL_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_UI_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_MAIN_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_IMPL_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_FORWARD_SCROLL_UPDATE_TO_MAIN_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_ACK_RWH_COMPONENT);
CASE_TYPE(WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT);
CASE_TYPE(TAB_SHOW_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_RENDERER_MAIN_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT);
CASE_TYPE(INPUT_EVENT_BROWSER_RECEIVED_RENDERER_SWAP_COMPONENT);
CASE_TYPE(INPUT_EVENT_GPU_SWAP_BUFFER_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_GENERATE_SCROLL_UPDATE_FROM_MOUSE_WHEEL);
CASE_TYPE(INPUT_EVENT_LATENCY_TERMINATED_MOUSE_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_TERMINATED_MOUSE_WHEEL_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_TERMINATED_KEYBOARD_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_TERMINATED_TOUCH_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_TERMINATED_GESTURE_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_TERMINATED_COMMIT_FAILED_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_TERMINATED_COMMIT_NO_UPDATE_COMPONENT);
CASE_TYPE(INPUT_EVENT_LATENCY_TERMINATED_SWAP_FAILED_COMPONENT);
default:
DLOG(WARNING) << "Unhandled LatencyComponentType.\n";
break;
}
#undef CASE_TYPE
return "unknown";
}
bool IsTerminalComponent(ui::LatencyComponentType type) {
switch (type) {
case ui::INPUT_EVENT_LATENCY_TERMINATED_MOUSE_COMPONENT:
case ui::INPUT_EVENT_LATENCY_TERMINATED_MOUSE_WHEEL_COMPONENT:
case ui::INPUT_EVENT_LATENCY_TERMINATED_KEYBOARD_COMPONENT:
case ui::INPUT_EVENT_LATENCY_TERMINATED_TOUCH_COMPONENT:
case ui::INPUT_EVENT_LATENCY_TERMINATED_GESTURE_COMPONENT:
case ui::INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT:
case ui::INPUT_EVENT_LATENCY_TERMINATED_COMMIT_FAILED_COMPONENT:
case ui::INPUT_EVENT_LATENCY_TERMINATED_COMMIT_NO_UPDATE_COMPONENT:
case ui::INPUT_EVENT_LATENCY_TERMINATED_SWAP_FAILED_COMPONENT:
return true;
default:
return false;
}
}
bool IsBeginComponent(ui::LatencyComponentType type) {
return (type == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
type == ui::LATENCY_BEGIN_SCROLL_LISTENER_UPDATE_MAIN_COMPONENT);
}
bool IsInputLatencyBeginComponent(ui::LatencyComponentType type) {
return type == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT;
}
// This class is for converting latency info to trace buffer friendly format.
class LatencyInfoTracedValue
: public base::trace_event::ConvertableToTraceFormat {
public:
static std::unique_ptr<ConvertableToTraceFormat> FromValue(
std::unique_ptr<base::Value> value);
void AppendAsTraceFormat(std::string* out) const override;
private:
explicit LatencyInfoTracedValue(base::Value* value);
~LatencyInfoTracedValue() override;
std::unique_ptr<base::Value> value_;
DISALLOW_COPY_AND_ASSIGN(LatencyInfoTracedValue);
};
std::unique_ptr<base::trace_event::ConvertableToTraceFormat>
LatencyInfoTracedValue::FromValue(std::unique_ptr<base::Value> value) {
return std::unique_ptr<base::trace_event::ConvertableToTraceFormat>(
new LatencyInfoTracedValue(value.release()));
}
LatencyInfoTracedValue::~LatencyInfoTracedValue() {
}
void LatencyInfoTracedValue::AppendAsTraceFormat(std::string* out) const {
std::string tmp;
base::JSONWriter::Write(*value_, &tmp);
*out += tmp;
}
LatencyInfoTracedValue::LatencyInfoTracedValue(base::Value* value)
: value_(value) {
}
const char kTraceCategoriesForAsyncEvents[] = "benchmark,latencyInfo,rail";
struct LatencyInfoEnabledInitializer {
LatencyInfoEnabledInitializer() :
latency_info_enabled(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
kTraceCategoriesForAsyncEvents)) {
}
const unsigned char* latency_info_enabled;
};
static base::LazyInstance<LatencyInfoEnabledInitializer>::Leaky
g_latency_info_enabled = LAZY_INSTANCE_INITIALIZER;
} // namespace
namespace ui {
LatencyInfo::LatencyInfo() : LatencyInfo(SourceEventType::UNKNOWN) {}
LatencyInfo::LatencyInfo(SourceEventType type)
: input_coordinates_size_(0),
trace_id_(-1),
coalesced_(false),
terminated_(false),
source_event_type_(type) {}
LatencyInfo::LatencyInfo(const LatencyInfo& other) = default;
LatencyInfo::~LatencyInfo() {}
LatencyInfo::LatencyInfo(int64_t trace_id, bool terminated)
: input_coordinates_size_(0),
trace_id_(trace_id),
terminated_(terminated),
source_event_type_(SourceEventType::UNKNOWN) {}
bool LatencyInfo::Verify(const std::vector<LatencyInfo>& latency_info,
const char* referring_msg) {
if (latency_info.size() > kMaxLatencyInfoNumber) {
LOG(ERROR) << referring_msg << ", LatencyInfo vector size "
<< latency_info.size() << " is too big.";
TRACE_EVENT_INSTANT1("input,benchmark", "LatencyInfo::Verify Fails",
TRACE_EVENT_SCOPE_GLOBAL,
"size", latency_info.size());
return false;
}
return true;
}
void LatencyInfo::CopyLatencyFrom(const LatencyInfo& other,
LatencyComponentType type) {
for (const auto& lc : other.latency_components()) {
if (lc.first.first == type) {
AddLatencyNumberWithTimestamp(lc.first.first,
lc.first.second,
lc.second.sequence_number,
lc.second.event_time,
lc.second.event_count);
}
}
}
void LatencyInfo::AddNewLatencyFrom(const LatencyInfo& other) {
for (const auto& lc : other.latency_components()) {
if (!FindLatency(lc.first.first, lc.first.second, NULL)) {
AddLatencyNumberWithTimestamp(lc.first.first,
lc.first.second,
lc.second.sequence_number,
lc.second.event_time,
lc.second.event_count);
}
}
}
void LatencyInfo::AddLatencyNumber(LatencyComponentType component,
int64_t id,
int64_t component_sequence_number) {
AddLatencyNumberWithTimestampImpl(component, id, component_sequence_number,
base::TimeTicks::Now(), 1, nullptr);
}
void LatencyInfo::AddLatencyNumberWithTraceName(
LatencyComponentType component,
int64_t id,
int64_t component_sequence_number,
const char* trace_name_str) {
AddLatencyNumberWithTimestampImpl(component, id, component_sequence_number,
base::TimeTicks::Now(), 1, trace_name_str);
}
void LatencyInfo::AddLatencyNumberWithTimestamp(
LatencyComponentType component,
int64_t id,
int64_t component_sequence_number,
base::TimeTicks time,
uint32_t event_count) {
AddLatencyNumberWithTimestampImpl(component, id, component_sequence_number,
time, event_count, nullptr);
}
void LatencyInfo::AddLatencyNumberWithTimestampImpl(
LatencyComponentType component,
int64_t id,
int64_t component_sequence_number,
base::TimeTicks time,
uint32_t event_count,
const char* trace_name_str) {
const unsigned char* latency_info_enabled =
g_latency_info_enabled.Get().latency_info_enabled;
if (IsBeginComponent(component)) {
// Should only ever add begin component once.
CHECK_EQ(-1, trace_id_);
trace_id_ = component_sequence_number;
if (*latency_info_enabled) {
// The timestamp for ASYNC_BEGIN trace event is used for drawing the
// beginning of the trace event in trace viewer. For better visualization,
// for an input event, we want to draw the beginning as when the event is
// originally created, e.g. the timestamp of its ORIGINAL/UI_COMPONENT,
// not when we actually issue the ASYNC_BEGIN trace event.
LatencyComponent begin_component;
base::TimeTicks ts;
if (FindLatency(INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
0,
&begin_component) ||
FindLatency(INPUT_EVENT_LATENCY_UI_COMPONENT,
0,
&begin_component)) {
ts = begin_component.event_time;
} else {
ts = base::TimeTicks::Now();
}
if (trace_name_str) {
if (IsInputLatencyBeginComponent(component))
trace_name_ = std::string("InputLatency::") + trace_name_str;
else
trace_name_ = std::string("Latency::") + trace_name_str;
}
TRACE_EVENT_COPY_ASYNC_BEGIN_WITH_TIMESTAMP0(
kTraceCategoriesForAsyncEvents,
trace_name_.c_str(),
TRACE_ID_DONT_MANGLE(trace_id_),
ts);
}
TRACE_EVENT_WITH_FLOW1("input,benchmark",
"LatencyInfo.Flow",
TRACE_ID_DONT_MANGLE(trace_id_),
TRACE_EVENT_FLAG_FLOW_OUT,
"trace_id", trace_id_);
}
LatencyMap::key_type key = std::make_pair(component, id);
LatencyMap::iterator it = latency_components_.find(key);
if (it == latency_components_.end()) {
LatencyComponent info = {component_sequence_number, time, event_count, time,
time};
latency_components_[key] = info;
} else {
it->second.sequence_number = std::max(component_sequence_number,
it->second.sequence_number);
uint32_t new_count = event_count + it->second.event_count;
if (event_count > 0 && new_count != 0) {
// Do a weighted average, so that the new event_time is the average of
// the times of events currently in this structure with the time passed
// into this method.
it->second.event_time += (time - it->second.event_time) * event_count /
new_count;
it->second.event_count = new_count;
it->second.last_event_time = std::max(it->second.last_event_time, time);
}
}
if (IsTerminalComponent(component) && trace_id_ != -1) {
// Should only ever add terminal component once.
CHECK(!terminated_);
terminated_ = true;
if (*latency_info_enabled) {
TRACE_EVENT_COPY_ASYNC_END2(kTraceCategoriesForAsyncEvents,
trace_name_.c_str(),
TRACE_ID_DONT_MANGLE(trace_id_),
"data", AsTraceableData(),
"coordinates", CoordinatesAsTraceableData());
}
TRACE_EVENT_WITH_FLOW0("input,benchmark",
"LatencyInfo.Flow",
TRACE_ID_DONT_MANGLE(trace_id_),
TRACE_EVENT_FLAG_FLOW_IN);
}
}
std::unique_ptr<base::trace_event::ConvertableToTraceFormat>
LatencyInfo::AsTraceableData() {
std::unique_ptr<base::DictionaryValue> record_data(
new base::DictionaryValue());
for (const auto& lc : latency_components_) {
std::unique_ptr<base::DictionaryValue> component_info(
new base::DictionaryValue());
component_info->SetDouble("comp_id", static_cast<double>(lc.first.second));
component_info->SetDouble(
"time",
static_cast<double>(lc.second.event_time.ToInternalValue()));
component_info->SetDouble("count", lc.second.event_count);
component_info->SetDouble("sequence_number",
lc.second.sequence_number);
record_data->Set(GetComponentName(lc.first.first),
std::move(component_info));
}
record_data->SetDouble("trace_id", static_cast<double>(trace_id_));
return LatencyInfoTracedValue::FromValue(std::move(record_data));
}
std::unique_ptr<base::trace_event::ConvertableToTraceFormat>
LatencyInfo::CoordinatesAsTraceableData() {
std::unique_ptr<base::ListValue> coordinates(new base::ListValue());
for (size_t i = 0; i < input_coordinates_size_; i++) {
std::unique_ptr<base::DictionaryValue> coordinate_pair(
new base::DictionaryValue());
coordinate_pair->SetDouble("x", input_coordinates_[i].x());
coordinate_pair->SetDouble("y", input_coordinates_[i].y());
coordinates->Append(std::move(coordinate_pair));
}
return LatencyInfoTracedValue::FromValue(std::move(coordinates));
}
bool LatencyInfo::FindLatency(LatencyComponentType type,
int64_t id,
LatencyComponent* output) const {
LatencyMap::const_iterator it = latency_components_.find(
std::make_pair(type, id));
if (it == latency_components_.end())
return false;
if (output)
*output = it->second;
return true;
}
void LatencyInfo::RemoveLatency(LatencyComponentType type) {
LatencyMap::iterator it = latency_components_.begin();
while (it != latency_components_.end()) {
if (it->first.first == type)
it = latency_components_.erase(it);
else
it++;
}
}
bool LatencyInfo::AddInputCoordinate(const gfx::PointF& input_coordinate) {
if (input_coordinates_size_ >= kMaxInputCoordinates)
return false;
input_coordinates_[input_coordinates_size_++] = input_coordinate;
return true;
}
} // namespace ui
| 6,346 |
583 |
<reponame>mrcl-tst/hyrise
#include "dp_ccp.hpp"
#include <unordered_map>
#include "cost_estimation/abstract_cost_estimator.hpp"
#include "enumerate_ccp.hpp"
#include "join_graph.hpp"
#include "logical_query_plan/lqp_utils.hpp"
#include "operators/operator_join_predicate.hpp"
#include "statistics/abstract_cardinality_estimator.hpp"
#include "statistics/cardinality_estimator.hpp"
namespace opossum {
std::shared_ptr<AbstractLQPNode> DpCcp::operator()(const JoinGraph& join_graph,
const std::shared_ptr<AbstractCostEstimator>& cost_estimator) {
Assert(!join_graph.vertices.empty(), "Code below relies on the JoinGraph having vertices");
// No std::unordered_map, since hashing of JoinGraphVertexSet is not (efficiently) possible because
// boost::dynamic_bitset hides the data necessary for doing so efficiently.
auto best_plan = std::map<JoinGraphVertexSet, std::shared_ptr<AbstractLQPNode>>{};
/**
* 1. Initialize best_plan[] with the vertices
*/
for (size_t vertex_idx = 0; vertex_idx < join_graph.vertices.size(); ++vertex_idx) {
auto single_vertex_set = JoinGraphVertexSet{join_graph.vertices.size()};
single_vertex_set.set(vertex_idx);
best_plan[single_vertex_set] = join_graph.vertices[vertex_idx];
}
/**
* 2. Place Uncorrelated Predicates (think "6 > 4": not referencing any vertex)
* 2.1 Collect uncorrelated predicates
*/
std::vector<std::shared_ptr<AbstractExpression>> uncorrelated_predicates;
for (const auto& edge : join_graph.edges) {
if (!edge.vertex_set.none()) continue;
uncorrelated_predicates.insert(uncorrelated_predicates.end(), edge.predicates.begin(), edge.predicates.end());
}
/**
* 2.2 Find the largest vertex and place the uncorrelated predicates for optimal execution.
* Reasoning: Uncorrelated predicates are either False or True for *all* rows. If an uncorrelated
* predicate is False and we place it on top of the largest vertex we avoid processing the vertex'
* many rows in later joins.
*/
if (!uncorrelated_predicates.empty()) {
// Find the largest vertex
auto largest_vertex_idx = size_t{0};
auto largest_vertex_cardinality =
cost_estimator->cardinality_estimator->estimate_cardinality(join_graph.vertices.front());
for (size_t vertex_idx = 1; vertex_idx < join_graph.vertices.size(); ++vertex_idx) {
const auto vertex_cardinality =
cost_estimator->cardinality_estimator->estimate_cardinality(join_graph.vertices[vertex_idx]);
if (vertex_cardinality > largest_vertex_cardinality) {
largest_vertex_idx = vertex_idx;
largest_vertex_cardinality = vertex_cardinality;
}
}
// Place the uncorrelated predicates on top of the largest vertex
auto largest_vertex_single_vertex_set = JoinGraphVertexSet{join_graph.vertices.size()};
largest_vertex_single_vertex_set.set(largest_vertex_idx);
auto largest_vertex_plan = best_plan[largest_vertex_single_vertex_set];
for (const auto& uncorrelated_predicate : uncorrelated_predicates) {
largest_vertex_plan = PredicateNode::make(uncorrelated_predicate, largest_vertex_plan);
}
best_plan[largest_vertex_single_vertex_set] = largest_vertex_plan;
}
/**
* 3. Add local predicates on top of the vertices
*/
for (size_t vertex_idx = 0; vertex_idx < join_graph.vertices.size(); ++vertex_idx) {
const auto vertex_predicates = join_graph.find_local_predicates(vertex_idx);
auto single_vertex_set = JoinGraphVertexSet{join_graph.vertices.size()};
single_vertex_set.set(vertex_idx);
auto& vertex_best_plan = best_plan[single_vertex_set];
vertex_best_plan = _add_predicates_to_plan(vertex_best_plan, vertex_predicates, cost_estimator);
}
/**
* 4. Prepare EnumerateCcp: Transform the JoinGraph's vertex-to-vertex edges into index pairs
*/
std::vector<std::pair<size_t, size_t>> enumerate_ccp_edges;
for (const auto& edge : join_graph.edges) {
// EnumerateCcp only deals with binary join predicates
if (edge.vertex_set.count() != 2) continue;
const auto first_vertex_idx = edge.vertex_set.find_first();
const auto second_vertex_idx = edge.vertex_set.find_next(first_vertex_idx);
enumerate_ccp_edges.emplace_back(first_vertex_idx, second_vertex_idx);
}
/**
* 5. Actual DpCcp algorithm: Enumerate the CsgCmpPairs; build candidate plans; update best_plan if the candidate plan
* is cheaper than the cheapest currently known plan for a particular subset of vertices.
*/
const auto csg_cmp_pairs = EnumerateCcp{join_graph.vertices.size(), enumerate_ccp_edges}(); // NOLINT
for (const auto& csg_cmp_pair : csg_cmp_pairs) {
const auto best_plan_left_iter = best_plan.find(csg_cmp_pair.first);
const auto best_plan_right_iter = best_plan.find(csg_cmp_pair.second);
DebugAssert(best_plan_left_iter != best_plan.end() && best_plan_right_iter != best_plan.end(),
"Subplan missing: either the JoinGraph is invalid or EnumerateCcp is buggy");
const auto join_predicates = join_graph.find_join_predicates(csg_cmp_pair.first, csg_cmp_pair.second);
auto candidate_plan =
_add_join_to_plan(best_plan_left_iter->second, best_plan_right_iter->second, join_predicates, cost_estimator);
const auto joined_vertex_set = csg_cmp_pair.first | csg_cmp_pair.second;
const auto best_plan_iter = best_plan.find(joined_vertex_set);
if (best_plan_iter == best_plan.end() || cost_estimator->estimate_plan_cost(candidate_plan) <
cost_estimator->estimate_plan_cost(best_plan_iter->second)) {
best_plan.insert_or_assign(joined_vertex_set, candidate_plan);
}
}
/**
* 6. Build vertex set with all vertices and return the plan for it - this will be the best plan for the entire join
* graph.
*/
boost::dynamic_bitset<> all_vertices_set{join_graph.vertices.size()};
all_vertices_set.flip(); // Turns all bits to '1'
const auto best_plan_iter = best_plan.find(all_vertices_set);
Assert(best_plan_iter != best_plan.end(), "No plan for all vertices generated. Maybe JoinGraph isn't connected?");
return best_plan_iter->second;
}
} // namespace opossum
| 2,413 |
412 |
<reponame>tobireinhard/cbmc<gh_stars>100-1000
public class ContainerForLong {
public Long longField;
public ContainerForLong(Long l) { longField = l; }
}
| 56 |
72,551 |
// Swift 3 sees the ObjC class NSRuncibleSpoon as the class, and uses methods
// with type signatures involving NSRuncibleSpoon to conform to protocols
// across the language boundary. Swift 4 sees the type as bridged to
// a RuncibleSpoon value type, but still needs to be able to use conformances
// declared by Swift 3.
@import Foundation;
@interface NSRuncibleSpoon: NSObject
@end
@interface SomeObjCClass: NSObject
- (instancetype _Nonnull)initWithSomeSwiftInitRequirement:(NSRuncibleSpoon* _Nonnull)s;
- (void)someSwiftMethodRequirement:(NSRuncibleSpoon* _Nonnull)s;
@property NSRuncibleSpoon * _Nonnull someSwiftPropertyRequirement;
@end
@protocol SomeObjCProtocol
- (instancetype _Nonnull)initWithSomeObjCInitRequirement:(NSRuncibleSpoon * _Nonnull)string;
- (void)someObjCMethodRequirement:(NSRuncibleSpoon * _Nonnull)string;
@property NSRuncibleSpoon * _Nonnull someObjCPropertyRequirement;
@end
| 278 |
577 |
<filename>Lib/test/test_decimal_jy.py
import unittest
from test import test_support
from decimal import Decimal
from java.lang import Float, Double, Object
from java.math import BigDecimal
class TestJavaDecimal(unittest.TestCase):
def test_decimal(self):
x = Decimal("1.1")
y = x.__tojava__(BigDecimal)
self.assertTrue(isinstance(y, BigDecimal))
def test_object(self):
x = Decimal("1.1")
y = x.__tojava__(Object)
self.assertTrue(isinstance(y, BigDecimal))
def test_float(self):
x = Decimal("1.1")
y = x.__tojava__(Float)
self.assertTrue(isinstance(y, Float))
def test_double(self):
x = Decimal("1.1")
y = x.__tojava__(Double)
self.assertTrue(isinstance(y, Double))
if __name__ == '__main__':
unittest.main()
| 382 |
1,099 |
package com.example.chat.mvp.group.groupInfo;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.chat.R;
import com.example.chat.base.ChatBaseActivity;
import com.example.chat.base.ConstantUtil;
import com.example.chat.events.GroupTableEvent;
import com.example.chat.manager.MsgManager;
import com.example.chat.manager.UserDBManager;
import com.example.chat.manager.UserManager;
import com.example.chat.mvp.editInfo.EditUserInfoDetailActivity;
import com.example.chat.mvp.photoSelect.PhotoSelectActivity;
import com.example.chat.mvp.selectFriend.SelectedFriendsActivity;
import com.example.chat.util.TimeUtil;
import com.example.commonlibrary.BaseApplication;
import com.example.commonlibrary.bean.chat.GroupTableEntity;
import com.example.commonlibrary.bean.chat.UserEntity;
import com.example.commonlibrary.customview.RoundAngleImageView;
import com.example.commonlibrary.imageloader.glide.GlideImageLoaderConfig;
import com.example.commonlibrary.rxbus.RxBusManager;
import com.example.commonlibrary.utils.CommonLogger;
import com.example.commonlibrary.utils.SystemUtil;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
/**
* 项目名称: TestChat
* 创建人: 陈锦军
* 创建时间: 2016/12/31 18:01
* QQ: 1981367757
*/
public class GroupInfoActivity extends ChatBaseActivity<Object, GroupInfoPresenter> implements View.OnClickListener {
private TextView notification;
private TextView number;
private RoundAngleImageView add, delete, groupAvatar,one, two,three;
private Button exit;
private TextView name;
private TextView description;
private TextView groupName, createTime;
private GroupTableEntity groupTableEntity;
private RelativeLayout avatarContainer, notificationContainer, groupNameContainer
,descriptionContainer;
private CheckBox remind;
@Override
public void updateData(Object o) {
finish();
}
@Override
protected boolean isNeedHeadLayout() {
return true;
}
@Override
protected boolean isNeedEmptyLayout() {
return false;
}
@Override
protected int getContentLayout() {
return R.layout.activity_group_info;
}
@Override
protected void initView() {
name = (TextView) findViewById(R.id.tv_activity_group_info_name);
groupName = (TextView) findViewById(R.id.tv_activity_group_info_group_name);
createTime = (TextView) findViewById(R.id.tv_activity_group_info_create_time);
notification = (TextView) findViewById(R.id.tv_activity_group_info_group_notification);
number = (TextView) findViewById(R.id.tv_activity_group_info_group_number);
one = (RoundAngleImageView) findViewById(R.id.riv_activity_group_info_number_avatar_one);
two = (RoundAngleImageView) findViewById(R.id.riv_activity_group_info_number_avatar_two);
three = (RoundAngleImageView) findViewById(R.id.riv_activity_group_info_number_avatar_three);
groupAvatar = (RoundAngleImageView) findViewById(R.id.riv_activity_group_info_avatar);
add = (RoundAngleImageView) findViewById(R.id.riv_activity_group_info_add);
delete = (RoundAngleImageView) findViewById(R.id.riv_activity_group_info_delete);
exit = (Button) findViewById(R.id.btn_activity_group_info_exit);
remind= (CheckBox) findViewById(R.id.cb_activity_group_info_remind);
description=(TextView)findViewById(R.id.tv_activity_group_info_group_description);
descriptionContainer=(RelativeLayout)findViewById(R.id.rl_activity_group_info_description);
groupNameContainer = (RelativeLayout) findViewById(R.id.rl_activity_group_info_group_name);
notificationContainer = (RelativeLayout) findViewById(R.id.rl_activity_group_info_notification);
avatarContainer = (RelativeLayout) findViewById(R.id.rl_activity_group_info_header);
exit.setOnClickListener(this);
add.setOnClickListener(this);
delete.setOnClickListener(this);
groupNameContainer.setOnClickListener(this);
avatarContainer.setOnClickListener(this);
descriptionContainer.setOnClickListener(this);
remind.setOnCheckedChangeListener((buttonView, isChecked) -> {
// MsgManager.getInstance().updateGroupMessage(groupTableEntity
// .getGroupId(), ConstantUtil.GROUP_REMIND, isChecked ? "true" : "false", new UpdateListener() {
// @Override
// public void done(BmobException e) {
// if (e != null) {
// ToastUtils.showShortToast("更新失败"+e.toString());
// }
// }
// });
});
findViewById(R.id.ll_activity_group_info_number_container).setOnClickListener(this);
notificationContainer.setOnClickListener(this);
}
@Override
protected void initData() {
groupTableEntity = UserDBManager.getInstance().getGroupTableEntity(getIntent().getStringExtra(ConstantUtil.GROUP_ID));
if (!groupTableEntity.getCreatorId().equals(UserManager.getInstance().getCurrentUserObjectId())) {
delete.setVisibility(View.GONE);
groupNameContainer.setClickable(false);
avatarContainer.setClickable(false);
notificationContainer.setClickable(false);
descriptionContainer.setClickable(false);
}
name.setText(groupTableEntity.getGroupName());
groupName.setText(groupTableEntity.getGroupName());
description.setText(groupTableEntity.getGroupDescription());
notification.setText(groupTableEntity.getNotification());
createTime.setText(TimeUtil.getTime(groupTableEntity.getCreatedTime()));
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append(groupTableEntity.getGroupNumber().size())
.append("位成员");
number.setText(stringBuilder.toString());
remind.setChecked(groupTableEntity.getIsRemind());
BaseApplication
.getAppComponent()
.getImageLoader().loadImage(this,new GlideImageLoaderConfig
.Builder().url(groupTableEntity.getGroupAvatar()).imageView(groupAvatar).build());
String oneUrl=UserDBManager.getInstance().getUser(groupTableEntity.getGroupNumber().get(0))
.getAvatar();
BaseApplication
.getAppComponent()
.getImageLoader().loadImage(this,new GlideImageLoaderConfig
.Builder().url(oneUrl).imageView(one).build());
String twoUrl=UserDBManager.getInstance().getUser(groupTableEntity.getGroupNumber().get(1))
.getAvatar();
BaseApplication
.getAppComponent()
.getImageLoader().loadImage(this,new GlideImageLoaderConfig
.Builder().url(twoUrl).imageView(two).build());
String threeUrl=UserDBManager.getInstance().getUser(groupTableEntity.getGroupNumber().get(2))
.getAvatar();
BaseApplication
.getAppComponent()
.getImageLoader().loadImage(this,new GlideImageLoaderConfig
.Builder().url(threeUrl).imageView(three).build());
}
@Override
public void onClick(View v) {
int id=v.getId();
if (id==R.id.rl_activity_group_info_header){
PhotoSelectActivity.start(this,null,true,true,null);
} else if (id == R.id.rl_activity_group_info_group_name) {
EditUserInfoDetailActivity.start(this,groupTableEntity.getGroupId(),ConstantUtil.GROUP_NAME,groupTableEntity.getGroupName()
,ConstantUtil.REQUEST_CODE_GROUP_NAME);
}else if (id==R.id.rl_activity_group_info_description){
EditUserInfoDetailActivity.start(this,groupTableEntity.getGroupId(),ConstantUtil.GROUP_DESCRIPTION,groupTableEntity.getGroupName()
,ConstantUtil.REQUEST_CODE_GROUP_DESCRIPTION);
} else if (id == R.id.rl_activity_group_info_notification) {
EditUserInfoDetailActivity.start(this,groupTableEntity.getGroupId(),ConstantUtil.GROUP_NOTIFICATION,groupTableEntity.getGroupName()
,ConstantUtil.REQUEST_CODE_GROUP_NOTIFICATION);
} else if (id == R.id.btn_activity_group_info_exit) {
presenter.exitGroup(groupTableEntity.getGroupId(),UserManager.getInstance()
.getCurrentUserObjectId());
} else if (id == R.id.riv_activity_group_info_add) {
ArrayList<UserEntity> list=new ArrayList<>();
list.addAll(UserDBManager.getInstance()
.getAllFriend());
for (String uid :
groupTableEntity.getGroupNumber()) {
UserEntity item = new UserEntity();
item.setUid(uid);
if (list.contains(item)){
list.remove(item);
}
}
SelectedFriendsActivity.start(this,ConstantUtil.FROM_GROUP_INFO,list,ConstantUtil.REQUEST_CODE_ADD_GROUP_NUMBER);
} else if (id == R.id.riv_activity_group_info_delete) {
ArrayList<UserEntity> list=new ArrayList<>();
for (int i = 0; i < groupTableEntity.getGroupNumber().size(); i++) {
if (!groupTableEntity.getGroupNumber().get(i).equals(UserManager.getInstance().getCurrentUserObjectId())) {
list.add(UserDBManager.getInstance().getUser(groupTableEntity.getGroupNumber().get(i)));
}
}
SelectedFriendsActivity.start(this,ConstantUtil.FROM_GROUP_INFO,list,ConstantUtil.REQUEST_CODE_DELETE_GROUP_NUMBER);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== Activity.RESULT_OK){
switch (requestCode){
case ConstantUtil.REQUEST_CODE_ADD_GROUP_NUMBER:
ArrayList<String> list= (ArrayList<String>) data.getSerializableExtra(ConstantUtil.DATA);
break;
case ConstantUtil.REQUEST_CODE_DELETE_GROUP_NUMBER:
break;
case ConstantUtil.REQUEST_CODE_GROUP_NOTIFICATION:
String content=data.getStringExtra(ConstantUtil.DATA);
notification.setText(content);
groupTableEntity.setNotification(content);
RxBusManager.getInstance().post(new GroupTableEvent(groupTableEntity.getGroupId()
,GroupTableEvent.TYPE_GROUP_NOTIFICATION,content));
break;
case ConstantUtil.REQUEST_CODE_GROUP_DESCRIPTION:
String str=data.getStringExtra(ConstantUtil.DATA);
description.setText(str);
groupTableEntity.setGroupDescription(str);
RxBusManager.getInstance().post(new GroupTableEvent(groupTableEntity.getGroupId()
,GroupTableEvent.TYPE_GROUP_DESCRIPTION,str));
break;
case SystemUtil.REQUEST_CODE_ONE_PHOTO:
try {
showLoadDialog("正在上传头像,请稍候........");
BmobFile bmobFile = new BmobFile(new File(new URI(data.getStringExtra(ConstantUtil.PATH))));
bmobFile.uploadblock(new UploadFileListener() {
@Override
public void done(BmobException e) {
if (e == null) {
MsgManager.getInstance().updateGroupMessage(groupTableEntity.getGroupId(),ConstantUtil.GROUP_AVATAR,data
.getStringExtra(ConstantUtil.PATH),new UpdateListener() {
@Override
public void done(BmobException e) {
dismissLoadDialog();
if (e == null) {
CommonLogger.e("更新用户头像成功");
groupTableEntity.setGroupAvatar(bmobFile.getFileUrl());
BaseApplication
.getAppComponent()
.getImageLoader().loadImage(GroupInfoActivity.this,new GlideImageLoaderConfig
.Builder().url(bmobFile.getFileUrl()).imageView(groupAvatar).build());
RxBusManager.getInstance().post(new GroupTableEvent(groupTableEntity.getGroupId()
,GroupTableEvent.TYPE_GROUP_AVATAR,bmobFile.getFileUrl()));
} else {
CommonLogger.e("更新用户头像失败" + e.toString());
}
}
});
} else {
dismissLoadDialog();
CommonLogger.e("加载失败");
}
}
});
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
}
public static void start(Activity activity, String groupId) {
Intent intent=new Intent(activity,GroupInfoActivity.class);
intent.putExtra(ConstantUtil.GROUP_ID,groupId);
activity.startActivity(intent);
}
}
| 6,634 |
366 |
<reponame>zhengjb/OpenExplorer<gh_stars>100-1000
package com.jdkcn.openexplorer;
import openexplorer.util.IOUtils;
/**
* @author <a href="mailto:<EMAIL>">Rory</a>
* @version $Id$
*/
public class BrowserDetachTest {
public static void main(String[] args) throws Exception {
Process process = Runtime.getRuntime().exec("which nautilus");
String nautilusPath = IOUtils.toString(process.getInputStream());
System.out.println("nautilus path:[" + nautilusPath + "]");
process = Runtime.getRuntime().exec("which pcmanfm");
String pcmanfmPath = IOUtils.toString(process.getInputStream());
System.out.println("pcmanfm path:[" + pcmanfmPath + "]");
process = Runtime.getRuntime().exec("which thunar");
String thunarPath = IOUtils.toString(process.getInputStream());
System.out.println("thunar path:[" + thunarPath + "]");
}
}
| 351 |
818 |
<filename>addons/common/monitoring/core/src/main/java/org/kie/kogito/monitoring/core/common/rule/RuleMetricsListener.java
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.kogito.monitoring.core.common.rule;
import java.util.Arrays;
import org.drools.core.event.rule.impl.AfterActivationFiredEventImpl;
import org.drools.core.event.rule.impl.BeforeActivationFiredEventImpl;
import org.kie.api.event.rule.AfterMatchFiredEvent;
import org.kie.api.event.rule.BeforeMatchFiredEvent;
import org.kie.api.event.rule.DefaultAgendaEventListener;
import org.kie.kogito.KogitoGAV;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
public class RuleMetricsListener extends DefaultAgendaEventListener {
private static final Logger logger = LoggerFactory.getLogger(RuleMetricsListener.class);
private final String identifier;
private final KogitoGAV gav;
private final MeterRegistry meterRegistry;
private static final long NANOSECONDS_PER_MICROSECOND = 1_000_000;
public RuleMetricsListener(String identifier, KogitoGAV gav, MeterRegistry meterRegistry) {
this.identifier = identifier;
this.gav = gav;
this.meterRegistry = meterRegistry;
}
@Override
public void beforeMatchFired(BeforeMatchFiredEvent event) {
long nanoTime = System.nanoTime();
BeforeActivationFiredEventImpl impl = getBeforeImpl(event);
impl.setTimestamp(nanoTime);
}
@Override
public void afterMatchFired(AfterMatchFiredEvent event) {
AfterActivationFiredEventImpl afterImpl = getAfterImpl(event);
BeforeActivationFiredEventImpl beforeImpl = getBeforeImpl(afterImpl.getBeforeMatchFiredEvent());
long startTime = beforeImpl.getTimestamp();
long elapsed = System.nanoTime() - startTime;
String ruleName = event.getMatch().getRule().getName();
getDroolsEvaluationTimeHistogram(identifier, ruleName).record(elapsed);
if (logger.isDebugEnabled()) {
logger.debug("Elapsed time: " + elapsed);
}
}
public BeforeActivationFiredEventImpl getBeforeImpl(BeforeMatchFiredEvent e) {
return (BeforeActivationFiredEventImpl) e;
}
public AfterActivationFiredEventImpl getAfterImpl(AfterMatchFiredEvent e) {
return (AfterActivationFiredEventImpl) e;
}
private static long toMicro(long second) {
return second * NANOSECONDS_PER_MICROSECOND;
}
private DistributionSummary getDroolsEvaluationTimeHistogram(String appId, String rule) {
DistributionSummary distributionSummary = DistributionSummary.builder("drl_match_fired_nanosecond")
.minimumExpectedValue((double) toMicro(1))
.maximumExpectedValue((double) toMicro(10))
.description("Drools Firing Time")
.tags(Arrays.asList(Tag.of("app_id", appId), Tag.of("rule", rule), Tag.of("artifactId", gav.getArtifactId()), Tag.of("version", gav.getVersion())))
.register(meterRegistry);
return distributionSummary;
}
}
| 1,330 |
679 |
<filename>main/sc/source/ui/dbgui/tpsubt.cxx
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_scui.hxx"
#include "scitems.hxx"
#include "uiitems.hxx"
#include "global.hxx"
#include "userlist.hxx"
#include "viewdata.hxx"
#include "document.hxx"
#include "scresid.hxx"
#include "sc.hrc" // -> Slot IDs
#include "subtdlg.hxx"
#include "subtdlg.hrc"
#include "tpsubt.hxx"
// STATIC DATA -----------------------------------------------------------
static sal_uInt16 pSubTotalsRanges[] =
{
SID_SUBTOTALS,
SID_SUBTOTALS,
0
};
//========================================================================
// Zwischenergebnisgruppen-Tabpage:
ScTpSubTotalGroup::ScTpSubTotalGroup( Window* pParent, sal_uInt16 nResId,
const SfxItemSet& rArgSet )
: SfxTabPage ( pParent,
ScResId( nResId ),
rArgSet ),
//
aFtGroup ( this, ScResId( FT_GROUP ) ),
aLbGroup ( this, ScResId( LB_GROUP ) ),
aFtColumns ( this, ScResId( FT_COLUMNS ) ),
aLbColumns ( this, ScResId( WND_COLUMNS ) ),
aFtFunctions ( this, ScResId( FT_FUNCTIONS ) ),
aLbFunctions ( this, ScResId( LB_FUNCTIONS ) ),
aStrNone ( ScResId( SCSTR_NONE ) ),
aStrColumn ( ScResId( SCSTR_COLUMN ) ),
//
pViewData ( NULL ),
pDoc ( NULL ),
nWhichSubTotals ( rArgSet.GetPool()->GetWhich( SID_SUBTOTALS ) ),
rSubTotalData ( ((const ScSubTotalItem&)
rArgSet.Get( nWhichSubTotals )).
GetSubTotalData() ),
nFieldCount ( 0 )
{
// Font is correctly initialized by SvTreeListBox ctor
aLbColumns.SetSelectionMode( SINGLE_SELECTION );
aLbColumns.SetDragDropMode( SV_DRAGDROP_NONE );
aLbColumns.SetSpaceBetweenEntries( 0 );
aLbColumns.Show();
Init ();
FreeResource();
}
// -----------------------------------------------------------------------
__EXPORT ScTpSubTotalGroup::~ScTpSubTotalGroup()
{
sal_uInt16 nCount = (sal_uInt16)aLbColumns.GetEntryCount();
if ( nCount > 0 )
{
sal_uInt16* pData = NULL;
for ( sal_uInt16 i=0; i<nCount; i++ )
{
pData = (sal_uInt16*)(aLbColumns.GetEntryData( i ));
DBG_ASSERT( pData, "EntryData not found" );
delete pData;
}
}
}
// -----------------------------------------------------------------------
void ScTpSubTotalGroup::Init()
{
const ScSubTotalItem& rSubTotalItem = (const ScSubTotalItem&)
GetItemSet().Get( nWhichSubTotals );
pViewData = rSubTotalItem.GetViewData();
pDoc = ( pViewData ) ? pViewData->GetDocument() : NULL;
DBG_ASSERT( pViewData && pDoc, "ViewData or Document not found :-(" );
aLbGroup.SetSelectHdl ( LINK( this, ScTpSubTotalGroup, SelectHdl ) );
aLbColumns.SetSelectHdl ( LINK( this, ScTpSubTotalGroup, SelectHdl ) );
aLbColumns.SetCheckButtonHdl ( LINK( this, ScTpSubTotalGroup, CheckHdl ) );
aLbFunctions.SetSelectHdl ( LINK( this, ScTpSubTotalGroup, SelectHdl ) );
nFieldArr[0] = 0;
FillListBoxes();
}
//------------------------------------------------------------------------
sal_uInt16* __EXPORT ScTpSubTotalGroup::GetRanges()
{
return pSubTotalsRanges;
}
// -----------------------------------------------------------------------
sal_Bool ScTpSubTotalGroup::DoReset( sal_uInt16 nGroupNo,
const SfxItemSet& rArgSet )
{
sal_uInt16 nGroupIdx = 0;
DBG_ASSERT( (nGroupNo<=3) && (nGroupNo>0), "Invalid group" );
if ( (nGroupNo > 3) || (nGroupNo == 0) )
return sal_False;
else
nGroupIdx = nGroupNo-1;
//----------------------------------------------------------
// #79058# first we have to clear the listboxes...
for ( sal_uInt16 nLbEntry = 0; nLbEntry < aLbColumns.GetEntryCount(); ++nLbEntry )
{
aLbColumns.CheckEntryPos( nLbEntry, sal_False );
*((sal_uInt16*)aLbColumns.GetEntryData( nLbEntry )) = 0;
}
aLbFunctions.SelectEntryPos( 0 );
ScSubTotalParam theSubTotalData( ((const ScSubTotalItem&)
rArgSet.Get( nWhichSubTotals )).
GetSubTotalData() );
if ( theSubTotalData.bGroupActive[nGroupIdx] )
{
SCCOL nField = theSubTotalData.nField[nGroupIdx];
SCCOL nSubTotals = theSubTotalData.nSubTotals[nGroupIdx];
SCCOL* pSubTotals = theSubTotalData.pSubTotals[nGroupIdx];
ScSubTotalFunc* pFunctions = theSubTotalData.pFunctions[nGroupIdx];
aLbGroup.SelectEntryPos( GetFieldSelPos( nField )+1 );
for ( sal_uInt16 i=0; i<nSubTotals; i++ )
{
sal_uInt16 nCheckPos = GetFieldSelPos( pSubTotals[i] );
sal_uInt16* pFunction = (sal_uInt16*)aLbColumns.GetEntryData( nCheckPos );
aLbColumns.CheckEntryPos( nCheckPos );
*pFunction = FuncToLbPos( pFunctions[i] );
}
aLbColumns.SelectEntryPos( 0 );
}
else
{
aLbGroup.SelectEntryPos( (nGroupNo == 1) ? 1 : 0 );
aLbColumns.SelectEntryPos( 0 );
aLbFunctions.SelectEntryPos( 0 );
}
return sal_True;
}
// -----------------------------------------------------------------------
sal_Bool ScTpSubTotalGroup::DoFillItemSet( sal_uInt16 nGroupNo,
SfxItemSet& rArgSet )
{
sal_uInt16 nGroupIdx = 0;
DBG_ASSERT( (nGroupNo<=3) && (nGroupNo>0), "Invalid group" );
DBG_ASSERT( (aLbGroup.GetEntryCount() > 0)
&& (aLbColumns.GetEntryCount() > 0)
&& (aLbFunctions.GetEntryCount() > 0),
"Non-initialized Lists" );
if ( (nGroupNo > 3) || (nGroupNo == 0)
|| (aLbGroup.GetEntryCount() == 0)
|| (aLbColumns.GetEntryCount() == 0)
|| (aLbFunctions.GetEntryCount() == 0)
)
return sal_False;
else
nGroupIdx = nGroupNo-1;
//----------------------------------------------------------
ScSubTotalParam theSubTotalData; // auslesen, wenn schon teilweise gefuellt
SfxTabDialog* pDlg = GetTabDialog();
if ( pDlg )
{
const SfxItemSet* pExample = pDlg->GetExampleSet();
const SfxPoolItem* pItem;
if ( pExample && pExample->GetItemState( nWhichSubTotals, sal_True, &pItem ) == SFX_ITEM_SET )
theSubTotalData = ((const ScSubTotalItem*)pItem)->GetSubTotalData();
}
ScSubTotalFunc* pFunctions = NULL;
SCCOL* pSubTotals = NULL;
sal_uInt16 nGroup = aLbGroup.GetSelectEntryPos();
sal_uInt16 nEntryCount = (sal_uInt16)aLbColumns.GetEntryCount();
sal_uInt16 nCheckCount = aLbColumns.GetCheckedEntryCount();
theSubTotalData.nCol1 = rSubTotalData.nCol1;
theSubTotalData.nRow1 = rSubTotalData.nRow1;
theSubTotalData.nCol2 = rSubTotalData.nCol2;
theSubTotalData.nRow2 = rSubTotalData.nRow2;
theSubTotalData.bGroupActive[nGroupIdx] = (nGroup != 0);
theSubTotalData.nField[nGroupIdx] = (nGroup != 0)
? nFieldArr[nGroup-1]
: static_cast<SCCOL>(0);
if ( nEntryCount>0 && nCheckCount>0 && nGroup!=0 )
{
sal_uInt16 nFunction = 0;
pSubTotals = new SCCOL [nCheckCount];
pFunctions = new ScSubTotalFunc [nCheckCount];
for ( sal_uInt16 i=0, nCheck=0; i<nEntryCount; i++ )
{
if ( aLbColumns.IsChecked( i ) )
{
DBG_ASSERT( nCheck <= nCheckCount,
"Range error :-(" );
nFunction = *((sal_uInt16*)aLbColumns.GetEntryData( i ));
pSubTotals[nCheck] = nFieldArr[i];
pFunctions[nCheck] = LbPosToFunc( nFunction );
nCheck++;
}
}
theSubTotalData.SetSubTotals( nGroupNo, // Gruppen-Nr.
pSubTotals,
pFunctions,
nCheckCount ); // Anzahl der Array-Elemente
}
rArgSet.Put( ScSubTotalItem( SCITEM_SUBTDATA, &theSubTotalData ) );
if ( pSubTotals ) delete [] pSubTotals;
if ( pFunctions ) delete [] pFunctions;
return sal_True;
}
// -----------------------------------------------------------------------
void ScTpSubTotalGroup::FillListBoxes()
{
DBG_ASSERT( pViewData && pDoc, "ViewData or Document not found :-/" );
if ( pViewData && pDoc )
{
SCCOL nFirstCol = rSubTotalData.nCol1;
SCROW nFirstRow = rSubTotalData.nRow1;
SCTAB nTab = pViewData->GetTabNo();
SCCOL nMaxCol = rSubTotalData.nCol2;
SCCOL col;
sal_uInt16 i=0;
String aFieldName;
aLbGroup.Clear();
aLbColumns.Clear();
aLbGroup.InsertEntry( aStrNone, 0 );
i=0;
for ( col=nFirstCol; col<=nMaxCol && i<SC_MAXFIELDS; col++ )
{
pDoc->GetString( col, nFirstRow, nTab, aFieldName );
if ( aFieldName.Len() == 0 )
{
aFieldName = aStrColumn;
aFieldName += ' ';
aFieldName += ::ScColToAlpha( col ); // from global.hxx
}
nFieldArr[i] = col;
aLbGroup.InsertEntry( aFieldName, i+1 );
aLbColumns.InsertEntry( aFieldName, i );
aLbColumns.SetEntryData( i, new sal_uInt16(0) );
i++;
}
// Nachtraegliche "Konstanteninitialisierung":
(sal_uInt16&)nFieldCount = i;
}
}
// -----------------------------------------------------------------------
sal_uInt16 ScTpSubTotalGroup::GetFieldSelPos( SCCOL nField )
{
sal_uInt16 nFieldPos = 0;
sal_Bool bFound = sal_False;
for ( sal_uInt16 n=0; n<nFieldCount && !bFound; n++ )
{
if ( nFieldArr[n] == nField )
{
nFieldPos = n;
bFound = sal_True;
}
}
return nFieldPos;
}
// -----------------------------------------------------------------------
ScSubTotalFunc ScTpSubTotalGroup::LbPosToFunc( sal_uInt16 nPos )
{
switch ( nPos )
{
// case 0: return SUBTOTAL_FUNC_NONE;
case 2: return SUBTOTAL_FUNC_AVE;
case 6: return SUBTOTAL_FUNC_CNT;
case 1: return SUBTOTAL_FUNC_CNT2;
case 3: return SUBTOTAL_FUNC_MAX;
case 4: return SUBTOTAL_FUNC_MIN;
case 5: return SUBTOTAL_FUNC_PROD;
case 7: return SUBTOTAL_FUNC_STD;
case 8: return SUBTOTAL_FUNC_STDP;
case 0: return SUBTOTAL_FUNC_SUM;
case 9: return SUBTOTAL_FUNC_VAR;
case 10: return SUBTOTAL_FUNC_VARP;
default:
DBG_ERROR( "ScTpSubTotalGroup::LbPosToFunc" );
return SUBTOTAL_FUNC_NONE;
}
}
// -----------------------------------------------------------------------
sal_uInt16 ScTpSubTotalGroup::FuncToLbPos( ScSubTotalFunc eFunc )
{
switch ( eFunc )
{
// case SUBTOTAL_FUNC_NONE: return 0;
case SUBTOTAL_FUNC_AVE: return 2;
case SUBTOTAL_FUNC_CNT: return 6;
case SUBTOTAL_FUNC_CNT2: return 1;
case SUBTOTAL_FUNC_MAX: return 3;
case SUBTOTAL_FUNC_MIN: return 4;
case SUBTOTAL_FUNC_PROD: return 5;
case SUBTOTAL_FUNC_STD: return 7;
case SUBTOTAL_FUNC_STDP: return 8;
case SUBTOTAL_FUNC_SUM: return 0;
case SUBTOTAL_FUNC_VAR: return 9;
case SUBTOTAL_FUNC_VARP: return 10;
default:
DBG_ERROR( "ScTpSubTotalGroup::FuncToLbPos" );
return 0;
}
}
// -----------------------------------------------------------------------
// Handler:
//---------
IMPL_LINK( ScTpSubTotalGroup, SelectHdl, ListBox *, pLb )
{
if ( (aLbColumns.GetEntryCount() > 0)
&& (aLbColumns.GetSelectionCount() > 0) )
{
sal_uInt16 nFunction = aLbFunctions.GetSelectEntryPos();
sal_uInt16 nColumn = aLbColumns.GetSelectEntryPos();
sal_uInt16* pFunction = (sal_uInt16*)aLbColumns.GetEntryData( nColumn );
DBG_ASSERT( pFunction, "EntryData nicht gefunden!" );
if ( !pFunction )
return 0;
if ( ((SvxCheckListBox*)pLb) == &aLbColumns )
{
aLbFunctions.SelectEntryPos( *pFunction );
}
else if ( pLb == &aLbFunctions )
{
*pFunction = nFunction;
// aLbColumns.CheckEntryPos( nColumn, (nFunction != 0) );//XXX
aLbColumns.CheckEntryPos( nColumn, sal_True );
}
}
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( ScTpSubTotalGroup, CheckHdl, ListBox *, pLb )
{
if ( ((SvxCheckListBox*)pLb) == &aLbColumns )
{
SvLBoxEntry* pEntry = aLbColumns.GetHdlEntry();
if ( pEntry )
{
aLbColumns.SelectEntryPos( (sal_uInt16)aLbColumns.GetModel()->GetAbsPos( pEntry ) );
SelectHdl( pLb );
}
}
return 0;
}
//========================================================================
// Abgeleitete Gruppen-TabPages:
SfxTabPage* __EXPORT ScTpSubTotalGroup1::Create( Window* pParent,
const SfxItemSet& rArgSet )
{ return ( new ScTpSubTotalGroup1( pParent, rArgSet ) ); }
// -----------------------------------------------------------------------
SfxTabPage* __EXPORT ScTpSubTotalGroup2::Create( Window* pParent,
const SfxItemSet& rArgSet )
{ return ( new ScTpSubTotalGroup2( pParent, rArgSet ) ); }
// -----------------------------------------------------------------------
SfxTabPage* __EXPORT ScTpSubTotalGroup3::Create( Window* pParent,
const SfxItemSet& rArgSet )
{ return ( new ScTpSubTotalGroup3( pParent, rArgSet ) ); }
// -----------------------------------------------------------------------
ScTpSubTotalGroup1::ScTpSubTotalGroup1( Window* pParent, const SfxItemSet& rArgSet ) :
ScTpSubTotalGroup( pParent, RID_SCPAGE_SUBT_GROUP1, rArgSet )
{}
ScTpSubTotalGroup2::ScTpSubTotalGroup2( Window* pParent, const SfxItemSet& rArgSet ) :
ScTpSubTotalGroup( pParent, RID_SCPAGE_SUBT_GROUP2, rArgSet )
{}
ScTpSubTotalGroup3::ScTpSubTotalGroup3( Window* pParent, const SfxItemSet& rArgSet ) :
ScTpSubTotalGroup( pParent, RID_SCPAGE_SUBT_GROUP3, rArgSet )
{}
// -----------------------------------------------------------------------
#define RESET(i) (ScTpSubTotalGroup::DoReset( (i), rArgSet ))
void __EXPORT ScTpSubTotalGroup1::Reset( const SfxItemSet& rArgSet ) { RESET(1); }
void __EXPORT ScTpSubTotalGroup2::Reset( const SfxItemSet& rArgSet ) { RESET(2); }
void __EXPORT ScTpSubTotalGroup3::Reset( const SfxItemSet& rArgSet ) { RESET(3); }
#undef RESET
// -----------------------------------------------------------------------
#define FILLSET(i) (ScTpSubTotalGroup::DoFillItemSet( (i), rArgSet ))
sal_Bool __EXPORT ScTpSubTotalGroup1::FillItemSet( SfxItemSet& rArgSet ) { return FILLSET(1); }
sal_Bool __EXPORT ScTpSubTotalGroup2::FillItemSet( SfxItemSet& rArgSet ) { return FILLSET(2); }
sal_Bool __EXPORT ScTpSubTotalGroup3::FillItemSet( SfxItemSet& rArgSet ) { return FILLSET(3); }
#undef FILL
//========================================================================
// Optionen-Tabpage:
ScTpSubTotalOptions::ScTpSubTotalOptions( Window* pParent,
const SfxItemSet& rArgSet )
: SfxTabPage ( pParent,
ScResId( RID_SCPAGE_SUBT_OPTIONS ),
rArgSet ),
//
aFlGroup ( this, ScResId( FL_GROUP ) ),
aBtnPagebreak ( this, ScResId( BTN_PAGEBREAK ) ),
aBtnCase ( this, ScResId( BTN_CASE ) ),
aBtnSort ( this, ScResId( BTN_SORT ) ),
aFlSort ( this, ScResId( FL_SORT ) ),
aBtnAscending ( this, ScResId( BTN_ASCENDING ) ),
aBtnDescending ( this, ScResId( BTN_DESCENDING ) ),
aBtnFormats ( this, ScResId( BTN_FORMATS ) ),
aBtnUserDef ( this, ScResId( BTN_USERDEF ) ),
aLbUserDef ( this, ScResId( LB_USERDEF ) ),
//
pViewData ( NULL ),
pDoc ( NULL ),
nWhichSubTotals ( rArgSet.GetPool()->GetWhich( SID_SUBTOTALS ) ),
rSubTotalData ( ((const ScSubTotalItem&)
rArgSet.Get( nWhichSubTotals )).
GetSubTotalData() )
{
Init();
FreeResource();
aLbUserDef.SetAccessibleRelationLabeledBy(&aBtnUserDef);
aLbUserDef.SetAccessibleName(aBtnUserDef.GetText());
}
// -----------------------------------------------------------------------
__EXPORT ScTpSubTotalOptions::~ScTpSubTotalOptions()
{
}
// -----------------------------------------------------------------------
void ScTpSubTotalOptions::Init()
{
const ScSubTotalItem& rSubTotalItem = (const ScSubTotalItem&)
GetItemSet().Get( nWhichSubTotals );
pViewData = rSubTotalItem.GetViewData();
pDoc = ( pViewData ) ? pViewData->GetDocument() : NULL;
DBG_ASSERT( pViewData && pDoc, "ViewData oder Document nicht gefunden!" );
aBtnSort.SetClickHdl ( LINK( this, ScTpSubTotalOptions, CheckHdl ) );
aBtnUserDef.SetClickHdl ( LINK( this, ScTpSubTotalOptions, CheckHdl ) );
FillUserSortListBox();
}
// -----------------------------------------------------------------------
SfxTabPage* __EXPORT ScTpSubTotalOptions::Create( Window* pParent,
const SfxItemSet& rArgSet )
{
return ( new ScTpSubTotalOptions( pParent, rArgSet ) );
}
// -----------------------------------------------------------------------
void __EXPORT ScTpSubTotalOptions::Reset( const SfxItemSet& /* rArgSet */ )
{
aBtnPagebreak.Check ( rSubTotalData.bPagebreak );
aBtnCase.Check ( rSubTotalData.bCaseSens );
aBtnFormats.Check ( rSubTotalData.bIncludePattern );
aBtnSort.Check ( rSubTotalData.bDoSort );
aBtnAscending.Check ( rSubTotalData.bAscending );
aBtnDescending.Check( !rSubTotalData.bAscending );
if ( rSubTotalData.bUserDef )
{
aBtnUserDef.Check( sal_True );
aLbUserDef.Enable();
aLbUserDef.SelectEntryPos( rSubTotalData.nUserIndex );
}
else
{
aBtnUserDef.Check( sal_False );
aLbUserDef.Disable();
aLbUserDef.SelectEntryPos( 0 );
}
CheckHdl( &aBtnSort );
}
// -----------------------------------------------------------------------
sal_Bool __EXPORT ScTpSubTotalOptions::FillItemSet( SfxItemSet& rArgSet )
{
ScSubTotalParam theSubTotalData; // auslesen, wenn schon teilweise gefuellt
SfxTabDialog* pDlg = GetTabDialog();
if ( pDlg )
{
const SfxItemSet* pExample = pDlg->GetExampleSet();
const SfxPoolItem* pItem;
if ( pExample && pExample->GetItemState( nWhichSubTotals, sal_True, &pItem ) == SFX_ITEM_SET )
theSubTotalData = ((const ScSubTotalItem*)pItem)->GetSubTotalData();
}
theSubTotalData.bPagebreak = aBtnPagebreak.IsChecked();
theSubTotalData.bReplace = sal_True;
theSubTotalData.bCaseSens = aBtnCase.IsChecked();
theSubTotalData.bIncludePattern = aBtnFormats.IsChecked();
theSubTotalData.bDoSort = aBtnSort.IsChecked();
theSubTotalData.bAscending = aBtnAscending.IsChecked();
theSubTotalData.bUserDef = aBtnUserDef.IsChecked();
theSubTotalData.nUserIndex = (aBtnUserDef.IsChecked())
? aLbUserDef.GetSelectEntryPos()
: 0;
rArgSet.Put( ScSubTotalItem( nWhichSubTotals, &theSubTotalData ) );
return sal_True;
}
// -----------------------------------------------------------------------
void ScTpSubTotalOptions::FillUserSortListBox()
{
ScUserList* pUserLists = ScGlobal::GetUserList();
aLbUserDef.Clear();
if ( pUserLists )
{
sal_uInt16 nCount = pUserLists->GetCount();
if ( nCount > 0 )
for ( sal_uInt16 i=0; i<nCount; i++ )
aLbUserDef.InsertEntry( (*pUserLists)[i]->GetString() );
}
}
// -----------------------------------------------------------------------
// Handler:
IMPL_LINK( ScTpSubTotalOptions, CheckHdl, CheckBox *, pBox )
{
if ( pBox == &aBtnSort )
{
if ( aBtnSort.IsChecked() )
{
aFlSort .Enable();
aBtnFormats .Enable();
aBtnUserDef .Enable();
aBtnAscending .Enable();
aBtnDescending .Enable();
if ( aBtnUserDef.IsChecked() )
aLbUserDef.Enable();
}
else
{
aFlSort .Disable();
aBtnFormats .Disable();
aBtnUserDef .Disable();
aBtnAscending .Disable();
aBtnDescending .Disable();
aLbUserDef .Disable();
}
}
else if ( pBox == &aBtnUserDef )
{
if ( aBtnUserDef.IsChecked() )
{
aLbUserDef.Enable();
aLbUserDef.GrabFocus();
}
else
aLbUserDef.Disable();
}
return 0;
}
__EXPORT ScTpSubTotalGroup1::~ScTpSubTotalGroup1()
{
}
__EXPORT ScTpSubTotalGroup2::~ScTpSubTotalGroup2()
{
}
__EXPORT ScTpSubTotalGroup3::~ScTpSubTotalGroup3()
{
}
| 8,210 |
403 |
package io.craft.atom.io;
/**
* The x-ray of {@link IoReactor}
*
* @author mindwind
* @version 1.0, Oct 15, 2014
*/
public interface IoReactorX {
/**
* @return current alive channel count.
*/
int aliveChannelCount();
/**
* @return current new channel to be processed count.
*/
int newChannelCount();
/**
* @return current flushing channel count.
*/
int flushingChannelCount();
/**
* @return current closing channel count.
*/
int closingChannelCount();
}
| 167 |
852 |
<gh_stars>100-1000
import FWCore.ParameterSet.Config as cms
hltTauDQMProcess = "HLT"
hltTauMonitor = cms.EDAnalyzer("HLTTauDQMSource",
HLTProcessName = cms.untracked.string(hltTauDQMProcess),
ModuleName = cms.untracked.string("hltTauMonitor"),
DQMBaseFolder = cms.untracked.string("HLT/TauOnline/Inclusive/"),
MonitorSetup = cms.VPSet(
cms.PSet(
ConfigType = cms.untracked.string("Path"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryRAW","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('DoubleTau'),
),
cms.PSet(
ConfigType = cms.untracked.string("Path"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryRAW","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('Ele.+?Tau'),
Alias = cms.untracked.string('EleTau'),
),
cms.PSet(
ConfigType = cms.untracked.string("Path"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryRAW","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('Mu.+?Tau'),
Alias = cms.untracked.string('MuTau'),
),
cms.PSet(
ConfigType = cms.untracked.string("Path"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryRAW","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('Single.+?Tau_MET'),
Alias = cms.untracked.string('SingleTau'),
),
cms.PSet(
ConfigType = cms.untracked.string("LitePath"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryAOD","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('Summary'),
),
cms.PSet(
ConfigType = cms.untracked.string("L1"),
DQMFolder = cms.untracked.string('L1'),
L1Taus = cms.InputTag("hltL1extraParticles","Tau"),
L1Jets = cms.InputTag("hltL1extraParticles","Central"),
L1Electrons = cms.InputTag("hltL1extraParticles","Isolated"),
L1Muons = cms.InputTag("hltL1extraParticles"),
),
),
Matching = cms.PSet(
doMatching = cms.untracked.bool(False),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryAOD","",hltTauDQMProcess),
matchFilters = cms.untracked.VPSet(),
),
)
hltTauElectronMonitor = cms.EDAnalyzer("HLTTauDQMSource",
HLTProcessName = cms.untracked.string(hltTauDQMProcess),
ModuleName = cms.untracked.string("hltTauElectronMonitor"),
DQMBaseFolder = cms.untracked.string("HLT/TauOnline/Electrons/"),
MonitorSetup = cms.VPSet(
cms.PSet(
ConfigType = cms.untracked.string("Path"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryRAW","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('DoubleTau'),
),
cms.PSet(
ConfigType = cms.untracked.string("Path"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryRAW","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('Single.+?Tau_MET'),
Alias = cms.untracked.string('SingleTau'),
),
cms.PSet(
ConfigType = cms.untracked.string("Path"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryRAW","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('LoosePFTau'),
),
cms.PSet(
ConfigType = cms.untracked.string("Path"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryRAW","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('MediumPFTau'),
),
cms.PSet(
ConfigType = cms.untracked.string("Path"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryRAW","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('TightPFTau'),
),
cms.PSet(
ConfigType = cms.untracked.string("LitePath"),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryAOD","",hltTauDQMProcess),
DQMFolder = cms.untracked.string('Summary'),
),
cms.PSet(
ConfigType = cms.untracked.string("L1"),
DQMFolder = cms.untracked.string('L1'),
L1Taus = cms.InputTag("hltL1extraParticles","Tau"),
L1Jets = cms.InputTag("hltL1extraParticles","Central"),
L1Electrons = cms.InputTag("hltL1extraParticles","Isolated"),
L1Muons = cms.InputTag("hltL1extraParticles"),
),
),
Matching = cms.PSet(
doMatching = cms.untracked.bool(True),
TriggerEventObject = cms.untracked.InputTag("hltTriggerSummaryAOD","",hltTauDQMProcess),
matchFilters = cms.untracked.VPSet(
cms.untracked.PSet(
AutomaticFilterName = cms.untracked.string('Ele.+?Tau'),
matchObjectID = cms.untracked.int32(11),
matchObjectMinPt = cms.untracked.double(10),
),
),
),
)
hltMonTauReco =cms.Sequence(hltTauMonitor+hltTauElectronMonitor)
| 3,263 |
505 |
package de.rieckpil.blog;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import java.util.List;
public interface CustomerRepository extends MongoRepository<Customer, String> {
@Query(sort = "{ rating : 1 }")
List<Customer> findByRatingBetween(int from, int to);
}
| 111 |
548 |
package com.yarolegovich.materialprefsample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
/**
* Created by yarolegovich on 16.05.2016.
*/
public class ToolbarActivity extends AppCompatActivity {
@SuppressWarnings("ConstantConditions")
protected void setupToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
| 174 |
1,085 |
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.service.namespace;
import com.dremio.datastore.adapter.LegacyKVStoreProviderAdapter;
import com.dremio.datastore.api.LegacyKVStoreProvider;
import com.dremio.test.DremioTest;
/**
* Test driver for spaces service.
*/
public class TestLocalKVStoreAdapterNamespaceService extends AbstractTestNamespaceService {
@Override
protected LegacyKVStoreProvider createKVStoreProvider() {
return LegacyKVStoreProviderAdapter.inMemory(DremioTest.CLASSPATH_SCAN_RESULT);
}
@Override
protected void closeResources() {
}
}
| 334 |
310 |
<reponame>dreeves/usesthis<filename>gear/hardware/m/marathon-supreme-700x28.json
{
"name": "Marathon Supreme 700x28",
"description": "Tires for a bike with integrated light reflection.",
"url": "https://www.amazon.com/Schwalbe-Marathon-Supreme-Speed-Folding/dp/B004JKJMB0"
}
| 105 |
3,459 |
# -*- coding: utf-8 -*-
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if width == 0 and height == 0 and \
color == 'red' and emphasis == 'strong' or \
highlight > 100:
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
# Some random text with multi-byte characters (utf-8 encoded)
#
# Εδώ μάτσο κειμένων τη, τρόπο πιθανό διευθυντές ώρα μη. Νέων απλό παράγει ροή
# κι, το επί δεδομένη καθορίζουν. Πάντως ζητήσεις περιβάλλοντος ένα με, τη
# ξέχασε αρπάζεις φαινόμενο όλη. Τρέξει εσφαλμένη χρησιμοποίησέ νέα τι. Θα όρο
# πετάνε φακέλους, άρα με διακοπής λαμβάνουν εφαμοργής. Λες κι μειώσει
# καθυστερεί.
# 79 narrow chars
# 01 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 [79]
# 78 narrow chars (Na) + 1 wide char (W)
# 01 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8情
# 3 narrow chars (Na) + 40 wide chars (W)
# 情 情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情
# 3 narrow chars (Na) + 76 wide chars (W)
# 情 情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情
#
#: E501
# 80 narrow chars (Na)
# 01 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 [80]
#
#: E501
# 78 narrow chars (Na) + 2 wide char (W)
# 01 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8情情
#
#: E501
# 3 narrow chars (Na) + 77 wide chars (W)
# 情 情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情情
#
| 1,454 |
439 |
<reponame>kant/beacon-platform
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sample.beaconservice;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
class BeaconArrayAdapter extends ArrayAdapter<Beacon> {
private static final int BLACK = Color.rgb(0, 0, 0);
private static final int GREEN = Color.rgb(0, 142, 9);
private static final int ORANGE = Color.rgb(255, 165, 0);
private static final int RED = Color.rgb(255, 5, 5);
private static final int GREY = Color.rgb(150, 150, 150);
public BeaconArrayAdapter(Context context, int resource, List<Beacon> objects) {
super(context, resource, objects);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Beacon beacon = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.beacon_list_item, parent, false);
}
ImageView registrationStatus = (ImageView) convertView.findViewById(R.id.registrationStatus);
TextView beaconId = (TextView) convertView.findViewById(R.id.beaconId);
beaconId.setText(beacon.getHexId());
switch (beacon.status) {
case Beacon.UNREGISTERED:
registrationStatus.setImageResource(R.drawable.ic_action_lock_open);
registrationStatus.setColorFilter(BLACK);
beaconId.setTextColor(BLACK);
break;
case Beacon.STATUS_ACTIVE:
registrationStatus.setImageResource(R.drawable.ic_action_check_circle);
registrationStatus.setColorFilter(GREEN);
beaconId.setTextColor(BLACK);
break;
case Beacon.STATUS_INACTIVE:
registrationStatus.setImageResource(R.drawable.ic_action_check_circle);
registrationStatus.setColorFilter(ORANGE);
beaconId.setTextColor(BLACK);
break;
case Beacon.STATUS_DECOMMISSIONED:
registrationStatus.setImageResource(R.drawable.ic_action_highlight_off);
registrationStatus.setColorFilter(RED);
beaconId.setTextColor(GREY);
break;
case Beacon.NOT_AUTHORIZED:
registrationStatus.setImageResource(R.drawable.ic_action_lock);
registrationStatus.setColorFilter(GREY);
beaconId.setTextColor(GREY);
break;
case Beacon.STATUS_UNSPECIFIED:
registrationStatus.setImageResource(R.drawable.ic_action_help);
registrationStatus.setColorFilter(GREY);
beaconId.setTextColor(GREY);
break;
default:
registrationStatus.setImageResource(R.drawable.ic_action_help);
registrationStatus.setColorFilter(BLACK);
beaconId.setTextColor(BLACK);
break;
}
return convertView;
}
}
| 1,215 |
716 |
<reponame>switchII/exhibitor
/*
* Copyright 2012 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 com.netflix.exhibitor.core.rest;
import javax.ws.rs.core.UriInfo;
public interface UITab
{
/**
* Return the tab name
*
* @return name
*/
public String getName();
/**
* Return the content (as text/plain) for the tab
*
* @param info uri context
* @return content
* @throws Exception errors
*/
public String getContent(UriInfo info) throws Exception;
/**
* Return true if the content of this tab is HTML that should be integrated
* into the page (do NOT include <html> tags, etc.). Otherwise it will
* be treated as plain text.
*
* @return true/false
*/
public boolean contentIsHtml();
public UITabType getUITabType();
}
| 495 |
534 |
<filename>src/main/java/mekanism/common/network/to_client/container/PacketUpdateContainer.java
package mekanism.common.network.to_client.container;
import java.util.ArrayList;
import java.util.List;
import mekanism.common.inventory.container.MekanismContainer;
import mekanism.common.network.IMekanismPacket;
import mekanism.common.network.to_client.container.property.PropertyData;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.network.NetworkEvent;
public class PacketUpdateContainer implements IMekanismPacket {
//Note: windowId gets transferred over the network as an unsigned byte
private final short windowId;
private final List<PropertyData> data;
public PacketUpdateContainer(short windowId, List<PropertyData> data) {
this.windowId = windowId;
this.data = data;
}
@Override
public void handle(NetworkEvent.Context context) {
ClientPlayerEntity player = Minecraft.getInstance().player;
//Ensure that the container is one of ours and that the window id is the same as we expect it to be
if (player != null && player.containerMenu instanceof MekanismContainer && player.containerMenu.containerId == windowId) {
//If so then handle the packet
data.forEach(data -> data.handleWindowProperty((MekanismContainer) player.containerMenu));
}
}
@Override
public void encode(PacketBuffer buffer) {
buffer.writeByte(windowId);
buffer.writeVarInt(data.size());
for (PropertyData data : data) {
data.writeToPacket(buffer);
}
}
public static PacketUpdateContainer decode(PacketBuffer buffer) {
short windowId = buffer.readUnsignedByte();
int size = buffer.readVarInt();
List<PropertyData> data = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
PropertyData propertyData = PropertyData.fromBuffer(buffer);
if (propertyData != null) {
data.add(propertyData);
}
}
return new PacketUpdateContainer(windowId, data);
}
}
| 780 |
526 |
/* SPDX-License-Identifier: Apache 2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
/**
* Remediation Governance Action Services that correct errors and enhance metadata elements, relationships and classifications.
*/
package org.odpi.openmetadata.adapters.connectors.governanceactions.remediation;
| 80 |
868 |
<filename>flare/fiber/fiber_local.h
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#ifndef FLARE_FIBER_FIBER_LOCAL_H_
#define FLARE_FIBER_FIBER_LOCAL_H_
#include "flare/base/internal/index_alloc.h"
#include "flare/fiber/detail/fiber_entity.h"
namespace flare {
namespace fiber::detail {
struct FiberLocalIndexTag;
struct TrivialFiberLocalIndexTag;
} // namespace fiber::detail
// `T` needs to be `DefaultConstructible`.
//
// You should normally use this class as static / member variable. In case of
// variable in stack, just use automatic variable (stack variable) instead.
template <class T>
class FiberLocal {
// @sa: Comments in `FiberEntity` for definition of "trivial" here.
inline static constexpr auto is_using_trivial_fls_v =
std::is_trivial_v<T> &&
sizeof(T) <= sizeof(fiber::detail::FiberEntity::trivial_fls_t);
public:
// A dedicated FLS slot is allocated for this `FiberLocal`.
FiberLocal() : slot_index_(GetIndexAlloc()->Next()) {}
// The FLS slot is released on destruction.
~FiberLocal() { GetIndexAlloc()->Free(slot_index_); }
// Accessor.
T* operator->() const noexcept { return get(); }
T& operator*() const noexcept { return *get(); }
T* get() const noexcept { return Get(); }
private:
T* Get() const noexcept {
auto current_fiber = fiber::detail::GetCurrentFiberEntity();
if constexpr (is_using_trivial_fls_v) {
return reinterpret_cast<T*>(current_fiber->GetTrivialFls(slot_index_));
} else {
auto ptr = current_fiber->GetFls(slot_index_);
if (!*ptr) {
*ptr = MakeErased<T>();
}
return static_cast<T*>(ptr->Get());
}
}
static internal::IndexAlloc* GetIndexAlloc() {
if constexpr (is_using_trivial_fls_v) {
return internal::IndexAlloc::For<
fiber::detail::TrivialFiberLocalIndexTag>();
} else {
return internal::IndexAlloc::For<fiber::detail::FiberLocalIndexTag>();
}
}
private:
std::size_t slot_index_;
};
} // namespace flare
#endif // FLARE_FIBER_FIBER_LOCAL_H_
| 915 |
313 |
<gh_stars>100-1000
package com.netflix.titus.federation.service;
import com.google.inject.Provides;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.grpc.protogen.JobActivityHistoryServiceGrpc;
import com.netflix.titus.grpc.protogen.JobActivityHistoryServiceGrpc.JobActivityHistoryServiceStub;
import com.netflix.titus.runtime.connector.GrpcClientConfiguration;
import io.grpc.Channel;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.inject.Named;
import javax.inject.Singleton;
@Configuration
public class JobActivityServiceComponent {
public static final String JOB_ACTIVITY_HISTORY_CHANNEL = "JobActivityHistoryChannel";
@Bean
@Singleton
@Named(JOB_ACTIVITY_HISTORY_CHANNEL)
Channel jobActivityHistoryChannel(GrpcClientConfiguration configuration, TitusRuntime titusRuntime) {
return NettyChannelBuilder.forTarget(configuration.getHostname()).build();
}
@Bean
@Provides
@Singleton
JobActivityHistoryServiceStub jobActivityHistoryClient(final @Named(JOB_ACTIVITY_HISTORY_CHANNEL) Channel channel) {
return JobActivityHistoryServiceGrpc.newStub(channel);
}
}
| 435 |
634 |
<filename>DDrawCompat/v0.2.1/CompatGdiPaintHandlers.cpp<gh_stars>100-1000
#include "CompatGdi.h"
#include "CompatGdiDc.h"
#include "CompatGdiPaintHandlers.h"
#include "CompatGdiScrollBar.h"
#include "CompatGdiScrollFunctions.h"
#include "CompatGdiTitleBar.h"
#include "CompatPrimarySurface.h"
#include "CompatRegistry.h"
#include "DDrawCompat\DDrawLog.h"
#include "Hook.h"
#include "RealPrimarySurface.h"
namespace Compat21
{
namespace
{
LRESULT WINAPI defPaintProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam,
WNDPROC origWndProc, const char* origWndProcName);
LRESULT onEraseBackground(HWND hwnd, HDC dc, WNDPROC origWndProc);
LRESULT onMenuPaint(HWND hwnd, WNDPROC origWndProc);
LRESULT onNcPaint(HWND hwnd, WPARAM wParam, WNDPROC origWndProc);
LRESULT onPaint(HWND hwnd, WNDPROC origWndProc);
LRESULT onPrint(HWND hwnd, UINT msg, HDC dc, LONG flags, WNDPROC origWndProc);
WNDPROC g_origComboListBoxWndProc = nullptr;
WNDPROC g_origEditWndProc = nullptr;
WNDPROC g_origListBoxWndProc = nullptr;
WNDPROC g_origMenuWndProc = nullptr;
WNDPROC g_origScrollBarWndProc = nullptr;
LRESULT WINAPI comboListBoxWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return defPaintProc(hwnd, msg, wParam, lParam, g_origComboListBoxWndProc, "comboListBoxWndProc");
}
LRESULT WINAPI defDlgProcA(HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
return defPaintProc(hdlg, msg, wParam, lParam, CALL_ORIG_FUNC(DefDlgProcA), "defDlgProcA");
}
LRESULT WINAPI defDlgProcW(HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
return defPaintProc(hdlg, msg, wParam, lParam, CALL_ORIG_FUNC(DefDlgProcW), "defDlgProcW");
}
LRESULT WINAPI defPaintProc(
HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam,
WNDPROC origWndProc,
const char* origWndProcName)
{
Compat::LogEnter(origWndProcName, hwnd, msg, wParam, lParam);
LRESULT result = 0;
switch (msg)
{
case WM_ERASEBKGND:
result = onEraseBackground(hwnd, reinterpret_cast<HDC>(wParam), origWndProc);
break;
case WM_NCPAINT:
result = onNcPaint(hwnd, wParam, origWndProc);
break;
case WM_PRINT:
case WM_PRINTCLIENT:
result = onPrint(hwnd, msg, reinterpret_cast<HDC>(wParam), lParam, origWndProc);
break;
default:
result = origWndProc(hwnd, msg, wParam, lParam);
break;
}
Compat::LogLeave(origWndProcName, hwnd, msg, wParam, lParam) << result;
return result;
}
LRESULT WINAPI defWindowProcA(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return defPaintProc(hwnd, msg, wParam, lParam, CALL_ORIG_FUNC(DefWindowProcA), "defWindowProcA");
}
LRESULT WINAPI defWindowProcW(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return defPaintProc(hwnd, msg, wParam, lParam, CALL_ORIG_FUNC(DefWindowProcW), "defWindowProcW");
}
void disableImmersiveContextMenus()
{
// Immersive context menus don't display properly (empty items) when theming is disabled
CompatRegistry::setValue(
HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FlightedFeatures",
"ImmersiveContextMenu",
0);
// An update in Windows 10 seems to have moved the key from the above location
CompatRegistry::setValue(
HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows\\CurrentVersion\\FlightedFeatures",
"ImmersiveContextMenu",
0);
}
LRESULT WINAPI editWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result = defPaintProc(hwnd, msg, wParam, lParam, g_origEditWndProc, "editWndProc");
if (0 == result && (WM_HSCROLL == msg || WM_VSCROLL == msg))
{
CompatGdiScrollFunctions::updateScrolledWindow(hwnd);
}
return result;
}
LRESULT WINAPI listBoxWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return defPaintProc(hwnd, msg, wParam, lParam, g_origListBoxWndProc, "listBoxWndProc");
}
LRESULT WINAPI menuWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
Compat::LogEnter("menuWndProc", hwnd, msg, wParam, lParam);
LRESULT result = 0;
switch (msg)
{
case WM_PAINT:
result = onMenuPaint(hwnd, g_origMenuWndProc);
break;
case 0x1e5:
if (-1 == wParam)
{
// Clearing of selection is not caught by WM_MENUSELECT when mouse leaves menu window
RedrawWindow(hwnd, nullptr, nullptr, RDW_INVALIDATE);
}
// fall through to default
default:
result = g_origMenuWndProc(hwnd, msg, wParam, lParam);
break;
}
Compat::LogLeave("menuWndProc", hwnd, msg, wParam, lParam) << result;
return result;
}
LRESULT onEraseBackground(HWND hwnd, HDC dc, WNDPROC origWndProc)
{
if (!hwnd || !CompatGdi::beginGdiRendering())
{
return origWndProc(hwnd, WM_ERASEBKGND, reinterpret_cast<WPARAM>(dc), 0);
}
LRESULT result = 0;
HDC compatDc = CompatGdiDc::getDc(dc);
if (compatDc)
{
result = origWndProc(hwnd, WM_ERASEBKGND, reinterpret_cast<WPARAM>(compatDc), 0);
CompatGdiDc::releaseDc(dc);
if (result)
{
RealPrimarySurface::disableUpdates();
}
}
else
{
result = origWndProc(hwnd, WM_ERASEBKGND, reinterpret_cast<WPARAM>(dc), 0);
}
CompatGdi::endGdiRendering();
if (result && compatDc)
{
UpdateWindow(hwnd);
RealPrimarySurface::enableUpdates();
}
return result;
}
LRESULT onMenuPaint(HWND hwnd, WNDPROC origWndProc)
{
if (!hwnd || !CompatGdi::beginGdiRendering())
{
return origWndProc(hwnd, WM_PAINT, 0, 0);
}
HDC dc = GetWindowDC(hwnd);
const bool isMenuPaintDc = true;
HDC compatDc = CompatGdiDc::getDc(dc, isMenuPaintDc);
if (compatDc)
{
origWndProc(hwnd, WM_PRINT, reinterpret_cast<WPARAM>(compatDc),
PRF_NONCLIENT | PRF_ERASEBKGND | PRF_CLIENT);
ValidateRect(hwnd, nullptr);
CompatGdiDc::releaseDc(dc);
}
else
{
origWndProc(hwnd, WM_PAINT, 0, 0);
}
ReleaseDC(hwnd, dc);
CompatGdi::endGdiRendering();
return 0;
}
LRESULT onNcPaint(HWND hwnd, WPARAM wParam, WNDPROC origWndProc)
{
if (!hwnd || !CompatGdi::beginGdiRendering())
{
return origWndProc(hwnd, WM_NCPAINT, wParam, 0);
}
HDC windowDc = GetWindowDC(hwnd);
HDC compatDc = CompatGdiDc::getDc(windowDc);
if (compatDc)
{
CompatGdi::TitleBar titleBar(hwnd, compatDc);
titleBar.drawAll();
titleBar.excludeFromClipRegion();
CompatGdi::ScrollBar scrollBar(hwnd, compatDc);
scrollBar.drawAll();
scrollBar.excludeFromClipRegion();
SendMessage(hwnd, WM_PRINT, reinterpret_cast<WPARAM>(compatDc), PRF_NONCLIENT);
CompatGdiDc::releaseDc(windowDc);
}
ReleaseDC(hwnd, windowDc);
CompatGdi::endGdiRendering();
return 0;
}
LRESULT onPaint(HWND hwnd, WNDPROC origWndProc)
{
if (!hwnd || !CompatGdi::beginGdiRendering())
{
return origWndProc(hwnd, WM_PAINT, 0, 0);
}
PAINTSTRUCT paint = {};
HDC dc = BeginPaint(hwnd, &paint);
HDC compatDc = CompatGdiDc::getDc(dc);
if (compatDc)
{
origWndProc(hwnd, WM_PRINTCLIENT, reinterpret_cast<WPARAM>(compatDc), PRF_CLIENT);
CompatGdiDc::releaseDc(dc);
}
else
{
origWndProc(hwnd, WM_PRINTCLIENT, reinterpret_cast<WPARAM>(dc), PRF_CLIENT);
}
EndPaint(hwnd, &paint);
CompatGdi::endGdiRendering();
return 0;
}
LRESULT onPrint(HWND hwnd, UINT msg, HDC dc, LONG flags, WNDPROC origWndProc)
{
if (!CompatGdi::beginGdiRendering())
{
return origWndProc(hwnd, msg, reinterpret_cast<WPARAM>(dc), flags);
}
LRESULT result = 0;
HDC compatDc = CompatGdiDc::getDc(dc);
if (compatDc)
{
result = origWndProc(hwnd, msg, reinterpret_cast<WPARAM>(compatDc), flags);
CompatGdiDc::releaseDc(dc);
}
else
{
result = origWndProc(hwnd, msg, reinterpret_cast<WPARAM>(dc), flags);
}
CompatGdi::endGdiRendering();
return result;
}
LRESULT WINAPI scrollBarWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
Compat::LogEnter("scrollBarWndProc", hwnd, msg, wParam, lParam);
LRESULT result = 0;
switch (msg)
{
case WM_PAINT:
result = onPaint(hwnd, g_origScrollBarWndProc);
break;
case WM_SETCURSOR:
if (GetWindowLong(hwnd, GWL_STYLE) & (SBS_SIZEBOX | SBS_SIZEGRIP))
{
SetCursor(LoadCursor(nullptr, IDC_SIZENWSE));
}
result = TRUE;
break;
default:
result = g_origScrollBarWndProc(hwnd, msg, wParam, lParam);
break;
}
Compat::LogLeave("scrollBarWndProc", hwnd, msg, wParam, lParam) << result;
return result;
}
}
namespace CompatGdiPaintHandlers
{
void installHooks()
{
disableImmersiveContextMenus();
CompatGdi::hookWndProc("ComboLBox", g_origComboListBoxWndProc, &comboListBoxWndProc);
CompatGdi::hookWndProc("Edit", g_origEditWndProc, &editWndProc);
CompatGdi::hookWndProc("ListBox", g_origListBoxWndProc, &listBoxWndProc);
CompatGdi::hookWndProc("#32768", g_origMenuWndProc, &menuWndProc);
CompatGdi::hookWndProc("ScrollBar", g_origScrollBarWndProc, &scrollBarWndProc);
HOOK_FUNCTION(user32, DefWindowProcA, defWindowProcA);
HOOK_FUNCTION(user32, DefWindowProcW, defWindowProcW);
HOOK_FUNCTION(user32, DefDlgProcA, defDlgProcA);
HOOK_FUNCTION(user32, DefDlgProcW, defDlgProcW);
}
void uninstallHooks()
{
CompatGdi::unhookWndProc("ComboLBox", g_origComboListBoxWndProc);
CompatGdi::unhookWndProc("Edit", g_origEditWndProc);
CompatGdi::unhookWndProc("ListBox", g_origListBoxWndProc);
CompatGdi::unhookWndProc("#32768", g_origMenuWndProc);
CompatGdi::unhookWndProc("ScrollBar", g_origScrollBarWndProc);
}
}
}
| 4,562 |
1,130 |
<gh_stars>1000+
import os
import pandas as pd
import panel as pn
from .pn_model import StockScreener
def app(doc):
data_path = os.path.join(os.path.dirname(__file__), 'datasets/market_data.csv')
df = pd.read_csv(data_path, index_col=0, parse_dates=True)
ss = StockScreener(df)
ss.panel().server_doc(doc)
| 136 |
819 |
from .resnet import ResNet50, ResNet101, ResNet152
from .alexnet import AlexNet
| 26 |
1,666 |
<gh_stars>1000+
package org.grobid.core.document;
/**
* General debugging counters
*/
public enum TEICounters {
CITATION_FIGURE_REF_MARKER_MISSED_SUBSTITUTION, TEI_POSITION_REF_MARKERS_OFFSET_TOO_LARGE, TEI_POSITION_REF_MARKERS_TOK_NOT_FOUND, CITATION_FIGURE_REF_MARKER_SUBSTITUTED
}
| 126 |
764 |
{
"website": "http://aelf.io/",
"published_on": "2017-11-28",
"links": {
"telegram": "https://t.me/aelfblockchain",
"reddit": "https://www.reddit.com/user/aelf_blockchain/",
"github": "https://github.com/aelfProject",
"facebook": "https://www.facebook.com/grid.blockchain.1",
"twitter": "https://twitter.com/aelfblockchain"
},
"overview": {
"en": "Decentralized Cloud Computing Blockchain Network.",
"zh": "去中心化云计算区块链网络。"
},
"symbol": "ELF",
"initial_price": {
"ETH": "0.00022 ETH",
"USD": "0.099 USD"
},
"whitepaper": "https://grid.hoopox.com/%C3%A6lf_whitepaper_v1.2.pdf",
"address": "0xbf2179859fc6D5BEE9Bf9158632Dc51678a4100e",
"email": "<EMAIL>"
}
| 401 |
435 |
<reponame>allen91wu/data<gh_stars>100-1000
{
"description": "Cleaning messy data is a necessary component of data science projects.\nThe vtreat package automates common data preparation steps for\nsupervised machine learning. In this talk, we will introduce vtreat and\ndemonstrate its effective use with Pandas and xgboost on real-world\ndata.\n\nData characterization, treatment, and cleaning are necessary (though not\nalways glamorous) components of machine learning and data science\nprojects. While there is no substitute for getting your hands dirty in\nthe data, there are many data issues that repeat from project to\nproject. In particular, there are pitfalls in properly dealing with\nmissing data values, previously unobserved categorical values, and\nhigh-cardinality categorical variables.\n\nIn this talk, we will discuss using the vtreat package to prepare data\nfor supervised machine learning. We will demonstrate vtreat on a\nreal-world data set, with xgboost and Pandas. Vtreat automates the\nstatistically sound treatment of common data problems, leaving the data\nscientist free to concentrate on problem-specific data and modeling\nissues.\n",
"duration": 1938,
"language": "eng",
"published_at": "2019-12-23T21:05:16.000Z",
"recorded": "2019-12-05",
"speakers": [
"<NAME>",
"<NAME>"
],
"thumbnail_url": "https://i.ytimg.com/vi/qMCQFjEV90k/hqdefault.jpg",
"title": "Preparing messy data for supervised learning with vtreat",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=qMCQFjEV90k"
}
]
}
| 476 |
527 |
import logging
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.dispatch import receiver
from django.db.models import signals
from drfpasswordless.models import CallbackToken
from drfpasswordless.models import generate_numeric_token
from drfpasswordless.settings import api_settings
from drfpasswordless.services import TokenService
logger = logging.getLogger(__name__)
@receiver(signals.post_save, sender=CallbackToken)
def invalidate_previous_tokens(sender, instance, created, **kwargs):
"""
Invalidates all previously issued tokens of that type when a new one is created, used, or anything like that.
"""
if instance.user.pk in api_settings.PASSWORDLESS_DEMO_USERS.keys():
return
if isinstance(instance, CallbackToken):
CallbackToken.objects.active().filter(user=instance.user, type=instance.type).exclude(id=instance.id).update(is_active=False)
@receiver(signals.pre_save, sender=CallbackToken)
def check_unique_tokens(sender, instance, **kwargs):
"""
Ensures that mobile and email tokens are unique or tries once more to generate.
Note that here we've decided keys are unique even across auth and validation.
We could consider relaxing this in the future as well by filtering on the instance.type.
"""
if instance._state.adding:
# save is called on a token to create it in the db
# before creating check whether a token with the same key exists
if isinstance(instance, CallbackToken):
unique = False
tries = 0
if CallbackToken.objects.filter(key=instance.key, is_active=True).exists():
# Try N(default=3) times before giving up.
while tries < api_settings.PASSWORDLESS_TOKEN_GENERATION_ATTEMPTS:
tries = tries + 1
new_key = generate_numeric_token()
instance.key = new_key
if not CallbackToken.objects.filter(key=instance.key, is_active=True).exists():
# Leave the loop if we found a valid token that doesn't exist yet.
unique = True
break
if not unique:
# A unique value wasn't found after three tries
raise ValidationError("Couldn't create a unique token even after retrying.")
else:
# A unique value was found immediately.
pass
else:
# save is called on an already existing token to update it. Such as invalidating it.
# in that case there is no need to check for the key. This way we both avoid an unneccessary db hit
# and avoid to change key field of used tokens.
pass
User = get_user_model()
@receiver(signals.pre_save, sender=User)
def update_alias_verification(sender, instance, **kwargs):
"""
Flags a user's email as unverified if they change it.
Optionally sends a verification token to the new endpoint.
"""
if isinstance(instance, User):
if instance.id:
if api_settings.PASSWORDLESS_USER_MARK_EMAIL_VERIFIED is True:
"""
For marking email aliases as not verified when a user changes it.
"""
email_field = api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME
email_verified_field = api_settings.PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME
# Verify that this is an existing instance and not a new one.
try:
user_old = User.objects.get(id=instance.id) # Pre-save object
instance_email = getattr(instance, email_field) # Incoming Email
old_email = getattr(user_old, email_field) # Pre-save object email
if instance_email != old_email and instance_email != "" and instance_email is not None:
# Email changed, verification should be flagged
setattr(instance, email_verified_field, False)
if api_settings.PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN is True:
email_subject = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_SUBJECT
email_plaintext = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_PLAINTEXT_MESSAGE
email_html = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_TOKEN_HTML_TEMPLATE_NAME
message_payload = {'email_subject': email_subject,
'email_plaintext': email_plaintext,
'email_html': email_html}
success = TokenService.send_token(instance, 'email', CallbackToken.TOKEN_TYPE_VERIFY, **message_payload)
if success:
logger.info('drfpasswordless: Successfully sent email on updated address: %s'
% instance_email)
else:
logger.info('drfpasswordless: Failed to send email to updated address: %s'
% instance_email)
except User.DoesNotExist:
# User probably is just initially being created
return
if api_settings.PASSWORDLESS_USER_MARK_MOBILE_VERIFIED is True:
"""
For marking mobile aliases as not verified when a user changes it.
"""
mobile_field = api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME
mobile_verified_field = api_settings.PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME
# Verify that this is an existing instance and not a new one.
try:
user_old = User.objects.get(id=instance.id) # Pre-save object
instance_mobile = getattr(instance, mobile_field) # Incoming mobile
old_mobile = getattr(user_old, mobile_field) # Pre-save object mobile
if instance_mobile != old_mobile and instance_mobile != "" and instance_mobile is not None:
# Mobile changed, verification should be flagged
setattr(instance, mobile_verified_field, False)
if api_settings.PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN is True:
mobile_message = api_settings.PASSWORDLESS_MOBILE_MESSAGE
message_payload = {'mobile_message': mobile_message}
success = TokenService.send_token(instance, 'mobile', CallbackToken.TOKEN_TYPE_VERIFY, **message_payload)
if success:
logger.info('drfpasswordless: Successfully sent SMS on updated mobile: %s'
% instance_mobile)
else:
logger.info('drfpasswordless: Failed to send SMS to updated mobile: %s'
% instance_mobile)
except User.DoesNotExist:
# User probably is just initially being created
pass
| 3,444 |
777 |
#!/usr/bin/env python
# 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.
"""Logging handler used to log into a JSON file."""
import json
import logging
class JSONLoggingHandler(logging.Handler):
"""A logging handler that forwards log messages into a JSON file."""
def __init__(self, json_file):
logging.Handler.__init__(self)
formatter = logging.Formatter('%(name)s:%(message)s')
self.setFormatter(formatter)
self.json_file_ = json_file
self.log_messages_ = []
def close(self):
"""Dump the list of log messages into the JSON file."""
with open(self.json_file_, 'w') as f:
f.write(json.dumps(self.log_messages_))
logging.Handler.close(self)
def emit(self, record):
"""Append the record to list of messages."""
self.log_messages_.append({record.levelname: self.format(record)})
| 321 |
562 |
#include <g3log/g3log.hpp>
#include <g3log/logworker.hpp>
#include <iostream>
int main()
{
auto worker = g3::LogWorker::createLogWorker();
auto defaultHandler = worker->addDefaultLogger("my_log", ".");
g3::initializeLogging(worker.get());
LOG(INFO) << "Make a log call";
return 0;
}
| 125 |
1,264 |
<reponame>danielhanchen/hiperlearn
from numba import njit, prange
from numpy import zeros
"""
TCSR Matrix functions.
1. _XXT
"""
def _XXT_triangular(val, colPointer, rowIndices, n, p):
"""
[Added 21/10/2018]
Computes XXT and stores it as a triangular sparse matrix.
A triangular sparse matrix removes the colPointer and rowIndices
since the TCSR format assumes each element is in sucession.
This cuts memory total memory usage of the full dense matrix by 1/2
[actually 1/2n^2 - n is used].
"""
size = n*(n-1) // 2 # floor division
D = zeros(size, dtype = val.dtype)
P = zeros(p, dtype = val.dtype)
for k in prange(n-1):
l = rowIndices[k]
r = rowIndices[k+1]
A = P.copy()
b = l
for i in range(r-l):
x = colPointer[b]
A[x] = val[b]
b += 1
for j in prange(k+1, n):
l = rowIndices[j]
r = rowIndices[j+1]
s = 0
c = l
for a in range(r-l):
z = colPointer[c]
v = A[z]
if v != 0:
s += v*val[c]
c += 1
# Exact position in CSR is found via j(j-1)/2 + k
D_where = j*(j-1) // 2 + k
D[D_where] = s
return D
_XXT_triangular_single = njit(_XXT_triangular, fastmath = True, nogil = True, cache = True)
_XXT_triangular_parallel = njit(_XXT_triangular, fastmath = True, nogil = True, parallel = True)
def _XXT(val, colPointer, rowIndices, n, p, n_jobs = 1):
"""
[Added 16/10/2018]
Computes X @ XT very quickly, and stores it in a modified CSR matrix (Triangular CSR).
Uses 1/2n^2 - n memory, and thus much more efficient and space conversing than if
using a full CSR Matrix (memory reduced by approx 25 - 50%).
"""
XXT = _XXT_triangular_parallel(val, colPointer, rowIndices, n, p) if n_jobs != 1 else \
_XXT_triangular_single(val, colPointer, rowIndices, n, p)
return XXT
| 757 |
7,302 |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB 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.
#
from __future__ import annotations
import textwrap
from ..common import qname as qn
from ..common import quote_literal as ql
from . import base
from . import ddl
class View(base.DBObject):
def __init__(self, name, query):
super().__init__()
self.name = name
self.query = query
def get_type(self) -> str:
return "VIEW"
def get_id(self):
return qn(*self.name)
class CreateView(ddl.SchemaObjectOperation):
def __init__(
self,
view,
*,
conditions=None,
neg_conditions=None,
or_replace=False,
):
super().__init__(view.name, conditions=conditions,
neg_conditions=neg_conditions)
self.view = view
self.or_replace = or_replace
def code(self, block: base.PLBlock) -> str:
query = textwrap.indent(textwrap.dedent(self.view.query), ' ')
return (
f'CREATE {"OR REPLACE" if self.or_replace else ""}'
f' VIEW {qn(*self.view.name)} AS\n{query}'
)
class DropView(ddl.SchemaObjectOperation):
def code(self, block: base.PLBlock) -> str:
return f'DROP VIEW {qn(*self.name)}'
class ViewExists(base.Condition):
def __init__(self, name):
self.name = name
def code(self, block: base.PLBlock) -> str:
return textwrap.dedent(f'''\
SELECT
viewname
FROM
pg_catalog.pg_views
WHERE
schemaname = {ql(self.name[0])}
AND viewname = {ql(self.name[1])}
''')
| 950 |
691 |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import division
from __future__ import print_function
import argparse
import json
import os
import tensorflow as tf
from tensorflow.contrib.learn import Estimator, Experiment
from tensorflow.contrib.learn.python.learn import learn_runner
import model
import util
tf.logging.set_verbosity(tf.logging.INFO)
def make_experiment_fn(args):
train_input_fn = util.make_input_fn(
args.train_data_file,
args.batch_size,
args.num_skips,
args.skip_window,
args.vocab_size,
num_epochs=args.num_epochs
)
eval_input_fn = util.make_input_fn(
args.eval_data_file,
args.batch_size,
args.num_skips,
args.skip_window,
args.vocab_size,
num_epochs=args.num_epochs
)
def experiment_fn(output_dir):
return Experiment(
Estimator(
model_fn=model.make_model_fn(**args.__dict__),
model_dir=output_dir
),
train_input_fn=train_input_fn,
eval_input_fn=eval_input_fn,
continuous_eval_throttle_secs=args.min_eval_seconds,
min_eval_frequency=args.min_train_eval_rate,
# Until Experiment moves to train_and_evaluate call internally
local_eval_frequency=args.min_train_eval_rate
)
return experiment_fn
def model_args(parser):
group = parser.add_argument_group(title='Model Arguments')
group.add_argument('--reference-words', nargs='*', type=str)
group.add_argument('--num-partitions', default=1, type=int)
group.add_argument('--embedding-size', default=128, type=int)
group.add_argument('--vocab-size', default=2 ** 15, type=int)
group.add_argument('--num-sim', default=8, type=int)
group.add_argument('--num-sampled', default=64, type=int)
group.add_argument('--num-skips', default=4, type=int)
group.add_argument('--skip-window', default=8, type=int)
group.add_argument('--learning-rate', default=0.1, type=float)
group.add_argument(
'--vocab-file',
required=True,
help='Path to a TSV file containing the vocab index'
)
return group
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--train-data-file',
help='Binary files for training',
type=str
)
parser.add_argument(
'--output-path',
help='GCS path to output files',
required=True
)
parser.add_argument(
'--eval-data-file',
help='Binary files for evaluation',
type=str
)
parser.add_argument(
'--batch-size',
help="""\
Batch size for skipgrams. Note that batch size may be approximate.
Actual batch_size is (batch_size // num_skips) * num_skips.\
""",
type=int,
default=512
)
parser.add_argument(
'--num-epochs',
help='Number of epochs for training',
type=int,
default=1
)
parser.add_argument(
'--min-eval-seconds',
type=float,
default=5,
help="""\
Minimal interval between calculating evaluation metrics and saving
evaluation summaries.\
"""
)
parser.add_argument(
'--min-train-eval-rate',
type=int,
default=20,
help="""\
Minimal train / eval time ratio on master:
The number of steps between evaluations
"""
)
model_args(parser)
args = parser.parse_args()
# Extend output path with trial ID if it exists
args.output_path = os.path.join(
args.output_path,
json.loads(
os.environ.get('TF_CONFIG', '{}')
).get('task', {}).get('trial', '')
)
learn_runner.run(make_experiment_fn(args), args.output_path)
| 1,638 |
1,296 |
<reponame>sishui/nova-ejoy2d
#include "ppm.h"
#include "texture.h"
#include "array.h"
#include "render.h"
#include <lua.h>
#include <lauxlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PPM_RGBA8 0
#define PPM_RGB8 1
#define PPM_RGBA4 2
#define PPM_RGB4 3
#define PPM_ALPHA8 4
#define PPM_ALPHA4 5
struct ppm {
int type;
int depth;
int step;
int width;
int height;
uint8_t *buffer;
};
#define LINEMAX 128
static char *
readline(FILE *f, char *buffer) {
for (;;) {
char * ret = fgets(buffer, LINEMAX, f);
if (ret == NULL) {
return NULL;
}
if (ret[0] != '#') {
return ret;
}
}
}
static int
ppm_header(FILE *f, struct ppm *ppm) {
char tmp[LINEMAX];
char *line = readline(f, tmp);
if (line == NULL)
return 0;
char c = 0;
sscanf(line, "P%c", &c);
ppm->type = c;
line = readline(f, tmp);
if (line == NULL)
return 0;
sscanf(line, "%d %d", &(ppm->width), &(ppm->height));
line = readline(f, tmp);
if (line == NULL)
return 0;
sscanf(line, "%d", &(ppm->depth));
return 1;
}
static int
ppm_data(struct ppm *ppm, FILE *f, int id, int skip) {
int i;
int n = ppm->width * ppm->height;
uint8_t * buffer = ppm->buffer + skip;
uint8_t * tmp;
int step = ppm->step;
switch(id) {
case '3': // RGB text
for (i=0;i<n;i++) {
int r,g,b;
fscanf(f, "%d %d %d", &r,&g,&b);
buffer[i*step+0] = (uint8_t)r;
buffer[i*step+1] = (uint8_t)g;
buffer[i*step+2] = (uint8_t)b;
}
break;
case '2': // ALPHA text
for (i=0;i<n;i++) {
int alpha;
fscanf(f, "%d", &alpha);
buffer[i*step] = (uint8_t)alpha;
}
break;
case '6': // RGB binary
tmp = (uint8_t *)malloc(n * 3);
if (fread(tmp, n*3, 1, f)==0) {
free(tmp);
return 0;
}
for (i=0;i<n;i++) {
buffer[i*step+0] = tmp[i*3+0];
buffer[i*step+1] = tmp[i*3+1];
buffer[i*step+2] = tmp[i*3+2];
}
free(tmp);
break;
case '5': // ALPHA binary
tmp = (uint8_t *)malloc(n);
if (fread(tmp, n, 1, f)==0) {
free(tmp);
return 0;
}
for (i=0;i<n;i++) {
buffer[i*step] = tmp[i];
}
free(tmp);
break;
default:
return 0;
}
return 1;
}
static int
loadppm_from_file(FILE *rgb, FILE *alpha, struct ppm *ppm) {
ppm->buffer = NULL;
ppm->step = 0;
int rgb_id = 0;
int alpha_id = 0;
if (rgb) {
if (!ppm_header(rgb, ppm)) {
return 0;
}
rgb_id = ppm->type;
ppm->step += 3;
}
if (alpha) {
if (rgb == NULL) {
if (!ppm_header(alpha, ppm)) {
return 0;
}
alpha_id = ppm->type;
} else {
struct ppm pgm;
if (!ppm_header(alpha, &pgm)) {
return 0;
}
if (ppm->depth != pgm.depth || ppm->width != pgm.width || ppm->height != pgm.height) {
return 0;
}
alpha_id = pgm.type;
}
ppm->step += 1;
}
ppm->buffer = (uint8_t *)malloc(ppm->height * ppm->width * ppm->step);
if (rgb) {
if (!ppm_data(ppm, rgb, rgb_id, 0))
return 0;
}
if (alpha) {
int skip = 0;
if (rgb) {
skip = 3;
}
if (!ppm_data(ppm, alpha, alpha_id, skip))
return 0;
}
return 1;
}
static int
loadppm(lua_State *L) {
size_t sz = 0;
const char * filename = luaL_checklstring(L, 1, &sz);
ARRAY(char, tmp, sz+5);
sprintf(tmp, "%s.ppm", filename);
FILE *rgb = fopen(tmp, "rb");
sprintf(tmp, "%s.pgm", filename);
FILE *alpha = fopen(tmp, "rb");
if (rgb == NULL && alpha == NULL) {
return luaL_error(L, "Can't open %s(.ppm/.pgm)", filename);
}
struct ppm ppm;
int ok = loadppm_from_file(rgb, alpha, &ppm);
if (rgb) {
fclose(rgb);
}
if (alpha) {
fclose(alpha);
}
if (!ok) {
if (ppm.buffer) {
free(ppm.buffer);
}
luaL_error(L, "Invalid file %s", filename);
}
if (ppm.depth == 255) {
if (ppm.step == 4) {
lua_pushliteral(L, "RGBA8");
} else if (ppm.step == 3) {
lua_pushliteral(L, "RGB8");
} else {
lua_pushliteral(L, "ALPHA8");
}
} else {
if (ppm.step == 4) {
lua_pushliteral(L, "RGBA4");
} else if (ppm.step == 3) {
lua_pushliteral(L, "RGB4");
} else {
lua_pushliteral(L, "ALPHA4");
}
}
lua_pushinteger(L, ppm.width);
lua_pushinteger(L, ppm.height);
int n = ppm.width * ppm.height * ppm.step;
lua_createtable(L, n, 0);
int i;
for (i=0;i<n;i++) {
lua_pushinteger(L, ppm.buffer[i]);
lua_rawseti(L, -2, i+1);
}
free(ppm.buffer);
return 4;
}
static int
loadtexture(lua_State *L) {
int id = (int)luaL_checkinteger(L,1);
size_t sz = 0;
const char * filename = luaL_checklstring(L, 2, &sz);
ARRAY(char, tmp, sz + 5);
sprintf(tmp, "%s.ppm", filename);
FILE *rgb = fopen(tmp, "rb");
sprintf(tmp, "%s.pgm", filename);
FILE *alpha = fopen(tmp, "rb");
if (rgb == NULL && alpha == NULL) {
return luaL_error(L, "Can't open %s(.ppm/.pgm)", filename);
}
struct ppm ppm;
int ok = loadppm_from_file(rgb, alpha, &ppm);
if (rgb) {
fclose(rgb);
}
if (alpha) {
fclose(alpha);
}
if (!ok) {
if (ppm.buffer) {
free(ppm.buffer);
}
luaL_error(L, "Invalid file %s", filename);
}
int type = 0;
if (ppm.depth == 255) {
if (ppm.step == 4) {
type = TEXTURE_RGBA8;
} else if (ppm.step == 3) {
type = TEXTURE_RGB;
} else {
type = TEXTURE_A8;
}
} else {
if (ppm.step == 4) {
type = TEXTURE_RGBA8;
uint16_t * tmp = (uint16_t * )malloc(ppm.width * ppm.height * sizeof(uint16_t));
int i;
for (i=0;i<ppm.width * ppm.height;i++) {
uint32_t r = ppm.buffer[i*4+0];
uint32_t g = ppm.buffer[i*4+1];
uint32_t b = ppm.buffer[i*4+2];
uint32_t a = ppm.buffer[i*4+3];
tmp[i] = r << 12 | g << 8 | b << 4 | a;
}
free(ppm.buffer);
ppm.buffer = (uint8_t*)tmp;
} else if (ppm.step == 3) {
type = TEXTURE_RGB565;
uint16_t * tmp = (uint16_t *)malloc(ppm.width * ppm.height * sizeof(uint16_t));
int i;
for (i=0;i<ppm.width * ppm.height;i++) {
uint32_t r = ppm.buffer[i*3+0];
if (r == 15) {
r = 31;
} else {
r <<= 1;
}
uint32_t g = ppm.buffer[i*3+1];
if (g == 15) {
g = 63;
} else {
g <<= 2;
}
uint32_t b = ppm.buffer[i*3+2];
if (b == 15) {
b = 31;
} else {
b <<= 1;
}
tmp[i] = r << 11 | g << 5 | b;
}
free(ppm.buffer);
ppm.buffer = (uint8_t*)tmp;
} else {
type = TEXTURE_RGBA8;
int i;
for (i=0;i<ppm.width * ppm.height;i++) {
uint8_t c = ppm.buffer[i];
if (c == 15) {
ppm.buffer[i] = 255;
} else {
ppm.buffer[i] *= 16;
}
}
}
}
const char * err = texture_load(id, (enum TEXTURE_FORMAT)type, ppm.width, ppm.height, ppm.buffer, lua_toboolean(L, 3));
free(ppm.buffer);
if (err) {
return luaL_error(L, "%s", err);
}
return 0;
}
static void
ppm_type(lua_State *L, const char * format, struct ppm *ppm) {
if (strcmp(format, "RGBA8")==0) {
ppm->type = PPM_RGBA8;
ppm->depth = 255;
ppm->step = 4;
} else if (strcmp(format, "RGB8")==0) {
ppm->type = PPM_RGB8;
ppm->depth = 255;
ppm->step = 3;
} else if (strcmp(format, "RGBA4")==0) {
ppm->type = PPM_RGBA4;
ppm->depth = 15;
ppm->step = 4;
} else if (strcmp(format, "RGB4")==0) {
ppm->type = PPM_RGB4;
ppm->depth = 15;
ppm->step = 3;
} else if (strcmp(format, "ALPHA8")==0) {
ppm->type = PPM_ALPHA8;
ppm->depth = 255;
ppm->step = 1;
} else if (strcmp(format, "ALPHA4")==0) {
ppm->type = PPM_ALPHA4;
ppm->depth = 15;
ppm->step = 1;
} else {
luaL_error(L, "Invalid ppm format %s, only support RGBA8 RGBA4 RGB8 RGB4 ALPHA8 ALPHA4", format);
}
}
/*
string filename (without ext)
type : RGBA8 RGB8 RGBA4 RGBA4 ALPHA8 ALPHA4
integer width
integer height
table data
*/
static void
save_rgb(lua_State *L, int step, int depth) {
size_t sz = 0;
const char * filename = lua_tolstring(L, 1, &sz);
ARRAY(char, tmp, sz + 5);
int width = (int)lua_tointeger(L, 3);
int height = (int)lua_tointeger(L, 4);
sprintf(tmp, "%s.ppm", filename);
FILE *f = fopen(tmp,"wb");
if (f == NULL) {
luaL_error(L, "Can't write to %s", tmp);
}
fprintf(f,
"P6\n"
"%d %d\n"
"%d\n"
, width, height, depth);
int i;
uint8_t *buffer = (uint8_t *)malloc(width * height * 3);
for (i=0;i<width * height;i++) {
lua_rawgeti(L, 5, i*step+1);
lua_rawgeti(L, 5, i*step+2);
lua_rawgeti(L, 5, i*step+3);
buffer[i*3+0] = (uint8_t)lua_tointeger(L, -3);
buffer[i*3+1] =(uint8_t)lua_tointeger(L, -2);
buffer[i*3+2] =(uint8_t)lua_tointeger(L, -1);
lua_pop(L,3);
}
int wn = fwrite(buffer, width * height * 3,1,f);
free(buffer);
fclose(f);
if (wn != 1) {
luaL_error(L, "Write to %s failed", tmp);
}
}
static void
save_alpha(lua_State *L, int step, int depth, int offset) {
size_t sz = 0;
const char * filename = lua_tolstring(L, 1, &sz);
ARRAY(char, tmp, sz + 5);
int width = (int)lua_tointeger(L, 3);
int height = (int)lua_tointeger(L, 4);
sprintf(tmp, "%s.pgm", filename);
FILE *f = fopen(tmp,"wb");
if (f == NULL) {
luaL_error(L, "Can't write to %s", tmp);
}
fprintf(f,
"P5\n"
"%d %d\n"
"%d\n"
, width, height, depth);
int i;
uint8_t *buffer = (uint8_t *)malloc(width * height);
for (i=0;i<width * height;i++) {
lua_rawgeti(L, 5, i*step+1+offset);
buffer[i] = (uint8_t)lua_tointeger(L, -1);
lua_pop(L,1);
}
int wn = fwrite(buffer, width * height,1,f);
free(buffer);
fclose(f);
if (wn != 1) {
luaL_error(L, "Write to %s failed", tmp);
}
}
static int
saveppm(lua_State *L) {
struct ppm ppm;
luaL_checktype(L,1,LUA_TSTRING);
ppm_type(L, luaL_checkstring(L, 2), &ppm);
ppm.width = (int)luaL_checkinteger(L, 3);
ppm.height = (int)luaL_checkinteger(L, 4);
luaL_checktype(L, 5, LUA_TTABLE);
int n = (int)lua_rawlen(L,5);
if (n != ppm.width * ppm.height * ppm.step) {
return luaL_error(L, "Data number %d invalid , should be %d * %d * %d = %d", n, ppm.width, ppm.height, ppm.step, ppm.width * ppm.height * ppm.step);
}
if (ppm.type != PPM_ALPHA8 && ppm.type != PPM_ALPHA4) {
save_rgb(L, ppm.step, ppm.depth);
}
if (ppm.type != PPM_RGB8 && ppm.type != PPM_RGB4) {
int offset = 3;
if (ppm.type == PPM_ALPHA8 || ppm.type == PPM_ALPHA4) {
offset = 0;
}
save_alpha(L, ppm.step, ppm.depth, offset);
}
return 0;
}
static int
unload_tex(struct lua_State* L)
{
int id = (int) luaL_checkinteger(L, 1);
texture_unload(id);
return 0;
}
int
ejoy2d_ppm(lua_State *L) {
luaL_Reg l[] = {
{ "texture", loadtexture },
{ "load", loadppm },
{ "save", saveppm },
{ "unload",unload_tex},
{ NULL, NULL },
};
luaL_newlib(L,l);
return 1;
}
| 5,224 |
478 |
{
"name": "tstl",
"description": "TypeScript-STL (Standard Template Library, migrated from C++)",
"author": {
"name": "<NAME>",
"email": "<EMAIL>",
"url": "http://samchon.org"
},
"version": "2.5.0",
"main": "./index.js",
"typings": "./index.d.ts",
"scripts": {
"api": "typedoc src --exclude \"**/+(test|benchmark)/**\" --excludeNotDocumented --plugin typedoc-plugin-external-module-name --plugin typedoc-plugin-exclude-references --out ../tstl@gh-pages/api",
"migration": "ts-node build/migration",
"benchmark": "node benchmark",
"build": "npm run clean && npm run module && npm run compile && npm run test",
"clean": "ts-node build/clean",
"compile": "tsc",
"dev": "tsc --watch",
"dev:ts": "tsc --watch --noEmit --module esnext",
"module": "tsc --noEmit --module amd && tsc --noEmit --module system && tsc --noEmit --module umd && tsc --noEmit --module esnext",
"package": "npm run build && ts-node build/dist && cd dist && npm publish",
"package:next": "npm run package -- --tag next",
"test": "node dist/test",
"test:ts": "ts-node src/test"
},
"devDependencies": {
"@types/cli": "^0.11.19",
"@types/node": "^14.6.3",
"cli": "^1.0.1",
"rimraf": "^3.0.2",
"source-map-support": "^0.5.19",
"ts-node": "^9.0.0",
"typedoc": "^0.19.0",
"typedoc-plugin-exclude-references": "1.0.0",
"typedoc-plugin-external-module-name": "^4.0.3",
"typescript": "^4.0.3"
},
"homepage": "https://github.com/samchon/tstl",
"repository": {
"type": "git",
"url": "https://github.com/samchon/tstl"
},
"bugs": {
"url": "https://github.com/samchon/tstl/issues"
},
"license": "MIT",
"keywords": [
"tstl",
"typecript",
"c++",
"cpp",
"stl",
"standard template library",
"algorithm",
"container",
"exception",
"functional",
"iterator",
"numeric",
"ranges",
"thread",
"utility",
"base",
"experimental",
"internal",
"Vector",
"Deque",
"List",
"VectorBoolean",
"ForwardList",
"Stack",
"Queue",
"PriorityQueue",
"FlatMap",
"FlatMultiMap",
"FlatMultiSet",
"FlatSet",
"HashMap",
"HashMultiMap",
"HashMultiSet",
"HashSet",
"TreeMap",
"TreeMultiMap",
"TreeMultiSet",
"TreeSet",
"ConditionVariable",
"Semaphore",
"Latch",
"Barrier",
"FlexBarrier",
"Mutex",
"TimedMutex",
"SharedMutex",
"SharedTimedMutex",
"SharedLock",
"UniqueLock"
]
}
| 1,159 |
302 |
/*
* Copyright 2012 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 com.netflix.blitz4j;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
/**
* A Category factory that overrides log4j to provide a less contended
* implementation.
*
* @author <NAME>
*
*/
public class NFCategoryFactory implements LoggerFactory {
public NFCategoryFactory() {
}
/*
* (non-Javadoc)
*
* @see
* org.apache.log4j.spi.LoggerFactory#makeNewLoggerInstance(java.lang.String
* )
*/
@Override
public Logger makeNewLoggerInstance(String name) {
return new NFLockFreeLogger(name);
}
}
| 415 |
848 |
<gh_stars>100-1000
#include <fstream>
#include <iostream>
#include <string>
#include "clstm.h"
using namespace std;
int main(int argc, char **argv) {
ifstream file1(argv[1]);
ifstream file2(argv[2]);
for (;;) {
std::string line1, line2;
if (file1.eof() || file2.eof()) break;
getline(file1, line1);
getline(file2, line2);
int err = levenshtein(line1, line2);
cout << err << "\t";
cout << line1 << "\t";
cout << line2 << "\n";
}
}
| 210 |
3,673 |
<gh_stars>1000+
#pragma once
#include <sys/epoll.h>
namespace linux
{
void epoll_add_fd(int fd, epoll_event& event);
void epoll_del_fd(int fd);
void epoll_wait_events();
}
| 79 |
460 |
<filename>trunk/win/Source/Includes/QtIncludes/src/3rdparty/javascriptcore/JavaScriptCore/runtime/JSString.h<gh_stars>100-1000
/*
* Copyright (C) 1999-2001 <NAME> (<EMAIL>)
* Copyright (C) 2001 <NAME> (<EMAIL>)
* Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef JSString_h
#define JSString_h
#include "CallFrame.h"
#include "CommonIdentifiers.h"
#include "Identifier.h"
#include "JSNumberCell.h"
#include "PropertyDescriptor.h"
#include "PropertySlot.h"
namespace JSC {
class JSString;
JSString* jsEmptyString(JSGlobalData*);
JSString* jsEmptyString(ExecState*);
JSString* jsString(JSGlobalData*, const UString&); // returns empty string if passed null string
JSString* jsString(ExecState*, const UString&); // returns empty string if passed null string
JSString* jsSingleCharacterString(JSGlobalData*, UChar);
JSString* jsSingleCharacterString(ExecState*, UChar);
JSString* jsSingleCharacterSubstring(JSGlobalData*, const UString&, unsigned offset);
JSString* jsSingleCharacterSubstring(ExecState*, const UString&, unsigned offset);
JSString* jsSubstring(JSGlobalData*, const UString&, unsigned offset, unsigned length);
JSString* jsSubstring(ExecState*, const UString&, unsigned offset, unsigned length);
// Non-trivial strings are two or more characters long.
// These functions are faster than just calling jsString.
JSString* jsNontrivialString(JSGlobalData*, const UString&);
JSString* jsNontrivialString(ExecState*, const UString&);
JSString* jsNontrivialString(JSGlobalData*, const char*);
JSString* jsNontrivialString(ExecState*, const char*);
// Should be used for strings that are owned by an object that will
// likely outlive the JSValue this makes, such as the parse tree or a
// DOM object that contains a UString
JSString* jsOwnedString(JSGlobalData*, const UString&);
JSString* jsOwnedString(ExecState*, const UString&);
typedef void (*JSStringFinalizerCallback)(JSString*, void* context);
JSString* jsStringWithFinalizer(ExecState*, const UString&, JSStringFinalizerCallback callback, void* context);
class JS_EXPORTCLASS JSString : public JSCell {
public:
friend class JIT;
friend class JSGlobalData;
// A Rope is a string composed of a set of substrings.
class Rope : public RefCounted<Rope> {
public:
// A Rope is composed from a set of smaller strings called Fibers.
// Each Fiber in a rope is either UString::Rep or another Rope.
class Fiber {
public:
Fiber() : m_value(0) {}
Fiber(UString::Rep* string) : m_value(reinterpret_cast<intptr_t>(string)) {}
Fiber(Rope* rope) : m_value(reinterpret_cast<intptr_t>(rope) | 1) {}
Fiber(void* nonFiber) : m_value(reinterpret_cast<intptr_t>(nonFiber)) {}
void deref()
{
if (isRope())
rope()->deref();
else
string()->deref();
}
Fiber& ref()
{
if (isString())
string()->ref();
else
rope()->ref();
return *this;
}
unsigned refAndGetLength()
{
if (isString()) {
UString::Rep* rep = string();
return rep->ref()->size();
} else {
Rope* r = rope();
r->ref();
return r->stringLength();
}
}
bool isRope() { return m_value & 1; }
Rope* rope() { return reinterpret_cast<Rope*>(m_value & ~1); }
bool isString() { return !isRope(); }
UString::Rep* string() { return reinterpret_cast<UString::Rep*>(m_value); }
void* nonFiber() { return reinterpret_cast<void*>(m_value); }
private:
intptr_t m_value;
};
// Creates a Rope comprising of 'ropeLength' Fibers.
// The Rope is constructed in an uninitialized state - initialize must be called for each Fiber in the Rope.
static PassRefPtr<Rope> createOrNull(unsigned ropeLength)
{
void* allocation;
if (tryFastMalloc(sizeof(Rope) + (ropeLength - 1) * sizeof(Fiber)).getValue(allocation))
return adoptRef(new (allocation) Rope(ropeLength));
return 0;
}
~Rope();
void destructNonRecursive();
void append(unsigned &index, Fiber& fiber)
{
m_fibers[index++] = fiber;
m_stringLength += fiber.refAndGetLength();
}
void append(unsigned &index, const UString& string)
{
UString::Rep* rep = string.rep();
m_fibers[index++] = Fiber(rep);
m_stringLength += rep->ref()->size();
}
void append(unsigned& index, JSString* jsString)
{
if (jsString->isRope()) {
for (unsigned i = 0; i < jsString->m_ropeLength; ++i)
append(index, jsString->m_fibers[i]);
} else
append(index, jsString->string());
}
unsigned ropeLength() { return m_ropeLength; }
unsigned stringLength() { return m_stringLength; }
Fiber& fibers(unsigned index) { return m_fibers[index]; }
private:
Rope(unsigned ropeLength) : m_ropeLength(ropeLength), m_stringLength(0) {}
void* operator new(size_t, void* inPlace) { return inPlace; }
unsigned m_ropeLength;
unsigned m_stringLength;
Fiber m_fibers[1];
};
ALWAYS_INLINE JSString(JSGlobalData* globalData, const UString& value)
: JSCell(globalData->stringStructure.get())
, m_stringLength(value.size())
, m_value(value)
, m_ropeLength(0)
{
Heap::heap(this)->reportExtraMemoryCost(value.cost());
}
enum HasOtherOwnerType { HasOtherOwner };
JSString(JSGlobalData* globalData, const UString& value, HasOtherOwnerType)
: JSCell(globalData->stringStructure.get())
, m_stringLength(value.size())
, m_value(value)
, m_ropeLength(0)
{
}
JSString(JSGlobalData* globalData, PassRefPtr<UString::Rep> value, HasOtherOwnerType)
: JSCell(globalData->stringStructure.get())
, m_stringLength(value->size())
, m_value(value)
, m_ropeLength(0)
{
}
JSString(JSGlobalData* globalData, PassRefPtr<JSString::Rope> rope)
: JSCell(globalData->stringStructure.get())
, m_stringLength(rope->stringLength())
, m_ropeLength(1)
{
m_fibers[0] = rope.releaseRef();
}
// This constructor constructs a new string by concatenating s1 & s2.
// This should only be called with ropeLength <= 3.
JSString(JSGlobalData* globalData, unsigned ropeLength, JSString* s1, JSString* s2)
: JSCell(globalData->stringStructure.get())
, m_stringLength(s1->length() + s2->length())
, m_ropeLength(ropeLength)
{
ASSERT(ropeLength <= s_maxInternalRopeLength);
unsigned index = 0;
appendStringInConstruct(index, s1);
appendStringInConstruct(index, s2);
ASSERT(ropeLength == index);
}
// This constructor constructs a new string by concatenating s1 & s2.
// This should only be called with ropeLength <= 3.
JSString(JSGlobalData* globalData, unsigned ropeLength, JSString* s1, const UString& u2)
: JSCell(globalData->stringStructure.get())
, m_stringLength(s1->length() + u2.size())
, m_ropeLength(ropeLength)
{
ASSERT(ropeLength <= s_maxInternalRopeLength);
unsigned index = 0;
appendStringInConstruct(index, s1);
appendStringInConstruct(index, u2);
ASSERT(ropeLength == index);
}
// This constructor constructs a new string by concatenating s1 & s2.
// This should only be called with ropeLength <= 3.
JSString(JSGlobalData* globalData, unsigned ropeLength, const UString& u1, JSString* s2)
: JSCell(globalData->stringStructure.get())
, m_stringLength(u1.size() + s2->length())
, m_ropeLength(ropeLength)
{
ASSERT(ropeLength <= s_maxInternalRopeLength);
unsigned index = 0;
appendStringInConstruct(index, u1);
appendStringInConstruct(index, s2);
ASSERT(ropeLength == index);
}
// This constructor constructs a new string by concatenating v1, v2 & v3.
// This should only be called with ropeLength <= 3 ... which since every
// value must require a ropeLength of at least one implies that the length
// for each value must be exactly 1!
JSString(ExecState* exec, JSValue v1, JSValue v2, JSValue v3)
: JSCell(exec->globalData().stringStructure.get())
, m_stringLength(0)
, m_ropeLength(s_maxInternalRopeLength)
{
unsigned index = 0;
appendValueInConstructAndIncrementLength(exec, index, v1);
appendValueInConstructAndIncrementLength(exec, index, v2);
appendValueInConstructAndIncrementLength(exec, index, v3);
ASSERT(index == s_maxInternalRopeLength);
}
JSString(JSGlobalData* globalData, const UString& value, JSStringFinalizerCallback finalizer, void* context)
: JSCell(globalData->stringStructure.get())
, m_stringLength(value.size())
, m_value(value)
, m_ropeLength(0)
{
// nasty hack because we can't union non-POD types
m_fibers[0] = reinterpret_cast<void*>(reinterpret_cast<ptrdiff_t>(finalizer));
m_fibers[1] = context;
Heap::heap(this)->reportExtraMemoryCost(value.cost());
}
~JSString()
{
ASSERT(vptr() == JSGlobalData::jsStringVPtr);
for (unsigned i = 0; i < m_ropeLength; ++i)
m_fibers[i].deref();
if (!m_ropeLength && m_fibers[0].nonFiber()) {
JSStringFinalizerCallback finalizer = (JSStringFinalizerCallback)(m_fibers[0].nonFiber());
finalizer(this, m_fibers[1].nonFiber());
}
}
const UString& value(ExecState* exec) const
{
if (isRope())
resolveRope(exec);
return m_value;
}
const UString tryGetValue() const
{
if (isRope())
UString();
return m_value;
}
unsigned length() { return m_stringLength; }
bool getStringPropertySlot(ExecState*, const Identifier& propertyName, PropertySlot&);
bool getStringPropertySlot(ExecState*, unsigned propertyName, PropertySlot&);
bool getStringPropertyDescriptor(ExecState*, const Identifier& propertyName, PropertyDescriptor&);
bool canGetIndex(unsigned i) { return i < m_stringLength; }
JSString* getIndex(ExecState*, unsigned);
static PassRefPtr<Structure> createStructure(JSValue proto) { return Structure::create(proto, TypeInfo(StringType, OverridesGetOwnPropertySlot | NeedsThisConversion)); }
private:
enum VPtrStealingHackType { VPtrStealingHack };
JSString(VPtrStealingHackType)
: JSCell(0)
, m_ropeLength(0)
{
}
void resolveRope(ExecState*) const;
void appendStringInConstruct(unsigned& index, const UString& string)
{
m_fibers[index++] = Rope::Fiber(string.rep()->ref());
}
void appendStringInConstruct(unsigned& index, JSString* jsString)
{
if (jsString->isRope()) {
for (unsigned i = 0; i < jsString->m_ropeLength; ++i)
m_fibers[index++] = jsString->m_fibers[i].ref();
} else
appendStringInConstruct(index, jsString->string());
}
void appendValueInConstructAndIncrementLength(ExecState* exec, unsigned& index, JSValue v)
{
if (v.isString()) {
ASSERT(asCell(v)->isString());
JSString* s = static_cast<JSString*>(asCell(v));
ASSERT(s->ropeLength() == 1);
appendStringInConstruct(index, s);
m_stringLength += s->length();
} else {
UString u(v.toString(exec));
m_fibers[index++] = Rope::Fiber(u.rep()->ref());
m_stringLength += u.size();
}
}
virtual JSValue toPrimitive(ExecState*, PreferredPrimitiveType) const;
virtual bool getPrimitiveNumber(ExecState*, double& number, JSValue& value);
virtual bool toBoolean(ExecState*) const;
virtual double toNumber(ExecState*) const;
virtual JSObject* toObject(ExecState*) const;
virtual UString toString(ExecState*) const;
virtual JSObject* toThisObject(ExecState*) const;
virtual UString toThisString(ExecState*) const;
virtual JSString* toThisJSString(ExecState*);
// Actually getPropertySlot, not getOwnPropertySlot (see JSCell).
virtual bool getOwnPropertySlot(ExecState*, const Identifier& propertyName, PropertySlot&);
virtual bool getOwnPropertySlot(ExecState*, unsigned propertyName, PropertySlot&);
virtual bool getOwnPropertyDescriptor(ExecState*, const Identifier&, PropertyDescriptor&);
static const unsigned s_maxInternalRopeLength = 3;
// A string is represented either by a UString or a Rope.
unsigned m_stringLength;
mutable UString m_value;
mutable unsigned m_ropeLength;
mutable Rope::Fiber m_fibers[s_maxInternalRopeLength];
bool isRope() const { return m_ropeLength; }
UString& string() { ASSERT(!isRope()); return m_value; }
unsigned ropeLength() { return m_ropeLength ? m_ropeLength : 1; }
friend JSValue jsString(ExecState* exec, JSString* s1, JSString* s2);
friend JSValue jsString(ExecState* exec, const UString& u1, JSString* s2);
friend JSValue jsString(ExecState* exec, JSString* s1, const UString& u2);
friend JSValue jsString(ExecState* exec, Register* strings, unsigned count);
friend JSValue jsString(ExecState* exec, JSValue thisValue, const ArgList& args);
friend JSString* jsStringWithFinalizer(ExecState*, const UString&, JSStringFinalizerCallback callback, void* context);
};
JSString* asString(JSValue);
// When an object is created from a different DLL, MSVC changes vptr to a "local" one right after invoking a constructor,
// see <http://groups.google.com/group/microsoft.public.vc.language/msg/55cdcefeaf770212>.
// This breaks isJSString(), and we don't need that hack anyway, so we change vptr back to primary one.
// The below function must be called by any inline function that invokes a JSString constructor.
#if COMPILER(MSVC) && !defined(BUILDING_JavaScriptCore)
inline JSString* fixupVPtr(JSGlobalData* globalData, JSString* string) { string->setVPtr(globalData->jsStringVPtr); return string; }
#else
inline JSString* fixupVPtr(JSGlobalData*, JSString* string) { return string; }
#endif
inline JSString* asString(JSValue value)
{
ASSERT(asCell(value)->isString());
return static_cast<JSString*>(asCell(value));
}
inline JSString* jsEmptyString(JSGlobalData* globalData)
{
return globalData->smallStrings.emptyString(globalData);
}
inline JSString* jsSingleCharacterString(JSGlobalData* globalData, UChar c)
{
if (c <= 0xFF)
return globalData->smallStrings.singleCharacterString(globalData, c);
return fixupVPtr(globalData, new (globalData) JSString(globalData, UString(&c, 1)));
}
inline JSString* jsSingleCharacterSubstring(JSGlobalData* globalData, const UString& s, unsigned offset)
{
ASSERT(offset < static_cast<unsigned>(s.size()));
UChar c = s.data()[offset];
if (c <= 0xFF)
return globalData->smallStrings.singleCharacterString(globalData, c);
return fixupVPtr(globalData, new (globalData) JSString(globalData, UString(UString::Rep::create(s.rep(), offset, 1))));
}
inline JSString* jsNontrivialString(JSGlobalData* globalData, const char* s)
{
ASSERT(s);
ASSERT(s[0]);
ASSERT(s[1]);
return fixupVPtr(globalData, new (globalData) JSString(globalData, s));
}
inline JSString* jsNontrivialString(JSGlobalData* globalData, const UString& s)
{
ASSERT(s.size() > 1);
return fixupVPtr(globalData, new (globalData) JSString(globalData, s));
}
inline JSString* JSString::getIndex(ExecState* exec, unsigned i)
{
ASSERT(canGetIndex(i));
return jsSingleCharacterSubstring(&exec->globalData(), value(exec), i);
}
inline JSString* jsString(JSGlobalData* globalData, const UString& s)
{
int size = s.size();
if (!size)
return globalData->smallStrings.emptyString(globalData);
if (size == 1) {
UChar c = s.data()[0];
if (c <= 0xFF)
return globalData->smallStrings.singleCharacterString(globalData, c);
}
return fixupVPtr(globalData, new (globalData) JSString(globalData, s));
}
inline JSString* jsStringWithFinalizer(ExecState* exec, const UString& s, JSStringFinalizerCallback callback, void* context)
{
ASSERT(s.size() && (s.size() > 1 || s.data()[0] > 0xFF));
JSGlobalData* globalData = &exec->globalData();
return fixupVPtr(globalData, new (globalData) JSString(globalData, s, callback, context));
}
inline JSString* jsSubstring(JSGlobalData* globalData, const UString& s, unsigned offset, unsigned length)
{
ASSERT(offset <= static_cast<unsigned>(s.size()));
ASSERT(length <= static_cast<unsigned>(s.size()));
ASSERT(offset + length <= static_cast<unsigned>(s.size()));
if (!length)
return globalData->smallStrings.emptyString(globalData);
if (length == 1) {
UChar c = s.data()[offset];
if (c <= 0xFF)
return globalData->smallStrings.singleCharacterString(globalData, c);
}
return fixupVPtr(globalData, new (globalData) JSString(globalData, UString(UString::Rep::create(s.rep(), offset, length)), JSString::HasOtherOwner));
}
inline JSString* jsOwnedString(JSGlobalData* globalData, const UString& s)
{
int size = s.size();
if (!size)
return globalData->smallStrings.emptyString(globalData);
if (size == 1) {
UChar c = s.data()[0];
if (c <= 0xFF)
return globalData->smallStrings.singleCharacterString(globalData, c);
}
return fixupVPtr(globalData, new (globalData) JSString(globalData, s, JSString::HasOtherOwner));
}
inline JSString* jsEmptyString(ExecState* exec) { return jsEmptyString(&exec->globalData()); }
inline JSString* jsString(ExecState* exec, const UString& s) { return jsString(&exec->globalData(), s); }
inline JSString* jsSingleCharacterString(ExecState* exec, UChar c) { return jsSingleCharacterString(&exec->globalData(), c); }
inline JSString* jsSingleCharacterSubstring(ExecState* exec, const UString& s, unsigned offset) { return jsSingleCharacterSubstring(&exec->globalData(), s, offset); }
inline JSString* jsSubstring(ExecState* exec, const UString& s, unsigned offset, unsigned length) { return jsSubstring(&exec->globalData(), s, offset, length); }
inline JSString* jsNontrivialString(ExecState* exec, const UString& s) { return jsNontrivialString(&exec->globalData(), s); }
inline JSString* jsNontrivialString(ExecState* exec, const char* s) { return jsNontrivialString(&exec->globalData(), s); }
inline JSString* jsOwnedString(ExecState* exec, const UString& s) { return jsOwnedString(&exec->globalData(), s); }
ALWAYS_INLINE bool JSString::getStringPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
if (propertyName == exec->propertyNames().length) {
slot.setValue(jsNumber(exec, m_stringLength));
return true;
}
bool isStrictUInt32;
unsigned i = propertyName.toStrictUInt32(&isStrictUInt32);
if (isStrictUInt32 && i < m_stringLength) {
slot.setValue(jsSingleCharacterSubstring(exec, value(exec), i));
return true;
}
return false;
}
ALWAYS_INLINE bool JSString::getStringPropertySlot(ExecState* exec, unsigned propertyName, PropertySlot& slot)
{
if (propertyName < m_stringLength) {
slot.setValue(jsSingleCharacterSubstring(exec, value(exec), propertyName));
return true;
}
return false;
}
inline bool isJSString(JSGlobalData* globalData, JSValue v) { return v.isCell() && v.asCell()->vptr() == globalData->jsStringVPtr; }
// --- JSValue inlines ----------------------------
inline JSString* JSValue::toThisJSString(ExecState* exec)
{
return isCell() ? asCell()->toThisJSString(exec) : jsString(exec, toString(exec));
}
inline UString JSValue::toString(ExecState* exec) const
{
if (isString())
return static_cast<JSString*>(asCell())->value(exec);
if (isInt32())
return exec->globalData().numericStrings.add(asInt32());
if (isDouble())
return exec->globalData().numericStrings.add(asDouble());
if (isTrue())
return "true";
if (isFalse())
return "false";
if (isNull())
return "null";
if (isUndefined())
return "undefined";
ASSERT(isCell());
return asCell()->toString(exec);
}
inline UString JSValue::toPrimitiveString(ExecState* exec) const
{
if (isString())
return static_cast<JSString*>(asCell())->value(exec);
if (isInt32())
return exec->globalData().numericStrings.add(asInt32());
if (isDouble())
return exec->globalData().numericStrings.add(asDouble());
if (isTrue())
return "true";
if (isFalse())
return "false";
if (isNull())
return "null";
if (isUndefined())
return "undefined";
ASSERT(isCell());
return asCell()->toPrimitive(exec, NoPreference).toString(exec);
}
} // namespace JSC
#endif // JSString_h
| 11,046 |
8,027 |
package com.facebook.buck.demo;
import com.facebook.buck.android.support.exopackage.ExopackageApplication;
public class WithExo extends ExopackageApplication {
public WithExo() {
super(com.facebook.buck.demo.BuildConfig.EXOPACKAGE_FLAGS);
}
}
| 88 |
2,908 |
package com.xuhao.didi.core.utils;
/**
* Created by xuhao on 2017/6/9.
*/
public class SLog {
private static boolean isDebug;
public static void setIsDebug(boolean isDebug) {
SLog.isDebug = isDebug;
}
public static boolean isDebug() {
return isDebug;
}
public static void e(String msg) {
if (isDebug) {
System.err.println("OkSocket, " + msg);
}
}
public static void i(String msg) {
if (isDebug) {
System.out.println("OkSocket, " + msg);
}
}
public static void w(String msg) {
i(msg);
}
}
| 282 |
8,747 |
#!/usr/bin/env python
from __future__ import division, print_function
import io
import sys
import unittest
from test_utils import Py23TestCase
try:
from typing import IO
except ImportError:
pass # only needed for type annotations
try:
import check_sizes
except ImportError:
sys.path.append('..')
import check_sizes
try:
import gen_esp32part
except ImportError:
sys.path.append('..')
import gen_esp32part
BASE_CSV = """
# Name, Type, SubType, Offset, Size, Flags
# Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
nvs, data, nvs, , 0x4000,
otadata, data, ota, , 0x2000,
phy_init, data, phy, , 0x1000,
"""
def gen_table(factory_appsize=None, ota0_appsize=None, ota1_appsize=None): # type: (str, str, str) -> io.BytesIO
""" generate a partition table binary with up to 3 app partitions with the specified sizes. """
csv = BASE_CSV
if factory_appsize:
csv += 'factory, app, factory, , {}\n'.format(factory_appsize)
if ota0_appsize:
csv += 'ota0, app, ota_0, , {}\n'.format(ota0_appsize)
if ota1_appsize:
csv += 'ota1, app, ota_1, , {}\n'.format(ota1_appsize)
table = gen_esp32part.PartitionTable.from_csv(csv)
return io.BytesIO(table.to_binary())
def fake_file(kilobytes, name): # type: (int, str) -> IO
result = io.BytesIO(b'\xEE' * kilobytes * 1024)
result.name = name
return result
class TestAppSizes(Py23TestCase):
def test_sizes_ok(self): # type: () -> None
pt = gen_table('1M')
app = fake_file(512, 'test.bin')
check_sizes.check_partition('app', None, pt, app)
def test_single_part_too_small(self): # type: () -> None
pt = gen_table('1M')
app = fake_file(1500, 'too_big.bin')
with self.assertRaises(SystemExit) as e:
check_sizes.check_partition('app', None, pt, app)
self.assertIn('too small', str(e.exception))
self.assertIn('too_big.bin', str(e.exception))
def test_all_parts_too_small(self): # type: () -> None
pt = gen_table('500K', '500K', '500K')
app = fake_file(501, 'just_too_big.bin')
with self.assertRaises(SystemExit) as e:
check_sizes.check_partition('app', None, pt, app)
self.assertIn('All', str(e.exception))
self.assertIn('too small', str(e.exception))
self.assertIn('just_too_big.bin', str(e.exception))
def test_one_part_too_small_warning(self): # type: () -> None
pt = gen_table('500K', '1M', '1M')
app = fake_file(501, 'big.bin')
# this will print a warning, no easy way to verify it looks correct
check_sizes.check_partition('app', None, pt, app)
class TestBootloaderSizes(Py23TestCase):
def test_sizes_ok(self): # type: () -> None
bootloader = fake_file(25, 'test.bin')
check_sizes.check_bootloader(0x8000, 0x1000, bootloader)
def test_bootloader_too_big_default(self): # type: () -> None
bootloader = fake_file(40, 'test.bin')
with self.assertRaises(SystemExit) as e:
check_sizes.check_bootloader(0x8000, 0x1000, bootloader)
self.assertIn('overlap', str(e.exception))
# move the partition table offset up, it will pass
check_sizes.check_bootloader(0xb000, 0x1000, bootloader)
if __name__ == '__main__':
unittest.main()
| 1,467 |
5,169 |
<reponame>Gantios/Specs
{
"name": "SwitchLanguage",
"version": "1.0.7",
"license": "MIT",
"summary": "Manage translation easily in your app",
"homepage": "https://github.com/NicolasPoincet/SwitchLanguage",
"authors": {
"<NAME>": "",
"<NAME>": "",
"<NAME>": ""
},
"source": {
"git": "https://github.com/NicolasPoincet/SwitchLanguage.git",
"tag": "1.0.7"
},
"platforms": {
"ios": "8.0",
"tvos": "9.0"
},
"frameworks": [
"UIKit",
"Foundation"
],
"source_files": "CIFramework/*.swift"
}
| 245 |
362 |
package subreddit.android.appstore.screens.details;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import subreddit.android.appstore.R;
public class ScreenshotDialog extends Dialog implements View.OnClickListener {
private final List<String> urls;
private final int currentImage;
@BindView(R.id.screenshot_dialog_pager) ViewPager viewPager;
@BindView(R.id.screenshot_dialog_toolbar) Toolbar toolbar;
public ScreenshotDialog(Context context, List<String> urls, int currentImage) {
super(context, R.style.AppTheme_Black);
this.currentImage = currentImage;
this.urls = urls;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_screenshot);
ButterKnife.bind(this);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_48px);
toolbar.setNavigationOnClickListener(this);
toolbar.setTitle(R.string.screenshots);
ScreenshotsAdapter screenshotsAdapter = new ScreenshotsAdapter(getContext(), 1);
screenshotsAdapter.update(urls);
viewPager.setAdapter(screenshotsAdapter);
viewPager.setCurrentItem(currentImage, false);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
updatePageIndicator(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
updatePageIndicator(currentImage);
}
private void updatePageIndicator(int position) {
toolbar.setSubtitle(String.format("%s/%s", position + 1, urls.size()));
}
@Override
public void onClick(View view) {
dismiss();
}
}
| 861 |
9,156 |
/**
* 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.pulsar.broker.loadbalance.impl;
import com.google.common.base.MoreObjects;
import org.apache.pulsar.broker.loadbalance.ResourceDescription;
import org.apache.pulsar.broker.loadbalance.ResourceUnit;
public class SimpleResourceUnit implements ResourceUnit {
private String resourceId;
private ResourceDescription resourceDescription;
public SimpleResourceUnit(String resourceId, ResourceDescription resourceDescription) {
this.resourceId = resourceId;
this.resourceDescription = resourceDescription;
}
@Override
public String getResourceId() {
// TODO Auto-generated method stub
return resourceId;
}
@Override
public ResourceDescription getAvailableResource() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean canFit(ResourceDescription resourceDescription) {
// TODO Auto-generated method stub
return this.resourceDescription.compareTo(resourceDescription) > 0;
}
@Override
public int compareTo(ResourceUnit o) {
return resourceId.compareTo(o.getResourceId());
}
@Override
public boolean equals(Object o) {
if (!(o instanceof SimpleResourceUnit)) {
return false;
}
SimpleResourceUnit other = (SimpleResourceUnit) o;
return this.resourceId.equals(other.resourceId);
}
@Override
public int hashCode() {
return this.resourceId.hashCode();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("resourceId", resourceId).toString();
}
}
| 765 |
5,250 |
<reponame>jiandiao/flowable-engine
/* 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.flowable.content.rest.service.api.content;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.rest.api.DataResponse;
import org.flowable.common.rest.api.RequestUtil;
import org.flowable.content.api.ContentItem;
import org.flowable.content.api.ContentService;
import org.flowable.content.rest.ContentRestResponseFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
/**
* @author <NAME>
*/
@RestController
@Api(tags = { "Content item" }, description = "Manages Content item", authorizations = { @Authorization(value = "basicAuth") })
public class ContentItemCollectionResource extends ContentItemBaseResource {
@Autowired
protected ContentService contentService;
@Autowired
protected ContentRestResponseFactory contentRestResponseFactory;
@Autowired
protected ObjectMapper objectMapper;
@ApiOperation(value = "List content items", tags = { "Content item" }, nickname = "listContentItems")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", dataType = "string", value = "Only return content items with the given id.", paramType = "query"),
@ApiImplicitParam(name = "name", dataType = "string", value = "Only return content items with the given name.", paramType = "query"),
@ApiImplicitParam(name = "nameLike", dataType = "string", value = "Only return content items with a name like the given value.", paramType = "query"),
@ApiImplicitParam(name = "mimeType", dataType = "string", value = "Only return content items with the given mime type.", paramType = "query"),
@ApiImplicitParam(name = "mimeTypeLike", dataType = "string", value = "Only return content items with a mime type like the given value.", paramType = "query"),
@ApiImplicitParam(name = "taskId", dataType = "string", value = "Only return content items with the given task id.", paramType = "query"),
@ApiImplicitParam(name = "taskIdLike", dataType = "string", value = "Only return content items with a task like the given value.", paramType = "query"),
@ApiImplicitParam(name = "processInstanceId", dataType = "string", value = "Only return content items with the given process instance id.", paramType = "query"),
@ApiImplicitParam(name = "processInstanceIdLike", dataType = "string", value = "Only return content items with a process instance like the given value.", paramType = "query"),
@ApiImplicitParam(name = "contentStoreId", dataType = "string", value = "Only return content items with the given content store id.", paramType = "query"),
@ApiImplicitParam(name = "contentStoreIdLike", dataType = "string", value = "Only return content items with a content store id like the given value.", paramType = "query"),
@ApiImplicitParam(name = "contentStoreName", dataType = "string", value = "Only return content items with the given content store name.", paramType = "query"),
@ApiImplicitParam(name = "contentStoreNameLike", dataType = "string", value = "Only return content items with a content store name like the given value.", paramType = "query"),
@ApiImplicitParam(name = "contentAvailable", dataType = "boolean", value = "Only return content items with or without content available.", paramType = "query"),
@ApiImplicitParam(name = "contentSize", dataType = "number", format ="int64", value = "Only return content items with the given content size.", paramType = "query"),
@ApiImplicitParam(name = "minimumContentSize", dataType = "number", format ="int64", value = "Only return content items with the a minimum content size of the given value.", paramType = "query"),
@ApiImplicitParam(name = "maximumContentSize", dataType = "number", format ="int64", value = "Only return content items with the a maximum content size of the given value.", paramType = "query"),
@ApiImplicitParam(name = "field", dataType = "string", value = "Only return content items with the given field.", paramType = "query"),
@ApiImplicitParam(name = "fieldLike", dataType = "string", value = "Only return content items with a field like the given value.", paramType = "query"),
@ApiImplicitParam(name = "createdOn", dataType = "string", format = "date-time", value = "Only return content items with the given create date.", paramType = "query"),
@ApiImplicitParam(name = "createdBefore", dataType = "string", format = "date-time", value = "Only return content items before given create date.", paramType = "query"),
@ApiImplicitParam(name = "createdAfter", dataType = "string", format = "date-time", value = "Only return content items after given create date.", paramType = "query"),
@ApiImplicitParam(name = "createdBy", dataType = "string", value = "Only return content items with the given created by.", paramType = "query"),
@ApiImplicitParam(name = "createdByLike", dataType = "string", value = "Only return content items with a created by like the given value.", paramType = "query"),
@ApiImplicitParam(name = "lastModifiedOn", dataType = "string", format = "date-time", value = "Only return content items with the given last modified date.", paramType = "query"),
@ApiImplicitParam(name = "lastModifiedBefore", dataType = "string", format = "date-time", value = "Only return content items before given last modified date.", paramType = "query"),
@ApiImplicitParam(name = "lastModifiedAfter", dataType = "string", format = "date-time", value = "Only return content items after given last modified date.", paramType = "query"),
@ApiImplicitParam(name = "lastModifiedBy", dataType = "string", value = "Only return content items with the given last modified by.", paramType = "query"),
@ApiImplicitParam(name = "lastModifiedByLike", dataType = "string", value = "Only return content items with a last modified by like the given value.", paramType = "query"),
@ApiImplicitParam(name = "tenantId", dataType = "string", value = "Only return content items with the given tenantId.", paramType = "query"),
@ApiImplicitParam(name = "tenantIdLike", dataType = "string", value = "Only return content items with a tenantId like the given value.", paramType = "query"),
@ApiImplicitParam(name = "withoutTenantId", dataType = "boolean", value = "If true, only returns content items without a tenantId set. If false, the withoutTenantId parameter is ignored.", paramType = "query"),
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The content items are returned.")
})
@GetMapping(value = "/content-service/content-items", produces = "application/json")
public DataResponse<ContentItemResponse> getContentItems(@ApiParam(hidden = true) @RequestParam Map<String, String> requestParams, HttpServletRequest httpRequest) {
// Create a Content item query request
ContentItemQueryRequest request = new ContentItemQueryRequest();
// Populate filter-parameters
if (requestParams.containsKey("id")) {
request.setId(requestParams.get("id"));
}
if (requestParams.containsKey("name")) {
request.setName(requestParams.get("name"));
}
if (requestParams.containsKey("nameLike")) {
request.setNameLike(requestParams.get("nameLike"));
}
if (requestParams.containsKey("mimeType")) {
request.setMimeType(requestParams.get("mimeType"));
}
if (requestParams.containsKey("mimeTypeLike")) {
request.setMimeTypeLike(requestParams.get("mimeTypeLike"));
}
if (requestParams.containsKey("taskId")) {
request.setTaskId(requestParams.get("taskId"));
}
if (requestParams.containsKey("taskIdLike")) {
request.setTaskIdLike(requestParams.get("taskIdLike"));
}
if (requestParams.containsKey("processInstanceId")) {
request.setProcessInstanceId(requestParams.get("processInstanceId"));
}
if (requestParams.containsKey("processInstanceIdLike")) {
request.setProcessInstanceIdLike(requestParams.get("processInstanceIdLike"));
}
if (requestParams.containsKey("contentStoreId")) {
request.setContentStoreId(requestParams.get("contentStoreId"));
}
if (requestParams.containsKey("contentStoreIdLike")) {
request.setContentStoreIdLike(requestParams.get("contentStoreIdLike"));
}
if (requestParams.containsKey("contentStoreName")) {
request.setContentStoreName(requestParams.get("contentStoreName"));
}
if (requestParams.containsKey("contentStoreNameLike")) {
request.setContentStoreNameLike(requestParams.get("contentStoreNameLike"));
}
if (requestParams.containsKey("contentSize")) {
request.setContentSize(Long.valueOf(requestParams.get("contentSize")));
}
if (requestParams.containsKey("minimumContentSize")) {
request.setMinimumContentSize(Long.valueOf(requestParams.get("minimumContentSize")));
}
if (requestParams.containsKey("maximumContentSize")) {
request.setMaximumContentSize(Long.valueOf(requestParams.get("maximumContentSize")));
}
if (requestParams.containsKey("contentAvailable")) {
request.setContentAvailable(Boolean.valueOf(requestParams.get("contentAvailable")));
}
if (requestParams.containsKey("field")) {
request.setField(requestParams.get("field"));
}
if (requestParams.containsKey("fieldLike")) {
request.setFieldLike(requestParams.get("fieldLike"));
}
if (requestParams.containsKey("createdOn")) {
request.setCreatedOn(RequestUtil.getDate(requestParams, "createdOn"));
}
if (requestParams.containsKey("createdBefore")) {
request.setCreatedBefore(RequestUtil.getDate(requestParams, "createdBefore"));
}
if (requestParams.containsKey("createdAfter")) {
request.setCreatedAfter(RequestUtil.getDate(requestParams, "createdAfter"));
}
if (requestParams.containsKey("createdBy")) {
request.setCreatedBy(requestParams.get("createdBy"));
}
if (requestParams.containsKey("createdByLike")) {
request.setCreatedByLike(requestParams.get("createdByLike"));
}
if (requestParams.containsKey("lastModifiedOn")) {
request.setLastModifiedOn(RequestUtil.getDate(requestParams, "lastModifiedOn"));
}
if (requestParams.containsKey("lastModifiedBefore")) {
request.setLastModifiedBefore(RequestUtil.getDate(requestParams, "lastModifiedBefore"));
}
if (requestParams.containsKey("lastModifiedAfter")) {
request.setLastModifiedAfter(RequestUtil.getDate(requestParams, "lastModifiedAfter"));
}
if (requestParams.containsKey("lastModifiedBy")) {
request.setLastModifiedBy(requestParams.get("lastModifiedBy"));
}
if (requestParams.containsKey("lastModifiedByLike")) {
request.setLastModifiedByLike(requestParams.get("lastModifiedByLike"));
}
if (requestParams.containsKey("tenantId")) {
request.setTenantId(requestParams.get("tenantId"));
}
if (requestParams.containsKey("tenantIdLike")) {
request.setTenantIdLike(requestParams.get("tenantIdLike"));
}
if (requestParams.containsKey("withoutTenantId") && Boolean.valueOf(requestParams.get("withoutTenantId"))) {
request.setWithoutTenantId(Boolean.TRUE);
}
return getContentItemsFromQueryRequest(request, requestParams);
}
@ApiOperation(value = "Create a new content item, with content item information and an optional attached file", tags = { "Content item" },
notes = "This endpoint can be used in 2 ways: By passing a JSON Body (ContentItemRequest) to link an external resource or by passing a multipart/form-data Object to attach a file.\n"
+ "NB: Swagger V2 specification doesn't support this use case that is why this endpoint might be buggy/incomplete if used with other tools.")
@ApiImplicitParams({
@ApiImplicitParam(name = "body", type = "org.flowable.rest.service.api.engine.ContentItemRequest", value = "Create a new content item, with content item information", paramType = "body", example = "{\n" + " \"name\":\"Simple content item\",\n" + " \"mimeType\":\"application/pdf\",\n"
+ " \"taskId\":\"12345\",\n" + " \"processInstanceId\":\"1234\"\n"
+ " \"contentStoreId\":\"5678\",\n" + " \"contentStoreName\":\"myFileStore\"\n"
+ " \"field\":\"uploadField\",\n" + " \"createdBy\":\"johndoe\"\n"
+ " \"lastModifiedBy\":\"johndoe\",\n" + " \"tenantId\":\"myTenantId\"\n" + "}"),
@ApiImplicitParam(name = "file", dataType = "file", value = "Attachment file", paramType = "form"),
@ApiImplicitParam(name = "name", dataType = "string", value = "Required name of the variable", paramType = "form", example = "Simple content item"),
@ApiImplicitParam(name = "mimeType", dataType = "string", value = "Mime type of the content item, optional", paramType = "form", example = "application/pdf"),
@ApiImplicitParam(name = "taskId", dataType = "string", value = "Task identifier for the content item, optional", paramType = "form", example = "12345"),
@ApiImplicitParam(name = "processInstanceId", dataType = "string", value = "Process instance identifier for the content item, optional", paramType = "form", example = "1234"),
@ApiImplicitParam(name = "contentStoreId", dataType = "string", value = "The identifier of the content item in an external content store, optional", paramType = "form", example = "5678"),
@ApiImplicitParam(name = "contentStoreName", dataType = "string", value = "The name of an external content store, optional", paramType = "form", example = "myFileStore"),
@ApiImplicitParam(name = "field", dataType = "string", value = "The form field for the content item, optional", paramType = "form", example = "uploadField"),
@ApiImplicitParam(name = "createdBy", dataType = "string", value = "The user identifier that created the content item, optional", paramType = "form", example = "johndoe"),
@ApiImplicitParam(name = "lastModifiedBy", dataType = "string", value = "The user identifier that last modified the content item, optional", paramType = "form", example = "johndoe"),
@ApiImplicitParam(name = "tenantId", dataType = "string", value = "The tenant identifier of the content item, optional", paramType = "form", example = "myTenantId")
})
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Indicates the content item was created and the result is returned."),
@ApiResponse(code = 400, message = "Indicates required content item info is missing from the request.")
})
@PostMapping(value = "/content-service/content-items", produces = "application/json", consumes = {"application/json", "multipart/form-data"})
public ContentItemResponse createContentItem(HttpServletRequest request, HttpServletResponse response) {
ContentItemResponse result = null;
if (request instanceof MultipartHttpServletRequest) {
result = createBinaryContentItem((MultipartHttpServletRequest) request, response);
} else {
ContentItemRequest contentItemRequest = null;
try {
contentItemRequest = objectMapper.readValue(request.getInputStream(), ContentItemRequest.class);
} catch (Exception e) {
throw new FlowableIllegalArgumentException("Failed to serialize to a ContentItemRequest instance", e);
}
if (contentItemRequest == null) {
throw new FlowableIllegalArgumentException("ContentItemRequest properties not found in request");
}
result = createSimpleContentItem(contentItemRequest);
}
response.setStatus(HttpStatus.CREATED.value());
return result;
}
protected ContentItemResponse createSimpleContentItem(ContentItemRequest contentItemRequest) {
if (contentItemRequest.getName() == null) {
throw new FlowableIllegalArgumentException("Content item name is required.");
}
ContentItem contentItem = contentService.newContentItem();
contentItem.setName(contentItemRequest.getName());
contentItem.setMimeType(contentItemRequest.getMimeType());
contentItem.setTaskId(contentItemRequest.getTaskId());
contentItem.setProcessInstanceId(contentItemRequest.getProcessInstanceId());
contentItem.setContentStoreId(contentItemRequest.getContentStoreId());
contentItem.setContentStoreName(contentItemRequest.getContentStoreName());
contentItem.setField(contentItemRequest.getField());
contentItem.setCreatedBy(contentItemRequest.getCreatedBy());
contentItem.setLastModifiedBy(contentItemRequest.getLastModifiedBy());
contentItem.setTenantId(contentItemRequest.getTenantId());
if (restApiInterceptor != null) {
restApiInterceptor.createNewContentItem(contentItem);
}
contentService.saveContentItem(contentItem);
return contentRestResponseFactory.createContentItemResponse(contentItem);
}
protected ContentItemResponse createBinaryContentItem(MultipartHttpServletRequest request, HttpServletResponse response) {
ContentItem contentItem = contentService.newContentItem();
Map<String, String[]> paramMap = request.getParameterMap();
for (String parameterName : paramMap.keySet()) {
if (paramMap.get(parameterName).length > 0) {
if ("name".equalsIgnoreCase(parameterName)) {
contentItem.setName(paramMap.get(parameterName)[0]);
} else if ("mimeType".equalsIgnoreCase(parameterName)) {
contentItem.setMimeType(paramMap.get(parameterName)[0]);
} else if ("taskId".equalsIgnoreCase(parameterName)) {
contentItem.setTaskId(paramMap.get(parameterName)[0]);
} else if ("processInstanceId".equalsIgnoreCase(parameterName)) {
contentItem.setProcessInstanceId(paramMap.get(parameterName)[0]);
} else if ("contentStoreId".equalsIgnoreCase(parameterName)) {
contentItem.setContentStoreId(paramMap.get(parameterName)[0]);
} else if ("contentStoreName".equalsIgnoreCase(parameterName)) {
contentItem.setContentStoreName(paramMap.get(parameterName)[0]);
} else if ("field".equalsIgnoreCase(parameterName)) {
contentItem.setField(paramMap.get(parameterName)[0]);
} else if ("createdBy".equalsIgnoreCase(parameterName)) {
contentItem.setCreatedBy(paramMap.get(parameterName)[0]);
} else if ("lastModifiedBy".equalsIgnoreCase(parameterName)) {
contentItem.setLastModifiedBy(paramMap.get(parameterName)[0]);
} else if ("tenantId".equalsIgnoreCase(parameterName)) {
contentItem.setTenantId(paramMap.get(parameterName)[0]);
}
}
}
if (contentItem.getName() == null) {
throw new FlowableIllegalArgumentException("Content item name is required.");
}
if (request.getFileMap().size() == 0) {
throw new FlowableIllegalArgumentException("Content item content is required.");
}
if (restApiInterceptor != null) {
restApiInterceptor.createNewContentItem(contentItem);
}
MultipartFile file = request.getFileMap().values().iterator().next();
if (file == null) {
throw new FlowableIllegalArgumentException("Content item file is required.");
}
try {
contentService.saveContentItem(contentItem, file.getInputStream());
response.setStatus(HttpStatus.CREATED.value());
return contentRestResponseFactory.createContentItemResponse(contentItem);
} catch (Exception e) {
throw new FlowableException("Error creating content item response", e);
}
}
}
| 8,146 |
10,192 |
<reponame>mahak/akka
/*
* Copyright (C) 2009-2021 Lightbend Inc. <https://www.lightbend.com>
*/
package akka.japi;
import akka.japi.pf.FI;
import akka.japi.pf.Match;
import org.junit.Assert;
import org.junit.Test;
import org.scalatestplus.junit.JUnitSuite;
import scala.MatchError;
import static org.junit.Assert.*;
public class MatchBuilderTest extends JUnitSuite {
@Test
public void shouldPassBasicMatchTest() {
Match<Object, Double> pf =
Match.create(
Match.match(
Integer.class,
new FI.Apply<Integer, Double>() {
@Override
public Double apply(Integer integer) {
return integer * 10.0;
}
})
.match(
Number.class,
new FI.Apply<Number, Double>() {
@Override
public Double apply(Number number) {
return number.doubleValue() * (-10.0);
}
}));
assertTrue(
"An integer should be multiplied by 10",
Double.valueOf(47110).equals(pf.match(Integer.valueOf(4711))));
assertTrue(
"A double should be multiplied by -10",
Double.valueOf(-47110).equals(pf.match(Double.valueOf(4711))));
Assert.assertThrows(
"A string should throw a MatchError", MatchError.class, () -> pf.match("4711"));
}
static class GenericClass<T> {
T val;
public GenericClass(T val) {
this.val = val;
}
}
@Test
public void shouldHandleMatchOnGenericClass() {
Match<Object, String> pf =
Match.create(
Match.matchUnchecked(
GenericClass.class,
new FI.Apply<GenericClass<String>, String>() {
@Override
public String apply(GenericClass<String> stringGenericClass) {
return stringGenericClass.val;
}
}));
assertEquals(
"String value should be extract from GenericMessage",
"A",
pf.match(new GenericClass<>("A")));
}
@Test
public void shouldHandleMatchWithPredicateOnGenericClass() {
Match<Object, String> pf =
Match.create(
Match.matchUnchecked(
GenericClass.class,
new FI.TypedPredicate<GenericClass<String>>() {
@Override
public boolean defined(GenericClass<String> genericClass) {
return !genericClass.val.isEmpty();
}
},
new FI.Apply<GenericClass<String>, String>() {
@Override
public String apply(GenericClass<String> stringGenericClass) {
return stringGenericClass.val;
}
}));
Assert.assertThrows(
"empty GenericMessage should throw match error",
MatchError.class,
() -> pf.match(new GenericClass<>("")));
}
}
| 1,543 |
4,224 |
<reponame>uavosky/uavosky-px4<filename>src/lib/matrix/test/MatrixSliceTest.cpp<gh_stars>1000+
/****************************************************************************
*
* Copyright (C) 2022 PX4 Development Team. 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 PX4 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.
*
****************************************************************************/
#include <gtest/gtest.h>
#include <matrix/math.hpp>
using namespace matrix;
TEST(MatrixSliceTest, Slice)
{
float data[9] = {0, 2, 3,
4, 5, 6,
7, 8, 10
};
SquareMatrix<float, 3> A(data);
// Test row slicing
Matrix<float, 2, 3> B_rowslice(A.slice<2, 3>(1, 0));
float data_check_rowslice[6] = {
4, 5, 6,
7, 8, 10
};
Matrix<float, 2, 3> B_check_rowslice(data_check_rowslice);
EXPECT_EQ(B_rowslice, B_check_rowslice);
// Test column slicing
Matrix<float, 3, 2> B_colslice(A.slice<3, 2>(0, 1));
float data_check_colslice[6] = {
2, 3,
5, 6,
8, 10
};
Matrix<float, 3, 2> B_check_colslice(data_check_colslice);
EXPECT_EQ(B_colslice, B_check_colslice);
// Test slicing both
Matrix<float, 2, 2> B_bothslice(A.slice<2, 2>(1, 1));
float data_check_bothslice[4] = {
5, 6,
8, 10
};
Matrix<float, 2, 2> B_check_bothslice(data_check_bothslice);
EXPECT_EQ(B_bothslice, B_check_bothslice);
//Test block writing
float data_2[4] = {
11, 12,
13, 14
};
Matrix<float, 2, 2> C(data_2);
A.slice<2, 2>(1, 1) = C;
float data_2_check[9] = {
0, 2, 3,
4, 11, 12,
7, 13, 14
};
Matrix<float, 3, 3> D(data_2_check);
EXPECT_EQ(A, D);
//Test writing to slices
Matrix<float, 3, 1> E;
E(0, 0) = -1;
E(1, 0) = 1;
E(2, 0) = 3;
Matrix<float, 2, 1> F;
F(0, 0) = 9;
F(1, 0) = 11;
E.slice<2, 1>(0, 0) = F;
float data_3_check[3] = {9, 11, 3};
Matrix<float, 3, 1> G(data_3_check);
EXPECT_EQ(E, G);
EXPECT_EQ(E, (Matrix<float, 3, 1>(E.slice<3, 1>(0, 0))));
Matrix<float, 2, 1> H = E.slice<2, 1>(0, 0);
EXPECT_EQ(H, F);
float data_4_check[5] = {3, 11, 9, 0, 0};
{
// assigning row slices to each other
const Matrix<float, 3, 1> J(data_3_check);
Matrix<float, 5, 1> K;
K.row(2) = J.row(0);
K.row(1) = J.row(1);
K.row(0) = J.row(2);
Matrix<float, 5, 1> K_check(data_4_check);
EXPECT_EQ(K, K_check);
}
{
// assigning col slices to each other
const Matrix<float, 1, 3> J(data_3_check);
Matrix<float, 1, 5> K;
K.col(2) = J.col(0);
K.col(1) = J.col(1);
K.col(0) = J.col(2);
Matrix<float, 1, 5> K_check(data_4_check);
EXPECT_EQ(K, K_check);
}
// check that slice of a slice works for reading
const Matrix<float, 3, 3> cm33(data);
Matrix<float, 2, 1> topRight = cm33.slice<2, 3>(0, 0).slice<2, 1>(0, 2);
float top_right_check[2] = {3, 6};
EXPECT_EQ(topRight, (Matrix<float, 2, 1>(top_right_check)));
// check that slice of a slice works for writing
Matrix<float, 3, 3> m33(data);
m33.slice<2, 3>(0, 0).slice<2, 1>(0, 2) = Matrix<float, 2, 1>();
const float data_check[9] = {0, 2, 0,
4, 5, 0,
7, 8, 10
};
EXPECT_EQ(m33, (Matrix<float, 3, 3>(data_check)));
// longerThan
Vector3f v5;
v5(0) = 3;
v5(1) = 4;
v5(2) = 9;
EXPECT_TRUE(v5.xy().longerThan(4.99f));
EXPECT_FALSE(v5.xy().longerThan(5.f));
EXPECT_FLOAT_EQ(v5.xy().norm(), 5.f);
// min/max
EXPECT_FLOAT_EQ(m33.row(1).max(), 5.f);
EXPECT_FLOAT_EQ(m33.col(0).min(), 0.f);
EXPECT_FLOAT_EQ((m33.slice<2, 2>(1, 1).max()), 10.f);
// assign scalar value to slice
Matrix<float, 3, 1> L;
L(0, 0) = -1;
L(1, 0) = 1;
L(2, 0) = 3;
L.slice<2, 1>(0, 0) = 0.0f;
float data_5_check[3] = {0, 0, 3};
Matrix<float, 3, 1> M(data_5_check);
EXPECT_EQ(L, M);
// return diagonal elements
float data_6[9] = {0, 2, 3,
4, 5, 6,
7, 8, 10
};
SquareMatrix<float, 3> N(data_6);
Vector3f v6 = N.slice<3, 3>(0, 0).diag();
Vector3f v6_check = {0, 5, 10};
EXPECT_EQ(v6, v6_check);
Vector2f v7 = N.slice<2, 3>(1, 0).diag();
Vector2f v7_check = {4, 8};
EXPECT_EQ(v7, v7_check);
Vector2f v8 = N.slice<3, 2>(0, 1).diag();
Vector2f v8_check = {2, 6};
EXPECT_EQ(v8, v8_check);
Vector2f v9(N.slice<1, 2>(1, 1));
Vector2f v9_check = {5, 6};
EXPECT_EQ(v9, v9_check);
Vector3f v10(N.slice<1, 3>(1, 0));
Vector3f v10_check = {4, 5, 6};
EXPECT_EQ(v10, v10_check);
// Different assignment operators
SquareMatrix3f O(data);
float operand_data [4] = {2, 1, -3, -1};
const SquareMatrix<float, 2> operand(operand_data);
O.slice<2, 2>(1, 0) += operand;
float O_check_data_1 [9] = {0, 2, 3, 6, 6, 6, 4, 7, 10};
EXPECT_EQ(O, SquareMatrix3f(O_check_data_1));
O = SquareMatrix3f(data);
O.slice<2, 1>(1, 1) += operand.slice<2, 1>(0, 0);
float O_check_data_2 [9] = {0, 2, 3, 4, 7, 6, 7, 5, 10};
EXPECT_EQ(O, SquareMatrix3f(O_check_data_2));
O = SquareMatrix3f(data);
O.slice<3, 3>(0, 0) += -1;
float O_check_data_3 [9] = {-1, 1, 2, 3, 4, 5, 6, 7, 9};
EXPECT_EQ(O, SquareMatrix3f(O_check_data_3));
O = SquareMatrix3f(data);
O.col(1) += Vector3f{1, -2, 3};
float O_check_data_4 [9] = {0, 3, 3, 4, 3, 6, 7, 11, 10};
EXPECT_EQ(O, SquareMatrix3f(O_check_data_4));
O = SquareMatrix3f(data);
O.slice<2, 2>(1, 0) -= operand;
float O_check_data_5 [9] = {0, 2, 3, 2, 4, 6, 10, 9, 10};
EXPECT_EQ(O, SquareMatrix3f(O_check_data_5));
O = SquareMatrix3f(data);
O.slice<2, 1>(1, 1) -= operand.slice<2, 1>(0, 0);
float O_check_data_6 [9] = {0, 2, 3, 4, 3, 6, 7, 11, 10};
EXPECT_EQ(O, SquareMatrix3f(O_check_data_6));
O = SquareMatrix3f(data);
O.slice<3, 3>(0, 0) -= -1;
float O_check_data_7 [9] = {1, 3, 4, 5, 6, 7, 8, 9, 11};
EXPECT_EQ(O, SquareMatrix3f(O_check_data_7));
O = SquareMatrix3f(data);
O.col(1) -= Vector3f{1, -2, 3};
float O_check_data_8 [9] = {0, 1, 3, 4, 7, 6, 7, 5, 10};
EXPECT_EQ(O, SquareMatrix3f(O_check_data_8));
O = SquareMatrix3f(data);
O.slice<2, 1>(1, 1) *= 5.f;
float O_check_data_9 [9] = {0, 2, 3, 4, 25, 6, 7, 40, 10};
EXPECT_EQ(O, SquareMatrix3f(O_check_data_9));
O = SquareMatrix3f(data);
O.slice<2, 1>(1, 1) /= 2.f;
float O_check_data_10 [9] = {0, 2, 3, 4, 2.5, 6, 7, 4, 10};
EXPECT_EQ(O, SquareMatrix3f(O_check_data_10));
// Different operations
O = SquareMatrix3f(data);
SquareMatrix<float, 2> res_11(O.slice<2, 2>(1, 1) * 2.f);
float O_check_data_11 [4] = {10, 12, 16, 20};
EXPECT_EQ(res_11, (SquareMatrix<float, 2>(O_check_data_11)));
O = SquareMatrix3f(data);
SquareMatrix<float, 2> res_12(O.slice<2, 2>(1, 1) / 2.f);
float O_check_data_12 [4] = {2.5, 3, 4, 5};
EXPECT_EQ(res_12, (SquareMatrix<float, 2>(O_check_data_12)));
}
| 3,626 |
2,542 |
<gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Data
{
template <typename TKey, typename TValue>
class IDictionary : public KObject<IDictionary<TKey, TValue>>, public KShared<IDictionary<TKey, TValue>>
{
K_FORCE_SHARED_WITH_INHERITANCE(IDictionary)
public:
__declspec(property(get = get_Count)) ULONG Count;
virtual ULONG get_Count() const = 0;
virtual void Add(__in const TKey&, __in const TValue&) = 0;
virtual void Clear() = 0;
virtual bool ContainsKey(__in const TKey&) const = 0;
virtual KSharedPtr<IEnumerator<KeyValuePair<TKey, TValue>>> GetEnumerator() const = 0;
virtual bool Remove(__in const TKey&) = 0;
virtual bool TryGetValue(__in const TKey&, __out TValue& value) const = 0;
};
template <typename TKey, typename TValue>
IDictionary<TKey, TValue>::IDictionary()
{
}
template <typename TKey, typename TValue>
IDictionary<TKey, TValue>::~IDictionary()
{
}
}
| 470 |
493 |
package cn.workcenter.common.response;
public interface ResponseBody {
}
| 22 |
347 |
////////////////////////////////////////////////////////////////////////////////
// Copyright 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
////////////////////////////////////////////////////////////////////////////////
#ifndef _CPUTFRUSTUM_H
#define _CPUTFRUSTUM_H
#include "CPUT.h"
#include "CPUTMath.h"
class CPUTCamera;
class CPUTFrustum
{
public:
float3 mpPosition[8];
float3 mpNormal[6];
float *mPlanes;
UINT mNumFrustumVisibleModels;
UINT mNumFrustumCulledModels;
CPUTFrustum();
~CPUTFrustum();
void InitializeFrustum
(
float nearClipDistance,
float farClipDistance,
float aspectRatio,
float fov,
const float3 &position,
const float3 &look,
const float3 &up
);
void InitializeFrustum( CPUTCamera *pCamera );
bool IsVisible(
const float3 ¢er,
const float3 &half
);
};
#endif // _CPUTFRUSTUM_H
| 555 |
9,402 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <limits.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#ifdef _MSC_VER
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT __attribute__((visibility("default")))
#endif
typedef enum {
CONVERT_BACKWARD_COMPATIBLE,
CONVERT_SENTINEL,
CONVERT_SATURATING,
CONVERT_NATIVECOMPILERBEHAVIOR,
CONVERT_MANAGED_BACKWARD_COMPATIBLE_X86_X64,
CONVERT_MANAGED_BACKWARD_COMPATIBLE_ARM32,
} FPtoIntegerConversionType;
extern "C" DLLEXPORT int32_t ConvertDoubleToInt32(double x, FPtoIntegerConversionType t)
{
if (t == CONVERT_NATIVECOMPILERBEHAVIOR)
return (int32_t)x;
x = trunc(x); // truncate (round toward zero)
switch (t) {
case CONVERT_BACKWARD_COMPATIBLE:
case CONVERT_MANAGED_BACKWARD_COMPATIBLE_X86_X64:
case CONVERT_SENTINEL:
return ((x != x) || (x < INT32_MIN) || (x > INT32_MAX)) ? INT32_MIN : (int32_t)x;
case CONVERT_MANAGED_BACKWARD_COMPATIBLE_ARM32:
case CONVERT_SATURATING:
return (x != x) ? 0 : (x < INT32_MIN) ? INT32_MIN : (x > INT32_MAX) ? INT32_MAX : (int32_t)x;
case CONVERT_NATIVECOMPILERBEHAVIOR: // handled above, but add case to silence warning
return 0;
}
return 0;
}
extern "C" DLLEXPORT uint32_t ConvertDoubleToUInt32(double x, FPtoIntegerConversionType t)
{
if (t == CONVERT_NATIVECOMPILERBEHAVIOR)
return (uint32_t)x;
x = trunc(x); // truncate (round toward zero)
const double int64_max_plus_1 = 0x1.p63; // 0x43e0000000000000 // (uint64_t)INT64_MAX + 1;
switch (t) {
case CONVERT_MANAGED_BACKWARD_COMPATIBLE_X86_X64:
case CONVERT_BACKWARD_COMPATIBLE:
return ((x != x) || (x < INT64_MIN) || (x >= int64_max_plus_1)) ? 0 : (uint32_t)(int64_t)x;
case CONVERT_SENTINEL:
return ((x != x) || (x < 0) || (x > UINT32_MAX)) ? UINT32_MAX : (uint32_t)x;
case CONVERT_MANAGED_BACKWARD_COMPATIBLE_ARM32:
case CONVERT_SATURATING:
return ((x != x) || (x < 0)) ? 0 : (x > UINT32_MAX) ? UINT32_MAX : (uint32_t)x;
case CONVERT_NATIVECOMPILERBEHAVIOR: // handled above, but add case to silence warning
return 0;
}
return 0;
}
static uint64_t CppNativeArm32ConvertDoubleToUInt64(double y)
{
const double uintmax_plus_1 = -2.0 * (double)INT32_MIN;
uint32_t hi32Bits = ConvertDoubleToUInt32(y / uintmax_plus_1, CONVERT_SATURATING);
uint32_t lo32Bits = ConvertDoubleToUInt32(y - (((double)hi32Bits) * uintmax_plus_1), CONVERT_SATURATING);
return (((uint64_t)hi32Bits) << 32) + lo32Bits;
}
extern "C" DLLEXPORT int64_t ConvertDoubleToInt64(double x, FPtoIntegerConversionType t)
{
if (t == CONVERT_NATIVECOMPILERBEHAVIOR)
return (int64_t)x;
x = trunc(x); // truncate (round toward zero)
// (double)INT64_MAX cannot be represented exactly as double
const double int64_max_plus_1 = 0x1.p63; // 0x43e0000000000000 // (uint64_t)INT64_MAX + 1;
const double int64_min = -0x1.p63; // 0xC3E0000000000000 // INT64_MIN
const double uint64_max_plus_1 = 0x1.p64; // 43f0000000000000; // -2.0 * (double)INT64_MIN;
const double two63 = 0x1.p63; // 0x43e0000000000000 // (uint64_t)INT64_MAX + 1;
const double int32_min = -0x1.p31;// c1e0000000000000// INT32_MIN;
const double int32_max = 0x1.fffffffcp30;// 41dfffffffc00000 // INT32_MAX;
const double int32_max_plus1 = ((double)INT32_MAX) + 1;
switch (t) {
case CONVERT_MANAGED_BACKWARD_COMPATIBLE_X86_X64:
case CONVERT_BACKWARD_COMPATIBLE:
case CONVERT_SENTINEL:
return ((x != x) || (x < INT64_MIN) || (x >= int64_max_plus_1)) ? INT64_MIN : (int64_t)x;
case CONVERT_MANAGED_BACKWARD_COMPATIBLE_ARM32:
if (x > 0)
{
return (int64_t)CppNativeArm32ConvertDoubleToUInt64(x);
}
else
{
return -(int64_t)CppNativeArm32ConvertDoubleToUInt64(-x);
}
case CONVERT_SATURATING:
return (x != x) ? 0 : (x < INT64_MIN) ? INT64_MIN : (x >= int64_max_plus_1) ? INT64_MAX : (int64_t)x;
case CONVERT_NATIVECOMPILERBEHAVIOR: // handled above, but add case to silence warning
return 0;
}
return 0;
}
extern "C" DLLEXPORT uint64_t ConvertDoubleToUInt64(double x, FPtoIntegerConversionType t)
{
if (t == CONVERT_NATIVECOMPILERBEHAVIOR)
return (uint64_t)x;
x = trunc(x); // truncate (round toward zero)
// (double)UINT64_MAX cannot be represented exactly as double
const double uint64_max_plus_1 = -2.0 * (double)INT64_MIN;
// (double)INT64_MAX cannot be represented exactly as double
const double int64_max_plus_1 = 0x1.p63; // 0x43e0000000000000 // (uint64_t)INT64_MAX + 1;
switch (t) {
case CONVERT_BACKWARD_COMPATIBLE:
return ((x != x) || (x < INT64_MIN) || (x >= uint64_max_plus_1)) ? (uint64_t)INT64_MIN : (x < 0) ? (uint64_t)(int64_t)x : (uint64_t)x;
case CONVERT_SENTINEL:
return ((x != x) || (x < 0) || (x >= uint64_max_plus_1)) ? UINT64_MAX : (uint64_t)x;
case CONVERT_SATURATING:
return ((x != x) || (x < 0)) ? 0 : (x >= uint64_max_plus_1) ? UINT64_MAX : (uint64_t)x;
case CONVERT_MANAGED_BACKWARD_COMPATIBLE_ARM32:
{
if (x < int64_max_plus_1)
{
return (uint64_t)ConvertDoubleToInt64(x, CONVERT_MANAGED_BACKWARD_COMPATIBLE_ARM32);
}
else
{
return (uint64_t)ConvertDoubleToInt64(x - int64_max_plus_1, CONVERT_MANAGED_BACKWARD_COMPATIBLE_ARM32) + (0x8000000000000000);
}
}
case CONVERT_MANAGED_BACKWARD_COMPATIBLE_X86_X64:
if (x < int64_max_plus_1)
{
return (x < INT64_MIN) ? (uint64_t)INT64_MIN : (uint64_t)(int64_t)x;
}
else
{
x -= int64_max_plus_1;
x = trunc(x);
return (uint64_t)(((x != x) || (x >= int64_max_plus_1)) ? INT64_MIN : (int64_t)x) + (0x8000000000000000);
}
case CONVERT_NATIVECOMPILERBEHAVIOR: // handled above, but add case to silence warning
return 0;
}
return 0;
}
| 2,897 |
348 |
{"nom":"Avesnelles","circ":"12ème circonscription","dpt":"Nord","inscrits":1963,"abs":1222,"votants":741,"blancs":43,"nuls":27,"exp":671,"res":[{"nuance":"REM","nom":"<NAME>","voix":379},{"nuance":"FN","nom":"<NAME>","voix":292}]}
| 91 |
678 |
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/ManagedConfiguration.framework/ManagedConfiguration
*/
#import <ManagedConfiguration/MCPayload.h>
@interface MCUnknownPayload : MCPayload {
}
- (id)description; // 0x1d61d
- (id)subtitle1Description; // 0x1d689
@end
| 111 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay
{"nom":"<NAME>","dpt":"Yvelines","inscrits":43,"abs":13,"votants":30,"blancs":4,"nuls":1,"exp":25,"res":[{"panneau":"1","voix":13},{"panneau":"2","voix":12}]}
| 87 |
808 |
/*
* Copyright 2017 dmfs GmbH
*
* 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.dmfs.provider.tasks.processors.tasks;
import android.database.sqlite.SQLiteDatabase;
import org.dmfs.provider.tasks.TaskDatabaseHelper;
import org.dmfs.provider.tasks.model.TaskAdapter;
import org.dmfs.provider.tasks.processors.EntityProcessor;
import org.dmfs.tasks.contract.TaskContract;
/**
* A processor that performs the actual operations on tasks.
*
* @author <NAME>
*/
public final class TaskCommitProcessor implements EntityProcessor<TaskAdapter>
{
@Override
public TaskAdapter insert(SQLiteDatabase db, TaskAdapter task, boolean isSyncAdapter)
{
task.commit(db);
return task;
}
@Override
public TaskAdapter update(SQLiteDatabase db, TaskAdapter task, boolean isSyncAdapter)
{
task.commit(db);
return task;
}
@Override
public void delete(SQLiteDatabase db, TaskAdapter task, boolean isSyncAdapter)
{
String accountType = task.valueOf(TaskAdapter.ACCOUNT_TYPE);
if (isSyncAdapter || TaskContract.LOCAL_ACCOUNT_TYPE.equals(accountType))
{
// this is a local task or it's removed by a sync adapter, in either case we delete it right away
db.delete(TaskDatabaseHelper.Tables.TASKS, TaskContract.TaskColumns._ID + "=" + task.id(), null);
}
else
{
// just set the deleted flag otherwise
task.set(TaskAdapter._DELETED, true);
task.commit(db);
}
}
}
| 719 |
515 |
#ifndef BITCOIN_SIGHASHTYPE_H
#define BITCOIN_SIGHASHTYPE_H
#include <string>
#include <cstdint>
/** Signature hash types/flags */
enum class SigHashType : uint32_t
{
UNDEFINED = 0,
ALL = 1,
NONE = 2,
SINGLE = 3,
FORKID = 0x40,
ANYONECANPAY = 0x80,
};
inline SigHashType operator|(SigHashType lhs, SigHashType rhs) {
return static_cast<SigHashType>(
static_cast<uint32_t>(lhs) | static_cast<uint32_t>(rhs));
}
inline SigHashType operator&(SigHashType lhs, SigHashType rhs) {
return static_cast<SigHashType>(
static_cast<uint32_t>(lhs) & static_cast<uint32_t>(rhs));
}
inline SigHashType operator~(SigHashType rhs) {
return static_cast<SigHashType>(~static_cast<uint32_t>(rhs));
}
inline bool operator!(SigHashType rhs) {
return !static_cast<uint32_t>(rhs);
}
inline SigHashType& operator|=(SigHashType& lhs, SigHashType rhs) {
lhs = static_cast<SigHashType>(
static_cast<uint32_t>(lhs) | static_cast<uint32_t>(rhs));
return lhs;
}
inline SigHashType& operator&=(SigHashType& lhs, SigHashType rhs) {
lhs = static_cast<SigHashType>(
static_cast<uint32_t>(lhs) & static_cast<uint32_t>(rhs));
return lhs;
}
SigHashType GetBaseType(SigHashType);
SigHashType RemoveBaseType(SigHashType);
SigHashType FromStr(const std::string& sighashtype);
std::string ToStr(SigHashType);
uint32_t ToInt(SigHashType);
std::ostream& operator<<(std::ostream& stream, const SigHashType& h);
#endif // BITCOIN_SIGHASHTYPE_H
| 654 |
478 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "pch.h"
#include "Util.h"
#include "AdaptiveColorConfig.h"
#include "AdaptiveHighlightColorConfig.h"
#include "AdaptiveColorConfig.g.cpp"
namespace winrt::AdaptiveCards::Rendering::Uwp::implementation
{
AdaptiveColorConfig::AdaptiveColorConfig(::AdaptiveCards::ColorConfig colorConfig)
{
Default = GetColorFromString(colorConfig.defaultColor);
Subtle = GetColorFromString(colorConfig.subtleColor);
HighlightColors = winrt::make<implementation::AdaptiveHighlightColorConfig>(colorConfig.highlightColors);
}
}
| 215 |
852 |
import FWCore.ParameterSet.Config as cms
process = cms.Process("TestCocoa")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.MessageLogger.debugModules = cms.untracked.vstring('cocoa')
process.MessageLogger.cout = cms.untracked.PSet(
threshold = cms.untracked.string('DEBUG')
)
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) )
# A data source must always be defined. We don't need it, so here's a dummy one.
process.source = cms.Source("EmptyIOVSource",
timetype = cms.string('runnumber'),
firstValue = cms.uint64(1),
lastValue = cms.uint64(1),
interval = cms.uint64(1)
)
# dd4hep-based geometry
process.DDDetectorESProducer = cms.ESSource("DDDetectorESProducer",
confGeomXMLFiles = cms.FileInPath('Alignment/CocoaApplication/test/cmsCocoaTable2DWithMirror.xml'),
appendToDataLabel = cms.string('')
)
process.DDCompactViewESProducer = cms.ESProducer("DDCompactViewESProducer",
appendToDataLabel = cms.string('')
)
process.load("CondCore.CondDB.CondDB_cfi")
process.CondDB.connect = 'sqlite_file:OpticalAlignments.db'
# Read DB: this is used to correct internal geometry with geo from DB.
process.PoolDBESSource = cms.ESSource("PoolDBESSource",
process.CondDB,
DumpStat=cms.untracked.bool(True),
toGet = cms.VPSet(cms.PSet(
record = cms.string('OpticalAlignmentsRcd'),
tag = cms.string("OpticalAlignmentsRcdInput")
)),
)
# Write COCOA output to DB ('Output tag')
process.PoolDBOutputService = cms.Service("PoolDBOutputService",
process.CondDB,
timetype = cms.untracked.string('runnumber'),
toPut = cms.VPSet(
cms.PSet(
record = cms.string('OpticalAlignmentsRcd'),
tag = cms.string('OpticalAlignmentsRcdOutput')
),
cms.PSet(
record = cms.string('DTAlignmentRcd'),
tag = cms.string('DTAlignmentRcdOutput')
),
cms.PSet(
record = cms.string('DTAlignmentErrorExtendedRcd'),
tag = cms.string('DTAlignmentErrorExtendedRcdOutput')
),
cms.PSet(
record = cms.string('CSCAlignmentRcd'),
tag = cms.string('CSCAlignmentRcdOutput')
),
cms.PSet(
record = cms.string('CSCAlignmentErrorExtendedRcd'),
tag = cms.string('CSCAlignmentErrorExtendedRcdOutput')
),
)
)
# Run COCOA
process.cocoa = cms.EDAnalyzer('CocoaAnalyzer',
maxEvents = cms.int32(1),
cocoaDaqRootFile = cms.string("cocoaDaqTest.root")
)
process.p = cms.Path(process.cocoa)
| 1,476 |
584 |
<filename>src/test/java/org/springframework/data/mapping/model/PersistentPropertyAccessorTests.java
/*
* Copyright 2018-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mapping.model;
import static org.assertj.core.api.Assertions.*;
import lombok.Data;
import lombok.Value;
import lombok.With;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.data.classloadersupport.HidingClassLoader;
import org.springframework.data.mapping.PersistentPropertyAccessor;
import org.springframework.data.mapping.context.SampleMappingContext;
import org.springframework.data.mapping.context.SamplePersistentProperty;
import org.springframework.util.Assert;
/**
* Unit tests for {@link PersistentPropertyAccessor} through {@link BeanWrapper} and
* {@link ClassGeneratingPropertyAccessorFactory}.
*
* @author <NAME>
*/
public class PersistentPropertyAccessorTests {
private final static SampleMappingContext MAPPING_CONTEXT = new SampleMappingContext();
@SuppressWarnings("unchecked")
public static List<Object[]> parameters() {
List<Object[]> parameters = new ArrayList<>();
ClassGeneratingPropertyAccessorFactory factory = new ClassGeneratingPropertyAccessorFactory();
Function<Object, PersistentPropertyAccessor<?>> beanWrapper = BeanWrapper::new;
Function<Object, PersistentPropertyAccessor<?>> classGenerating = it -> factory
.getPropertyAccessor(MAPPING_CONTEXT.getRequiredPersistentEntity(it.getClass()), it);
parameters.add(new Object[] { beanWrapper, "BeanWrapper" });
parameters.add(new Object[] { classGenerating, "ClassGeneratingPropertyAccessorFactory" });
return parameters;
}
@ParameterizedTest // DATACMNS-1322
@MethodSource("parameters")
void shouldSetProperty(Function<Object, PersistentPropertyAccessor<?>> propertyAccessorFunction) {
DataClass bean = new DataClass();
PersistentPropertyAccessor accessor = propertyAccessorFunction.apply(bean);
SamplePersistentProperty property = getProperty(bean, "id");
accessor.setProperty(property, "value");
assertThat(accessor.getBean()).hasFieldOrPropertyWithValue("id", "value");
assertThat(accessor.getBean()).isSameAs(bean);
assertThat(accessor.getProperty(property)).isEqualTo("value");
}
@ParameterizedTest // DATACMNS-1322
@MethodSource("parameters")
void shouldSetKotlinDataClassProperty(Function<Object, PersistentPropertyAccessor<?>> propertyAccessorFunction) {
DataClassKt bean = new DataClassKt("foo");
PersistentPropertyAccessor accessor = propertyAccessorFunction.apply(bean);
SamplePersistentProperty property = getProperty(bean, "id");
accessor.setProperty(property, "value");
assertThat(accessor.getBean()).hasFieldOrPropertyWithValue("id", "value");
assertThat(accessor.getBean()).isNotSameAs(bean);
assertThat(accessor.getProperty(property)).isEqualTo("value");
}
@ParameterizedTest // DATACMNS-1322, DATACMNS-1391
@MethodSource("parameters")
void shouldSetExtendedKotlinDataClassProperty(
Function<Object, PersistentPropertyAccessor<?>> propertyAccessorFunction) {
ExtendedDataClassKt bean = new ExtendedDataClassKt(0, "bar");
PersistentPropertyAccessor accessor = propertyAccessorFunction.apply(bean);
SamplePersistentProperty property = getProperty(bean, "id");
accessor.setProperty(property, 1L);
assertThat(accessor.getBean()).hasFieldOrPropertyWithValue("id", 1L);
assertThat(accessor.getBean()).isNotSameAs(bean);
assertThat(accessor.getProperty(property)).isEqualTo(1L);
}
@ParameterizedTest // DATACMNS-1391
@MethodSource("parameters")
void shouldUseKotlinGeneratedCopyMethod(Function<Object, PersistentPropertyAccessor<?>> propertyAccessorFunction) {
UnusedCustomCopy bean = new UnusedCustomCopy(new Timestamp(100));
PersistentPropertyAccessor accessor = propertyAccessorFunction.apply(bean);
SamplePersistentProperty property = getProperty(bean, "date");
accessor.setProperty(property, new Timestamp(200));
assertThat(accessor.getBean()).hasFieldOrPropertyWithValue("date", new Timestamp(200));
assertThat(accessor.getBean()).isNotSameAs(bean);
assertThat(accessor.getProperty(property)).isEqualTo(new Timestamp(200));
}
@ParameterizedTest // DATACMNS-1391
@MethodSource("parameters")
void kotlinCopyMethodShouldNotSetUnsettableProperty(
Function<Object, PersistentPropertyAccessor<?>> propertyAccessorFunction) {
SingleSettableProperty bean = new SingleSettableProperty(1.1);
PersistentPropertyAccessor accessor = propertyAccessorFunction.apply(bean);
SamplePersistentProperty property = getProperty(bean, "version");
assertThatThrownBy(() -> accessor.setProperty(property, 1)).isInstanceOf(UnsupportedOperationException.class);
}
@ParameterizedTest // DATACMNS-1451
@MethodSource("parameters")
void shouldSet17thImmutableNullableKotlinProperty(
Function<Object, PersistentPropertyAccessor<?>> propertyAccessorFunction) {
With33Args bean = new With33Args();
PersistentPropertyAccessor accessor = propertyAccessorFunction.apply(bean);
SamplePersistentProperty property = getProperty(bean, "17");
accessor.setProperty(property, "foo");
With33Args updated = (With33Args) accessor.getBean();
assertThat(updated.get17()).isEqualTo("foo");
}
@ParameterizedTest // DATACMNS-1322
@MethodSource("parameters")
void shouldWitherProperty(Function<Object, PersistentPropertyAccessor<?>> propertyAccessorFunction) {
ValueClass bean = new ValueClass("foo", "bar");
PersistentPropertyAccessor accessor = propertyAccessorFunction.apply(bean);
SamplePersistentProperty property = getProperty(bean, "id");
accessor.setProperty(property, "value");
assertThat(accessor.getBean()).hasFieldOrPropertyWithValue("id", "value");
assertThat(accessor.getBean()).isNotSameAs(bean);
assertThat(accessor.getProperty(property)).isEqualTo("value");
}
@ParameterizedTest // DATACMNS-1322
@MethodSource("parameters")
void shouldRejectImmutablePropertyUpdate(Function<Object, PersistentPropertyAccessor<?>> propertyAccessorFunction) {
ValueClass bean = new ValueClass("foo", "bar");
PersistentPropertyAccessor accessor = propertyAccessorFunction.apply(bean);
SamplePersistentProperty property = getProperty(bean, "immutable");
assertThatThrownBy(() -> accessor.setProperty(property, "value")).isInstanceOf(UnsupportedOperationException.class);
}
@ParameterizedTest // DATACMNS-1322
@MethodSource("parameters")
void shouldRejectImmutableKotlinClassPropertyUpdate(
Function<Object, PersistentPropertyAccessor<?>> propertyAccessorFunction) {
ValueClassKt bean = new ValueClassKt("foo");
PersistentPropertyAccessor accessor = propertyAccessorFunction.apply(bean);
SamplePersistentProperty property = getProperty(bean, "immutable");
assertThatThrownBy(() -> accessor.setProperty(property, "value")).isInstanceOf(UnsupportedOperationException.class);
}
@Test // DATACMNS-1422
void shouldUseReflectionIfFrameworkTypesNotVisible() throws Exception {
HidingClassLoader classLoader = HidingClassLoader.hide(Assert.class);
classLoader.excludePackage("org.springframework.data.mapping.model");
Class<?> entityType = classLoader
.loadClass("org.springframework.data.mapping.model.PersistentPropertyAccessorTests$ClassLoaderTest");
ClassGeneratingPropertyAccessorFactory factory = new ClassGeneratingPropertyAccessorFactory();
BasicPersistentEntity<Object, SamplePersistentProperty> entity = MAPPING_CONTEXT
.getRequiredPersistentEntity(entityType);
assertThat(factory.isSupported(entity)).isFalse();
}
private static SamplePersistentProperty getProperty(Object bean, String propertyName) {
return MAPPING_CONTEXT.getRequiredPersistentEntity(bean.getClass()).getRequiredPersistentProperty(propertyName);
}
@Data
static class DataClass {
String id;
}
static class ClassLoaderTest {}
@Value
private static class ValueClass {
@With String id;
String immutable;
}
static class UnsettableVersion {
private final int version = (int) Math.random();
}
}
| 2,637 |
1,068 |
<filename>handlebars/src/test/java/com/github/jknack/handlebars/issues/Issue611.java
package com.github.jknack.handlebars.issues;
import com.github.jknack.handlebars.v4Test;
import org.junit.Test;
public class Issue611 extends v4Test {
@Test
public void shouldScapeRightBracket() throws Exception {
shouldCompileTo("<div class=\"entry\">\n"
+ " <h1>{{ fields.[Special [case\\]] }}</h1>\n"
+ "</div>", $("hash", $("fields", $("Special [case\\]", "yo"))), "<div class=\"entry\">\n"
+ " <h1>yo</h1>\n"
+ "</div>");
}
}
| 237 |
14,668 |
<filename>chrome/browser/ui/hid/hid_chooser_controller_unittest.cc
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <set>
#include <string>
#include <utility>
#include "base/callback_helpers.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "chrome/browser/hid/hid_chooser_context.h"
#include "chrome/browser/hid/hid_chooser_context_factory.h"
#include "chrome/browser/hid/mock_hid_device_observer.h"
#include "chrome/browser/ui/hid/hid_chooser_controller.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "components/permissions/mock_chooser_controller_view.h"
#include "content/public/browser/hid_chooser.h"
#include "content/public/test/web_contents_tester.h"
#include "services/device/public/cpp/hid/fake_hid_manager.h"
#include "services/device/public/cpp/hid/hid_switches.h"
#include "services/device/public/mojom/hid.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/resource/resource_bundle.h"
#include "url/gurl.h"
using ::base::test::RunClosure;
using ::testing::_;
namespace {
constexpr char kDefaultTestUrl[] = "https://www.google.com/";
const char* const kTestPhysicalDeviceIds[] = {"1", "2", "3"};
constexpr uint16_t kVendorYubico = 0x1050;
constexpr uint16_t kProductYubicoGnubby = 0x0200;
constexpr uint16_t kUsageFidoU2f = 0x0001;
class HidChooserControllerTest : public ChromeRenderViewHostTestHarness {
public:
HidChooserControllerTest() = default;
HidChooserControllerTest(HidChooserControllerTest&) = delete;
HidChooserControllerTest& operator=(HidChooserControllerTest&) = delete;
~HidChooserControllerTest() override = default;
permissions::MockChooserControllerView& view() {
return mock_chooser_controller_view_;
}
MockHidDeviceObserver& device_observer() { return mock_device_observer_; }
void SetUp() override {
ChromeRenderViewHostTestHarness::SetUp();
content::WebContentsTester* web_contents_tester =
content::WebContentsTester::For(web_contents());
web_contents_tester->NavigateAndCommit(GURL(kDefaultTestUrl));
// Set fake HID manager for HidChooserContext.
mojo::PendingRemote<device::mojom::HidManager> hid_manager;
hid_manager_.Bind(hid_manager.InitWithNewPipeAndPassReceiver());
base::RunLoop run_loop;
auto* chooser_context = HidChooserContextFactory::GetForProfile(profile());
chooser_context->SetHidManagerForTesting(
std::move(hid_manager),
base::BindLambdaForTesting(
[&run_loop](std::vector<device::mojom::HidDeviceInfoPtr> devices) {
run_loop.Quit();
}));
run_loop.Run();
chooser_context->AddDeviceObserver(&mock_device_observer_);
}
void TearDown() override {
auto* chooser_context = HidChooserContextFactory::GetForProfile(profile());
chooser_context->RemoveDeviceObserver(&mock_device_observer_);
ChromeRenderViewHostTestHarness::TearDown();
}
std::unique_ptr<HidChooserController> CreateHidChooserController(
std::vector<blink::mojom::HidDeviceFilterPtr> filters,
content::HidChooser::Callback callback = base::DoNothing()) {
auto hid_chooser_controller = std::make_unique<HidChooserController>(
main_rfh(), std::move(filters), std::move(callback));
hid_chooser_controller->set_view(&mock_chooser_controller_view_);
return hid_chooser_controller;
}
device::mojom::HidDeviceInfoPtr CreateAndAddFakeHidDevice(
const std::string& physical_device_id,
uint32_t vendor_id,
uint16_t product_id,
const std::string& product_string,
const std::string& serial_number,
uint16_t usage_page = device::mojom::kPageGenericDesktop,
uint16_t usage = device::mojom::kGenericDesktopGamePad) {
return hid_manager_.CreateAndAddDeviceWithTopLevelUsage(
physical_device_id, vendor_id, product_id, product_string,
serial_number, device::mojom::HidBusType::kHIDBusTypeUSB, usage_page,
usage);
}
void ConnectDevice(const device::mojom::HidDeviceInfo& device) {
hid_manager_.AddDevice(device.Clone());
}
void DisconnectDevice(const device::mojom::HidDeviceInfo& device) {
hid_manager_.RemoveDevice(device.guid);
}
void UpdateDevice(const device::mojom::HidDeviceInfo& device) {
hid_manager_.ChangeDevice(device.Clone());
}
blink::mojom::DeviceIdFilterPtr CreateVendorFilter(uint16_t vendor_id) {
return blink::mojom::DeviceIdFilter::NewVendor(vendor_id);
}
blink::mojom::DeviceIdFilterPtr CreateVendorAndProductFilter(
uint16_t vendor_id,
uint16_t product_id) {
return blink::mojom::DeviceIdFilter::NewVendorAndProduct(
blink::mojom::VendorAndProduct::New(vendor_id, product_id));
}
blink::mojom::UsageFilterPtr CreatePageFilter(uint16_t usage_page) {
return blink::mojom::UsageFilter::NewPage(usage_page);
}
blink::mojom::UsageFilterPtr CreateUsageAndPageFilter(uint16_t usage_page,
uint16_t usage) {
return blink::mojom::UsageFilter::NewUsageAndPage(
device::mojom::HidUsageAndPage::New(usage, usage_page));
}
private:
device::FakeHidManager hid_manager_;
permissions::MockChooserControllerView mock_chooser_controller_view_;
MockHidDeviceObserver mock_device_observer_;
};
} // namespace
TEST_F(HidChooserControllerTest, EmptyChooser) {
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// Create the HidChooserController. There should be no options.
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
EXPECT_EQ(0u, hid_chooser_controller->NumOptions());
}
TEST_F(HidChooserControllerTest, AddBlockedFidoDevice) {
base::RunLoop device_added_loop;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device blocked by vendor/product ID.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], kVendorYubico,
kProductYubicoGnubby, "gnubby", "001");
device_added_loop.Run();
// 2. Create the HidChooserController. The blocked device should be excluded.
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
EXPECT_EQ(0u, hid_chooser_controller->NumOptions());
}
TEST_F(HidChooserControllerTest, AddUnknownFidoDevice) {
// Devices that expose a top-level collection with the FIDO usage page should
// be blocked even if they aren't on the HID blocklist.
base::RunLoop device_added_loop1;
base::RunLoop device_added_loop2;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop1.QuitClosure()))
.WillOnce(RunClosure(device_added_loop2.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device blocked by HID usage.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "fido", "001",
device::mojom::kPageFido, kUsageFidoU2f);
device_added_loop1.Run();
// 2. Connect a second device blocked by HID usage.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[1], 2, 2, "fido", "002",
device::mojom::kPageFido, 0);
device_added_loop2.Run();
// 3. Create the HidChooserController. The blocked devices should be excluded.
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
EXPECT_EQ(0u, hid_chooser_controller->NumOptions());
}
TEST_F(HidChooserControllerTest, BlockedFidoDeviceAllowedWithFlag) {
base::RunLoop device_added_loop;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Allow WebHID to access devices on the HID blocklist.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisableHidBlocklist);
// 2. Connect a device with the FIDO usage page. The device uses
// vendor/product IDs that are blocked by the HID blocklist.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], kVendorYubico,
kProductYubicoGnubby, "gnubby", "001",
device::mojom::kPageFido, kUsageFidoU2f);
device_added_loop.Run();
// 3. Create the HidChooserController. The blocked device should be included.
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
EXPECT_EQ(u"gnubby", hid_chooser_controller->GetOption(0));
}
TEST_F(HidChooserControllerTest, AddNamedDevice) {
base::RunLoop device_added_loop;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device with a non-empty product name string.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001");
device_added_loop.Run();
// 2. Create the HidChooserController. The option text should include the
// product name.
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
}
TEST_F(HidChooserControllerTest, AddUnnamedDevice) {
base::RunLoop device_added_loop;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device with an empty product name string.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "", "001");
device_added_loop.Run();
// 2. Create the HidChooserController. The option text should use an alternate
// string.
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
EXPECT_EQ(u"Unknown Device (0001:0001)",
hid_chooser_controller->GetOption(0));
}
TEST_F(HidChooserControllerTest, DeviceIdFilterVendorOnly) {
base::RunLoop device_added_loop1;
base::RunLoop device_added_loop2;
base::RunLoop device_added_loop3;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop1.QuitClosure()))
.WillOnce(RunClosure(device_added_loop2.QuitClosure()))
.WillOnce(RunClosure(device_added_loop3.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001");
device_added_loop1.Run();
// 2. Connect a second device with the same vendor ID.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[1], 1, 2, "b", "002");
device_added_loop2.Run();
// 3. Connect a device with a different vendor ID.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[2], 2, 2, "c", "003");
device_added_loop3.Run();
// 4. Create the HidChooserController with a vendor ID filter. The third
// device should be excluded.
std::vector<blink::mojom::HidDeviceFilterPtr> filters;
filters.push_back(
blink::mojom::HidDeviceFilter::New(CreateVendorFilter(1), nullptr));
auto hid_chooser_controller = CreateHidChooserController(std::move(filters));
options_initialized_loop.Run();
EXPECT_EQ(2u, hid_chooser_controller->NumOptions());
std::set<std::u16string> options{hid_chooser_controller->GetOption(0),
hid_chooser_controller->GetOption(1)};
EXPECT_THAT(options, testing::UnorderedElementsAre(u"a", u"b"));
}
TEST_F(HidChooserControllerTest, DeviceIdFilterVendorAndProduct) {
base::RunLoop device_added_loop1;
base::RunLoop device_added_loop2;
base::RunLoop device_added_loop3;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop1.QuitClosure()))
.WillOnce(RunClosure(device_added_loop2.QuitClosure()))
.WillOnce(RunClosure(device_added_loop3.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001");
device_added_loop1.Run();
// 2. Connect a device with matching vendor ID but non-matching product ID.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[1], 1, 2, "b", "002");
device_added_loop2.Run();
// 3. Connect a device with non-matching vendor and product IDs.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[2], 2, 2, "c", "003");
device_added_loop3.Run();
// 4. Create the HidChooserController with a vendor and product ID filter. The
// second and third devices should be excluded.
std::vector<blink::mojom::HidDeviceFilterPtr> filters;
filters.push_back(blink::mojom::HidDeviceFilter::New(
CreateVendorAndProductFilter(1, 1), nullptr));
auto hid_chooser_controller = CreateHidChooserController(std::move(filters));
options_initialized_loop.Run();
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
}
TEST_F(HidChooserControllerTest, UsageFilterUsagePageOnly) {
base::RunLoop device_added_loop1;
base::RunLoop device_added_loop2;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop1.QuitClosure()))
.WillOnce(RunClosure(device_added_loop2.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop1.Run();
// 2. Connect a device with a different top-level usage page.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[1], 2, 2, "b", "002",
device::mojom::kPageSimulation, 5);
device_added_loop2.Run();
// 3. Create the HidChooserController with a usage page filter. The second
// device should be excluded.
std::vector<blink::mojom::HidDeviceFilterPtr> filters;
filters.push_back(blink::mojom::HidDeviceFilter::New(
nullptr, CreatePageFilter(device::mojom::kPageGenericDesktop)));
auto hid_chooser_controller = CreateHidChooserController(std::move(filters));
options_initialized_loop.Run();
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
}
TEST_F(HidChooserControllerTest, UsageFilterUsageAndPage) {
base::RunLoop device_added_loop1;
base::RunLoop device_added_loop2;
base::RunLoop device_added_loop3;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop1.QuitClosure()))
.WillOnce(RunClosure(device_added_loop2.QuitClosure()))
.WillOnce(RunClosure(device_added_loop3.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop1.Run();
// 2. Connect a device with matching usage page but non-matching usage.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[1], 2, 2, "b", "002",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopKeyboard);
device_added_loop2.Run();
// 3. Connect a device with non-matching usage page and usage.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[2], 3, 3, "c", "003",
device::mojom::kPageSimulation, 5);
device_added_loop3.Run();
// 4. Create the HidChooserController with a usage page and usage filter. The
// second and third devices should be excluded.
std::vector<blink::mojom::HidDeviceFilterPtr> filters;
filters.push_back(blink::mojom::HidDeviceFilter::New(
nullptr,
CreateUsageAndPageFilter(device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad)));
auto hid_chooser_controller = CreateHidChooserController(std::move(filters));
options_initialized_loop.Run();
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
}
TEST_F(HidChooserControllerTest, DeviceIdAndUsageFilterIntersection) {
base::RunLoop device_added_loop1;
base::RunLoop device_added_loop2;
base::RunLoop device_added_loop3;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop1.QuitClosure()))
.WillOnce(RunClosure(device_added_loop2.QuitClosure()))
.WillOnce(RunClosure(device_added_loop3.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop1.Run();
// 2. Connect a device with matching usage page and usage but non-matching
// vendor and product IDs.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[1], 2, 2, "b", "002",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop2.Run();
// 3. Connect a device with matching vendor and product IDs but non-matching
// usage page and usage.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[2], 1, 1, "c", "003",
device::mojom::kPageSimulation, 5);
device_added_loop3.Run();
// 4. Create the HidChooserController with a filter that tests vendor ID,
// product ID, usage page, and usage. The second and third devices should be
// excluded.
std::vector<blink::mojom::HidDeviceFilterPtr> filters;
filters.push_back(blink::mojom::HidDeviceFilter::New(
CreateVendorAndProductFilter(1, 1),
CreateUsageAndPageFilter(device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad)));
auto hid_chooser_controller = CreateHidChooserController(std::move(filters));
options_initialized_loop.Run();
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
}
TEST_F(HidChooserControllerTest, DeviceIdAndUsageFilterUnion) {
base::RunLoop device_added_loop1;
base::RunLoop device_added_loop2;
base::RunLoop device_added_loop3;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop1.QuitClosure()))
.WillOnce(RunClosure(device_added_loop2.QuitClosure()))
.WillOnce(RunClosure(device_added_loop3.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop1.Run();
// 2. Connect a device with matching usage page and usage but non-matching
// vendor and product IDs.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[1], 2, 2, "b", "002",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop2.Run();
// 3. Connect a device with matching vendor and product IDs but non-matching
// usage page and usage.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[2], 1, 1, "c", "003",
device::mojom::kPageSimulation, 5);
device_added_loop3.Run();
// 4. Create the HidChooserController with a vendor/product ID filter and a
// usage page/usage filter. No devices should be excluded.
std::vector<blink::mojom::HidDeviceFilterPtr> filters;
filters.push_back(blink::mojom::HidDeviceFilter::New(
CreateVendorAndProductFilter(1, 1), nullptr));
filters.push_back(blink::mojom::HidDeviceFilter::New(
nullptr,
CreateUsageAndPageFilter(device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad)));
auto hid_chooser_controller = CreateHidChooserController(std::move(filters));
options_initialized_loop.Run();
EXPECT_EQ(3u, hid_chooser_controller->NumOptions());
}
TEST_F(HidChooserControllerTest, OneOptionForSamePhysicalDevice) {
base::RunLoop device_added_loop1;
base::RunLoop device_added_loop2;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop1.QuitClosure()))
.WillOnce(RunClosure(device_added_loop2.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
base::MockCallback<content::HidChooser::Callback> callback;
base::RunLoop callback_loop;
std::vector<device::mojom::HidDeviceInfoPtr> devices;
EXPECT_CALL(callback, Run(_))
.WillOnce([&devices, &callback_loop](
std::vector<device::mojom::HidDeviceInfoPtr> d) {
devices = std::move(d);
callback_loop.Quit();
});
// 1. Connect a device.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop1.Run();
// 2. Connect a second device with the same physical device ID.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001",
device::mojom::kPageSimulation, 5);
device_added_loop2.Run();
// 3. Create the HidChooserController and register a callback to get the
// returned device list. There should be a single chooser option representing
// both devices.
auto hid_chooser_controller = CreateHidChooserController({}, callback.Get());
options_initialized_loop.Run();
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
// 4. Select the chooser option. The returned device list should include both
// devices.
hid_chooser_controller->Select({0});
callback_loop.Run();
EXPECT_EQ(2u, devices.size());
EXPECT_EQ(kTestPhysicalDeviceIds[0], devices[0]->physical_device_id);
EXPECT_EQ(kTestPhysicalDeviceIds[0], devices[1]->physical_device_id);
EXPECT_NE(devices[0]->guid, devices[1]->guid);
// Regression test for https://crbug.com/1069057. Ensure that the
// set of options is still valid after the callback is run.
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
}
TEST_F(HidChooserControllerTest, NoMergeWithDifferentPhysicalDeviceIds) {
base::RunLoop device_added_loop1;
base::RunLoop device_added_loop2;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop1.QuitClosure()))
.WillOnce(RunClosure(device_added_loop2.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop1.Run();
// 2. Connect a second device with the same info as the first device except
// for the physical device ID.
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[1], 1, 1, "a", "001",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop2.Run();
// 3. Create the HidChooserController. The devices should have separate
// chooser options.
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
EXPECT_EQ(2u, hid_chooser_controller->NumOptions());
}
TEST_F(HidChooserControllerTest, NoMergeWithEmptyPhysicalDeviceId) {
base::RunLoop device_added_loop1;
base::RunLoop device_added_loop2;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop1.QuitClosure()))
.WillOnce(RunClosure(device_added_loop2.QuitClosure()));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
// 1. Connect a device with an empty physical device ID.
CreateAndAddFakeHidDevice("", 1, 1, "a", "001",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop1.Run();
// 2. Connect a second device with an empty physical device ID.
CreateAndAddFakeHidDevice("", 1, 1, "a", "001",
device::mojom::kPageSimulation, 5);
device_added_loop2.Run();
// 3. Create the HidChooserController. The devices should have separate
// chooser options.
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
EXPECT_EQ(2u, hid_chooser_controller->NumOptions());
}
TEST_F(HidChooserControllerTest, DeviceConnectAddsOption) {
EXPECT_CALL(device_observer(), OnDeviceAdded(_));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
base::RunLoop option_added_loop;
EXPECT_CALL(view(), OnOptionAdded(0))
.WillOnce(RunClosure(option_added_loop.QuitClosure()));
// 1. Create the HidChooserController.
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
EXPECT_EQ(0u, hid_chooser_controller->NumOptions());
// 2. Connect a device and verify a chooser option is added.
auto device =
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
option_added_loop.Run();
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
}
TEST_F(HidChooserControllerTest, DeviceDisconnectRemovesOption) {
base::RunLoop device_added_loop;
EXPECT_CALL(device_observer(), OnDeviceAdded(_))
.WillOnce(RunClosure(device_added_loop.QuitClosure()));
EXPECT_CALL(device_observer(), OnDeviceRemoved(_));
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized())
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
base::RunLoop option_removed_loop;
EXPECT_CALL(view(), OnOptionRemoved(0))
.WillOnce(RunClosure(option_removed_loop.QuitClosure()));
// 1. Connect a device.
auto device =
CreateAndAddFakeHidDevice(kTestPhysicalDeviceIds[0], 1, 1, "a", "001",
device::mojom::kPageGenericDesktop,
device::mojom::kGenericDesktopGamePad);
device_added_loop.Run();
// 2. Create the HidChooserController and verify that the device is included.
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
EXPECT_EQ(1u, hid_chooser_controller->NumOptions());
// 3. Disconnect the device and verify the chooser option is removed.
DisconnectDevice(*device);
option_removed_loop.Run();
EXPECT_EQ(0u, hid_chooser_controller->NumOptions());
}
namespace {
device::mojom::HidDeviceInfoPtr CreateDeviceWithOneCollection(
const std::string& guid) {
auto device_info = device::mojom::HidDeviceInfo::New();
device_info->guid = guid;
device_info->physical_device_id = "physical-device-id";
device_info->vendor_id = 1;
device_info->product_id = 1;
device_info->product_name = "a";
auto collection = device::mojom::HidCollectionInfo::New();
collection->usage = device::mojom::HidUsageAndPage::New(1, 1);
collection->input_reports.push_back(
device::mojom::HidReportDescription::New());
device_info->collections.push_back(std::move(collection));
return device_info;
}
device::mojom::HidDeviceInfoPtr CreateDeviceWithTwoCollections(
const std::string guid) {
auto device_info = CreateDeviceWithOneCollection(guid);
auto collection = device::mojom::HidCollectionInfo::New();
collection->usage = device::mojom::HidUsageAndPage::New(2, 2);
collection->output_reports.push_back(
device::mojom::HidReportDescription::New());
device_info->collections.push_back(std::move(collection));
return device_info;
}
} // namespace
TEST_F(HidChooserControllerTest, DeviceChangeUpdatesDeviceInfo) {
const char kTestGuid[] = "guid";
// Connect a partially-initialized device with one collection.
base::RunLoop device_added_loop;
EXPECT_CALL(device_observer(), OnDeviceAdded).WillOnce([&](const auto& d) {
EXPECT_EQ(d.guid, kTestGuid);
EXPECT_EQ(d.collections.size(), 1u);
device_added_loop.Quit();
});
auto partial_device = CreateDeviceWithOneCollection(kTestGuid);
ConnectDevice(*partial_device);
device_added_loop.Run();
// Create the HidChooserController.
base::MockCallback<content::HidChooser::Callback> callback;
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized)
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
auto hid_chooser_controller = CreateHidChooserController({}, callback.Get());
options_initialized_loop.Run();
// Check that the option is present.
EXPECT_EQ(hid_chooser_controller->NumOptions(), 1u);
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
// Update the device to add another collection.
base::RunLoop device_changed_loop;
EXPECT_CALL(device_observer(), OnDeviceChanged).WillOnce([&](const auto& d) {
EXPECT_EQ(d.guid, kTestGuid);
EXPECT_EQ(d.collections.size(), 2u);
device_changed_loop.Quit();
});
auto complete_device = CreateDeviceWithTwoCollections(kTestGuid);
UpdateDevice(*complete_device);
device_changed_loop.Run();
// Check that the option is still present and the name has not changed.
EXPECT_EQ(hid_chooser_controller->NumOptions(), 1u);
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
// Select the option and check that only the updated device info is returned.
base::RunLoop callback_loop;
EXPECT_CALL(callback, Run).WillOnce([&](auto devices) {
ASSERT_EQ(devices.size(), 1u);
EXPECT_EQ(devices[0]->guid, kTestGuid);
EXPECT_EQ(devices[0]->collections.size(), 2u);
callback_loop.Quit();
});
hid_chooser_controller->Select({0});
callback_loop.Run();
}
TEST_F(HidChooserControllerTest, ExcludedDeviceChangedToIncludedDevice) {
const char kTestGuid[] = "guid";
// Connect a partially-initialized device with one collection.
base::RunLoop device_added_loop;
EXPECT_CALL(device_observer(), OnDeviceAdded).WillOnce([&](const auto& d) {
EXPECT_EQ(d.guid, kTestGuid);
EXPECT_EQ(d.collections.size(), 1u);
device_added_loop.Quit();
});
auto partial_device = CreateDeviceWithOneCollection(kTestGuid);
ConnectDevice(*partial_device);
device_added_loop.Run();
// Create the HidChooserController. Set a usage page filter that excludes
// |partial_device|.
std::vector<blink::mojom::HidDeviceFilterPtr> filters;
filters.push_back(
blink::mojom::HidDeviceFilter::New(nullptr, CreatePageFilter(2)));
base::MockCallback<content::HidChooser::Callback> callback;
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized)
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
auto hid_chooser_controller =
CreateHidChooserController(std::move(filters), callback.Get());
options_initialized_loop.Run();
// Check that the option is not present.
EXPECT_EQ(hid_chooser_controller->NumOptions(), 0u);
// Update the device to add another collection. Now the device should be
// allowed by the filter.
base::RunLoop option_added_loop;
EXPECT_CALL(view(), OnOptionAdded(0))
.WillOnce(RunClosure(option_added_loop.QuitClosure()));
EXPECT_CALL(device_observer(), OnDeviceChanged).WillOnce([&](const auto& d) {
EXPECT_EQ(d.guid, kTestGuid);
EXPECT_EQ(d.collections.size(), 2u);
});
auto complete_device = CreateDeviceWithTwoCollections(kTestGuid);
UpdateDevice(*complete_device);
option_added_loop.Run();
// Check that the option has been added.
EXPECT_EQ(hid_chooser_controller->NumOptions(), 1u);
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
// Select the option and check that only the updated device info is returned.
base::RunLoop callback_loop;
EXPECT_CALL(callback, Run).WillOnce([&](auto devices) {
ASSERT_EQ(devices.size(), 1u);
EXPECT_EQ(devices[0]->guid, kTestGuid);
EXPECT_EQ(devices[0]->collections.size(), 2u);
callback_loop.Quit();
});
hid_chooser_controller->Select({0});
callback_loop.Run();
}
TEST_F(HidChooserControllerTest, DeviceChangedToBlockedDevice) {
const char kTestGuid[] = "guid";
// Connect a partially-initialized device with one collection.
base::RunLoop device_added_loop;
EXPECT_CALL(device_observer(), OnDeviceAdded).WillOnce([&](const auto& d) {
EXPECT_EQ(d.guid, kTestGuid);
EXPECT_EQ(d.collections.size(), 1u);
device_added_loop.Quit();
});
auto partial_device = CreateDeviceWithOneCollection(kTestGuid);
ConnectDevice(*partial_device);
device_added_loop.Run();
// Create the HidChooserController.
base::RunLoop options_initialized_loop;
EXPECT_CALL(view(), OnOptionsInitialized)
.WillOnce(RunClosure(options_initialized_loop.QuitClosure()));
auto hid_chooser_controller = CreateHidChooserController({});
options_initialized_loop.Run();
// Check that the option is present.
EXPECT_EQ(hid_chooser_controller->NumOptions(), 1u);
EXPECT_EQ(u"a", hid_chooser_controller->GetOption(0));
// Update the device to add another collection with the FIDO usage page.
// Devices with any FIDO collection are blocked, so the chooser option should
// be removed.
base::RunLoop option_removed_loop;
EXPECT_CALL(view(), OnOptionRemoved(0))
.WillOnce(RunClosure(option_removed_loop.QuitClosure()));
EXPECT_CALL(device_observer(), OnDeviceChanged).WillOnce([&](const auto& d) {
EXPECT_EQ(d.guid, kTestGuid);
EXPECT_EQ(d.collections.size(), 2u);
});
auto complete_device = CreateDeviceWithTwoCollections(kTestGuid);
complete_device->collections[1]->usage->usage_page = device::mojom::kPageFido;
UpdateDevice(*complete_device);
option_removed_loop.Run();
// Check that the option has been removed.
EXPECT_EQ(hid_chooser_controller->NumOptions(), 0u);
}
| 13,414 |
940 |
/*
* test-powerpc.cpp - PowerPC regression testing
*
* Kheperix (C) 2003-2005 <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// NOTE: Results file md5sum: 3e29432abb6e21e625a2eef8cf2f0840 ($Revision$)
#include <vector>
#include <limits>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <netinet/in.h> // ntohl(), htonl()
#include <setjmp.h>
#include <signal.h>
#include <ctype.h>
#include <math.h>
#if defined(__powerpc__) || defined(__ppc__)
#define NATIVE_POWERPC
#endif
#if EMU_KHEPERIX
#include "sysdeps.h"
#include "vm_alloc.h"
#include "cpu/ppc/ppc-cpu.hpp"
#include "cpu/ppc/ppc-instructions.hpp"
#endif
#if EMU_MICROLIB
#include <ppcemul.h>
typedef unsigned int uint32;
typedef unsigned long uintptr;
#undef RD
#undef RA
#undef RB
#undef FB
#undef FE
#endif
#if EMU_MODEL3PPC
extern "C" {
#include "ppc.h"
}
typedef unsigned int uint32;
typedef unsigned long uintptr;
typedef uint32_t UINT32;
typedef char CHAR;
typedef int BOOL;
#endif
#if EMU_QEMU
extern "C" {
#include "target-ppc/cpu.h"
extern void tb_flush();
}
typedef uint32_t uint32;
typedef uintptr_t uintptr;
#endif
// Disassemblers needed for debugging purposes
#if ENABLE_MON
#include "mon.h"
#include "mon_disass.h"
#endif
// Define units to test (in-order: ALU, FPU, VMX)
#define TEST_ALU_OPS 1
#if EMU_KHEPERIX
#define TEST_FPU_OPS 1
#define TEST_VMX_OPS 1
#endif
// Define units to skip during testing
#define SKIP_ALU_OPS 0
#define SKIP_FPU_OPS 0
#define SKIP_VMX_OPS 0
// Define instructions to test
#define TEST_ADD 1
#define TEST_SUB 1
#define TEST_MUL 1
#define TEST_DIV 1
#define TEST_SHIFT 1
#define TEST_ROTATE 1
#define TEST_MISC 1
#define TEST_LOGICAL 1
#define TEST_COMPARE 1
#define TEST_CR_LOGICAL 1
#define TEST_VMX_LOADSH 1
#define TEST_VMX_LOAD 1
#define TEST_VMX_ARITH 1
// Partial PowerPC runtime assembler from GNU lightning
#undef _I
#define _I(X) ((uint32)(X))
#undef _UL
#define _UL(X) ((uint32)(X))
#undef _MASK
#define _MASK(N) ((uint32)((1<<(N)))-1)
#undef _ck_s
#define _ck_s(W,I) (_UL(I) & _MASK(W))
#undef _ck_u
#define _ck_u(W,I) (_UL(I) & _MASK(W))
#undef _ck_su
#define _ck_su(W,I) (_UL(I) & _MASK(W))
#undef _u1
#define _u1(I) _ck_u( 1,I)
#undef _u5
#define _u5(I) _ck_u( 5,I)
#undef _u6
#define _u6(I) _ck_u( 6,I)
#undef _u9
#define _u9(I) _ck_u( 9,I)
#undef _u10
#define _u10(I) _ck_u(10,I)
#undef _u11
#define _u11(I) _ck_u(11,I)
#undef _s16
#define _s16(I) _ck_s(16,I)
#undef _D
#define _D( OP,RD,RA, DD ) _I((_u6(OP)<<26)|(_u5(RD)<<21)|(_u5(RA)<<16)| _s16(DD) )
#undef _X
#define _X( OP,RD,RA,RB, XO,RC ) _I((_u6(OP)<<26)|(_u5(RD)<<21)|(_u5(RA)<<16)|( _u5(RB)<<11)| (_u10(XO)<<1)|_u1(RC))
#undef _XO
#define _XO( OP,RD,RA,RB,OE,XO,RC ) _I((_u6(OP)<<26)|(_u5(RD)<<21)|(_u5(RA)<<16)|( _u5(RB)<<11)|(_u1(OE)<<10)|( _u9(XO)<<1)|_u1(RC))
#undef _M
#define _M( OP,RS,RA,SH,MB,ME,RC ) _I((_u6(OP)<<26)|(_u5(RS)<<21)|(_u5(RA)<<16)|( _u5(SH)<<11)|(_u5(MB)<< 6)|( _u5(ME)<<1)|_u1(RC))
#undef _VX
#define _VX( OP,VD,VA,VB, XO ) _I((_u6(OP)<<26)|(_u5(VD)<<21)|(_u5(VA)<<16)|( _u5(VB)<<11)| _u11(XO) )
#undef _VXR
#define _VXR( OP,VD,VA,VB, XO,RC ) _I((_u6(OP)<<26)|(_u5(VD)<<21)|(_u5(VA)<<16)|( _u5(VB)<<11)| (_u1(RC)<<10)|_u10(XO))
#undef _VA
#define _VA( OP,VD,VA,VB,VC,XO ) _I((_u6(OP)<<26)|(_u5(VD)<<21)|(_u5(VA)<<16)|( _u5(VB)<<11)|(_u5(VC)<< 6)| _u6(XO) )
// PowerPC opcodes
static inline uint32 POWERPC_LI(int RD, uint32 v) { return _D(14,RD,00,(v&0xffff)); }
static inline uint32 POWERPC_MR(int RD, int RA) { return _X(31,RA,RD,RA,444,0); }
static inline uint32 POWERPC_MFCR(int RD) { return _X(31,RD,00,00,19,0); }
static inline uint32 POWERPC_LVX(int vD, int rA, int rB) { return _X(31,vD,rA,rB,103,0); }
static inline uint32 POWERPC_STVX(int vS, int rA, int rB) { return _X(31,vS,rA,rB,231,0); }
static inline uint32 POWERPC_MFSPR(int rD, int SPR) { return _X(31,rD,(SPR&0x1f),((SPR>>5)&0x1f),339,0); }
static inline uint32 POWERPC_MTSPR(int rS, int SPR) { return _X(31,rS,(SPR&0x1f),((SPR>>5)&0x1f),467,0); }
const uint32 POWERPC_NOP = 0x60000000;
const uint32 POWERPC_BLR = 0x4e800020;
const uint32 POWERPC_BLRL = 0x4e800021;
const uint32 POWERPC_ILLEGAL = 0x00000000;
const uint32 POWERPC_EMUL_OP = 0x18000000;
// Invalidate test cache
#ifdef NATIVE_POWERPC
static void inline ppc_flush_icache_range(uint32 *start_p, uint32 length)
{
const int MIN_CACHE_LINE_SIZE = 8; /* conservative value */
unsigned long start = (unsigned long)start_p;
unsigned long stop = start + length;
unsigned long p;
p = start & ~(MIN_CACHE_LINE_SIZE - 1);
stop = (stop + MIN_CACHE_LINE_SIZE - 1) & ~(MIN_CACHE_LINE_SIZE - 1);
for (p = start; p < stop; p += MIN_CACHE_LINE_SIZE) {
asm volatile ("dcbst 0,%0" : : "r"(p) : "memory");
}
asm volatile ("sync" : : : "memory");
for (p = start; p < stop; p += MIN_CACHE_LINE_SIZE) {
asm volatile ("icbi 0,%0" : : "r"(p) : "memory");
}
asm volatile ("sync" : : : "memory");
asm volatile ("isync" : : : "memory");
}
#else
static void inline ppc_flush_icache_range(uint32 *start_p, uint32 length)
{
}
#endif
#if EMU_KHEPERIX
// Wrappers when building from SheepShaver tree
#ifdef SHEEPSHAVER
uint32 ROMBase = 0x40800000;
int64 TimebaseSpeed = 25000000; // Default: 25 MHz
uint32 PVR = 0x000c0000; // Default: 7400 (with AltiVec)
bool PrefsFindBool(const char *name)
{
return false;
}
uint64 GetTicks_usec(void)
{
return clock();
}
void HandleInterrupt(powerpc_registers *)
{
}
#if PPC_ENABLE_JIT && PPC_REENTRANT_JIT
void init_emul_op_trampolines(basic_dyngen & dg)
{
}
#endif
#endif
struct powerpc_cpu_base
: public powerpc_cpu
{
powerpc_cpu_base();
void init_decoder();
void execute_return(uint32 opcode);
void invalidate_cache_range(uint32 *start, uint32 size)
{ powerpc_cpu::invalidate_cache_range((uintptr)start, ((uintptr)start) + size); }
uint32 emul_get_xer() const { return xer().get(); }
void emul_set_xer(uint32 value) { xer().set(value); }
uint32 emul_get_cr() const { return cr().get(); }
void emul_set_cr(uint32 value) { cr().set(value); }
uint32 get_lr() const { return lr(); }
void set_lr(uint32 value) { lr() = value; }
uint32 get_gpr(int i) const { return gpr(i); }
void set_gpr(int i, uint32 value) { gpr(i) = value; }
};
powerpc_cpu_base::powerpc_cpu_base()
#ifndef SHEEPSHAVER
: powerpc_cpu(NULL)
#endif
{
init_decoder();
}
void powerpc_cpu_base::execute_return(uint32 opcode)
{
spcflags().set(SPCFLAG_CPU_EXEC_RETURN);
}
void powerpc_cpu_base::init_decoder()
{
static const instr_info_t return_ii_table[] = {
{ "return",
(execute_pmf)&powerpc_cpu_base::execute_return,
PPC_I(MAX),
D_form, 6, 0, CFLOW_JUMP
}
};
const int ii_count = sizeof(return_ii_table)/sizeof(return_ii_table[0]);
for (int i = 0; i < ii_count; i++) {
const instr_info_t * ii = &return_ii_table[i];
init_decoder_entry(ii);
}
}
#endif
#if EMU_MICROLIB
static volatile bool ppc_running = false;
struct powerpc_cpu_base
{
powerpc_cpu_base();
void execute(uintptr);
void enable_jit() { }
void invalidate_cache() { }
void invalidate_cache_range(uint32 *start, uint32 size) { }
uint32 emul_get_xer() const { return XER; }
void emul_set_xer(uint32 value) { XER = value; }
uint32 emul_get_cr() const { return CR; }
void emul_set_cr(uint32 value) { CR = value; }
uint32 get_lr() const { return LR; }
void set_lr(uint32 value) { LR = value; }
uint32 get_gpr(int i) const { return GPR(i); }
void set_gpr(int i, uint32 value) { GPR(i) = value; }
};
void sheep_impl(ppc_inst_t inst)
{
ppc_running = false;
}
extern "C" void init_table(int opcd, void (*impl)(ppc_inst_t), char *(*bin2c)(ppc_inst_t, addr_t, char *), char *(*disasm)(ppc_inst_t, addr_t, char *), void (*translate)(ppc_inst_t, struct DecodedInstruction *), void (*xmlize)(ppc_inst_t, addr_t, char *), char *mnemonic);
powerpc_cpu_base::powerpc_cpu_base()
{
ppc_init();
init_table(6, sheep_impl, NULL, NULL, NULL, NULL, "sheep");
}
#define ppc_code_fetch(A) ntohl(*((uint32 *)(A)))
void powerpc_cpu_base::execute(uintptr entry_point)
{
PC = entry_point;
ppc_running = true;
while (ppc_running) {
ppc_inst_t inst = ppc_code_fetch(PC);
ppc_execute(inst);
}
}
#endif
#if EMU_MODEL3PPC
extern "C" BOOL DisassemblePowerPC(UINT32, UINT32, CHAR *, CHAR *, BOOL);
BOOL DisassemblePowerPC(UINT32, UINT32, CHAR *, CHAR *, BOOL) { }
static volatile bool ppc_running = false;
struct powerpc_cpu_base
{
powerpc_cpu_base();
void execute(uintptr);
void enable_jit() { }
void invalidate_cache() { }
void invalidate_cache_range(uint32 *start, uint32 size) { }
uint32 emul_get_xer() const { return ppc_get_reg(PPC_REG_XER); }
void emul_set_xer(uint32 value) { ppc_set_reg(PPC_REG_XER, value); }
uint32 emul_get_cr() const { return ppc_get_reg(PPC_REG_CR); }
void emul_set_cr(uint32 value) { ppc_set_reg(PPC_REG_CR, value); }
uint32 get_lr() const { return ppc_get_reg(PPC_REG_LR); }
void set_lr(uint32 value) { ppc_set_reg(PPC_REG_LR, value); }
uint32 get_gpr(int i) const { return ppc_get_r(i); }
void set_gpr(int i, uint32 value) { ppc_set_r(i, value); }
};
static uint32 read_32(uint32 a)
{
return ntohl(*((uint32 *)a));
}
static uint32 read_op(uint32 a)
{
uint32 opcode = read_32(a);
if (opcode == POWERPC_EMUL_OP) {
ppc_running = false;
return POWERPC_NOP;
}
return opcode;
}
powerpc_cpu_base::powerpc_cpu_base()
{
ppc_init(NULL);
ppc_set_read_32_handler((void *)&read_32);
ppc_set_read_op_handler((void *)&read_op);
}
void powerpc_cpu_base::execute(uintptr entry_point)
{
ppc_set_reg(PPC_REG_PC, entry_point);
ppc_running = true;
while (ppc_running)
ppc_run(1);
}
#endif
#if EMU_QEMU
class powerpc_cpu_base
{
CPUPPCState *ppc;
public:
powerpc_cpu_base();
~powerpc_cpu_base();
void execute(uintptr);
void enable_jit() { }
void invalidate_cache() { tb_flush(); }
void invalidate_cache_range(uint32 *start, uint32 size) { invalidate_cache(); }
uint32 emul_get_xer() const;
void emul_set_xer(uint32 value);
uint32 emul_get_cr() const;
void emul_set_cr(uint32 value);
uint32 get_lr() const { return ppc->LR; }
void set_lr(uint32 value) { ppc->LR = value; }
uint32 get_gpr(int i) const { return ppc->gpr[i]; }
void set_gpr(int i, uint32 value) { ppc->gpr[i] = value; }
};
uint32 powerpc_cpu_base::emul_get_xer() const
{
uint32 xer = 0;
for (int i = 0; i < 32; i++)
xer |= ppc->xer[i] << i;
return xer;
}
void powerpc_cpu_base::emul_set_xer(uint32 value)
{
for (int i = 0; i < 32; i++)
ppc->xer[i] = (value >> i) & 1;
}
uint32 powerpc_cpu_base::emul_get_cr() const
{
uint32 cr = 0;
for (int i = 0; i < 8; i++)
cr |= (ppc->crf[i] & 15) << (28 - 4 * i);
return cr;
}
void powerpc_cpu_base::emul_set_cr(uint32 value)
{
for (int i = 0; i < 8; i++)
ppc->crf[i] = (value >> (28 - 4 * i)) & 15;
}
powerpc_cpu_base::powerpc_cpu_base()
{
ppc = cpu_ppc_init();
}
powerpc_cpu_base::~powerpc_cpu_base()
{
cpu_ppc_close(ppc);
}
void powerpc_cpu_base::execute(uintptr entry_point)
{
ppc->nip = entry_point;
cpu_exec(ppc);
}
#endif
// Define bit-fields
#if !EMU_KHEPERIX
template< int FB, int FE >
struct static_mask {
enum { value = (0xffffffff >> FB) ^ (0xffffffff >> (FE + 1)) };
};
template< int FB >
struct static_mask<FB, 31> {
enum { value = 0xffffffff >> FB };
};
template< int FB, int FE >
struct bit_field {
static inline uint32 mask() {
return static_mask<FB, FE>::value;
}
static inline bool test(uint32 value) {
return value & mask();
}
static inline uint32 extract(uint32 value) {
const uint32 m = mask() >> (31 - FE);
return (value >> (31 - FE)) & m;
}
static inline void insert(uint32 & data, uint32 value) {
const uint32 m = mask();
data = (data & ~m) | ((value << (31 - FE)) & m);
}
};
// General purpose registers
typedef bit_field< 11, 15 > rA_field;
typedef bit_field< 16, 20 > rB_field;
typedef bit_field< 6, 10 > rD_field;
typedef bit_field< 6, 10 > rS_field;
// Vector registers
typedef bit_field< 11, 15 > vA_field;
typedef bit_field< 16, 20 > vB_field;
typedef bit_field< 21, 25 > vC_field;
typedef bit_field< 6, 10 > vD_field;
typedef bit_field< 6, 10 > vS_field;
typedef bit_field< 22, 25 > vSH_field;
// Condition registers
typedef bit_field< 11, 15 > crbA_field;
typedef bit_field< 16, 20 > crbB_field;
typedef bit_field< 6, 10 > crbD_field;
typedef bit_field< 6, 8 > crfD_field;
typedef bit_field< 11, 13 > crfS_field;
// CR register fields
template< int CRn > struct CR_field : bit_field< 4*CRn+0, 4*CRn+3 > { };
template< int CRn > struct CR_LT_field : bit_field< 4*CRn+0, 4*CRn+0 > { };
template< int CRn > struct CR_GT_field : bit_field< 4*CRn+1, 4*CRn+1 > { };
template< int CRn > struct CR_EQ_field : bit_field< 4*CRn+2, 4*CRn+2 > { };
template< int CRn > struct CR_SO_field : bit_field< 4*CRn+3, 4*CRn+3 > { };
template< int CRn > struct CR_UN_field : bit_field< 4*CRn+3, 4*CRn+3 > { };
// Immediates
typedef bit_field< 16, 31 > UIMM_field;
typedef bit_field< 21, 25 > MB_field;
typedef bit_field< 26, 30 > ME_field;
typedef bit_field< 16, 20 > SH_field;
// XER register fields
typedef bit_field< 0, 0 > XER_SO_field;
typedef bit_field< 1, 1 > XER_OV_field;
typedef bit_field< 2, 2 > XER_CA_field;
#endif
#undef CA
#define CA XER_CA_field::mask()
#undef OV
#define OV XER_OV_field::mask()
#undef SO
#define SO XER_SO_field::mask()
// Flag: does the host support AltiVec instructions?
static bool has_altivec = true;
// A 128-bit AltiVec register
typedef uint8 vector_t[16];
class aligned_vector_t {
struct {
vector_t v;
uint8 pad[16];
} vs;
public:
aligned_vector_t()
{ clear(); }
void clear()
{ memset(addr(), 0, sizeof(vector_t)); }
void copy(vector_t const & vi, int n = sizeof(vector_t))
{ clear(); memcpy(addr(), &vi, n); }
vector_t *addr() const
{ return (vector_t *)(((char *)&vs.v) + (16 - (((uintptr)&vs.v) % 16))); }
vector_t const & value() const
{ return *addr(); }
vector_t & value()
{ return *addr(); }
};
union vector_helper_t {
vector_t v;
uint8 b[16];
uint16 h[8];
uint32 w[4];
float f[4];
};
static void print_vector(vector_t const & v, char type = 'b')
{
vector_helper_t x;
memcpy(&x.b, &v, sizeof(vector_t));
printf("{");
switch (type) {
case 'b':
default:
for (int i = 0; i < 16; i++) {
if (i != 0)
printf(",");
printf(" %02x", x.b[i]);
}
break;
case 'h':
for (int i = 0; i < 8; i++) {
if (i != 0)
printf(",");
printf(" %04x", x.h[i]);
}
break;
case 'w':
for (int i = 0; i < 4; i++) {
if (i != 0)
printf(",");
printf(" %08x", x.w[i]);
}
break;
case 'f':
case 'e': // estimate result
case 'l': // estimate log2 result
for (int i = 0; i < 4; i++) {
x.w[i] = ntohl(x.w[i]);
if (i != 0)
printf(",");
printf(" %g", x.f[i]);
}
break;
}
printf(" }");
}
static inline bool do_float_equals(float a, float b, float tolerance)
{
if (a == b)
return true;
if (isnan(a) && isnan(b))
return true;
if (isinf(a) && isinf(b) && signbit(a) == signbit(b))
return true;
if ((b < (a + tolerance)) && (b > (a - tolerance)))
return true;
return false;
}
static inline bool float_equals(float a, float b)
{
return do_float_equals(a, b, 3 * std::numeric_limits<float>::epsilon());
}
static bool vector_equals(char type, vector_t const & a, vector_t const & b)
{
// the vector is in ppc big endian format
float tolerance;
switch (type) {
case 'f':
tolerance = 3 * std::numeric_limits<float>::epsilon();
goto do_compare;
case 'l': // FIXME: this does not handle |x-1|<=1/8 case
tolerance = 1. / 32.;
goto do_compare;
case 'e':
tolerance = 1. / 4096.;
do_compare:
for (int i = 0; i < 4; i++) {
union { float f; uint32 i; } u, v;
u.i = ntohl(((uint32 *)&a)[i]);
v.i = ntohl(((uint32 *)&b)[i]);
if (!do_float_equals(u.f, v.f, tolerance))
return false;
}
return true;
}
return memcmp(&a, &b, sizeof(vector_t)) == 0;
}
static bool vector_all_eq(char type, vector_t const & b)
{
uint32 v;
vector_helper_t x;
memcpy(&x.v, &b, sizeof(vector_t));
bool all_eq = true;
switch (type) {
case 'b':
default:
v = x.b[0];
for (int i = 1; all_eq && i < 16; i++)
if (x.b[i] != v)
all_eq = false;
break;
case 'h':
v = x.h[0];
for (int i = 1; all_eq && i < 8; i++)
if (x.h[i] != v)
all_eq = false;
break;
case 'w':
case 'f':
v = x.w[0];
for (int i = 1; all_eq && i < 4; i++)
if (x.w[i] != v)
all_eq = false;
break;
}
return all_eq;
}
// Define PowerPC tester
class powerpc_test_cpu
: public powerpc_cpu_base
{
#ifdef NATIVE_POWERPC
uint32 native_get_xer() const
{ uint32 xer; asm volatile ("mfxer %0" : "=r" (xer)); return xer; }
void native_set_xer(uint32 xer) const
{ asm volatile ("mtxer %0" : : "r" (xer)); }
uint32 native_get_cr() const
{ uint32 cr; asm volatile ("mfcr %0" : "=r" (cr)); return cr; }
void native_set_cr(uint32 cr) const
{ asm volatile ("mtcr %0" : : "r" (cr)); }
#endif
void flush_icache_range(uint32 *start, uint32 size)
{ invalidate_cache_range(start, size); ppc_flush_icache_range(start, size); }
void print_xer_flags(uint32 xer) const;
void print_flags(uint32 cr, uint32 xer, int crf = 0) const;
void execute(uint32 *code);
public:
powerpc_test_cpu();
~powerpc_test_cpu();
bool test(void);
void set_results_file(FILE *fp)
{ results_file = fp; }
private:
static const bool verbose = false;
uint32 tests, errors;
// Results file for reference
FILE *results_file;
uint32 get32();
void put32(uint32 v);
void get_vector(vector_t & v);
void put_vector(vector_t const & v);
// Initial CR0, XER states
uint32 init_cr;
uint32 init_xer;
// XER preset values to test with
std::vector<uint32> xer_values;
void gen_xer_values(uint32 use_mask, uint32 set_mask);
// Emulated registers IDs
enum {
RD = 3,
RA = 4,
RB = 5,
RC = 6,
VSCR = 7,
};
// Operands
enum {
__,
vD, vS, vA, vB, vC, vI, vN,
rD, rS, rA, rB, rC,
};
struct vector_test_t {
uint8 name[14];
char type;
char op_type;
uint32 opcode;
uint8 operands[4];
};
struct vector_value_t {
char type;
vector_t v;
};
static const uint32 reg_values[];
static const uint32 imm_values[];
static const uint32 msk_values[];
static const vector_value_t vector_values[];
static const vector_value_t vector_fp_values[];
void test_one_1(uint32 *code, const char *insn, uint32 a1, uint32 a2, uint32 a3, uint32 a0 = 0);
void test_one(uint32 *code, const char *insn, uint32 a1, uint32 a2, uint32 a3, uint32 a0 = 0);
void test_instruction_CNTLZ(const char *insn, uint32 opcode);
void test_instruction_RR___(const char *insn, uint32 opcode);
void test_instruction_RRI__(const char *insn, uint32 opcode);
#define test_instruction_RRK__ test_instruction_RRI__
void test_instruction_RRS__(const char *insn, uint32 opcode);
void test_instruction_RRR__(const char *insn, uint32 opcode);
void test_instruction_RRRSH(const char *insn, uint32 opcode);
void test_instruction_RRIII(const char *insn, uint32 opcode);
void test_instruction_RRRII(const char *insn, uint32 opcode);
void test_instruction_CRR__(const char *insn, uint32 opcode);
void test_instruction_CRI__(const char *insn, uint32 opcode);
#define test_instruction_CRK__ test_instruction_CRI__
void test_instruction_CCC__(const char *insn, uint32 opcode);
void test_add(void);
void test_sub(void);
void test_mul(void);
void test_div(void);
void test_shift(void);
void test_rotate(void);
void test_logical(void);
void test_compare(void);
void test_cr_logical(void);
void test_one_vector(uint32 *code, vector_test_t const & vt, uint8 *rA, uint8 *rB = 0, uint8 *rC = 0);
void test_one_vector(uint32 *code, vector_test_t const & vt, vector_t const *vA = 0, vector_t const *vB = 0, vector_t const *vC = 0)
{ test_one_vector(code, vt, (uint8 *)vA, (uint8 *)vB, (uint8 *)vC); }
void test_vector_load(void);
void test_vector_load_for_shift(void);
void test_vector_arith(void);
};
powerpc_test_cpu::powerpc_test_cpu()
: powerpc_cpu_base(), results_file(NULL)
{
#if ENABLE_MON
mon_init();
#endif
}
powerpc_test_cpu::~powerpc_test_cpu()
{
#if ENABLE_MON
mon_exit();
#endif
}
uint32 powerpc_test_cpu::get32()
{
uint32 v;
if (fread(&v, sizeof(v), 1, results_file) != 1) {
fprintf(stderr, "ERROR: unexpected end of results file\n");
exit(EXIT_FAILURE);
}
return ntohl(v);
}
void powerpc_test_cpu::put32(uint32 v)
{
uint32 out = htonl(v);
if (fwrite(&out, sizeof(out), 1, results_file) != 1) {
fprintf(stderr, "could not write item to results file\n");
exit(EXIT_FAILURE);
}
}
void powerpc_test_cpu::get_vector(vector_t & v)
{
if (fread(&v, sizeof(v), 1, results_file) != 1) {
fprintf(stderr, "ERROR: unexpected end of results file\n");
exit(EXIT_FAILURE);
}
}
void powerpc_test_cpu::put_vector(vector_t const & v)
{
if (fwrite(&v, sizeof(v), 1, results_file) != 1) {
fprintf(stderr, "could not write vector to results file\n");
exit(EXIT_FAILURE);
}
}
void powerpc_test_cpu::execute(uint32 *code_p)
{
static uint32 code[2];
code[0] = htonl(POWERPC_BLRL);
code[1] = htonl(POWERPC_EMUL_OP);
#ifndef NATIVE_POWERPC
const int n_func_words = 1024;
static uint32 func[n_func_words];
static int old_i;
again:
int i = old_i;
for (int j = 0; ; j++, i++) {
if (i >= n_func_words) {
old_i = 0;
invalidate_cache();
goto again;
}
uint32 opcode = code_p[j];
func[i] = htonl(opcode);
if (opcode == POWERPC_BLR)
break;
}
code_p = &func[old_i];
old_i = i;
#endif
assert((uintptr)code_p <= UINT_MAX);
set_lr((uintptr)code_p);
assert((uintptr)code <= UINT_MAX);
powerpc_cpu_base::execute((uintptr)code);
}
void powerpc_test_cpu::gen_xer_values(uint32 use_mask, uint32 set_mask)
{
const uint32 mask = use_mask | set_mask;
// Always test with XER=0
xer_values.clear();
xer_values.push_back(0);
// Iterate over XER fields, only handle CA, OV, SO
for (uint32 m = 0x80000000; m != 0; m >>= 1) {
if (m & (CA | OV | SO) & mask) {
const int n_xer_values = xer_values.size();
for (int i = 0; i < n_xer_values; i++)
xer_values.push_back(xer_values[i] | m);
}
}
#if 0
printf("%d XER values\n", xer_values.size());
for (int i = 0; i < xer_values.size(); i++) {
print_xer_flags(xer_values[i]);
printf("\n");
}
#endif
}
void powerpc_test_cpu::print_xer_flags(uint32 xer) const
{
printf("%s,%s,%s",
(xer & XER_CA_field::mask() ? "CA" : "__"),
(xer & XER_OV_field::mask() ? "OV" : "__"),
(xer & XER_SO_field::mask() ? "SO" : "__"));
}
void powerpc_test_cpu::print_flags(uint32 cr, uint32 xer, int crf) const
{
cr = cr << (4 * crf);
printf("%s,%s,%s,%s,%s,%s",
(cr & CR_LT_field<0>::mask() ? "LT" : "__"),
(cr & CR_GT_field<0>::mask() ? "GT" : "__"),
(cr & CR_EQ_field<0>::mask() ? "EQ" : "__"),
(cr & CR_SO_field<0>::mask() ? "SO" : "__"),
(xer & XER_OV_field::mask() ? "OV" : "__"),
(xer & XER_CA_field::mask() ? "CA" : "__"));
}
#define TEST_INSTRUCTION(FORMAT, NATIVE_OP, EMUL_OP) do { \
printf("Testing " NATIVE_OP "\n"); \
test_instruction_##FORMAT(NATIVE_OP, EMUL_OP); \
} while (0)
void powerpc_test_cpu::test_one(uint32 *code, const char *insn, uint32 a1, uint32 a2, uint32 a3, uint32 a0)
{
// Iterate over test XER values as input
const int n_xer_values = xer_values.size();
for (int i = 0; i < n_xer_values; i++) {
init_xer = xer_values[i];
test_one_1(code, insn, a1, a2, a3, a0);
}
init_xer = 0;
}
void powerpc_test_cpu::test_one_1(uint32 *code, const char *insn, uint32 a1, uint32 a2, uint32 a3, uint32 a0)
{
#ifdef NATIVE_POWERPC
// Invoke native code
const uint32 save_xer = native_get_xer();
const uint32 save_cr = native_get_cr();
native_set_xer(init_xer);
native_set_cr(init_cr);
typedef uint32 (*func_t)(uint32, uint32, uint32);
func_t func = (func_t)code;
const uint32 native_rd = func(a0, a1, a2);
const uint32 native_xer = native_get_xer();
const uint32 native_cr = native_get_cr();
native_set_xer(save_xer);
native_set_cr(save_cr);
if (results_file) {
put32(native_rd);
put32(native_xer);
put32(native_cr);
}
#else
const uint32 native_rd = get32();
const uint32 native_xer = get32();
const uint32 native_cr = get32();
#endif
if (SKIP_ALU_OPS)
return;
// Invoke emulated code
emul_set_xer(init_xer);
emul_set_cr(init_cr);
set_gpr(RD, a0);
set_gpr(RA, a1);
set_gpr(RB, a2);
execute(code);
const uint32 emul_rd = get_gpr(RD);
const uint32 emul_xer = emul_get_xer();
const uint32 emul_cr = emul_get_cr();
++tests;
bool ok = native_rd == emul_rd
&& native_xer == emul_xer
&& native_cr == emul_cr;
if (code[0] == POWERPC_MR(0, RA))
code++;
if (!ok) {
printf("FAIL: %s [%08x]\n", insn, code[0]);
errors++;
}
else if (verbose) {
printf("PASS: %s [%08x]\n", insn, code[0]);
}
if (!ok || verbose) {
#if ENABLE_MON
disass_ppc(stdout, (uintptr)code, code[0]);
#endif
#define PRINT_OPERANDS(PREFIX) do { \
printf(" %08x, %08x, %08x, %08x => %08x [", \
a0, a1, a2, a3, PREFIX##_rd); \
print_flags(PREFIX##_cr, PREFIX##_xer); \
printf("]\n"); \
} while (0)
PRINT_OPERANDS(native);
PRINT_OPERANDS(emul);
#undef PRINT_OPERANDS
}
}
const uint32 powerpc_test_cpu::reg_values[] = {
0x00000000, 0x10000000, 0x20000000,
0x30000000, 0x40000000, 0x50000000,
0x60000000, 0x70000000, 0x80000000,
0x90000000, 0xa0000000, 0xb0000000,
0xc0000000, 0xd0000000, 0xe0000000,
0xf0000000, 0xfffffffd, 0xfffffffe,
0xffffffff, 0x00000001, 0x00000002,
0x00000003, 0x11111111, 0x22222222,
0x33333333, 0x44444444, 0x55555555,
0x66666666, 0x77777777, 0x88888888,
0x99999999, 0xaaaaaaaa, 0xbbbbbbbb,
0xcccccccc, 0xdddddddd, 0xeeeeeeee
};
const uint32 powerpc_test_cpu::imm_values[] = {
0x0000, 0x1000, 0x2000,
0x3000, 0x4000, 0x5000,
0x6000, 0x7000, 0x8000,
0x9000, 0xa000, 0xb000,
0xc000, 0xd000, 0xe000,
0xf000, 0xfffd, 0xfffe,
0xffff, 0x0001, 0x0002,
0x0003, 0x1111, 0x2222,
0x3333, 0x4444, 0x5555,
0x6666, 0x7777, 0x8888,
0x9999, 0xaaaa, 0xbbbb,
0xcccc, 0xdddd, 0xeeee
};
const uint32 powerpc_test_cpu::msk_values[] = {
0, 1,
// 15, 16, 17,
30, 31
};
void powerpc_test_cpu::test_instruction_CNTLZ(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_BLR,
POWERPC_MR(0, RA), POWERPC_ILLEGAL, POWERPC_BLR
};
// Input values
const int n_values = sizeof(reg_values)/sizeof(reg_values[0]);
code[0] = code[3] = opcode; // <op> RD,RA,RB
rA_field::insert(code[3], 0); // <op> RD,R0,RB
flush_icache_range(code, sizeof(code));
for (uint32 mask = 0x80000000; mask != 0; mask >>= 1) {
uint32 ra = mask;
test_one(&code[0], insn, ra, 0, 0);
test_one(&code[2], insn, ra, 0, 0);
}
// random values (including zero)
for (int i = 0; i < n_values; i++) {
uint32 ra = reg_values[i];
test_one(&code[0], insn, ra, 0, 0);
test_one(&code[2], insn, ra, 0, 0);
}
}
void powerpc_test_cpu::test_instruction_RR___(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_BLR,
POWERPC_MR(0, RA), POWERPC_ILLEGAL, POWERPC_BLR
};
// Input values
const int n_values = sizeof(reg_values)/sizeof(reg_values[0]);
code[0] = code[3] = opcode; // <op> RD,RA,RB
rA_field::insert(code[3], 0); // <op> RD,R0,RB
flush_icache_range(code, sizeof(code));
for (int i = 0; i < n_values; i++) {
uint32 ra = reg_values[i];
test_one(&code[0], insn, ra, 0, 0);
test_one(&code[2], insn, ra, 0, 0);
}
}
void powerpc_test_cpu::test_instruction_RRI__(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_BLR,
POWERPC_MR(0, RA), POWERPC_ILLEGAL, POWERPC_BLR
};
// Input values
const int n_reg_values = sizeof(reg_values)/sizeof(reg_values[0]);
const int n_imm_values = sizeof(imm_values)/sizeof(imm_values[0]);
for (int j = 0; j < n_imm_values; j++) {
const uint32 im = imm_values[j];
uint32 op = opcode;
UIMM_field::insert(op, im);
code[0] = code[3] = op; // <op> RD,RA,IM
rA_field::insert(code[3], 0); // <op> RD,R0,IM
flush_icache_range(code, sizeof(code));
for (int i = 0; i < n_reg_values; i++) {
const uint32 ra = reg_values[i];
test_one(&code[0], insn, ra, im, 0);
test_one(&code[2], insn, ra, im, 0);
}
}
}
void powerpc_test_cpu::test_instruction_RRS__(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_BLR,
POWERPC_MR(0, RA), POWERPC_ILLEGAL, POWERPC_BLR
};
// Input values
const int n_values = sizeof(reg_values)/sizeof(reg_values[0]);
for (int j = 0; j < 32; j++) {
const uint32 sh = j;
SH_field::insert(opcode, sh);
code[0] = code[3] = opcode;
rA_field::insert(code[3], 0);
flush_icache_range(code, sizeof(code));
for (int i = 0; i < n_values; i++) {
const uint32 ra = reg_values[i];
test_one(&code[0], insn, ra, sh, 0);
}
}
}
void powerpc_test_cpu::test_instruction_RRR__(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_BLR,
POWERPC_MR(0, RA), POWERPC_ILLEGAL, POWERPC_BLR
};
// Input values
const int n_values = sizeof(reg_values)/sizeof(reg_values[0]);
code[0] = code[3] = opcode; // <op> RD,RA,RB
rA_field::insert(code[3], 0); // <op> RD,R0,RB
flush_icache_range(code, sizeof(code));
for (int i = 0; i < n_values; i++) {
const uint32 ra = reg_values[i];
for (int j = 0; j < n_values; j++) {
const uint32 rb = reg_values[j];
test_one(&code[0], insn, ra, rb, 0);
test_one(&code[2], insn, ra, rb, 0);
}
}
}
void powerpc_test_cpu::test_instruction_RRRSH(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_BLR,
POWERPC_MR(0, RA), POWERPC_ILLEGAL, POWERPC_BLR
};
// Input values
const int n_values = sizeof(reg_values)/sizeof(reg_values[0]);
code[0] = code[3] = opcode; // <op> RD,RA,RB
rA_field::insert(code[3], 0); // <op> RD,R0,RB
flush_icache_range(code, sizeof(code));
for (int i = 0; i < n_values; i++) {
const uint32 ra = reg_values[i];
for (int j = 0; j <= 64; j++) {
const uint32 rb = j;
test_one(&code[0], insn, ra, rb, 0);
test_one(&code[2], insn, ra, rb, 0);
}
}
}
void powerpc_test_cpu::test_instruction_RRIII(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_BLR,
POWERPC_MR(0, RA), POWERPC_ILLEGAL, POWERPC_BLR
};
// Input values
const int n_reg_values = sizeof(reg_values)/sizeof(reg_values[0]);
const int n_msk_values = sizeof(msk_values)/sizeof(msk_values[0]);
for (int sh = 0; sh < 32; sh++) {
for (int i_mb = 0; i_mb < n_msk_values; i_mb++) {
const uint32 mb = msk_values[i_mb];
for (int i_me = 0; i_me < n_msk_values; i_me++) {
const uint32 me = msk_values[i_me];
SH_field::insert(opcode, sh);
MB_field::insert(opcode, mb);
ME_field::insert(opcode, me);
code[0] = opcode;
code[3] = opcode;
rA_field::insert(code[3], 0);
flush_icache_range(code, sizeof(code));
for (int i = 0; i < n_reg_values; i++) {
const uint32 ra = reg_values[i];
test_one(&code[0], insn, ra, sh, 0, 0);
test_one(&code[2], insn, ra, sh, 0, 0);
}
}
}
}
}
void powerpc_test_cpu::test_instruction_RRRII(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_BLR,
POWERPC_MR(0, RA), POWERPC_ILLEGAL, POWERPC_BLR
};
// Input values
const int n_reg_values = sizeof(reg_values)/sizeof(reg_values[0]);
const int n_msk_values = sizeof(msk_values)/sizeof(msk_values[0]);
for (int i_mb = 0; i_mb < n_msk_values; i_mb++) {
const uint32 mb = msk_values[i_mb];
for (int i_me = 0; i_me < n_msk_values; i_me++) {
const uint32 me = msk_values[i_me];
MB_field::insert(opcode, mb);
ME_field::insert(opcode, me);
code[0] = opcode;
code[3] = opcode;
rA_field::insert(code[3], 0);
flush_icache_range(code, sizeof(code));
for (int i = 0; i < n_reg_values; i++) {
const uint32 ra = reg_values[i];
for (int j = -1; j <= 33; j++) {
const uint32 rb = j;
test_one(&code[0], insn, ra, rb, 0, 0);
test_one(&code[2], insn, ra, rb, 0, 0);
}
}
}
}
}
void powerpc_test_cpu::test_instruction_CRR__(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_BLR,
POWERPC_MR(0, RA), POWERPC_ILLEGAL, POWERPC_BLR
};
// Input values
const int n_values = sizeof(reg_values)/sizeof(reg_values[0]);
for (int k = 0; k < 8; k++) {
crfD_field::insert(opcode, k);
code[0] = code[3] = opcode; // <op> crfD,RA,RB
rA_field::insert(code[3], 0); // <op> crfD,R0,RB
flush_icache_range(code, sizeof(code));
for (int i = 0; i < n_values; i++) {
const uint32 ra = reg_values[i];
for (int j = 0; j < n_values; j++) {
const uint32 rb = reg_values[j];
test_one(&code[0], insn, ra, rb, 0);
test_one(&code[2], insn, ra, rb, 0);
}
}
}
}
void powerpc_test_cpu::test_instruction_CRI__(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_BLR,
POWERPC_MR(0, RA), POWERPC_ILLEGAL, POWERPC_BLR
};
// Input values
const int n_reg_values = sizeof(reg_values)/sizeof(reg_values[0]);
const int n_imm_values = sizeof(imm_values)/sizeof(imm_values[0]);
for (int k = 0; k < 8; k++) {
crfD_field::insert(opcode, k);
for (int j = 0; j < n_imm_values; j++) {
const uint32 im = imm_values[j];
UIMM_field::insert(opcode, im);
code[0] = code[3] = opcode; // <op> crfD,RA,SIMM
rA_field::insert(code[3], 0); // <op> crfD,R0,SIMM
flush_icache_range(code, sizeof(code));
for (int i = 0; i < n_reg_values; i++) {
const uint32 ra = reg_values[i];
test_one(&code[0], insn, ra, im, 0);
test_one(&code[2], insn, ra, im, 0);
}
}
}
}
void powerpc_test_cpu::test_instruction_CCC__(const char *insn, uint32 opcode)
{
// Test code
static uint32 code[] = {
POWERPC_ILLEGAL, POWERPC_MFCR(RD), POWERPC_BLR,
};
const uint32 saved_cr = init_cr;
crbD_field::insert(opcode, 0);
// Loop over crbA=[4-7] (crf1), crbB=[28-31] (crf7)
for (int crbA = 4; crbA <= 7; crbA++) {
crbA_field::insert(opcode, crbA);
for (int crbB = 28; crbB <= 31; crbB++) {
crbB_field::insert(opcode, crbB);
code[0] = opcode;
flush_icache_range(code, sizeof(code));
// Generate CR values for (crf1, crf7)
uint32 cr = 0;
for (int i = 0; i < 16; i++) {
CR_field<1>::insert(cr, i);
for (int j = 0; j < 16; j++) {
CR_field<7>::insert(cr, j);
init_cr = cr;
test_one(&code[0], insn, init_cr, 0, 0);
}
}
}
}
init_cr = saved_cr;
}
void powerpc_test_cpu::test_add(void)
{
#if TEST_ADD
gen_xer_values(0, 0);
TEST_INSTRUCTION(RRI__,"addi", _D (14,RD,RA,00));
TEST_INSTRUCTION(RRI__,"addis", _D (15,RD,RA,00));
gen_xer_values(0, SO);
TEST_INSTRUCTION(RRR__,"add", _XO(31,RD,RA,RB,0,266,0));
TEST_INSTRUCTION(RRR__,"add.", _XO(31,RD,RA,RB,0,266,1));
gen_xer_values(0, SO|OV);
TEST_INSTRUCTION(RRR__,"addo", _XO(31,RD,RA,RB,1,266,0));
TEST_INSTRUCTION(RRR__,"addo." , _XO(31,RD,RA,RB,1,266,1));
gen_xer_values(0, SO|CA);
TEST_INSTRUCTION(RRR__,"addc", _XO(31,RD,RA,RB,0, 10,0));
TEST_INSTRUCTION(RRR__,"addc.", _XO(31,RD,RA,RB,0, 10,1));
TEST_INSTRUCTION(RRI__,"addic", _D (12,RD,RA,00));
TEST_INSTRUCTION(RRI__,"addic.", _D (13,RD,RA,00));
gen_xer_values(0, SO|CA|OV);
TEST_INSTRUCTION(RRR__,"addco", _XO(31,RD,RA,RB,1, 10,0));
TEST_INSTRUCTION(RRR__,"addco.", _XO(31,RD,RA,RB,1, 10,1));
gen_xer_values(CA, SO|CA);
TEST_INSTRUCTION(RRR__,"adde", _XO(31,RD,RA,RB,0,138,0));
TEST_INSTRUCTION(RRR__,"adde.", _XO(31,RD,RA,RB,0,138,1));
TEST_INSTRUCTION(RR___,"addme", _XO(31,RD,RA,00,0,234,0));
TEST_INSTRUCTION(RR___,"addme.", _XO(31,RD,RA,00,0,234,1));
TEST_INSTRUCTION(RR___,"addze", _XO(31,RD,RA,00,0,202,0));
TEST_INSTRUCTION(RR___,"addze.", _XO(31,RD,RA,00,0,202,1));
gen_xer_values(CA, SO|CA|OV);
TEST_INSTRUCTION(RRR__,"addeo", _XO(31,RD,RA,RB,1,138,0));
TEST_INSTRUCTION(RRR__,"addeo.", _XO(31,RD,RA,RB,1,138,1));
TEST_INSTRUCTION(RR___,"addmeo", _XO(31,RD,RA,00,1,234,0));
TEST_INSTRUCTION(RR___,"addmeo.", _XO(31,RD,RA,00,1,234,1));
TEST_INSTRUCTION(RR___,"addzeo", _XO(31,RD,RA,00,1,202,0));
TEST_INSTRUCTION(RR___,"addzeo.", _XO(31,RD,RA,00,1,202,1));
#endif
}
void powerpc_test_cpu::test_sub(void)
{
#if TEST_SUB
gen_xer_values(0, SO);
TEST_INSTRUCTION(RRR__,"subf", _XO(31,RD,RA,RB,0, 40,0));
TEST_INSTRUCTION(RRR__,"subf.", _XO(31,RD,RA,RB,0, 40,1));
gen_xer_values(0, SO|OV);
TEST_INSTRUCTION(RRR__,"subfo", _XO(31,RD,RA,RB,1, 40,0));
TEST_INSTRUCTION(RRR__,"subfo.", _XO(31,RD,RA,RB,1, 40,1));
gen_xer_values(0, SO|CA);
TEST_INSTRUCTION(RRR__,"subfc", _XO(31,RD,RA,RB,0, 8,0));
TEST_INSTRUCTION(RRR__,"subfc.", _XO(31,RD,RA,RB,0, 8,1));
gen_xer_values(0, SO|CA|OV);
TEST_INSTRUCTION(RRR__,"subfco", _XO(31,RD,RA,RB,1, 8,0));
TEST_INSTRUCTION(RRR__,"subfco.", _XO(31,RD,RA,RB,1, 8,1));
gen_xer_values(0, CA);
TEST_INSTRUCTION(RRI__,"subfic", _D ( 8,RD,RA,00));
gen_xer_values(CA, SO|CA);
TEST_INSTRUCTION(RRR__,"subfe", _XO(31,RD,RA,RB,0,136,0));
TEST_INSTRUCTION(RRR__,"subfe.", _XO(31,RD,RA,RB,0,136,1));
TEST_INSTRUCTION(RR___,"subfme", _XO(31,RD,RA,00,0,232,0));
TEST_INSTRUCTION(RR___,"subfme.", _XO(31,RD,RA,00,0,232,1));
TEST_INSTRUCTION(RR___,"subfze", _XO(31,RD,RA,00,0,200,0));
TEST_INSTRUCTION(RR___,"subfze.", _XO(31,RD,RA,00,0,200,1));
gen_xer_values(CA, SO|CA|OV);
TEST_INSTRUCTION(RRR__,"subfeo", _XO(31,RD,RA,RB,1,136,0));
TEST_INSTRUCTION(RRR__,"subfeo.", _XO(31,RD,RA,RB,1,136,1));
TEST_INSTRUCTION(RR___,"subfmeo", _XO(31,RD,RA,00,1,232,0));
TEST_INSTRUCTION(RR___,"subfmeo.", _XO(31,RD,RA,00,1,232,1));
TEST_INSTRUCTION(RR___,"subfzeo", _XO(31,RD,RA,00,1,200,0));
TEST_INSTRUCTION(RR___,"subfzeo.", _XO(31,RD,RA,00,1,200,1));
#endif
}
void powerpc_test_cpu::test_mul(void)
{
#if TEST_MUL
gen_xer_values(0, SO);
TEST_INSTRUCTION(RRR__,"mulhw", _XO(31,RD,RA,RB,0, 75,0));
TEST_INSTRUCTION(RRR__,"mulhw.", _XO(31,RD,RA,RB,0, 75,1));
TEST_INSTRUCTION(RRR__,"mulhwu", _XO(31,RD,RA,RB,0, 11,0));
TEST_INSTRUCTION(RRR__,"mulhwu.", _XO(31,RD,RA,RB,0, 11,1));
TEST_INSTRUCTION(RRI__,"mulli", _D ( 7,RD,RA,00));
TEST_INSTRUCTION(RRR__,"mullw", _XO(31,RD,RA,RB,0,235,0));
TEST_INSTRUCTION(RRR__,"mullw.", _XO(31,RD,RA,RB,0,235,1));
gen_xer_values(0, SO|OV);
TEST_INSTRUCTION(RRR__,"mullwo", _XO(31,RD,RA,RB,1,235,0));
TEST_INSTRUCTION(RRR__,"mullwo.", _XO(31,RD,RA,RB,1,235,1));
#endif
}
void powerpc_test_cpu::test_div(void)
{
#if TEST_DIV
gen_xer_values(0, SO);
TEST_INSTRUCTION(RRR__,"divw", _XO(31,RD,RA,RB,0,491,0));
TEST_INSTRUCTION(RRR__,"divw.", _XO(31,RD,RA,RB,0,491,1));
TEST_INSTRUCTION(RRR__,"divwu", _XO(31,RD,RA,RB,0,459,0));
TEST_INSTRUCTION(RRR__,"divwu.", _XO(31,RD,RA,RB,0,459,1));
gen_xer_values(0, SO|OV);
TEST_INSTRUCTION(RRR__,"divwo", _XO(31,RD,RA,RB,1,491,0));
TEST_INSTRUCTION(RRR__,"divwo.", _XO(31,RD,RA,RB,1,491,1));
TEST_INSTRUCTION(RRR__,"divwuo", _XO(31,RD,RA,RB,1,459,0));
TEST_INSTRUCTION(RRR__,"divwuo.", _XO(31,RD,RA,RB,1,459,1));
#endif
}
void powerpc_test_cpu::test_logical(void)
{
#if TEST_LOGICAL
gen_xer_values(0, SO);
TEST_INSTRUCTION(RRR__,"and", _X (31,RA,RD,RB,28,0));
TEST_INSTRUCTION(RRR__,"and.", _X (31,RA,RD,RB,28,1));
TEST_INSTRUCTION(RRR__,"andc", _X (31,RA,RD,RB,60,0));
TEST_INSTRUCTION(RRR__,"andc.", _X (31,RA,RD,RB,60,1));
TEST_INSTRUCTION(RRK__,"andi.", _D (28,RA,RD,00));
TEST_INSTRUCTION(RRK__,"andis.", _D (29,RA,RD,00));
TEST_INSTRUCTION(CNTLZ,"cntlzw", _X (31,RA,RD,00,26,0));
TEST_INSTRUCTION(CNTLZ,"cntlzw.", _X (31,RA,RD,00,26,1));
TEST_INSTRUCTION(RRR__,"eqv", _X (31,RA,RD,RB,284,0));
TEST_INSTRUCTION(RRR__,"eqv.", _X (31,RA,RD,RB,284,1));
TEST_INSTRUCTION(RR___,"extsb", _X (31,RA,RD,00,954,0));
TEST_INSTRUCTION(RR___,"extsb.", _X (31,RA,RD,00,954,1));
TEST_INSTRUCTION(RR___,"extsh", _X (31,RA,RD,00,922,0));
TEST_INSTRUCTION(RR___,"extsh.", _X (31,RA,RD,00,922,1));
TEST_INSTRUCTION(RRR__,"nand", _X (31,RA,RD,RB,476,0));
TEST_INSTRUCTION(RRR__,"nand.", _X (31,RA,RD,RB,476,1));
TEST_INSTRUCTION(RR___,"neg", _XO(31,RD,RA,RB,0,104,0));
TEST_INSTRUCTION(RR___,"neg.", _XO(31,RD,RA,RB,0,104,1));
TEST_INSTRUCTION(RRR__,"nor", _X (31,RA,RD,RB,124,0));
TEST_INSTRUCTION(RRR__,"nor.", _X (31,RA,RD,RB,124,1));
TEST_INSTRUCTION(RRR__,"or", _X (31,RA,RD,RB,444,0));
TEST_INSTRUCTION(RRR__,"or.", _X (31,RA,RD,RB,444,1));
TEST_INSTRUCTION(RRR__,"orc", _X (31,RA,RD,RB,412,0));
TEST_INSTRUCTION(RRR__,"orc.", _X (31,RA,RD,RB,412,1));
TEST_INSTRUCTION(RRK__,"ori", _D (24,RA,RD,00));
TEST_INSTRUCTION(RRK__,"oris", _D (25,RA,RD,00));
TEST_INSTRUCTION(RRR__,"xor", _X (31,RA,RD,RB,316,0));
TEST_INSTRUCTION(RRR__,"xor.", _X (31,RA,RD,RB,316,1));
TEST_INSTRUCTION(RRK__,"xori", _D (26,RA,RD,00));
TEST_INSTRUCTION(RRK__,"xoris", _D (27,RA,RD,00));
gen_xer_values(0, SO|OV);
TEST_INSTRUCTION(RR___,"nego", _XO(31,RD,RA,RB,1,104,0));
TEST_INSTRUCTION(RR___,"nego.", _XO(31,RD,RA,RB,1,104,1));
#endif
}
void powerpc_test_cpu::test_shift(void)
{
#if TEST_SHIFT
gen_xer_values(0, SO);
TEST_INSTRUCTION(RRRSH,"slw", _X (31,RA,RD,RB, 24,0));
TEST_INSTRUCTION(RRRSH,"slw.", _X (31,RA,RD,RB, 24,1));
TEST_INSTRUCTION(RRRSH,"sraw", _X (31,RA,RD,RB,792,0));
TEST_INSTRUCTION(RRRSH,"sraw.", _X (31,RA,RD,RB,792,1));
TEST_INSTRUCTION(RRS__,"srawi", _X (31,RA,RD,00,824,0));
TEST_INSTRUCTION(RRS__,"srawi.", _X (31,RA,RD,00,824,1));
TEST_INSTRUCTION(RRRSH,"srw", _X (31,RA,RD,RB,536,0));
TEST_INSTRUCTION(RRRSH,"srw.", _X (31,RA,RD,RB,536,1));
#endif
}
void powerpc_test_cpu::test_rotate(void)
{
#if TEST_ROTATE
gen_xer_values(0, SO);
TEST_INSTRUCTION(RRIII,"rlwimi", _M (20,RA,RD,00,00,00,0));
TEST_INSTRUCTION(RRIII,"rlwimi.", _M (20,RA,RD,00,00,00,1));
TEST_INSTRUCTION(RRIII,"rlwinm", _M (21,RA,RD,00,00,00,0));
TEST_INSTRUCTION(RRIII,"rlwinm.", _M (21,RA,RD,00,00,00,1));
TEST_INSTRUCTION(RRRII,"rlwnm", _M (23,RA,RD,RB,00,00,0));
TEST_INSTRUCTION(RRRII,"rlwnm.", _M (23,RA,RD,RB,00,00,1));
#endif
}
void powerpc_test_cpu::test_compare(void)
{
#if TEST_COMPARE
gen_xer_values(0, SO);
TEST_INSTRUCTION(CRR__,"cmp", _X (31,00,RA,RB,000,0));
TEST_INSTRUCTION(CRI__,"cmpi", _D (11,00,RA,00));
TEST_INSTRUCTION(CRR__,"cmpl", _X (31,00,RA,RB, 32,0));
TEST_INSTRUCTION(CRK__,"cmpli", _D (10,00,RA,00));
#endif
}
void powerpc_test_cpu::test_cr_logical(void)
{
#if TEST_CR_LOGICAL
gen_xer_values(0, SO);
TEST_INSTRUCTION(CCC__,"crand", _X (19,00,00,00,257,0));
TEST_INSTRUCTION(CCC__,"crandc", _X (19,00,00,00,129,0));
TEST_INSTRUCTION(CCC__,"creqv", _X (19,00,00,00,289,0));
TEST_INSTRUCTION(CCC__,"crnand", _X (19,00,00,00,225,0));
TEST_INSTRUCTION(CCC__,"crnor", _X (19,00,00,00, 33,0));
TEST_INSTRUCTION(CCC__,"cror", _X (19,00,00,00,449,0));
TEST_INSTRUCTION(CCC__,"crorc", _X (19,00,00,00,417,0));
TEST_INSTRUCTION(CCC__,"crxor", _X (19,00,00,00,193,0));
#endif
}
// Template-generated vector values
const powerpc_test_cpu::vector_value_t powerpc_test_cpu::vector_values[] = {
{'w',{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}},
{'w',{0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01}},
{'w',{0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02}},
{'w',{0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03}},
{'w',{0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04}},
{'w',{0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05}},
{'w',{0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06}},
{'w',{0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07}},
{'w',{0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08}},
{'w',{0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10}},
{'w',{0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18}},
{'w',{0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20}},
{'w',{0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28}},
{'w',{0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30}},
{'w',{0x38,0x38,0x38,0x38,0x38,0x38,0x38,0x38,0x38,0x38,0x38,0x38,0x38,0x38,0x38,0x38}},
{'w',{0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40}},
{'w',{0x48,0x48,0x48,0x48,0x48,0x48,0x48,0x48,0x48,0x48,0x48,0x48,0x48,0x48,0x48,0x48}},
{'w',{0x50,0x50,0x50,0x50,0x50,0x50,0x50,0x50,0x50,0x50,0x50,0x50,0x50,0x50,0x50,0x50}},
{'w',{0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58}},
{'w',{0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60}},
{'w',{0x68,0x68,0x68,0x68,0x68,0x68,0x68,0x68,0x68,0x68,0x68,0x68,0x68,0x68,0x68,0x68}},
{'w',{0x70,0x70,0x70,0x70,0x70,0x70,0x70,0x70,0x70,0x70,0x70,0x70,0x70,0x70,0x70,0x70}},
{'w',{0x78,0x78,0x78,0x78,0x78,0x78,0x78,0x78,0x78,0x78,0x78,0x78,0x78,0x78,0x78,0x78}},
{'w',{0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00}},
{'w',{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04}},
{'w',{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10}},
{'w',{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}},
{'w',{0x11,0x11,0x11,0x11,0x22,0x22,0x22,0x22,0x33,0x33,0x33,0x33,0x44,0x44,0x44,0x44}},
{'w',{0x88,0x88,0x88,0x88,0x77,0x77,0x77,0x77,0x66,0x66,0x66,0x66,0x55,0x55,0x55,0x55}},
{'w',{0x99,0x99,0x99,0x99,0xaa,0xaa,0xaa,0xaa,0xbb,0xbb,0xbb,0xbb,0xcc,0xcc,0xcc,0xcc}},
{'w',{0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xee,0xee,0xee,0xee,0xdd,0xdd,0xdd,0xdd}},
{'w',{0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff}},
{'h',{0x00,0x00,0x11,0x11,0x22,0x22,0x33,0x33,0x44,0x44,0x55,0x55,0x66,0x66,0x77,0x77}},
{'h',{0x00,0x01,0x00,0x02,0x00,0x03,0x00,0x04,0x00,0x05,0x00,0x06,0x00,0x07,0x00,0x08}},
{'h',{0x00,0x16,0x00,0x15,0x00,0x14,0x00,0x13,0x00,0x12,0x00,0x10,0x00,0x10,0x00,0x09}},
{'b',{0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff}},
{'b',{0xff,0xee,0xdd,0xcc,0xbb,0xaa,0x99,0x88,0x77,0x66,0x55,0x44,0x33,0x22,0x11,0x00}},
{'b',{0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f}},
{'b',{0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f}},
{'b',{0x2f,0x2e,0x2d,0x2c,0x2b,0x2a,0x29,0x28,0x27,0x26,0x25,0x24,0x23,0x22,0x21,0x20}}
};
const powerpc_test_cpu::vector_value_t powerpc_test_cpu::vector_fp_values[] = {
{'f',{0x80,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x80,0x00,0x00,0x00}}, // -0, -0, -0, -0
{'f',{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}, // 0, 0, 0, 0
{'f',{0xbf,0x80,0x00,0x00,0xbf,0x80,0x00,0x00,0xbf,0x80,0x00,0x00,0xbf,0x80,0x00,0x00}}, // -1, -1, -1, -1
{'f',{0x3f,0x80,0x00,0x00,0x3f,0x80,0x00,0x00,0x3f,0x80,0x00,0x00,0x3f,0x80,0x00,0x00}}, // 1, 1, 1, 1
{'f',{0xc0,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0xc0,0x00,0x00,0x00}}, // -2, -2, -2, -2
{'f',{0x40,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x40,0x00,0x00,0x00}}, // 2, 2, 2, 2
{'f',{0xc0,0x00,0x00,0x00,0xbf,0x80,0x00,0x00,0x3f,0x80,0x00,0x00,0x40,0x00,0x00,0x00}}, // -2, -1, 1, 2
{'f',{0xc0,0x40,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x40,0x00,0x00}}, // -3, -0, 0, 3
{'f',{0x40,0x00,0x00,0x00,0x3f,0x80,0x00,0x00,0xbf,0x80,0x00,0x00,0xc0,0x00,0x00,0x00}} // 2, 1, -1, -2
};
void powerpc_test_cpu::test_one_vector(uint32 *code, vector_test_t const & vt, uint8 *rAp, uint8 *rBp, uint8 *rCp)
{
#if TEST_VMX_OPS
static vector_t native_vD;
memset(&native_vD, 0, sizeof(native_vD));
static vector_helper_t native_vSCR;
memset(&native_vSCR, 0, sizeof(native_vSCR));
static aligned_vector_t dummy_vector;
dummy_vector.clear();
if (!rAp) rAp = (uint8 *)dummy_vector.addr();
if (!rBp) rBp = (uint8 *)dummy_vector.addr();
if (!rCp) rCp = (uint8 *)dummy_vector.addr();
#ifdef NATIVE_POWERPC
// Invoke native code
const uint32 save_cr = native_get_cr();
native_set_cr(init_cr);
native_vSCR.w[3] = 0;
typedef void (*func_t)(uint8 *, uint8 *, uint8 *, uint8 *, uint8 *);
func_t func = (func_t)code;
func((uint8 *)&native_vD, rAp, rBp, rCp, native_vSCR.b);
const uint32 native_cr = native_get_cr();
const uint32 native_vscr = native_vSCR.w[3];
native_set_cr(save_cr);
if (results_file) {
put_vector(native_vD);
put32(native_cr);
put32(native_vscr);
}
#else
get_vector(native_vD);
const uint32 native_cr = get32();
const uint32 native_vscr = get32();
#endif
if (SKIP_VMX_OPS)
return;
// Invoke emulated code
static aligned_vector_t emul_vD;
emul_vD.clear();
static aligned_vector_t emul_vSCR;
emul_vSCR.clear();
emul_set_cr(init_cr);
set_gpr(RD, (uintptr)emul_vD.addr());
set_gpr(RA, (uintptr)rAp);
set_gpr(RB, (uintptr)rBp);
set_gpr(RC, (uintptr)rCp);
set_gpr(VSCR, (uintptr)emul_vSCR.addr());
execute(code);
vector_helper_t emul_vSCR_helper;
memcpy(&emul_vSCR_helper, emul_vSCR.addr(), sizeof(vector_t));
const uint32 emul_cr = emul_get_cr();
const uint32 emul_vscr = ntohl(emul_vSCR_helper.w[3]);
++tests;
bool ok = vector_equals(vt.type, native_vD, emul_vD.value())
&& native_cr == emul_cr
&& native_vscr == emul_vscr;
if (!ok) {
printf("FAIL: %s [%08x]\n", vt.name, vt.opcode);
errors++;
}
else if (verbose) {
printf("PASS: %s [%08x]\n", vt.name, vt.opcode);
}
if (!ok || verbose) {
#if ENABLE_MON
disass_ppc(stdout, (uintptr)code, vt.opcode);
#endif
char op_type = tolower(vt.op_type);
if (!op_type)
op_type = vt.type;
#define PRINT_OPERAND(N, vX, rX) \
switch (vt.operands[N]) { \
case vX: \
printf(#vX " = "); \
print_vector(*((vector_t *)rX##p)); \
printf("\n"); \
break; \
case vI: \
case vN: \
printf(#vX " = %d\n", vX##_field::extract(vt.opcode)); \
break; \
case rX: \
printf(#rX " = %08x", rX##p); \
if (rX##p) switch (op_type) { \
case 'b': printf(" [%02x]", *rX##p); break; \
case 'h': printf(" [%04x]", *((uint16 *)rX##p)); break; \
case 'w': printf(" [%08x]", *((uint32 *)rX##p)); break; \
} \
printf("\n"); \
break; \
}
PRINT_OPERAND(1, vA, rA);
PRINT_OPERAND(2, vB, rB);
PRINT_OPERAND(3, vC, rC);
#undef PRINT_OPERAND
printf("vD.N = ");
print_vector(native_vD, vt.type);
printf("\n");
printf("vD.E = ");
print_vector(emul_vD.value(), vt.type);
printf("\n");
printf("CR.N = %08x ; VSCR.N = %08x\n", native_cr, native_vscr);
printf("CR.E = %08x ; VSCR.E = %08x\n", emul_cr, emul_vscr);
}
#endif
}
void powerpc_test_cpu::test_vector_load_for_shift(void)
{
#if TEST_VMX_LOADSH
// Tested instructions
static const vector_test_t tests[] = {
{ "lvsl", 'b', 0, _X (31,00,00,00, 6,0), { vD, rA, rB } },
{ "lvsr", 'b', 0, _X (31,00,00,00, 38,0), { vD, rA, rB } },
};
// Code template
static uint32 code[] = {
POWERPC_MFSPR(12, 256), // mfvrsave r12
_D(15,0,0,0x1000), // lis r0,0x1000 ([v3])
POWERPC_MTSPR(0, 256), // mtvrsave r0
POWERPC_LI(RA, 0), // li rB,<val>
0, // <insn>
POWERPC_STVX(RD, 0, RD), // stvx v3,r3(0)
POWERPC_MTSPR(12, 256), // mtvrsave r12
POWERPC_BLR // blr
};
int i_opcode = -1;
const int n_instructions = sizeof(code) / sizeof(code[0]);
for (int i = 0; i < n_instructions; i++) {
if (code[i] == 0) {
i_opcode = i;
break;
}
}
assert(i_opcode != -1);
const int n_elements = sizeof(tests) / sizeof(tests[0]);
for (int i = 0; i < n_elements; i++) {
vector_test_t const & vt = tests[i];
code[i_opcode] = vt.opcode;
vD_field::insert(code[i_opcode], RD);
rA_field::insert(code[i_opcode], 00);
rB_field::insert(code[i_opcode], RA);
printf("Testing %s\n", vt.name);
for (int j = 0; j < 32; j++) {
UIMM_field::insert(code[i_opcode - 1], j);
flush_icache_range(code, sizeof(code));
test_one_vector(code, vt, (uint8 *)NULL);
}
}
#endif
}
void powerpc_test_cpu::test_vector_load(void)
{
#if TEST_VMX_LOAD
// Tested instructions
static const vector_test_t tests[] = {
{ "lvebx", 'b', 0, _X (31,00,00,00, 7,0), { vD, rA, rB } },
{ "lvehx", 'h', 0, _X (31,00,00,00, 39,0), { vD, rA, rB } },
{ "lvewx", 'w', 0, _X (31,00,00,00, 71,0), { vD, rA, rB } }
};
// Code template
static uint32 code[] = {
POWERPC_MFSPR(12, 256), // mfvrsave r12
_D(15,0,0,0x1000), // lis r0,0x1000 ([v3])
POWERPC_MTSPR(0, 256), // mtvrsave r0
POWERPC_LVX(RD, 0, RD), // lvx v3,r3(0)
0, // <insn>
POWERPC_STVX(RD, 0, RD), // stvx v3,r3(0)
POWERPC_MTSPR(12, 256), // mtvrsave r12
POWERPC_BLR // blr
};
int i_opcode = -1;
const int n_instructions = sizeof(code) / sizeof(code[0]);
for (int i = 0; i < n_instructions; i++) {
if (code[i] == 0) {
i_opcode = i;
break;
}
}
assert(i_opcode != -1);
const int n_elements = sizeof(tests) / sizeof(tests[0]);
for (int i = 0; i < n_elements; i++) {
vector_test_t const & vt = tests[i];
code[i_opcode] = vt.opcode;
vD_field::insert(code[i_opcode], RD);
rA_field::insert(code[i_opcode], 00);
rB_field::insert(code[i_opcode], RA);
flush_icache_range(code, sizeof(code));
printf("Testing %s\n", vt.name);
const int n_vector_values = sizeof(vector_values)/sizeof(vector_values[0]);
for (int j = 0; j < n_vector_values; j++) {
static aligned_vector_t av;
switch (vt.type) {
case 'b':
for (int k = 0; k < 16; k++) {
av.copy(*(vector_t *)((uint8 *)(&vector_values[j].v) + 1 * k), 16 - 1 * k);
test_one_vector(code, vt, av.addr());
}
break;
case 'h':
for (int k = 0; k < 8; k++) {
av.copy(*(vector_t *)((uint8 *)(&vector_values[j].v) + 2 * k), 16 - 2 * k);
test_one_vector(code, vt, av.addr());
}
break;
case 'w':
for (int k = 0; k < 4; k++) {
av.copy(*(vector_t *)((uint8 *)(&vector_values[j].v) + 4 * k), 16 - 4 * k);
test_one_vector(code, vt, av.addr());
}
break;
}
}
}
#endif
}
void powerpc_test_cpu::test_vector_arith(void)
{
#if TEST_VMX_ARITH
// Tested instructions
static const vector_test_t tests[] = {
{ "vaddcuw", 'w', 0 , _VX(04,RD,RA,RB, 384), { vD, vA, vB } },
{ "vaddfp", 'f', 0 , _VX(04,RD,RA,RB, 10), { vD, vA, vB } },
{ "vaddsbs", 'b', 0 , _VX(04,RD,RA,RB, 768), { vD, vA, vB } },
{ "vaddshs", 'h', 0 , _VX(04,RD,RA,RB, 832), { vD, vA, vB } },
{ "vaddsws", 'w', 0 , _VX(04,RD,RA,RB, 896), { vD, vA, vB } },
{ "vaddubm", 'b', 0 , _VX(04,RD,RA,RB, 0), { vD, vA, vB } },
{ "vaddubs", 'b', 0 , _VX(04,RD,RA,RB, 512), { vD, vA, vB } },
{ "vadduhm", 'h', 0 , _VX(04,RD,RA,RB, 64), { vD, vA, vB } },
{ "vadduhs", 'h', 0 , _VX(04,RD,RA,RB, 576), { vD, vA, vB } },
{ "vadduwm", 'w', 0 , _VX(04,RD,RA,RB, 128), { vD, vA, vB } },
{ "vadduws", 'w', 0 , _VX(04,RD,RA,RB, 640), { vD, vA, vB } },
{ "vand", 'w', 0 , _VX(04,RD,RA,RB,1028), { vD, vA, vB } },
{ "vandc", 'w', 0 , _VX(04,RD,RA,RB,1092), { vD, vA, vB } },
{ "vavgsb", 'b', 0 , _VX(04,RD,RA,RB,1282), { vD, vA, vB } },
{ "vavgsh", 'h', 0 , _VX(04,RD,RA,RB,1346), { vD, vA, vB } },
{ "vavgsw", 'w', 0 , _VX(04,RD,RA,RB,1410), { vD, vA, vB } },
{ "vavgub", 'b', 0 , _VX(04,RD,RA,RB,1026), { vD, vA, vB } },
{ "vavguh", 'h', 0 , _VX(04,RD,RA,RB,1090), { vD, vA, vB } },
{ "vavguw", 'w', 0 , _VX(04,RD,RA,RB,1154), { vD, vA, vB } },
{ "vcfsx", 'f', 'w', _VX(04,RD,00,RB, 842), { vD, vI, vB } },
{ "vcfux", 'f', 'w', _VX(04,RD,00,RB, 778), { vD, vI, vB } },
{ "vcmpbfp", 'w', 'f', _VXR(04,RD,RA,RB,966,0), { vD, vA, vB } },
{ "vcmpbfp.", 'w', 'f', _VXR(04,RD,RA,RB,966,1), { vD, vA, vB } },
{ "vcmpeqfp", 'w', 'f', _VXR(04,RD,RA,RB,198,0), { vD, vA, vB } },
{ "vcmpeqfp.", 'w', 'f', _VXR(04,RD,RA,RB,198,1), { vD, vA, vB } },
{ "vcmpequb", 'b', 0 , _VXR(04,RD,RA,RB, 6,0), { vD, vA, vB } },
{ "vcmpequb.", 'b', 0 , _VXR(04,RD,RA,RB, 6,1), { vD, vA, vB } },
{ "vcmpequh", 'h', 0 , _VXR(04,RD,RA,RB, 70,0), { vD, vA, vB } },
{ "vcmpequh.", 'h', 0 , _VXR(04,RD,RA,RB, 70,1), { vD, vA, vB } },
{ "vcmpequw", 'w', 0 , _VXR(04,RD,RA,RB,134,0), { vD, vA, vB } },
{ "vcmpequw.", 'w', 0 , _VXR(04,RD,RA,RB,134,1), { vD, vA, vB } },
{ "vcmpgefp", 'w', 'f', _VXR(04,RD,RA,RB,454,0), { vD, vA, vB } },
{ "vcmpgefp.", 'w', 'f', _VXR(04,RD,RA,RB,454,1), { vD, vA, vB } },
{ "vcmpgtfp", 'w', 'f', _VXR(04,RD,RA,RB,710,0), { vD, vA, vB } },
{ "vcmpgtfp.", 'w', 'f', _VXR(04,RD,RA,RB,710,1), { vD, vA, vB } },
{ "vcmpgtsb", 'b', 0 , _VXR(04,RD,RA,RB,774,0), { vD, vA, vB } },
{ "vcmpgtsb.", 'b', 0 , _VXR(04,RD,RA,RB,774,1), { vD, vA, vB } },
{ "vcmpgtsh", 'h', 0 , _VXR(04,RD,RA,RB,838,0), { vD, vA, vB } },
{ "vcmpgtsh.", 'h', 0 , _VXR(04,RD,RA,RB,838,1), { vD, vA, vB } },
{ "vcmpgtsw", 'w', 0 , _VXR(04,RD,RA,RB,902,0), { vD, vA, vB } },
{ "vcmpgtsw.", 'w', 0 , _VXR(04,RD,RA,RB,902,1), { vD, vA, vB } },
{ "vcmpgtub", 'b', 0 , _VXR(04,RD,RA,RB,518,0), { vD, vA, vB } },
{ "vcmpgtub.", 'b', 0 , _VXR(04,RD,RA,RB,518,1), { vD, vA, vB } },
{ "vcmpgtuh", 'h', 0 , _VXR(04,RD,RA,RB,582,0), { vD, vA, vB } },
{ "vcmpgtuh.", 'h', 0 , _VXR(04,RD,RA,RB,582,1), { vD, vA, vB } },
{ "vcmpgtuw", 'w', 0 , _VXR(04,RD,RA,RB,646,0), { vD, vA, vB } },
{ "vcmpgtuw.", 'w', 0 , _VXR(04,RD,RA,RB,646,1), { vD, vA, vB } },
{ "vctsxs", 'w', 'f', _VX(04,RD,00,RB, 970), { vD, vI, vB } },
{ "vctuxs", 'w', 'f', _VX(04,RD,00,RB, 906), { vD, vI, vB } },
{ "vexptefp", 'f', 0 , _VX(04,RD,00,RB, 394), { vD, __, vB } },
{ "vlogefp", 'l', 'f', _VX(04,RD,00,RB, 458), { vD, __, vB } },
{ "vmaddfp", 'f', 0 , _VA(04,RD,RA,RB,RC,46),{ vD, vA, vB, vC } },
{ "vmaxfp", 'f', 0 , _VX(04,RD,RA,RB,1034), { vD, vA, vB } },
{ "vmaxsb", 'b', 0 , _VX(04,RD,RA,RB, 258), { vD, vA, vB } },
{ "vmaxsh", 'h', 0 , _VX(04,RD,RA,RB, 322), { vD, vA, vB } },
{ "vmaxsw", 'w', 0 , _VX(04,RD,RA,RB, 386), { vD, vA, vB } },
{ "vmaxub", 'b', 0 , _VX(04,RD,RA,RB, 2), { vD, vA, vB } },
{ "vmaxuh", 'h', 0 , _VX(04,RD,RA,RB, 66), { vD, vA, vB } },
{ "vmaxuw", 'w', 0 , _VX(04,RD,RA,RB, 130), { vD, vA, vB } },
{ "vmhaddshs", 'h', 0 , _VA(04,RD,RA,RB,RC,32),{ vD, vA, vB, vC } },
{ "vmhraddshs", 'h', 0 , _VA(04,RD,RA,RB,RC,33),{ vD, vA, vB, vC } },
{ "vminfp", 'f', 0 , _VX(04,RD,RA,RB,1098), { vD, vA, vB } },
{ "vminsb", 'b', 0 , _VX(04,RD,RA,RB, 770), { vD, vA, vB } },
{ "vminsh", 'h', 0 , _VX(04,RD,RA,RB, 834), { vD, vA, vB } },
{ "vminsw", 'w', 0 , _VX(04,RD,RA,RB, 898), { vD, vA, vB } },
{ "vminub", 'b', 0 , _VX(04,RD,RA,RB, 514), { vD, vA, vB } },
{ "vminuh", 'h', 0 , _VX(04,RD,RA,RB, 578), { vD, vA, vB } },
{ "vminuw", 'w', 0 , _VX(04,RD,RA,RB, 642), { vD, vA, vB } },
{ "vmladduhm", 'h', 0 , _VA(04,RD,RA,RB,RC,34),{ vD, vA, vB, vC } },
{ "vmrghb", 'b', 0 , _VX(04,RD,RA,RB, 12), { vD, vA, vB } },
{ "vmrghh", 'h', 0 , _VX(04,RD,RA,RB, 76), { vD, vA, vB } },
{ "vmrghw", 'w', 0 , _VX(04,RD,RA,RB, 140), { vD, vA, vB } },
{ "vmrglb", 'b', 0 , _VX(04,RD,RA,RB, 268), { vD, vA, vB } },
{ "vmrglh", 'h', 0 , _VX(04,RD,RA,RB, 332), { vD, vA, vB } },
{ "vmrglw", 'w', 0 , _VX(04,RD,RA,RB, 396), { vD, vA, vB } },
{ "vmsummbm", 'b', 0 , _VA(04,RD,RA,RB,RC,37),{ vD, vA, vB, vC } },
{ "vmsumshm", 'h', 0 , _VA(04,RD,RA,RB,RC,40),{ vD, vA, vB, vC } },
{ "vmsumshs", 'h', 0 , _VA(04,RD,RA,RB,RC,41),{ vD, vA, vB, vC } },
{ "vmsumubm", 'b', 0 , _VA(04,RD,RA,RB,RC,36),{ vD, vA, vB, vC } },
{ "vmsumuhm", 'h', 0 , _VA(04,RD,RA,RB,RC,38),{ vD, vA, vB, vC } },
{ "vmsumuhs", 'h', 0 , _VA(04,RD,RA,RB,RC,39),{ vD, vA, vB, vC } },
{ "vmulesb", 'b', 0 , _VX(04,RD,RA,RB, 776), { vD, vA, vB } },
{ "vmulesh", 'h', 0 , _VX(04,RD,RA,RB, 840), { vD, vA, vB } },
{ "vmuleub", 'b', 0 , _VX(04,RD,RA,RB, 520), { vD, vA, vB } },
{ "vmuleuh", 'h', 0 , _VX(04,RD,RA,RB, 584), { vD, vA, vB } },
{ "vmulosb", 'b', 0 , _VX(04,RD,RA,RB, 264), { vD, vA, vB } },
{ "vmulosh", 'h', 0 , _VX(04,RD,RA,RB, 328), { vD, vA, vB } },
{ "vmuloub", 'b', 0 , _VX(04,RD,RA,RB, 8), { vD, vA, vB } },
{ "vmulouh", 'h', 0 , _VX(04,RD,RA,RB, 72), { vD, vA, vB } },
{ "vnmsubfp", 'f', 0 , _VA(04,RD,RA,RB,RC,47),{ vD, vA, vB, vC } },
{ "vnor", 'w', 0 , _VX(04,RD,RA,RB,1284), { vD, vA, vB } },
{ "vor", 'w', 0 , _VX(04,RD,RA,RB,1156), { vD, vA, vB } },
{ "vperm", 'b', 0 , _VA(04,RD,RA,RB,RC,43),{ vD, vA, vB, vC } },
{ "vpkpx", 'h', 0 , _VX(04,RD,RA,RB, 782), { vD, vA, vB } },
{ "vpkshss", 'b', 0 , _VX(04,RD,RA,RB, 398), { vD, vA, vB } },
{ "vpkshus", 'b', 0 , _VX(04,RD,RA,RB, 270), { vD, vA, vB } },
{ "vpkswss", 'h', 0 , _VX(04,RD,RA,RB, 462), { vD, vA, vB } },
{ "vpkswus", 'h', 0 , _VX(04,RD,RA,RB, 334), { vD, vA, vB } },
{ "vpkuhum", 'b', 0 , _VX(04,RD,RA,RB, 14), { vD, vA, vB } },
{ "vpkuhus", 'b', 0 , _VX(04,RD,RA,RB, 142), { vD, vA, vB } },
{ "vpkuwum", 'h', 0 , _VX(04,RD,RA,RB, 78), { vD, vA, vB } },
{ "vpkuwus", 'h', 0 , _VX(04,RD,RA,RB, 206), { vD, vA, vB } },
{ "vrefp", 'e', 'f', _VX(04,RD,00,RB, 266), { vD, __, vB } },
{ "vrfim", 'f', 0 , _VX(04,RD,00,RB, 714), { vD, __, vB } },
{ "vrfin", 'f', 0 , _VX(04,RD,00,RB, 522), { vD, __, vB } },
{ "vrfip", 'f', 0 , _VX(04,RD,00,RB, 650), { vD, __, vB } },
{ "vrfiz", 'f', 0 , _VX(04,RD,00,RB, 586), { vD, __, vB } },
{ "vrlb", 'b', 0 , _VX(04,RD,RA,RB, 4), { vD, vA, vB } },
{ "vrlh", 'h', 0 , _VX(04,RD,RA,RB, 68), { vD, vA, vB } },
{ "vrlw", 'w', 0 , _VX(04,RD,RA,RB, 132), { vD, vA, vB } },
{ "vrsqrtefp", 'e', 'f', _VX(04,RD,00,RB, 330), { vD, __, vB } },
{ "vsel", 'b', 0 , _VA(04,RD,RA,RB,RC,42),{ vD, vA, vB, vC } },
{ "vsl", 'b', 'B', _VX(04,RD,RA,RB, 452), { vD, vA, vB } },
{ "vslb", 'b', 0 , _VX(04,RD,RA,RB, 260), { vD, vA, vB } },
{ "vsldoi", 'b', 0 , _VA(04,RD,RA,RB,00,44),{ vD, vA, vB, vN } },
{ "vslh", 'h', 0 , _VX(04,RD,RA,RB, 324), { vD, vA, vB } },
{ "vslo", 'b', 0 , _VX(04,RD,RA,RB,1036), { vD, vA, vB } },
{ "vslw", 'w', 0 , _VX(04,RD,RA,RB, 388), { vD, vA, vB } },
{ "vspltb", 'b', 0 , _VX(04,RD,00,RB, 524), { vD, vI, vB } },
{ "vsplth", 'h', 0 , _VX(04,RD,00,RB, 588), { vD, vI, vB } },
{ "vspltisb", 'b', 0 , _VX(04,RD,00,00, 780), { vD, vI } },
{ "vspltish", 'h', 0 , _VX(04,RD,00,00, 844), { vD, vI } },
{ "vspltisw", 'w', 0 , _VX(04,RD,00,00, 908), { vD, vI } },
{ "vspltw", 'w', 0 , _VX(04,RD,00,RB, 652), { vD, vI, vB } },
{ "vsr", 'b', 'B', _VX(04,RD,RA,RB, 708), { vD, vA, vB } },
{ "vsrab", 'b', 0 , _VX(04,RD,RA,RB, 772), { vD, vA, vB } },
{ "vsrah", 'h', 0 , _VX(04,RD,RA,RB, 836), { vD, vA, vB } },
{ "vsraw", 'w', 0 , _VX(04,RD,RA,RB, 900), { vD, vA, vB } },
{ "vsrb", 'b', 0 , _VX(04,RD,RA,RB, 516), { vD, vA, vB } },
{ "vsrh", 'h', 0 , _VX(04,RD,RA,RB, 580), { vD, vA, vB } },
{ "vsro", 'b', 0 , _VX(04,RD,RA,RB,1100), { vD, vA, vB } },
{ "vsrw", 'w', 0 , _VX(04,RD,RA,RB, 644), { vD, vA, vB } },
{ "vsubcuw", 'w', 0 , _VX(04,RD,RA,RB,1408), { vD, vA, vB } },
{ "vsubfp", 'f', 0 , _VX(04,RD,RA,RB, 74), { vD, vA, vB } },
{ "vsubsbs", 'b', 0 , _VX(04,RD,RA,RB,1792), { vD, vA, vB } },
{ "vsubshs", 'h', 0 , _VX(04,RD,RA,RB,1856), { vD, vA, vB } },
{ "vsubsws", 'w', 0 , _VX(04,RD,RA,RB,1920), { vD, vA, vB } },
{ "vsububm", 'b', 0 , _VX(04,RD,RA,RB,1024), { vD, vA, vB } },
{ "vsububs", 'b', 0 , _VX(04,RD,RA,RB,1536), { vD, vA, vB } },
{ "vsubuhm", 'h', 0 , _VX(04,RD,RA,RB,1088), { vD, vA, vB } },
{ "vsubuhs", 'h', 0 , _VX(04,RD,RA,RB,1600), { vD, vA, vB } },
{ "vsubuwm", 'w', 0 , _VX(04,RD,RA,RB,1152), { vD, vA, vB } },
{ "vsubuws", 'w', 0 , _VX(04,RD,RA,RB,1664), { vD, vA, vB } },
{ "vsum2sws", 'w', 0 , _VX(04,RD,RA,RB,1672), { vD, vA, vB } },
{ "vsum4sbs", 'w', 0 , _VX(04,RD,RA,RB,1800), { vD, vA, vB } },
{ "vsum4shs", 'w', 0 , _VX(04,RD,RA,RB,1608), { vD, vA, vB } },
{ "vsum4ubs", 'w', 0 , _VX(04,RD,RA,RB,1544), { vD, vA, vB } },
{ "vsumsws", 'w', 0 , _VX(04,RD,RA,RB,1928), { vD, vA, vB } },
{ "vupkhpx", 'w', 0 , _VX(04,RD,00,RB, 846), { vD, __, vB } },
{ "vupkhsb", 'h', 0 , _VX(04,RD,00,RB, 526), { vD, __, vB } },
{ "vupkhsh", 'w', 0 , _VX(04,RD,00,RB, 590), { vD, __, vB } },
{ "vupklpx", 'w', 0 , _VX(04,RD,00,RB, 974), { vD, __, vB } },
{ "vupklsb", 'h', 0 , _VX(04,RD,00,RB, 654), { vD, __, vB } },
{ "vupklsh", 'w', 0 , _VX(04,RD,00,RB, 718), { vD, __, vB } },
{ "vxor", 'w', 0 , _VX(04,RD,RA,RB,1220), { vD, vA, vB } },
};
// Code template
static uint32 code[] = {
POWERPC_MFSPR(12, 256), // mfvrsave r12
_D(15,0,0,0x9e00), // lis r0,0x9e00 ([v0;v3-v6])
POWERPC_MTSPR(0, 256), // mtvrsave r0
POWERPC_LVX(RA, 0, RA), // lvx v4,r4(0)
POWERPC_LVX(RB, 0, RB), // lvx v5,r5(0)
POWERPC_LVX(RC, 0, RC), // lvx v6,r6(0)
POWERPC_LVX(0, 0, VSCR), // lvx v0,r7(0)
_VX(04,00,00,00,1604), // mtvscr v0
0, // <op> v3,v4,v5
_VX(04,00,00,00,1540), // mfvscr v0
POWERPC_STVX(0, 0, VSCR), // stvx v0,r7(0)
POWERPC_STVX(RD, 0, RD), // stvx v3,r3(0)
POWERPC_MTSPR(12, 256), // mtvrsave r12
POWERPC_BLR // blr
};
int i_opcode = -1;
const int n_instructions = sizeof(code) / sizeof(code[0]);
for (int i = 0; i < n_instructions; i++) {
if (code[i] == 0) {
i_opcode = i;
break;
}
}
assert(i_opcode != -1);
const int n_elements = sizeof(tests) / sizeof(tests[0]);
for (int n = 0; n < n_elements; n++) {
vector_test_t vt = tests[n];
code[i_opcode] = vt.opcode;
flush_icache_range(code, sizeof(code));
// Operand type
char op_type = vt.op_type;
if (!op_type)
op_type = vt.type;
// Operand values
int n_vector_values;
const vector_value_t *vvp;
if (op_type == 'f') {
n_vector_values = sizeof(vector_fp_values)/sizeof(vector_fp_values[0]);
vvp = vector_fp_values;
}
else {
n_vector_values = sizeof(vector_values)/sizeof(vector_values[0]);
vvp = vector_values;
}
printf("Testing %s\n", vt.name);
static aligned_vector_t avi, avj, avk;
if (vt.operands[1] == vA && vt.operands[2] == vB && vt.operands[3] == vC) {
for (int i = 0; i < n_vector_values; i++) {
avi.copy(vvp[i].v);
for (int j = 0; j < n_vector_values; j++) {
avj.copy(vvp[j].v);
for (int k = 0; k < n_vector_values; k++) {
avk.copy(vvp[k].v);
test_one_vector(code, vt, avi.addr(), avj.addr(), avk.addr());
}
}
}
}
else if (vt.operands[1] == vA && vt.operands[2] == vB && vt.operands[3] == vN) {
for (int i = 0; i < 16; i++) {
vSH_field::insert(vt.opcode, i);
code[i_opcode] = vt.opcode;
flush_icache_range(code, sizeof(code));
avi.copy(vvp[i].v);
for (int j = 0; j < n_vector_values; j++) {
avj.copy(vvp[j].v);
for (int k = 0; k < n_vector_values; k++)
test_one_vector(code, vt, avi.addr(), avj.addr());
}
}
}
else if (vt.operands[1] == vA && vt.operands[2] == vB) {
for (int i = 0; i < n_vector_values; i++) {
avi.copy(vvp[i].v);
for (int j = 0; j < n_vector_values; j++) {
if (op_type == 'B') {
if (!vector_all_eq('b', vvp[j].v))
continue;
}
avj.copy(vvp[j].v);
test_one_vector(code, vt, avi.addr(), avj.addr());
}
}
}
else if (vt.operands[1] == vI && vt.operands[2] == vB) {
for (int i = 0; i < 32; i++) {
rA_field::insert(vt.opcode, i);
code[i_opcode] = vt.opcode;
flush_icache_range(code, sizeof(code));
for (int j = 0; j < n_vector_values; j++) {
avj.copy(vvp[j].v);
test_one_vector(code, vt, NULL, avj.addr());
}
}
}
else if (vt.operands[1] == vI) {
for (int i = 0; i < 32; i++) {
rA_field::insert(vt.opcode, i);
code[i_opcode] = vt.opcode;
flush_icache_range(code, sizeof(code));
test_one_vector(code, vt);
}
}
else if (vt.operands[1] == __ && vt.operands[2] == vB) {
for (int i = 0; i < n_vector_values; i++) {
avi.copy(vvp[i].v);
test_one_vector(code, vt, NULL, avi.addr());
}
}
else {
printf("ERROR: unhandled test case\n");
abort();
}
}
#endif
}
// Illegal handler to catch out AltiVec instruction
#ifdef NATIVE_POWERPC
static sigjmp_buf env;
static void sigill_handler(int sig)
{
has_altivec = false;
siglongjmp(env, 1);
}
#endif
bool powerpc_test_cpu::test(void)
{
// Tests initialization
tests = errors = 0;
init_cr = init_xer = 0;
// Execution ALU tests
#if TEST_ALU_OPS
test_add();
test_sub();
test_mul();
test_div();
test_shift();
test_rotate();
test_logical();
test_compare();
test_cr_logical();
#endif
// Execute VMX tests
#if TEST_VMX_OPS
if (has_altivec) {
test_vector_load_for_shift();
test_vector_load();
test_vector_arith();
}
#endif
printf("%u errors out of %u tests\n", errors, tests);
return errors == 0;
}
int main(int argc, char *argv[])
{
#ifdef EMU_KHEPERIX
// Initialize VM system (predecode cache uses vm_acquire())
vm_init();
#endif
FILE *fp = NULL;
powerpc_test_cpu *ppc = new powerpc_test_cpu;
if (argc > 1) {
const char *arg = argv[1];
if (strcmp(arg, "--jit") == 0) {
--argc;
argv[1] = argv[0];
++argv;
ppc->enable_jit();
}
}
if (argc > 1) {
const char *file = argv[1];
#ifdef NATIVE_POWERPC
if ((fp = fopen(file, "wb")) == NULL) {
fprintf(stderr, "ERROR: can't open %s for writing\n", file);
return EXIT_FAILURE;
}
#else
if ((fp = fopen(file, "rb")) == NULL) {
fprintf(stderr, "ERROR: can't open %s for reading\n", file);
return EXIT_FAILURE;
}
#endif
ppc->set_results_file(fp);
// Use a large enough buffer
static char buffer[4096];
setvbuf(fp, buffer, _IOFBF, sizeof(buffer));
}
// We need a results file on non PowerPC platforms
#ifndef NATIVE_POWERPC
if (fp == NULL) {
fprintf(stderr, "ERROR: a results file for reference is required\n");
return EXIT_FAILURE;
}
#endif
// Check if host CPU supports AltiVec instructions
has_altivec = true;
#ifdef NATIVE_POWERPC
signal(SIGILL, sigill_handler);
if (!sigsetjmp(env, 1))
asm volatile(".long 0x10000484"); // vor v0,v0,v0
signal(SIGILL, SIG_DFL);
#endif
bool ok = ppc->test();
if (fp) fclose(fp);
delete ppc;
return !ok;
}
| 37,753 |
1,056 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.notifications.center;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.Icon;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
/**
*
* @author <NAME>
* @author jpeska
*/
class MenuToggleButton extends JToggleButton {
private boolean mouseInArrowArea = false;
/**
* Creates a new instance of MenuToggleButton
*/
public MenuToggleButton(final Icon regIcon, Icon rollOverIcon, int arrowWidth) {
assert null != regIcon;
assert null != rollOverIcon;
final Icon lineIcon = new LineIcon(rollOverIcon, arrowWidth);
setIcon(regIcon);
setRolloverIcon(lineIcon);
setRolloverSelectedIcon(lineIcon);
setFocusable(false);
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
mouseInArrowArea = isInArrowArea(e.getPoint());
setRolloverIcon(mouseInArrowArea ? regIcon : lineIcon);
setRolloverSelectedIcon(mouseInArrowArea ? regIcon : lineIcon);
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (isInArrowArea(e.getPoint())) {
JPopupMenu popup = getPopupMenu();
if (null != popup) {
popup.show(MenuToggleButton.this, 0, getHeight());
}
}
}
@Override
public void mouseEntered(MouseEvent e) {
mouseInArrowArea = isInArrowArea(e.getPoint());
setRolloverIcon(mouseInArrowArea ? regIcon : lineIcon);
setRolloverSelectedIcon(mouseInArrowArea ? regIcon : lineIcon);
}
@Override
public void mouseExited(MouseEvent e) {
mouseInArrowArea = false;
setRolloverIcon(regIcon);
setRolloverSelectedIcon(regIcon);
}
});
setModel(new Model());
}
protected JPopupMenu getPopupMenu() {
return null;
}
private boolean isInArrowArea(Point p) {
return p.getLocation().x >= getWidth() - 3 - 2 - getInsets().right;
}
private static class LineIcon implements Icon {
private final Icon origIcon;
private final int arrowWidth;
public LineIcon(Icon origIcon, int arrowWidth) {
this.origIcon = origIcon;
this.arrowWidth = arrowWidth;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
origIcon.paintIcon(c, g, x, y);
g.setColor(UIManager.getColor("controlHighlight")); //NOI18N
g.drawLine(x + origIcon.getIconWidth() - arrowWidth - 2, y,
x + origIcon.getIconWidth() - arrowWidth - 2, y + getIconHeight());
g.setColor(UIManager.getColor("controlShadow")); //NOI18N
g.drawLine(x + origIcon.getIconWidth() - arrowWidth - 3, y,
x + origIcon.getIconWidth() - arrowWidth - 3, y + getIconHeight());
}
@Override
public int getIconWidth() {
return origIcon.getIconWidth();
}
@Override
public int getIconHeight() {
return origIcon.getIconHeight();
}
}
private class Model extends JToggleButton.ToggleButtonModel {
@Override
public void setPressed(boolean b) {
if (mouseInArrowArea) {
return;
}
super.setPressed(b);
}
}
}
| 1,985 |
2,542 |
<gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "Ra.Stdafx.h"
using namespace Common;
using namespace Reliability::ReconfigurationAgentComponent;
ComProxyReplicator::UpdateEpochAsyncOperation::UpdateEpochAsyncOperation(
ComProxyReplicator & owner,
FABRIC_EPOCH const & epoch,
Common::AsyncCallback callback,
Common::AsyncOperationSPtr const & parent)
: Common::ComProxyAsyncOperation(callback, parent, true),
epoch_(epoch),
owner_(owner)
{
// Empty
}
HRESULT ComProxyReplicator::UpdateEpochAsyncOperation::BeginComAsyncOperation(
IFabricAsyncOperationCallback * callback,
IFabricAsyncOperationContext ** context)
{
return owner_.replicator_->BeginUpdateEpoch(
&epoch_,
callback,
context);
}
HRESULT ComProxyReplicator::UpdateEpochAsyncOperation::EndComAsyncOperation(IFabricAsyncOperationContext * context)
{
return owner_.replicator_->EndUpdateEpoch(context);
}
ErrorCode ComProxyReplicator::UpdateEpochAsyncOperation::End(AsyncOperationSPtr const & asyncOperation)
{
auto thisPtr = AsyncOperation::End<UpdateEpochAsyncOperation>(asyncOperation);
return thisPtr->Error;
}
| 441 |
818 |
/*
GRT MIT License
Copyright (c) <2012> <<NAME>, Media Lab, 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.
*/
#define GRT_DLL_EXPORTS
#include "RangeTracker.h"
GRT_BEGIN_NAMESPACE
RangeTracker::RangeTracker(){
trackData = true;
numDimensions = 0;
totalNumSamplesViewed = 0;
}
RangeTracker::RangeTracker(UINT numDimensions){
trackData = true;
setNumDimensions( numDimensions );
}
RangeTracker::RangeTracker(const RangeTracker &rhs){
this->trackData = rhs.trackData;
this->numDimensions = rhs.numDimensions;
this->totalNumSamplesViewed = rhs.totalNumSamplesViewed;
this->ranges = rhs.ranges;
}
RangeTracker::~RangeTracker(){};
void RangeTracker::clear(){
totalNumSamplesViewed = 0;
ranges.clear();
if( numDimensions > 0 )
ranges.resize(numDimensions,MinMax(BIG_POSITIVE_VALUE,BIG_NEGATIVE_VALUE));
}
bool RangeTracker::setNumDimensions(UINT numDimensions){
if( numDimensions > 0 ){
//Set the dimensionality of the data
this->numDimensions = numDimensions;
//Reset the ranges values
clear();
return true;
}
return false;
}
bool RangeTracker::update(VectorFloat sample){
if( sample.size() != numDimensions ) return false;
if( !trackData ) return true;
totalNumSamplesViewed++;
for(UINT j=0; j<numDimensions; j++){
if( sample[j] < ranges[j].minValue ){ ranges[j].minValue = sample[j]; }
else if( sample[j] > ranges[j].maxValue ){ ranges[j].maxValue = sample[j]; }
}
return true;
}
bool RangeTracker::saveRangeDataToFile(std::string filename){
std::fstream file;
file.open(filename.c_str(), std::ios::out);
if( !file.is_open() ){
return false;
}
file << "GRT_RANGE_TRACKER_DATA_FILE_V1.0\n";
file << "NumDimensions: " << numDimensions << std::endl;
file << "TotalNumSamplesViewed: " << totalNumSamplesViewed << std::endl;
file << "Ranges: " << std::endl;
for(UINT i=0; i<ranges.getSize(); i++){
file << ranges[i].minValue << "\t" << ranges[i].maxValue << std::endl;
}
file.close();
return true;
}
bool RangeTracker::loadRangeDataFromFile(std::string filename){
std::fstream file;
file.open(filename.c_str(), std::ios::in);
clear();
if( !file.is_open() ){
std::cout << "FILE NOT FOUND\n";
return false;
}
std::string word;
//Check to make sure this is a file with the correct file format
file >> word;
if(word != "GRT_RANGE_TRACKER_DATA_FILE_V1.0"){
file.close();
return false;
}
//Get the number of dimensions in the data
file >> word;
if(word != "NumDimensions:"){
file.close();
return false;
}
file >> numDimensions;
//Get the total number of training examples in the training data
file >> word;
if(word != "TotalNumSamplesViewed:"){
file.close();
return false;
}
file >> totalNumSamplesViewed;
//Load the ranges
file >> word;
if(word != "Ranges:"){
file.close();
return false;
}
ranges.resize(numDimensions);
for(UINT i=0; i<ranges.size(); i++){
file >> ranges[i].minValue;
file >> ranges[i].maxValue;
}
file.close();
return true;
}
Vector<MinMax> RangeTracker::getRanges(){
return ranges;
}
GRT_END_NAMESPACE
| 1,763 |
9,959 |
class LoggerCustomLog {
@java.lang.SuppressWarnings("all")
private static final MyLogger log = MyLoggerFactory.create(LoggerCustomLog.class);
}
class MyLoggerFactory {
static MyLogger create(Class<?> clazz) {
return null;
}
}
class MyLogger {
}
| 90 |
517 |
<filename>tensorflow-framework/src/main/java/org/tensorflow/framework/data/DatasetIterator.java
/*
* Copyright 2020 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.
*/
package org.tensorflow.framework.data;
import org.tensorflow.Graph;
import org.tensorflow.Operand;
import org.tensorflow.op.Op;
import org.tensorflow.op.Ops;
import org.tensorflow.ndarray.Shape;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.tensorflow.types.family.TType;
/**
* Represents the state of an iteration through a tf.data Datset. DatasetIterator is not a
* java.util.Iterator. In eager mode, `Dataset` can be used as an Iterable, returning dataset
* elements each iteration.
*
* <p>Example: Iteration in graph mode.
*
* <pre>{@code
* // Create input tensors
* Operand<?> features = tf.constant( ... );
* Operand<?> labels = tf.constant( ... );
*
*
* Dataset dataset = Dataset
* .fromTensorSlices(XTensor, yTensor);
* .batch(BATCH_SIZE);
*
* DatasetIterator iterator = dataset.makeInitializeableIterator();
* List<Operand<?>> components = iterator.getNext();
* Operand<?> featureBatch = components.get(0);
* Operand<?> labelBatch = components.get(1);
*
* // Build a TensorFlow graph that does something on each element.
* loss = computeModelLoss(featureBatch, labelBatch);
*
* optimizer = ... // create an optimizer
* trainOp = optimizer.minimize(loss);
*
* try (Session session = new Session(graph) {
* while (true) {
* session.run(iterator.getInitializer());
* try {
* session
* .addTarget(trainOp)
* .fetch(loss)
* .run();
*
* ...
* } catch (TFOutOfRangeError e) {
* System.out.println("finished iterating.");
* break;
* }
* }
* }
*
* }</pre>
*
* <p>Example: Iteration in eager mode.
*
* <pre>{@code
* // Create input tensors
* Operand<?> features = tf.constant( ... );
* Operand<?> labels = tf.constant( ... );
*
* int BATCH_SIZE = ...
*
* Dataset dataset = Dataset
* .fromTensorSlices(features, labels)
* .batch(BATCH_SIZE);
* DatasetIterator iterator = dataset.makeIterator();
*
* Optimizer optimizer = ... // create an optimizer
*
* for (List<Operand<?>> components : dataset) {
* Operand<?> featureBatch = components.get(0);
* Operand<?> labelBatch = components.get(1);
*
* loss = computeModelLoss(featureBatch, labelBatch);
* trainOp = optimizer.minimize(loss);
* }
* }</pre>
*/
public class DatasetIterator implements Iterable<List<Operand<?>>> {
public static final String EMPTY_SHARED_NAME = "";
protected Ops tf;
private Operand<?> iteratorResource;
private Op initializer;
protected List<Class<? extends TType>> outputTypes;
protected List<Shape> outputShapes;
/**
* @param tf Ops accessor corresponding to the same `ExecutionEnvironment` as the
* `iteratorResource`.
* @param iteratorResource An Operand representing the iterator (e.g. constructed from
* `tf.data.iterator` or `tf.data.anonymousIterator`)
* @param initializer An `Op` that should be run to initialize this iterator
* @param outputTypes A list of classes corresponding to the tensor type of each component of
* a dataset element.
* @param outputShapes A list of `Shape` objects corresponding to the shapes of each component of
* a dataset element.
*/
public DatasetIterator(
Ops tf,
Operand<?> iteratorResource,
Op initializer,
List<Class<? extends TType>> outputTypes,
List<Shape> outputShapes) {
this.tf = tf;
this.iteratorResource = iteratorResource;
this.initializer = initializer;
this.outputTypes = outputTypes;
this.outputShapes = outputShapes;
}
public DatasetIterator(
Ops tf,
Operand<?> iteratorResource,
List<Class<? extends TType>> outputTypes,
List<Shape> outputShapes) {
this.tf = tf;
this.iteratorResource = iteratorResource;
this.outputTypes = outputTypes;
this.outputShapes = outputShapes;
}
protected DatasetIterator(DatasetIterator other) {
this.tf = other.tf;
this.iteratorResource = other.iteratorResource;
this.initializer = other.initializer;
this.outputTypes = other.outputTypes;
this.outputShapes = other.outputShapes;
}
/**
* Returns a list of {@code Operand<?>} representing the components of the next dataset element.
*
* <p>In graph mode, call this method once, and use its result as input to another computation.
* Then in the training loop, on successive calls to session.run(), successive dataset elements
* will be retrieved through these components.
*
* <p>In eager mode, each time this method is called, the next dataset element will be returned.
* (This is done automatically by iterating through `Dataset` as a Java `Iterable`).
*
* @return A {@code List<Operand<?>>} representing dataset element components.
*/
public List<Operand<?>> getNext() {
List<Operand<?>> components = new ArrayList<>();
tf.data
.iteratorGetNext(getIteratorResource(), outputTypes, outputShapes)
.iterator()
.forEachRemaining(components::add);
return components;
}
/**
* Returns a `DatasetOptional` representing the components of the next dataset element.
*
* <p>In eager mode, each time this method is called, the next dataset element will be returned as
* a `DatasetOptional`.
*
* <p>Use `DatasetOptional.hasValue` to check if this optional has a value, and
* `DatasetOptional.getValue` to retrieve the value.
*
* @return A `DatasetOptional` representing dataset element components.
*/
public DatasetOptional getNextAsOptional() {
Operand<?> optionalVariant =
tf.data
.iteratorGetNextAsOptional(getIteratorResource(), outputTypes, outputShapes)
.optional();
return new DatasetOptional(tf, optionalVariant, outputTypes, outputShapes);
}
/**
* Creates and returns a TF `Op` that can be run to initialize this iterator on a dataset. The
* dataset must have a structure (outputTypes, outputShapes) that match this iterator, and share
* the same ExecutionEnvironment as this iterator.
*
* <p>When this `Op` is run, this iterator will be "re-initialized" at the first element of the
* input dataset.
*
* <p>In eager mode, the op will be run automatically as part of a call to `makeIterator`.
*
* @param dataset An `org.tensorflow.data.Dataset` to initialize this iterator on.
* @return A TF `Op` that can be used to initialize this iterator on the dataset.
* @throws IllegalArgumentException if the dataset's ExecutionEnvironment or structure doesn't
* match this iterator.
*/
public Op makeInitializer(Dataset dataset) {
if (tf.scope().env() != dataset.tf.scope().env()) {
throw new IllegalArgumentException(
"Dataset must share the same" + "ExecutionEnvironment as this iterator.");
}
if (!dataset.getOutputShapes().equals(outputShapes)
|| !dataset.getOutputTypes().equals(outputTypes)) {
throw new IllegalArgumentException(
"Dataset structure (types, " + "output shapes) must match this iterator.");
}
this.initializer = tf.data.makeIterator(dataset.getVariant(), getIteratorResource());
return this.initializer;
}
/**
* Creates a new iterator from a "structure" defined by `outputShapes` and `outputTypes`.
*
* @param tf Ops accessor
* @param outputTypes A list of classes repesenting the tensor type of each component of a
* dataset element.
* @param outputShapes A list of Shape objects representing the shape of each component of a
* dataset element.
* @return A new DatasetIterator
*/
public static DatasetIterator fromStructure(
Ops tf, List<Class<? extends TType>> outputTypes, List<Shape> outputShapes) {
Operand<?> iteratorResource =
tf.scope().env() instanceof Graph
? tf.data.iterator(EMPTY_SHARED_NAME, "", outputTypes, outputShapes)
: tf.data.anonymousIterator(outputTypes, outputShapes).handle();
return new DatasetIterator(tf, iteratorResource, outputTypes, outputShapes);
}
public Operand<?> getIteratorResource() {
return iteratorResource;
}
public Op getInitializer() {
return initializer;
}
public Ops getOpsInstance() {
return tf;
}
@Override
public Iterator<List<Operand<?>>> iterator() {
if (!tf.scope().env().isEager()) {
throw new UnsupportedOperationException(
"Cannot use foreach iteration through a dataset in graph mode.");
}
DatasetIterator iterator = this;
return new Iterator<List<Operand<?>>>() {
private DatasetOptional nextOptional = iterator.getNextAsOptional();
@Override
public boolean hasNext() {
return nextOptional.hasValue().asTensor().getBoolean();
}
@Override
public List<Operand<?>> next() {
List<Operand<?>> result = nextOptional.getValue();
nextOptional = iterator.getNextAsOptional();
return result;
}
};
}
}
| 3,261 |
373 |
<reponame>noittom/finmath-lib
/**
* Provides various day count conventions, e.g., as used in the definition of coupon payments of interest rate products.
*
* @author <NAME>
*/
package net.finmath.time.daycount;
| 64 |
679 |
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include <comphelper/serviceinfohelper.hxx>
#include "SdUnoOutlineView.hxx"
#include "DrawController.hxx"
#include "OutlineViewShell.hxx"
#include "sdpage.hxx"
#include "unopage.hxx"
#include <cppuhelper/proptypehlp.hxx>
#include <svx/unopage.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
using ::rtl::OUString;
using namespace ::vos;
using namespace ::cppu;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace sd {
SdUnoOutlineView::SdUnoOutlineView(
DrawController& rController,
OutlineViewShell& rViewShell,
View& rView) throw()
: DrawSubControllerInterfaceBase(m_aMutex),
mrController(rController),
mrOutlineViewShell(rViewShell),
mrView(rView)
{
}
SdUnoOutlineView::~SdUnoOutlineView (void) throw()
{
}
void SAL_CALL SdUnoOutlineView::disposing (void)
{
}
//----- XSelectionSupplier ----------------------------------------------------
sal_Bool SAL_CALL SdUnoOutlineView::select( const Any& )
throw(lang::IllegalArgumentException, RuntimeException)
{
// todo: add selections for text ranges
return sal_False;
}
Any SAL_CALL SdUnoOutlineView::getSelection()
throw(RuntimeException)
{
Any aAny;
return aAny;
}
void SAL_CALL SdUnoOutlineView::addSelectionChangeListener (
const css::uno::Reference<css::view::XSelectionChangeListener>& rxListener)
throw(css::uno::RuntimeException)
{
(void)rxListener;
}
void SAL_CALL SdUnoOutlineView::removeSelectionChangeListener (
const css::uno::Reference<css::view::XSelectionChangeListener>& rxListener)
throw(css::uno::RuntimeException)
{
(void)rxListener;
}
//----- XDrawView -------------------------------------------------------------
void SAL_CALL SdUnoOutlineView::setCurrentPage (
const Reference< drawing::XDrawPage >& xPage)
throw(RuntimeException)
{
SvxDrawPage* pDrawPage = SvxDrawPage::getImplementation( xPage );
SdrPage *pSdrPage = pDrawPage ? pDrawPage->GetSdrPage() : NULL;
if (pSdrPage != NULL)
mrOutlineViewShell.SetCurrentPage(dynamic_cast<SdPage*>(pSdrPage));
}
Reference< drawing::XDrawPage > SAL_CALL SdUnoOutlineView::getCurrentPage (void)
throw(RuntimeException)
{
Reference<drawing::XDrawPage> xPage;
SdPage* pPage = mrOutlineViewShell.getCurrentPage();
if (pPage != NULL)
xPage = Reference<drawing::XDrawPage>::query(pPage->getUnoPage());
return xPage;
}
/*
// Return sal_True, value change
sal_Bool SdUnoOutlineView::convertFastPropertyValue (
Any & rConvertedValue,
Any & rOldValue,
sal_Int32 nHandle,
const Any& rValue)
throw ( com::sun::star::lang::IllegalArgumentException)
{
sal_Bool bResult = sal_False;
switch( nHandle )
{
case DrawController::PROPERTY_CURRENTPAGE:
{
Reference< drawing::XDrawPage > xOldPage( getCurrentPage() );
Reference< drawing::XDrawPage > xNewPage;
::cppu::convertPropertyValue( xNewPage, rValue );
if( xOldPage != xNewPage )
{
rConvertedValue <<= xNewPage;
rOldValue <<= xOldPage;
bResult = sal_True;
}
}
break;
default:
break;
}
return bResult;
}
*/
void SdUnoOutlineView::setFastPropertyValue (
sal_Int32 nHandle,
const Any& rValue)
throw(css::beans::UnknownPropertyException,
css::beans::PropertyVetoException,
css::lang::IllegalArgumentException,
css::lang::WrappedTargetException,
css::uno::RuntimeException)
{
switch( nHandle )
{
case DrawController::PROPERTY_CURRENTPAGE:
{
Reference< drawing::XDrawPage > xPage;
rValue >>= xPage;
setCurrentPage( xPage );
}
break;
default:
throw beans::UnknownPropertyException();
}
}
void SAL_CALL SdUnoOutlineView::disposing (const ::com::sun::star::lang::EventObject& )
throw (::com::sun::star::uno::RuntimeException)
{
}
Any SAL_CALL SdUnoOutlineView::getFastPropertyValue (
sal_Int32 nHandle)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException,
css::uno::RuntimeException)
{
Any aValue;
switch( nHandle )
{
case DrawController::PROPERTY_CURRENTPAGE:
{
SdPage* pPage = const_cast<OutlineViewShell&>(mrOutlineViewShell).GetActualPage();
if (pPage != NULL)
aValue <<= pPage->getUnoPage();
}
break;
case DrawController::PROPERTY_VIEWOFFSET:
break;
default:
throw beans::UnknownPropertyException();
}
return aValue;
}
// XServiceInfo
OUString SAL_CALL SdUnoOutlineView::getImplementationName( ) throw (RuntimeException)
{
return OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.sd.SdUnoOutlineView") );
}
sal_Bool SAL_CALL SdUnoOutlineView::supportsService( const OUString& ServiceName ) throw (RuntimeException)
{
return comphelper::ServiceInfoHelper::supportsService( ServiceName, getSupportedServiceNames() );
}
Sequence< OUString > SAL_CALL SdUnoOutlineView::getSupportedServiceNames( ) throw (RuntimeException)
{
OUString aSN( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.presentation.OutlineView") );
uno::Sequence< OUString > aSeq( &aSN, 1 );
return aSeq;
}
} // end of namespace sd
| 2,389 |
2,338 |
// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve2 -fallow-half-arguments-and-returns -fsyntax-only -verify %s
// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu -target-feature +sve2 -fallow-half-arguments-and-returns -fsyntax-only -verify %s
#ifdef SVE_OVERLOADED_FORMS
// A simple used,unused... macro, long enough to represent any SVE builtin.
#define SVE_ACLE_FUNC(A1,A2_UNUSED,A3,A4_UNUSED) A1##A3
#else
#define SVE_ACLE_FUNC(A1,A2,A3,A4) A1##A2##A3##A4
#endif
#include <arm_sve.h>
svint16_t test_svmls_lane_s16(svint16_t op1, svint16_t op2, svint16_t op3)
{
// expected-error-re@+1 {{argument value {{[0-9]+}} is outside the valid range [0, 7]}}
return SVE_ACLE_FUNC(svmls_lane,_s16,,)(op1, op2, op3, -1);
}
svint32_t test_svmls_lane_s32(svint32_t op1, svint32_t op2, svint32_t op3)
{
// expected-error-re@+1 {{argument value {{[0-9]+}} is outside the valid range [0, 3]}}
return SVE_ACLE_FUNC(svmls_lane,_s32,,)(op1, op2, op3, 4);
}
svint64_t test_svmls_lane_s64(svint64_t op1, svint64_t op2, svint64_t op3)
{
// expected-error-re@+1 {{argument value {{[0-9]+}} is outside the valid range [0, 1]}}
return SVE_ACLE_FUNC(svmls_lane,_s64,,)(op1, op2, op3, -1);
}
svuint16_t test_svmls_lane_u16(svuint16_t op1, svuint16_t op2, svuint16_t op3)
{
// expected-error-re@+1 {{argument value {{[0-9]+}} is outside the valid range [0, 7]}}
return SVE_ACLE_FUNC(svmls_lane,_u16,,)(op1, op2, op3, 8);
}
svuint32_t test_svmls_lane_u32(svuint32_t op1, svuint32_t op2, svuint32_t op3)
{
// expected-error-re@+1 {{argument value {{[0-9]+}} is outside the valid range [0, 3]}}
return SVE_ACLE_FUNC(svmls_lane,_u32,,)(op1, op2, op3, -1);
}
svuint64_t test_svmls_lane_u64(svuint64_t op1, svuint64_t op2, svuint64_t op3)
{
// expected-error-re@+1 {{argument value {{[0-9]+}} is outside the valid range [0, 1]}}
return SVE_ACLE_FUNC(svmls_lane,_u64,,)(op1, op2, op3, 2);
}
| 918 |
765 |
<reponame>hyu-iot/gem5
#include <systemc.h>
sc_trace_file* sc_tf;
class Mod : public sc_module
{
public:
sc_in_clk clk;
sc_in<sc_uint<37> > a;
sc_inout<bool > b;
SC_HAS_PROCESS(Mod);
void foo()
{
cout << sc_time_stamp() << "\n";
cout << " a = " << a << " b = " << b << "\n";
cout << "\n";
return;
} // foo()
Mod(const sc_module_name& name) : sc_module(name), a("a")
{
SC_METHOD(foo);
sensitive << clk.pos();
dont_initialize();
}
void start_of_simulation() {
sc_trace(sc_tf, a, a.name());
sc_trace(sc_tf, b, b.name());
}
}; // class Mod
int sc_main(int argc, char* argv[])
{
sc_clock clk("clk", 50, SC_NS, 0.5, 0, SC_NS);
sc_signal<sc_uint<37> > a;
sc_signal<bool> b;
sc_tf = sc_create_vcd_trace_file("test14");
Mod mod("mod");
mod.clk(clk);
mod.a(a);
mod.b(b);
sc_trace(sc_tf, clk, clk.name());
sc_start(50, SC_NS);
a = 12;
b = true;
sc_start(50, SC_NS);
return 0;
} // sc_main()
| 503 |
559 |
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kancolle.msg;
import java.io.IOException;
import kancolle.keyx.DiffieHellmanManager;
import com.netflix.msl.msg.MessageOutputStream;
/**
* <p>Request orders.</p>
*
* @author <NAME> <<EMAIL>>
*/
public class OrderRequestMessageContext extends KanColleMessageContext {
/**
* Create a new order request message sent by the specified officer.
*
* @param name reporting officer name.
* @param fingerprint reporting officer fingerprint. May be null if the
* officer is already authenticated (a user ID token exists).
* @param keyxManager key exchange manager.
*/
public OrderRequestMessageContext(final String name, final byte[] fingerprint, final DiffieHellmanManager keyxManager) {
super(name, fingerprint, keyxManager);
if (name == null)
throw new NullPointerException("Reports must specify an officer name.");
}
@Override
public boolean isEncrypted() {
return false;
}
@Override
public void write(final MessageOutputStream output) throws IOException {
// TODO Auto-generated method stub
}
}
| 537 |
16,989 |
<gh_stars>1000+
/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2019 Guardsquare NV
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.classfile.constant;
import proguard.classfile.ClassConstants;
import proguard.classfile.Clazz;
import proguard.classfile.constant.visitor.ConstantVisitor;
import proguard.classfile.constant.visitor.PrimitiveArrayConstantElementVisitor;
import proguard.classfile.constant.visitor.PrimitiveArrayConstantVisitor;
/**
* This unofficial Constant represents an array of primitives in the constant
* pool. It is not supported by any Java specification and therefore only for
* internal use.
*
* @author <NAME>
*/
public class PrimitiveArrayConstant extends Constant
{
public Object values;
/**
* Creates an uninitialized PrimitiveArrayConstant.
*/
public PrimitiveArrayConstant()
{
}
/**
* Creates a new PrimitiveArrayConstant with the given array of values.
*/
public PrimitiveArrayConstant(Object values)
{
this.values = values;
}
/**
* Returns the type of the elements of the primitive array.
*/
public char getPrimitiveType()
{
return values instanceof boolean[] ? ClassConstants.TYPE_BOOLEAN :
values instanceof byte[] ? ClassConstants.TYPE_BYTE :
values instanceof char[] ? ClassConstants.TYPE_CHAR :
values instanceof short[] ? ClassConstants.TYPE_SHORT :
values instanceof int[] ? ClassConstants.TYPE_INT :
values instanceof float[] ? ClassConstants.TYPE_FLOAT :
values instanceof long[] ? ClassConstants.TYPE_LONG :
values instanceof double[] ? ClassConstants.TYPE_DOUBLE :
0;
}
/**
* Returns the length of the primitive array.
*/
public int getLength()
{
return values instanceof boolean[] ? ((boolean[])values).length :
values instanceof byte[] ? ((byte[] )values).length :
values instanceof char[] ? ((char[] )values).length :
values instanceof short[] ? ((short[] )values).length :
values instanceof int[] ? ((int[] )values).length :
values instanceof float[] ? ((float[] )values).length :
values instanceof long[] ? ((long[] )values).length :
values instanceof double[] ? ((double[] )values).length :
0;
}
/**
* Returns the values.
*/
public Object getValues()
{
return values;
}
/**
* Applies the given PrimitiveArrayConstantVisitor to the primitive array.
*/
public void primitiveArrayAccept(Clazz clazz, PrimitiveArrayConstantVisitor primitiveArrayConstantVisitor)
{
// The primitive arrays themselves don't accept visitors, so we have to
// use instanceof tests.
if (values instanceof boolean[])
{
primitiveArrayConstantVisitor.visitBooleanArrayConstant(clazz, this, (boolean[])values);
}
else if (values instanceof byte[])
{
primitiveArrayConstantVisitor.visitByteArrayConstant(clazz, this, (byte[])values);
}
else if (values instanceof char[])
{
primitiveArrayConstantVisitor.visitCharArrayConstant(clazz, this, (char[])values);
}
else if (values instanceof short[])
{
primitiveArrayConstantVisitor.visitShortArrayConstant(clazz, this, (short[])values);
}
else if (values instanceof int[])
{
primitiveArrayConstantVisitor.visitIntArrayConstant(clazz, this, (int[])values);
}
else if (values instanceof float[])
{
primitiveArrayConstantVisitor.visitFloatArrayConstant(clazz, this, (float[])values);
}
else if (values instanceof long[])
{
primitiveArrayConstantVisitor.visitLongArrayConstant(clazz, this, (long[])values);
}
else if (values instanceof double[])
{
primitiveArrayConstantVisitor.visitDoubleArrayConstant(clazz, this, (double[])values);
}
}
/**
* Applies the given PrimitiveArrayConstantElementVisitor to all elements
* of the primitive array.
*/
public void primitiveArrayElementsAccept(Clazz clazz, PrimitiveArrayConstantElementVisitor primitiveArrayConstantElementVisitor)
{
// The primitive arrays themselves don't accept visitors, so we have to
// use instanceof tests.
if (values instanceof boolean[])
{
boolean[] booleanValues = (boolean[])this.values;
for (int index = 0; index < booleanValues.length; index++)
{
primitiveArrayConstantElementVisitor.visitBooleanArrayConstantElement(clazz, this, index, booleanValues[index]);
}
}
else if (values instanceof byte[])
{
byte[] byteValues = (byte[])this.values;
for (int index = 0; index < byteValues.length; index++)
{
primitiveArrayConstantElementVisitor.visitByteArrayConstantElement(clazz, this, index, byteValues[index]);
}
}
else if (values instanceof char[])
{
char[] charValues = (char[])this.values;
for (int index = 0; index < charValues.length; index++)
{
primitiveArrayConstantElementVisitor.visitCharArrayConstantElement(clazz, this, index, charValues[index]);
}
}
else if (values instanceof short[])
{
short[] shortValues = (short[])this.values;
for (int index = 0; index < shortValues.length; index++)
{
primitiveArrayConstantElementVisitor.visitShortArrayConstantElement(clazz, this, index, shortValues[index]);
}
}
else if (values instanceof int[])
{
int[] intValues = (int[])this.values;
for (int index = 0; index < intValues.length; index++)
{
primitiveArrayConstantElementVisitor.visitIntArrayConstantElement(clazz, this, index, intValues[index]);
}
}
else if (values instanceof float[])
{
float[] floatValues = (float[])this.values;
for (int index = 0; index < floatValues.length; index++)
{
primitiveArrayConstantElementVisitor.visitFloatArrayConstantElement(clazz, this, index, floatValues[index]);
}
}
else if (values instanceof long[])
{
long[] longValues = (long[])this.values;
for (int index = 0; index < longValues.length; index++)
{
primitiveArrayConstantElementVisitor.visitLongArrayConstantElement(clazz, this, index, longValues[index]);
}
}
else if (values instanceof double[])
{
double[] doubleValues = (double[])this.values;
for (int index = 0; index < doubleValues.length; index++)
{
primitiveArrayConstantElementVisitor.visitDoubleArrayConstantElement(clazz, this, index, doubleValues[index]);
}
}
}
// Implementations for Constant.
public int getTag()
{
return ClassConstants.CONSTANT_PrimitiveArray;
}
public void accept(Clazz clazz, ConstantVisitor constantVisitor)
{
constantVisitor.visitPrimitiveArrayConstant(clazz, this);
}
}
| 3,484 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.