max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
2,452 | #!/usr/bin/env python
from __future__ import print_function
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import sys
import os
# add the lib directory to the path
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
import base64
import pg8000
import datetime
import boto3
import json
import collections
__version__ = "1.4"
print('Loading function')
#### Configuration
ssl = True
interval = '5 minutes'
debug = False
##################
pg8000.paramstyle = "qmark"
def get_env_var(name):
return os.environ[name] if name in os.environ else None
# resolve cluster connection settings and SNS from environment if set
user = get_env_var('user')
enc_password = get_env_var('enc_password')
host = get_env_var('host')
port = int(get_env_var('port'))
database = get_env_var('database')
sns_arn = get_env_var('sns_arn')
clusterid = host.split(".")[0]
try:
kms = boto3.client('kms')
password = kms.decrypt(CiphertextBlob=base64.b64decode(enc_password))['Plaintext']
except:
print('KMS access failed: Exception %s' % sys.exc_info()[1])
try:
sns = boto3.resource('sns')
platform_endpoint = sns.PlatformEndpoint('{sns_arn}'.format(sns_arn = sns_arn))
except:
print('SNS access failed: Exception %s' % sys.exc_info()[1])
def run_command(cursor, statement):
if debug:
print("Running Statement: %s" % statement)
return cursor.execute(statement)
def publish_to_sns(message):
try:
if debug:
print('Publishing messages to SNS topic')
# Publish a message.
response = platform_endpoint.publish(
Subject='Redshift Query Monitoring Rule Notifications',
Message=message,
MessageStructure='string',
MessageAttributes={
'RedshiftQueryMonitoringRuleNotifications': {
'StringValue': 'Redshift Query Monitoring Rule Notifications',
'DataType': 'String'
}
}
)
return response
except:
print(' Failed to publish messages to SNS topic: exception %s' % sys.exc_info()[1])
return 'Failed'
def query_redshift(conn):
try:
sql_query = """select /* Lambda Redshift Query Monitoring SNS Notifications */ userid,query,service_class,trim(rule) as rule,trim(action) as action,recordtime from stl_wlm_rule_action WHERE userid > 1 AND recordtime >= GETDATE() - INTERVAL '{interval}' order by recordtime desc;""".format(interval = interval)
print(sql_query)
# connect to Redshift and run the query
cursor = conn.cursor()
run_command(cursor,sql_query)
result = cursor.fetchall()
objects_list = []
for row in result:
userid,query,service_class,rule,action,recordtime = row
d = collections.OrderedDict()
d['clusterid'] = clusterid
d['database'] = database
d['userid'] = userid
d['query'] = query
d['service_class'] = service_class
d['rule'] = rule
d['action'] = action
d['recordtime'] = recordtime.isoformat()
objects_list.append(d)
#Publish to SNS if any rows fetched
if len(objects_list) == 0:
print('No rows to publish to SNS')
else:
query_result_json = json.dumps(objects_list)
print(query_result_json)
response= publish_to_sns(query_result_json)
cursor.close()
conn.commit()
print('Completed Succesfully ')
except:
print('Query Failed: exception %s' % sys.exc_info()[1])
return 'Failed'
def lambda_handler(event, context):
try:
if debug:
print('Connect to Redshift: %s' % host)
conn = pg8000.connect(database=database, user=user, password=password, host=host, port=port, ssl=ssl)
except:
print('Redshift Connection Failed: exception %s' % sys.exc_info()[1])
return 'Failed'
if debug:
print('Succesfully Connected Redshift Cluster')
# Collect Query Monitoring Rule metrics and Publish to SNS topic
query_redshift(conn)
conn.close()
return 'Finished'
if __name__ == "__main__":
lambda_handler(sys.argv[0], None)
| 1,865 |
4,238 | <gh_stars>1000+
#!/usr/bin/env python
"""Tests for the MySQL migrations logic."""
import contextlib
import io
import os
import shutil
from absl import app
from absl.testing import absltest
from grr_response_core import config
from grr_response_core.lib.util import temp
from grr_response_server.databases import mysql_migration
from grr_response_server.databases import mysql_test
from grr.test_lib import test_lib
class ListMigrationsToProcessTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.temp_dir = temp.TempDirPath()
self.addCleanup(lambda: shutil.rmtree(self.temp_dir, ignore_errors=True))
def _CreateMigrationFiles(self, fnames):
for fname in fnames:
with open(os.path.join(self.temp_dir, fname), "w"):
pass
def testReturnsAllMigrationsWhenCurrentNumberIsNone(self):
fnames = ["0000.sql", "0001.sql", "0002.sql"]
self._CreateMigrationFiles(fnames)
self.assertListEqual(
mysql_migration.ListMigrationsToProcess(self.temp_dir, None), fnames)
def testReturnsOnlyMigrationsWithNumbersBiggerThanCurrentMigrationIndex(self):
fnames = ["0000.sql", "0001.sql", "0002.sql", "0003.sql"]
self._CreateMigrationFiles(fnames)
self.assertListEqual(
mysql_migration.ListMigrationsToProcess(self.temp_dir, 1),
["0002.sql", "0003.sql"])
def testDoesNotAssumeLexicalSortingOrder(self):
fnames = ["7.sql", "8.sql", "9.sql", "10.sql"]
self._CreateMigrationFiles(fnames)
self.assertListEqual(
mysql_migration.ListMigrationsToProcess(self.temp_dir, None), fnames)
class MySQLMigrationTest(mysql_test.MySQLDatabaseProviderMixin,
absltest.TestCase):
def _GetLatestMigrationNumber(self, conn):
with contextlib.closing(conn.cursor()) as cursor:
return mysql_migration.GetLatestMigrationNumber(cursor)
def testMigrationsTableIsCorrectlyUpdates(self):
all_migrations = mysql_migration.ListMigrationsToProcess(
config.CONFIG["Mysql.migrations_dir"], None)
self.assertEqual(
self._conn._RunInTransaction(self._GetLatestMigrationNumber),
len(all_migrations) - 1)
def _DumpSchema(self, conn):
with contextlib.closing(conn.cursor()) as cursor:
return mysql_migration.DumpCurrentSchema(cursor)
def testSavedSchemaIsUpToDate(self):
# An up-to-date MySQL schema dump (formed by applying all the available
# migrations) is stored in MySQL.schema_dump_path (currently - mysql.ddl).
# This file has to be updated every time a new migration is introduced.
# Please use test/grr_response_test/dump_mysql_schema.py to do that.
schema = self._conn._RunInTransaction(self._DumpSchema)
schema_dump_path = config.CONFIG["Mysql.schema_dump_path"]
with io.open(schema_dump_path) as fd:
saved_schema = fd.read()
self.assertMultiLineEqual(
schema.strip(),
saved_schema.strip(),
"%s is not updated. Make sure to run grr_dump_mysql_schema to update it"
% os.path.basename(schema_dump_path))
if __name__ == "__main__":
app.run(test_lib.main)
| 1,177 |
318 | <reponame>adam11grafik/maven-surefire
package org.apache.maven.surefire.booter.spi;
/*
* 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.
*/
import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel;
import org.apache.maven.surefire.spi.MasterProcessChannelProcessorFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.AccessControlException;
import java.security.PrivilegedAction;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import static java.security.AccessController.doPrivileged;
import static java.util.concurrent.Executors.newScheduledThreadPool;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.maven.surefire.api.util.internal.DaemonThreadFactory.newDaemonThreadFactory;
/**
* Default implementation of {@link MasterProcessChannelProcessorFactory}.
*/
public abstract class AbstractMasterProcessChannelProcessorFactory
implements MasterProcessChannelProcessorFactory
{
private static final String STREAM_FLUSHER = "surefire-forkedjvm-stream-flusher";
private final ScheduledExecutorService flusher;
public AbstractMasterProcessChannelProcessorFactory()
{
flusher = newScheduledThreadPool( 1, newDaemonThreadFactory( STREAM_FLUSHER ) );
}
protected void schedulePeriodicFlusher( int delayInMillis, final WritableBufferedByteChannel channel )
{
final AtomicLong bufferOverflows = new AtomicLong();
flusher.scheduleWithFixedDelay( new Runnable()
{
@Override
public void run()
{
long currentBufferOverflows = channel.countBufferOverflows();
// optimization: flush the Channel only if the buffer has not overflew after last period of time
if ( bufferOverflows.get() == currentBufferOverflows )
{
try
{
channel.write( ByteBuffer.allocate( 0 ) );
}
catch ( Exception e )
{
// cannot do anything about this I/O issue
}
}
else
{
bufferOverflows.set( currentBufferOverflows );
}
}
}, 0L, delayInMillis, MILLISECONDS );
}
@Override
public void close() throws IOException
{
try
{
doPrivileged( new PrivilegedAction<Object>()
{
@Override
public Object run()
{
flusher.shutdown();
// Do NOT call awaitTermination() due to this would unnecessarily prolong teardown
// time of the JVM. It is not a critical situation when the JXM exits this daemon
// thread because the interrupted flusher does not break any business function.
// All business data is already safely flushed by test events, then by sending BYE
// event at the exit time and finally by flushEventChannelOnExit() in ForkedBooter.
return null;
}
}
);
}
catch ( AccessControlException e )
{
// ignore
}
}
}
| 1,823 |
577 | <filename>WeAC/src/main/java/com/kaku/weac/fragment/NapEditFragment.java
/*
* Copyright (c) 2016 咖枯 <<EMAIL> | <EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.kaku.weac.fragment;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import com.kaku.weac.R;
import com.kaku.weac.common.WeacConstants;
import com.kaku.weac.util.LogUtil;
/**
* 小睡编辑fragment
*
* @author 咖枯
* @version 1.0 2015/07
*/
public class NapEditFragment extends BaseFragment implements OnClickListener {
/**
* Log tag :NapEditFragment
*/
private static final String LOG_TAG = "NapEditFragment";
/**
* 小睡间隔RadioButton
*/
private RadioButton mNapIntervalRbtn;
/**
* 选中的小睡间隔RadioButtonId
*/
private int mNapIntervalRbtnId;
/**
* 小睡次数RadioButton
*/
private RadioButton mNapTimesRbtn;
/**
* 选中的小睡次数RadioButtonId
*/
private int mNapTimesRbtnId;
/**
* 小睡间隔
*/
private int mNapInterval;
/**
* 小睡次数
*/
private int mNapTimes;
@Override
public void onCreate(Bundle savedInstanceState) {
getActivity().setFinishOnTouchOutside(false);
Intent i = getActivity().getIntent();
// 小睡间隔默认10分钟
mNapInterval = i.getIntExtra(WeacConstants.NAP_INTERVAL, 10);
// 小睡次数默认3次
mNapTimes = i.getIntExtra(WeacConstants.NAP_TIMES, 3);
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fm_nap_edit, container,
false);
// 设置Dialog全屏显示
getActivity().getWindow().setLayout(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
// 小睡间隔RadioGroup
RadioGroup napIntervalRg = (RadioGroup) view
.findViewById(R.id.nap_interval_radio_group);
// 设置默认选中的小睡间隔按钮Id
initNapIntervalRbtnId();
napIntervalRg
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// 取得选中小睡间隔按钮
mNapIntervalRbtn = (RadioButton) view
.findViewById(checkedId);
// 取得选中按钮的小睡间隔时间
mNapInterval = Integer.parseInt(mNapIntervalRbtn
.getText().toString());
LogUtil.i(LOG_TAG, "小睡间隔:" + mNapInterval);
}
});
// 默认选中小睡间隔按钮
napIntervalRg.check(mNapIntervalRbtnId);
// 小睡次数RadioGroup
RadioGroup napTimesRg = (RadioGroup) view
.findViewById(R.id.nap_times_radio_group);
// 设置默认选中的小睡次数按钮Id
initNapTimesRbtnId();
napTimesRg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// 取得选中的小睡次数按钮
mNapTimesRbtn = (RadioButton) view.findViewById(checkedId);
// 取得选中按钮的小睡次数
mNapTimes = Integer
.parseInt(mNapTimesRbtn.getText().toString());
LogUtil.i(LOG_TAG, "小睡次数:" + mNapTimes);
}
});
// 默认选中小睡次数按钮
napTimesRg.check(mNapTimesRbtnId);
// 取消按钮
Button cancelBtn = (Button) view.findViewById(R.id.cancel_btn);
cancelBtn.setOnClickListener(this);
// 完成按钮
Button finishBtn = (Button) view.findViewById(R.id.sure_btn);
finishBtn.setOnClickListener(this);
return view;
}
/**
* 初始化默认选中的小睡次数按钮Id
*/
private void initNapTimesRbtnId() {
switch (mNapTimes) {
case 1:
mNapTimesRbtnId = R.id.nap_times_btn1;
break;
case 3:
mNapTimesRbtnId = R.id.nap_times_btn3;
break;
case 5:
mNapTimesRbtnId = R.id.nap_times_btn5;
break;
case 8:
mNapTimesRbtnId = R.id.nap_times_btn8;
break;
case 10:
mNapTimesRbtnId = R.id.nap_times_btn10;
break;
default:
mNapTimesRbtnId = R.id.nap_times_btn3;
break;
}
}
/**
* 初始化默认选择选中的小睡间隔按钮Id
*/
private void initNapIntervalRbtnId() {
switch (mNapInterval) {
case 5:
mNapIntervalRbtnId = R.id.nap_interval_btn5;
break;
case 10:
mNapIntervalRbtnId = R.id.nap_interval_btn10;
break;
case 20:
mNapIntervalRbtnId = R.id.nap_interval_btn20;
break;
case 30:
mNapIntervalRbtnId = R.id.nap_interval_btn30;
break;
case 60:
mNapIntervalRbtnId = R.id.nap_interval_btn60;
break;
default:
mNapIntervalRbtnId = R.id.nap_interval_btn10;
break;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
// 取消按钮
case R.id.cancel_btn:
getActivity().finish();
break;
// 完成按钮
case R.id.sure_btn:
Intent data = new Intent();
data.putExtra(WeacConstants.NAP_INTERVAL, mNapInterval);
data.putExtra(WeacConstants.NAP_TIMES, mNapTimes);
getActivity().setResult(Activity.RESULT_OK, data);
getActivity().finish();
break;
}
}
}
| 3,817 |
903 | package com.github.vole.mps.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.vole.common.constants.CommonConstant;
import com.github.vole.common.validate.Assert;
import com.github.vole.mps.mapper.SysLogMapper;
import com.github.vole.mps.model.entity.SysLog;
import com.github.vole.mps.service.SysLogService;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {
@Override
public Boolean updateByLogId(Long id) {
Assert.isNull(id, "日志ID为空");
SysLog sysLog = new SysLog();
sysLog.setId(id);
sysLog.setDelFlag(CommonConstant.STATUS_DEL);
sysLog.setUpdateTime(new Date());
return updateById(sysLog);
}
}
| 335 |
434 | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.lambda.runtime.events;
import lombok.*;
import java.util.Map;
/**
* Represent the class for the Cognito User Pool Define Auth Challenge Lambda Trigger
*
* See <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html">Define Auth Challenge Lambda Trigger</a>
*
* @author jvdl <<EMAIL>>
*/
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class CognitoUserPoolDefineAuthChallengeEvent extends CognitoUserPoolEvent {
/**
* The request from the Amazon Cognito service.
*/
private Request request;
/**
* The response from your Lambda trigger.
*/
private Response response;
@Builder(setterPrefix = "with")
public CognitoUserPoolDefineAuthChallengeEvent(
String version,
String triggerSource,
String region,
String userPoolId,
String userName,
CallerContext callerContext,
Request request,
Response response) {
super(version, triggerSource, region, userPoolId, userName, callerContext);
this.request = request;
this.response = response;
}
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public static class Request extends CognitoUserPoolEvent.Request {
/**
* One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the define auth challenge trigger.
*/
private Map<String, String> clientMetadata;
private ChallengeResult[] session;
/**
* A Boolean that is populated when PreventUserExistenceErrors is set to ENABLED for your user pool client.
* A value of true means that the user id (user name, email address, etc.) did not match any existing users.
*/
private boolean userNotFound;
@Builder(setterPrefix = "with")
public Request(Map<String, String> userAttributes, Map<String, String> clientMetadata, ChallengeResult[] session, boolean userNotFound) {
super(userAttributes);
this.clientMetadata = clientMetadata;
this.session = session;
this.userNotFound = userNotFound;
}
}
@Data
@AllArgsConstructor
@Builder(setterPrefix = "with")
@NoArgsConstructor
public static class ChallengeResult {
/**
* The challenge type. One of: CUSTOM_CHALLENGE, SRP_A, PASSWORD_VERIFIER, SMS_MFA, DEVICE_SRP_AUTH, DEVICE_PASSWORD_VERIFIER, or ADMIN_NO_SRP_AUTH.
*/
private String challengeName;
/**
* Set to true if the user successfully completed the challenge, or false otherwise.
*/
private boolean challengeResult;
/**
* Your name for the custom challenge. Used only if challengeName is CUSTOM_CHALLENGE.
*/
private String challengeMetadata;
}
@Data
@AllArgsConstructor
@Builder(setterPrefix = "with")
@NoArgsConstructor
public static class Response {
/**
* Name of the next challenge, if you want to present a new challenge to your user.
*/
private String challengeName;
/**
* Set to true if you determine that the user has been sufficiently authenticated by completing the challenges, or false otherwise.
*/
private boolean issueTokens;
/**
* Set to true if you want to terminate the current authentication process, or false otherwise.
*/
private boolean failAuthentication;
}
}
| 1,511 |
2,338 | <filename>libcxx/test/std/strings/basic.string/string.cons/nullptr.compile.pass.cpp<gh_stars>1000+
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
// <string>
// basic_string(nullptr_t) = delete; // C++2b
// basic_string& operator=(nullptr_t) = delete; // C++2b
#include <string>
#include <type_traits>
static_assert(!std::is_convertible_v<decltype(nullptr), std::string>);
static_assert(!std::is_constructible_v<std::string, decltype(nullptr)>);
static_assert(!std::is_assignable_v<std::string, decltype(nullptr)>);
| 292 |
852 | import FWCore.ParameterSet.Config as cms
from CalibTracker.SiStripESProducers.fake.SiStripFedCablingFakeESSource_cfi import *
sistripconn = cms.ESProducer("SiStripConnectivity")
| 62 |
575 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include <string>
#include "net/http/http_util.h"
#include "services/network/public/cpp/cors/cors.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
namespace {
// A parser for the value of the Access-Control-Expose-Headers header.
class HTTPHeaderNameListParser {
STACK_ALLOCATED();
public:
explicit HTTPHeaderNameListParser(const String& value)
: value_(value), pos_(0) {}
// Tries parsing |value_| expecting it to be conforming to the #field-name
// ABNF rule defined in RFC 7230. Returns with the field-name entries stored
// in |output| when successful. Otherwise, returns with |output| kept empty.
//
// |output| must be empty.
void Parse(HTTPHeaderSet& output) {
DCHECK(output.empty());
while (true) {
ConsumeSpaces();
if (pos_ == value_.length() && !output.empty()) {
output.insert(std::string());
return;
}
size_t token_start = pos_;
ConsumeTokenChars();
size_t token_size = pos_ - token_start;
if (token_size == 0) {
output.clear();
return;
}
output.insert(value_.Substring(token_start, token_size).Ascii());
ConsumeSpaces();
if (pos_ == value_.length())
return;
if (value_[pos_] == ',') {
++pos_;
} else {
output.clear();
return;
}
}
}
private:
// Consumes zero or more spaces (SP and HTAB) from value_.
void ConsumeSpaces() {
while (true) {
if (pos_ == value_.length())
return;
UChar c = value_[pos_];
if (c != ' ' && c != '\t')
return;
++pos_;
}
}
// Consumes zero or more tchars from value_.
void ConsumeTokenChars() {
while (true) {
if (pos_ == value_.length())
return;
UChar c = value_[pos_];
if (c > 0x7F || !net::HttpUtil::IsTokenChar(c))
return;
++pos_;
}
}
const String value_;
size_t pos_;
};
} // namespace
namespace cors {
bool IsCorsEnabledRequestMode(network::mojom::RequestMode request_mode) {
return network::cors::IsCorsEnabledRequestMode(request_mode);
}
bool IsCorsSafelistedMethod(const String& method) {
DCHECK(!method.IsNull());
return network::cors::IsCorsSafelistedMethod(method.Latin1());
}
bool IsCorsSafelistedContentType(const String& media_type) {
return network::cors::IsCorsSafelistedContentType(media_type.Latin1());
}
bool IsNoCorsSafelistedHeader(const String& name, const String& value) {
DCHECK(!name.IsNull());
DCHECK(!value.IsNull());
return network::cors::IsNoCorsSafelistedHeader(name.Latin1(), value.Latin1());
}
bool IsPrivilegedNoCorsHeaderName(const String& name) {
DCHECK(!name.IsNull());
return network::cors::IsPrivilegedNoCorsHeaderName(name.Latin1());
}
bool IsNoCorsSafelistedHeaderName(const String& name) {
DCHECK(!name.IsNull());
return network::cors::IsNoCorsSafelistedHeaderName(name.Latin1());
}
PLATFORM_EXPORT Vector<String> PrivilegedNoCorsHeaderNames() {
Vector<String> header_names;
for (const auto& name : network::cors::PrivilegedNoCorsHeaderNames())
header_names.push_back(WebString::FromLatin1(name));
return header_names;
}
bool IsForbiddenHeaderName(const String& name) {
return !net::HttpUtil::IsSafeHeader(name.Latin1());
}
bool ContainsOnlyCorsSafelistedHeaders(const HTTPHeaderMap& header_map) {
net::HttpRequestHeaders::HeaderVector in;
for (const auto& entry : header_map) {
in.push_back(net::HttpRequestHeaders::HeaderKeyValuePair(
entry.key.Latin1(), entry.value.Latin1()));
}
return network::cors::CorsUnsafeRequestHeaderNames(in).empty();
}
bool ContainsOnlyCorsSafelistedOrForbiddenHeaders(
const HTTPHeaderMap& headers) {
Vector<String> header_names;
net::HttpRequestHeaders::HeaderVector in;
for (const auto& entry : headers) {
in.push_back(net::HttpRequestHeaders::HeaderKeyValuePair(
entry.key.Latin1(), entry.value.Latin1()));
}
// |is_revalidating| is not needed for blink-side CORS.
constexpr bool is_revalidating = false;
return network::cors::CorsUnsafeNotForbiddenRequestHeaderNames(
in, is_revalidating)
.empty();
}
bool IsOkStatus(int status) {
return network::cors::IsOkStatus(status);
}
bool CalculateCorsFlag(const KURL& url,
const SecurityOrigin* initiator_origin,
const SecurityOrigin* isolated_world_origin,
network::mojom::RequestMode request_mode) {
if (request_mode == network::mojom::RequestMode::kNavigate ||
request_mode == network::mojom::RequestMode::kNoCors) {
return false;
}
// CORS needs a proper origin (including a unique opaque origin). If the
// request doesn't have one, CORS will not work.
DCHECK(initiator_origin);
if (initiator_origin->CanReadContent(url))
return false;
if (isolated_world_origin && isolated_world_origin->CanReadContent(url))
return false;
return true;
}
HTTPHeaderSet ExtractCorsExposedHeaderNamesList(
network::mojom::CredentialsMode credentials_mode,
const ResourceResponse& response) {
// If a response was fetched via a service worker, it will always have
// CorsExposedHeaderNames set from the Access-Control-Expose-Headers header.
// For requests that didn't come from a service worker, just parse the CORS
// header.
if (response.WasFetchedViaServiceWorker()) {
HTTPHeaderSet header_set;
for (const auto& header : response.CorsExposedHeaderNames())
header_set.insert(header.Ascii());
return header_set;
}
HTTPHeaderSet header_set;
HTTPHeaderNameListParser parser(
response.HttpHeaderField(http_names::kAccessControlExposeHeaders));
parser.Parse(header_set);
if (credentials_mode != network::mojom::CredentialsMode::kInclude &&
header_set.find("*") != header_set.end()) {
header_set.clear();
for (const auto& header : response.HttpHeaderFields())
header_set.insert(header.key.Ascii());
}
return header_set;
}
bool IsCorsSafelistedResponseHeader(const String& name) {
// https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name
// TODO(dcheng): Consider using a flat_set here with a transparent comparator.
DEFINE_THREAD_SAFE_STATIC_LOCAL(HTTPHeaderSet,
allowed_cross_origin_response_headers,
({
"cache-control",
"content-language",
"content-length",
"content-type",
"expires",
"last-modified",
"pragma",
}));
return allowed_cross_origin_response_headers.find(name.Ascii()) !=
allowed_cross_origin_response_headers.end();
}
// In the spec, https://fetch.spec.whatwg.org/#ref-for-concept-request-mode,
// No-CORS mode is highly discouraged from using it for new features. Only
// legacy usages for backward compatibility are allowed except for well-designed
// usages over the fetch API.
bool IsNoCorsAllowedContext(mojom::blink::RequestContextType context) {
switch (context) {
case mojom::blink::RequestContextType::AUDIO:
case mojom::blink::RequestContextType::FAVICON:
case mojom::blink::RequestContextType::FETCH:
case mojom::blink::RequestContextType::IMAGE:
case mojom::blink::RequestContextType::OBJECT:
case mojom::blink::RequestContextType::PLUGIN:
case mojom::blink::RequestContextType::SCRIPT:
case mojom::blink::RequestContextType::SHARED_WORKER:
case mojom::blink::RequestContextType::VIDEO:
case mojom::blink::RequestContextType::WORKER:
case mojom::blink::RequestContextType::SUBRESOURCE_WEBBUNDLE:
return true;
default:
return false;
}
}
} // namespace cors
} // namespace blink
| 3,358 |
679 | <reponame>Grosskopf/openoffice<filename>main/toolkit/source/layout/core/byteseq.cxx<gh_stars>100-1000
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include <com/sun/star/io/XInputStream.hpp>
#include <osl/file.hxx>
#include <comphelper/oslfile2streamwrap.hxx>
using osl::File;
using osl::FileBase;
using namespace ::com::sun::star;
namespace layoutimpl
{
uno::Reference< io::XInputStream > getFileAsStream( const rtl::OUString &rName )
{
rtl::OUString sFileURL;
if( FileBase::E_None != FileBase::getFileURLFromSystemPath( rName, sFileURL ) )
sFileURL = rName; // maybe it already was a file url
File * blobFile = new File(sFileURL);
File::RC errorCode = blobFile->open(OpenFlag_Read);
uno::Reference<io::XInputStream> xResult;
switch (errorCode)
{
case osl::File::E_None: // got it
xResult.set( new comphelper::OSLInputStreamWrapper(blobFile,true) );
break;
case osl::File::E_NOENT: // no file => no stream
delete blobFile;
break;
default:
delete blobFile;
/* {
rtl::OUStringBuffer sMsg;
sMsg.appendAscii("Cannot open output file \"");
sMsg.append(aURL);
sMsg.appendAscii("\" : ");
sMsg.append(configmgr::FileHelper::createOSLErrorString(errorCode));
throw io::IOException(sMsg.makeStringAndClear(),NULL);
}
*/
}
return xResult;
}
} // namespace layoutimpl
| 827 |
1,909 | package info.bitrich.xchangestream.lgo.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
import java.util.Map;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order;
/** Order entered order book */
public class LgoOpenOrderEvent extends LgoBatchOrderEvent {
public LgoOpenOrderEvent(Long batchId, String type, String orderId, Date time) {
super(batchId, type, orderId, time);
}
public LgoOpenOrderEvent(
@JsonProperty("type") String type,
@JsonProperty("order_id") String orderId,
@JsonProperty("time")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
Date time) {
super(type, orderId, time);
}
@Override
public Order applyOnOrders(CurrencyPair currencyPair, Map<String, Order> allOrders) {
Order pendingOrder = allOrders.get(getOrderId());
Order.OrderStatus status =
pendingOrder.getStatus().equals(Order.OrderStatus.PARTIALLY_FILLED)
? pendingOrder.getStatus()
: Order.OrderStatus.NEW;
pendingOrder.setOrderStatus(status);
return pendingOrder;
}
}
| 462 |
335 | <gh_stars>100-1000
{
"word": "Profitable",
"definitions": [
"(of a business or activity) yielding profit or financial gain.",
"Beneficial; useful."
],
"parts-of-speech": "Adjective"
} | 88 |
1,480 | <filename>compressor/filters/css_default.py
import os
import re
import posixpath
from compressor.cache import get_hashed_mtime, get_hashed_content
from compressor.conf import settings
from compressor.filters import FilterBase, FilterError
URL_PATTERN = re.compile(r"""
url\(
\s* # any amount of whitespace
([\'"]?) # optional quote
(.*?) # any amount of anything, non-greedily (this is the actual url)
\1 # matching quote (or nothing if there was none)
\s* # any amount of whitespace
\)""", re.VERBOSE)
SRC_PATTERN = re.compile(r'src=([\'"])(.*?)\1')
SCHEMES = ('http://', 'https://', '/')
class CssAbsoluteFilter(FilterBase):
run_with_compression_disabled = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.root = settings.COMPRESS_ROOT
self.url = settings.COMPRESS_URL.rstrip('/')
self.url_path = self.url
self.has_scheme = False
def input(self, filename=None, basename=None, **kwargs):
if not filename:
return self.content
self.path = basename.replace(os.sep, '/')
self.path = self.path.lstrip('/')
if self.url.startswith(('http://', 'https://')):
self.has_scheme = True
parts = self.url.split('/')
self.url = '/'.join(parts[2:])
self.url_path = '/%s' % '/'.join(parts[3:])
self.protocol = '%s/' % '/'.join(parts[:2])
self.host = parts[2]
self.directory_name = '/'.join((self.url, os.path.dirname(self.path)))
return SRC_PATTERN.sub(self.src_converter,
URL_PATTERN.sub(self.url_converter, self.content))
def guess_filename(self, url):
local_path = url
if self.has_scheme:
# COMPRESS_URL had a protocol,
# remove it and the hostname from our path.
local_path = local_path.replace(self.protocol + self.host, "", 1)
# remove url fragment, if any
local_path = local_path.rsplit("#", 1)[0]
# remove querystring, if any
local_path = local_path.rsplit("?", 1)[0]
# Now, we just need to check if we can find
# the path from COMPRESS_URL in our url
if local_path.startswith(self.url_path):
local_path = local_path.replace(self.url_path, "", 1)
# Re-build the local full path by adding root
filename = os.path.join(self.root, local_path.lstrip('/'))
return os.path.exists(filename) and filename
def add_suffix(self, url):
filename = self.guess_filename(url)
if not filename:
return url
if settings.COMPRESS_CSS_HASHING_METHOD is None:
return url
if not url.startswith(SCHEMES):
return url
suffix = None
if settings.COMPRESS_CSS_HASHING_METHOD == "mtime":
suffix = get_hashed_mtime(filename)
elif settings.COMPRESS_CSS_HASHING_METHOD in ("hash", "content"):
suffix = get_hashed_content(filename)
else:
raise FilterError('COMPRESS_CSS_HASHING_METHOD is configured '
'with an unknown method (%s).' %
settings.COMPRESS_CSS_HASHING_METHOD)
fragment = None
if "#" in url:
url, fragment = url.rsplit("#", 1)
if "?" in url:
url = "%s&%s" % (url, suffix)
else:
url = "%s?%s" % (url, suffix)
if fragment is not None:
url = "%s#%s" % (url, fragment)
return url
def _converter(self, url):
if url.startswith(('#', 'data:')):
return url
elif url.startswith(SCHEMES):
return self.add_suffix(url)
full_url = posixpath.normpath('/'.join([str(self.directory_name),
url]))
if self.has_scheme:
full_url = "%s%s" % (self.protocol, full_url)
full_url = self.add_suffix(full_url)
return self.post_process_url(full_url)
def post_process_url(self, url):
"""
Extra URL processing, to be overridden in subclasses.
"""
return url
def url_converter(self, matchobj):
quote = matchobj.group(1)
converted_url = self._converter(matchobj.group(2))
return "url(%s%s%s)" % (quote, converted_url, quote)
def src_converter(self, matchobj):
quote = matchobj.group(1)
converted_url = self._converter(matchobj.group(2))
return "src=%s%s%s" % (quote, converted_url, quote)
class CssRelativeFilter(CssAbsoluteFilter):
"""
Do similar to ``CssAbsoluteFilter`` URL processing
but add a *relative URL prefix* instead of ``settings.COMPRESS_URL``.
"""
run_with_compression_disabled = True
def post_process_url(self, url):
"""
Replace ``settings.COMPRESS_URL`` URL prefix with '../' * (N + 1)
where N is the *depth* of ``settings.COMPRESS_OUTPUT_DIR`` folder.
E.g. by default ``settings.COMPRESS_OUTPUT_DIR == 'CACHE'``,
the depth is 1, and the prefix will be '../../'.
If ``settings.COMPRESS_OUTPUT_DIR == 'my/compiled/data'``,
the depth is 3, and the prefix will be '../../../../'.
Example:
- original file URL: '/static/my-app/style.css'
- it has an image link: ``url(images/logo.svg)``
- compiled file URL: '/static/CACHE/css/output.abcdef123456.css'
- replaced image link URL: ``url(../../my-app/images/logo.svg)``
"""
old_prefix = self.url
if self.has_scheme:
old_prefix = '{}{}'.format(self.protocol, old_prefix)
# One level up from 'css' / 'js' folder
new_prefix = '..'
# N levels up from ``settings.COMPRESS_OUTPUT_DIR``
new_prefix += '/..' * len(list(filter(
None, os.path.normpath(settings.COMPRESS_OUTPUT_DIR).split(os.sep)
)))
return re.sub('^{}'.format(old_prefix), new_prefix, url)
| 2,787 |
852 | <reponame>ckamtsikis/cmssw
// Include files
// local
#include "L1Trigger/RPCTechnicalTrigger/interface/RBCEmulator.h"
#include "L1Trigger/RPCTechnicalTrigger/interface/RBCBasicConfig.h"
#include "L1Trigger/RPCTechnicalTrigger/interface/RBCProcessTestSignal.h"
#include "L1Trigger/RPCTechnicalTrigger/interface/RBCLinkBoardSignal.h"
//-----------------------------------------------------------------------------
// Implementation file for class : RBCEmulator
//
// 2008-10-10 : <NAME>
//-----------------------------------------------------------------------------
//=============================================================================
// Standard constructor, initializes variables
//=============================================================================
RBCEmulator::RBCEmulator() : m_rbcinfo{}, m_signal{}, m_input{}, m_logtype{"TestLogic"}, m_debug{false} {
m_layersignal[0] = &m_layersignalVec[0];
m_layersignal[1] = &m_layersignalVec[1];
}
RBCEmulator::RBCEmulator(const char* logic_type)
: m_rbcinfo{},
m_signal{},
m_rbcconf{std::make_unique<RBCBasicConfig>(logic_type)},
m_input{},
m_logtype{logic_type},
m_debug{false} {
m_layersignal[0] = &m_layersignalVec[0];
m_layersignal[1] = &m_layersignalVec[1];
}
RBCEmulator::RBCEmulator(const char* f_name, const char* logic_type)
: m_rbcinfo{},
m_signal{std::make_unique<RBCProcessTestSignal>(f_name)},
m_rbcconf{std::make_unique<RBCBasicConfig>(logic_type)},
m_input{},
m_logtype{logic_type},
m_debug{false} {
m_layersignal[0] = &m_layersignalVec[0];
m_layersignal[1] = &m_layersignalVec[1];
}
//=============================================================================
void RBCEmulator::setSpecifications(const RBCBoardSpecs* rbcspecs) {
m_rbcconf = std::make_unique<RBCBasicConfig>(rbcspecs, &m_rbcinfo);
}
bool RBCEmulator::initialise() {
bool status(true);
status = m_rbcconf->initialise();
if (!status) {
if (m_debug)
std::cout << "RBCEmulator> Problem initialising the Configuration \n";
return false;
};
return true;
}
void RBCEmulator::setid(int wh, int* sec) { m_rbcinfo.setid(wh, sec); }
void RBCEmulator::emulate() {
if (m_debug)
std::cout << "RBCEmulator> starting test emulation" << std::endl;
std::bitset<2> decision;
while (m_signal->next()) {
RPCInputSignal* data = m_signal->retrievedata();
m_input = dynamic_cast<RBCLinkBoardSignal*>(data)->m_linkboardin;
m_rbcconf->rbclogic()->run(m_input, decision);
m_layersignal[0] = m_rbcconf->rbclogic()->getlayersignal(0);
m_layersignal[1] = m_rbcconf->rbclogic()->getlayersignal(1);
printlayerinfo();
if (m_debug)
std::cout << decision[0] << " " << decision[1] << std::endl;
}
if (m_debug)
std::cout << "RBCEmulator> end test emulation" << std::endl;
}
void RBCEmulator::emulate(RBCInput* in) {
if (m_debug)
std::cout << "RBCEmulator> starting emulation" << std::endl;
std::bitset<2> decision;
in->setWheelId(m_rbcinfo.wheel());
m_input = (*in);
if (m_debug)
std::cout << "RBCEmulator> copied data" << std::endl;
//.. mask and force as specified in hardware configuration
m_rbcconf->preprocess(m_input);
if (m_debug)
std::cout << "RBCEmulator> preprocessing done" << std::endl;
m_rbcconf->rbclogic()->run(m_input, decision);
if (m_debug)
std::cout << "RBCEmulator> applying logic" << std::endl;
m_layersignal[0] = m_rbcconf->rbclogic()->getlayersignal(0);
m_layersignal[1] = m_rbcconf->rbclogic()->getlayersignal(1);
m_decision.set(0, decision[0]);
m_decision.set(1, decision[1]);
if (m_debug) {
printlayerinfo();
std::cout << decision[0] << " " << decision[1] << std::endl;
std::cout << "RBCEmulator> end emulation" << std::endl;
}
decision.reset();
}
void RBCEmulator::reset() {
m_decision.reset();
m_layersignal[0]->reset();
m_layersignal[1]->reset();
}
void RBCEmulator::printinfo() const {
if (m_debug) {
std::cout << "RBC --> \n";
m_rbcinfo.printinfo();
}
}
void RBCEmulator::printlayerinfo() const {
std::cout << "Sector summary by layer: \n";
for (int i = 0; i < 6; ++i)
std::cout << (*m_layersignal[0])[i] << '\t' << (*m_layersignal[1])[i] << '\n';
}
| 1,717 |
1,125 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common;
import org.elasticsearch.common.settings.SecureString;
import java.util.Arrays;
import java.util.Base64;
import java.util.Random;
class RandomBasedUUIDGenerator implements UUIDGenerator {
/**
* Returns a Base64 encoded version of a Version 4.0 compatible UUID
* as defined here: http://www.ietf.org/rfc/rfc4122.txt
*/
@Override
public String getBase64UUID() {
return getBase64UUID(SecureRandomHolder.INSTANCE);
}
/**
* Returns a Base64 encoded {@link SecureString} of a Version 4.0 compatible UUID
* as defined here: http://www.ietf.org/rfc/rfc4122.txt
*/
public SecureString getBase64UUIDSecureString() {
byte[] uuidBytes = null;
byte[] encodedBytes = null;
try {
uuidBytes = getUUIDBytes(SecureRandomHolder.INSTANCE);
encodedBytes = Base64.getUrlEncoder().withoutPadding().encode(uuidBytes);
return new SecureString(CharArrays.utf8BytesToChars(encodedBytes));
} finally {
if (uuidBytes != null) {
Arrays.fill(uuidBytes, (byte) 0);
}
if (encodedBytes != null) {
Arrays.fill(encodedBytes, (byte) 0);
}
}
}
/**
* Returns a Base64 encoded version of a Version 4.0 compatible UUID
* randomly initialized by the given {@link java.util.Random} instance
* as defined here: http://www.ietf.org/rfc/rfc4122.txt
*/
public String getBase64UUID(Random random) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(getUUIDBytes(random));
}
private byte[] getUUIDBytes(Random random) {
final byte[] randomBytes = new byte[16];
random.nextBytes(randomBytes);
/* Set the version to version 4 (see http://www.ietf.org/rfc/rfc4122.txt)
* The randomly or pseudo-randomly generated version.
* The version number is in the most significant 4 bits of the time
* stamp (bits 4 through 7 of the time_hi_and_version field).*/
randomBytes[6] &= 0x0f; /* clear the 4 most significant bits for the version */
randomBytes[6] |= 0x40; /* set the version to 0100 / 0x40 */
/* Set the variant:
* The high field of th clock sequence multiplexed with the variant.
* We set only the MSB of the variant*/
randomBytes[8] &= 0x3f; /* clear the 2 most significant bits */
randomBytes[8] |= 0x80; /* set the variant (MSB is set)*/
return randomBytes;
}
}
| 1,227 |
8,027 | import org.junit.Test;
public class MockTest2 {
@Test
public void passingTestOne() {
System.out.println("passed!");
}
@Test
public void passingTestTwo() {
System.out.println("passed!");
}
@Test
public void passingTestThree() {
System.out.println("passed!");
}
@Test
public void passingTestFour() {
System.out.println("passed!");
}
}
| 139 |
605 | /* This file can be generated using
* javah -jni -classpath src/ -o jni/vectorAdd.h org.pocl.sample1.MainActivity
*/
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_pocl_sample1_MainActivity */
#ifndef _Included_org_pocl_sample1_MainActivity
#define _Included_org_pocl_sample1_MainActivity
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: org_pocl_sample1_MainActivity
* Method: initCL
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_org_pocl_sample1_MainActivity_initCL
(JNIEnv *, jobject);
/*
* Class: org_pocl_sample1_MainActivity
* Method: vectorAddCL
* Signature: (I[F[F[F)I
*/
JNIEXPORT jint JNICALL Java_org_pocl_sample1_MainActivity_vectorAddCL
(JNIEnv *, jobject, jint, jfloatArray, jfloatArray, jfloatArray);
/*
* Class: org_pocl_sample1_MainActivity
* Method: destroyCL
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_org_pocl_sample1_MainActivity_destroyCL
(JNIEnv *, jobject);
/*
* Class: org_pocl_sample1_MainActivity
* Method: setenv
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_pocl_sample1_MainActivity_setenv
(JNIEnv *, jobject, jstring, jstring);
#ifdef __cplusplus
}
#endif
#endif
| 501 |
377 | <gh_stars>100-1000
// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coinsbyscript.h"
#include "txdb.h"
#include "hash.h"
#include <assert.h>
CCoinsViewByScript::CCoinsViewByScript(CCoinsViewDB* viewIn) : base(viewIn) { }
bool CCoinsViewByScript::GetCoinsByScript(const CScript &script, CCoinsByScript &coins) {
const uint256 key = CCoinsViewByScript::getKey(script);
if (cacheCoinsByScript.count(key)) {
coins = cacheCoinsByScript[key];
return true;
}
if (base->GetCoinsByHashOfScript(key, coins)) {
cacheCoinsByScript[key] = coins;
return true;
}
return false;
}
CCoinsMapByScript::iterator CCoinsViewByScript::FetchCoinsByScript(const CScript &script, bool fRequireExisting) {
const uint256 key = CCoinsViewByScript::getKey(script);
CCoinsMapByScript::iterator it = cacheCoinsByScript.find(key);
if (it != cacheCoinsByScript.end())
return it;
CCoinsByScript tmp;
if (!base->GetCoinsByHashOfScript(key, tmp))
{
if (fRequireExisting)
return cacheCoinsByScript.end();
}
CCoinsMapByScript::iterator ret = cacheCoinsByScript.insert(it, std::make_pair(key, CCoinsByScript()));
tmp.swap(ret->second);
return ret;
}
CCoinsByScript &CCoinsViewByScript::GetCoinsByScript(const CScript &script, bool fRequireExisting) {
CCoinsMapByScript::iterator it = FetchCoinsByScript(script, fRequireExisting);
assert(it != cacheCoinsByScript.end());
return it->second;
}
uint256 CCoinsViewByScript::getKey(const CScript &script) {
return Hash(script.begin(), script.end());
}
| 672 |
14,668 | <reponame>zealoussnow/chromium<filename>testing/android/junit/java/src/org/chromium/testing/local/RunnerFilter.java
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.testing.local;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.manipulation.Filter;
/**
* Filters tests based on the Runner class annotating the test class.
*/
class RunnerFilter extends Filter {
private final Class<?> mRunnerClass;
/**
* Creates the filter.
*/
public RunnerFilter(Class<?> runnerClass) {
mRunnerClass = runnerClass;
}
/**
* Determines whether or not a test with the provided description should
* run based on the Runner class annotating the test class.
*/
@Override
public boolean shouldRun(Description description) {
Class<?> c = description.getTestClass();
return c != null && c.isAnnotationPresent(RunWith.class)
&& c.getAnnotation(RunWith.class).value() == mRunnerClass;
}
/**
* Returns a description of this filter.
*/
@Override
public String describe() {
return "runner-filter: " + mRunnerClass.getName();
}
}
| 456 |
1,139 | <reponame>ghiloufibelgacem/jornaldev
# import the module
# get the current clock ticks from the time() function
seconds = basic_examples.time()
print(seconds)
currentTime = time.localtime(seconds)
# print the currentTime variable to know about it
print(currentTime,'\n')
# use current time to show current time in formatted string
print('Current System time is :', time.asctime(currentTime))
print('Formatted Time is :', time.strftime("%d/%m/%Y", currentTime)) | 141 |
4,440 | # flake8: noqa
from .base import BaseModelView
from .form import InlineFormAdmin
from flask_admin.actions import action
| 34 |
839 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.systest.jaxrs.security;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.Path;
import org.apache.cxf.systest.jaxrs.Book;
import org.apache.cxf.systest.jaxrs.BookInterface;
import org.apache.cxf.systest.jaxrs.BookNotFoundFault;
@Path("/bookstorestorage/")
public class SecureBookStoreNoAnnotations implements BookInterface {
private Map<Long, Book> books = new HashMap<>();
public SecureBookStoreNoAnnotations() {
Book book = new Book();
book.setId(123L);
book.setName("CXF in Action");
books.put(book.getId(), book);
}
public Book getThatBook(Long id) {
return books.get(id);
}
public Book getThatBook(Long id, String s) {
if (s == null) {
throw new RuntimeException();
}
return books.get(id);
}
public Book getThatBook() throws BookNotFoundFault {
return books.get(123L);
}
public Book echoBook(Book b) {
return b;
}
}
| 614 |
834 |
//<Snippet1>
#using <System.Windows.Forms.dll>
#using <System.Data.dll>
#using <System.Drawing.dll>
#using <System.dll>
using namespace System;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design;
using namespace System::Drawing;
using namespace System::Data;
using namespace System::Windows::Forms;
// This control displays the name and type of the primary selection
// component in design mode, if there is one,
// and uses the IReferenceService interface to display the names of
// any components of the type of the primary selected component.
// This control uses the IComponentChangeService to monitor for
// selection changed events.
public ref class IReferenceServiceControl: public System::Windows::Forms::UserControl
{
private:
// Indicates the name of the type of the selected component, or "None selected.".
String^ selected_typename;
// Indicates the name of the base type of the selected component, or "None selected."
String^ selected_basetypename;
// Indicates the name of the selected component.
String^ selected_componentname;
// Contains the names of components of the type of the selected
// component in design mode.
array<String^>^typeComponents;
// Contains the names of components of the base type of the selected component in design mode.
array<String^>^basetypeComponents;
// Reference to the IComponentChangeService for the current component.
ISelectionService^ selectionService;
public:
IReferenceServiceControl()
{
// Initializes the control properties.
this->BackColor = Color::White;
this->SetStyle( ControlStyles::ResizeRedraw, true );
this->Name = "IReferenceServiceControl";
this->Size = System::Drawing::Size( 500, 250 );
// Initializes the data properties.
typeComponents = gcnew array<String^>(0);
basetypeComponents = gcnew array<String^>(0);
selected_typename = "None selected.";
selected_basetypename = "None selected.";
selected_componentname = "None selected.";
selectionService = nullptr;
}
property System::ComponentModel::ISite^ Site
{
// Registers and unregisters design-mode services when
// the component is sited and unsited.
virtual System::ComponentModel::ISite^ get() override
{
// Returns the site for the control.
return __super::Site;
}
virtual void set( System::ComponentModel::ISite^ value ) override
{
// The site is set to null when a component is cut or
// removed from a design-mode site.
// If an event handler has already been linked with
// an ISelectionService, remove the handler.
if ( selectionService != nullptr )
selectionService->SelectionChanged -= gcnew EventHandler( this, &IReferenceServiceControl::OnSelectionChanged );
// Sites the control.
__super::Site = value;
// Obtains an ISelectionService interface to register
// the selection changed event handler with.
selectionService = dynamic_cast<ISelectionService^>(this->GetService( ISelectionService::typeid ));
if ( selectionService != nullptr )
{
selectionService->SelectionChanged += gcnew EventHandler( this, &IReferenceServiceControl::OnSelectionChanged );
// Updates the display for the current selection, if any.
DisplayComponentsOfSelectedComponentType();
}
}
}
private:
// Updates the display according to the primary selected component,
// if any, and the names of design-mode components that the
// IReferenceService returns references for when queried for
// references to components of the primary selected component's
// type and base type.
void DisplayComponentsOfSelectedComponentType()
{
// If a component is selected...
if ( selectionService->PrimarySelection != nullptr )
{
// Sets the selected type name and selected component name to the type and name of the primary selected component.
selected_typename = selectionService->PrimarySelection->GetType()->FullName;
selected_basetypename = selectionService->PrimarySelection->GetType()->BaseType->FullName;
selected_componentname = (dynamic_cast<IComponent^>(selectionService->PrimarySelection))->Site->Name;
// Obtain an IReferenceService and obtain references to
// each component in the design-mode project
// of the selected component's type and base type.
IReferenceService^ rs = dynamic_cast<IReferenceService^>(this->GetService( IReferenceService::typeid ));
if ( rs != nullptr )
{
// Get references to design-mode components of the
// primary selected component's type.
array<Object^>^comps = (array<Object^>^)rs->GetReferences( selectionService->PrimarySelection->GetType() );
typeComponents = gcnew array<String^>(comps->Length);
for ( int i = 0; i < comps->Length; i++ )
typeComponents[ i ] = (dynamic_cast<IComponent^>(comps[ i ]))->Site->Name;
// Get references to design-mode components with a base type
// of the primary selected component's base type.
comps = (array<Object^>^)rs->GetReferences( selectionService->PrimarySelection->GetType()->BaseType );
basetypeComponents = gcnew array<String^>(comps->Length);
for ( int i = 0; i < comps->Length; i++ )
basetypeComponents[ i ] = (dynamic_cast<IComponent^>(comps[ i ]))->Site->Name;
}
}
else
{
selected_typename = "None selected.";
selected_basetypename = "None selected.";
selected_componentname = "None selected.";
typeComponents = gcnew array<String^>(0);
basetypeComponents = gcnew array<String^>(0);
}
this->Refresh();
}
void OnSelectionChanged( Object^ /*sender*/, EventArgs^ /*e*/ )
{
DisplayComponentsOfSelectedComponentType();
}
protected:
virtual void OnPaint( System::Windows::Forms::PaintEventArgs^ e ) override
{
e->Graphics->DrawString( "IReferenceService Example Control", gcnew System::Drawing::Font( FontFamily::GenericMonospace,9 ), gcnew SolidBrush( Color::Blue ), 5, 5 );
e->Graphics->DrawString( "Primary Selected Component from IComponentChangeService:", gcnew System::Drawing::Font( FontFamily::GenericMonospace,8 ), gcnew SolidBrush( Color::Red ), 5, 20 );
e->Graphics->DrawString( String::Format( "Name: {0}", selected_componentname ), gcnew System::Drawing::Font( FontFamily::GenericMonospace,8 ), gcnew SolidBrush( Color::Black ), 10, 32 );
e->Graphics->DrawString( String::Format( "Type: {0}", selected_typename ), gcnew System::Drawing::Font( FontFamily::GenericMonospace,8 ), gcnew SolidBrush( Color::Black ), 10, 44 );
e->Graphics->DrawString( String::Format( "Base Type: {0}", selected_basetypename ), gcnew System::Drawing::Font( FontFamily::GenericMonospace,8 ), gcnew SolidBrush( Color::Black ), 10, 56 );
e->Graphics->DrawLine( gcnew Pen( gcnew SolidBrush( Color::Black ),1 ), 5, 77, this->Width - 5, 77 );
e->Graphics->DrawString( "Components of Type from IReferenceService:", gcnew System::Drawing::Font( FontFamily::GenericMonospace,8 ), gcnew SolidBrush( Color::Red ), 5, 85 );
if ( !selected_typename->Equals( "None selected." ) )
for ( int i = 0; i < typeComponents->Length; i++ )
e->Graphics->DrawString( typeComponents[ i ], gcnew System::Drawing::Font( FontFamily::GenericMonospace,8 ), gcnew SolidBrush( Color::Black ), 20.f, 97.f + (i * 12) );
e->Graphics->DrawString( "Components of Base Type from IReferenceService:", gcnew System::Drawing::Font( FontFamily::GenericMonospace,8 ), gcnew SolidBrush( Color::Red ), 5.f, 109.f + (typeComponents->Length * 12) );
if ( !selected_typename->Equals( "None selected." ) )
for ( int i = 0; i < basetypeComponents->Length; i++ )
e->Graphics->DrawString( basetypeComponents[ i ], gcnew System::Drawing::Font( FontFamily::GenericMonospace,8 ), gcnew SolidBrush( Color::Black ), 20.f, 121.f + (typeComponents->Length * 12) + (i * 12) );
}
};
//</Snippet1>
| 2,912 |
2,628 | <filename>pony/orm/tests/test_prop_sum_orderby.py<gh_stars>1000+
from __future__ import absolute_import, print_function, division
import unittest
from pony.orm.core import *
from pony.orm.tests.testutils import *
from pony.orm.tests import setup_database, teardown_database
db = Database()
db = Database('sqlite', ':memory:')
class Product(db.Entity):
id = PrimaryKey(int)
name = Required(str)
comments = Set('Comment')
@property
def sum_01(self):
return coalesce(select(c.points for c in self.comments).sum(), 0)
@property
def sum_02(self):
return coalesce(select(c.points for c in self.comments).sum(), 0.0)
@property
def sum_03(self):
return coalesce(select(sum(c.points) for c in self.comments), 0)
@property
def sum_04(self):
return coalesce(select(sum(c.points) for c in self.comments), 0.0)
@property
def sum_05(self):
return sum(c.points for c in self.comments)
@property
def sum_06(self):
return coalesce(sum(c.points for c in self.comments), 0)
@property
def sum_07(self):
return coalesce(sum(c.points for c in self.comments), 0.0)
@property
def sum_08(self):
return select(sum(c.points) for c in self.comments)
@property
def sum_09(self):
return select(coalesce(sum(c.points), 0) for c in self.comments)
@property
def sum_10(self):
return select(coalesce(sum(c.points), 0.0) for c in self.comments)
@property
def sum_11(self):
return select(sum(c.points) for c in self.comments)
@property
def sum_12(self):
return sum(self.comments.points)
@property
def sum_13(self):
return coalesce(sum(self.comments.points), 0)
@property
def sum_14(self):
return coalesce(sum(self.comments.points), 0.0)
class Comment(db.Entity):
id = PrimaryKey(int)
points = Required(int)
product = Optional('Product')
class TestQuerySetMonad(unittest.TestCase):
@classmethod
def setUpClass(cls):
setup_database(db)
with db_session:
p1 = Product(id=1, name='P1')
p2 = Product(id=2, name='P1', comments=[
Comment(id=201, points=5)
])
p3 = Product(id=3, name='P1', comments=[
Comment(id=301, points=1), Comment(id=302, points=2)
])
p4 = Product(id=4, name='P1', comments=[
Comment(id=401, points=1), Comment(id=402, points=5), Comment(id=403, points=1)
])
@classmethod
def tearDownClass(cls):
teardown_database(db)
def setUp(self):
rollback()
db_session.__enter__()
def tearDown(self):
rollback()
db_session.__exit__()
def test_sum_01(self):
q = list(Product.select().sort_by(lambda p: p.sum_01))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_02(self):
q = list(Product.select().sort_by(lambda p: p.sum_02))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_03(self):
q = list(Product.select().sort_by(lambda p: p.sum_03))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_04(self):
q = list(Product.select().sort_by(lambda p: p.sum_04))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_05(self):
q = list(Product.select().sort_by(lambda p: p.sum_05))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_06(self):
q = list(Product.select().sort_by(lambda p: p.sum_06))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_07(self):
q = list(Product.select().sort_by(lambda p: p.sum_07))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_08(self):
q = list(Product.select().sort_by(lambda p: p.sum_08))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_09(self):
q = list(Product.select().sort_by(lambda p: p.sum_09))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_10(self):
q = list(Product.select().sort_by(lambda p: p.sum_10))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_11(self):
q = list(Product.select().sort_by(lambda p: p.sum_11))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_12(self):
q = list(Product.select().sort_by(lambda p: p.sum_12))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_13(self):
q = list(Product.select().sort_by(lambda p: p.sum_13))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
def test_sum_14(self):
q = list(Product.select().sort_by(lambda p: p.sum_14))
result = [p.id for p in q]
self.assertEqual(result, [1, 3, 2, 4])
if __name__ == "__main__":
unittest.main()
| 2,446 |
3,073 | <reponame>Paul3MK/NewsBlur<gh_stars>1000+
//
// AddSiteTableCell.h
// NewsBlur
//
// Created by <NAME> on 8/7/12.
// Copyright (c) 2012 NewsBlur. All rights reserved.
//
#import "ABTableViewCell.h"
@interface AddSiteTableCell : ABTableViewCell {
NewsBlurAppDelegate *appDelegate;
NSString *siteTitle;
NSString *siteUrl;
NSString *siteSubscribers;
UIImage *siteFavicon;
UIColor *feedColorBar;
UIColor *feedColorBarTopBorder;
}
@property (nonatomic) NSString *siteTitle;
@property (nonatomic) NSString *siteUrl;
@property (nonatomic) NSString *siteSubscribers;
@property (nonatomic) UIImage *siteFavicon;
@property (nonatomic) UIColor *feedColorBar;
@property (nonatomic) UIColor *feedColorBarTopBorder;
@end
| 290 |
879 | <gh_stars>100-1000
package org.zstack.storage.ceph.backup;
import org.zstack.header.message.APIEvent;
import org.zstack.header.rest.RestResponse;
import org.zstack.header.storage.backup.BackupStorageState;
import org.zstack.header.storage.backup.BackupStorageStatus;
import java.sql.Timestamp;
import java.util.Collections;
/**
* Created by <NAME> on 6/6/2016.
*/
@RestResponse(allTo = "inventory")
public class APIUpdateCephBackupStorageMonEvent extends APIEvent {
private CephBackupStorageInventory inventory;
public APIUpdateCephBackupStorageMonEvent() {
}
public APIUpdateCephBackupStorageMonEvent(String apiId) {
super(apiId);
}
public CephBackupStorageInventory getInventory() {
return inventory;
}
public void setInventory(CephBackupStorageInventory inventory) {
this.inventory = inventory;
}
public static APIUpdateCephBackupStorageMonEvent __example__() {
APIUpdateCephBackupStorageMonEvent event = new APIUpdateCephBackupStorageMonEvent();
CephBackupStorageInventory bs = new CephBackupStorageInventory();
bs.setName("My Ceph Backup Storage");
bs.setDescription("Public Ceph Backup Storage");
bs.setCreateDate(new Timestamp(org.zstack.header.message.DocUtils.date));
bs.setLastOpDate(new Timestamp(org.zstack.header.message.DocUtils.date));
bs.setType("Ceph");
CephBackupStorageMonInventory mon = new CephBackupStorageMonInventory();
mon.setMonUuid(uuid());
mon.setMonAddr("10.0.1.4");
bs.setMons(Collections.singletonList(mon));
bs.setState(BackupStorageState.Enabled.toString());
bs.setStatus(BackupStorageStatus.Connected.toString());
bs.setAvailableCapacity(924L * 1024L * 1024L);
bs.setTotalCapacity(1024L * 1024L * 1024L);
bs.setAttachedZoneUuids(Collections.singletonList(uuid()));
event.setInventory(bs);
return event;
}
}
| 764 |
892 | <reponame>westonsteimel/advisory-database-github<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-92x4-fq2c-9xx4",
"modified": "2022-05-01T07:20:30Z",
"published": "2022-05-01T07:20:30Z",
"aliases": [
"CVE-2006-4635"
],
"details": "Unspecified vulnerability in MySource Classic 2.14.6, and possibly earlier, allows remote authenticated users, with superuser privileges, to inject arbitrary PHP code via unspecified vectors related to the Equation attribute in Web_Extensions - Notitia (I/II). NOTE: due to lack of details, it is not clear whether this issue is file inclusion, static code injection, or another type of issue.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2006-4635"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/28768"
},
{
"type": "WEB",
"url": "http://classic.squiz.net/download/changelogs/change_log_2.14.8"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/21757"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/19868"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2006/3477"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 614 |
648 | {"resourceType":"DataElement","id":"Procedure.report","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00"},"url":"http://hl7.org/fhir/DataElement/Procedure.report","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"path":"Procedure.report","short":"Any report resulting from the procedure","definition":"This could be a histology result, pathology report, surgical report, etc..","comments":"There could potentially be multiple reports - e.g. if this was a procedure which took multiple biopsies resulting in a number of anatomical pathology reports.","min":0,"max":"*","type":[{"code":"Reference","profile":["http://hl7.org/fhir/StructureDefinition/DiagnosticReport"]}],"mapping":[{"identity":"rim","map":".inboundRelationship[typeCode=SUBJ].source[classCode=OBS, moodCode=EVN]"}]}]} | 225 |
631 | package com.neu.his.cloud.zuul.dto.dms;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.math.BigDecimal;
@Setter
@Getter
@ToString
public class DmsNonDrugItemRecordParam implements Serializable {
@ApiModelProperty(value = "目的")
String aim;
@ApiModelProperty(value = "要求")
String demand;
@ApiModelProperty(value = "临床印象")
String clinicalImpression;
@ApiModelProperty(value = "临床诊断")
String clinicalDiagnosis;
@ApiModelProperty(value = "非药品Id")
Long noDrugId;
@ApiModelProperty(value = "检查部位")
String checkParts;
@ApiModelProperty(value = "执行科室id")
Long excuteDeptId;
@ApiModelProperty(value = "项目金额")
BigDecimal amount;
}
| 361 |
1,403 | #ifndef CLIPPER_UTIL_HPP
#define CLIPPER_UTIL_HPP
namespace container {
template <class T>
class CircularBuffer {
public:
explicit CircularBuffer(const size_t capacity) : capacity_(capacity) {
if (capacity <= 0) {
throw std::runtime_error(
"Circular buffer instance must have a positive capacity!");
}
items_.reserve(capacity_);
}
void insert(T item) {
if (items_.size() < capacity_) {
items_.push_back(item);
} else {
items_[curr_index_] = item;
}
curr_index_ = (curr_index_ + 1) % capacity_;
}
std::vector<T> get_items() const {
std::vector<T> items_to_return;
items_to_return.reserve(items_.size());
size_t output_index = curr_index_ % items_.size();
for (size_t i = 0; i < items_.size(); i++) {
items_to_return.push_back(items_[output_index]);
output_index = (output_index + 1) % items_.size();
}
return items_to_return;
}
private:
size_t curr_index_ = 0;
std::vector<T> items_;
const size_t capacity_;
};
} // namespace container
#endif // CLIPPER_UTIL_HPP
| 440 |
436 | /**
* The MIT License
* Copyright (c) 2019- Nordic Institute for Interoperability Solutions (NIIS)
* Copyright (c) 2018 Estonian Information System Authority (RIA),
* Nordic Institute for Interoperability Solutions (NIIS), Population Register Centre (VRK)
* Copyright (c) 2015-2017 Estonian Information System Authority (RIA), Population Register Centre (VRK)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package ee.ria.xroad.proxy.messagelog;
import ee.ria.xroad.common.conf.globalconf.GlobalConf;
import ee.ria.xroad.common.signature.TimestampVerifier;
import org.bouncycastle.tsp.TimeStampRequest;
import org.bouncycastle.tsp.TimeStampResponse;
import org.bouncycastle.tsp.TimeStampToken;
import java.util.List;
import static ee.ria.xroad.proxy.messagelog.TimestamperUtil.getTimestampResponse;
class TestTimestamperWorker extends TimestamperWorker {
private static volatile Boolean shouldFail;
TestTimestamperWorker(List<String> tspUrls) {
super(tspUrls);
}
public static void failNextTimestamping(boolean failureExpected) {
TestTimestamperWorker.shouldFail = failureExpected;
}
@Override
protected AbstractTimestampRequest createSingleTimestampRequest(Long logRecord) {
return new SingleTimestampRequest(logRecord) {
@Override
protected Timestamper.TimestampResult makeTsRequest(TimeStampRequest tsRequest, List<String> tspUrls)
throws Exception {
synchronized (shouldFail) {
if (shouldFail) {
shouldFail = false;
throw new RuntimeException("time-stamping failed");
}
}
TsRequest req = DummyTSP.makeRequest(tsRequest);
TimeStampResponse tsResponse = getTimestampResponse(req.getInputStream());
verify(tsRequest, tsResponse);
return result(tsResponse, req.getUrl());
}
@Override
protected void verify(TimeStampRequest request, TimeStampResponse response) throws Exception {
// do not validate against request
TimeStampToken token = response.getTimeStampToken();
TimestampVerifier.verify(token, GlobalConf.getTspCertificates());
}
};
}
@Override
protected AbstractTimestampRequest createBatchTimestampRequest(Long[] logRecords, String[] signatureHashes) {
return new BatchTimestampRequest(logRecords, signatureHashes) {
@Override
protected Timestamper.TimestampResult makeTsRequest(TimeStampRequest tsRequest, List<String> tspUrls)
throws Exception {
synchronized (shouldFail) {
if (shouldFail) {
shouldFail = false;
throw new RuntimeException("time-stamping failed");
}
}
TsRequest req = DummyTSP.makeRequest(tsRequest);
TimeStampResponse tsResponse = getTimestampResponse(req.getInputStream());
verify(tsRequest, tsResponse);
return result(tsResponse, req.getUrl());
}
@Override
protected void verify(TimeStampRequest request, TimeStampResponse response) throws Exception {
// do not validate against request
TimeStampToken token = response.getTimeStampToken();
TimestampVerifier.verify(token, GlobalConf.getTspCertificates());
}
};
}
}
| 1,768 |
467 | package com.yoyiyi.soleil.adapter.home.section.chase;
import android.content.Intent;
import com.yoyiyi.soleil.R;
import com.yoyiyi.soleil.module.bangumi.BangumiIndexActivity;
import com.yoyiyi.soleil.module.bangumi.BangumiScheduleActivity;
import com.yoyiyi.soleil.widget.section.StatelessSection;
import com.yoyiyi.soleil.widget.section.ViewHolder;
/**
* @author zzq 作者 E-mail: <EMAIL>
* @date 创建时间:2017/5/26 21:59
* 描述:
*/
public class ChaseIndexSection extends StatelessSection {
public ChaseIndexSection() {
super(R.layout.layout_item_home_chase_bangumi_index, R.layout.layout_empty);
}
@Override
public void onBindHeaderViewHolder(ViewHolder holder) {
holder.getView(R.id.ll_bangumi_timeline)
.setOnClickListener(view ->
mContext.startActivity(new Intent(mContext, BangumiScheduleActivity.class)));
holder.getView(R.id.ll_bangumi_index)
.setOnClickListener(view ->
mContext.startActivity(new Intent(mContext, BangumiIndexActivity.class)));
}
}
| 472 |
994 | <gh_stars>100-1000
/*++
Copyright (c) Microsoft Corporation
Module Name:
FxFileObjectUm.hpp
Abstract:
This module implements a frameworks managed FileObject
Author:
Environment:
User mode only
Revision History:
--*/
#ifndef _FXFILEOBJECTUM_H_
#define _FXFILEOBJECTUM_H_
#include "FxFileObject.hpp"
#endif // _FXFILEOBJECTUM_H_
| 134 |
14,668 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/public/web/modules/media/audio/audio_output_ipc_factory.h"
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/message_loop/message_pump_type.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/threading/thread.h"
#include "media/audio/audio_output_ipc.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/public/mojom/media/renderer_audio_output_stream_factory.mojom-blink.h"
#include "third_party/blink/renderer/platform/testing/io_task_runner_testing_platform_support.h"
using ::testing::_;
namespace blink {
namespace {
const int kRenderFrameId = 0;
blink::LocalFrameToken TokenFromInt(int i) {
static base::UnguessableToken base_token = base::UnguessableToken::Create();
return blink::LocalFrameToken(base::UnguessableToken::Deserialize(
base_token.GetHighForSerialization() + i,
base_token.GetLowForSerialization() + i));
}
std::unique_ptr<base::Thread> MakeIOThread() {
auto io_thread = std::make_unique<base::Thread>("test IO thread");
base::Thread::Options thread_options(base::MessagePumpType::IO, 0);
CHECK(io_thread->StartWithOptions(std::move(thread_options)));
return io_thread;
}
class FakeRemoteFactory
: public mojom::blink::RendererAudioOutputStreamFactory {
public:
FakeRemoteFactory() = default;
~FakeRemoteFactory() override {}
void RequestDeviceAuthorization(
mojo::PendingReceiver<media::mojom::blink::AudioOutputStreamProvider>
stream_provider,
const absl::optional<base::UnguessableToken>& session_id,
const String& device_id,
RequestDeviceAuthorizationCallback callback) override {
std::move(callback).Run(
static_cast<media::mojom::blink::OutputDeviceStatus>(
media::OutputDeviceStatus::
OUTPUT_DEVICE_STATUS_ERROR_NOT_AUTHORIZED),
media::AudioParameters::UnavailableDeviceParams(), WTF::g_empty_string);
EXPECT_FALSE(on_called_.is_null());
std::move(on_called_).Run();
}
void SetOnCalledCallback(base::OnceClosure on_called) {
on_called_ = std::move(on_called);
}
void Bind(mojo::ScopedMessagePipeHandle handle) {
EXPECT_FALSE(receiver_.is_bound());
receiver_.Bind(
mojo::PendingReceiver<mojom::blink::RendererAudioOutputStreamFactory>(
std::move(handle)));
}
private:
mojo::Receiver<mojom::blink::RendererAudioOutputStreamFactory> receiver_{
this};
base::OnceClosure on_called_;
};
class FakeAudioOutputIPCDelegate : public media::AudioOutputIPCDelegate {
void OnError() override {}
void OnDeviceAuthorized(media::OutputDeviceStatus device_status,
const media::AudioParameters& output_params,
const std::string& matched_device_id) override {}
void OnStreamCreated(base::UnsafeSharedMemoryRegion region,
base::SyncSocket::ScopedHandle socket_handle,
bool playing_automatically) override {}
void OnIPCClosed() override {}
};
} // namespace
class AudioOutputIPCFactoryTest : public testing::Test {
public:
AudioOutputIPCFactoryTest() = default;
~AudioOutputIPCFactoryTest() override = default;
void RequestAuthorizationOnIOThread(
std::unique_ptr<media::AudioOutputIPC> output_ipc) {
output_ipc->RequestDeviceAuthorization(&fake_delegate,
base::UnguessableToken(), "");
output_ipc->CloseStream();
}
private:
FakeAudioOutputIPCDelegate fake_delegate;
};
TEST_F(AudioOutputIPCFactoryTest, CallFactoryFromIOThread) {
// This test makes sure that AudioOutputIPCFactory correctly binds the
// RendererAudioOutputStreamFactory to the IO thread.
ScopedTestingPlatformSupport<IOTaskRunnerTestingPlatformSupport> platform;
base::RunLoop run_loop;
auto io_thread = MakeIOThread();
FakeRemoteFactory remote_factory;
remote_factory.SetOnCalledCallback(run_loop.QuitWhenIdleClosure());
auto& interface_broker = blink::GetEmptyBrowserInterfaceBroker();
interface_broker.SetBinderForTesting(
mojom::blink::RendererAudioOutputStreamFactory::Name_,
base::BindRepeating(&FakeRemoteFactory::Bind,
base::Unretained(&remote_factory)));
AudioOutputIPCFactory ipc_factory(io_thread->task_runner());
ipc_factory.RegisterRemoteFactory(TokenFromInt(kRenderFrameId),
&interface_broker);
// To make sure that the pointer stored in |ipc_factory| is connected to
// |remote_factory|, and also that it's bound to |io_thread|, we create an
// AudioOutputIPC object and request device authorization on the IO thread.
// This is supposed to call |remote_factory| on the main thread.
io_thread->task_runner()->PostTask(
FROM_HERE,
base::BindOnce(
&AudioOutputIPCFactoryTest::RequestAuthorizationOnIOThread,
base::Unretained(this),
ipc_factory.CreateAudioOutputIPC(TokenFromInt(kRenderFrameId))));
// Wait for call to |remote_factory|:
run_loop.Run();
ipc_factory.MaybeDeregisterRemoteFactory(TokenFromInt(0));
interface_broker.SetBinderForTesting(
mojom::blink::RendererAudioOutputStreamFactory::Name_, {});
io_thread.reset();
base::RunLoop().RunUntilIdle();
}
TEST_F(AudioOutputIPCFactoryTest, SeveralFactories) {
// This test simulates having several frames being created and destructed.
ScopedTestingPlatformSupport<IOTaskRunnerTestingPlatformSupport> platform;
auto io_thread = MakeIOThread();
const int n_factories = 5;
std::vector<FakeRemoteFactory> remote_factories(n_factories);
auto& interface_broker = blink::GetEmptyBrowserInterfaceBroker();
interface_broker.SetBinderForTesting(
mojom::blink::RendererAudioOutputStreamFactory::Name_,
base::BindLambdaForTesting([&](mojo::ScopedMessagePipeHandle handle) {
static int factory_index = 0;
DCHECK_LT(factory_index, n_factories);
remote_factories[factory_index++].Bind(std::move(handle));
}));
base::RunLoop().RunUntilIdle();
AudioOutputIPCFactory ipc_factory(io_thread->task_runner());
for (int i = 0; i < n_factories; i++) {
ipc_factory.RegisterRemoteFactory(TokenFromInt(kRenderFrameId + i),
&interface_broker);
}
base::RunLoop run_loop;
remote_factories[0].SetOnCalledCallback(run_loop.QuitWhenIdleClosure());
io_thread->task_runner()->PostTask(
FROM_HERE,
base::BindOnce(
&AudioOutputIPCFactoryTest::RequestAuthorizationOnIOThread,
base::Unretained(this),
ipc_factory.CreateAudioOutputIPC(TokenFromInt(kRenderFrameId))));
run_loop.Run();
// Do some operation and make sure the internal state isn't messed up:
ipc_factory.MaybeDeregisterRemoteFactory(TokenFromInt(1));
base::RunLoop run_loop2;
remote_factories[2].SetOnCalledCallback(run_loop2.QuitWhenIdleClosure());
io_thread->task_runner()->PostTask(
FROM_HERE,
base::BindOnce(
&AudioOutputIPCFactoryTest::RequestAuthorizationOnIOThread,
base::Unretained(this),
ipc_factory.CreateAudioOutputIPC(TokenFromInt(kRenderFrameId + 2))));
run_loop2.Run();
for (int i = 0; i < n_factories; i++) {
if (i == 1)
continue;
ipc_factory.MaybeDeregisterRemoteFactory(TokenFromInt(i));
}
interface_broker.SetBinderForTesting(
mojom::blink::RendererAudioOutputStreamFactory::Name_, {});
io_thread.reset();
base::RunLoop().RunUntilIdle();
}
TEST_F(AudioOutputIPCFactoryTest, RegisterDeregisterBackToBack_Deregisters) {
// This test makes sure that calling Register... followed by Deregister...
// correctly sequences the registration before the deregistration.
ScopedTestingPlatformSupport<IOTaskRunnerTestingPlatformSupport> platform;
auto io_thread = MakeIOThread();
FakeRemoteFactory remote_factory;
auto& interface_broker = blink::GetEmptyBrowserInterfaceBroker();
interface_broker.SetBinderForTesting(
mojom::blink::RendererAudioOutputStreamFactory::Name_,
base::BindRepeating(&FakeRemoteFactory::Bind,
base::Unretained(&remote_factory)));
AudioOutputIPCFactory ipc_factory(io_thread->task_runner());
ipc_factory.RegisterRemoteFactory(TokenFromInt(kRenderFrameId),
&interface_broker);
ipc_factory.MaybeDeregisterRemoteFactory(TokenFromInt(kRenderFrameId));
// That there is no factory remaining at destruction is DCHECKed in the
// AudioOutputIPCFactory destructor.
base::RunLoop().RunUntilIdle();
interface_broker.SetBinderForTesting(
mojom::blink::RendererAudioOutputStreamFactory::Name_, {});
io_thread.reset();
base::RunLoop().RunUntilIdle();
}
} // namespace blink
| 3,401 |
2,151 | package org.junit.tests.running.classes;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runner.Runner;
import org.junit.runner.notification.Failure;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Parameterized.UseParametersRunnerFactory;
import org.junit.runners.model.InitializationError;
import org.junit.runners.parameterized.ParametersRunnerFactory;
import org.junit.runners.parameterized.TestWithParameters;
public class ParameterizedTestTest {
@RunWith(Parameterized.class)
static public class FibonacciTest {
@Parameters(name = "{index}: fib({0})={1}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][]{{0, 0}, {1, 1}, {2, 1},
{3, 2}, {4, 3}, {5, 5}, {6, 8}});
}
private final int fInput;
private final int fExpected;
public FibonacciTest(int input, int expected) {
fInput = input;
fExpected = expected;
}
@Test
public void test() {
assertEquals(fExpected, fib(fInput));
}
private int fib(int x) {
return 0;
}
}
@Test
public void count() {
Result result = JUnitCore.runClasses(FibonacciTest.class);
assertEquals(7, result.getRunCount());
assertEquals(6, result.getFailureCount());
}
@Test
public void failuresNamedCorrectly() {
Result result = JUnitCore.runClasses(FibonacciTest.class);
assertEquals(
"test[1: fib(1)=1](" + FibonacciTest.class.getName() + ")",
result.getFailures().get(0).getTestHeader());
}
@Test
public void countBeforeRun() throws Exception {
Runner runner = Request.aClass(FibonacciTest.class).getRunner();
assertEquals(7, runner.testCount());
}
@Test
public void plansNamedCorrectly() throws Exception {
Runner runner = Request.aClass(FibonacciTest.class).getRunner();
Description description = runner.getDescription();
assertEquals("[0: fib(0)=0]", description.getChildren().get(0)
.getDisplayName());
}
@RunWith(Parameterized.class)
public static class ParameterizedWithoutSpecialTestname {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{{3}, {3}});
}
public ParameterizedWithoutSpecialTestname(Object something) {
}
@Test
public void testSomething() {
}
}
@Test
public void usesIndexAsTestName() {
Runner runner = Request
.aClass(ParameterizedWithoutSpecialTestname.class).getRunner();
Description description = runner.getDescription();
assertEquals("[1]", description.getChildren().get(1).getDisplayName());
}
@RunWith(Parameterized.class)
static public class FibonacciWithParameterizedFieldTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{{0, 0}, {1, 1}, {2, 1},
{3, 2}, {4, 3}, {5, 5}, {6, 8}});
}
@Parameter(0)
public int fInput;
@Parameter(1)
public int fExpected;
@Test
public void test() {
assertEquals(fExpected, fib(fInput));
}
private int fib(int x) {
return 0;
}
}
@Test
public void countWithParameterizedField() {
Result result = JUnitCore.runClasses(FibonacciWithParameterizedFieldTest.class);
assertEquals(7, result.getRunCount());
assertEquals(6, result.getFailureCount());
}
@Test
public void failuresNamedCorrectlyWithParameterizedField() {
Result result = JUnitCore.runClasses(FibonacciWithParameterizedFieldTest.class);
assertEquals(String
.format("test[1](%s)", FibonacciWithParameterizedFieldTest.class.getName()), result
.getFailures().get(0).getTestHeader());
}
@Test
public void countBeforeRunWithParameterizedField() throws Exception {
Runner runner = Request.aClass(FibonacciWithParameterizedFieldTest.class).getRunner();
assertEquals(7, runner.testCount());
}
@Test
public void plansNamedCorrectlyWithParameterizedField() throws Exception {
Runner runner = Request.aClass(FibonacciWithParameterizedFieldTest.class).getRunner();
Description description = runner.getDescription();
assertEquals("[0]", description.getChildren().get(0).getDisplayName());
}
@RunWith(Parameterized.class)
static public class BadIndexForAnnotatedFieldTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{{0}});
}
@Parameter(2)
public int fInput;
public int fExpected;
@Test
public void test() {
assertEquals(fExpected, fib(fInput));
}
private int fib(int x) {
return 0;
}
}
@Test
public void failureOnInitialization() {
Result result = JUnitCore.runClasses(BadIndexForAnnotatedFieldTest.class);
assertEquals(2, result.getFailureCount());
List<Failure> failures = result.getFailures();
assertEquals("Invalid @Parameter value: 2. @Parameter fields counted: 1. Please use an index between 0 and 0.",
failures.get(0).getException().getMessage());
assertEquals("@Parameter(0) is never used.", failures.get(1).getException().getMessage());
}
@RunWith(Parameterized.class)
static public class BadNumberOfAnnotatedFieldTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{{0, 0}});
}
@Parameter(0)
public int fInput;
public int fExpected;
@Test
public void test() {
assertEquals(fExpected, fib(fInput));
}
private int fib(int x) {
return 0;
}
}
@Test
public void numberOfFieldsAndParametersShouldMatch() {
Result result = JUnitCore.runClasses(BadNumberOfAnnotatedFieldTest.class);
assertEquals(1, result.getFailureCount());
List<Failure> failures = result.getFailures();
assertTrue(failures.get(0).getException().getMessage().contains("Wrong number of parameters and @Parameter fields. @Parameter fields counted: 1, available parameters: 2."));
}
private static String fLog;
@RunWith(Parameterized.class)
static public class BeforeAndAfter {
@BeforeClass
public static void before() {
fLog += "before ";
}
@AfterClass
public static void after() {
fLog += "after ";
}
public BeforeAndAfter(int x) {
}
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{{3}});
}
@Test
public void aTest() {
}
}
@Test
public void beforeAndAfterClassAreRun() {
fLog = "";
JUnitCore.runClasses(BeforeAndAfter.class);
assertEquals("before after ", fLog);
}
@RunWith(Parameterized.class)
static public class EmptyTest {
@BeforeClass
public static void before() {
fLog += "before ";
}
@AfterClass
public static void after() {
fLog += "after ";
}
}
@Test
public void validateClassCatchesNoParameters() {
Result result = JUnitCore.runClasses(EmptyTest.class);
assertEquals(1, result.getFailureCount());
}
@RunWith(Parameterized.class)
static public class IncorrectTest {
@Test
public int test() {
return 0;
}
@Parameters
public static Collection<Object[]> data() {
return Collections.singletonList(new Object[]{1});
}
}
@Test
public void failuresAddedForBadTestMethod() throws Exception {
Result result = JUnitCore.runClasses(IncorrectTest.class);
assertEquals(1, result.getFailureCount());
}
@RunWith(Parameterized.class)
static public class ProtectedParametersTest {
@Parameters
protected static Collection<Object[]> data() {
return Collections.emptyList();
}
@Test
public void aTest() {
}
}
@Test
public void meaningfulFailureWhenParametersNotPublic() {
assertTestCreatesSingleFailureWithMessage(ProtectedParametersTest.class,
"No public static parameters method on class "
+ ProtectedParametersTest.class.getName());
}
@RunWith(Parameterized.class)
static public class ParametersNotIterable {
@Parameters
public static String data() {
return "foo";
}
@Test
public void aTest() {
}
}
@Test
public void meaningfulFailureWhenParametersAreNotAnIterable() {
assertThat(
testResult(ParametersNotIterable.class).toString(),
containsString("ParametersNotIterable.data() must return an Iterable of arrays."));
}
@RunWith(Parameterized.class)
static public class PrivateConstructor {
private PrivateConstructor(int x) {
}
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{{3}});
}
@Test
public void aTest() {
}
}
@Test(expected = InitializationError.class)
public void exceptionWhenPrivateConstructor() throws Throwable {
new Parameterized(PrivateConstructor.class);
}
@RunWith(Parameterized.class)
static public class FibonacciTestWithArray {
@Parameters(name= "{index}: fib({0})={1}")
public static Object[][] data() {
return new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
{ 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } };
}
private final int fInput;
private final int fExpected;
public FibonacciTestWithArray(int input, int expected) {
fInput= input;
fExpected= expected;
}
@Test
public void test() {
assertEquals(fExpected, fib(fInput));
}
private int fib(int x) {
return 0;
}
}
@Test
public void runsEveryTestOfArray() {
Result result= JUnitCore.runClasses(FibonacciTestWithArray.class);
assertEquals(7, result.getRunCount());
}
@RunWith(Parameterized.class)
static public class SingleArgumentTestWithArray {
@Parameters
public static Object[] data() {
return new Object[] { "first test", "second test" };
}
public SingleArgumentTestWithArray(Object argument) {
}
@Test
public void aTest() {
}
}
@Test
public void runsForEverySingleArgumentOfArray() {
Result result= JUnitCore.runClasses(SingleArgumentTestWithArray.class);
assertEquals(2, result.getRunCount());
}
@RunWith(Parameterized.class)
static public class SingleArgumentTestWithIterable {
@Parameters
public static Iterable<? extends Object> data() {
return asList("first test", "second test");
}
public SingleArgumentTestWithIterable(Object argument) {
}
@Test
public void aTest() {
}
}
@Test
public void runsForEverySingleArgumentOfIterable() {
Result result= JUnitCore
.runClasses(SingleArgumentTestWithIterable.class);
assertEquals(2, result.getRunCount());
}
static public class ExceptionThrowingRunnerFactory implements
ParametersRunnerFactory {
public Runner createRunnerForTestWithParameters(TestWithParameters test)
throws InitializationError {
throw new InitializationError(
"Called ExceptionThrowingRunnerFactory.");
}
}
@RunWith(Parameterized.class)
@UseParametersRunnerFactory(ExceptionThrowingRunnerFactory.class)
static public class TestWithUseParametersRunnerFactoryAnnotation {
@Parameters
public static Iterable<? extends Object> data() {
return asList("single test");
}
public TestWithUseParametersRunnerFactoryAnnotation(Object argument) {
}
@Test
public void aTest() {
}
}
@Test
public void usesParametersRunnerFactoryThatWasSpecifiedByAnnotation() {
assertTestCreatesSingleFailureWithMessage(
TestWithUseParametersRunnerFactoryAnnotation.class,
"Called ExceptionThrowingRunnerFactory.");
}
private void assertTestCreatesSingleFailureWithMessage(Class<?> test, String message) {
Result result = JUnitCore.runClasses(test);
assertEquals(1, result.getFailures().size());
assertEquals(message, result.getFailures().get(0).getMessage());
}
@RunWith(Parameterized.class)
@UseParametersRunnerFactory(ExceptionThrowingRunnerFactory.class)
public static abstract class UseParameterizedFactoryAbstractTest {
@Parameters
public static Iterable<? extends Object> data() {
return asList("single test");
}
}
public static class UseParameterizedFactoryTest extends
UseParameterizedFactoryAbstractTest {
public UseParameterizedFactoryTest(String parameter) {
}
@Test
public void parameterizedTest() {
}
}
@Test
public void usesParametersRunnerFactoryThatWasSpecifiedByAnnotationInSuperClass() {
assertTestCreatesSingleFailureWithMessage(
UseParameterizedFactoryTest.class,
"Called ExceptionThrowingRunnerFactory.");
}
} | 6,084 |
550 | <reponame>iLiuKun/java-sdk<gh_stars>100-1000
package com.qiniu.qvs.model;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.qiniu.util.StringMap;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Device {
private int type; //可选项为摄像头、平台两类,1:摄像头,2:平台。
private String name; // 设备名称 (可包含 字母、数字、中划线、下划线;1 ~ 100 个字符长)
private String username; // 用户名, 4~40位,可包含大写字母、小写字母、数字、中划线,建议与设备国标ID一致
private String password; // 密码, 4~40位,可包含大写字母、小写字母、数字、中划线
private boolean pullIfRegister; // 注册成功后启动拉流, 默认关闭
private String desc; // 关于设备的描述信息
private String gbId; // 设备国标ID
/**
* 转换为POST参数对象
*
* @return POST参数对象
*/
public StringMap transferPostParam() {
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
return gson.fromJson(gson.toJson(this), StringMap.class);
}
}
| 646 |
6,457 | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2020 Intel Corporation. All Rights Reserved.
//#cmake:add-file ../../../../common/utilities/number/stabilized-value.h
#include "../../../test.h"
#include <../common/utilities/number/stabilized-value.h>
using namespace utilities::number;
// Test group description:
// * This tests group verifies stabilized_value class.
//
// Current test description:
// * Verify stabilized_value percentage input is at range (0-100] % (zero not included)
TEST_CASE( "Illegal input - percentage value too high", "[stabilized value]" )
{
stabilized_value< float > stab_value( 5 );
stab_value.add( 55.f );
CHECK_THROWS( stab_value.get( 1.1f ) );
CHECK_THROWS( stab_value.get( -1.1f ) );
CHECK_THROWS( stab_value.get( 0.0f ) );
}
| 291 |
29,258 | package com.taobao.arthas.core.distribution.impl;
import com.alibaba.arthas.deps.org.slf4j.Logger;
import com.alibaba.arthas.deps.org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.taobao.arthas.core.command.model.ResultModel;
import com.taobao.arthas.core.distribution.DistributorOptions;
import com.taobao.arthas.core.distribution.ResultConsumer;
import com.taobao.arthas.core.distribution.ResultConsumerHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author gongdewei 2020/3/27
*/
public class ResultConsumerImpl implements ResultConsumer {
private static final Logger logger = LoggerFactory.getLogger(ResultConsumerImpl.class);
private BlockingQueue<ResultModel> resultQueue;
private volatile long lastAccessTime;
private volatile boolean polling;
private ReentrantLock lock = new ReentrantLock();
private int resultBatchSizeLimit = 20;
private int resultQueueSize = DistributorOptions.resultQueueSize;
private long pollTimeLimit = 2 * 1000;
private String consumerId;
private boolean closed;
private long sendingItemCount;
public ResultConsumerImpl() {
lastAccessTime = System.currentTimeMillis();
resultQueue = new ArrayBlockingQueue<ResultModel>(resultQueueSize);
}
@Override
public boolean appendResult(ResultModel result) {
//可能某些Consumer已经断开,不会再读取,这里不能堵塞!
boolean discard = false;
while (!resultQueue.offer(result)) {
ResultModel discardResult = resultQueue.poll();
discard = true;
}
return !discard;
}
@Override
public List<ResultModel> pollResults() {
try {
lastAccessTime = System.currentTimeMillis();
long accessTime = lastAccessTime;
if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
polling = true;
sendingItemCount = 0;
long firstResultTime = 0;
// sending delay: time elapsed after firstResultTime
long sendingDelay = 0;
// waiting time: time elapsed after access
long waitingTime = 0;
List<ResultModel> sendingResults = new ArrayList<ResultModel>(resultBatchSizeLimit);
while (!closed
&&sendingResults.size() < resultBatchSizeLimit
&& sendingDelay < 100
&& waitingTime < pollTimeLimit) {
ResultModel aResult = resultQueue.poll(100, TimeUnit.MILLISECONDS);
if (aResult != null) {
sendingResults.add(aResult);
//是否为第一次获取到数据
if (firstResultTime == 0) {
firstResultTime = System.currentTimeMillis();
}
//判断是否需要立即发送出去
if (shouldFlush(sendingResults, aResult)) {
break;
}
} else {
if (firstResultTime > 0) {
//获取到部分数据后,队列已经取完,计算发送延时时间
sendingDelay = System.currentTimeMillis() - firstResultTime;
}
//计算总共等待时间,长轮询最大等待时间
waitingTime = System.currentTimeMillis() - accessTime;
}
}
//resultQueue.drainTo(sendingResults, resultSizeLimit-sendingResults.size());
if(logger.isDebugEnabled()) {
logger.debug("pollResults: {}, results: {}", sendingResults.size(), JSON.toJSONString(sendingResults));
}
return sendingResults;
}
} catch (InterruptedException e) {
//e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread()) {
lastAccessTime = System.currentTimeMillis();
polling = false;
lock.unlock();
}
}
return Collections.emptyList();
}
/**
* 估算对象数量及大小,判断是否需要立即发送出去
* @param sendingResults
* @param last
* @return
*/
private boolean shouldFlush(List<ResultModel> sendingResults, ResultModel last) {
//TODO 引入一个估算模型,每个model自统计对象数量
sendingItemCount += ResultConsumerHelper.getItemCount(last);
return sendingItemCount >= 100;
}
@Override
public boolean isHealthy() {
return isPolling()
|| resultQueue.size() < resultQueueSize
|| System.currentTimeMillis() - lastAccessTime < 1000;
}
@Override
public long getLastAccessTime() {
return lastAccessTime;
}
@Override
public void close(){
this.closed = true;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public boolean isPolling() {
return polling;
}
public int getResultBatchSizeLimit() {
return resultBatchSizeLimit;
}
public void setResultBatchSizeLimit(int resultBatchSizeLimit) {
this.resultBatchSizeLimit = resultBatchSizeLimit;
}
@Override
public String getConsumerId() {
return consumerId;
}
@Override
public void setConsumerId(String consumerId) {
this.consumerId = consumerId;
}
}
| 2,762 |
349 | /*
* Copyright 2015 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.appeaser.sublimenavigationviewlibrary;
import android.content.Context;
import android.content.res.Resources;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.List;
/**
* Menu implementation.
*
* Created by Vikram.
*/
public class SublimeMenu implements Parcelable {
private static final String TAG = SublimeMenu.class.getSimpleName();
public static final int NO_GROUP_ID = -1;
public static final int NO_ITEM_ID = -1;
protected static final SublimeBaseMenuItem HEADER_STUB = new SublimeBaseMenuItem(null,
NO_GROUP_ID, NO_ITEM_ID, "", "", SublimeBaseMenuItem.ItemType.HEADER, false, false) {
@Override
public boolean invoke() {
return false;
}
};
private int mMenuResourceID = -1;
private Context mContext;
/**
* Callback that will receive the various menu-related events generated by this class. Use
* getCallback to get a reference to the callback.
*/
private Callback mCallback;
/**
* Contains all of the items for this menu
*/
private ArrayList<SublimeBaseMenuItem> mItems = new ArrayList<>();
/**
* Contains all of the groups for this menu
*/
private ArrayList<SublimeGroup> mGroups = new ArrayList<>();
/**
* Contains only the items that are currently visible. This will be created/refreshed from
* {@link #getVisibleItems()}
*/
private ArrayList<SublimeBaseMenuItem> mVisibleItems = new ArrayList<>();
// We only require _one_ presenter
private SublimeMenuPresenter mPresenter;
private boolean mBlockUpdates;
private ArrayList<SublimeBaseMenuItem> mAdapterData = new ArrayList<>();
/**
* Called by menu to notify of close and selection changes.
*/
public interface Callback {
/**
* Called when a menu item is selected.
*
* @param menu The menu that is the parent of the item
* @param item The menu item that is selected
* @param event EventType associated with this selection
* @return whether the menu item selection was handled
*/
boolean onMenuItemSelected(SublimeMenu menu, SublimeBaseMenuItem item,
OnNavigationMenuEventListener.Event event);
}
public SublimeMenu(int menuResourceID) {
mMenuResourceID = menuResourceID;
}
public int getMenuResourceID() {
return mMenuResourceID;
}
/**
* Set a presenter to this menu.
*
* @param presenter The presenter to set
*/
public void setMenuPresenter(Context context, @Nullable SublimeMenuPresenter presenter) {
mContext = context;
mPresenter = presenter;
if (presenter != null) {
if (Config.DEBUG) {
Log.d(TAG, "Presenter set on menu");
}
presenter.initForMenu(mContext, this);
presenter.invalidateEntireMenu();
}
}
public void setCallback(Callback cb) {
mCallback = cb;
}
public SublimeGroup addGroup(boolean isCollapsible,
boolean collapsed, boolean enabled,
boolean visible,
SublimeGroup.CheckableBehavior checkableBehavior) {
return addGroup(generateUniqueGroupID(), isCollapsible, collapsed,
enabled, visible, checkableBehavior);
}
protected SublimeGroup addGroup(int groupId, boolean isCollapsible,
boolean collapsed, boolean enabled,
boolean visible,
SublimeGroup.CheckableBehavior checkableBehavior) {
SublimeGroup group = new SublimeGroup(this,
groupId,
isCollapsible, collapsed, enabled,
visible, checkableBehavior);
mGroups.add(group);
return group;
}
private int generateUniqueGroupID() {
int groupId = 1;
if (mGroups.size() > 0) {
while (getGroup(groupId) != null) {
groupId++;
}
}
return groupId;
}
private int generateUniqueItemID() {
int menuItemId = 1;
if (mItems.size() > 0) {
while (getMenuItem(menuItemId) != null) {
menuItemId++;
}
}
return menuItemId;
}
/**
* Adds an item to the menu. The other add methods funnel to this.
*/
private SublimeBaseMenuItem addInternal(int group, int id, CharSequence title,
CharSequence hint,
SublimeBaseMenuItem.ItemType itemType,
boolean valueProvidedAsync,
CharSequence badgeText,
boolean showsIconSpace, boolean addedByUser) {
SublimeBaseMenuItem item;
boolean isGroupHeader = false;
switch (itemType) {
case SEPARATOR:
item = new SublimeSeparatorMenuItem(this, group, id);
break;
case BADGE:
item = new SublimeTextWithBadgeMenuItem(this, group, id, title,
hint, valueProvidedAsync, badgeText, showsIconSpace);
break;
case SWITCH:
item = new SublimeSwitchMenuItem(this, group, id, title,
hint, valueProvidedAsync, showsIconSpace);
break;
case CHECKBOX:
item = new SublimeCheckboxMenuItem(this, group, id, title,
hint, valueProvidedAsync,
showsIconSpace);
break;
case GROUP_HEADER:
isGroupHeader = true;
item = new SublimeGroupHeaderMenuItem(this, group, id, title,
hint, valueProvidedAsync, showsIconSpace);
break;
default:
// TEXT
item = new SublimeTextMenuItem(this, group, id, title,
hint, valueProvidedAsync, showsIconSpace);
break;
}
// if itemType is 'GroupHeader', 'group' != NO_GROUP_ID
// since we check for this in 'addGroupHeaderItem(...)'
checkExistenceOfGroup(group);
if (isGroupHeader) {
checkIfGroupHeaderAlreadyExistsForGroup(group);
int index = findGroupIndex(group);
if (index >= 0) {
mItems.add(index, item);
} else {
mItems.add(item);
}
} else if (addedByUser) {
if (group != NO_GROUP_ID) {
int lastGroupIndex = findLastGroupIndex(group);
mItems.add(lastGroupIndex == mItems.size() ?
lastGroupIndex : lastGroupIndex + 1, item);
} else {
mItems.add(item);
}
} else {
mItems.add(item);
}
onItemsChanged();
return item;
}
public enum Positioned {BEFORE, AFTER}
/**
* Adds an item to the menu and positions it using the given `pivot`.
*
* @param pivotID Item ID that will be used for positioning the added item
* @param positioned before or after
* @param newItem added item
* @return item that was just added
*/
private SublimeBaseMenuItem addInternal(int pivotID, Positioned positioned,
SublimeBaseMenuItem newItem) {
int newItemGroupId = newItem.getGroupId();
// if itemType is 'GroupHeader', 'group' != NO_GROUP_ID
// since we check for this in 'addGroupHeaderItem(...)'
checkExistenceOfGroup(newItemGroupId);
int pivotIndex = findItemIndex(pivotID);
SublimeBaseMenuItem pivot = mItems.get(pivotIndex);
// GROUP_HEADER is a special item. In addition to the positional
// requirements given above, it should be placed at the beginning
// of the Group.
if (newItem.getItemType() == SublimeBaseMenuItem.ItemType.GROUP_HEADER) {
checkIfGroupHeaderAlreadyExistsForGroup(newItemGroupId);
int index = findGroupIndex(newItemGroupId);
if (index >= 0) { // we found a valid index for the group
mItems.add(index, newItem);
} else { // group exists, but does not contain any items at the moment
// try to use the `pivot` to place the first group item
if (positioned == Positioned.BEFORE) {
if (pivot.getGroupId() == NO_GROUP_ID
|| pivot.getItemType()
== SublimeBaseMenuItem.ItemType.GROUP_HEADER) {
// `pivot` is not part of a Group
// - or -
// `pivot` is a GROUP_HEADER
mItems.add(pivotIndex, newItem);
} else {
// we could not position the item as per the
// requirements - add the item at the very end
mItems.add(newItem);
}
} else if (positioned == Positioned.AFTER) {
if (pivot.getGroupId() == NO_GROUP_ID
|| pivotIndex
== findLastGroupIndex(newItemGroupId)) {
// `pivot` is not part of a Group
// - or -
// `pivot` is the very last item in a Group
mItems.add(pivotIndex + 1, newItem);
} else {
// we could not position the item as per the
// requirements - add the item at the very end
mItems.add(newItem);
}
}
}
} else { // item is not a GROUP_HEADER
if (newItemGroupId != NO_GROUP_ID) { // item is part of a Group
int lastGroupIndex = findLastGroupIndex(newItemGroupId);
if (lastGroupIndex == mItems.size()) { // no Group items found
// try to use the `pivot` to position the new item
if (positioned == Positioned.BEFORE) {
if (pivot.getGroupId() == NO_GROUP_ID
|| pivotIndex == findGroupIndex(pivot.getGroupId())) {
// `pivot` is not part of a Group
// - or -
// `pivot` is the very first item in a Group
mItems.add(pivotIndex, newItem);
} else {
// we could not position the item as per the
// requirements - add the item at the very end
//mItems.add(lastGroupIndex + 1, item);
mItems.add(newItem);
}
} else if (positioned == Positioned.AFTER) {
if (pivot.getGroupId() == NO_GROUP_ID
|| pivotIndex == findLastGroupIndex(pivot.getGroupId())) {
// `pivot` is not part of a Group
// - or -
// `pivot` is the very last item in a Group
mItems.add(pivotIndex + 1, newItem);
} else {
// we could not position the item as per the
// requirements - add the item at the very end
//mItems.add(lastGroupIndex + 1, item);
mItems.add(newItem);
}
}
} else {
if (newItemGroupId == pivot.getGroupId()) {
if (positioned == Positioned.BEFORE) {
if (pivot.getItemType()
!= SublimeBaseMenuItem.ItemType.GROUP_HEADER) {
// `pivot` is not GroupHeader - add before
mItems.add(pivotIndex, newItem);
} else {
// cannot add an item before the GroupHeader.
// add item at the end of the Group
mItems.add(lastGroupIndex + 1, newItem);
}
} else if (positioned == Positioned.AFTER) {
// all positions after the `pivot` are valid
mItems.add(pivotIndex + 1, newItem);
}
} else {
// `newItem` & `pivot` belong to different Groups.
// The only valid position for `newItem` in this case
// is at the end of `newItem's` Group.
mItems.add(lastGroupIndex + 1, newItem);
}
}
} else {
// `newItem` is independent - no Group membership
if (positioned == Positioned.BEFORE) {
if (pivot.getGroupId() == NO_GROUP_ID
|| findGroupIndex(pivot.getGroupId()) == pivotIndex) {
// `pivot` is not part of a Group
// - or -
// `pivot` is the very first item in a Group
mItems.add(pivotIndex, newItem);
} else {
// we could not position the item as per the
// requirements - add the item at the very end
mItems.add(newItem);
}
} else if (positioned == Positioned.AFTER) {
if (pivot.getGroupId() == NO_GROUP_ID
|| pivotIndex == findLastGroupIndex(pivot.getGroupId())) {
// `pivot` is not part of a Group
// - or -
// `pivot` is the very last item in a Group
mItems.add(pivotIndex + 1, newItem);
} else {
// we could not position the item as per the
// requirements - add the item at the very end
mItems.add(newItem);
}
}
}
}
onItemsChanged();
return newItem;
}
/**
* Creates an item. The other 'create' methods funnel to this.
*/
private SublimeBaseMenuItem createInternal(int group, int id, CharSequence title,
CharSequence hint,
SublimeBaseMenuItem.ItemType itemType,
boolean valueProvidedAsync,
CharSequence badgeText,
boolean showsIconSpace) {
SublimeBaseMenuItem item;
switch (itemType) {
case SEPARATOR:
item = new SublimeSeparatorMenuItem(this, group, id);
break;
case BADGE:
item = new SublimeTextWithBadgeMenuItem(this, group, id, title,
hint, valueProvidedAsync, badgeText, showsIconSpace);
break;
case SWITCH:
item = new SublimeSwitchMenuItem(this, group, id, title,
hint, valueProvidedAsync, showsIconSpace);
break;
case CHECKBOX:
item = new SublimeCheckboxMenuItem(this, group, id, title,
hint, valueProvidedAsync,
showsIconSpace);
break;
case GROUP_HEADER:
item = new SublimeGroupHeaderMenuItem(this, group, id, title,
hint, valueProvidedAsync, showsIconSpace);
break;
default:
// TEXT
item = new SublimeTextMenuItem(this, group, id, title,
hint, valueProvidedAsync, showsIconSpace);
break;
}
return item;
}
/**
* This check is performed before adding an item to this menu
* that has positional instructions: addAfter(...), addBefore(...) etc..
* Throws {@link RuntimeException} if the item
* used for positioning does not exist.
*
* @param itemId ID of the item to check for
*/
private void checkExistenceOfItem(int itemId) {
if (itemId == NO_ITEM_ID || getMenuItem(itemId) == null) {
throw new RuntimeException("'itemId' passed was invalid: '" + itemId + "'.");
}
}
/**
* This check is performed before adding an item to this menu.
* If the item indicates its membership to a {@link SublimeGroup}
* (by supplying a 'groupID'), this check confirms that such a
* group does exist. Throws {@link RuntimeException} if a group
* with ID == 'groupId' is not found.
*
* @param groupId ID of the group to check for
*/
private void checkExistenceOfGroup(int groupId) {
if (groupId != NO_GROUP_ID && getGroup(groupId) == null) {
throw new RuntimeException("'groupId' passed was invalid: '" + groupId + "'. Items can only " +
"be added to existing Group(s)");
}
}
/**
* This check is performed before adding an item of type
* {@link SublimeBaseMenuItem.ItemType#GROUP_HEADER}.
* A {@link RuntimeException} is thrown if the {@link SublimeGroup}
* already contains an item of this type. A {@link SublimeGroup}
* can only have one header.
*
* @param groupId ID of the group on which to perform this check.
*/
private void checkIfGroupHeaderAlreadyExistsForGroup(int groupId) {
for (SublimeBaseMenuItem item : mItems) {
if (item.getGroupId() == groupId
&& item.getItemType() == SublimeBaseMenuItem.ItemType.GROUP_HEADER) {
throw new RuntimeException("Attempt to add 'GroupHeader' to " +
"a 'Group' that already contains one.");
}
}
}
public SublimeBaseMenuItem createTextItem(int groupId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
return createInternal(groupId, generateUniqueItemID()/* itemId */,
title, hint, SublimeBaseMenuItem.ItemType.TEXT,
false /*valueProvidedAsync*/, null, showsIconSpace);
}
public SublimeBaseMenuItem addTextItem(int groupId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
return addInternal(groupId, generateUniqueItemID()/* itemId */, title, hint, SublimeBaseMenuItem.ItemType.TEXT,
false /*valueProvidedAsync*/, null, showsIconSpace, true);
}
protected SublimeBaseMenuItem addTextItem(int groupId, int itemId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
return addInternal(groupId, itemId, title, hint, SublimeBaseMenuItem.ItemType.TEXT,
false /*valueProvidedAsync*/, null, showsIconSpace, false);
}
public SublimeBaseMenuItem createTextWithBadgeItem(int groupId,
CharSequence title, CharSequence hint,
CharSequence badgeText,
boolean showsIconSpace) {
return createInternal(groupId, generateUniqueItemID()/* itemId */, title,
hint, SublimeBaseMenuItem.ItemType.BADGE,
false /*valueProvidedAsync*/, badgeText, showsIconSpace);
}
public SublimeBaseMenuItem addTextWithBadgeItem(int groupId,
CharSequence title, CharSequence hint,
CharSequence badgeText,
boolean showsIconSpace) {
return addInternal(groupId, generateUniqueItemID()/* itemId */, title,
hint, SublimeBaseMenuItem.ItemType.BADGE,
false /*valueProvidedAsync*/, badgeText, showsIconSpace, true);
}
protected SublimeBaseMenuItem addTextWithBadgeItem(int groupId, int itemId,
CharSequence title, CharSequence hint,
CharSequence badgeText,
boolean showsIconSpace) {
return addInternal(groupId, itemId, title, hint, SublimeBaseMenuItem.ItemType.BADGE,
false /*valueProvidedAsync*/, badgeText, showsIconSpace, false);
}
public SublimeBaseMenuItem createCheckboxItem(int groupId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
return createInternal(groupId, generateUniqueItemID()/* itemId */, title, hint, SublimeBaseMenuItem.ItemType.CHECKBOX,
false /*valueProvidedAsync*/, null, showsIconSpace);
}
public SublimeBaseMenuItem addCheckboxItem(int groupId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
return addInternal(groupId, generateUniqueItemID()/* itemId */, title, hint, SublimeBaseMenuItem.ItemType.CHECKBOX,
false /*valueProvidedAsync*/, null, showsIconSpace, true);
}
protected SublimeBaseMenuItem addCheckboxItem(int groupId, int itemId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
return addInternal(groupId, itemId, title,
hint, SublimeBaseMenuItem.ItemType.CHECKBOX,
false /*valueProvidedAsync*/, null, showsIconSpace, false);
}
public SublimeBaseMenuItem createSwitchItem(int groupId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
return createInternal(groupId, generateUniqueItemID()/* itemId */, title,
hint, SublimeBaseMenuItem.ItemType.SWITCH,
false /*valueProvidedAsync*/, null, showsIconSpace);
}
public SublimeBaseMenuItem addSwitchItem(int groupId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
return addInternal(groupId, generateUniqueItemID()/* itemId */, title,
hint, SublimeBaseMenuItem.ItemType.SWITCH,
false /*valueProvidedAsync*/, null, showsIconSpace, true);
}
protected SublimeBaseMenuItem addSwitchItem(int groupId, int itemId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
return addInternal(groupId, itemId, title,
hint, SublimeBaseMenuItem.ItemType.SWITCH,
false /*valueProvidedAsync*/, null, showsIconSpace, false);
}
public SublimeBaseMenuItem createGroupHeaderItem(int groupId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
if (groupId == NO_GROUP_ID) {
throw new RuntimeException("Attempt to create 'GroupHeader' without " +
"providing a valid groupID");
}
return createInternal(groupId, generateUniqueItemID()/* itemId */, title, hint,
SublimeBaseMenuItem.ItemType.GROUP_HEADER,
false /*valueProvidedAsync*/, null, showsIconSpace);
}
public SublimeBaseMenuItem addGroupHeaderItem(int groupId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
if (groupId == NO_GROUP_ID) {
throw new RuntimeException("Attempt to add 'GroupHeader' without " +
"providing a valid groupID");
}
return addInternal(groupId, generateUniqueItemID()/* itemId */, title, hint,
SublimeBaseMenuItem.ItemType.GROUP_HEADER,
false /*valueProvidedAsync*/, null, showsIconSpace, true);
}
protected SublimeBaseMenuItem addGroupHeaderItem(int groupId, int itemId,
CharSequence title, CharSequence hint,
boolean showsIconSpace) {
return addInternal(groupId, itemId, title, hint,
SublimeBaseMenuItem.ItemType.GROUP_HEADER,
false /*valueProvidedAsync*/, null, showsIconSpace, false);
}
public SublimeBaseMenuItem createSeparatorItem(int groupId) {
return createInternal(groupId, generateUniqueItemID()/* itemId */, null, null,
SublimeBaseMenuItem.ItemType.SEPARATOR,
false /*valueProvidedAsync*/, null, false);
}
public SublimeBaseMenuItem addSeparatorItem(int groupId) {
return addInternal(groupId, generateUniqueItemID()/* itemId */, null, null,
SublimeBaseMenuItem.ItemType.SEPARATOR,
false /*valueProvidedAsync*/, null, false, true);
}
protected SublimeBaseMenuItem addSeparatorItem(int groupId, int itemId) {
return addInternal(groupId, itemId, null, null,
SublimeBaseMenuItem.ItemType.SEPARATOR,
false /*valueProvidedAsync*/, null, false, false);
}
public void addBefore(int pivotId, SublimeBaseMenuItem item) {
checkExistenceOfItem(pivotId);
addInternal(pivotId, Positioned.BEFORE, item);
}
public void addAfter(int pivotId, SublimeBaseMenuItem item) {
checkExistenceOfItem(pivotId);
addInternal(pivotId, Positioned.AFTER, item);
}
public void removeItem(int id) {
removeItemAtInt(findItemIndex(id), true);
}
public void removeGroup(int groupId) {
final int i = findGroupIndex(groupId);
if (i >= 0) {
final int maxRemovable = mItems.size() - i;
int numRemoved = 0;
while ((numRemoved++ < maxRemovable) && (mItems.get(i).getGroupId() == groupId)) {
// Don't force update for each one, this method will do it at the end
removeItemAtInt(i, false);
}
// Remove Group
int groups = mGroups.size();
for (int j = 0; j < groups; j++) {
SublimeGroup curGroup = mGroups.get(j);
if (curGroup.getGroupId() == groupId) {
mGroups.remove(j);
break;
}
}
// Notify menu views
onItemsChanged();
}
}
/**
* Remove the item at the given index and optionally forces menu views to
* update.
*
* @param index The index of the item to be removed. If this index is
* invalid an exception is thrown.
* @param updateChildrenOnMenuViews Whether to force update on menu views.
* Please make sure you eventually call this after your batch of
* removals.
*/
private void removeItemAtInt(int index, boolean updateChildrenOnMenuViews) {
if ((index < 0) || (index >= mItems.size())) return;
mItems.remove(index);
if (updateChildrenOnMenuViews) {
onItemsChanged();
}
}
public void clear() {
mItems.clear();
mGroups.clear();
onItemsChanged();
}
/**
* Performs required changes to other group items
* before the passed item's checked state is set to true.
*
* @param item Item on which setChecked(true) has been called
*/
void setItemChecked(SublimeBaseMenuItem item) {
SublimeGroup group = getGroup(item.getGroupId());
if (group == null) return;
if (group.getCheckableBehavior() == SublimeGroup.CheckableBehavior.SINGLE) {
final int N = mItems.size();
for (int i = 0; i < N; i++) {
SublimeBaseMenuItem curItem = mItems.get(i);
if (curItem.getGroupId() == group.getGroupId()) {
if (!curItem.isCheckable()) {
continue;
}
// Check the item meant to be checked,
// un-check the others (that are in the group)
if (curItem != item) {
curItem.setCheckedInt(false);
}
}
}
}
}
protected List<SublimeBaseMenuItem> getItemsForGroup(int groupId) {
ArrayList<SublimeBaseMenuItem> groupItems = new ArrayList<>();
final int N = mItems.size();
for (int i = 0; i < N; i++) {
SublimeBaseMenuItem item = mItems.get(i);
if (item.getGroupId() == groupId) {
groupItems.add(item);
}
}
return groupItems;
}
protected int getVisibleItemCountForGroup(List<SublimeBaseMenuItem> groupItems) {
int visibleItems = 0;
for (SublimeBaseMenuItem menuItem : groupItems) {
if (menuItem.isVisible()) {
visibleItems++;
}
}
return visibleItems;
}
public boolean hasVisibleItems() {
final int size = size();
for (int i = 0; i < size; i++) {
SublimeBaseMenuItem item = mItems.get(i);
if (item.isVisible()) {
return true;
}
}
return false;
}
public boolean groupHasVisibleItems(int groupId) {
final int size = size();
for (int i = 0; i < size; i++) {
SublimeBaseMenuItem item = mItems.get(i);
if (item.getGroupId() == groupId && item.isVisible()) {
return true;
}
}
return false;
}
public SublimeBaseMenuItem getMenuItem(int itemId) {
final int size = size();
for (int i = 0; i < size; i++) {
SublimeBaseMenuItem item = mItems.get(i);
if (item.getItemId() == itemId) {
return item;
}
}
return null;
}
private int findItemIndex(int itemId) {
final int size = size();
for (int i = 0; i < size; i++) {
SublimeBaseMenuItem item = mItems.get(i);
if (item.getItemId() == itemId) {
return i;
}
}
return -1;
}
private int findGroupIndex(int groupId) {
final int size = size();
for (int i = 0; i < size; i++) {
final SublimeBaseMenuItem item = mItems.get(i);
if (item.getGroupId() == groupId) {
return i;
}
}
return -1;
}
/**
* Returns the last index at which a member of the indicated group
* exists. If the group currently does not have any members,
* size of the MenuItem-list is returned.
*
* @param groupId ID of the group whose last member's index needs to be
* found
* @return index of the last member of the indicated group, or size of
* the MenuItem-list if no members are found.
*/
private int findLastGroupIndex(int groupId) {
int i = 0, size = mItems.size();
boolean traversingGroup = false;
while (true) {
if (i < size) {
final SublimeBaseMenuItem item = mItems.get(i);
if (item.getGroupId() == groupId) {
traversingGroup = true;
} else if (traversingGroup) {
// Take one step back
return i - 1;
}
i++;
} else {
return traversingGroup ? size - 1 : size;
}
}
}
public int size() {
return mItems.size();
}
public Context getContext() {
return mContext;
}
boolean dispatchMenuItemSelected(SublimeBaseMenuItem item,
OnNavigationMenuEventListener.Event event) {
return mCallback != null && mCallback.onMenuItemSelected(this, item, event);
}
public boolean performItemAction(SublimeBaseMenuItem item) {
return !(item == null || !item.isEnabled()) && item.invoke();
}
public ArrayList<SublimeBaseMenuItem> getVisibleItems() {
// Refresh the visible items
mVisibleItems.clear();
final int itemsSize = mItems.size();
SublimeBaseMenuItem item;
for (int i = 0; i < itemsSize; i++) {
item = mItems.get(i);
if (item.isVisible()) mVisibleItems.add(item);
}
return mVisibleItems;
}
//----------------------------------------------------------------//
//---------------------------Item changes-------------------------//
//----------------------------------------------------------------//
protected SublimeMenu blockUpdates() {
mBlockUpdates = true;
return this;
}
protected SublimeMenu allowUpdates() {
mBlockUpdates = false;
return this;
}
public void finalizeUpdates() {
if (mBlockUpdates) {
Log.e(TAG, "Cannot finalize updates until 'allowUpdates()' is called.");
return;
}
if (mPresenter == null) {
Log.e(TAG, "Cannot finalize updates until a presenter is set.");
return;
}
mPresenter.invalidateEntireMenu();
}
private void attemptUpdate() {
if (!mBlockUpdates) {
finalizeUpdates();
}
}
//----------------------------------------------------------------//
//---------------------------Adapter data-------------------------//
//----------------------------------------------------------------//
public static class Change {
protected enum ChangeType {
ITEM_INSERTED, ITEM_REMOVED,
ITEM_CHANGED, ITEM_MOVED,
RANGE_INSERTED, RANGE_REMOVED,
RANGE_CHANGED, INVALIDATE_ENTIRE_MENU
}
// Used with ChangeType: ITEM_INSERTED, ITEM_REMOVED, ITEM_CHANGED,
// RANGE_INSERTED, RANGE_REMOVED, RANGE_CHANGED
private int mAffectedPosition;
// Used with ChangeType: ITEM_MOVED
private int mMovedFromPosition;
private int mMovedToPosition;
// Used with ChangeType: RANGE_INSERTED, RANGE_REMOVED, RANGE_CHANGED
private int mNumberOfAffectedItems;
private ChangeType mChangeType;
public Change(ChangeType changeType, int affectedPosition, int movedFromPosition,
int movedToPosition, int numberOfAffectedItems) {
mChangeType = changeType;
mAffectedPosition = affectedPosition;
mMovedFromPosition = movedFromPosition;
mMovedToPosition = movedToPosition;
mNumberOfAffectedItems = numberOfAffectedItems;
}
public ChangeType getChangeType() {
return mChangeType;
}
public int getAffectedPosition() {
return mAffectedPosition;
}
public int getNumberOfAffectedItems() {
return mNumberOfAffectedItems;
}
public int getMovedFromPosition() {
return mMovedFromPosition;
}
public int getMovedToPosition() {
return mMovedToPosition;
}
}
protected ArrayList<SublimeBaseMenuItem> getAdapterData() {
// Possibly redundant check unless this method is
// called from outside of SublimeMenuPresenterNew.
// We shouldn't return 'null' here.
if (mPresenter == null) return mAdapterData;
prepareMenuItems();
return mAdapterData;
}
/**
* Creates/refreshes the data that is presented by SublimeMenuPresenter.
*/
private void prepareMenuItems() {
if (Config.DEBUG) {
Log.i(TAG, "prepareMenuItems()");
}
mAdapterData.clear();
boolean hasHeader = mPresenter != null && mPresenter.hasHeader();
if (hasHeader) {
mAdapterData.add(SublimeMenu.HEADER_STUB);
}
int i = 0;
SublimeGroup currentGroup = null;
for (int totalSize = getVisibleItems().size(); i < totalSize; ++i) {
SublimeBaseMenuItem item = getVisibleItems().get(i);
if (currentGroup == null || currentGroup.getGroupId() != item.getGroupId()) {
currentGroup = getGroup(item.getGroupId());
}
if (currentGroup != null
&& (!currentGroup.isVisible()
|| (currentGroup.isCollapsed()
&& item.getItemType() != SublimeBaseMenuItem.ItemType.GROUP_HEADER))) {
continue;
}
mAdapterData.add(item);
}
}
//----------------------------------------------------------------//
//-----------------------Adapter data changes---------------------//
//----------------------------------------------------------------//
/**
* Called when an item is changed. Type of change is evaluated
* by comparing the 'old' position & the 'new' position of the item.
*
* @param itemId id of item that's been changed
*/
public void onItemChanged(int itemId) {
if (mBlockUpdates || mPresenter == null) return;
int oldPos = getAdapterPosForId(itemId);
prepareMenuItems();
int newPos = getAdapterPosForId(itemId);
if (oldPos == -1 && newPos == -1) {
// No change to report
return;
}
if (oldPos == -1) {
mPresenter.reportChange(
new Change(Change.ChangeType.ITEM_INSERTED, newPos, -1, -1, -1),
mAdapterData);
} else if (newPos == -1) {
mPresenter.reportChange(
new Change(Change.ChangeType.ITEM_REMOVED, oldPos, -1, -1, -1),
mAdapterData);
} else if (oldPos == newPos) {
mPresenter.reportChange(
new Change(Change.ChangeType.ITEM_CHANGED, newPos, -1, -1, -1),
mAdapterData);
} else {
mPresenter.reportChange(
new Change(Change.ChangeType.ITEM_MOVED, -1, oldPos, newPos, -1),
mAdapterData);
}
}
/**
* Called by {@link SublimeBaseMenuItem} after a batch update.
*/
void onItemsChanged() {
if (mBlockUpdates || mPresenter == null) return;
mPresenter.invalidateEntireMenu();
}
private int getAdapterPosForId(int itemId) {
for (int i = 0; i < mAdapterData.size(); i++) {
if (mAdapterData.get(i).getItemId() == itemId) {
return i;
}
}
return -1;
}
//----------------------------------------------------------------//
//--------------------------SublimeGroup--------------------------//
//----------------------------------------------------------------//
/**
* Finds and returns the SublimeGroup with id == groupId.
*
* @param groupId id of the group to find
* @return SublimeGroup with id == groupId if found, 'null' otherwise
*/
public SublimeGroup getGroup(int groupId) {
for (int i = 0; i < mGroups.size(); i++) {
if (mGroups.get(i).getGroupId() == groupId) {
return mGroups.get(i);
}
}
return null;
}
/**
* Called when a Group is collapsed/expanded.
*
* @param groupId id of group that's been collapsed/expanded
* @param collapsed 'true' if group has been collapsed, 'false' if expanded
*/
protected void onGroupExpandedOrCollapsed(int groupId, boolean collapsed) {
if (mBlockUpdates || mPresenter == null) return;
List<SublimeBaseMenuItem> groupItems = getItemsForGroup(groupId);
if (groupItems.size() > 0) {
int headerPos = getAdapterPosForId(groupItems.get(0).getItemId());
int visibleItemCountForGroupBeforeUpdate = getVisibleItemCountForGroup(groupItems);
prepareMenuItems();
int visibleItemCountForGroupAfterUpdate = getVisibleItemCountForGroup(groupItems);
if (headerPos != -1) {
// GroupHeader qualifies for ITEM_CHANGED.
mPresenter.reportChange(
new Change(Change.ChangeType.ITEM_CHANGED, headerPos, -1, -1, -1),
mAdapterData);
if (collapsed) {
// The '> 1' check determines if there are any
// GroupItems that are *visible*.
// '- 1' because the GroupHeader does not
// qualify for RANGE_REMOVED.
if (visibleItemCountForGroupBeforeUpdate > 1) {
mPresenter.reportChange(
new Change(Change.ChangeType.RANGE_REMOVED, headerPos + 1,
//-1, -1, groupItems.size() - 1),
-1, -1, visibleItemCountForGroupBeforeUpdate - 1),
mAdapterData);
}
} else {
if (visibleItemCountForGroupAfterUpdate > 1) {
mPresenter.reportChange(
new Change(Change.ChangeType.RANGE_INSERTED, headerPos + 1,
//-1, -1, groupItems.size() - 1),
-1, -1, visibleItemCountForGroupAfterUpdate - 1),
mAdapterData);
}
}
} else {
// be safe
mPresenter.invalidateEntireMenu();
}
}
}
/**
* Called when a Group's visibility is changed.
*
* @param groupId id of group that is now visible/invisible
* @param visible 'true' if the group is now visible, 'false' otherwise
*/
protected void onGroupVisibilityChanged(int groupId, boolean visible) {
if (mBlockUpdates || mPresenter == null) return;
List<SublimeBaseMenuItem> groupItems = getItemsForGroup(groupId);
if (groupItems.size() > 0) {
boolean invalidateEntireMenu = false;
if (visible) {
prepareMenuItems();
int headerPos = getAdapterPosForId(groupItems.get(0).getItemId());
if (headerPos != -1) {
mPresenter.reportChange(
new Change(Change.ChangeType.RANGE_INSERTED, headerPos,
//-1, -1, groupItems.size()),
-1, -1, getVisibleItemCountForGroup(groupItems)),
mAdapterData);
} else {
// be safe
invalidateEntireMenu = true;
}
} else {
// Get position & count before preparing updated menu
int headerPos = getAdapterPosForId(groupItems.get(0).getItemId());
int visibleItemCountForGroup = getVisibleItemCountForGroup(groupItems);
prepareMenuItems();
if (headerPos != -1) {
mPresenter.reportChange(
new Change(Change.ChangeType.RANGE_REMOVED, headerPos,
//-1, -1, groupItems.size()),
-1, -1, visibleItemCountForGroup),
mAdapterData);
} else {
invalidateEntireMenu = true;
}
}
if (invalidateEntireMenu) {
// be safe
mPresenter.invalidateEntireMenu();
}
}
}
/**
* Called in response to change in 'collapsible' status of a group
*
* @param sublimeGroup group for which 'collapsible' status has changed
*/
protected void onGroupCollapsibleStatusChanged(SublimeGroup sublimeGroup) {
if (mBlockUpdates || mPresenter == null) return;
List<SublimeBaseMenuItem> groupItems = getItemsForGroup(sublimeGroup.getGroupId());
if (groupItems.size() > 0) {
int headerPos = getAdapterPosForId(groupItems.get(0).getItemId());
if (headerPos != -1) {
if (sublimeGroup.isCollapsible() || !sublimeGroup.isCollapsed()) {
// Todo: check if call to 'prepareMenuItems()' is required
mPresenter.reportChange(
new Change(Change.ChangeType.ITEM_CHANGED, headerPos,
-1, -1, -1),
mAdapterData);
} else {
sublimeGroup.setStateCollapsed(false);
}
} else {
// be safe
mPresenter.invalidateEntireMenu();
}
}
}
/**
* Called when a Group is enabled/disabled.
*
* @param groupId 'id' of group that's been enabled/disabled
* @param enabled 'true' if the group has been 'enabled', false
* otherwise
*/
protected void onGroupEnabledOrDisabled(int groupId, boolean enabled) {
if (mBlockUpdates || mPresenter == null) return;
List<SublimeBaseMenuItem> groupItems = getItemsForGroup(groupId);
for (SublimeBaseMenuItem item : groupItems) {
item.blockUpdates().setEnabled(enabled).allowUpdates();
}
if (groupItems.size() > 0) {
int firstPos = getAdapterPosForId(groupItems.get(0).getItemId());
if (firstPos != -1) {
mPresenter.reportChange(
new Change(Change.ChangeType.RANGE_CHANGED, firstPos,
//-1, -1, groupItems.size()),
-1, -1, getVisibleItemCountForGroup(groupItems)),
mAdapterData);
} else {
// be safe
mPresenter.invalidateEntireMenu();
}
}
}
/**
* Sets the 'checkable' behavior for this group. For more information,
* see {@link SublimeGroup#setCheckableBehavior(SublimeGroup.CheckableBehavior)}.
*
* @param groupId 'id' for which to set the new 'checkableBehavior'
* @param newCheckableBehavior the 'checkableBehavior' to set
*/
protected void onGroupCheckableBehaviorChanged(
int groupId, SublimeGroup.CheckableBehavior newCheckableBehavior) {
List<SublimeBaseMenuItem> groupItems = getItemsForGroup(groupId);
// flag set when 'newCheckableBehavior' is 'SINGLE' & the first
// checked item is found.
boolean foundCheckedIfExclusive = false;
for (SublimeBaseMenuItem item : groupItems) {
switch (newCheckableBehavior) {
case NONE:
item.setCheckable(false);
break;
case ALL:
item.setCheckable(true);
break;
case SINGLE:
if (foundCheckedIfExclusive && item.isCheckable()) {
item.setChecked(false);
} else {
// Can an item be !checkable & checked?
if (item.isCheckable() && item.isChecked()) {
foundCheckedIfExclusive = true;
}
}
break;
}
}
}
//----------------------------------------------------------------//
//---------------------------Parcelable---------------------------//
//----------------------------------------------------------------//
public SublimeMenu(Parcel in) {
readParcel(in);
}
private void readParcel(Parcel in) {
mMenuResourceID = in.readInt();
in.readTypedList(mItems, SublimeBaseMenuItem.CREATOR);
for (SublimeBaseMenuItem item : mItems) {
item.setParentMenu(this);
}
in.readTypedList(mGroups, SublimeGroup.CREATOR);
for (SublimeGroup group : mGroups) {
group.setParentMenu(this);
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mMenuResourceID);
dest.writeTypedList(mItems);
dest.writeTypedList(mGroups);
}
public static final Creator CREATOR = new Creator() {
public SublimeMenu createFromParcel(Parcel in) {
return new SublimeMenu(in);
}
public SublimeMenu[] newArray(int size) {
return new SublimeMenu[size];
}
};
}
| 24,987 |
569 | <gh_stars>100-1000
/*
Copyright 1995-2015 Esri
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.
For additional information, contact:
Environmental Systems Research Institute, Inc.
Attn: Contracts Dept
380 New York Street
Redlands, California, USA 92373
email: <EMAIL>
*/
package com.esri.core.geometry;
import java.nio.ByteBuffer;
import com.esri.core.geometry.Operator.Type;
/**
*Import from ESRI shape format.
*/
public abstract class OperatorImportFromESRIShape extends Operator {
@Override
public Type getType() {
return Type.ImportFromESRIShape;
}
/**
* Performs the ImportFromESRIShape operation on a stream of shape buffers
* @param importFlags Use the {@link ShapeImportFlags} interface. The default is 0, which means geometry comes from a trusted source and is topologically simple.
* If the geometry comes from non-trusted source (that is it can be non-simple), pass ShapeImportNonTrusted.
* @param type The geometry type that you want to import. Use the {@link Geometry.Type} enum. It can be Geometry.Type.Unknown if the type of geometry has to be
* figured out from the shape buffer.
* @param shapeBuffers The cursor over shape buffers that hold the Geometries in ESRIShape format.
* @return Returns a GeometryCursor.
*/
abstract GeometryCursor execute(int importFlags, Geometry.Type type,
ByteBufferCursor shapeBuffers);
/**
* Performs the ImportFromESRIShape operation.
* @param importFlags Use the {@link ShapeImportFlags} interface. The default is 0, which means geometry comes from a trusted source and is topologically simple.
* If the geometry comes from non-trusted source (that is it can be non-simple), pass ShapeImportNonTrusted.
* @param type The geometry type that you want to import. Use the {@link Geometry.Type} enum. It can be Geometry.Type.Unknown if the type of geometry has to be
* figured out from the shape buffer.
* @param shapeBuffer The buffer holding the Geometry in ESRIShape format.
* @return Returns the imported Geometry.
*/
public abstract Geometry execute(int importFlags, Geometry.Type type,
ByteBuffer shapeBuffer);
public static OperatorImportFromESRIShape local() {
return (OperatorImportFromESRIShape) OperatorFactoryLocal.getInstance()
.getOperator(Type.ImportFromESRIShape);
}
}
| 790 |
483 | /**
Copyright 2013 Intel Corporation, 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.intel.cosbench.bench;
import com.intel.cosbench.utils.MapRegistry;
/**
* This class is a list of mark, it represents all marks at different time point.
*
* @author ywang19, qzheng7
* @see com.intel.cosbench.bench.Metrics
*
*/
public class Status extends MapRegistry<Mark> {
public void addMark(Mark mark) {
addItem(mark);
}
public Mark getMark(String name) {
return getItem(name);
}
public Mark[] getAllMarks() {
return getAllItems().toArray(new Mark[getSize()]);
}
}
| 354 |
892 | <gh_stars>100-1000
/*
* Copyright 2015 jmrozanec
* 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.cronutils.model.field.expression;
import com.cronutils.model.field.value.IntegerFieldValue;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class EveryTest {
@Test
public void testGetTime() {
final int every = 5;
assertEquals(every, (int) new Every(new IntegerFieldValue(every)).getPeriod().getValue());
}
@Test
public void testGetTimeNull() {
assertEquals(1, (int) new Every(null).getPeriod().getValue());
}
@Test //issue #180
public void testAsString() {
assertEquals("0/1", new Every(new On(new IntegerFieldValue(0)), new IntegerFieldValue(1)).asString());
}
} | 408 |
1,433 | <reponame>rzr/iotivity-1
/******************************************************************
*
* Copyright 2015 Samsung Electronics 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.
*
******************************************************************/
#ifndef SIMULATOR_RESOURCE_SERVER_IMPL_H_
#define SIMULATOR_RESOURCE_SERVER_IMPL_H_
#include "simulator_resource_server.h"
#include "resource_update_automation_mngr.h"
class SimulatorResourceServerImpl : public SimulatorResourceServer
{
public:
SimulatorResourceServerImpl();
void setURI(const std::string &uri);
void setResourceType(const std::string &resourceType);
void setInterfaceType(const std::string &interfaceType);
void setName(const std::string &name);
void setObservable(bool state);
bool isObservable() const;
int startUpdateAutomation(AutomationType type,
updateCompleteCallback callback);
int startUpdateAutomation(const std::string &attrName, AutomationType type,
updateCompleteCallback callback);
std::vector<int> getResourceAutomationIds();
std::vector<int> getAttributeAutomationIds();
void stopUpdateAutomation(const int id);
void setModelChangeCallback(ResourceModelChangedCB callback);
void setObserverCallback(ObserverCB callback);
std::vector<ObserverInfo> getObserversList();
void notify(uint8_t id);
void notifyAll();
void start();
void stop();
void notifyApp();
private:
OC::OCRepresentation getOCRepresentation();
bool modifyResourceModel(OC::OCRepresentation &ocRep);
OCEntityHandlerResult entityHandler(std::shared_ptr<OC::OCResourceRequest> request);
void resourceModified();
ResourceModelChangedCB m_callback;
ObserverCB m_observeCallback;
UpdateAutomationMngr m_updateAutomationMgr;
std::vector<ObserverInfo> m_observersList;
OCResourceProperty m_property;
OCResourceHandle m_resourceHandle;
};
typedef std::shared_ptr<SimulatorResourceServerImpl> SimulatorResourceServerImplSP;
#endif
| 938 |
453 | <gh_stars>100-1000
; @(#)fpsymbol.h 1.4 90/10/14 20:55:59, Copyright 1989, 1990 AMD
; start of fpsymbol.h file
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright 1989, 1990 Advanced Micro Devices, Inc.
;
; This software is the property of Advanced Micro Devices, Inc (AMD) which
; specifically grants the user the right to modify, use and distribute this
; software provided this notice is not removed or altered. All other rights
; are reserved by AMD.
;
; AMD MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH REGARD TO THIS
; SOFTWARE. IN NO EVENT SHALL AMD BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL
; DAMAGES IN CONNECTION WITH OR ARISING FROM THE FURNISHING, PERFORMANCE, OR
; USE OF THIS SOFTWARE.
;
; So that all may benefit from your experience, please report any problems
; or suggestions about this software to the 29K Technical Support Center at
; 800-29-29-AMD (800-292-9263) in the USA, or 0800-89-1131 in the UK, or
; 0031-11-1129 in Japan, toll free. The direct dial number is 512-462-4118.
;
; Advanced Micro Devices, Inc.
; 29K Support Products
; Mail Stop 573
; 5900 E. <NAME> Blvd.
; Austin, TX 78741
; 800-292-9263
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; ______________________________________________________________________
;|______________________________________________________________________|
;| |
;| SYMBOLS FOR DEFINING THE INSTRUCTION WORD |
;| |
;|______________________________________________________________________|
;|______________________________________________________________________|
;
;
; Revision Information:
;------------------------------------------------------------------------
; Date: March 31, 1989
; Author: <NAME> per <NAME> and <NAME>
;
; The symbols section describing transactions was modified to contain
; several new symbol values. The reason for the change was to force the
; CA bit to be set--and remain set--once code accesses the coprocessor.
;
; Future operating systems will use the Coprocessor Active (CA) bit in
; the Old Processor Status Register to determine whether or not to save
; coprocessor state, etc.. This means that the instruction control field
; Set Coprocessor Active (SA) bit should be used as follows:
;
; (1) any coprocessor STORE must have its SA bit set to 1,
; so as to set CA,
;
; and (2) any coprocessor LOAD must have its SA bit set to 0,
; so as to prevent clearing CA.
;------------------------------------------------------------------------
; Date: 89/01/30 12:32:13; author: jim; lines added/del: 5/4
; Corrected CP_IEEE_GRADUAL_UFLOW_MODE and CP_RMS_MASK.
; Added CP_EXCPS_POSITION, the ls bit of the CP_XXX_EXCP ensemble.
; fixed a few typos in comments.
;------------------------------------------------------------------------
; Date: 89/01/23 18:00:26; author: jim; lines added/del: 488/468
; <NAME>
; January 5, 1989
;
; 1) The _cp_prec_field in the "cp_build_inst", "cp_build_inst_h"
; and "cp_build_inst_l" macros was not being defined in the case
; of Am29K-supported floating-point instructions (e.g., FADD, FSUB,
; DADD, etc.).
;
; 2) The multiplexor select codes in the opcode table entries
; associated with the "cp_build_inst", "cp_build_inst_h" and
; "cp_build_inst_l" macros, pertaining to the CONVERT_F_TO_D
; and CONVERT_D_TO_F instructions were incorrect.
;------------------------------------------------------------------------
; Date: 88/12/20 14:28:26; author: jim; lines added/del: 1/1
; <NAME> corrected definition of CP_MOVE_P.
; Version required for Release 1.1 of the Intrinsics shipped 12/12/88.
;------------------------------------------------------------------------
; Date: 88/11/18 15:44:45; author: law;
; Initial revision
;
;
;========================================================================
;
; The following mnemonics are used to specify the 14 LSBs of the
; instruction word (fields SIP, SIQ, SIT, SIF, IF, and CO).
;
;========================================================================
;
; floating point operation codes.
;
.equ CP_PASS_P, 0x00000000 ; pass P
.equ CP_MINUSP, 0x00000040 ; -P
.equ CP_ABSP, 0x00000080 ; |P|
.equ CP_SIGNT_TIMES_ABSP, 0x00000C00 ; SIGN(T) * |P|
;
.equ CP_P_PLUS_T, 0x00000001 ; P + T
.equ CP_P_MINUS_T, 0x00000101 ; P - T
.equ CP_MINUSP_PLUS_T, 0x00001001 ; -P + T
.equ CP_MINUSP_MINUS_T, 0x00001101 ; -P - T
.equ CP_ABS_P_PLUS_T, 0x00000081 ; |P + T|
.equ CP_ABS_P_MINUS_T, 0x00000181 ; |P - T|
.equ CP_ABSP_PLUS_ABST, 0x00002201 ; |P| + |T|
.equ CP_ABSP_MINUS_ABST, 0x00002301 ; |P| - |T|
.equ CP_ABS_ABSP_MINUS_ABST, 0x00002381 ; ||P| - |T||
;
.equ CP_P_TIMES_Q, 0x00000002 ; P * Q
.equ CP_MINUSP_TIMES_Q, 0x00001002 ; -P * Q
.equ CP_ABS_P_TIMES_Q, 0x00000082 ; |P * Q|
;
.equ CP_COMPARE_P_AND_T, 0x00000103 ; compare P and T
;
.equ CP_MAX_P_AND_T, 0x00000104 ; max P,T
.equ CP_MAX_ABSP_AND_ABST, 0x00002304 ; max |P|, |T|
;
.equ CP_MIN_P_AND_T, 0x00001005 ; min P,T
.equ CP_MIN_ABSP_AND_ABST, 0x00003205 ; min |P|,|T|
.equ CP_LIMIT_P_TO_MAGT, 0x00003A05 ; limit P to magnitude of T
;
.equ CP_CONVERT_T_TO_INT, 0x00000006 ; convert T to integer
;
.equ CP_SCALE_T_TO_INT_BY_Q, 0x00000007 ; scale T to integer by Q
;
.equ CP_PQ_PLUS_T, 0x00000008 ; (P * Q) + T
.equ CP_MINUSPQ_PLUS_T, 0x00001008 ; (-P * Q) + T
.equ CP_PQ_MINUS_T, 0x00000108 ; (P * Q) - T
.equ CP_MINUSPQ_MINUS_T, 0x00001108 ; (-P * Q) - T
.equ CP_ABSPQ_PLUS_ABST, 0x00002A08 ; |(P * Q)| + T
.equ CP_MINUSABSPQ_PLUS_ABST, 0x00003A08 ;-|(P * Q)| + T
.equ CP_ABSPQ_MINUS_ABST, 0x00002B08 ; |(P * Q)| - |T|
;
.equ CP_ROUND_T_TO_INT, 0x00000009 ; round T to integral value
;
.equ CP_RECIPROCAL_OF_P, 0x0000000A ; reciprocal of P
;
.equ CP_CONVERT_T_TO_ALT, 0x0000000B ; convert T to alt. f.p. format
.equ CP_CONVERT_T_FROM_ALT, 0x0000000C ; convert T to alt. f.p. format
;
;
; integer operation codes.
;
.equ CP_I_PASS_P, 0x00000020 ; integer pass P
.equ CP_I_MINUSP, 0x00000060 ; integer -P
.equ CP_I_ABSP, 0x000000A0 ; integer |P|
.equ CP_I_SIGNT_TIMES_ABSP, 0x00000C20 ; integer SIGN(T) * |P|
;
.equ CP_I_P_PLUS_T, 0x00000021 ; integer P + T
.equ CP_I_P_MINUS_T, 0x00000121 ; integer P - T
.equ CP_I_MINUSP_PLUS_T, 0x00001021 ; integer -P + T
.equ CP_I_ABS_P_PLUS_T, 0x000000A1 ; integer |P + T|
.equ CP_I_ABS_P_MINUS_T, 0x000001A1 ; integer |P - T|
;
.equ CP_I_P_TIMES_Q, 0x00000022 ; integer P * Q
;
.equ CP_I_COMPARE_P_AND_T, 0x00000123 ; integer compare P and T
;
.equ CP_I_MAX_P_AND_T, 0x00000124 ; integer max P,T
;
.equ CP_I_MIN_P_AND_T, 0x00001025 ; integer min P,T
;
.equ CP_I_CONVERT_T_TO_FLOAT, 0x00000026 ; integer convert T to f.p.
;
.equ CP_I_SCALE_T_TO_FLOAT_BY_Q, 0x00000027 ; integer scale T to f.p. by Q
;
.equ CP_I_P_OR_T, 0x00000030 ; integer P OR T
;
.equ CP_I_P_AND_T, 0x00000031 ; integer P AND T
;
.equ CP_I_P_XOR_T, 0x00000032 ; integer P XOR T
;
.equ CP_I_NOT_T, 0x00000032 ; integer NOT T
;
.equ CP_I_LSHIFT_P_BY_Q, 0x00000033 ; integer logical shift P by Q
; places
;
.equ CP_I_ASHIFT_P_BY_Q, 0x00000034 ; integer arith. shift P by Q
; places
;
.equ CP_I_FSHIFT_PT_BY_Q, 0x00000035 ; integer funnel shift PT by Q
; places
;
;
; move instruction (f.p. or integer)
;
.equ CP_MOVE_P, 0x00000018 ; move operand P
;
;
;========================================================================
;
; precision codes for the the operands in registers R and S, and for
; the result (instruction word fields IPR, RPR).
;
;========================================================================
;
;
.equ CP_D_S, 0x00008000 ;Double result, single input(s)
.equ CP_S_D, 0x00004000 ;Single result, double input(s)
.equ CP_D_D, 0x00000000 ;Double result, double input(s)
.equ CP_S_S, 0x0000C000 ;Single result, single input(s)
;
;========================================================================
;
; The following mnemonics are used to specify the 16 LSBs of an Am29027
; instruction word for floating-point instructions supported by the
; Am29000 instruction set.
;
;========================================================================
;
.equ CP_FADD, 0x0000C001
.equ CP_DADD, 0x00000001
.equ CP_FSUB, 0x0000C101
.equ CP_DSUB, 0x00000101
.equ CP_FMUL, 0x0000C002
.equ CP_DMUL, 0x00000002
.equ CP_FEQ, 0x0000C103
.equ CP_DEQ, 0x00000103
.equ CP_FGE, 0x0000C103
.equ CP_DGE, 0x00000103
.equ CP_FGT, 0x0000C103
.equ CP_DGT, 0x00000103
.equ CP_CONVERT_I_TO_F, 0x0000C026 ; CONVERT (int -> s.p.)
.equ CP_CONVERT_I_TO_D, 0x00008026 ; CONVERT (int -> d.p.)
.equ CP_CONVERT_F_TO_I, 0x0000C006 ; CONVERT (s.p.-> int)
.equ CP_CONVERT_D_TO_I, 0x00004006 ; CONVERT (d.p.-> int)
.equ CP_CONVERT_F_TO_D, 0x00008000 ; CONVERT (s.p.-> d.p.)
.equ CP_CONVERT_D_TO_F, 0x00004000 ; CONVERT (d.p.-> s.p.)
;
;
;========================================================================
;
; operand select codes (instruction word fields PMS, QMS, TMS).
;
;========================================================================
;
;
.equ CP_P_EQ_R, 0x00000000
.equ CP_P_EQ_S, 0x01000000
.equ CP_P_EQ_0, 0x02000000
.equ CP_P_EQ_ONE_HALF, 0x03000000
.equ CP_P_EQ_IMINUS1, 0x03000000
.equ CP_P_EQ_1, 0x04000000
.equ CP_P_EQ_2, 0x05000000
.equ CP_P_EQ_3, 0x06000000
.equ CP_P_EQ_PI, 0x07000000
.equ CP_P_EQ_IMINUSMAX, 0x07000000
.equ CP_P_EQ_RF0, 0x08000000
.equ CP_P_EQ_RF1, 0x09000000
.equ CP_P_EQ_RF2, 0x0A000000
.equ CP_P_EQ_RF3, 0x0B000000
.equ CP_P_EQ_RF4, 0x0C000000
.equ CP_P_EQ_RF5, 0x0D000000
.equ CP_P_EQ_RF6, 0x0E000000
.equ CP_P_EQ_RF7, 0x0F000000
;
.equ CP_Q_EQ_R, 0x00000000
.equ CP_Q_EQ_S, 0x00100000
.equ CP_Q_EQ_0, 0x00200000
.equ CP_Q_EQ_ONE_HALF, 0x00300000
.equ CP_Q_EQ_IMINUS1, 0x00300000
.equ CP_Q_EQ_1, 0x00400000
.equ CP_Q_EQ_2, 0x00500000
.equ CP_Q_EQ_3, 0x00600000
.equ CP_Q_EQ_PI, 0x00700000
.equ CP_Q_EQ_IMINUSMAX, 0x00700000
.equ CP_Q_EQ_RF0, 0x00800000
.equ CP_Q_EQ_RF1, 0x00900000
.equ CP_Q_EQ_RF2, 0x00A00000
.equ CP_Q_EQ_RF3, 0x00B00000
.equ CP_Q_EQ_RF4, 0x00C00000
.equ CP_Q_EQ_RF5, 0x00D00000
.equ CP_Q_EQ_RF6, 0x00E00000
.equ CP_Q_EQ_RF7, 0x00F00000
;
.equ CP_T_EQ_R, 0x00000000
.equ CP_T_EQ_S, 0x00010000
.equ CP_T_EQ_0, 0x00020000
.equ CP_T_EQ_ONE_HALF, 0x00030000
.equ CP_T_EQ_IMINUS1, 0x00030000
.equ CP_T_EQ_1, 0x00040000
.equ CP_T_EQ_2, 0x00050000
.equ CP_T_EQ_3, 0x00060000
.equ CP_T_EQ_PI, 0x00070000
.equ CP_T_EQ_IMINUSMAX, 0x00070000
.equ CP_T_EQ_RF0, 0x00080000
.equ CP_T_EQ_RF1, 0x00090000
.equ CP_T_EQ_RF2, 0x000A0000
.equ CP_T_EQ_RF3, 0x000B0000
.equ CP_T_EQ_RF4, 0x000C0000
.equ CP_T_EQ_RF5, 0x000D0000
.equ CP_T_EQ_RF6, 0x000E0000
.equ CP_T_EQ_RF7, 0x000F0000
;
;
;========================================================================
;
; destination select codes (instruction word fields RF, RFS)
;
;========================================================================
;
;
.equ CP_DEST_EQ_GP, 0x00000000
.equ CP_DEST_EQ_RF0, 0x80000000
.equ CP_DEST_EQ_RF1, 0x90000000
.equ CP_DEST_EQ_RF2, 0xA0000000
.equ CP_DEST_EQ_RF3, 0xB0000000
.equ CP_DEST_EQ_RF4, 0xC0000000
.equ CP_DEST_EQ_RF5, 0xD0000000
.equ CP_DEST_EQ_RF6, 0xE0000000
.equ CP_DEST_EQ_RF7, 0xF0000000
;
;
; ______________________________________________________________________
;|______________________________________________________________________|
;| |
;| SYMBOLS FOR DEFINING THE MODE REGISTER DOUBLE WORD |
;| |
;|______________________________________________________________________|
;|______________________________________________________________________|
;
;
;
.equ CP_PFF_MASK, 0x00000003 ; primary f.p. format mask
.equ CP_PFF_EQ_IEEE, 0x00000000 ; primary f.p. format = IEEE
.equ CP_PFF_EQ_DECD, 0x00000001 ; primary f.p. format = DEC D
.equ CP_PFF_EQ_DECG, 0x00000002 ; primary f.p. format = DEC G
.equ CP_PFF_EQ_IBM, 0x00000003 ; primary f.p. format = IBM
.equ CP_PFF_POSITION, 0
;
.equ CP_AFF_MASK, 0x0000000C ; alternate f.p. format mask
.equ CP_AFF_EQ_IEEE, 0x00000000 ; alternate f.p. format = IEEE
.equ CP_AFF_EQ_DECD, 0x00000004 ; alternate f.p. format = DEC D
.equ CP_AFF_EQ_DECG, 0x00000008 ; alternate f.p. format = DEC G
.equ CP_AFF_EQ_IBM, 0x0000000C ; alternate f.p. format = IBM
.equ CP_AFF_POSITION, 2
;
.equ CP_SAT_MASK, 0x00000010 ; saturate mode (SAT) mask
.equ CP_SATURATE_MODE, 0x00000010 ; enable saturate mode (SAT=1)
.equ CP_SAT_POSITION, 4
;
.equ CP_AP_MASK, 0x00000020 ; affine/proj. mode (AP) mask
.equ CP_AFFINE_MODE, 0x00000020 ; enable affine mode (AP=1)
.equ CP_PROJECTIVE_MODE, 0x00000000 ; enable projective mode (AP=0)
.equ CP_AP_POSITION, 5
;
.equ CP_TRP_MASK, 0x00000040 ; IEEE trap mode (TRP) mask
.equ CP_IEEE_TRAPS_ENABLED, 0x00000040 ; IEEE trap mode enabled (TRP=1)
.equ CP_IEEE_TRAPS_DISABLED, 0x00000000 ; IEEE trap mode disabled (TRP=0)
.equ CP_TRP_POSITION, 6
;
.equ CP_SU_MASK, 0x00000080 ; IEEE sud. uflow (SU) mask
.equ CP_IEEE_SUDDEN_UFLOW_MODE, 0x00000080 ; IEEE sud. uflow mode (SU=1)
.equ CP_IEEE_GRADUAL_UFLOW_MODE,0x00000000 ; IEEE grad uflow mode (SU=0)
.equ CP_SU_POSITION, 7
;
.equ CP_BS_MASK, 0x00000100 ; IBM sig. mask (BS)
.equ CP_BS_POSITION, 8
;
.equ CP_BU_MASK, 0x00000200 ; IBM underflow mask (BU)
.equ CP_BU_POSITION, 9
;
.equ CP_MS_MASK, 0x00000800 ; signed int. mpy (MS) mask
.equ CP_SIGNED_INT_MPY_MODE, 0x00000800 ; signed int. mpy mode (MS=1)
.equ CP_UNSIGNED_INT_MPY_MODE, 0x00000000 ; unsigned int. mpy mode (MS=0)
.equ CP_MS_POSITION, 11
;
.equ CP_MF_MASK, 0x00003000 ; int. mult. fmt. mode (MF) mask
.equ CP_MF_EQ_LSBS, 0x00000000 ; int. mult. fmt. = LSBs
.equ CP_MF_EQ_LSBSFA, 0x00001000 ; int. mult. fmt. = LSBs,fmt. adj.
.equ CP_MF_EQ_MSBS, 0x00002000 ; int. mult. fmt. = MSBs
.equ CP_MF_EQ_MSBSFA, 0x00003000 ; int. mult. fmt. = MSBs,fmt. adj.
.equ CP_MF_POSITION, 12
;
.equ CP_RMS_MASK, 0x0001C000 ; round mode (RMS) mask
.equ CP_RMS_EQ_NEAREST, 0x00000000 ; round mode = to nearest
.equ CP_RMS_EQ_MINUS_INF, 0x00004000 ; round mode = toward -oo
.equ CP_RMS_EQ_PLUS_INF, 0x00008000 ; round mode = toward +oo
.equ CP_RMS_EQ_ZERO, 0x0000C000 ; round mode = toward zero
.equ CP_RMS_POSITION, 14
;
.equ CP_PL_MASK, 0x00100000 ; pipeline mode (PL) mask
.equ CP_FLOWTHROUGH_MODE, 0x00000000 ; select flow-through mode
.equ CP_PIPELINE_MODE, 0x00100000 ; select pipeline mode
.equ CP_PL_POSITION, 20
;
.equ CP_INVALID_OP_EXCP_MASK, 0x00400000 ; invalid operation excp. mask(IM)
.equ CP_RESERVED_OP_EXCP_MASK,0x00800000 ; reserved operand excp. mask(RM)
.equ CP_OVERFLOW_EXCP_MASK, 0x01000000 ; overflow exception mask (VM)
.equ CP_UNDERFLOW_EXCP_MASK, 0x02000000 ; underflow exception mask(UM)
.equ CP_INEXACT_EXCP_MASK, 0x04000000 ; inexact result excp. mask(XM)
.equ CP_ZERO_EXCP_MASK, 0x08000000 ; zero result exception mask (ZM)
.equ CP_EXCPS_POSITION, 22
;
.equ CP_PLTC_MASK, 0x0000000F ; pipeline timer count (PLTC) mask
.equ CP_PLTC_EQ_2, 0x00000002 ; pipeline timer count = 2
.equ CP_PLTC_EQ_3, 0x00000003 ; pipeline timer count = 3
.equ CP_PLTC_EQ_4, 0x00000004 ; pipeline timer count = 4
.equ CP_PLTC_EQ_5, 0x00000005 ; pipeline timer count = 5
.equ CP_PLTC_EQ_6, 0x00000006 ; pipeline timer count = 6
.equ CP_PLTC_EQ_7, 0x00000007 ; pipeline timer count = 7
.equ CP_PLTC_EQ_8, 0x00000008 ; pipeline timer count = 8
.equ CP_PLTC_EQ_9, 0x00000009 ; pipeline timer count = 9
.equ CP_PLTC_EQ_10, 0x0000000A ; pipeline timer count = 10
.equ CP_PLTC_EQ_11, 0x0000000B ; pipeline timer count = 11
.equ CP_PLTC_EQ_12, 0x0000000C ; pipeline timer count = 12
.equ CP_PLTC_EQ_13, 0x0000000D ; pipeline timer count = 13
.equ CP_PLTC_EQ_14, 0x0000000E ; pipeline timer count = 14
.equ CP_PLTC_EQ_15, 0x0000000F ; pipeline timer count = 15
.equ CP_PLTC_POSITION, 0
;
.equ CP_MATC_MASK, 0x000000F0 ; mpy-acc timer count (MATC) mask
.equ CP_MATC_EQ_2, 0x00000020 ; mpy-acc timer count = 2
.equ CP_MATC_EQ_3, 0x00000030 ; mpy-acc timer count = 3
.equ CP_MATC_EQ_4, 0x00000040 ; mpy-acc timer count = 4
.equ CP_MATC_EQ_5, 0x00000050 ; mpy-acc timer count = 5
.equ CP_MATC_EQ_6, 0x00000060 ; mpy-acc timer count = 6
.equ CP_MATC_EQ_7, 0x00000070 ; mpy-acc timer count = 7
.equ CP_MATC_EQ_8, 0x00000080 ; mpy-acc timer count = 8
.equ CP_MATC_EQ_9, 0x00000090 ; mpy-acc timer count = 9
.equ CP_MATC_EQ_10, 0x000000A0 ; mpy-acc timer count = 10
.equ CP_MATC_EQ_11, 0x000000B0 ; mpy-acc timer count = 11
.equ CP_MATC_EQ_12, 0x000000C0 ; mpy-acc timer count = 12
.equ CP_MATC_EQ_13, 0x000000D0 ; mpy-acc timer count = 13
.equ CP_MATC_EQ_14, 0x000000E0 ; mpy-acc timer count = 14
.equ CP_MATC_EQ_15, 0x000000F0 ; mpy-acc timer count = 15
.equ CP_MATC_POSITION, 4
;
.equ CP_MVTC_MASK, 0x00000F00 ; MOVE P timer count (MVTC) mask
.equ CP_MVTC_EQ_2, 0x00000200 ; MOVE P timer count = 2
.equ CP_MVTC_EQ_3, 0x00000300 ; MOVE P timer count = 3
.equ CP_MVTC_EQ_4, 0x00000400 ; MOVE P timer count = 4
.equ CP_MVTC_EQ_5, 0x00000500 ; MOVE P timer count = 5
.equ CP_MVTC_EQ_6, 0x00000600 ; MOVE P timer count = 6
.equ CP_MVTC_EQ_7, 0x00000700 ; MOVE P timer count = 7
.equ CP_MVTC_EQ_8, 0x00000800 ; MOVE P timer count = 8
.equ CP_MVTC_EQ_9, 0x00000900 ; MOVE P timer count = 9
.equ CP_MVTC_EQ_10, 0x00000A00 ; MOVE P timer count = 10
.equ CP_MVTC_EQ_11, 0x00000B00 ; MOVE P timer count = 11
.equ CP_MVTC_EQ_12, 0x00000C00 ; MOVE P timer count = 12
.equ CP_MVTC_EQ_13, 0x00000D00 ; MOVE P timer count = 13
.equ CP_MVTC_EQ_14, 0x00000E00 ; MOVE P timer count = 14
.equ CP_MVTC_EQ_15, 0x00000F00 ; MOVE P timer count = 15
.equ CP_MVTC_POSITION, 8
;
.equ CP_AD_MASK, 0x00001000 ;
.equ CP_ADVANCE_DRDY_MODE, 0x00001000 ;
.equ CP_NORMAL_DRDY_MODE, 0x00000000 ;
.equ CP_AD_POSITION, 12
;
.equ CP_HE_MASK, 0x00002000 ; Halt-on-error mask (HE)
.equ CP_HALT_ON_ERROR_ENABLED, 0x00002000 ; Halt-on-error enabled (HE=1)
.equ CP_HALT_ON_ERROR_DISABLED,0x00000000 ; Halt-on-error disabled (HE=0)
.equ CP_HE_POSITION, 13
;
.equ CP_EX_MASK, 0x00004000 ; EXCP enable mask (EX)
.equ CP_EXCP_ENABLED, 0x00004000 ; EXCP enabled (EX=1)
.equ CP_EXCP_DISABLED, 0x00000000 ; EXCP disabled (EX=0)
.equ CP_EX_POSITION, 14
;
;
;
; ______________________________________________________________________
;|______________________________________________________________________|
;| |
;| SYMBOLS FOR DEFINING THE STATUS REGISTER WORD |
;| |
;|______________________________________________________________________|
;|______________________________________________________________________|
;
;
.equ CP_INVALID_OP_EXCP, 0x00000001
.equ CP_INVALID_OP_EXCP_POSITION, 0
;
.equ CP_RESERVED_OP_EXCP, 0x00000002
.equ CP_RESERVED_OP_EXCP_POSITION, 1
;
.equ CP_OVERFLOW_EXCP, 0x00000004
.equ CP_OVERFLOW_EXCP_POSITION, 2
;
.equ CP_UNDERFLOW_EXCP, 0x00000008
.equ CP_UNDERFLOW_EXCP_POSITION, 3
;
.equ CP_INEXACT_EXCP, 0x00000010
.equ CP_INEXACT_EXCP_POSITION, 4
;
.equ CP_ZERO_EXCP, 0x00000020
.equ CP_ZERO_EXCP_POSITION, 5
;
.equ CP_EXCP_STATUS_MASK, 0x00000040
.equ CP_EXCP_STATUS_FLAG_POSITION, 6
;
.equ CP_R_TEMP_VALID_MASK, 0x00000080
.equ R_TEMP_VALID_POSITION, 7
;
.equ CP_S_TEMP_VALID_MASK, 0x00000100
.equ CP_S_TEMP_VALID_POSITION, 8
;
.equ CP_I_TEMP_VALID_FLAG, 0x00000200
.equ CP_I_TEMP_VALID_POSITION, 9
;
.equ CP_OPERATION_PENDING_MASK, 0x00000400
.equ CP_OPERATION_PENDING_POSITION,10
;
;
; ______________________________________________________________________
;|______________________________________________________________________|
;| |
;| SYMBOLS FOR DEFINING THE FLAG REGISTER WORD |
;| |
;|______________________________________________________________________|
;|______________________________________________________________________|
;
;
.equ CP_INVALID_OP_FLAG, 0x00000001
.equ CP_INVALID_OP_FLAG_POSITION, 0
;
.equ CP_CARRY_FLAG, 0x00000001
.equ CP_CARRY_FLAG_POSITION, 0
;
.equ CP_RESERVED_OP_FLAG, 0x00000002
.equ CP_RESERVED_OP_FLAG_POSITION, 1
;
.equ CP_OVERFLOW_FLAG, 0x00000004
.equ CP_OVERFLOW_FLAG_POSITION, 2
;
.equ CP_UNORDERED_FLAG, 0x00000004
.equ CP_UNORDERED_FLAG_POSITION, 2
;
.equ CP_UNDERFLOW_FLAG, 0x00000008
.equ CP_UNDERFLOW_FLAG_POSITION, 3
;
.equ CP_LESS_THAN_FLAG, 0x00000008
.equ CP_LESS_THAN_POSITION, 3
;
.equ CP_WINNER_FLAG, 0x00000008
.equ CP_WINNER_FLAG_POSITION, 3
;
.equ CP_INEXACT_FLAG, 0x00000010
.equ CP_INEXACT_FLAG_POSITION, 4
;
.equ CP_GREATER_THAN_FLAG, 0x00000010
.equ CP_GREATER_THAN_FLAG_POSITION,4
;
.equ CP_ZERO_FLAG, 0x00000020
.equ CP_ZERO_FLAG_POSITION, 5
;
.equ CP_EQUAL_FLAG, 0x00000020
.equ CP_EQUAL_FLAG_POSITION, 5
;
.equ CP_SIGN_FLAG, 0x00000040
.equ CP_SIGN_FLAG_POSITION, 6
;
;
; ______________________________________________________________________
;|______________________________________________________________________|
;| |
;| SYMBOLS FOR TRANSACTION REQUEST TYPES |
;| |
;|______________________________________________________________________|
;|______________________________________________________________________|
;
;
; write requests
;
; Note: Each WRITE_* transaction request, plus ADV_TEMPS sets the CA
; (Coprocessor Active) bit in the 29000 Current Processor Status Register.
;
.equ CP_WRITE_R, 0x20 ;write sing or doub to R register
.equ CP_WRITE_S, 0x21 ;write sing or doub to S register
.equ CP_WRITE_RS, 0x22 ;write sing operands to R and S
.equ CP_WRITE_MODE, 0x23 ;write mode double word to 29027
.equ CP_WRITE_STATUS, 0x24 ;write status word to 29027
.equ CP_WRITE_PREC, 0x25 ;write reg. file precision word
; to 29027
.equ CP_WRITE_INST, 0x26 ;write instruction to 29027
.equ CP_ADV_TEMPS, 0x27 ;move R-Temp, S-Temp into R,S
;
; read requests
;
.equ CP_READ_MSBS, 0x00 ;read sing result or MSB of doub
.equ CP_READ_LSBS, 0x01 ;read LSB of doub result
.equ CP_READ_FLAGS, 0x02 ;read 29027 flag register
.equ CP_READ_STATUS, 0x03 ;read 29027 status register
.equ CP_SAVE_STATE, 0x04 ;read one word of 29027 state
;
; "start operation" symbol; this is "OR"ed with a WRITE_R, WRITE_S,
; WRITE_RS, or WRITE_INST symbol.
;
.equ CP_START, 0b1000000 ;bit to start 29027 operation
;
; "suppress exceptions reporting" symbol; this is "OR"ed with a ed
;
;
.equ CP_NO_ERR, 0b1000000 ;suppress exception reporting
; ; during load.
; cp_write_r - transfers 32- or 64-bit operand to Am29027
; register R
; cp_write_s - transfers 32- or 64-bit operand to Am29027
; register S
; cp_write_rs - transfers two 32-bit floating-point operands to
; Am29027 registers R and S
; cp_write_prec - transfers a word to the Am29027 precision register
; cp_write_status - transfers a word to the Am29027 status register
; cp_write_inst - transfers an instruction to the Am29027
; instruction register
; cp_advance_temps - transfers the contents of the Am29027 temporary
; registers to the corresponding working registers
; cp_write_mode - transfers a mode specification the the Am29027
; mode register
; cp_read_dp - read a double-precision floating-point result
; from the Am29027
; cp_read_sp - read a single-precision floating-point result
; from the Am29027
; cp_read_int - read an integer result from the Am29027
; cp_read_flags - read the contents of the Am29027 flag register
; cp_read_status - read the contents of the Am29027 status register
; cp_read_state_wd - read a single Am29027 state word
; cp_save_state - save Am29027 state
; cp_restore_state - restore Am29027 state
; cp_build_inst - build an Am29027 instruction
; cp_build_inst_h - build 16 MSBs of an Am29027 instruction
; cp_build_inst_l - build 16 LSBs of an Am29027 instruction
;
;
;
;============================================================================
; MACRO NAME: cp_write_r
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 16, 1988
;
; FUNCTION: Transfers a 32- or 64-bit operand to Am29027 input register R
;
; PARAMETERS:
; reg - the Am29000 g.p. register containing the 32-bit operand to be
; transferred, or the 32 MSBs of the 64-bit operand to be
; transferred.
;
; LSB_reg - the Am29000 g.p. register containing the 32 LSBs of the
; 64-bit operand to be transferred
;
; INT - indicates that the operand to be transferred is a 32-bit
; integer
;
; START - indicates that a new Am29027 operation is to be started
; once the operand has been transferred
;
;
; USAGE:
;
; cp_write_r reg [,LSB_reg] [,START] for floating-point operands
; or cp_write_r reg, INT [,START] for integer operands
;
; Transferring double-precision floating-point operands - Either of
; two forms is acceptable:
;
; cp_write_r reg
; or cp_write_r reg, LSB_reg
;
; If LSB_reg is omitted, the LSBs are taken from the next g.p.
; register.
;
; Ex: cp_write_r lr2 Transfers the contents of lr2 to
; the most-significant half of Am29027
; register R, and the contents of lr3
; to the least-significant half.
;
; cp_write_r lr2,lr5 Transfers the contents of lr2 to
; the most-significant half of Am29027
; register R, and the contents of lr5
; to the least-significant half.
;
;
; Transferring single-precision floating-point operands - Use the
; form:
;
; cp_write_r reg
;
;
; Ex: cp_write_r lr2 Transfers the contents of lr2 to
; the most-significant half of Am29027
; register R, (the contents of lr3
; will be transferred to the least-
; significant half of register R, but
; these bits are don't cares).
;
;
; Transferring integer operands - Use the form:
;
; cp_write_r reg,INT
;
;
; Ex: cp_write_r lr2,INT Transfers the contents of lr2 to
; the least-significant half of Am29027
; register R, (the contents of lr2
; will also be transferred to the most-
; significant half of register R, but
; these bits are don't cares).
;
;
; Starting an Am29027 operation - Any of the forms above may be
; appended with parameter START, e.g.:
;
; cp_write_r lr2,START
;
; cp_write_r lr2,lr5,START
;
; cp_write_r lr2,INT,START
;
;
;============================================================================
;
.macro cp_write_r,p1,p2,p3
;
.if $narg==0
.err
.print "cp_WRITE_R: missing parameter(s)"
.endif
;
;
.if $narg==1
store 1,CP_WRITE_R,p1,%%((&p1)+1)
.exitm
.endif
;
;
.if $narg==2
;
.ifeqs "@p2@","INT"
store 1,CP_WRITE_R,p1,p1
.exitm
.endif
;
.ifeqs "@p2@","START"
store 1,CP_WRITE_R|CP_START,p1,%%((&p1)+1)
.exitm
.endif
;
store 1,CP_WRITE_R,p1,p2
.exitm
;
.endif
;
;
.if $narg==3
;
.ifeqs "@p2@","START"
.ifeqs "@p3@","INT"
store 1,CP_WRITE_R|CP_START,p1,p1
.else
.err
.print "cp_write_r: bad parameter list"
.endif
.exitm
.endif
;
.ifeqs "@p2@","INT"
.ifeqs "@p3@","START"
store 1,CP_WRITE_R|CP_START,p1,p1
.else
.err
.print "cp_write_r: bad parameter list"
.endif
.exitm
.endif
;
.ifeqs "@p3@","START"
store 1,CP_WRITE_R|CP_START,p1,p2
.else
.err
.print "cp_write_r: bad parameter list"
.endif
.exitm
;
.endif
;
;
.if $narg>=4
.err
.print "cp_write_r: too many parameters"
.endif
;
.endm
;
;
;
;
;
;============================================================================
; MACRO NAME: cp_write_s
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 16, 1988
;
; FUNCTION: Transfers a 32- or 64-bit operand to Am29027 input register S
;
; PARAMETERS:
; reg - the Am29000 g.p. register containing the 32-bit operand to be
; transferred, or the 32 MSBs of the 64-bit operand to be
; transferred.
;
; LSB_reg - the Am29000 g.p. register containing the 32 LSBs of the
; 64-bit operand to be transferred
;
; INT - indicates that the operand to be transferred is a 32-bit
; integer
;
; START - indicates that a new Am29027 operation is to be started
; once the operand has been transferred
;
;
; USAGE:
;
; cp_write_s reg [,LSB_reg] [,START] for floating-point operands
; or cp_write_s reg, INT [,START] for integer operands
;
; Transferring double-precision floating-point operands - Either of
; two forms is acceptable:
;
; cp_write_s reg
; or cp_write_s reg, LSB_reg
;
; If LSB_reg is omitted, the LSBs are taken from the next g.p.
; register.
;
; Ex: cp_write_s lr2 Transfers the contents of lr2 to
; the most-significant half of Am29027
; register S, and the contents of lr3
; to the least-significant half.
;
; cp_write_s lr2,lr5 Transfers the contents of lr2 to
; the most-significant half of Am29027
; register S, and the contents of lr5
; to the least-significant half.
;
;
; Transferring single-precision floating-point operands - Use the
; form:
;
; cp_write_s reg
;
;
; Ex: cp_write_s lr2 Transfers the contents of lr2 to
; the most-significant half of Am29027
; register S, (the contents of lr3
; will be transferred to the least-
; significant half of register S, but
; these bits are don't cares).
;
;
; Transferring integer operands - Use the form:
;
; cp_write_s reg,INT
;
;
; Ex: cp_write_s lr2,INT Transfers the contents of lr2 to
; the least-significant half of Am29027
; register S, (the contents of lr2
; will also be transferred to the most-
; significant half of register S, but
; these bits are don't cares).
;
;
; Starting an Am29027 operation - Any of the forms above may be
; appended with parameter START, e.g.:
;
; cp_write_s lr2,START
;
; cp_write_s lr2,lr5,START
;
; cp_write_s lr2,INT,START
;
;
;============================================================================
;
.macro cp_write_s,p1,p2,p3
;
.if $narg==0
.err
.print "cp_write_s: missing parameter(s)"
.endif
;
;
.if $narg==1
store 1,CP_WRITE_S,p1,%%((&p1)+1)
.exitm
.endif
;
;
.if $narg==2
;
.ifeqs "@p2@","INT"
store 1,CP_WRITE_S,p1,p1
.exitm
.endif
;
.ifeqs "@p2@","START"
store 1,CP_WRITE_S|CP_START,p1,%%((&p1)+1)
.exitm
.endif
;
store 1,CP_WRITE_S,p1,p2
.exitm
;
.endif
;
;
.if $narg==3
;
.ifeqs "@p2@","START"
.ifeqs "@p3@","INT"
store 1,CP_WRITE_S|CP_START,p1,p1
.else
.err
.print "cp_write_s: bad parameter list"
.endif
.exitm
.endif
;
.ifeqs "@p2@","INT"
.ifeqs "@p3@","START"
store 1,CP_WRITE_S|CP_START,p1,p1
.else
.err
.print "cp_write_s: bad parameter list"
.endif
.exitm
.endif
;
.ifeqs "@p3@","START"
store 1,CP_WRITE_S|CP_START,p1,p2
.else
.err
.print "cp_write_s: bad parameter list"
.endif
.exitm
;
.endif
;
;
.if $narg>=4
.err
.print "cp_write_s: too many parameters"
.endif
;
.endm
;
;
;
;
;============================================================================
; MACRO NAME: cp_write_rs
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 16, 1988
;
; FUNCTION: Transfers two 32-bit floating-point operands to Am29027
; input registers R and S
;
; PARAMETERS:
; reg1 - the Am29000 g.p. register containing the 32-bit operand to be
; transferred to register R
;
; reg2 - the Am29000 g.p. register containing the 32-bit operand to be
; transferred to register S
;
; START - indicates that a new Am29027 operation is to be started
; once the operands have been transferred
;
;
; USAGE:
;
; cp_write_rs reg1, reg2 [,START]
;
; Ex: cp_write_rs lr2,lr5 Transfers the contents of lr2 to
; the most-significant half of Am29027
; register R, and the contents of lr5
; to the most-significant half of Am29027
; register S.
;
; cp_write_rs lr2,lr5,START Transfers the contents of lr2 to
; the most-significant half of Am29027
; register R, and the contents of lr5
; to the most-significant half of Am29027
; register S; a new operation is started
; once the transfer is complete.
;
;
;
;============================================================================
;
.macro cp_write_rs,p1,p2,p3
;
;
.if $narg<=1
.err
.print "cp_write_rs: missing parameter(s)"
.exitm
.endif
;
;
.if $narg==2
.ifeqs "@p2@","START"
.err
.print "cp_write_rs: bad parameter list"
.else
store 1,CP_WRITE_RS,p1,p2
.endif
.exitm
.endif
;
;
.if $narg==3
.ifeqs "@p3@","START"
store 1,CP_WRITE_RS|CP_START,p1,p2
.else
.err
.print "cp_write_rs: bad parameter list"
.endif
.exitm
.endif
;
;
.if $narg>=4
.err
.print "cp_write_rs: too many parameters"
.exitm
.endif
;
.endm
;
;
;
;
;
;
;============================================================================
; MACRO NAME: cp_write_prec
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 16, 1988
;
; FUNCTION: Transfers a word to the Am29027 precision register
;
; PARAMETERS:
; reg - the Am29000 g.p. register containing the word to be
; transferred to the Am29027 precision register
;
; USAGE:
;
; cp_write_prec reg
;
; Ex: cp_write_prec lr2 Transfers the contents of lr2 to
; the Am29027 precision register.
;
;
;============================================================================
;
.macro cp_write_prec,p1
;
;
.if $narg!=1
.err
.print "cp_write_prec: bad parameter list"
.else
store 1,CP_WRITE_PREC,p1,0
.endif
;
.endm
;
;
;
;
;
;
;============================================================================
; MACRO NAME: cp_write_status
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 16, 1988
;
; FUNCTION: Transfers a word to the Am29027 precision register
;
; PARAMETERS:
; reg - the Am29000 g.p. register containing the word to be
; transferred to the Am29027 status register
;
; RESTORE - indicates that this is the last step of a state restoration
; sequence (flow-through mode only)
;
; INVALIDATE - indicates that the current contents of the ALU pipeline
; register are to be invalidated (pipeline mode only)
;
; USAGE:
;
; cp_write_status reg [,RESTORE|INVALIDATE]
;
; Ex: cp_write_status lr2 Transfers the contents of lr2 to
; the Am29027 status register.
;
;
; cp_write_status lr2,RESTORE Transfers the contents of lr2 to
; the Am29027 status register, and
; completes the state restore
; sequence
;
; cp_write_status lr2,INVALIDATE Transfers the contents of lr2 to
; the Am29027 status register, and
; invalidates the contents of the
; ALU pipeline.
;
;
;============================================================================
;
.macro cp_write_status,p1,p2
;
.if $narg==0
.err
.print "cp_write_status: missing parameter(s)"
.endif
;
;
.if $narg==1
store 1,CP_WRITE_STATUS,p1,0
.exitm
.endif
;
;
.if $narg==2
;
.ifeqs "@p2@","RESTORE"
store 1,CP_WRITE_STATUS|CP_START,p1,0
.exitm
.endif
;
.ifeqs "@p2@","INVALIDATE"
store 1,CP_WRITE_STATUS|CP_START,p1,0
.exitm
.endif
;
.err
.print "cp_write_status: bad parameter list"
.exitm
;
.endif
;
;
.if $narg >=3
.err
.print "cp_write_status: too many parameters"
.exitm
.endif
;
.endm
;
;
;
;
;
;============================================================================
; MACRO NAME: cp_write_inst
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 16, 1988
;
; FUNCTION: Transfers an instruction word to the Am29027 instruction
; register
;
; PARAMETERS:
; reg - the Am29000 g.p. register containing the word to be
; transferred to the Am29027 instruction register
;
; START - indicates that a new Am29027 operation is to be started
; once the instruction word has been transferred
;
; USAGE:
;
; cp_write_inst reg [,START]
;
; Ex: cp_write_inst lr2 Transfers the contents of lr2 to
; the Am29027 instruction register.
;
;
; cp_write_inst lr2,START Transfers the contents of lr2 to
; the Am29027 status register; a
; new operation is started once the
; transfer is complete.
;
;
;============================================================================
;
.macro cp_write_inst,p1,p2
;
.if $narg==0
.err
.print "cp_write_inst: missing parameter(s)"
.endif
;
;
.if $narg==1
store 1,CP_WRITE_INST,p1,p1
.exitm
.endif
;
;
.if $narg==2
;
.ifeqs "@p2@","START"
store 1,CP_WRITE_INST|CP_START,p1,p1
.else
.err
.print "cp_write_inst: bad parameter list"
.endif
.exitm
;
.endif
;
;
.if $narg >=3
.err
.print "cp_write_inst: too many parameters"
.exitm
.endif
;
.endm
;
;
;
;
;
;
;============================================================================
; MACRO NAME: cp_advance_temps
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 17, 1988
;
; FUNCTION: Transfers the contents of Am29027 registers R-Temp, S-Temp,
; and I-Temp to register R, register S, and the instruction
; register, respectively.
;
; PARAMETERS: none
;
; USAGE:
;
; cp_advance_temps
;
;
;
;============================================================================
;
.macro cp_advance_temps
;
;
.if $narg!=0
.err
.print "cp_advance_temp: takes no parameters"
.else
store 1,CP_ADV_TEMPS,gr1,0 ; use gr1 because it's never protected
.endif
;
.endm
;
;
;
;
;============================================================================
; MACRO NAME: cp_write_mode
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 17, 1988
;
; FUNCTION: Transfers a 64-bit mode specification to the Am29027 mode
; register
;
; PARAMETERS:
; reg - the Am29000 g.p. register containing the 32 MSBs of the
; 64-bit mode specification to be transferred.
;
; LSB_reg - the Am29000 g.p. register containing the 32 LSBs of the
; 64-bit mode specification to be transferred.
;
; USAGE:
;
; cp_write_mode reg [,LSB_reg]
;
; Either of two forms is acceptable:
;
; cp_write_mode reg
; or cp_write_mode reg, LSB_reg
;
; If LSB_reg is omitted, the LSBs are taken from the next g.p.
; register.
;
; Ex: cp_write_mode lr2 Transfers the contents of lr2 to
; the most-significant half of the Am29027
; mode register, and the contents of lr3
; to the least-significant half.
;
; cp_write_mode lr2,lr5 Transfers the contents of lr2 to
; the most-significant half of the Am29027
; mode register, and the contents of lr5
; to the least-significant half.
;
;
;
;============================================================================
;
.macro cp_write_mode,p1,p2
;
.if $narg==0
.err
.print "cp_write_mode: missing parameter(s)"
.endif
;
;
.if $narg==1
store 1,CP_WRITE_MODE,%%((&p1)+1),p1
.exitm
.endif
;
;
.if $narg==2
store 1,CP_WRITE_MODE,p2,p1
.exitm
.endif
;
;
.if $narg>=3
.err
.print "cp_write_mode: too many parameters"
.endif
;
.endm
;
;
;
;============================================================================
; MACRO NAME: cp_read_dp
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 17, 1988
;
; FUNCTION: Transfers the current Am29027 double-precison floating-point
; result to the Am29000
;
; PARAMETERS:
; reg - the Am29000 g.p. register into which the 32 MSBs of the
; current Am29027 result are to be written.
;
; LSB_reg - the Am29000 g.p. register into which the 32 LSBs of the
; current Am29027 result are to be written.
;
; NO_ERR - indicates that exception reporting is to be suppressed for this
; transfer.
;
; USAGE:
;
; cp_read_dp reg [,LSB_reg] [,START]
;
; Either of two forms is acceptable:
;
; cp_read_dp reg
; or cp_read_dp reg, LSB_reg
;
; If LSB_reg is omitted, the LSBs are written to the next g.p. register.
;
; Ex: cp_read_dp lr2 Transfers the 32 MSBs of the current
; Am29027 result to lr2, and the 32 LSBs
; to lr3.
;
; cp_read_dp lr2,lr5 Transfers the 32 MSBs of the current
; Am29027 result to lr2, and the 32 LSBs
; to lr5.
;
; Exception reporting can be suppressed by appending NO_ERR to either
; of the above, e.g.:
;
; cp_read_dp lr2,NO_ERR
; cp_read_dp lr2,lr5,NO_ERR
;
;
;============================================================================
;
.macro cp_read_dp,p1,p2,p3
;
.if $narg==0
.err
.print "cp_read_dp: missing parameter(s)"
.endif
;
;
.if $narg==1
load 1,CP_READ_LSBS,%%((&p1)+1),0
load 1,CP_READ_MSBS,p1,0
.exitm
.endif
;
;
.if $narg==2
;
.ifeqs "@p2@","NO_ERR"
load 1,CP_READ_LSBS|CP_NO_ERR,%%((&p1)+1),0
load 1,CP_READ_MSBS|CP_NO_ERR,p1,0
.exitm
.endif
;
load 1,CP_READ_LSBS,p2,0
load 1,CP_READ_MSBS,p1,0
.exitm
;
.endif
;
;
.if $narg==3
;
.ifeqs "@p3@","NO_ERR"
load 1,CP_READ_LSBS|CP_NO_ERR,p2,0
load 1,CP_READ_MSBS|CP_NO_ERR,p1,0
.else
.err
.print "cp_read_dp: bad parameter list"
.endif
.exitm
;
.endif
;
;
.if $narg>=4
.err
.print "cp_read_dp: too many parameters"
.endif
;
.endm
;
;
;
;============================================================================
; MACRO NAME: cp_read_sp
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 17, 1988
;
; FUNCTION: Transfers the current Am29027 single-precison floating-point
; result to the Am29000
;
; PARAMETERS:
; reg - the Am29000 g.p. register into which the current Am29027
; result is to be written.
;
; NO_ERR - indicates that exception reporting is to be suppressed for this
; transfer.
;
; USAGE:
;
; cp_read_sp reg [,START]
;
; Ex: cp_read_sp lr2 Transfers the current Am29027 result
; to lr2.
;
; cp_read_sp lr2,NO_ERR Transfers the current Am29027 result
; to lr2, and suppresses exception
; reporting for this transfer.
;
;
;============================================================================
;
.macro cp_read_sp,p1,p2
;
.if $narg==0
.err
.print "cp_read_sp: missing parameter(s)"
.endif
;
;
.if $narg==1
load 1,CP_READ_MSBS,p1,0
.exitm
.endif
;
;
.if $narg==2
;
.ifeqs "@p2@","NO_ERR"
load 1,CP_READ_MSBS|CP_NO_ERR,p1,0
.else
.err
.print "cp_read_sp: bad parameter list"
.endif
.exitm
;
.endif
;
;
.if $narg>=3
.err
.print "cp_read_sp: too many parameters"
.endif
;
.endm
;
;
;
;============================================================================
; MACRO NAME: cp_read_int
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 17, 1988
;
; FUNCTION: Transfers the current Am29027 integer result to the Am29000
;
; PARAMETERS:
; reg - the Am29000 g.p. register into which the current Am29027
; result is to be written.
;
; NO_ERR - indicates that exception reporting is to be suppressed for this
; transfer.
;
; USAGE:
;
; cp_read_int reg [,START]
;
; Ex: cp_read_int lr2 Transfers the current Am29027 result
; to lr2.
;
; cp_read_int lr2,NO_ERR Transfers the current Am29027 result
; to lr2, and suppresses exception
; reporting for this transfer.
;
;
;============================================================================
;
.macro cp_read_int,p1,p2
;
.if $narg==0
.err
.print "cp_read_int: missing parameter(s)"
.endif
;
;
.if $narg==1
load 1,CP_READ_LSBS,p1,0
nop ; leave a cycle for the MSBs to come out
.exitm
.endif
;
;
.if $narg==2
;
.ifeqs "@p2@","NO_ERR"
load 1,CP_READ_LSBS|CP_NO_ERR,p1,0
nop ; leave a cycle for the MSBs to come out
.else
.err
.print "cp_read_int: bad parameter list"
.endif
.exitm
;
.endif
;
;
.if $narg>=3
.err
.print "cp_read_int: too many parameters"
.endif
;
.endm
;
;
;
;============================================================================
; MACRO NAME: cp_read_flags
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 17, 1988
;
; FUNCTION: Transfers the contents of the Am29027 flag register
; to the Am29000
;
; PARAMETERS:
; reg - the Am29000 g.p. register into which the current Am29027
; flag register contents are to be written.
;
; NO_ERR - indicates that exception reporting is to be suppressed for this
; transfer.
;
; USAGE:
;
; cp_read_flags reg [,START]
;
; Ex: cp_read_flags lr2 Transfers the Am29027 flag register
; contents to lr2.
;
; cp_read_flags lr2,NO_ERR Transfers the Am29027 flag register
; contents to lr2, and suppresses
; exception reporting for this
; transfer.
;
;
;============================================================================
;
.macro cp_read_flags,p1,p2
;
.if $narg==0
.err
.print "cp_read_flags: missing parameter(s)"
.endif
;
;
.if $narg==1
load 1,CP_READ_FLAGS,p1,0
.exitm
.endif
;
;
.if $narg==2
;
.ifeqs "@p2@","NO_ERR"
load 1,CP_READ_FLAGS|CP_NO_ERR,p1,0
.else
.err
.print "cp_read_flags: bad parameter list"
.endif
.exitm
;
.endif
;
;
.if $narg>=3
.err
.print "cp_read_flags: too many parameters"
.endif
;
.endm
;
;
;
;============================================================================
; MACRO NAME: cp_read_status
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 18, 1988
;
; FUNCTION: Transfers the contents of the Am29027 status register
; to the Am29000
;
; PARAMETERS:
; reg - the Am29000 g.p. register into which the current Am29027
; status register contents are to be written.
;
; NO_ERR - indicates that exception reporting is to be suppressed for this
; transfer.
;
; USAGE:
;
; cp_read_status reg [,START]
;
; Ex: cp_read_status lr2 Transfers the Am29027 status register
; contents to lr2.
;
; cp_read_status lr2,NO_ERR Transfers the Am29027 status register
; contents to lr2, and suppresses
; exception reporting for this
; transfer.
;
;
;============================================================================
;
.macro cp_read_status,p1,p2
;
.if $narg==0
.err
.print "cp_read_status: missing parameter(s)"
.endif
;
;
.if $narg==1
load 1,CP_READ_STATUS,p1,0
.exitm
.endif
;
;
.if $narg==2
;
.ifeqs "@p2@","NO_ERR"
load 1,CP_READ_STATUS|CP_NO_ERR,p1,0
.else
.err
.print "cp_read_status: bad parameter list"
.endif
.exitm
;
.endif
;
;
.if $narg>=3
.err
.print "cp_read_status: too many parameters"
.endif
;
.endm
;
;
;
;============================================================================
; MACRO NAME: cp_read_state_wd
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 18, 1988
;
; FUNCTION: Transfers the next Am29027 state word to the Am29000
;
; PARAMETERS:
; reg - the Am29000 g.p. register into which the next Am29027
; state word contents are to be written.
;
; USAGE:
;
; cp_read_state_wd reg
;
; Ex: cp_read_state_wd lr2 Transfers the next Am29027 state word
; to lr2.
;
;============================================================================
;
.macro cp_read_state_wd,p1
;
.if $narg==0
.err
.print "cp_read_state_wd: missing parameter"
.endif
;
;
.if $narg==1
load 1,CP_SAVE_STATE,p1,0
.exitm
.endif
;
;
.if $narg>=2
.err
.print "cp_read_state_wd: too many parameters"
.endif
;
.endm
;
;
;
;============================================================================
; MACRO NAME: cp_save_state
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 18, 1988
;
; FUNCTION: Transfers the current Am29027 state to the Am29000
;
; PARAMETERS:
; reg - the first of 30 Am29000 g.p. registers in which Am29027 state
; is saved.
;
; USAGE:
;
; cp_save_state reg
;
; This macro transfers the current Am29027 state to a block of 30 Am29000
; registers. State is stored in the following order:
;
; reg instruction register
; reg+1 I-Temp
; reg+2 R MSBs
; reg+3 R LSBs
; reg+4 S MSBs
; reg+5 S LSBs
; reg+6 R-Temp MSBs
; reg+7 R-Temp LSBs
; reg+8 S-Temp MSBs
; reg+9 S-Temp LSBs
; reg+10 status
; reg+11 precision
; reg+12 RF0 MSBs
; reg+13 RF0 LSBs
; . .
; . .
; . .
; reg+26 RF7 MSBs
; reg+27 RF7 LSBs
; reg+28 mode MSBs
; reg+29 mode LSBs
;
;
; Ex: cp_save_state lr2 Transfers the current Am29027 state to
; the Am29000, starting at lr2.
;
; NOTES:
; 1) This macro stores all 64-bit quantities in "big-endian" order,
; i.e. MSBs first. For example, the 32 MSBs of register R are
; stored in reg+2, and the 32 LSBs are stored in reg+3. The Am29027
; transfers these quantites in "little-endian" order; the macro
; is responsible for swapping MS and LS words.
;
;============================================================================
;
.macro cp_save_state,p1
;
.if $narg==0
.err
.print "cp_save_state: missing parameter"
.endif
;
;
.if $narg==1
cp_read_sp p1,NO_ERR
;guarantee that we're at beginning of
; save state sequence
cp_read_state_wd %%((&p1)+ 0) ; instruction
cp_read_state_wd %%((&p1)+ 1) ; I-Temp
cp_read_state_wd %%((&p1)+ 3) ; R MSBs
cp_read_state_wd %%((&p1)+ 2) ; R LSBs
cp_read_state_wd %%((&p1)+ 5) ; S MSBs
cp_read_state_wd %%((&p1)+ 4) ; S LSBs
cp_read_state_wd %%((&p1)+ 7) ; R-Temp MSBs
cp_read_state_wd %%((&p1)+ 6) ; R-Temp LSBs
cp_read_state_wd %%((&p1)+ 9) ; S-Temp MSBs
cp_read_state_wd %%((&p1)+ 8) ; S-Temp LSBs
cp_read_state_wd %%((&p1)+10) ; status
cp_read_state_wd %%((&p1)+11) ; precision
cp_read_state_wd %%((&p1)+13) ; RF0 MSBs
cp_read_state_wd %%((&p1)+12) ; RF0 LSBs
cp_read_state_wd %%((&p1)+15) ; RF1 MSBs
cp_read_state_wd %%((&p1)+14) ; RF1 LSBs
cp_read_state_wd %%((&p1)+17) ; RF2 MSBs
cp_read_state_wd %%((&p1)+16) ; RF2 LSBs
cp_read_state_wd %%((&p1)+19) ; RF3 MSBs
cp_read_state_wd %%((&p1)+18) ; RF3 LSBs
cp_read_state_wd %%((&p1)+21) ; RF4 MSBs
cp_read_state_wd %%((&p1)+20) ; RF4 LSBs
cp_read_state_wd %%((&p1)+23) ; RF5 MSBs
cp_read_state_wd %%((&p1)+22) ; RF5 LSBs
cp_read_state_wd %%((&p1)+25) ; RF6 MSBs
cp_read_state_wd %%((&p1)+24) ; RF6 LSBs
cp_read_state_wd %%((&p1)+27) ; RF7 MSBs
cp_read_state_wd %%((&p1)+26) ; RF7 LSBs
cp_read_state_wd %%((&p1)+29) ; mode MSBs
cp_read_state_wd %%((&p1)+28) ; mode LSBs
.exitm
.endif
;
;
.if $narg>=2
.err
.print "cp_save_state: too many parameters"
.endif
;
.endm
;
;
;
;
;
;============================================================================
; MACRO NAME: cp_restore_state
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 18, 1988
;
; FUNCTION: Restores Am29027 state
;
; PARAMETERS:
; reg - the first of 30 Am29000 g.p. registers containing Am29027
; state.
;
; temp - a scratch register used by cp_restore_state
;
; USAGE:
;
; cp_restore_state reg,temp
;
; This macro restores Am29027 state by transferring 30 words to the
; Am29027; these words are taken from a block of Am29000 g.p. registers
; starting at "reg." The words are assumed to be stored in the following
; order:
;
; reg instruction register
; reg+1 I-Temp
; reg+2 R MSBs
; reg+3 R LSBs
; reg+4 S MSBs
; reg+5 S LSBs
; reg+6 R-Temp MSBs
; reg+7 R-Temp LSBs
; reg+8 S-Temp MSBs
; reg+9 S-Temp LSBs
; reg+10 status
; reg+11 precision
; reg+12 RF0 MSBs
; reg+13 RF0 LSBs
; . .
; . .
; . .
; reg+26 RF7 MSBs
; reg+27 RF7 LSBs
; reg+28 mode MSBs
; reg+29 mode LSBs
;
;
; Ex: cp_restore_state lr2,gr70 Restores Am29027 state by
; transferring a block of 30 words
; that begins at lr2. Register gr70
; is used as scratch storage by this
; macro.
;
;
;============================================================================
;
.macro cp_restore_state,p1,p2
;
.if $narg<=1
.err
.print "cp_restore_state: missing parameter(s)"
.endif
;
;
.if $narg==2
const p2,0 ;clear the status register
cp_write_status p2
;
cp_write_mode %%((&p1)+28) ;restore the mode register
;
const p2,0x80000018 ; restore RF0
consth p2,0x80000018
cp_write_inst p2
cp_write_r %%((&p1)+12),START
;
consth p2,0x90000018 ; restore RF1
cp_write_inst p2
cp_write_r %%((&p1)+14),START
;
consth p2,0xA0000018 ; restore RF2
cp_write_inst p2
cp_write_r %%((&p1)+16),START
;
consth p2,0xB0000018 ; restore RF3
cp_write_inst p2
cp_write_r %%((&p1)+18),START
;
consth p2,0xC0000018 ; restore RF4
cp_write_inst p2
cp_write_r %%((&p1)+20),START
;
consth p2,0xD0000018 ; restore RF5
cp_write_inst p2
cp_write_r %%((&p1)+22),START
;
consth p2,0xE0000018 ; restore RF6
cp_write_inst p2
cp_write_r %%((&p1)+24),START
;
consth p2,0xF0000018 ; restore RF7
cp_write_inst p2
cp_write_r %%((&p1)+26),START
;
cp_read_sp p2 ; do a dummy read, to guarantee that
; the last operation is complete
;
cp_write_prec %%((&p1)+11) ; restore precision
;
cp_write_r %%((&p1)+2) ; restore R
cp_write_s %%((&p1)+4) ; restore S
cp_write_inst %%((&p1)+0) ; restore instruction
cp_advance_temps ; move R,S, and inst. to working registers
;
cp_write_r %%((&p1)+6) ; restore R-Temp
cp_write_s %%((&p1)+8) ; restore S-Temp
cp_write_inst %%((&p1)+1) ; restore I-Temp
;
; restore the status register, retime last operation
;
cp_write_status %%((&p1)+10),RESTORE
;
.exitm
.endif
;
;
.if $narg>=3
.err
.print "cp_restore_state: too many parameters"
.endif
;
.endm
;
;
;
;============================================================================
; MACRO NAME: cp_build_inst
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 24, 1988
; : January 4, 1989 <NAME>
;
; FUNCTION: Builds a 32-bit Am29027 instruction in an Am29000 g.p.
; register.
;
; PARAMETERS:
; reg - the Am29000 g.p. register into which the instruction word
; is to be written
;
; op_code - mnemonic specifying the operation to be performed
; (e.g. FADD, P_TIMES_Q)
;
; precision - precision specification for destination, source operands:
; D_S - double-prec. result, single-prec. input(s)
; D_D - double-prec. result, double-prec. input(s)
; S_S - single-prec. result, single-prec. input(s)
; S_D - single-prec. result, double-prec. input(s)
;
; dest - destination for the operation result:
; RF0 - store result in Am29027 register file location RF0
; RF1 - store result in Am29027 register file location RF1
; RF2 - store result in Am29027 register file location RF2
; RF3 - store result in Am29027 register file location RF3
; RF4 - store result in Am29027 register file location RF4
; RF5 - store result in Am29027 register file location RF5
; RF6 - store result in Am29027 register file location RF6
; RF7 - store result in Am29027 register file location RF7
; GP - result is to be stored in an Am29000 g.p. register
; with a read_dp, read_sp, or read_int macro.
;
; source1,
; source2,
; source3 - source operand specifications:
; R - take source from Am29027 register R
; S - take source from Am29027 register S
; RF0 - take source from Am29027 register file location RF0
; RF1 - take source from Am29027 register file location RF1
; RF2 - take source from Am29027 register file location RF2
; RF3 - take source from Am29027 register file location RF3
; RF4 - take source from Am29027 register file location RF4
; RF5 - take source from Am29027 register file location RF5
; RF6 - take source from Am29027 register file location RF6
; RF7 - take source from Am29027 register file location RF7
; 0 - source is 0
; ONE_HALF - source is constant .5 (f.p. operations only)
; IMINUS1 - source is constant -1 (integer operations only)
; 1 - source is constant 1
; 2 - source is constant 2
; 3 - source is constant 3
; PI - source is constant pi (f.p. operations only)
; IMINUSMAX - source is -(2**63) (integer operations only)
;
;
; USAGE:
;
; cp_build_inst reg,op_code,[precision,]dest,source1[,source2][,source3]
;
; Op-codes fall into two categories: those that correspond to Am29000
; floating-point op-codes, and for which the precision is implicit (e.g.
; FADD, DMUL); and those that correspond to Am29027 base operations
; (e.g. P_PLUS_T, P_TIMES_Q), and which require an explicit precision
; specification.
;
; Every operation specified must have a destination; if the operation
; does not write a result to the Am29027 register file, destination GP
; must be specified. The number of source operands specified must agree
; with the number of source operands required by the operation specified.
;
; Ex:
;
; cp_build_inst lr2,FADD,RF7,R,S
; Builds an instruction word to
; perform the operation:
; RF7 <- R + S
; where R, S, and RF7 are single-
; precision f.p. operands. The
; instruction word is placed in lr2.
;
; cp_build_inst gr119,DMUL,GP,R,ONE_HALF
; Builds an instruction word to
; perform the operation:
; R * .5
; where R, .5, and the result
; are double-precision f.p. operands.
; The result is not written to the
; Am29027 register file. The
; instruction word is written to
; gr119.
;
;
; cp_build_inst lr3,MIN_P_AND_T,S_D,RF7,R,S
; Builds an instruction word to
; perform the operation:
; RF7 <- smaller of(R,S)
; where R and S are double-precision
; f.p. operands, and RF7 is a single-
; precison f.p. operand. The
; instruction word is written to
; lr3.
;
;
; cp_build_inst gr97,I_P_TIMES_Q,S_S,GP,R,2
; Builds an instruction word to
; perform the operation:
; R * 2
; where R, .5, and the result
; are single-precision integer operands.
; The result is not written to the
; Am29027 register file. The
; instruction word is written to
; gr97
;
;
; cp_build_inst lr7,ABS_P,D_D,RF6,S
; Builds an instruction word to
; perform the operation:
; RF6 <- |S|
; where S and RF7 are double-precision
; f.p. operands. The instruction
; word is written to gr7.
;
;
; cp_build_inst gr127,PQ_PLUS_T,D_D,RF6,R,S,RF6
; Builds an instruction word to
; perform the operation:
; RF6 <- (R * S) + RF6
; where R, S and the result are
; double-precision f.p. operands.
; The instruction word is written
; to gr127.
;
;
;
;============================================================================
;
.macro cp_build_inst,p1,p2,p3,p4,p5,p6,p7
;
.if $narg<=3
.err
.print "cp_build_inst: missing parameter(s)"
.exitm
.endif
;
; classify operation type
;
.set _cp_op_type,255
_cp_set_op_params p2,FADD,1,5,4,0,5
_cp_set_op_params p2,DADD,1,5,4,0,5
_cp_set_op_params p2,FSUB,1,5,4,0,5
_cp_set_op_params p2,DSUB,1,5,4,0,5
_cp_set_op_params p2,FMUL,1,5,4,5,0
_cp_set_op_params p2,DMUL,1,5,4,5,0
_cp_set_op_params p2,FEQ,1,5,4,0,5
_cp_set_op_params p2,DEQ,1,5,4,0,5
_cp_set_op_params p2,FGE,1,5,4,0,5
_cp_set_op_params p2,DGE,1,5,4,0,5
_cp_set_op_params p2,FGT,1,5,4,0,5
_cp_set_op_params p2,DGT,1,5,4,0,5
_cp_set_op_params p2,CONVERT_I_TO_F,1,4,0,0,4
_cp_set_op_params p2,CONVERT_I_TO_D,1,4,0,0,4
_cp_set_op_params p2,CONVERT_F_TO_I,1,4,0,0,4
_cp_set_op_params p2,CONVERT_D_TO_I,1,4,0,0,4
;
; The next two lines were corrected on 1-4-89, <NAME>
;
_cp_set_op_params p2,CONVERT_F_TO_D,1,4,4,0,0
_cp_set_op_params p2,CONVERT_D_TO_F,1,4,4,0,0
;
_cp_set_op_params p2,PASS_P,0,5,5,0,0
_cp_set_op_params p2,MINUSP,0,5,5,0,0
_cp_set_op_params p2,ABSP,0,5,5,0,0
_cp_set_op_params p2,SIGNT_TIMES_ABSP,0,6,6,0,5
_cp_set_op_params p2,P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,MINUSP_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,MINUSP_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,ABS_P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,ABS_P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,ABSP_PLUS_ABST,0,6,5,0,6
_cp_set_op_params p2,ABSP_MINUS_ABST,0,6,5,0,6
_cp_set_op_params p2,ABS_ABSP_MINUS_ABST,0,6,5,0,6
_cp_set_op_params p2,P_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,MINUSP_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,ABS_P_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,COMPARE_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,MAX_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,MAX_ABSP_AND_ABST,0,6,5,0,6
_cp_set_op_params p2,MIN_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,MIN_ABSP_AND_ABST,0,6,5,0,6
_cp_set_op_params p2,LIMIT_P_TO_MAGT,0,6,5,0,6
_cp_set_op_params p2,CONVERT_T_TO_INT,0,5,0,0,5
_cp_set_op_params p2,SCALE_T_TO_INT_BY_Q,0,6,0,6,5
_cp_set_op_params p2,PQ_PLUS_T,0,7,5,6,7
_cp_set_op_params p2,MINUSPQ_PLUS_T,0,7,5,6,7
_cp_set_op_params p2,PQ_MINUS_T,0,7,5,6,7
_cp_set_op_params p2,MINUSPQ_MINUS_T,0,7,5,6,7
_cp_set_op_params p2,ABSPQ_PLUS_ABST,0,7,5,6,7
_cp_set_op_params p2,MINUSABSPQ_PLUS_ABST,0,7,5,6,7
_cp_set_op_params p2,ABSPQ_MINUS_ABST,0,7,5,6,7
_cp_set_op_params p2,ROUND_T_TO_INT,0,5,0,0,5
_cp_set_op_params p2,RECIPROCAL_OF_P,0,5,5,0,0
_cp_set_op_params p2,CONVERT_T_TO_ALT,0,5,0,0,5
_cp_set_op_params p2,CONVERT_T_FROM_ALT,0,5,0,0,5
_cp_set_op_params p2,I_PASS_P,0,5,5,0,0
_cp_set_op_params p2,I_MINUSP,0,5,5,0,0
_cp_set_op_params p2,I_ABSP,0,5,5,0,0
_cp_set_op_params p2,I_SIGNT_TIMES_ABSP,0,6,6,0,5
_cp_set_op_params p2,I_P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,I_P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,I_MINUSP_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,I_ABS_P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,I_ABS_P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,I_P_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,I_COMPARE_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_MAX_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_MIN_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_CONVERT_T_TO_FLOAT,0,5,0,0,5
_cp_set_op_params p2,I_SCALE_T_TO_FLOAT_BY_Q,0,6,0,6,5
_cp_set_op_params p2,I_P_OR_T,0,6,5,0,6
_cp_set_op_params p2,I_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_P_XOR_T,0,6,5,0,6
_cp_set_op_params p2,I_NOT_T,0,5,0,0,5
_cp_set_op_params p2,I_LSHIFT_P_BY_Q,0,6,5,6,0
_cp_set_op_params p2,I_ASHIFT_P_BY_Q,0,6,5,6,0
_cp_set_op_params p2,I_FSHIFT_PT_BY_Q,0,7,5,7,6
_cp_set_op_params p2,MOVE_P,0,5,5,0,0
;
;
; if we couldn't find the op_code, flag an error
;
.if _cp_op_type>=2
.err
.print "cp_build_inst: invalid Am29027 instruction mnemonic"
.exitm
.endif
;
; if number of parameters is incorrect, flag error
;
.if $narg!=_cp_no_params
.err
.print "cp_build_inst: incorrect number of parameters"
.exitm
.endif
;
; find correct value for precision field, if appropriate
;
.set _cp_prec_field,0 ; ** CORRECTION (1/4/89 ROP)
.if _cp_op_type==0 ; need to look for precision
.set _cp_found_precision,0
.ifeqs "@p3@","D_D"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.ifeqs "@p3@","D_S"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.ifeqs "@p3@","S_D"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.ifeqs "@p3@","S_S"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.if _cp_found_precision==0
.err
.print "cp_build_inst: missing precision field"
.exitm
.endif
.endif
;
; find value for destination field
;
.if _cp_op_type==0
.set _cp_dest_field_val,CP_DEST_EQ_@p4
.else
.set _cp_dest_field_val,CP_DEST_EQ_@p3
.endif
;
; find correct value for p select field
;
.if _cp_p_paramno==0
.set _cp_p_field_val,0x00000000
.endif
.if _cp_p_paramno==4
.set _cp_p_field_val,CP_P_EQ_@p4
.endif
.if _cp_p_paramno==5
.set _cp_p_field_val,CP_P_EQ_@p5
.endif
.if _cp_p_paramno==6
.set _cp_p_field_val,CP_P_EQ_@p6
.endif
.if _cp_p_paramno==7
.set _cp_p_field_val,CP_P_EQ_@p7
.endif
.ifeqs "@p2@","I_NOT_T"
.set _cp_p_field_val,CP_P_EQ_IMINUS1
.endif
;
; find correct value for q select field
;
.if _cp_q_paramno==0
.set _cp_q_field_val,0x00000000
.endif
.if _cp_q_paramno==4
.set _cp_q_field_val,CP_Q_EQ_@p4
.endif
.if _cp_q_paramno==5
.set _cp_q_field_val,CP_Q_EQ_@p5
.endif
.if _cp_q_paramno==6
.set _cp_q_field_val,CP_Q_EQ_@p6
.endif
.if _cp_q_paramno==7
.set _cp_q_field_val,CP_Q_EQ_@p7
.endif
;
; find correct value for t select field
;
.if _cp_t_paramno==0
.set _cp_t_field_val,0x00000000
.endif
.if _cp_t_paramno==4
.set _cp_t_field_val,CP_T_EQ_@p4
.endif
.if _cp_t_paramno==5
.set _cp_t_field_val,CP_T_EQ_@p5
.endif
.if _cp_t_paramno==6
.set _cp_t_field_val,CP_T_EQ_@p6
.endif
.if _cp_t_paramno==7
.set _cp_t_field_val,CP_T_EQ_@p7
.endif
;
;
.set _cp_inst_word,CP_@p2@|_cp_prec_field|_cp_dest_field_val
.set _cp_inst_word,_cp_inst_word|_cp_p_field_val
.set _cp_inst_word,_cp_inst_word|_cp_q_field_val
.set _cp_inst_word,_cp_inst_word|_cp_t_field_val
const p1,_cp_inst_word
consth p1,_cp_inst_word
;
.endm
;
;
;
.macro _cp_set_op_params,par1,par2,par3,par4,par5,par6,par7
.ifeqs "@par1@","@par2@"
.set _cp_op_type,par3
.set _cp_no_params,par4
.set _cp_p_paramno,par5
.set _cp_q_paramno,par6
.set _cp_t_paramno,par7
.endif
.endm
;
;
;
;============================================================================
; MACRO NAME: cp_build_inst_h
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 24, 1988
; : January 4, 1989 <NAME>
;
; FUNCTION: Builds a 16 MSBs of a 32-bit Am29027 instruction in an
; Am29000 g.p. register.
;
; PARAMETERS:
; reg - the Am29000 g.p. register into which the instruction word
; is to be written
;
; op_code - mnemonic specifying the operation to be performed
; (e.g. FADD, P_TIMES_Q)
;
; precision - precision specification for destination, source operands:
; D_S - double-prec. result, single-prec. input(s)
; D_D - double-prec. result, double-prec. input(s)
; S_S - single-prec. result, single-prec. input(s)
; S_D - single-prec. result, double-prec. input(s)
;
; dest - destination for the operation result:
; RF0 - store result in Am29027 register file location RF0
; RF1 - store result in Am29027 register file location RF1
; RF2 - store result in Am29027 register file location RF2
; RF3 - store result in Am29027 register file location RF3
; RF4 - store result in Am29027 register file location RF4
; RF5 - store result in Am29027 register file location RF5
; RF6 - store result in Am29027 register file location RF6
; RF7 - store result in Am29027 register file location RF7
; GP - result is to be stored in an Am29000 g.p. register
; with a read_dp, read_sp, or read_int macro.
;
; source1,
; source2,
; source3 - source operand specifications:
; R - take source from Am29027 register R
; S - take source from Am29027 register S
; RF0 - take source from Am29027 register file location RF0
; RF1 - take source from Am29027 register file location RF1
; RF2 - take source from Am29027 register file location RF2
; RF3 - take source from Am29027 register file location RF3
; RF4 - take source from Am29027 register file location RF4
; RF5 - take source from Am29027 register file location RF5
; RF6 - take source from Am29027 register file location RF6
; RF7 - take source from Am29027 register file location RF7
; 0 - source is 0
; ONE_HALF - source is constant .5 (f.p. operations only)
; IMINUS1 - source is constant -1 (integer operations only)
; 1 - source is constant 1
; 2 - source is constant 2
; 3 - source is constant 3
; PI - source is constant pi (f.p. operations only)
; IMINUSMAX - source is -(2**63) (integer operations only)
;
;
; USAGE:
;
; cp_build_inst_h reg,op_code,[precision,]dest,source1[,source2][,source3]
;
; This macro is similar to cp_build_inst, but creates only the 16 MSBs
; of the 32-bit Am29027 instruction word. This macro is useful in cases
; where the 16 LSBs of instruction word, which specify the operation
; to be performed, already exist in an Am29000 g.p. register, but where
; the 16 MSBs, which specify operand sources and destination, must be
; changed. In such cases, one Am29000 instruction can be saved by using
; cp_build_inst_h instead of cp_build_inst.
;
; Syntax and usage are identical to that of cp_build_inst.
;
; NOTE: This macro references macro _cp_set_op_params, which appears
; in the assembly listing for macro _cp_build_inst.
;
;
;
;
;============================================================================
;
.macro cp_build_inst_h,p1,p2,p3,p4,p5,p6,p7
;
.if $narg<=3
.err
.print "cp_build_inst_h: missing parameter(s)"
.exitm
.endif
;
; classify operation type
;
.set _cp_op_type,255
_cp_set_op_params p2,FADD,1,5,4,0,5
_cp_set_op_params p2,DADD,1,5,4,0,5
_cp_set_op_params p2,FSUB,1,5,4,0,5
_cp_set_op_params p2,DSUB,1,5,4,0,5
_cp_set_op_params p2,FMUL,1,5,4,5,0
_cp_set_op_params p2,DMUL,1,5,4,5,0
_cp_set_op_params p2,FEQ,1,5,4,0,5
_cp_set_op_params p2,DEQ,1,5,4,0,5
_cp_set_op_params p2,FGE,1,5,4,0,5
_cp_set_op_params p2,DGE,1,5,4,0,5
_cp_set_op_params p2,FGT,1,5,4,0,5
_cp_set_op_params p2,DGT,1,5,4,0,5
_cp_set_op_params p2,CONVERT_I_TO_F,1,4,0,0,4
_cp_set_op_params p2,CONVERT_I_TO_D,1,4,0,0,4
_cp_set_op_params p2,CONVERT_F_TO_I,1,4,0,0,4
_cp_set_op_params p2,CONVERT_D_TO_I,1,4,0,0,4
;
; The next two lines were corrected on 1-4-89, <NAME>
;
_cp_set_op_params p2,CONVERT_F_TO_D,1,4,4,0,0
_cp_set_op_params p2,CONVERT_D_TO_F,1,4,4,0,0
;
_cp_set_op_params p2,PASS_P,0,5,5,0,0
_cp_set_op_params p2,MINUSP,0,5,5,0,0
_cp_set_op_params p2,ABSP,0,5,5,0,0
_cp_set_op_params p2,SIGNT_TIMES_ABSP,0,6,6,0,5
_cp_set_op_params p2,P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,MINUSP_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,MINUSP_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,ABS_P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,ABS_P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,ABSP_PLUS_ABST,0,6,5,0,6
_cp_set_op_params p2,ABSP_MINUS_ABST,0,6,5,0,6
_cp_set_op_params p2,ABS_ABSP_MINUS_ABST,0,6,5,0,6
_cp_set_op_params p2,P_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,MINUSP_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,ABS_P_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,COMPARE_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,MAX_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,MAX_ABSP_AND_ABST,0,6,5,0,6
_cp_set_op_params p2,MIN_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,MIN_ABSP_AND_ABST,0,6,5,0,6
_cp_set_op_params p2,LIMIT_P_TO_MAGT,0,6,5,0,6
_cp_set_op_params p2,CONVERT_T_TO_INT,0,5,0,0,5
_cp_set_op_params p2,SCALE_T_TO_INT_BY_Q,0,6,0,6,5
_cp_set_op_params p2,PQ_PLUS_T,0,7,5,6,7
_cp_set_op_params p2,MINUSPQ_PLUS_T,0,7,5,6,7
_cp_set_op_params p2,PQ_MINUS_T,0,7,5,6,7
_cp_set_op_params p2,MINUSPQ_MINUS_T,0,7,5,6,7
_cp_set_op_params p2,ABSPQ_PLUS_ABST,0,7,5,6,7
_cp_set_op_params p2,MINUSABSPQ_PLUS_ABST,0,7,5,6,7
_cp_set_op_params p2,ABSPQ_MINUS_ABST,0,7,5,6,7
_cp_set_op_params p2,ROUND_T_TO_INT,0,5,0,0,5
_cp_set_op_params p2,RECIPROCAL_OF_P,0,5,5,0,0
_cp_set_op_params p2,CONVERT_T_TO_ALT,0,5,0,0,5
_cp_set_op_params p2,CONVERT_T_FROM_ALT,0,5,0,0,5
_cp_set_op_params p2,I_PASS_P,0,5,5,0,0
_cp_set_op_params p2,I_MINUSP,0,5,5,0,0
_cp_set_op_params p2,I_ABSP,0,5,5,0,0
_cp_set_op_params p2,I_SIGNT_TIMES_ABSP,0,6,6,0,5
_cp_set_op_params p2,I_P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,I_P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,I_MINUSP_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,I_ABS_P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,I_ABS_P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,I_P_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,I_COMPARE_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_MAX_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_MIN_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_CONVERT_T_TO_FLOAT,0,5,0,0,5
_cp_set_op_params p2,I_SCALE_T_TO_FLOAT_BY_Q,0,6,0,6,5
_cp_set_op_params p2,I_P_OR_T,0,6,5,0,6
_cp_set_op_params p2,I_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_P_XOR_T,0,6,5,0,6
_cp_set_op_params p2,I_NOT_T,0,5,0,0,5
_cp_set_op_params p2,I_LSHIFT_P_BY_Q,0,6,5,6,0
_cp_set_op_params p2,I_ASHIFT_P_BY_Q,0,6,5,6,0
_cp_set_op_params p2,I_FSHIFT_PT_BY_Q,0,7,5,7,6
_cp_set_op_params p2,MOVE_P,0,5,5,0,0
;
;
; if we couldn't find the op_code, flag an error
;
.if _cp_op_type>=2
.err
.print "cp_build_inst_h: invalid Am29027 instruction mnemonic"
.exitm
.endif
;
; if number of parameters is incorrect, flag error
;
.if $narg!=_cp_no_params
.err
.print "cp_build_inst_h: incorrect number of parameters"
.exitm
.endif
;
; find correct value for precision field, if appropriate
;
.set _cp_prec_field,0 ; ** CORRECTION (1-4-89 <NAME>)
.if _cp_op_type==0 ; need to look for precision
.set _cp_found_precision,0
.ifeqs "@p3@","D_D"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.ifeqs "@p3@","D_S"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.ifeqs "@p3@","S_D"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.ifeqs "@p3@","S_S"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.if _cp_found_precision==0
.err
.print "cp_build_inst_h: missing precision field"
.exitm
.endif
.endif
;
; find value for destination field
;
.if _cp_op_type==0
.set _cp_dest_field_val,CP_DEST_EQ_@p4
.else
.set _cp_dest_field_val,CP_DEST_EQ_@p3
.endif
;
; find correct value for p select field
;
.if _cp_p_paramno==0
.set _cp_p_field_val,0x00000000
.endif
.if _cp_p_paramno==4
.set _cp_p_field_val,CP_P_EQ_@p4
.endif
.if _cp_p_paramno==5
.set _cp_p_field_val,CP_P_EQ_@p5
.endif
.if _cp_p_paramno==6
.set _cp_p_field_val,CP_P_EQ_@p6
.endif
.if _cp_p_paramno==7
.set _cp_p_field_val,CP_P_EQ_@p7
.endif
.ifeqs "@p2@","I_NOT_T"
.set _cp_p_field_val,CP_P_EQ_IMINUS1
.endif
;
; find correct value for q select field
;
.if _cp_q_paramno==0
.set _cp_q_field_val,0x00000000
.endif
.if _cp_q_paramno==4
.set _cp_q_field_val,CP_Q_EQ_@p4
.endif
.if _cp_q_paramno==5
.set _cp_q_field_val,CP_Q_EQ_@p5
.endif
.if _cp_q_paramno==6
.set _cp_q_field_val,CP_Q_EQ_@p6
.endif
.if _cp_q_paramno==7
.set _cp_q_field_val,CP_Q_EQ_@p7
.endif
;
; find correct value for t select field
;
.if _cp_t_paramno==0
.set _cp_t_field_val,0x00000000
.endif
.if _cp_t_paramno==4
.set _cp_t_field_val,CP_T_EQ_@p4
.endif
.if _cp_t_paramno==5
.set _cp_t_field_val,CP_T_EQ_@p5
.endif
.if _cp_t_paramno==6
.set _cp_t_field_val,CP_T_EQ_@p6
.endif
.if _cp_t_paramno==7
.set _cp_t_field_val,CP_T_EQ_@p7
.endif
;
;
.set _cp_inst_word,CP_@p2@|_cp_prec_field|_cp_dest_field_val
.set _cp_inst_word,_cp_inst_word|_cp_p_field_val
.set _cp_inst_word,_cp_inst_word|_cp_q_field_val
.set _cp_inst_word,_cp_inst_word|_cp_t_field_val
;
consth p1,_cp_inst_word
;
.endm
;
;
;
;
;============================================================================
; MACRO NAME: cp_build_inst_l
;
; WRITTEN BY: <NAME>
;
; MOST RECENT UPDATE: April 24, 1988
; : January 4, 1989 <NAME>
;
; FUNCTION: Builds a 16 LSBs of a 32-bit Am29027 instruction in an
; Am29000 g.p. register; the 16 MSBs of the register are
; set to 0..
;
; PARAMETERS:
; reg - the Am29000 g.p. register into which the instruction word
; is to be written
;
; op_code - mnemonic specifying the operation to be performed
; (e.g. FADD, P_TIMES_Q)
;
; precision - precision specification for destination, source operands:
; D_S - double-prec. result, single-prec. input(s)
; D_D - double-prec. result, double-prec. input(s)
; S_S - single-prec. result, single-prec. input(s)
; S_D - single-prec. result, double-prec. input(s)
;
; dest - destination for the operation result:
; RF0 - store result in Am29027 register file location RF0
; RF1 - store result in Am29027 register file location RF1
; RF2 - store result in Am29027 register file location RF2
; RF3 - store result in Am29027 register file location RF3
; RF4 - store result in Am29027 register file location RF4
; RF5 - store result in Am29027 register file location RF5
; RF6 - store result in Am29027 register file location RF6
; RF7 - store result in Am29027 register file location RF7
; GP - result is to be stored in an Am29000 g.p. register
; with a read_dp, read_sp, or read_int macro.
;
; source1,
; source2,
; source3 - source operand specifications:
; R - take source from Am29027 register R
; S - take source from Am29027 register S
; RF0 - take source from Am29027 register file location RF0
; RF1 - take source from Am29027 register file location RF1
; RF2 - take source from Am29027 register file location RF2
; RF3 - take source from Am29027 register file location RF3
; RF4 - take source from Am29027 register file location RF4
; RF5 - take source from Am29027 register file location RF5
; RF6 - take source from Am29027 register file location RF6
; RF7 - take source from Am29027 register file location RF7
; 0 - source is 0
; ONE_HALF - source is constant .5 (f.p. operations only)
; IMINUS1 - source is constant -1 (integer operations only)
; 1 - source is constant 1
; 2 - source is constant 2
; 3 - source is constant 3
; PI - source is constant pi (f.p. operations only)
; IMINUSMAX - source is -(2**63) (integer operations only)
;
;
; USAGE:
;
; cp_build_inst_l reg,op_code,[precision,]dest,source1[,source2][,source3]
;
; This macro is similar to cp_build_inst, but creates only the 16 LSBs
; of the 32-bit Am29027 instruction word; the 16 MSBs of the target
; register are set to 0. This macro is useful in cases
; where it is helpful to specify instruction LSBs and MSBs separately,
; to improve instruction scheduling.
;
; Syntax and usage are identical to that of cp_build_inst.
;
; NOTE: This macro references macro _cp_set_op_params, which appears
; in the assembly listing for macro _cp_build_inst.
;
;
;============================================================================
;
.macro cp_build_inst_l,p1,p2,p3,p4,p5,p6,p7
;
.if $narg<=3
.err
.print "cp_build_inst_h: missing parameter(s)"
.exitm
.endif
;
; classify operation type
;
.set _cp_op_type,255
_cp_set_op_params p2,FADD,1,5,4,0,5
_cp_set_op_params p2,DADD,1,5,4,0,5
_cp_set_op_params p2,FSUB,1,5,4,0,5
_cp_set_op_params p2,DSUB,1,5,4,0,5
_cp_set_op_params p2,FMUL,1,5,4,5,0
_cp_set_op_params p2,DMUL,1,5,4,5,0
_cp_set_op_params p2,FEQ,1,5,4,0,5
_cp_set_op_params p2,DEQ,1,5,4,0,5
_cp_set_op_params p2,FGE,1,5,4,0,5
_cp_set_op_params p2,DGE,1,5,4,0,5
_cp_set_op_params p2,FGT,1,5,4,0,5
_cp_set_op_params p2,DGT,1,5,4,0,5
_cp_set_op_params p2,CONVERT_I_TO_F,1,4,0,0,4
_cp_set_op_params p2,CONVERT_I_TO_D,1,4,0,0,4
_cp_set_op_params p2,CONVERT_F_TO_I,1,4,0,0,4
_cp_set_op_params p2,CONVERT_D_TO_I,1,4,0,0,4
;
; The next two lines were corrected on 1-4-89, <NAME>
;
_cp_set_op_params p2,CONVERT_F_TO_D,1,4,4,0,0
_cp_set_op_params p2,CONVERT_D_TO_F,1,4,4,0,0
;
_cp_set_op_params p2,PASS_P,0,5,5,0,0
_cp_set_op_params p2,MINUSP,0,5,5,0,0
_cp_set_op_params p2,ABSP,0,5,5,0,0
_cp_set_op_params p2,SIGNT_TIMES_ABSP,0,6,6,0,5
_cp_set_op_params p2,P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,MINUSP_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,MINUSP_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,ABS_P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,ABS_P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,ABSP_PLUS_ABST,0,6,5,0,6
_cp_set_op_params p2,ABSP_MINUS_ABST,0,6,5,0,6
_cp_set_op_params p2,ABS_ABSP_MINUS_ABST,0,6,5,0,6
_cp_set_op_params p2,P_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,MINUSP_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,ABS_P_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,COMPARE_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,MAX_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,MAX_ABSP_AND_ABST,0,6,5,0,6
_cp_set_op_params p2,MIN_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,MIN_ABSP_AND_ABST,0,6,5,0,6
_cp_set_op_params p2,LIMIT_P_TO_MAGT,0,6,5,0,6
_cp_set_op_params p2,CONVERT_T_TO_INT,0,5,0,0,5
_cp_set_op_params p2,SCALE_T_TO_INT_BY_Q,0,6,0,6,5
_cp_set_op_params p2,PQ_PLUS_T,0,7,5,6,7
_cp_set_op_params p2,MINUSPQ_PLUS_T,0,7,5,6,7
_cp_set_op_params p2,PQ_MINUS_T,0,7,5,6,7
_cp_set_op_params p2,MINUSPQ_MINUS_T,0,7,5,6,7
_cp_set_op_params p2,ABSPQ_PLUS_ABST,0,7,5,6,7
_cp_set_op_params p2,MINUSABSPQ_PLUS_ABST,0,7,5,6,7
_cp_set_op_params p2,ABSPQ_MINUS_ABST,0,7,5,6,7
_cp_set_op_params p2,ROUND_T_TO_INT,0,5,0,0,5
_cp_set_op_params p2,RECIPROCAL_OF_P,0,5,5,0,0
_cp_set_op_params p2,CONVERT_T_TO_ALT,0,5,0,0,5
_cp_set_op_params p2,CONVERT_T_FROM_ALT,0,5,0,0,5
_cp_set_op_params p2,I_PASS_P,0,5,5,0,0
_cp_set_op_params p2,I_MINUSP,0,5,5,0,0
_cp_set_op_params p2,I_ABSP,0,5,5,0,0
_cp_set_op_params p2,I_SIGNT_TIMES_ABSP,0,6,6,0,5
_cp_set_op_params p2,I_P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,I_P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,I_MINUSP_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,I_ABS_P_PLUS_T,0,6,5,0,6
_cp_set_op_params p2,I_ABS_P_MINUS_T,0,6,5,0,6
_cp_set_op_params p2,I_P_TIMES_Q,0,6,5,6,0
_cp_set_op_params p2,I_COMPARE_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_MAX_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_MIN_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_CONVERT_T_TO_FLOAT,0,5,0,0,5
_cp_set_op_params p2,I_SCALE_T_TO_FLOAT_BY_Q,0,6,0,6,5
_cp_set_op_params p2,I_P_OR_T,0,6,5,0,6
_cp_set_op_params p2,I_P_AND_T,0,6,5,0,6
_cp_set_op_params p2,I_P_XOR_T,0,6,5,0,6
_cp_set_op_params p2,I_NOT_T,0,5,0,0,5
_cp_set_op_params p2,I_LSHIFT_P_BY_Q,0,6,5,6,0
_cp_set_op_params p2,I_ASHIFT_P_BY_Q,0,6,5,6,0
_cp_set_op_params p2,I_FSHIFT_PT_BY_Q,0,7,5,7,6
_cp_set_op_params p2,MOVE_P,0,5,5,0,0
;
;
; if we couldn't find the op_code, flag an error
;
.if _cp_op_type>=2
.err
.print "cp_build_inst_h: invalid Am29027 instruction mnemonic"
.exitm
.endif
;
; if number of parameters is incorrect, flag error
;
.if $narg!=_cp_no_params
.err
.print "cp_build_inst_h: incorrect number of parameters"
.exitm
.endif
;
; find correct value for precision field, if appropriate
;
.set _cp_prec_field,0 ; CORRECTION (1-4-89 <NAME>)
.if _cp_op_type==0 ; need to look for precision
.set _cp_found_precision,0
.ifeqs "@p3@","D_D"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.ifeqs "@p3@","D_S"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.ifeqs "@p3@","S_D"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.ifeqs "@p3@","S_S"
.set _cp_prec_field,CP_@p3
.set _cp_found_precision,1
.endif
.if _cp_found_precision==0
.err
.print "cp_build_inst_h: missing precision field"
.exitm
.endif
.endif
;
; find value for destination field
;
.if _cp_op_type==0
.set _cp_dest_field_val,CP_DEST_EQ_@p4
.else
.set _cp_dest_field_val,CP_DEST_EQ_@p3
.endif
;
; find correct value for p select field
;
.if _cp_p_paramno==0
.set _cp_p_field_val,0x00000000
.endif
.if _cp_p_paramno==4
.set _cp_p_field_val,CP_P_EQ_@p4
.endif
.if _cp_p_paramno==5
.set _cp_p_field_val,CP_P_EQ_@p5
.endif
.if _cp_p_paramno==6
.set _cp_p_field_val,CP_P_EQ_@p6
.endif
.if _cp_p_paramno==7
.set _cp_p_field_val,CP_P_EQ_@p7
.endif
.ifeqs "@p2@","I_NOT_T"
.set _cp_p_field_val,CP_P_EQ_IMINUS1
.endif
;
; find correct value for q select field
;
.if _cp_q_paramno==0
.set _cp_q_field_val,0x00000000
.endif
.if _cp_q_paramno==4
.set _cp_q_field_val,CP_Q_EQ_@p4
.endif
.if _cp_q_paramno==5
.set _cp_q_field_val,CP_Q_EQ_@p5
.endif
.if _cp_q_paramno==6
.set _cp_q_field_val,CP_Q_EQ_@p6
.endif
.if _cp_q_paramno==7
.set _cp_q_field_val,CP_Q_EQ_@p7
.endif
;
; find correct value for t select field
;
.if _cp_t_paramno==0
.set _cp_t_field_val,0x00000000
.endif
.if _cp_t_paramno==4
.set _cp_t_field_val,CP_T_EQ_@p4
.endif
.if _cp_t_paramno==5
.set _cp_t_field_val,CP_T_EQ_@p5
.endif
.if _cp_t_paramno==6
.set _cp_t_field_val,CP_T_EQ_@p6
.endif
.if _cp_t_paramno==7
.set _cp_t_field_val,CP_T_EQ_@p7
.endif
;
;
.set _cp_inst_word,CP_@p2@|_cp_prec_field|_cp_dest_field_val
.set _cp_inst_word,_cp_inst_word|_cp_p_field_val
.set _cp_inst_word,_cp_inst_word|_cp_q_field_val
.set _cp_inst_word,_cp_inst_word|_cp_t_field_val
;
const p1,_cp_inst_word
;
.endm
;
; end of file fpsymbol.h
| 53,370 |
2,399 | <reponame>allran/SJVideoPlayer
//
// SJViewControllerObserver.h
// SJUIKit_Example
//
// Created by 畅三江 on 2018/12/23.
// Copyright © 2018 <EMAIL>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "SJBaseProtocols.h"
NS_ASSUME_NONNULL_BEGIN
@interface SJAppearStateObserver : NSObject<SJAppearStateObserver>
@end
NS_ASSUME_NONNULL_END
| 145 |
1,623 | /* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2014 <NAME>
*
* 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.
*/
#pragma once
#include <pangolin/geometry/geometry.h>
#include <pangolin/gl/gl.h>
#include <pangolin/gl/glsl.h>
namespace pangolin {
struct GlGeometry
{
GlGeometry() = default;
GlGeometry(GlGeometry&&) = default;
GlGeometry& operator=(GlGeometry&&) = default;
struct Element : public GlBufferData
{
Element() = default;
Element(Element&&) = default;
Element& operator=(Element&&) = default;
Element(GlBufferType buffer_type, size_t size_bytes, GLenum gluse, uint8_t* data)
: GlBufferData(buffer_type, size_bytes, gluse, data)
{}
inline bool HasAttribute(const std::string& name) const {
return attributes.find(name) != attributes.end();
}
struct Attribute {
// Stuff needed by glVertexAttribPointer
GLenum gltype;
size_t count_per_element;
size_t num_elements;
size_t offset;
size_t stride_bytes;
};
std::map<std::string, Attribute> attributes;
};
inline bool HasAttribute(const std::string& name) const
{
for(const auto& b : buffers) if(b.second.HasAttribute(name)) return true;
return false;
}
// Store vertices and attributes
std::map<std::string, Element> buffers;
// Stores index buffers for each sub-object
std::multimap<std::string, Element> objects;
// Stores pixmaps
std::map<std::string, GlTexture> textures;
};
GlGeometry::Element ToGlGeometry(const Geometry::Element& el, GlBufferType buffertype);
GlGeometry ToGlGeometry(const Geometry& geom);
void GlDraw(GlSlProgram& prog, const GlGeometry& geom, const GlTexture *matcap);
}
| 1,020 |
338 | <filename>ants/utils/label_image_centroids.py
__all__ = ['label_image_centroids']
import numpy as np
from ..core import ants_transform as tio
def label_image_centroids(image, physical=False, convex=True, verbose=False):
"""
Converts a label image to coordinates summarizing their positions
ANTsR function: `labelImageCentroids`
Arguments
---------
image : ANTsImage
image of integer labels
physical : boolean
whether you want physical space coordinates or not
convex : boolean
if True, return centroid
if False return point with min average distance to other points with same label
Returns
-------
dictionary w/ following key-value pairs:
`labels` : 1D-ndarray
array of label values
`vertices` : pd.DataFrame
coordinates of label centroids
Example
-------
>>> import ants
>>> import numpy as np
>>> image = ants.from_numpy(np.asarray([[[0,2],[1,3]],[[4,6],[5,7]]]).astype('float32'))
>>> labels = ants.label_image_centroids(image)
"""
d = image.shape
if len(d) != 3:
raise ValueError('image must be 3 dimensions')
xcoords = np.asarray(np.arange(d[0]).tolist()*(d[1]*d[2]))
ycoords = np.asarray(np.repeat(np.arange(d[1]),d[0]).tolist()*d[2])
zcoords = np.asarray(np.repeat(np.arange(d[1]), d[0]*d[2]))
labels = image.numpy()
mylabels = np.sort(np.unique(labels[labels > 0])).astype('int')
n_labels = len(mylabels)
xc = np.zeros(n_labels)
yc = np.zeros(n_labels)
zc = np.zeros(n_labels)
if convex:
for i in mylabels:
idx = (labels == i).flatten()
xc[i-1] = np.mean(xcoords[idx])
yc[i-1] = np.mean(ycoords[idx])
zc[i-1] = np.mean(zcoords[idx])
else:
for i in mylabels:
idx = (labels == i).flatten()
xci = xcoords[idx]
yci = ycoords[idx]
zci = zcoords[idx]
dist = np.zeros(len(xci))
for j in range(len(xci)):
dist[j] = np.mean(np.sqrt((xci[j] - xci)**2 + (yci[j] - yci)**2 + (zci[j] - zci)**2))
mid = np.where(dist==np.min(dist))
xc[i-1] = xci[mid]
yc[i-1] = yci[mid]
zc[i-1] = zci[mid]
centroids = np.vstack([xc,yc,zc]).T
#if physical:
# centroids = tio.transform_index_to_physical_point(image, centroids)
return {
'labels': mylabels,
'vertices': centroids
}
| 1,249 |
1,223 | /*
Copyright 2016 Nidium Inc. All rights reserved.
Use of this source code is governed by a MIT license
that can be found in the LICENSE file.
*/
#include <jni.h>
#include <string>
#include "Core/Context.h"
#include "ape_netlib.h"
#include "AndroidUIInterface.h"
#include "System.h"
#include <SDL.h>
#define LOG_TAG __FILE__ ":"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,__VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
unsigned long _ape_seed;
namespace Nidium {
namespace Interface {
SystemInterface *SystemInterface::_interface = nullptr;
UIInterface *__NidiumUI;
}
}
using namespace Nidium::Interface;
// Entry point called by SDL
int main(int argc, char **argv)
{
AndroidUIInterface UI;
__NidiumUI = &UI;
_ape_seed = time(NULL) ^ (getpid() << 16);
const char *nml = NULL;
LOGD("argc=%d\n", argc);
for (int i = 0; i < argc; i++) {
LOGD("%s", argv[i]);
}
nml = argc > 1 ? argv[1] : "embed://default.nml";
LOGD("Loading argument %s\n", nml);
UI.setArguments(argc, argv);
if (!UI.runApplication(nml)) {
LOGE("Failed to run nidium application");
return 0;
}
UI.runLoop();
return 0;
}
| 553 |
2,816 | //===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/execution/operator/helper/physical_explain_analyze.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/execution/physical_operator.hpp"
#include "duckdb/planner/expression.hpp"
namespace duckdb {
class PhysicalExplainAnalyze : public PhysicalOperator {
public:
PhysicalExplainAnalyze(vector<LogicalType> types)
: PhysicalOperator(PhysicalOperatorType::EXPLAIN_ANALYZE, move(types), 1) {
}
public:
// Source interface
unique_ptr<GlobalSourceState> GetGlobalSourceState(ClientContext &context) const override;
void GetData(ExecutionContext &context, DataChunk &chunk, GlobalSourceState &gstate,
LocalSourceState &lstate) const override;
public:
// Sink Interface
SinkResultType Sink(ExecutionContext &context, GlobalSinkState &state, LocalSinkState &lstate,
DataChunk &input) const override;
SinkFinalizeType Finalize(Pipeline &pipeline, Event &event, ClientContext &context,
GlobalSinkState &gstate) const override;
unique_ptr<GlobalSinkState> GetGlobalSinkState(ClientContext &context) const override;
bool IsSink() const override {
return true;
}
bool ParallelSink() const override {
return true;
}
};
} // namespace duckdb
| 476 |
301 | package commons.model.gateway;
public class Measure {
private String capabilityAlternateId;
private Object[][] measures;
private String sensorAlternateId;
public String getCapabilityAlternateId() {
return capabilityAlternateId;
}
public void setCapabilityAlternateId(String capabilityAlternateId) {
this.capabilityAlternateId = capabilityAlternateId;
}
public Object[][] getMeasures() {
return measures;
}
public void setMeasures(Object[][] measures) {
this.measures = measures;
}
public String getSensorAlternateId() {
return sensorAlternateId;
}
public void setSensorAlternateId(String sensorAlternateId) {
this.sensorAlternateId = sensorAlternateId;
}
}
| 213 |
10,364 | <reponame>equinux/CocoaPods
#import "Bar/Bar.h"
| 25 |
724 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import inspect
from TestDataMani import TestDataMani
from TestDataAug import TestDataAug
almost_current = os.path.abspath(inspect.getfile(inspect.currentframe()))
currentdir = os.path.dirname(almost_current)
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
from util import run_test # noqa
def main():
run_test(TestDataMani)
run_test(TestDataAug)
if __name__ == "__main__":
main()
| 190 |
619 | <reponame>ligurio/mull
void void_sum(int a, int b, int *result) {
*result = a + b;
}
int sum(int a, int b) {
int result = 0;
void_sum(a, b, &result);
return result;
}
int main() {
return ! (sum(2, 3) == 5);
}
// clang-format off
/**
RUN: cd / && %CLANG_EXEC -fembed-bitcode -g %s -o %s.exe
RUN: cd %CURRENT_DIR
RUN: sed -e "s:%PWD:%S:g" %S/compile_commands.json.template > %S/compile_commands.json
RUN: (unset TERM; %MULL_EXEC -linker=%clang_cxx -debug -mutators=cxx_remove_void_call -reporters=IDE -reporters=Elements --report-dir=%S/Output --report-name=sample -ide-reporter-show-killed -compdb-path %S/compile_commands.json %s.exe 2>&1; test $? = 0) | %FILECHECK_EXEC %s --dump-input=fail --strict-whitespace --match-full-lines
RUN: [[ -f %S/Output/sample.json ]]
RUN: cat %S/Output/sample.json | filecheck %s --check-prefix=CHECK-JSON
CHECK-JSON: "mutants": [{"id": "cxx_remove_void_call", "location": {"end": {"column": 26, "line": 6}, "start": {"column": 3, "line": 6}}, "mutatorName": "Removed the call to the function", "replacement": "", "status": "Killed"}]
CHECK:[info] Killed mutants (1/1):
CHECK:{{^.*}}sample.cpp:6:3: warning: Killed: Removed the call to the function [cxx_remove_void_call]
CHECK: void_sum(a, b, &result);
CHECK: ^
CHECK:[info] Mutation score: 100%
CHECK:[info] Total execution time: {{.*}}
CHECK-EMPTY:
**/
| 550 |
348 | {"nom":"Pineuilh","circ":"10ème circonscription","dpt":"Gironde","inscrits":3037,"abs":1327,"votants":1710,"blancs":18,"nuls":22,"exp":1670,"res":[{"nuance":"LR","nom":"<NAME>","voix":580},{"nuance":"REM","nom":"M. <NAME>","voix":524},{"nuance":"FN","nom":"Mme <NAME>","voix":234},{"nuance":"FI","nom":"Mme <NAME>","voix":186},{"nuance":"ECO","nom":"Mme <NAME>","voix":42},{"nuance":"SOC","nom":"M. <NAME>","voix":41},{"nuance":"UDI","nom":"M. <NAME>","voix":23},{"nuance":"DIV","nom":"Mme <NAME>","voix":19},{"nuance":"DLF","nom":"M. <NAME>","voix":11},{"nuance":"EXG","nom":"Mme <NAME>","voix":5},{"nuance":"DIV","nom":"Mme <NAME>","voix":5}]} | 264 |
405 | package weixin.guanjia.core.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import org.apache.log4j.Logger;
import com.baidu.inf.iis.bcs.BaiduBCS;
import com.baidu.inf.iis.bcs.auth.BCSCredentials;
import com.baidu.inf.iis.bcs.model.BucketSummary;
import com.baidu.inf.iis.bcs.model.DownloadObject;
import com.baidu.inf.iis.bcs.model.ObjectListing;
import com.baidu.inf.iis.bcs.model.ObjectMetadata;
import com.baidu.inf.iis.bcs.model.ObjectSummary;
import com.baidu.inf.iis.bcs.request.GetObjectRequest;
import com.baidu.inf.iis.bcs.request.ListBucketRequest;
import com.baidu.inf.iis.bcs.request.ListObjectRequest;
import com.baidu.inf.iis.bcs.request.PutObjectRequest;
import com.baidu.inf.iis.bcs.response.BaiduBCSResponse;
public class BCSUtil {
private static final Logger log = Logger.getLogger(BCSUtil.class);
private static String host = "bcs.duapp.com";
private static BCSCredentials credentials;// 开发者信息
private static BaiduBCS baiduBCS;// 百度云服务
/**
* TODO 将文件上传到云存储
*
* @param accessKey
* 百度APP提供
* @param secretKey
* 百度APP提供
* @param uploadFile
* 上传文件
* @param bucket
* 上传到云存储的bucket名称
* @param object
* 上传文件路径,包括扩展名,默认路径要在第一位补"/"
* @throws FileNotFoundException
*/
public static void putObjectByInputStream(String accessKey,
String secretKey, File uploadFile, String bucket, String object)
throws FileNotFoundException {
credentials = new BCSCredentials(accessKey, secretKey);
baiduBCS = new BaiduBCS(credentials, host);
// baiduBCS.setDefaultEncoding("GBK");
baiduBCS.setDefaultEncoding("UTF-8"); // Default UTF-8
InputStream fileContent = new FileInputStream(uploadFile);
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType("text/html");
objectMetadata.setContentLength(uploadFile.length());
PutObjectRequest request = new PutObjectRequest(bucket, object,
fileContent, objectMetadata);
ObjectMetadata result = baiduBCS.putObject(request).getResult();
log.info(result);
}
/**
* TODO 获取bucket列表
*
* @param accessKey
* @param secretKey
* @return
*/
public static List<BucketSummary> listBucket(String accessKey,
String secretKey) {
credentials = new BCSCredentials(accessKey, secretKey);
baiduBCS = new BaiduBCS(credentials, host);
ListBucketRequest listBucketRequest = new ListBucketRequest();
BaiduBCSResponse<List<BucketSummary>> response = baiduBCS
.listBucket(listBucketRequest);
for (BucketSummary bucket : response.getResult()) {
log.info(bucket);
}
return response.getResult();
}
/**
* TODO 通过bucket模拟分页获取云存储文件列表
*
* @param accessKey
* @param secretKey
* @param bucket
* bucket名称
* @param start
* 起始位置
* @param limit
* 数量限制
* @return 文件列表
*/
public static List<ObjectSummary> listObject(String accessKey,
String secretKey, String bucket, int start, int limit) {
credentials = new BCSCredentials(accessKey, secretKey);
baiduBCS = new BaiduBCS(credentials, host);
ListObjectRequest listObjectRequest = new ListObjectRequest(bucket);
listObjectRequest.setStart(start);
listObjectRequest.setLimit(limit);
// ------------------by dir
{
// prefix must start with '/' and end with '/'
// listObjectRequest.setPrefix("/1/");
// listObjectRequest.setListModel(2);
}
// ------------------only object
{
// prefix must start with '/'
// listObjectRequest.setPrefix("/1/");
}
BaiduBCSResponse<ObjectListing> response = baiduBCS
.listObject(listObjectRequest);
return response.getResult().getObjectSummaries();
}
/**
* TODO 获取云存储的全部信息
*
* @param accessKey
* 开发者信息
* @param secretKey
* 开发者信息
* @param bucket
* 云存储bucket名称
* @return 文件列表
*/
public static List<ObjectSummary> listObject(String accessKey,
String secretKey, String bucket) {
credentials = new BCSCredentials(accessKey, secretKey);
baiduBCS = new BaiduBCS(credentials, host);
ListObjectRequest listObjectRequest = new ListObjectRequest(bucket);
BaiduBCSResponse<ObjectListing> response = baiduBCS
.listObject(listObjectRequest);
return response.getResult().getObjectSummaries();
}
public static InputStream getObject(String accessKey, String secretKey,
String bucket, String object) {
credentials = new BCSCredentials(accessKey, secretKey);
baiduBCS = new BaiduBCS(credentials, host);
GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, object);
BaiduBCSResponse<DownloadObject> baiduBCSResponse = baiduBCS
.getObject(getObjectRequest);
InputStream in = baiduBCSResponse.getResult().getContent();
return in;
}
/**
* TODO 删除文件
*
* @param accessKey
* @param secretKey
* @param bucket
* @param object
*/
public static void deleteObject(String accessKey, String secretKey,
String bucket, String object) {
credentials = new BCSCredentials(accessKey, secretKey);
baiduBCS = new BaiduBCS(credentials, host);
com.baidu.inf.iis.bcs.model.Empty result = baiduBCS.deleteObject(bucket, object).getResult();
log.info(result);
}
/**
* TODO 上传文件
*
* @param accessKey
* @param secretKey
* @param uploadFile
* 上传的文件
* @param bucket
* bucket名称
* @param object
*/
public static void putObjectByFile(String accessKey, String secretKey,
File uploadFile, String bucket, String object) {
credentials = new BCSCredentials(accessKey, secretKey);
baiduBCS = new BaiduBCS(credentials, host);
PutObjectRequest request = new PutObjectRequest(bucket, object,
uploadFile);
ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentType("text/html");
request.setMetadata(metadata);
BaiduBCSResponse<ObjectMetadata> response = baiduBCS.putObject(request);
ObjectMetadata objectMetadata = response.getResult();
log.info("x-bs-request-id: " + response.getRequestId());
log.info(objectMetadata);
}
}
| 2,533 |
608 | <gh_stars>100-1000
{
"name": "seemple-parse-form",
"version": "2.4.17",
"description": "Binds named fields of HTML5 form",
"main": "index.js",
"scripts": {
"test": "npm run cover",
"cover": "../../node_modules/.bin/babel-node ../../node_modules/.bin/babel-istanbul cover test/index.js",
"npm-compile": "babel src -d npm && cp package.json npm/package.json && cp README.md npm/README.md",
"build": "../../node_modules/.bin/webpack --mode=production"
},
"repository": {
"type": "git",
"url": "https://github.com/finom/seemple-parse-form.git"
},
"keywords": [
"seemplejs",
"codemirror"
],
"author": "<NAME>",
"license": "MIT",
"bugs": {
"url": "https://github.com/finom/seemple-parse-form/issues"
},
"homepage": "https://github.com/finom/seemple-parse-form#readme",
"peerDependencies": {
"seemple": "2.x"
},
"dependencies": {
"balajs": "^1.0.7"
},
"gitHead": "73cc162ade078967f510f052ee94a782a807a8af"
}
| 430 |
578 | <reponame>llitfkitfk/bk-job
/*
* Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-JOB蓝鲸智云作业平台 is licensed under the MIT License.
*
* License for BK-JOB蓝鲸智云作业平台:
* --------------------------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package com.tencent.bk.job.execute.engine.model;
import com.tencent.bk.job.common.constant.TaskVariableTypeEnum;
import lombok.Getter;
import lombok.ToString;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/*
*全局变量分析结果
*/
@Getter
@ToString
public class TaskVariablesAnalyzeResult {
private List<TaskVariableDTO> taskVars;
private boolean existAnyVar = false; //作业中是否存在变量
private boolean existOnlyConstVar = true; //作业中是否仅存在常量
private boolean existNamespaceVar = false; //是否存在命名空间变量
private boolean existChangeableGlobalVar = false; //是否存在可赋值全局变量
private List<String> allVarNames = new ArrayList<>(); // 所有变量列表
private List<String> constVarNames = new ArrayList<>(); // 常量列表
private List<String> namespaceVarNames = new ArrayList<>(); // 命名空间变量列表
private List<String> changeableGlobalVarNames = new ArrayList<>(); // 赋值可变变量列表
public TaskVariablesAnalyzeResult(List<TaskVariableDTO> taskVars) {
if (CollectionUtils.isEmpty(taskVars)) {
return;
}
this.taskVars = taskVars;
this.existAnyVar = true;
for (TaskVariableDTO taskVar : taskVars) {
if (taskVar.isChangeable()) {
existOnlyConstVar = false;
existChangeableGlobalVar = true;
changeableGlobalVarNames.add(taskVar.getName());
if (taskVar.getType() == TaskVariableTypeEnum.NAMESPACE.getType()) {
existNamespaceVar = true;
namespaceVarNames.add(taskVar.getName());
}
} else {
constVarNames.add(taskVar.getName());
}
}
if (!changeableGlobalVarNames.isEmpty()) {
changeableGlobalVarNames.sort(String.CASE_INSENSITIVE_ORDER);
}
if (!namespaceVarNames.isEmpty()) {
namespaceVarNames.sort(String.CASE_INSENSITIVE_ORDER);
}
allVarNames.addAll(changeableGlobalVarNames);
allVarNames.addAll(namespaceVarNames);
allVarNames.addAll(constVarNames);
}
public boolean isNamespaceVar(String varName) {
return namespaceVarNames.contains(varName);
}
public boolean isChangeableGlobalVar(String varName) {
return changeableGlobalVarNames.contains(varName);
}
public boolean isConstVar(String varName) {
return constVarNames.contains(varName);
}
public TaskVariableDTO getTaskVarByVarName(String varName) {
for (TaskVariableDTO taskVar : taskVars) {
if (taskVar.getName().equals(varName)) {
return taskVar;
}
}
return null;
}
public boolean isExistConstVar() {
return !constVarNames.isEmpty();
}
}
| 1,723 |
14,668 | // 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.
#ifndef COMPONENTS_DOM_DISTILLER_CORE_ARTICLE_ENTRY_H_
#define COMPONENTS_DOM_DISTILLER_CORE_ARTICLE_ENTRY_H_
#include <string>
#include <vector>
#include "url/gurl.h"
namespace dom_distiller {
struct ArticleEntry {
ArticleEntry();
ArticleEntry(const ArticleEntry&);
~ArticleEntry();
std::string entry_id;
std::string title;
std::vector<GURL> pages;
};
// A valid entry has a non-empty entry_id and all its pages have a valid URL.
bool IsEntryValid(const ArticleEntry& entry);
} // namespace dom_distiller
#endif // COMPONENTS_DOM_DISTILLER_CORE_ARTICLE_ENTRY_H_
| 257 |
343 | <reponame>nzeh/syzygy<filename>syzygy/common/align_unittest.cc
// Copyright 2011 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.
#include "syzygy/common/align.h"
#include "gtest/gtest.h"
namespace common {
TEST(AlignTest, IsPowerOfTwo) {
EXPECT_FALSE(IsPowerOfTwo(0));
EXPECT_TRUE(IsPowerOfTwo(1));
EXPECT_TRUE(IsPowerOfTwo(2));
EXPECT_FALSE(IsPowerOfTwo(3));
EXPECT_TRUE(IsPowerOfTwo(4));
EXPECT_TRUE(IsPowerOfTwo(0x80000000));
EXPECT_FALSE(IsPowerOfTwo(0x80000001U));
EXPECT_TRUE(IsPowerOfTwo(reinterpret_cast<uint16_t*>(0x40000000U)));
EXPECT_FALSE(IsPowerOfTwo(reinterpret_cast<uint16_t*>(0x40000001U)));
}
TEST(AlignTest, AlignUp) {
// Try power of two alignments.
EXPECT_EQ(0, AlignUp(0, 1));
EXPECT_EQ(1, AlignUp(1, 1));
EXPECT_EQ(0, AlignUp(0, 2));
EXPECT_EQ(2, AlignUp(1, 2));
EXPECT_EQ(0x8000000, AlignUp(3, 0x8000000));
EXPECT_EQ(0x8000000, AlignUp(0x8000000, 0x8000000));
EXPECT_EQ(reinterpret_cast<void*>(0x40000000U),
AlignUp(reinterpret_cast<void*>(0x40000000U), 4));
// And non-power of two alignments.
EXPECT_EQ(0, AlignUp(0, 3));
EXPECT_EQ(3, AlignUp(1, 3));
EXPECT_EQ(0, AlignUp(0, 7));
EXPECT_EQ(7, AlignUp(1, 7));
EXPECT_EQ(0, AlignUp(0, 0x8000123));
EXPECT_EQ(0x8000123, AlignUp(3, 0x8000123));
EXPECT_EQ(reinterpret_cast<void*>(0x40000008U),
AlignUp(reinterpret_cast<void*>(0x40000001U), 8));
}
TEST(AlignTest, AlignDown) {
// Try power of two alignments.
EXPECT_EQ(0, AlignDown(0, 1));
EXPECT_EQ(1, AlignDown(1, 1));
EXPECT_EQ(0, AlignDown(0, 2));
EXPECT_EQ(0, AlignDown(1, 2));
EXPECT_EQ(0x8000000, AlignDown(0x8000000, 0x8000000));
EXPECT_EQ(0x8000000, AlignDown(0x8000003, 0x8000000));
EXPECT_EQ(reinterpret_cast<int32_t*>(0x40000000U),
AlignUp(reinterpret_cast<int32_t*>(0x40000000U), 4));
// And non-power of two alignments.
EXPECT_EQ(0, AlignDown(0, 3));
EXPECT_EQ(0, AlignDown(1, 3));
EXPECT_EQ(6, AlignDown(7, 3));
EXPECT_EQ(0, AlignDown(0, 7));
EXPECT_EQ(14, AlignDown(14, 7));
EXPECT_EQ(0, AlignDown(1234, 0x8000123));
EXPECT_EQ(0x8000123, AlignDown(0x8000123, 0x8000123));
EXPECT_EQ(0x8000123, AlignDown(0x8000124, 0x8000123));
EXPECT_EQ(reinterpret_cast<int32_t*>(0x40000010U),
AlignUp(reinterpret_cast<int32_t*>(0x40000001U), 16));
}
TEST(AlignTest, IsAligned) {
// Try power of two alignments.
EXPECT_TRUE(IsAligned(0, 1));
EXPECT_TRUE(IsAligned(1, 1));
EXPECT_TRUE(IsAligned(0, 2));
EXPECT_FALSE(IsAligned(1, 2));
EXPECT_TRUE(IsAligned(0x8000000, 0x8000000));
EXPECT_FALSE(IsAligned(0x8000003, 0x8000000));
EXPECT_TRUE(IsAligned(reinterpret_cast<const char*>(0x40000000U), 4));
// And non-power of two alignments.
EXPECT_TRUE(IsAligned(0, 3));
EXPECT_FALSE(IsAligned(1, 3));
EXPECT_FALSE(IsAligned(7, 3));
EXPECT_TRUE(IsAligned(3, 3));
EXPECT_TRUE(IsAligned(0, 7));
EXPECT_TRUE(IsAligned(14, 7));
EXPECT_FALSE(IsAligned(13, 7));
EXPECT_FALSE(IsAligned(1234, 0x8000123));
EXPECT_TRUE(IsAligned(0x8000123, 0x8000123));
EXPECT_FALSE(IsAligned(0x8000124, 0x8000123));
EXPECT_FALSE(IsAligned(reinterpret_cast<const char*>(0x40000001U), 4));
}
TEST(AlignTest, GetAlignment) {
const size_t max_alignment = 0x80000000;
EXPECT_EQ(max_alignment, GetAlignment(0));
// Try power of 2 values.
for (uint32_t i = 1; i < max_alignment; i <<= 1)
EXPECT_EQ(i, GetAlignment(i));
EXPECT_EQ(max_alignment, GetAlignment(max_alignment));
// Try non-power of 2 values.
EXPECT_EQ(16, GetAlignment(0x3210));
EXPECT_EQ(8, GetAlignment(0xFFF8));
EXPECT_EQ(4, GetAlignment(0xF0F4));
EXPECT_EQ(2, GetAlignment(0xF122));
EXPECT_EQ(1, GetAlignment(0xF123));
}
TEST(AlignTest, IsPowerOfTwo64) {
EXPECT_FALSE(IsPowerOfTwo64(0));
EXPECT_TRUE(IsPowerOfTwo64(1));
EXPECT_TRUE(IsPowerOfTwo64(2));
EXPECT_FALSE(IsPowerOfTwo64(3));
EXPECT_TRUE(IsPowerOfTwo64(4));
EXPECT_TRUE(IsPowerOfTwo64(0x80000000ULL));
EXPECT_FALSE(IsPowerOfTwo64(0x80000001ULL));
EXPECT_FALSE(IsPowerOfTwo64(0x123000000000ULL));
EXPECT_FALSE(IsPowerOfTwo64(0x123000000001ULL));
EXPECT_TRUE(IsPowerOfTwo64(0x100000000000ULL));
EXPECT_TRUE(IsPowerOfTwo64(0x200000000000ULL));
EXPECT_FALSE(IsPowerOfTwo64(0x100000000001ULL));
EXPECT_FALSE(IsPowerOfTwo64(0x200000000002ULL));
EXPECT_TRUE(IsPowerOfTwo64(0x8000000000000000ULL));
EXPECT_FALSE(IsPowerOfTwo64(0x8000000000000001ULL));
}
TEST(AlignTest, AlignUp64) {
// Try power of two alignments.
EXPECT_EQ(0, AlignUp64(0, 1));
EXPECT_EQ(1, AlignUp64(1, 1));
EXPECT_EQ(0, AlignUp64(0, 2));
EXPECT_EQ(2, AlignUp64(1, 2));
EXPECT_EQ(0x8000000, AlignUp64(3, 0x8000000));
EXPECT_EQ(0x8000000, AlignUp64(0x8000000, 0x8000000));
// And non-power of two alignments.
EXPECT_EQ(0, AlignUp64(0, 3));
EXPECT_EQ(3, AlignUp64(1, 3));
EXPECT_EQ(0, AlignUp64(0, 7));
EXPECT_EQ(7, AlignUp64(1, 7));
EXPECT_EQ(0, AlignUp64(0, 0x8000123));
EXPECT_EQ(0x8000123, AlignUp64(3, 0x8000123));
// Try alignments of huge values.
EXPECT_EQ(0x1000000004ULL, AlignUp64(0x1000000001ULL, 4));
EXPECT_EQ(0x1000000002ULL, AlignUp64(0x1000000001ULL, 2));
EXPECT_EQ(0x1000000001ULL, AlignUp64(0x1000000001ULL, 1));
EXPECT_EQ(0xCCCCCCCCABCDABD0ULL, AlignUp64(0xCCCCCCCCABCDABCDULL, 16));
}
TEST(AlignTest, AlignDown64) {
// Try power of two alignments.
EXPECT_EQ(0, AlignDown64(0, 1));
EXPECT_EQ(1, AlignDown64(1, 1));
EXPECT_EQ(0, AlignDown64(0, 2));
EXPECT_EQ(0, AlignDown64(1, 2));
EXPECT_EQ(0x8000000, AlignDown64(0x8000000, 0x8000000));
EXPECT_EQ(0x8000000, AlignDown64(0x8000003, 0x8000000));
// And non-power of two alignments.
EXPECT_EQ(0, AlignDown64(0, 3));
EXPECT_EQ(0, AlignDown64(1, 3));
EXPECT_EQ(6, AlignDown64(7, 3));
EXPECT_EQ(0, AlignDown64(0, 7));
EXPECT_EQ(14, AlignDown64(14, 7));
EXPECT_EQ(0, AlignDown64(1234, 0x8000123));
EXPECT_EQ(0x8000123, AlignDown64(0x8000123, 0x8000123));
EXPECT_EQ(0x8000123, AlignDown64(0x8000124, 0x8000123));
// Try alignments of huge values.
EXPECT_EQ(0x1000000000ULL, AlignDown64(0x1000000001ULL, 4));
EXPECT_EQ(0x1000000000ULL, AlignDown64(0x1000000001ULL, 2));
EXPECT_EQ(0x1000000001ULL, AlignDown64(0x1000000001ULL, 1));
EXPECT_EQ(0xCCCCCCCCABCDABC0ULL, AlignDown64(0xCCCCCCCCABCDABCDULL, 16));
}
TEST(AlignTest, IsAligned64) {
// Try power of two alignments.
EXPECT_TRUE(IsAligned64(0, 1));
EXPECT_TRUE(IsAligned64(1, 1));
EXPECT_TRUE(IsAligned64(0, 2));
EXPECT_FALSE(IsAligned64(1, 2));
EXPECT_TRUE(IsAligned64(0x8000000, 0x8000000));
EXPECT_FALSE(IsAligned64(0x8000003, 0x8000000));
// And non-power of two alignments.
EXPECT_TRUE(IsAligned64(0, 3));
EXPECT_FALSE(IsAligned64(1, 3));
EXPECT_FALSE(IsAligned64(7, 3));
EXPECT_TRUE(IsAligned64(3, 3));
EXPECT_TRUE(IsAligned64(0, 7));
EXPECT_TRUE(IsAligned64(14, 7));
EXPECT_FALSE(IsAligned64(13, 7));
EXPECT_FALSE(IsAligned64(1234, 0x8000123));
EXPECT_TRUE(IsAligned64(0x8000123, 0x8000123));
EXPECT_FALSE(IsAligned64(0x8000124, 0x8000123));
// Try alignments of huge values.
EXPECT_FALSE(IsAligned64(0x1000000001ULL, 4));
EXPECT_FALSE(IsAligned64(0x1000000001ULL, 2));
EXPECT_TRUE(IsAligned64(0x1000000002ULL, 2));
EXPECT_TRUE(IsAligned64(0x1000000001ULL, 1));
EXPECT_FALSE(IsAligned64(0xCCCCCCCCABCDABCDULL, 16));
EXPECT_TRUE(IsAligned64(0xCCCCCCCCABCDABC0ULL, 16));
}
TEST(AlignTest, GetAlignment64) {
const uint64_t max_alignment = 1ULL << 63;
EXPECT_EQ(max_alignment, GetAlignment64(0));
// Try power of 2 values.
for (uint64_t i = 1; i < max_alignment; i <<= 1)
EXPECT_EQ(i, GetAlignment64(i));
EXPECT_EQ(max_alignment, GetAlignment64(max_alignment));
// Try non-power of 2 values.
EXPECT_EQ(0x800000000, GetAlignment64(0x1111111800000000));
EXPECT_EQ(16, GetAlignment64(0x1111111176543210));
EXPECT_EQ(8, GetAlignment64(0x11111111FFFFFFF8));
EXPECT_EQ(4, GetAlignment64(0x11111111BCDEF0F4));
EXPECT_EQ(2, GetAlignment64(0x11111111AAAAF122));
EXPECT_EQ(1, GetAlignment64(0x111111111212F123));
}
} // namespace common
| 3,895 |
804 | package com.github.liuweijw.business.wechat.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import com.github.liuweijw.business.commons.web.jpa.JPAFactoryImpl;
import com.github.liuweijw.business.wechat.domain.AuthInfo;
import com.github.liuweijw.business.wechat.domain.QAuthInfo;
import com.github.liuweijw.business.wechat.repository.AuthInfoRepository;
import com.github.liuweijw.commons.utils.StringHelper;
/**
* 微信授权信息保存
*
* @author liuweijw
*/
@CacheConfig(cacheNames = "wechat_auth_info_")
@Component
public class AuthInfoServiceImpl extends JPAFactoryImpl implements AuthInfoService {
@Autowired
private AuthInfoRepository authInfoRepository;
@Override
@CacheEvict(key = "#authInfo.openId + '_' + #authInfo.wechatId")
public AuthInfo saveOrUpdate(AuthInfo authInfo) {
if (null == authInfo) return null;
return authInfoRepository.saveAndFlush(authInfo);
}
@Override
@Cacheable(key = "#openId + '_' + #wechatId")
public AuthInfo findByOpenIdAndWechatId(String openId, String wechatId) {
if (StringHelper.isBlank(openId) || StringHelper.isBlank(wechatId)) return null;
QAuthInfo qAuthInfo = QAuthInfo.authInfo;
return this.queryFactory.selectFrom(qAuthInfo).where(qAuthInfo.openId.eq(openId.trim()))
.where(qAuthInfo.wechatId.eq(wechatId.trim())).fetchFirst();
}
}
| 557 |
2,753 | /*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: <NAME>, <NAME>, <NAME>, <NAME>,
* <NAME>, <NAME>, <NAME>
*/
#ifndef _LINEAR_STRUCTURED_OUTPUT_MACHINE__H__
#define _LINEAR_STRUCTURED_OUTPUT_MACHINE__H__
#include <shogun/lib/config.h>
#include <shogun/machine/StructuredOutputMachine.h>
#include <shogun/lib/SGVector.h>
namespace shogun
{
class Features;
/** TODO doc */
class LinearStructuredOutputMachine : public StructuredOutputMachine
{
public:
/** default constructor */
LinearStructuredOutputMachine();
/** standard constructor
*
* @param model structured model with application specific functions
* @param labs structured labels
*/
LinearStructuredOutputMachine(std::shared_ptr<StructuredModel> model, std::shared_ptr<StructuredLabels> labs);
/** destructor */
~LinearStructuredOutputMachine() override;
/** set w (useful for modular interfaces)
*
* @param w weight vector to set
*/
void set_w(SGVector<float64_t> w);
/** get w
*
* @return w
*/
SGVector< float64_t > get_w() const;
/**
* apply structured machine to data for Structured Output (SO)
* problem
*
* @param data (test)data to be classified
*
* @return classified 'labels'
*/
std::shared_ptr<StructuredLabels> apply_structured(std::shared_ptr<Features> data = NULL) override;
/** @return object name */
const char* get_name() const override
{
return "LinearStructuredOutputMachine";
}
private:
/** register class members */
void register_parameters();
protected:
/** weight vector */
SGVector< float64_t > m_w;
}; /* class LinearStructuredOutputMachine */
} /* namespace shogun */
#endif /* _LINEAR_STRUCTURED_OUTPUT_MACHINE__H__ */
| 620 |
2,151 | <filename>chrome/browser/android/chrome_feature_list.h
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ANDROID_CHROME_FEATURE_LIST_H_
#define CHROME_BROWSER_ANDROID_CHROME_FEATURE_LIST_H_
#include <base/feature_list.h>
#include <jni.h>
namespace chrome {
namespace android {
// Alphabetical:
extern const base::Feature kAdjustWebApkInstallationSpace;
extern const base::Feature kAllowReaderForAccessibility;
extern const base::Feature kAndroidPayIntegrationV1;
extern const base::Feature kAndroidPayIntegrationV2;
extern const base::Feature kAndroidPaymentApps;
extern const base::Feature kCCTBackgroundTab;
extern const base::Feature kCCTExternalLinkHandling;
extern const base::Feature kCCTParallelRequest;
extern const base::Feature kCCTPostMessageAPI;
extern const base::Feature kCCTRedirectPreconnect;
extern const base::Feature kChromeDuplexFeature;
extern const base::Feature kChromeHomeSwipeLogic;
extern const base::Feature kChromeHomeSwipeLogicVelocity;
extern const base::Feature kChromeMemexFeature;
extern const base::Feature kChromeModernAlternateCardLayout;
extern const base::Feature kChromeModernDesign;
extern const base::Feature kChromeSmartSelection;
extern const base::Feature kCommandLineOnNonRooted;
extern const base::Feature kContentSuggestionsScrollToLoad;
extern const base::Feature kContentSuggestionsSettings;
extern const base::Feature kContentSuggestionsThumbnailDominantColor;
extern const base::Feature kContextualSearchMlTapSuppression;
extern const base::Feature kContextualSearchSecondTap;
extern const base::Feature kContextualSearchTapDisableOverride;
extern const base::Feature kCustomContextMenu;
extern const base::Feature kCustomFeedbackUi;
extern const base::Feature kDontPrefetchLibraries;
extern const base::Feature kDownloadAutoResumptionThrottling;
extern const base::Feature kDownloadProgressInfoBar;
extern const base::Feature kDownloadHomeShowStorageInfo;
extern const base::Feature kFullscreenActivity;
extern const base::Feature kHomePageButtonForceEnabled;
extern const base::Feature kHorizontalTabSwitcherAndroid;
extern const base::Feature kImprovedA2HS;
extern const base::Feature kLanguagesPreference;
extern const base::Feature kLongPressBackForHistory;
extern const base::Feature kModalPermissionDialogView;
extern const base::Feature kSearchEnginePromoExistingDevice;
extern const base::Feature kSearchEnginePromoNewDevice;
extern const base::Feature kNewPhotoPicker;
extern const base::Feature kNoCreditCardAbort;
extern const base::Feature kNTPButton;
extern const base::Feature kNTPLaunchAfterInactivity;
extern const base::Feature kNTPModernLayoutFeature;
extern const base::Feature kNTPShowGoogleGInOmniboxFeature;
extern const base::Feature kOmniboxSpareRenderer;
extern const base::Feature kOmniboxVoiceSearchAlwaysVisible;
extern const base::Feature kPayWithGoogleV1;
extern const base::Feature kProgressBarThrottleFeature;
extern const base::Feature kPwaImprovedSplashScreen;
extern const base::Feature kPwaPersistentNotification;
extern const base::Feature kQueryInOmnibox;
extern const base::Feature kReaderModeInCCT;
extern const base::Feature kSimplifiedNTP;
extern const base::Feature kSoleIntegration;
extern const base::Feature kSpannableInlineAutocomplete;
extern const base::Feature kSpecialLocaleFeature;
extern const base::Feature kSpecialLocaleWrapper;
extern const base::Feature kTabModalJsDialog;
extern const base::Feature kTabReparenting;
extern const base::Feature kTrustedWebActivity;
extern const base::Feature kUserMediaScreenCapturing;
extern const base::Feature kVideoPersistence;
extern const base::Feature kVrBrowsingFeedback;
extern const base::Feature kVrBrowsingInCustomTab;
extern const base::Feature kVrBrowsingNativeAndroidUi;
extern const base::Feature kVrBrowsingTabsView;
extern const base::Feature kWebVrAutopresentFromIntent;
extern const base::Feature kWebVrCardboardSupport;
} // namespace android
} // namespace chrome
#endif // CHROME_BROWSER_ANDROID_CHROME_FEATURE_LIST_H_
| 1,204 |
1,223 | <filename>app/src/main/java/com/sdsmdg/harjot/crollerTest/MainActivity.java
package com.sdsmdg.harjot.crollerTest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.widget.CompoundButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Croller croller;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
croller = findViewById(R.id.croller);
SwitchCompat enableSwitch = findViewById(R.id.enableSwitch);
enableSwitch.setChecked(croller.isEnabled());
// croller.setIndicatorWidth(10);
// croller.setBackCircleColor(Color.parseColor("#EDEDED"));
// croller.setMainCircleColor(Color.WHITE);
// croller.setMax(50);
// croller.setStartOffset(45);
// croller.setIsContinuous(false);
// croller.setLabelColor(Color.BLACK);
// croller.setProgressPrimaryColor(Color.parseColor("#0B3C49"));
// croller.setIndicatorColor(Color.parseColor("#0B3C49"));
// croller.setProgressSecondaryColor(Color.parseColor("#EEEEEE"));
// croller.setProgressRadius(380);
// croller.setBackCircleRadius(300);
croller.setOnCrollerChangeListener(new OnCrollerChangeListener() {
@Override
public void onProgressChanged(Croller croller, int progress) {
}
@Override
public void onStartTrackingTouch(Croller croller) {
Toast.makeText(MainActivity.this, "Start", Toast.LENGTH_SHORT).show();
}
@Override
public void onStopTrackingTouch(Croller croller) {
Toast.makeText(MainActivity.this, "Stop", Toast.LENGTH_SHORT).show();
}
});
enableSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
croller.setEnabled(true);
} else {
croller.setEnabled(false);
}
}
});
}
}
| 1,094 |
679 | <reponame>Grosskopf/openoffice<filename>main/ooxml/source/framework/JavaOOXMLParser/src/org/apache/openoffice/ooxml/parser/AcceptingStateTable.java<gh_stars>100-1000
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
package org.apache.openoffice.ooxml.parser;
import java.util.HashSet;
import java.util.Set;
/** List of all accepting states.
*
* The accepting status of states is important when a closing tag is seen.
* It denotes the end of the input stream for the state machine of the currently
* processed element. It is an error when the current state is not accepting
* when a closing tag is processed.
*/
public class AcceptingStateTable
{
public AcceptingStateTable (final Iterable<String[]> aData)
{
maAcceptingStates = new HashSet<>();
for (final String[] aLine : aData)
{
// Create new transition.
final int nStateId = Integer.parseInt(aLine[1]);
maAcceptingStates.add(nStateId);
}
}
public boolean Contains (final int nStateId)
{
return maAcceptingStates.contains(nStateId);
}
public int GetAcceptingStateCount ()
{
return maAcceptingStates.size();
}
private final Set<Integer> maAcceptingStates;
}
| 709 |
3,508 | package com.fishercoder;
import com.fishercoder.solutions._1813;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class _1813Test {
private static _1813.Solution1 solution1;
@BeforeClass
public static void setup() {
solution1 = new _1813.Solution1();
}
@Test
public void test1() {
assertEquals(false, solution1.areSentencesSimilar("of", "A lot of words"));
}
@Test
public void test2() {
assertEquals(true, solution1.areSentencesSimilar("Eating right now", "Eating"));
}
@Test
public void test3() {
assertEquals(true, solution1.areSentencesSimilar("c h p Ny", "c BDQ r h p Ny"));
}
@Test
public void test4() {
assertEquals(true, solution1.areSentencesSimilar("A", "a A b A"));
}
} | 341 |
2,984 | <reponame>ieugen/calcite
/*
* 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.calcite.adapter.druid;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.type.SqlTypeFamily;
import org.apache.calcite.sql.type.SqlTypeName;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.BaseEncoding;
import com.google.common.primitives.Chars;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;
/**
* Expression utility class to transform Calcite expressions to Druid expressions when possible.
*/
public class DruidExpressions {
/** Type mapping between Calcite SQL family types and native Druid expression
* types. */
static final Map<SqlTypeName, DruidType> EXPRESSION_TYPES;
/**
* Druid expression safe chars, must be sorted.
*/
private static final char[] SAFE_CHARS = " ,._-;:(){}[]<>!@#$%^&*`~?/".toCharArray();
static {
final ImmutableMap.Builder<SqlTypeName, DruidType> builder = ImmutableMap.builder();
for (SqlTypeName type : SqlTypeName.FRACTIONAL_TYPES) {
builder.put(type, DruidType.DOUBLE);
}
for (SqlTypeName type : SqlTypeName.INT_TYPES) {
builder.put(type, DruidType.LONG);
}
for (SqlTypeName type : SqlTypeName.STRING_TYPES) {
builder.put(type, DruidType.STRING);
}
// booleans in expressions are returned from druid as long.
// Druid will return 0 for false, non-zero value for true and null for absent value.
for (SqlTypeName type : SqlTypeName.BOOLEAN_TYPES) {
builder.put(type, DruidType.LONG);
}
// Timestamps are treated as longs (millis since the epoch) in Druid expressions.
builder.put(SqlTypeName.TIMESTAMP, DruidType.LONG);
builder.put(SqlTypeName.DATE, DruidType.LONG);
builder.put(SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE, DruidType.LONG);
builder.put(SqlTypeName.OTHER, DruidType.COMPLEX);
EXPRESSION_TYPES = builder.build();
// Safe chars must be sorted
Arrays.sort(SAFE_CHARS);
}
private DruidExpressions() {
}
/**
* Translates a Calcite {@link RexNode} to a Druid expression, if possible;
* returns null if not possible.
*
* @param rexNode RexNode to convert to a Druid Expression
* @param inputRowType Input row type of the rexNode to translate
* @param druidRel Druid query
*
* @return Druid Expression, or null when can not convert the RexNode
*/
public static @Nullable String toDruidExpression(
final RexNode rexNode,
final RelDataType inputRowType,
final DruidQuery druidRel) {
SqlKind kind = rexNode.getKind();
SqlTypeName sqlTypeName = rexNode.getType().getSqlTypeName();
if (kind == SqlKind.INPUT_REF) {
final RexInputRef ref = (RexInputRef) rexNode;
final String columnName = inputRowType.getFieldNames().get(ref.getIndex());
if (columnName == null) {
return null;
}
if (druidRel.getDruidTable().timestampFieldName.equals(columnName)) {
return DruidExpressions.fromColumn(DruidTable.DEFAULT_TIMESTAMP_COLUMN);
}
return DruidExpressions.fromColumn(columnName);
}
if (rexNode instanceof RexCall) {
final SqlOperator operator = ((RexCall) rexNode).getOperator();
final DruidSqlOperatorConverter conversion = druidRel.getOperatorConversionMap()
.get(operator);
if (conversion == null) {
//unknown operator can not translate
return null;
} else {
return conversion.toDruidExpression(rexNode, inputRowType, druidRel);
}
}
if (kind == SqlKind.LITERAL) {
// Translate literal.
if (RexLiteral.isNullLiteral(rexNode)) {
//case the filter/project might yield to unknown let Calcite deal with this for now
return null;
} else if (SqlTypeName.NUMERIC_TYPES.contains(sqlTypeName)) {
return DruidExpressions.numberLiteral((Number) RexLiteral
.value(rexNode));
} else if (SqlTypeFamily.INTERVAL_DAY_TIME == sqlTypeName.getFamily()) {
// Calcite represents DAY-TIME intervals in milliseconds.
final long milliseconds = ((Number) RexLiteral.value(rexNode)).longValue();
return DruidExpressions.numberLiteral(milliseconds);
} else if (SqlTypeFamily.INTERVAL_YEAR_MONTH == sqlTypeName.getFamily()) {
// Calcite represents YEAR-MONTH intervals in months.
final long months = ((Number) RexLiteral.value(rexNode)).longValue();
return DruidExpressions.numberLiteral(months);
} else if (SqlTypeName.STRING_TYPES.contains(sqlTypeName)) {
return
DruidExpressions.stringLiteral(RexLiteral.stringValue(rexNode));
} else if (SqlTypeName.DATE == sqlTypeName
|| SqlTypeName.TIMESTAMP == sqlTypeName
|| SqlTypeName.TIME_WITH_LOCAL_TIME_ZONE == sqlTypeName) {
return DruidExpressions.numberLiteral(
DruidDateTimeUtils.literalValue(rexNode));
} else if (SqlTypeName.BOOLEAN == sqlTypeName) {
return DruidExpressions.numberLiteral(RexLiteral.booleanValue(rexNode) ? 1 : 0);
}
}
// Not Literal/InputRef/RexCall or unknown type?
return null;
}
public static String fromColumn(String columnName) {
return DruidQuery.format("\"%s\"", columnName);
}
public static String nullLiteral() {
return "null";
}
public static String numberLiteral(final Number n) {
return n == null ? nullLiteral() : n.toString();
}
public static String stringLiteral(final String s) {
return s == null ? nullLiteral() : "'" + escape(s) + "'";
}
private static String escape(final String s) {
final StringBuilder escaped = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (Character.isLetterOrDigit(c) || Arrays.binarySearch(SAFE_CHARS, c) >= 0) {
escaped.append(c);
} else {
escaped.append("\\u").append(BaseEncoding.base16().encode(Chars.toByteArray(c)));
}
}
return escaped.toString();
}
public static String functionCall(final String functionName, final List<String> args) {
Objects.requireNonNull(functionName, "druid functionName");
Objects.requireNonNull(args, "args");
final StringBuilder builder = new StringBuilder(functionName);
builder.append("(");
for (int i = 0; i < args.size(); i++) {
int finalI = i;
final String arg = Objects.requireNonNull(args.get(i),
() -> "arg #" + finalI);
builder.append(arg);
if (i < args.size() - 1) {
builder.append(",");
}
}
builder.append(")");
return builder.toString();
}
public static String nAryOperatorCall(final String druidOperator, final List<String> args) {
Objects.requireNonNull(druidOperator, "druid operator missing");
Objects.requireNonNull(args, "args");
final StringBuilder builder = new StringBuilder();
builder.append("(");
for (int i = 0; i < args.size(); i++) {
int finalI = i;
final String arg = Objects.requireNonNull(args.get(i),
() -> "arg #" + finalI);
builder.append(arg);
if (i < args.size() - 1) {
builder.append(druidOperator);
}
}
builder.append(")");
return builder.toString();
}
/**
* Translate a list of Calcite {@code RexNode} to Druid expressions.
*
* @param rexNodes list of Calcite expressions meant to be applied on top of the rows
*
* @return list of Druid expressions in the same order as rexNodes, or null if not possible.
* If a non-null list is returned, all elements will be non-null.
*/
public static @Nullable List<String> toDruidExpressions(
final DruidQuery druidRel, final RelDataType rowType,
final List<RexNode> rexNodes) {
final List<String> retVal = new ArrayList<>(rexNodes.size());
for (RexNode rexNode : rexNodes) {
final String druidExpression = toDruidExpression(rexNode, rowType, druidRel);
if (druidExpression == null) {
return null;
}
retVal.add(druidExpression);
}
return retVal;
}
public static String applyTimestampFloor(
final String input,
final String granularity,
final String origin,
final TimeZone timeZone) {
Objects.requireNonNull(input, "input");
Objects.requireNonNull(granularity, "granularity");
return DruidExpressions.functionCall(
"timestamp_floor",
ImmutableList.of(input,
DruidExpressions.stringLiteral(granularity),
DruidExpressions.stringLiteral(origin),
DruidExpressions.stringLiteral(timeZone.getID())));
}
public static String applyTimestampCeil(
final String input,
final String granularity,
final String origin,
final TimeZone timeZone) {
Objects.requireNonNull(input, "input");
Objects.requireNonNull(granularity, "granularity");
return DruidExpressions.functionCall(
"timestamp_ceil",
ImmutableList.of(input,
DruidExpressions.stringLiteral(granularity),
DruidExpressions.stringLiteral(origin),
DruidExpressions.stringLiteral(timeZone.getID())));
}
public static String applyTimeExtract(String timeExpression, String druidUnit,
TimeZone timeZone) {
return DruidExpressions.functionCall(
"timestamp_extract",
ImmutableList.of(
timeExpression,
DruidExpressions.stringLiteral(druidUnit),
DruidExpressions.stringLiteral(timeZone.getID())));
}
}
| 3,986 |
721 | /*
* Copyright (C) 2012 Sony Mobile Communications AB
*
* This file is part of ApkAnalyser.
*
* 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 andreflect.injection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.jf.dexlib.CodeItem;
import org.jf.dexlib.DexFile;
import org.jf.dexlib.MethodIdItem;
import org.jf.dexlib.ProtoIdItem;
import org.jf.dexlib.StringIdItem;
import org.jf.dexlib.TypeIdItem;
import org.jf.dexlib.TypeListItem;
import org.jf.dexlib.Code.Instruction;
import org.jf.dexlib.Code.Opcode;
import org.jf.dexlib.Code.Format.Instruction10x;
public class ItemCreator {
public DexFile m_dex;
public MethodIdItem[] methodItems = new MethodIdItem[DebugMethod.values().length];
public HashMap<String, StringIdItem> stringItems = new HashMap<String, StringIdItem>();
public ItemCreator(DexFile dexfile) {
m_dex = dexfile;
}
public MethodIdItem prepareMethodIdItem(DebugMethod method) {
if (methodItems[method.ordinal()] == null) {
methodItems[method.ordinal()] = addMethodIdItem(method.className, method.returnName, method.params, method.methodName);
}
return methodItems[method.ordinal()];
}
public StringIdItem prepareStringIdItem(String string) {
StringIdItem stringIdItem = stringItems.get(string);
if (stringIdItem == null) {
stringIdItem = addStringIdItem(string);
stringItems.put(string, stringIdItem);
}
return addStringIdItem(string);
}
private StringIdItem addStringIdItem(String string) {
StringIdItem item = StringIdItem.lookupStringIdItem(m_dex, string);
if (item == null) {
item = StringIdItem.internStringIdItem(m_dex, string);
}
return item;
}
public TypeIdItem addTypeIdItem(String string) {
TypeIdItem item = TypeIdItem.lookupTypeIdItem(m_dex, string);
if (item == null) {
StringIdItem typeIdStringIdItem = addStringIdItem(string);
item = TypeIdItem.internTypeIdItem(m_dex, typeIdStringIdItem);
}
return item;
}
private TypeListItem addTypeListItem(String[] paramType) {
if (paramType.length == 0) {
return null;
}
List<TypeIdItem> paramTypeList = new ArrayList<TypeIdItem>();
for (String param : paramType) {
paramTypeList.add(addTypeIdItem(param));
}
TypeListItem item = TypeListItem.lookupTypeListItem(m_dex, paramTypeList);
if (item == null) {
item = TypeListItem.internTypeListItem(m_dex, paramTypeList);
}
return item;
}
public MethodIdItem addMethodIdItem(String classType, String returnType, String[] paramType, String methodName) {
TypeIdItem classTypeIdItem = addTypeIdItem(classType);
TypeIdItem returnTypeIdItem = addTypeIdItem(returnType);
TypeListItem paramTypeListItem = addTypeListItem(paramType);
ProtoIdItem protoItem = ProtoIdItem.lookupProtoIdItem(m_dex, returnTypeIdItem, paramTypeListItem);
if (protoItem == null) {
protoItem = ProtoIdItem.internProtoIdItem(m_dex, returnTypeIdItem, paramTypeListItem);
}
StringIdItem nameStringIdItem = addStringIdItem(methodName);
return MethodIdItem.internMethodIdItem(m_dex, classTypeIdItem, protoItem, nameStringIdItem);
}
public CodeItem addEmptyVirtualCodeItem() {
ArrayList<Instruction> instructions = new ArrayList<Instruction>();
instructions.add(new Instruction10x(Opcode.RETURN_VOID)); //NOT SET INJECT FLAG HERE
CodeItem item = CodeItem.internCodeItem(m_dex,
1, //registerCount
1, //inWords
0, //outWords
null, //debugInfo
instructions,
null, //tries
null); //encodedCatchHandlers
return item;
}
}
| 1,770 |
9,945 | <reponame>lukaslihotzki/synapse
# Copyright 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from synapse.storage.engines import PostgresEngine
from synapse.storage.prepare_database import get_statements
logger = logging.getLogger(__name__)
# This stream is used to notify replication slaves that some caches have
# been invalidated that they cannot infer from the other streams.
CREATE_TABLE = """
CREATE TABLE cache_invalidation_stream (
stream_id BIGINT,
cache_func TEXT,
keys TEXT[],
invalidation_ts BIGINT
);
CREATE INDEX cache_invalidation_stream_id ON cache_invalidation_stream(stream_id);
"""
def run_create(cur, database_engine, *args, **kwargs):
if not isinstance(database_engine, PostgresEngine):
return
for statement in get_statements(CREATE_TABLE.splitlines()):
cur.execute(statement)
def run_upgrade(cur, database_engine, *args, **kwargs):
pass
| 460 |
406 | /**
🍪 the_hyp0cr1t3
🍪 06.09.2021 00:33:57
**/
#ifdef W
#include <k_II.h>
#else
#include <bits/stdc++.h>
using namespace std;
#endif
#define pb emplace_back
#define all(x) x.begin(), x.end()
#define sz(x) static_cast<int32_t>(x.size())
auto chmax = [](auto& A, auto&& B) { return B > A? A = B, true : false; };
auto chmin = [](auto& A, auto&& B) { return B < A? A = B, true : false; };
const int64_t k_II = 2e18;
const int INF = 2e9, MOD = 1e9+7;
const int N = 2e5 + 5;
int main() {
ios_base::sync_with_stdio(false), cin.tie(nullptr);
int i, n, m;
cin >> n >> m;
vector<int> indeg(n);
vector<vector<int>> g(n);
for(i = 0; i < m; i++) {
int u, v; cin >> u >> v;
g[--u].pb(--v); indeg[v]++;
}
vector<int> par(n, -1), dp(n, -INF);
dp[0] = 1;
queue<int> q;
for(i = 0; i < n; i++)
if(!indeg[i]) q.push(i);
while(!q.empty()) {
auto v = q.front(); q.pop();
for(auto& x: g[v]) {
if(!--indeg[x]) q.push(x);
if(chmax(dp[x], dp[v] + 1)) par[x] = v;
}
}
if(dp[n - 1] < 0)
return cout << "IMPOSSIBLE" << '\n', 0;
vector<int> ans;
ans.reserve(dp[n - 1]);
for(i = n-1; ~i; i = par[i]) ans.pb(i);
reverse(all(ans));
cout << sz(ans) << '\n';
for(auto& x: ans) cout << x + 1 << ' ';
} // ~W | 726 |
852 | <reponame>ckamtsikis/cmssw<filename>DataFormats/Provenance/interface/LuminosityBlockRange.h
#ifndef DataFormats_Provenance_LuminosityBlockRange_h
#define DataFormats_Provenance_LuminosityBlockRange_h
// -*- C++ -*-
//
// Package: DataFormats/Provenance
// Class : LuminosityBlockRange
//
/**\class LuminosityBlockRange LuminosityBlockRange.h DataFormats/Provenance/interface/LuminosityBlockRange.h
Description: Holds run and luminosityBlock range.
Usage:
<usage>
*/
//
//
// system include files
#include <functional>
#include <iosfwd>
#include <vector>
// user include files
#include "DataFormats/Provenance/interface/LuminosityBlockID.h"
// forward declarations
namespace edm {
// typedef unsigned int LuminosityBlockNumber_t;
class LuminosityBlockRange {
public:
LuminosityBlockRange();
LuminosityBlockRange(RunNumber_t startRun,
LuminosityBlockNumber_t startLuminosityBlock,
RunNumber_t endRun,
LuminosityBlockNumber_t endLuminosityBlock);
LuminosityBlockRange(LuminosityBlockID const& begin, LuminosityBlockID const& end);
//virtual ~LuminosityBlockID();
// ---------- const member functions ---------------------
LuminosityBlockID startLumiID() const { return startLumiID_; }
LuminosityBlockID endLumiID() const { return endLumiID_; }
RunNumber_t startRun() const { return startLumiID_.run(); }
RunNumber_t endRun() const { return endLumiID_.run(); }
LuminosityBlockNumber_t startLumi() const { return startLumiID_.luminosityBlock(); }
LuminosityBlockNumber_t endLumi() const { return endLumiID_.luminosityBlock(); }
// ---------- static functions ---------------------------
// ---------- member functions ---------------------------
private:
// ---------- member data --------------------------------
//RunNumber_t startRun_;
//RunNumber_t endRun_;
//LuminosityBlockNumber_t startLumi_;
//LuminosityBlockNumber_t endLumi_;
LuminosityBlockID startLumiID_;
LuminosityBlockID endLumiID_;
};
std::ostream& operator<<(std::ostream& oStream, LuminosityBlockRange const& iID);
bool contains(LuminosityBlockRange const& lh, LuminosityBlockID const& rh);
bool contains(LuminosityBlockRange const& lh, LuminosityBlockRange const& rh);
bool lessThan(LuminosityBlockRange const& lh, LuminosityBlockRange const& rh);
bool overlaps(LuminosityBlockRange const& lh, LuminosityBlockRange const& rh);
bool distinct(LuminosityBlockRange const& lh, LuminosityBlockRange const& rh);
bool merge(LuminosityBlockRange& lh, LuminosityBlockRange& rh);
std::vector<LuminosityBlockRange>& sortAndRemoveOverlaps(std::vector<LuminosityBlockRange>& lumiRange);
} // namespace edm
#endif
| 960 |
348 | <filename>docs/data/leg-t2/065/06501464.json
{"nom":"Vielle-Adour","circ":"1ère circonscription","dpt":"Hautes-Pyrénées","inscrits":410,"abs":203,"votants":207,"blancs":7,"nuls":4,"exp":196,"res":[{"nuance":"REM","nom":"<NAME>","voix":119},{"nuance":"FI","nom":"Mme <NAME>","voix":77}]} | 120 |
484 | /*
* Copyright 2017 Xiaomi, 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.xiaomi.shepher.controller;
import com.xiaomi.shepher.exception.ShepherException;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* The {@link ShepherExceptionHandler} is a general exception handler of this project.
*
* Created by weichuyang on 16-8-4.
*/
@ControllerAdvice
@Controller
public class ShepherExceptionHandler implements ErrorController {
private static final Logger logger = LoggerFactory.getLogger(com.xiaomi.shepher.controller.ShepherExceptionHandler.class);
private static final String ERROR_PATH = "/error";
/**
* Handles self define {@link ShepherException}.
*
* @param exception
* @param model
* @return
*/
@ExceptionHandler(value = ShepherException.class)
public String handleShepherException(ShepherException exception, Model model) {
logger.info("Handle ShepherException:code {}, message: {}", exception.getCode(), exception.getMessage());
model.addAttribute("message", StringEscapeUtils.escapeHtml4(exception.getMessage()));
return ERROR_PATH;
}
/**
* Handles unknown exception.
*
* @param exception
* @param model
* @return
*/
@ExceptionHandler(value = Exception.class)
public String handleUndefinedException(Exception exception, Model model) {
logger.warn("Handle Unknown Exception: {} ", exception.getMessage());
model.addAttribute("message", StringEscapeUtils.escapeHtml4(exception.getMessage()));
return ERROR_PATH;
}
/**
* Handles http status error.
*
* @param request
* @param model
* @return
*/
@RequestMapping(value = ERROR_PATH)
public String handleError(HttpServletRequest request, Model model) {
HttpStatus httpStatus = getStatus(request);
model.addAttribute("message", httpStatus.getReasonPhrase());
return getErrorPath();
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}
/**
* Handles error of {@link ErrorController}
*
* @return
*/
@Override
public String getErrorPath() {
return ERROR_PATH;
}
}
| 1,155 |
1,511 | /* GObject - GLib Type, Object, Parameter and Signal Library
* Copyright (C) 2006 Imendio AB
*
* This library is free software; you can redistribute it and/or
#define MY_TYPE_SINGLETON (my_singleton_get_type ())
#define MY_SINGLETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), MY_TYPE_SINGLETON, MySingleton))
#define MY_IS_SINGLETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), MY_TYPE_SINGLETON))
#define MY_SINGLETON_CLASS(c) (G_TYPE_CHECK_CLASS_CAST ((c), MY_TYPE_SINGLETON, MySingletonClass))
#define MY_IS_SINGLETON_CLASS(c) (G_TYPE_CHECK_CLASS_TYPE ((c), MY_TYPE_SINGLETON))
#define MY_SINGLETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), MY_TYPE_SINGLETON, MySingletonClass))
| 295 |
1,091 | <filename>apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/cli/KubevirtListApiConfigsCommand.java
/*
* Copyright 2020-present Open Networking Foundation
*
* 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.onosproject.kubevirtnode.cli;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.kubevirtnode.api.KubevirtApiConfig;
import org.onosproject.kubevirtnode.api.KubevirtApiConfigService;
import static org.onosproject.kubevirtnode.util.KubevirtNodeUtil.prettyJson;
/**
* Lists all KubeVirt API server configs registered to the service.
*/
@Service
@Command(scope = "onos", name = "kubevirt-api-configs",
description = "Lists all KubeVirt API server configs registered to the service")
public class KubevirtListApiConfigsCommand extends AbstractShellCommand {
private static final String FORMAT = "%-10s%-20s%-10s%-25s%-10s";
@Override
protected void doExecute() throws Exception {
KubevirtApiConfigService service = get(KubevirtApiConfigService.class);
KubevirtApiConfig config = service.apiConfig();
if (outputJson()) {
print("%s", json(config));
} else {
print(FORMAT, "Scheme", "Server IP", "Port", "Controller IP", "State");
String controllerIp = "N/A";
if (config != null) {
if (config.controllerIp() != null) {
controllerIp = config.controllerIp().toString();
}
print(FORMAT, config.scheme().name(), config.ipAddress().toString(),
config.port(), controllerIp, config.state().name());
} else {
print("Kubevirt config not found!");
}
}
}
private String json(KubevirtApiConfig config) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = jsonForEntity(config, KubevirtApiConfig.class);
return prettyJson(mapper, node.toString());
}
}
| 1,015 |
823 | <filename>src/lib/openjpip/faixbox_manager.c
/*
* $Id$
*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor <NAME>
* Copyright (c) 2010-2011, <NAME>
* 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.
*
* 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 <stdio.h>
#include <stdlib.h>
#include "faixbox_manager.h"
#include "opj_inttypes.h"
#ifdef SERVER
#include "fcgi_stdio.h"
#define logstream FCGI_stdout
#else
#define FCGI_stdout stdout
#define FCGI_stderr stderr
#define logstream stderr
#endif /*SERVER*/
faixbox_param_t * gene_faixbox(box_param_t *box)
{
faixbox_param_t *faix;
size_t numOfelem;
long pos = 0;
faix = (faixbox_param_t *)malloc(sizeof(faixbox_param_t));
faix->version = fetch_DBox1byte(box, (pos += 1) - 1);
if (3 < faix->version) {
fprintf(FCGI_stderr, "Error: version %d in faix box is reserved for ISO use.\n",
faix->version);
free(faix);
return NULL;
}
if (faix->version % 2) {
subfaixbox8_param_t *subfaixbox;
size_t i;
faix->subfaixbox.byte8_params = (subfaixbox8_param_t *)malloc(sizeof(
subfaixbox8_param_t));
subfaixbox = faix->subfaixbox.byte8_params;
subfaixbox->nmax = fetch_DBox8bytebigendian(box, (pos += 8) - 8);
subfaixbox->m = fetch_DBox8bytebigendian(box, (pos += 8) - 8);
numOfelem = subfaixbox->nmax * subfaixbox->m;
subfaixbox->elem = (faixelem8_param_t *)malloc(numOfelem * sizeof(
faixelem8_param_t));
if (faix->version == 3) {
subfaixbox->aux = (Byte4_t *)malloc(numOfelem * sizeof(Byte4_t));
}
for (i = 0; i < numOfelem; i++) {
subfaixbox->elem[i].off = fetch_DBox8bytebigendian(box, (pos += 8) - 8);
subfaixbox->elem[i].len = fetch_DBox8bytebigendian(box, (pos += 8) - 8);
if (faix->version == 3) {
subfaixbox->aux[i] = fetch_DBox4bytebigendian(box, (pos += 4) - 4);
}
}
} else {
subfaixbox4_param_t *subfaixbox;
size_t i;
faix->subfaixbox.byte4_params = (subfaixbox4_param_t *)malloc(sizeof(
subfaixbox4_param_t));
subfaixbox = faix->subfaixbox.byte4_params;
subfaixbox->nmax = fetch_DBox4bytebigendian(box, (pos += 4) - 4);
subfaixbox->m = fetch_DBox4bytebigendian(box, (pos += 4) - 4);
numOfelem = subfaixbox->nmax * subfaixbox->m;
subfaixbox->elem = (faixelem4_param_t *)malloc(numOfelem * sizeof(
faixelem4_param_t));
if (faix->version == 2) {
subfaixbox->aux = (Byte4_t *)malloc(numOfelem * sizeof(Byte4_t));
}
for (i = 0; i < numOfelem; i++) {
subfaixbox->elem[i].off = fetch_DBox4bytebigendian(box, (pos += 4) - 4);
subfaixbox->elem[i].len = fetch_DBox4bytebigendian(box, (pos += 4) - 4);
if (faix->version == 2) {
subfaixbox->aux[i] = fetch_DBox4bytebigendian(box, (pos += 4) - 4);
}
}
}
return faix;
}
void print_faixbox(faixbox_param_t *faix)
{
Byte8_t i, j;
fprintf(logstream, "faix box info\n");
fprintf(logstream, "\tversion: %d\n", faix->version);
fprintf(logstream, "\t nmax: %#" PRIx64 " = %" PRId64 "\n", get_nmax(faix),
get_nmax(faix));
fprintf(logstream, "\t m: %#" PRIx64 " = %" PRId64 "\n", get_m(faix),
get_m(faix));
for (i = 0; i < get_m(faix); i++) {
for (j = 0; j < get_nmax(faix); j++) {
fprintf(logstream, "\t off = %#" PRIx64 ", len = %#" PRIx64 "",
get_elemOff(faix, j, i), get_elemLen(faix, j, i));
if (2 <= faix->version) {
fprintf(logstream, ", aux = %#x", get_elemAux(faix, j, i));
}
fprintf(logstream, "\n");
}
fprintf(logstream, "\n");
}
}
void delete_faixbox(faixbox_param_t **faix)
{
if ((*faix)->version % 2) {
free((*faix)->subfaixbox.byte8_params->elem);
if ((*faix)->version == 3) {
free((*faix)->subfaixbox.byte8_params->aux);
}
free((*faix)->subfaixbox.byte8_params);
} else {
free((*faix)->subfaixbox.byte4_params->elem);
if ((*faix)->version == 2) {
free((*faix)->subfaixbox.byte4_params->aux);
}
free((*faix)->subfaixbox.byte4_params);
}
free(*faix);
}
Byte8_t get_nmax(faixbox_param_t *faix)
{
if (faix->version % 2) {
return faix->subfaixbox.byte8_params->nmax;
} else {
return (Byte8_t)faix->subfaixbox.byte4_params->nmax;
}
}
Byte8_t get_m(faixbox_param_t *faix)
{
if (faix->version % 2) {
return faix->subfaixbox.byte8_params->m;
} else {
return (Byte8_t)faix->subfaixbox.byte4_params->m;
}
}
Byte8_t get_elemOff(faixbox_param_t *faix, Byte8_t elem_id, Byte8_t row_id)
{
Byte8_t nmax = get_nmax(faix);
if (faix->version % 2) {
return faix->subfaixbox.byte8_params->elem[ row_id * nmax + elem_id].off;
} else {
return (Byte8_t)faix->subfaixbox.byte4_params->elem[ row_id * nmax +
elem_id].off;
}
}
Byte8_t get_elemLen(faixbox_param_t *faix, Byte8_t elem_id, Byte8_t row_id)
{
Byte8_t nmax = get_nmax(faix);
if (faix->version % 2) {
return faix->subfaixbox.byte8_params->elem[ row_id * nmax + elem_id].len;
} else {
return (Byte8_t)faix->subfaixbox.byte4_params->elem[ row_id * nmax +
elem_id].len;
}
}
Byte4_t get_elemAux(faixbox_param_t *faix, Byte8_t elem_id, Byte8_t row_id)
{
Byte8_t nmax;
if (faix->version < 2) {
return (Byte4_t) - 1;
}
nmax = get_nmax(faix);
if (faix->version % 2) {
return faix->subfaixbox.byte8_params->aux[ row_id * nmax + elem_id];
} else {
return faix->subfaixbox.byte4_params->aux[ row_id * nmax + elem_id];
}
}
| 3,588 |
1,953 | <reponame>Riessarius/mne-python
"""
.. _tut-fnirs-processing:
Preprocessing functional near-infrared spectroscopy (fNIRS) data
================================================================
This tutorial covers how to convert functional near-infrared spectroscopy
(fNIRS) data from raw measurements to relative oxyhaemoglobin (HbO) and
deoxyhaemoglobin (HbR) concentration, view the average waveform, and
topographic representation of the response.
Here we will work with the :ref:`fNIRS motor data <fnirs-motor-dataset>`.
"""
# %%
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
from itertools import compress
import mne
fnirs_data_folder = mne.datasets.fnirs_motor.data_path()
fnirs_cw_amplitude_dir = op.join(fnirs_data_folder, 'Participant-1')
raw_intensity = mne.io.read_raw_nirx(fnirs_cw_amplitude_dir, verbose=True)
raw_intensity.load_data()
# %%
# Providing more meaningful annotation information
# ------------------------------------------------
#
# First, we attribute more meaningful names to the trigger codes which are
# stored as annotations. Second, we include information about the duration of
# each stimulus, which was 5 seconds for all conditions in this experiment.
# Third, we remove the trigger code 15, which signaled the start and end
# of the experiment and is not relevant to our analysis.
raw_intensity.annotations.set_durations(5)
raw_intensity.annotations.rename({'1.0': 'Control',
'2.0': 'Tapping/Left',
'3.0': 'Tapping/Right'})
unwanted = np.nonzero(raw_intensity.annotations.description == '15.0')
raw_intensity.annotations.delete(unwanted)
# %%
# Viewing location of sensors over brain surface
# ----------------------------------------------
#
# Here we validate that the location of sources-detector pairs and channels
# are in the expected locations. Source-detector pairs are shown as lines
# between the optodes, channels (the mid point of source-detector pairs) are
# optionally shown as orange dots. Source are optionally shown as red dots and
# detectors as black.
subjects_dir = op.join(mne.datasets.sample.data_path(), 'subjects')
brain = mne.viz.Brain(
'fsaverage', subjects_dir=subjects_dir, background='w', cortex='0.5')
brain.add_sensors(
raw_intensity.info, trans='fsaverage',
fnirs=['channels', 'pairs', 'sources', 'detectors'])
brain.show_view(azimuth=20, elevation=60, distance=400)
# %%
# Selecting channels appropriate for detecting neural responses
# -------------------------------------------------------------
#
# First we remove channels that are too close together (short channels) to
# detect a neural response (less than 1 cm distance between optodes).
# These short channels can be seen in the figure above.
# To achieve this we pick all the channels that are not considered to be short.
picks = mne.pick_types(raw_intensity.info, meg=False, fnirs=True)
dists = mne.preprocessing.nirs.source_detector_distances(
raw_intensity.info, picks=picks)
raw_intensity.pick(picks[dists > 0.01])
raw_intensity.plot(n_channels=len(raw_intensity.ch_names),
duration=500, show_scrollbars=False)
# %%
# Converting from raw intensity to optical density
# ------------------------------------------------
#
# The raw intensity values are then converted to optical density.
raw_od = mne.preprocessing.nirs.optical_density(raw_intensity)
raw_od.plot(n_channels=len(raw_od.ch_names),
duration=500, show_scrollbars=False)
# %%
# Evaluating the quality of the data
# ----------------------------------
#
# At this stage we can quantify the quality of the coupling
# between the scalp and the optodes using the scalp coupling index. This
# method looks for the presence of a prominent synchronous signal in the
# frequency range of cardiac signals across both photodetected signals.
#
# In this example the data is clean and the coupling is good for all
# channels, so we will not mark any channels as bad based on the scalp
# coupling index.
sci = mne.preprocessing.nirs.scalp_coupling_index(raw_od)
fig, ax = plt.subplots()
ax.hist(sci)
ax.set(xlabel='Scalp Coupling Index', ylabel='Count', xlim=[0, 1])
# %%
# In this example we will mark all channels with a SCI less than 0.5 as bad
# (this dataset is quite clean, so no channels are marked as bad).
raw_od.info['bads'] = list(compress(raw_od.ch_names, sci < 0.5))
# %%
# At this stage it is appropriate to inspect your data
# (for instructions on how to use the interactive data visualisation tool
# see :ref:`tut-visualize-raw`)
# to ensure that channels with poor scalp coupling have been removed.
# If your data contains lots of artifacts you may decide to apply
# artifact reduction techniques as described in :ref:`ex-fnirs-artifacts`.
# %%
# Converting from optical density to haemoglobin
# ----------------------------------------------
#
# Next we convert the optical density data to haemoglobin concentration using
# the modified Beer-Lambert law.
raw_haemo = mne.preprocessing.nirs.beer_lambert_law(raw_od)
raw_haemo.plot(n_channels=len(raw_haemo.ch_names),
duration=500, show_scrollbars=False)
# %%
# Removing heart rate from signal
# -------------------------------
#
# The haemodynamic response has frequency content predominantly below 0.5 Hz.
# An increase in activity around 1 Hz can be seen in the data that is due to
# the person's heart beat and is unwanted. So we use a low pass filter to
# remove this. A high pass filter is also included to remove slow drifts
# in the data.
fig = raw_haemo.plot_psd(average=True)
fig.suptitle('Before filtering', weight='bold', size='x-large')
fig.subplots_adjust(top=0.88)
raw_haemo = raw_haemo.filter(0.05, 0.7, h_trans_bandwidth=0.2,
l_trans_bandwidth=0.02)
fig = raw_haemo.plot_psd(average=True)
fig.suptitle('After filtering', weight='bold', size='x-large')
fig.subplots_adjust(top=0.88)
# %%
# Extract epochs
# --------------
#
# Now that the signal has been converted to relative haemoglobin concentration,
# and the unwanted heart rate component has been removed, we can extract epochs
# related to each of the experimental conditions.
#
# First we extract the events of interest and visualise them to ensure they are
# correct.
events, event_dict = mne.events_from_annotations(raw_haemo)
fig = mne.viz.plot_events(events, event_id=event_dict,
sfreq=raw_haemo.info['sfreq'])
fig.subplots_adjust(right=0.7) # make room for the legend
# %%
# Next we define the range of our epochs, the rejection criteria,
# baseline correction, and extract the epochs. We visualise the log of which
# epochs were dropped.
reject_criteria = dict(hbo=80e-6)
tmin, tmax = -5, 15
epochs = mne.Epochs(raw_haemo, events, event_id=event_dict,
tmin=tmin, tmax=tmax,
reject=reject_criteria, reject_by_annotation=True,
proj=True, baseline=(None, 0), preload=True,
detrend=None, verbose=True)
epochs.plot_drop_log()
# %%
# View consistency of responses across trials
# -------------------------------------------
#
# Now we can view the haemodynamic response for our tapping condition.
# We visualise the response for both the oxy- and deoxyhaemoglobin, and
# observe the expected peak in HbO at around 6 seconds consistently across
# trials, and the consistent dip in HbR that is slightly delayed relative to
# the HbO peak.
epochs['Tapping'].plot_image(combine='mean', vmin=-30, vmax=30,
ts_args=dict(ylim=dict(hbo=[-15, 15],
hbr=[-15, 15])))
# %%
# We can also view the epoched data for the control condition and observe
# that it does not show the expected morphology.
epochs['Control'].plot_image(combine='mean', vmin=-30, vmax=30,
ts_args=dict(ylim=dict(hbo=[-15, 15],
hbr=[-15, 15])))
# %%
# View consistency of responses across channels
# ---------------------------------------------
#
# Similarly we can view how consistent the response is across the optode
# pairs that we selected. All the channels in this data are located over the
# motor cortex, and all channels show a similar pattern in the data.
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15, 6))
clims = dict(hbo=[-20, 20], hbr=[-20, 20])
epochs['Control'].average().plot_image(axes=axes[:, 0], clim=clims)
epochs['Tapping'].average().plot_image(axes=axes[:, 1], clim=clims)
for column, condition in enumerate(['Control', 'Tapping']):
for ax in axes[:, column]:
ax.set_title('{}: {}'.format(condition, ax.get_title()))
# %%
# Plot standard fNIRS response image
# ----------------------------------
#
# Next we generate the most common visualisation of fNIRS data: plotting
# both the HbO and HbR on the same figure to illustrate the relation between
# the two signals.
evoked_dict = {'Tapping/HbO': epochs['Tapping'].average(picks='hbo'),
'Tapping/HbR': epochs['Tapping'].average(picks='hbr'),
'Control/HbO': epochs['Control'].average(picks='hbo'),
'Control/HbR': epochs['Control'].average(picks='hbr')}
# Rename channels until the encoding of frequency in ch_name is fixed
for condition in evoked_dict:
evoked_dict[condition].rename_channels(lambda x: x[:-4])
color_dict = dict(HbO='#AA3377', HbR='b')
styles_dict = dict(Control=dict(linestyle='dashed'))
mne.viz.plot_compare_evokeds(evoked_dict, combine="mean", ci=0.95,
colors=color_dict, styles=styles_dict)
# %%
# View topographic representation of activity
# -------------------------------------------
#
# Next we view how the topographic activity changes throughout the response.
times = np.arange(-3.5, 13.2, 3.0)
topomap_args = dict(extrapolate='local')
epochs['Tapping'].average(picks='hbo').plot_joint(
times=times, topomap_args=topomap_args)
# %%
# Compare tapping of left and right hands
# ---------------------------------------
#
# Finally we generate topo maps for the left and right conditions to view
# the location of activity. First we visualise the HbO activity.
times = np.arange(4.0, 11.0, 1.0)
epochs['Tapping/Left'].average(picks='hbo').plot_topomap(
times=times, **topomap_args)
epochs['Tapping/Right'].average(picks='hbo').plot_topomap(
times=times, **topomap_args)
# %%
# And we also view the HbR activity for the two conditions.
epochs['Tapping/Left'].average(picks='hbr').plot_topomap(
times=times, **topomap_args)
epochs['Tapping/Right'].average(picks='hbr').plot_topomap(
times=times, **topomap_args)
# %%
# And we can plot the comparison at a single time point for two conditions.
fig, axes = plt.subplots(nrows=2, ncols=4, figsize=(9, 5),
gridspec_kw=dict(width_ratios=[1, 1, 1, 0.1]))
vmin, vmax, ts = -8, 8, 9.0
evoked_left = epochs['Tapping/Left'].average()
evoked_right = epochs['Tapping/Right'].average()
evoked_left.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 0],
vmin=vmin, vmax=vmax, colorbar=False,
**topomap_args)
evoked_left.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 0],
vmin=vmin, vmax=vmax, colorbar=False,
**topomap_args)
evoked_right.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 1],
vmin=vmin, vmax=vmax, colorbar=False,
**topomap_args)
evoked_right.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 1],
vmin=vmin, vmax=vmax, colorbar=False,
**topomap_args)
evoked_diff = mne.combine_evoked([evoked_left, evoked_right], weights=[1, -1])
evoked_diff.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 2:],
vmin=vmin, vmax=vmax, colorbar=True,
**topomap_args)
evoked_diff.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 2:],
vmin=vmin, vmax=vmax, colorbar=True,
**topomap_args)
for column, condition in enumerate(
['Tapping Left', 'Tapping Right', 'Left-Right']):
for row, chroma in enumerate(['HbO', 'HbR']):
axes[row, column].set_title('{}: {}'.format(chroma, condition))
fig.tight_layout()
# %%
# Lastly, we can also look at the individual waveforms to see what is
# driving the topographic plot above.
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 4))
mne.viz.plot_evoked_topo(epochs['Left'].average(picks='hbo'), color='b',
axes=axes, legend=False)
mne.viz.plot_evoked_topo(epochs['Right'].average(picks='hbo'), color='r',
axes=axes, legend=False)
# Tidy the legend.
leg_lines = [line for line in axes.lines if line.get_c() == 'b'][:1]
leg_lines.append([line for line in axes.lines if line.get_c() == 'r'][0])
fig.legend(leg_lines, ['Left', 'Right'], loc='lower right')
| 4,870 |
30,023 | """Define constants for the GeoNet NZ Quakes integration."""
from datetime import timedelta
from homeassistant.const import Platform
DOMAIN = "geonetnz_quakes"
PLATFORMS = [Platform.SENSOR, Platform.GEO_LOCATION]
CONF_MINIMUM_MAGNITUDE = "minimum_magnitude"
CONF_MMI = "mmi"
FEED = "feed"
DEFAULT_FILTER_TIME_INTERVAL = timedelta(days=7)
DEFAULT_MINIMUM_MAGNITUDE = 0.0
DEFAULT_MMI = 3
DEFAULT_RADIUS = 50.0
DEFAULT_SCAN_INTERVAL = timedelta(minutes=5)
| 183 |
1,916 | /* -------------------------------------------------------------------------- *
* Simbody(tm): SimTKmath *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2010-12 Stanford University and the Authors. *
* Authors: <NAME> *
* Contributors: *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
/** @file
* This is the private (library side) implementation of the
* RungeKutta3Integrator and RungeKutta3IntegratorRep classes.
*/
#include "SimTKcommon.h"
#include "simmath/Integrator.h"
#include "simmath/RungeKutta3Integrator.h"
#include "IntegratorRep.h"
#include "RungeKutta3IntegratorRep.h"
#include <exception>
#include <limits>
using namespace SimTK;
//------------------------------------------------------------------------------
// RUNGE KUTTA 3 INTEGRATOR
//------------------------------------------------------------------------------
RungeKutta3Integrator::RungeKutta3Integrator(const System& sys)
{
rep = new RungeKutta3IntegratorRep(this, sys);
}
//------------------------------------------------------------------------------
// RUNGE KUTTA 3 INTEGRATOR REP
//------------------------------------------------------------------------------
RungeKutta3IntegratorRep::RungeKutta3IntegratorRep
(Integrator* handle, const System& sys)
: AbstractIntegratorRep(handle, sys, 3, 3, "RungeKutta3", true) {
}
// For a discussion of this Runge-Kutta 3(2) method, see <NAME>, "The
// Numerical Analysis of Ordinary Differential Equations", <NAME> & Sons,
// 1987, page 325. The embedded error estimate was derived using the method
// mentioned in Hairer, Norsett & Wanner, Solving ODEs I, 2nd rev. ed. on
// page 166. This is the Butcher diagram:
//
// 0|
// 1/2| 1/2
// 1| -1 2
// --|-------------------
// 1| 1/6 2/3 1/6 3rd order propagated solution
// --|-------------------
// 1| 0 1 0 0 2nd order midpoint for error estimate
//
// This is a 3-stage, first-same-as-last (FSAL) 3rd order method which
// gives us an embedded 2nd order method as well, so we can extract
// a 3rd-order error estimate for the 2nd-order result, which error
// estimate can then be used for step size control, since it will
// behave as h^3. We then propagate the 3rd order result (whose error
// is unknown), which Hairer calls "local extrapolation".
// We call the initial state (t0,y0) and want (t0+h,y1). We are
// given the initial derivative f0=f(t0,y0), which most likely
// is left over from an evaluation at the end of the last step.
bool RungeKutta3IntegratorRep::attemptODEStep
(Real t1, Vector& y1err, int& errOrder, int& numIterations)
{
const Real t0 = getPreviousTime();
assert(t1 > t0);
statsStepsAttempted++;
errOrder = 3;
const Vector& y0 = getPreviousY();
const Vector& f0 = getPreviousYDot();
if (ytmp[0].size() != y0.size())
for (int i=0; i<NTemps; ++i)
ytmp[i].resize(y0.size());
Vector& f1 = ytmp[0]; // rename temps
Vector& f2 = ytmp[1];
const Real h = t1-t0;
setAdvancedStateAndRealizeDerivatives(t0+h/2, y0 + (h/2)*f0);
f1 = getAdvancedState().getYDot();
setAdvancedStateAndRealizeDerivatives(t1, y0 + h*(2*f1-f0));
f2 = getAdvancedState().getYDot();
// Final value. This is the 3rd order accurate estimate for
// y1=y(t0+h)+O(h^4): y1 = y0 + (h/6)*(f0 + 4 f1 + f2).
// Evaluate through kinematics only; it is a waste of a stage to
// evaluate derivatives here since the caller will muck with this before
// the end of the step.
setAdvancedStateAndRealizeKinematics(t1, y0 + (h/6)*(f0 + 4*f1 + f2));
// YErr is valid now
// This is an embedded 2nd-order estimate y1hat=y(t1)+O(h^3), with
// y1hat = y0 + h*f1 (explicit midpoint method). We just need the
// error y1-y1hat.
const Vector& y1 = getAdvancedState().getY();
for (int i=0; i<y1.size(); ++i)
y1err[i] = std::abs(y1[i]-(y0[i] + h*f1[i]));
return true;
}
| 2,226 |
528 | /******************************************************************************
Copyright 2019-2020 <NAME>
Licensed under the Apache License, Version 2.0 (the "License"),
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*******************************************************************************
FILE: Test/ArcBallCameraTest.cpp
Arc-Ball camera unit tests
******************************************************************************/
#include <Methane/Graphics/ArcBallCamera.h>
#include <Methane/Data/Types.h>
#include <Methane/Checks.hpp>
#include <Methane/HlslCatchHelpers.hpp>
#include <catch2/catch.hpp>
#include <cmath>
using namespace Methane::Graphics;
using namespace Methane::Data;
using namespace Methane;
static const FloatSize g_test_screen_size { 640.f, 480.f };
static const Point2F g_test_screen_center { g_test_screen_size.GetWidth() / 2.f, g_test_screen_size.GetHeight() / 2.f };
static const Camera::Orientation g_test_view_orientation { { 0.f, 5.f, 10.f }, { 0.f, 5.f, 0.f }, { 0.f, 1.f, 0.f } };
static const Camera::Orientation g_test_dept_orientation { { 10.f, 7.f, 0.f }, { 0.f, 7.f, 0.f }, { 0.f, 0.f, 1.f } };
static const float g_test_radius_ratio = 0.75F;
static const float g_test_radius_pixels = g_test_screen_center.GetY() * g_test_radius_ratio;
static const hlslpp::float3 g_axis_x { 1.f, 0.f, 0.f };
static const hlslpp::float3 g_axis_y { 0.f, 1.f, 0.f };
static const hlslpp::float3 g_axis_z { 0.f, 0.f, -1.f };
inline void SetupCamera(ArcBallCamera& camera, const Camera::Orientation& orientation)
{
camera.Resize(g_test_screen_size);
camera.ResetOrientation(orientation);
camera.SetRadiusRatio(g_test_radius_ratio);
CHECK(camera.GetRadiusInPixels() == g_test_radius_pixels);
}
inline ArcBallCamera SetupViewCamera(ArcBallCamera::Pivot pivot, const Camera::Orientation& orientation)
{
ArcBallCamera view_camera(pivot);
SetupCamera(view_camera, orientation);
return view_camera;
}
inline ArcBallCamera SetupDependentCamera(const ArcBallCamera& view_camera, ArcBallCamera::Pivot pivot, const Camera::Orientation& orientation)
{
ArcBallCamera dependent_camera(view_camera, pivot);
SetupCamera(dependent_camera, orientation);
return dependent_camera;
}
inline void CheckOrientation(const Camera::Orientation& actual_orientation, const Camera::Orientation& reference_orientation, float epsilon = 0.00001F)
{
CHECK_THAT(actual_orientation.aim, HlslVectorApproxEquals(reference_orientation.aim, epsilon));
CHECK_THAT(actual_orientation.eye, HlslVectorApproxEquals(reference_orientation.eye, epsilon));
CHECK_THAT(actual_orientation.up , HlslVectorApproxEquals(reference_orientation.up, epsilon));
}
inline void TestViewCameraRotation(ArcBallCamera::Pivot view_pivot,
const Camera::Orientation& initial_view_orientation,
const Point2I& mouse_press_pos, const Point2I& mouse_drag_pos,
const Camera::Orientation& rotated_view_orientation,
const float vectors_equality_epsilon = 0.00001F)
{
ArcBallCamera view_camera = SetupViewCamera(view_pivot, initial_view_orientation);
view_camera.MousePress(mouse_press_pos);
view_camera.MouseDrag(mouse_drag_pos);
CheckOrientation(view_camera.GetOrientation(), rotated_view_orientation, vectors_equality_epsilon);
}
inline void TestDependentCameraRotation(ArcBallCamera::Pivot view_pivot,
const Camera::Orientation& initial_view_orientation,
ArcBallCamera::Pivot dependent_pivot,
const Camera::Orientation& initial_dependent_orientation,
const Point2I& mouse_press_pos, const Point2I& mouse_drag_pos,
const Camera::Orientation& rotated_dependent_orientation,
const float vectors_equality_epsilon = 0.00001F)
{
ArcBallCamera view_camera = SetupViewCamera(view_pivot, initial_view_orientation);
ArcBallCamera dependent_camera = SetupDependentCamera(view_camera, dependent_pivot, initial_dependent_orientation);
dependent_camera.MousePress(mouse_press_pos);
dependent_camera.MouseDrag(mouse_drag_pos);
CheckOrientation(dependent_camera.GetOrientation(), rotated_dependent_orientation, vectors_equality_epsilon);
}
inline Camera::Orientation RotateOrientation(const Camera::Orientation& orientation, const ArcBallCamera::Pivot pivot, const hlslpp::float3& axis, float angle_degrees)
{
hlslpp::float3x3 rotation_matrix = hlslpp::float3x3::rotation_axis(hlslpp::normalize(axis), angle_degrees * ConstFloat::RadPerDeg);
const hlslpp::float3 look_dir = hlslpp::mul(orientation.aim - orientation.eye, rotation_matrix);
const hlslpp::float3 up_dir = hlslpp::mul(orientation.up, rotation_matrix);
switch (pivot)
{
case ArcBallCamera::Pivot::Aim: return { orientation.aim - look_dir, orientation.aim, up_dir };
case ArcBallCamera::Pivot::Eye: return { orientation.eye, orientation.eye + look_dir, up_dir };
default: META_UNEXPECTED_ARG_RETURN(pivot, { });
}
}
TEST_CASE("View arc-ball camera rotation around Aim pivot < 90 degrees", "[camera][rotate][aim][view]")
{
const ArcBallCamera::Pivot test_pivot = ArcBallCamera::Pivot::Aim;
SECTION("Rotation 90 degrees")
{
SECTION("Around X-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center + Point2F(0.f, g_test_radius_pixels)),
{ { 0.f, 15.f, 0.f }, g_test_view_orientation.aim, { 0.f, 0.f, -1.f } });
}
SECTION("Around Y-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center + Point2F(g_test_radius_pixels, 0.f)),
{ { 10.f, 5.f, 0.f }, g_test_view_orientation.aim, g_test_view_orientation.up });
}
SECTION("Around Z-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
Point2I(static_cast<int>(g_test_screen_center.GetX()), 0),
Point2I(0, static_cast<int>(g_test_screen_center.GetY())),
{ g_test_view_orientation.eye, g_test_view_orientation.aim, { -1.f, 0.f, 0.f } });
}
}
SECTION("Rotation 45 degrees")
{
// Lower equality precision because of integer screen-space coordinates use
const float test_equality_epsilon = 0.1F;
const float test_angle_deg = 45.f;
const float test_angle_rad = test_angle_deg * ConstFloat::RadPerDeg;
SECTION("Around X axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center - Point2F(0.f, g_test_radius_pixels * std::sin(test_angle_rad))),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_x, test_angle_deg), test_equality_epsilon);
}
SECTION("Around Y axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center + Point2F(g_test_radius_pixels * std::cos(test_angle_rad), 0.f)),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_y, test_angle_deg), test_equality_epsilon);
}
SECTION("Around Z axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
Point2I(static_cast<int>(g_test_screen_center.GetX()), 0),
static_cast<Point2I>(g_test_screen_center + Point2F(g_test_radius_pixels * std::cos(test_angle_rad), -g_test_radius_pixels * std::sin(test_angle_rad))),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_z, test_angle_deg), test_equality_epsilon);
}
}
}
TEST_CASE("View arc-ball camera rotation around Aim pivot > 90 degrees", "[camera][rotate][aim][view]")
{
const ArcBallCamera::Pivot test_pivot = ArcBallCamera::Pivot::Aim;
SECTION("Rotation 180 degrees")
{
SECTION("Around X-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center - Point2F(0.f, g_test_radius_pixels)),
static_cast<Point2I>(g_test_screen_center + Point2F(0.f, g_test_radius_pixels)),
{ { 0.f, 5.f, -10.f }, g_test_view_orientation.aim, { 0.f, -1.f, 0.f } });
}
SECTION("Around Y-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center - Point2F(g_test_radius_pixels, 0.f)),
static_cast<Point2I>(g_test_screen_center + Point2F(g_test_radius_pixels, 0.f)),
{ { 0.f, 5.f, -10.f }, g_test_view_orientation.aim, g_test_view_orientation.up });
}
SECTION("Around Z-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
Point2I(static_cast<int>(g_test_screen_center.GetX()), 0),
Point2I(static_cast<int>(g_test_screen_center.GetX()), static_cast<int>(g_test_screen_size.GetHeight())),
{ g_test_view_orientation.eye, g_test_view_orientation.aim, { 0.f, -1.f, 0.f } });
}
}
SECTION("Rotation 135 degrees")
{
// Lower equality precision because of integer screen-space coordinates use
const float test_equality_epsilon = 0.1F;
const float test_angle_deg = 135.f;
const float test_angle_rad = test_angle_deg * ConstFloat::RadPerDeg;
SECTION("Around X axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center + Point2F(0.f, g_test_radius_pixels)),
static_cast<Point2I>(g_test_screen_center - Point2F(0.f, g_test_radius_pixels * std::sin(test_angle_rad))),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_x, test_angle_deg), test_equality_epsilon);
}
SECTION("Around Y axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center - Point2F(g_test_radius_pixels, 0.f)),
static_cast<Point2I>(g_test_screen_center - Point2F(g_test_radius_pixels * std::cos(test_angle_rad), 0.f)),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_y, test_angle_deg), test_equality_epsilon);
}
SECTION("Around Z axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
Point2I(static_cast<int>(g_test_screen_size.GetWidth()), static_cast<int>(g_test_screen_center.GetY())),
Point2I(g_test_screen_center + Point2F(g_test_screen_center.GetY() * std::cos(test_angle_rad), g_test_screen_center.GetY() * std::sin(test_angle_rad))),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_z, test_angle_deg), test_equality_epsilon);
}
}
}
TEST_CASE("View arc-ball camera rotation around Eye pivot < 90 degrees", "[camera][rotate][eye][view]")
{
const ArcBallCamera::Pivot test_pivot = ArcBallCamera::Pivot::Eye;
SECTION("Rotation 90 degrees")
{
SECTION("Around X-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center + Point2F(0.f, g_test_radius_pixels)),
{ g_test_view_orientation.eye, { 0.f, -5.f, 10.f }, { 0.f, 0.f, -1.f } });
}
SECTION("Around Y-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center + Point2F(g_test_radius_pixels, 0.f)),
{ g_test_view_orientation.eye, { -10.f, 5.f, 10.f }, g_test_view_orientation.up });
}
SECTION("Around Z-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
Point2I(static_cast<int>(g_test_screen_center.GetX()), 0),
Point2I(0, static_cast<int>(g_test_screen_center.GetY())),
{ g_test_view_orientation.eye, g_test_view_orientation.aim, { -1.f, 0.f, 0.f } });
}
}
SECTION("Rotation 45 degrees")
{
// Lower equality precision because of integer screen-space coordinates use
const float test_equality_epsilon = 0.1F;
const float test_angle_deg = 45.f;
const float test_angle_rad = test_angle_deg * ConstFloat::RadPerDeg;
SECTION("Around X axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center - Point2F(0.f, g_test_radius_pixels * std::sin(test_angle_rad))),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_x, test_angle_deg), test_equality_epsilon);
}
SECTION("Around Y axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center + Point2F(g_test_radius_pixels * std::cos(test_angle_rad), 0.f)),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_y, test_angle_deg), test_equality_epsilon);
}
SECTION("Around Z axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
Point2I(static_cast<int>(g_test_screen_center.GetX()), 0),
static_cast<Point2I>(g_test_screen_center + Point2F(g_test_radius_pixels * std::cos(test_angle_rad), -g_test_radius_pixels * std::sin(test_angle_rad))),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_z, test_angle_deg), test_equality_epsilon);
}
}
}
TEST_CASE("View arc-ball camera rotation around Eye pivot > 90 degrees", "[camera][rotate][eye][view]")
{
const ArcBallCamera::Pivot test_pivot = ArcBallCamera::Pivot::Eye;
SECTION("Rotation 180 degrees")
{
SECTION("Around X-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center + Point2F(0.f, g_test_radius_pixels)),
static_cast<Point2I>(g_test_screen_center - Point2F(0.f, g_test_radius_pixels)),
{ g_test_view_orientation.eye, { 0.f, 5.f, 20.f }, { 0.f, -1.f, 0.f } });
}
SECTION("Around Y-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center - Point2F(g_test_radius_pixels, 0.f)),
static_cast<Point2I>(g_test_screen_center + Point2F(g_test_radius_pixels, 0.f)),
{ g_test_view_orientation.eye, { 0.f, 5.f, 20.f }, g_test_view_orientation.up });
}
SECTION("Around Z-axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
Point2I(static_cast<int>(g_test_screen_center.GetX()), 0),
Point2I(static_cast<int>(g_test_screen_center.GetX()), static_cast<int>(g_test_screen_size.GetHeight())),
{ g_test_view_orientation.eye, g_test_view_orientation.aim, { 0.f, -1.f, 0.f } });
}
}
SECTION("Rotation 135 degrees")
{
// Lower equality precision because of integer screen-space coordinates use
const float test_equality_epsilon = 0.1F;
const float test_angle_deg = 135.f;
const float test_angle_rad = test_angle_deg * ConstFloat::RadPerDeg;
SECTION("Around X axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center + Point2F(0.f, g_test_radius_pixels)),
static_cast<Point2I>(g_test_screen_center - Point2F(0.f, g_test_radius_pixels * std::sin(test_angle_rad))),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_x, test_angle_deg), test_equality_epsilon);
}
SECTION("Around Y axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
static_cast<Point2I>(g_test_screen_center - Point2F(g_test_radius_pixels, 0.f)),
static_cast<Point2I>(g_test_screen_center - Point2F(g_test_radius_pixels * std::cos(test_angle_rad), 0.f)),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_y, test_angle_deg), test_equality_epsilon);
}
SECTION("Around Z axis")
{
TestViewCameraRotation(test_pivot, g_test_view_orientation,
Point2I(static_cast<int>(g_test_screen_size.GetWidth()), static_cast<int>(g_test_screen_center.GetY())),
Point2I(g_test_screen_center + Point2F(g_test_screen_center.GetY() * std::cos(test_angle_rad), g_test_screen_center.GetY() * std::sin(test_angle_rad))),
RotateOrientation(g_test_view_orientation, test_pivot, g_axis_z, test_angle_deg), test_equality_epsilon);
}
}
}
TEST_CASE("Dependent arc-ball camera rotation around Aim pivot < 90 degrees", "[camera][rotate][aim][dependent]")
{
const ArcBallCamera::Pivot test_pivot = ArcBallCamera::Pivot::Aim;
SECTION("Rotation 90 degrees")
{
const float test_equality_epsilon = 0.00001F;
SECTION("Around X-axis")
{
TestDependentCameraRotation(test_pivot, g_test_view_orientation, test_pivot, g_test_dept_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center - Point2F(0.f, g_test_radius_pixels)),
{ g_test_dept_orientation.eye, g_test_dept_orientation.aim, { 0.f, 1.f, 0.f } }, test_equality_epsilon);
}
SECTION("Around Y-axis")
{
TestDependentCameraRotation(test_pivot, g_test_view_orientation, test_pivot, g_test_dept_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center + Point2F(g_test_radius_pixels, 0.f)),
{ { 0.f, 7.f, 10.f }, g_test_dept_orientation.aim, { -1.f, 0.f, 0.f } }, test_equality_epsilon);
}
SECTION("Around Z-axis")
{
TestDependentCameraRotation(test_pivot, g_test_view_orientation, test_pivot, g_test_dept_orientation,
Point2I(static_cast<int>(g_test_screen_center.GetX()), 0),
Point2I(0, static_cast<int>(g_test_screen_center.GetY())),
{ { 0.f, -3.f, 0.f }, g_test_dept_orientation.aim, g_test_dept_orientation.up }, test_equality_epsilon);
}
}
SECTION("Rotation 45 degrees")
{
// Lower equality precision because of integer screen-space coordinates use
const float test_equality_epsilon = 0.1F;
const float test_angle_deg = 45.f;
const float test_angle_rad = test_angle_deg * ConstFloat::RadPerDeg;
SECTION("Around X axis")
{
TestDependentCameraRotation(test_pivot, g_test_view_orientation, test_pivot, g_test_dept_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center + Point2F(0.f, g_test_radius_pixels * std::sin(test_angle_rad))),
RotateOrientation(g_test_dept_orientation, test_pivot, g_axis_x, test_angle_deg), test_equality_epsilon);
}
SECTION("Around Y axis")
{
TestDependentCameraRotation(test_pivot, g_test_view_orientation, test_pivot, g_test_dept_orientation,
static_cast<Point2I>(g_test_screen_center),
static_cast<Point2I>(g_test_screen_center - Point2F(g_test_radius_pixels * std::cos(test_angle_rad), 0.f)),
RotateOrientation(g_test_dept_orientation, test_pivot, g_axis_y, test_angle_deg), test_equality_epsilon);
}
SECTION("Around Z axis")
{
TestDependentCameraRotation(test_pivot, g_test_view_orientation, test_pivot, g_test_dept_orientation,
Point2I(static_cast<int>(g_test_screen_center.GetX()), 0),
static_cast<Point2I>(g_test_screen_center - Point2F(g_test_radius_pixels * std::cos(test_angle_rad), g_test_radius_pixels * std::sin(test_angle_rad))),
RotateOrientation(g_test_dept_orientation, test_pivot, g_axis_z, test_angle_deg), test_equality_epsilon);
}
}
}
| 9,908 |
937 | <reponame>shisheng-1/cyclops
package cyclops.data.talk.arraylist.immutable.stub;
public class ImmutableList<E> {
private final E[] elementData;
private ImmutableList(E[] elementData){
this.elementData=elementData;
}
}
| 94 |
858 | //===-- options.h - jit support ---------------------------------*- C++ -*-===//
//
// LDC – the LLVM D compiler
//
// This file is distributed under the Boost Software License. See the LICENSE
// file for details.
//
//===----------------------------------------------------------------------===//
//
// Jit runtime - compilation options.
//
//===----------------------------------------------------------------------===//
#ifndef OPTIONS_HPP
#define OPTIONS_HPP
#include "slice.h"
bool parseOptions(Slice<Slice<const char>> args,
void (*errs)(void *, const char *, size_t),
void *errsContext);
#endif // OPTIONS_HPP
| 224 |
634 | <gh_stars>100-1000
package com.intellij.vcs.log;
import javax.annotation.Nonnull;
import java.awt.*;
/**
* @author <NAME>
*/
public interface VcsRefType {
/**
* <p>Tells if this reference type should be considered a branch.</p>
* <p>
* <p>Although there are different ref types across different VCSs, generally they can be divided into development branches producing
* separate branches in the graph, and tags which are just handy labels to specific repository states.
* This difference is not clear enough for Git branches or Mercurial bookmarks, which internally have no differences with tags,
* but they are still considered as branches due to their purpose, rather than to their internal structure.</p>
* <p>
* <p>Although this is implementation specific and may change, here are some examples of the difference between branches and not-branches
* considering the VCS Log:
* <ul>
* <li>branch references stop collapsing of long linear branches, while tags don't.</li>
* <li>branches try to keep their color through time, while tags don't affect colors of branches.</li>
* </ul></p>
*/
boolean isBranch();
/**
* Returns the background color which should be used to paint a {@link VcsRef reference label} of this type.
* TODO maybe this is not the right place for color
*/
@Nonnull
Color getBackgroundColor();
}
| 388 |
359 | <reponame>nyx-litenite/never<filename>getopt.c
/*
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "getopt.h"
#include <stdio.h>
#include <string.h>
char * optarg;
int optind = 1;
int optopt;
int opterr;
int optreset;
int getopt(int argc, char * const argv[], const char * optstring)
{
static char * place = "";
const char * oli;
if (optreset || !*place)
{
optreset = 0;
if (optind >= argc || *(place = argv[optind]) != '-')
{
place = "";
return (-1);
}
if (place[1] && *++place == '-')
{
++optind;
place = "";
return (-1);
}
}
if ((optopt = (int)*place++) == (int)':' ||
!(oli = strchr(optstring, optopt)))
{
if (optopt == (int)'-')
{
return (-1);
}
if (!*place)
{
++optind;
}
if (opterr && *optstring != ':')
{
(void)printf("illegal option -- %c\n", optopt);
}
return (int)'?';
}
if (*++oli != ':')
{
optarg = NULL;
if (!*place)
++optind;
}
else
{
if (*place)
optarg = place;
else if (argc <= ++optind)
{
place = "";
if (*optstring == ':')
return (int)':';
if (opterr)
(void)printf("option requires an argument -- %c\n", optopt);
return (int)'?';
}
else
optarg = argv[optind];
place = "";
++optind;
}
return (optopt);
}
| 1,166 |
648 | {"resourceType":"DataElement","id":"ImplementationGuide.page.name","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00"},"url":"http://hl7.org/fhir/DataElement/ImplementationGuide.page.name","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"path":"ImplementationGuide.page.name","short":"Short name shown for navigational assistance","definition":"A short name used to represent this page in navigational structures such as table of contents, bread crumbs, etc.","min":1,"max":"1","type":[{"code":"string"}],"isSummary":true}]} | 148 |
11,699 | #include "short_name.h"
#include "base64.h"
TI_NAMESPACE_BEGIN
namespace {
const std::string alphatable =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // e.g. `if` is not a good var name, but `If`
// does.
const std::string alnumtable =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
}; // namespace
std::string make_short_name_by_id(int id) {
std::string res;
while (id >= alphatable.size()) {
res.push_back(alnumtable[id % alnumtable.size()]);
id /= alnumtable.size();
}
res.push_back(alphatable[id]);
std::reverse(res.begin(), res.end());
return res;
}
TI_NAMESPACE_END
| 297 |
575 | <gh_stars>100-1000
// 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 "chromeos/components/help_app_ui/help_app_untrusted_ui.h"
#include "chromeos/components/help_app_ui/help_app_ui_delegate.h"
#include "chromeos/components/help_app_ui/url_constants.h"
#include "chromeos/grit/chromeos_help_app_bundle_resources.h"
#include "chromeos/grit/chromeos_help_app_bundle_resources_map.h"
#include "chromeos/grit/chromeos_help_app_resources.h"
#include "chromeos/strings/grit/chromeos_strings.h"
#include "content/public/browser/web_ui_data_source.h"
#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/resources/grit/webui_generated_resources.h"
#include "ui/resources/grit/webui_resources.h"
namespace chromeos {
// static
content::WebUIDataSource* CreateHelpAppUntrustedDataSource(
HelpAppUIDelegate* delegate) {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(kChromeUIHelpAppUntrustedURL);
// app.html is the default resource because it has routing logic to handle all
// the other paths.
source->SetDefaultResource(IDR_HELP_APP_APP_HTML);
source->AddResourcePath("app_bin.js", IDR_HELP_APP_APP_BIN_JS);
source->AddResourcePath("load_time_data.js", IDR_WEBUI_JS_LOAD_TIME_DATA_JS);
source->AddResourcePath("help_app_app_scripts.js",
IDR_HELP_APP_APP_SCRIPTS_JS);
source->DisableTrustedTypesCSP();
// Add all resources from chromeos_media_app_bundle.pak.
source->AddResourcePaths(base::make_span(
kChromeosHelpAppBundleResources, kChromeosHelpAppBundleResourcesSize));
// Add device and feature flags.
delegate->PopulateLoadTimeData(source);
source->AddLocalizedString("appName", IDS_HELP_APP_EXPLORE);
source->UseStringsJs();
source->AddFrameAncestor(GURL(kChromeUIHelpAppURL));
// TODO(https://crbug.com/1085328): Audit and tighten CSP.
source->OverrideContentSecurityPolicy(
network::mojom::CSPDirectiveName::DefaultSrc, "");
return source;
}
} // namespace chromeos
| 771 |
1,224 | <reponame>timgates42/processing.py
"""
* List of objects
* based on ArrayListClass <NAME>.
*
* This example demonstrates how to use a Python list to store
* a variable number of objects. Items can be added and removed
* from the list.
*
* Click the mouse to add bouncing balls.
"""
balls = []
ballWidth = 48
# Simple bouncing ball class
class Ball:
def __init__(self, tempX, tempY, tempW):
self.x = tempX
self.y = tempY
self.w = tempW
self.speed = 0
self.gravity = 0.1
self.life = 255
def move(self):
# Add gravity to speed
self.speed = self.speed + self.gravity
# Add speed to y location
self.y = self.y + self.speed
# If square reaches the bottom
# Reverse speed
if self.y > height:
# Dampening
self.speed = self.speed * -0.8
self.y = height
self.life -= 1
def finished(self):
# Balls fade out
return self.life < 0
def display(self):
# Display the circle
fill(0, self.life)
#stroke(0,life)
ellipse(self.x, self.y, self.w, self.w)
def setup():
size(200, 200)
smooth()
noStroke()
# Start by adding one element
balls.append(Ball(width / 2, 0, ballWidth))
def draw():
background(255)
# Count down backwards from the end of the list
for ball in reversed(balls):
ball.move()
ball.display()
if ball.finished():
balls.remove(ball)
def mousePressed():
# A new ball object is added to the list (by default to the end)
balls.append(Ball(mouseX, mouseY, ballWidth))
| 706 |
364 | <reponame>xiaobing007/dagli
package com.linkedin.dagli.handle;
import com.linkedin.dagli.dag.DAG;
import com.linkedin.dagli.dag.DAG1x5;
import com.linkedin.dagli.dag.DAG2x3;
import com.linkedin.dagli.dag.DAGExecutor;
import com.linkedin.dagli.dag.DelayedIdentity;
import com.linkedin.dagli.dag.PreparedDAGExecutor;
import com.linkedin.dagli.dag.Sum;
import com.linkedin.dagli.placeholder.Placeholder;
import com.linkedin.dagli.tuple.Tuple3;
import com.linkedin.dagli.tuple.Tuple5;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/**
* These tests have been greatly reduced from their original purpose as most of handles' former functionality has been
* removed, but are retained for the tests that remain.
*/
public class HandleTest {
// used for testing
private static class SumSubclass extends Sum {
private static final long serialVersionUID = 1;
}
@ParameterizedTest
@MethodSource("com.linkedin.dagli.dag.DAGTest#preparedExecutors")
public void unorderedInputsTest(PreparedDAGExecutor executor) {
Placeholder<Long> input1 = new Placeholder<>();
Placeholder<Long> input2 = new Placeholder<>();
Sum sum1 = new Sum().withInputs(input1, input2);
Sum sum2 = new Sum().withInputs(input2, input1);
Sum sum3 = new SumSubclass().withInputs(input2, input1);
Assertions.assertEquals(sum1, sum2);
Assertions.assertEquals(sum1, sum3);
DAG2x3.Prepared<Long, Long, Long, Long, Long> dag =
DAG.Prepared.withPlaceholders(input1, input2).withOutputs(sum1, sum2, sum3);
Assertions.assertEquals(dag.withExecutor(executor).apply(5L, 6L), Tuple3.of(11L, 11L, 11L));
}
@ParameterizedTest
@MethodSource("com.linkedin.dagli.dag.DAGTest#preparableExecutors")
public void preparedHandleTest(DAGExecutor executor) {
Placeholder<Long> input = new Placeholder<>();
DelayedIdentity<Long> delayedIdentityA1 = new DelayedIdentity<Long>(0).withInput(input);
DelayedIdentity<Long> delayedIdentityA2 = new DelayedIdentity<Long>(0).withInput(input);
DelayedIdentity<Long> delayedIdentityA3 = new DelayedIdentity<Long>(0).withInput(input);
DelayedIdentity<Long> delayedIdentityB1 = new DelayedIdentity<Long>(0).withInput(delayedIdentityA1);
DelayedIdentity<Long> delayedIdentityB2 = new DelayedIdentity<Long>(0).withInput(delayedIdentityA1);
DelayedIdentity<Long> delayedIdentityB3 = new DelayedIdentity<Long>(0).withInput(delayedIdentityA2);
DelayedIdentity<Long> delayedIdentityB4 = new DelayedIdentity<Long>(0).withInput(delayedIdentityA3);
DelayedIdentity<Long> delayedIdentityC1 = new DelayedIdentity<Long>(0).withInput(delayedIdentityB1);
DAG1x5<Long, Long, Long, Long, Long, Long> preparableDAG = DAG.withPlaceholder(input)
.withOutputs(delayedIdentityC1, delayedIdentityA1, delayedIdentityB2, delayedIdentityB3, delayedIdentityB4);
DAG1x5.Prepared<Long, Long, Long, Long, Long, Long> preparedDAG =
preparableDAG.withExecutor(executor).prepare(Arrays.asList(1L, 2L, 3L));
Assertions.assertEquals(preparedDAG.apply(3L), Tuple5.of(3L, 3L, 3L, 3L, 3L));
}
}
| 1,196 |
2,405 | <reponame>kiki-lamb/Arduino_STM32
#ifndef __FLASH_STM32_H
#define __FLASH_STM32_H
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
FLASH_BUSY = 1,
FLASH_ERROR_PG,
FLASH_ERROR_WRP,
FLASH_ERROR_OPT,
FLASH_COMPLETE,
FLASH_TIMEOUT,
FLASH_BAD_ADDRESS
} FLASH_Status;
#define IS_FLASH_ADDRESS(ADDRESS) (((ADDRESS) >= 0x08000000) && ((ADDRESS) < 0x0807FFFF))
FLASH_Status FLASH_WaitForLastOperation(uint32 Timeout);
FLASH_Status FLASH_ErasePage(uint32 Page_Address);
FLASH_Status FLASH_ProgramHalfWord(uint32 Address, uint16 Data);
void FLASH_Unlock(void);
void FLASH_Lock(void);
#ifdef __cplusplus
}
#endif
#endif /* __FLASH_STM32_H */
| 294 |
1,027 | /**
* Global.cpp
*
* Implementation for the global variable
*
* @author <NAME> <<EMAIL>>
* @copyright 2013 Copernica BV
*/
#include "includes.h"
/**
* Namespace
*/
namespace Php {
/**
* Move constructor
* @param global
*/
Global::Global(Global &&global) _NOEXCEPT :
Value(std::move(global)),
_name(global._name),
_exists(global._exists)
{
// remove from other global to avoid double free
global._name = nullptr;
}
/**
* Constructor for non-existing var
*
* @param name Name for the variable that does not exist
*/
Global::Global(const char *name) :
Value(),
_name(zend_string_init(name, ::strlen(name), 1)),
_exists(false) {}
/**
* Alternative constructor for non-existing var
* @param name
*/
Global::Global(const std::string &name) :
Value(),
_name(zend_string_init(name.data(), name.size(), 1)),
_exists(false) {}
/**
* Constructor to wrap zval for existing global bar
* @param name
* @param val
*/
Global::Global(const char *name, struct _zval_struct *val) :
Value(val, true),
_name(zend_string_init(name, ::strlen(name), 1)),
_exists(true) {}
/**
* Alternative constructor to wrap zval
* @param name
* @param val
*/
Global::Global(const std::string &name, struct _zval_struct *val) :
Value(val, true),
_name(zend_string_init(name.data(), name.size(), 1)),
_exists(true) {}
/**
* Destructor
*/
Global::~Global()
{
// release the string
if (_name) zend_string_release(_name);
}
/**
* Function that is called when the value is updated
* @return Value
*/
Global &Global::update()
{
// skip if the variable already exists
if (_exists) return *this;
// add one extra reference because the variable now is a global var too
Z_TRY_ADDREF_P(_val);
// add the variable to the globals
zend_symtable_update_ind(&EG(symbol_table), _name, _val);
// remember that the variable now exists
_exists = true;
// done
return *this;
}
/**
* End of namespace
*/
}
| 744 |
355 | /*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* 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.kurento.orion.entities;
import static com.google.common.collect.Lists.newArrayList;
import java.util.List;
/**
* A context element from Orion.
*
* @author <NAME> (<EMAIL>)
*
*/
public class OrionContextElement {
private String type;
private boolean isPattern;
private String id;
private final List<OrionAttribute<?>> attributes = newArrayList();
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isPattern() {
return isPattern;
}
public void setPattern(boolean isPattern) {
this.isPattern = isPattern;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<OrionAttribute<?>> getAttributes() {
return attributes;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" Type: ").append(type).append("\n");
sb.append(" Id: ").append(id).append("\n");
sb.append(" IsPattern: ").append(isPattern).append("\n");
return sb.toString();
}
}
| 546 |
2,875 | # -*- coding: utf-8 -*-
# @Time : 2017/7/13 下午2:23
# @Author : play4fun
# @File : sift.py
# @Software: PyCharm
"""
sift.py:尺度不变特征变换
关键点 极值点 定位
"""
import cv2
import numpy as np
img = cv2.imread('../data/home.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
kp = sift.detect(gray, None)
img = cv2.drawKeypoints(gray, kp, img)
# 计算关键点描述符
# 使用函数 sift.compute() 来 计算 些关键点的描述符。例如
# kp, des = sift.compute(gray, kp)
kp, des = sift.detectAndCompute(gray,None)
cv2.imwrite('sift_keypoints.jpg', img)
cv2.imshow('sift_keypoints.jpg', img)
cv2.waitKey(0)
| 379 |
1,863 | //
// 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 NVIDIA CORPORATION 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 ``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.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef SNIPPET_VEHICLE_WHEELQUERYRESULT_H
#define SNIPPET_VEHICLE_WHEELQUERYRESULT_H
#include "PxPhysicsAPI.h"
#include <new>
namespace snippetvehicle
{
using namespace physx;
//Data structure for quick setup of wheel query data structures.
class VehicleWheelQueryResults
{
public:
VehicleWheelQueryResults()
: mVehicleWheelQueryResults(NULL)
{
}
~VehicleWheelQueryResults()
{
}
//Allocate wheel results for up to maxNumVehicles with up to maxNumWheelsPerVehicle.
static VehicleWheelQueryResults* allocate(const PxU32 maxNumVehicles, const PxU32 maxNumWheelsPerVehicle, PxAllocatorCallback& allocator)
{
const PxU32 byteSize = sizeof(VehicleWheelQueryResults) + sizeof(PxVehicleWheelQueryResult)*maxNumVehicles + sizeof(PxWheelQueryResult)*maxNumWheelsPerVehicle*maxNumVehicles;
PxU8* buffer = static_cast<PxU8*>(allocator.allocate(byteSize, NULL, NULL, 0));
VehicleWheelQueryResults* vwqr = reinterpret_cast<VehicleWheelQueryResults*>(buffer);
buffer += sizeof(VehicleWheelQueryResults);
vwqr->mVehicleWheelQueryResults = reinterpret_cast<PxVehicleWheelQueryResult*>(buffer);
buffer+=sizeof(PxVehicleWheelQueryResult)*maxNumVehicles;
for(PxU32 i=0;i<maxNumVehicles;i++)
{
new(buffer) PxWheelQueryResult();
vwqr->mVehicleWheelQueryResults[i].wheelQueryResults = reinterpret_cast<PxWheelQueryResult*>(buffer);
vwqr->mVehicleWheelQueryResults[i].nbWheelQueryResults = maxNumWheelsPerVehicle;
buffer += sizeof(PxWheelQueryResult)*maxNumWheelsPerVehicle;
}
return vwqr;
}
//Free allocated buffer for scene queries of suspension raycasts.
void free(PxAllocatorCallback& allocator)
{
allocator.deallocate(this);
}
//Return the PxVehicleWheelQueryResult for a vehicle specified by an index.
PxVehicleWheelQueryResult* getVehicleWheelQueryResults(const PxU32 id)
{
return (mVehicleWheelQueryResults + id);
}
private:
PxVehicleWheelQueryResult* mVehicleWheelQueryResults;
};
} // namespace snippetvehicle
#endif //SNIPPET_VEHICLE_WHEELQUERYRESULT_H
| 1,176 |
2,360 | <reponame>LiamBindle/spack<gh_stars>1000+
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PySoupsieve(PythonPackage):
"""A modern CSS selector implementation for Beautiful Soup."""
homepage = "https://github.com/facelessuser/soupsieve"
pypi = "soupsieve/soupsieve-1.9.3.tar.gz"
version('2.2.1', sha256='052774848f448cf19c7e959adf5566904d525f33a3f8b6ba6f6f8f26ec7de0cc')
version('1.9.6', sha256='7985bacc98c34923a439967c1a602dc4f1e15f923b6fcf02344184f86cc7efaa')
version('1.9.3', sha256='8662843366b8d8779dec4e2f921bebec9afd856a5ff2e82cd419acc5054a1a92')
depends_on('[email protected]:', when='@2.2:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('py-setuptools@42:', when='@2.2:', type='build')
depends_on('py-backports-functools-lru-cache', when='^python@:2', type=('build', 'run'))
| 448 |
607 | <reponame>AIHZP/andysworkshop-stm32plus
/*
* This file is a part of the open source stm32plus library.
* Copyright (c) 2011,2012,2013,2014 <NAME> <www.andybrown.me.uk>
* Please see website for licensing terms.
*/
#pragma once
namespace stm32plus {
/**
* STL compatible forward iterator that can be used to iterate over GpioPinRef
* instances in a port. Instances of this iterator should be obtained from the
* GpioPort object using the begin() and end() methods. Basic usage example:
*
* GpioC<DefaultDigitalInputFeature<1,7,13>,DefaultDigitalOutputFeature<8,9,15>> pc;
*
* for(auto it=pc.begin();it!=pc.end();it++) {
* if(it->getMode()==Gpio::OUTPUT) {
* // do something
* }
* }
*
* This iterator is compatible with algorithms in the <algorithm> and <util/StdExt.h> header
* that take a forward iterator. In common with the STL iterators you are expected to
* be diligent in checking the start and end position using begin() and end() because
* the increment and decrement operators will not check for you.
*/
struct GpioIterator {
Gpio **_pinHandlers;
GPIO_TypeDef *_peripheralAddress;
uint8_t _index;
GpioPinRef _current;
/**
* Default constructor
*/
GpioIterator() {}
/**
* Construct with initial parameters
* @param pinHandlers The base of the sparse array of Gpio pointers
* @param peripheralAddress The GPIO peripheral address
* @param index The initial index for this iterator
*/
GpioIterator(Gpio **pinHandlers,GPIO_TypeDef *peripheralAddress,uint8_t index) {
_pinHandlers=pinHandlers;
_peripheralAddress=peripheralAddress;
_index=index;
}
/**
* Copy constructor
* @param it The iterator to copy from
*/
GpioIterator(const GpioIterator& it) {
_pinHandlers=it._pinHandlers;
_peripheralAddress=it._peripheralAddress;
_index=it._index;
}
/**
* Dereference operator
* @return reference to GpioPinRef object at position
*/
GpioPinRef& operator*() {
Gpio& r(*_pinHandlers[_index]);
r.setSelectedPin(_index);
_current=r;
return _current;
}
/**
* Pointer operator
* @return address of the current object at the index
*/
GpioPinRef *operator->() {
return &(operator*());
}
/**
* Increment the iterator
* @return self reference
*/
GpioIterator& operator++() {
increment();
return *this;
}
/**
* Increment the iterator
* @return self reference
*/
GpioIterator& operator++(int) {
GpioIterator& tmp=*this;
increment();
return tmp;
}
/**
* Decrement the iterator
* @return self reference
*/
GpioIterator& operator--() {
decrement();
return *this;
}
/**
* Decrement the iterator
* @return self reference
*/
GpioIterator& operator--(int) {
GpioIterator& tmp=*this;
increment();
return tmp;
}
/**
* Equality comparison
* @param rhs the other iterator
* @return true if the iterators are logically equivalent
*/
bool operator==(const GpioIterator& rhs) const {
return _peripheralAddress==rhs._peripheralAddress && _index==rhs._index;
}
/**
* Inequality comparison
* @param rhs the other iterator
* @return true if the iterators are not logically equivalent
*/
bool operator!=(const GpioIterator& rhs) const {
return _peripheralAddress!=rhs._peripheralAddress || _index!=rhs._index;
}
/**
* Increment the iterator to the next active pin
*/
void increment() {
do {
_index++;
} while(_pinHandlers[_index]==nullptr && _index!=16);
}
/**
* Decrement the iterator to the next active pin
*/
void decrement() {
do {
_index--;
} while(_pinHandlers[_index]==nullptr);
}
};
}
| 1,595 |
310 | <reponame>luccaportes/DESlib
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# DCS techniques
from deslib.dcs.a_priori import APriori
from deslib.dcs.mcb import MCB
# DES techniques
from deslib.des.des_mi import DESMI
from deslib.des.des_p import DESP
from deslib.des.knop import KNOP
from deslib.des.meta_des import METADES
def setup_classifiers():
rng = np.random.RandomState(123456)
X_dsel, X_test, X_train, y_dsel, y_test, y_train = load_dataset(rng)
# Train a pool of 100 classifiers
pool_classifiers = AdaBoostClassifier(random_state=rng)
pool_classifiers.fit(X_train, y_train)
return pool_classifiers, X_dsel, y_dsel, X_test, y_test
def load_dataset(rng):
# Generate a classification dataset
weights = [0.1, 0.2, 0.7]
X, y = make_classification(n_classes=3, n_samples=2000, n_informative=3,
random_state=rng, weights=weights)
# split the data into training and test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33,
random_state=rng)
# Scale the variables to have 0 mean and unit variance
scalar = StandardScaler()
X_train = scalar.fit_transform(X_train)
X_test = scalar.transform(X_test)
# Split the data into training and DSEL for DS techniques
X_train, X_dsel, y_train, y_dsel = train_test_split(X_train, y_train,
test_size=0.5,
random_state=rng)
# Considering a pool composed of 10 base classifiers
# Calibrating Perceptrons to estimate probabilities
return X_dsel, X_test, X_train, y_dsel, y_test, y_train
def test_desp():
pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()
desp = DESP(pool_classifiers)
desp.fit(X_dsel, y_dsel)
assert np.isclose(desp.score(X_test, y_test), 0.6954545454545454)
def test_mcb():
pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()
rng = np.random.RandomState(123456)
mcb = MCB(pool_classifiers, random_state=rng)
mcb.fit(X_dsel, y_dsel)
assert np.isclose(mcb.score(X_test, y_test), 0.7196969696969697)
def test_apriori():
pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()
rng = np.random.RandomState(123456)
apriori = APriori(pool_classifiers, random_state=rng)
apriori.fit(X_dsel, y_dsel)
assert np.isclose(apriori.score(X_test, y_test), 0.6878787878787879)
def test_meta():
pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()
meta_des = METADES(pool_classifiers)
meta_des.fit(X_dsel, y_dsel)
assert np.isclose(meta_des.score(X_test, y_test), 0.796969696969697)
def test_knop():
pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()
knop = KNOP(pool_classifiers)
knop.fit(X_dsel, y_dsel)
assert np.isclose(knop.score(X_test, y_test), 0.8106060606060606)
def test_mi():
pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()
desmi = DESMI(pool_classifiers, alpha=0.9)
desmi.fit(X_dsel, y_dsel)
assert np.isclose(desmi.score(X_test, y_test), 0.3500000000)
| 1,531 |
1,049 | <reponame>edvlili/Time-Appliance-Project<filename>Time-Card/TEST/ptp/userptp.c
#include <err.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <libgen.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <sys/ioctl.h>
#include <linux/ptp_clock.h>
struct {
const char *ptp_dev;
int channel;
bool show;
bool read;
bool set;
bool enable;
bool pps;
} opt = {
.ptp_dev = "/proc/driver/ocp0/ptp",
};
int
showpin(int fd, int pin)
{
struct ptp_pin_desc desc = {};
int rc;
rc = ioctl(fd, PTP_PIN_GETFUNC, &desc, sizeof(desc));
if (rc)
err(1, "ioctl(GETFUNC)");
printf("pin %d\n", pin);
printf(" name: %s\n", desc.name);
printf(" index: %d\n", desc.index);
printf(" func: %d\n", desc.func);
printf(" chan: %d\n", desc.chan);
return 0;
}
int
showcaps(int fd)
{
struct ptp_clock_caps caps = {};
int i, rc;
rc = ioctl(fd, PTP_CLOCK_GETCAPS, &caps, sizeof(caps));
if (rc)
err(1, "ioctl(GETCAPS)");
printf("max_adj: %d\n", caps.max_adj);
printf("n_alarm: %d\n", caps.n_alarm);
printf("n_ext_ts: %d\n", caps.n_ext_ts);
printf("n_per_out: %d\n", caps.n_per_out);
printf("pps: %d\n", caps.pps);
printf("n_pins: %d\n", caps.n_pins);
// printf("adjust_phase: %d\n", caps.adjust_phase);
for (i = 0; i < caps.n_pins; i++)
showpin(fd, i);
return 0;
}
int
extts_control(int fd, int channel, bool on)
{
struct ptp_extts_request req = {};
int rc;
req.index = channel;
req.flags = on ? PTP_ENABLE_FEATURE : 0;
rc = ioctl(fd, PTP_EXTTS_REQUEST, &req, sizeof(req));
if (rc)
err(1, "ioctl(EXTTS_REQUEST)");
return 0;
}
int
pps_control(int fd, bool on)
{
int rc;
rc = ioctl(fd, PTP_ENABLE_PPS, &on, sizeof(on));
if (rc)
err(1, "ioctl(ENABLE_PPS)");
return 0;
}
void
ptp_control(int fd)
{
const char *state = opt.enable ? "ON" : "OFF";
if (opt.pps) {
printf("pps = %s\n", state);
pps_control(fd, opt.enable);
} else {
printf("channel %d = %s\n", opt.channel, state);
extts_control(fd, opt.channel, opt.enable);
}
}
int
get_msg(int fd)
{
struct ptp_extts_event evt[8];
int n, count;
printf("Reading from PTP device, ^C to abort...\n");
for (;;) {
n = read(fd, &evt, sizeof(evt));
if (n == -1)
err(1, "read");
if (n == 0)
break;
count = n / sizeof(evt[0]);
if (count * sizeof(evt[0]) != n)
errx(1, "size mismatch: %ld vs %d\n",
count * sizeof(evt[0]), n);
for (n = 0; n < count; n++) {
printf("idx: %d time:%lld.%u data:%d\n",
evt[n].index,
evt[n].t.sec, evt[n].t.nsec,
evt[n].rsv[0]);
}
}
return 0;
}
static void
usage(const char *prog)
{
printf("Usage: %s [options] [<extts#|pps> <on|off>]\n", prog);
printf("\t-h: help\n");
printf("\t-d: pps_device\n");
printf("\t-s: show ptp information\n");
printf("\t-r: read ptp timestamps\n");
printf("\textts# = external timestamp channel #, starting at 0\n");
exit(1);
}
#define OPTSTR "d:hrs"
static void
parse_cmdline(int argc, char **argv)
{
char *prog = basename(argv[0]);
int c;
while ((c = getopt(argc, argv, OPTSTR)) != -1) {
switch (c) {
case 'd':
opt.ptp_dev = optarg;
break;
case 'r':
opt.read = true;
break;
case 's':
opt.show = true;
break;
case 'h':
default:
usage(prog);
}
}
if (argc - optind >= 2) {
opt.channel = atoi(argv[optind]);
opt.pps = !strcmp(argv[optind], "pps");
opt.enable = !strcmp(argv[optind + 1], "on");
opt.set = true;
opt.read = true;
}
if (opt.show || opt.read || opt.set)
return;
if (argc != optind)
usage(prog);
opt.show = true;
}
int
main(int argc, char **argv)
{
int fd;
parse_cmdline(argc, argv);
printf("Using PTP device %s\n", opt.ptp_dev);
fd = open(opt.ptp_dev, O_RDWR);
if (fd == -1)
err(1, "open");
if (opt.show)
showcaps(fd);
if (opt.set)
ptp_control(fd);
if (opt.read)
get_msg(fd);
return 0;
}
| 2,109 |
418 | //
// UIAlertView+BFError.h
// OpenShop
//
// Created by <NAME>
// Copyright (c) 2015 Business Factory. All rights reserved.
//
#import "BFError.h"
NS_ASSUME_NONNULL_BEGIN
/**
* `BFError` category of UIAlertView adds ability to present error description with possible
* recovery options. Recovery options are connected to a recovery attempter specified in
* `BFError`. Every recovery option corresponds to the alert view button.
*/
@interface UIAlertView (BFError)
/**
* Creates an alert view with a specified error and completion block to be executed when the
* alert view was dismissed.
*
* @param error The error information.
* @param block The completion block.
* @return The newly-initialized `UIAlertView`.
*/
- (instancetype)initWithError:(BFError *) error completionBlock:(nullable BFErrorCompletionBlock)block;
@end
NS_ASSUME_NONNULL_END
| 244 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-v5rq-2q5p-p82v",
"modified": "2022-05-13T01:23:03Z",
"published": "2022-05-13T01:23:03Z",
"aliases": [
"CVE-2019-9192"
],
"details": "** DISPUTED ** In the GNU C Library (aka glibc or libc6) through 2.29, check_dst_limits_calc_pos_1 in posix/regexec.c has Uncontrolled Recursion, as demonstrated by '(|)(\\\\1\\\\1)*' in grep, a different issue than CVE-2018-20796. NOTE: the software maintainer disputes that this is a vulnerability because the behavior occurs only with a crafted pattern.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2019-9192"
},
{
"type": "WEB",
"url": "https://sourceware.org/bugzilla/show_bug.cgi?id=24269"
},
{
"type": "WEB",
"url": "https://support.f5.com/csp/article/K26346590?utm_source=f5support&utm_medium=RSS"
}
],
"database_specific": {
"cwe_ids": [
"CWE-674"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 565 |
1,687 | <filename>13-Dynamic-Programming-1/13-5-LIS/最大子段和以及相关问题/0053-maximum-subarray/src/Solution.java
public class Solution {
// 方法一:暴力解法(可以不看)
// 时间复杂度:O(N^3)
// 空间复杂度:O(1)
public int maxSubArray(int[] nums) {
int len = nums.length;
int res = Integer.MIN_VALUE;
for (int i = 0; i < len; i++) {
for (int j = 0; j <= i; j++) {
int sum = sumOfSubArray(nums, j, i);
res = Math.max(res, sum);
}
}
return res;
}
private int sumOfSubArray(int[] nums, int left, int right) {
// 子区间的和
int res = 0;
for (int i = left; i <= right; i++) {
res += nums[i];
}
return res;
}
} | 491 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.