max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
6,457 |
package com.intel.realsense.sensor;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.intel.realsense.librealsense.Colorizer;
import com.intel.realsense.librealsense.DepthSensor;
import com.intel.realsense.librealsense.DeviceList;
import com.intel.realsense.librealsense.Device;
import com.intel.realsense.librealsense.DeviceListener;
import com.intel.realsense.librealsense.Frame;
import com.intel.realsense.librealsense.Sensor;
import com.intel.realsense.librealsense.StreamProfile;
import com.intel.realsense.librealsense.StreamFormat;
import com.intel.realsense.librealsense.StreamType;
import com.intel.realsense.librealsense.Extension;
import com.intel.realsense.librealsense.FrameCallback;
import com.intel.realsense.librealsense.GLRsSurfaceView;
import com.intel.realsense.librealsense.RsContext;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "librs sensor example";
private static final int PERMISSIONS_REQUEST_CAMERA = 0;
private boolean mPermissionsGranted = false;
private Context mAppContext;
private TextView mBackGroundText;
private GLRsSurfaceView mGLSurfaceView;
private boolean mIsStreaming = false;
private Colorizer mColorizer;
private RsContext mRsContext;
private Device mDevice;
DepthSensor mDepthSensor = null;
StreamProfile mDepthProfile = null;
StreamProfile mIrProfile = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAppContext = getApplicationContext();
mBackGroundText = findViewById(R.id.connectCameraText);
mGLSurfaceView = findViewById(R.id.glSurfaceView);
mGLSurfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
// Android 9 also requires camera permissions
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.O &&
ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAMERA);
return;
}
mPermissionsGranted = true;
}
@Override
protected void onDestroy() {
super.onDestroy();
mGLSurfaceView.close();
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAMERA);
return;
}
mPermissionsGranted = true;
}
@Override
protected void onResume() {
super.onResume();
if(mPermissionsGranted)
init();
else
Log.e(TAG, "missing permissions");
}
@Override
protected void onPause() {
super.onPause();
stop();
releaseContext();
}
private FrameCallback mFrameHandler = new FrameCallback()
{
@Override
public void onFrame(final Frame f) {
try {
if (f != null) {
if (f.is(Extension.DEPTH_FRAME))
{
try (Frame processed = f.applyFilter(mColorizer)) {
mGLSurfaceView.upload(processed);
}
}
else
{
mGLSurfaceView.upload(f);
}
}
} catch (Exception e) {}
}
};
private void init(){
//RsContext.init must be called once in the application lifetime before any interaction with physical RealSense devices.
//For multi activities applications use the application context instead of the activity context
RsContext.init(mAppContext);
//Register to notifications regarding RealSense devices attach/detach events via the DeviceListener.
mRsContext = new RsContext();
mRsContext.setDevicesChangedCallback(mListener);
mColorizer = new Colorizer();
try(DeviceList dl = mRsContext.queryDevices()){
int num_devices = dl.getDeviceCount();
Log.d(TAG, "devices found: " + num_devices);
if( num_devices> 0) {
mDevice = dl.createDevice(0);
showConnectLabel(false);
assignDepthSensor();
assignProfiles();
start();
}
}
}
private void showConnectLabel(final boolean state){
runOnUiThread(new Runnable() {
@Override
public void run() {
mBackGroundText.setVisibility(state ? View.VISIBLE : View.GONE);
}
});
}
private DeviceListener mListener = new DeviceListener() {
@Override
public void onDeviceAttach() {
showConnectLabel(false);
}
@Override
public void onDeviceDetach() {
showConnectLabel(true);
stop();
}
};
private void configAndStart() throws Exception {
if (mDepthSensor != null) {
if (mDepthProfile == null && mIrProfile == null) {
Toast.makeText(this, "The requested profiles are not available in this device ", Toast.LENGTH_LONG).show();
}
else {
List<StreamProfile> requested_profiles = new ArrayList<StreamProfile>();
if (mDepthProfile != null)
requested_profiles.add(mDepthProfile);
else
Toast.makeText(this, "The depth requested profile is not available in this device ", Toast.LENGTH_LONG).show();
if (mIrProfile != null)
requested_profiles.add(mIrProfile);
else
Toast.makeText(this, "The infrared requested profile is not available in this device ", Toast.LENGTH_LONG).show();
mDepthSensor.openSensor(requested_profiles);
mDepthSensor.start(mFrameHandler);
}
}
}
private synchronized void start() {
if(mIsStreaming)
return;
try{
Log.d(TAG, "try start streaming");
mGLSurfaceView.clear();
mIsStreaming = true;
configAndStart();
Log.d(TAG, "streaming started successfully");
} catch (Exception e) {
Log.e(TAG, "failed to start streaming");
}
}
private synchronized void stop() {
if(!mIsStreaming)
return;
try {
Log.d(TAG, "try stop streaming");
mIsStreaming = false;
if (mDepthSensor != null){
mDepthSensor.stop();
mDepthSensor.closeSensor();
}
mGLSurfaceView.clear();
Log.d(TAG, "streaming stopped successfully");
} catch (Exception e) {
Log.e(TAG, "failed to stop streaming");
}
}
private void releaseContext() {
if (mDevice != null) mDevice.close();
if (mColorizer != null) mColorizer.close();
if(mRsContext != null) {
mRsContext.removeDevicesChangedCallback();
mRsContext.close();
mRsContext = null;
}
}
private void assignDepthSensor() {
List<Sensor> sensors = mDevice.querySensors();
for(Sensor s : sensors)
{
if (s.is(Extension.DEPTH_SENSOR)) {
mDepthSensor = s.as(Extension.DEPTH_SENSOR);
}
}
}
private void assignProfiles() {
if (mDepthSensor != null) {
mDepthProfile = mDepthSensor.findProfile(StreamType.DEPTH, -1, 640, 480, StreamFormat.Z16, 30);
mIrProfile = mDepthSensor.findProfile(StreamType.INFRARED, -1, 640, 480, StreamFormat.Y8, 30);
}
}
}
| 3,902 |
2,792 |
<reponame>daniel-falk/nnabla
# Copyright 2020,2021 Sony Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
import numpy as np
import nnabla as nn
import nnabla.functions as F
from nnabla.ext_utils import get_extension_context, list_extensions
from nnabla.utils.inspection import NanInfTracer
from .models import simple_cnn
def _refresh_inputs_grad(f):
for i in f.inputs:
i.grad.zero()
@pytest.mark.parametrize("batch_size", [8])
@pytest.mark.parametrize("n_class", [5])
@pytest.mark.parametrize("ext_name", list_extensions())
@pytest.mark.parametrize("trace_nan", [False, True])
@pytest.mark.parametrize("trace_inf", [False, True])
def test_nan_inf_tracer(batch_size, n_class, ext_name, trace_nan, trace_inf):
nn.clear_parameters()
ctx = get_extension_context(ext_name)
nn.set_default_context(ctx)
x = nn.Variable.from_numpy_array(
np.random.normal(size=(batch_size, 3, 16, 16)))
t = nn.Variable.from_numpy_array(np.random.randint(low=0, high=n_class,
size=(batch_size, 1)))
y = simple_cnn(x, t, n_class)
must_be_inf = y / F.constant(0, shape=y.shape)
must_be_nan = must_be_inf / must_be_inf
# Refresh all arrays once so as to ensure all grad values are 0.
must_be_nan.visit(_refresh_inputs_grad)
nit = NanInfTracer(trace_nan=trace_nan, trace_inf=trace_inf)
# can be run at any cases without exception.
with nit.trace():
y.forward(clear_no_need_grad=True,
function_post_hook=nit.forward_post_hook)
y.backward(clear_buffer=True,
function_post_hook=nit.backward_post_hook)
nit.check() # this call can also work without exception.
# check nan
if trace_nan:
with pytest.raises(ValueError):
with nit.trace():
must_be_nan.forward(clear_buffer=True,
function_post_hook=nit.forward_post_hook)
with pytest.raises(ValueError):
with nit.trace():
must_be_nan.backward(clear_buffer=True,
function_post_hook=nit.backward_post_hook)
must_be_nan.forward(clear_buffer=True,
function_post_hook=nit.forward_post_hook)
with pytest.raises(ValueError):
nit.check()
must_be_nan.backward(clear_buffer=True,
function_post_hook=nit.backward_post_hook)
with pytest.raises(ValueError):
nit.check()
# check inf
if trace_inf:
with pytest.raises(ValueError):
with nit.trace():
must_be_inf.forward(clear_buffer=True,
function_post_hook=nit.forward_post_hook)
must_be_inf.forward(clear_buffer=True,
function_post_hook=nit.forward_post_hook)
with pytest.raises(ValueError):
nit.check()
| 1,565 |
1,444 |
package mage.cards.k;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.DealsDamageToAPlayerAttachedTriggeredAbility;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Outcome;
import mage.constants.TargetController;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author LevelX2
*/
public final class KeenSense extends CardImpl {
public KeenSense(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{G}");
this.subtype.add(SubType.AURA);
// Enchant creature
TargetPermanent auraTarget = new TargetCreaturePermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.DrawCard));
Ability ability = new EnchantAbility(auraTarget.getTargetName());
this.addAbility(ability);
// Whenever enchanted creature deals damage to an opponent, you may draw a card.
this.addAbility(new DealsDamageToAPlayerAttachedTriggeredAbility(new DrawCardSourceControllerEffect(1), "enchanted creature", true, false, false, TargetController.OPPONENT));
}
private KeenSense(final KeenSense card) {
super(card);
}
@Override
public KeenSense copy() {
return new KeenSense(this);
}
}
| 541 |
3,651 |
<filename>server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/post/OServerCommandPostImportDatabase.java
/*
*
* Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
* 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.orientechnologies.orient.server.network.protocol.http.command.post;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.util.OCommonConst;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.tool.ODatabaseImport;
import com.orientechnologies.orient.server.network.protocol.http.OHttpRequest;
import com.orientechnologies.orient.server.network.protocol.http.OHttpResponse;
import com.orientechnologies.orient.server.network.protocol.http.OHttpUtils;
import com.orientechnologies.orient.server.network.protocol.http.multipart.OHttpMultipartContentBaseParser;
import com.orientechnologies.orient.server.network.protocol.http.multipart.OHttpMultipartDatabaseImportContentParser;
import com.orientechnologies.orient.server.network.protocol.http.multipart.OHttpMultipartRequestCommand;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
/** @author <NAME> (<EMAIL>--at--<EMAIL>) */
public class OServerCommandPostImportDatabase
extends OHttpMultipartRequestCommand<String, InputStream> implements OCommandOutputListener {
protected static final String[] NAMES = {"POST|import/*"};
protected StringWriter buffer;
protected InputStream importData;
protected ODatabaseDocumentInternal database;
@Override
public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
if (!iRequest.isMultipart()) {
database = getProfiledDatabaseInstance(iRequest);
try {
ODatabaseImport importer =
new ODatabaseImport(
database, new ByteArrayInputStream(iRequest.getContent().getBytes("UTF8")), this);
for (Map.Entry<String, String> option : iRequest.getParameters().entrySet())
importer.setOption(option.getKey(), option.getValue());
importer.importDatabase();
iResponse.send(
OHttpUtils.STATUS_OK_CODE,
OHttpUtils.STATUS_OK_DESCRIPTION,
OHttpUtils.CONTENT_JSON,
"{\"responseText\": \"Database imported Correctly, see server log for more informations.\"}",
null);
} catch (Exception e) {
iResponse.send(
OHttpUtils.STATUS_INTERNALERROR_CODE,
e.getMessage() + ": " + e.getCause() != null ? e.getCause().getMessage() : "",
OHttpUtils.CONTENT_JSON,
"{\"responseText\": \""
+ e.getMessage()
+ ": "
+ (e.getCause() != null ? e.getCause().getMessage() : "")
+ "\"}",
null);
} finally {
if (database != null) database.close();
database = null;
}
} else if (iRequest.getMultipartStream() == null
|| iRequest.getMultipartStream().available() <= 0) {
iResponse.send(
OHttpUtils.STATUS_INVALIDMETHOD_CODE,
"Content stream is null or empty",
OHttpUtils.CONTENT_TEXT_PLAIN,
"Content stream is null or empty",
null);
} else {
database = getProfiledDatabaseInstance(iRequest);
try {
parse(
iRequest,
iResponse,
new OHttpMultipartContentBaseParser(),
new OHttpMultipartDatabaseImportContentParser(),
database);
ODatabaseImport importer = new ODatabaseImport(database, importData, this);
for (Map.Entry<String, String> option : iRequest.getParameters().entrySet())
importer.setOption(option.getKey(), option.getValue());
importer.importDatabase();
iResponse.send(
OHttpUtils.STATUS_OK_CODE,
OHttpUtils.STATUS_OK_DESCRIPTION,
OHttpUtils.CONTENT_JSON,
"{\"responseText\": \"Database imported Correctly, see server log for more informations.\"}",
null);
} catch (Exception e) {
iResponse.send(
OHttpUtils.STATUS_INTERNALERROR_CODE,
e.getMessage() + ": " + e.getCause() != null ? e.getCause().getMessage() : "",
OHttpUtils.CONTENT_JSON,
"{\"responseText\": \""
+ e.getMessage()
+ ": "
+ (e.getCause() != null ? e.getCause().getMessage() : "")
+ "\"}",
null);
} finally {
if (database != null) database.close();
database = null;
if (importData != null) importData.close();
importData = null;
}
}
return false;
}
@Override
protected void processBaseContent(
final OHttpRequest iRequest,
final String iContentResult,
final HashMap<String, String> headers)
throws Exception {}
@Override
protected void processFileContent(
final OHttpRequest iRequest,
final InputStream iContentResult,
final HashMap<String, String> headers)
throws Exception {
importData = iContentResult;
}
@Override
protected String getDocumentParamenterName() {
return "linkValue";
}
@Override
protected String getFileParamenterName() {
return "databaseFile";
}
@Override
public String[] getNames() {
return NAMES;
}
@Override
public void onMessage(String iText) {
final String msg = iText.startsWith("\n") ? iText.substring(1) : iText;
OLogManager.instance().info(this, msg, OCommonConst.EMPTY_OBJECT_ARRAY);
}
}
| 2,429 |
1,338 |
#ifndef _MIDI_PORT_H
#define _MIDI_PORT_H
#include <Midi.h>
class BMidiConsumer;
class BMidiProducer;
namespace BPrivate { class BMidiPortGlue; }
class BMidiPort : public BMidi {
public:
BMidiPort(const char* name = NULL);
~BMidiPort();
status_t InitCheck() const;
status_t Open(const char* name);
void Close();
const char* PortName() const;
virtual void NoteOff(
uchar channel, uchar note, uchar velocity, uint32 time = B_NOW);
virtual void NoteOn(
uchar channel, uchar note, uchar velocity, uint32 time = B_NOW);
virtual void KeyPressure(
uchar channel, uchar note, uchar pressure, uint32 time = B_NOW);
virtual void ControlChange(
uchar channel, uchar controlNumber, uchar controlValue,
uint32 time = B_NOW);
virtual void ProgramChange(
uchar channel, uchar programNumber, uint32 time = B_NOW);
virtual void ChannelPressure(
uchar channel, uchar pressure, uint32 time = B_NOW);
virtual void PitchBend(
uchar channel, uchar lsb, uchar msb, uint32 time = B_NOW);
virtual void SystemExclusive(
void* data, size_t length, uint32 time = B_NOW);
virtual void SystemCommon(
uchar status, uchar data0, uchar data2, uint32 time = B_NOW);
virtual void SystemRealTime(uchar status, uint32 time = B_NOW);
virtual status_t Start();
virtual void Stop();
int32 CountDevices();
status_t GetDeviceName(
int32 n, char* name, size_t bufSize = B_OS_NAME_LENGTH);
private:
typedef BMidi super;
friend class BPrivate::BMidiPortGlue;
virtual void _ReservedMidiPort1();
virtual void _ReservedMidiPort2();
virtual void _ReservedMidiPort3();
virtual void Run();
void ScanDevices();
void EmptyDeviceList();
BMidiLocalProducer* fLocalSource;
BMidiLocalConsumer* fLocalSink;
BMidiProducer* fRemoteSource;
BMidiConsumer* fRemoteSink;
char* fPortName;
status_t fStatus;
BList* fDevices;
uint32 _reserved[1];
};
#endif // _MIDI_PORT_H
| 670 |
4,140 |
/*
* 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.hadoop.hive.serde2.binarysortable;
import java.util.List;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.ByteStream.Output;
import org.apache.hadoop.hive.serde2.binarysortable.BinarySortableSerDe;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
public class BinarySortableSerDeWithEndPrefix extends BinarySortableSerDe {
public static void serializeStruct(Output byteStream, Object[] fieldData,
List<ObjectInspector> fieldOis, boolean endPrefix) throws SerDeException {
for (int i = 0; i < fieldData.length; i++) {
serialize(byteStream, fieldData[i], fieldOis.get(i), false, ZERO, ONE);
}
if (endPrefix) {
if (fieldData[fieldData.length-1]!=null) {
byteStream.getData()[byteStream.getLength()-1]++;
} else {
byteStream.getData()[byteStream.getLength()-1]+=2;
}
}
}
}
| 558 |
18,621 |
<filename>superset/datasets/commands/create.py
# 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 logging
from typing import Any, Dict, List, Optional
from flask_appbuilder.models.sqla import Model
from flask_appbuilder.security.sqla.models import User
from marshmallow import ValidationError
from sqlalchemy.exc import SQLAlchemyError
from superset.commands.base import BaseCommand, CreateMixin
from superset.dao.exceptions import DAOCreateFailedError
from superset.datasets.commands.exceptions import (
DatabaseNotFoundValidationError,
DatasetCreateFailedError,
DatasetExistsValidationError,
DatasetInvalidError,
TableNotFoundValidationError,
)
from superset.datasets.dao import DatasetDAO
from superset.extensions import db, security_manager
logger = logging.getLogger(__name__)
class CreateDatasetCommand(CreateMixin, BaseCommand):
def __init__(self, user: User, data: Dict[str, Any]):
self._actor = user
self._properties = data.copy()
def run(self) -> Model:
self.validate()
try:
# Creates SqlaTable (Dataset)
dataset = DatasetDAO.create(self._properties, commit=False)
# Updates columns and metrics from the dataset
dataset.fetch_metadata(commit=False)
# Add datasource access permission
security_manager.add_permission_view_menu(
"datasource_access", dataset.get_perm()
)
# Add schema access permission if exists
if dataset.schema:
security_manager.add_permission_view_menu(
"schema_access", dataset.schema_perm
)
db.session.commit()
except (SQLAlchemyError, DAOCreateFailedError) as ex:
logger.warning(ex, exc_info=True)
db.session.rollback()
raise DatasetCreateFailedError() from ex
return dataset
def validate(self) -> None:
exceptions: List[ValidationError] = []
database_id = self._properties["database"]
table_name = self._properties["table_name"]
schema = self._properties.get("schema", None)
owner_ids: Optional[List[int]] = self._properties.get("owners")
# Validate uniqueness
if not DatasetDAO.validate_uniqueness(database_id, schema, table_name):
exceptions.append(DatasetExistsValidationError(table_name))
# Validate/Populate database
database = DatasetDAO.get_database_by_id(database_id)
if not database:
exceptions.append(DatabaseNotFoundValidationError())
self._properties["database"] = database
# Validate table exists on dataset
if database and not DatasetDAO.validate_table_exists(
database, table_name, schema
):
exceptions.append(TableNotFoundValidationError(table_name))
try:
owners = self.populate_owners(self._actor, owner_ids)
self._properties["owners"] = owners
except ValidationError as ex:
exceptions.append(ex)
if exceptions:
exception = DatasetInvalidError()
exception.add_list(exceptions)
raise exception
| 1,488 |
4,345 |
//
// Depot.h
// Coding_iOS
//
// Created by <NAME> on 14-9-17.
// Copyright (c) 2014年 Coding. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Depot : NSObject
@property (strong, nonatomic) NSNumber *id;
@property (readwrite, nonatomic, strong) NSString *name, *path, *depot_path, *default_branch;
@end
| 121 |
310 |
/// \file DefaultModuleCache.cpp
#include "chi/DefaultModuleCache.hpp"
#include <llvm-c/BitWriter.h>
#include <cassert>
#include "chi/BitcodeParser.hpp"
#include "chi/Context.hpp"
#include "chi/ModuleCache.hpp"
#include "chi/Support/Result.hpp"
namespace chi {
DefaultModuleCache::DefaultModuleCache(chi::Context& ctx) : ModuleCache{ctx} {}
Result DefaultModuleCache::cacheModule(const std::filesystem::path& moduleName,
LLVMModuleRef compiledModule, time_point timeAtFileRead) {
assert(!moduleName.empty() &&
"Cannot pass a empty module name to DefaultModuleCache::cacheModule");
Result res;
auto cachePath = cachePathForModule(moduleName);
// make the directories
std::filesystem::create_directories(cachePath.parent_path());
// open & write
if (LLVMWriteBitcodeToFile(compiledModule, cachePath.string().c_str()) != 0) {
res.addEntry("EUKN", "Failed to open file", {{"Path", cachePath.string()}});
return res;
}
// set age to be correct
std::filesystem::last_write_time(cachePath, timeAtFileRead);
return res;
}
std::filesystem::path DefaultModuleCache::cachePathForModule(
const std::filesystem::path& moduleName) const {
return context().workspacePath() / "lib" / (moduleName.string() + ".bc");
}
void DefaultModuleCache::invalidateCache(const std::filesystem::path& moduleName) {
assert(!moduleName.empty() && "Cannot pass empty path to DefaultModuleCache::invalidateCache");
auto cachePath = cachePathForModule(moduleName);
std::filesystem::remove(cachePath);
}
ModuleCache::time_point DefaultModuleCache::cacheUpdateTime(
const std::filesystem::path& moduleName) const {
return std::filesystem::last_write_time(cachePathForModule(moduleName));
}
OwnedLLVMModule DefaultModuleCache::retrieveFromCache(const std::filesystem::path& moduleName,
time_point atLeastThisNew) {
assert(!moduleName.empty() &&
"Cannot pass empty path to DefaultModuleCache::retrieveFromCache");
auto cachePath = cachePathForModule(moduleName);
// if there is no cache, then there is nothing to retrieve
if (!std::filesystem::is_regular_file(cachePath)) { return nullptr; }
// see if the cache is new enough
auto cacheEditTime = cacheUpdateTime(moduleName);
if (cacheEditTime < atLeastThisNew) { return nullptr; }
// read the cache
OwnedLLVMModule fetchedMod;
auto res = parseBitcodeFile(cachePath, context().llvmContext(), &fetchedMod);
if (!res) { return nullptr; }
return fetchedMod;
}
} // namespace chi
| 908 |
990 |
<reponame>krmartin/sparkling-water
{
"bundles" : [
{ "bundleName" : "apache2", "licenseName" : "Apache License, Version 2.0", "licenseUrl" : "http://www.apache.org/licenses/LICENSE-2.0" },
{ "bundleName" : "MIT", "licenseName" : "The MIT License", "licenseUrl" : "https://opensource.org/licenses/MIT"},
{ "bundleName" : "apache1.1", "licenseName": "Apache Software License, version 1.1", "licenseUrl": "https://www.apache.org/licenses/LICENSE-1.1"},
{ "bundleName" : "3clauseBSD", "licenseName": "The 3-Clause BSD License", "licenseUrl": "https://opensource.org/licenses/BSD-3-Clause"},
{ "bundleName" : "2clauseBSD", "licenseName": "The 2-Clause BSD License", "licenseUrl": "https://opensource.org/licenses/BSD-2-Clause"}
],
"transformationRules" : [
{ "bundleName" : "apache2", "licenseNamePattern" : "The Apache Software License, Version 2.0"},
{ "bundleName" : "apache2", "licenseNamePattern" : "Apache 2.0"},
{ "bundleName" : "apache2", "licenseNamePattern" : "Apache 2"},
{ "bundleName" : "apache2", "licenseNamePattern" : "Apache License 2.0"},
{ "bundleName" : "apache2", "licenseNamePattern" : "The Apache License, Version 2.0"},
{ "bundleName" : "apache2", "licenseNamePattern" : "Apache License, Version 2.0"},
{ "bundleName" : "apache2", "licenseNamePattern" : "Apache 2.0"},
{ "bundleName" : "apache2", "licenseNamePattern" : "Apache License, Version 2.0"},
{ "bundleName" : "apache2", "licenseNamePattern" : "Apache 2.0 License"},
{ "bundleName" : "apache2", "licenseNamePattern" : "Apache Software License - Version 2.0"},
{ "bundleName" : "apache2", "licenseNamePattern" : "Apache License (v2.0)"},
{ "bundleName" : "2clauseBSD", "licenseNamePattern" : "BSD 2-Clause License"},
{ "bundleName" : "3clauseBSD", "licenseNamePattern" : "3-Clause BSD License"},
{ "bundleName" : "3clauseBSD", "licenseNamePattern" : "BSD 3-clausee"},
{ "bundleName" : "3clauseBSD", "licenseNamePattern" : "BSD 3 Clause"},
{ "bundleName" : "MIT", "licenseNamePattern" : "MIT License"},
{ "bundleName" : "MIT", "licenseNamePattern" : "MIT license"},
{ "bundleName" : "MIT", "licenseNamePattern" : "MIT"}
]
}
| 825 |
20,325 |
<reponame>yogeshpatel276052/generator-jhipster
{
"error": {
"title": "Page d'erreur !",
"http": {
"400": "Mauvaise requête.",
"403": "Vous n'avez pas les droits pour accéder à cette page.",
"404": "La page n'existe pas.",
"405": "Le verbe HTTP que vous avez utilisé n'est pas reconnu par cet URL.",
"500": "Erreur interne du serveur."
},
"concurrencyFailure": "Un autre utilisateur a modifié ces données en même temps que vous. Vos changements n'ont pas été sauvegardés.",
"validation": "Erreur de validation côté serveur."
}
}
| 306 |
305 |
<reponame>medismailben/llvm-project<gh_stars>100-1000
/*
* lock-nested-unrelated.c -- Archer testcase
*/
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
//
// See tools/archer/LICENSE.txt for details.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// RUN: %libarcher-compile-and-run-race | FileCheck %s
// REQUIRES: tsan
#include <omp.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
int var = 0;
omp_nest_lock_t lock;
omp_init_nest_lock(&lock);
#pragma omp parallel num_threads(2) shared(var)
{
omp_set_nest_lock(&lock);
omp_set_nest_lock(&lock);
// Dummy locking.
omp_unset_nest_lock(&lock);
omp_unset_nest_lock(&lock);
var++;
}
omp_destroy_nest_lock(&lock);
fprintf(stderr, "DONE\n");
}
// CHECK: WARNING: ThreadSanitizer: data race
// CHECK-NEXT: {{(Write|Read)}} of size 4
// CHECK-NEXT: #0 {{.*}}lock-nested-unrelated.c:33
// CHECK: Previous write of size 4
// CHECK-NEXT: #0 {{.*}}lock-nested-unrelated.c:33
// CHECK: DONE
// CHECK: ThreadSanitizer: reported 1 warnings
| 475 |
2,053 |
/*
* Copyright 2015 the original author or authors.
* @https://github.com/scouter-project/scouter
*
* 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 scouter.lang.constants;
/**
* @author <NAME> (<EMAIL>) on 2017. 8. 28.
*/
public class ParamConstant {
public static final String USER_ID = "id";
public static final String USER_PASSWROD = "<PASSWORD>";
public static final String OBJ_TYPE = "objType";
public static final String OBJ_HASH = "objHash";
public static final String COUNTER = "counter";
public static final String KEY = "key";
public static final String VALUE = "value";
public static final String KEY_SPACE = "keySpace";
public static final String KEY_VALUE = "kv";
public static final String TTL = "ttl";
public static final Long TTL_PERMANENT = -1L;
public static final String DATE = "date";
public static final String TIME = "time";
public static final String SDATE = "sDate";
public static final String EDATE = "eDate";
public static final String STIME = "stime";
public static final String ETIME = "etime";
public static final String HASH = "hash";
public static final String TYPE = "type";
public static final String OFFSET_LOOP = "loop";
public static final String OFFSET_INDEX = "index";
public static final String XLOG_COUNT = "count";
public static final String XLOG_MAX_COUNT = "max";
public static final String XLOG_START_TIME = "stime";
public static final String XLOG_END_TIME = "etime";
public static final String XLOG_LAST_BUCKET_TIME = "lastBucketTime";
public static final String XLOG_PAGE_COUNT = "pageCount";
public static final String XLOG_SERVICE="service";
public static final String XLOG_LOGIN="login";
public static final String XLOG_IP="ip";
public static final String XLOG_DESC="desc";
public static final String XLOG_TEXT_1="text1";
public static final String XLOG_TEXT_2="text2";
public static final String XLOG_TEXT_3="text3";
public static final String XLOG_TEXT_4="text4";
public static final String XLOG_TEXT_5="text5";
public static final String XLOG_TXID = "txid";
public static final String XLOG_GXID = "gxid";
public static final String PROFILE_MAX = "max";
public static final String XLOG_RESULT_LAST_TIME = "lastXLogTime";
public static final String XLOG_RESULT_LAST_TXID = "lastTxid";
public static final String XLOG_RESULT_HAS_MORE = "hasMore";
public static final String ACTIVE_SERVICE_STEP1 = "act1";
public static final String ACTIVE_SERVICE_STEP2 = "act2";
public static final String ACTIVE_SERVICE_STEP3 = "act3";
public static final String TEXT_TYPE = "type";
public static final String TEXT_DICTKEY = "hash";
}
| 1,053 |
1,030 |
"""
Precompute ngram counts of captions, to accelerate cider computation during training time.
"""
import os
import json
import argparse
from six.moves import cPickle
import captioning.utils.misc as utils
from collections import defaultdict
import sys
sys.path.append("cider")
from pyciderevalcap.ciderD.ciderD_scorer import CiderScorer
def get_doc_freq(refs, params):
tmp = CiderScorer(df_mode="corpus")
for ref in refs:
tmp.cook_append(None, ref)
tmp.compute_doc_freq()
return tmp.document_frequency, len(tmp.crefs)
def build_dict(imgs, wtoi, params):
wtoi['<eos>'] = 0
count_imgs = 0
refs_words = []
refs_idxs = []
for img in imgs:
if (params['split'] == img['split']) or \
(params['split'] == 'train' and img['split'] == 'restval') or \
(params['split'] == 'all'):
#(params['split'] == 'val' and img['split'] == 'restval') or \
ref_words = []
ref_idxs = []
for sent in img['sentences']:
if hasattr(params, 'bpe'):
sent['tokens'] = params.bpe.segment(' '.join(sent['tokens'])).strip().split(' ')
tmp_tokens = sent['tokens'] + ['<eos>']
tmp_tokens = [_ if _ in wtoi else 'UNK' for _ in tmp_tokens]
ref_words.append(' '.join(tmp_tokens))
ref_idxs.append(' '.join([str(wtoi[_]) for _ in tmp_tokens]))
refs_words.append(ref_words)
refs_idxs.append(ref_idxs)
count_imgs += 1
print('total imgs:', count_imgs)
ngram_words, count_refs = get_doc_freq(refs_words, params)
ngram_idxs, count_refs = get_doc_freq(refs_idxs, params)
print('count_refs:', count_refs)
return ngram_words, ngram_idxs, count_refs
def main(params):
imgs = json.load(open(params['input_json'], 'r'))
dict_json = json.load(open(params['dict_json'], 'r'))
itow = dict_json['ix_to_word']
wtoi = {w:i for i,w in itow.items()}
# Load bpe
if 'bpe' in dict_json:
import tempfile
import codecs
codes_f = tempfile.NamedTemporaryFile(delete=False)
codes_f.close()
with open(codes_f.name, 'w') as f:
f.write(dict_json['bpe'])
with codecs.open(codes_f.name, encoding='UTF-8') as codes:
bpe = apply_bpe.BPE(codes)
params.bpe = bpe
imgs = imgs['images']
ngram_words, ngram_idxs, ref_len = build_dict(imgs, wtoi, params)
utils.pickle_dump({'document_frequency': ngram_words, 'ref_len': ref_len}, open(params['output_pkl']+'-words.p','wb'))
utils.pickle_dump({'document_frequency': ngram_idxs, 'ref_len': ref_len}, open(params['output_pkl']+'-idxs.p','wb'))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# input json
parser.add_argument('--input_json', default='data/dataset_coco.json', help='input json file to process into hdf5')
parser.add_argument('--dict_json', default='data/cocotalk.json', help='output json file')
parser.add_argument('--output_pkl', default='data/coco-all', help='output pickle file')
parser.add_argument('--split', default='all', help='test, val, train, all')
args = parser.parse_args()
params = vars(args) # convert to ordinary dict
main(params)
| 1,480 |
2,151 |
<filename>app/src/main/java/org/chromium/chrome/browser/compositor/resources/ResourceFactory.java
// 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.
package org.chromium.chrome.browser.compositor.resources;
import android.graphics.Rect;
import org.chromium.base.annotations.JNINamespace;
/**
* Utility class for creating native resources.
*/
@JNINamespace("android")
public class ResourceFactory {
public static long createToolbarContainerResource(
Rect toolbarPosition, Rect locationBarPosition, int shadowHeight) {
return nativeCreateToolbarContainerResource(toolbarPosition.left, toolbarPosition.top,
toolbarPosition.right, toolbarPosition.bottom, locationBarPosition.left,
locationBarPosition.top, locationBarPosition.right, locationBarPosition.bottom,
shadowHeight);
}
private static native long nativeCreateToolbarContainerResource(int toolbarLeft, int toolbarTop,
int toolbarRight, int toolbarBottom, int locationBarLeft, int locationBarTop,
int locationBarRight, int locationBarBottom, int shadowHeight);
}
| 386 |
2,504 |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#pragma once
#include "Scenario3_Size.g.h"
namespace winrt::SDKTemplate::implementation
{
struct Scenario3_Size : Scenario3_SizeT<Scenario3_Size>
{
Scenario3_Size();
fire_and_forget OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
fire_and_forget ShowWindowBtn_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
private:
Windows::UI::WindowManagement::AppWindow appWindow{ nullptr };
Windows::UI::Xaml::Controls::Frame appWindowFrame{};
void OnWindowClosed(Windows::UI::WindowManagement::AppWindow const& sender, IInspectable const&);
};
}
namespace winrt::SDKTemplate::factory_implementation
{
struct Scenario3_Size : Scenario3_SizeT<Scenario3_Size, implementation::Scenario3_Size>
{
};
}
| 465 |
669 |
<reponame>mszhanyi/onnxruntime<gh_stars>100-1000
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
################################################################################
# Refer to orttraining_test_checkpoint.py for an overview about Checkpoint tests
################################################################################
import os
import pickle
from numpy.testing import assert_allclose
import argparse
import glob
import torch
import torch.distributed as dist
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import onnxruntime
from onnxruntime.training import checkpoint, optim
from _test_helpers import distributed_setup, load_model_optim_state_and_eval, aggregate_states
from _test_commons import assert_all_states_close_ort
def verify_optimizer_state_match(device, opts, checkpoint_dir, world_rank, use_lamb=False):
expected_optim_state, trainer_optim_state = load_model_optim_state_and_eval(device, opts, use_lamb)
# verify optimizer states are matching by:
# - Saving the state dictionaries for each rank in the zero run in a pickle file.
# - Loading them one by one and aggregating them into a single state dictionary
# - Comparing this aggregated state dictionary with the full dummy optimizer dictionary (expected_optim_state)
# created by load_model_optim_state_and_eval
with open(os.path.join(checkpoint_dir, "distributed_state_" + str(world_rank) + ".pkl"), "wb") as f:
pickle.dump(trainer_optim_state, f)
dist.barrier()
if world_rank == 0:
# aggregate states and compare
aggregated_state_dict = aggregate_states(
checkpoint_dir, filename_prefix="distributed_state", state_dict_key_name=None
)
# compare all states
assert_all_states_close_ort(aggregated_state_dict, expected_optim_state, reshape_states=True)
dist.barrier()
os.remove(os.path.join(checkpoint_dir, "distributed_state_" + str(world_rank) + ".pkl"))
@distributed_setup
def test_optim_load_to_distributed_zero_full_precision_adam(
world_rank, world_size, device, checkpoint_dir="checkpoint_dir/distributed_zero/full_precision/adam/"
):
opts = {
"device": {"id": device},
"distributed": {
"world_rank": world_rank,
"world_size": world_size,
"allreduce_post_accumulation": True,
"deepspeed_zero_optimization": {"stage": 1},
},
"debug": {"deterministic_compute": True},
}
verify_optimizer_state_match(device, opts, checkpoint_dir, world_rank, use_lamb=False)
@distributed_setup
def test_optim_load_to_distributed_zero_mixed_precision_adam(
world_rank, world_size, device, checkpoint_dir="checkpoint_dir/distributed_zero/mixed_precision/adam/"
):
opts = {
"device": {"id": device},
"mixed_precision": {"enabled": True},
"distributed": {
"world_rank": world_rank,
"world_size": world_size,
"allreduce_post_accumulation": True,
"deepspeed_zero_optimization": {"stage": 1},
},
"debug": {"deterministic_compute": True},
}
verify_optimizer_state_match(device, opts, checkpoint_dir, world_rank, use_lamb=False)
@distributed_setup
def test_optim_load_to_distributed_zero_full_precision_lamb(
world_rank, world_size, device, checkpoint_dir="checkpoint_dir/distributed_zero/full_precision/lamb/"
):
opts = {
"device": {"id": device},
"distributed": {
"world_rank": world_rank,
"world_size": world_size,
"allreduce_post_accumulation": True,
"deepspeed_zero_optimization": {"stage": 1},
},
"debug": {"deterministic_compute": True},
}
verify_optimizer_state_match(device, opts, checkpoint_dir, world_rank, use_lamb=True)
@distributed_setup
def test_optim_load_to_distributed_zero_mixed_precision_lamb(
world_rank, world_size, device, checkpoint_dir="checkpoint_dir/distributed_zero/mixed_precision/lamb/"
):
opts = {
"device": {"id": device},
"mixed_precision": {"enabled": True},
"distributed": {
"world_rank": world_rank,
"world_size": world_size,
"allreduce_post_accumulation": True,
"deepspeed_zero_optimization": {"stage": 1},
},
"debug": {"deterministic_compute": True},
}
verify_optimizer_state_match(device, opts, checkpoint_dir, world_rank, use_lamb=True)
function_map = {
# load to zero configs
"test_optim_load_to_distributed_zero_full_precision_adam": test_optim_load_to_distributed_zero_full_precision_adam,
"test_optim_load_to_distributed_zero_mixed_precision_adam": test_optim_load_to_distributed_zero_mixed_precision_adam,
"test_optim_load_to_distributed_zero_mixed_precision_lamb": test_optim_load_to_distributed_zero_mixed_precision_lamb,
"test_optim_load_to_distributed_zero_full_precision_lamb": test_optim_load_to_distributed_zero_full_precision_lamb,
}
parser = argparse.ArgumentParser(description="Test loading of initial optimizer state for Zero-1")
parser.add_argument(
"--scenario", choices=function_map.keys(), help="training scenario to test loaded states", required=True
)
parser.add_argument("--checkpoint_dir", help="path to the saved states directory", required=True)
args = parser.parse_args()
function_map[args.scenario](checkpoint_dir=args.checkpoint_dir)
| 2,091 |
7,482 |
/*
* @ : Copyright (c) 2021 Phytium Information Technology, Inc.
*
* SPDX-License-Identifier: Apache-2.0.
*
* @Date: 2021-04-29 10:40:47
* @LastEditTime: 2021-04-29 10:40:47
* @Description: Description of file
* @Modify History:
* * * Ver Who Date Changes
* * ----- ------ -------- --------------------------------------
*/
#include "ft_can.h"
#include "ft_can_hw.h"
#include "ft_assert.h"
#include "ft_types.h"
ft_error_t FCan_SetHandler(FCan_t *Can_p, u32 HandlerType, FCan_irqHandler_t IrqCallBackFunc, void *IrqCallBackRef)
{
ft_error_t status = FCAN_SUCCESS;
Ft_assertNonvoid(Can_p != NULL);
Ft_assertNonvoid(Can_p->IsReady == FT_COMPONENT_IS_READLY);
switch (HandlerType)
{
case FCAN_HANDLER_SEND:
Can_p->SendHandler = IrqCallBackFunc;
Can_p->SendRef = IrqCallBackRef;
break;
case FCAN_HANDLER_RECV:
Can_p->RecvHandler = IrqCallBackFunc;
Can_p->RecvRef = IrqCallBackRef;
break;
case FCAN_HANDLER_ERROR:
Can_p->ErrorHandler = IrqCallBackFunc;
Can_p->ErrorRef = IrqCallBackRef;
break;
default:
status = FCAN_FAILURE;
}
return status;
}
static void FCan_TxInterrupt(FCan_t *Can_p)
{
FCan_Config_t *Config_p = &Can_p->Config;
FCan_SetBit(Config_p->CanBaseAddress, FCAN_INTR_OFFSET, FCAN_INTR_TEIC_MASK | FCAN_INTR_REIC_MASK);
if (0 != Can_p->TxFifoCnt)
{
Can_p->TxFifoCnt--;
FCan_ClearBit(Config_p->CanBaseAddress, FCAN_CTRL_OFFSET, FCAN_CTRL_XFER_MASK);
FCan_SetBit(Config_p->CanBaseAddress, FCAN_CTRL_OFFSET, FCAN_CTRL_TXREQ_MASK);
FCan_SetBit(Config_p->CanBaseAddress, FCAN_CTRL_OFFSET, FCAN_CTRL_XFER_MASK);
}
else
{
if (Can_p->SendHandler)
{
Can_p->SendHandler(Can_p->SendRef);
}
}
}
static void FCan_ErrorInterrupt(FCan_t *Can_p)
{
if (Can_p->ErrorHandler)
{
Can_p->ErrorHandler(Can_p->ErrorRef);
}
}
static void FCan_RxInterrupt(FCan_t *Can_p)
{
if (Can_p->RecvHandler)
{
Can_p->RecvHandler(Can_p->RecvRef);
}
}
void FCan_IntrHandler(void *InstancePtr)
{
u32 Irq;
FCan_t *Can_p = (FCan_t *)InstancePtr;
FCan_Config_t *Config_p;
Ft_assertVoid(Can_p != NULL);
Ft_assertVoid(Can_p->IsReady == FT_COMPONENT_IS_READLY);
Config_p = &Can_p->Config;
Irq = FCan_ReadReg(Config_p->CanBaseAddress, FCAN_INTR_OFFSET);
if (0 == Irq)
{
return;
}
/* Check for the type of error interrupt and Processing it */
if (Irq & FCAN_INTR_TEIS_MASK)
{
Irq &= ~FCAN_INTR_REIS_MASK;
FCan_TxInterrupt(Can_p);
}
if (Irq & (FCAN_INTR_EIS_MASK | FCAN_INTR_RFIS_MASK |
FCAN_INTR_BOIS_MASK | FCAN_INTR_PEIS_MASK | FCAN_INTR_PWIS_MASK))
{
FCan_SetBit(Config_p->CanBaseAddress, FCAN_INTR_OFFSET, (FCAN_INTR_EIC_MASK | FCAN_INTR_RFIC_MASK | FCAN_INTR_BOIC_MASK | FCAN_INTR_PEIC_MASK | FCAN_INTR_PWIC_MASK));
FCan_ErrorInterrupt(Can_p);
}
if (Irq & FCAN_INTR_REIS_MASK)
{
FCan_SetBit(Config_p->CanBaseAddress, FCAN_INTR_OFFSET, FCAN_INTR_REIE_MASK);
FCan_RxInterrupt(Can_p);
FCan_SetBit(Config_p->CanBaseAddress, FCAN_INTR_OFFSET, FCAN_INTR_REIC_MASK);
FCan_SetBit(Config_p->CanBaseAddress, FCAN_INTR_OFFSET, FCAN_INTR_REIE_MASK);
}
}
| 1,711 |
1,250 |
{
"name": "url-shortener",
"version": "1.0.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "url-shortener",
"version": "1.0.0",
"license": "MIT",
"dependencies": {
"form-data": "^4.0.0",
"hashids": "^2.0.0"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k="
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/hashids": {
"version": "2.2.10",
"resolved": "https://registry.npmjs.org/hashids/-/hashids-2.2.10.tgz",
"integrity": "<KEY>
},
"node_modules/mime-db": {
"version": "1.51.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz",
"integrity": "<KEY>
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.34",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz",
"integrity": "<KEY>
"dependencies": {
"mime-db": "1.51.0"
},
"engines": {
"node": ">= 0.6"
}
}
},
"dependencies": {
"asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k="
},
"combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "<KEY>
"requires": {
"delayed-stream": "~1.0.0"
}
},
"delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk="
},
"form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "<KEY>
"requires": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
}
},
"hashids": {
"version": "2.2.10",
"resolved": "https://registry.npmjs.org/hashids/-/hashids-2.2.10.tgz",
"integrity": "sha512-nXnYums7F8B5Y+GSThutLPlKMaamW1yjWNZVt0WModiJfdjaDZHnhYTWblS+h1OoBx3yjwiBwxldPP3nIbFSSA=="
},
"mime-db": {
"version": "1.51.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz",
"integrity": "<KEY>
},
"mime-types": {
"version": "2.1.34",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz",
"integrity": "<KEY>
"requires": {
"mime-db": "1.51.0"
}
}
}
}
| 2,192 |
2,637 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 <NAME> <<EMAIL>>
*
* 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.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_DFU_RUNTIME)
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "dfu_rt_device.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void dfu_rtd_init(void)
{
}
void dfu_rtd_reset(uint8_t rhport)
{
(void) rhport;
}
uint16_t dfu_rtd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len)
{
(void) rhport;
(void) max_len;
// Ensure this is DFU Runtime
TU_VERIFY((itf_desc->bInterfaceSubClass == TUD_DFU_APP_SUBCLASS) &&
(itf_desc->bInterfaceProtocol == DFU_PROTOCOL_RT), 0);
uint8_t const * p_desc = tu_desc_next( itf_desc );
uint16_t drv_len = sizeof(tusb_desc_interface_t);
if ( TUSB_DESC_FUNCTIONAL == tu_desc_type(p_desc) )
{
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
return drv_len;
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool dfu_rtd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request)
{
// nothing to do with DATA or ACK stage
if ( stage != CONTROL_STAGE_SETUP ) return true;
TU_VERIFY(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE);
// dfu-util will try to claim the interface with SET_INTERFACE request before sending DFU request
if ( TUSB_REQ_TYPE_STANDARD == request->bmRequestType_bit.type &&
TUSB_REQ_SET_INTERFACE == request->bRequest )
{
tud_control_status(rhport, request);
return true;
}
// Handle class request only from here
TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
switch (request->bRequest)
{
case DFU_REQUEST_DETACH:
{
TU_LOG2(" DFU RT Request: DETACH\r\n");
tud_control_status(rhport, request);
tud_dfu_runtime_reboot_to_dfu_cb();
}
break;
case DFU_REQUEST_GETSTATUS:
{
TU_LOG2(" DFU RT Request: GETSTATUS\r\n");
dfu_status_response_t resp;
// Status = OK, Poll timeout is ignored during RT, State = APP_IDLE, IString = 0
memset(&resp, 0x00, sizeof(dfu_status_response_t));
tud_control_xfer(rhport, request, &resp, sizeof(dfu_status_response_t));
}
break;
default:
{
TU_LOG2(" DFU RT Unexpected Request: %d\r\n", request->bRequest);
return false; // stall unsupported request
}
}
return true;
}
#endif
| 1,415 |
3,882 |
"""Tests for reloading generated pyi."""
from pytype import file_utils
from pytype.pytd import pytd_utils
from pytype.tests import test_base
class ReingestTest(test_base.BaseTest):
"""Tests for reloading the pyi we generate."""
def test_container(self):
ty = self.Infer("""
class Container:
def Add(self):
pass
class A(Container):
pass
""", deep=False)
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(ty))
self.Check("""
# u.py
from foo import A
A().Add()
""", pythonpath=[d.path])
def test_union(self):
ty = self.Infer("""
class Union:
pass
x = {"Union": Union}
""", deep=False)
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(ty))
self.Check("""
from foo import Union
""", pythonpath=[d.path])
def test_identity_decorators(self):
foo = self.Infer("""
def decorate(f):
return f
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
ty = self.Infer("""
import foo
@foo.decorate
def f():
return 3
def g():
return f()
""", pythonpath=[d.path])
self.assertTypesMatchPytd(ty, """
foo = ... # type: module
def f() -> int: ...
def g() -> int: ...
""")
@test_base.skip("Needs better handling of Union[Callable, f] in output.py.")
def test_maybe_identity_decorators(self):
foo = self.Infer("""
def maybe_decorate(f):
return f or (lambda *args: 42)
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
ty = self.Infer("""
import foo
@foo.maybe_decorate
def f():
return 3
def g():
return f()
""", pythonpath=[d.path])
self.assertTypesMatchPytd(ty, """
foo = ... # type: module
def f() -> int: ...
def g() -> int: ...
""")
def test_namedtuple(self):
foo = self.Infer("""
import collections
X = collections.namedtuple("X", ["a", "b"])
""", deep=False)
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check("""
import foo
foo.X(0, 0)
foo.X(a=0, b=0)
""", pythonpath=[d.path])
def test_new_chain(self):
foo = self.Infer("""
class X:
def __new__(cls, x):
return super(X, cls).__new__(cls)
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check("""
import foo
class Y(foo.X):
def __new__(cls, x):
return super(Y, cls).__new__(cls, x)
def __init__(self, x):
self.x = x
Y("x").x
""", pythonpath=[d.path])
def test_namedtuple_subclass(self):
foo = self.Infer("""
import collections
class X(collections.namedtuple("X", ["a"])):
def __new__(cls, a, b):
_ = b
return super(X, cls).__new__(cls, a)
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
_, errors = self.InferWithErrors("""
import foo
foo.X("hello", "world")
foo.X(42) # missing-parameter[e]
""", pythonpath=[d.path])
self.assertErrorRegexes(errors, {"e": r"b.*__new__"})
def test_alias(self):
foo = self.Infer("""
class _Foo:
def __new__(cls, _):
return super(_Foo, cls).__new__(cls)
Foo = _Foo
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check("""
import foo
foo.Foo("hello world")
""", pythonpath=[d.path])
def test_dynamic_attributes(self):
foo1 = self.Infer("""
HAS_DYNAMIC_ATTRIBUTES = True
""")
foo2 = self.Infer("""
has_dynamic_attributes = True
""")
with file_utils.Tempdir() as d:
d.create_file("foo1.pyi", pytd_utils.Print(foo1))
d.create_file("foo2.pyi", pytd_utils.Print(foo2))
d.create_file("bar.pyi", """
from foo1 import xyz
from foo2 import zyx
""")
self.Check("""
import foo1
import foo2
import bar
foo1.abc
foo2.abc
bar.xyz
bar.zyx
""", pythonpath=[d.path])
def test_inherited_mutation(self):
foo = self.Infer("""
class MyList(list):
write = list.append
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
ty = self.Infer("""
import foo
lst = foo.MyList()
lst.write(42)
""", pythonpath=[d.path])
# MyList is not parameterized because it inherits from List[Any].
self.assertTypesMatchPytd(ty, """
foo = ... # type: module
lst = ... # type: foo.MyList
""")
@test_base.skip("Need to give MyList.write the right self mutation.")
def test_inherited_mutation_in_generic_class(self):
foo = self.Infer("""
from typing import List, TypeVar
T = TypeVar("T")
class MyList(List[T]):
write = list.append
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
ty = self.Infer("""
import foo
lst = foo.MyList()
lst.write(42)
""", pythonpath=[d.path])
self.assertTypesMatchPytd(ty, """
foo = ... # type: module
lst = ... # type: foo.MyList[int]
""")
def test_instantiate_imported_generic(self):
foo = self.Infer("""
from typing import Generic, TypeVar
T = TypeVar('T')
class Foo(Generic[T]):
def __init__(self):
pass
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
ty = self.Infer("""
import foo
x = foo.Foo[int]()
""", pythonpath=[d.path])
self.assertTypesMatchPytd(ty, """
foo: module
x: foo.Foo[int]
""")
class StrictNoneTest(test_base.BaseTest):
"""Tests for strict none."""
def test_pyi_return_constant(self):
foo = self.Infer("""
x = None
def f():
return x
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check("""
import foo
def g():
return foo.f().upper()
""", pythonpath=[d.path])
def test_pyi_yield_constant(self):
foo = self.Infer("""
x = None
def f():
yield x
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check("""
import foo
def g():
return [v.upper() for v in foo.f()]
""", pythonpath=[d.path])
def test_pyi_return_contained_constant(self):
foo = self.Infer("""
x = None
def f():
return [x]
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check("""
import foo
def g():
return [v.upper() for v in foo.f()]
""", pythonpath=[d.path])
def test_pyi_return_attribute(self):
foo = self.Infer("""
class Foo:
x = None
def f():
return Foo.x
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check("""
import foo
def g():
return foo.f().upper()
""", pythonpath=[d.path])
def test_no_return(self):
foo = self.Infer("""
def fail():
raise ValueError()
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check("""
import foo
def g():
x = "hello" if __random__ else None
if x is None:
foo.fail()
return x.upper()
""", pythonpath=[d.path])
def test_context_manager_subclass(self):
foo = self.Infer("""
class Foo:
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
return None
""")
with file_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check("""
import foo
class Bar(foo.Foo):
x = None
with Bar() as bar:
bar.x
""", pythonpath=[d.path])
if __name__ == "__main__":
test_base.main()
| 4,168 |
2,529 |
/* 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.
*/
/* Memory handler for a plain memory divided in slot.
* This one uses plain memory.
*/
#include "ap_slotmem.h"
#define AP_SLOTMEM_IS_PREGRAB(t) (t->type & AP_SLOTMEM_TYPE_PREGRAB)
struct ap_slotmem_instance_t {
char *name; /* per segment name */
void *base; /* data set start */
apr_size_t size; /* size of each memory slot */
unsigned int num; /* number of mem slots */
apr_pool_t *gpool; /* per segment global pool */
char *inuse; /* in-use flag table*/
ap_slotmem_type_t type; /* type-specific flags */
struct ap_slotmem_instance_t *next; /* location of next allocated segment */
};
/* global pool and list of slotmem we are handling */
static struct ap_slotmem_instance_t *globallistmem = NULL;
static apr_pool_t *gpool = NULL;
static apr_status_t slotmem_do(ap_slotmem_instance_t *mem, ap_slotmem_callback_fn_t *func, void *data, apr_pool_t *pool)
{
unsigned int i;
char *ptr;
char *inuse;
apr_status_t retval = APR_SUCCESS;
if (!mem)
return APR_ENOSHMAVAIL;
ptr = (char *)mem->base;
inuse = mem->inuse;
for (i = 0; i < mem->num; i++, inuse++) {
if (!AP_SLOTMEM_IS_PREGRAB(mem) ||
(AP_SLOTMEM_IS_PREGRAB(mem) && *inuse)) {
retval = func((void *) ptr, data, pool);
if (retval != APR_SUCCESS)
break;
}
ptr += mem->size;
}
return retval;
}
static apr_status_t slotmem_create(ap_slotmem_instance_t **new, const char *name, apr_size_t item_size, unsigned int item_num, ap_slotmem_type_t type, apr_pool_t *pool)
{
ap_slotmem_instance_t *res;
ap_slotmem_instance_t *next = globallistmem;
apr_size_t basesize = (item_size * item_num);
const char *fname;
if (name) {
if (name[0] == ':')
fname = name;
else
fname = ap_runtime_dir_relative(pool, name);
/* first try to attach to existing slotmem */
if (next) {
for (;;) {
if (strcmp(next->name, fname) == 0) {
/* we already have it */
*new = next;
return APR_SUCCESS;
}
if (!next->next) {
break;
}
next = next->next;
}
}
}
else
fname = "anonymous";
/* create the memory using the gpool */
res = (ap_slotmem_instance_t *) apr_pcalloc(gpool, sizeof(ap_slotmem_instance_t));
res->base = apr_pcalloc(gpool, basesize + (item_num * sizeof(char)));
if (!res->base)
return APR_ENOSHMAVAIL;
/* For the chained slotmem stuff */
res->name = apr_pstrdup(gpool, fname);
res->size = item_size;
res->num = item_num;
res->next = NULL;
res->type = type;
res->inuse = (char *)res->base + basesize;
if (globallistmem == NULL)
globallistmem = res;
else
next->next = res;
*new = res;
return APR_SUCCESS;
}
static apr_status_t slotmem_attach(ap_slotmem_instance_t **new, const char *name, apr_size_t *item_size, unsigned int *item_num, apr_pool_t *pool)
{
ap_slotmem_instance_t *next = globallistmem;
const char *fname;
if (name) {
if (name[0] == ':')
fname = name;
else
fname = ap_runtime_dir_relative(pool, name);
}
else
return APR_ENOSHMAVAIL;
/* first try to attach to existing slotmem */
while (next) {
if (strcmp(next->name, fname) == 0) {
/* we already have it */
*new = next;
*item_size = next->size;
*item_num = next->num;
return APR_SUCCESS;
}
next = next->next;
}
return APR_ENOSHMAVAIL;
}
static apr_status_t slotmem_dptr(ap_slotmem_instance_t *score, unsigned int id, void **mem)
{
char *ptr;
if (!score)
return APR_ENOSHMAVAIL;
if (id >= score->num)
return APR_EINVAL;
ptr = (char *)score->base + score->size * id;
if (!ptr)
return APR_ENOSHMAVAIL;
*mem = ptr;
return APR_SUCCESS;
}
static apr_status_t slotmem_get(ap_slotmem_instance_t *slot, unsigned int id, unsigned char *dest, apr_size_t dest_len)
{
void *ptr;
char *inuse;
apr_status_t ret;
if (!slot) {
return APR_ENOSHMAVAIL;
}
inuse = slot->inuse + id;
if (id >= slot->num) {
return APR_EINVAL;
}
if (AP_SLOTMEM_IS_PREGRAB(slot) && !*inuse) {
return APR_NOTFOUND;
}
ret = slotmem_dptr(slot, id, &ptr);
if (ret != APR_SUCCESS) {
return ret;
}
*inuse=1;
memcpy(dest, ptr, dest_len); /* bounds check? */
return APR_SUCCESS;
}
static apr_status_t slotmem_put(ap_slotmem_instance_t *slot, unsigned int id, unsigned char *src, apr_size_t src_len)
{
void *ptr;
char *inuse;
apr_status_t ret;
if (!slot) {
return APR_ENOSHMAVAIL;
}
inuse = slot->inuse + id;
if (id >= slot->num) {
return APR_EINVAL;
}
if (AP_SLOTMEM_IS_PREGRAB(slot) && !*inuse) {
return APR_NOTFOUND;
}
ret = slotmem_dptr(slot, id, &ptr);
if (ret != APR_SUCCESS) {
return ret;
}
*inuse=1;
memcpy(ptr, src, src_len); /* bounds check? */
return APR_SUCCESS;
}
static unsigned int slotmem_num_slots(ap_slotmem_instance_t *slot)
{
return slot->num;
}
static unsigned int slotmem_num_free_slots(ap_slotmem_instance_t *slot)
{
unsigned int i, counter=0;
char *inuse = slot->inuse;
for (i = 0; i < slot->num; i++, inuse++) {
if (!*inuse)
counter++;
}
return counter;
}
static apr_size_t slotmem_slot_size(ap_slotmem_instance_t *slot)
{
return slot->size;
}
/*
* XXXX: if !AP_SLOTMEM_IS_PREGRAB, then still worry about
* inuse for grab and return?
*/
static apr_status_t slotmem_grab(ap_slotmem_instance_t *slot, unsigned int *id)
{
unsigned int i;
char *inuse;
if (!slot) {
return APR_ENOSHMAVAIL;
}
inuse = slot->inuse;
for (i = 0; i < slot->num; i++, inuse++) {
if (!*inuse) {
break;
}
}
if (i >= slot->num) {
return APR_EINVAL;
}
*inuse = 1;
*id = i;
return APR_SUCCESS;
}
static apr_status_t slotmem_fgrab(ap_slotmem_instance_t *slot, unsigned int id)
{
char *inuse;
if (!slot) {
return APR_ENOSHMAVAIL;
}
if (id >= slot->num) {
return APR_EINVAL;
}
inuse = slot->inuse + id;
*inuse = 1;
return APR_SUCCESS;
}
static apr_status_t slotmem_release(ap_slotmem_instance_t *slot, unsigned int id)
{
char *inuse;
if (!slot) {
return APR_ENOSHMAVAIL;
}
inuse = slot->inuse;
if (id >= slot->num) {
return APR_EINVAL;
}
if (!inuse[id] ) {
return APR_NOTFOUND;
}
inuse[id] = 0;
return APR_SUCCESS;
}
static const ap_slotmem_provider_t storage = {
"plainmem",
&slotmem_do,
&slotmem_create,
&slotmem_attach,
&slotmem_dptr,
&slotmem_get,
&slotmem_put,
&slotmem_num_slots,
&slotmem_num_free_slots,
&slotmem_slot_size,
&slotmem_grab,
&slotmem_release,
&slotmem_fgrab
};
static int pre_config(apr_pool_t *p, apr_pool_t *plog,
apr_pool_t *ptemp)
{
gpool = p;
return OK;
}
static void ap_slotmem_plain_register_hook(apr_pool_t *p)
{
/* XXX: static const char * const prePos[] = { "mod_slotmem.c", NULL }; */
ap_register_provider(p, AP_SLOTMEM_PROVIDER_GROUP, "plain",
AP_SLOTMEM_PROVIDER_VERSION, &storage);
ap_hook_pre_config(pre_config, NULL, NULL, APR_HOOK_MIDDLE);
}
AP_DECLARE_MODULE(slotmem_plain) = {
STANDARD20_MODULE_STUFF,
NULL, /* create per-directory config structure */
NULL, /* merge per-directory config structures */
NULL, /* create per-server config structure */
NULL, /* merge per-server config structures */
NULL, /* command apr_table_t */
ap_slotmem_plain_register_hook /* register hooks */
};
| 4,253 |
1,529 |
/*
* Copyright (c) 2016 咖枯 <<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.colorfulnews.utils;
import android.os.SystemClock;
/**
* @author 咖枯
* @version 1.0 2016/7/4
*/
public class ClickUtil {
private static long mLastClickTime = 0;
private static final int SPACE_TIME = 500;
public static boolean isFastDoubleClick() {
long time = SystemClock.elapsedRealtime();
if (time - mLastClickTime <= SPACE_TIME) {
return true;
} else {
mLastClickTime = time;
return false;
}
}
}
| 380 |
352 |
# coding=utf-8
import sys, traceback, argparse
from py4j.java_gateway import java_import, JavaGateway, GatewayClient
from py4j.java_collections import JavaMap, JavaList
from pyspark.sql.types import *
from mistpy.executable_entry import load_entry
from mistpy.context_wrapper import ContextWrapper
from mistpy.decorators import SPARK_CONTEXT, SPARK_SESSION, SPARK_STREAMING, HIVE_CONTEXT, HIVE_SESSION, SQL_CONTEXT
def to_python_types(any):
python_any = any
if isinstance(any, JavaMap):
python_any = dict()
for key, value in any.items():
python_any[key] = to_python_types(value)
elif isinstance(any, JavaList):
python_any = list()
for i, value in enumerate(any):
python_any.insert(i, to_python_types(value))
return python_any
def initialized_context_value(_gateway, context_wrapper, selected_spark_argument):
if selected_spark_argument == SPARK_CONTEXT:
argument = context_wrapper.context
elif selected_spark_argument == SPARK_SESSION:
context_wrapper.set_session(_gateway)
argument = context_wrapper.session
elif selected_spark_argument == HIVE_SESSION:
context_wrapper.set_hive_session(_gateway)
argument = context_wrapper.session
elif selected_spark_argument == HIVE_CONTEXT:
context_wrapper.set_hive_context(_gateway)
argument = context_wrapper.hive_context
elif selected_spark_argument == SPARK_STREAMING:
context_wrapper.set_streaming_context(_gateway)
argument = context_wrapper.streaming_context
elif selected_spark_argument == SQL_CONTEXT:
context_wrapper.set_sql_context(_gateway)
argument = context_wrapper.sql_context
else:
raise Exception('Unknown spark argument type: ' + selected_spark_argument)
return argument
def execution_cmd(args):
_client = GatewayClient(port=args.gateway_port)
_gateway = JavaGateway(_client, auto_convert=True)
_entry_point = _gateway.entry_point
java_import(_gateway.jvm, "org.apache.spark.SparkContext")
java_import(_gateway.jvm, "org.apache.spark.SparkEnv")
java_import(_gateway.jvm, "org.apache.spark.SparkConf")
java_import(_gateway.jvm, "org.apache.spark.streaming.*")
java_import(_gateway.jvm, "org.apache.spark.streaming.api.java.*")
java_import(_gateway.jvm, "org.apache.spark.streaming.api.python.*")
java_import(_gateway.jvm, "org.apache.spark.api.java.*")
java_import(_gateway.jvm, "org.apache.spark.api.python.*")
java_import(_gateway.jvm, "org.apache.spark.mllib.api.python.*")
java_import(_gateway.jvm, "org.apache.spark.*")
java_import(_gateway.jvm, "org.apache.spark.sql.*")
java_import(_gateway.jvm, 'java.util.*')
context_wrapper = ContextWrapper()
context_wrapper.set_context(_gateway)
configuration_wrapper = _entry_point.configurationWrapper()
error_wrapper = _entry_point.error()
path = configuration_wrapper.path()
fn_name = configuration_wrapper.className()
parameters = configuration_wrapper.parameters()
data_wrapper = _entry_point.data()
try:
executable_entry = load_entry(path, fn_name)
selected_spark_argument = executable_entry.selected_spark_argument
argument = initialized_context_value(_gateway, context_wrapper, selected_spark_argument)
result = executable_entry.invoke(argument, to_python_types(parameters))
data_wrapper.set(result)
except Exception:
error_wrapper.set(traceback.format_exc())
| 1,339 |
6,989 |
import numpy as np
from ._fortran import *
from scipy._lib._version import NumpyVersion
# Don't use deprecated Numpy C API. Define this to a fixed version instead of
# NPY_API_VERSION in order not to break compilation for released Scipy versions
# when Numpy introduces a new deprecation. Use in setup.py::
#
# config.add_extension('_name', sources=['source_fname'], **numpy_nodepr_api)
#
if NumpyVersion(np.__version__) >= '1.10.0.dev':
numpy_nodepr_api = dict(define_macros=[("NPY_NO_DEPRECATED_API",
"NPY_1_9_API_VERSION")])
else:
numpy_nodepr_api = dict()
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester
| 290 |
1,056 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.j2ee.jboss4.ide.ui;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.jar.Attributes;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.annotations.common.NonNull;
import org.netbeans.api.annotations.common.NullAllowed;
import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
import org.netbeans.modules.j2ee.jboss4.JBDeploymentManager;
import org.netbeans.modules.j2ee.jboss4.ide.ui.JBPluginUtils.Version;
import org.netbeans.modules.j2ee.jboss4.util.JBProperties;
import org.openide.filesystems.JarFileSystem;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author <NAME>
*/
public class JBPluginUtils {
public static final String SERVER_4_XML = File.separator + "deploy" + File.separator + // NOI18N
"jbossweb-tomcat55.sar" + File.separator + "server.xml"; // NOI18N
public static final String SERVER_4_2_XML = File.separator + "deploy" + File.separator + // NOI18N
"jboss-web.deployer" + File.separator + "server.xml"; // NOI18N
// public static final String SERVER_5_XML = File.separator + "deployers" + File.separator + // NOI18N
// "jbossweb.deployer" + File.separator + "server.xml"; // NOI18N
public static final String SERVER_5_XML = File.separator + "deploy" + File.separator + // NOI18N
"jbossweb.sar" + File.separator + "server.xml"; // NOI18N
public static final Version JBOSS_5_0_0 = new Version("5.0.0"); // NOI18N
public static final Version JBOSS_5_0_1 = new Version("5.0.1"); // NOI18N
public static final Version JBOSS_6_0_0 = new Version("6.0.0"); // NOI18N
public static final Version JBOSS_7_0_0 = new Version("7.0.0"); // NOI18N
public static final Version JBOSS_7_1_0 = new Version("7.1.0"); // NOI18N
private static final Logger LOGGER = Logger.getLogger(JBPluginUtils.class.getName());
private static final Version DOM4J_SERVER = new Version("4.0.4"); // NOI18N
public static final String LIB = "lib" + File.separator;
public static final String MODULES_BASE = "modules" + File.separator;
public static final String MODULES_BASE_7 = "modules" + File.separator + "system"
+ File.separator + "layers" + File.separator + "base" + File.separator;
public static final String CLIENT = "client" + File.separator;
public static final String COMMON = "common" + File.separator;
// For JBoss 5.0 under JBOSS_ROOT_DIR/lib
public static final String[] JBOSS5_CLIENT_LIST = {
"javassist.jar",
"jbossall-client.jar",
"jboss-deployment.jar",
"jnp-client.jar",
"jbosssx-client.jar",
"jboss-client.jar",
"jboss-common-core.jar",
"jboss-logging-log4j.jar",
"jboss-logging-spi.jar"
};
public static List<URL> getJB5ClientClasspath(String serverRoot) throws
MalformedURLException {
List<URL> urlList = new ArrayList<URL>();
File clientDir = new File(serverRoot, JBPluginUtils.CLIENT);
if (clientDir.exists()) {
for (String jar : JBPluginUtils.JBOSS5_CLIENT_LIST) {
File jarFile = new File(clientDir, jar);
if (jarFile.exists()) {
urlList.add(jarFile.toURI().toURL());
}
}
}
return urlList;
}
//--------------- checking for possible domain directory -------------
private static List<String> domainRequirements4x;
private static synchronized List<String> getDomainRequirements4x() {
if (domainRequirements4x == null) {
domainRequirements4x = new ArrayList<String>(13);
Collections.addAll(domainRequirements4x,
"conf", // NOI18N
"deploy", // NOI18N
"lib", // NOI18N
"conf/jboss-service.xml", // NOI18N
"lib/jboss-j2ee.jar", // NOI18N
"lib/jboss.jar", // NOI18N
"lib/jbosssx.jar", // NOI18N
"lib/jboss-transaction.jar", // NOI18N
"lib/jmx-adaptor-plugin.jar", // NOI18N
"lib/jnpserver.jar", // NOI18N
"lib/log4j.jar", // NOI18N
// not present in 4.0.0
//"lib/xmlentitymgr.jar", // NOI18N
"deploy/jmx-invoker-service.xml"); // NOI18N
}
return domainRequirements4x;
}
private static List<String> domainRequirements5x;
private static synchronized List<String> getDomainRequirements5x() {
if (domainRequirements5x == null) {
domainRequirements5x = new ArrayList<String>(11);
Collections.addAll(domainRequirements5x,
"conf", // NOI18N
"deploy", // NOI18N
"deployers", // NOI18N
"lib", // NOI18N
"conf/jboss-service.xml", // NOI18N
"conf/bootstrap.xml", // NOI18N
"deploy/jmx-invoker-service.xml" // NOI18N
);
}
return domainRequirements5x;
}
private static List<String> domainRequirements6x;
private static synchronized List<String> getDomainRequirements6x() {
if (domainRequirements6x == null) {
domainRequirements6x = new ArrayList<String>(11);
Collections.addAll(domainRequirements6x,
"conf", // NOI18N
"deploy", // NOI18N
"deployers", // NOI18N
"lib", // NOI18N
"conf/jboss-service.xml", // NOI18N
"conf/bootstrap.xml", // NOI18N
"deploy/hdscanner-jboss-beans.xml" // NOI18N
);
}
return domainRequirements6x;
}
private static List<String> domainRequirements7x;
private static synchronized List<String> getDomainRequirements7x() {
if (domainRequirements7x == null) {
domainRequirements7x = new ArrayList<String>(11);
Collections.addAll(domainRequirements7x,
"configuration", // NOI18N
"deployments", // NOI18N
"lib" // NOI18N
);
}
return domainRequirements7x;
}
//--------------- checking for possible server directory -------------
private static List<String> serverRequirements4x;
private static synchronized List<String> getServerRequirements4x() {
if (serverRequirements4x == null) {
serverRequirements4x = new ArrayList<String>(6);
Collections.addAll(serverRequirements4x,
"bin", // NOI18N
"client", // NOI18N
"lib", // NOI18N
"server", // NOI18N
"lib/jboss-common.jar", // NOI18N
"lib/endorsed/resolver.jar"); // NOI18N
}
return serverRequirements4x;
}
private static List<String> serverAlterRequirements4x;
private static synchronized List<String> getServerAlterRequirements4x() {
if (serverAlterRequirements4x == null) {
serverAlterRequirements4x = new ArrayList<String>(8);
Collections.addAll(serverAlterRequirements4x,
"bin", // NOI18N
"client", // NOI18N
"lib", // NOI18N
"server", // NOI18N
"lib/jboss-common.jar", // NOI18N
"client/jaxb-xjc.jar", // NOI18N
"client/jaxb-impl.jar", // NOI18N
"client/jaxb-api.jar"); // NOI18N
}
return serverAlterRequirements4x;
}
private static List<String> serverRequirements5And6x;
private static synchronized List<String> getServerRequirements5And6x() {
if (serverRequirements5And6x == null) {
serverRequirements5And6x = new ArrayList<String>(6);
Collections.addAll(serverRequirements5And6x,
"bin", // NOI18N
"client", // NOI18N
"lib", // NOI18N
"server", // NOI18N
"common/lib", // NOI18N
"lib/dom4j.jar", // NOI18N
"lib/jboss-dependency.jar", // NOI18N
"lib/jboss-common-core.jar", // NOI18N
"lib/endorsed"); // NOI18N
}
return serverRequirements5And6x;
}
private static List<String> serverRequirements7x;
private static synchronized List<String> getServerRequirements7x() {
if (serverRequirements7x == null) {
serverRequirements7x = new ArrayList<String>(6);
Collections.addAll(serverRequirements7x,
"bin", // NOI18N
"modules", // NOI18N
"jboss-modules.jar"); // NOI18N
}
return serverRequirements7x;
}
@NonNull
public static String getModulesBase(String serverRoot) {
File file = new File(serverRoot, MODULES_BASE_7);
if (file.isDirectory()) {
return MODULES_BASE_7;
}
return MODULES_BASE;
}
//------------ getting exists servers---------------------------
/**
* returns Hashmap
* key = server name
* value = server folder full path
*/
public static Hashtable getRegisteredDomains(String serverLocation){
Hashtable result = new Hashtable();
// String domainListFile = File.separator+"common"+File.separator+"nodemanager"+File.separator+"nodemanager.domains"; // NOI18N
File serverDirectory = new File(serverLocation);
if (isGoodJBServerLocation(serverDirectory, (Version) null)) {
Version version = getServerVersion(serverDirectory);
File file;
String[] files;
if(version != null && "7".equals(version.getMajorNumber())) {
files = new String[]{"standalone", "domain"};
file = serverDirectory;
} else {
file = new File(serverLocation + File.separator + "server"); // NOI18N
files = file.list(new FilenameFilter(){
@Override
public boolean accept(File dir, String name){
if ((new File(dir.getAbsolutePath()+File.separator+name)).isDirectory()) return true;
return false;
}
});
}
if (files != null) {
for (int i = 0; i<files.length; i++) {
String path = file.getAbsolutePath() + File.separator + files[i];
if (isGoodJBInstanceLocation(serverDirectory, new File(path))) {
result.put(files[i], path);
}
}
}
}
return result;
}
private static boolean isGoodJBInstanceLocation(File candidate, List<String> requirements){
if (null == candidate ||
!candidate.exists() ||
!candidate.canRead() ||
!candidate.isDirectory() ||
!hasRequiredChildren(candidate, requirements)) {
return false;
}
return true;
}
private static boolean isGoodJBInstanceLocation4x(File serverDir, File candidate) {
if (!isGoodJBInstanceLocation(candidate, getDomainRequirements4x())) {
return false;
}
Version version = getServerVersion(serverDir);
if (version == null) {
// optimistic expectation
return true;
}
if (version.compareToIgnoreUpdate(DOM4J_SERVER) > 0) {
// in server lib
File dom4j = new File(candidate, "lib/dom4j.jar"); // NOI18N
return dom4j.exists() && dom4j.canRead();
}
return true;
}
private static boolean isGoodJBInstanceLocation5x(File serverDir, File candidate){
return isGoodJBInstanceLocation(candidate, getDomainRequirements5x());
}
private static boolean isGoodJBInstanceLocation6x(File serverDir, File candidate){
return isGoodJBInstanceLocation(candidate, getDomainRequirements6x());
}
private static boolean isGoodJBInstanceLocation7x(File serverDir, File candidate){
return isGoodJBInstanceLocation(candidate, getDomainRequirements7x());
}
public static boolean isGoodJBInstanceLocation(File serverDir, File candidate){
Version version = getServerVersion(serverDir);
if (version == null || (!"4".equals(version.getMajorNumber())
&& !"5".equals(version.getMajorNumber()) // NOI18N
&& !"6".equals(version.getMajorNumber()) // NOI18N
&& !"7".equals(version.getMajorNumber()))) { // NOI18N
return JBPluginUtils.isGoodJBInstanceLocation4x(serverDir, candidate)
|| JBPluginUtils.isGoodJBInstanceLocation5x(serverDir, candidate)
|| JBPluginUtils.isGoodJBInstanceLocation6x(serverDir, candidate)
|| JBPluginUtils.isGoodJBInstanceLocation7x(serverDir, candidate);
}
return ("4".equals(version.getMajorNumber()) && JBPluginUtils.isGoodJBInstanceLocation4x(serverDir, candidate)) // NOI18N
|| ("5".equals(version.getMajorNumber()) && JBPluginUtils.isGoodJBInstanceLocation5x(serverDir, candidate)) // NOI18N
|| ("6".equals(version.getMajorNumber()) && JBPluginUtils.isGoodJBInstanceLocation6x(serverDir, candidate)) // NOI18N
|| ("7".equals(version.getMajorNumber()) && JBPluginUtils.isGoodJBInstanceLocation7x(serverDir, candidate)); // NOI18N
}
private static boolean isGoodJBServerLocation(File candidate, List<String> requirements){
if (null == candidate ||
!candidate.exists() ||
!candidate.canRead() ||
!candidate.isDirectory() ||
!hasRequiredChildren(candidate, requirements)) {
return false;
}
return true;
}
private static boolean isGoodJBServerLocation4x(File candidate) {
if (!isGoodJBServerLocation(candidate, getServerRequirements4x())
&& !isGoodJBServerLocation(candidate, getServerAlterRequirements4x())) {
return false;
}
Version version = getServerVersion(candidate);
if (version == null) {
// optimistic expectation
return true;
}
if (version.compareToIgnoreUpdate(DOM4J_SERVER) <= 0) {
// in server lib
File dom4j = new File(candidate, "lib/dom4j.jar"); // NOI18N
return dom4j.exists() && dom4j.canRead();
}
return true;
}
private static boolean isGoodJBServerLocation5x(File candidate){
return isGoodJBServerLocation(candidate, getServerRequirements5And6x());
}
private static boolean isGoodJBServerLocation6x(File candidate){
return isGoodJBServerLocation(candidate, getServerRequirements5And6x());
}
private static boolean isGoodJBServerLocation7x(File candidate){
return isGoodJBServerLocation(candidate, getServerRequirements7x());
}
public static boolean isGoodJBServerLocation(@NonNull File candidate, @NullAllowed Version version) {
Version realVersion = version;
if (realVersion == null) {
realVersion = getServerVersion(candidate);
}
if (realVersion == null || (!"4".equals(realVersion.getMajorNumber())
&& !"5".equals(realVersion.getMajorNumber())
&& !"6".equals(realVersion.getMajorNumber())
&& !"7".equals(realVersion.getMajorNumber()))) { // NOI18N
return JBPluginUtils.isGoodJBServerLocation4x(candidate)
|| JBPluginUtils.isGoodJBServerLocation5x(candidate)
|| JBPluginUtils.isGoodJBServerLocation5x(candidate)
|| JBPluginUtils.isGoodJBServerLocation7x(candidate);
}
return ("4".equals(realVersion.getMajorNumber()) && JBPluginUtils.isGoodJBServerLocation4x(candidate)) // NOI18n
|| ("5".equals(realVersion.getMajorNumber()) && JBPluginUtils.isGoodJBServerLocation5x(candidate)) // NOI18N
|| ("6".equals(realVersion.getMajorNumber()) && JBPluginUtils.isGoodJBServerLocation6x(candidate)) // NOI18N
|| ("7".equals(realVersion.getMajorNumber()) && JBPluginUtils.isGoodJBServerLocation7x(candidate)); // NOI18N
}
public static boolean isJB4(JBDeploymentManager dm) {
String installDir = dm.getInstanceProperties().getProperty(JBPluginProperties.PROPERTY_ROOT_DIR);
Version version = getServerVersion(new File(installDir));
if (version == null) {
return isGoodJBServerLocation4x(new File(installDir));
}
return "4".equals(version.getMajorNumber()); // NOI18N
}
public static boolean isGoodJBLocation(File server, File domain) {
return (JBPluginUtils.isGoodJBServerLocation4x(server)
&& JBPluginUtils.isGoodJBInstanceLocation4x(server, domain))
|| (JBPluginUtils.isGoodJBServerLocation5x(server)
&& JBPluginUtils.isGoodJBInstanceLocation5x(server, domain));
}
/**
* Checks whether the given candidate has all required childrens. Children
* can be both files and directories. Method does not distinguish between them.
*
* @return true if the candidate has all files/directories named in requiredChildren,
* false otherwise
*/
private static boolean hasRequiredChildren(File candidate, List<String> requiredChildren) {
if (null == candidate || null == candidate.list()) {
return false;
}
if (null == requiredChildren) {
return true;
}
for (String next : requiredChildren) {
File test = new File(candidate.getPath() + File.separator + next);
if (!test.exists()) {
return false;
}
}
return true;
}
//--------------------------------------------------------------------
/**
*
*
*/
public static String getDeployDir(String domainDir){
Version version = JBPluginUtils.getServerVersion(new File(JBPluginProperties.getInstance().getInstallLocation()));
if("7".equals(version.getMajorNumber())) {
return domainDir + File.separator + "deployments"; //NOI18N
}
return domainDir + File.separator + "deploy"; //NOI18N
//todo: get real deploy path
}
public static String getHTTPConnectorPort(String domainDir) {
String defaultPort = "8080"; // NOI18N
/*
* Following block is trying to solve different server versions.
*/
File serverXmlFile = new File(domainDir + SERVER_4_XML);
if (!serverXmlFile.exists()) {
serverXmlFile = new File(domainDir + SERVER_4_2_XML);
if (!serverXmlFile.exists()) {
serverXmlFile = new File(domainDir + SERVER_5_XML);
if (!serverXmlFile.exists()) {
return defaultPort;
}
}
}
InputStream inputStream = null;
Document document = null;
try {
inputStream = new FileInputStream(serverXmlFile);
try {
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
} finally {
inputStream.close();
}
// get the root element
Element root = document.getDocumentElement();
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeName().equals("Service")) { // NOI18N
NodeList nl = child.getChildNodes();
for (int j = 0; j < nl.getLength(); j++) {
Node ch = nl.item(j);
if (ch.getNodeName().equals("Connector")) { // NOI18N
String port = ch.getAttributes().getNamedItem("port").getNodeValue();
if (port.startsWith("$")) {
// FIXME check properties somehow
return defaultPort;
}
try {
Integer.parseInt(port);
return port;
} catch (NumberFormatException ex) {
return defaultPort;
}
}
}
}
}
} catch (Exception e) {
LOGGER.log(Level.INFO, null, e);
// it is ok
// it optional functionality so we don't need to look at any exception
}
return defaultPort;
}
public static int getJnpPortNumber(String domainDir) {
String jnpPort = getJnpPort(domainDir);
if(jnpPort != null) {
jnpPort = jnpPort.trim();
if (jnpPort.length() > 0) {
try {
return Integer.parseInt(jnpPort);
} catch(NumberFormatException e) {
// pass through to default
}
}
}
return 1099;
}
public static int getJmxPortNumber(JBProperties jb, InstanceProperties ip) {
String strPort = ip.getProperty(JBPluginProperties.PROPERTY_JMX_PORT);
if (strPort == null || strPort.trim().isEmpty()) {
return getDefaultJmxPortNumber(jb.getServerVersion());
}
try {
return Integer.parseInt(strPort.trim());
} catch(NumberFormatException e) {
// pass through to default
}
return getDefaultJmxPortNumber(jb.getServerVersion());
}
public static String getJnpPort(String domainDir) {
String serviceXml = domainDir+File.separator+"conf"+File.separator+"jboss-service.xml"; //NOI18N
File xmlFile = new File(serviceXml);
if (!xmlFile.exists()) return "";
InputStream inputStream = null;
Document document = null;
try {
inputStream = new FileInputStream(xmlFile);
try {
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
} finally {
inputStream.close();
}
// get the root element
Element root = document.getDocumentElement();
// get the child nodes
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeName().equals("mbean")) { // NOI18N
NodeList nl = child.getChildNodes();
if (!child.getAttributes().getNamedItem("name").getNodeValue().equals("jboss:service=Naming")) //NOI18N
continue;
for (int j = 0; j < nl.getLength(); j++){
Node ch = nl.item(j);
if (ch.getNodeName().equals("attribute")) { // NOI18N
if (!ch.getAttributes().getNamedItem("name").getNodeValue().equals("Port")) //NOI18N
continue;
return ch.getFirstChild().getNodeValue();
}
}
}
}
} catch (Exception e) {
Logger.getLogger("global").log(Level.INFO, null, e);
}
return "";
}
public static String getRMINamingServicePort(String domainDir){
String serviceXml = domainDir+File.separator+"conf"+File.separator+"jboss-service.xml"; //NOI18N
File xmlFile = new File(serviceXml);
if (!xmlFile.exists()) return "";
InputStream inputStream = null;
Document document = null;
try {
inputStream = new FileInputStream(xmlFile);
try {
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
} finally {
inputStream.close();
}
// get the root element
Element root = document.getDocumentElement();
// get the child nodes
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeName().equals("mbean")) { // NOI18N
NodeList nl = child.getChildNodes();
if (!child.getAttributes().getNamedItem("name").getNodeValue().equals("jboss:service=Naming")) //NOI18N
continue;
for (int j = 0; j < nl.getLength(); j++){
Node ch = nl.item(j);
if (ch.getNodeName().equals("attribute")) { // NOI18N
if (!ch.getAttributes().getNamedItem("name").getNodeValue().equals("RmiPort")) //NOI18N
continue;
return ch.getFirstChild().getNodeValue();
}
}
}
}
} catch (Exception e) {
Logger.getLogger("global").log(Level.INFO, null, e);
}
return "";
}
public static String getRMIInvokerPort(String domainDir){
String serviceXml = domainDir+File.separator+"conf"+File.separator+"jboss-service.xml"; //NOI18N
File xmlFile = new File(serviceXml);
if (!xmlFile.exists()) return "";
InputStream inputStream = null;
Document document = null;
try {
inputStream = new FileInputStream(xmlFile);
try {
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
} finally {
inputStream.close();
}
// get the root element
Element root = document.getDocumentElement();
// get the child nodes
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeName().equals("mbean")) { // NOI18N
NodeList nl = child.getChildNodes();
if (!child.getAttributes().getNamedItem("name").getNodeValue().equals("jboss:service=invoker,type=jrmp")) //NOI18N
continue;
for (int j = 0; j < nl.getLength(); j++){
Node ch = nl.item(j);
if (ch.getNodeName().equals("attribute")) { // NOI18N
if (!ch.getAttributes().getNamedItem("name").getNodeValue().equals("RMIObjectPort")) //NOI18N
continue;
return ch.getFirstChild().getNodeValue();
}
}
}
}
} catch (Exception e) {
Logger.getLogger("global").log(Level.INFO, null, e);
}
return "";
}
/** Return true if the specified port is free, false otherwise. */
public static boolean isPortFree(int port) {
ServerSocket soc = null;
try {
soc = new ServerSocket(port);
} catch (IOException ioe) {
return false;
} finally {
if (soc != null)
try { soc.close(); } catch (IOException ex) {} // noop
}
return true;
}
/**
* Return the version of the server located at the given path.
* If the server version can't be determined returns <code>null</code>.
*
* @param serverPath path to the server directory
* @return specification version of the server
*/
@CheckForNull
public static Version getServerVersion(File serverPath) {
assert serverPath != null : "Can't determine version with null server path"; // NOI18N
File systemJarFile = new File(serverPath, "lib/jboss-system.jar"); // NOI18N
Version version = getVersion(systemJarFile);
if (version == null) {
// check for JBoss AS 7
File serverDir = new File(serverPath, getModulesBase(serverPath.getAbsolutePath()) + "org/jboss/as/server/main");
File[] files = serverDir.listFiles(new JarFileFilter());
if (files != null) {
for (File jarFile : files) {
version = getVersion(jarFile);
if(version != null) {
break;
}
}
}
}
return version;
}
static class JarFileFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
}
public static int getDefaultJmxPortNumber(Version version) {
if (version != null && version.compareToIgnoreUpdate(JBPluginUtils.JBOSS_7_0_0) >= 0) {
return 9999;
} else {
return 1090;
}
}
private static Version getVersion(File systemJarFile) {
if (!systemJarFile.exists()) {
return null;
}
try {
JarFileSystem systemJar = new JarFileSystem();
systemJar.setJarFile(systemJarFile);
Attributes attributes = systemJar.getManifest().getMainAttributes();
String version = attributes.getValue("Specification-Version"); // NOI18N
if (version != null) {
return new Version(version);
}
return null;
} catch (IOException ex) {
LOGGER.log(Level.INFO, null, ex);
return null;
} catch (PropertyVetoException ex) {
LOGGER.log(Level.INFO, null, ex);
return null;
}
}
/**
* Class representing the JBoss version.
* <p>
* <i>Immutable</i>
*
* @author <NAME>
*/
public static final class Version implements Comparable<Version> {
private String majorNumber = "0";
private String minorNumber = "0";
private String microNumber = "0";
private String update = "";
/**
* Constructs the version from the spec version string.
* Expected format is <code>MAJOR_NUMBER[.MINOR_NUMBER[.MICRO_NUMBER[.UPDATE]]]</code>.
*
* @param version spec version string with the following format:
* <code>MAJOR_NUMBER[.MINOR_NUMBER[.MICRO_NUMBER[.UPDATE]]]</code>
*/
public Version(String version) {
assert version != null : "Version can't be null"; // NOI18N
String[] tokens = version.split("\\.");
if (tokens.length >= 4) {
update = tokens[3];
}
if (tokens.length >= 3) {
microNumber = tokens[2];
}
if (tokens.length >= 2) {
minorNumber = tokens[1];
}
majorNumber = tokens[0];
}
/**
* Returns the major number.
*
* @return the major number. Never returns <code>null</code>.
*/
public String getMajorNumber() {
return majorNumber;
}
/**
* Returns the minor number.
*
* @return the minor number. Never returns <code>null</code>.
*/
public String getMinorNumber() {
return minorNumber;
}
/**
* Returns the micro number.
*
* @return the micro number. Never returns <code>null</code>.
*/
public String getMicroNumber() {
return microNumber;
}
/**
* Returns the update.
*
* @return the update. Never returns <code>null</code>.
*/
public String getUpdate() {
return update;
}
/**
* {@inheritDoc}<p>
* Two versions are equal if and only if they have same major, minor,
* micro number and update.
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Version other = (Version) obj;
if (this.majorNumber != other.majorNumber
&& (this.majorNumber == null || !this.majorNumber.equals(other.majorNumber))) {
return false;
}
if (this.minorNumber != other.minorNumber
&& (this.minorNumber == null || !this.minorNumber.equals(other.minorNumber))) {
return false;
}
if (this.microNumber != other.microNumber
&& (this.microNumber == null || !this.microNumber.equals(other.microNumber))) {
return false;
}
if (this.update != other.update
&& (this.update == null || !this.update.equals(other.update))) {
return false;
}
return true;
}
/**
* {@inheritDoc}<p>
* The implementation consistent with {@link #equals(Object)}.
*/
@Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + (this.majorNumber != null ? this.majorNumber.hashCode() : 0);
hash = 17 * hash + (this.minorNumber != null ? this.minorNumber.hashCode() : 0);
hash = 17 * hash + (this.microNumber != null ? this.microNumber.hashCode() : 0);
hash = 17 * hash + (this.update != null ? this.update.hashCode() : 0);
return hash;
}
/**
* {@inheritDoc}<p>
* Compares the versions based on its major, minor, micro and update.
* Major number is the most significant. Implementation is consistent
* with {@link #equals(Object)}.
*/
public int compareTo(Version o) {
int comparison = compareToIgnoreUpdate(o);
if (comparison != 0) {
return comparison;
}
return update.compareTo(o.update);
}
/**
* Compares the versions based on its major, minor, micro. Update field
* is ignored. Major number is the most significant.
*
* @param o version to compare with
*/
public int compareToIgnoreUpdate(Version o) {
int comparison = majorNumber.compareTo(o.majorNumber);
if (comparison != 0) {
return comparison;
}
comparison = minorNumber.compareTo(o.minorNumber);
if (comparison != 0) {
return comparison;
}
return microNumber.compareTo(o.microNumber);
}
}
}
| 17,315 |
328 |
// Copyright 2022 The BladeDISC Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <torch/csrc/jit/ir/alias_analysis.h>
#include <torch/csrc/jit/ir/irparser.h>
#include <torch/csrc/jit/passes/dead_code_elimination.h>
#include <torch/csrc/jit/testing/file_check.h>
#include <torch/custom_class.h>
#include <torch/script.h>
#include "ltc/disc_compiler/passes/disc_fuser.h"
#include "ltc/disc_compiler/passes/graph_fuser.h"
namespace torch_disc {
namespace compiler {
TEST(TestDiscFusion, TestConstantNode) {
const std::string graph_str = R"IR(
graph(%p1 : Float(64, 1, 28, 28, strides=[784, 784, 28, 1], requires_grad=0, device=cuda:0)):
%1 : int[] = prim::Constant[value=[64, 784]]()
%2 : Float(*, *, requires_grad=0, device=cuda:0) = aten::reshape(%p1, %1)
return (%2)
)IR";
auto g = std::make_shared<torch::jit::Graph>();
torch::jit::parseIR(graph_str, g.get());
DiscFusion(g);
torch::jit::EliminateDeadCode(g);
torch::jit::testing::FileCheck()
.check("prim::FusionGroup_0")
->check("prim::Constant")
->check("aten::reshape")
->run(*g);
}
TEST(TestDiscFusion, TestScalarInput) {
const std::string graph_str = R"IR(
graph(%p0 : int,
%p1 : Float(4, 1, strides=[1, 1], requires_grad=0, device=cuda:0),
%p2 : Float(4, strides=[1], requires_grad=0, device=cuda:0)):
%4 : Float(*, *, device=cuda:0) = aten::relu(%p2)
%3 : Float(*, *, device=cuda:0) = aten::add(%4, %p1, %p0)
return (%3)
)IR";
auto g = std::make_shared<torch::jit::Graph>();
torch::jit::parseIR(graph_str, g.get());
DiscFusion(g);
torch::jit::EliminateDeadCode(g);
torch::jit::testing::FileCheck()
.check("prim::NumToTensor")
->check("prim::FusionGroup_0")
->check("aten::relu")
->check("aten::item")
->check("aten::add")
->run(*g);
}
TEST(TestDiscFusion, TestCycle) {
//
// sort
// / \
// ↓ ↓
// relu -> add
//
auto graph_string_cycle = R"IR(
graph(%p1 : Float(2, 2, strides=[2, 1], requires_grad=0, device=cuda:0),
%p3 : Float(2, 2, strides=[2, 1], requires_grad=0, device=cuda:0)):
%4 : int = prim::Constant[value=-1]()
%5 : bool = prim::Constant[value=0]()
%6 : Tensor, %7 : Tensor = aten::sort(%p1, %4, %5)
%8 : Tensor = aten::relu(%6)
%9 : Tensor = aten::add(%7, %8, %4)
return (%9)
)IR";
auto g = std::make_shared<torch::jit::Graph>();
torch::jit::parseIR(graph_string_cycle, g.get());
g->lint();
torch::jit::EliminateDeadCode(g);
torch::jit::AliasDb db(g);
overrideCanFuseOnCPULegacy(true);
CustomFuseGraph(
g,
[](torch::jit::Node* n) {
if (n->kind() == torch::prim::Param || n->kind() == torch::aten::relu)
return false;
for (auto inp : n->inputs()) {
if (inp->type()->isSubtypeOf(*torch::NumberType::get()) &&
inp->node()->kind() != torch::prim::Constant)
return false;
}
return true;
},
torch::jit::Symbol::fromQualString("prim::FusionGroup"));
overrideCanFuseOnCPULegacy(false);
torch::jit::EliminateDeadCode(g);
torch::jit::testing::FileCheck()
.check("prim::FusionGroup_0")
->check("prim::Constant")
->check("aten::sort")
->run(*g);
torch::jit::testing::FileCheck()
.check("prim::FusionGroup_1")
->check("prim::Constant")
->check("aten::add")
->run(*g);
}
} // namespace compiler
} // namespace torch_disc
| 1,665 |
500 |
<filename>OpenBCI_GUI/libraries/oscP5/src/netP5/NetMessage.java
/**
* A network library for processing which supports UDP, TCP and Multicast.
*
* (c) 2004-2012
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*
* @author <NAME> http://www.sojamo.de
* @modified 12/23/2012
* @version 0.9.9
*/
package netP5;
import java.net.DatagramPacket;
import java.net.InetAddress;
/**
* @author <NAME>
*/
public class NetMessage {
private InetAddress _myInetAddress;
private int _myPort;
private String _myString = "";
private byte[] _myData = new byte[0];
private TcpClient _myTcpClient;
private boolean isDatagramPacket = false;
private int _myProtocol;
private DatagramPacket _myDatagramPacket;
private TcpPacket _myTcpPacket;
protected NetMessage(DatagramPacket theDatagramPacket) {
_myDatagramPacket = theDatagramPacket;
_myInetAddress = theDatagramPacket.getAddress();
_myPort = theDatagramPacket.getPort();
_myData = theDatagramPacket.getData();
_myProtocol = NetP5.UDP;
isDatagramPacket = true;
}
protected NetMessage(TcpPacket theTcpPacket) {
_myTcpPacket = theTcpPacket;
_myInetAddress = theTcpPacket.getTcpConnection().socket().getInetAddress();
_myPort = theTcpPacket.getTcpConnection().socket().getPort();
_myString = theTcpPacket.getTcpConnection().getString();
_myData = theTcpPacket.getData();
_myProtocol = NetP5.TCP;
_myTcpClient = theTcpPacket.getTcpConnection();
}
public TcpPacket getTcpPacket() {
return _myTcpPacket;
}
public DatagramPacket getDatagramPacket() {
return _myDatagramPacket;
}
protected void setProtocol(int theType) {
_myProtocol = theType;
}
/**
* get the data of the message as bytes.
* @return
*/
public byte[] getData() {
return _myData;
}
/**
* get the data the message as string.
* @return
*/
public String getString() {
if(isDatagramPacket) {
return new String(_myData);
} else {
return _myString;
}
}
/**
* get the protocol type the message was sent over.
* NetP5.TCP or NetP5.UDP are possible.
* @return
*/
public int protocol() {
return _myProtocol;
}
/**
* get the port the net message was received at.
* @return
*/
public int port() {
return _myPort;
}
public TcpClient tcpConnection() {
return _myTcpClient;
}
public String address() {
return _myInetAddress.getHostAddress();
}
public InetAddress inetAddress() {
return _myInetAddress;
}
}
| 1,163 |
15,337 |
<gh_stars>1000+
from django.apps import AppConfig
from django.conf import settings
from django.db.models import Field
from .db.filters import PostgresILike
class CoreAppConfig(AppConfig):
name = "saleor.core"
def ready(self):
Field.register_lookup(PostgresILike)
if settings.SENTRY_DSN:
settings.SENTRY_INIT(settings.SENTRY_DSN, settings.SENTRY_OPTS)
| 156 |
984 |
<reponame>om-sharma/java-driver
/*
* Copyright DataStax, 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.datastax.oss.driver.mapper;
import static com.datastax.oss.driver.api.mapper.entity.naming.GetterStyle.FLUENT;
import static org.assertj.core.api.Assertions.assertThat;
import com.datastax.oss.driver.api.core.CqlIdentifier;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import com.datastax.oss.driver.api.core.data.UdtValue;
import com.datastax.oss.driver.api.core.type.UserDefinedType;
import com.datastax.oss.driver.api.mapper.MapperBuilder;
import com.datastax.oss.driver.api.mapper.annotations.Computed;
import com.datastax.oss.driver.api.mapper.annotations.CqlName;
import com.datastax.oss.driver.api.mapper.annotations.Dao;
import com.datastax.oss.driver.api.mapper.annotations.DaoFactory;
import com.datastax.oss.driver.api.mapper.annotations.DaoKeyspace;
import com.datastax.oss.driver.api.mapper.annotations.DefaultNullSavingStrategy;
import com.datastax.oss.driver.api.mapper.annotations.Entity;
import com.datastax.oss.driver.api.mapper.annotations.GetEntity;
import com.datastax.oss.driver.api.mapper.annotations.Insert;
import com.datastax.oss.driver.api.mapper.annotations.Mapper;
import com.datastax.oss.driver.api.mapper.annotations.PartitionKey;
import com.datastax.oss.driver.api.mapper.annotations.PropertyStrategy;
import com.datastax.oss.driver.api.mapper.annotations.Select;
import com.datastax.oss.driver.api.mapper.entity.saving.NullSavingStrategy;
import com.datastax.oss.driver.api.testinfra.ccm.CcmRule;
import com.datastax.oss.driver.api.testinfra.session.SessionRule;
import com.datastax.oss.driver.categories.ParallelizableTests;
import java.util.Objects;
import java.util.UUID;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
@Category(ParallelizableTests.class)
public class ImmutableEntityIT extends InventoryITBase {
private static final CcmRule CCM_RULE = CcmRule.getInstance();
private static final SessionRule<CqlSession> SESSION_RULE = SessionRule.builder(CCM_RULE).build();
@ClassRule
public static final TestRule CHAIN = RuleChain.outerRule(CCM_RULE).around(SESSION_RULE);
private static final UUID PRODUCT_2D_ID = UUID.randomUUID();
private static ImmutableProductDao dao;
@BeforeClass
public static void setup() {
CqlSession session = SESSION_RULE.session();
for (String query : createStatements(CCM_RULE)) {
session.execute(
SimpleStatement.builder(query).setExecutionProfile(SESSION_RULE.slowProfile()).build());
}
UserDefinedType dimensions2d =
session
.getKeyspace()
.flatMap(ks -> session.getMetadata().getKeyspace(ks))
.flatMap(ks -> ks.getUserDefinedType("dimensions2d"))
.orElseThrow(AssertionError::new);
session.execute(
"INSERT INTO product2d (id, description, dimensions) VALUES (?, ?, ?)",
PRODUCT_2D_ID,
"2D product",
dimensions2d.newValue(12, 34));
InventoryMapper mapper = InventoryMapper.builder(session).build();
dao = mapper.immutableProductDao(SESSION_RULE.keyspace());
}
@Test
public void should_insert_and_retrieve_immutable_entities() {
ImmutableProduct originalProduct =
new ImmutableProduct(
UUID.randomUUID(), "mock description", new ImmutableDimensions(1, 2, 3), -1);
dao.save(originalProduct);
ImmutableProduct retrievedProduct = dao.findById(originalProduct.id());
assertThat(retrievedProduct).isEqualTo(originalProduct);
}
@Test
public void should_map_immutable_entity_from_complete_row() {
ImmutableProduct originalProduct =
new ImmutableProduct(
UUID.randomUUID(), "mock description", new ImmutableDimensions(1, 2, 3), -1);
dao.save(originalProduct);
Row row =
SESSION_RULE
.session()
.execute(
"SELECT id, description, dimensions, writetime(description) AS writetime, now() "
+ "FROM product WHERE id = ?",
originalProduct.id())
.one();
ImmutableProduct retrievedProduct = dao.mapStrict(row);
assertThat(retrievedProduct.id()).isEqualTo(originalProduct.id());
assertThat(retrievedProduct.description()).isEqualTo(originalProduct.description());
assertThat(retrievedProduct.dimensions()).isEqualTo(originalProduct.dimensions());
assertThat(retrievedProduct.writetime()).isGreaterThan(0);
}
@Test
public void should_map_immutable_entity_from_partial_row_when_lenient() {
Row row =
SESSION_RULE
.session()
.execute("SELECT id, dimensions FROM product2d WHERE id = ?", PRODUCT_2D_ID)
.one();
ImmutableProduct retrievedProduct = dao.mapLenient(row);
assertThat(retrievedProduct.id()).isEqualTo(PRODUCT_2D_ID);
assertThat(retrievedProduct.dimensions()).isEqualTo(new ImmutableDimensions(0, 12, 34));
assertThat(retrievedProduct.description()).isNull();
assertThat(retrievedProduct.writetime()).isZero();
}
@Test
public void should_map_immutable_entity_from_complete_udt() {
ImmutableProduct originalProduct =
new ImmutableProduct(
UUID.randomUUID(), "mock description", new ImmutableDimensions(1, 2, 3), -1);
dao.save(originalProduct);
Row row =
SESSION_RULE
.session()
.execute("SELECT dimensions FROM product WHERE id = ?", originalProduct.id())
.one();
assertThat(row).isNotNull();
ImmutableDimensions retrievedDimensions = dao.mapStrict(row.getUdtValue(0));
assertThat(retrievedDimensions).isEqualTo(originalProduct.dimensions());
}
@Test
public void should_map_immutable_entity_from_partial_udt_when_lenient() {
Row row =
SESSION_RULE
.session()
.execute("SELECT dimensions FROM product2d WHERE id = ?", PRODUCT_2D_ID)
.one();
assertThat(row).isNotNull();
ImmutableDimensions retrievedDimensions = dao.mapLenient(row.getUdtValue(0));
assertThat(retrievedDimensions).isEqualTo(new ImmutableDimensions(0, 12, 34));
}
@Entity
@CqlName("product")
@PropertyStrategy(getterStyle = FLUENT, mutable = false)
public static class ImmutableProduct {
@PartitionKey private final UUID id;
private final String description;
private final ImmutableDimensions dimensions;
@Computed("writetime(description)")
private final long writetime;
public ImmutableProduct(
UUID id, String description, ImmutableDimensions dimensions, long writetime) {
this.id = id;
this.description = description;
this.dimensions = dimensions;
this.writetime = writetime;
}
public UUID id() {
return id;
}
public String description() {
return description;
}
public ImmutableDimensions dimensions() {
return dimensions;
}
public long writetime() {
return writetime;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
} else if (other instanceof ImmutableProduct) {
ImmutableProduct that = (ImmutableProduct) other;
return Objects.equals(this.id, that.id)
&& Objects.equals(this.description, that.description)
&& Objects.equals(this.dimensions, that.dimensions);
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(id, description, dimensions);
}
}
@Entity
@PropertyStrategy(mutable = false)
public static class ImmutableDimensions {
private final int length;
private final int width;
private final int height;
public ImmutableDimensions(int length, int width, int height) {
this.length = length;
this.width = width;
this.height = height;
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof ImmutableDimensions) {
ImmutableDimensions that = (ImmutableDimensions) other;
return this.length == that.length && this.width == that.width && this.height == that.height;
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(length, width, height);
}
@Override
public String toString() {
return "Dimensions{length=" + length + ", width=" + width + ", height=" + height + '}';
}
}
@Mapper
public interface InventoryMapper {
static MapperBuilder<InventoryMapper> builder(CqlSession session) {
return new ImmutableEntityIT_InventoryMapperBuilder(session);
}
@DaoFactory
ImmutableProductDao immutableProductDao(@DaoKeyspace CqlIdentifier keyspace);
}
@Dao
@DefaultNullSavingStrategy(NullSavingStrategy.SET_TO_NULL)
public interface ImmutableProductDao {
@Select
ImmutableProduct findById(UUID productId);
@Insert
void save(ImmutableProduct product);
@GetEntity
ImmutableProduct mapStrict(Row row);
@GetEntity(lenient = true)
ImmutableProduct mapLenient(Row row);
@GetEntity
ImmutableDimensions mapStrict(UdtValue udt);
@GetEntity(lenient = true)
ImmutableDimensions mapLenient(UdtValue udt);
}
}
| 3,770 |
664 |
#!/usr/bin/env python
import glob
import os
import sys
# usage: parse_peer_log <path-to-libtorrent-peer-logs>
log_files = []
for p in glob.iglob(os.path.join(sys.argv[1], '*.log')):
name = os.path.split(p)[1]
if name == 'main_session.log': continue
print name
f = open(p, 'r')
out_file = p + '.dat'
log_files.append(out_file)
out = open(out_file, 'w+')
uploaded_blocks = 0;
downloaded_blocks = 0;
for l in f:
t = l.split(': ')[0].split('.')[0]
log_line = False
if ' ==> PIECE' in l:
uploaded_blocks+= 1
log_line = True
if ' <== PIECE' in l:
downloaded_blocks+= 1
log_line = True
if log_line:
print >>out, '%s\t%d\t%d' % (t, uploaded_blocks, downloaded_blocks)
out.close()
f.close()
out = open('peers.gnuplot', 'wb')
print >>out, "set term png size 1200,700"
print >>out, 'set xrange [0:*]'
print >>out, 'set xlabel "time"'
print >>out, 'set ylabel "blocks"'
print >>out, 'set key box'
print >>out, 'set xdata time'
print >>out, 'set timefmt "%H:%M:%S"'
print >>out, 'set title "uploaded blocks"'
print >>out, 'set output "peers_upload.png"'
print >>out, 'plot',
first = True
for n in log_files:
if not first:
print >>out, ',',
first = False
print >>out, ' "%s" using 1:2 title "%s" with steps' % (n, os.path.split(n)[1].split('.log')[0]),
print >>out, ''
print >>out, 'set title "downloaded blocks"'
print >>out, 'set output "peers_download.png"'
print >>out, 'plot',
first = True
for n in log_files:
if not first:
print >>out, ',',
first = False
print >>out, ' "%s" using 1:3 title "%s" with steps' % (n, os.path.split(n)[1].split('.log')[0]),
print >>out, ''
out.close()
os.system('gnuplot peers.gnuplot');
| 691 |
2,151 |
<gh_stars>1000+
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_NETWORK_CONNECT_DELEGATE_MUS_H_
#define ASH_NETWORK_CONNECT_DELEGATE_MUS_H_
#include "base/macros.h"
#include "chromeos/network/network_connect.h"
namespace ash {
// Routes requests to show network config UI over the mojom::SystemTrayClient
// interface.
// TODO(mash): Replace NetworkConnect::Delegate with a client interface on
// a mojo NetworkConfig service. http://crbug.com/644355
class NetworkConnectDelegateMus : public chromeos::NetworkConnect::Delegate {
public:
NetworkConnectDelegateMus();
~NetworkConnectDelegateMus() override;
// chromeos::NetworkConnect::Delegate:
void ShowNetworkConfigure(const std::string& network_id) override;
void ShowNetworkSettings(const std::string& network_id) override;
bool ShowEnrollNetwork(const std::string& network_id) override;
void ShowMobileSetupDialog(const std::string& network_id) override;
void ShowNetworkConnectError(const std::string& error_name,
const std::string& network_id) override;
void ShowMobileActivationError(const std::string& network_id) override;
private:
DISALLOW_COPY_AND_ASSIGN(NetworkConnectDelegateMus);
};
} // namespace ash
#endif // ASH_NETWORK_CONNECT_DELEGATE_MUS_H_
| 455 |
317 |
// Released under the MIT License. See LICENSE for details.
#ifndef BALLISTICA_PYTHON_CLASS_PYTHON_CLASS_SESSION_PLAYER_H_
#define BALLISTICA_PYTHON_CLASS_PYTHON_CLASS_SESSION_PLAYER_H_
#include "ballistica/core/object.h"
#include "ballistica/python/class/python_class.h"
namespace ballistica {
class PythonClassSessionPlayer : public PythonClass {
public:
static auto type_name() -> const char* { return "SessionPlayer"; }
static void SetupType(PyTypeObject* obj);
static auto Create(Player* player) -> PyObject*;
static auto Check(PyObject* o) -> bool {
return PyObject_TypeCheck(o, &type_obj);
}
static PyTypeObject type_obj;
auto GetPlayer(bool doraise) const -> Player*;
private:
static bool s_create_empty_;
static PyMethodDef tp_methods[];
static auto tp_repr(PythonClassSessionPlayer* self) -> PyObject*;
static auto tp_new(PyTypeObject* type, PyObject* args, PyObject* keywds)
-> PyObject*;
static void tp_dealloc(PythonClassSessionPlayer* self);
static auto tp_getattro(PythonClassSessionPlayer* self, PyObject* attr)
-> PyObject*;
static auto tp_setattro(PythonClassSessionPlayer* self, PyObject* attr,
PyObject* val) -> int;
static auto GetName(PythonClassSessionPlayer* self, PyObject* args,
PyObject* keywds) -> PyObject*;
static auto Exists(PythonClassSessionPlayer* self) -> PyObject*;
static auto SetName(PythonClassSessionPlayer* self, PyObject* args,
PyObject* keywds) -> PyObject*;
static auto ResetInput(PythonClassSessionPlayer* self) -> PyObject*;
static auto AssignInputCall(PythonClassSessionPlayer* self, PyObject* args,
PyObject* keywds) -> PyObject*;
static auto RemoveFromGame(PythonClassSessionPlayer* self) -> PyObject*;
static auto GetTeam(PythonClassSessionPlayer* self) -> PyObject*;
static auto GetAccountID(PythonClassSessionPlayer* self) -> PyObject*;
static auto SetData(PythonClassSessionPlayer* self, PyObject* args,
PyObject* keywds) -> PyObject*;
static auto GetIconInfo(PythonClassSessionPlayer* self) -> PyObject*;
static auto SetIconInfo(PythonClassSessionPlayer* self, PyObject* args,
PyObject* keywds) -> PyObject*;
static auto SetActivity(PythonClassSessionPlayer* self, PyObject* args,
PyObject* keywds) -> PyObject*;
static auto SetNode(PythonClassSessionPlayer* self, PyObject* args,
PyObject* keywds) -> PyObject*;
static auto GetIcon(PythonClassSessionPlayer* self) -> PyObject*;
static auto Dir(PythonClassSessionPlayer* self) -> PyObject*;
Object::WeakRef<Player>* player_;
static auto nb_bool(PythonClassSessionPlayer* self) -> int;
static PyNumberMethods as_number_;
};
} // namespace ballistica
#endif // BALLISTICA_PYTHON_CLASS_PYTHON_CLASS_SESSION_PLAYER_H_
| 1,064 |
482 |
<gh_stars>100-1000
package io.cattle.platform.configitem.server.template;
import io.cattle.platform.configitem.server.resource.Resource;
import java.io.IOException;
public interface TemplateLoader {
public static final int NO_PRIORITY = Integer.MAX_VALUE;
public static final int HIGH_PRIORITY = 100;
public static final int MID_PRIORITY = 500;
public static final int LOW_PRIORITY = 1000;
int canHandle(Resource resource);
Template loadTemplate(Resource resource) throws IOException;
}
| 158 |
460 |
/*******************************************************************************
* Copyright 2015 <NAME>, <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 de.saxsys.mvvmfx.utils.notifications.viewmodel;
import de.saxsys.mvvmfx.MvvmFX;
import de.saxsys.mvvmfx.ViewModel;
import de.saxsys.mvvmfx.testingutils.FxTestingUtils;
import de.saxsys.mvvmfx.testingutils.JfxToolkitExtension;
import de.saxsys.mvvmfx.utils.notifications.DefaultNotificationCenter;
import de.saxsys.mvvmfx.utils.notifications.DefaultNotificationCenterTest;
import de.saxsys.mvvmfx.utils.notifications.NotificationCenterFactory;
import de.saxsys.mvvmfx.utils.notifications.NotificationObserver;
import javafx.application.Platform;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* This test verifies the communication via notifications between the View and ViewModel.
*/
@ExtendWith(JfxToolkitExtension.class)
public class ViewModelTest {
private static final String TEST_NOTIFICATION = "test_notification";
private static final Object[] OBJECT_ARRAY_FOR_NOTIFICATION = new String[] { "test" };
ViewModel viewModel;
DummyNotificationObserver observer1;
DummyNotificationObserver observer2;
DummyNotificationObserver observer3;
@BeforeEach
public void init() {
observer1 = Mockito.mock(DummyNotificationObserver.class);
observer2 = Mockito.mock(DummyNotificationObserver.class);
observer3 = Mockito.mock(DummyNotificationObserver.class);
viewModel = new ViewModel() {
};
NotificationCenterFactory.setNotificationCenter(new DefaultNotificationCenter());
}
@Test
public void observerFromOutsideDoesNotReceiveNotifications() {
MvvmFX.getNotificationCenter().subscribe(TEST_NOTIFICATION, observer1);
viewModel.publish(TEST_NOTIFICATION);
FxTestingUtils.waitForUiThread();
Mockito.verify(observer1, Mockito.never()).receivedNotification(TEST_NOTIFICATION);
}
@Test
public void addObserverAndPublish() throws Exception {
viewModel.subscribe(TEST_NOTIFICATION, observer1);
viewModel.publish(TEST_NOTIFICATION, OBJECT_ARRAY_FOR_NOTIFICATION);
FxTestingUtils.waitForUiThread();
Mockito.verify(observer1).receivedNotification(TEST_NOTIFICATION, OBJECT_ARRAY_FOR_NOTIFICATION);
}
@Test
public void addAndRemoveObserverAndPublish() throws Exception {
viewModel.subscribe(TEST_NOTIFICATION, observer1);
viewModel.unsubscribe(observer1);
viewModel.publish(TEST_NOTIFICATION);
FxTestingUtils.waitForUiThread();
Mockito.verify(observer1, Mockito.never()).receivedNotification(TEST_NOTIFICATION);
viewModel.subscribe(TEST_NOTIFICATION, observer1);
viewModel.unsubscribe(TEST_NOTIFICATION, observer1);
viewModel.publish(TEST_NOTIFICATION);
FxTestingUtils.waitForUiThread();
Mockito.verify(observer1, Mockito.never()).receivedNotification(TEST_NOTIFICATION);
}
@Test
public void addMultipleObserverAndPublish() throws Exception {
viewModel.subscribe(TEST_NOTIFICATION, observer1);
viewModel.subscribe(TEST_NOTIFICATION, observer2);
viewModel.subscribe(TEST_NOTIFICATION, observer3);
viewModel.publish(TEST_NOTIFICATION, OBJECT_ARRAY_FOR_NOTIFICATION);
FxTestingUtils.waitForUiThread();
Mockito.verify(observer1).receivedNotification(TEST_NOTIFICATION, OBJECT_ARRAY_FOR_NOTIFICATION);
Mockito.verify(observer2).receivedNotification(TEST_NOTIFICATION, OBJECT_ARRAY_FOR_NOTIFICATION);
Mockito.verify(observer3).receivedNotification(TEST_NOTIFICATION, OBJECT_ARRAY_FOR_NOTIFICATION);
}
@Test
public void addMultipleObserverAndRemoveOneAndPublish() throws Exception {
viewModel.subscribe(TEST_NOTIFICATION, observer1);
viewModel.subscribe(TEST_NOTIFICATION, observer2);
viewModel.subscribe(TEST_NOTIFICATION, observer3);
viewModel.unsubscribe(observer1);
viewModel.publish(TEST_NOTIFICATION, OBJECT_ARRAY_FOR_NOTIFICATION);
FxTestingUtils.waitForUiThread();
Mockito.verify(observer1, Mockito.never()).receivedNotification(TEST_NOTIFICATION,
OBJECT_ARRAY_FOR_NOTIFICATION);
Mockito.verify(observer2).receivedNotification(TEST_NOTIFICATION,
OBJECT_ARRAY_FOR_NOTIFICATION);
Mockito.verify(observer3).receivedNotification(TEST_NOTIFICATION,
OBJECT_ARRAY_FOR_NOTIFICATION);
}
/**
* See {@link DefaultNotificationCenterTest#removeObserverThatWasNotRegisteredYet()}.
*/
@Test
public void removeObserverThatWasNotRegisteredYet() {
viewModel.unsubscribe(observer1);
viewModel.unsubscribe(TEST_NOTIFICATION, observer1);
}
private class DummyNotificationObserver implements NotificationObserver {
@Override
public void receivedNotification(String key, Object... payload) {
}
}
}
| 1,859 |
1,144 |
<gh_stars>1000+
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via <EMAIL> or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.minigrid;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
/**
* ID Column Renderer
*
* @author <NAME>
* @version $Id: IDColumnRenderer.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $
*/
public class IDColumnRenderer extends DefaultTableCellRenderer
{
/**
*
*/
private static final long serialVersionUID = -7513837304119751313L;
/**
* Constructor
* @param multiSelection determines layout - button for single, check for multi
*/
public IDColumnRenderer(boolean multiSelection)
{
super();
m_multiSelection = multiSelection;
// Multi => Check
if (m_multiSelection)
{
m_check = new JCheckBox();
m_check.setMargin(new Insets(0,0,0,0));
m_check.setHorizontalAlignment(JLabel.CENTER);
}
else // Single => Button
{
m_button = new JButton();
m_button.setMargin(new Insets(0,0,0,0));
m_button.setSize(new Dimension(5,5));
}
} // IDColumnRenderer
/** Mult-Selection flag */
private boolean m_multiSelection;
/** The Single-Selection renderer */
private JButton m_button;
/* The Multi-Selection renderer */
private JCheckBox m_check;
/**
* Set Value (for multi-selection)
* @param value
*/
@Override
protected void setValue(Object value)
{
if (m_multiSelection)
{
boolean sel = false;
if (value == null)
;
else if (value instanceof IDColumn)
sel = ((IDColumn)value).isSelected();
else if (value instanceof Boolean)
sel = ((Boolean)value).booleanValue();
else
sel = value.toString().equals("Y");
//
m_check.setSelected(sel);
}
} // setValue
/**
* Return rendering component
* @param table
* @param value
* @param isSelected
* @param hasFocus
* @param row
* @param column
* @return Component (CheckBox or Button)
*/
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
setValue(value);
if (m_multiSelection)
return m_check;
else
return m_button;
} // setTableCellRenderereComponent
} // IDColumnRenderer
| 1,314 |
23,439 |
/*
* Copyright 1999-2021 Alibaba Group Holding 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.
*
*/
package com.alibaba.nacos.core.remote.core;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.api.remote.request.ServerLoaderInfoRequest;
import com.alibaba.nacos.api.remote.response.ServerLoaderInfoResponse;
import com.alibaba.nacos.core.remote.ConnectionManager;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
/**
* {@link ServerLoaderInfoRequestHandler} unit test.
*
* @author chenglu
* @date 2021-07-01 12:48
*/
@RunWith(MockitoJUnitRunner.class)
public class ServerLoaderInfoRequestHandlerTest {
@InjectMocks
private ServerLoaderInfoRequestHandler handler;
@Mock
private ConnectionManager connectionManager;
@Test
public void testHandle() {
Mockito.when(connectionManager.currentClientsCount()).thenReturn(1);
Mockito.when(connectionManager.currentClientsCount(Mockito.any())).thenReturn(1);
Mockito.when(connectionManager.getConnectionLimitRule()).thenReturn(null);
ServerLoaderInfoRequest request = new ServerLoaderInfoRequest();
RequestMeta meta = new RequestMeta();
try {
ServerLoaderInfoResponse response = handler.handle(request, meta);
String sdkConCount = response.getMetricsValue("sdkConCount");
Assert.assertEquals(sdkConCount, "1");
} catch (NacosException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
}
| 820 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Sauveterre","circ":"3ème circonscription","dpt":"Gard","inscrits":1659,"abs":932,"votants":727,"blancs":66,"nuls":27,"exp":634,"res":[{"nuance":"REM","nom":"<NAME>","voix":403},{"nuance":"FN","nom":"<NAME>","voix":231}]}
| 112 |
2,151 |
<filename>code/jshrink/jshrink-lib/src/test/resources/junit4/src/test/java/org/junit/validator/AnnotationsValidatorTest.java
package org.junit.validator;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.junit.runners.model.FrameworkField;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.TestClass;
public class AnnotationsValidatorTest {
public static class ExampleAnnotationValidator extends AnnotationValidator {
private static final String ANNOTATED_METHOD_CALLED= "annotated method called";
private static final String ANNOTATED_FIELD_CALLED= "annotated field called";
private static final String ANNOTATED_CLASS_CALLED= "annotated class called";
@Override
public List<Exception> validateAnnotatedClass(TestClass testClass) {
return asList(new Exception(ANNOTATED_CLASS_CALLED));
}
@Override
public List<Exception> validateAnnotatedField(FrameworkField field) {
return asList(new Exception(ANNOTATED_FIELD_CALLED));
}
@Override
public List<Exception> validateAnnotatedMethod(FrameworkMethod method) {
return asList(new Exception(ANNOTATED_METHOD_CALLED));
}
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@ValidateWith(ExampleAnnotationValidator.class)
public @interface ExampleAnnotationWithValidator {
}
public static class AnnotationValidatorMethodTest {
@ExampleAnnotationWithValidator
@Test
public void test() {
}
}
public static class AnnotationValidatorFieldTest {
@ExampleAnnotationWithValidator
private String field;
@Test
public void test() {
}
}
@ExampleAnnotationWithValidator
public static class AnnotationValidatorClassTest {
@Test
public void test() {
}
}
@Test
public void validatorIsCalledForAClass() {
assertClassHasFailureMessage(AnnotationValidatorClassTest.class,
ExampleAnnotationValidator.ANNOTATED_CLASS_CALLED);
}
@Test
public void validatorIsCalledForAMethod() {
assertClassHasFailureMessage(AnnotationValidatorMethodTest.class,
ExampleAnnotationValidator.ANNOTATED_METHOD_CALLED);
}
@Test
public void validatorIsCalledForAField() {
assertClassHasFailureMessage(AnnotationValidatorFieldTest.class,
ExampleAnnotationValidator.ANNOTATED_FIELD_CALLED);
}
private void assertClassHasFailureMessage(Class<?> klass,
String expectedFailure) {
AnnotationsValidator validator= new AnnotationsValidator();
Collection<Exception> errors= validator
.validateTestClass(new TestClass(klass));
assertThat(errors.size(), is(1));
assertThat(errors.iterator().next().getMessage(),
is(expectedFailure));
}
}
| 1,223 |
431 |
<reponame>rwinch/thymeleaf-extras-springsecurity<filename>thymeleaf-extras-springsecurity3/src/main/java/org/thymeleaf/extras/springsecurity3/dialect/processor/AuthorizeAclAttrProcessor.java
/*
* =============================================================================
*
* Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.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.thymeleaf.extras.springsecurity3.dialect.processor;
import javax.servlet.ServletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.IExpressionContext;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.exceptions.ConfigurationException;
import org.thymeleaf.exceptions.TemplateProcessingException;
import org.thymeleaf.extras.springsecurity3.auth.AclAuthUtils;
import org.thymeleaf.extras.springsecurity3.auth.AuthUtils;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.standard.expression.TextLiteralExpression;
import org.thymeleaf.standard.processor.AbstractStandardConditionalVisibilityTagProcessor;
import org.thymeleaf.templatemode.TemplateMode;
/**
* Takes the form sec:authorize-acl="object :: permissions", renders the element
* children (*tag content*) if the authenticated user has the specified
* permissions on the specified domain object, according to Spring Source's
* Access Control List system.
*
* @author <NAME>
*/
public final class AuthorizeAclAttrProcessor extends AbstractStandardConditionalVisibilityTagProcessor {
public static final int ATTR_PRECEDENCE = 300;
public static final String ATTR_NAME = "authorize-acl";
private static final String VALUE_SEPARATOR = "::";
public AuthorizeAclAttrProcessor(final TemplateMode templateMode, final String dialectPrefix) {
super(templateMode, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE);
}
@Override
protected boolean isVisible(
final ITemplateContext context, final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue) {
final String attrValue = (attributeValue == null? null : attributeValue.trim());
if (attrValue == null || attrValue.length() == 0) {
return false;
}
if (!(context instanceof IWebContext)) {
throw new ConfigurationException(
"Thymeleaf execution context is not a web context (implementation of " +
IWebContext.class.getName() + "). Spring Security integration can only be used in " +
"web environments.");
}
final IWebContext webContext = (IWebContext) context;
final ServletContext servletContext = webContext.getServletContext();
final Authentication authentication = AuthUtils.getAuthenticationObject();
if (authentication == null) {
return false;
}
final ApplicationContext applicationContext = AuthUtils.getContext(servletContext);
final IEngineConfiguration configuration = context.getConfiguration();
final int separatorPos = attrValue.lastIndexOf(VALUE_SEPARATOR);
if (separatorPos == -1) {
throw new TemplateProcessingException(
"Could not parse \"" + attributeValue + "\" as an access control list " +
"expression. Syntax should be \"[domain object expression] :: [permissions]\"");
}
final String domainObjectExpression = attrValue.substring(0,separatorPos).trim();
final String permissionsExpression = attrValue.substring(separatorPos + 2).trim();
final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(configuration);
final IStandardExpression domainObjectExpr =
getExpressionDefaultToLiteral(expressionParser, context, domainObjectExpression);
final IStandardExpression permissionsExpr =
getExpressionDefaultToLiteral(expressionParser, context, permissionsExpression);
final Object domainObject = domainObjectExpr.execute(context);
final Object permissionsObject = permissionsExpr.execute(context);
final String permissionsStr =
(permissionsObject == null? null : permissionsObject.toString());
return AclAuthUtils.authorizeUsingAccessControlList(
domainObject, applicationContext, permissionsStr, authentication, servletContext);
}
protected static IStandardExpression getExpressionDefaultToLiteral(
final IStandardExpressionParser expressionParser, final IExpressionContext context, final String input) {
final IStandardExpression expression = expressionParser.parseExpression(context, input);
if (expression == null) {
return new TextLiteralExpression(input);
}
return expression;
}
}
| 1,960 |
3,102 |
#include "cxx-irgen-top.h"
inline int h() { return S<int>::f(); }
namespace ImplicitSpecialMembers {
inline void create_right() {
// Trigger declaration, but not definition, of special members.
B b(0); C c(0); D d(0);
// Trigger definition of move constructor.
B b2(static_cast<B&&>(b));
D d2(static_cast<D&&>(d));
}
}
| 133 |
675 |
<filename>engine/core/render/base/shader/editor/shader_editor.h<gh_stars>100-1000
#pragma once
#include "engine/core/render/base/shader/shader_program.h"
namespace Echo
{
#ifdef ECHO_EDITOR_MODE
class ShaderEditor : public ObjectEditor
{
public:
ShaderEditor(Object* object);
virtual ~ShaderEditor();
// get icon, used for editor
ImagePtr getThumbnail() const;
private:
};
#endif
}
| 200 |
777 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gmock/gmock.h"
namespace blink {
class Interface {
public:
virtual void myMethod(int my_param) {}
};
class MockedInterface : public Interface {
public:
MOCK_METHOD1(myMethod, void(int));
};
void test() {
MockedInterface mockedInterface;
EXPECT_CALL(mockedInterface, myMethod(1));
EXPECT_CALL(
mockedInterface, // A comment to prevent reformatting into single line.
myMethod(1));
mockedInterface.myMethod(123);
}
} // namespace blink
| 204 |
2,164 |
<gh_stars>1000+
//
// Crashlytics.h
// Crashlytics
//
// Copyright (c) 2015 Crashlytics, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "CLSAttributes.h"
#import "CLSLogging.h"
#import "CLSReport.h"
#import "CLSStackFrame.h"
#import "Answers.h"
NS_ASSUME_NONNULL_BEGIN
@protocol CrashlyticsDelegate;
/**
* Crashlytics. Handles configuration and initialization of Crashlytics.
*
* Note: The Crashlytics class cannot be subclassed. If this is causing you pain for
* testing, we suggest using either a wrapper class or a protocol extension.
*/
@interface Crashlytics : NSObject
@property (nonatomic, readonly, copy) NSString *APIKey;
@property (nonatomic, readonly, copy) NSString *version;
@property (nonatomic, assign) BOOL debugMode;
/**
*
* The delegate can be used to influence decisions on reporting and behavior, as well as reacting
* to previous crashes.
*
* Make certain that the delegate is setup before starting Crashlytics with startWithAPIKey:... or
* via +[Fabric with:...]. Failure to do will result in missing any delegate callbacks that occur
* synchronously during start.
*
**/
@property (nonatomic, assign, nullable) id <CrashlyticsDelegate> delegate;
/**
* The recommended way to install Crashlytics into your application is to place a call to +startWithAPIKey:
* in your -application:didFinishLaunchingWithOptions: or -applicationDidFinishLaunching:
* method.
*
* Note: Starting with 3.0, the submission process has been significantly improved. The delay parameter
* is no longer required to throttle submissions on launch, performance will be great without it.
*
* @param apiKey The Crashlytics API Key for this app
*
* @return The singleton Crashlytics instance
*/
+ (Crashlytics *)startWithAPIKey:(NSString *)apiKey;
+ (Crashlytics *)startWithAPIKey:(NSString *)apiKey afterDelay:(NSTimeInterval)delay CLS_DEPRECATED("Crashlytics no longer needs or uses the delay parameter. Please use +startWithAPIKey: instead.");
/**
* If you need the functionality provided by the CrashlyticsDelegate protocol, you can use
* these convenience methods to activate the framework and set the delegate in one call.
*
* @param apiKey The Crashlytics API Key for this app
* @param delegate A delegate object which conforms to CrashlyticsDelegate.
*
* @return The singleton Crashlytics instance
*/
+ (Crashlytics *)startWithAPIKey:(NSString *)apiKey delegate:(nullable id<CrashlyticsDelegate>)delegate;
+ (Crashlytics *)startWithAPIKey:(NSString *)apiKey delegate:(nullable id<CrashlyticsDelegate>)delegate afterDelay:(NSTimeInterval)delay CLS_DEPRECATED("Crashlytics no longer needs or uses the delay parameter. Please use +startWithAPIKey:delegate: instead.");
/**
* Access the singleton Crashlytics instance.
*
* @return The singleton Crashlytics instance
*/
+ (Crashlytics *)sharedInstance;
/**
* The easiest way to cause a crash - great for testing!
*/
- (void)crash;
/**
* The easiest way to cause a crash with an exception - great for testing.
*/
- (void)throwException;
/**
* Specify a user identifier which will be visible in the Crashlytics UI.
*
* Many of our customers have requested the ability to tie crashes to specific end-users of their
* application in order to facilitate responses to support requests or permit the ability to reach
* out for more information. We allow you to specify up to three separate values for display within
* the Crashlytics UI - but please be mindful of your end-user's privacy.
*
* We recommend specifying a user identifier - an arbitrary string that ties an end-user to a record
* in your system. This could be a database id, hash, or other value that is meaningless to a
* third-party observer but can be indexed and queried by you.
*
* Optionally, you may also specify the end-user's name or username, as well as email address if you
* do not have a system that works well with obscured identifiers.
*
* Pursuant to our EULA, this data is transferred securely throughout our system and we will not
* disseminate end-user data unless required to by law. That said, if you choose to provide end-user
* contact information, we strongly recommend that you disclose this in your application's privacy
* policy. Data privacy is of our utmost concern.
*
* @param identifier An arbitrary user identifier string which ties an end-user to a record in your system.
*/
- (void)setUserIdentifier:(nullable NSString *)identifier;
/**
* Specify a user name which will be visible in the Crashlytics UI.
* Please be mindful of your end-user's privacy and see if setUserIdentifier: can fulfil your needs.
* @see setUserIdentifier:
*
* @param name An end user's name.
*/
- (void)setUserName:(nullable NSString *)name;
/**
* Specify a user email which will be visible in the Crashlytics UI.
* Please be mindful of your end-user's privacy and see if setUserIdentifier: can fulfil your needs.
*
* @see setUserIdentifier:
*
* @param email An end user's email address.
*/
- (void)setUserEmail:(nullable NSString *)email;
+ (void)setUserIdentifier:(nullable NSString *)identifier CLS_DEPRECATED("Please access this method via +sharedInstance");
+ (void)setUserName:(nullable NSString *)name CLS_DEPRECATED("Please access this method via +sharedInstance");
+ (void)setUserEmail:(nullable NSString *)email CLS_DEPRECATED("Please access this method via +sharedInstance");
/**
* Set a value for a for a key to be associated with your crash data which will be visible in the Crashlytics UI.
* When setting an object value, the object is converted to a string. This is typically done by calling
* -[NSObject description].
*
* @param value The object to be associated with the key
* @param key The key with which to associate the value
*/
- (void)setObjectValue:(nullable id)value forKey:(NSString *)key;
/**
* Set an int value for a key to be associated with your crash data which will be visible in the Crashlytics UI.
*
* @param value The integer value to be set
* @param key The key with which to associate the value
*/
- (void)setIntValue:(int)value forKey:(NSString *)key;
/**
* Set an BOOL value for a key to be associated with your crash data which will be visible in the Crashlytics UI.
*
* @param value The BOOL value to be set
* @param key The key with which to associate the value
*/
- (void)setBoolValue:(BOOL)value forKey:(NSString *)key;
/**
* Set an float value for a key to be associated with your crash data which will be visible in the Crashlytics UI.
*
* @param value The float value to be set
* @param key The key with which to associate the value
*/
- (void)setFloatValue:(float)value forKey:(NSString *)key;
+ (void)setObjectValue:(nullable id)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance");
+ (void)setIntValue:(int)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance");
+ (void)setBoolValue:(BOOL)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance");
+ (void)setFloatValue:(float)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance");
/**
* This method can be used to record a single exception structure in a report. This is particularly useful
* when your code interacts with non-native languages like Lua, C#, or Javascript. This call can be
* expensive and should only be used shortly before process termination. This API is not intended be to used
* to log NSException objects. All safely-reportable NSExceptions are automatically captured by
* Crashlytics.
*
* @param name The name of the custom exception
* @param reason The reason this exception occured
* @param frameArray An array of CLSStackFrame objects
*/
- (void)recordCustomExceptionName:(NSString *)name reason:(nullable NSString *)reason frameArray:(CLS_GENERIC_NSARRAY(CLSStackFrame *) *)frameArray;
/**
*
* This allows you to record a non-fatal event, described by an NSError object. These events will be grouped and
* displayed similarly to crashes. Keep in mind that this method can be expensive. Also, the total number of
* NSErrors that can be recorded during your app's life-cycle is limited by a fixed-size circular buffer. If the
* buffer is overrun, the oldest data is dropped. Errors are relayed to Crashlytics on a subsequent launch
* of your application.
*
* You can also use the -recordError:withAdditionalUserInfo: to include additional context not represented
* by the NSError instance itself.
*
**/
- (void)recordError:(NSError *)error;
- (void)recordError:(NSError *)error withAdditionalUserInfo:(nullable CLS_GENERIC_NSDICTIONARY(NSString *, id) *)userInfo;
- (void)logEvent:(NSString *)eventName CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:");
- (void)logEvent:(NSString *)eventName attributes:(nullable NSDictionary *) attributes CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:");
+ (void)logEvent:(NSString *)eventName CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:");
+ (void)logEvent:(NSString *)eventName attributes:(nullable NSDictionary *) attributes CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:");
@end
/**
*
* The CrashlyticsDelegate protocol provides a mechanism for your application to take
* action on events that occur in the Crashlytics crash reporting system. You can make
* use of these calls by assigning an object to the Crashlytics' delegate property directly,
* or through the convenience +startWithAPIKey:delegate: method.
*
*/
@protocol CrashlyticsDelegate <NSObject>
@optional
- (void)crashlyticsDidDetectCrashDuringPreviousExecution:(Crashlytics *)crashlytics CLS_DEPRECATED("Please refer to -crashlyticsDidDetectReportForLastExecution:");
- (void)crashlytics:(Crashlytics *)crashlytics didDetectCrashDuringPreviousExecution:(id <CLSCrashReport>)crash CLS_DEPRECATED("Please refer to -crashlyticsDidDetectReportForLastExecution:");
/**
*
* Called when a Crashlytics instance has determined that the last execution of the
* application ended in a crash. This is called synchronously on Crashlytics
* initialization. Your delegate must invoke the completionHandler, but does not need to do so
* synchronously, or even on the main thread. Invoking completionHandler with NO will cause the
* detected report to be deleted and not submitted to Crashlytics. This is useful for
* implementing permission prompts, or other more-complex forms of logic around submitting crashes.
*
* @warning Failure to invoke the completionHandler will prevent submissions from being reported. Watch out.
*
* @warning Just implementing this delegate method will disable all forms of synchronous report submission. This can
* impact the reliability of reporting crashes very early in application launch.
*
* @param report The CLSReport object representing the last detected crash
* @param completionHandler The completion handler to call when your logic has completed.
*
*/
- (void)crashlyticsDidDetectReportForLastExecution:(CLSReport *)report completionHandler:(void (^)(BOOL submit))completionHandler;
/**
* If your app is running on an OS that supports it (OS X 10.9+, iOS 7.0+), Crashlytics will submit
* most reports using out-of-process background networking operations. This results in a significant
* improvement in reliability of reporting, as well as power and performance wins for your users.
* If you don't want this functionality, you can disable by returning NO from this method.
*
* @warning Background submission is not supported for extensions on iOS or OS X.
*
* @param crashlytics The Crashlytics singleton instance
*
* @return Return NO if you don't want out-of-process background network operations.
*
*/
- (BOOL)crashlyticsCanUseBackgroundSessions:(Crashlytics *)crashlytics;
@end
/**
* `CrashlyticsKit` can be used as a parameter to `[Fabric with:@[CrashlyticsKit]];` in Objective-C. In Swift, use Crashlytics.sharedInstance()
*/
#define CrashlyticsKit [Crashlytics sharedInstance]
NS_ASSUME_NONNULL_END
| 3,343 |
9,516 |
import argparse
import json
import logging
import os
from time import time
import dgl
import torch
import torch.nn
import torch.nn.functional as F
from dgl.data import LegacyTUDataset
from dgl.dataloading import GraphDataLoader
from torch.utils.data import random_split
from network import get_sag_network
from utils import get_stats
def parse_args():
parser = argparse.ArgumentParser(description="Self-Attention Graph Pooling")
parser.add_argument("--dataset", type=str, default="DD",
choices=["DD", "PROTEINS", "NCI1", "NCI109", "Mutagenicity"],
help="DD/PROTEINS/NCI1/NCI109/Mutagenicity")
parser.add_argument("--batch_size", type=int, default=128,
help="batch size")
parser.add_argument("--lr", type=float, default=5e-4,
help="learning rate")
parser.add_argument("--weight_decay", type=float, default=1e-4,
help="weight decay")
parser.add_argument("--pool_ratio", type=float, default=0.5,
help="pooling ratio")
parser.add_argument("--hid_dim", type=int, default=128,
help="hidden size")
parser.add_argument("--dropout", type=float, default=0.5,
help="dropout ratio")
parser.add_argument("--epochs", type=int, default=100000,
help="max number of training epochs")
parser.add_argument("--patience", type=int, default=50,
help="patience for early stopping")
parser.add_argument("--device", type=int, default=-1,
help="device id, -1 for cpu")
parser.add_argument("--architecture", type=str, default="hierarchical",
choices=["hierarchical", "global"],
help="model architecture")
parser.add_argument("--dataset_path", type=str, default="./dataset",
help="path to dataset")
parser.add_argument("--conv_layers", type=int, default=3,
help="number of conv layers")
parser.add_argument("--print_every", type=int, default=10,
help="print trainlog every k epochs, -1 for silent training")
parser.add_argument("--num_trials", type=int, default=1,
help="number of trials")
parser.add_argument("--output_path", type=str, default="./output")
args = parser.parse_args()
# device
args.device = "cpu" if args.device == -1 else "cuda:{}".format(args.device)
if not torch.cuda.is_available():
logging.warning("CUDA is not available, use CPU for training.")
args.device = "cpu"
# print every
if args.print_every == -1:
args.print_every = args.epochs + 1
# paths
if not os.path.exists(args.dataset_path):
os.makedirs(args.dataset_path)
if not os.path.exists(args.output_path):
os.makedirs(args.output_path)
name = "Data={}_Hidden={}_Arch={}_Pool={}_WeightDecay={}_Lr={}.log".format(
args.dataset, args.hid_dim, args.architecture, args.pool_ratio, args.weight_decay, args.lr)
args.output_path = os.path.join(args.output_path, name)
return args
def train(model:torch.nn.Module, optimizer, trainloader, device):
model.train()
total_loss = 0.
num_batches = len(trainloader)
for batch in trainloader:
optimizer.zero_grad()
batch_graphs, batch_labels = batch
batch_graphs = batch_graphs.to(device)
batch_labels = batch_labels.long().to(device)
out = model(batch_graphs)
loss = F.nll_loss(out, batch_labels)
loss.backward()
optimizer.step()
total_loss += loss.item()
return total_loss / num_batches
@torch.no_grad()
def test(model:torch.nn.Module, loader, device):
model.eval()
correct = 0.
loss = 0.
num_graphs = 0
for batch in loader:
batch_graphs, batch_labels = batch
num_graphs += batch_labels.size(0)
batch_graphs = batch_graphs.to(device)
batch_labels = batch_labels.long().to(device)
out = model(batch_graphs)
pred = out.argmax(dim=1)
loss += F.nll_loss(out, batch_labels, reduction="sum").item()
correct += pred.eq(batch_labels).sum().item()
return correct / num_graphs, loss / num_graphs
def main(args):
# Step 1: Prepare graph data and retrieve train/validation/test index ============================= #
dataset = LegacyTUDataset(args.dataset, raw_dir=args.dataset_path)
# add self loop. We add self loop for each graph here since the function "add_self_loop" does not
# support batch graph.
for i in range(len(dataset)):
dataset.graph_lists[i] = dgl.add_self_loop(dataset.graph_lists[i])
num_training = int(len(dataset) * 0.8)
num_val = int(len(dataset) * 0.1)
num_test = len(dataset) - num_val - num_training
train_set, val_set, test_set = random_split(dataset, [num_training, num_val, num_test])
train_loader = GraphDataLoader(train_set, batch_size=args.batch_size, shuffle=True, num_workers=6)
val_loader = GraphDataLoader(val_set, batch_size=args.batch_size, num_workers=2)
test_loader = GraphDataLoader(test_set, batch_size=args.batch_size, num_workers=2)
device = torch.device(args.device)
# Step 2: Create model =================================================================== #
num_feature, num_classes, _ = dataset.statistics()
model_op = get_sag_network(args.architecture)
model = model_op(in_dim=num_feature, hid_dim=args.hid_dim, out_dim=num_classes,
num_convs=args.conv_layers, pool_ratio=args.pool_ratio, dropout=args.dropout).to(device)
args.num_feature = int(num_feature)
args.num_classes = int(num_classes)
# Step 3: Create training components ===================================================== #
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
# Step 4: training epoches =============================================================== #
bad_cound = 0
best_val_loss = float("inf")
final_test_acc = 0.
best_epoch = 0
train_times = []
for e in range(args.epochs):
s_time = time()
train_loss = train(model, optimizer, train_loader, device)
train_times.append(time() - s_time)
val_acc, val_loss = test(model, val_loader, device)
test_acc, _ = test(model, test_loader, device)
if best_val_loss > val_loss:
best_val_loss = val_loss
final_test_acc = test_acc
bad_cound = 0
best_epoch = e + 1
else:
bad_cound += 1
if bad_cound >= args.patience:
break
if (e + 1) % args.print_every == 0:
log_format = "Epoch {}: loss={:.4f}, val_acc={:.4f}, final_test_acc={:.4f}"
print(log_format.format(e + 1, train_loss, val_acc, final_test_acc))
print("Best Epoch {}, final test acc {:.4f}".format(best_epoch, final_test_acc))
return final_test_acc, sum(train_times) / len(train_times)
if __name__ == "__main__":
args = parse_args()
res = []
train_times = []
for i in range(args.num_trials):
print("Trial {}/{}".format(i + 1, args.num_trials))
acc, train_time = main(args)
res.append(acc)
train_times.append(train_time)
mean, err_bd = get_stats(res)
print("mean acc: {:.4f}, error bound: {:.4f}".format(mean, err_bd))
out_dict = {"hyper-parameters": vars(args),
"result": "{:.4f}(+-{:.4f})".format(mean, err_bd),
"train_time": "{:.4f}".format(sum(train_times) / len(train_times))}
with open(args.output_path, "w") as f:
json.dump(out_dict, f, sort_keys=True, indent=4)
| 3,399 |
2,542 |
<gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace ServiceModel;
using namespace Hosting2;
ComCodePackage::ComCodePackage(
ServiceModel::CodePackageDescription const & codePackageDescription,
std::wstring const& serviceManifestName,
std::wstring const& serviceManifestVersion,
std::wstring const& path,
ServiceModel::RunAsPolicyDescription const & setupRunAsPolicyDescription,
ServiceModel::RunAsPolicyDescription const & runAsPolicyDescription)
: heap_(),
codePackageDescription_(),
runAsPolicy_(),
setupRunAsPolicy_(),
path_(path)
{
codePackageDescription_ = heap_.AddItem<FABRIC_CODE_PACKAGE_DESCRIPTION>();
codePackageDescription.ToPublicApi(heap_, serviceManifestName, serviceManifestVersion, *codePackageDescription_);
if (!setupRunAsPolicyDescription.UserRef.empty())
{
setupRunAsPolicy_ = heap_.AddItem<FABRIC_RUNAS_POLICY_DESCRIPTION>();
setupRunAsPolicyDescription.ToPublicApi(heap_, *setupRunAsPolicy_);
}
if (!runAsPolicyDescription.UserRef.empty())
{
runAsPolicy_ = heap_.AddItem<FABRIC_RUNAS_POLICY_DESCRIPTION>();
runAsPolicyDescription.ToPublicApi(heap_, *runAsPolicy_);
}
}
ComCodePackage::~ComCodePackage()
{
}
const FABRIC_CODE_PACKAGE_DESCRIPTION * ComCodePackage::get_Description(void)
{
return codePackageDescription_.GetRawPointer();
}
LPCWSTR ComCodePackage::get_Path(void)
{
return path_.c_str();
}
const FABRIC_RUNAS_POLICY_DESCRIPTION * ComCodePackage::get_SetupEntryPointRunAsPolicy(void)
{
return setupRunAsPolicy_.GetRawPointer();
}
const FABRIC_RUNAS_POLICY_DESCRIPTION * ComCodePackage::get_EntryPointRunAsPolicy(void)
{
return runAsPolicy_.GetRawPointer();
}
| 686 |
753 |
<filename>tests/test_message_request_handler.py
import unittest
from test_mocks import MockSession
from LSP.plugin.core.message_request_handler import MessageRequestHandler
import sublime
class MessageRequestHandlerTest(unittest.TestCase):
def test_show_popup(self):
window = sublime.active_window()
view = window.active_view()
session = MockSession()
params = {
'type': 1,
'message': 'hello',
'actions': [
{'title': "abc"},
{'title': "def"}
]
}
handler = MessageRequestHandler(view, session, "1", params, 'lsp server')
handler.show()
self.assertTrue(view.is_popup_visible())
| 316 |
428 |
/**
* Copyright 2008 - 2011
*
* 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.
*
* @project loon
* @author cping
* @email <EMAIL>
* @version 0.1.1
*/
package loon.action.map;
import loon.LSystem;
import loon.Screen;
import loon.action.ActionBind;
import loon.action.collision.CollisionHelper;
import loon.action.map.colider.Tile;
import loon.action.map.colider.TileHelper;
import loon.geom.PointF;
import loon.geom.PointI;
import loon.geom.RectBox;
import loon.geom.Vector2f;
import loon.utils.CollectionUtils;
import loon.utils.IArray;
import loon.utils.IntArray;
import loon.utils.MathUtils;
import loon.utils.StrBuilder;
import loon.utils.TArray;
/**
* 二维数组到地图数据的存储转化与处理用类
*/
public class Field2D implements IArray, Config {
private final static int[][][] NEIGHBORS = { { { 1, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 }, { -1, 1 }, { 0, 1 } },
{ { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 }, { -1, 0 }, { 0, 1 } } };
private final static float ANGULAR = 0.706F;
private String _fieldName = "Field2D";
private Vector2f _offset = new Vector2f();
private RectBox _rectTemp = null;
private Tile _tileImpl;
public Object Tag;
private TArray<Vector2f> result;
private int[][] mapArrays;
private int[] moveLimited;
// default size
private int tileWidth = 32;
private int tileHeight = 32;
private int width, height;
private IntArray allowMove;
public TArray<PointI> getPosOfLine(int x0, int y0, int x1, int y1) {
TArray<PointI> list = new TArray<PointI>();
int dx = MathUtils.abs(x1 - x0);
int dy = MathUtils.abs(y1 - y0);
int sx = (x0 < x1) ? 1 : -1;
int sy = (y0 < y1) ? 1 : -1;
int err = dx - dy;
for (;;) {
list.add(new PointI(x0, y1));
if ((x0 == x1) && (y0 == y1)) {
break;
}
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x0 += sx;
}
if (e2 < dx) {
err += dx;
y0 += sy;
}
}
return list;
}
public TArray<PointI> getPosOfParabola(int x0, int y0, int x1, int y1, int height) {
if (x0 == x1) {
return this.getPosOfLine(x0, y0, x1, y1);
}
TArray<PointI> list = new TArray<PointI>();
int top_y, start_x, start_y, dest_x, dest_y;
top_y = (y0 + y1) / 2 - height;
if (y0 > y1) {
start_y = y1;
dest_y = y0;
} else {
start_y = y0;
dest_y = y1;
}
if (x0 > x1) {
start_x = x1;
dest_x = x0;
} else {
dest_x = x1;
start_x = x0;
}
int k = (int) -MathUtils.sqrt((top_y - start_y) / (top_y - dest_y));
int v = (k * dest_x - start_x) / (k - 1);
int u = (top_y - start_y) / ((start_x - v) * (start_x - v));
for (int x = start_x; x <= dest_x; x++) {
int y = top_y - u * (x - v) * (x - v);
list.add(new PointI(x, y));
}
if (x0 > x1) {
list = list.reverse();
}
return list;
}
public TArray<PointI> getPosOfParabola(int x1, int y1, int x2, int y2, int x3, int y3) {
TArray<PointI> list = new TArray<PointI>();
int a = (x1 * (y3 - y2) - x2 * y3 + y2 * x3 + y1 * (x2 - x3))
/ (x1 * ((x3 * x3) - (x2 * x2)) - x2 * (x3 * x3) + (x2 * x2) * x3 + (x1 * x1) * (x2 - x3));
int b = -((x1 * x1) * (y3 - y2) - (x2 * x2) * y3 + y2 * (x3 * x3) + y1 * ((x2 * x2) - (x3 * x3)))
/ (x1 * ((x3 * x3) - (x2 * x2)) - x2 * (x3 * x3) + (x2 * x2) * x3 + (x1 * x1) * (x2 - x3));
int c = (x1 * (y2 * (x3 * x3) - (x2 * x2) * y3) + (x1 * x1) * (x2 * y3 - y2 * x3)
+ y1 * ((x2 * x2) * x3 - x2 * (x3 * x3)))
/ (x1 * ((x3 * x3) - (x2 * x2)) - x2 * (x3 * x3) + (x2 * x2) * x3 + (x1 * x1) * (x2 - x3));
int start_x;
int end_x;
if (x1 <= x3) {
start_x = x1;
end_x = x3;
} else {
start_x = x3;
end_x = x1;
}
for (int x = start_x; x <= end_x; x++) {
int y = a * x * x + b * x + c;
list.add(new PointI(x, y));
}
return list;
}
public static final Vector2f shiftPosition(TArray<ActionBind> items, float x, float y, int direction) {
return shiftPosition(items, x, y, direction, null);
}
public static final Vector2f shiftPosition(TArray<ActionBind> items, float x, float y, int direction,
Vector2f output) {
if (output == null) {
output = new Vector2f();
}
float px;
float py;
if (items.size > 1) {
int i = 0;
float cx = 0f;
float cy = 0f;
ActionBind cur = null;
if (direction == 0) {
// 下方坐标转上方坐标
int len = items.size - 1;
ActionBind obj = items.get(len);
px = obj.getX();
py = obj.getY();
for (i = len - 1; i >= 0; i--) {
cur = items.get(i);
cx = cur.getX();
cy = cur.getX();
cur.setX(px);
cur.setY(py);
px = cx;
py = cy;
}
obj.setX(x);
obj.setX(y);
} else {
// 上方坐标转下方坐标
ActionBind obj = items.get(0);
px = obj.getX();
py = obj.getY();
for (i = 1; i < items.size; i++) {
cur = items.get(i);
cx = cur.getX();
cy = cur.getX();
cur.setX(px);
cur.setY(py);
px = cx;
py = cy;
}
obj.setX(x);
obj.setX(y);
}
} else {
ActionBind obj = items.get(0);
px = obj.getX();
py = obj.getY();
obj.setX(x);
obj.setX(y);
}
output.x = px;
output.y = py;
return output;
}
public final static Vector2f toXY(int index, int width, int height) {
Vector2f out = new Vector2f();
float nx = 0f;
float ny = 0f;
int total = width * height;
if (index > 0 && index <= total) {
if (index > width - 1) {
ny = MathUtils.floor(index / width);
nx = index - (ny * width);
} else {
nx = index;
}
out.set(nx, ny);
}
return out;
}
public static final float getRelation(float x, float x1, float x2, float y1, float y2, float scale) {
if (scale <= 0f) {
scale = 1f;
}
return ((y2 - y1) / MathUtils.pow((x2 - x1), scale) * 1f) * MathUtils.pow((x - x1), scale) + y1;
}
public static final float rotation(Vector2f source, Vector2f target) {
int nx = MathUtils.floor(target.getX() - source.getX());
int ny = MathUtils.floor(target.getY() - source.getY());
return MathUtils.toDegrees(MathUtils.atan2(ny, nx));
}
public static final int angle(Vector2f source, Vector2f target) {
float nx = target.getX() - source.getX();
float ny = target.getY() - source.getY();
float r = MathUtils.sqrt(nx * nx + ny * ny);
float cos = nx / r;
int angle = MathUtils.floor(MathUtils.acos(cos) * 180 / MathUtils.PI);
if (ny < 0) {
angle = 360 - angle;
}
return angle;
}
public static final float getDirectionToAngle(int dir) {
switch (dir) {
case Config.UP:
return 45;
case Config.LEFT:
return 315;
case Config.RIGHT:
return 135;
case Config.DOWN:
return 225;
case Config.TRIGHT:
return 90;
case Config.TDOWN:
return 180;
case Config.TLEFT:
return 270;
case Config.TUP:
default:
return 0;
}
}
public static final Vector2f getDirectionToPoint(int dir, int value) {
Vector2f direction = null;
switch (dir) {
case Config.UP:
direction = new Vector2f(value, -value);
break;
case Config.LEFT:
direction = new Vector2f(-value, -value);
break;
case Config.RIGHT:
direction = new Vector2f(value, value);
break;
case Config.DOWN:
direction = new Vector2f(-value, value);
break;
case Config.TUP:
direction = new Vector2f(0, -value);
break;
case Config.TLEFT:
direction = new Vector2f(-value, 0);
break;
case Config.TRIGHT:
direction = new Vector2f(value, 0);
break;
case Config.TDOWN:
direction = new Vector2f(0, value);
break;
default:
direction = new Vector2f(0, 0);
break;
}
return direction;
}
public static final int getDirection(int x, int y) {
return getDirection(x, y, Config.EMPTY);
}
public static final int getDirection(int x, int y, int value) {
int newX = 0;
int newY = 0;
if (x > 0) {
newX = 1;
} else if (x < 0) {
newX = -1;
}
if (y > 0) {
newY = 1;
} else if (y < 0) {
newY = -1;
}
int dir = getDirectionImpl(newX, newY);
return Config.EMPTY == dir ? value : dir;
}
private static final int getDirectionImpl(int x, int y) {
if (x == 0 && y == 0) {
return Config.EMPTY;
} else if (x == 1 && y == -1) {
return Config.UP;
} else if (x == 0 && y == -1) {
return Config.TUP;
} else if (x == -1 && y == -1) {
return Config.LEFT;
} else if (x == 1 && y == 1) {
return Config.RIGHT;
} else if (x == -1 && y == 1) {
return Config.DOWN;
} else if (x == -1 && y == 0) {
return Config.TLEFT;
} else if (x == 1 && y == 0) {
return Config.TRIGHT;
} else if (x == 0 && y == 1) {
return Config.TDOWN;
}
return Config.EMPTY;
}
public static final Vector2f getDirection(int type) {
if (type > Config.TDOWN) {
type = Config.TDOWN;
}
return getDirectionToPoint(type, 1).cpy();
}
public static final String toDirection(int id) {
switch (id) {
default:
case Config.EMPTY:
return "EMPTY";
case Config.LEFT:
return "LEFT";
case Config.RIGHT:
return "RIGHT";
case Config.UP:
return "UP";
case Config.DOWN:
return "DOWN";
case Config.TLEFT:
return "TLEFT";
case Config.TRIGHT:
return "TRIGHT";
case Config.TDOWN:
return "TDOWN";
case Config.TUP:
return "TUP";
}
}
private static void insertArrays(int[][] arrays, int index, int px, int py) {
arrays[index][0] = px;
arrays[index][1] = py;
}
public static final int getDirection(Vector2f source, Vector2f target, int dirNumber) {
int angleValue = angle(source, target);
return getDirection(source, target, angleValue, dirNumber);
}
public static final int getDirection(Vector2f source, Vector2f target, float angleValue, int dirNumber) {
if (dirNumber == 4) {
if (angleValue < 90) {
return Config.RIGHT;
} else if (angleValue < 180) {
return Config.DOWN;
} else if (angleValue < 270) {
return Config.LEFT;
} else {
return Config.UP;
}
} else if (dirNumber == 6) {
if (angleValue > 337 || angleValue < 23) {
return Config.TRIGHT;
} else if (angleValue > 270) {
return Config.UP;
} else if (angleValue > 202) {
return Config.LEFT;
} else if (angleValue > 157) {
return Config.TLEFT;
} else if (angleValue > 90) {
return Config.DOWN;
} else {
return Config.RIGHT;
}
} else if (dirNumber == 8) {
if (angleValue > 337 || angleValue < 23) {
return Config.TRIGHT;
} else if (angleValue > 292) {
return Config.UP;
} else if (angleValue > 247) {
return Config.TUP;
} else if (angleValue > 202) {
return Config.LEFT;
} else if (angleValue > 157) {
return Config.TLEFT;
} else if (angleValue > 112) {
return Config.DOWN;
} else if (angleValue > 67) {
return Config.TDOWN;
} else {
return Config.RIGHT;
}
}
return Config.EMPTY;
}
public static final int getDirection(Vector2f source, Vector2f target) {
return getDirection(source.x, source.y, target.x, target.y);
}
public static final int getDirection(float srcX, float srcY, float destX, float destY) {
if (srcX - destX > 0) {
if (srcY - destY > 0) {
return Config.LEFT;
} else if (srcY - destY < 0) {
return Config.DOWN;
} else {
return Config.TLEFT;
}
} else if (srcX - destX < 0) {
if (srcY - destY > 0) {
return Config.UP;
} else if (srcY - destY < 0) {
return Config.RIGHT;
} else {
return Config.TRIGHT;
}
} else {
if (srcY - destY > 0) {
return Config.TUP;
} else if (srcY - destY < 0) {
return Config.TDOWN;
} else {
return Config.EMPTY;
}
}
}
public static final int getDirection(float angle) {
float tup = MathUtils.sin(angle) * 0 + MathUtils.cos(angle) * -1;
float tright = MathUtils.sin(angle) * 1 + MathUtils.cos(angle) * 0;
float tleft = MathUtils.sin(angle) * -1 + MathUtils.cos(angle) * 0;
float tdown = MathUtils.sin(angle) * 0 + MathUtils.cos(angle) * 1;
if (tup > ANGULAR) {
return TUP;
}
if (tright > ANGULAR) {
return TRIGHT;
}
if (tleft > ANGULAR) {
return TLEFT;
}
if (tdown > ANGULAR) {
return TDOWN;
}
return EMPTY;
}
public Field2D(Field2D field) {
cpy(field);
}
public Field2D(String fileName, int tw, int th) {
set(TileMapConfig.loadAthwartArray(fileName), tw, th);
}
public Field2D(int[][] mapArrays) {
this(mapArrays, 0, 0);
}
public Field2D(int[][] mapArrays, int tw, int th) {
this.set(mapArrays, tw, th);
}
public Field2D(int w, int h) {
this(w, h, 32, 32, 0);
}
public Field2D(Screen screen, int tw, int th) {
this(MathUtils.floor(screen.getWidth() / tw), MathUtils.floor(screen.getHeight() / th), tw, th, 0);
}
public Field2D(int w, int h, int tw, int th) {
this(w, h, tw, th, 0);
}
public Field2D(int w, int h, int tw, int th, int val) {
int[][] newMap = new int[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
newMap[i][j] = val;
}
}
this.set(newMap, tw, th);
}
public Field2D fill(int val) {
return setValues(val);
}
public Field2D cpy() {
return new Field2D(this);
}
public Field2D cpy(Field2D field) {
this.set(CollectionUtils.copyOf(field.mapArrays), field.tileWidth, field.tileHeight);
if (field._offset != null) {
this._offset = field._offset.cpy();
}
if (field._rectTemp != null) {
this._rectTemp = field._rectTemp.cpy();
}
this._tileImpl = field._tileImpl;
this.Tag = field.Tag;
if (field.result != null) {
this.result = field.result.cpy();
}
if (field.moveLimited != null) {
this.moveLimited = CollectionUtils.copyOf(field.moveLimited);
}
this.width = field.width;
this.height = field.height;
if (field.allowMove != null) {
this.allowMove = new IntArray(field.allowMove);
}
return this;
}
public Tile getTile(int x, int y) {
if (contains(x, y)) {
return _tileImpl.at(getTileType(x, y), x, y, this.tileWidth, this.tileHeight);
}
return null;
}
public Tile getPointTile(float px, float py) {
int x = MathUtils.floor(px / this.tileWidth);
int y = MathUtils.floor(py / this.tileHeight);
return getTile(x, y);
}
public Field2D set(int[][] arrays, int tw, int th) {
if (this.allowMove == null) {
this.allowMove = new IntArray();
}
this.setMap(arrays);
this.setTileWidth(tw);
this.setTileHeight(th);
if (arrays != null) {
this.width = arrays[0].length;
this.height = arrays.length;
}
if (_tileImpl == null) {
this._tileImpl = new TileHelper(tileWidth, tileHeight);
} else {
this._tileImpl.setWidth(tileWidth);
this._tileImpl.setHeight(tileHeight);
}
return this;
}
public Field2D setSize(int width, int height) {
this.width = width;
this.height = height;
return this;
}
public Field2D setTile(int tw, int th) {
this.tileWidth = tw;
this.tileHeight = th;
return this;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getDrawWidth() {
return tilesToHeightPixels(width);
}
public int getDrawHeight() {
return tilesToHeightPixels(height);
}
public int getHexagonWidth() {
return MathUtils.floor(width / 3f * 2f);
}
public int getHexagonHeight() {
return MathUtils.floor(height / MathUtils.sqrt(3f)) - 1;
}
public PointI pixelsHexagonToTiles(float x, float y) {
float sqrte = MathUtils.sqrt(3f) / 3f;
int hx = MathUtils.floor(2 / 3 * x / tileWidth);
int hy = (int) ((sqrte * y / tileHeight + MathUtils.round(hx) % 2f) * sqrte);
return new PointI(hx, hy);
}
public PointI pixelsIsometricToTiles(float x, float y) {
int hx = MathUtils.floor(x / (tileWidth * 0.5f));
int hy = MathUtils.floor((y - hx * (tileHeight / 2f)) / tileHeight);
return new PointI(hx + hy, hy);
}
public PointI pixelsOrthogonalToTiles(float x, float y) {
int hx = MathUtils.floor(x / tileWidth);
int hy = MathUtils.floor(y / tileHeight);
return new PointI(hx, hy);
}
public int toPixelX(float x) {
return tilesToWidthPixels(x);
}
public int toPixelY(float y) {
return tilesToHeightPixels(y);
}
public int toTileX(float x) {
return pixelsToTilesWidth(x);
}
public int toTileY(float y) {
return pixelsToTilesHeight(y);
}
public int pixelsToTilesWidth(float x) {
return MathUtils.floor(x / tileWidth);
}
public int pixelsToTilesWidth(int x) {
return MathUtils.floor(x / tileWidth);
}
public int pixelsToTilesHeight(float y) {
return MathUtils.floor(y / tileHeight);
}
public int pixelsToTilesHeight(int y) {
return MathUtils.floor(y / tileHeight);
}
public int tilesToWidthPixels(int tiles) {
return tiles * tileWidth;
}
public int tilesToHeightPixels(int tiles) {
return tiles * tileHeight;
}
public int tilesToWidthPixels(float tiles) {
return (int) (tiles * tileWidth);
}
public int tilesToHeightPixels(float tiles) {
return (int) (tiles * tileHeight);
}
public int getViewWidth() {
return tilesToWidthPixels(width);
}
public int getViewHeight() {
return tilesToWidthPixels(height);
}
public int getTileHeight() {
return tileHeight;
}
public int getTileHalfHeight() {
return tileHeight / 2;
}
public Field2D setTileHeight(int tileHeight) {
this.tileHeight = tileHeight;
return this;
}
public int getTileHalfWidth() {
return tileWidth / 2;
}
public int getTileWidth() {
return tileWidth;
}
public Field2D setTileWidth(int tileWidth) {
this.tileWidth = tileWidth;
return this;
}
public Field2D addActionBindToMap(TArray<ActionBind> acts, ActionBind other) {
return addActionBindToMap(acts, -1, other);
}
public Field2D addActionBindToMap(TArray<ActionBind> acts, int flagid, ActionBind other) {
for (ActionBind act : acts) {
if (act != null && act != other) {
float x = act.getX();
float y = act.getY();
float w = act.getWidth();
float h = act.getHeight();
int dstTileX = pixelsToTilesWidth(x);
int dstTileY = pixelsToTilesHeight(y);
int dstTileWidth = dstTileX + pixelsToTilesWidth(w);
int dstTileHeight = dstTileY + pixelsToTilesWidth(h);
int fieldWidth = mapArrays[0].length;
int fieldHeight = mapArrays.length;
for (int i = 0; i < fieldHeight; i++) {
for (int j = 0; j < fieldWidth; j++) {
if (j > dstTileX && j < dstTileWidth && i > dstTileY && i < dstTileHeight) {
mapArrays[i][j] = flagid;
}
}
}
}
}
return this;
}
public int[] getLimit() {
return moveLimited;
}
public Field2D setLimit(int[] limit) {
this.moveLimited = limit;
return this;
}
public Field2D setAllowMove(int[] args) {
this.allowMove.addAll(args);
return this;
}
public boolean contains(int x, int y) {
return x >= 0 && x < width && y >= 0 && y < height;
}
public Field2D replaceType(int oldid, int newid) {
int w = mapArrays[0].length;
int h = mapArrays.length;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
int id = mapArrays[i][j];
if (id == oldid) {
mapArrays[i][j] = newid;
}
}
}
return this;
}
public boolean isTileType(int x, int y, int type) {
return getTileType(x, y) == type;
}
public int getTileType(int x, int y) {
try {
if (!contains(x, y)) {
return -1;
}
return mapArrays[y][x];
} catch (Throwable e) {
return -1;
}
}
public Field2D setTileType(int x, int y, int tile) {
try {
if (!contains(x, y)) {
return this;
}
this.mapArrays[y][x] = tile;
} catch (Throwable e) {
}
return this;
}
public int[][] getMap() {
return CollectionUtils.copyOf(mapArrays);
}
public Field2D setMap(int[][] arrays) {
if (arrays == null) {
return this;
}
this.mapArrays = arrays;
return this;
}
public int getPixelsAtFieldType(Vector2f pos) {
return getPixelsAtFieldType(pos.x, pos.y);
}
public int getPixelsAtFieldType(float x, float y) {
int itsX = pixelsToTilesWidth(x);
int itsY = pixelsToTilesHeight(y);
return getPixelsAtFieldType(itsX, itsY);
}
public IntArray getAllowMove() {
return this.allowMove;
}
public boolean inside(int x, int y) {
return CollisionHelper.intersects(0, 0, getDrawWidth(), getDrawHeight(), x, y);
}
public boolean inside(float x, float y) {
return inside((int) x, (int) y);
}
public boolean isHit(Vector2f point) {
return isHit(point.x(), point.y());
}
public boolean isHit(PointI point) {
return isHit(point.x, point.y);
}
public boolean isHit(PointF point) {
return isHit((int) point.x, (int) point.y);
}
public boolean isPixelHit(float px, float py) {
return isHit(pixelsToTilesWidth(px), pixelsToTilesHeight(py));
}
public Vector2f getPixelLimitPos(float px, float py) {
if (!isHit(pixelsToTilesWidth(px), pixelsToTilesHeight(py))) {
return new Vector2f(px, py);
}
return null;
}
public boolean isHit(int px, int py) {
int type = get(mapArrays, px, py);
if (type == -1 && !allowMove.contains(type)) {
return false;
}
if (moveLimited != null) {
final int size = moveLimited.length - 1;
for (int i = size; i > -1; i--) {
if (moveLimited[i] == type) {
return false;
}
}
}
return true;
}
public Vector2f getTileCollision(ActionBind bind, float newX, float newY) {
if (bind == null) {
return null;
}
return getTileCollision(bind.getX(), bind.getY(), bind.getWidth(), bind.getHeight(), newX, newY);
}
public Vector2f getTileCollision(float srcX, float srcY, float srcWidth, float srcHeight, float newX, float newY) {
newX = MathUtils.ceil(newX);
newY = MathUtils.ceil(newY);
float fromX = MathUtils.min(srcX, newX);
float fromY = MathUtils.min(srcY, newY);
float toX = MathUtils.max(srcX, newX);
float toY = MathUtils.max(srcY, newY);
int fromTileX = pixelsToTilesWidth(fromX);
int fromTileY = pixelsToTilesHeight(fromY);
int toTileX = pixelsToTilesWidth(toX + srcWidth - 1f);
int toTileY = pixelsToTilesHeight(toY + srcHeight - 1f);
for (int x = fromTileX; x <= toTileX; x++) {
for (int y = fromTileY; y <= toTileY; y++) {
if ((x < 0) || (x >= getWidth())) {
return new Vector2f(x, y);
}
if ((y < 0) || (y >= getHeight())) {
return new Vector2f(x, y);
}
if (!this.isHit(x, y)) {
return new Vector2f(x, y);
}
}
}
return null;
}
public boolean checkTileCollision(ActionBind bind, float newX, float newY) {
if (bind == null) {
return false;
}
return checkTileCollision(bind.getX(), bind.getY(), bind.getWidth(), bind.getHeight(), newX, newY);
}
public boolean checkTileCollision(float srcX, float srcY, float srcWidth, float srcHeight, float newX, float newY) {
newX = MathUtils.ceil(newX);
newY = MathUtils.ceil(newY);
float fromX = MathUtils.min(srcX, newX);
float fromY = MathUtils.min(srcY, newY);
float toX = MathUtils.max(srcX, newX);
float toY = MathUtils.max(srcY, newY);
int fromTileX = pixelsToTilesWidth(fromX);
int fromTileY = pixelsToTilesHeight(fromY);
int toTileX = pixelsToTilesWidth(toX + srcWidth - 1f);
int toTileY = pixelsToTilesHeight(toY + srcHeight - 1f);
for (int x = fromTileX; x <= toTileX; x++) {
for (int y = fromTileY; y <= toTileY; y++) {
if ((x < 0) || (x >= getWidth())) {
return true;
}
if ((y < 0) || (y >= getHeight())) {
return true;
}
if (!this.isHit(x, y)) {
return true;
}
}
}
return false;
}
public boolean notWidth(final int x) {
return x < 0 || x >= width;
}
public boolean notHeight(final int y) {
return y < 0 || y >= height;
}
public Vector2f toXY(int index) {
return toXY(index, this.width, this.height);
}
public int[][] neighbors(int px, int py, boolean flag) {
int[][] pos = new int[flag ? 8 : 4][2];
insertArrays(pos, 0, px, py - 1);
insertArrays(pos, 0, px + 1, py);
insertArrays(pos, 0, px, py + 1);
insertArrays(pos, 0, px - 1, py);
if (flag) {
insertArrays(pos, 0, px - 1, py - 1);
insertArrays(pos, 0, px + 1, py - 1);
insertArrays(pos, 0, px + 1, py + 1);
insertArrays(pos, 0, px - 1, py + 1);
}
return pos;
}
public TArray<Vector2f> neighbors(Vector2f pos, boolean flag) {
if (result == null) {
result = new TArray<Vector2f>(flag ? 8 : 4);
} else {
result.clear();
}
int x = pos.x();
int y = pos.y();
result.add(new Vector2f(x, y - 1));
result.add(new Vector2f(x + 1, y));
result.add(new Vector2f(x, y + 1));
result.add(new Vector2f(x - 1, y));
if (flag) {
result.add(new Vector2f(x - 1, y - 1));
result.add(new Vector2f(x + 1, y - 1));
result.add(new Vector2f(x + 1, y + 1));
result.add(new Vector2f(x - 1, y + 1));
}
return result;
}
protected int get(int[][] mapArrays, int px, int py) {
try {
if (contains(px, py)) {
return mapArrays[py][px];
} else {
return -1;
}
} catch (Throwable e) {
return -1;
}
}
protected int get(int[][] mapArrays, Vector2f point) {
return get(mapArrays, point.x(), point.y());
}
public RectBox getRect() {
if (_rectTemp == null) {
_rectTemp = new RectBox(0, 0, getViewWidth(), getViewHeight());
} else {
_rectTemp.setSize(getViewWidth(), getViewHeight());
}
return _rectTemp;
}
public Field2D setValues(int val) {
int w = mapArrays[0].length;
int h = mapArrays.length;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
mapArrays[i][j] = val;
}
}
return this;
}
public Tile getTileImpl() {
return _tileImpl;
}
public Field2D setTileImpl(Tile tileImpl) {
this._tileImpl = tileImpl;
return this;
}
public int clampX(int x) {
return MathUtils.clamp(x, 0, this.width - 1);
}
public int clampY(int y) {
return MathUtils.clamp(y, 0, this.height - 1);
}
public boolean canOffsetTile(float x, float y) {
return this._offset.x >= x - width && this._offset.x <= x + width && this._offset.y >= y - height
&& this._offset.y <= y + height;
}
public float getIsometricType(float px, float py) {
float halfWidth = this.getDrawWidth() * 0.5f;
if (px < 0 || px >= halfWidth || py < 0 || py >= this.getDrawHeight()) {
return -1;
}
PointI point = this.pixelsIsometricToTiles(px, py);
return this.getTileType(point.x, point.y);
}
public Field2D setIsometricType(float px, float py, int t) {
float halfWidth = this.getDrawWidth() * 0.5f;
if (px < 0 || px >= halfWidth || py < 0 || py >= this.getDrawHeight()) {
return this;
}
PointI point = this.pixelsIsometricToTiles(px, py);
return this.setTileType(point.x, point.y, t);
}
public int getNeighborType(float px, float py, int d) {
PointI point = this.pixelsHexagonToTiles(px, py);
int[] n = NEIGHBORS[point.x & 1][d];
int nx = point.x + n[0];
int ny = point.y + n[1];
if (nx < 0 || nx >= getHexagonWidth() || ny < 0 || ny >= getHexagonHeight()) {
return -1;
}
return getTileType(nx, ny);
}
public Field2D setNeighborType(float px, float py, int d, int t) {
PointI point = this.pixelsHexagonToTiles(px, py);
int[] n = NEIGHBORS[point.x & 1][d];
int nx = point.x + n[0];
int ny = point.y + n[1];
if (nx < 0 || nx >= getHexagonWidth() || ny < 0 || ny >= getHexagonHeight()) {
return this;
}
return setTileType(nx, ny, t);
}
public Vector2f getOffset() {
return _offset;
}
public Field2D setOffset(Vector2f offset) {
this._offset = offset;
return this;
}
public int offsetXPixel(int x) {
return x - _offset.x();
}
public int offsetYPixel(int y) {
return y - _offset.y();
}
@Override
public boolean isEmpty() {
return mapArrays == null || mapArrays.length == 0;
}
public Field2D setName(String n) {
this._fieldName = n;
return this;
}
public String getName() {
return this._fieldName;
}
@Override
public int size() {
return width * height;
}
@Override
public void clear() {
set(new int[height][width], width, height);
}
@Override
public String toString() {
return toString(',');
}
public String toString(char split) {
if (isEmpty()) {
return "[]";
}
StrBuilder buffer = new StrBuilder(size() * 2 + height + 2);
buffer.append('[');
buffer.append(LSystem.LS);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
buffer.append(mapArrays[i][j]);
if (j < width - 1) {
buffer.append(split);
}
}
buffer.append(LSystem.LS);
}
buffer.append(']');
return buffer.toString();
}
}
| 12,431 |
571 |
<gh_stars>100-1000
package camelinaction;
import org.apache.camel.Exchange;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Unit test to demonstrate using the Log EIP for custom logging using Spring XML
*/
public class LogEIPSpringTest extends CamelSpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("camelinaction/LogEIPSpringTest.xml");
}
@Override
public void setUp() throws Exception {
deleteDirectory("target/rider/orders");
super.setUp();
}
@Test
public void testLogEIP() throws Exception {
template.sendBodyAndHeader("file://target/rider/orders", "123,4444,20170810,222,1", Exchange.FILE_NAME, "someorder.csv");
String xml = consumer.receiveBody("seda:queue:orders", 5000, String.class);
assertEquals("<order><id>123/id><customerId>4444/customerId><date>20170810</date>"
+ "<item><id>222</id><amount>1</amount></itemn></order>", xml);
}
}
| 423 |
2,062 |
<filename>tests/aiohttp/app.py
from aiohttp import web
from strawberry.aiohttp.handlers import GraphQLTransportWSHandler, GraphQLWSHandler
from strawberry.aiohttp.views import GraphQLView
from tests.aiohttp.schema import Query, schema
class DebuggableGraphQLTransportWSHandler(GraphQLTransportWSHandler):
async def get_context(self) -> object:
context = await super().get_context()
context["ws"] = self._ws
context["tasks"] = self.tasks
context["connectionInitTimeoutTask"] = self.connection_init_timeout_task
return context
class DebuggableGraphQLWSHandler(GraphQLWSHandler):
async def get_context(self) -> object:
context = await super().get_context()
context["ws"] = self._ws
context["tasks"] = self.tasks
context["connectionInitTimeoutTask"] = None
return context
class MyGraphQLView(GraphQLView):
graphql_transport_ws_handler_class = DebuggableGraphQLTransportWSHandler
graphql_ws_handler_class = DebuggableGraphQLWSHandler
async def get_root_value(self, request: web.Request):
return Query()
def create_app(**kwargs):
app = web.Application()
app.router.add_route("*", "/graphql", MyGraphQLView(schema=schema, **kwargs))
return app
| 464 |
1,840 |
/**
* Copyright Pravega Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.pravega.controller.store.kvtable;
import com.google.common.base.Preconditions;
import io.pravega.client.tables.KeyValueTableConfiguration;
import io.pravega.common.concurrent.Futures;
import io.pravega.controller.store.Version;
import io.pravega.controller.store.VersionedMetadata;
import io.pravega.controller.store.kvtable.records.KVTConfigurationRecord;
import io.pravega.controller.store.kvtable.records.KVTEpochRecord;
import io.pravega.controller.store.kvtable.records.KVTStateRecord;
import io.pravega.controller.store.stream.OperationContext;
import io.pravega.controller.store.stream.StoreException;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.concurrent.GuardedBy;
import java.util.Map;
import java.util.HashMap;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicLong;
@Slf4j
public class InMemoryKVTable extends AbstractKVTableBase {
private final UUID id;
private final AtomicLong creationTime = new AtomicLong(Long.MIN_VALUE);
private final Object lock = new Object();
@GuardedBy("lock")
private VersionedMetadata<KVTConfigurationRecord> configuration;
@GuardedBy("lock")
private VersionedMetadata<KVTStateRecord> state;
@GuardedBy("lock")
private VersionedMetadata<KVTEpochRecord> currentEpochRecord;
@GuardedBy("lock")
private Map<Integer, VersionedMetadata<KVTEpochRecord>> epochRecords = new HashMap<>();
public InMemoryKVTable(String scope, String name, UUID id) {
super(scope, name);
this.id = id;
}
public InMemoryKVTable(String scope, String name) {
this(scope, name, UUID.randomUUID());
}
@Override
public CompletableFuture<String> getId(OperationContext context) {
return CompletableFuture.completedFuture(id.toString());
}
@Override
public CompletableFuture<Void> delete(OperationContext context) {
return CompletableFuture.completedFuture(null);
}
@Override
public void refresh() {
}
@Override
CompletableFuture<CreateKVTableResponse> checkKeyValueTableExists(KeyValueTableConfiguration configuration,
long timestamp, final int startingSegmentNumber, OperationContext context) {
CompletableFuture<CreateKVTableResponse> result = new CompletableFuture<>();
final long time;
final KVTConfigurationRecord config;
final VersionedMetadata<KVTStateRecord> currentState;
synchronized (lock) {
time = creationTime.get();
config = this.configuration == null ? null : this.configuration.getObject();
currentState = this.state;
}
if (time != Long.MIN_VALUE) {
if (config != null) {
handleMetadataExists(timestamp, result, time, startingSegmentNumber, config.getKvtConfiguration(), currentState);
} else {
result.complete(new CreateKVTableResponse(CreateKVTableResponse.CreateStatus.NEW, configuration, time, startingSegmentNumber));
}
} else {
result.complete(new CreateKVTableResponse(CreateKVTableResponse.CreateStatus.NEW, configuration, timestamp, startingSegmentNumber));
}
return result;
}
@Override
CompletableFuture<Void> createKVTableMetadata(OperationContext context) {
return CompletableFuture.completedFuture(null);
}
private void handleMetadataExists(final long timestamp, CompletableFuture<CreateKVTableResponse> result, final long time,
final int startingSegmentNumber, final KeyValueTableConfiguration config, VersionedMetadata<KVTStateRecord> currentState) {
if (currentState != null) {
KVTableState stateVal = currentState.getObject().getState();
if (stateVal.equals(KVTableState.UNKNOWN) || stateVal.equals(KVTableState.CREATING)) {
CreateKVTableResponse.CreateStatus status;
status = (time == timestamp) ? CreateKVTableResponse.CreateStatus.NEW :
CreateKVTableResponse.CreateStatus.EXISTS_CREATING;
result.complete(new CreateKVTableResponse(status, config, time, startingSegmentNumber));
} else {
result.complete(new CreateKVTableResponse(CreateKVTableResponse.CreateStatus.EXISTS_ACTIVE, config, time, startingSegmentNumber));
}
} else {
CreateKVTableResponse.CreateStatus status = (time == timestamp) ? CreateKVTableResponse.CreateStatus.NEW :
CreateKVTableResponse.CreateStatus.EXISTS_CREATING;
result.complete(new CreateKVTableResponse(status, config, time, startingSegmentNumber));
}
}
@Override
CompletableFuture<Void> storeCreationTimeIfAbsent(long timestamp, OperationContext context) {
creationTime.compareAndSet(Long.MIN_VALUE, timestamp);
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<Long> getCreationTime(OperationContext context) {
return CompletableFuture.completedFuture(creationTime.get());
}
@Override
CompletableFuture<Void> createConfigurationIfAbsent(KVTConfigurationRecord config, OperationContext context) {
Preconditions.checkNotNull(config);
synchronized (lock) {
if (configuration == null) {
configuration = new VersionedMetadata<>(config, new Version.IntVersion(0));
}
}
return CompletableFuture.completedFuture(null);
}
@Override
CompletableFuture<VersionedMetadata<KVTConfigurationRecord>> getConfigurationData(boolean ignoreCached, OperationContext context) {
synchronized (lock) {
if (this.configuration == null) {
return Futures.failedFuture(StoreException.create(StoreException.Type.DATA_NOT_FOUND, getName()));
}
return CompletableFuture.completedFuture(this.configuration);
}
}
@Override
CompletableFuture<Void> createStateIfAbsent(KVTStateRecord state, OperationContext context) {
Preconditions.checkNotNull(state);
synchronized (lock) {
if (this.state == null) {
this.state = new VersionedMetadata<>(state, new Version.IntVersion(0));
}
}
return CompletableFuture.completedFuture(null);
}
@Override
CompletableFuture<Version> setStateData(VersionedMetadata<KVTStateRecord> newState, OperationContext context) {
Preconditions.checkNotNull(newState);
CompletableFuture<Version> result = new CompletableFuture<>();
synchronized (lock) {
if (Objects.equals(this.state.getVersion(), newState.getVersion())) {
this.state = updatedCopy(newState);
result.complete(this.state.getVersion());
} else {
result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT, getName()));
}
}
return result;
}
@Override
CompletableFuture<VersionedMetadata<KVTStateRecord>> getStateData(boolean ignoreCached, OperationContext context) {
synchronized (lock) {
if (this.state == null) {
return Futures.failedFuture(StoreException.create(StoreException.Type.DATA_NOT_FOUND, getName()));
}
return CompletableFuture.completedFuture(state);
}
}
@Override
CompletableFuture<Void> createCurrentEpochRecordDataIfAbsent(KVTEpochRecord data, OperationContext context) {
Preconditions.checkNotNull(data);
CompletableFuture<Void> result = new CompletableFuture<>();
synchronized (lock) {
if (this.currentEpochRecord == null) {
this.currentEpochRecord = new VersionedMetadata<>(data, new Version.IntVersion(0));
}
result.complete(null);
}
return result;
}
@Override
CompletableFuture<VersionedMetadata<KVTEpochRecord>> getCurrentEpochRecordData(boolean ignoreCached, OperationContext context) {
synchronized (lock) {
if (this.currentEpochRecord == null) {
return Futures.failedFuture(StoreException.create(StoreException.Type.DATA_NOT_FOUND, getName()));
}
return CompletableFuture.completedFuture(this.currentEpochRecord);
}
}
@Override
CompletableFuture<Void> createEpochRecordDataIfAbsent(int epoch, KVTEpochRecord data, OperationContext context) {
Preconditions.checkNotNull(data);
CompletableFuture<Void> result = new CompletableFuture<>();
synchronized (lock) {
this.epochRecords.putIfAbsent(epoch, new VersionedMetadata<>(data, new Version.IntVersion(0)));
result.complete(null);
}
return result;
}
@Override
CompletableFuture<VersionedMetadata<KVTEpochRecord>> getEpochRecordData(int epoch, OperationContext context) {
synchronized (lock) {
if (!this.epochRecords.containsKey(epoch)) {
return Futures.failedFuture(StoreException.create(StoreException.Type.DATA_NOT_FOUND, getName()));
}
return CompletableFuture.completedFuture(this.epochRecords.get(epoch));
}
}
private <T> VersionedMetadata<T> updatedCopy(VersionedMetadata<T> input) {
return new VersionedMetadata<>(input.getObject(), new Version.IntVersion(input.getVersion().asIntVersion().getIntValue() + 1));
}
}
| 3,895 |
547 |
<gh_stars>100-1000
// CoreBitcoin by <NAME> <<EMAIL>>, WTFPL.
#import <Foundation/Foundation.h>
#import <openssl/bn.h>
// Bitcoin-flavoured big number wrapping OpenSSL BIGNUM.
// It is doing byte ordering like bitcoind does to stay compatible.
// BTCBigNumber is immutable. BTCMutableBigNumber is its mutable counterpart.
// -copy always returns immutable instance, like in other Cocoa containers.
@class BTCBigNumber;
@class BTCMutableBigNumber;
@interface BTCBigNumber : NSObject <NSCopying, NSMutableCopying>
@property(nonatomic, readonly) uint32_t compact; // compact representation used for the difficulty target
@property(nonatomic, readonly) uint32_t uint32value;
@property(nonatomic, readonly) int32_t int32value;
@property(nonatomic, readonly) uint64_t uint64value;
@property(nonatomic, readonly) int64_t int64value;
@property(nonatomic, readonly) NSData* littleEndianData; // data is reversed before being interpreted as internal state.
@property(nonatomic, readonly) NSData* unsignedData;
@property(nonatomic, readonly) NSString* hexString;
@property(nonatomic, readonly) NSString* decimalString;
// Pointer to an internal BIGNUM value. You should not modify it.
// To modify, use [[bn mutableCopy] mutableBIGNUM] methods.
@property(nonatomic, readonly) const BIGNUM* BIGNUM;
// BTCBigNumber returns always the same object for these constants.
// BTCMutableBigNumber returns a new object every time.
+ (instancetype) zero; // 0
+ (instancetype) one; // 1
+ (instancetype) negativeOne; // -1
- (id) init;
- (id) initWithCompact:(uint32_t)compact;
- (id) initWithUInt32:(uint32_t)value;
- (id) initWithInt32:(int32_t)value;
- (id) initWithUInt64:(uint64_t)value;
- (id) initWithInt64:(int64_t)value;
- (id) initWithLittleEndianData:(NSData*)data; // data is reversed before being interpreted as internal state.
- (id) initWithUnsignedData:(NSData*)data;
// Initialized with OpenSSL representation of bignum.
- (id) initWithBIGNUM:(const BIGNUM*)bignum;
// Inits with setString:base:
- (id) initWithString:(NSString*)string base:(NSUInteger)base;
// Same as initWithString:base:16
- (id) initWithHexString:(NSString*)hexString;
// Same as initWithString:base:10
- (id) initWithDecimalString:(NSString*)decimalString;
- (NSString*) stringInBase:(NSUInteger)base;
// Re-declared copy and mutableCopy to provide exact return type.
- (BTCBigNumber*) copy;
- (BTCMutableBigNumber*) mutableCopy;
// TODO: maybe add support for hash, figure out what the heck is that.
//void set_hash(hash_digest load_hash);
//hash_digest hash() const;
// Returns MIN(self, other)
- (BTCBigNumber*) min:(BTCBigNumber*)other;
// Returns MAX(self, other)
- (BTCBigNumber*) max:(BTCBigNumber*)other;
- (BOOL) less:(BTCBigNumber*)other;
- (BOOL) lessOrEqual:(BTCBigNumber*)other;
- (BOOL) greater:(BTCBigNumber*)other;
- (BOOL) greaterOrEqual:(BTCBigNumber*)other;
// Divides receiver by another bignum.
// Returns an array of two new BTCBigNumber instances: @[ quotient, remainder ]
- (NSArray*) divmod:(BTCBigNumber*)other;
// Destroys sensitive data and sets the value to 0.
// It is also called on dealloc.
// This method is available for both mutable and immutable numbers by design.
- (void) clear;
@end
@interface BTCMutableBigNumber : BTCBigNumber
@property(nonatomic, readwrite) uint32_t compact; // compact representation used for the difficulty target
@property(nonatomic, readwrite) uint32_t uint32value;
@property(nonatomic, readwrite) int32_t int32value;
@property(nonatomic, readwrite) uint64_t uint64value;
@property(nonatomic, readwrite) int64_t int64value;
@property(nonatomic, readwrite) NSData* littleEndianData;
@property(nonatomic, readwrite) NSData* unsignedData;
@property(nonatomic, readwrite) NSString* hexString;
@property(nonatomic, readwrite) NSString* decimalString;
@property(nonatomic, readonly) BIGNUM* mutableBIGNUM;
// BTCBigNumber returns always the same object for these constants.
// BTCMutableBigNumber returns a new object every time.
+ (instancetype) zero; // 0
+ (instancetype) one; // 1
+ (instancetype) negativeOne; // -1
// Supports bases from 2 to 36. For base 2 allows optional 0b prefix, base 16 allows optional 0x prefix. Spaces are ignored.
- (void) setString:(NSString*)string base:(NSUInteger)base;
// Operators modify the receiver and return self.
// To create a new instance z = x + y use copy method: z = [[x copy] add:y]
- (instancetype) add:(BTCBigNumber*)other; // +=
- (instancetype) add:(BTCBigNumber*)other mod:(BTCBigNumber*)mod;
- (instancetype) subtract:(BTCBigNumber*)other; // -=
- (instancetype) subtract:(BTCBigNumber*)other mod:(BTCBigNumber*)mod;
- (instancetype) multiply:(BTCBigNumber*)other; // *=
- (instancetype) multiply:(BTCBigNumber*)other mod:(BTCBigNumber*)mod;
- (instancetype) divide:(BTCBigNumber*)other; // /=
- (instancetype) mod:(BTCBigNumber*)other; // %=
- (instancetype) lshift:(unsigned int)shift; // <<=
- (instancetype) rshift:(unsigned int)shift; // >>=
@end
| 1,626 |
4,538 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __INTERSYSHCI_H__
#define __INTERSYSHCI_H__
#include "trans_adapt.h"
#if defined(__cplusplus)
extern "C" {
#endif
void BESHCI_BufferAvai(void *packet);
void BESHCI_Open(void);
void BESHCI_Close(void);
void BESHCI_Poll(void);
void BESHCI_LockBuffer(void);
void BESHCI_UNLockBuffer(void);
void BESHCI_SCO_Data_Start(void);
void BESHCI_SCO_Data_Stop(void);
void uartrxtx(void const *argument);
bool BESHCI_Controller_Log_Handler(const unsigned char *p_buff, uint32_t length);
void BESHCI_Dump_A2DP_Seq(const unsigned char *p_buff, uint32_t length);
typedef bool (*intersys_hci_cmd_filter_handler_func)(uint8_t* pbuf, uint32_t length);
void intersys_register_hci_cmd_filter_handler_callback(intersys_hci_cmd_filter_handler_func func);
#if defined(__cplusplus)
}
#endif
#endif /* __INTERSYSHCI_H__ */
| 353 |
809 |
<reponame>mfkiwl/embox
/**
* @file qspi.c
* @brief QSPI flash driver (currently just for STM32F7Discovery)
* @author <NAME> <<EMAIL>>
* @version
* @date 07.06.2019
*/
#include <embox/unit.h>
#include "stm32h745i_discovery.h"
#include "stm32h745i_discovery_qspi.h"
EMBOX_UNIT_INIT(stm32h7_qspi_init);
static int stm32h7_qspi_init(void) {
BSP_QSPI_Init_t qspi_init;
qspi_init.InterfaceMode = MT25TL01G_QPI_MODE;
qspi_init.TransferRate = MT25TL01G_DTR_TRANSFER;
qspi_init.DualFlashMode = MT25TL01G_DUALFLASH_ENABLE;
//BSP_QSPI_DisableMemoryMappedMode(0);
//BSP_QSPI_DeInit(0);
BSP_QSPI_Init(0, &qspi_init);
BSP_QSPI_EnableMemoryMappedMode(0);
return 0;
}
| 330 |
2,151 |
// 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.
#ifndef COMPONENTS_VIZ_SERVICE_FRAME_SINKS_VIDEO_CAPTURE_CAPTURABLE_FRAME_SINK_H_
#define COMPONENTS_VIZ_SERVICE_FRAME_SINKS_VIDEO_CAPTURE_CAPTURABLE_FRAME_SINK_H_
#include <memory>
#include "base/time/time.h"
#include "ui/gfx/geometry/size.h"
namespace gfx {
class Rect;
} // namespace gfx
namespace viz {
class CompositorFrameMetadata;
class CopyOutputRequest;
class LocalSurfaceId;
// Interface for CompositorFrameSink implementations that support frame sink
// video capture.
class CapturableFrameSink {
public:
// Interface for a client that observes certain frame events and calls
// RequestCopyOfSurface() at the appropriate times.
class Client {
public:
virtual ~Client() = default;
// Called when a frame's content, or that of one or more of its child
// frames, has changed. |frame_size| is the output size of the currently-
// active compositor frame for the frame sink being monitored, with
// |damage_rect| being the region within that has changed (never empty).
// |expected_display_time| indicates when the content change was expected to
// appear on the Display.
virtual void OnFrameDamaged(
const gfx::Size& frame_size,
const gfx::Rect& damage_rect,
base::TimeTicks expected_display_time,
const CompositorFrameMetadata& frame_metadata) = 0;
};
virtual ~CapturableFrameSink() = default;
// Attach/Detach a video capture client to the frame sink. The client will
// receive frame begin and draw events, and issue copy requests, when
// appropriate.
virtual void AttachCaptureClient(Client* client) = 0;
virtual void DetachCaptureClient(Client* client) = 0;
// Returns the currently-active frame size, or an empty size if there is no
// active frame.
virtual gfx::Size GetActiveFrameSize() = 0;
// Issues a request for a copy of the next composited frame whose
// LocalSurfaceId is at least |local_surface_id|. Note that if this id is
// default constructed, then the next surface will provide the copy output
// regardless of its LocalSurfaceId.
virtual void RequestCopyOfOutput(
const LocalSurfaceId& local_surface_id,
std::unique_ptr<CopyOutputRequest> request) = 0;
// Returns the CompositorFrameMetadata of the last activated CompositorFrame.
// Return null if no CompositorFrame has activated yet.
virtual const CompositorFrameMetadata* GetLastActivatedFrameMetadata() = 0;
};
} // namespace viz
#endif // COMPONENTS_VIZ_SERVICE_FRAME_SINKS_VIDEO_CAPTURE_CAPTURABLE_FRAME_SINK_H_
| 831 |
3,976 |
from app import app
from flask import render_template
@app.route('/')
def index():
return render_template('index.html')
@app.route('/postmessage',methods=["POST",])
def postMessage():
return render_template('handlemessage.html')
| 75 |
1,168 |
<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zeroturnaround.zip.commons;
import java.io.File;
/**
* This is a class that has been made significantly smaller (deleted a bunch of methods) and originally
* is from the Apache Commons IO 2.2 package (the latest version that supports Java 1.5). All license and other documentation is intact.
*
* General filename and filepath manipulation utilities.
* <p>
* When dealing with filenames you can hit problems when moving from a Windows based development machine to a Unix based production machine. This class aims to help avoid those
* problems.
* <p>
* <b>NOTE</b>: You may be able to avoid using this class entirely simply by using JDK {@link java.io.File File} objects and the two argument constructor
* {@link java.io.File#File(java.io.File, java.lang.String) File(File,String)}.
* <p>
* Most methods on this class are designed to work the same on both Unix and Windows. Those that don't include 'System', 'Unix' or 'Windows' in their name.
* <p>
* Most methods recognise both separators (forward and back), and both sets of prefixes. See the javadoc of each method for details.
* <p>
* This class defines six components within a filename (example C:\dev\project\file.txt):
* <ul>
* <li>the prefix - C:\</li>
* <li>the path - dev\project\</li>
* <li>the full path - C:\dev\project\</li>
* <li>the name - file.txt</li>
* <li>the base name - file</li>
* <li>the extension - txt</li>
* </ul>
* Note that this class works best if directory filenames end with a separator. If you omit the last separator, it is impossible to determine if the filename corresponds to a file
* or a directory. As a result, we have chosen to say it corresponds to a file.
* <p>
* This class only supports Unix and Windows style names. Prefixes are matched as follows:
*
* <pre>
* Windows:
* a\b\c.txt --> "" --> relative
* \a\b\c.txt --> "\" --> current drive absolute
* C:a\b\c.txt --> "C:" --> drive relative
* C:\a\b\c.txt --> "C:\" --> absolute
* \\server\a\b\c.txt --> "\\server\" --> UNC
*
* Unix:
* a/b/c.txt --> "" --> relative
* /a/b/c.txt --> "/" --> absolute
* ~/a/b/c.txt --> "~/" --> current user
* ~ --> "~/" --> current user (slash added)
* ~user/a/b/c.txt --> "~user/" --> named user
* ~user --> "~user/" --> named user (slash added)
* </pre>
*
* Both prefix styles are matched always, irrespective of the machine that you are currently running on.
* <p>
* Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils.
*
* @author <a href="mailto:<EMAIL>"><NAME></A>
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author <a href="mailto:<EMAIL>">Christoph.Reck</a>
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author <NAME>
* @author <NAME>
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author <NAME>
* @version $Id: FilenameUtils.java 609870 2008-01-08 04:46:26Z niallp $
* @since Commons IO 1.1
*/
public class FilenameUtils {
/**
* The extension separator character.
*
* @since Commons IO 1.4
*/
public static final char EXTENSION_SEPARATOR = '.';
/**
* The extension separator String.
*
* @since Commons IO 1.4
*/
public static final String EXTENSION_SEPARATOR_STR = (Character.valueOf(EXTENSION_SEPARATOR)).toString();
/**
* The Unix separator character.
*/
private static final char UNIX_SEPARATOR = '/';
/**
* The Windows separator character.
*/
private static final char WINDOWS_SEPARATOR = '\\';
/**
* The system separator character.
*/
private static final char SYSTEM_SEPARATOR = File.separatorChar;
/**
* Instances should NOT be constructed in standard programming.
*/
public FilenameUtils() {
super();
}
// -----------------------------------------------------------------------
/**
* Determines if Windows file system is in use.
*
* @return true if the system is Windows
*/
static boolean isSystemWindows() {
return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR;
}
// -----------------------------------------------------------------------
/**
* Checks if the character is a separator.
*
* @param ch the character to check
* @return true if it is a separator character
*/
private static boolean isSeparator(char ch) {
return (ch == UNIX_SEPARATOR) || (ch == WINDOWS_SEPARATOR);
}
// -----------------------------------------------------------------------
/**
* Returns the length of the filename prefix, such as <code>C:/</code> or <code>~/</code>.
* <p>
* This method will handle a file in either Unix or Windows format.
* <p>
* The prefix length includes the first slash in the full filename if applicable. Thus, it is possible that the length returned is greater than the length of the input string.
*
* <pre>
* Windows:
* a\b\c.txt --> "" --> relative
* \a\b\c.txt --> "\" --> current drive absolute
* C:a\b\c.txt --> "C:" --> drive relative
* C:\a\b\c.txt --> "C:\" --> absolute
* \\server\a\b\c.txt --> "\\server\" --> UNC
*
* Unix:
* a/b/c.txt --> "" --> relative
* /a/b/c.txt --> "/" --> absolute
* ~/a/b/c.txt --> "~/" --> current user
* ~ --> "~/" --> current user (slash added)
* ~user/a/b/c.txt --> "~user/" --> named user
* ~user --> "~user/" --> named user (slash added)
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on. ie. both Unix and Windows prefixes are matched regardless.
*
* @param filename the filename to find the prefix in, null returns -1
* @return the length of the prefix, -1 if invalid or null
*/
public static int getPrefixLength(String filename) {
if (filename == null) {
return -1;
}
int len = filename.length();
if (len == 0) {
return 0;
}
char ch0 = filename.charAt(0);
if (ch0 == ':') {
return -1;
}
if (len == 1) {
if (ch0 == '~') {
return 2; // return a length greater than the input
}
return (isSeparator(ch0) ? 1 : 0);
}
else {
if (ch0 == '~') {
int posUnix = filename.indexOf(UNIX_SEPARATOR, 1);
int posWin = filename.indexOf(WINDOWS_SEPARATOR, 1);
if (posUnix == -1 && posWin == -1) {
return len + 1; // return a length greater than the input
}
posUnix = (posUnix == -1 ? posWin : posUnix);
posWin = (posWin == -1 ? posUnix : posWin);
return Math.min(posUnix, posWin) + 1;
}
char ch1 = filename.charAt(1);
if (ch1 == ':') {
ch0 = Character.toUpperCase(ch0);
if (ch0 >= 'A' && ch0 <= 'Z') {
if (len == 2 || isSeparator(filename.charAt(2)) == false) {
return 2;
}
return 3;
}
return -1;
}
else if (isSeparator(ch0) && isSeparator(ch1)) {
int posUnix = filename.indexOf(UNIX_SEPARATOR, 2);
int posWin = filename.indexOf(WINDOWS_SEPARATOR, 2);
if ((posUnix == -1 && posWin == -1) || posUnix == 2 || posWin == 2) {
return -1;
}
posUnix = (posUnix == -1 ? posWin : posUnix);
posWin = (posWin == -1 ? posUnix : posWin);
return Math.min(posUnix, posWin) + 1;
}
else {
return (isSeparator(ch0) ? 1 : 0);
}
}
}
}
| 3,335 |
10,504 |
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include <string>
#include "value/Value.h"
#include "value/ValueType.h"
namespace milvus {
struct ServerStatus {
using String = Value<std::string>;
using Bool = Value<bool>;
using Integer = Value<int64_t>;
using Floating = Value<double>;
Bool indexing;
};
extern ServerStatus server_status;
} // namespace milvus
| 282 |
643 |
// Generated automatically from okhttp3.internal.http2.ErrorCode for testing purposes
package okhttp3.internal.http2;
public enum ErrorCode
{
CANCEL, COMPRESSION_ERROR, CONNECT_ERROR, ENHANCE_YOUR_CALM, FLOW_CONTROL_ERROR, FRAME_SIZE_ERROR, HTTP_1_1_REQUIRED, INADEQUATE_SECURITY, INTERNAL_ERROR, NO_ERROR, PROTOCOL_ERROR, REFUSED_STREAM, SETTINGS_TIMEOUT, STREAM_CLOSED;
private ErrorCode() {}
public final int getHttpCode(){ return 0; }
public static ErrorCode.Companion Companion = null;
static public class Companion
{
protected Companion() {}
public final ErrorCode fromHttp2(int p0){ return null; }
}
}
| 237 |
852 |
<reponame>Purva-Chaudhari/cmssw<filename>DQM/Physics/src/TopDiLeptonDQM.cc
/*
* $Date: 2012/01/11 13:53:29 $
* $Revision: 1.14 $
* \author <NAME> - DESY Hamburg
*/
#include "TLorentzVector.h"
#include "DataFormats/Math/interface/deltaR.h"
#include "DataFormats/Provenance/interface/RunLumiEventNumber.h"
#include "DQM/Physics/src/TopDiLeptonDQM.h"
#include "FWCore/Common/interface/TriggerNames.h"
using namespace std;
using namespace edm;
TopDiLeptonDQM::TopDiLeptonDQM(const edm::ParameterSet& ps) {
moduleName_ = ps.getUntrackedParameter<string>("moduleName");
outputFile_ = ps.getUntrackedParameter<string>("outputFile");
triggerResults_ = consumes<TriggerResults>(ps.getParameter<edm::InputTag>("TriggerResults"));
hltPaths_ = ps.getParameter<vector<string> >("hltPaths");
hltPaths_sig_ = ps.getParameter<vector<string> >("hltPaths_sig");
hltPaths_trig_ = ps.getParameter<vector<string> >("hltPaths_trig");
vertex_ = consumes<reco::VertexCollection>(ps.getParameter<edm::InputTag>("vertexCollection"));
vertex_X_cut_ = ps.getParameter<double>("vertex_X_cut");
vertex_Y_cut_ = ps.getParameter<double>("vertex_Y_cut");
vertex_Z_cut_ = ps.getParameter<double>("vertex_Z_cut");
muons_ = consumes<reco::MuonCollection>(ps.getParameter<edm::InputTag>("muonCollection"));
muon_pT_cut_ = ps.getParameter<double>("muon_pT_cut");
muon_eta_cut_ = ps.getParameter<double>("muon_eta_cut");
muon_iso_cut_ = ps.getParameter<double>("muon_iso_cut");
elecs_ = consumes<reco::GsfElectronCollection>(ps.getParameter<edm::InputTag>("elecCollection"));
elec_pT_cut_ = ps.getParameter<double>("elec_pT_cut");
elec_eta_cut_ = ps.getParameter<double>("elec_eta_cut");
elec_iso_cut_ = ps.getParameter<double>("elec_iso_cut");
elec_emf_cut_ = ps.getParameter<double>("elec_emf_cut");
MassWindow_up_ = ps.getParameter<double>("MassWindow_up");
MassWindow_down_ = ps.getParameter<double>("MassWindow_down");
for (int i = 0; i < 100; ++i) {
N_sig[i] = 0;
N_trig[i] = 0;
Eff[i] = 0.;
}
N_mumu = 0;
N_muel = 0;
N_elel = 0;
Events_ = nullptr;
Trigs_ = nullptr;
TriggerEff_ = nullptr;
Ntracks_ = nullptr;
Nmuons_ = nullptr;
Nmuons_iso_ = nullptr;
Nmuons_charge_ = nullptr;
VxVy_muons_ = nullptr;
Vz_muons_ = nullptr;
pT_muons_ = nullptr;
eta_muons_ = nullptr;
phi_muons_ = nullptr;
Nelecs_ = nullptr;
Nelecs_iso_ = nullptr;
Nelecs_charge_ = nullptr;
HoverE_elecs_ = nullptr;
pT_elecs_ = nullptr;
eta_elecs_ = nullptr;
phi_elecs_ = nullptr;
MuIso_emEt03_ = nullptr;
MuIso_hadEt03_ = nullptr;
MuIso_hoEt03_ = nullptr;
MuIso_nJets03_ = nullptr;
MuIso_nTracks03_ = nullptr;
MuIso_sumPt03_ = nullptr;
MuIso_CombRelIso03_ = nullptr;
ElecIso_cal_ = nullptr;
ElecIso_trk_ = nullptr;
ElecIso_CombRelIso_ = nullptr;
dimassRC_ = nullptr;
dimassWC_ = nullptr;
dimassRC_LOGX_ = nullptr;
dimassWC_LOGX_ = nullptr;
dimassRC_LOG10_ = nullptr;
dimassWC_LOG10_ = nullptr;
D_eta_muons_ = nullptr;
D_phi_muons_ = nullptr;
D_eta_elecs_ = nullptr;
D_phi_elecs_ = nullptr;
D_eta_lepts_ = nullptr;
D_phi_lepts_ = nullptr;
}
TopDiLeptonDQM::~TopDiLeptonDQM() {}
void TopDiLeptonDQM::bookHistograms(DQMStore::IBooker& iBooker, edm::Run const&, edm::EventSetup const&) {
iBooker.setCurrentFolder(moduleName_);
Events_ = iBooker.book1D("00_Events", "Isolated dilepton events", 5, 0., 5.);
Events_->setBinLabel(2, "#mu #mu", 1);
Events_->setBinLabel(3, "#mu e", 1);
Events_->setBinLabel(4, "e e", 1);
Trigs_ = iBooker.book1D("01_Trigs", "Fired muon/electron triggers", 15, 0., 15.);
TriggerEff_ = iBooker.book1D("02_TriggerEff", "HL Trigger Efficiencies", 10, 0., 10.);
TriggerEff_->setTitle(
"HL Trigger Efficiencies #epsilon_{signal} = #frac{[signal] && "
"[control]}{[control]}");
Ntracks_ = iBooker.book1D("Ntracks", "Number of tracks", 50, 0., 50.);
Nmuons_ = iBooker.book1D("03_Nmuons", "Number of muons", 20, 0., 10.);
Nmuons_iso_ = iBooker.book1D("04_Nmuons_iso", "Number of isolated muons", 20, 0., 10.);
Nmuons_charge_ = iBooker.book1D("Nmuons_charge", "Number of muons * moun charge", 19, -10., 10.);
VxVy_muons_ = iBooker.book2D("VxVy_muons", "Vertex x-y-positon (global)", 40, -1., 1., 40, -1., 1.);
Vz_muons_ = iBooker.book1D("Vz_muons", "Vertex z-positon (global)", 40, -20., 20.);
pT_muons_ = iBooker.book1D("pT_muons", "P_T of muons", 40, 0., 200.);
eta_muons_ = iBooker.book1D("eta_muons", "Eta of muons", 50, -5., 5.);
phi_muons_ = iBooker.book1D("phi_muons", "Phi of muons", 40, -4., 4.);
Nelecs_ = iBooker.book1D("05_Nelecs", "Number of electrons", 20, 0., 10.);
Nelecs_iso_ = iBooker.book1D("06_Nelecs_iso", "Number of isolated electrons", 20, 0., 10.);
Nelecs_charge_ = iBooker.book1D("Nelecs_charge", "Number of elecs * elec charge", 19, -10., 10.);
HoverE_elecs_ = iBooker.book1D("HoverE_elecs", "Hadronic over Ecal energy", 50, 0., 1.);
pT_elecs_ = iBooker.book1D("pT_elecs", "P_T of electrons", 40, 0., 200.);
eta_elecs_ = iBooker.book1D("eta_elecs", "Eta of electrons", 50, -5., 5.);
phi_elecs_ = iBooker.book1D("phi_elecs", "Phi of electrons", 40, -4., 4.);
MuIso_emEt03_ = iBooker.book1D("MuIso_emEt03", "Muon emEt03", 20, 0., 20.);
MuIso_hadEt03_ = iBooker.book1D("MuIso_hadEt03", "Muon hadEt03", 20, 0., 20.);
MuIso_hoEt03_ = iBooker.book1D("MuIso_hoEt03", "Muon hoEt03", 20, 0., 20.);
MuIso_nJets03_ = iBooker.book1D("MuIso_nJets03", "Muon nJets03", 10, 0., 10.);
MuIso_nTracks03_ = iBooker.book1D("MuIso_nTracks03", "Muon nTracks03", 20, 0., 20.);
MuIso_sumPt03_ = iBooker.book1D("MuIso_sumPt03", "Muon sumPt03", 20, 0., 40.);
MuIso_CombRelIso03_ = iBooker.book1D("07_MuIso_CombRelIso03", "Muon CombRelIso03", 20, 0., 1.);
ElecIso_cal_ = iBooker.book1D("ElecIso_cal", "Electron Iso_cal", 21, -1., 20.);
ElecIso_trk_ = iBooker.book1D("ElecIso_trk", "Electron Iso_trk", 21, -2., 40.);
ElecIso_CombRelIso_ = iBooker.book1D("08_ElecIso_CombRelIso", "Electron CombRelIso", 20, 0., 1.);
const int nbins = 200;
double logmin = 0.;
double logmax = 3.; // 10^(3.)=1000
float bins[nbins + 1];
for (int i = 0; i <= nbins; i++) {
double log = logmin + (logmax - logmin) * i / nbins;
bins[i] = std::pow(10.0, log);
}
dimassRC_ = iBooker.book1D("09_dimassRC", "Dilepton mass RC", 50, 0., 200.);
dimassWC_ = iBooker.book1D("11_dimassWC", "Dilepton mass WC", 50, 0., 200.);
dimassRC_LOGX_ = iBooker.book1D("10_dimassRC_LOGX", "Dilepton mass RC LOG", nbins, &bins[0]);
dimassWC_LOGX_ = iBooker.book1D("12_dimassWC_LOGX", "Dilepton mass WC LOG", nbins, &bins[0]);
dimassRC_LOG10_ = iBooker.book1D("dimassRC_LOG10", "Dilepton mass RC LOG", 50, 0., 2.5);
dimassWC_LOG10_ = iBooker.book1D("dimassWC_LOG10", "Dilepton mass WC LOG", 50, 0., 2.5);
D_eta_muons_ = iBooker.book1D("13_D_eta_muons", "#Delta eta_muons", 20, -5., 5.);
D_phi_muons_ = iBooker.book1D("14_D_phi_muons", "#Delta phi_muons", 20, -5., 5.);
D_eta_elecs_ = iBooker.book1D("D_eta_elecs", "#Delta eta_elecs", 20, -5., 5.);
D_phi_elecs_ = iBooker.book1D("D_phi_elecs", "#Delta phi_elecs", 20, -5., 5.);
D_eta_lepts_ = iBooker.book1D("D_eta_lepts", "#Delta eta_lepts", 20, -5., 5.);
D_phi_lepts_ = iBooker.book1D("D_phi_lepts", "#Delta phi_lepts", 20, -5., 5.);
}
void TopDiLeptonDQM::analyze(const edm::Event& evt, const edm::EventSetup& context) {
// ------------------------
// Global Event Variables
// ------------------------
const int N_TriggerPaths = hltPaths_.size();
const int N_SignalPaths = hltPaths_sig_.size();
const int N_ControlPaths = hltPaths_trig_.size();
bool Fired_Signal_Trigger[100] = {false};
bool Fired_Control_Trigger[100] = {false};
int N_leptons = 0;
int N_iso_mu = 0;
int N_iso_el = 0;
double DilepMass = 0.;
double vertex_X = 100.;
double vertex_Y = 100.;
double vertex_Z = 100.;
// ------------------------
// Analyze Primary Vertex
// ------------------------
edm::Handle<reco::VertexCollection> vertexs;
evt.getByToken(vertex_, vertexs);
if (!vertexs.failedToGet()) {
reco::Vertex primaryVertex = vertexs->front();
int numberTracks = primaryVertex.tracksSize();
// double ndof = primaryVertex.ndof();
bool fake = primaryVertex.isFake();
Ntracks_->Fill(numberTracks);
if (!fake && numberTracks > 3) {
vertex_X = primaryVertex.x();
vertex_Y = primaryVertex.y();
vertex_Z = primaryVertex.z();
}
}
// -------------------------
// Analyze Trigger Results
// -------------------------
edm::Handle<TriggerResults> trigResults;
evt.getByToken(triggerResults_, trigResults);
if (!trigResults.failedToGet()) {
int N_Triggers = trigResults->size();
const edm::TriggerNames& trigName = evt.triggerNames(*trigResults);
for (int i_Trig = 0; i_Trig < N_Triggers; ++i_Trig) {
if (trigResults.product()->accept(i_Trig)) {
// Check for all trigger paths
for (int i = 0; i < N_TriggerPaths; i++) {
if (trigName.triggerName(i_Trig) == hltPaths_[i]) {
Trigs_->Fill(i);
Trigs_->setBinLabel(i + 1, hltPaths_[i], 1);
}
}
// Check for signal & control trigger paths
for (int j = 0; j < N_SignalPaths; ++j) {
if (trigName.triggerName(i_Trig) == hltPaths_sig_[j])
Fired_Signal_Trigger[j] = true;
}
for (int k = 0; k < N_ControlPaths; ++k) {
if (trigName.triggerName(i_Trig) == hltPaths_trig_[k])
Fired_Control_Trigger[k] = true;
}
}
}
}
// ------------------------
// Analyze Muon Isolation
// ------------------------
edm::Handle<reco::MuonCollection> muons;
evt.getByToken(muons_, muons);
reco::MuonCollection::const_iterator muon;
if (!muons.failedToGet()) {
Nmuons_->Fill(muons->size());
N_leptons = N_leptons + muons->size();
for (muon = muons->begin(); muon != muons->end(); ++muon) {
float N_muons = muons->size();
float Q_muon = muon->charge();
Nmuons_charge_->Fill(N_muons * Q_muon);
double track_X = 100.;
double track_Y = 100.;
double track_Z = 100.;
if (muon->isGlobalMuon()) {
reco::TrackRef track = muon->globalTrack();
track_X = track->vx();
track_Y = track->vy();
track_Z = track->vz();
VxVy_muons_->Fill(track_X, track_Y);
Vz_muons_->Fill(track_Z);
}
// Vertex and kinematic cuts
if (track_X > vertex_X_cut_)
continue;
if (track_Y > vertex_Y_cut_)
continue;
if (track_Z > vertex_Z_cut_)
continue;
if (muon->pt() < muon_pT_cut_)
continue;
if (abs(muon->eta()) > muon_eta_cut_)
continue;
reco::MuonIsolation muIso03 = muon->isolationR03();
double muonCombRelIso = 1.;
if (muon->pt() != 0.)
muonCombRelIso = (muIso03.emEt + muIso03.hadEt + muIso03.hoEt + muIso03.sumPt) / muon->pt();
MuIso_CombRelIso03_->Fill(muonCombRelIso);
MuIso_emEt03_->Fill(muIso03.emEt);
MuIso_hadEt03_->Fill(muIso03.hadEt);
MuIso_hoEt03_->Fill(muIso03.hoEt);
MuIso_nJets03_->Fill(muIso03.nJets);
MuIso_nTracks03_->Fill(muIso03.nTracks);
MuIso_sumPt03_->Fill(muIso03.sumPt);
if (muonCombRelIso < muon_iso_cut_)
++N_iso_mu;
}
Nmuons_iso_->Fill(N_iso_mu);
}
// ----------------------------
// Analyze Electron Isolation
// ----------------------------
edm::Handle<reco::GsfElectronCollection> elecs;
evt.getByToken(elecs_, elecs);
reco::GsfElectronCollection::const_iterator elec;
if (!elecs.failedToGet()) {
Nelecs_->Fill(elecs->size());
N_leptons = N_leptons + elecs->size();
for (elec = elecs->begin(); elec != elecs->end(); ++elec) {
float N_elecs = elecs->size();
float Q_elec = elec->charge();
float HoverE = elec->hcalOverEcal();
HoverE_elecs_->Fill(HoverE);
Nelecs_charge_->Fill(N_elecs * Q_elec);
double track_X = 100.;
double track_Y = 100.;
double track_Z = 100.;
reco::GsfTrackRef track = elec->gsfTrack();
track_X = track->vx();
track_Y = track->vy();
track_Z = track->vz();
// Vertex and kinematic cuts
if (track_X > vertex_X_cut_)
continue;
if (track_Y > vertex_Y_cut_)
continue;
if (track_Z > vertex_Z_cut_)
continue;
if (elec->pt() < elec_pT_cut_)
continue;
if (abs(elec->eta()) > elec_eta_cut_)
continue;
if (HoverE > elec_emf_cut_)
continue;
reco::GsfElectron::IsolationVariables elecIso = elec->dr03IsolationVariables();
double elecCombRelIso = 1.;
if (elec->et() != 0.)
elecCombRelIso = (elecIso.ecalRecHitSumEt + elecIso.hcalRecHitSumEt[0] + elecIso.tkSumPt) / elec->et();
ElecIso_CombRelIso_->Fill(elecCombRelIso);
ElecIso_cal_->Fill(elecIso.ecalRecHitSumEt);
ElecIso_trk_->Fill(elecIso.tkSumPt);
if (elecCombRelIso < elec_iso_cut_)
++N_iso_el;
}
Nelecs_iso_->Fill(N_iso_el);
}
// --------------------
// TWO Isolated MUONS
// --------------------
if (N_iso_mu > 1) {
// Vertex cut
if (vertex_X < vertex_X_cut_ && vertex_Y < vertex_Y_cut_ && vertex_Z < vertex_Z_cut_) {
++N_mumu;
Events_->Fill(1.);
reco::MuonCollection::const_reference mu1 = muons->at(0);
reco::MuonCollection::const_reference mu2 = muons->at(1);
DilepMass = sqrt((mu1.energy() + mu2.energy()) * (mu1.energy() + mu2.energy()) -
(mu1.px() + mu2.px()) * (mu1.px() + mu2.px()) - (mu1.py() + mu2.py()) * (mu1.py() + mu2.py()) -
(mu1.pz() + mu2.pz()) * (mu1.pz() + mu2.pz()));
// Opposite muon charges -> Right Charge (RC)
if (mu1.charge() * mu2.charge() < 0.) {
dimassRC_LOG10_->Fill(log10(DilepMass));
dimassRC_->Fill(DilepMass);
dimassRC_LOGX_->Fill(DilepMass);
if (DilepMass > MassWindow_down_ && DilepMass < MassWindow_up_) {
for (muon = muons->begin(); muon != muons->end(); ++muon) {
pT_muons_->Fill(muon->pt());
eta_muons_->Fill(muon->eta());
phi_muons_->Fill(muon->phi());
}
D_eta_muons_->Fill(mu1.eta() - mu2.eta());
D_phi_muons_->Fill(mu1.phi() - mu2.phi());
// Determinating trigger efficiencies
for (int k = 0; k < N_SignalPaths; ++k) {
if (Fired_Signal_Trigger[k] && Fired_Control_Trigger[k])
++N_sig[k];
if (Fired_Control_Trigger[k])
++N_trig[k];
if (N_trig[k] != 0)
Eff[k] = N_sig[k] / static_cast<float>(N_trig[k]);
TriggerEff_->setBinContent(k + 1, Eff[k]);
TriggerEff_->setBinLabel(k + 1, "#frac{[" + hltPaths_sig_[k] + "]}{vs. [" + hltPaths_trig_[k] + "]}", 1);
}
}
}
// Same muon charges -> Wrong Charge (WC)
if (mu1.charge() * mu2.charge() > 0.) {
dimassWC_LOG10_->Fill(log10(DilepMass));
dimassWC_->Fill(DilepMass);
dimassWC_LOGX_->Fill(DilepMass);
}
}
}
// -----------------------------
// TWO Isolated LEPTONS (mu/e)
// -----------------------------
if (N_iso_el > 0 && N_iso_mu > 0) {
// Vertex cut
if (vertex_X < vertex_X_cut_ && vertex_Y < vertex_Y_cut_ && vertex_Z < vertex_Z_cut_) {
++N_muel;
Events_->Fill(2.);
reco::MuonCollection::const_reference mu1 = muons->at(0);
reco::GsfElectronCollection::const_reference el1 = elecs->at(0);
DilepMass = sqrt((mu1.energy() + el1.energy()) * (mu1.energy() + el1.energy()) -
(mu1.px() + el1.px()) * (mu1.px() + el1.px()) - (mu1.py() + el1.py()) * (mu1.py() + el1.py()) -
(mu1.pz() + el1.pz()) * (mu1.pz() + el1.pz()));
// Opposite lepton charges -> Right Charge (RC)
if (mu1.charge() * el1.charge() < 0.) {
dimassRC_LOG10_->Fill(log10(DilepMass));
dimassRC_->Fill(DilepMass);
dimassRC_LOGX_->Fill(DilepMass);
if (DilepMass > MassWindow_down_ && DilepMass < MassWindow_up_) {
for (muon = muons->begin(); muon != muons->end(); ++muon) {
pT_muons_->Fill(muon->pt());
eta_muons_->Fill(muon->eta());
phi_muons_->Fill(muon->phi());
}
for (elec = elecs->begin(); elec != elecs->end(); ++elec) {
pT_elecs_->Fill(elec->pt());
eta_elecs_->Fill(elec->eta());
phi_elecs_->Fill(elec->phi());
}
D_eta_lepts_->Fill(mu1.eta() - el1.eta());
D_phi_lepts_->Fill(mu1.phi() - el1.phi());
// Determinating trigger efficiencies
for (int k = 0; k < N_SignalPaths; ++k) {
if (Fired_Signal_Trigger[k] && Fired_Control_Trigger[k])
++N_sig[k];
if (Fired_Control_Trigger[k])
++N_trig[k];
if (N_trig[k] != 0)
Eff[k] = N_sig[k] / static_cast<float>(N_trig[k]);
TriggerEff_->setBinContent(k + 1, Eff[k]);
TriggerEff_->setBinLabel(k + 1, "#frac{[" + hltPaths_sig_[k] + "]}{vs. [" + hltPaths_trig_[k] + "]}", 1);
}
}
}
// Same muon charges -> Wrong Charge (WC)
if (mu1.charge() * el1.charge() > 0.) {
dimassWC_LOG10_->Fill(log10(DilepMass));
dimassWC_->Fill(DilepMass);
dimassWC_LOGX_->Fill(DilepMass);
}
}
}
// ------------------------
// TWO Isolated ELECTRONS
// ------------------------
if (N_iso_el > 1) {
// Vertex cut
if (vertex_X < vertex_X_cut_ && vertex_Y < vertex_Y_cut_ && vertex_Z < vertex_Z_cut_) {
++N_elel;
Events_->Fill(3.);
reco::GsfElectronCollection::const_reference el1 = elecs->at(0);
reco::GsfElectronCollection::const_reference el2 = elecs->at(1);
DilepMass = sqrt((el1.energy() + el2.energy()) * (el1.energy() + el2.energy()) -
(el1.px() + el2.px()) * (el1.px() + el2.px()) - (el1.py() + el2.py()) * (el1.py() + el2.py()) -
(el1.pz() + el2.pz()) * (el1.pz() + el2.pz()));
// Opposite lepton charges -> Right Charge (RC)
if (el1.charge() * el2.charge() < 0.) {
dimassRC_LOG10_->Fill(log10(DilepMass));
dimassRC_->Fill(DilepMass);
dimassRC_LOGX_->Fill(DilepMass);
if (DilepMass > MassWindow_down_ && DilepMass < MassWindow_up_) {
for (elec = elecs->begin(); elec != elecs->end(); ++elec) {
pT_elecs_->Fill(elec->pt());
eta_elecs_->Fill(elec->eta());
phi_elecs_->Fill(elec->phi());
}
D_eta_elecs_->Fill(el1.eta() - el2.eta());
D_phi_elecs_->Fill(el1.phi() - el2.phi());
// Determinating trigger efficiencies
for (int k = 0; k < N_SignalPaths; ++k) {
if (Fired_Signal_Trigger[k] && Fired_Control_Trigger[k])
++N_sig[k];
if (Fired_Control_Trigger[k])
++N_trig[k];
if (N_trig[k] != 0)
Eff[k] = N_sig[k] / static_cast<float>(N_trig[k]);
TriggerEff_->setBinContent(k + 1, Eff[k]);
TriggerEff_->setBinLabel(k + 1, "#frac{[" + hltPaths_sig_[k] + "]}{vs. [" + hltPaths_trig_[k] + "]}", 1);
}
}
}
// Same muon charges -> Wrong Charge (WC)
if (el1.charge() * el2.charge() > 0.) {
dimassWC_LOG10_->Fill(log10(DilepMass));
dimassWC_->Fill(DilepMass);
dimassWC_LOGX_->Fill(DilepMass);
}
}
}
}
| 10,220 |
590 |
/*******************************************************************************
* Copyright 2017 Bstek
*
* 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.bstek.uflo.command.impl;
import java.util.List;
import org.hibernate.Session;
import com.bstek.uflo.command.Command;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.HistoryTask;
import com.bstek.uflo.model.task.Task;
import com.bstek.uflo.model.task.TaskParticipator;
import com.bstek.uflo.model.task.TaskType;
import com.bstek.uflo.service.SchedulerService;
/**
* @author Jacky.gao
* @since 2017年5月2日
*/
public class DeleteTaskByNodeCommand implements Command<Integer> {
private long processInstanceId;
private String nodeName;
public DeleteTaskByNodeCommand(long processInstanceId,String nodeName){
this.processInstanceId=processInstanceId;
this.nodeName=nodeName;
}
@SuppressWarnings("unchecked")
public Integer execute(Context context) {
Session session=context.getSession();
String hql="from "+Task.class.getName()+" where nodeName=:nodeName and (processInstanceId=:processInstanceId or rootProcessInstanceId=:rootProcessInstanceId)";
List<Task> list=session.createQuery(hql)
.setString("nodeName", nodeName)
.setLong("processInstanceId", processInstanceId)
.setLong("rootProcessInstanceId", processInstanceId)
.list();
SchedulerService schedulerService=(SchedulerService)context.getApplicationContext().getBean(SchedulerService.BEAN_ID);
for(Task task:list){
if(task.getType().equals(TaskType.Participative)){
session.createQuery("delete "+TaskParticipator.class.getName()+" where taskId=:taskId").setLong("taskId", task.getId()).executeUpdate();
}
hql="delete "+HistoryTask.class.getName()+" where taskId=:taskId";
session.createQuery(hql).setLong("taskId", task.getId()).executeUpdate();
session.delete(task);
schedulerService.removeReminderJob(task);
}
return list.size();
}
}
| 794 |
2,757 |
<reponame>BearerPipelineTest/google-ctf<gh_stars>1000+
#include <cerrno>
#include <iostream>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/times.h>
#include <unistd.h>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <filesystem>
#include <sstream>
#include <algorithm>
#include <random>
std::string recv_file() {
unsigned int size = 0;
std::cin.read((char*)&size, 4);
std::string ret;
ret.resize(size);
std::cin.read(&ret[0], size);
std::cerr << std::endl;
return ret;
}
std::string read_file(const char* path) {
std::ifstream t(path);
if (!t.is_open()) {
std::cerr << "Failed to open " << path << std::endl;
exit(1);
}
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
return str;
}
std::map<std::string, bool> load_results(const char* path) {
std::map<std::string, bool> ret;
std::ifstream infile(path);
std::string line;
while(std::getline(infile, line)) {
while(line.back() == '\n') line.pop_back();
if (line.empty()) continue;
int space = line.find(' ');
if (space == std::string::npos) {
std::cerr << "Failed to find space delimiter in results line " << line << std::endl;
exit(3);
}
std::string filename = line.substr(0, space);
std::string retcode = line.substr(space + 1, std::string::npos);
ret[filename] = (retcode != "0");
}
return ret;
}
void make_nsjail_cfg(std::istream& infile, std::ostream& outfile, const char* tmpdir) {
std::string line;
while(std::getline(infile, line)) {
if(line.back() == '\n') line.pop_back();
if(line.empty()) continue;
if(line == "# INSERT BIND HERE") {
std::stringstream buf;
buf
<< "{\n"
<< "src: \"" << tmpdir << "\"\n"
<< "dst: \"/home/user/\"\n"
<< "is_bind: true\n"
<< "},\n";
outfile << buf.str();
} else {
outfile << line << "\n";
}
}
}
long double clocks_per_sec = sysconf(_SC_CLK_TCK);
// Used to subtract out the time it takes to spawn a simple nsjail.
long double time_normalization_factor(const std::string& tmpdir) {
static long double ret = [&](){
struct tms old_times;
if (times(&old_times) == -1) {
std::cerr << "times(): " << strerror(errno) << std::endl;
}
for (int i = 0; i < 10; ++i) {
pid_t pid = fork();
if (pid == 0) {
std::string nsjail_cfg = tmpdir + "/nsjail.cfg";
std::vector<const char*> subprocess;
subprocess.push_back("/usr/bin/nsjail");
subprocess.push_back("-q");
subprocess.push_back("--config");
subprocess.push_back(nsjail_cfg.c_str());
subprocess.push_back("/bin/true");
subprocess.push_back(nullptr);
execv(subprocess[0], (char**)&subprocess[0]);
std::cerr << "Failed to execv: " << subprocess[0] << "\n" << strerror(errno) << std::endl;
exit(1);
} else if (pid < 0) {
std::cerr << "Failed to fork: " << strerror(errno) << std::endl;
exit(2);
}
int status;
waitpid(pid, &status, 0);
}
struct tms new_times;
if (times(&new_times) == -1) {
std::cerr << "times(): " << strerror(errno) << std::endl;
}
return (new_times.tms_cutime - old_times.tms_cutime + new_times.tms_cstime - old_times.tms_cstime) / clocks_per_sec / 10;
}();
return ret;
}
bool run_test_case(const std::string& tmpdir, const std::string& testcase, bool silence, long double* time) {
std::string tmp_testcase = tmpdir + "/test_case";
int removeret = remove(tmp_testcase.c_str());
if (removeret) {
int x = errno;
if (x != ENOENT) {
std::cerr << "remove(" << tmp_testcase.c_str() << "): " << strerror(x) << std::endl;
exit(1);
}
}
std::filesystem::copy(testcase, tmp_testcase, std::filesystem::copy_options::overwrite_existing);
chmod(tmp_testcase.c_str(), 0777);
struct tms old_times;
if (times(&old_times) == -1) {
std::cerr << "times(): " << strerror(errno) << std::endl;
}
pid_t pid = ::fork();
if (pid == 0) {
dup2(STDERR_FILENO, STDOUT_FILENO);
if (silence) {
int devnull = open("/dev/null", O_RDONLY);
if (devnull < 0) {
std::cerr << "Failed to open /dev/null: " << strerror(errno) << std::endl;
exit(1);
}
dup2(devnull, STDOUT_FILENO);
dup2(devnull, STDERR_FILENO);
close(devnull);
}
std::string nsjail_cfg = tmpdir + "/nsjail.cfg";
std::vector<const char*> subprocess;
subprocess.push_back("/usr/bin/nsjail");
subprocess.push_back("-q");
subprocess.push_back("--config");
subprocess.push_back(nsjail_cfg.c_str());
subprocess.push_back("/home/user/antivirus");
subprocess.push_back("/home/user/test_case");
subprocess.push_back(nullptr);
execv(subprocess[0], (char**)&subprocess[0]);
std::cerr << "Failed to execv: " << subprocess[0] << "\n" << strerror(errno) << std::endl;
exit(1);
} else if (pid < 0) {
std::cerr << "Failed to fork: " << strerror(errno) << std::endl;
exit(2);
}
int status;
waitpid(pid, &status, 0);
struct tms new_times;
if (times(&new_times) == -1) {
std::cerr << "times(): " << strerror(errno) << std::endl;
}
// This time-measuring mechanism is probably bypassable - nsjail needs to be a
// subreaper, or a subreaper needs to be run inside nsjail, to fix that.
*time += (new_times.tms_cutime - old_times.tms_cutime + new_times.tms_cstime - old_times.tms_cstime) / clocks_per_sec - time_normalization_factor(tmpdir);
return status;
}
void run_test_cases(int* passed, int* failed, const std::string& tmpdir, const std::string& mapping_file, bool silence, bool super_silence=false) {
std::map<std::string, bool> ordered_mapping = load_results(mapping_file.c_str());
std::vector<std::pair<std::string, bool>> mapping(ordered_mapping.begin(), ordered_mapping.end());
if (silence) {
std::random_device rd;
std::mt19937 mt(rd());
std::shuffle(mapping.begin(), mapping.end(), mt);
}
long double time = 0;
for (const auto& [s, b] : mapping) {
if (!super_silence) std::cout << " Running test " << s << "... " << std::endl;
bool result = run_test_case(tmpdir, s, silence, &time);
bool matches = (result == b);
if (!super_silence) std::cout <<" " << s << ": " << (matches? "✅ " : "❌ ");
if (!matches) {
(*failed)++;
if (!super_silence) std::cout << "Expected " << b << ", got " << result;
} else {
(*passed)++;
}
if (!super_silence) std::cout << std::endl;
if (time > mapping.size() * 4.04) {
if (!super_silence) std::cerr << "❌❌ Exceeded maximum time! Your program has consumed " << time << " seconds, but must take (on average) no more than 4 cpu-seconds per test case. " << std::endl;
*failed += mapping.size() - (*passed + *failed);
break;
}
}
if (!super_silence) std::cerr << "Total time: " << time << std::endl;
}
char tmpdirname_for_cleanup[256] = "\0";
void cleanup() {
system((std::string("rm -rf ") + tmpdirname_for_cleanup + std::string(" > /dev/null 2>&1")).c_str());
}
int main(int argc, char** argv) {
dup2(STDOUT_FILENO, STDERR_FILENO);
std::cout <<
R"(Malware Autograder
==================
Please upload a 4-byte little-endian integer specifying the size of your binary,
followed by your binary.
)" << std::flush;
// Load antivirus
std::string antivirus = recv_file();
close(STDIN_FILENO);
std::string tmpdirname("/tmp/autograder.XXXXXX");
char* tmperror = mkdtemp(&tmpdirname[0]);
if (!tmperror) {
std::cerr << "Failed to create tmpdir: " << strerror(errno) << std::endl;
exit(1);
}
strcpy(tmpdirname_for_cleanup, tmpdirname.c_str());
atexit(cleanup);
std::string filename = tmpdirname + "/antivirus";
{
std::ofstream av_outfile(filename.c_str());
av_outfile << antivirus;
}
chmod(tmpdirname.c_str(), 0777);
chmod(filename.c_str(), 0777);
std::string built_nsjail_cfg = tmpdirname + "/nsjail.cfg";
{
std::ifstream nsjail_cfg_in("/home/user/nsjail.cfg");
std::ofstream nsjail_cfg_out(built_nsjail_cfg.c_str());
make_nsjail_cfg(nsjail_cfg_in, nsjail_cfg_out, tmpdirname.c_str());
}
int passed = 0;
int failed = 0;
std::cout <<
R"(
Running public test cases
-------------------------
)";
run_test_cases(&passed, &failed, tmpdirname, "/home/user/expected_public_map", false);
std::cout << "-------------------------" << std::endl;
std::cout << "Score: " << passed << "/" << (passed + failed) << std::endl;
if (failed > 0) {
std::cout << "You must pass all public test cases to continue. These test cases are available in your downloaded package." << std::endl;
return 1;
}
passed = 0;
failed = 0;
std::cout <<
R"(
Running private test cases
--------------------------
)";
run_test_cases(&passed, &failed, tmpdirname, "/home/user/expected_map", true);
std::cout << "-------------------------" << std::endl;
std::cout << "Score: " << passed << "/" << (passed + failed) << std::endl;
if (failed >= 3) {
std::cout << "You are permitted to fail up to 3 private test cases. You failed too many." << std::endl;
return 1;
}
std::string flag = read_file("/home/user/flag");
std::cout << "Your flag is:\x1b[38;5;198m\n" << flag << "\n\x1b[39;49m" << std::flush;
passed = 0;
failed = 0;
run_test_cases(&passed, &failed, tmpdirname, "/home/user/expected_super_secret_map", true, true);
if (passed <= 10) {
std::cout << "\x1b[38;5;198m\n\nCongrats on finding the 'unintended' solution ;)\n\x1b[39;49m" << std::endl;
}
}
| 4,035 |
1,056 |
<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.core.windows.view.ui.slides;
import java.awt.Component;
import java.awt.Rectangle;
import javax.swing.JLayeredPane;
import org.netbeans.core.windows.Constants;
import org.openide.windows.TopComponent;
import org.netbeans.swing.tabcontrol.SlideBarDataModel;
/*
* Interface for slide in and slide out operations. Acts as command interface
* for desktop part of winsys to be able to request slide operation.
*
* @author <NAME>
*/
public interface SlideOperation {
public static final int SLIDE_IN = 0;
public static final int SLIDE_OUT = 1;
public static final int SLIDE_INTO_EDGE = 2;
public static final int SLIDE_INTO_DESKTOP = 3;
public static final int SLIDE_RESIZE = 4;
public Component getComponent ();
public Rectangle getStartBounds ();
public Rectangle getFinishBounds ();
public String getSide ();
public boolean requestsActivation ();
public void run (JLayeredPane pane, Integer layer);
public void setStartBounds (Rectangle bounds);
public void setFinishBounds (Rectangle bounds);
public int getType();
public void prepareEffect();
}
| 597 |
401 |
package com.almasb.civ6menu;
import javafx.animation.*;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.util.Pair;
import java.util.Arrays;
import java.util.List;
public class Civ6MenuApp extends Application {
private static final int WIDTH = 1280;
private static final int HEIGHT = 720;
private List<Pair<String, Runnable>> menuData = Arrays.asList(
new Pair<String, Runnable>("Single Player", () -> {}),
new Pair<String, Runnable>("Multiplayer", () -> {}),
new Pair<String, Runnable>("Game Options", () -> {}),
new Pair<String, Runnable>("Additional Content", () -> {}),
new Pair<String, Runnable>("Tutorial", () -> {}),
new Pair<String, Runnable>("Benchmark", () -> {}),
new Pair<String, Runnable>("Credits", () -> {}),
new Pair<String, Runnable>("Exit to Desktop", Platform::exit)
);
private Pane root = new Pane();
private VBox menuBox = new VBox(-5);
private Line line;
private Parent createContent() {
addBackground();
addTitle();
double lineX = WIDTH / 2 - 100;
double lineY = HEIGHT / 3 + 50;
addLine(lineX, lineY);
addMenu(lineX + 5, lineY + 5);
startAnimation();
return root;
}
private void addBackground() {
ImageView imageView = new ImageView(new Image(getClass().getResource("res/Civ6_bg.png").toExternalForm()));
imageView.setFitWidth(WIDTH);
imageView.setFitHeight(HEIGHT);
root.getChildren().add(imageView);
}
private void addTitle() {
Civ6Title title = new Civ6Title("CIVILIZATION VI");
title.setTranslateX(WIDTH / 2 - title.getTitleWidth() / 2);
title.setTranslateY(HEIGHT / 3);
root.getChildren().add(title);
}
private void addLine(double x, double y) {
line = new Line(x, y, x, y + 300);
line.setStrokeWidth(3);
line.setStroke(Color.color(1, 1, 1, 0.75));
line.setEffect(new DropShadow(5, Color.BLACK));
line.setScaleY(0);
root.getChildren().add(line);
}
private void startAnimation() {
ScaleTransition st = new ScaleTransition(Duration.seconds(1), line);
st.setToY(1);
st.setOnFinished(e -> {
for (int i = 0; i < menuBox.getChildren().size(); i++) {
Node n = menuBox.getChildren().get(i);
TranslateTransition tt = new TranslateTransition(Duration.seconds(1 + i * 0.15), n);
tt.setToX(0);
tt.setOnFinished(e2 -> n.setClip(null));
tt.play();
}
});
st.play();
}
private void addMenu(double x, double y) {
menuBox.setTranslateX(x);
menuBox.setTranslateY(y);
menuData.forEach(data -> {
Civ6MenuItem item = new Civ6MenuItem(data.getKey());
item.setOnAction(data.getValue());
item.setTranslateX(-300);
Rectangle clip = new Rectangle(300, 30);
clip.translateXProperty().bind(item.translateXProperty().negate());
item.setClip(clip);
menuBox.getChildren().addAll(item);
});
root.getChildren().add(menuBox);
}
@Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(createContent());
primaryStage.setTitle("Civilization VI Menu");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| 1,771 |
626 |
#ifndef POISSONDISCSAMPLER_H
#define POISSONDISCSAMPLER_H
#include <vector>
#include <cmath>
#include <stdlib.h>
#include <time.h>
#include "dcel.h"
#include "extents2d.h"
namespace PoissonDiscSampler {
using namespace dcel;
struct GridIndex {
int i = 0;
int j = 0;
GridIndex() {}
GridIndex(int ii, int jj) : i(ii), j(jj) {}
};
struct SampleGrid {
Extents2d bounds;
int width = 0;
int height = 0;
double dx = 0.0;
std::vector<int> grid;
SampleGrid(Extents2d extents, double cellsize) {
bounds = extents;
dx = cellsize;
double bw = bounds.maxx - bounds.minx;
double bh = bounds.maxy - bounds.miny;
width = (int)ceil(bw / cellsize);
height = (int)ceil(bh / cellsize);
grid = std::vector<int>(width*height, -1);
}
int getFlatIndex(int i, int j) {
return i + j*width;
}
int getSample(GridIndex g) {
return getSample(g.i, g.j);
}
int getSample(int i, int j) {
if (i < 0 || i > width || j < 0 || j > height) {
throw std::range_error("getSample");
}
return grid[getFlatIndex(i, j)];
}
void setSample(GridIndex g, int s) {
setSample(g.i, g.j, s);
}
void setSample(int i, int j, int s) {
if (i < 0 || i > width || j < 0 || j > height) {
throw std::range_error("setSample");
}
grid[getFlatIndex(i, j)] = s;
}
GridIndex getCell(Point p) {
return getCell(p.x, p.y);
}
GridIndex getCell(double x, double y) {
x -= bounds.minx;
y -= bounds.miny;
return GridIndex((int)floor(x / dx), (int)floor(y / dx));
}
};
std::vector<Point> generateSamples(Extents2d bounds, double r, int k);
double _randomDouble(double min, double max);
int _randomRange(int min, int max);
Point _randomPoint(Extents2d &extents);
Point _randomDiscPoint(Point ¢er, double r);
bool _findDiscPoint(Point ¢er, double r, int k,
std::vector<Point> &points, SampleGrid &grid, Point *p);
bool _isSampleValid(Point &p, double r,
std::vector<Point> &points, SampleGrid &grid);
}
#endif
| 1,226 |
629 |
<reponame>unghee/TorchCraftAI
/*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "gameutils/game.h"
#include "test.h"
#include "buildorders/base.h"
#include "modules.h"
#include "player.h"
#include "utils.h"
#include <bwem/map.h>
using namespace cherrypi;
CASE("core/areaInfo/cache[hide]") {
const std::string scmap = "maps/(4)Circuit Breaker.scx";
std::unique_ptr<Player> bot;
auto scenario = GameSinglePlayerMelee(scmap, "Zerg", "Terran");
bot = std::make_unique<Player>(scenario.makeClient());
bot->setWarnIfSlow(false);
bot->addModule(Module::make<CreateGatherAttackModule>());
bot->addModule(Module::make<UPCToCommandModule>());
bot->init();
bot->step();
auto& areaInfo = bot->state()->areaInfo();
auto* map = bot->state()->map();
int mismatch = 0;
// uncomment if you want to dump and inspect differences
// std::ofstream f1("groundtruth.txt"), f2("ours.txt");
for (int x = 0; x < map->WalkSize().x; ++x) {
for (int y = 0; y < map->WalkSize().y; ++y) {
auto curArea = map->GetArea(BWAPI::WalkPosition(x, y));
if (curArea == nullptr) {
curArea = map->GetNearestArea(BWAPI::WalkPosition(x, y));
}
auto ourArea = areaInfo.getArea(Position(x, y));
// f1 << curArea->Id() << std::endl;
// f2 << ourArea.id << std::endl;
if (curArea->Id() != ourArea.id) {
mismatch++;
}
}
}
double mismatchRate =
double(mismatch) / double(map->WalkSize().x * map->WalkSize().y);
// we can have a few mismatch, since tie-breaking is not canonical. We expect
// the mismatch to be very low though.
EXPECT(mismatchRate < 0.5 / 100.);
}
| 670 |
1,056 |
#pragma once
#include "../netvars.hpp"
#include "vector.h"
#include "../../utils/utils.hpp"
#include <functional>
inline std::map<float, int, std::greater<float>> entityDistanceMap; // Map containing entity distance
void cachePlayers();
class ICollideable {
public:
virtual void pad0();
virtual const Vector& OBBMins() const;
virtual const Vector& OBBMaxs() const;
};
class Entity {
public:
void* networkable() {
return reinterpret_cast<void*>(uintptr_t(this) + 16);
}
void* renderable() {
return reinterpret_cast<void*>(uintptr_t(this) + 0x8);
}
ClientClass* clientClass() {
typedef ClientClass*(*Fn)(void*);
return getVirtualFunc<Fn>(networkable(), 2)(networkable());
}
bool dormant() {
typedef bool(*Fn)(void*);
return getVirtualFunc<Fn>(networkable(), 9)(networkable());
}
int index() {
typedef int(*Fn)(void*);
return getVirtualFunc<Fn>(networkable(), 10)(networkable());
}
model_t* model() {
typedef model_t* (*Fn)(void*);
return getVirtualFunc<Fn>(renderable(), 8)(renderable());
}
bool setupBones(matrix3x4_t* pBoneMatrix, int nMaxBones, int nBoneMask, float flCurTime = 0) {
typedef bool (*Fn)(void*, matrix3x4_t*, int, int, float);
return getVirtualFunc<Fn>(renderable(), 13)(renderable(), pBoneMatrix, nMaxBones, nBoneMask, flCurTime);
}
bool shouldDraw() {
typedef bool (*Fn)(void*);
return getVirtualFunc<Fn>(renderable(), 5)(renderable());
}
const Vector& origin()
{
typedef const Vector& (*Fn)(void*);
return getVirtualFunc<Fn>(this, 12)(this);
}
bool isPlayer() {
typedef bool (*Fn)(void*);
return getVirtualFunc<Fn>(this, 157)(this);
}
NETVAR("DT_BaseEntity", "m_Collision", collideable, ICollideable);
NETVAR("DT_BaseEntity", "m_iTeamNum", team, int);
NETVAR("DT_BaseEntity", "m_bSpotted", spotted, bool);
};
class Player : public Entity {
public:
NETVAR("DT_BasePlayer", "m_vecVelocity[0]", velocity, Vector);
NETVAR("DT_BasePlayer", "m_nTickBase", tickbase, unsigned int);
NETVAR("DT_CSPlayer", "m_iAccount", money, int);
NETVAR("DT_BasePlayer", "m_iHealth", health, int);
NETVAR("DT_CSPlayer", "m_fFlags", flags, int);
NETVAR("DT_BasePlayer", "m_aimPunchAngle", aimPunch, QAngle);
NETVAR("DT_BasePlayer", "m_viewPunchAngle", viewPunch, QAngle);
NETVAR("DT_CSPlayer", "m_hActiveWeapon", activeWeapon, void*);
NETVAR("DT_CSPlayer", "m_hObserverTarget", observerTarget, Player*);
NETVAR("DT_CSPlayer", "m_bHasDefuser", defuser, bool);
NETVAR("DT_BasePlayer", "m_vecViewOffset[0]", viewOffset, Vector);
NETVAR("DT_CSPlayer", "m_angEyeAngles[0]", eyeAngles, QAngle);
NETVAR("DT_CSPlayer", "m_flLowerBodyYawTarget", lbyTarget, float);
NETVAR("DT_CSPlayer", "m_bIsScoped", scoped, bool);
NETVAR("DT_BasePlayer", "deadflag", deadflag, bool);
NETVAR("DT_CSPlayer", "m_flFlashDuration", flashDuration, float);
NETVAR("DT_CSPlayer", "m_flFlashMaxAlpha", maxFlashAlpha, float);
NETVAR("DT_CSPlayer", "m_bHasHelmet", helmet, bool);
NETVAR("DT_CSPlayer", "m_ArmorValue", armor, int);
NETVAR("DT_CSPlayer", "m_nSurvivalTeam", survivalTeam, int);
AnimState* animState() {
return *reinterpret_cast<AnimState **>((uintptr_t)
this + Offsets::animState);
}
QAngle* viewAngles() {
return (QAngle*)((uintptr_t)deadflag_ptr() + 0x4);
}
Vector eyePos() {
return origin() + ((viewOffset().z > 0) ? viewOffset() : Vector(0, 0, (flags() & (1 << 1)) ? 46 : 64)); // For some reason some ents' viewoffset is all 0s, this is a hacky fix for it
}
int crosshair() {
return *reinterpret_cast<int*>((uintptr_t)defuser_ptr()+0x7c);
}
int moveType() {
return *reinterpret_cast<int*>((uintptr_t)this + GETNETVAROFFSET("DT_BaseEntity", "m_nRenderMode") + 1);
}
void saveData(const char *context, int slot, int type) {
Offsets::saveData(this, context, slot, type);
}
void restoreData (const char *context, int slot, int type) {
Offsets::restoreData(this, context, slot, type);
}
void onPostRestoreData() {
Offsets::onPostRestoreData(this);
}
bool isEnemy();
bool getHitboxBones(matrix3x4_t* boneMatrix);
bool getAnythingBones(matrix3x4_t* boneMatrix);
Vector getBonePos(int bone);
bool visible();
};
class Item : public Entity{
public:
NETVAR("DT_BaseAttributableItem", "m_iItemDefinitionIndex", itemIndex, ItemIndex);
};
class Weapon : public Item {
public:
NETVAR("DT_BaseCombatWeapon", "m_hOwner", owner, int);
NETVAR("DT_BaseCombatWeapon", "m_iItemIDHigh", itemIDHigh, int);
NETVAR("DT_BaseCombatWeapon", "m_iAccountID", accountID, int);
NETVAR("DT_BaseCombatWeapon", "m_nFallbackPaintKit", paintKit, int);
NETVAR("DT_BaseCombatWeapon", "m_flFallbackWear", wear, float);
NETVAR("DT_BaseCombatWeapon", "m_nFallbackStatTrak", statTrack, int);
float GetSpread() {
typedef float (*Fn)(void*);
return getVirtualFunc<Fn>(this, 521)(this);
}
float GetInaccuracy() {
typedef float (*Fn)(void*);
return getVirtualFunc<Fn>(this, 551)(this);
}
};
class PlantedC4 : public Item {
public:
NETVAR("DT_PlantedC4", "m_flC4Blow", time, float);
};
class TonemapController {
public:
NETVAR("DT_EnvTonemapController", "m_bUseCustomAutoExposureMin", useExposureMin, bool);
NETVAR("DT_EnvTonemapController", "m_bUseCustomAutoExposureMax", useExposureMax, bool);
NETVAR("DT_EnvTonemapController", "m_flCustomAutoExposureMin", exposureMin, float);
NETVAR("DT_EnvTonemapController", "m_flCustomAutoExposureMax", exposureMax, float);
};
class FogController {
public:
NETVAR("DT_FogController", "m_fog.enable", enable, bool);
NETVAR("DT_FogController", "m_fog.start", start, float);
NETVAR("DT_FogController", "m_fog.end", end, float);
NETVAR("DT_FogController", "m_fog.farz", farz, float);
NETVAR("DT_FogController", "m_fog.maxdensity", maxDensity, float);
NETVAR("DT_FogController", "m_fog.colorPrimary", colorPrimary, int);
};
| 2,243 |
4,372 |
<reponame>Trydamere/shardingsphere
/*
* 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.shardingsphere.sharding.rewrite.token;
import org.apache.shardingsphere.infra.binder.segment.select.projection.impl.AggregationDistinctProjection;
import org.apache.shardingsphere.infra.binder.statement.ddl.CreateDatabaseStatementContext;
import org.apache.shardingsphere.infra.binder.statement.dml.SelectStatementContext;
import org.apache.shardingsphere.sharding.rewrite.token.generator.impl.DistinctProjectionPrefixTokenGenerator;
import org.junit.Test;
import java.util.LinkedList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public final class DistinctProjectionPrefixTokenGeneratorTest {
@Test
public void assertIsGenerateSQLToken() {
DistinctProjectionPrefixTokenGenerator generator = new DistinctProjectionPrefixTokenGenerator();
assertFalse(generator.isGenerateSQLToken(mock(CreateDatabaseStatementContext.class)));
SelectStatementContext selectStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS);
List<AggregationDistinctProjection> aggregationDistinctProjections = new LinkedList<>();
when(selectStatementContext.getProjectionsContext().getAggregationDistinctProjections()).thenReturn(aggregationDistinctProjections);
assertFalse(generator.isGenerateSQLToken(selectStatementContext));
aggregationDistinctProjections.add(mock(AggregationDistinctProjection.class));
assertTrue(generator.isGenerateSQLToken(selectStatementContext));
}
@Test
public void assertGenerateSQLToken() {
SelectStatementContext selectStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS);
final int testStartIndex = 1;
when(selectStatementContext.getProjectionsContext().getStartIndex()).thenReturn(testStartIndex);
DistinctProjectionPrefixTokenGenerator generator = new DistinctProjectionPrefixTokenGenerator();
assertThat(generator.generateSQLToken(selectStatementContext).toString(), is("DISTINCT "));
}
}
| 957 |
1,853 |
<reponame>galorojo/cppinsights<gh_stars>1000+
auto gp = new int[2][3][4];
auto gz = new int[1];
auto gx = new int;
auto gu = new int[0x2][0x3][0x4];
int main()
{
}
| 82 |
1,545 |
<filename>tsai/__init__.py
__version__ = "0.2.25"
| 23 |
1,119 |
import matplotlib as mpl
# This line allows mpl to run with no DISPLAY defined
mpl.use('Agg')
from keras.layers import Flatten, Dropout, LeakyReLU, Input, Activation
from keras.models import Model
from keras.layers.convolutional import UpSampling2D
from keras.optimizers import Adam
from keras.datasets import mnist
import pandas as pd
import numpy as np
import keras.backend as K
from keras_adversarial.legacy import Dense, BatchNormalization, Convolution2D
from keras_adversarial.image_grid_callback import ImageGridCallback
from keras_adversarial import AdversarialModel, simple_gan, gan_targets
from keras_adversarial import AdversarialOptimizerSimultaneous, normal_latent_sampling
from image_utils import dim_ordering_fix, dim_ordering_input, dim_ordering_reshape, dim_ordering_unfix
def leaky_relu(x):
return K.relu(x, 0.2)
def model_generator():
nch = 256
g_input = Input(shape=[100])
H = Dense(nch * 14 * 14)(g_input)
H = BatchNormalization(mode=2)(H)
H = Activation('relu')(H)
H = dim_ordering_reshape(nch, 14)(H)
H = UpSampling2D(size=(2, 2))(H)
H = Convolution2D(int(nch / 2), 3, 3, border_mode='same')(H)
H = BatchNormalization(mode=2, axis=1)(H)
H = Activation('relu')(H)
H = Convolution2D(int(nch / 4), 3, 3, border_mode='same')(H)
H = BatchNormalization(mode=2, axis=1)(H)
H = Activation('relu')(H)
H = Convolution2D(1, 1, 1, border_mode='same')(H)
g_V = Activation('sigmoid')(H)
return Model(g_input, g_V)
def model_discriminator(input_shape=(1, 28, 28), dropout_rate=0.5):
d_input = dim_ordering_input(input_shape, name="input_x")
nch = 512
# nch = 128
H = Convolution2D(int(nch / 2), 5, 5, subsample=(2, 2), border_mode='same', activation='relu')(d_input)
H = LeakyReLU(0.2)(H)
H = Dropout(dropout_rate)(H)
H = Convolution2D(nch, 5, 5, subsample=(2, 2), border_mode='same', activation='relu')(H)
H = LeakyReLU(0.2)(H)
H = Dropout(dropout_rate)(H)
H = Flatten()(H)
H = Dense(int(nch / 2))(H)
H = LeakyReLU(0.2)(H)
H = Dropout(dropout_rate)(H)
d_V = Dense(1, activation='sigmoid')(H)
return Model(d_input, d_V)
def mnist_process(x):
x = x.astype(np.float32) / 255.0
return x
def mnist_data():
(xtrain, ytrain), (xtest, ytest) = mnist.load_data()
return mnist_process(xtrain), mnist_process(xtest)
def generator_sampler(latent_dim, generator):
def fun():
zsamples = np.random.normal(size=(10 * 10, latent_dim))
gen = dim_ordering_unfix(generator.predict(zsamples))
return gen.reshape((10, 10, 28, 28))
return fun
if __name__ == "__main__":
# z \in R^100
latent_dim = 100
# x \in R^{28x28}
input_shape = (1, 28, 28)
# generator (z -> x)
generator = model_generator()
# discriminator (x -> y)
discriminator = model_discriminator(input_shape=input_shape)
# gan (x - > yfake, yreal), z generated on GPU
gan = simple_gan(generator, discriminator, normal_latent_sampling((latent_dim,)))
# print summary of models
generator.summary()
discriminator.summary()
gan.summary()
# build adversarial model
model = AdversarialModel(base_model=gan,
player_params=[generator.trainable_weights, discriminator.trainable_weights],
player_names=["generator", "discriminator"])
model.adversarial_compile(adversarial_optimizer=AdversarialOptimizerSimultaneous(),
player_optimizers=[Adam(1e-4, decay=1e-4), Adam(1e-3, decay=1e-4)],
loss='binary_crossentropy')
# train model
generator_cb = ImageGridCallback("output/gan_convolutional/epoch-{:03d}.png",
generator_sampler(latent_dim, generator))
xtrain, xtest = mnist_data()
xtrain = dim_ordering_fix(xtrain.reshape((-1, 1, 28, 28)))
xtest = dim_ordering_fix(xtest.reshape((-1, 1, 28, 28)))
y = gan_targets(xtrain.shape[0])
ytest = gan_targets(xtest.shape[0])
history = model.fit(x=xtrain, y=y, validation_data=(xtest, ytest), callbacks=[generator_cb], nb_epoch=100,
batch_size=32)
df = pd.DataFrame(history.history)
df.to_csv("output/gan_convolutional/history.csv")
generator.save("output/gan_convolutional/generator.h5")
discriminator.save("output/gan_convolutional/discriminator.h5")
| 1,925 |
466 |
/*
Copyright (c) 2010, NullNoname
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of NullNoname nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package mu.nu.nullpo.game.component;
import java.io.Serializable;
/**
* button inputClass to manage the state
*/
public class Controller implements Serializable {
/** Serial version ID */
private static final long serialVersionUID = -4855072501928533723L;
/** ↑ (Hard drop) button */
public static final int BUTTON_UP = 0;
/** ↓ (Soft drop) button */
public static final int BUTTON_DOWN = 1;
/** ← (Left movement) button */
public static final int BUTTON_LEFT = 2;
/** → (Right movement) button */
public static final int BUTTON_RIGHT = 3;
/** A (Regular rotation) button */
public static final int BUTTON_A = 4;
/** B (Reverse rotation) button */
public static final int BUTTON_B = 5;
/** C (Regular rotation) button */
public static final int BUTTON_C = 6;
/** D (Hold) button */
public static final int BUTTON_D = 7;
/** E (180-degree rotation) button */
public static final int BUTTON_E = 8;
/** F (Use item, staff roll fast-forward, etc.) button */
public static final int BUTTON_F = 9;
/** Number of buttons */
public static final int BUTTON_COUNT = 10;
/** Constant-bit operationcount */
public static final int BUTTON_BIT_UP = 1,
BUTTON_BIT_DOWN = 2,
BUTTON_BIT_LEFT = 4,
BUTTON_BIT_RIGHT = 8,
BUTTON_BIT_A = 16,
BUTTON_BIT_B = 32,
BUTTON_BIT_C = 64,
BUTTON_BIT_D = 128,
BUTTON_BIT_E = 256,
BUTTON_BIT_F = 512;
/** ButtonIf you hold down thetrue */
public boolean[] buttonPress;
/** ButtonI have to leave the press time */
public int[] buttonTime;
/**
* Constructor
*/
public Controller() {
reset();
}
/**
* Copy constructor
* @param c Copy source
*/
public Controller(Controller c) {
copy(c);
}
/**
* Back to the initial state
*/
public void reset() {
buttonPress = new boolean[BUTTON_COUNT];
buttonTime = new int[BUTTON_COUNT];
}
/**
* OtherController stateCopy
* @param c Copy source
*/
public void copy(Controller c) {
buttonPress = new boolean[BUTTON_COUNT];
buttonTime = new int[BUTTON_COUNT];
for(int i = 0; i < BUTTON_COUNT; i++) {
buttonPress[i] = c.buttonPress[i];
buttonTime[i] = c.buttonTime[i];
}
}
/**
* buttonThe state is not pressed all the
*/
public void clearButtonState() {
for(int i = 0; i < BUTTON_COUNT; i++) buttonPress[i] = false;
}
/**
* buttonA1 frame Determine whether the state I was only pressed
* @param btn Button number
* @return buttonA1 frame If you hold down onlytrue
*/
public boolean isPush(int btn) {
return (buttonTime[btn] == 1);
}
/**
* buttonDetermine whether the state is pressed
* @param btn Button number
* @return buttonState if you press thetrue
*/
public boolean isPress(int btn) {
return (buttonTime[btn] >= 1);
}
/**
* Menu Determines whether the cursor is moved in
* @param key Button number
* @return If the cursor movestrue
*/
public boolean isMenuRepeatKey(int key) {
return isMenuRepeatKey(key, true);
}
/**
* Menu Determines whether the cursor is moved in
* @param key Button number
* @param enableCButton C buttonAllow for high-speed movement
* @return If the cursor movestrue
*/
public boolean isMenuRepeatKey(int key, boolean enableCButton) {
if( (buttonTime[key] == 1) || ((buttonTime[key] >= 25) && (buttonTime[key] % 3 == 0)) ||
((buttonTime[key] >= 1) && isPress(BUTTON_C) && enableCButton) )
{
return true;
}
return false;
}
/**
* buttonThe Press and hold the
* @param key Button number
*/
public void setButtonPressed(int key) {
if((key >= 0) && (key < buttonPress.length)) buttonPress[key] = true;
}
/**
* buttonThe state did not press
* @param key Button number
*/
public void setButtonUnpressed(int key) {
if((key >= 0) && (key < buttonPress.length)) buttonPress[key] = false;
}
/**
* buttonSets the status by pressing the
* @param key Button number
* @param pressed When true,Press, falseIf I do not press
*/
public void setButtonState(int key, boolean pressed) {
if((key >= 0) && (key < buttonPress.length)) buttonPress[key] = pressed;
}
/**
* button inputBit state flagReturns
* @return button inputBit of state flag
*/
public int getButtonBit() {
int input = 0;
if(buttonPress[BUTTON_UP]) input |= BUTTON_BIT_UP;
if(buttonPress[BUTTON_DOWN]) input |= BUTTON_BIT_DOWN;
if(buttonPress[BUTTON_LEFT]) input |= BUTTON_BIT_LEFT;
if(buttonPress[BUTTON_RIGHT]) input |= BUTTON_BIT_RIGHT;
if(buttonPress[BUTTON_A]) input |= BUTTON_BIT_A;
if(buttonPress[BUTTON_B]) input |= BUTTON_BIT_B;
if(buttonPress[BUTTON_C]) input |= BUTTON_BIT_C;
if(buttonPress[BUTTON_D]) input |= BUTTON_BIT_D;
if(buttonPress[BUTTON_E]) input |= BUTTON_BIT_E;
if(buttonPress[BUTTON_F]) input |= BUTTON_BIT_F;
return input;
}
/**
* button inputBit state flagSet based on
* @param input button inputBit of state flag
*/
public void setButtonBit(int input) {
clearButtonState();
if((input & BUTTON_BIT_UP) != 0) buttonPress[BUTTON_UP] = true;
if((input & BUTTON_BIT_DOWN) != 0) buttonPress[BUTTON_DOWN] = true;
if((input & BUTTON_BIT_LEFT) != 0) buttonPress[BUTTON_LEFT] = true;
if((input & BUTTON_BIT_RIGHT) != 0) buttonPress[BUTTON_RIGHT] = true;
if((input & BUTTON_BIT_A) != 0) buttonPress[BUTTON_A] = true;
if((input & BUTTON_BIT_B) != 0) buttonPress[BUTTON_B] = true;
if((input & BUTTON_BIT_C) != 0) buttonPress[BUTTON_C] = true;
if((input & BUTTON_BIT_D) != 0) buttonPress[BUTTON_D] = true;
if((input & BUTTON_BIT_E) != 0) buttonPress[BUTTON_E] = true;
if((input & BUTTON_BIT_F) != 0) buttonPress[BUTTON_F] = true;
}
/**
* button input timeUpdate
*/
public void updateButtonTime() {
for(int i = 0; i < BUTTON_COUNT; i++) {
if(buttonPress[i]) buttonTime[i]++;
else buttonTime[i] = 0;
}
}
/**
* button inputResets the state
*/
public void clearButtonTime() {
for(int i = 0; i < BUTTON_COUNT; i++) {
buttonTime[i] = 0;
}
}
}
| 3,020 |
4,310 |
<gh_stars>1000+
//
// MRCOAuthViewController.h
// MVVMReactiveCocoa
//
// Created by leichunfeng on 16/5/15.
// Copyright © 2016年 leichunfeng. All rights reserved.
//
#import "MRCWebViewController.h"
@interface MRCOAuthViewController : MRCWebViewController
@end
| 103 |
3,084 |
<filename>network/ndis/netvmini/6x/mphal.c
/*++
Copyright (c) Microsoft Corporation. All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
PURPOSE.
Module Name:
MpHAL.C
Abstract:
This module implements the adapter's hardware.
--*/
#include "netvmin6.h"
#include "mphal.tmh"
//
// This registry value saves the permanent MAC address of a netvmini NIC. It is
// only needed because there's no hardware that keeps track of the permanent
// address across reboots.
//
// It is saved as a NdisParameterBinary configuration value (REG_BINARY) with
// length NIC_MACADDR_LEN (6 bytes).
//
#define NETVMINI_MAC_ADDRESS_KEY L"NetvminiMacAddress"
static
NDIS_STATUS
HWCopyBytesFromNetBuffer(
_In_ PNET_BUFFER NetBuffer,
_Inout_ PULONG cbDest,
_Out_writes_bytes_to_(*cbDest, *cbDest) PVOID Dest);
#pragma NDIS_PAGEABLE_FUNCTION(HWInitialize)
#pragma NDIS_PAGEABLE_FUNCTION(HWReadPermanentMacAddress)
NDIS_STATUS
HWInitialize(
_In_ PMP_ADAPTER Adapter,
_In_ PNDIS_MINIPORT_INIT_PARAMETERS InitParameters)
/*++
Routine Description:
Query assigned resources and initialize the adapter.
Arguments:
Adapter Pointer to our adapter
InitParameters Parameters to MiniportInitializeEx
Return Value:
NDIS_STATUS_SUCCESS
NDIS_STATUS_ADAPTER_NOT_FOUND
--*/
{
NDIS_STATUS Status = NDIS_STATUS_ADAPTER_NOT_FOUND;
PCM_PARTIAL_RESOURCE_DESCRIPTOR pResDesc;
ULONG index;
UNREFERENCED_PARAMETER(Adapter);
DEBUGP(MP_TRACE, "[%p] ---> HWInitialize\n", Adapter);
PAGED_CODE();
do
{
if (InitParameters->AllocatedResources)
{
for (index=0; index < InitParameters->AllocatedResources->Count; index++)
{
pResDesc = &InitParameters->AllocatedResources->PartialDescriptors[index];
switch (pResDesc->Type)
{
case CmResourceTypePort:
DEBUGP(MP_INFO, "[%p] IoBaseAddress = 0x%x\n", Adapter,
NdisGetPhysicalAddressLow(pResDesc->u.Port.Start));
DEBUGP(MP_INFO, "[%p] IoRange = x%x\n", Adapter,
pResDesc->u.Port.Length);
break;
case CmResourceTypeInterrupt:
DEBUGP(MP_INFO, "[%p] InterruptLevel = x%x\n", Adapter,
pResDesc->u.Interrupt.Level);
break;
case CmResourceTypeMemory:
DEBUGP(MP_INFO, "[%p] MemPhysAddress(Low) = 0x%0x\n", Adapter,
NdisGetPhysicalAddressLow(pResDesc->u.Memory.Start));
DEBUGP(MP_INFO, "[%p] MemPhysAddress(High) = 0x%0x\n", Adapter,
NdisGetPhysicalAddressHigh(pResDesc->u.Memory.Start));
break;
}
}
}
Status = NDIS_STATUS_SUCCESS;
//
// Map bus-relative IO range to system IO space using
// NdisMRegisterIoPortRange
//
//
// Map bus-relative registers to virtual system-space
// using NdisMMapIoSpace
//
//
// Disable interrupts here as soon as possible
//
//
// Register the interrupt using NdisMRegisterInterruptEx
//
//
// Initialize the hardware with mapped resources
//
//
// Enable the interrupt
//
} while (FALSE);
DEBUGP(MP_TRACE, "[%p] <--- HWInitialize Status = 0x%x\n", Adapter, Status);
return Status;
}
VOID
HWReadPermanentMacAddress(
_In_ PMP_ADAPTER Adapter,
_In_ NDIS_HANDLE ConfigurationHandle,
_Out_writes_bytes_(NIC_MACADDR_SIZE) PUCHAR PermanentMacAddress)
/*++
Routine Description:
Loads the permanent MAC address that is burnt into the NIC.
IRQL = PASSIVE_LEVEL
Arguments:
Adapter Pointer to our adapter
ConfigurationHandle NIC configuration from NdisOpenConfigurationEx
PermanentMacAddress On return, receives the NIC's MAC address
Return Value:
None.
--*/
{
NDIS_STATUS Status;
PNDIS_CONFIGURATION_PARAMETER Parameter = NULL;
NDIS_STRING PermanentAddressKey = RTL_CONSTANT_STRING(NETVMINI_MAC_ADDRESS_KEY);
UNREFERENCED_PARAMETER(Adapter);
PAGED_CODE();
//
// We want to figure out what the NIC's physical address is.
// If we had a hardware NIC, we would query the physical address from it.
// Instead, for the purposes of this sample, we'll read it from the
// registry. This will help us keep the permanent address constant, even
// if the adapter is disabled/enabled.
//
// Note that the registry value that saves our permanent MAC address isn't
// the one that end-users can configure through the NIC management GUI,
// nor is it expected that other miniports would need to use a parameter
// like this. We only have it to work around the lack of physical hardware.
//
NdisReadConfiguration(
&Status,
&Parameter,
ConfigurationHandle,
&PermanentAddressKey,
NdisParameterBinary);
if (Status == NDIS_STATUS_SUCCESS
&& Parameter->ParameterType == NdisParameterBinary
&& Parameter->ParameterData.BinaryData.Length == NIC_MACADDR_SIZE)
{
//
// There is a permanent address stashed in the special netvmini
// parameter.
//
NIC_COPY_ADDRESS(PermanentMacAddress, Parameter->ParameterData.BinaryData.Buffer);
}
else
{
NDIS_CONFIGURATION_PARAMETER NewPhysicalAddress;
LARGE_INTEGER TickCountValue;
UCHAR CurrentMacIndex = 3;
//
// There is no (valid) address stashed in the netvmini parameter, so
// this is probably the first time we've loaded this adapter before.
//
// Just for testing purposes, let us make up a dummy mac address.
// In order to avoid conflicts with MAC addresses, it is usually a good
// idea to check the IEEE OUI list (e.g. at
// http://standards.ieee.org/regauth/oui/oui.txt). According to that
// list 00-50-F2 is owned by Microsoft.
//
// An important rule to "generating" MAC addresses is to have the
// "locally administered bit" set in the address, which is bit 0x02 for
// LSB-type networks like Ethernet. Also make sure to never set the
// multicast bit in any MAC address: bit 0x01 in LSB networks.
//
{C_ASSERT(NIC_MACADDR_SIZE > 3);}
NdisZeroMemory(PermanentMacAddress, NIC_MACADDR_SIZE);
PermanentMacAddress[0] = 0x02;
PermanentMacAddress[1] = 0x50;
PermanentMacAddress[2] = 0xF2;
//
// Generated value based on the current tick count value.
//
KeQueryTickCount(&TickCountValue);
do
{
//
// Pick up the value in groups of 8 bits to populate the rest of the MAC address.
//
PermanentMacAddress[CurrentMacIndex] = (UCHAR)(TickCountValue.LowPart>>((CurrentMacIndex-3)*8));
} while(++CurrentMacIndex < NIC_MACADDR_SIZE);
//
// Finally, we should make a best-effort attempt to save this address
// to our configuration, so the NIC will always come up with this
// permanent address.
//
NewPhysicalAddress.ParameterType = NdisParameterBinary;
NewPhysicalAddress.ParameterData.BinaryData.Length = NIC_MACADDR_SIZE;
NewPhysicalAddress.ParameterData.BinaryData.Buffer = PermanentMacAddress;
NdisWriteConfiguration(
&Status,
ConfigurationHandle,
&PermanentAddressKey,
&NewPhysicalAddress);
if (NDIS_STATUS_SUCCESS != Status)
{
DEBUGP(MP_WARNING, "[%p] NdisWriteConfiguration failed to save the permanent MAC address", Adapter);
// No other handling -- this isn't a fatal error
}
}
}
_IRQL_requires_same_
_Function_class_(ALLOCATE_FUNCTION)
PVOID
HWFrameAllocate (
_In_ POOL_TYPE PoolType,
_In_ SIZE_T NumberOfBytes,
_In_ ULONG Tag)
/*++
Routine Description:
This routine allocates memory for a FRAME. It is an ALLOCATE_FUNCTION, so
its parameters and usage are the same as ExAllocatePoolWithTag.
This allocator is meant to be used with the send NPAGED_LOOKASIDE_LIST.
While you do not normally need to provide your own allocator (and in fact
there is a performance penalty for doing so), we use the allocator to
initialize the FRAME's MDL. This saves us the effort of (re)initializing
the same MDL every time we reuse the FRAME.
Runs at IRQL <= DISPATCH_LEVEL
Arguments:
PoolType Must be NonPagedPool, or NonPagedPoolNx for Win8
and later
NumberOfBytes Must be sizeof(FRAME)
Tag The pool allocation tag
Return Value:
NULL if there are insufficient resources to allocate a FRAME.
Else, a pointer to a newly-allocated FRAME. Free it with HWFrameFree.
--*/
{
PFRAME Frame = NULL;
DEBUGP(MP_TRACE, "---> HWFrameAllocate\n");
UNREFERENCED_PARAMETER(PoolType);
ASSERT(NumberOfBytes == sizeof(FRAME));
Frame = (PFRAME) NdisAllocateMemoryWithTagPriority(
NdisDriverHandle,
(UINT)NumberOfBytes,
Tag,
NormalPoolPriority);
if (!Frame)
{
DEBUGP(MP_ERROR, "NdisAllocateMemoryWithTagPriority failed");
return NULL;
}
NdisZeroMemory(Frame, NumberOfBytes);
Frame->Mdl = NdisAllocateMdl(
NdisDriverHandle,
(PVOID)&Frame->Data[0],
sizeof(Frame->Data));
if (Frame->Mdl == NULL)
{
DEBUGP(MP_ERROR, "NdisAllocateMdl failed\n");
NdisFreeMemory(Frame, (UINT)NumberOfBytes, 0);
return NULL;
}
DEBUGP(MP_TRACE, "<--- HWFrameAllocate. Frame: %p\n", Frame);
return Frame;
}
_Use_decl_annotations_
VOID
HWFrameFree (
PVOID Memory)
/*++
Routine Description:
This routine frees memory for a FRAME. It is a FREE_FUNCTION, the
reciprocal of HWFrameAllocate.
Runs at IRQL <= DISPATCH_LEVEL
Arguments:
Memory A buffer allocated with HWFrameAllocate
Return Value:
None.
--*/
{
PFRAME Frame = (PFRAME) Memory;
DEBUGP(MP_TRACE, "---> HWFrameFree. Frame: %p\n", Frame);
ASSERT(Frame && Frame->Mdl);
NdisFreeMdl(Frame->Mdl);
NdisFreeMemory(Frame, sizeof(FRAME), 0);
DEBUGP(MP_TRACE, "<--- HWFrameFree\n");
}
VOID
HWFrameReference(
_In_ PFRAME Frame)
/*++
Routine Description:
This routine increments the reference count of a FRAME.
Runs at IRQL <= DISPATCH_LEVEL
Arguments:
Frame Frame to reference
Return Value:
None.
--*/
{
DEBUGP(MP_TRACE, "---> HWFrameReference. Frame: %p\n", Frame);
NdisInterlockedIncrement(&Frame->Ref);
DEBUGP(MP_TRACE, "<--- HWFrameReference. Frame: %p\n", Frame);
}
VOID
HWFrameRelease(
_In_ PFRAME Frame)
/*++
Routine Description:
This routine decrements the reference count of a FRAME. If the last
refernce was released, the FRAME is freed back to the unused pool.
Runs at IRQL <= DISPATCH_LEVEL
Arguments:
Frame Frame to release
Return Value:
None.
--*/
{
DEBUGP(MP_TRACE, "---> HWFrameRelease. Frame: %p\n", Frame);
if (0 == NdisInterlockedDecrement(&Frame->Ref))
{
DEBUGP(MP_TRACE, "---> Freeing Frame: %p\n", Frame);
NdisFreeToNPagedLookasideList(&GlobalData.FrameDataLookaside, Frame);
Frame = NULL;
}
DEBUGP(MP_TRACE, "<--- HWFrameRelease. Frame: %p\n", Frame);
}
NDIS_STATUS
HWCopyBytesFromNetBuffer(
_In_ PNET_BUFFER NetBuffer,
_Inout_ PULONG cbDest,
_Out_writes_bytes_to_(*cbDest, *cbDest) PVOID Dest)
/*++
Routine Description:
Copies the first cbDest bytes from a NET_BUFFER. In order to show how the various data structures fit together, this
implementation copies the data by iterating through the MDLs for the NET_BUFFER. The NdisGetDataBuffer API also allows you
to copy a contiguous block of data from a NET_BUFFER.
Runs at IRQL <= DISPATCH_LEVEL.
Arguments:
NetBuffer The NB to read
cbDest On input, the number of bytes in the buffer Dest
On return, the number of bytes actually copied
Dest On return, receives the first cbDest bytes of
the network frame in NetBuffer
Return Value:
None.
Notes:
If the output buffer is larger than the NB's frame size, *cbDest will
contain the number of bytes in the frame size.
If the output buffer is smaller than the NB's frame size, only the first
*cbDest bytes will be copied (the buffer will receive a truncated copy of
the frame).
--*/
{
NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
//
// Start copy from current MDL
//
PMDL CurrentMdl = NET_BUFFER_CURRENT_MDL(NetBuffer);
//
// Data on current MDL may be offset from start of MDL
//
ULONG DestOffset = 0;
while (DestOffset < *cbDest && CurrentMdl)
{
//
// Map MDL memory to System Address Space. LowPagePriority means mapping may fail if
// system is low on memory resources.
//
PUCHAR SrcMemory = MmGetSystemAddressForMdlSafe(CurrentMdl, LowPagePriority | MdlMappingNoExecute);
ULONG Length = MmGetMdlByteCount(CurrentMdl);
if (!SrcMemory)
{
Status = NDIS_STATUS_RESOURCES;
break;
}
if(DestOffset==0)
{
//
// The first MDL segment should be accessed from the current MDL offset
//
ULONG MdlOffset = NET_BUFFER_CURRENT_MDL_OFFSET(NetBuffer);
SrcMemory += MdlOffset;
Length -= MdlOffset;
}
Length = min(Length, *cbDest-DestOffset);
//
// Copy Memory
//
NdisMoveMemory((PUCHAR)Dest+DestOffset, SrcMemory, Length);
DestOffset += Length;
//
// Get next MDL (if any available)
//
CurrentMdl = NDIS_MDL_LINKAGE(CurrentMdl);
}
if(Status == NDIS_STATUS_SUCCESS)
{
*cbDest = DestOffset;
}
return Status;
}
NDIS_STATUS
HWGetDestinationAddress(
_In_ PNET_BUFFER NetBuffer,
_Out_writes_bytes_(NIC_MACADDR_SIZE) PUCHAR DestAddress)
/*++
Routine Description:
Returns the destination address of a NET_BUFFER that is to be sent.
Runs at IRQL <= DISPATCH_LEVEL.
Arguments:
NetBuffer The NB containing the frame that is being sent
DestAddress On return, receives the frame's destination
Return Value:
NDIS_STATUS_FAILURE The frame is too short
NDIS_STATUS_SUCCESS Else
--*/
{
NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
NIC_FRAME_HEADER Header;
ULONG cbHeader = sizeof(Header);
Status = HWCopyBytesFromNetBuffer(NetBuffer, &cbHeader, &Header);
if(Status == NDIS_STATUS_SUCCESS)
{
if (cbHeader < sizeof(Header))
{
NdisZeroMemory(DestAddress, NIC_MACADDR_SIZE);
Status = NDIS_STATUS_FAILURE;
}
else
{
GET_DESTINATION_OF_FRAME(DestAddress, &Header);
}
}
else
{
NdisZeroMemory(DestAddress, NIC_MACADDR_SIZE);
}
return Status;
}
BOOLEAN
HWIsFrameAcceptedByPacketFilter(
_In_ PMP_ADAPTER Adapter,
_In_reads_bytes_(NIC_MACADDR_SIZE) PUCHAR DestAddress,
_In_ ULONG FrameType)
/*++
Routine Description:
This routines checks to see whether the packet can be accepted
for transmission based on the currently programmed filter type
of the NIC and the mac address of the packet.
With real adapter, this routine would be implemented in hardware. However,
since we don't have any hardware to do the matching for us, we'll do it in
the driver.
Arguments:
Adapter Our adapter that is receiving a frame
FrameData The raw frame, starting at the frame header
cbFrameData Number of bytes in the FrameData buffer
Return Value:
TRUE if the frame is accepted by the packet filter, and should be indicated
up to the higher levels of the stack.
FALSE if the frame doesn't match the filter, and should just be dropped.
--*/
{
BOOLEAN result = FALSE;
DEBUGP(MP_LOUD, "[%p] ---> HWIsFrameAcceptedByPacketFilter PacketFilter = 0x%08x, FrameType = 0x%08x\n",
Adapter,
Adapter->PacketFilter,
FrameType);
do
{
//
// If the NIC is in promiscuous mode, we will accept anything
// and everything.
//
if (Adapter->PacketFilter & NDIS_PACKET_TYPE_PROMISCUOUS)
{
result = TRUE;
break;
}
switch (FrameType)
{
case NDIS_PACKET_TYPE_BROADCAST:
if (Adapter->PacketFilter & NDIS_PACKET_TYPE_BROADCAST)
{
//
// If it's a broadcast packet and broadcast is enabled,
// we can accept that.
//
result = TRUE;
}
break;
case NDIS_PACKET_TYPE_MULTICAST:
//
// If it's a multicast packet and multicast is enabled,
// we can accept that.
//
if (Adapter->PacketFilter & NDIS_PACKET_TYPE_ALL_MULTICAST)
{
result = TRUE;
break;
}
else if (Adapter->PacketFilter & NDIS_PACKET_TYPE_MULTICAST)
{
ULONG index;
//
// Check to see if the multicast address is in our list
//
ASSERT(Adapter->ulMCListSize <= NIC_MAX_MCAST_LIST);
for (index=0; index < Adapter->ulMCListSize && index < NIC_MAX_MCAST_LIST; index++)
{
if (NIC_ADDR_EQUAL(DestAddress, Adapter->MCList[index]))
{
result = TRUE;
break;
}
}
}
break;
case NDIS_PACKET_TYPE_DIRECTED:
if (Adapter->PacketFilter & NDIS_PACKET_TYPE_DIRECTED)
{
//
// This has to be a directed packet. If so, does packet dest
// address match with the mac address of the NIC.
//
if (NIC_ADDR_EQUAL(DestAddress, Adapter->CurrentAddress))
{
result = TRUE;
break;
}
}
break;
}
} while(FALSE);
DEBUGP(MP_LOUD, "[%p] <--- HWIsFrameAcceptedByPacketFilter Result = %u\n", Adapter, result);
return result;
}
NDIS_MEDIA_CONNECT_STATE
HWGetMediaConnectStatus(
_In_ PMP_ADAPTER Adapter)
/*++
Routine Description:
This routine will query the hardware and return
the media status.
Arguments:
Adapter Our Adapter
Return Value:
NdisMediaStateDisconnected or
NdisMediaStateConnected
--*/
{
if (MP_TEST_FLAG(Adapter, fMP_DISCONNECTED))
{
return MediaConnectStateDisconnected;
}
else
{
return MediaConnectStateConnected;
}
}
VOID
HWProgramDmaForSend(
_In_ PMP_ADAPTER Adapter,
_In_ PTCB Tcb,
_In_ PNET_BUFFER NetBuffer,
_In_ BOOLEAN fAtDispatch)
/*++
Routine Description:
Program the hardware to read the data payload from the NET_BUFFER's MDL
and queue it for transmission. When the hardware has finished reading the
MDL, it will fire an interrupt to indicate that it no longer needs the MDL
anymore.
Our hardware, of course, doesn't have any DMA, so it just copies the data
to a FRAME structure and transmits that.
Runs at IRQL <= DISPATCH_LEVEL
Arguments:
Adapter Our adapter that will send a frame
Tcb The TCB that tracks the transmit status
NetBuffer Contains the data to send
fAtDispatch TRUE if the current IRQL is DISPATCH_LEVEL
Return Value:
None.
--*/
{
PFRAME Frame;
NDIS_NET_BUFFER_LIST_8021Q_INFO Nbl1QInfo = {0};
PNET_BUFFER_LIST Nbl = NULL;
NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
DEBUGP(MP_TRACE, "[%p] ---> HWProgramDmaForSend. NB: 0x%p\n", Adapter, NetBuffer);
do
{
//
// Program the hardware to begin reading the data from NetBuffer's MDL and
// queue it for transmission.
//
Tcb->NetBuffer = NetBuffer;
Tcb->BytesActuallySent = 0;
Frame = (PFRAME)NdisAllocateFromNPagedLookasideList(&GlobalData.FrameDataLookaside);
if (!Frame)
{
DEBUGP(MP_TRACE, "[%p] ---> No frames available for send.\n", Adapter);
//
// Oops, we couldn't get any more FRAMEs to send.
//
// When the SendComplete fires, we'll tell the driver that zero bytes
// were sent successfully. It will update the bookkeeping and inform
// the protocol that the NBL wasn't completely sent.
//
break;
}
DEBUGP(MP_TRACE, "[%p] Send Frame: 0x%p\n", Adapter, Frame);
ASSERT(NET_BUFFER_DATA_LENGTH(NetBuffer) <= NIC_BUFFER_SIZE);
Frame->Ref = 1;
//
// Copy the data from the NB to the FRAME's data region. This step roughly
// corresponds to a hardware DMA.
//
Frame->ulSize = min(NET_BUFFER_DATA_LENGTH(NetBuffer), NIC_BUFFER_SIZE);
Status = HWCopyBytesFromNetBuffer(NetBuffer, &Frame->ulSize, Frame->Data);
if(Status != NDIS_STATUS_SUCCESS)
{
DEBUGP(MP_TRACE, "[%p] ---> Failed to copy frame buffer. Result = %u\n", Adapter, Status);
break;
}
if (Frame->ulSize < HW_MIN_FRAME_SIZE)
{
// Don't leak the contents of kernel memory! Zero out padding bytes.
ULONG cbPaddingNeeded = HW_MIN_FRAME_SIZE - Frame->ulSize;
NdisZeroMemory(Frame->Data + Frame->ulSize, cbPaddingNeeded);
Frame->ulSize += cbPaddingNeeded;
}
ASSERT(Frame->ulSize >= HW_MIN_FRAME_SIZE && Frame->ulSize <= NIC_BUFFER_SIZE);
//
// For simplicity in the sample in order to support VLAN we extract the information from the NBL or frame and pass the
// NDIS_NET_BUFFER_LIST_8021Q_INFO structure to the code that simulates the send/receive. The code does nothing to convert
// modify the frame format.
// In real HW, on send the code should extract the information from the NBL and covert it to 802.1Q format for transmission, and
// on receive the adapter should detect if the packet is in 802.1Q format and if so convert it back to 802.3 before indicating it up to NDIS
// (populating the 8021Q info in the NBL being indicated).
//
Nbl = NBL_FROM_SEND_NB(NetBuffer);
Nbl1QInfo.Value = NET_BUFFER_LIST_INFO(Nbl, Ieee8021QNetBufferListInfo);
if(Nbl1QInfo.Value)
{
DEBUGP(MP_TRACE, "[%p] Send NBL (%p) OOB Vlan ID: %i\n", Adapter, Nbl, Nbl1QInfo.TagHeader.VlanId);
}
else
{
DEBUGP(MP_TRACE, "[%p] Send NBL (%p) has no OOB VLAN tag, checking frame header.\n", Adapter, Nbl);
if(IS_FRAME_8021Q(Frame))
{
//
// The frame has type of 802.1Q. Retrieve the VLAN information
//
COPY_TAG_INFO_FROM_HEADER_TO_PACKET_INFO(Nbl1QInfo, GET_FRAME_VLAN_TAG_HEADER(Frame));
DEBUGP(MP_TRACE, "[%p] Send NBL (%p) frame Vlan ID: %i\n", Adapter, Nbl, Nbl1QInfo.TagHeader.VlanId);
}
else
{
DEBUGP(MP_TRACE, "[%p] Send NBL (%p) has no VLAN information in its frame header.\n", Adapter, Nbl);
}
}
RXDeliverFrameToEveryAdapter(Adapter, &Nbl1QInfo, Frame, fAtDispatch);
Tcb->BytesActuallySent = Frame->ulSize;
} while(FALSE);
if(Frame)
{
HWFrameRelease(Frame);
}
DEBUGP(MP_TRACE, "[%p] <--- HWProgramDmaForSend\n", Adapter);
}
_IRQL_requires_(DISPATCH_LEVEL)
ULONG
HWGetBytesSent(
_In_ PMP_ADAPTER Adapter,
_In_ PTCB Tcb)
/*++
Routine Description:
When the adapter indicates it has completed the send operation, call this
routine to determine how many bytes were successfully sent (if any).
Arguments:
Adapter Our adapter that will send a frame
Tcb The TCB that tracks the transmit status
Return Value:
0 There was an error sending this frame
>0 Number of bytes actually sent
--*/
{
UNREFERENCED_PARAMETER(Adapter);
return Tcb->BytesActuallySent;
}
NDIS_STATUS
HWBeginReceiveDma(
_In_ PMP_ADAPTER Adapter,
_In_ PNDIS_NET_BUFFER_LIST_8021Q_INFO Nbl1QInfo,
_In_ PRCB Rcb,
_In_ PFRAME Frame)
/*++
Routine Description:
Simulate the hardware deciding to receive a FRAME into one of its RCBs. In VMQ enabled scenarios, it will
find the matching queue and if matched retrieve the shared memory for the queue for the NBL. Otherwise, it
uses the existing Frame for the NBL.
Arguments:
Adapter Pointer to our adapter
Nbl1QInfo 8021Q Tag information for the FRAME being received
Rcb The RCB that tracks this receive operation
Frame The FRAME that to receive
Return Value:
NDIS_STATUS
--*/
{
NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
PNET_BUFFER NetBuffer = NET_BUFFER_LIST_FIRST_NB(Rcb->Nbl);
do
{
DEBUGP(MP_TRACE, "[%p] ---> HWBeginReceiveDma. Frame: 0x%p\n", Adapter, Frame);
//
// Preserve 802.1Q information, if specified.
//
if(Nbl1QInfo->Value)
{
DEBUGP(MP_TRACE, "[%p] Preserved VLAN Id=%i\n", Adapter, Nbl1QInfo->TagHeader.VlanId);
NET_BUFFER_LIST_INFO(Rcb->Nbl, Ieee8021QNetBufferListInfo) = Nbl1QInfo->Value;
}
else
{
DEBUGP(MP_TRACE, "[%p] No VLAN tag to preserve.\n", Adapter);
NET_BUFFER_LIST_INFO(Rcb->Nbl, Ieee8021QNetBufferListInfo) = 0;
}
//
// If VMQ is enabled, and we're not using the default queue,
// we need to copy the FRAME to the NBL's shared memory area
//
if(VMQ_ENABLED(Adapter))
{
BOOLEAN Copied;
Status = CopyFrameToRxQueueRcb(Adapter, Frame, Nbl1QInfo, Rcb, &Copied);
if(Copied || Status != NDIS_STATUS_SUCCESS)
{
break;
}
}
else
{
UNREFERENCED_PARAMETER(Adapter);
}
//
// Either 6.20 is not supported, VMQ is disabled, or matched default queue, so use existing frame memory for indication
//
HWFrameReference(Frame);
Rcb->Data = Frame;
NET_BUFFER_FIRST_MDL(NetBuffer) = Frame->Mdl;
NET_BUFFER_DATA_LENGTH(NetBuffer) = Frame->ulSize;
NET_BUFFER_DATA_OFFSET(NetBuffer) = 0;
NET_BUFFER_CURRENT_MDL(NetBuffer) = NET_BUFFER_FIRST_MDL(NetBuffer);
NET_BUFFER_CURRENT_MDL_OFFSET(NetBuffer) = 0;
}
while(FALSE);
DEBUGP(MP_TRACE, "[%p] <--- HWBeginReceiveDma Status 0x%08x\n", Adapter, Status);
return Status;
}
| 14,321 |
662 |
<reponame>magicboylinw/autobahn-java
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJava - http://crossbar.io/autobahn
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
package io.crossbar.autobahn.websocket.interfaces;
public interface IThreadMessenger {
void notify(Object message);
void postDelayed(Runnable runnable, long delayMillis);
void setOnMessageListener(OnMessageListener listener);
void cleanup();
interface OnMessageListener {
void onMessage(Object message);
}
}
| 215 |
3,301 |
<reponame>vacaly/Alink
package com.alibaba.alink.params.dataproc.format;
import com.alibaba.alink.params.io.HasQuoteCharDefaultAsDoubleQuote;
import com.alibaba.alink.params.io.HasSchemaStr;
public interface FromCsvParams<T> extends
HasCsvCol <T>,
HasSchemaStr <T>,
HasCsvFieldDelimiterDefaultAsComma <T>,
HasQuoteCharDefaultAsDoubleQuote <T> {
}
| 133 |
2,151 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.wifi;
import android.app.backup.BackupManager;
/**
* Wrapper around BackupManager, to allow use of mock during unit test.
*/
public class BackupManagerProxy {
/**
* Notify BackupManager of dataChanged event.
* Hardcode to use SettingsProvider package for backup.
*/
public void notifyDataChanged() {
BackupManager.dataChanged("com.android.providers.settings");
}
}
| 297 |
410 |
// Copyright(c) 2017 POLYGONTEK
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http ://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "Event.h"
#include "SignalObject.h"
BE_NAMESPACE_BEGIN
class SignalObject;
class BE_API SignalDef {
public:
static constexpr int MaxSignalDefs = 4096;
explicit SignalDef(const char *name, const char *formatSpec = nullptr, char returnType = 0);
/// Prevents copy constructor.
SignalDef(const SignalDef &rhs) = delete;
/// Prevents assignment operator.
SignalDef & operator=(const SignalDef &rhs) = delete;
const char * GetName() const { return name; }
const char * GetArgFormat() const { return formatSpec; }
char GetReturnType() const { return returnType; }
int GetSignalNum() const { return signalNum; }
int GetNumArgs() const { return numArgs; }
unsigned int GetFormatSpecBits() const { return formatSpecBits; }
size_t GetArgSize() const { return argSize; }
int GetArgOffset(int arg) const { assert((arg >= 0) && (arg < EventDef::MaxArgs)); return argOffset[arg]; }
static int NumSignals() { return numSignalDefs; }
static const SignalDef *GetSignal(int signalNum) { return signalDefs[signalNum]; }
static const SignalDef *FindSignal(const char *name);
private:
const char * name;
const char * formatSpec;
unsigned int formatSpecBits;
int returnType;
int numArgs;
size_t argSize;
int argOffset[EventDef::MaxArgs];
int signalNum;
static SignalDef * signalDefs[MaxSignalDefs];
static int numSignalDefs;
};
class BE_API Signal {
friend class SignalSystem;
public:
~Signal();
byte * GetData() { return data; }
private:
const SignalDef * signalDef;
byte * data;
SignalObject * receiver;
SignalCallback callback;
LinkList<Signal> node;
};
class BE_API SignalSystem {
public:
static constexpr int MaxSignals = 8192;
static void Init();
static void Shutdown();
static void Clear();
/// Create a new signal with the given signal def and arguments.
static Signal * AllocSignal(const SignalDef *signalDef, const SignalCallback callback, int numArgs, va_list args);
static void FreeSignal(Signal *signal);
static void CopyArgPtrs(const SignalDef *signalDef, int numArgs, va_list args, intptr_t data[EventDef::MaxArgs]);
static void ScheduleSignal(Signal *signal, SignalObject *receiver);
static void CancelSignal(const SignalObject *receiver, const SignalDef *signalDef = nullptr);
static void ServiceSignal(Signal *signal);
static void ServiceSignals();
static bool initialized;
private:
static Signal signalPool[MaxSignals];
static LinkList<Signal> freeSignals;
static LinkList<Signal> signalQueue;
};
BE_NAMESPACE_END
| 1,611 |
2,449 |
package com.pinterest.deployservice.db;
import com.pinterest.deployservice.bean.DeployConstraintBean;
import com.pinterest.deployservice.bean.SetClause;
import com.pinterest.deployservice.bean.TagSyncState;
import com.pinterest.deployservice.bean.UpdateStatement;
import com.pinterest.deployservice.dao.DeployConstraintDAO;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.util.List;
public class DBDeployConstraintDAOImpl implements DeployConstraintDAO {
private static final String INSERT_CONSTRAINT_TEMPLATE = "INSERT INTO deploy_constraints SET %s";
private static final String UPDATE_CONSTRAINT_TEMPLATE = "UPDATE deploy_constraints SET %s WHERE constraint_id=?";
private static final String GET_CONSTRAINT_BY_ID = "SELECT * FROM deploy_constraints WHERE constraint_id = ?";
private static final String REMOVE_CONSTRAINT_BY_ID = "DELETE FROM deploy_constraints WHERE constraint_id = ?";
private static final String GET_ALL_ACTIVE = "SELECT * FROM deploy_constraints WHERE state != ?";
private BasicDataSource dataSource;
public DBDeployConstraintDAOImpl(BasicDataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public DeployConstraintBean getById(String constraintId) throws Exception {
ResultSetHandler<DeployConstraintBean> h = new BeanHandler<>(DeployConstraintBean.class);
return new QueryRunner(dataSource).query(GET_CONSTRAINT_BY_ID, h, constraintId);
}
@Override
public void updateById(String constraintId, DeployConstraintBean deployConstraintBean) throws Exception {
SetClause setClause = deployConstraintBean.genSetClause();
String clause = String.format(UPDATE_CONSTRAINT_TEMPLATE, setClause.getClause());
setClause.addValue(constraintId);
new QueryRunner(dataSource).update(clause, setClause.getValueArray());
}
@Override
public UpdateStatement genInsertStatement(DeployConstraintBean deployConstraintBean) {
SetClause setClause = deployConstraintBean.genSetClause();
String clause = String.format(INSERT_CONSTRAINT_TEMPLATE, setClause.getClause());
return new UpdateStatement(clause, setClause.getValueArray());
}
@Override
public UpdateStatement genUpdateStatement(String constraintId, DeployConstraintBean deployConstraintBean) {
SetClause setClause = deployConstraintBean.genSetClause();
String clause = String.format(UPDATE_CONSTRAINT_TEMPLATE, setClause.getClause());
setClause.addValue(constraintId);
return new UpdateStatement(clause, setClause.getValueArray());
}
@Override
public void delete(String constraintId) throws Exception {
new QueryRunner(dataSource).update(REMOVE_CONSTRAINT_BY_ID, constraintId);
}
@Override
public List<DeployConstraintBean> getAllActiveDeployConstraint() throws Exception {
ResultSetHandler<List<DeployConstraintBean>> h = new BeanListHandler<DeployConstraintBean>(DeployConstraintBean.class);
return new QueryRunner(dataSource).query(GET_ALL_ACTIVE, h, TagSyncState.ERROR.toString());
}
}
| 1,150 |
7,409 |
<gh_stars>1000+
# Generated by Django 3.2.5 on 2021-11-29 14:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("posthog", "0183_groups_pg"),
]
operations = [
migrations.DeleteModel(name="SessionsFilter",),
]
| 115 |
8,805 |
// Copyright 2005 The Trustees of Indiana University.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Authors: <NAME>
// <NAME>
#ifndef BOOST_GRAPH_PARALLEL_INPLACE_ALL_TO_ALL_HPP
#define BOOST_GRAPH_PARALLEL_INPLACE_ALL_TO_ALL_HPP
#ifndef BOOST_GRAPH_USE_MPI
#error "Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included"
#endif
//
// Implements the inplace all-to-all communication algorithm.
//
#include <vector>
#include <iterator>
namespace boost { namespace parallel {
template<typename ProcessGroup, typename T>
// where {LinearProcessGroup<ProcessGroup>, MessagingProcessGroup<ProcessGroup>}
void
inplace_all_to_all(ProcessGroup pg,
const std::vector<std::vector<T> >& outgoing,
std::vector<std::vector<T> >& incoming)
{
typedef typename std::vector<T>::size_type size_type;
typedef typename ProcessGroup::process_size_type process_size_type;
typedef typename ProcessGroup::process_id_type process_id_type;
process_size_type p = num_processes(pg);
// Make sure there are no straggling messages
synchronize(pg);
// Send along the count (always) and the data (if count > 0)
for (process_id_type dest = 0; dest < p; ++dest) {
if (dest != process_id(pg)) {
send(pg, dest, 0, outgoing[dest].size());
if (!outgoing[dest].empty())
send(pg, dest, 1, &outgoing[dest].front(), outgoing[dest].size());
}
}
// Make sure all of the data gets transferred
synchronize(pg);
// Receive the sizes and data
for (process_id_type source = 0; source < p; ++source) {
if (source != process_id(pg)) {
size_type size;
receive(pg, source, 0, size);
incoming[source].resize(size);
if (size > 0)
receive(pg, source, 1, &incoming[source].front(), size);
} else if (&incoming != &outgoing) {
incoming[source] = outgoing[source];
}
}
}
template<typename ProcessGroup, typename T>
// where {LinearProcessGroup<ProcessGroup>, MessagingProcessGroup<ProcessGroup>}
void
inplace_all_to_all(ProcessGroup pg, std::vector<std::vector<T> >& data)
{
inplace_all_to_all(pg, data, data);
}
} } // end namespace boost::parallel
#endif // BOOST_GRAPH_PARALLEL_INPLACE_ALL_TO_ALL_HPP
| 984 |
2,236 |
<filename>solution/greedy/1931/main.py
# Authored by : gusdn3477
# Co-authored by : -
# Link : http://boj.kr/7150be3ff485402ebb4c5011fa88ac7d
import sys
def input():
return sys.stdin.readline().rstrip()
N = int(input())
arr = []
total = 1
for i in range(N):
a,b = map(int, input().split())
arr.append((a,b))
arr.sort(key = lambda x : (x[1],x[0]))
end_time = arr[0][1]
for i in range(1,N):
if arr[i][0] >= end_time:
end_time = arr[i][1]
total += 1
print(total)
| 234 |
335 |
<filename>K/Kumquat_noun.json
{
"word": "Kumquat",
"definitions": [
"An orange-like fruit related to the citruses, with an edible sweet rind and acid pulp.",
"The East Asian shrub or small tree that yields the kumquat."
],
"parts-of-speech": "Noun"
}
| 116 |
937 |
<gh_stars>100-1000
package com.oath.cyclops.util.function;
import static cyclops.function.Predicates.anyOf;
import static cyclops.function.Predicates.eq;
import static cyclops.function.Predicates.eqv;
import static cyclops.function.Predicates.eqv2;
import static cyclops.function.Predicates.greaterThan;
import static cyclops.function.Predicates.greaterThanOrEquals;
import static cyclops.function.Predicates.in;
import static cyclops.function.Predicates.lessThan;
import static cyclops.function.Predicates.lessThanOrEquals;
import static cyclops.function.Predicates.not;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import cyclops.control.Eval;
import cyclops.function.Predicates;
import org.junit.Test;
import cyclops.control.Maybe;
import cyclops.reactive.ReactiveSeq;
public class PredicatesTest {
@Test
public void testSampleTime(){
assertThat(Stream.of(1,2,3,4).filter(Predicates.sample(1, TimeUnit.MILLISECONDS)).collect(Collectors.toList()).size(),equalTo(1));
assertThat(Stream.of(1,2,3,4).filter(Predicates.sample(1, TimeUnit.NANOSECONDS)).collect(Collectors.toList()).size(),equalTo(4));
}
@Test
public void testSample(){
assertThat(Stream.of(1,2,3,4).filter(Predicates.sample(2)).collect(Collectors.toList()).size(),equalTo(2));
assertThat(Stream.of(1,2,3,4).filter(Predicates.sample(4)).collect(Collectors.toList()).size(),equalTo(1));
}
@Test
public void testFilter(){
ReactiveSeq.of(1,2,3).filter(anyOf(not(in(2,3,4)),in(1,10,20)));
ReactiveSeq.of(1,2,3).filter(anyOf(not(greaterThan(2)),in(1,10,20)));
ReactiveSeq.of(1,2,3).filter(anyOf(not(greaterThanOrEquals(2)),in(1,10,20)));
ReactiveSeq.of(1,2,3).filter(anyOf(not(lessThan(2)),in(1,10,20)));
ReactiveSeq.of(1,2,3).filter(anyOf(not(lessThanOrEquals(2)),in(1,10,20)));
ReactiveSeq.of(1,2,3).filter(anyOf(not(eq(2)),in(1,10,20)));
Stream.of(Maybe.of(2)).filter(eqv(Eval.now(2)));
}
@Test
public void testEqv() {
assertThat(Stream.of(Maybe.of(2)).filter(eqv(Eval.now(2))).collect(Collectors.toList()).get(0),equalTo(Maybe.of(2)));
}
@Test
public void testEqvFalse() {
assertThat(Stream.of(Maybe.of(3)).filter(eqv(Maybe.of(2))).collect(Collectors.toList()).size(),equalTo(0));
}
@Test
public void testEqvNonValue() {
assertThat(Stream.of(2).filter(eqv2(Maybe.of(2))).collect(Collectors.toList()).get(0),equalTo(2));
}
@Test
public void testEqvNone() {
assertTrue(eqv(Maybe.nothing()).test(null));
}
@Test
public void testEqvNull() {
assertTrue(eqv(null).test(null));
}
@Test
public void hasItems(){
assertTrue(Predicates.hasItems(Arrays.asList(1,2,3)).test(Arrays.asList(10,1,23,2,3,4,5,6)));
}
@Test
public void startsWith(){
assertFalse(Predicates.startsWith(1,2,3).test(Arrays.asList(10,1,23,2,3,4,5,6)));
}
@Test
public void endsWith(){
assertFalse(Predicates.startsWith(1,2,3).test(Arrays.asList(10,1,23,2,3,4,5,6)));
}
@Test
public void startsWithTrue(){
assertTrue(Predicates.startsWith(1,2,3).test(Arrays.asList(1,2,3,10,1,23,2,3,4,5,6)));
}
@Test
public void endsWithTrue(){
assertTrue(Predicates.endsWith(1,2,3).test(Arrays.asList(10,1,23,2,3,4,5,6,1,2,3)));
}
}
| 1,583 |
1,176 |
<gh_stars>1000+
// Copyright 2017 <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.
// Precompiled header file
#include "stdafx.h"
#define LUM_AND_BRIGHT_THREADS 8u
#define ADD_THREADS_X 64u
#define ADD_THREADS_Y 2u
namespace Intrinsic
{
namespace Renderer
{
namespace RenderPass
{
struct PerInstanceDataLumBright
{
uint32_t dim[4];
glm::vec4 bloomThreshold;
};
struct PerInstanceDataAvgLum
{
uint32_t dim[4];
glm::vec4 data;
};
struct PerInstanceDataAdd
{
uint32_t dim[4];
uint32_t mipLevel[4];
};
namespace
{
ImageRef _lumImageRef;
ImageRef _blurPingPongImageRef;
ImageRef _blurImageRef;
ImageRef _summedImageRef;
ImageRef _brightImageRef;
PipelineRef _brightLumPipelineRef;
PipelineRef _avgLumPipelineRef;
PipelineRef _blurXPipelineRef;
PipelineRef _blurYPipelineRef;
PipelineRef _addPipelineRef;
ComputeCallRef _lumComputeCallRef;
ComputeCallRef _avgLumComputeCallRef;
ComputeCallRefArray _blurXComputeCallRefs;
ComputeCallRefArray _blurYComputeCallRefs;
ComputeCallRefArray _addComputeCallRefs;
BufferRef _lumBuffer;
bool _initAvgLum = true;
_INTR_INLINE glm::uvec2 calcBloomBaseDim()
{
return glm::uvec2(RenderSystem::_backbufferDimensions.x / 2u,
RenderSystem::_backbufferDimensions.y / 2u);
}
_INTR_INLINE void dispatchLum(VkCommandBuffer p_CommandBuffer)
{
const glm::uvec2 bloomBaseDim = calcBloomBaseDim();
PerInstanceDataLumBright lumData = {};
{
lumData.dim[0] = bloomBaseDim.x;
lumData.dim[1] = bloomBaseDim.y;
lumData.bloomThreshold.x = 0.9f;
}
ComputeCallManager::updateUniformMemory({_lumComputeCallRef}, &lumData,
sizeof(PerInstanceDataLumBright));
RenderSystem::dispatchComputeCall(_lumComputeCallRef, p_CommandBuffer);
ImageManager::insertImageMemoryBarrier(
_brightImageRef, VK_IMAGE_LAYOUT_GENERAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
}
// <-
_INTR_INLINE void dispatchAvgLum(VkCommandBuffer p_CommandBuffer)
{
const glm::uvec2 bloomBaseDim = calcBloomBaseDim();
PerInstanceDataAvgLum avgLumData = {};
{
avgLumData.dim[0] = Bloom::calculateThreadGroups(bloomBaseDim.x / 2u,
LUM_AND_BRIGHT_THREADS);
avgLumData.dim[1] = Bloom::calculateThreadGroups(bloomBaseDim.y / 2u,
LUM_AND_BRIGHT_THREADS);
if (_initAvgLum)
{
avgLumData.data.y = 1.0f;
_initAvgLum = false;
}
else
{
avgLumData.data.y = 0.0f;
}
avgLumData.data.x = TaskManager::_lastDeltaT;
}
ComputeCallManager::updateUniformMemory({_avgLumComputeCallRef}, &avgLumData,
sizeof(PerInstanceDataAvgLum));
RenderSystem::dispatchComputeCall(_avgLumComputeCallRef, p_CommandBuffer);
BufferManager::insertBufferMemoryBarrier(
_lumBuffer, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
}
// <-
_INTR_INLINE void dispatchBlur(VkCommandBuffer p_CommandBuffer,
uint32_t p_MipLevel0)
{
PerInstanceDataBlur blurData = {};
{
blurData.mipLevel[0] = p_MipLevel0;
}
ComputeCallManager::updateUniformMemory({_blurXComputeCallRefs[p_MipLevel0]},
&blurData,
sizeof(PerInstanceDataBlur));
ImageManager::insertImageMemoryBarrierSubResource(
_blurPingPongImageRef, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_IMAGE_LAYOUT_GENERAL, p_MipLevel0, 0u,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
RenderSystem::dispatchComputeCall(_blurXComputeCallRefs[p_MipLevel0],
p_CommandBuffer);
ImageManager::insertImageMemoryBarrierSubResource(
_blurPingPongImageRef, VK_IMAGE_LAYOUT_GENERAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, p_MipLevel0, 0u,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
ComputeCallManager::updateUniformMemory({_blurYComputeCallRefs[p_MipLevel0]},
&blurData,
sizeof(PerInstanceDataBlur));
ImageManager::insertImageMemoryBarrierSubResource(
_blurImageRef, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_IMAGE_LAYOUT_GENERAL, p_MipLevel0, 0u,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
RenderSystem::dispatchComputeCall(_blurYComputeCallRefs[p_MipLevel0],
p_CommandBuffer);
ImageManager::insertImageMemoryBarrierSubResource(
_blurImageRef, VK_IMAGE_LAYOUT_GENERAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, p_MipLevel0, 0u,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
}
// <-
_INTR_INLINE void dispatchAdd(VkCommandBuffer p_CommandBuffer,
uint32_t p_MipLevel0, uint32_t p_MipLevel1)
{
const glm::uvec2 bloomBaseDim = calcBloomBaseDim();
PerInstanceDataAdd addData = {};
{
addData.mipLevel[0] = p_MipLevel0;
addData.mipLevel[1] = p_MipLevel1;
addData.dim[0] = (bloomBaseDim.x * 2u) >> (p_MipLevel0 + 1);
addData.dim[1] = (bloomBaseDim.y * 2u) >> (p_MipLevel0 + 1);
}
ComputeCallManager::updateUniformMemory({_addComputeCallRefs[p_MipLevel0]},
&addData, sizeof(PerInstanceDataAdd));
ImageManager::insertImageMemoryBarrierSubResource(
_summedImageRef, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_IMAGE_LAYOUT_GENERAL, p_MipLevel0, 0u,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
RenderSystem::dispatchComputeCall(_addComputeCallRefs[p_MipLevel0],
p_CommandBuffer);
ImageManager::insertImageMemoryBarrierSubResource(
_summedImageRef, VK_IMAGE_LAYOUT_GENERAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, p_MipLevel0, 0u,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
}
}
// <-
void Bloom::init()
{
PipelineRefArray pipelinesToCreate;
BufferRefArray buffersToCreate;
PipelineLayoutRefArray pipelineLayoutsToCreate;
// Buffers
{
_lumBuffer = BufferManager::createBuffer(_N(BloomLumBuffer));
{
BufferManager::resetToDefault(_lumBuffer);
BufferManager::addResourceFlags(
_lumBuffer, Dod::Resources::ResourceFlags::kResourceVolatile);
BufferManager::_descBufferType(_lumBuffer) = BufferType::kStorage;
BufferManager::_descSizeInBytes(_lumBuffer) = sizeof(float);
}
buffersToCreate.push_back(_lumBuffer);
}
BufferManager::createResources(buffersToCreate);
// Pipeline layouts
PipelineLayoutRef pipelineLayoutLumBright;
{
pipelineLayoutLumBright =
PipelineLayoutManager::createPipelineLayout(_N(BloomLumBright));
PipelineLayoutManager::resetToDefault(pipelineLayoutLumBright);
GpuProgramManager::reflectPipelineLayout(
32u,
{GpuProgramManager::getResourceByName("post_bloom_bright_lum.comp")},
pipelineLayoutLumBright);
}
pipelineLayoutsToCreate.push_back(pipelineLayoutLumBright);
PipelineLayoutRef pipelineLayoutAvgLum;
{
pipelineLayoutAvgLum =
PipelineLayoutManager::createPipelineLayout(_N(BloomAvgLum));
PipelineLayoutManager::resetToDefault(pipelineLayoutAvgLum);
GpuProgramManager::reflectPipelineLayout(
32u, {GpuProgramManager::getResourceByName("post_bloom_avg_lum.comp")},
pipelineLayoutAvgLum);
}
pipelineLayoutsToCreate.push_back(pipelineLayoutAvgLum);
PipelineLayoutRef pipelineLayoutAdd;
{
pipelineLayoutAdd =
PipelineLayoutManager::createPipelineLayout(_N(BloomAdd));
PipelineLayoutManager::resetToDefault(pipelineLayoutAdd);
GpuProgramManager::reflectPipelineLayout(
32u, {GpuProgramManager::getResourceByName("post_bloom_add.comp")},
pipelineLayoutAdd);
}
pipelineLayoutsToCreate.push_back(pipelineLayoutAdd);
PipelineLayoutRef pipelineLayoutBlur;
{
pipelineLayoutBlur =
PipelineLayoutManager::createPipelineLayout(_N(BloomBlur));
PipelineLayoutManager::resetToDefault(pipelineLayoutBlur);
GpuProgramManager::reflectPipelineLayout(
128u, {GpuProgramManager::getResourceByName("post_bloom_blur_x.comp")},
pipelineLayoutBlur);
}
pipelineLayoutsToCreate.push_back(pipelineLayoutBlur);
PipelineLayoutManager::createResources(pipelineLayoutsToCreate);
// Pipelines
{
_brightLumPipelineRef = PipelineManager::createPipeline(_N(BloomBrightLum));
PipelineManager::resetToDefault(_brightLumPipelineRef);
PipelineManager::_descComputeProgram(_brightLumPipelineRef) =
GpuProgramManager::getResourceByName("post_bloom_bright_lum.comp");
PipelineManager::_descPipelineLayout(_brightLumPipelineRef) =
pipelineLayoutLumBright;
}
pipelinesToCreate.push_back(_brightLumPipelineRef);
{
_avgLumPipelineRef = PipelineManager::createPipeline(_N(BloomAvgLum));
PipelineManager::resetToDefault(_avgLumPipelineRef);
PipelineManager::_descComputeProgram(_avgLumPipelineRef) =
GpuProgramManager::getResourceByName("post_bloom_avg_lum.comp");
PipelineManager::_descPipelineLayout(_avgLumPipelineRef) =
pipelineLayoutAvgLum;
}
pipelinesToCreate.push_back(_avgLumPipelineRef);
{
_addPipelineRef = PipelineManager::createPipeline(_N(BloomAdd));
PipelineManager::resetToDefault(_addPipelineRef);
PipelineManager::_descComputeProgram(_addPipelineRef) =
GpuProgramManager::getResourceByName("post_bloom_add.comp");
PipelineManager::_descPipelineLayout(_addPipelineRef) = pipelineLayoutAdd;
}
pipelinesToCreate.push_back(_addPipelineRef);
{
_blurXPipelineRef = PipelineManager::createPipeline(_N(BloomBlurX));
PipelineManager::resetToDefault(_blurXPipelineRef);
PipelineManager::_descComputeProgram(_blurXPipelineRef) =
GpuProgramManager::getResourceByName("post_bloom_blur_x.comp");
PipelineManager::_descPipelineLayout(_blurXPipelineRef) =
pipelineLayoutBlur;
}
pipelinesToCreate.push_back(_blurXPipelineRef);
{
_blurYPipelineRef = PipelineManager::createPipeline(_N(BloomBlurY));
PipelineManager::resetToDefault(_blurYPipelineRef);
PipelineManager::_descComputeProgram(_blurYPipelineRef) =
GpuProgramManager::getResourceByName("post_bloom_blur_y.comp");
PipelineManager::_descPipelineLayout(_blurYPipelineRef) =
pipelineLayoutBlur;
}
pipelinesToCreate.push_back(_blurYPipelineRef);
PipelineManager::createResources(pipelinesToCreate);
}
// <-
void Bloom::onReinitRendering()
{
ImageRefArray imgsToDestroy;
ImageRefArray imgsToCreate;
ComputeCallRefArray computeCallsToDestroy;
ComputeCallRefArray computeCallsToCreate;
// Cleanup old resources
{
if (_lumImageRef.isValid())
imgsToDestroy.push_back(_lumImageRef);
if (_blurImageRef.isValid())
imgsToDestroy.push_back(_blurImageRef);
if (_blurPingPongImageRef.isValid())
imgsToDestroy.push_back(_blurPingPongImageRef);
if (_summedImageRef.isValid())
imgsToDestroy.push_back(_summedImageRef);
if (_brightImageRef.isValid())
imgsToDestroy.push_back(_brightImageRef);
ImageManager::destroyImagesAndResources(imgsToDestroy);
}
// Compute Calls
if (_lumComputeCallRef.isValid())
{
computeCallsToDestroy.push_back(_lumComputeCallRef);
}
if (!_addComputeCallRefs.empty())
{
for (uint32_t i = 0u; i < _addComputeCallRefs.size(); ++i)
{
computeCallsToDestroy.push_back(_addComputeCallRefs[i]);
}
_addComputeCallRefs.clear();
}
if (_avgLumComputeCallRef.isValid())
{
computeCallsToDestroy.push_back(_avgLumComputeCallRef);
}
if (!_blurXComputeCallRefs.empty())
{
for (uint32_t i = 0u; i < _blurXComputeCallRefs.size(); ++i)
{
computeCallsToDestroy.push_back(_blurXComputeCallRefs[i]);
}
_blurXComputeCallRefs.clear();
}
if (!_blurYComputeCallRefs.empty())
{
for (uint32_t i = 0u; i < _blurYComputeCallRefs.size(); ++i)
{
computeCallsToDestroy.push_back(_blurYComputeCallRefs[i]);
}
_blurYComputeCallRefs.clear();
}
ComputeCallManager::destroyResources(computeCallsToDestroy);
for (uint32_t i = 0u; i < (uint32_t)computeCallsToDestroy.size(); ++i)
{
ComputeCallManager::destroyComputeCall(computeCallsToDestroy[i]);
}
// Images
glm::uvec3 dim = glm::uvec3(calcBloomBaseDim(), 1u);
_lumImageRef = ImageManager::createImage(_N(BloomLum));
{
ImageManager::resetToDefault(_lumImageRef);
ImageManager::addResourceFlags(
_lumImageRef, Dod::Resources::ResourceFlags::kResourceVolatile);
ImageManager::_descMemoryPoolType(_lumImageRef) =
MemoryPoolType::kResolutionDependentImages;
ImageManager::_descDimensions(_lumImageRef) = glm::uvec3(
calculateThreadGroups(dim.x / 2u, LUM_AND_BRIGHT_THREADS),
calculateThreadGroups(dim.y / 2u, LUM_AND_BRIGHT_THREADS), 1u);
ImageManager::_descImageFormat(_lumImageRef) = Format::kR32SFloat;
ImageManager::_descImageType(_lumImageRef) = ImageType::kTexture;
ImageManager::_descImageFlags(_lumImageRef) &=
~ImageFlags::kUsageAttachment;
ImageManager::_descImageFlags(_lumImageRef) |= ImageFlags::kUsageStorage;
}
imgsToCreate.push_back(_lumImageRef);
_blurImageRef = ImageManager::createImage(_N(BloomBlur));
{
ImageManager::resetToDefault(_blurImageRef);
ImageManager::addResourceFlags(
_blurImageRef, Dod::Resources::ResourceFlags::kResourceVolatile);
ImageManager::_descMemoryPoolType(_blurImageRef) =
MemoryPoolType::kResolutionDependentImages;
ImageManager::_descDimensions(_blurImageRef) = dim;
ImageManager::_descImageFormat(_blurImageRef) = Format::kR16G16B16A16Float;
ImageManager::_descImageType(_blurImageRef) = ImageType::kTexture;
ImageManager::_descMipLevelCount(_blurImageRef) = 4u;
ImageManager::_descImageFlags(_blurImageRef) &=
~ImageFlags::kUsageAttachment;
ImageManager::_descImageFlags(_blurImageRef) |= ImageFlags::kUsageStorage;
}
imgsToCreate.push_back(_blurImageRef);
_blurPingPongImageRef = ImageManager::createImage(_N(BloomBlurPingPong));
{
ImageManager::resetToDefault(_blurPingPongImageRef);
ImageManager::addResourceFlags(
_blurPingPongImageRef,
Dod::Resources::ResourceFlags::kResourceVolatile);
ImageManager::_descMemoryPoolType(_blurPingPongImageRef) =
MemoryPoolType::kResolutionDependentImages;
ImageManager::_descDimensions(_blurPingPongImageRef) = dim;
ImageManager::_descImageFormat(_blurPingPongImageRef) =
Format::kR16G16B16A16Float;
ImageManager::_descImageType(_blurPingPongImageRef) = ImageType::kTexture;
ImageManager::_descMipLevelCount(_blurPingPongImageRef) = 4u;
ImageManager::_descImageFlags(_blurPingPongImageRef) &=
~ImageFlags::kUsageAttachment;
ImageManager::_descImageFlags(_blurPingPongImageRef) |=
ImageFlags::kUsageStorage;
}
imgsToCreate.push_back(_blurPingPongImageRef);
_summedImageRef = ImageManager::createImage(_N(BloomSummed));
{
ImageManager::resetToDefault(_summedImageRef);
ImageManager::addResourceFlags(
_summedImageRef, Dod::Resources::ResourceFlags::kResourceVolatile);
ImageManager::_descMemoryPoolType(_summedImageRef) =
MemoryPoolType::kResolutionDependentImages;
ImageManager::_descDimensions(_summedImageRef) = dim;
ImageManager::_descImageFormat(_summedImageRef) =
Format::kR16G16B16A16Float;
ImageManager::_descImageType(_summedImageRef) = ImageType::kTexture;
ImageManager::_descMipLevelCount(_summedImageRef) = 4u;
ImageManager::_descImageFlags(_summedImageRef) &=
~ImageFlags::kUsageAttachment;
ImageManager::_descImageFlags(_summedImageRef) |= ImageFlags::kUsageStorage;
}
imgsToCreate.push_back(_summedImageRef);
_brightImageRef = ImageManager::createImage(_N(BloomBright));
{
ImageManager::resetToDefault(_brightImageRef);
ImageManager::addResourceFlags(
_brightImageRef, Dod::Resources::ResourceFlags::kResourceVolatile);
ImageManager::_descMemoryPoolType(_brightImageRef) =
MemoryPoolType::kResolutionDependentImages;
ImageManager::_descDimensions(_brightImageRef) = dim;
ImageManager::_descImageFormat(_brightImageRef) =
Format::kR16G16B16A16Float;
ImageManager::_descImageType(_brightImageRef) = ImageType::kTexture;
ImageManager::_descMipLevelCount(_brightImageRef) = 4u;
ImageManager::_descImageFlags(_brightImageRef) &=
~ImageFlags::kUsageAttachment;
ImageManager::_descImageFlags(_brightImageRef) |= ImageFlags::kUsageStorage;
}
imgsToCreate.push_back(_brightImageRef);
ImageManager::createResources(imgsToCreate);
// Compute calls
_lumComputeCallRef =
ComputeCallManager::createComputeCall(_N(BloomBrightLum));
{
ComputeCallManager::resetToDefault(_lumComputeCallRef);
ComputeCallManager::addResourceFlags(
_lumComputeCallRef, Dod::Resources::ResourceFlags::kResourceVolatile);
ComputeCallManager::_descPipeline(_lumComputeCallRef) =
_brightLumPipelineRef;
ComputeCallManager::_descDimensions(_lumComputeCallRef) =
glm::vec3(calculateThreadGroups(dim.x / 2u, LUM_AND_BRIGHT_THREADS),
calculateThreadGroups(dim.y / 2u, LUM_AND_BRIGHT_THREADS), 1);
ComputeCallManager::bindBuffer(
_lumComputeCallRef, _N(PerInstance), GpuProgramType::kCompute,
UniformManager::_perInstanceUniformBuffer, UboType::kPerInstanceCompute,
sizeof(PerInstanceDataLumBright));
ComputeCallManager::bindImage(_lumComputeCallRef, _N(output0Tex),
GpuProgramType::kCompute, _brightImageRef,
Samplers::kLinearRepeat,
BindingFlags::kAdressSubResource, 0u, 0u);
ComputeCallManager::bindImage(_lumComputeCallRef, _N(output1Tex),
GpuProgramType::kCompute, _brightImageRef,
Samplers::kLinearRepeat,
BindingFlags::kAdressSubResource, 0u, 1u);
ComputeCallManager::bindImage(_lumComputeCallRef, _N(output2Tex),
GpuProgramType::kCompute, _brightImageRef,
Samplers::kLinearRepeat,
BindingFlags::kAdressSubResource, 0u, 2u);
ComputeCallManager::bindImage(_lumComputeCallRef, _N(output3Tex),
GpuProgramType::kCompute, _brightImageRef,
Samplers::kLinearRepeat,
BindingFlags::kAdressSubResource, 0u, 3u);
ComputeCallManager::bindImage(_lumComputeCallRef, _N(outputLumTex),
GpuProgramType::kCompute, _lumImageRef,
Samplers::kLinearRepeat);
ComputeCallManager::bindImage(
_lumComputeCallRef, _N(input0Tex), GpuProgramType::kCompute,
ImageManager::getResourceByName(_N(Scene)), Samplers::kLinearRepeat);
computeCallsToCreate.push_back(_lumComputeCallRef);
}
_avgLumComputeCallRef =
ComputeCallManager::createComputeCall(_N(BloomAvgLum));
{
ComputeCallManager::resetToDefault(_avgLumComputeCallRef);
ComputeCallManager::addResourceFlags(
_avgLumComputeCallRef,
Dod::Resources::ResourceFlags::kResourceVolatile);
ComputeCallManager::_descPipeline(_avgLumComputeCallRef) =
_avgLumPipelineRef;
ComputeCallManager::bindBuffer(
_avgLumComputeCallRef, _N(PerInstance), GpuProgramType::kCompute,
UniformManager::_perInstanceUniformBuffer, UboType::kPerInstanceCompute,
sizeof(PerInstanceDataAvgLum));
ComputeCallManager::bindImage(_avgLumComputeCallRef, _N(inOutLumTex),
GpuProgramType::kCompute, _lumImageRef,
Samplers::kInvalidSampler);
ComputeCallManager::bindBuffer(_avgLumComputeCallRef, _N(AvgLum),
GpuProgramType::kCompute, _lumBuffer,
UboType::kInvalidUbo, sizeof(float));
computeCallsToCreate.push_back(_avgLumComputeCallRef);
}
for (uint32_t i = 0; i < 4u; ++i)
{
ComputeCallRef computeCallBlurXRef =
ComputeCallManager::createComputeCall(_N(BloomBlurX));
{
ComputeCallManager::resetToDefault(computeCallBlurXRef);
ComputeCallManager::addResourceFlags(
computeCallBlurXRef,
Dod::Resources::ResourceFlags::kResourceVolatile);
ComputeCallManager::_descPipeline(computeCallBlurXRef) =
_blurXPipelineRef;
ComputeCallManager::_descDimensions(computeCallBlurXRef) =
glm::vec3(calculateThreadGroups(
dim.x >> i, BLUR_THREADS - 2u * BLUR_HALF_BLUR_WIDTH),
dim.y >> i, 1);
ComputeCallManager::bindBuffer(
computeCallBlurXRef, _N(PerInstance), GpuProgramType::kCompute,
UniformManager::_perInstanceUniformBuffer,
UboType::kPerInstanceCompute, sizeof(PerInstanceDataBlur));
ComputeCallManager::bindImage(
computeCallBlurXRef, _N(outTex), GpuProgramType::kCompute,
_blurPingPongImageRef, Samplers::kInvalidSampler,
BindingFlags::kAdressSubResource, 0u, i);
if (i == 3u)
{
ComputeCallManager::bindImage(computeCallBlurXRef, _N(inTex),
GpuProgramType::kCompute, _brightImageRef,
Samplers::kLinearClamp);
}
else
{
ComputeCallManager::bindImage(computeCallBlurXRef, _N(inTex),
GpuProgramType::kCompute, _summedImageRef,
Samplers::kLinearClamp);
}
computeCallsToCreate.push_back(computeCallBlurXRef);
_blurXComputeCallRefs.push_back(computeCallBlurXRef);
ComputeCallRef computeCallBlurYRef =
ComputeCallManager::createComputeCall(_N(BloomBlurY));
{
ComputeCallManager::resetToDefault(computeCallBlurYRef);
ComputeCallManager::addResourceFlags(
computeCallBlurYRef,
Dod::Resources::ResourceFlags::kResourceVolatile);
ComputeCallManager::_descPipeline(computeCallBlurYRef) =
_blurYPipelineRef;
ComputeCallManager::_descDimensions(computeCallBlurYRef) =
glm::vec3(calculateThreadGroups(
dim.y >> i, BLUR_THREADS - 2u * BLUR_HALF_BLUR_WIDTH),
dim.x >> i, 1);
ComputeCallManager::bindBuffer(
computeCallBlurYRef, _N(PerInstance), GpuProgramType::kCompute,
UniformManager::_perInstanceUniformBuffer,
UboType::kPerInstanceCompute, sizeof(PerInstanceDataBlur));
ComputeCallManager::bindImage(computeCallBlurYRef, _N(outTex),
GpuProgramType::kCompute, _blurImageRef,
Samplers::kInvalidSampler,
BindingFlags::kAdressSubResource, 0u, i);
ComputeCallManager::bindImage(
computeCallBlurYRef, _N(inTex), GpuProgramType::kCompute,
_blurPingPongImageRef, Samplers::kLinearClamp);
computeCallsToCreate.push_back(computeCallBlurYRef);
_blurYComputeCallRefs.push_back(computeCallBlurYRef);
}
for (uint32_t i = 0u; i < 3u; ++i)
{
ComputeCallRef computeCallAddRef =
ComputeCallManager::createComputeCall(_N(BloomAdd));
{
ComputeCallManager::resetToDefault(computeCallAddRef);
ComputeCallManager::addResourceFlags(
computeCallAddRef,
Dod::Resources::ResourceFlags::kResourceVolatile);
ComputeCallManager::_descPipeline(computeCallAddRef) =
_addPipelineRef;
ComputeCallManager::_descDimensions(computeCallAddRef) =
glm::uvec3(calculateThreadGroups(dim.x >> i, ADD_THREADS_X),
calculateThreadGroups(dim.y >> i, ADD_THREADS_Y), 1u);
ComputeCallManager::bindBuffer(
computeCallAddRef, _N(PerInstance), GpuProgramType::kCompute,
UniformManager::_perInstanceUniformBuffer,
UboType::kPerInstanceCompute, sizeof(PerInstanceDataAdd));
ComputeCallManager::bindImage(
computeCallAddRef, _N(input0Tex), GpuProgramType::kCompute,
_brightImageRef, Samplers::kLinearClamp);
ComputeCallManager::bindImage(computeCallAddRef, _N(input1Tex),
GpuProgramType::kCompute, _blurImageRef,
Samplers::kLinearClamp);
ComputeCallManager::bindImage(
computeCallAddRef, _N(output0Tex), GpuProgramType::kCompute,
_summedImageRef, Samplers::kInvalidSampler,
BindingFlags::kAdressSubResource, 0u, i);
computeCallsToCreate.push_back(computeCallAddRef);
_addComputeCallRefs.push_back(computeCallAddRef);
}
}
}
}
ComputeCallManager::createResources(computeCallsToCreate);
}
// <-
void Bloom::destroy() {}
// <-
void Bloom::render(float p_DeltaT, Components::CameraRef p_CameraRef)
{
_INTR_PROFILE_CPU("Render Pass", "Render Bloom");
_INTR_PROFILE_GPU("Render Bloom");
VkCommandBuffer primaryCmdBuffer = RenderSystem::getPrimaryCommandBuffer();
ImageManager::insertImageMemoryBarrier(
_brightImageRef, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
ImageManager::insertImageMemoryBarrier(
_lumImageRef, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
ImageManager::insertImageMemoryBarrier(
_summedImageRef, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
ImageManager::insertImageMemoryBarrier(
_blurImageRef, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
ImageManager::insertImageMemoryBarrier(
_blurPingPongImageRef, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
dispatchLum(primaryCmdBuffer);
dispatchAvgLum(primaryCmdBuffer);
dispatchBlur(primaryCmdBuffer, 3u);
dispatchAdd(primaryCmdBuffer, 2u, 3u);
dispatchBlur(primaryCmdBuffer, 2u);
dispatchAdd(primaryCmdBuffer, 1u, 2u);
dispatchBlur(primaryCmdBuffer, 1u);
dispatchAdd(primaryCmdBuffer, 0u, 1u);
dispatchBlur(primaryCmdBuffer, 0u);
ImageManager::insertImageMemoryBarrier(
_lumImageRef, VK_IMAGE_LAYOUT_GENERAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
}
}
}
}
| 12,269 |
1,223 |
package carpet.mixins;
import carpet.CarpetSettings;
import net.minecraft.world.gen.heightprovider.TrapezoidHeightProvider;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(TrapezoidHeightProvider.class)
public class TrapezoidHeightProvider_cleanLogsMixin {
@SuppressWarnings("UnresolvedMixinReference")
@Redirect(method = "get",
at = @At(value = "INVOKE", target = "Lorg/apache/logging/log4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;)V")
)
private void skipLogs(Logger logger, String message, Object p0)
{
if (!CarpetSettings.cleanLogs) logger.warn(message, p0);
}
}
| 295 |
11,775 |
<filename>jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/WarProjectIntegrationTest.java
/*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.tools.jib.gradle;
import com.google.cloud.tools.jib.Command;
import com.google.cloud.tools.jib.IntegrationTestingConfiguration;
import java.io.IOException;
import java.net.URL;
import java.security.DigestException;
import javax.annotation.Nullable;
import org.junit.After;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
/** Integration tests for building WAR images. */
public class WarProjectIntegrationTest {
@ClassRule public static final TestProject servlet25Project = new TestProject("war_servlet25");
@Nullable private String containerName;
@After
public void tearDown() throws IOException, InterruptedException {
if (containerName != null) {
new Command("docker", "stop", containerName).run();
}
}
@Test
public void testBuild_jettyServlet25() throws IOException, InterruptedException, DigestException {
verifyBuildAndRun(servlet25Project, "war_jetty_servlet25:gradle", "build.gradle");
}
@Test
public void testBuild_tomcatServlet25()
throws IOException, InterruptedException, DigestException {
verifyBuildAndRun(servlet25Project, "war_tomcat_servlet25:gradle", "build-tomcat.gradle");
}
private void verifyBuildAndRun(TestProject project, String label, String gradleBuildFile)
throws IOException, InterruptedException, DigestException {
String nameBase = IntegrationTestingConfiguration.getTestRepositoryLocation() + '/';
String targetImage = nameBase + label + System.nanoTime();
String output =
JibRunHelper.buildAndRun(project, targetImage, gradleBuildFile, "--detach", "-p8080:8080");
containerName = output.trim();
Assert.assertEquals(
"Hello world", JibRunHelper.getContent(new URL("http://localhost:8080/hello")));
}
}
| 761 |
578 |
<gh_stars>100-1000
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace facebook {
namespace cachelib {
/* Iterator Implementation */
template <typename T, DListHook<T> T::*HookPtr>
void MultiDList<T, HookPtr>::Iterator::goForward() noexcept {
if (index_ == kInvalidIndex) {
return; // Can't go any further
}
// Move iterator forward
++currIter_;
// If we land at the rend of this list, move to the previous list.
while (index_ != kInvalidIndex &&
currIter_ == mlist_.lists_[index_]->rend()) {
--index_;
if (index_ != kInvalidIndex) {
currIter_ = mlist_.lists_[index_]->rbegin();
}
}
}
template <typename T, DListHook<T> T::*HookPtr>
void MultiDList<T, HookPtr>::Iterator::goBackward() noexcept {
if (index_ == mlist_.lists_.size()) {
return; // Can't go backward
}
// If we're not at rbegin, we can go backward
if (currIter_ != mlist_.lists_[index_]->rbegin()) {
--currIter_;
return;
}
// We're at rbegin, jump to the head of the next list.
while (index_ < mlist_.lists_.size() &&
currIter_ == mlist_.lists_[index_]->rbegin()) {
++index_;
if (index_ < mlist_.lists_.size()) {
currIter_ = DListIterator(mlist_.lists_[index_]->getHead(),
DListIterator::Direction::FROM_TAIL,
*(mlist_.lists_[index_].get()));
}
}
}
template <typename T, DListHook<T> T::*HookPtr>
void MultiDList<T, HookPtr>::Iterator::initToValidRBeginFrom(
size_t listIdx) noexcept {
// Find the first non-empty list.
index_ = listIdx;
while (index_ != std::numeric_limits<size_t>::max() &&
mlist_.lists_[index_]->size() == 0) {
--index_;
}
currIter_ = index_ == std::numeric_limits<size_t>::max()
? mlist_.lists_[0]->rend()
: mlist_.lists_[index_]->rbegin();
}
template <typename T, DListHook<T> T::*HookPtr>
typename MultiDList<T, HookPtr>::Iterator&
MultiDList<T, HookPtr>::Iterator::operator++() noexcept {
goForward();
return *this;
}
template <typename T, DListHook<T> T::*HookPtr>
typename MultiDList<T, HookPtr>::Iterator&
MultiDList<T, HookPtr>::Iterator::operator--() noexcept {
goBackward();
return *this;
}
template <typename T, DListHook<T> T::*HookPtr>
typename MultiDList<T, HookPtr>::Iterator MultiDList<T, HookPtr>::rbegin()
const noexcept {
return MultiDList<T, HookPtr>::Iterator(*this);
}
template <typename T, DListHook<T> T::*HookPtr>
typename MultiDList<T, HookPtr>::Iterator MultiDList<T, HookPtr>::rbegin(
size_t listIdx) const {
if (listIdx >= lists_.size()) {
throw std::invalid_argument("Invalid list index for MultiDList iterator.");
}
return MultiDList<T, HookPtr>::Iterator(*this, listIdx);
}
template <typename T, DListHook<T> T::*HookPtr>
typename MultiDList<T, HookPtr>::Iterator MultiDList<T, HookPtr>::rend()
const noexcept {
auto it = MultiDList<T, HookPtr>::Iterator(*this);
it.reset();
return it;
}
} // namespace cachelib
} // namespace facebook
| 1,402 |
2,757 |
<filename>MdeModulePkg/Include/Protocol/SmmReadyToBoot.h
/** @file
EDKII SMM Ready To Boot protocol.
This SMM protocol is to be published by the SMM Foundation code to associate
with EFI_EVENT_GROUP_READY_TO_BOOT to notify SMM driver that system enter
ready to boot.
Copyright (c) 2015, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef _SMM_READY_TO_BOOT_H_
#define _SMM_READY_TO_BOOT_H_
#define EDKII_SMM_READY_TO_BOOT_PROTOCOL_GUID \
{ \
0x6e057ecf, 0xfa99, 0x4f39, { 0x95, 0xbc, 0x59, 0xf9, 0x92, 0x1d, 0x17, 0xe4 } \
}
extern EFI_GUID gEdkiiSmmReadyToBootProtocolGuid;
#endif
| 407 |
1,687 |
package cn.leetcode.sorting;
import cn.leetcode.examples.GenerateRandomArrayStrategy;
import cn.leetcode.utils.SortingUtil;
/**
* @author liweiwei1419
* @date 2019/9/8 4:32 AM
*/
public class MergeSortInPlace implements ISortingAlgorithm {
/**
* 列表大小等于或小于该大小,将优先于 mergesort 使用插入排序
*/
private static final int INSERTION_SORT_THRESHOLD = 7;
@Override
public String toString() {
// 了解思想即可,不建议掌握
return "归并排序(原地归并)";
}
@Override
public void sort(int[] arr) {
int len = arr.length;
mergeSort(arr, 0, len - 1);
}
private void mergeSort(int[] arr, int left, int right) {
if (right - left <= INSERTION_SORT_THRESHOLD) {
insertionSort(arr, left, right);
return;
}
// int mid = left + (right - left) / 2;
int mid = (left + right) >>> 1;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
if (arr[mid] <= arr[mid + 1]) {
return;
}
mergeOfTwoSortArray(arr, left, mid, right);
}
/**
* 对数组给定的部分使用插入排序
*
* @param arr 给定数组
* @param left 左边界,能取到
* @param right 右边界,能取到
*/
private void insertionSort(int[] arr, int left, int right) {
// 第 1 遍不用插入,所以是总长度减去 1
for (int i = left + 1; i <= right; i++) {
int temp = arr[i];
int j = i;
while (j > left && arr[j - 1] > temp) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = temp;
}
}
/**
* 注意:该实现编写繁琐,需要花很长时间调试,并且代码也没有技巧性,个人不建议花时间掌握,
* 只需要知道原地排序虽然节约了空间,但是时间增加了,我们优化的方向通常是节约时间,用户也不太关心空间使用的效率
*
* @param arr
* @param left
* @param mid [left, mid] 有序,[mid + 1, right] 有序
* @param right
*/
private void mergeOfTwoSortArray(int[] arr, int left, int mid, int right) {
// 使用新变量 j,表示右有序区间的左端点,这个变量会变化
int j = mid + 1;
while (left < j && j <= right) {
// 因为 j 指向了右有序区间的左端点,left == j 成立的时候,左区间没有元素,循环终止
// 同理 j = right + 1 的时候,循环终止
while (left < j && arr[left] <= arr[j]) {
// <= 保证了稳定性
left++;
}
// left 一旦移动,它前面的元素就确定了下来,即 left 是不回头的
// 暂时存一下原来 j 的位置,rotate 的时候用
int index = j;
while (j <= right && arr[j] < arr[left]) {
// [4, 5, 6, 10, 1, 2, 3, 11, 12]
// id j
j++;
}
rotate(arr, left, index, j - 1);
left += (j - index);
// 如果 j 前后正好有序,就退出循环
if (j <= right && arr[j - 1] <= arr[j]) {
break;
}
}
}
/**
* 力扣第 189 题:旋转数组的思路,这里更直接,把旋转数组恢复成有序数组
* 注意 mid 定义的位置
*
* @param arr
* @param left
* @param mid [left, mid - 1] 有序,[mid, right] 有序
* @param right
*/
private void rotate(int[] arr, int left, int mid, int right) {
reverse(arr, left, mid - 1);
reverse(arr, mid, right);
reverse(arr, left, right);
}
/**
* 反转对数组在区间 [left, right] 内执行一次反转
*
* @param arr
* @param left
* @param right
*/
private void reverse(int[] arr, int left, int right) {
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
public static void main(String[] args) {
SortingUtil.testSortingAlgorithm(new MergeSortInPlace(), new GenerateRandomArrayStrategy(10_0000));
// 明显非原地的归并排序要快很多
SortingUtil.compareSortingAlgorithms(new GenerateRandomArrayStrategy(10_0000),
new MergeSortOptimize(),
new MergeSortInPlace());
}
}
| 2,696 |
348 |
{"nom":"Villapourçon","circ":"2ème circonscription","dpt":"Nièvre","inscrits":346,"abs":169,"votants":177,"blancs":2,"nuls":20,"exp":155,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":78},{"nuance":"SOC","nom":"<NAME>","voix":77}]}
| 94 |
1,125 |
<reponame>peterjc123/XNNPACK
// Copyright 2020 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <assert.h>
#include <stddef.h>
#include <immintrin.h>
#include <xnnpack/math.h>
#include <xnnpack/math-stubs.h>
void xnn_math_f32_sqrt__fma3_nr1fma1adj(
size_t n,
const float* input,
float* output)
{
assert(n % (8 * sizeof(float)) == 0);
const __m256 vhalf = _mm256_set1_ps(0.5f);
for (; n != 0; n -= 8 * sizeof(float)) {
const __m256 vx = _mm256_load_ps(input);
input += 8;
// Initial approximation
const __m256 vrsqrtx = _mm256_rsqrt_ps(vx);
__m256 vsqrtx = _mm256_mul_ps(vrsqrtx, vx);
__m256 vhalfrsqrtx = _mm256_mul_ps(vrsqrtx, vhalf);
// Netwon-Raphson iteration:
// residual <- 0.5 - sqrtx * halfrsqrtx
// halfrsqrtx <- halfrsqrtx + halfrsqrtx * residual
// sqrtx <- sqrtx + sqrtx * residual
const __m256 vresidual = _mm256_fnmadd_ps(vsqrtx, vhalfrsqrtx, vhalf);
vhalfrsqrtx = _mm256_fmadd_ps(vhalfrsqrtx, vresidual, vhalfrsqrtx);
vsqrtx = _mm256_fmadd_ps(vsqrtx, vresidual, vsqrtx);
// Final adjustment:
// adjustment <- x - sqrtx * sqrtx
// sqrtx <- sqrtx + halfrsqrtx * adjustment
const __m256 vadjustment = _mm256_fnmadd_ps(vsqrtx, vsqrtx, vx);
vsqrtx = _mm256_fmadd_ps(vhalfrsqrtx, vadjustment, vsqrtx);
const __m256 vy = vsqrtx;
_mm256_store_ps(output, vy);
output += 8;
}
}
| 713 |
369 |
/* ----------------------------------------------------------------------------
* ATMEL Microcontroller Software Support
* ----------------------------------------------------------------------------
* Copyright (c) 2008, Atmel Corporation
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
* ----------------------------------------------------------------------------
*/
//------------------------------------------------------------------------------
// Headers
//------------------------------------------------------------------------------
#include "lcdd.h"
#include <board.h>
#include <pmc/pmc.h>
#include <hx8347/hx8347.h>
#include <pio/pio.h>
#include "FreeRTOS.h"
#include "task.h"
//------------------------------------------------------------------------------
// Global functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/// Initializes the LCD controller.
/// \param pLcdBase LCD base address.
//------------------------------------------------------------------------------
void LCDD_Initialize(void)
{
const Pin pPins[] = {BOARD_LCD_PINS};
AT91PS_HSMC4_CS pSMC = AT91C_BASE_HSMC4_CS2;
unsigned int rMode;
// Enable pins
PIO_Configure(pPins, PIO_LISTSIZE(pPins));
// Enable peripheral clock
PMC_EnablePeripheral(AT91C_ID_HSMC4);
// EBI SMC Configuration
pSMC->HSMC4_SETUP = 0
| ((4 << 0) & AT91C_HSMC4_NWE_SETUP)
| ((2 << 8) & AT91C_HSMC4_NCS_WR_SETUP)
| ((4 << 16) & AT91C_HSMC4_NRD_SETUP)
| ((2 << 24) & AT91C_HSMC4_NCS_RD_SETUP)
;
pSMC->HSMC4_PULSE = 0
| (( 5 << 0) & AT91C_HSMC4_NWE_PULSE)
| (( 18 << 8) & AT91C_HSMC4_NCS_WR_PULSE)
| (( 5 << 16) & AT91C_HSMC4_NRD_PULSE)
| (( 18 << 24) & AT91C_HSMC4_NCS_RD_PULSE)
;
pSMC->HSMC4_CYCLE = 0
| ((22 << 0) & AT91C_HSMC4_NWE_CYCLE)
| ((22 << 16) & AT91C_HSMC4_NRD_CYCLE)
;
rMode = pSMC->HSMC4_MODE;
pSMC->HSMC4_MODE = (rMode & ~(AT91C_HSMC4_DBW | AT91C_HSMC4_READ_MODE
| AT91C_HSMC4_WRITE_MODE | AT91C_HSMC4_PMEN))
| (AT91C_HSMC4_READ_MODE)
| (AT91C_HSMC4_WRITE_MODE)
| (AT91C_HSMC4_DBW_WIDTH_SIXTEEN_BITS)
;
// Initialize LCD controller (HX8347)
LCD_Initialize((void *)BOARD_LCD_BASE);
// Set LCD backlight
LCDD_SetBacklight(25);
}
//------------------------------------------------------------------------------
/// Turn on the LCD
//------------------------------------------------------------------------------
void LCDD_Start(void)
{
LCD_On((void *)BOARD_LCD_BASE);
}
//------------------------------------------------------------------------------
/// Turn off the LCD
//------------------------------------------------------------------------------
void LCDD_Stop(void)
{
LCD_Off((void *)BOARD_LCD_BASE);
}
//------------------------------------------------------------------------------
/// Set the backlight of the LCD.
/// \param level Backlight brightness level [1..32], 32 is maximum level.
//------------------------------------------------------------------------------
void LCDD_SetBacklight (unsigned int level)
{
unsigned int i;
const Pin pPins[] = {BOARD_BACKLIGHT_PIN};
// Enable pins
PIO_Configure(pPins, PIO_LISTSIZE(pPins));
// Switch off backlight
PIO_Clear(pPins);
vTaskDelay( 2 );
// Set new backlight level
for (i = 0; i < level; i++) {
PIO_Set(pPins);
PIO_Set(pPins);
PIO_Set(pPins);
PIO_Clear(pPins);
PIO_Clear(pPins);
PIO_Clear(pPins);
}
PIO_Set(pPins);
}
| 1,890 |
517 |
from __future__ import absolute_import, division, print_function, unicode_literals
from .takes import ZERO, PENNY
class Membership(object):
"""Teams may have zero or more members, who are participants that take money from the team.
"""
def add_member(self, participant, recorder):
"""Add a participant to this team.
:param Participant participant: the participant to add
:param Participant recorder: the participant making the change
"""
self.set_take_for(participant, PENNY, recorder)
def remove_member(self, participant, recorder):
"""Remove a participant from this team.
:param Participant participant: the participant to remove
:param Participant recorder: the participant making the change
"""
self.set_take_for(participant, ZERO, recorder)
@property
def nmembers(self):
"""The number of members. Read-only and computed (not in the db); equal to
:py:attr:`~gratipay.models.team.mixins.takes.ndistributing_to`.
"""
return self.ndistributing_to
def get_memberships(self, current_participant=None):
"""Return a list of member dicts.
"""
takes = self.compute_actual_takes()
members = []
for take in takes.values():
member = {}
member['participant_id'] = take['participant'].id
member['username'] = take['participant'].username
member['take'] = take['nominal_amount']
member['balance'] = take['balance']
member['percentage'] = take['percentage']
member['editing_allowed'] = False
member['is_current_user'] = False
if current_participant:
member['removal_allowed'] = current_participant.username == self.owner
if member['username'] == current_participant.username:
member['editing_allowed']= True
member['last_week'] = self.get_take_last_week_for(take['participant'])
members.append(member)
return members
| 821 |
462 |
/******************************************************************************
* Project: OGR
* Purpose: OGRGMLASDriver implementation
* Author: <NAME>, <even dot rouault at spatialys dot com>
*
* Initial development funded by the European Earth observation programme
* Copernicus
*
******************************************************************************
* Copyright (c) 2016, <NAME>, <even dot rouault at spatialys dot com>
*
* 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 "ogr_gmlas.h"
/************************************************************************/
/* OGRGMLASTruncateIdentifier() */
/************************************************************************/
CPLString OGRGMLASTruncateIdentifier(const CPLString& osName,
int nIdentMaxLength)
{
int nExtra = static_cast<int>(osName.size()) - nIdentMaxLength;
CPLAssert(nExtra > 0);
// Decompose in tokens
char** papszTokens = CSLTokenizeString2(osName, "_",
CSLT_ALLOWEMPTYTOKENS );
std::vector< char > achDelimiters;
std::vector< CPLString > aosTokens;
for( int j=0; papszTokens[j] != nullptr; ++j )
{
const char* pszToken = papszTokens[j];
bool bIsCamelCase = false;
// Split parts like camelCase or CamelCase into several tokens
if( pszToken[0] != '\0' && islower(pszToken[1]) )
{
bIsCamelCase = true;
bool bLastIsLower = true;
std::vector<CPLString> aoParts;
CPLString osCurrentPart;
osCurrentPart += pszToken[0];
osCurrentPart += pszToken[1];
for( int k=2; pszToken[k]; ++k)
{
if( isupper(pszToken[k]) )
{
if( !bLastIsLower )
{
bIsCamelCase = false;
break;
}
aoParts.push_back(osCurrentPart);
osCurrentPart.clear();
bLastIsLower = false;
}
else
{
bLastIsLower = true;
}
osCurrentPart += pszToken[k];
}
if( bIsCamelCase )
{
if( !osCurrentPart.empty() )
aoParts.push_back(osCurrentPart);
for( size_t k=0; k<aoParts.size(); ++k )
{
achDelimiters.push_back( (j > 0 && k == 0) ? '_' : '\0' );
aosTokens.push_back( aoParts[k] );
}
}
}
if( !bIsCamelCase )
{
achDelimiters.push_back( (j > 0) ? '_' : '\0' );
aosTokens.push_back( pszToken );
}
}
CSLDestroy(papszTokens);
// Truncate identifier by removing last character of longest part
bool bHasDoneSomething = true;
while( nExtra > 0 && bHasDoneSomething )
{
bHasDoneSomething = false;
int nMaxSize = 0;
size_t nIdxMaxSize = 0;
for( size_t j=0; j < aosTokens.size(); ++j )
{
int nTokenLen = static_cast<int>(aosTokens[j].size());
if( nTokenLen > nMaxSize )
{
// Avoid truncating last token unless it is excessively longer
// than previous ones.
if( j < aosTokens.size() - 1 ||
nTokenLen > 2 * nMaxSize )
{
nMaxSize = nTokenLen;
nIdxMaxSize = j;
}
}
}
if( nMaxSize > 1 )
{
aosTokens[nIdxMaxSize].resize( nMaxSize - 1 );
bHasDoneSomething = true;
nExtra --;
}
}
// Reassemble truncated parts
CPLString osNewName;
for( size_t j=0; j < aosTokens.size(); ++j )
{
if( achDelimiters[j] )
osNewName += achDelimiters[j];
osNewName += aosTokens[j];
}
// If we are still longer than max allowed, truncate beginning of name
if( nExtra > 0 )
{
osNewName = osNewName.substr(nExtra);
}
CPLAssert( static_cast<int>(osNewName.size()) == nIdentMaxLength );
return osNewName;
}
/************************************************************************/
/* OGRGMLASAddSerialNumber() */
/************************************************************************/
CPLString OGRGMLASAddSerialNumber(const CPLString& osNameIn,
int iOccurrence,
size_t nOccurrences,
int nIdentMaxLength)
{
CPLString osName(osNameIn);
const int nDigitsSize = (nOccurrences < 10) ? 1:
(nOccurrences < 100) ? 2 : 3;
char szDigits[4];
snprintf(szDigits, sizeof(szDigits), "%0*d",
nDigitsSize, iOccurrence);
if( nIdentMaxLength >= MIN_VALUE_OF_MAX_IDENTIFIER_LENGTH )
{
if( static_cast<int>(osName.size()) < nIdentMaxLength )
{
if( static_cast<int>(osName.size()) + nDigitsSize <
nIdentMaxLength )
{
osName += szDigits;
}
else
{
osName.resize(nIdentMaxLength - nDigitsSize);
osName += szDigits;
}
}
else
{
osName.resize(osName.size() - nDigitsSize);
osName += szDigits;
}
}
else
{
osName += szDigits;
}
return osName;
}
| 3,270 |
577 |
package javatests;
public class Coercion {
public static void string_array(String[] args) {
}
}
| 42 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000
{"nom":"Vaychis","circ":"1ère circonscription","dpt":"Ariège","inscrits":46,"abs":22,"votants":24,"blancs":3,"nuls":2,"exp":19,"res":[{"nuance":"REM","nom":"<NAME>","voix":11},{"nuance":"FI","nom":"<NAME>","voix":8}]}
| 116 |
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.provider;
import java.io.InputStream;
import javax.annotation.Resource;
import javax.xml.namespace.QName;
import javax.xml.soap.Detail;
import javax.xml.soap.DetailEntry;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.Provider;
import javax.xml.ws.Service;
import javax.xml.ws.ServiceMode;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.WebServiceProvider;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.soap.SOAPFaultException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.apache.cxf.binding.soap.saaj.SAAJUtils;
import org.apache.cxf.helpers.DOMUtils;
//The following wsdl file is used.
//wsdlLocation = "/trunk/testutils/src/main/resources/wsdl/hello_world.wsdl"
@WebServiceProvider(portName = "SoapProviderPort", serviceName = "SOAPProviderService",
targetNamespace = "http://apache.org/hello_world_soap_http",
wsdlLocation = "/org/apache/cxf/systest/provider/hello_world_with_restriction.wsdl")
@ServiceMode(value = Service.Mode.MESSAGE)
public class HWSoapMessageDocProvider implements Provider<SOAPMessage> {
private static QName sayHi = new QName("http://apache.org/hello_world_soap_http", "sayHi");
private static QName greetMe = new QName("http://apache.org/hello_world_soap_http", "greetMe");
@Resource
WebServiceContext ctx;
private SOAPMessage sayHiResponse;
private SOAPMessage greetMeResponse;
private SOAPMessage greetMeResponseExceedMaxLengthRestriction;
public HWSoapMessageDocProvider() {
try {
MessageFactory factory = MessageFactory.newInstance();
InputStream is = getClass().getResourceAsStream("resources/sayHiDocLiteralResp.xml");
sayHiResponse = factory.createMessage(null, is);
is.close();
is = getClass().getResourceAsStream("resources/GreetMeDocLiteralResp.xml");
greetMeResponse = factory.createMessage(null, is);
is.close();
is = getClass().getResourceAsStream("resources/GreetMeDocLiteralRespExceedLength.xml");
greetMeResponseExceedMaxLengthRestriction = factory.createMessage(null, is);
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public SOAPMessage invoke(SOAPMessage request) {
QName qn = (QName)ctx.getMessageContext().get(MessageContext.WSDL_OPERATION);
if (qn == null) {
throw new RuntimeException("No Operation Name");
}
SOAPMessage response = null;
SOAPBody body = null;
try {
body = SAAJUtils.getBody(request);
} catch (SOAPException e) {
return null;
}
Node n = body.getFirstChild();
while (n.getNodeType() != Node.ELEMENT_NODE) {
n = n.getNextSibling();
}
if (n.getLocalName().equals(sayHi.getLocalPart())) {
response = sayHiResponse;
} else if (n.getLocalName().equals(greetMe.getLocalPart())) {
Element el = DOMUtils.getFirstElement(n);
String v = DOMUtils.getContent(el);
if (v.contains("Return sayHi")) {
response = sayHiResponse;
} else if (v.contains("exceed maxLength")) {
response = greetMeResponseExceedMaxLengthRestriction;
} else if (v.contains("throwFault")) {
try {
SOAPFactory f = SOAPFactory.newInstance();
SOAPFault soapFault = f.createFault();
soapFault.setFaultString("Test Fault String ****");
Detail detail = soapFault.addDetail();
detail = soapFault.getDetail();
QName qName = new QName("http://www.Hello.org/greeter", "TestFault", "ns");
DetailEntry de = detail.addDetailEntry(qName);
qName = new QName("http://www.Hello.org/greeter", "ErrorCode", "ns");
SOAPElement errorElement = de.addChildElement(qName);
errorElement.setTextContent("errorcode");
throw new SOAPFaultException(soapFault);
} catch (SOAPException ex) {
//ignore
}
} else {
response = greetMeResponse;
}
}
return response;
}
}
| 2,264 |
5,535 |
from mock import *
from .gp_unittest import *
from gpcheckcat_modules.repair_missing_extraneous import RepairMissingExtraneous
class RepairMissingExtraneousTestCase(GpTestCase):
def setUp(self):
self.all_seg_ids = [-1,0,1,2,3]
self.table_name = 'pg_attribut"e'
self.catalog_table_obj = Mock(spec=['getTableName',
'tableHasConsistentOids',
'getPrimaryKey'])
self.catalog_table_obj.getTableName.return_value = self.table_name
def test_get_segment_to_oid_mapping_with_both_extra_and_missing(self):
issues = [(49401, "extra", [1,2]),
(49401, "extra", [1,2]),
(49402, "missing", [2,3]),
(49403, "extra", [2,3]),
(49404, "missing", [1]),
(49405, "extra", [2,3]),
(49406, "missing", [2])]
self.subject = RepairMissingExtraneous(self.catalog_table_obj, issues, "attrelid")
repair_sql_contents = self.subject.get_segment_to_oid_mapping(self.all_seg_ids)
self.assertEqual(len(repair_sql_contents), 5)
self.assertEqual(repair_sql_contents[-1], set([49402, 49404, 49406]))
self.assertEqual(repair_sql_contents[0], set([49402, 49404, 49406]))
self.assertEqual(repair_sql_contents[1], set([49401, 49402, 49406]))
self.assertEqual(repair_sql_contents[2], set([49401, 49403, 49404, 49405]))
self.assertEqual(repair_sql_contents[3], set([49403, 49404, 49405, 49406]))
def test_get_segment_to_oid_mapping_with_only_extra(self):
issues = [(49401, 'cmax', "extra", [1,2]),
(49401, 'cmax', "extra", [1,2]),
(49403, 'cmax', "extra", [2,3]),
(49405, 'cmax', "extra", [2,3])]
self.subject = RepairMissingExtraneous(self.catalog_table_obj, issues, "attrelid")
repair_sql_contents = self.subject.get_segment_to_oid_mapping(self.all_seg_ids)
self.assertEqual(len(repair_sql_contents), 3)
self.assertEqual(repair_sql_contents[1], set([49401]))
self.assertEqual(repair_sql_contents[2], set([49401, 49403, 49405]))
self.assertEqual(repair_sql_contents[3], set([49403, 49405]))
def test_get_segment_to_oid_mapping_with_only_missing(self):
issues = [(49401, 'cmax', "missing", [1,2]),
(49401, 'cmax', "missing", [1,2]),
(49403, 'cmax', "missing", [2,3]),
(49405, 'cmax', "missing", [2,3])]
self.subject = RepairMissingExtraneous(self.catalog_table_obj, issues, "attrelid")
repair_sql_contents = self.subject.get_segment_to_oid_mapping(self.all_seg_ids)
self.assertEqual(len(repair_sql_contents), 4)
self.assertEqual(repair_sql_contents[-1], set([49401, 49403, 49405]))
self.assertEqual(repair_sql_contents[0], set([49401, 49403, 49405]))
self.assertEqual(repair_sql_contents[1], set([49403, 49405]))
self.assertEqual(repair_sql_contents[3], set([49401]))
def test_get_delete_sql__with_multiple_oids(self):
self.subject = RepairMissingExtraneous(self.catalog_table_obj, None, "attrelid")
oids = [1,3,4]
delete_sql = self.subject.get_delete_sql(oids)
self.assertEqual(delete_sql, 'BEGIN;set allow_system_table_mods=true;'
'delete from "pg_attribut""e" where "attrelid" in (1,3,4);COMMIT;')
def test_get_delete_sql__with_one_oid(self):
self.subject = RepairMissingExtraneous(self.catalog_table_obj, None, "attrelid")
oids = [5]
delete_sql = self.subject.get_delete_sql(oids)
self.assertEqual(delete_sql, 'BEGIN;set allow_system_table_mods=true;'
'delete from "pg_attribut""e" where "attrelid" in (5);COMMIT;')
def test_get_delete_sql__with_one_pkey_one_issue(self):
issues = [('!!', 'cmax', "extra", [1,2]),]
self.catalog_table_obj.tableHasConsistentOids.return_value = False
self.catalog_table_obj.getPrimaryKey.return_value = ["oprname"]
self.subject = RepairMissingExtraneous(self.catalog_table_obj, issues, None)
oids = None
delete_sql = self.subject.get_delete_sql(oids)
self.assertEqual(delete_sql, 'BEGIN;set allow_system_table_mods=true;'
'delete from "pg_attribut""e" where oprname = \'!!\';COMMIT;')
def test_get_delete_sql__with_one_pkey_mult_issues(self):
issues = [('!!', 'cmax', "missing", [1,2]),
('8!', 'cmax', "extra", [1,2]),
('*!', 'cmax', "missing", [2,3]),
('!!', 'cmax', "extra", [2,3])]
self.catalog_table_obj.tableHasConsistentOids.return_value = False
self.catalog_table_obj.getPrimaryKey.return_value = ["oprname"]
self.subject = RepairMissingExtraneous(self.catalog_table_obj, issues, None)
oids = None
delete_sql = self.subject.get_delete_sql(oids)
self.assertEqual(delete_sql, 'BEGIN;set allow_system_table_mods=true;'
'delete from "pg_attribut""e" where oprname = \'!!\';'
'delete from "pg_attribut""e" where oprname = \'8!\';'
'delete from "pg_attribut""e" where oprname = \'*!\';'
'delete from "pg_attribut""e" where oprname = \'!!\';COMMIT;')
def test_get_delete_sql__with_multiple_pkey_mult_issue(self):
issues = [('!!', 48920, 0, 1, 'cmax', "missing", [1,2]),
('8!', 15, 1, 3, 'cmax', "extra", [1,2]),
('*!', 48920, 2, 3, 'cmax', "missing", [2,3]),
('!!', 11, 2, 3, 'cmax', "extra", [2,3])]
self.catalog_table_obj.tableHasConsistentOids.return_value = False
self.catalog_table_obj.getPrimaryKey.return_value = ["oprname",
"oprnamespace",
"oprleft",
"oprright"]
self.subject = RepairMissingExtraneous(self.catalog_table_obj, issues, None)
oids = None
delete_sql = self.subject.get_delete_sql(oids)
self.assertEqual(delete_sql, 'BEGIN;set allow_system_table_mods=true;'
'delete from "pg_attribut""e" where oprname = \'!!\' and oprnamespace = \'48920\''
' and oprleft = \'0\' and oprright = \'1\';'
'delete from "pg_attribut""e" where oprname = \'8!\' and oprnamespace = \'15\''
' and oprleft = \'1\' and oprright = \'3\';'
'delete from "pg_attribut""e" where oprname = \'*!\' and oprnamespace = \'48920\''
' and oprleft = \'2\' and oprright = \'3\';'
'delete from "pg_attribut""e" where oprname = \'!!\' and oprnamespace = \'11\''
' and oprleft = \'2\' and oprright = \'3\';'
'COMMIT;')
if __name__ == '__main__':
run_tests()
| 3,971 |
4,538 |
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/experimental/resource/resource_variable.h"
#include <vector>
#include <gtest/gtest.h>
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/util.h"
namespace tflite {
namespace resource {
// Helper util that initialize 'tensor'.
void InitTensor(const std::vector<int>& shape, TfLiteAllocationType alloc_type,
float default_value, TfLiteTensor* tensor) {
memset(tensor, 0, sizeof(TfLiteTensor));
int num_elements = 1;
for (auto dim : shape) num_elements *= dim;
if (shape.empty()) num_elements = 0;
float* buf = static_cast<float*>(malloc(sizeof(float) * num_elements));
for (int i = 0; i < num_elements; ++i) buf[i] = default_value;
const int bytes = num_elements * sizeof(buf[0]);
auto* dims = ConvertArrayToTfLiteIntArray(shape.size(), shape.data());
TfLiteTensorReset(TfLiteType::kTfLiteFloat32, nullptr, dims, {},
reinterpret_cast<char*>(buf), bytes, alloc_type, nullptr,
false, tensor);
}
TEST(ResourceTest, NonDynamicTensorAssign) {
ResourceVariable var;
EXPECT_FALSE(var.IsInitialized());
TfLiteTensor tensor;
std::vector<int> shape = {1};
InitTensor(shape, kTfLiteArenaRw, 1.0f, &tensor);
EXPECT_EQ(kTfLiteOk, var.AssignFrom(&tensor));
EXPECT_TRUE(var.IsInitialized());
auto* value = var.GetTensor();
// Variables are always dynamic type.
EXPECT_EQ(kTfLiteDynamic, value->allocation_type);
EXPECT_EQ(kTfLiteFloat32, value->type);
EXPECT_EQ(sizeof(float), value->bytes);
EXPECT_EQ(1, value->dims->size);
EXPECT_EQ(1, value->dims->data[0]);
EXPECT_EQ(1.0f, value->data.f[0]);
// Cleanup
// For non dynamic tensors we need to delete the buffers manually.
free(tensor.data.raw);
TfLiteTensorFree(&tensor);
}
TEST(ResourceTest, DynamicTensorAssign) {
ResourceVariable var;
EXPECT_FALSE(var.IsInitialized());
TfLiteTensor tensor;
std::vector<int> shape = {1};
InitTensor(shape, kTfLiteDynamic, 1.0f, &tensor);
EXPECT_EQ(kTfLiteOk, var.AssignFrom(&tensor));
EXPECT_TRUE(var.IsInitialized());
auto* value = var.GetTensor();
// Variables are always dynamic type.
EXPECT_EQ(kTfLiteDynamic, value->allocation_type);
EXPECT_EQ(kTfLiteFloat32, value->type);
EXPECT_EQ(sizeof(float), value->bytes);
EXPECT_EQ(1, value->dims->size);
EXPECT_EQ(1, value->dims->data[0]);
EXPECT_EQ(1.0f, value->data.f[0]);
// Cleanup
TfLiteTensorFree(&tensor);
}
TEST(ResourceTest, AssignSameSizeTensor) {
ResourceVariable var;
EXPECT_FALSE(var.IsInitialized());
// We create 2 tensors and make 2 calls for Assign.
// The second Assign call should trigger the case of assign with same size.
TfLiteTensor tensor_a, tensor_b;
std::vector<int> shape_a = {1};
std::vector<int> shape_b = {1};
InitTensor(shape_a, kTfLiteDynamic, 1.0, &tensor_a);
InitTensor(shape_b, kTfLiteDynamic, 4.0, &tensor_b);
EXPECT_EQ(kTfLiteOk, var.AssignFrom(&tensor_a));
EXPECT_TRUE(var.IsInitialized());
auto* value = var.GetTensor();
// Variables are always dynamic type.
EXPECT_EQ(kTfLiteDynamic, value->allocation_type);
EXPECT_EQ(kTfLiteFloat32, value->type);
EXPECT_EQ(sizeof(float), value->bytes);
EXPECT_EQ(1, value->dims->size);
EXPECT_EQ(1, value->dims->data[0]);
EXPECT_EQ(1.0f, value->data.f[0]);
// Second AssignFrom but now tensor_b has same size as the variable.
EXPECT_EQ(kTfLiteOk, var.AssignFrom(&tensor_b));
EXPECT_TRUE(var.IsInitialized());
value = var.GetTensor();
// Variables are always dynamic type.
EXPECT_EQ(kTfLiteDynamic, value->allocation_type);
EXPECT_EQ(kTfLiteFloat32, value->type);
EXPECT_EQ(sizeof(float), value->bytes);
EXPECT_EQ(1, value->dims->size);
EXPECT_EQ(1, value->dims->data[0]);
EXPECT_EQ(4.0f, value->data.f[0]);
// Cleanup
TfLiteTensorFree(&tensor_a);
TfLiteTensorFree(&tensor_b);
}
TEST(ResourceTest, AssignDifferentSizeTensor) {
ResourceVariable var;
EXPECT_FALSE(var.IsInitialized());
// We create 2 tensors and make 2 calls for Assign.
// The second Assign call should trigger the case of assign with different
// size.
TfLiteTensor tensor_a, tensor_b;
std::vector<int> shape_a = {1};
std::vector<int> shape_b = {2};
InitTensor(shape_a, kTfLiteDynamic, 1.0, &tensor_a);
InitTensor(shape_b, kTfLiteDynamic, 4.0, &tensor_b);
EXPECT_EQ(kTfLiteOk, var.AssignFrom(&tensor_a));
EXPECT_TRUE(var.IsInitialized());
auto* value = var.GetTensor();
// Variables are always dynamic type.
EXPECT_EQ(kTfLiteDynamic, value->allocation_type);
EXPECT_EQ(kTfLiteFloat32, value->type);
EXPECT_EQ(sizeof(float), value->bytes);
EXPECT_EQ(1, value->dims->size);
EXPECT_EQ(1, value->dims->data[0]);
EXPECT_EQ(1.0f, value->data.f[0]);
// Second AssignFrom but now tensor_b has different size from the variable.
EXPECT_EQ(kTfLiteOk, var.AssignFrom(&tensor_b));
EXPECT_TRUE(var.IsInitialized());
value = var.GetTensor();
// Variables are always dynamic type.
EXPECT_EQ(kTfLiteDynamic, value->allocation_type);
EXPECT_EQ(kTfLiteFloat32, value->type);
EXPECT_EQ(sizeof(float) * 2, value->bytes);
EXPECT_EQ(1, value->dims->size);
EXPECT_EQ(2, value->dims->data[0]);
EXPECT_EQ(4.0f, value->data.f[0]);
// Cleanup
TfLiteTensorFree(&tensor_a);
TfLiteTensorFree(&tensor_b);
}
} // namespace resource
} // namespace tflite
| 2,329 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.