max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
626 | #ifndef NODEMAP_H
#define NODEMAP_H
#include "vertexmap.h"
#include "dcel.h"
namespace gen {
template <class T>
class NodeMap {
public:
NodeMap() {}
NodeMap(VertexMap *vertexMap) : _vertexMap(vertexMap) {
_initializeNodes();
}
NodeMap(VertexMap *vertexMap, T fillval) : _vertexMap(vertexMap) {
_initializeNodes();
fill(fillval);
}
unsigned int size() {
return _vertexMap->size();
}
T min() {
T minval = _nodes[0];
for (unsigned int i = 0; i < _nodes.size(); i++) {
if (_nodes[i] < minval) {
minval = _nodes[i];
}
}
return minval;
}
T max() {
T maxval = _nodes[0];
for (unsigned int i = 0; i < _nodes.size(); i++) {
if (_nodes[i] > maxval) {
maxval = _nodes[i];
}
}
return maxval;
}
int getNodeIndex(dcel::Vertex &v) {
return _vertexMap->getVertexIndex(v);
}
void fill(T fillval) {
for (unsigned int i = 0; i < _nodes.size(); i++) {
_nodes[i] = fillval;
}
}
T operator()(int idx) {
if (!_isInRange(idx)) {
throw std::range_error("Index out of range:" + idx);
}
return _nodes[idx];
}
T operator()(dcel::Vertex v) {
int idx = getNodeIndex(v);
if (idx == -1) {
throw std::range_error("Vertex is not in NodeMap.");
}
return _nodes[idx];
}
T* getPointer(int idx) {
if (!_isInRange(idx)) {
throw std::range_error("Index out of range:" + idx);
}
return &_nodes[idx];
}
T* getPointer(dcel::Vertex v) {
int idx = getNodeIndex(v);
if (idx == -1) {
throw std::range_error("Vertex is not in NodeMap.");
}
return &_nodes[idx];
}
void set(int idx, T val) {
if (!_isInRange(idx)) {
throw std::range_error("Index out of range:" + idx);
}
_nodes[idx] = val;
}
void set(dcel::Vertex &v, T val) {
int idx = getNodeIndex(v);
if (idx == -1 || !_isInRange(idx)) {
throw std::range_error("Vertex is not in NodeMap.");
}
_nodes[idx] = val;
}
void getNeighbours(int idx, std::vector<T> &nbs) {
if (!_isInRange(idx)) {
throw std::range_error("Index out of range:" + idx);
}
std::vector<int> indices;
indices.reserve(3);
_vertexMap->getNeighbourIndices(_vertexMap->vertices[idx], indices);
for (unsigned int i = 0; i < indices.size(); i++) {
nbs.push_back(_nodes[indices[i]]);
}
}
void getNeighbours(dcel::Vertex &v, std::vector<T> &nbs) {
int idx = getNodeIndex(v);
if (idx == -1) {
throw std::range_error("Vertex is not in NodeMap.");
}
std::vector<int> indices;
indices.reserve(3);
_vertexMap->getNeighbourIndices(v, indices);
for (unsigned int i = 0; i < indices.size(); i++) {
nbs.push_back(_nodes[indices[i]]);
}
}
bool isNode(int idx) {
return _isInRange(idx);
}
bool isNode(dcel::Vertex &v) {
int idx = getNodeIndex(v);
return idx != -1;
}
bool isEdge(int idx) {
if (!_isInRange(idx)) {
return false;
}
return _vertexMap->isEdge(_vertexMap->vertices[idx]);
}
bool isEdge(dcel::Vertex &v) {
return _vertexMap->isEdge(v);
}
bool isInterior(int idx) {
if (!_isInRange(idx)) {
return false;
}
return _vertexMap->isInterior(_vertexMap->vertices[idx]);
}
bool isInterior(dcel::Vertex &v) {
return _vertexMap->isInterior(v);
}
// Normalize height map values to range [0, 1]
void normalize() {
double min = std::numeric_limits<double>::infinity();
double max = -std::numeric_limits<double>::infinity();
for (unsigned int i = 0; i < size(); i++) {
min = fmin(min, (*this)(i));
max = fmax(max, (*this)(i));
}
for (unsigned int i = 0; i < size(); i++) {
double val = (*this)(i);
double normalized = (val - min) / (max - min);
set(i, normalized);
}
}
// Normalize height map and square root the values
void round() {
normalize();
for (unsigned int i = 0; i < size(); i++) {
double rounded = sqrt((*this)(i));
set(i, rounded);
}
}
// Replace height with average of its neighbours
void relax() {
std::vector<double> averages;
averages.reserve(size());
std::vector<double> nbs;
for (unsigned int i = 0; i < size(); i++) {
nbs.clear();
getNeighbours(i, nbs);
if (nbs.size() == 0) {
continue;
}
double sum = 0.0;
for (unsigned int nidx = 0; nidx < nbs.size(); nidx++) {
sum += nbs[nidx];
}
averages.push_back(sum / nbs.size());
}
for (unsigned int i = 0; i < size(); i++) {
set(i, averages[i]);
}
}
// Translate height map so that level is at zero
void setLevel(double level) {
for (unsigned int i = 0; i < size(); i++) {
double newval = (*this)(i) - level;
set(i, newval);
}
}
void setLevelToMedian() {
std::vector<double> values;
values.reserve(size());
for (unsigned int i = 0; i < size(); i++) {
values.push_back((*this)(i));
}
std::sort(values.begin(), values.end());
int mididx = values.size() / 2;
double median;
if (values.size() % 2 == 0) {
median = 0.5 * (values[mididx - 1] + values[mididx]);
} else {
median = values[mididx];
}
setLevel(median);
}
private:
void _initializeNodes() {
_nodes = std::vector<T>(size(), T());
}
bool _isInRange(int idx) {
return idx >= 0 && idx < (int)_nodes.size();
}
VertexMap *_vertexMap;
std::vector<T> _nodes;
};
}
#endif | 3,246 |
1,178 | from sciapp.action import Simple
from sciapp.object import Mesh
from sciapp.util import meshutil
import numpy as np
class Plugin(Simple):
title = 'RGB Points Cloud'
note = ['rgb']
para = {'name':'undifine', 'num':100, 'r':1}
view = [(str, 'name', 'Name', ''),
(int, 'num', (10,10240), 0, 'number', 'points'),
(float, 'r', (0.1,30), 1, 'radius', '')]
def run(self, ips, imgs, para = None):
num,r = para['num'], para['r']
if ips.roi != None: pts = ips.img[ips.get_msk()]
else: pts = ips.img.reshape((-1,3))
pts = pts[::len(pts)//num]
vts, fs, cs = meshutil.create_balls(pts, np.ones(len(pts))*r, pts/255)
self.app.show_mesh(Mesh(pts, colors=pts/255), para['name'])
(r1,g1,b1),(r2,g2,b2) = (0,0,0),(1,1,1)
rs = (r1,r2,r2,r1,r1,r1,r1,r1,r1,r2,r2,r1,r2,r2,r2,r2)
gs = (g1,g1,g1,g1,g1,g2,g2,g1,g2,g2,g2,g2,g2,g1,g1,g2)
bs = (b1,b1,b2,b2,b1,b1,b2,b2,b2,b2,b1,b1,b1,b1,b2,b2)
vts, fs, ls = meshutil.create_cube((0,0,0),(255,255,255))
cs = np.array(list(zip(rs,gs,bs)))
self.app.show_mesh(Mesh(vts, ls, colors=vts/255, mode='grid'), 'cube')
if __name__ == '__main__':
pass | 696 |
312 | <filename>src/occa/internal/modes/dpcpp.hpp
#include <occa/defines.hpp>
#if OCCA_DPCPP_ENABLED
# ifndef OCCA_MODES_DPCPP_HEADER
# define OCCA_MODES_DPCPP_HEADER
#include <occa/internal/modes/dpcpp/utils.hpp>
# endif
#endif
| 114 |
3,269 | <reponame>jaiskid/LeetCode-Solutions
// Time: O(m^2 * n^2)
// Space: O(m * n)
class Solution {
public:
int getMaximumGold(vector<vector<int>>& grid) {
int result = 0;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[0].size(); ++j) {
if (grid[i][j]) {
result = max(result, backtracking(&grid, i, j));
}
}
}
return result;
}
private:
int backtracking(vector<vector<int>> *grid, int i, int j) {
static const vector<pair<int, int>> directions{{0, 1}, {1, 0},
{0, -1}, {-1, 0}};
int result = 0;
(*grid)[i][j] *= -1;
for (const auto& [dx, dy] : directions) {
int ni = i + dx;
int nj = j + dy;
if (!(0 <= ni && ni < grid->size() &&
0 <= nj && nj < (*grid)[0].size() &&
(*grid)[ni][nj] > 0)) {
continue;
}
result = max(result, backtracking(grid, ni, nj));
}
(*grid)[i][j] *= -1;
return (*grid)[i][j] + result;
}
};
| 675 |
567 | <gh_stars>100-1000
#ifndef CC_DUAL_NET_TRT_DUAL_NET_H_
#define CC_DUAL_NET_TRT_DUAL_NET_H_
#include "cc/dual_net/dual_net.h"
namespace minigo {
class TrtDualNetFactory : public DualNetFactory {
public:
TrtDualNetFactory();
int GetBufferCount() const override;
std::unique_ptr<DualNet> NewDualNet(const std::string& model) override;
private:
int device_count_;
};
} // namespace minigo
#endif // CC_DUAL_NET_TRT_DUAL_NET_H_
| 180 |
15,872 | {
"name": "rotate",
"scripts": {
"build": "../build-rust.sh ./build.sh",
"benchmark": "echo File size after gzip && npm run benchmark:filesize && echo Optimizing && npm run -s benchmark:optimizing",
"benchmark:baseline": "v8 --liftoff --no-wasm-tier-up --no-opt ./benchmark.js",
"benchmark:optimizing": "v8 --no-liftoff --no-wasm-tier-up ./benchmark.js",
"benchmark:filesize": "cat rotate.wasm | gzip -c9n | wc -c"
}
}
| 179 |
464 | <reponame>sailxjx/DI-engine
from .dataset import ImageNetDataset
from .sampler import DistributedSampler
| 37 |
626 | // Copyright (c) Facebook, Inc. and its affiliates.
#pragma once
#include <array>
#include <string>
#include "types.h"
////////////////
// Events
//
// Each event represents a clientbound packet that requires
// handling (a response, or a modification of GameState). These
// events are created by PacketReader and sent to EventHandler.
struct KeepaliveEvent {
uint64_t id;
};
struct LoginSuccessEvent {
std::string uuid;
std::string username;
};
struct JoinGameEvent {
uint32_t entityId;
GameMode gameMode;
};
struct SpawnPositionEvent {
BlockPos pos;
};
struct ChunkDataEvent {
int cx;
int cz;
std::array<ChunkSection, 16> chunks;
};
struct PlayerPositionAndLookEvent {
Pos pos;
Look look;
uint8_t flags;
long teleportId;
};
struct BlockChangeEvent {
BlockPos pos;
Block block;
};
struct ChatMessageEvent {
std::string chat;
uint8_t position;
};
struct AddPlayersEvent {
std::vector<std::pair<std::string, std::string>> uuidNamePairs;
};
struct RemovePlayersEvent {
std::vector<std::string> uuidsToRemove;
};
struct SpawnPlayerEvent {
unsigned long entityId;
std::string uuid;
Pos pos;
Look look;
};
struct EntityRelativeMoveEvent {
unsigned long entityId;
Pos deltaPos;
};
struct EntityLookAndRelativeMoveEvent {
unsigned long entityId;
Pos deltaPos;
Look look;
};
struct EntityTeleportEvent {
unsigned long entityId;
Pos pos;
Look look;
};
struct EntityHeadLookEvent {
unsigned long entityId;
float yaw;
};
struct DestroyEntitiesEvent {
unsigned long count;
std::vector<uint64_t> entityIds;
};
struct WindowItemsEvent {
uint8_t windowId;
std::vector<Slot> slots;
};
struct SetSlotEvent {
uint8_t windowId;
uint16_t index;
Slot slot;
};
struct ServerDifficultyEvent {
uint8_t difficulty;
};
struct SpawnMobEvent {
unsigned long entityId;
std::string uuid;
uint8_t mobType;
Pos pos;
Look look;
};
struct SpawnObjectEvent {
uint64_t entityId;
std::string uuid;
uint8_t objectType;
Pos pos;
};
struct SpawnItemStackEvent {
uint64_t entityId;
Slot item;
};
struct CollectItemEvent {
uint64_t collectedEntityId;
uint64_t collectorEntityId;
uint8_t count;
};
struct UpdateHealthEvent {
float health;
uint32_t foodLevel;
};
struct TimeUpdateEvent {
long worldAge;
long timeOfDay;
};
struct OpenWindowEvent {
uint8_t windowId;
WindowType windowType;
};
struct ConfirmTransactionEvent {
uint8_t windowId;
uint16_t counter;
bool accepted;
};
struct EntityEquipmentEvent {
unsigned long entityId;
uint8_t which;
Slot slot;
};
| 866 |
3,212 | /*
* 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.nifi.registry.db.mapper;
import org.apache.nifi.registry.db.entity.BucketItemEntityType;
import org.apache.nifi.registry.db.entity.FlowEntity;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.Nullable;
import java.sql.ResultSet;
import java.sql.SQLException;
public class FlowEntityRowMapper implements RowMapper<FlowEntity> {
@Nullable
@Override
public FlowEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
final FlowEntity flowEntity = new FlowEntity();
flowEntity.setId(rs.getString("ID"));
flowEntity.setName(rs.getString("NAME"));
flowEntity.setDescription(rs.getString("DESCRIPTION"));
flowEntity.setCreated(rs.getTimestamp("CREATED"));
flowEntity.setModified(rs.getTimestamp("MODIFIED"));
flowEntity.setBucketId(rs.getString("BUCKET_ID"));
flowEntity.setType(BucketItemEntityType.FLOW);
return flowEntity;
}
}
| 562 |
1,546 | <gh_stars>1000+
/*
* Copyright (C) 2020 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.quickstep.util;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
/**
* Utility class to executore a task on background and post the result on UI thread
*/
public abstract class CancellableTask<T> implements Runnable {
private boolean mCancelled = false;
@Override
public final void run() {
if (mCancelled) {
return;
}
T result = getResultOnBg();
if (mCancelled) {
return;
}
MAIN_EXECUTOR.execute(() -> {
if (mCancelled) {
return;
}
handleResult(result);
});
}
/**
* Called on the worker thread to process the request. The return object is passed to
* {@link #handleResult(Object)}
*/
@WorkerThread
public abstract T getResultOnBg();
/**
* Called on the UI thread to handle the final result.
* @param result
*/
@UiThread
public abstract void handleResult(T result);
/**
* Cancels the request. If it is called before {@link #handleResult(Object)}, that method
* will not be called
*/
public void cancel() {
mCancelled = true;
}
}
| 702 |
459 | // File implement/oalplus/enums/source_type_range.ipp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oalplus/source_type.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2015 <NAME>.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
namespace enums {
OALPLUS_LIB_FUNC aux::CastIterRange<
const ALenum*,
SourceType
> ValueRange_(SourceType*)
#if (!OALPLUS_LINK_LIBRARY || defined(OALPLUS_IMPLEMENTING_LIBRARY)) && \
!defined(OALPLUS_IMPL_EVR_SOURCETYPE)
#define OALPLUS_IMPL_EVR_SOURCETYPE
{
static const ALenum _values[] = {
#if defined AL_UNDETERMINED
AL_UNDETERMINED,
#endif
#if defined AL_STATIC
AL_STATIC,
#endif
#if defined AL_STREAMING
AL_STREAMING,
#endif
0
};
return aux::CastIterRange<
const ALenum*,
SourceType
>(_values, _values+sizeof(_values)/sizeof(_values[0])-1);
}
#else
;
#endif
} // namespace enums
| 395 |
12,874 | <reponame>Devyani606/chatwoot<gh_stars>1000+
{
"RESET_PASSWORD": {
"TITLE": "ریست کردن رمز عبور",
"EMAIL": {
"LABEL": "ایمیل",
"PLACEHOLDER": "لطفا ایمیل خود را وارد کنید",
"ERROR": "ظاهرا این ایمیل صحیح نیست، لطفا اصلاح کنید"
},
"API": {
"SUCCESS_MESSAGE": "لینک ریست کردن رمز عبور به ایمیلتان ارسال شد",
"ERROR_MESSAGE": "ارتباط با سرور برقرار نشد، لطفا مجددا امتحان کنید"
},
"SUBMIT": "ثبت"
}
}
| 385 |
2,338 | //===-- Implementation header for bsearch -----------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>
namespace __llvm_libc {
void *bsearch(const void *key, const void *array, size_t array_size,
size_t elem_size, int (*compare)(const void *, const void *));
} // namespace __llvm_libc
| 185 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <StdAfx.h>
#include <AzQtComponents/Components/Widgets/TabWidget.h>
#include <Editor/ConfigurationWidget.h>
#include <Editor/SettingsWidget.h>
#include <QBoxLayout>
namespace Blast
{
namespace Editor
{
ConfigurationWidget::ConfigurationWidget(QWidget* parent)
: QWidget(parent)
{
QVBoxLayout* verticalLayout = new QVBoxLayout(this);
verticalLayout->setContentsMargins(0, 5, 0, 0);
verticalLayout->setSpacing(0);
m_tabs = new AzQtComponents::TabWidget(this);
AzQtComponents::TabWidget::applySecondaryStyle(m_tabs, false);
m_settings = new SettingsWidget();
m_tabs->addTab(m_settings, "Configuration");
verticalLayout->addWidget(m_tabs);
connect(
m_settings, &SettingsWidget::onValueChanged, this,
[this](const BlastGlobalConfiguration& configuration)
{
m_configuration = configuration;
emit onConfigurationChanged(m_configuration);
});
}
ConfigurationWidget::~ConfigurationWidget() {}
void ConfigurationWidget::SetConfiguration(const BlastGlobalConfiguration& configuration)
{
m_configuration = configuration;
m_settings->SetValue(m_configuration);
}
} // namespace Editor
} // namespace Blast
#include <Editor/ConfigurationWidget.moc>
| 766 |
1,473 | <reponame>rd2281136306/pinpoint
package com.navercorp.pinpoint.plugin.arcus;
import org.junit.Ignore;
import org.junit.Test;
//@RunWith(ForkRunner.class)
//@PinpointConfig("pinpoint-test.config")
//@PinpointAgent("build/pinpoint-agent")
//@OnChildClassLoader
public class ArcusPluginTest {
// TODO how to test intercpetor?
@Test
@Ignore // until arcus modifier/interceptors are removed from pinpoint-profiler
public void test() throws Exception {
//
// Class<?> arcusClient = Class.forName("net.spy.memcached.ArcusClient");
//
// Class<?> cacheManager = Class.forName("net.spy.memcached.CacheManager");
// assertTrue(ObjectAccessor.class.isAssignableFrom(cacheManager));
//
// Class<?> collectionFuture = Class.forName("net.spy.memcached.internal.CollectionFuture");
// assertTrue(ObjectAccessor.class.isAssignableFrom(collectionFuture));
//
// Class<?> baseOperationImpl = Class.forName("net.spy.memcached.protocol.BaseOperationImpl");
// assertTrue(ObjectAccessor.class.isAssignableFrom(baseOperationImpl));
//
//
// Class<?> getFuture = Class.forName("net.spy.memcached.internal.GetFuture");
// assertTrue(ObjectAccessor.class.isAssignableFrom(getFuture));
//
// Class<?> immediateFuture = Class.forName("net.spy.memcached.internal.ImmediateFuture");
//// assertTrue(OperationAccessor.class.isAssignableFrom(immediateFuture));
//
// Class<?> operationFuture = Class.forName("net.spy.memcached.internal.OperationFuture");
// assertTrue(ObjectAccessor.class.isAssignableFrom(operationFuture));
//
// Class<?> frontCacheGetFuture = Class.forName("net.spy.memcached.plugin.FrontCacheGetFuture");
// assertTrue(ObjectAccessor.class.isAssignableFrom(frontCacheGetFuture));
// assertTrue(ObjectAccessor2.class.isAssignableFrom(frontCacheGetFuture));
//
// Class<?> frontCacheMemcachedClient = Class.forName("net.spy.memcached.plugin.FrontCacheMemcachedClient");
//
// Class<?> memcachedClient = Class.forName("net.spy.memcached.MemcachedClient");
// assertTrue(ObjectAccessor.class.isAssignableFrom(memcachedClient));
}
} | 867 |
1,006 | /****************************************************************************
* libs/libc/spawn/lib_psfa_destroy.c
*
* 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdlib.h>
#include <spawn.h>
#include <assert.h>
#include <nuttx/spawn.h>
#include "libc.h"
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: posix_spawn_file_actions_destroy
*
* Description:
* The posix_spawn_file_actions_destroy() function destroys the object
* referenced by file_actions which was previously initializeed by
* posix_spawn_file_actions_init(), returning any resources obtained at the
* time of initialization to the system for subsequent reuse. A
* posix_spawn_file_actions_t may be reinitialized after having been
* destroyed, but must not be reused after destruction, unless it has been
* reinitialized.
*
* Input Parameters:
* file_actions - The posix_spawn_file_actions_t to be destroyed.
*
* Returned Value:
* On success, these functions return 0; on failure they return an error
* number from <errno.h>.
*
****************************************************************************/
int posix_spawn_file_actions_destroy(
FAR posix_spawn_file_actions_t *file_actions)
{
FAR struct spawn_general_file_action_s *curr;
FAR struct spawn_general_file_action_s *next;
DEBUGASSERT(file_actions);
/* Destroy each file action, one at a time */
for (curr = (FAR struct spawn_general_file_action_s *)*file_actions;
curr;
curr = next)
{
/* Get the pointer to the next element before destroying the current
* one
*/
next = curr->flink;
lib_free(curr);
}
/* Mark the list empty */
*file_actions = NULL;
return OK;
}
| 793 |
2,375 | /*
* Copyright (C) 2014-2016 Qiujuer <<EMAIL>>
* WebSite http://www.qiujuer.net
* Author qiujuer
*
* 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 net.qiujuer.genius.kit.handler;
import android.os.Handler;
import android.os.Looper;
import net.qiujuer.genius.kit.handler.runable.Action;
import net.qiujuer.genius.kit.handler.runable.Func;
/**
* This is UI operation class
* You can run thread on MainThread By Async and Sync
* <p/>
* You don't need initialize, but when you don't need run
* You should call {@link #dispose()} operation for destruction.
*/
@SuppressWarnings("WeakerAccess")
final public class Run {
private static HandlerPoster uiPoster = null;
private static HandlerPoster backgroundPoster = null;
/**
* Get the Ui thread Handler
*
* @return Handler
*/
public static Handler getUiHandler() {
return getUiPoster();
}
private static HandlerPoster getUiPoster() {
if (uiPoster == null) {
synchronized (Run.class) {
if (uiPoster == null) {
// This time is 1000/60 (60fps)
// And the async dif to sync method
uiPoster = new HandlerPoster(Looper.getMainLooper(), 16, false);
}
}
}
return uiPoster;
}
/**
* Get the Background thread Handler
*
* @return Handler
*/
public static Handler getBackgroundHandler() {
return getBackgroundPoster();
}
private static HandlerPoster getBackgroundPoster() {
if (backgroundPoster == null) {
synchronized (Run.class) {
if (backgroundPoster == null) {
Thread thread = new Thread("ThreadRunHandler") {
@Override
public void run() {
Looper.prepare();
synchronized (Run.class) {
// This time is 1000*3 (3 milliseconds)
// And the async dif to sync method
backgroundPoster = new HandlerPoster(Looper.myLooper(), 3 * 1000, true);
// notify run next
try {
Run.class.notifyAll();
} catch (Exception e) {
e.printStackTrace();
}
}
Looper.loop();
}
};
thread.setDaemon(true);
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
// in this we can wait set the backgroundPoster
try {
Run.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
return backgroundPoster;
}
/**
* Asynchronously
* The current thread asynchronous run relative to the sub thread,
* not blocking the current thread
*
* @param action Action Interface, you can do something in this
*/
public static Result onBackground(Action action) {
final HandlerPoster poster = getBackgroundPoster();
if (Looper.myLooper() == poster.getLooper()) {
action.call();
return new ActionAsyncTask(action, true);
}
ActionAsyncTask task = new ActionAsyncTask(action);
poster.async(task);
return task;
}
/**
* Asynchronously
* The current thread asynchronous run relative to the main thread,
* not blocking the current thread
*
* @param action Action Interface
*/
public static Result onUiAsync(Action action) {
if (Looper.myLooper() == Looper.getMainLooper()) {
action.call();
return new ActionAsyncTask(action, true);
}
ActionAsyncTask task = new ActionAsyncTask(action);
getUiPoster().async(task);
return task;
}
/**
* Synchronously
* The current thread relative thread synchronization operation,
* blocking the current thread,
* thread for the main thread to complete
*
* @param action Action Interface
*/
public static void onUiSync(Action action) {
if (Looper.myLooper() == Looper.getMainLooper()) {
action.call();
return;
}
ActionSyncTask poster = new ActionSyncTask(action);
getUiPoster().sync(poster);
poster.waitRun();
}
/**
* Synchronously
* The current thread relative thread synchronization operation,
* blocking the current thread,
* thread for the main thread to complete
* But the current thread just wait for the waitTime long.
*
* @param action Action Interface
* @param waitMillis wait for the main thread run milliseconds Time
* @param cancelOnTimeOut on timeout the current thread cancel the runnable task
*/
public static void onUiSync(Action action, long waitMillis, boolean cancelOnTimeOut) {
onUiSync(action, waitMillis, 0, cancelOnTimeOut);
}
/**
* Synchronously
* The current thread relative thread synchronization operation,
* blocking the current thread,
* thread for the main thread to complete
* But the current thread just wait for the waitTime long.
*
* @param action Action Interface
* @param waitMillis wait for the main thread run milliseconds Time
* @param waitNanos wait for the main thread run nanoseconds Time
* @param cancelOnTimeOut on timeout the current thread cancel the runnable task
*/
public static void onUiSync(Action action, long waitMillis, int waitNanos, boolean cancelOnTimeOut) {
if (Looper.myLooper() == Looper.getMainLooper()) {
action.call();
return;
}
ActionSyncTask poster = new ActionSyncTask(action);
getUiPoster().sync(poster);
poster.waitRun(waitMillis, waitNanos, cancelOnTimeOut);
}
/**
* Synchronously
* <p/>
* In this you can receiver {@link Func#call()} return
* <p/>
* The current thread relative thread synchronization operation,
* blocking the current thread,
* thread for the main thread to complete
*
* @param func Func Interface
* @param <T> you can set any type to return
* @return {@link T}
*/
public static <T> T onUiSync(Func<T> func) {
if (Looper.myLooper() == Looper.getMainLooper()) {
return func.call();
}
FuncSyncTask<T> poster = new FuncSyncTask<T>(func);
getUiPoster().sync(poster);
return poster.waitRun();
}
/**
* Synchronously
* <p/>
* In this you can receiver {@link Func#call()} return
* <p/>
* The current thread relative thread synchronization operation,
* blocking the current thread,
* thread for the main thread to complete
* But the current thread just wait for the waitTime long.
*
* @param func Func Interface
* @param waitMillis wait for the main thread run milliseconds Time
* @param cancelOnTimeOut on timeout the current thread cancel the runnable task
* @param <T> you can set any type to return
* @return {@link T}
*/
public static <T> T onUiSync(Func<T> func, long waitMillis, boolean cancelOnTimeOut) {
return onUiSync(func, waitMillis, 0, cancelOnTimeOut);
}
/**
* Synchronously
* <p/>
* In this you can receiver {@link Func#call()} return
* <p/>
* The current thread relative thread synchronization operation,
* blocking the current thread,
* thread for the main thread to complete
* But the current thread just wait for the waitTime long.
*
* @param func Func Interface
* @param waitMillis wait for the main thread run milliseconds Time
* @param waitNanos wait for the main thread run nanoseconds Time
* @param cancelOnTimeOut on timeout the current thread cancel the runnable task
* @param <T> you can set any type to return
* @return {@link T}
*/
public static <T> T onUiSync(Func<T> func, long waitMillis, int waitNanos, boolean cancelOnTimeOut) {
if (Looper.myLooper() == Looper.getMainLooper()) {
return func.call();
}
FuncSyncTask<T> poster = new FuncSyncTask<T>(func);
getUiPoster().sync(poster);
return poster.waitRun(waitMillis, waitNanos, cancelOnTimeOut);
}
/**
* Call this on you need dispose
*/
public static void dispose() {
if (uiPoster != null) {
uiPoster.dispose();
uiPoster = null;
}
}
}
| 4,100 |
325 | <gh_stars>100-1000
package com.box.l10n.mojito.slack;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties("l10n.slack")
public class SlackClientConfiguration {
String token;
@ConditionalOnProperty("l10n.slack.token")
@Bean
SlackClient getSlackClient() {
return new SlackClient(token);
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
| 242 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Epernon","circ":"1ère circonscription","dpt":"Eure-et-Loir","inscrits":3820,"abs":2422,"votants":1398,"blancs":126,"nuls":54,"exp":1218,"res":[{"nuance":"REM","nom":"<NAME>","voix":770},{"nuance":"LR","nom":"<NAME>","voix":448}]} | 115 |
2,634 | #define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_DDS_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb_image.h"
#include "stb_image_dds.h"
#include "stb_image_write.h"
#include "stb_image_resize.h"
| 113 |
1,130 | #include <stdio.h>
#include <string.h>
int main()
{
char a[10];
strcpy(a, "abcdef");
printf("%s\n", &a[1]);
return 0;
}
/* vim: set expandtab ts=4 sw=3 sts=3 tw=80 :*/
| 90 |
343 | <filename>internal/ccall/glcomp/glcompdefs.h
/* $Id$Revision: */
/* vim:set shiftwidth=4 ts=8: */
/*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************/
#ifndef GLCOMPDEFS_H
#define GLCOMPDEFS_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#ifdef WIN32
#include <windows.h>
#include <winuser.h>
#include <tchar.h>
#endif
#include <GL/gl.h>
#include <stdlib.h>
#include <stdio.h>
#include <GL/gl.h>
#include <GL/glu.h>
#ifdef WIN32
#define strdup _strdup
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define GLCOMPSET_PANEL_COLOR_R (GLfloat)0.16
#define GLCOMPSET_PANEL_COLOR_G (GLfloat)0.44
#define GLCOMPSET_PANEL_COLOR_B (GLfloat)0.87
#define GLCOMPSET_PANEL_COLOR_ALPHA (GLfloat)0.5
#define GLCOMPSET_PANEL_SHADOW_COLOR_R (GLfloat)0
#define GLCOMPSET_PANEL_SHADOW_COLOR_G (GLfloat)0
#define GLCOMPSET_PANEL_SHADOW_COLOR_B (GLfloat)0
#define GLCOMPSET_PANEL_SHADOW_COLOR_A (GLfloat)0.3
#define GLCOMPSET_PANEL_SHADOW_WIDTH (GLfloat)4
#define GLCOMPSET_BUTTON_COLOR_R (GLfloat)0
#define GLCOMPSET_BUTTON_COLOR_G (GLfloat)1
#define GLCOMPSET_BUTTON_COLOR_B (GLfloat)0.3
#define GLCOMPSET_BUTTON_COLOR_ALPHA (GLfloat)0.6
#define GLCOMPSET_BUTTON_THICKNESS (GLfloat)3
#define GLCOMPSET_BUTTON_BEVEL_BRIGHTNESS (GLfloat)1.7
#define GLCOMPSET_FONT_SIZE (GLfloat)14
#define GLCOMPSET_BUTTON_FONT_COLOR_R (GLfloat)0
#define GLCOMPSET_BUTTON_FONT_COLOR_G (GLfloat)0
#define GLCOMPSET_BUTTON_FONT_COLOR_B (GLfloat)0
#define GLCOMPSET_BUTTON_FONT_COLOR_ALPHA (GLfloat)1
#define GLCOMPSET_FONT_SIZE_FACTOR (GLfloat)0.7
#define GLCOMPSET_LABEL_COLOR_R (GLfloat)0
#define GLCOMPSET_LABEL_COLOR_G (GLfloat)0
#define GLCOMPSET_LABEL_COLOR_B (GLfloat)0
#define GLCOMPSET_LABEL_COLOR_ALPHA (GLfloat)1
#define GLCOMPSET_FONT_COLOR_R (GLfloat)0
#define GLCOMPSET_FONT_COLOR_G (GLfloat)0
#define GLCOMPSET_FONT_COLOR_B (GLfloat)0
#define GLCOMPSET_FONT_COLOR_ALPHA (GLfloat)1
#define GLCOMPSET_FONT_DESC "Times Italic"
#define GL_FONTOPTIMIZE 1
#define GL_FONTVJUSTIFY 0
#define GL_FONTHJUSTIFY 0
#define DEFAULT_GLUT_FONT GLUT_BITMAP_HELVETICA_12
#define GLCOMPSET_BORDERWIDTH (GLfloat)2
#define GLCOMPSET_PANEL_BORDERWIDTH (GLfloat)3
#define GLCOMPSET_BUTTON_BEVEL (GLfloat)5
#define GLCOMPSET_BEVEL_DIFF (GLfloat)0.001
#define GLCOMPSET_DEFAULT_PAD (GLfloat)3
#define GLCOMP_DEFAULT_WIDTH (GLfloat)10
#define GLCOMP_DEFAULT_HEIGHT (GLfloat)10
#define FONT_MAX_LEN 1024 /* maximum chars to draw to the screen, used for buffers also */
#define FONT_TAB_SPACE 4 /* spaces to draw for a tab, make option? */
#define C_DPI 16
#define R_DPI 16
typedef enum { inverted_y, scientific_y } glCompOrientation;
typedef enum { gluttext, pangotext } glCompFontType;
typedef enum { glAlignNone, glAlignLeft, glAlignTop, glAlignBottom,
glAlignRight, glAlignParent, glAlignCenter } glCompAlignment;
typedef enum { glFontVJustifyNone, glFontVJustifyTop,
glFontVJustifyBottom, glFontVJustifyCenter } glCompVJustify;
typedef enum { glFontHJustifyNone, glFontHJustifyLeft,
glFontHJustifyRight, glFontHJustifyCenter } glCompHJustify;
typedef enum { glButtonGlyphLeft, glButtonGlyphRight, glButtonGlyphTop,
glButtonGlyphBottom } glCompButtonGlyph;
typedef enum { glBorderNone, glBorderSolid, glBorderBevel,
glBorderCustom } glCompBorderType;
typedef enum { glMouseDown, glMouseUp } glCompMouseStatus;
typedef enum { glMouseLeftButton, glMouseRightButton,
glMouseMiddleButton } glMouseButtonType;
typedef enum { glTexImage, glTexLabel } glCompTexType;
typedef enum { glPanelObj, glButtonObj, glLabelObj,
glImageObj } glObjType;
typedef struct _glCompButton glCompButton;
typedef struct _glCompObj glCompObj;
/*call backs for widgets*/
typedef void (*glcompdrawfunc_t) (void *obj);
typedef void (*glcompclickfunc_t) (glCompObj * obj, GLfloat x,
GLfloat y, glMouseButtonType t);
typedef void (*glcompdoubleclickfunc_t) (glCompObj * obj, GLfloat x,
GLfloat y,
glMouseButtonType t);
typedef void (*glcompmouseoverfunc_t) (glCompObj * obj, GLfloat x,
GLfloat y);
typedef void (*glcompmouseinfunc_t) (glCompObj * obj, GLfloat x,
GLfloat y);
typedef void (*glcompmouseoutfunc_t) (glCompObj * obj, GLfloat x,
GLfloat y);
typedef void (*glcompmousedownfunc_t) (glCompObj * obj, GLfloat x,
GLfloat y, glMouseButtonType t);
typedef void (*glcompmouseupfunc_t) (glCompObj * obj, GLfloat x,
GLfloat y, glMouseButtonType t);
typedef void (*glcompmousedragfunct_t) (glCompObj * obj, GLfloat dx,
GLfloat dy,
glMouseButtonType t);
typedef struct _glCompAnchor {
int topAnchor; /*anchor booleans */
int leftAnchor;
int rightAnchor;
int bottomAnchor;
GLfloat top; /*anchor values */
GLfloat left;
GLfloat right;
GLfloat bottom;
} glCompAnchor;
typedef struct _glCompJustify {
glCompVJustify VJustify;
glCompHJustify HJustify;
} glCompJustify;
typedef struct _glCompPoint {
GLfloat x, y, z;
} glCompPoint;
typedef struct _glCompPointI {
int x, y;
} glCompPointI;
typedef struct {
int cnt;
int hotKey;
glCompPoint* pts;
}glCompPoly;
typedef struct {
GLfloat R;
GLfloat G;
GLfloat B;
GLfloat A; //Alpha
int tag;
int test;
} glCompColor;
typedef struct _glCompRect {
glCompPoint pos;
GLfloat w;
GLfloat h;
} glCompRect;
typedef struct _glCompTex {
GLuint id;
char *def;
char *text;
float width;
float height;
glCompTexType type;
int userCount;
int fontSize;
unsigned char *data; /*data */
} glCompTex;
/*opengl font*/
typedef struct {
char *fontdesc; //font description , only used with pango fonts
glCompColor color;
glCompFontType type;
void *glutfont; /*glut font pointer if used */
int transparent;
glCompTex *tex; /* texture, if type is pangotext */
int size;
int reference; /*if font has references to parent */
glCompJustify justify;
int is2D;
int optimize;
} glCompFont;
typedef struct _glCompCallBacks {
glcompdrawfunc_t draw;
glcompclickfunc_t click;
glcompdoubleclickfunc_t doubleclick;
glcompmouseoverfunc_t mouseover;
glcompmouseinfunc_t mousein;
glcompmouseoutfunc_t mouseout;
glcompmousedownfunc_t mousedown;
glcompmouseupfunc_t mouseup;
glcompmousedragfunct_t mousedrag;
} glCompCallBacks;
/*
common widget properties
also each widget has pointer to its parents common
*/
typedef struct _glCompCommon {
glCompPoint pos;
glCompPoint refPos; /*calculated pos after anchors and aligns */
GLfloat width, height;
GLfloat borderWidth;
glCompBorderType borderType;
glCompColor color;
int enabled;
int visible;
void *compset; // compset
void *parent; /*parent widget */
int data;
glCompFont *font; //pointer to font to use
glCompAlignment align;
glCompAnchor anchor;
int layer; /*keep track of object order, what to draw on top */
glCompCallBacks callbacks;
glCompCallBacks functions;
glCompJustify justify;
} glCompCommon;
/*generic image*/
typedef struct _glCompImage {
glObjType objType; /*always keep this here for each drawable object */
glCompCommon common;
glCompTex *texture;
GLfloat width, height; /* width and height in world coords */
/* char *pngFile; */
int stretch;
} glCompImage;
/*generic panel*/
typedef struct _glCompPanel {
glObjType objType; /*always keep this here for each drawable object */
glCompCommon common;
GLfloat shadowwidth;
glCompColor shadowcolor;
char *text;
glCompImage *image;
} glCompPanel;
/*label*/
typedef struct _glCompLabel {
glObjType objType; /*always keep this here for each drawable object */
glCompCommon common;
int autosize; /*if 1 label sized is calculated from font */
char *text;
int transparent;
} glCompLabel;
/*buttons*/
struct _glCompButton {
glObjType objType; /*always keep this here for each drawable object */
glCompCommon common;
GLfloat width, height;
glCompLabel *label;
int status; //0 not pressed 1 pressed;
int refStatus; //0 not pressed 1 pressed;
int groupid;
glCompImage *image; /*glyph */
glCompButtonGlyph glyphPos;
void *customptr; //general purpose void pointer to pass to call back
int data;
};
/*texture based image*/
/*track bar*/
typedef struct _glCompTrackBar {
glObjType objType; /*always keep this here for each drawable object */
GLfloat width, height;
glCompPanel *outerpanel;
glCompPanel *trackline;
glCompPanel *indicator;
GLfloat bevel;
glCompColor color;
glCompColor shadowcolor;
float value;
float maxvalue;
float minvalue;
int enabled;
int visible;
void *parentset; //parent compset
int data;
glCompFont *font; //pointer to font to use
glCompOrientation orientation;
} glCompTrackBar;
/*glCompFont container class*/
typedef struct {
glCompFont **fonts;
int count;
int activefont;
char *font_directory; //location where the glfont files are stored
} fontset_t;
/*object prototype*/
struct _glCompObj {
glObjType objType;
glCompCommon common;
};
typedef struct _glCompMouse {
glCompMouseStatus status;
glMouseButtonType t;
glCompPoint initPos; /*current mouse pos,*/
glCompPoint pos; /*current mouse pos,*/
glCompPoint finalPos; /*current mouse pos,*/
glCompPoint GLpos;/*3d converted opengl position*/
glCompPoint GLinitPos;/*mouse button down pos*/
glCompPoint GLfinalPos;/*mouse button up pos*/
GLfloat dragX, dragY;/*GLpos - GLinitpos*/
glCompObj *clickedObj;
glCompCallBacks callbacks;
glCompCallBacks functions;
int down;
} glCompMouse;
/*main widget set manager*/
typedef struct {
glObjType objType; /*always keep this here for each drawable object */
glCompCommon common;
glCompObj **obj;
int objcnt;
glCompPanel **panels;
glCompButton **buttons;
glCompLabel **labels;
int groupCount; /*group id counter */
int active; //0 dont draw, 1 draw
int enabled; //0 disabled 1 enabled(allow mouse interaction)
GLfloat clickedX, clickedY;
int textureCount;
glCompTex **textures;
glCompMouse mouse;
} glCompSet;
#ifdef __cplusplus
}
#endif
#endif
| 4,232 |
1,144 | // SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2015 National Instruments
*
* (C) Copyright 2015
* <NAME> <<EMAIL>>
*/
#include <asm/eth-raw-os.h>
#include <common.h>
#include <dm.h>
#include <malloc.h>
#include <net.h>
DECLARE_GLOBAL_DATA_PTR;
static int reply_arp;
static struct in_addr arp_ip;
static int sb_eth_raw_start(struct udevice *dev)
{
struct eth_sandbox_raw_priv *priv = dev_get_priv(dev);
struct eth_pdata *pdata = dev_get_platdata(dev);
const char *interface;
debug("eth_sandbox_raw: Start\n");
interface = fdt_getprop(gd->fdt_blob, dev_of_offset(dev),
"host-raw-interface", NULL);
if (interface == NULL)
return -EINVAL;
if (strcmp(interface, "lo") == 0) {
priv->local = 1;
env_set("ipaddr", "127.0.0.1");
env_set("serverip", "127.0.0.1");
}
return sandbox_eth_raw_os_start(interface, pdata->enetaddr, priv);
}
static int sb_eth_raw_send(struct udevice *dev, void *packet, int length)
{
struct eth_sandbox_raw_priv *priv = dev_get_priv(dev);
debug("eth_sandbox_raw: Send packet %d\n", length);
if (priv->local) {
struct ethernet_hdr *eth = packet;
if (ntohs(eth->et_protlen) == PROT_ARP) {
struct arp_hdr *arp = packet + ETHER_HDR_SIZE;
/**
* localhost works on a higher-level API in Linux than
* ARP packets, so fake it
*/
arp_ip = net_read_ip(&arp->ar_tpa);
reply_arp = 1;
return 0;
}
packet += ETHER_HDR_SIZE;
length -= ETHER_HDR_SIZE;
}
return sandbox_eth_raw_os_send(packet, length, priv);
}
static int sb_eth_raw_recv(struct udevice *dev, int flags, uchar **packetp)
{
struct eth_pdata *pdata = dev_get_platdata(dev);
struct eth_sandbox_raw_priv *priv = dev_get_priv(dev);
int retval = 0;
int length;
if (reply_arp) {
struct arp_hdr *arp = (void *)net_rx_packets[0] +
ETHER_HDR_SIZE;
/*
* Fake an ARP response. The u-boot network stack is sending an
* ARP request (to find the MAC address to address the actual
* packet to) and requires an ARP response to continue. Since
* this is the localhost interface, there is no Etherent level
* traffic at all, so there is no way to send an ARP request or
* to get a response. For this reason we fake the response to
* make the u-boot network stack happy.
*/
arp->ar_hrd = htons(ARP_ETHER);
arp->ar_pro = htons(PROT_IP);
arp->ar_hln = ARP_HLEN;
arp->ar_pln = ARP_PLEN;
arp->ar_op = htons(ARPOP_REPLY);
/* Any non-zero MAC address will work */
memset(&arp->ar_sha, 0x01, ARP_HLEN);
/* Use whatever IP we were looking for (always 127.0.0.1?) */
net_write_ip(&arp->ar_spa, arp_ip);
memcpy(&arp->ar_tha, pdata->enetaddr, ARP_HLEN);
net_write_ip(&arp->ar_tpa, net_ip);
length = ARP_HDR_SIZE;
} else {
/* If local, the Ethernet header won't be included; skip it */
uchar *pktptr = priv->local ?
net_rx_packets[0] + ETHER_HDR_SIZE : net_rx_packets[0];
retval = sandbox_eth_raw_os_recv(pktptr, &length, priv);
}
if (!retval && length) {
if (priv->local) {
struct ethernet_hdr *eth = (void *)net_rx_packets[0];
/* Fill in enough of the missing Ethernet header */
memcpy(eth->et_dest, pdata->enetaddr, ARP_HLEN);
memset(eth->et_src, 0x01, ARP_HLEN);
eth->et_protlen = htons(reply_arp ? PROT_ARP : PROT_IP);
reply_arp = 0;
length += ETHER_HDR_SIZE;
}
debug("eth_sandbox_raw: received packet %d\n",
length);
*packetp = net_rx_packets[0];
return length;
}
return retval;
}
static void sb_eth_raw_stop(struct udevice *dev)
{
struct eth_sandbox_raw_priv *priv = dev_get_priv(dev);
debug("eth_sandbox_raw: Stop\n");
sandbox_eth_raw_os_stop(priv);
}
static const struct eth_ops sb_eth_raw_ops = {
.start = sb_eth_raw_start,
.send = sb_eth_raw_send,
.recv = sb_eth_raw_recv,
.stop = sb_eth_raw_stop,
};
static int sb_eth_raw_ofdata_to_platdata(struct udevice *dev)
{
struct eth_pdata *pdata = dev_get_platdata(dev);
pdata->iobase = devfdt_get_addr(dev);
return 0;
}
static const struct udevice_id sb_eth_raw_ids[] = {
{ .compatible = "sandbox,eth-raw" },
{ }
};
U_BOOT_DRIVER(eth_sandbox_raw) = {
.name = "eth_sandbox_raw",
.id = UCLASS_ETH,
.of_match = sb_eth_raw_ids,
.ofdata_to_platdata = sb_eth_raw_ofdata_to_platdata,
.ops = &sb_eth_raw_ops,
.priv_auto_alloc_size = sizeof(struct eth_sandbox_raw_priv),
.platdata_auto_alloc_size = sizeof(struct eth_pdata),
};
| 1,878 |
828 | /*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hasor.rsf.rpc.net.http;
import net.hasor.rsf.InterAddress;
import net.hasor.rsf.domain.RequestInfo;
import net.hasor.rsf.domain.ResponseInfo;
import java.io.IOException;
/**
* Http 解码器组
* @version : 2017年11月22日
* @author 赵永春 (<EMAIL>)
*/
public interface HttpHandler {
/**
* 接收到 http request 请求并做出响应。
* 1. 可以解析 httpRequest,并生成 RequestInfo 对象。然后 outputTo.callRPC 进行服务调用。
* 2. 或者直接把rpc结果写到 RsfHttpResponse 的输出流中,然后直接 outputTo.finishRPC 完成响应。
*/
public void receivedRequest(RsfHttpRequest httpRequest, RsfHttpResponse httpResponse, HttpResult outputTo) throws Throwable;
/** 结果处理方式 */
public static interface HttpResult {
/**
* 方式一:解析 httpRequest,并生成 RequestInfo 对象,然后让 rsf 调度这个请求。
* @throws IllegalStateException callRPC、finishRPC 两个方法中只有一个能被成功调用,且只能调用一次。
*/
public void callRPC(RequestInfo requestInfo, ResponseEncoder encoder);
/**
* 方式二:结束 RPC 调用立即进行 response 响应。
* @throws IllegalStateException callRPC、finishRPC 两个方法中只有一个能被成功调用,且只能调用一次。
*/
public void finishRPC();
}
/** Response 编码器 */
public static interface ResponseEncoder {
/** 发生异常 */
public void exception(RsfHttpResponse httpResponse, Throwable e) throws IOException;
/** 完成调用 */
public void complete(RsfHttpResponse httpResponse, ResponseInfo info) throws IOException;
}
//
// ------------------------------------------------------------------------------------------------------
//
/**
* 准备向外发送 http request 请求。
* 1. 可以解析 RequestInfo,并生成 RequestObject 对象。然后通过 builder.sendRequest 进行服务调用。
* 2. 或者直接把rpc结果写到 builder.finishRequest 中。
*/
public void sendRequest(InterAddress requestHost, RequestInfo info, SenderBuilder builder) throws Throwable;
/** Response 编码器 */
public static interface SenderBuilder {
/**
* 方式一:发送调用请求。
* @throws IllegalStateException sendRequest、finishRequest 两个方法中只有一个能被成功调用,且只能调用一次。
*/
public void sendRequest(RequestObject httpRequest, ResponseDecoder decoder);
/**
* 方式二:直接给出请求结果。
* @throws IllegalStateException sendRequest、finishRequest 两个方法中只有一个能被成功调用,且只能调用一次。
*/
public void finishRequest(ResponseInfo responseInfo) throws IOException;
}
/** Response 解码器 */
public static interface ResponseDecoder {
/** 完成调用 */
public ResponseInfo complete(long requestID, RsfHttpResponseData httpResponse) throws IOException;
}
} | 1,608 |
364 | <reponame>xiaobing007/dagli<gh_stars>100-1000
package com.linkedin.dagli.preparer;
import com.linkedin.dagli.objectio.ObjectReader;
import com.linkedin.dagli.transformer.PreparedTransformer;
/**
* Base interface for preparers of dynamic-arity transformers.
*
* @param <R> the type of value produced by the transformer.
* @param <N> the type of the resultant prepared transformer.
*/
public interface PreparerDynamic<R, N extends PreparedTransformer<? extends R>> extends Preparer<R, N> {
@Override
PreparerResultMixed<? extends PreparedTransformer<? extends R>, N> finishUnsafe(ObjectReader<Object[]> inputs);
}
| 190 |
10,225 | <reponame>CraigMcDonaldCodes/quarkus
package io.quarkus.hibernate.validator.test;
import javax.inject.Inject;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Pattern;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
public class UserCountryNotSetValidatorLocaleTest {
@Inject
ValidatorFactory validatorFactory;
@RegisterExtension
static final QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(() -> ShrinkWrap
.create(JavaArchive.class).addClasses(Bean.class)
.addAsResource(new StringAsset("foo=bar"), "application.properties"))
.setBeforeAllCustomizer(new Runnable() {
@Override
public void run() {
userCountry = System.clearProperty("user.country");
userLanguage = System.clearProperty("user.language");
}
}).setAfterAllCustomizer(new Runnable() {
@Override
public void run() {
if (userCountry != null) {
System.setProperty("user.country", userCountry);
}
System.setProperty("user.language", userLanguage);
}
});
private static String userCountry;
private static String userLanguage;
@Test
public void testApplicationStarts() {
// we don't really need to test anything, just make sure that the application starts
}
static class Bean {
public Bean(String name) {
super();
this.name = name;
}
@Pattern(regexp = "A.*", message = "{pattern.message}")
private String name;
}
}
| 850 |
1,350 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.apimanagement.implementation;
import com.azure.resourcemanager.apimanagement.fluent.models.RegionContractInner;
import com.azure.resourcemanager.apimanagement.models.RegionContract;
public final class RegionContractImpl implements RegionContract {
private RegionContractInner innerObject;
private final com.azure.resourcemanager.apimanagement.ApiManagementManager serviceManager;
RegionContractImpl(
RegionContractInner innerObject, com.azure.resourcemanager.apimanagement.ApiManagementManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
}
public String name() {
return this.innerModel().name();
}
public Boolean isMasterRegion() {
return this.innerModel().isMasterRegion();
}
public Boolean isDeleted() {
return this.innerModel().isDeleted();
}
public RegionContractInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.apimanagement.ApiManagementManager manager() {
return this.serviceManager;
}
}
| 409 |
8,451 | <filename>core/src/main/java/io/questdb/griffin/engine/functions/conditional/SwitchFunctionFactory.java
/*******************************************************************************
* ___ _ ____ ____
* / _ \ _ _ ___ ___| |_| _ \| __ )
* | | | | | | |/ _ \/ __| __| | | | _ \
* | |_| | |_| | __/\__ \ |_| |_| | |_) |
* \__\_\\__,_|\___||___/\__|____/|____/
*
* Copyright (c) 2014-2019 Appsicle
* Copyright (c) 2019-2020 QuestDB
*
* 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.questdb.griffin.engine.functions.conditional;
import io.questdb.cairo.CairoConfiguration;
import io.questdb.cairo.ColumnType;
import io.questdb.cairo.sql.Function;
import io.questdb.cairo.sql.Record;
import io.questdb.griffin.FunctionFactory;
import io.questdb.griffin.SqlCompiler;
import io.questdb.griffin.SqlException;
import io.questdb.griffin.SqlExecutionContext;
import io.questdb.griffin.engine.functions.constants.Constants;
import io.questdb.std.*;
public class SwitchFunctionFactory implements FunctionFactory {
private static final LongMethod GET_LONG = SwitchFunctionFactory::getLong;
private static final IntMethod GET_SHORT = SwitchFunctionFactory::getShort;
private static final IntMethod GET_BYTE = SwitchFunctionFactory::getByte;
private static final IntMethod GET_INT = SwitchFunctionFactory::getInt;
private static final IntMethod GET_CHAR = SwitchFunctionFactory::getChar;
private static final LongMethod GET_DATE = SwitchFunctionFactory::getDate;
private static final LongMethod GET_TIMESTAMP = SwitchFunctionFactory::getTimestamp;
private static final CharSequenceMethod GET_STRING = SwitchFunctionFactory::getString;
private static final CharSequenceMethod GET_SYMBOL = SwitchFunctionFactory::getSymbol;
@Override
public String getSignature() {
return "switch(V)";
}
@Override
public Function newInstance(int position, ObjList<Function> args, IntList argPositions, CairoConfiguration configuration, SqlExecutionContext sqlExecutionContext) throws SqlException {
int n = args.size();
final Function keyFunction = args.getQuick(0);
final int keyType = keyFunction.getType();
final Function elseBranch;
if (n % 2 == 0) {
elseBranch = args.getLast();
n--;
} else {
elseBranch = null;
}
int returnType = -1;
for (int i = 1; i < n; i += 2) {
final Function keyFunc = args.getQuick(i);
final int keyArgType = keyFunc.getType();
if (!keyFunc.isConstant()) {
throw SqlException.$(argPositions.getQuick(i), "constant expected");
}
if (!SqlCompiler.isAssignableFrom(keyType, keyArgType)) {
throw SqlException.position(argPositions.getQuick(i))
.put("type mismatch [expected=").put(ColumnType.nameOf(keyType))
.put(", actual=").put(ColumnType.nameOf(keyArgType))
.put(']');
}
// determine common return type
final Function value = args.getQuick(i + 1);
returnType = CaseCommon.getCommonType(returnType, value.getType(), argPositions.getQuick(i + 1));
}
// another loop to create cast functions and replace current value function
// start with 2 to avoid offsetting each function position
for (int i = 2; i < n; i += 2) {
args.setQuick(i,
CaseCommon.getCastFunction(
args.getQuick(i),
argPositions.getQuick(i),
returnType,
configuration,
sqlExecutionContext
)
);
}
switch (ColumnType.tagOf(keyType)) {
case ColumnType.CHAR:
return getIntKeyedFunction(args, argPositions, position, n, keyFunction, returnType, elseBranch, GET_CHAR);
case ColumnType.INT:
return getIntKeyedFunction(args, argPositions, position, n, keyFunction, returnType, elseBranch, GET_INT);
case ColumnType.BYTE:
return getIntKeyedFunction(args, argPositions, position, n, keyFunction, returnType, elseBranch, GET_BYTE);
case ColumnType.SHORT:
return getIntKeyedFunction(args, argPositions, position, n, keyFunction, returnType, elseBranch, GET_SHORT);
case ColumnType.LONG:
return getLongKeyedFunction(args, argPositions, position, n, keyFunction, returnType, elseBranch, GET_LONG);
case ColumnType.DATE:
return getLongKeyedFunction(args, argPositions, position, n, keyFunction, returnType, elseBranch, GET_DATE);
case ColumnType.TIMESTAMP:
return getLongKeyedFunction(args, argPositions, position, n, keyFunction, returnType, elseBranch, GET_TIMESTAMP);
case ColumnType.BOOLEAN:
return getIfElseFunction(args, argPositions, position, n, keyFunction, returnType, elseBranch);
case ColumnType.STRING:
return getCharSequenceKeyedFunction(args, argPositions, position, n, keyFunction, returnType, elseBranch, GET_STRING);
case ColumnType.SYMBOL:
return getCharSequenceKeyedFunction(args, argPositions, position, n, keyFunction, returnType, elseBranch, GET_SYMBOL);
default:
throw SqlException.
$(argPositions.getQuick(0), "type ")
.put(ColumnType.nameOf(keyType))
.put(" is not supported in 'switch' type of 'case' statement");
}
}
private static char getChar(Function function, Record record) {
return function.getChar(record);
}
private static int getInt(Function function, Record record) {
return function.getInt(record);
}
private static byte getByte(Function function, Record record) {
return function.getByte(record);
}
private static short getShort(Function function, Record record) {
return function.getShort(record);
}
private static long getLong(Function function, Record record) {
return function.getLong(record);
}
private static long getDate(Function function, Record record) {
return function.getDate(record);
}
private static long getTimestamp(Function function, Record record) {
return function.getTimestamp(record);
}
private static CharSequence getString(Function function, Record record) {
return function.getStr(record);
}
private static CharSequence getSymbol(Function function, Record record) {
return function.getSymbol(record);
}
private Function getCharSequenceKeyedFunction(
ObjList<Function> args,
IntList argPositions,
int position,
int n,
Function keyFunction,
int valueType,
Function elseBranch,
CharSequenceMethod method
) throws SqlException {
final CharSequenceObjHashMap<Function> map = new CharSequenceObjHashMap<>();
final ObjList<Function> argsToPoke = new ObjList<>();
Function nullFunc = null;
for (int i = 1; i < n; i += 2) {
final Function fun = args.getQuick(i);
final CharSequence key = method.getKey(fun, null);
if (key == null) {
nullFunc = args.getQuick(i + 1);
} else {
final int index = map.keyIndex(key);
if (index < 0) {
throw SqlException.$(argPositions.getQuick(i), "duplicate branch");
}
map.putAt(index, key, args.getQuick(i + 1));
argsToPoke.add(args.getQuick(i + 1));
}
}
final Function elseB = getElseFunction(valueType, elseBranch);
final CaseFunctionPicker picker;
if (nullFunc == null) {
picker = record -> {
final CharSequence value = method.getKey(keyFunction, record);
if (value != null) {
final int index = map.keyIndex(value);
if (index < 0) {
return map.valueAtQuick(index);
}
}
return elseB;
};
} else {
final Function nullFuncRef = nullFunc;
picker = record -> {
final CharSequence value = method.getKey(keyFunction, record);
if (value == null) {
return nullFuncRef;
}
final int index = map.keyIndex(value);
if (index < 0) {
return map.valueAtQuick(index);
}
return elseB;
};
argsToPoke.add(nullFunc);
}
argsToPoke.add(elseB);
argsToPoke.add(keyFunction);
return CaseCommon.getCaseFunction(position, valueType, picker, argsToPoke);
}
private Function getElseFunction(int valueType, Function elseBranch) {
return elseBranch != null ? elseBranch : Constants.getNullConstant(valueType);
}
private Function getIfElseFunction(
ObjList<Function> args,
IntList argPositions,
int position,
int n,
Function keyFunction,
int returnType,
Function elseBranch
) throws SqlException {
final CaseFunctionPicker picker;
final ObjList<Function> argsToPoke;
if (n == 3) {
// only one conditional branch
boolean value = args.getQuick(1).getBool(null);
final Function branch = args.getQuick(2);
final Function elseB = getElseFunction(returnType, elseBranch);
if (value) {
picker = record -> keyFunction.getBool(record) ? branch : elseB;
} else {
picker = record -> keyFunction.getBool(record) ? elseB : branch;
}
argsToPoke = new ObjList<>();
argsToPoke.add(keyFunction);
argsToPoke.add(elseB);
argsToPoke.add(branch);
} else if (n == 5) {
final boolean a = args.getQuick(1).getBool(null);
final Function branchA = args.getQuick(2);
final boolean b = args.getQuick(3).getBool(null);
final Function branchB = args.getQuick(4);
if (a && b || !a && !b) {
throw SqlException.$(argPositions.getQuick(3), "duplicate branch");
}
if (a) {
picker = record -> keyFunction.getBool(record) ? branchA : branchB;
} else {
picker = record -> keyFunction.getBool(record) ? branchB : branchA;
}
argsToPoke = new ObjList<>();
argsToPoke.add(keyFunction);
argsToPoke.add(branchA);
argsToPoke.add(branchB);
} else {
throw SqlException.$(argPositions.getQuick(5), "too many branches");
}
return CaseCommon.getCaseFunction(position, returnType, picker, argsToPoke);
}
private Function getIntKeyedFunction(
ObjList<Function> args,
IntList argPositions,
int position,
int n,
Function keyFunction,
int valueType,
Function elseBranch,
IntMethod intMethod
) throws SqlException {
final IntObjHashMap<Function> map = new IntObjHashMap<>();
final ObjList<Function> argsToPoke = new ObjList<>();
for (int i = 1; i < n; i += 2) {
final Function fun = args.getQuick(i);
final int key = intMethod.getKey(fun, null);
final int index = map.keyIndex(key);
if (index < 0) {
throw SqlException.$(argPositions.getQuick(i), "duplicate branch");
}
map.putAt(index, key, args.getQuick(i + 1));
argsToPoke.add(args.getQuick(i + 1));
}
final Function elseB = getElseFunction(valueType, elseBranch);
final CaseFunctionPicker picker = record -> {
final int index = map.keyIndex(intMethod.getKey(keyFunction, record));
if (index < 0) {
return map.valueAtQuick(index);
}
return elseB;
};
argsToPoke.add(elseB);
argsToPoke.add(keyFunction);
return CaseCommon.getCaseFunction(position, valueType, picker, argsToPoke);
}
private Function getLongKeyedFunction(
ObjList<Function> args,
IntList argPositions,
int position,
int n,
Function keyFunction,
int valueType,
Function elseBranch,
LongMethod longMethod
) throws SqlException {
final LongObjHashMap<Function> map = new LongObjHashMap<>();
final ObjList<Function> argsToPoke = new ObjList<>();
for (int i = 1; i < n; i += 2) {
final Function fun = args.getQuick(i);
final long key = longMethod.getKey(fun, null);
final int index = map.keyIndex(key);
if (index < 0) {
throw SqlException.$(argPositions.getQuick(i), "duplicate branch");
}
map.putAt(index, key, args.getQuick(i + 1));
argsToPoke.add(args.getQuick(i + 1));
}
final Function elseB = getElseFunction(valueType, elseBranch);
final CaseFunctionPicker picker = record -> {
final int index = map.keyIndex(longMethod.getKey(keyFunction, record));
if (index < 0) {
return map.valueAtQuick(index);
}
return elseB;
};
argsToPoke.add(elseB);
argsToPoke.add(keyFunction);
return CaseCommon.getCaseFunction(position, valueType, picker, argsToPoke);
}
@FunctionalInterface
private interface IntMethod {
int getKey(Function function, Record record);
}
@FunctionalInterface
private interface LongMethod {
long getKey(Function function, Record record);
}
@FunctionalInterface
private interface CharSequenceMethod {
CharSequence getKey(Function function, Record record);
}
}
| 6,671 |
2,255 | <reponame>psmitty7373/koadic<filename>core/cidr.py
# Parts of this file are:
# Copyright (c) 2007 <NAME>
# 2015 Updates by <NAME>
# Licensed under the MIT license.
# http://brandon.sternefamily.net/files/mit-license.txt
# CIDR Block Converter - 2007
def ip2bin(ip):
b = ""
inQuads = ip.split(".")
outQuads = 4
for q in inQuads:
if q != "":
b += dec2bin(int(q),8)
outQuads -= 1
while outQuads > 0:
b += "00000000"
outQuads -= 1
return b
def dec2bin(n,d=None):
s = ""
while n>0:
if n&1:
s = "1"+s
else:
s = "0"+s
n >>= 1
if d is not None:
while len(s)<d:
s = "0"+s
if s == "": s = "0"
return s
def bin2ip(b):
ip = ""
for i in range(0,len(b),8):
ip += str(int(b[i:i+8],2))+"."
return ip[:-1]
def parse_cidr(str):
splitted = str.split("/")
if len(splitted) > 2:
raise ValueError
if len(splitted) == 1:
subnet = 32
else:
subnet = int(splitted[1])
if subnet > 32:
raise ValueError
str_ip = splitted[0]
ip = str_ip.split(".")
if len(ip) != 4:
raise ValueError
for i in ip:
if int(i) < 0 or int(i) > 255:
raise ValueError
if subnet == 32:
return [str_ip]
bin_ip = ip2bin(str_ip)
ip_prefix = bin_ip[:-(32-subnet)]
ret = []
for i in range(2**(32-subnet)):
ret.append(bin2ip(ip_prefix+dec2bin(i, (32-subnet))))
return ret
def get_ports(str):
ports = []
for x in str.split(","):
x = x.strip()
if "-" in x:
x = x.split("-")
if len(x) > 2:
raise ValueError
if int(x[0]) < 0 or int(x[0]) > 65535:
raise ValueError
if int(x[1]) < 0 or int(x[1]) + 1 > 65535:
raise ValueError
if int(x[0]) > int(x[1]) + 1:
raise ValueError
ports += range(int(x[0]), int(x[1]) + 1)
else:
if int(x) < 0 or int(x) > 65535:
raise ValueError
ports.append(int(x))
return ports
def get_ips(str):
ips = []
for x in str.split(","):
ips += parse_cidr(x.strip())
return ips
if __name__ == "__main__":
ips = get_ips("127.0.0.1,192.168.0.0/24,10.0.0.40/28")
print(ips)
ports = get_ports("4444,1-100,5432")
print(ports)
| 1,335 |
1,473 | /*
* Autopsy Forensic Browser
*
* Copyright 2017-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> 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.sleuthkit.autopsy.experimental.autoingest;
import java.awt.Component;
import java.lang.reflect.InvocationTargetException;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import static javax.swing.SwingConstants.CENTER;
import org.openide.nodes.Node;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle.Messages;
import org.sleuthkit.autopsy.guiutils.GrayableCellRenderer;
import org.sleuthkit.autopsy.datamodel.NodeProperty;
/**
* A JTable and Outline view cell renderer that represents whether the priority
* value of a job has ever been increased, tick if prioritized nothing if not.
*/
class PrioritizedIconCellRenderer extends GrayableCellRenderer {
@Messages({
"PrioritizedIconCellRenderer.prioritized.tooltiptext=This job has been prioritized. The most recently prioritized job should be processed next.",
"PrioritizedIconCellRenderer.notPrioritized.tooltiptext=This job has not been prioritized."
})
private static final long serialVersionUID = 1L;
static final ImageIcon checkedIcon = new ImageIcon(ImageUtilities.loadImage("org/sleuthkit/autopsy/experimental/images/tick.png", false));
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setHorizontalAlignment(CENTER);
Object switchValue = null;
if ((value instanceof NodeProperty)) {
//The Outline view has properties in the cell, the value contained in the property is what we want
try {
switchValue = ((Node.Property) value).getValue();
} catch (IllegalAccessException | InvocationTargetException ignored) {
//Unable to get the value from the NodeProperty no Icon will be displayed
}
} else {
//JTables contain the value we want directly in the cell
switchValue = value;
}
if (switchValue instanceof Integer && (int) switchValue != 0) {
setIcon(checkedIcon);
setToolTipText(org.openide.util.NbBundle.getMessage(PrioritizedIconCellRenderer.class, "PrioritizedIconCellRenderer.prioritized.tooltiptext"));
} else {
setIcon(null);
if (switchValue instanceof Integer) {
setToolTipText(org.openide.util.NbBundle.getMessage(PrioritizedIconCellRenderer.class, "PrioritizedIconCellRenderer.notPrioritized.tooltiptext"));
}
}
grayCellIfTableNotEnabled(table, isSelected);
return this;
}
}
| 1,128 |
767 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT
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.
""" # noqa
import copy
ERROR_CODE_PREFIX_SYSTEM = '0'
ERROR_CODE_PREFIX_THIRD_PARTY = '1'
def wrap_error_code(code):
"""
包装第三方系统返回的错误代码
"""
return ERROR_CODE_PREFIX_THIRD_PARTY + str(code)
class BaseException(Exception):
pass
class RequestThirdPartyException(BaseException):
"""
当请求第三方系统时抛出的异常
"""
def __init__(self, raw_exc, system_name, interface_name):
self.raw_exc = raw_exc
self.system_name = system_name
self.interface_name = interface_name
def __str__(self):
return u'Component request third-party system [%s] interface [%s] error: %s, '\
'please try again later or contact component developer to handle this'\
% (self.system_name, self.interface_name, self.raw_exc.message)
def get_message(self):
"""
返回到终端用户的错误信息
"""
return u'Component request third-party system [%s] interface [%s] error: %s, '\
'please try again later or contact component developer to handle this'\
% (self.system_name, self.interface_name, self.raw_exc.message)
class RequestSSLException(BaseException):
"""SSL错误,明确错误信息
"""
def __init__(self, raw_exc, system_name, interface_name):
self.raw_exc = raw_exc
self.system_name = system_name
self.interface_name = interface_name
def __str__(self):
return self.get_message()
def get_message(self):
"""
返回到终端用户的错误信息
"""
if isinstance(self.raw_exc.cert, tuple):
self.raw_exc.cert = u', '.join(self.raw_exc.cert)
return u'Component request third-party system [%s] interface [%s] SSL error: '\
'SSL configuration file [%s] does not exist or is illegal, '\
'please get the certificates from the documentation and unzip it into [%s]' % (
self.system_name, self.interface_name, self.raw_exc.cert, self.raw_exc.SSL_ROOT_DIR)
class TestHostNotFoundException(BaseException):
"""
当以测试环境访问没有host_test的SmartHost时抛出
"""
pass
class RequestBlockedException(BaseException):
"""
当前请求被屏蔽之后抛出的异常
"""
pass
class APIError(BaseException):
"""
API Error
"""
def __init__(self, code):
self.code = code
BaseException.__init__(self, code.prompt)
def __str__(self):
return "<APIError %s[%s]: %s>" \
% (self.code.status, self.code.code, self.code.prompt)
def format_prompt(self, prompt=None, replace=False, args=(), kwargs={}):
"""
Using a customized prompt for this ErrorCode
"""
self.code = copy.copy(self.code)
if prompt:
if replace:
self.code.prompt = prompt
else:
self.code.prompt += ', %s' % prompt
# Render prompt string
if args:
self.code.prompt = self.code.prompt % args
if kwargs:
self.code.prompt = self.code.prompt % kwargs
return self
class ErrorCode(object):
"""
Error Code class
"""
def __init__(self, code_name, code, prompt, status=200):
self.code_name = code_name
self.code = code
self.prompt = prompt
self.status = status
def as_dict(self):
return {
'result': False,
'code': self.code,
'data': None,
'message': self.prompt
}
class ErrorCodes(object):
"""
错误代码规范
7位整数,13代表蓝鲸PaaS,06代表ESB,最后3位可自定义
1306xxx
"""
error_codes = (
# 13064xx, user error
ErrorCode('OPERATOR_REQUIRED', 1306401, 'You must specify the current operator'),
ErrorCode('USER_PERMISSION_DENIED', 1306402, 'User permission is insufficient'),
ErrorCode('APP_PERMISSION_DENIED', 1306403, 'APP permission is insufficient'),
ErrorCode('COMPONENT_NOT_FOUND', 1306404, 'Not found, component class not found'),
ErrorCode('INACTIVE_CHANNEL', 1306405, 'Not found, inactive channel'),
ErrorCode('ARGUMENT_ERROR', 1306406, 'Parameters error'),
ErrorCode('BUFFET_CANNOT_FORMAT_PATH', 1306407, "The component's destination request path cannot be formatted"),
ErrorCode('RATE_LIMIT_RESTRICTION', 1306429, 'Access frequency limit'),
# 通用错误编码,用于目前系统中没有错误code的情况
ErrorCode('COMMON_ERROR', 1306000, 'System error'),
# 13062xx, 第三方系统错误
ErrorCode('REQUEST_THIRD_PARTY_ERROR', 1306201, 'Request third-party interface error'),
ErrorCode('REQUEST_SSL_ERROR', 1306203, 'Request third-party interface error'),
ErrorCode('TEST_HOST_NOT_FOUND', 1306206, 'Error, the component does not support access third-party test environment'), # noqa
ErrorCode('REQUEST_BLOCKED', 1306207, 'Request to the third-party system is blocked'),
ErrorCode('THIRD_PARTY_RESULT_ERROR', 1306208, '%s system interface results in an unknown format'),
ErrorCode('REQEUST_DEST_METHOD_ERROR', 1306209, 'The system interface does not support the request method'),
)
# Init dict
_error_codes_dict = {}
for error_code in error_codes:
_error_codes_dict[error_code.code_name] = error_code
def __getattr__(self, code_name):
error_code = self._error_codes_dict[code_name]
return APIError(error_code)
class RequestThirdPartyErrorCodes(object):
"""
请求第三方系统错误代码
"""
error_codes = {
'STATUS_CODE_500': 'Third-party system internal error',
'STATUS_CODE_502': 'Third-party system Bad Gateway',
'STATUS_CODE_403': 'Third-party system prohibit access to this interface',
'STATUS_CODE_404': 'Third-party system does not find this interface',
'STATUS_CODE_302': 'Third-party system redirects this interface',
}
error_codes = ErrorCodes()
request_third_party_error_codes = RequestThirdPartyErrorCodes()
class CommonAPIError(APIError):
"""
Shortcut for returning an error response
"""
def __init__(self, message, error_code=None, status=None):
"""
初始化一个常用的通用错误
:param str message: 自定义的错误消息
:param str error_code: 返回到相应的错误代码,默认 1306000
"""
self.message = message
code = error_codes.COMMON_ERROR.format_prompt(message, replace=True).code
if error_code:
code.code = error_code
if status:
code.status = status
super(CommonAPIError, self).__init__(code)
| 3,243 |
2,338 | // RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
// rdar://problem/54359410
// expected-no-diagnostics
int rand();
void test() {
int offset = 0;
int value;
int test = rand();
switch (test & 0x1) {
case 0:
case 1:
value = 0;
break;
}
offset += value; // no-warning
}
| 126 |
12,718 | <filename>clang/lib/Headers/enqcmdintrin.h
/*===------------------ enqcmdintrin.h - enqcmd intrinsics -----------------===
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===-----------------------------------------------------------------------===
*/
#ifndef __IMMINTRIN_H
#error "Never use <enqcmdintrin.h> directly; include <immintrin.h> instead."
#endif
#ifndef __ENQCMDINTRIN_H
#define __ENQCMDINTRIN_H
/* Define the default attributes for the functions in this file */
#define _DEFAULT_FN_ATTRS \
__attribute__((__always_inline__, __nodebug__, __target__("enqcmd")))
/// Reads 64-byte command pointed by \a __src, formats 64-byte enqueue store
/// data, and performs 64-byte enqueue store to memory pointed by \a __dst.
/// This intrinsics may only be used in User mode.
///
/// \headerfile <x86intrin.h>
///
/// This intrinsics corresponds to the <c> ENQCMD </c> instruction.
///
/// \param __dst
/// Pointer to the destination of the enqueue store.
/// \param __src
/// Pointer to 64-byte command data.
/// \returns If the command data is successfully written to \a __dst then 0 is
/// returned. Otherwise 1 is returned.
static __inline__ int _DEFAULT_FN_ATTRS
_enqcmd (void *__dst, const void *__src)
{
return __builtin_ia32_enqcmd(__dst, __src);
}
/// Reads 64-byte command pointed by \a __src, formats 64-byte enqueue store
/// data, and performs 64-byte enqueue store to memory pointed by \a __dst
/// This intrinsic may only be used in Privileged mode.
///
/// \headerfile <x86intrin.h>
///
/// This intrinsics corresponds to the <c> ENQCMDS </c> instruction.
///
/// \param __dst
/// Pointer to the destination of the enqueue store.
/// \param __src
/// Pointer to 64-byte command data.
/// \returns If the command data is successfully written to \a __dst then 0 is
/// returned. Otherwise 1 is returned.
static __inline__ int _DEFAULT_FN_ATTRS
_enqcmds (void *__dst, const void *__src)
{
return __builtin_ia32_enqcmds(__dst, __src);
}
#undef _DEFAULT_FN_ATTRS
#endif /* __ENQCMDINTRIN_H */
| 746 |
4,535 | #include "base/util/hexdump.h"
#include <iomanip>
#include <sstream>
#include "base/util/logging.h"
namespace vertexai {
void hexdump(int log_level, void* buf, size_t len) {
const size_t LINE_SIZE = 16;
char* line = static_cast<char*>(buf);
size_t offset = 0;
size_t remain = len;
size_t lines = (len / LINE_SIZE) + 1;
for (size_t j = 0; j < lines; j++) {
std::stringstream ss;
ss << std::hex << std::setfill('0');
size_t line_remain = std::min(LINE_SIZE, remain);
ss << std::setw(8) << offset;
for (size_t i = 0; i < LINE_SIZE; i++) {
if (i % 8 == 0) {
ss << ' ';
}
if (i < line_remain) {
ss << ' ' << std::setw(2) << std::hex << (static_cast<int>(line[i]) & 0xff);
} else {
ss << " ";
}
}
ss << " ";
for (size_t i = 0; i < line_remain; i++) {
if (std::isprint(line[i])) {
ss << line[i];
} else {
ss << '.';
}
}
VLOG(log_level) << ss.str();
line += LINE_SIZE;
offset += LINE_SIZE;
remain -= LINE_SIZE;
}
}
} // namespace vertexai
| 525 |
379 | <reponame>addstone/Doraemon
package com.example.transaction.transaction.chain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* @program: testSpring
* @description:
* @author: hu_pf
* @create: 2019-11-10 00:25
**/
@Slf4j
@Component
@Order(2)
public class TwoPrintChainPattern extends PrintChainPattern{
@Override
public String getMessage() {
log.info("name:{},age:{}",getUser().getName(),getUser().getAge());
return "two";
}
}
| 207 |
467 | package com.yoyiyi.soleil.mvp.presenter.app.up;
import com.annimon.stream.Stream;
import com.yoyiyi.soleil.base.BaseSubscriber;
import com.yoyiyi.soleil.base.RxPresenter;
import com.yoyiyi.soleil.bean.user.MulUpDetail;
import com.yoyiyi.soleil.bean.user.UpDetail;
import com.yoyiyi.soleil.event.Event;
import com.yoyiyi.soleil.mvp.contract.app.up.FavouriteContract;
import com.yoyiyi.soleil.rx.RxBus;
import com.yoyiyi.soleil.rx.RxUtils;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
/**
* @author zzq 作者 E-mail: <EMAIL>
* @date 创建时间:2017/6/17 12:37
* 描述:
*/
public class FavouritePresenter extends RxPresenter<FavouriteContract.View> implements FavouriteContract.Presenter<FavouriteContract.View> {
@Inject
public FavouritePresenter() {
}
@Override
public void getFavouriteData() {
BaseSubscriber<List<MulUpDetail>> subscriber = RxBus.INSTANCE.toFlowable(Event.UpDetailFavourteEvent.class)
.map(event -> {
List<UpDetail.DataBean.FavouriteBean.ItemBeanX> favouriteList = event.favouriteList;
List<MulUpDetail> mulUpDetailList = new ArrayList<>();
Stream.of(favouriteList).forEach(itemBeanX ->
mulUpDetailList.add(new MulUpDetail()
.setItemType(MulUpDetail.TYPE_FAVOURITE_ITEM)
.setFavouriteBean(itemBeanX)));
return mulUpDetailList;
})
.compose(RxUtils.rxSchedulerHelper())
.subscribeWith(new BaseSubscriber<List<MulUpDetail>>(mView) {
@Override
public void onSuccess(List<MulUpDetail> mulUpDetailList) {
mView.showFavourite(mulUpDetailList);
}
});
addSubscribe(subscriber);
}
}
| 985 |
777 | <filename>third_party/WebKit/Source/core/animation/AnimationTestHelper.h
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef AnimationTestHelper_h
#define AnimationTestHelper_h
#include "wtf/text/StringView.h"
#include "wtf/text/WTFString.h"
#include <v8.h>
namespace blink {
void setV8ObjectPropertyAsString(v8::Isolate*,
v8::Local<v8::Object>,
const StringView& name,
const StringView& value);
void setV8ObjectPropertyAsNumber(v8::Isolate*,
v8::Local<v8::Object>,
const StringView& name,
double value);
} // namespace blink
#endif // AnimationTestHelper_h
| 418 |
1,858 | <reponame>cyq89051127/flinkStreamSQL<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 com.dtstack.flink.sql.sink.elasticsearch;
import com.dtstack.flink.sql.util.DtStringUtil;
import org.apache.flink.types.Row;
import org.apache.flink.util.Preconditions;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utilities for ElasticSearch
*
* Company: www.dtstack.com
* @author <EMAIL>
*/
public class EsUtil {
public static Map<String, Object> rowToJsonMap(Row row, List<String> fields, List<String> types) {
Preconditions.checkArgument(row.getArity() == fields.size());
Map<String,Object> jsonMap = new HashMap<>();
int i = 0;
for(; i < fields.size(); ++i) {
String field = fields.get(i);
String[] parts = field.split("\\.");
Map<String, Object> currMap = jsonMap;
for(int j = 0; j < parts.length - 1; ++j) {
String key = parts[j];
if(currMap.get(key) == null) {
currMap.put(key, new HashMap<String,Object>());
}
currMap = (Map<String, Object>) currMap.get(key);
}
String key = parts[parts.length - 1];
Object col = row.getField(i);
if(col != null) {
Object value = DtStringUtil.col2string(col, types.get(i));
currMap.put(key, value);
}
}
return jsonMap;
}
}
| 894 |
335 | {
"word": "Jaundiced",
"definitions": [
"Affected by jaundice, in particular unnaturally yellow in complexion.",
"Affected by bitterness, resentment, or cynicism."
],
"parts-of-speech": "Adjective"
} | 90 |
305 | <filename>llvm-project/clang/test/CodeGen/asan-globals.cpp
// RUN: echo "int extra_global;" > %t.extra-source.cpp
// RUN: echo "global:*blacklisted_global*" > %t.blacklist
// RUN: %clang_cc1 -include %t.extra-source.cpp -fsanitize=address -fsanitize-blacklist=%t.blacklist -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
// RUN: %clang_cc1 -include %t.extra-source.cpp -fsanitize=kernel-address -fsanitize-blacklist=%t.blacklist -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
// The blacklist file uses regexps, so Windows path backslashes.
// RUN: echo "src:%s" | sed -e 's/\\/\\\\/g' > %t.blacklist-src
// RUN: %clang_cc1 -include %t.extra-source.cpp -fsanitize=address -fsanitize-blacklist=%t.blacklist-src -emit-llvm -o - %s | FileCheck %s --check-prefix=BLACKLIST-SRC
// RUN: %clang_cc1 -include %t.extra-source.cpp -fsanitize=kernel-address -fsanitize-blacklist=%t.blacklist-src -emit-llvm -o - %s | FileCheck %s --check-prefix=BLACKLIST-SRC
int global;
int dyn_init_global = global;
int __attribute__((no_sanitize("address"))) attributed_global;
int blacklisted_global;
int __attribute__((section("__DATA, __common"))) sectioned_global; // KASAN - ignore globals in a section
extern "C" {
int __special_global; // KASAN - ignore globals with __-prefix
}
void func() {
static int static_var = 0;
const char *literal = "Hello, world!";
}
// ASAN: sectioned_global{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
// KASAN: sectioned_global{{.*}} global i32
// ASAN: @__special_global{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
// KASAN: @__special_global{{.*}} global i32
// CHECK-LABEL: define internal void @asan.module_ctor
// ASAN-NEXT: call void @__asan_init
// ASAN-NEXT: call void @__asan_version_mismatch_check
// KASAN-NOT: call void @__asan_init
// KASAN-NOT: call void @__asan_version_mismatch_check
// ASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 7)
// KASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 5)
// CHECK-NEXT: ret void
// CHECK-LABEL: define internal void @asan.module_dtor
// CHECK-NEXT: call void @__asan_unregister_globals
// CHECK-NEXT: ret void
// CHECK: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], ![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
// CHECK: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], !"extra_global", i1 false, i1 false}
// CHECK: ![[EXTRA_GLOBAL_LOC]] = !{!"{{.*}}extra-source.cpp", i32 1, i32 5}
// CHECK: ![[GLOBAL]] = !{{{.*}} ![[GLOBAL_LOC:[0-9]+]], !"global", i1 false, i1 false}
// CHECK: ![[GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 10, i32 5}
// CHECK: ![[DYN_INIT_GLOBAL]] = !{{{.*}} ![[DYN_INIT_LOC:[0-9]+]], !"dyn_init_global", i1 true, i1 false}
// CHECK: ![[DYN_INIT_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 11, i32 5}
// CHECK: ![[ATTR_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
// CHECK: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
// CHECK: ![[SECTIONED_GLOBAL]] = !{{{.*}} ![[SECTIONED_GLOBAL_LOC:[0-9]+]], !"sectioned_global", i1 false, i1 false}
// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 15, i32 50}
// CHECK: ![[SPECIAL_GLOBAL]] = !{{{.*}} ![[SPECIAL_GLOBAL_LOC:[0-9]+]], !"__special_global", i1 false, i1 false}
// CHECK: ![[SPECIAL_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 5}
// CHECK: ![[STATIC_VAR]] = !{{{.*}} ![[STATIC_LOC:[0-9]+]], !"static_var", i1 false, i1 false}
// CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 21, i32 14}
// CHECK: ![[LITERAL]] = !{{{.*}} ![[LITERAL_LOC:[0-9]+]], !"<string literal>", i1 false, i1 false}
// CHECK: ![[LITERAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 22, i32 25}
// BLACKLIST-SRC: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], ![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
// BLACKLIST-SRC: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], !"extra_global", i1 false, i1 false}
// BLACKLIST-SRC: ![[EXTRA_GLOBAL_LOC]] = !{!"{{.*}}extra-source.cpp", i32 1, i32 5}
// BLACKLIST-SRC: ![[GLOBAL]] = !{{{.*}} null, null, i1 false, i1 true}
// BLACKLIST-SRC: ![[DYN_INIT_GLOBAL]] = !{{{.*}} null, null, i1 true, i1 true}
// BLACKLIST-SRC: ![[ATTR_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
// BLACKLIST-SRC: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
// BLACKLIST-SRC: ![[SECTIONED_GLOBAL]] = !{{{.*}} null, null, i1 false, i1 true}
// BLACKLIST-SRC: ![[SPECIAL_GLOBAL]] = !{{{.*}} null, null, i1 false, i1 true}
// BLACKLIST-SRC: ![[STATIC_VAR]] = !{{{.*}} null, null, i1 false, i1 true}
// BLACKLIST-SRC: ![[LITERAL]] = !{{{.*}} null, null, i1 false, i1 true}
| 2,211 |
887 | package org.javers.core.diff.changetype.container;
import org.javers.core.diff.changetype.Atomic;
import java.util.Objects;
/**
* internal wrapper for Collection or Array
*/
class Container<T> {
private final T value;
Container(T value) {
this.value = value;
}
public T unwrap() {
return value;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Container)) {
return false;
}
Container other = (Container)obj;
return Objects.equals(value, other.value);
}
@Override
public int hashCode() {
if (value == null) {
return 0;
}
return value.hashCode();
}
}
| 308 |
1,056 | <filename>java/maven/src/org/netbeans/modules/maven/spi/IconResources.java<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.maven.spi;
import org.netbeans.api.annotations.common.StaticResource;
/**
* static resources pointing to maven specific icons worth reusing (file an issue if you need some others)
* @author mkleint
* @since 2.93
*/
public class IconResources {
public static final @StaticResource String JAVADOC_BADGE_ICON = "org/netbeans/modules/maven/DependencyJavadocIncluded.png"; //NOI18N
public static final @StaticResource String SOURCE_BADGE_ICON = "org/netbeans/modules/maven/DependencySrcIncluded.png"; //NOI18N
public static final @StaticResource String MAVEN_ICON = "org/netbeans/modules/maven/resources/Maven2Icon.gif";
public static final @StaticResource String MANAGED_BADGE_ICON = "org/netbeans/modules/maven/DependencyManaged.png"; //NOI18N
public static final @StaticResource String ARTIFACT_ICON = "org/netbeans/modules/maven/ArtifactIcon.png";
public static final @StaticResource String DEPENDENCY_ICON = "org/netbeans/modules/maven/DependencyIcon.png";
public static final @StaticResource String BROKEN_PROJECT_BADGE_ICON = "org/netbeans/modules/maven/brokenProjectBadge.png"; //NOI18N
/**
* Icon for a dependency JAR file.
*/
public static final @StaticResource String ICON_DEPENDENCY_JAR = "org/netbeans/modules/maven/spi/nodes/DependencyJar.gif";
public static final @StaticResource String TRANSITIVE_ARTIFACT_ICON = "org/netbeans/modules/maven/TransitiveArtifactIcon.png";
public static final @StaticResource String TRANSITIVE_DEPENDENCY_ICON = "org/netbeans/modules/maven/TransitiveDependencyIcon.png";
public static final @StaticResource String TRANSITIVE_MAVEN_ICON = "org/netbeans/modules/maven/TransitiveMaven2Icon.png";
public static final @StaticResource String MOJO_ICON = "org/netbeans/modules/maven/execute/ui/mojo.png";
private IconResources() {
}
}
| 862 |
1,013 | <reponame>JosephChataignon/pyclustering<gh_stars>1000+
"""!
@brief Neural and oscillatory network module. Consists of models of bio-inspired networks.
@authors <NAME> (<EMAIL>)
@date 2014-2020
@copyright BSD-3-Clause
"""
import math
from enum import IntEnum
class initial_type(IntEnum):
"""!
@brief Enumerator of types of oscillator output initialization.
"""
## Output of oscillators are random in line with gaussian distribution.
RANDOM_GAUSSIAN = 0
## Output of oscillators are equidistant from each other (uniformly distributed, not randomly).
EQUIPARTITION = 1
class solve_type(IntEnum):
"""!
@brief Enumerator of solver types that are used for network simulation.
"""
## Forward Euler first-order method.
FAST = 0 # Usual calculation: x(k + 1) = x(k) + f(x(k)).
## Classic fourth-order Runge-Kutta method (fixed step).
RK4 = 1
## Runge-Kutta-Fehlberg method with order 4 and 5 (float step)."
RKF45 = 2
class conn_type(IntEnum):
"""!
@brief Enumerator of connection types between oscillators.
"""
## No connection between oscillators.
NONE = 0
## All oscillators have connection with each other.
ALL_TO_ALL = 1
## Connections between oscillators represent grid where one oscillator can be connected with four neighbor oscillators: right, upper, left, lower.
GRID_FOUR = 2
## Connections between oscillators represent grid where one oscillator can be connected with eight neighbor oscillators: right, right-upper, upper, upper-left, left, left-lower, lower, lower-right.
GRID_EIGHT = 3
## Connections between oscillators represent bidirectional list.
LIST_BIDIR = 4
## Connections are defined by user or by network during simulation.
DYNAMIC = 5
class conn_represent(IntEnum):
"""!
@brief Enumerator of internal network connection representation between oscillators.
"""
## Each oscillator has list of his neighbors.
LIST = 0
## Connections are represented my matrix connection NxN, where N is number of oscillators.
MATRIX = 1
class network:
"""!
@brief Common network description that consists of information about oscillators and connection between them.
"""
_num_osc = 0
_osc_conn = None
_conn_represent = None
__conn_type = None
__height = 0
__width = 0
@property
def height(self):
"""!
@brief Height of the network grid (that is defined by amout of oscillators in each column), this value is zero in case of non-grid structure.
@note This property returns valid value only for network with grid structure.
"""
return self.__height
@property
def width(self):
"""!
@brief Width of the network grid, this value is zero in case of non-grid structure.
@note This property returns valid value only for network with grid structure.
"""
return self.__width
@property
def structure(self):
"""!
@brief Type of network structure that is used for connecting oscillators.
"""
return self.__conn_type
def __init__(self, num_osc, type_conn = conn_type.ALL_TO_ALL, conn_repr = conn_represent.MATRIX, height = None, width = None):
"""!
@brief Constructor of the network.
@param[in] num_osc (uint): Number of oscillators in the network that defines size of the network.
@param[in] type_conn (conn_type): Type of connections that are used in the network between oscillators.
@param[in] conn_repr (conn_represent): Type of representation of connections.
@param[in] height (uint): Number of oscillators in column of the network, this argument is used
only for network with grid structure (GRID_FOUR, GRID_EIGHT), for other types this argument is ignored.
@param[in] width (uint): Number of oscillotors in row of the network, this argument is used only
for network with grid structure (GRID_FOUR, GRID_EIGHT), for other types this argument is ignored.
"""
self._num_osc = num_osc
self._conn_represent = conn_repr
self.__conn_type = type_conn
if conn_repr is None:
self._conn_represent = conn_represent.MATRIX
if (type_conn == conn_type.GRID_EIGHT) or (type_conn == conn_type.GRID_FOUR):
if (height is not None) and (width is not None):
self.__height = height
self.__width = width
else:
side_size = self._num_osc ** 0.5
if (side_size - math.floor(side_size) > 0):
raise NameError("Invalid number of oscillators '" + str(num_osc) + "' in the network in case of grid structure (root square should be extractable for the number of oscillators).");
self.__height = int(side_size)
self.__width = self.__height
if self.__height * self.__width != self._num_osc:
raise NameError('Width (' + str(self.__width) + ') x Height (' + str(self.__height) + ') must be equal to Size (' + str(self._num_osc) + ') in case of grid structure');
self._create_structure(type_conn)
def __len__(self):
"""!
@brief Returns size of the network that is defined by amount of oscillators.
"""
return self._num_osc;
def __create_connection(self, index1, index2):
if (self._conn_represent == conn_represent.MATRIX):
self._osc_conn[index1][index2] = True;
else:
self._osc_conn[index1].append(index2);
def __create_all_to_all_connections(self):
"""!
@brief Creates connections between all oscillators.
"""
if (self._conn_represent == conn_represent.MATRIX):
for index in range(0, self._num_osc, 1):
self._osc_conn.append([True] * self._num_osc);
self._osc_conn[index][index] = False;
elif (self._conn_represent == conn_represent.LIST):
for index in range(0, self._num_osc, 1):
self._osc_conn.append([neigh for neigh in range(0, self._num_osc, 1) if index != neigh]);
def __create_grid_four_connections(self):
"""!
@brief Creates network with connections that make up four grid structure.
@details Each oscillator may be connected with four neighbors in line with 'grid' structure: right, upper, left, lower.
"""
side_size = self.__width;
if (self._conn_represent == conn_represent.MATRIX):
self._osc_conn = [[0] * self._num_osc for index in range(0, self._num_osc, 1)];
elif (self._conn_represent == conn_represent.LIST):
self._osc_conn = [[] for index in range(0, self._num_osc, 1)];
else:
raise NameError("Unknown type of representation of connections");
for index in range(0, self._num_osc, 1):
upper_index = index - side_size;
lower_index = index + side_size;
left_index = index - 1;
right_index = index + 1;
node_row_index = math.ceil(index / side_size);
if (upper_index >= 0):
self.__create_connection(index, upper_index);
if (lower_index < self._num_osc):
self.__create_connection(index, lower_index);
if ( (left_index >= 0) and (math.ceil(left_index / side_size) == node_row_index) ):
self.__create_connection(index, left_index);
if ( (right_index < self._num_osc) and (math.ceil(right_index / side_size) == node_row_index) ):
self.__create_connection(index, right_index);
def __create_grid_eight_connections(self):
"""!
@brief Creates network with connections that make up eight grid structure.
@details Each oscillator may be connected with eight neighbors in line with grid structure: right, right-upper, upper, upper-left, left, left-lower, lower, lower-right.
"""
self.__create_grid_four_connections(); # create connection with right, upper, left, lower.
side_size = self.__width;
for index in range(0, self._num_osc, 1):
upper_left_index = index - side_size - 1;
upper_right_index = index - side_size + 1;
lower_left_index = index + side_size - 1;
lower_right_index = index + side_size + 1;
node_row_index = math.floor(index / side_size);
upper_row_index = node_row_index - 1;
lower_row_index = node_row_index + 1;
if ( (upper_left_index >= 0) and (math.floor(upper_left_index / side_size) == upper_row_index) ):
self.__create_connection(index, upper_left_index);
if ( (upper_right_index >= 0) and (math.floor(upper_right_index / side_size) == upper_row_index) ):
self.__create_connection(index, upper_right_index);
if ( (lower_left_index < self._num_osc) and (math.floor(lower_left_index / side_size) == lower_row_index) ):
self.__create_connection(index, lower_left_index);
if ( (lower_right_index < self._num_osc) and (math.floor(lower_right_index / side_size) == lower_row_index) ):
self.__create_connection(index, lower_right_index);
def __create_list_bidir_connections(self):
"""!
@brief Creates network as bidirectional list.
@details Each oscillator may be conneted with two neighbors in line with classical list structure: right, left.
"""
if (self._conn_represent == conn_represent.MATRIX):
for index in range(0, self._num_osc, 1):
self._osc_conn.append([0] * self._num_osc);
self._osc_conn[index][index] = False;
if (index > 0):
self._osc_conn[index][index - 1] = True;
if (index < (self._num_osc - 1)):
self._osc_conn[index][index + 1] = True;
elif (self._conn_represent == conn_represent.LIST):
for index in range(self._num_osc):
self._osc_conn.append([]);
if (index > 0):
self._osc_conn[index].append(index - 1);
if (index < (self._num_osc - 1)):
self._osc_conn[index].append(index + 1);
def __create_none_connections(self):
"""!
@brief Creates network without connections.
"""
if (self._conn_represent == conn_represent.MATRIX):
for _ in range(0, self._num_osc, 1):
self._osc_conn.append([False] * self._num_osc);
elif (self._conn_represent == conn_represent.LIST):
self._osc_conn = [[] for _ in range(0, self._num_osc, 1)];
def __create_dynamic_connection(self):
"""!
@brief Prepare storage for dynamic connections.
"""
if (self._conn_represent == conn_represent.MATRIX):
for _ in range(0, self._num_osc, 1):
self._osc_conn.append([False] * self._num_osc);
elif (self._conn_represent == conn_represent.LIST):
self._osc_conn = [[] for _ in range(0, self._num_osc, 1)];
def _create_structure(self, type_conn = conn_type.ALL_TO_ALL):
"""!
@brief Creates connection in line with representation of matrix connections [NunOsc x NumOsc].
@param[in] type_conn (conn_type): Connection type (all-to-all, bidirectional list, grid structure, etc.) that is used by the network.
"""
self._osc_conn = list();
if (type_conn == conn_type.NONE):
self.__create_none_connections();
elif (type_conn == conn_type.ALL_TO_ALL):
self.__create_all_to_all_connections();
elif (type_conn == conn_type.GRID_FOUR):
self.__create_grid_four_connections();
elif (type_conn == conn_type.GRID_EIGHT):
self.__create_grid_eight_connections();
elif (type_conn == conn_type.LIST_BIDIR):
self.__create_list_bidir_connections();
elif (type_conn == conn_type.DYNAMIC):
self.__create_dynamic_connection();
else:
raise NameError('The unknown type of connections');
def has_connection(self, i, j):
"""!
@brief Returns True if there is connection between i and j oscillators and False - if connection doesn't exist.
@param[in] i (uint): index of an oscillator in the network.
@param[in] j (uint): index of an oscillator in the network.
"""
if (self._conn_represent == conn_represent.MATRIX):
return (self._osc_conn[i][j]);
elif (self._conn_represent == conn_represent.LIST):
for neigh_index in range(0, len(self._osc_conn[i]), 1):
if (self._osc_conn[i][neigh_index] == j):
return True;
return False;
else:
raise NameError("Unknown type of representation of coupling");
def set_connection(self, i, j):
"""!
@brief Couples two specified oscillators in the network with dynamic connections.
@param[in] i (uint): index of an oscillator that should be coupled with oscillator 'j' in the network.
@param[in] j (uint): index of an oscillator that should be coupled with oscillator 'i' in the network.
@note This method can be used only in case of DYNAMIC connections, otherwise it throws expection.
"""
if (self.structure != conn_type.DYNAMIC):
raise NameError("Connection between oscillators can be changed only in case of dynamic type.");
if (self._conn_represent == conn_represent.MATRIX):
self._osc_conn[i][j] = True;
self._osc_conn[j][i] = True;
else:
self._osc_conn[i].append(j);
self._osc_conn[j].append(i);
def get_neighbors(self, index):
"""!
@brief Finds neighbors of the oscillator with specified index.
@param[in] index (uint): index of oscillator for which neighbors should be found in the network.
@return (list) Indexes of neighbors of the specified oscillator.
"""
if (self._conn_represent == conn_represent.LIST):
return self._osc_conn[index]; # connections are represented by list.
elif (self._conn_represent == conn_represent.MATRIX):
return [neigh_index for neigh_index in range(self._num_osc) if self._osc_conn[index][neigh_index] == True];
else:
raise NameError("Unknown type of representation of connections");
| 7,345 |
315 | /*!
* \file
* \brief Class module::Reducer.
*/
#ifndef INCREMENTER_HPP_
#define INCREMENTER_HPP_
#include <cstdint>
#include <vector>
#include "Tools/Math/binaryop.h"
#include "Module/Module.hpp"
namespace aff3ct
{
namespace module
{
namespace red
{
enum class tsk : size_t { reduce, SIZE };
namespace sck
{
enum class reduce : size_t { in, out, status };
}
}
template <typename TI, typename TO, tools::proto_bop<TI,TO> BOP>
class Reducer : public Module
{
public:
inline Task& operator[](const red::tsk t);
inline Socket& operator[](const red::sck::reduce s);
protected:
const size_t n_elmts;
public:
Reducer(const size_t n_elmts);
virtual ~Reducer() = default;
virtual Reducer<TI,TO,BOP>* clone() const;
size_t get_n_elmts() const;
template <class AI = std::allocator<TI>, class AO = std::allocator<TO>>
void reduce(const std::vector<TI,AI>& in,
std::vector<TO,AO>& out,
const int frame_id = -1,
const bool managed_memory = true);
void reduce(const TI *in, TO *out, const int frame_id = -1, const bool managed_memory = true);
protected:
virtual void _reduce(const TI *in, TO *out, const size_t frame_id);
};
template <typename TI, typename TO = TI, tools::proto_bop<TI, TO> BOP = tools::bop_add<TI, TO>> using Reducer_add = Reducer<TI, TO, BOP>;
template <typename TI, typename TO = TI, tools::proto_bop<TI, TO> BOP = tools::bop_sub<TI, TO>> using Reducer_sub = Reducer<TI, TO, BOP>;
template <typename TI, typename TO = TI, tools::proto_bop<TI, TO> BOP = tools::bop_mul<TI, TO>> using Reducer_mul = Reducer<TI, TO, BOP>;
template <typename TI, typename TO = TI, tools::proto_bop<TI, TO> BOP = tools::bop_div<TI, TO>> using Reducer_div = Reducer<TI, TO, BOP>;
template <typename TI, typename TO = TI, tools::proto_bop<TI, TO> BOP = tools::bop_or <TI, TO>> using Reducer_or = Reducer<TI, TO, BOP>;
template <typename TI, typename TO = TI, tools::proto_bop<TI, TO> BOP = tools::bop_xor<TI, TO>> using Reducer_xor = Reducer<TI, TO, BOP>;
template <typename TI, typename TO = TI, tools::proto_bop<TI, TO> BOP = tools::bop_and<TI, TO>> using Reducer_and = Reducer<TI, TO, BOP>;
template <typename TI, typename TO = TI, tools::proto_bop<TI, TO> BOP = tools::bop_min<TI, TO>> using Reducer_min = Reducer<TI, TO, BOP>;
template <typename TI, typename TO = TI, tools::proto_bop<TI, TO> BOP = tools::bop_max<TI, TO>> using Reducer_max = Reducer<TI, TO, BOP>;
}
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
#include "Module/Reducer/Reducer.hxx"
#endif
#endif /* INCREMENTER_HPP_ */
| 1,073 |
435 | {
"copyright_text": "Creative Commons Attribution license (reuse allowed)",
"description": "Montreal, June 9, 2014 - <NAME> presents configparser, a Python 3 module that you can use to write Python programs which can be customized by end users easily.\n\nUseful links:\n\n* Rory: https://twitter.com/r_geoghegan\n* configparser: http://sflx.ca/configparser\n* MP47: http://sflx.ca/mp47\n* Montreal Python: http://montrealpython.org\n* Savoir-faire Linux: http://www.savoirfairelinux.com",
"duration": 363,
"language": "eng",
"recorded": "2014-06-09",
"related_urls": [
{
"label": "group web",
"url": "https://montrealpython.org"
},
{
"label": "MP47",
"url": "http://sflx.ca/mp47"
},
{
"label": "Savoir-faire Linux",
"url": "http://www.savoirfairelinux.com"
},
{
"label": "configparser",
"url": "http://sflx.ca/configparser"
},
{
"label": "<NAME>",
"url": "https://twitter.com/r_geoghegan"
}
],
"speakers": [
"<NAME>"
],
"tags": [],
"thumbnail_url": "https://i.ytimg.com/vi/MRupY_nRNgA/maxresdefault.jpg",
"title": "Module of the Month: configparser",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=MRupY_nRNgA"
}
]
}
| 556 |
2,199 | /*
* Copyright (c) 2016—2021 <NAME> and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package bt.data;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static bt.data.ChunkDescriptorTestUtil.mockStorageUnits;
import static bt.data.ReadWriteDataRangeTest.assertHasUnits;
import static org.junit.Assert.assertEquals;
public class ReadWriteDataRange_SubrangeTest {
/**************************************************************************************************/
@Test
public void testSubrange_SingleUnit_Full() {
long len = 256;
List<StorageUnit> units = mockStorageUnits(len);
DataRange range = new ReadWriteDataRange(units, 0, len).getSubrange(0);
assertEquals(len, range.length());
List<UnitAccess> expectedUnits = Collections.singletonList(new UnitAccess(units.get(0), 0, len));
assertHasUnits(expectedUnits, range);
}
@Test
public void testSubrange_SingleUnit_WithOffset() {
long len = 256;
long off = 16;
List<StorageUnit> units = mockStorageUnits(len);
DataRange range = new ReadWriteDataRange(units, 0, len).getSubrange(16);
assertEquals(len - off, range.length());
List<UnitAccess> expectedUnits = Collections.singletonList(new UnitAccess(units.get(0), off, len));
assertHasUnits(expectedUnits, range);
}
@Test
public void testSubrange_SingleUnit_WithLength() {
long len = 256;
long lim = 192;
List<StorageUnit> units = mockStorageUnits(len);
DataRange range = new ReadWriteDataRange(units, 0, len).getSubrange(0, lim);
assertEquals(lim, range.length());
List<UnitAccess> expectedUnits = Collections.singletonList(new UnitAccess(units.get(0), 0, lim));
assertHasUnits(expectedUnits, range);
}
@Test
public void testSubrange_SingleUnit_WithOffsetAndLength() {
long len = 256;
long off = 16;
long lim = 192;
List<StorageUnit> units = mockStorageUnits(len);
DataRange range = new ReadWriteDataRange(units, 0, len).getSubrange(off, lim - off);
assertEquals(lim - off, range.length());
List<UnitAccess> expectedUnits = Collections.singletonList(new UnitAccess(units.get(0), off, lim));
assertHasUnits(expectedUnits, range);
}
/**************************************************************************************************/
@Test
public void testSubrange_MultipleUnits_Full() {
long len1 = 256, len2 = 64, len3 = 192;
List<StorageUnit> units = mockStorageUnits(len1, len2, len3);
DataRange range = new ReadWriteDataRange(units, 0, len3).getSubrange(0);
assertEquals(len1 + len2 + len3, range.length());
List<UnitAccess> expectedUnits = Arrays.asList(
new UnitAccess(units.get(0), 0, len1),
new UnitAccess(units.get(1), 0, len2),
new UnitAccess(units.get(2), 0, len3));
assertHasUnits(expectedUnits, range);
}
@Test
public void testSubrange_MultipleUnits_WithOffset() {
long len1 = 256, len2 = 64, len3 = 192;
long off = 32;
List<StorageUnit> units = mockStorageUnits(len1, len2, len3);
DataRange range = new ReadWriteDataRange(units, 0, len3).getSubrange(off);
assertEquals(len1 - off + len2 + len3, range.length());
List<UnitAccess> expectedUnits = Arrays.asList(
new UnitAccess(units.get(0), off, len1),
new UnitAccess(units.get(1), 0, len2),
new UnitAccess(units.get(2), 0, len3));
assertHasUnits(expectedUnits, range);
}
@Test
public void testSubrange_MultipleUnits_WithOffsetInSecondUnit() {
long len1 = 256, len2 = 64, len3 = 192;
long off = 32;
List<StorageUnit> units = mockStorageUnits(len1, len2, len3);
DataRange range = new ReadWriteDataRange(units, 0, len3).getSubrange(len1 + off);
assertEquals(len2 - off + len3, range.length());
List<UnitAccess> expectedUnits = Arrays.asList(
new UnitAccess(units.get(1), off, len2),
new UnitAccess(units.get(2), 0, len3));
assertHasUnits(expectedUnits, range);
}
@Test
public void testSubrange_MultipleUnits_WithLength() {
long len1 = 256, len2 = 64, len3 = 192;
long lim = 64;
List<StorageUnit> units = mockStorageUnits(len1, len2, len3);
DataRange range = new ReadWriteDataRange(units, 0, len3).getSubrange(0, len1 + len2 + lim);
assertEquals(len1 + len2 + lim, range.length());
List<UnitAccess> expectedUnits = Arrays.asList(
new UnitAccess(units.get(0), 0, len1),
new UnitAccess(units.get(1), 0, len2),
new UnitAccess(units.get(2), 0, lim));
assertHasUnits(expectedUnits, range);
}
@Test
public void testSubrange_MultipleUnits_WithLength_TrimLastUnit() {
long len1 = 256, len2 = 64, len3 = 192;
long lim = 64;
List<StorageUnit> units = mockStorageUnits(len1, len2, len3);
DataRange range = new ReadWriteDataRange(units, 0, len3).getSubrange(0, len1 + lim);
assertEquals(len1 + lim, range.length());
List<UnitAccess> expectedUnits = Arrays.asList(
new UnitAccess(units.get(0), 0, len1),
new UnitAccess(units.get(1), 0, lim));
assertHasUnits(expectedUnits, range);
}
@Test
public void testSubrange_MultipleUnits_WithOffsetAndLength() {
long len1 = 256, len2 = 64, len3 = 192;
long off = 192;
long lim = 64;
List<StorageUnit> units = mockStorageUnits(len1, len2, len3);
DataRange range = new ReadWriteDataRange(units, 0, len3).getSubrange(off, len1 - off + len2 + lim);
assertEquals(len1 - off + len2 + lim, range.length());
List<UnitAccess> expectedUnits = Arrays.asList(
new UnitAccess(units.get(0), off, len1),
new UnitAccess(units.get(1), 0, len2),
new UnitAccess(units.get(2), 0, lim));
assertHasUnits(expectedUnits, range);
}
@Test
public void testSubrange_MultipleUnits_WithOffsetAndLength_TrimFirstAndLastUnits() {
long len1 = 256, len2 = 64, len3 = 192;
long off = 32;
List<StorageUnit> units = mockStorageUnits(len1, len2, len3);
DataRange range = new ReadWriteDataRange(units, 0, len3).getSubrange(len1 + off, 1);
assertEquals(1, range.length());
List<UnitAccess> expectedUnits = Collections.singletonList(new UnitAccess(units.get(1), off, off + 1));
assertHasUnits(expectedUnits, range);
}
}
| 2,932 |
777 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/files/file_util.h"
#include "breakpad/src/common/linux/libcurl_wrapper.h"
#include "chromecast/base/scoped_temp_file.h"
#include "chromecast/crash/cast_crashdump_uploader.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromecast {
class MockLibcurlWrapper : public google_breakpad::LibcurlWrapper {
public:
MOCK_METHOD0(Init, bool());
MOCK_METHOD2(SetProxy,
bool(const std::string& proxy_host,
const std::string& proxy_userpwd));
MOCK_METHOD2(AddFile,
bool(const std::string& upload_file_path,
const std::string& basename));
MOCK_METHOD5(SendRequest,
bool(const std::string& url,
const std::map<std::string, std::string>& parameters,
int* http_status_code,
std::string* http_header_data,
std::string* http_response_data));
};
// Declared for the scope of this file to increase readability.
using testing::_;
using testing::Return;
TEST(CastCrashdumpUploaderTest, UploadFailsWhenInitFails) {
testing::StrictMock<MockLibcurlWrapper> m;
EXPECT_CALL(m, Init()).Times(1).WillOnce(Return(false));
CastCrashdumpData data;
data.product = "foobar";
data.version = "1.0";
data.guid = "AAA-BBB";
data.email = "<EMAIL>";
data.comments = "none";
data.minidump_pathname = "/tmp/foo.dmp";
data.crash_server = "http://foo.com";
CastCrashdumpUploader uploader(data, &m);
ASSERT_FALSE(uploader.Upload(nullptr));
}
TEST(CastCrashdumpUploaderTest, UploadSucceedsWithValidParameters) {
testing::StrictMock<MockLibcurlWrapper> m;
// Create a temporary file.
ScopedTempFile minidump;
EXPECT_CALL(m, Init()).Times(1).WillOnce(Return(true));
EXPECT_CALL(m, AddFile(minidump.path().value(), _)).WillOnce(Return(true));
EXPECT_CALL(m, SendRequest("http://foo.com", _, _, _, _)).Times(1).WillOnce(
Return(true));
CastCrashdumpData data;
data.product = "foobar";
data.version = "1.0";
data.guid = "AAA-BBB";
data.email = "<EMAIL>";
data.comments = "none";
data.minidump_pathname = minidump.path().value();
data.crash_server = "http://foo.com";
CastCrashdumpUploader uploader(data, &m);
ASSERT_TRUE(uploader.Upload(nullptr));
}
TEST(CastCrashdumpUploaderTest, UploadFailsWithInvalidPathname) {
testing::StrictMock<MockLibcurlWrapper> m;
EXPECT_CALL(m, Init()).Times(1).WillOnce(Return(true));
EXPECT_CALL(m, SendRequest(_, _, _, _, _)).Times(0);
CastCrashdumpData data;
data.product = "foobar";
data.version = "1.0";
data.guid = "AAA-BBB";
data.email = "<EMAIL>";
data.comments = "none";
data.minidump_pathname = "/invalid/file/path";
data.crash_server = "http://foo.com";
CastCrashdumpUploader uploader(data, &m);
ASSERT_FALSE(uploader.Upload(nullptr));
}
TEST(CastCrashdumpUploaderTest, UploadFailsWithoutAllRequiredParameters) {
testing::StrictMock<MockLibcurlWrapper> m;
// Create a temporary file.
ScopedTempFile minidump;
// Has all the require fields for a crashdump.
CastCrashdumpData data;
data.product = "foobar";
data.version = "1.0";
data.guid = "AAA-BBB";
data.email = "<EMAIL>";
data.comments = "none";
data.minidump_pathname = minidump.path().value();
data.crash_server = "http://foo.com";
// Test with empty product name.
data.product = "";
EXPECT_CALL(m, Init()).Times(1).WillOnce(Return(true));
CastCrashdumpUploader uploader_no_product(data, &m);
ASSERT_FALSE(uploader_no_product.Upload(nullptr));
data.product = "foobar";
// Test with empty product version.
data.version = "";
EXPECT_CALL(m, Init()).Times(1).WillOnce(Return(true));
CastCrashdumpUploader uploader_no_version(data, &m);
ASSERT_FALSE(uploader_no_version.Upload(nullptr));
data.version = "1.0";
// Test with empty client GUID.
data.guid = "";
EXPECT_CALL(m, Init()).Times(1).WillOnce(Return(true));
CastCrashdumpUploader uploader_no_guid(data, &m);
ASSERT_FALSE(uploader_no_guid.Upload(nullptr));
}
TEST(CastCrashdumpUploaderTest, UploadFailsWithInvalidAttachment) {
testing::StrictMock<MockLibcurlWrapper> m;
// Create a temporary file.
ScopedTempFile minidump;
EXPECT_CALL(m, Init()).Times(1).WillOnce(Return(true));
EXPECT_CALL(m, AddFile(minidump.path().value(), _)).WillOnce(Return(true));
CastCrashdumpData data;
data.product = "foobar";
data.version = "1.0";
data.guid = "AAA-BBB";
data.email = "<EMAIL>";
data.comments = "none";
data.minidump_pathname = minidump.path().value();
data.crash_server = "http://foo.com";
CastCrashdumpUploader uploader(data, &m);
// Add a file that does not exist as an attachment.
uploader.AddAttachment("label", "/path/does/not/exist");
ASSERT_FALSE(uploader.Upload(nullptr));
}
TEST(CastCrashdumpUploaderTest, UploadSucceedsWithValidAttachment) {
testing::StrictMock<MockLibcurlWrapper> m;
// Create a temporary file.
ScopedTempFile minidump;
// Create a valid attachment.
ScopedTempFile attachment;
EXPECT_CALL(m, Init()).Times(1).WillOnce(Return(true));
EXPECT_CALL(m, AddFile(minidump.path().value(), _)).WillOnce(Return(true));
EXPECT_CALL(m, AddFile(attachment.path().value(), _)).WillOnce(Return(true));
EXPECT_CALL(m, SendRequest(_, _, _, _, _)).Times(1).WillOnce(Return(true));
CastCrashdumpData data;
data.product = "foobar";
data.version = "1.0";
data.guid = "AAA-BBB";
data.email = "<EMAIL>";
data.comments = "none";
data.minidump_pathname = minidump.path().value();
data.crash_server = "http://foo.com";
CastCrashdumpUploader uploader(data, &m);
// Add a valid file as an attachment.
uploader.AddAttachment("label", attachment.path().value());
ASSERT_TRUE(uploader.Upload(nullptr));
}
} // namespace chromeceast
| 2,300 |
335 | <reponame>Safal08/Hacktoberfest-1<gh_stars>100-1000
{
"word": "Explorer",
"definitions": [
"A person who explores a new or unfamiliar area."
],
"parts-of-speech": "Noun"
} | 87 |
575 | <reponame>iridium-browser/iridium-browser
// Copyright 2021 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 REMOTING_PROTOCOL_WEBRTC_VIDEO_FRAME_ADAPTER_H_
#define REMOTING_PROTOCOL_WEBRTC_VIDEO_FRAME_ADAPTER_H_
#include <memory>
#include "third_party/webrtc/api/video/video_frame.h"
#include "third_party/webrtc/api/video/video_frame_buffer.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
namespace remoting {
namespace protocol {
// Adapter class to wrap a DesktopFrame produced by the capturer, and provide
// it as a VideoFrame to the WebRTC video sink. The encoder will extract the
// captured DesktopFrame from VideoFrame::video_frame_buffer().
class WebrtcVideoFrameAdapter : public webrtc::VideoFrameBuffer {
public:
explicit WebrtcVideoFrameAdapter(std::unique_ptr<webrtc::DesktopFrame> frame);
~WebrtcVideoFrameAdapter() override;
WebrtcVideoFrameAdapter(const WebrtcVideoFrameAdapter&) = delete;
WebrtcVideoFrameAdapter& operator=(const WebrtcVideoFrameAdapter&) = delete;
// Returns a VideoFrame that wraps the provided DesktopFrame.
static webrtc::VideoFrame CreateVideoFrame(
std::unique_ptr<webrtc::DesktopFrame> desktop_frame);
// Used by the encoder. After this returns, the adapter no longer wraps a
// DesktopFrame.
std::unique_ptr<webrtc::DesktopFrame> TakeDesktopFrame();
// webrtc::VideoFrameBuffer overrides.
Type type() const override;
int width() const override;
int height() const override;
rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() override;
private:
std::unique_ptr<webrtc::DesktopFrame> frame_;
webrtc::DesktopSize frame_size_;
};
} // namespace protocol
} // namespace remoting
#endif // REMOTING_PROTOCOL_WEBRTC_VIDEO_FRAME_ADAPTER_H_
| 594 |
1,067 | //
// MHSearchCommonSearchCell.h
// WeChat
//
// Created by admin on 2020/5/15.
// Copyright © 2020 CoderMikeHe. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface MHSearchCommonSearchCell : UITableViewCell<MHReactiveView>
// generate cell
+ (instancetype)cellWithTableView:(UITableView *)tableView;
@end
NS_ASSUME_NONNULL_END
| 139 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/network/sct_auditing/sct_auditing_cache.h"
#include "base/callback.h"
#include "base/metrics/histogram_functions.h"
#include "base/rand_util.h"
#include "components/version_info/version_info.h"
#include "crypto/secure_hash.h"
#include "crypto/sha2.h"
#include "net/base/hash_value.h"
#include "net/cert/ct_serialization.h"
#include "net/cert/sct_status_flags.h"
#include "net/cert/signed_certificate_timestamp.h"
#include "net/cert/signed_certificate_timestamp_and_status.h"
#include "net/cert/x509_certificate.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "services/network/network_context.h"
#include "services/network/public/proto/sct_audit_report.pb.h"
#include "services/network/sct_auditing/sct_auditing_handler.h"
#include "third_party/boringssl/src/include/openssl/pool.h"
#include "third_party/boringssl/src/include/openssl/sha.h"
namespace network {
namespace {
// Records the high-water mark of the cache size (in number of reports).
void RecordSCTAuditingCacheHighWaterMarkMetrics(size_t cache_hwm) {
base::UmaHistogramCounts1000("Security.SCTAuditing.OptIn.DedupeCacheHWM",
cache_hwm);
}
// Records whether a new report is deduplicated against an existing report in
// the cache.
void RecordSCTAuditingReportDeduplicatedMetrics(bool deduplicated) {
base::UmaHistogramBoolean("Security.SCTAuditing.OptIn.ReportDeduplicated",
deduplicated);
}
// Records whether a new report that wasn't deduplicated was sampled for
// sending to the reporting server.
void RecordSCTAuditingReportSampledMetrics(bool sampled) {
base::UmaHistogramBoolean("Security.SCTAuditing.OptIn.ReportSampled",
sampled);
}
// Records the size of a report that will be sent to the reporting server, in
// bytes. Used to track how much bandwidth is consumed by sending reports.
void RecordSCTAuditingReportSizeMetrics(size_t report_size) {
base::UmaHistogramCounts10M("Security.SCTAuditing.OptIn.ReportSize",
report_size);
}
} // namespace
SCTAuditingCache::SCTAuditingCache(size_t cache_size)
: dedupe_cache_(cache_size) {}
SCTAuditingCache::~SCTAuditingCache() = default;
void SCTAuditingCache::MaybeEnqueueReport(
NetworkContext* context,
const net::HostPortPair& host_port_pair,
const net::X509Certificate* validated_certificate_chain,
const net::SignedCertificateTimestampAndStatusList&
signed_certificate_timestamps) {
if (!enabled_)
return;
auto report = std::make_unique<sct_auditing::SCTClientReport>();
auto* tls_report = report->add_certificate_report();
// Encode the SCTs in the report and generate the cache key. The hash of the
// SCTs is used as the cache key to deduplicate reports with the same SCTs.
// Constructing the report in parallel with computing the hash avoids
// encoding the SCTs multiple times and avoids extra copies.
SHA256_CTX ctx;
SHA256_Init(&ctx);
for (const auto& sct : signed_certificate_timestamps) {
// Only audit valid SCTs. This ensures that they come from a known log, have
// a valid signature, and thus are expected to be public certificates. If
// there are no valid SCTs, there's no need to report anything.
if (sct.status != net::ct::SCT_STATUS_OK)
continue;
auto* sct_source_and_status = tls_report->add_included_sct();
// TODO(crbug.com/1082860): Update the proto to remove the status entirely
// since only valid SCTs are reported now.
sct_source_and_status->set_status(
sct_auditing::SCTWithVerifyStatus::SctVerifyStatus::
SCTWithVerifyStatus_SctVerifyStatus_OK);
net::ct::EncodeSignedCertificateTimestamp(
sct.sct, sct_source_and_status->mutable_serialized_sct());
SHA256_Update(&ctx, sct_source_and_status->serialized_sct().data(),
sct_source_and_status->serialized_sct().size());
}
// Don't handle reports if there were no valid SCTs.
if (tls_report->included_sct().empty())
return;
net::SHA256HashValue cache_key;
SHA256_Final(reinterpret_cast<uint8_t*>(&cache_key), &ctx);
// Check if the SCTs are already in the cache. This will update the last seen
// time if they are present in the cache.
auto it = dedupe_cache_.Get(cache_key);
if (it != dedupe_cache_.end()) {
RecordSCTAuditingReportDeduplicatedMetrics(true);
return;
}
RecordSCTAuditingReportDeduplicatedMetrics(false);
report->set_user_agent(version_info::GetProductNameAndVersionForUserAgent());
// Add `cache_key` to the dedupe cache. The cache value is not used.
dedupe_cache_.Put(cache_key, true);
if (base::RandDouble() > sampling_rate_) {
RecordSCTAuditingReportSampledMetrics(false);
return;
}
RecordSCTAuditingReportSampledMetrics(true);
auto* connection_context = tls_report->mutable_context();
base::TimeDelta time_since_unix_epoch =
base::Time::Now() - base::Time::UnixEpoch();
connection_context->set_time_seen(time_since_unix_epoch.InSeconds());
auto* origin = connection_context->mutable_origin();
origin->set_hostname(host_port_pair.host());
origin->set_port(host_port_pair.port());
// Convert the certificate chain to a PEM encoded vector, and then initialize
// the proto's |certificate_chain| repeated field using the data in the
// vector. Note that GetPEMEncodedChain() can fail, but we still want to
// enqueue the report for the SCTs (in that case, |certificate_chain| is not
// guaranteed to be valid).
std::vector<std::string> certificate_chain;
validated_certificate_chain->GetPEMEncodedChain(&certificate_chain);
*connection_context->mutable_certificate_chain() = {certificate_chain.begin(),
certificate_chain.end()};
// Log the size of the report. This only tracks reports that are not dropped
// due to sampling (as those reports will just be empty).
RecordSCTAuditingReportSizeMetrics(report->ByteSizeLong());
// Track high-water-mark for the size of the cache.
if (dedupe_cache_.size() > dedupe_cache_size_hwm_)
dedupe_cache_size_hwm_ = dedupe_cache_.size();
// Ensure that the URLLoaderFactory is still bound.
if (!url_loader_factory_ || !url_loader_factory_.is_connected()) {
// TODO(cthomp): Should this signal to embedder that something has failed?
return;
}
context->sct_auditing_handler()->AddReporter(
cache_key, std::move(report), *url_loader_factory_, report_uri_,
traffic_annotation_);
}
void SCTAuditingCache::ClearCache() {
// Empty the deduplication cache.
dedupe_cache_.Clear();
}
void SCTAuditingCache::set_enabled(bool enabled) {
enabled_ = enabled;
SetPeriodicMetricsEnabled(enabled);
}
void SCTAuditingCache::ReportHWMMetrics() {
if (!enabled_)
return;
RecordSCTAuditingCacheHighWaterMarkMetrics(dedupe_cache_size_hwm_);
}
void SCTAuditingCache::SetPeriodicMetricsEnabled(bool enabled) {
// High-water-mark metrics get logged hourly (rather than once-per-session at
// shutdown, as Network Service shutdown is not consistent and non-browser
// processes can fail to report metrics during shutdown). The timer should
// only be running if SCT auditing is enabled.
if (enabled) {
histogram_timer_.Start(FROM_HERE, base::Hours(1), this,
&SCTAuditingCache::ReportHWMMetrics);
} else {
histogram_timer_.Stop();
}
}
} // namespace network
| 2,734 |
678 | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/AirPortAssistant.framework/AirPortAssistant
*/
#import <AirPortAssistant/AirPortAssistant-Structs.h>
#import <AirPortAssistant/APFormatter.h>
__attribute__((visibility("hidden")))
@interface IPv4AddressFormatter : APFormatter {
}
- (BOOL)isPartialStringValid:(id)valid newEditingString:(id *)string errorDescription:(id *)description; // 0x8b085
@end
| 144 |
553 | {
"editor.insertSpaces": false,
"prettier.requireConfig": true,
"search.exclude": {
"**/dist": true
},
"eslint.alwaysShowStatus": true,
"eslint.codeActionsOnSave.mode": "problems"
}
| 80 |
872 | <filename>502 IPO.py
#!/usr/bin/python3
"""
Suppose LeetCode will start its IPO soon. In order to sell a good price of its
shares to Venture Capital, LeetCode would like to work on some projects to
increase its capital before the IPO. Since it has limited resources, it can
only finish at most k distinct projects before the IPO. Help LeetCode design
the best way to maximize its total capital after finishing at most k distinct
projects.
You are given several projects. For each project i, it has a pure profit Pi and
a minimum capital of Ci is needed to start the corresponding project.
Initially, you have W capital. When you finish a project, you will obtain its
pure profit and the profit will be added to your total capital.
To sum up, pick a list of at most k distinct projects from given projects to
maximize your final capital, and output your final maximized capital.
Example 1:
Input: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1].
Output: 4
Explanation: Since your initial capital is 0, you can only start the project indexed 0.
After finishing it you will obtain profit 1 and your capital becomes 1.
With capital 1, you can either start the project indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
Note:
You may assume all numbers in the input are non-negative integers.
The length of Profits array and Capital array will not exceed 50,000.
The answer is guaranteed to fit in a 32-bit signed integer.
"""
from typing import List
import heapq
class Solution:
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""
Greedy + dual PQ
Greedy: need max profit meeting the current capital requirement
1st pq sort by min capital
2nd pq sort by max profit
O(N logN) + O(N log N)
"""
capital_q = list(zip(Capital, Profits))
profit_q = []
heapq.heapify(capital_q)
capital = W
for _ in range(k):
while capital_q and capital_q[0][0] <= capital:
_, pro = heapq.heappop(capital_q)
heapq.heappush(profit_q, (-pro, pro))
if profit_q:
_, pro = heapq.heappop(profit_q)
capital += pro
else:
break
return capital
def findMaximizedCapital_TLE(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""
Knapsack problem
Difference from original knapsack: weight vs. capitcal + profit
Doing a project has profit and open new project opportunities.
F[m][c] = F[m-1][] + profit[i]
final F[k][W]
Greedy, always do the max profits given the capital requirement fullfilled
O(k * N)
"""
capital = W
n = len(Profits)
visited = [False for _ in range(n)]
for _ in range(k):
maxa = 0
maxa_i = 0
for i in range(n):
if not visited[i] and Profits[i] >= maxa and Capital[i] <= capital:
maxa = Profits[i]
maxa_i = i
if maxa > 0:
capital += maxa
visited[maxa_i] = True
else:
break
return capital
| 1,379 |
1,256 | #pragma once
#include "Rtl.Base.h"
typedef unsigned long dword;
typedef unsigned short word;
typedef unsigned char byte;
typedef dword longbool;
| 52 |
317 | <reponame>abir1999/xiaoPi<filename>src/network/network_manager.cc
#include <string>
#include <fstream>
#include <vector>
#include <unistd.h>
#include "network/network_manager.h"
#include "utility/utility.h"
#include "system/system_manager.h"
std::map <int, int> kWifiChannelFreqMap
{
std::make_pair (2412, 1),
std::make_pair (2417, 2),
std::make_pair (2422, 3),
std::make_pair (2427, 4),
std::make_pair (2432, 5),
std::make_pair (2437, 6),
std::make_pair (2442, 7),
std::make_pair (2447, 8),
std::make_pair (2452, 9),
std::make_pair (2457, 10),
std::make_pair (2462, 11),
std::make_pair (2467, 12),
std::make_pair (2462, 13),
};
static NetworkManager *instance_ = nullptr;
NetworkManager::NetworkManager() {
if(access(network_config_file_.c_str(), F_OK ) == -1) {
network_config_ = {{"channel", 6}};
}
else {
std::ifstream i(network_config_file_);
i >> network_config_;
i.close();
}
restart_time_ms_ = -60*1000;
std::string hwaddr = utility::Net::GetHwAddr("wlan0");
std::string device_name = "xiaopi_" + hwaddr.substr(0,2) + hwaddr.substr(3,2) + hwaddr.substr(6,2);
wifi_softap_ = std::make_shared<WifiSoftap>();
wifi_softap_->UpdateConfig("ssid", device_name);
int channel = network_config_["channel"];
if(channel != 6 ) {
wifi_softap_->UpdateConfig("channel", std::to_string(channel));
}
wifi_softap_->SaveConfig();
system("hostapd /tmp/hostapd.conf -B");
wifi_softap_->Init();
wifi_station_ = std::make_shared<WifiStation>();
wifi_station_->Subscribe(this);
wifi_station_->Init();
wifi_station_->Enable();
}
NetworkManager* NetworkManager::GetInstance() {
if(instance_ == nullptr)
instance_ = new NetworkManager();
return instance_;
}
void NetworkManager::WifiMonitor() {
wifi_station_->StartMonitor();
wifi_softap_->StartMonitor();
};
std::vector<WpaInfo> NetworkManager::Scan(void) {
std::string scan_results;
scan_results = wifi_station_->GetScanResults();
PLOGI("%s", scan_results.c_str());
auto wpa_infos_str = utility::Parser::Split(scan_results, "\n");
std::vector<WpaInfo> wpa_infos;
for(int i = 1; i < wpa_infos_str.size() - 1; ++i) {
auto wpa_info_str = utility::Parser::Split(wpa_infos_str[i], "\t");
if(wpa_info_str.size() < 5)
break;
WpaInfo wpa_info;
wpa_info.freq = std::stoi(wpa_info_str[1]);
wpa_info.signal = std::stoi(wpa_info_str[2]);
wpa_info.bssid = wpa_info_str[0];
wpa_info.flags = wpa_info_str[3];
wpa_info.ssid = wpa_info_str[4];
wpa_infos.push_back(wpa_info);
}
return wpa_infos;
}
WpaStatus NetworkManager::GetWpaStatus() {
WpaStatus wpa_status;
wpa_status.freq = 0;
std::string wpa_status_str = wifi_station_->GetStatus();
// PLOGI("%s", wpa_status_str.c_str());
auto wpa_status_details = utility::Parser::Split(wpa_status_str, "\n");
for(int i = 0; i < wpa_status_details.size(); ++i) {
auto wpa_status_detail = utility::Parser::Split(wpa_status_details[i], "=");
// PLOGI("%s", wpa_status_details[i].c_str());
if(wpa_status_detail.size() == 2) {
if(wpa_status_detail[0] == "freq")
wpa_status.freq = std::stoi(wpa_status_detail[1]);
else if(wpa_status_detail[0] == "ssid")
wpa_status.ssid = wpa_status_detail[1];
else if(wpa_status_detail[0] == "bssid")
wpa_status.bssid = wpa_status_detail[1];
else if(wpa_status_detail[0] == "key_mgmt")
wpa_status.key_mgmt = wpa_status_detail[1];
else if(wpa_status_detail[0] == "wpa_state")
wpa_status.wpa_state = wpa_status_detail[1];
}
}
return wpa_status;
}
void NetworkManager::AddNetwork(std::string ssid, std::string psk, std::string security) {
wifi_station_->AddNetwork(ssid, psk, security);
}
std::string NetworkManager::GetStationStatus(void) {
return utility::Net::GetIpAddr("wlan0");
}
std::string NetworkManager::GetSoftapStatus(void) {
return utility::Net::GetIpAddr("wlan1");
}
std::string NetworkManager::GetUsbEthernetStatus(void) {
return utility::Net::GetIpAddr("usb0");
}
std::string NetworkManager::GetStationNetmask(void) {
return utility::Net::GetNetmask("wlan0");
}
std::string NetworkManager::GetStationHwAddr(void) {
return utility::Net::GetHwAddr("wlan0");
}
void NetworkManager::OnEvent(char *buf, int len) {
char cmd[64] = {0};
char reply[256] = {0};
size_t reply_len = sizeof(reply);
if(strstr(buf, "Trying to associate") != nullptr) {
PLOGI("Station is connected");
if((utility::time::getms() - restart_time_ms_) < 60*1000) {
return;
}
WpaStatus wpa_status = GetWpaStatus();
int station_channel = kWifiChannelFreqMap[wpa_status.freq];
if(station_channel == 0 || station_channel == network_config_["channel"]) {
PLOGI("Channel does not need to change");
return;
}
network_config_["channel"] = station_channel;
PLOGI("Change channel of softap to %d", station_channel);
wifi_softap_->UpdateConfig("channel", std::to_string(station_channel));
wifi_softap_->SaveConfig();
system("killall hostapd");
system("hostapd /tmp/hostapd.conf -B");
restart_time_ms_ = utility::time::getms();
std::ofstream o(network_config_file_);
o << network_config_ << std::endl;
o.close();
}
}
| 2,170 |
5,964 | // Copyright (c) 2009 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 "head.h"
#include <cstring>
// head - Font Header
// http://www.microsoft.com/typography/otspec/head.htm
#define TABLE_NAME "head"
namespace ots {
bool ots_head_parse(Font* font, const uint8_t *data, size_t length) {
Buffer table(data, length);
OpenTypeHEAD *head = new OpenTypeHEAD;
font->head = head;
uint32_t version = 0;
if (!table.ReadU32(&version) ||
!table.ReadU32(&head->revision)) {
return OTS_FAILURE_MSG("Failed to read head header");
}
if (version >> 16 != 1) {
return OTS_FAILURE_MSG("Bad head table version of %d", version);
}
// Skip the checksum adjustment
if (!table.Skip(4)) {
return OTS_FAILURE_MSG("Failed to read checksum");
}
uint32_t magic;
if (!table.ReadU32(&magic) || magic != 0x5F0F3CF5) {
return OTS_FAILURE_MSG("Failed to read font magic number");
}
if (!table.ReadU16(&head->flags)) {
return OTS_FAILURE_MSG("Failed to read head flags");
}
// We allow bits 0..4, 11..13
head->flags &= 0x381f;
if (!table.ReadU16(&head->ppem)) {
return OTS_FAILURE_MSG("Failed to read pixels per em");
}
// ppem must be in range
if (head->ppem < 16 ||
head->ppem > 16384) {
return OTS_FAILURE_MSG("Bad ppm of %d", head->ppem);
}
// ppem must be a power of two
#if 0
// We don't call ots_failure() for now since lots of TrueType fonts are
// not following this rule. Putting OTS_WARNING here is too noisy.
if ((head->ppem - 1) & head->ppem) {
return OTS_FAILURE_MSG("ppm not a power of two: %d", head->ppem);
}
#endif
if (!table.ReadR64(&head->created) ||
!table.ReadR64(&head->modified)) {
return OTS_FAILURE_MSG("Can't read font dates");
}
if (!table.ReadS16(&head->xmin) ||
!table.ReadS16(&head->ymin) ||
!table.ReadS16(&head->xmax) ||
!table.ReadS16(&head->ymax)) {
return OTS_FAILURE_MSG("Failed to read font bounding box");
}
if (head->xmin > head->xmax) {
return OTS_FAILURE_MSG("Bad x dimension in the font bounding box (%d, %d)", head->xmin, head->xmax);
}
if (head->ymin > head->ymax) {
return OTS_FAILURE_MSG("Bad y dimension in the font bounding box (%d, %d)", head->ymin, head->ymax);
}
if (!table.ReadU16(&head->mac_style)) {
return OTS_FAILURE_MSG("Failed to read font style");
}
// We allow bits 0..6
head->mac_style &= 0x7f;
if (!table.ReadU16(&head->min_ppem)) {
return OTS_FAILURE_MSG("Failed to read font minimum ppm");
}
// We don't care about the font direction hint
if (!table.Skip(2)) {
return OTS_FAILURE_MSG("Failed to skip font direction hint");
}
if (!table.ReadS16(&head->index_to_loc_format)) {
return OTS_FAILURE_MSG("Failed to read index to loc format");
}
if (head->index_to_loc_format < 0 ||
head->index_to_loc_format > 1) {
return OTS_FAILURE_MSG("Bad index to loc format %d", head->index_to_loc_format);
}
int16_t glyph_data_format;
if (!table.ReadS16(&glyph_data_format) ||
glyph_data_format) {
return OTS_FAILURE_MSG("Failed to read glyph data format");
}
return true;
}
bool ots_head_should_serialise(Font *font) {
return font->head != NULL;
}
bool ots_head_serialise(OTSStream *out, Font *font) {
const OpenTypeHEAD *head = font->head;
if (!out->WriteU32(0x00010000) ||
!out->WriteU32(head->revision) ||
!out->WriteU32(0) || // check sum not filled in yet
!out->WriteU32(0x5F0F3CF5) ||
!out->WriteU16(head->flags) ||
!out->WriteU16(head->ppem) ||
!out->WriteR64(head->created) ||
!out->WriteR64(head->modified) ||
!out->WriteS16(head->xmin) ||
!out->WriteS16(head->ymin) ||
!out->WriteS16(head->xmax) ||
!out->WriteS16(head->ymax) ||
!out->WriteU16(head->mac_style) ||
!out->WriteU16(head->min_ppem) ||
!out->WriteS16(2) ||
!out->WriteS16(head->index_to_loc_format) ||
!out->WriteS16(0)) {
return OTS_FAILURE_MSG("Failed to write head table");
}
return true;
}
void ots_head_reuse(Font *font, Font *other) {
font->head = other->head;
font->head_reused = true;
}
void ots_head_free(Font *font) {
delete font->head;
}
} // namespace
#undef TABLE_NAME
| 1,784 |
460 | #ifndef WebCore_FWD_UTF8_h
#define WebCore_FWD_UTF8_h
#include <JavaScriptCore/UTF8.h>
#endif
| 48 |
1,514 | //
// FViewController.h
// HBDNavigationBar_Example
//
// Created by 李生 on 2019/11/27.
// Copyright © 2019 <EMAIL>. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface FViewController : UIViewController
@end
NS_ASSUME_NONNULL_END
| 108 |
648 | <gh_stars>100-1000
{"resourceType":"DataElement","id":"QuestionnaireResponse.subject","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/QuestionnaireResponse.subject","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"QuestionnaireResponse.subject","path":"QuestionnaireResponse.subject","short":"The subject of the questions","definition":"The subject of the questionnaire response. This could be a patient, organization, practitioner, device, etc. This is who/what the answers apply to, but is not necessarily the source of information.","comment":"If the Questionnaire declared a subjectType, the resource pointed to by this element must be an instance of one of the listed types.","requirements":"Allows linking the answers to the individual the answers describe. May also affect access control.","alias":["Patient","Focus"],"min":0,"max":"1","type":[{"code":"Reference","targetProfile":"http://hl7.org/fhir/StructureDefinition/Resource"}],"isSummary":true,"mapping":[{"identity":"rim","map":".participation[typeCode=SBJ].role"},{"identity":"w5","map":"who.focus"}]}]} | 287 |
767 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT
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.
""" # noqa
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_env', '0002_auto_20170821_1814'),
]
operations = [
migrations.AlterField(
model_name='appenvvar',
name='mode',
field=models.CharField(default=b'all', max_length=20, verbose_name='\u751f\u6548\u73af\u5883', choices=[('all', '\u6240\u6709\u73af\u5883'), (b'test', '\u6d4b\u8bd5\u73af\u5883'), (b'prod', '\u6b63\u5f0f\u73af\u5883')]),
),
migrations.AlterField(
model_name='appenvvar',
name='value',
field=models.CharField(max_length=1024, verbose_name='\u53d8\u91cf\u503c'),
),
]
| 576 |
1,546 | /////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tencent is pleased to support the open source community by making libpag available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. 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 "CGMask.h"
#include "platform/apple/BitmapContextUtil.h"
#include "tgfx/core/Bitmap.h"
#include "tgfx/core/Mask.h"
namespace tgfx {
static void Iterator(PathVerb verb, const Point points[4], void* info) {
auto cgPath = reinterpret_cast<CGMutablePathRef>(info);
switch (verb) {
case PathVerb::Move:
CGPathMoveToPoint(cgPath, nullptr, points[0].x, points[0].y);
break;
case PathVerb::Line:
CGPathAddLineToPoint(cgPath, nullptr, points[1].x, points[1].y);
break;
case PathVerb::Quad:
CGPathAddQuadCurveToPoint(cgPath, nullptr, points[1].x, points[1].y, points[2].x,
points[2].y);
break;
case PathVerb::Cubic:
CGPathAddCurveToPoint(cgPath, nullptr, points[1].x, points[1].y, points[2].x, points[2].y,
points[3].x, points[3].y);
break;
case PathVerb::Close:
CGPathCloseSubpath(cgPath);
break;
}
}
std::shared_ptr<Mask> Mask::Make(int width, int height) {
auto buffer = PixelBuffer::Make(width, height, true);
if (buffer == nullptr) {
return nullptr;
}
Bitmap(buffer).eraseAll();
return std::make_shared<CGMask>(std::move(buffer));
}
CGMask::CGMask(std::shared_ptr<PixelBuffer> buffer)
: Mask(buffer->width(), buffer->height()), buffer(std::move(buffer)) {
}
void CGMask::fillPath(const Path& path) {
if (path.isEmpty()) {
return;
}
const auto& info = buffer->info();
Bitmap bm(buffer);
auto cgContext = CreateBitmapContext(info, bm.writablePixels());
if (cgContext == nullptr) {
return;
}
auto finalPath = path;
auto totalMatrix = matrix;
totalMatrix.postScale(1, -1);
totalMatrix.postTranslate(0, static_cast<float>(info.height()));
finalPath.transform(totalMatrix);
auto cgPath = CGPathCreateMutable();
finalPath.decompose(Iterator, cgPath);
CGContextSetShouldAntialias(cgContext, true);
static const CGFloat white[] = {1.f, 1.f, 1.f, 1.f};
if (finalPath.isInverseFillType()) {
auto rect = CGRectMake(0.f, 0.f, info.width(), info.height());
CGContextAddRect(cgContext, rect);
CGContextSetFillColor(cgContext, white);
CGContextFillPath(cgContext);
CGContextAddPath(cgContext, cgPath);
if (finalPath.getFillType() == PathFillType::InverseWinding) {
CGContextClip(cgContext);
} else {
CGContextEOClip(cgContext);
}
CGContextClearRect(cgContext, rect);
} else {
CGContextAddPath(cgContext, cgPath);
CGContextSetFillColor(cgContext, white);
if (finalPath.getFillType() == PathFillType::Winding) {
CGContextFillPath(cgContext);
} else {
CGContextEOFillPath(cgContext);
}
}
CGContextRelease(cgContext);
CGPathRelease(cgPath);
}
void CGMask::clear() {
Bitmap(buffer).eraseAll();
}
} // namespace tgfx
| 1,368 |
325 | <reponame>patrick-kidger/equinox
from . import nn
from .filters import (
combine,
filter,
is_array,
is_array_like,
is_inexact_array,
is_inexact_array_like,
merge,
partition,
split,
)
from .grad import (
filter_custom_vjp,
filter_grad,
filter_value_and_grad,
gradf,
value_and_grad_f,
)
from .jit import filter_jit, jitf
from .module import Module, static_field
from .tree import tree_at, tree_equal
from .update import apply_updates
__version__ = "0.1.4"
| 217 |
902 | package org.anychat.util;
import java.util.UUID;
public class IdUtil {
/**
* 获取uuid
*
* @return
*/
public static String getUuid() {
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
return uuid;
}
}
| 116 |
617 | <filename>tools/minicluster/client.py
import json
import logging
from peloton_client.client import PelotonClient
import print_utils
log = logging.getLogger(__name__)
class PelotonClientWrapper(PelotonClient):
"""
Wrapper on the standard Peloton client to patch certain
parts of the data retrieved from Zookeeper. This is
needed to workaround the fact that Docker containers
created by minicluster cannot be directly addressed with
the information found in Zookeeper.
"""
def _on_job_mgr_leader_change(self, data, stat, event):
data = self._patch_leader_ip("job_mgr", data)
super(PelotonClientWrapper, self)._on_job_mgr_leader_change(
data, stat, event
)
def _on_res_mgr_leader_change(self, data, stat, event):
data = self._patch_leader_ip("res_mgr", data)
super(PelotonClientWrapper, self)._on_res_mgr_leader_change(
data, stat, event
)
def _on_host_mgr_leader_change(self, data, stat, event):
data = self._patch_leader_ip("host_mgr", data)
super(PelotonClientWrapper, self)._on_host_mgr_leader_change(
data, stat, event
)
def _patch_leader_ip(self, comp_name, data):
if data.startswith("{"):
try:
leader = json.loads(data)
leader["ip"] = "localhost"
log.info("Patching %s leader with %s", comp_name, leader)
data = json.dumps(leader)
except Exception as e:
log.warn("Failed to patch leader data: %s", e)
return data
def stop_discovery(self):
try:
print_utils.warn("stopping service discovery")
self.discovery.stop()
except Exception as e:
print_utils.fail("failed to stop discovery: {}".format(e))
print_utils.okgreen("stopped service discovery")
| 809 |
553 | # -*- coding: utf-8 -*-
"""Exceptions module for rfc3986."""
from . import compat
class RFC3986Exception(Exception):
"""Base class for all rfc3986 exception classes."""
pass
class InvalidAuthority(RFC3986Exception):
"""Exception when the authority string is invalid."""
def __init__(self, authority):
"""Initialize the exception with the invalid authority."""
super(InvalidAuthority, self).__init__(
u"The authority ({0}) is not valid.".format(compat.to_str(authority))
)
class InvalidPort(RFC3986Exception):
"""Exception when the port is invalid."""
def __init__(self, port):
"""Initialize the exception with the invalid port."""
super(InvalidPort, self).__init__('The port ("{0}") is not valid.'.format(port))
class ResolutionError(RFC3986Exception):
"""Exception to indicate a failure to resolve a URI."""
def __init__(self, uri):
"""Initialize the error with the failed URI."""
super(ResolutionError, self).__init__(
"{0} is not an absolute URI.".format(uri.unsplit())
)
class ValidationError(RFC3986Exception):
"""Exception raised during Validation of a URI."""
pass
class MissingComponentError(ValidationError):
"""Exception raised when a required component is missing."""
def __init__(self, uri, *component_names):
"""Initialize the error with the missing component name."""
verb = "was"
if len(component_names) > 1:
verb = "were"
self.uri = uri
self.components = sorted(component_names)
components = ", ".join(self.components)
super(MissingComponentError, self).__init__(
"{} {} required but missing".format(components, verb), uri, self.components
)
class UnpermittedComponentError(ValidationError):
"""Exception raised when a component has an unpermitted value."""
def __init__(self, component_name, component_value, allowed_values):
"""Initialize the error with the unpermitted component."""
super(UnpermittedComponentError, self).__init__(
"{} was required to be one of {!r} but was {!r}".format(
component_name, list(sorted(allowed_values)), component_value
),
component_name,
component_value,
allowed_values,
)
self.component_name = component_name
self.component_value = component_value
self.allowed_values = allowed_values
class PasswordForbidden(ValidationError):
"""Exception raised when a URL has a password in the userinfo section."""
def __init__(self, uri):
"""Initialize the error with the URI that failed validation."""
unsplit = getattr(uri, "unsplit", lambda: uri)
super(PasswordForbidden, self).__init__(
'"{}" contained a password when validation forbade it'.format(unsplit())
)
self.uri = uri
class InvalidComponentsError(ValidationError):
"""Exception raised when one or more components are invalid."""
def __init__(self, uri, *component_names):
"""Initialize the error with the invalid component name(s)."""
verb = "was"
if len(component_names) > 1:
verb = "were"
self.uri = uri
self.components = sorted(component_names)
components = ", ".join(self.components)
super(InvalidComponentsError, self).__init__(
"{} {} found to be invalid".format(components, verb), uri, self.components
)
class MissingDependencyError(RFC3986Exception):
"""Exception raised when an IRI is encoded without the 'idna' module."""
| 1,375 |
431 | <gh_stars>100-1000
#ifndef TST_CSTLCOMPILERATTRIBUTES_H
#define TST_CSTLCOMPILERATTRIBUTES_H
#include <QtTest>
#include <cwf/cstlcompilerattributes.h>
class TST_CSTLCompilerAttributes : public QObject
{
Q_OBJECT
private slots:
void test();
};
#endif // TST_CSTLCOMPILERATTRIBUTES_H
| 153 |
925 | <reponame>ju-sh/herbstluftwm<gh_stars>100-1000
#include "x11-types.h"
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <algorithm>
#include <cassert>
#include <iomanip>
#include <limits>
#include "globals.h"
#include "utils.h"
#include "xconnection.h"
using std::string;
using std::stringstream;
using std::vector;
Color Color::black() {
// currently, the constructor without arguments constructs black
return {};
}
Color::Color()
: red_(0), green_(0), blue_(0), x11pixelValue_(0)
{
}
Color::Color(XColor xcol, unsigned short alpha)
: red_(xcol.red), green_(xcol.green), blue_(xcol.blue), alpha_(alpha),
x11pixelValue_(x11PixelPlusAlpha(xcol.pixel, alpha))
{
// TODO: special interpretation of red, green, blue when
// xcol.flags lacks one of DoRed, DoGreen, DoBlue?
}
Color::Color(string name) {
try {
*this = fromStr(name);
} catch (...) {
*this = black();
}
}
string Color::str() const {
unsigned long divisor = (65536 + 1) / (0xFF + 1);
stringstream ss;
ss << "#"
<< std::hex << std::setfill('0') << std::setw(2) << (red_ / divisor)
<< std::hex << std::setfill('0') << std::setw(2) << (green_ / divisor)
<< std::hex << std::setfill('0') << std::setw(2) << (blue_ / divisor)
;
if (alpha_ != 0xff) {
ss << std::hex << std::setfill('0') << std::setw(2) << alpha_;
}
return ss.str();
}
Color Color::fromStr(const string& payload) {
// get X11 color from color string. This fails if there is no x connection
// from dwm.c
XColor screen_color, ret_color;
string rgb_str = payload;
unsigned short alpha = 0xff;
if (payload.size() == 9 && payload[0] == '#') {
// if the color has the format '#rrggbbaa'
rgb_str = payload.substr(0, 7);
string alpha_str = "0x" + payload.substr(7, 2);
size_t characters_processed = 0;
try {
alpha = std::stoi(alpha_str, &characters_processed, 16);
} catch(...) {
throw std::invalid_argument(
string("invalid alpha value \'") + alpha_str + "\'");
}
if (alpha > 0xff || characters_processed != alpha_str.size()) {
throw std::invalid_argument(
string("invalid alpha value \'") + alpha_str + "\'");
}
}
XConnection& xcon = XConnection::get();
auto success = XAllocNamedColor(xcon.display(),
xcon.colormap(),
rgb_str.c_str(), &screen_color, &ret_color);
if (!success) {
throw std::invalid_argument(
string("cannot allocate color \'") + payload + "\'");
}
return Color(ret_color, alpha);
}
XColor Color::toXColor() const {
return XColor{x11pixelValue_, red_, green_, blue_, DoRed | DoGreen | DoBlue, 0};
}
int Point2D::manhattanLength() const
{
return std::abs(x) + std::abs(y);
}
| 1,300 |
984 | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File: basetyps.h
//
//----------------------------------------------------------------------------
#if !defined( _BASETYPS_H_ )
#define _BASETYPS_H_
#if _MSC_VER > 1000
#pragma once
#endif
// Common macros gleamed from COMPOBJ.H
#ifdef __cplusplus
#define EXTERN_C extern "C"
#else
#define EXTERN_C extern
#endif
#ifdef _WIN32
// Win32 doesn't support __export
#define STDMETHODCALLTYPE __stdcall
#define STDMETHODVCALLTYPE __cdecl
#define STDAPICALLTYPE __stdcall
#define STDAPIVCALLTYPE __cdecl
#else
#define STDMETHODCALLTYPE __export __stdcall
#define STDMETHODVCALLTYPE __export __cdecl
#define STDAPICALLTYPE __export __stdcall
#define STDAPIVCALLTYPE __export __cdecl
#endif
#define STDAPI EXTERN_C HRESULT STDAPICALLTYPE
#define STDAPI_(type) EXTERN_C type STDAPICALLTYPE
#define STDMETHODIMP HRESULT STDMETHODCALLTYPE
#define STDMETHODIMP_(type) type STDMETHODCALLTYPE
// The 'V' versions allow Variable Argument lists.
#define STDAPIV EXTERN_C HRESULT STDAPIVCALLTYPE
#define STDAPIV_(type) EXTERN_C type STDAPIVCALLTYPE
#define STDMETHODIMPV HRESULT STDMETHODVCALLTYPE
#define STDMETHODIMPV_(type) type STDMETHODVCALLTYPE
/****** Interface Declaration ***********************************************/
/*
* These are macros for declaring interfaces. They exist so that
* a single definition of the interface is simulataneously a proper
* declaration of the interface structures (C++ abstract classes)
* for both C and C++.
*
* DECLARE_INTERFACE(iface) is used to declare an interface that does
* not derive from a base interface.
* DECLARE_INTERFACE_(iface, baseiface) is used to declare an interface
* that does derive from a base interface.
*
* By default if the source file has a .c extension the C version of
* the interface declaratations will be expanded; if it has a .cpp
* extension the C++ version will be expanded. if you want to force
* the C version expansion even though the source file has a .cpp
* extension, then define the macro "CINTERFACE".
* eg. cl -DCINTERFACE file.cpp
*
* Example Interface declaration:
*
* #undef INTERFACE
* #define INTERFACE IClassFactory
*
* DECLARE_INTERFACE_(IClassFactory, IUnknown)
* {
* // *** IUnknown methods ***
* STDMETHOD(QueryInterface) (THIS_
* REFIID riid,
* LPVOID FAR* ppvObj) PURE;
* STDMETHOD_(ULONG,AddRef) (THIS) PURE;
* STDMETHOD_(ULONG,Release) (THIS) PURE;
*
* // *** IClassFactory methods ***
* STDMETHOD(CreateInstance) (THIS_
* LPUNKNOWN pUnkOuter,
* REFIID riid,
* LPVOID FAR* ppvObject) PURE;
* };
*
* Example C++ expansion:
*
* struct FAR IClassFactory : public IUnknown
* {
* virtual HRESULT STDMETHODCALLTYPE QueryInterface(
* IID FAR& riid,
* LPVOID FAR* ppvObj) = 0;
* virtual HRESULT STDMETHODCALLTYPE AddRef(void) = 0;
* virtual HRESULT STDMETHODCALLTYPE Release(void) = 0;
* virtual HRESULT STDMETHODCALLTYPE CreateInstance(
* LPUNKNOWN pUnkOuter,
* IID FAR& riid,
* LPVOID FAR* ppvObject) = 0;
* };
*
* NOTE: Our documentation says '#define interface class' but we use
* 'struct' instead of 'class' to keep a lot of 'public:' lines
* out of the interfaces. The 'FAR' forces the 'this' pointers to
* be far, which is what we need.
*
* Example C expansion:
*
* typedef struct IClassFactory
* {
* const struct IClassFactoryVtbl FAR* lpVtbl;
* } IClassFactory;
*
* typedef struct IClassFactoryVtbl IClassFactoryVtbl;
*
* struct IClassFactoryVtbl
* {
* HRESULT (STDMETHODCALLTYPE * QueryInterface) (
* IClassFactory FAR* This,
* IID FAR* riid,
* LPVOID FAR* ppvObj) ;
* HRESULT (STDMETHODCALLTYPE * AddRef) (IClassFactory FAR* This) ;
* HRESULT (STDMETHODCALLTYPE * Release) (IClassFactory FAR* This) ;
* HRESULT (STDMETHODCALLTYPE * CreateInstance) (
* IClassFactory FAR* This,
* LPUNKNOWN pUnkOuter,
* IID FAR* riid,
* LPVOID FAR* ppvObject);
* HRESULT (STDMETHODCALLTYPE * LockServer) (
* IClassFactory FAR* This,
* BOOL fLock);
* };
*/
#if defined(__cplusplus) && !defined(CINTERFACE)
//#define interface struct FAR
#ifdef COM_STDMETHOD_CAN_THROW
#define COM_DECLSPEC_NOTHROW
#else
#define COM_DECLSPEC_NOTHROW DECLSPEC_NOTHROW
#endif
#define __STRUCT__ struct
#define interface __STRUCT__
#define STDMETHOD(method) virtual COM_DECLSPEC_NOTHROW HRESULT STDMETHODCALLTYPE method
#define STDMETHOD_(type,method) virtual COM_DECLSPEC_NOTHROW type STDMETHODCALLTYPE method
#define STDMETHODV(method) virtual COM_DECLSPEC_NOTHROW HRESULT STDMETHODVCALLTYPE method
#define STDMETHODV_(type,method) virtual COM_DECLSPEC_NOTHROW type STDMETHODVCALLTYPE method
#define PURE = 0
#define THIS_
#define THIS void
#define DECLARE_INTERFACE(iface) interface DECLSPEC_NOVTABLE iface
#define DECLARE_INTERFACE_(iface, baseiface) interface DECLSPEC_NOVTABLE iface : public baseiface
#define IFACEMETHOD(method) __override STDMETHOD(method)
#define IFACEMETHOD_(type,method) __override STDMETHOD_(type,method)
#define IFACEMETHODV(method) __override STDMETHODV(method)
#define IFACEMETHODV_(type,method) __override STDMETHODV_(type,method)
#else
#define interface struct
#define STDMETHOD(method) HRESULT (STDMETHODCALLTYPE * method)
#define STDMETHOD_(type,method) type (STDMETHODCALLTYPE * method)
#define STDMETHODV(method) HRESULT (STDMETHODVCALLTYPE * method)
#define STDMETHODV_(type,method) type (STDMETHODVCALLTYPE * method)
#define IFACEMETHOD(method) __override STDMETHOD(method)
#define IFACEMETHOD_(type,method) __override STDMETHOD_(type,method)
#define IFACEMETHODV(method) __override STDMETHODV(method)
#define IFACEMETHODV_(type,method) __override STDMETHODV_(type,method)
#define PURE
#define THIS_ INTERFACE FAR* This,
#define THIS INTERFACE FAR* This
#ifdef CONST_VTABLE
#define DECLARE_INTERFACE(iface) typedef interface iface { \
const struct iface##Vtbl FAR* lpVtbl; \
} iface; \
typedef const struct iface##Vtbl iface##Vtbl; \
const struct iface##Vtbl
#else
#define DECLARE_INTERFACE(iface) typedef interface iface { \
struct iface##Vtbl FAR* lpVtbl; \
} iface; \
typedef struct iface##Vtbl iface##Vtbl; \
struct iface##Vtbl
#endif
#define DECLARE_INTERFACE_(iface, baseiface) DECLARE_INTERFACE(iface)
#endif
#include <guiddef.h>
#ifndef _ERROR_STATUS_T_DEFINED
typedef unsigned long error_status_t;
#define _ERROR_STATUS_T_DEFINED
#endif
#ifndef _WCHAR_T_DEFINED
typedef unsigned short wchar_t;
#define _WCHAR_T_DEFINED
#endif
#endif
| 4,147 |
589 | <filename>inspectit.server/src/test/java/rocks/inspectit/server/processor/impl/InfluxProcessorTest.java
package rocks.inspectit.server.processor.impl;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import javax.persistence.EntityManager;
import org.influxdb.dto.Point;
import org.influxdb.dto.Point.Builder;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.testng.annotations.Test;
import rocks.inspectit.server.influx.builder.IPointBuilder;
import rocks.inspectit.server.influx.dao.InfluxDBDao;
import rocks.inspectit.shared.all.communication.DefaultData;
import rocks.inspectit.shared.all.communication.data.HttpTimerData;
import rocks.inspectit.shared.all.communication.data.InvocationSequenceData;
import rocks.inspectit.shared.all.communication.data.JmxSensorValueData;
import rocks.inspectit.shared.all.communication.data.TimerData;
import rocks.inspectit.shared.all.testbase.TestBase;
/**
* @author <NAME>
*
*/
@SuppressWarnings("all")
public class InfluxProcessorTest extends TestBase {
InfluxProcessor processor;
@Mock
InfluxDBDao influxDBDao;
@Mock
EntityManager entityManager;
@Mock
IPointBuilder<DefaultData> pointBuilder;
Builder builder = Point.measurement("test").addField("test", 1).time(1, TimeUnit.MILLISECONDS);
public class Process extends InfluxProcessorTest {
@Test
public void processed() {
InvocationSequenceData invocationData = new InvocationSequenceData();
when(influxDBDao.isConnected()).thenReturn(true);
doReturn(Collections.singleton(InvocationSequenceData.class)).when(pointBuilder).getDataClasses();
when(pointBuilder.createBuilders(invocationData)).thenReturn(Collections.singleton(builder));
processor = new InfluxProcessor(influxDBDao, Collections.<IPointBuilder<DefaultData>> singletonList(pointBuilder));
processor.process(invocationData, entityManager);
verify(influxDBDao).isConnected();
ArgumentCaptor<Point> pointCaptor = ArgumentCaptor.forClass(Point.class);
verify(influxDBDao).insert(pointCaptor.capture());
assertThat(pointCaptor.getValue().lineProtocol(), is(builder.build().lineProtocol()));
verifyZeroInteractions(entityManager);
}
@Test
public void noBuilders() {
InvocationSequenceData invocationData = new InvocationSequenceData();
when(influxDBDao.isConnected()).thenReturn(true);
processor = new InfluxProcessor(influxDBDao, Collections.<IPointBuilder<DefaultData>> emptyList());
processor.process(invocationData, entityManager);
verify(influxDBDao).isConnected();
verifyNoMoreInteractions(influxDBDao);
verifyZeroInteractions(entityManager);
}
@Test
public void influxOffline() {
InvocationSequenceData invocationData = new InvocationSequenceData();
when(influxDBDao.isConnected()).thenReturn(false);
doReturn(Collections.singleton(InvocationSequenceData.class)).when(pointBuilder).getDataClasses();
processor = new InfluxProcessor(influxDBDao, Collections.<IPointBuilder<DefaultData>> singletonList(pointBuilder));
processor.process(invocationData, entityManager);
verify(influxDBDao).isConnected();
verifyNoMoreInteractions(influxDBDao);
verifyZeroInteractions(entityManager);
}
@Test
public void builderForClassDoesNotExist() {
InvocationSequenceData invocationData = new InvocationSequenceData();
when(influxDBDao.isConnected()).thenReturn(true);
doReturn(Collections.singleton(HttpTimerData.class)).when(pointBuilder).getDataClasses();
processor = new InfluxProcessor(influxDBDao, Collections.<IPointBuilder<DefaultData>> singletonList(pointBuilder));
processor.process(invocationData, entityManager);
verify(influxDBDao).isConnected();
verify(pointBuilder).getDataClasses();
verifyNoMoreInteractions(influxDBDao, pointBuilder);
verifyZeroInteractions(entityManager);
}
@Test
public void timerNotCharting() {
TimerData data = new TimerData();
data.setCharting(false);
when(influxDBDao.isConnected()).thenReturn(true);
doReturn(Collections.singleton(TimerData.class)).when(pointBuilder).getDataClasses();
processor = new InfluxProcessor(influxDBDao, Collections.<IPointBuilder<DefaultData>> singletonList(pointBuilder));
processor.process(data, entityManager);
verify(influxDBDao).isConnected();
verify(pointBuilder).getDataClasses();
verifyNoMoreInteractions(influxDBDao, pointBuilder);
verifyZeroInteractions(entityManager);
}
@Test
public void timerCharting() {
TimerData data = new TimerData();
data.setCharting(true);
when(influxDBDao.isConnected()).thenReturn(true);
doReturn(Collections.singleton(TimerData.class)).when(pointBuilder).getDataClasses();
when(pointBuilder.createBuilders(data)).thenReturn(Collections.singleton(builder));
processor = new InfluxProcessor(influxDBDao, Collections.<IPointBuilder<DefaultData>> singletonList(pointBuilder));
processor.process(data, entityManager);
verify(influxDBDao).isConnected();
ArgumentCaptor<Point> pointCaptor = ArgumentCaptor.forClass(Point.class);
verify(influxDBDao).insert(pointCaptor.capture());
assertThat(pointCaptor.getValue().lineProtocol(), is(builder.build().lineProtocol()));
verifyZeroInteractions(entityManager);
}
@Test
public void jmxNotNumeric() {
JmxSensorValueData data = new JmxSensorValueData();
data.setValue("string value");
when(influxDBDao.isConnected()).thenReturn(true);
doReturn(Collections.singleton(JmxSensorValueData.class)).when(pointBuilder).getDataClasses();
processor = new InfluxProcessor(influxDBDao, Collections.<IPointBuilder<DefaultData>> singletonList(pointBuilder));
processor.process(data, entityManager);
verify(influxDBDao).isConnected();
verify(pointBuilder).getDataClasses();
verifyNoMoreInteractions(influxDBDao, pointBuilder);
verifyZeroInteractions(entityManager);
}
@Test
public void jmxNumeric() {
JmxSensorValueData data = new JmxSensorValueData();
data.setValue("1");
when(influxDBDao.isConnected()).thenReturn(true);
doReturn(Collections.singleton(JmxSensorValueData.class)).when(pointBuilder).getDataClasses();
when(pointBuilder.createBuilders(data)).thenReturn(Collections.singleton(builder));
processor = new InfluxProcessor(influxDBDao, Collections.<IPointBuilder<DefaultData>> singletonList(pointBuilder));
processor.process(data, entityManager);
verify(influxDBDao).isConnected();
ArgumentCaptor<Point> pointCaptor = ArgumentCaptor.forClass(Point.class);
verify(influxDBDao).insert(pointCaptor.capture());
assertThat(pointCaptor.getValue().lineProtocol(), is(builder.build().lineProtocol()));
verifyZeroInteractions(entityManager);
}
}
}
| 2,366 |
615 | package org.byron4j.cookbook.javacore.dynamicproxy.jdkproxy;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DynamicAnno {
}
| 82 |
432 | <reponame>Mu-L/activej<filename>core-datastream/src/main/java/io/activej/datastream/stats/StreamStatsDetailed.java
/*
* Copyright (C) 2020 ActiveJ 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 io.activej.datastream.stats;
import io.activej.datastream.StreamDataAcceptor;
import io.activej.jmx.api.attribute.JmxAttribute;
import io.activej.jmx.api.attribute.JmxReducers.JmxReducerSum;
import io.activej.jmx.stats.JmxStatsWithReset;
import io.activej.jmx.stats.StatsUtils;
import org.jetbrains.annotations.Nullable;
import java.time.Duration;
public final class StreamStatsDetailed<T> extends StreamStatsBasic<T> implements JmxStatsWithReset {
private final @Nullable StreamStatsSizeCounter<Object> sizeCounter;
private long count;
private long totalSize;
@SuppressWarnings("unchecked")
StreamStatsDetailed(@Nullable StreamStatsSizeCounter<?> sizeCounter) {
this.sizeCounter = (StreamStatsSizeCounter<Object>) sizeCounter;
}
@Override
public StreamStatsDetailed<T> withBasicSmoothingWindow(Duration smoothingWindow) {
return (StreamStatsDetailed<T>) super.withBasicSmoothingWindow(smoothingWindow);
}
@Override
public StreamDataAcceptor<T> createDataAcceptor(StreamDataAcceptor<T> actualDataAcceptor) {
return sizeCounter == null ?
item -> {
count++;
actualDataAcceptor.accept(item);
} :
item -> {
count++;
int size = sizeCounter.size(item);
totalSize += size;
actualDataAcceptor.accept(item);
};
}
@JmxAttribute(reducer = JmxReducerSum.class)
public long getCount() {
return count;
}
@JmxAttribute(reducer = JmxReducerSum.class)
public @Nullable Long getTotalSize() {
return sizeCounter != null ? totalSize : null;
}
@JmxAttribute(reducer = JmxReducerSum.class)
public @Nullable Long getTotalSizeAvg() {
return sizeCounter != null && getStarted().getTotalCount() != 0 ?
totalSize / getStarted().getTotalCount() :
null;
}
@Override
public void resetStats() {
count = totalSize = 0;
StatsUtils.resetStats(this);
}
}
| 837 |
681 | <filename>doc/sphinx-guides/source/_static/api/dataverse-minimal.json
{
"name": "<NAME>",
"alias": "science",
"dataverseContacts": [
{
"contactEmail": "<EMAIL>"
}
]
}
| 83 |
354 | <gh_stars>100-1000
/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2015 The Khronos Group Inc.
* Copyright (c) 2015 Samsung Electronics Co., 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.
*
*//*!
* \file
* \brief Vulkan Get Render Area Granularity Tests
*//*--------------------------------------------------------------------*/
#include "vktApiGranularityTests.hpp"
#include "deRandom.hpp"
#include "deSharedPtr.hpp"
#include "deStringUtil.hpp"
#include "deUniquePtr.hpp"
#include "vkImageUtil.hpp"
#include "vkMemUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkRefUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vktTestCase.hpp"
#include "tcuTestLog.hpp"
#include "tcuTextureUtil.hpp"
#include <string>
namespace vkt
{
namespace api
{
using namespace vk;
namespace
{
struct AttachmentInfo
{
AttachmentInfo (const VkFormat vkFormat,
const deUint32 width,
const deUint32 height,
const deUint32 depth)
: format (vkFormat)
{
extent.width = width;
extent.height = height;
extent.depth = depth;
}
~AttachmentInfo (void)
{}
VkFormat format;
VkExtent3D extent;
};
typedef de::SharedPtr<Allocation> AllocationSp;
typedef de::SharedPtr<Unique<VkImage> > VkImageSp;
typedef de::SharedPtr<Unique<VkImageView> > VkImageViewSp;
class GranularityInstance : public vkt::TestInstance
{
public:
GranularityInstance (Context& context,
const std::vector<AttachmentInfo>& attachments,
const bool useRenderPass);
virtual ~GranularityInstance (void);
void checkFormatSupport (const VkFormat format);
void initAttachmentDescriptions (void);
void initImages (void);
void initRenderPass (void);
void beginRenderPass (void);
void endRenderPass (void);
virtual tcu::TestStatus iterate (void);
private:
const std::vector<AttachmentInfo> m_attachments;
const bool m_useRenderPass;
Move<VkRenderPass> m_renderPass;
Move<VkFramebuffer> m_frameBuffer;
Move<VkCommandPool> m_cmdPool;
Move<VkCommandBuffer> m_cmdBuffer;
std::vector<VkAttachmentDescription> m_attachmentDescriptions;
std::vector<VkImageSp> m_images;
std::vector<AllocationSp> m_imageAllocs;
std::vector<VkImageViewSp> m_imageViews;
};
GranularityInstance::GranularityInstance (Context& context,
const std::vector<AttachmentInfo>& attachments,
const bool useRenderPass)
: vkt::TestInstance (context)
, m_attachments (attachments)
, m_useRenderPass (useRenderPass)
{
initAttachmentDescriptions();
}
GranularityInstance::~GranularityInstance (void)
{
}
void GranularityInstance::checkFormatSupport (const VkFormat format)
{
VkImageFormatProperties properties;
VkResult result = m_context.getInstanceInterface().getPhysicalDeviceImageFormatProperties(m_context.getPhysicalDevice(),
format, VK_IMAGE_TYPE_2D,
VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_SAMPLED_BIT,
0,
&properties);
if (result == VK_ERROR_FORMAT_NOT_SUPPORTED)
TCU_THROW(NotSupportedError, "Format not supported");
}
void GranularityInstance::initAttachmentDescriptions (void)
{
VkAttachmentDescription attachmentDescription =
{
0u, // VkAttachmentDescriptionFlags flags;
VK_FORMAT_UNDEFINED, // VkFormat format;
VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples;
VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp loadOp;
VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp storeOp;
VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp;
VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp;
VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout;
VK_IMAGE_LAYOUT_GENERAL, // VkImageLayout finalLayout;
};
for (std::vector<AttachmentInfo>::const_iterator it = m_attachments.begin(); it != m_attachments.end(); ++it)
{
checkFormatSupport(it->format);
attachmentDescription.format = it->format;
m_attachmentDescriptions.push_back(attachmentDescription);
}
}
void GranularityInstance::initImages (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice device = m_context.getDevice();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
SimpleAllocator memAlloc (vk, device, getPhysicalDeviceMemoryProperties(m_context.getInstanceInterface(), m_context.getPhysicalDevice()));
for (std::vector<AttachmentInfo>::const_iterator it = m_attachments.begin(); it != m_attachments.end(); ++it)
{
const VkImageCreateInfo imageInfo =
{
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkImageCreateFlags flags;
VK_IMAGE_TYPE_2D, // VkImageType imageType;
it->format, // VkFormat format;
it->extent, // VkExtent3D extent;
1u, // deUint32 mipLevels;
1u, // deUint32 arrayLayers;
VK_SAMPLE_COUNT_1_BIT, // deUint32 samples;
VK_IMAGE_TILING_OPTIMAL, // VkImageTiling tiling;
VK_IMAGE_USAGE_SAMPLED_BIT, // VkImageUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
1u, // deUint32 queueFamilyCount;
&queueFamilyIndex, // const deUint32* pQueueFamilyIndices;
VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout;
};
// Create the image
Move<VkImage> image = createImage(vk, device, &imageInfo);
de::MovePtr<Allocation> imageAlloc = memAlloc.allocate(getImageMemoryRequirements(vk, device, *image), MemoryRequirement::Any);
VK_CHECK(vk.bindImageMemory(device, *image, imageAlloc->getMemory(), imageAlloc->getOffset()));
VkImageAspectFlags aspectFlags = 0;
const tcu::TextureFormat tcuFormat = mapVkFormat(it->format);
if (tcu::hasDepthComponent(tcuFormat.order))
aspectFlags |= VK_IMAGE_ASPECT_DEPTH_BIT;
if (tcu::hasStencilComponent(tcuFormat.order))
aspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT;
if (!aspectFlags)
aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT;
VkFormatProperties formatProperties;
m_context.getInstanceInterface().getPhysicalDeviceFormatProperties(m_context.getPhysicalDevice(),
it->format, &formatProperties);
if ((formatProperties.optimalTilingFeatures & (VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT |
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) == 0)
throw tcu::NotSupportedError("Format not supported as attachment");
const VkImageViewCreateInfo createInfo =
{
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0, // VkImageViewCreateFlags flags;
*image, // VkImage image;
VK_IMAGE_VIEW_TYPE_2D, // VkImageViewType viewType;
it->format, // VkFormat format;
{
VK_COMPONENT_SWIZZLE_R,
VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B,
VK_COMPONENT_SWIZZLE_A
}, // VkComponentMapping components;
{ aspectFlags, 0u, 1u, 0u, 1u } // VkImageSubresourceRange subresourceRange;
};
// Create the Image View
Move<VkImageView> imageView = createImageView(vk, device, &createInfo);
// To prevent object free
m_images.push_back(VkImageSp(new Unique<VkImage>(image)));
m_imageAllocs.push_back(AllocationSp(imageAlloc.release()));
m_imageViews.push_back(VkImageViewSp(new Unique<VkImageView>(imageView)));
}
}
void GranularityInstance::initRenderPass (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice device = m_context.getDevice();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
{ // Create RenderPass
const VkSubpassDescription subpassDesc =
{
(VkSubpassDescriptionFlags)0u, // VkSubpassDescriptionFlags flags;
VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint;
0u, // deUint32 inputCount;
DE_NULL, // const VkAttachmentReference* pInputAttachments;
0u, // deUint32 colorCount;
DE_NULL, // const VkAttachmentReference* pColorAttachments;
DE_NULL, // const VkAttachmentReference* pResolveAttachments;
DE_NULL, // VkAttachmentReference depthStencilAttachment;
0u, // deUint32 preserveCount;
DE_NULL // const VkAttachmentReference* pPreserveAttachments;
};
const VkRenderPassCreateInfo renderPassParams =
{
VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkRenderPassCreateFlags)0, // VkRenderPassCreateFlags flags;
(deUint32)m_attachmentDescriptions.size(), // deUint32 attachmentCount;
&m_attachmentDescriptions[0], // const VkAttachmentDescription* pAttachments;
1u, // deUint32 subpassCount;
&subpassDesc, // const VkSubpassDescription* pSubpasses;
0u, // deUint32 dependencyCount;
DE_NULL // const VkSubpassDependency* pDependencies;
};
m_renderPass = createRenderPass(vk, device, &renderPassParams);
}
initImages();
{ // Create Framebuffer
std::vector<VkImageView> imageViews;
for (std::vector<VkImageViewSp>::const_iterator it = m_imageViews.begin(); it != m_imageViews.end(); ++it)
imageViews.push_back(it->get()->get());
const VkFramebufferCreateInfo framebufferParams =
{
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkFramebufferCreateFlags)0, // VkFramebufferCreateFlags flags;
*m_renderPass, // VkRenderPass renderPass;
(deUint32)imageViews.size(), // deUint32 attachmentCount;
&imageViews[0], // const VkImageView* pAttachments;
1, // deUint32 width;
1, // deUint32 height;
1 // deUint32 layers;
};
m_frameBuffer = createFramebuffer(vk, device, &framebufferParams);
}
m_cmdPool = createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, queueFamilyIndex);
// Create CommandBuffer
m_cmdBuffer = allocateCommandBuffer(vk, device, *m_cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY);
// Begin CommandBuffer
beginCommandBuffer(vk, *m_cmdBuffer, 0u);
}
void GranularityInstance::beginRenderPass (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkRect2D renderArea = makeRect2D(1u, 1u);
vk::beginRenderPass(vk, *m_cmdBuffer, *m_renderPass, *m_frameBuffer, renderArea);
}
void GranularityInstance::endRenderPass (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
vk::endRenderPass(vk, *m_cmdBuffer);
endCommandBuffer(vk, *m_cmdBuffer);
}
tcu::TestStatus GranularityInstance::iterate (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice device = m_context.getDevice();
tcu::TestLog& log = m_context.getTestContext().getLog();
initRenderPass();
VkExtent2D prePassGranularity = { ~0u, ~0u };
vk.getRenderAreaGranularity(device, *m_renderPass, &prePassGranularity);
if(m_useRenderPass)
beginRenderPass();
VkExtent2D granularity = { 0u, 0u };
vk.getRenderAreaGranularity(device, *m_renderPass, &granularity);
TCU_CHECK(granularity.width >= 1 && granularity.height >= 1);
TCU_CHECK(prePassGranularity.width == granularity.width && prePassGranularity.height == granularity.height);
TCU_CHECK(granularity.width <= m_context.getDeviceProperties().limits.maxFramebufferWidth && granularity.height <= m_context.getDeviceProperties().limits.maxFramebufferHeight);
if(m_useRenderPass)
endRenderPass();
log << tcu::TestLog::Message << "Horizontal granularity: " << granularity.width << " Vertical granularity: " << granularity.height << tcu::TestLog::EndMessage;
return tcu::TestStatus::pass("Granularity test");
}
class GranularityCase : public vkt::TestCase
{
public:
GranularityCase (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description,
const std::vector<AttachmentInfo>& attachments,
const bool useRenderPass);
virtual ~GranularityCase (void);
virtual TestInstance* createInstance (Context& context) const;
private:
const std::vector<AttachmentInfo> m_attachments;
const bool m_useRenderPass;
};
GranularityCase::GranularityCase (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description,
const std::vector<AttachmentInfo>& attachments,
const bool useRenderPass = false)
: vkt::TestCase (testCtx, name, description)
, m_attachments (attachments)
, m_useRenderPass (useRenderPass)
{
}
GranularityCase::~GranularityCase (void)
{
}
TestInstance* GranularityCase::createInstance (Context& context) const
{
return new GranularityInstance(context, m_attachments, m_useRenderPass);
}
} // anonymous
tcu::TestCaseGroup* createGranularityQueryTests (tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> group (new tcu::TestCaseGroup(testCtx, "granularity", "Granularity query tests"));
// Subgroups
de::MovePtr<tcu::TestCaseGroup> single (new tcu::TestCaseGroup(testCtx, "single", "Single texture granularity tests."));
de::MovePtr<tcu::TestCaseGroup> multi (new tcu::TestCaseGroup(testCtx, "multi", "Multiple textures with same format granularity tests."));
de::MovePtr<tcu::TestCaseGroup> random (new tcu::TestCaseGroup(testCtx, "random", "Multiple textures with a guaranteed format occurence."));
de::MovePtr<tcu::TestCaseGroup> inRenderPass (new tcu::TestCaseGroup(testCtx, "in_render_pass", "Single texture granularity tests, inside render pass"));
de::Random rnd(215);
const char* description = "Granularity case.";
const VkFormat mandatoryFormats[] =
{
VK_FORMAT_B4G4R4A4_UNORM_PACK16,
VK_FORMAT_R5G6B5_UNORM_PACK16,
VK_FORMAT_A1R5G5B5_UNORM_PACK16,
VK_FORMAT_R8_UNORM,
VK_FORMAT_R8_SNORM,
VK_FORMAT_R8_UINT,
VK_FORMAT_R8_SINT,
VK_FORMAT_R8G8_UNORM,
VK_FORMAT_R8G8_SNORM,
VK_FORMAT_R8G8_UINT,
VK_FORMAT_R8G8_SINT,
VK_FORMAT_R8G8B8A8_UNORM,
VK_FORMAT_R8G8B8A8_SNORM,
VK_FORMAT_R8G8B8A8_UINT,
VK_FORMAT_R8G8B8A8_SINT,
VK_FORMAT_R8G8B8A8_SRGB,
VK_FORMAT_B8G8R8A8_UNORM,
VK_FORMAT_B8G8R8A8_SRGB,
VK_FORMAT_A8B8G8R8_UNORM_PACK32,
VK_FORMAT_A8B8G8R8_SNORM_PACK32,
VK_FORMAT_A8B8G8R8_UINT_PACK32,
VK_FORMAT_A8B8G8R8_SINT_PACK32,
VK_FORMAT_A8B8G8R8_SRGB_PACK32,
VK_FORMAT_A2B10G10R10_UNORM_PACK32,
VK_FORMAT_A2B10G10R10_UINT_PACK32,
VK_FORMAT_R16_UINT,
VK_FORMAT_R16_SINT,
VK_FORMAT_R16_SFLOAT,
VK_FORMAT_R16G16_UINT,
VK_FORMAT_R16G16_SINT,
VK_FORMAT_R16G16_SFLOAT,
VK_FORMAT_R16G16B16A16_UINT,
VK_FORMAT_R16G16B16A16_SINT,
VK_FORMAT_R16G16B16A16_SFLOAT,
VK_FORMAT_R32_UINT,
VK_FORMAT_R32_SINT,
VK_FORMAT_R32_SFLOAT,
VK_FORMAT_R32G32_UINT,
VK_FORMAT_R32G32_SINT,
VK_FORMAT_R32G32_SFLOAT,
VK_FORMAT_R32G32B32A32_UINT,
VK_FORMAT_R32G32B32A32_SINT,
VK_FORMAT_R32G32B32A32_SFLOAT,
VK_FORMAT_B10G11R11_UFLOAT_PACK32,
VK_FORMAT_E5B9G9R9_UFLOAT_PACK32,
VK_FORMAT_D16_UNORM,
VK_FORMAT_D32_SFLOAT,
};
const deUint32 maxDimension = 500;
const deUint32 minIteration = 2;
const deUint32 maxIteration = 10;
for (deUint32 formatIdx = 1; formatIdx <= VK_FORMAT_D32_SFLOAT_S8_UINT; ++formatIdx)
{
VkFormat format = VkFormat(formatIdx);
std::string name = de::toLower(getFormatName(format)).substr(10);
{
std::vector<AttachmentInfo> attachments;
const int i0 = rnd.getInt(1, maxDimension);
const int i1 = rnd.getInt(1, maxDimension);
attachments.push_back(AttachmentInfo(format, i0, i1, 1));
single->addChild(new GranularityCase(testCtx, name.c_str(), description, attachments));
}
{
std::vector<AttachmentInfo> attachments;
const deUint32 iterations = rnd.getInt(minIteration, maxIteration);
const int i0 = rnd.getInt(1, maxDimension);
const int i1 = rnd.getInt(1, maxDimension);
for (deUint32 idx = 0; idx < iterations; ++idx)
attachments.push_back(AttachmentInfo(VkFormat(formatIdx), i0, i1, 1));
multi->addChild(new GranularityCase(testCtx, name.c_str(), description, attachments));
}
{
std::vector<AttachmentInfo> attachments;
const deUint32 iterations = rnd.getInt(minIteration, maxIteration);
const int i0 = rnd.getInt(1, maxDimension);
const int i1 = rnd.getInt(1, maxDimension);
attachments.push_back(AttachmentInfo(VkFormat(formatIdx), i0, i1, 1));
for (deUint32 idx = 0; idx < iterations; ++idx)
{
const int i2 = rnd.getInt(0, DE_LENGTH_OF_ARRAY(mandatoryFormats) - 1);
const int i3 = rnd.getInt(1, maxDimension);
const int i4 = rnd.getInt(1, maxDimension);
attachments.push_back(AttachmentInfo(mandatoryFormats[i2], i3, i4, 1));
}
random->addChild(new GranularityCase(testCtx, name.c_str(), description, attachments));
}
{
std::vector<AttachmentInfo> attachments;
const int i0 = rnd.getInt(1, maxDimension);
const int i1 = rnd.getInt(1, maxDimension);
attachments.push_back(AttachmentInfo(format, i0, i1, 1));
inRenderPass->addChild(new GranularityCase(testCtx, name.c_str(), description, attachments, true));
}
}
group->addChild(single.release());
group->addChild(multi.release());
group->addChild(random.release());
group->addChild(inRenderPass.release());
return group.release();
}
} // api
} // vkt
| 8,094 |
348 | {"nom":"Amendeuix-Oneix","dpt":"Pyrénées-Atlantiques","inscrits":363,"abs":55,"votants":308,"blancs":27,"nuls":6,"exp":275,"res":[{"panneau":"1","voix":225},{"panneau":"2","voix":50}]} | 78 |
982 | #pragma once
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <string.h>
#include <tchar.h>
#include <cguid.h>
#include <WtsApi32.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
//#include <atlbase.h>
//#include <atlcoll.h>
#include <atlstr.h>
#include <atlcoll.h>
#include "Log.h"
#include "Names.h"
#include "Service.h"
#include "CProcessRunner.h"
void ProcessProtocolUninstall();
| 195 |
464 | <gh_stars>100-1000
{
"name": "wtfnode",
"version": "0.9.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"version": "0.9.0",
"license": "ISC",
"bin": {
"wtfnode": "proxy.js"
},
"devDependencies": {
"coffeescript": "^2.5.1",
"source-map-support": "^0.5.19"
}
},
"node_modules/buffer-from": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz",
"integrity": "<KEY>
"dev": true
},
"node_modules/coffeescript": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/coffeescript/-/coffeescript-2.5.1.tgz",
"integrity": "<KEY>
"dev": true,
"bin": {
"cake": "bin/cake",
"coffee": "bin/coffee"
},
"engines": {
"node": ">=6"
}
},
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"dev": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/source-map-support": {
"version": "0.5.19",
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz",
"integrity": "<KEY>
"dev": true,
"dependencies": {
"buffer-from": "^1.0.0",
"source-map": "^0.6.0"
}
}
},
"dependencies": {
"buffer-from": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz",
"integrity": "<KEY>
"dev": true
},
"coffeescript": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/coffeescript/-/coffeescript-2.5.1.tgz",
"integrity": "<KEY>
"dev": true
},
"source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "<KEY>
"dev": true
},
"source-map-support": {
"version": "0.5.19",
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz",
"integrity": "<KEY>
"dev": true,
"requires": {
"buffer-from": "^1.0.0",
"source-map": "^0.6.0"
}
}
}
}
| 1,313 |
3,479 | <filename>eyes-two/src/main/jni/imageutils/similar-jni.cpp
/*
* Copyright 2011, Google 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.
*/
// Author: <NAME>
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include "types.h"
#include "time_log.h"
#include "similar.h"
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jintArray JNICALL
Java_com_googlecode_eyesfree_opticflow_ImageBlur_computeSignature(
JNIEnv* env, jclass clazz, jbyteArray input, jint width, jint height,
jintArray signatureBuffer);
JNIEXPORT jint JNICALL
Java_com_googlecode_eyesfree_opticflow_ImageBlur_diffSignature(
JNIEnv* env, jclass clazz, jintArray signature1, jintArray signature2);
#ifdef __cplusplus
}
#endif
JNIEXPORT jintArray JNICALL
Java_com_googlecode_eyesfree_opticflow_ImageBlur_computeSignature(
JNIEnv* env, jclass clazz, jbyteArray input, jint width, jint height,
jintArray signatureBuffer) {
jboolean inputCopy = JNI_FALSE;
jbyte* const i = env->GetByteArrayElements(input, &inputCopy);
int sig_len = 0;
resetTimeLog();
uint32_t* sig = ComputeSignature(reinterpret_cast<uint8*>(i),
width, height, &sig_len);
timeLog("Finished image signature computation");
printTimeLog();
env->ReleaseByteArrayElements(input, i, JNI_ABORT);
jintArray ret = signatureBuffer;
if (ret == NULL || env->GetArrayLength(ret) != sig_len) {
ret = env->NewIntArray(sig_len);
}
jint* body = env->GetIntArrayElements(ret, 0);
for (int i = 0; i < sig_len; ++i) {
body[i] = sig[i];
}
env->ReleaseIntArrayElements(ret, body, 0);
return ret;
}
JNIEXPORT jint JNICALL
Java_com_googlecode_eyesfree_opticflow_ImageBlur_diffSignature(
JNIEnv* env, jclass clazz, jintArray signature1, jintArray signature2) {
jint* sig1 = env->GetIntArrayElements(signature1, 0);
jint* sig2 = env->GetIntArrayElements(signature2, 0);
int size = env->GetArrayLength(signature1);
int diff = Diff(sig1, sig2, size);
env->ReleaseIntArrayElements(signature1, sig1, 0);
env->ReleaseIntArrayElements(signature2, sig2, 0);
return diff;
}
| 931 |
9,717 | #include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#define assert_success(e) do { if ((e) < 0) { perror(#e); abort(); } } while (0)
int main(int argc, char **argv) {
putenv("PART1=HELLO");
assert_success(setenv("PART2", "WORLD", 0));
assert_success(unsetenv("SOME_OTHER_VARIABLE"));
putenv("PART3=\"!!\n\"");
argv[0] = "/send/me/flags";
return execv("/send/me/flags", argv);
}
| 186 |
930 | <gh_stars>100-1000
# importing the libraries for loading data and visualisation
import os
import cv2
import numpy as np
from PIL import Image
# import for train-test-split
from sklearn.model_selection import train_test_split
# import for One Hot Encoding
from keras.utils import to_categorical
# importing libraries for Model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.layers import Dense, Flatten, Dropout, BatchNormalization
# loading the data of images and setting their labels
data = []
labels = []
Parasitized = os.listdir("../input/malaria/cell_images/Parasitized/")
for a in Parasitized:
try:
imageP = cv2.imread("../input/malaria/cell_images/Parasitized/" + a)
image_from_arrayP = Image.fromarray(imageP, 'RGB')
size_imageP = image_from_arrayP.resize((36, 36))
data.append(np.array(size_imageP))
labels.append(0)
except AttributeError:
print("")
Uninfected = os.listdir("../input/malaria/cell_images/Uninfected/")
for b in Uninfected:
try:
imageU = cv2.imread("../input/malaria/cell_images/Uninfected/" + b)
image_from_arrayU = Image.fromarray(imageU, 'RGB')
size_imageU = image_from_arrayU.resize((36, 36))
data.append(np.array(size_imageU))
labels.append(1)
except AttributeError:
print("")
# Creating single numpy array of all the images and labels
data1 = np.array(data)
labels1 = np.array(labels)
print('Cells : {} and labels : {}'.format(data1.shape, labels1.shape))
# lets shuffle the data and labels before splitting them into training and testing sets
n = np.arange(data1.shape[0])
np.random.shuffle(n)
data2 = data1[n]
labels2 = labels1[n]
# Splitting the dataset into the Training set and Test set
X_train, X_valid, y_train,y_valid = train_test_split(data2,
labels2, test_size=0.2, random_state=0)
X_trainF = X_train.astype('float32')
X_validF = X_valid.astype('float32')
y_trainF = to_categorical(y_train)
y_validF = to_categorical(y_valid)
classifier = Sequential()
# CNN layers
classifier.add(Conv2D(32, kernel_size=(3, 3),
input_shape=(36, 36, 3), activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(BatchNormalization(axis=-1))
classifier.add(Dropout(0.5)) # Dropout prevents overfitting
classifier.add(Conv2D(32, kernel_size=(3, 3),
input_shape=(36, 36, 3), activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(BatchNormalization(axis=-1))
classifier.add(Dropout(0.5))
classifier.add(Flatten())
classifier.add(Dense(units=128, activation='relu'))
classifier.add(BatchNormalization(axis=-1))
classifier.add(Dropout(0.5))
classifier.add(Dense(units=2, activation='softmax'))
classifier.compile(optimizer='adam',
loss='categorical_crossentropy', metrics=['accuracy'])
history = classifier.fit(X_trainF, y_trainF,
batch_size=120, epochs=15,
verbose=1, validation_data=(X_validF, y_validF))
classifier.summary()
y_pred = classifier.predict(X_validF)
y_predF = np.argmax(y_pred, axis=1)
y_valid_one = np.argmax(y_validF, axis=1)
classifier.save("./Malaria/Models/malaria.h5")
| 1,371 |
319 | <filename>web/twitter/src/main/java/org/openimaj/twitter/utils/Twitter4jUtil.java
/**
* Copyright (c) 2012, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.twitter.utils;
import org.apache.log4j.Logger;
import org.openimaj.util.api.auth.DefaultTokenFactory;
import org.openimaj.util.api.auth.common.TwitterAPIToken;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
/**
* Create a Twitter4j instance
*
* @author <NAME> (<EMAIL>)
*/
public class Twitter4jUtil {
private static Logger logger = Logger.getLogger(Twitter4jUtil.class);
/**
* @return create a {@link Twitter} instance using the tokens from
* {@link DefaultTokenFactory}
*/
public static Twitter create() {
Twitter INSTANCE = null;
if (INSTANCE == null) {
final Configuration config = makeConfiguration(DefaultTokenFactory.get(TwitterAPIToken.class));
INSTANCE = new TwitterFactory(config).getInstance();
}
return INSTANCE;
}
private static Configuration makeConfiguration(TwitterAPIToken token) {
final ConfigurationBuilder cb = new ConfigurationBuilder()
.setOAuthConsumerKey(token.consumerKey)
.setOAuthConsumerSecret(token.consumerSecret)
.setOAuthAccessToken(token.accessToken)
.setOAuthAccessTokenSecret(token.accessSecret);
cb.setJSONStoreEnabled(true);
return cb.build();
}
/**
* Handle a twitter exception, waiting the appropriate amount of time if the
* API requests this behaviour
*
* @param e
* @param errorWaitTime
* @return the errorWaitTime
*/
public static long handleTwitterException(TwitterException e, long errorWaitTime) {
if (e.exceededRateLimitation()) {
long retryAfter = e.getRetryAfter() * 1000;
logger.debug(String.format("Rate limit exceeded, waiting %dms", retryAfter));
if (retryAfter < 0) {
retryAfter = errorWaitTime * 5;
}
return retryAfter;
} else {
logger.error("Twitter Exception!", e);
logger.error("Waiting a short period of time");
return errorWaitTime;
}
}
}
| 1,126 |
1,473 | #pragma once
#include "../host_core/blockAllocator.h"
#include "../host_core/bitset.h"
namespace xenon
{
/// xenon memory allocator
class Memory
{
public:
Memory(native::IMemory& nativeMemory);
// initialize virtual memory range
const bool InitializeVirtualMemory(const uint32 prefferedBase, const uint32 totalVirtualMemoryAvaiable);
// initialize physical memory range
const bool InitializePhysicalMemory(const uint32 prefferedBase, const uint32 totalPhysicalMemoryAvaiable);
//---
// is this a valid virtual memory range ?
const bool IsVirtualMemory(void* base, const uint32 size) const;
// is this virtual memory reserved ?
const bool IsVirtualMemoryReserved(void* base, const uint32 size) const;
// get size of virtual memory allocation, zero if not allocated
const uint32 GetVirtualMemoryAllocationSize(void* base) const;
// get user flags for the memory (protection flags mostly)
const uint64 GetVirtualMemoryFlags(void* base, const uint32 size) const;
// set protection flag for range
const void SetVirtualMemoryFlags(void* base, const uint32 size, const uint64 flags);
// allocate virtual memory range
void* VirtualAlloc(void* base, const uint32 size, const uint64 allocFlags, const uint64 protectFlags);
// release virtual memory range (partial regions are supported, committed memory will be freed)
const bool VirtualFree(void* base, const uint32 size, const uint64 allocFlags, uint32& outFreedSize);
//--
// allocate physical memory range
void* PhysicalAlloc(const uint32 size, const uint32 alignment, const uint32 protectFlags);
// free physical memory range
void PhysicalFree(void* base, const uint32 size);
// translate local physical memory address to absolute address
const uint32 TranslatePhysicalAddress(const uint32 localAddress) const;
//--
// allocate small memory block that will be accessible by the simulated Xenon platform
void* AllocateSmallBlock(const uint32 size);
// free small memory block
void FreeSmallBlock(void* memory);
private:
static const uint32 PAGE_SIZE = 4096;
static const uint32 MAX_MEMORY_SIZE = 0x40000000;
static const uint32 MAX_PAGES = MAX_MEMORY_SIZE / PAGE_SIZE;
// native memory system
native::IMemory& m_nativeMemory;
struct MemoryClass
{
std::mutex m_lock;
void* m_base; // allocated base of the memory range
uint32 m_totalSize; // size of the allocated memory range
uint32 m_totalPages; // total number of memory pages
uint32 m_allocatedPages; // allocated number of memory pages
utils::BlockAllocator m_allocator; // page allocator
// get memory page from memory address
inline const uint32 PageFromAddress(const void* base) const
{
return (uint32)(((uint8*)base - (uint8*)m_base) / PAGE_SIZE);
}
// get base address for memory page
inline void* AddressFromPage(const uint32 page) const
{
return (uint8*)m_base + (page * PAGE_SIZE);
}
// get number of required pages for given size
inline const uint32 PagesFromSize(const uint32 size) const
{
return (size + (PAGE_SIZE - 1)) / PAGE_SIZE;
}
// check if the pointer is contained in this memory class range
inline const bool Contains(void* base, const uint32 size) const
{
if (((uint8*)base < (uint8*)m_base) || (((uint8*)base + size) > ((uint8*)m_base + m_totalSize)))
return false;
return true;
}
// initialize the memory range
const bool Initialize(native::IMemory& memory, const uint32 prefferedBase, const uint32 totalVirtualMemoryAvaiable);
// allocate memory
void* Allocate(const uint32 size, const bool top, const uint32 flags);
// free memory
void Free(void* memory, uint32& outNumPages);
};
MemoryClass m_virtual;
MemoryClass m_physical;
};
} // xenon | 1,220 |
325 | <filename>webapp/src/main/java/com/box/l10n/mojito/service/thirdparty/smartling/SmartlingResultProcessor.java
package com.box.l10n.mojito.service.thirdparty.smartling;
import com.amazonaws.SdkClientException;
import com.box.l10n.mojito.service.blobstorage.Retention;
import com.box.l10n.mojito.service.blobstorage.s3.S3BlobStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@ConditionalOnProperty(value = "l10n.ThirdPartyTMS.impl", havingValue = "ThirdPartyTMSSmartling")
@Component
public class SmartlingResultProcessor {
static Logger logger = LoggerFactory.getLogger(SmartlingResultProcessor.class);
private static final String NAME_FORMAT = "%s_%s_%s.zip";
@Autowired(required=false)
S3BlobStorage s3BlobStorage;
public String processPush(List<SmartlingFile> files,
SmartlingOptions options) {
return processAction(files, options, "push");
}
public String processPushTranslations(List<SmartlingFile> files,
SmartlingOptions options){
return processAction(files, options, "push_translations");
}
private String processAction(List<SmartlingFile> files,
SmartlingOptions options,
String action) {
String result = null;
if (!files.isEmpty() && options.isDryRun() && s3BlobStorage != null){
try {
result = uploadFiles(files, options.getRequestId(), action);
logger.info("{} result for request id {} uploaded to: {}", action, options.getRequestId(), result);
} catch (IOException | SdkClientException e) {
String errorMessage = String.format("An error ocurred when uploading a %s result zip file", action);
logger.error(errorMessage, e);
throw new RuntimeException(errorMessage, e);
}
}
return result;
}
String uploadFiles(List<SmartlingFile> files, String requestId, String type) throws IOException {
String name = String.format(NAME_FORMAT, requestId, type, ZonedDateTime.now().toEpochSecond());
Path zipFile = zipFiles(files, name);
byte[] content = Files.readAllBytes(zipFile);
s3BlobStorage.put(name, content, Retention.MIN_1_DAY);
return s3BlobStorage.getS3Url(name);
}
Path zipFiles(List<SmartlingFile> files, String name) throws IOException {
Path tmpDir = Files.createTempDirectory(name);
for (SmartlingFile file : files) {
Path filePath = Paths.get(tmpDir.toString(), file.getFileName());
Files.createDirectories(filePath.getParent());
Files.write(filePath, file.getFileContent().getBytes(StandardCharsets.UTF_8));
}
return zipDirectory(tmpDir);
}
private Path zipDirectory(Path sourceDirPath) throws IOException {
Path zipPath = Files.createFile(Paths.get(sourceDirPath + ".zip"));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(zipPath))) {
zs.setLevel(ZipOutputStream.STORED);
Files.walk(sourceDirPath)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(path).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(path, zs);
zs.closeEntry();
} catch (IOException e) {
System.err.println(e);
}
});
}
return zipPath;
}
}
| 1,828 |
875 | <gh_stars>100-1000
#ifdef HAS_QT
#include "FrameVisualizer.h"
#include <GSLAM/core/Timer.h>
#include <QPainter>
#include <QWheelEvent>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QDateTime>
using namespace std;
namespace GSLAM
{
InfomationViewer::InfomationViewer(QWidget* parent)
:QTableWidget(parent),lastUpdateTime(0){
setColumnCount(2);
setHorizontalHeaderLabels({"name","value"});
QHeaderView *HorzHdr = horizontalHeader();
#if QT_VERSION>=0x050000
HorzHdr->setSectionResizeMode(QHeaderView::Stretch);
#else
HorzHdr->setResizeMode(QHeaderView::Stretch);
#endif
}
QTableWidgetItem* InfomationViewer::setValue(int row,int col,QString val)
{
if(item(row,col)!=NULL)
{
item(row,col)->setText(val);
return item(row,col);
}
else
{
QTableWidgetItem* item=new QTableWidgetItem();
item->setText(val);
setItem(row,col,item);
return item;
}
}
QTableWidgetItem* InfomationViewer::setValue(int row,int col,double val)
{
if(item(row,col)!=NULL)
{
item(row,col)->setText(QString("%1").arg(val,0,'g',13));
return item(row,col);
}
else
{
QTableWidgetItem* item=new QTableWidgetItem();
item->setText(QString("%1").arg(val,0,'g',13));
setItem(row,col,item);
return item;
}
}
void InfomationViewer::update(const FramePtr& frame,bool flush)
{
double curTime=GSLAM::TicToc::timestamp();
if(!flush&&curTime-lastUpdateTime<0.033) return;
lastUpdateTime=curTime;
vars["id"]=QString("%1").arg(frame->id());
vars["type"]=frame->type().c_str();
QDateTime tm=QDateTime::fromMSecsSinceEpoch(frame->timestamp()*1e3);
vars["time"]=tm.toString("yyyy.MM.dd-hh:mm:ss.zzz");
if(frame->cameraNum())
{
vars["cameraNum"]=QString("%1").arg(frame->cameraNum());
for(int i=0;i<frame->cameraNum();i++)
{
vars[QString("Camera%1.Channels").arg(i)]=QString("%1").arg(frame->channelString(i).c_str());
vars[QString("Camera%1.Info").arg(i)]=frame->getCamera(i).info().c_str();
}
}
if(frame->getIMUNum())
{
vars["IMUNum"]=QString("%1").arg(frame->getIMUNum());
Point3d pt;
for(int i=0;i<frame->getIMUNum();i++)
{
if(frame->getPitchYawRoll(pt,i))
{
vars[QString("IMU%1.PitchYawRoll").arg(i)]=QString("%1,%2,%3")
.arg(pt.x,0,'g',13).arg(pt.y,0,'g',13).arg(pt.z,0,'g',13);
}
if(frame->getPYRSigma(pt,i))
{
vars[QString("IMU%1.PYRSigma").arg(i)]=QString("%1,%2,%3")
.arg(pt.x,0,'g',13).arg(pt.y,0,'g',13).arg(pt.z,0,'g',13);
}
}
}
if(frame->getGPSNum())
{
vars["GPSNum"]=QString("%1").arg(frame->getGPSNum());
for(int i=0;i<frame->getGPSNum();i++)
{
Point3d pt;
if(frame->getGPSLLA(pt,i))
{
vars[QString("GPS%1.LonLatAlt").arg(i)]=QString("%1,%2,%3")
.arg(pt.x,0,'g',13).arg(pt.y,0,'g',13).arg(pt.z,0,'g',13);
}
if(frame->getGPSLLASigma(pt,i))
{
vars[QString("GPS%1.LonLatAltSigma").arg(i)]=QString("%1,%2,%3")
.arg(pt.x,0,'g',13).arg(pt.y,0,'g',13).arg(pt.z,0,'g',13);
}
}
}
setRowCount(vars.size());
int i=0;
for(auto it:vars)
{
setValue(i,0,it.first)->setFlags(Qt::ItemIsEditable);
setValue(i,1,it.second)->setFlags(Qt::ItemIsEditable);
i++;
}
}
void FrameVisualizer::slotFrameUpdated()
{
GSLAM::ReadMutex lock(_mutex);
if(!_curFrame) return;
_infos->update(_curFrame);
if(!_lastImageFrame) return;
// GSLAM::ScopedTimer tm("FrameVisualizer::slotFrameUpdated");
for(int camIdx=0;camIdx<_lastImageFrame->cameraNum();camIdx++)
{
GSLAM::FramePtr _curFrame=_lastImageFrame;
if(_images.size()==camIdx)
{
_images.push_back(new GImageWidget(_splitter));
_splitter->addWidget(_images[camIdx]);
}
GImageWidget* gimageW=_images[camIdx];
int channelFlags=_curFrame->imageChannels();
GImage img=_curFrame->getImage(camIdx);
if(img.empty()) continue;
if(img.cols%4!=0)
{
#if defined(HAS_OPENCV)&&0
cv::Mat src=img,dst(src.rows,src.cols-(img.cols%4),src.type());
src(cv::Rect(0,0,dst.cols,dst.rows)).copyTo(dst);
img=dst;
#else
GImage dst(img.rows,img.cols-(img.cols%4),img.type());
int srcLineStep=img.elemSize()*img.cols;
int dstLineStep=dst.elemSize()*dst.cols;
for(int i=0;i<img.rows;i++)
memcpy(dst.data+dstLineStep*i,img.data+srcLineStep*i,dstLineStep);
img=dst;
#endif
}
if((channelFlags&IMAGE_BGRA)&&img.channels()==3)
{
gimageW->setQImage(QImage(img.data,img.cols,img.rows,QImage::Format_RGB888).rgbSwapped(),true);
}
else if((channelFlags&IMAGE_RGBA)&&img.channels()==4)
{
gimageW->setQImage(QImage(img.data,img.cols,img.rows,QImage::Format_RGB32).rgbSwapped(),true);
}
else
{
gimageW->setImage(img,true);
}
}
_lastImageFrame=FramePtr();
}
}
#endif
| 2,891 |
14,668 | <filename>rlz/lib/supplementary_branding.h
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef RLZ_LIB_SUPPLEMENTARY_BRANDING_H_
#define RLZ_LIB_SUPPLEMENTARY_BRANDING_H_
#include <string>
#include "base/memory/raw_ptr.h"
namespace rlz_lib {
class ScopedRlzValueStoreLock;
// Segment RLZ persistence based on branding information.
// All information for a given product is persisted under keys with the either
// product's name or its access point's name. This assumes that only
// one instance of the product is installed on the machine, and that only one
// product brand is associated with it.
//
// In some cases, a given product may be using supplementary brands. The RLZ
// information must be kept separately for each of these brands. To achieve
// this segmentation, scope all RLZ library calls that deal with supplementary
// brands within the lifetime of an rlz_lib::ProductBranding instance.
//
// For example, to record events for a supplementary brand, do the following:
//
// {
// rlz_lib::SupplementaryBranding branding("AAAA");
// // This call to RecordProductEvent is scoped to the AAAA brand.
// rlz_lib::RecordProductEvent(rlz_lib::DESKTOP, rlz_lib::GD_DESKBAND,
// rlz_lib::INSTALL);
// }
//
// // This call to RecordProductEvent is not scoped to any supplementary brand.
// rlz_lib::RecordProductEvent(rlz_lib::DESKTOP, rlz_lib::GD_DESKBAND,
// rlz_lib::INSTALL);
//
// In particular, this affects the recording of stateful events and the sending
// of financial pings. In the former case, a stateful event recorded while
// scoped to a supplementary brand will be recorded again when scoped to a
// different supplementary brand (or not scoped at all). In the latter case,
// the time skip check is specific to each supplementary brand.
class SupplementaryBranding {
public:
explicit SupplementaryBranding(const char* brand);
~SupplementaryBranding();
static const std::string& GetBrand();
private:
raw_ptr<ScopedRlzValueStoreLock> lock_;
};
} // namespace rlz_lib
#endif // RLZ_LIB_SUPPLEMENTARY_BRANDING_H_
| 710 |
5,813 | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.storage.azure.blob;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.CloudBlob;
import com.microsoft.azure.storage.blob.ListBlobItem;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Wrapper class for {@link ListBlobItem} interface, which was missing some useful
* functionality for telling whether the blob was a cloudBlob or not. This class was
* added mainly to make testing easier.
*/
public class ListBlobItemHolder
{
private final ListBlobItem delegate;
@AssistedInject
public ListBlobItemHolder(@Assisted ListBlobItem delegate)
{
this.delegate = delegate;
}
public String getContainerName() throws URISyntaxException, StorageException
{
return delegate.getContainer().getName();
}
public URI getUri()
{
return delegate.getUri();
}
public CloudBlobHolder getCloudBlob()
{
return new CloudBlobHolder((CloudBlob) delegate);
}
public boolean isCloudBlob()
{
return delegate instanceof CloudBlob;
}
@Override
public String toString()
{
return delegate.toString();
}
}
| 602 |
335 | {
"word": "Beginning",
"definitions": [
"The point in time or space at which something begins.",
"The first part or earliest stage of something.",
"The background or origins of a person or organization."
],
"parts-of-speech": "Noun"
} | 99 |
2,151 | // 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 COMPONENTS_VIZ_SERVICE_GL_GPU_SERVICE_IMPL_H_
#define COMPONENTS_VIZ_SERVICE_GL_GPU_SERVICE_IMPL_H_
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_refptr.h"
#include "base/single_thread_task_runner.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/threading/thread.h"
#include "build/build_config.h"
#include "components/viz/service/viz_service_export.h"
#include "gpu/command_buffer/client/gpu_memory_buffer_manager.h"
#include "gpu/command_buffer/common/activity_flags.h"
#include "gpu/command_buffer/service/sequence_id.h"
#include "gpu/config/gpu_info.h"
#include "gpu/config/gpu_preferences.h"
#include "gpu/ipc/common/surface_handle.h"
#include "gpu/ipc/service/gpu_channel.h"
#include "gpu/ipc/service/gpu_channel_manager.h"
#include "gpu/ipc/service/gpu_channel_manager_delegate.h"
#include "gpu/ipc/service/gpu_config.h"
#include "gpu/ipc/service/x_util.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "services/viz/privileged/interfaces/gl/gpu_host.mojom.h"
#include "services/viz/privileged/interfaces/gl/gpu_service.mojom.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "ui/gfx/native_widget_types.h"
class GrContext;
#if defined(OS_CHROMEOS)
namespace arc {
class ProtectedBufferManager;
}
#endif // OS_CHROMEOS
namespace gpu {
class GpuMemoryBufferFactory;
class GpuWatchdogThread;
class Scheduler;
class SyncPointManager;
} // namespace gpu
namespace media {
class MediaGpuChannelManager;
}
namespace viz {
// This runs in the GPU process, and communicates with the gpu host (which is
// the window server) over the mojom APIs. This is responsible for setting up
// the connection to clients, allocating/free'ing gpu memory etc.
class VIZ_SERVICE_EXPORT GpuServiceImpl : public gpu::GpuChannelManagerDelegate,
public mojom::GpuService {
public:
GpuServiceImpl(const gpu::GPUInfo& gpu_info,
std::unique_ptr<gpu::GpuWatchdogThread> watchdog,
scoped_refptr<base::SingleThreadTaskRunner> io_runner,
const gpu::GpuFeatureInfo& gpu_feature_info,
const gpu::GpuPreferences& gpu_preferences,
const base::Optional<gpu::GPUInfo>& gpu_info_for_hardware_gpu,
const base::Optional<gpu::GpuFeatureInfo>&
gpu_feature_info_for_hardware_gpu);
~GpuServiceImpl() override;
void UpdateGPUInfo();
void InitializeWithHost(mojom::GpuHostPtr gpu_host,
gpu::GpuProcessActivityFlags activity_flags,
gpu::SyncPointManager* sync_point_manager = nullptr,
base::WaitableEvent* shutdown_event = nullptr);
void Bind(mojom::GpuServiceRequest request);
bool CreateGrContextIfNecessary(gl::GLSurface* surface);
// Notifies the GpuHost to stop using GPU compositing. This should be called
// in response to an error in the GPU process that occurred after
// InitializeWithHost() was called, otherwise GpuFeatureInfo should be set
// accordingly. This can safely be called from any thread.
void DisableGpuCompositing();
bool is_initialized() const { return !!gpu_host_; }
media::MediaGpuChannelManager* media_gpu_channel_manager() {
return media_gpu_channel_manager_.get();
}
gpu::GpuChannelManager* gpu_channel_manager() {
return gpu_channel_manager_.get();
}
gpu::ImageFactory* gpu_image_factory();
gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory() {
return gpu_memory_buffer_factory_.get();
}
gpu::MailboxManager* mailbox_manager() {
return gpu_channel_manager_->mailbox_manager();
}
gl::GLShareGroup* share_group() {
return gpu_channel_manager_->share_group();
}
gpu::SyncPointManager* sync_point_manager() { return sync_point_manager_; }
gpu::Scheduler* scheduler() { return scheduler_.get(); }
gpu::GpuWatchdogThread* watchdog_thread() { return watchdog_thread_.get(); }
const gpu::GpuFeatureInfo& gpu_feature_info() const {
return gpu_feature_info_;
}
bool in_host_process() const { return gpu_info_.in_process_gpu; }
void set_start_time(base::Time start_time) { start_time_ = start_time; }
const gpu::GPUInfo& gpu_info() const { return gpu_info_; }
const gpu::GpuPreferences& gpu_preferences() const {
return gpu_preferences_;
}
gpu::SequenceId skia_output_surface_sequence_id() const {
return skia_output_surface_sequence_id_;
}
gl::GLContext* context_for_skia() { return context_for_skia_.get(); }
GrContext* gr_context() { return gr_context_.get(); }
private:
void RecordLogMessage(int severity,
size_t message_start,
const std::string& message);
void UpdateGpuInfoPlatform(base::OnceClosure on_gpu_info_updated);
// gpu::GpuChannelManagerDelegate:
void DidCreateContextSuccessfully() override;
void DidCreateOffscreenContext(const GURL& active_url) override;
void DidDestroyChannel(int client_id) override;
void DidDestroyOffscreenContext(const GURL& active_url) override;
void DidLoseContext(bool offscreen,
gpu::error::ContextLostReason reason,
const GURL& active_url) override;
void StoreShaderToDisk(int client_id,
const std::string& key,
const std::string& shader) override;
#if defined(OS_WIN)
void SendAcceleratedSurfaceCreatedChildWindow(
gpu::SurfaceHandle parent_window,
gpu::SurfaceHandle child_window) override;
#endif
void SetActiveURL(const GURL& url) override;
// mojom::GpuService:
void EstablishGpuChannel(int32_t client_id,
uint64_t client_tracing_id,
bool is_gpu_host,
EstablishGpuChannelCallback callback) override;
void CloseChannel(int32_t client_id) override;
#if defined(OS_CHROMEOS)
void CreateArcVideoDecodeAccelerator(
arc::mojom::VideoDecodeAcceleratorRequest vda_request) override;
void CreateArcVideoEncodeAccelerator(
arc::mojom::VideoEncodeAcceleratorRequest vea_request) override;
void CreateArcVideoProtectedBufferAllocator(
arc::mojom::VideoProtectedBufferAllocatorRequest pba_request) override;
void CreateArcProtectedBufferManager(
arc::mojom::ProtectedBufferManagerRequest pbm_request) override;
#endif // defined(OS_CHROMEOS)
void CreateJpegDecodeAccelerator(
media::mojom::JpegDecodeAcceleratorRequest jda_request) override;
void CreateJpegEncodeAccelerator(
media::mojom::JpegEncodeAcceleratorRequest jea_request) override;
void CreateVideoEncodeAcceleratorProvider(
media::mojom::VideoEncodeAcceleratorProviderRequest vea_provider_request)
override;
void CreateGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
const gfx::Size& size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
int client_id,
gpu::SurfaceHandle surface_handle,
CreateGpuMemoryBufferCallback callback) override;
void DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
int client_id,
const gpu::SyncToken& sync_token) override;
void GetVideoMemoryUsageStats(
GetVideoMemoryUsageStatsCallback callback) override;
void RequestCompleteGpuInfo(RequestCompleteGpuInfoCallback callback) override;
void GetGpuSupportedRuntimeVersion(
GetGpuSupportedRuntimeVersionCallback callback) override;
void RequestHDRStatus(RequestHDRStatusCallback callback) override;
void LoadedShader(const std::string& key, const std::string& data) override;
void DestroyingVideoSurface(int32_t surface_id,
DestroyingVideoSurfaceCallback callback) override;
void WakeUpGpu() override;
void GpuSwitched() override;
void DestroyAllChannels() override;
void OnBackgroundCleanup() override;
void OnBackgrounded() override;
void OnForegrounded() override;
void Crash() override;
void Hang() override;
void ThrowJavaException() override;
void Stop(StopCallback callback) override;
#if defined(OS_CHROMEOS)
void CreateArcVideoDecodeAcceleratorOnMainThread(
arc::mojom::VideoDecodeAcceleratorRequest vda_request);
void CreateArcVideoEncodeAcceleratorOnMainThread(
arc::mojom::VideoEncodeAcceleratorRequest vea_request);
void CreateArcVideoProtectedBufferAllocatorOnMainThread(
arc::mojom::VideoProtectedBufferAllocatorRequest pba_request);
void CreateArcProtectedBufferManagerOnMainThread(
arc::mojom::ProtectedBufferManagerRequest pbm_request);
#endif // defined(OS_CHROMEOS)
void RequestHDRStatusOnMainThread(RequestHDRStatusCallback callback);
scoped_refptr<base::SingleThreadTaskRunner> main_runner_;
scoped_refptr<base::SingleThreadTaskRunner> io_runner_;
std::unique_ptr<gpu::GpuWatchdogThread> watchdog_thread_;
std::unique_ptr<gpu::GpuMemoryBufferFactory> gpu_memory_buffer_factory_;
const gpu::GpuPreferences gpu_preferences_;
// Information about the GPU, such as device and vendor ID.
gpu::GPUInfo gpu_info_;
// Information about general chrome feature support for the GPU.
gpu::GpuFeatureInfo gpu_feature_info_;
// What we would have gotten if we haven't fallen back to SwiftShader or
// pure software (in the viz case).
base::Optional<gpu::GPUInfo> gpu_info_for_hardware_gpu_;
base::Optional<gpu::GpuFeatureInfo> gpu_feature_info_for_hardware_gpu_;
scoped_refptr<mojom::ThreadSafeGpuHostPtr> gpu_host_;
std::unique_ptr<gpu::GpuChannelManager> gpu_channel_manager_;
std::unique_ptr<media::MediaGpuChannelManager> media_gpu_channel_manager_;
// On some platforms (e.g. android webview), the SyncPointManager comes from
// external sources.
std::unique_ptr<gpu::SyncPointManager> owned_sync_point_manager_;
gpu::SyncPointManager* sync_point_manager_ = nullptr;
std::unique_ptr<gpu::Scheduler> scheduler_;
// sequence id for running tasks from SkiaOutputSurface;
gpu::SequenceId skia_output_surface_sequence_id_;
// A GLContext for |gr_context_|. It can only be accessed by Skia.
scoped_refptr<gl::GLContext> context_for_skia_;
// A GrContext for SkiaOutputSurface (maybe raster as well).
sk_sp<GrContext> gr_context_;
// An event that will be signalled when we shutdown. On some platforms it
// comes from external sources.
std::unique_ptr<base::WaitableEvent> owned_shutdown_event_;
base::WaitableEvent* shutdown_event_ = nullptr;
base::Time start_time_;
// Used to track the task to bind a GpuServiceRequest on the io thread.
base::CancelableTaskTracker bind_task_tracker_;
std::unique_ptr<mojo::BindingSet<mojom::GpuService>> bindings_;
#if defined(OS_CHROMEOS)
scoped_refptr<arc::ProtectedBufferManager> protected_buffer_manager_;
#endif // defined(OS_CHROMEOS)
base::WeakPtr<GpuServiceImpl> weak_ptr_;
base::WeakPtrFactory<GpuServiceImpl> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(GpuServiceImpl);
};
} // namespace viz
#endif // COMPONENTS_VIZ_SERVICE_GL_GPU_SERVICE_IMPL_H_
| 4,275 |
679 | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_PROPERTYHANDLER_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_PROPERTYHANDLER_HXX
#include "pcrcomponentcontext.hxx"
#include "pcrcommon.hxx"
#ifndef _EXTENSIONS_PROPCTRLR_MODULEPCR_HXX_
#include "modulepcr.hxx"
#endif
/** === begin UNO includes === **/
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/beans/PropertyState.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/Property.hpp>
#include <com/sun/star/script/XTypeConverter.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/util/Date.hpp>
#include <com/sun/star/util/Time.hpp>
#include <com/sun/star/util/DateTime.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/inspection/XPropertyHandler.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
/** === end UNO includes === **/
#include <osl/interlck.h>
#include <cppuhelper/compbase1.hxx>
#include <cppuhelper/implbase1.hxx>
#include <comphelper/uno3.hxx>
#include <memory>
#include <vector>
namespace com { namespace sun { namespace star {
namespace inspection {
struct LineDescriptor;
class XPropertyControlFactory;
}
} } }
class Window;
//........................................................................
namespace pcr
{
//........................................................................
typedef sal_Int32 PropertyId;
//====================================================================
//= PropertyHandler
//====================================================================
class OPropertyInfoService;
typedef ::cppu::WeakComponentImplHelper1 < ::com::sun::star::inspection::XPropertyHandler
> PropertyHandler_Base;
/** the base class for property handlers
*/
class PropertyHandler : public PropertyHandler_Base
{
private:
/// cache for getSupportedProperties
mutable StlSyntaxSequence< ::com::sun::star::beans::Property >
m_aSupportedProperties;
mutable bool m_bSupportedPropertiesAreKnown;
/// helper which ensures that we can access resources as long as the instance lives
PcrClient m_aEnsureResAccess;
private:
/// the property listener which has been registered
PropertyChangeListeners m_aPropertyListeners;
protected:
mutable ::osl::Mutex m_aMutex;
/// the context in which the instance was created
ComponentContext m_aContext;
/// the component we're inspecting
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xComponent;
/// info about our component's properties
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > m_xComponentPropertyInfo;
/// type converter, needed on various occasions
::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter > m_xTypeConverter;
/// access to property meta data
::std::auto_ptr< OPropertyInfoService > m_pInfoService;
protected:
PropertyHandler(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext
);
~PropertyHandler();
// default implementations for XPropertyHandler
virtual void SAL_CALL inspect( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxIntrospectee ) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::NullPointerException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL getSupportedProperties() throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupersededProperties( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getActuatingProperties( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL convertToPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rControlValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL convertToControlValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rPropertyValue, const ::com::sun::star::uno::Type& _rControlValueType ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::inspection::LineDescriptor SAL_CALL describePropertyLine( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL isComposable( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::inspection::InteractiveSelectionResult SAL_CALL onInteractivePropertySelection( const ::rtl::OUString& _rPropertyName, sal_Bool _bPrimary, ::com::sun::star::uno::Any& _rData, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL actuatingPropertyChanged( const ::rtl::OUString& _rActuatingPropertyName, const ::com::sun::star::uno::Any& _rNewValue, const ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI, sal_Bool _bFirstTimeInit ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addPropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL suspend( sal_Bool _bSuspend ) throw (::com::sun::star::uno::RuntimeException);
// XComponent
DECLARE_XCOMPONENT()
virtual void SAL_CALL disposing();
// own overridables
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >
SAL_CALL doDescribeSupportedProperties() const = 0;
/// called when XPropertyHandler::inspect has been called, and we thus have a new component to inspect
virtual void onNewComponent();
protected:
/** fires the change in a property value to our listener (if any)
@see addPropertyChangeListener
*/
void firePropertyChange( const ::rtl::OUString& _rPropName, PropertyId _nPropId,
const ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Any& _rNewValue ) SAL_THROW(());
/** retrieves a window which can be used as parent for dialogs
*/
Window* impl_getDefaultDialogParent_nothrow() const;
/** retrieves the property id for a given property name
@throw com::sun::star::beans::UnknownPropertyException
if the property name is not known to our ->m_pInfoService
*/
PropertyId impl_getPropertyId_throw( const ::rtl::OUString& _rPropertyName ) const;
//-------------------------------------------------------------------------------
// helper for implementing doDescribeSupportedProperties
/** adds a description for the given string property to the given property vector
Most probably to be called from within getSupportedProperties
*/
inline void addStringPropertyDescription(
::std::vector< ::com::sun::star::beans::Property >& _rProperties,
const ::rtl::OUString& _rPropertyName,
sal_Int16 _nAttribs = 0
) const;
/** adds a description for the given int32 property to the given property vector
*/
inline void addInt32PropertyDescription(
::std::vector< ::com::sun::star::beans::Property >& _rProperties,
const ::rtl::OUString& _rPropertyName,
sal_Int16 _nAttribs = 0
) const;
/** adds a description for the given int16 property to the given property vector
*/
inline void addInt16PropertyDescription(
::std::vector< ::com::sun::star::beans::Property >& _rProperties,
const ::rtl::OUString& _rPropertyName,
sal_Int16 _nAttribs = 0
) const;
/** adds a description for the given double property to the given property vector
*/
inline void addDoublePropertyDescription(
::std::vector< ::com::sun::star::beans::Property >& _rProperties,
const ::rtl::OUString& _rPropertyName,
sal_Int16 _nAttribs = 0
) const;
/** adds a description for the given date property to the given property vector
*/
inline void addDatePropertyDescription(
::std::vector< ::com::sun::star::beans::Property >& _rProperties,
const ::rtl::OUString& _rPropertyName,
sal_Int16 _nAttribs = 0
) const;
/** adds a description for the given time property to the given property vector
*/
inline void addTimePropertyDescription(
::std::vector< ::com::sun::star::beans::Property >& _rProperties,
const ::rtl::OUString& _rPropertyName,
sal_Int16 _nAttribs = 0
) const;
/** adds a description for the given DateTime property to the given property vector
*/
inline void addDateTimePropertyDescription(
::std::vector< ::com::sun::star::beans::Property >& _rProperties,
const ::rtl::OUString& _rPropertyName,
sal_Int16 _nAttribs = 0
) const;
/// adds a Property, given by name only, to a given vector of Properties
void implAddPropertyDescription(
::std::vector< ::com::sun::star::beans::Property >& _rProperties,
const ::rtl::OUString& _rPropertyName,
const ::com::sun::star::uno::Type& _rType,
sal_Int16 _nAttribs = 0
) const;
//-------------------------------------------------------------------------------
// helper for accessing and maintaining meta data about our supported properties
/** retrieves a property given by handle
@return
a pointer to the descriptor for the given properties, if it is one of our
supported properties, <NULL/> else.
@see doDescribeSupportedProperties
@see impl_getPropertyFromId_throw
*/
const ::com::sun::star::beans::Property*
impl_getPropertyFromId_nothrow( PropertyId _nPropId ) const;
/** retrieves a property given by handle
@throws UnknownPropertyException
if the handler does not support a property with the given handle
@seealso doDescribeSupportedProperties
@see impl_getPropertyFromId_nothrow
*/
const ::com::sun::star::beans::Property&
impl_getPropertyFromId_throw( PropertyId _nPropId ) const;
/** determines whether a given property id is part of our supported properties
@see getSupportedProperties
@see doDescribeSupportedProperties
*/
inline bool impl_isSupportedProperty_nothrow( PropertyId _nPropId ) const
{
return impl_getPropertyFromId_nothrow( _nPropId ) != NULL;
}
/** retrieves a property given by name
@throws UnknownPropertyException
if the handler does not support a property with the given name
@seealso doDescribeSupportedProperties
*/
const ::com::sun::star::beans::Property&
impl_getPropertyFromName_throw( const ::rtl::OUString& _rPropertyName ) const;
/** get the name of a property given by handle
*/
inline ::rtl::OUString
impl_getPropertyNameFromId_nothrow( PropertyId _nPropId ) const;
/** returns the value of the ContextDocument property in the ComponentContext which was used to create
this handler.
*/
inline ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >
impl_getContextDocument_nothrow() const
{
return ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >(
m_aContext.getContextValueByAsciiName( "ContextDocument" ), ::com::sun::star::uno::UNO_QUERY );
}
/** marks the context document as modified
@see impl_getContextDocument_nothrow
*/
void impl_setContextDocumentModified_nothrow() const;
/// determines whether our component has a given property
bool impl_componentHasProperty_throw( const ::rtl::OUString& _rPropName ) const;
/** determines the default measure unit for the document in which our component lives
*/
sal_Int16 impl_getDocumentMeasurementUnit_throw() const;
private:
PropertyHandler(); // never implemented
PropertyHandler( const PropertyHandler& ); // never implemented
PropertyHandler& operator=( const PropertyHandler& ); // never implemented
};
//--------------------------------------------------------------------
inline void PropertyHandler::addStringPropertyDescription( ::std::vector< ::com::sun::star::beans::Property >& _rProperties, const ::rtl::OUString& _rPropertyName, sal_Int16 _nAttribs ) const
{
implAddPropertyDescription( _rProperties, _rPropertyName, ::getCppuType( static_cast< ::rtl::OUString* >( NULL ) ), _nAttribs );
}
inline void PropertyHandler::addInt32PropertyDescription( ::std::vector< ::com::sun::star::beans::Property >& _rProperties, const ::rtl::OUString& _rPropertyName, sal_Int16 _nAttribs ) const
{
implAddPropertyDescription( _rProperties, _rPropertyName, ::getCppuType( static_cast< sal_Int32* >( NULL ) ), _nAttribs );
}
inline void PropertyHandler::addInt16PropertyDescription( ::std::vector< ::com::sun::star::beans::Property >& _rProperties, const ::rtl::OUString& _rPropertyName, sal_Int16 _nAttribs ) const
{
implAddPropertyDescription( _rProperties, _rPropertyName, ::getCppuType( static_cast< sal_Int16* >( NULL ) ), _nAttribs );
}
inline void PropertyHandler::addDoublePropertyDescription( ::std::vector< ::com::sun::star::beans::Property >& _rProperties, const ::rtl::OUString& _rPropertyName, sal_Int16 _nAttribs ) const
{
implAddPropertyDescription( _rProperties, _rPropertyName, ::getCppuType( static_cast< double* >( NULL ) ), _nAttribs );
}
inline void PropertyHandler::addDatePropertyDescription( ::std::vector< ::com::sun::star::beans::Property >& _rProperties, const ::rtl::OUString& _rPropertyName, sal_Int16 _nAttribs ) const
{
implAddPropertyDescription( _rProperties, _rPropertyName, ::getCppuType( static_cast< com::sun::star::util::Date* >( NULL ) ), _nAttribs );
}
inline void PropertyHandler::addTimePropertyDescription( ::std::vector< ::com::sun::star::beans::Property >& _rProperties, const ::rtl::OUString& _rPropertyName, sal_Int16 _nAttribs ) const
{
implAddPropertyDescription( _rProperties, _rPropertyName, ::getCppuType( static_cast< com::sun::star::util::Time* >( NULL ) ), _nAttribs );
}
inline void PropertyHandler::addDateTimePropertyDescription( ::std::vector< ::com::sun::star::beans::Property >& _rProperties, const ::rtl::OUString& _rPropertyName, sal_Int16 _nAttribs ) const
{
implAddPropertyDescription( _rProperties, _rPropertyName, ::getCppuType( static_cast< com::sun::star::util::DateTime* >( NULL ) ), _nAttribs );
}
inline ::rtl::OUString PropertyHandler::impl_getPropertyNameFromId_nothrow( PropertyId _nPropId ) const
{
const ::com::sun::star::beans::Property* pProp = impl_getPropertyFromId_nothrow( _nPropId );
return pProp ? pProp->Name : ::rtl::OUString();
}
//====================================================================
//= PropertyHandlerComponent
//====================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::lang::XServiceInfo
> PropertyHandlerComponent_Base;
/** PropertyHandler implementation which additionally supports XServiceInfo
*/
class PropertyHandlerComponent :public PropertyHandler
,public PropertyHandlerComponent_Base
{
protected:
PropertyHandlerComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext
);
DECLARE_XINTERFACE()
DECLARE_XTYPEPROVIDER()
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException) = 0;
virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException) = 0;
};
//====================================================================
//= HandlerComponentBase
//====================================================================
/** a PropertyHandlerComponent implementation which routes XServiceInfo::getImplementationName and
XServiceInfo::getSupportedServiceNames to static versions of those methods, which are part of
the derived class.
Additionally, a method <member>Create</member> is provided which takes a component context, and returns a new
instance of the derived class. This <member>Create</member> is used to register the implementation
of the derived class at the <type>PcrModule</type>.
Well, every time we're talking about derived class, we in fact mean the template argument of
<type>HandlerComponentBase</type>. But usually this equals your derived class:
<pre>
class MyHandler;
typedef HandlerComponentBase< MyHandler > MyHandler_Base;
class MyHandler : MyHandler_Base
{
...
public:
static ::rtl::OUString SAL_CALL getImplementationName_static( ) throw (::com::sun::star::uno::RuntimeException);
static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_static( ) throw (::com::sun::star::uno::RuntimeException);
};
</pre>
*/
template < class HANDLER >
class HandlerComponentBase : public PropertyHandlerComponent
{
protected:
HandlerComponentBase( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext )
:PropertyHandlerComponent( _rxContext )
{
}
protected:
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext );
public:
/** registers the implementation of HANDLER at the <type>PcrModule</type>
*/
static void registerImplementation();
};
//--------------------------------------------------------------------
template < class HANDLER >
::rtl::OUString SAL_CALL HandlerComponentBase< HANDLER >::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)
{
return HANDLER::getImplementationName_static();
}
//--------------------------------------------------------------------
template < class HANDLER >
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL HandlerComponentBase< HANDLER >::getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException)
{
return HANDLER::getSupportedServiceNames_static();
}
//--------------------------------------------------------------------
template < class HANDLER >
void HandlerComponentBase< HANDLER >::registerImplementation()
{
PcrModule::getInstance().registerImplementation(
HANDLER::getImplementationName_static(),
HANDLER::getSupportedServiceNames_static(),
HANDLER::Create
);
}
//--------------------------------------------------------------------
template < class HANDLER >
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL HandlerComponentBase< HANDLER >::Create( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext )
{
return *( new HANDLER( _rxContext ) );
}
//........................................................................
} // namespace pcr
//........................................................................
#endif // EXTENSIONS_SOURCE_PROPCTRLR_PROPERTYHANDLER_HXX
| 8,777 |
1,629 | <filename>cypress/fixtures/samples-dummies/TextEntityRelations.json
{
"name": "Text Entity Relations",
"interface": {
"type": "text_entity_relations",
"entityLabels": [
{ "id": "food", "displayName": "Food", "description": "Edible item." },
{
"id": "hat",
"displayName": "Hat",
"description": "Something worn on the head."
}
],
"relationLabels": [{ "id": "subject", "displayName": "Subject" }]
},
"samples": [
{
"_id": "s2wa87k79",
"document": "This strainer makes a great hat, I'll wear it while I serve spaghetti!"
},
{
"_id": "sroom9j13",
"document": "Why are all these dumpings covered in butter?!"
}
]
}
| 299 |
572 | //
// NSMutableArray+JKDataHelper.h
// Pods
//
// Created by Jack on 17/3/28.
//
//
#import <Foundation/Foundation.h>
@interface NSMutableArray (JKDataHelper)
@end
| 71 |
9,908 | <gh_stars>1000+
//
// FMTokenizers.h
// fmdb
//
// Created by Andrew on 4/9/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "FMDatabase+FTS3.h"
NS_ASSUME_NONNULL_BEGIN
/**
This is the base tokenizer implementation, using a CFStringTokenizer to find words.
*/
@interface FMSimpleTokenizer : NSObject <FMTokenizerDelegate>
/**
Create the tokenizer with a given locale. The locale will be used to initialize the string tokenizer and to lowercase the parsed word.
@param locale The locale used by the simple tokenizer. The locale can be @c NULL , in which case the current locale will be used.
*/
- (instancetype)initWithLocale:(CFLocaleRef _Nullable)locale;
@end
#pragma mark
/**
This tokenizer extends the simple tokenizer with support for a stop word list.
*/
@interface FMStopWordTokenizer : NSObject <FMTokenizerDelegate>
@property (atomic, copy) NSSet *words;
/**
Load a stop-word tokenizer using a file containing words delimited by newlines. The file should be encoded in UTF-8.
@param wordFileURL The file URL for the list of words.
@param tokenizer The @c FMTokenizerDelegate .
@param error The @c NSError if there was any error reading the file.
*/
+ (instancetype)tokenizerWithFileURL:(NSURL *)wordFileURL baseTokenizer:(id<FMTokenizerDelegate>)tokenizer error:(NSError * _Nullable *)error;
/**
Initialize an instance of the tokenizer using the set of words. The words should be lowercase if you're using the
`FMSimpleTokenizer` as the base.
@param words The @c NSSet of words.
@param tokenizer The @c FMTokenizerDelegate .
*/
- (instancetype)initWithWords:(NSSet *)words baseTokenizer:(id<FMTokenizerDelegate>)tokenizer;
@end
NS_ASSUME_NONNULL_END
| 553 |
482 | <filename>nutzcloud/nutzcloud-literpc/src/main/java/org/nutz/boot/starter/literpc/api/RpcSerializer.java
package org.nutz.boot.starter.literpc.api;
import java.io.InputStream;
import java.io.OutputStream;
public interface RpcSerializer {
void write(Object obj, OutputStream out) throws Exception;
Object read(InputStream ins) throws Exception;
String getName();
}
| 136 |
22,481 | <filename>homeassistant/components/evil_genius_labs/manifest.json
{
"domain": "evil_genius_labs",
"name": "<NAME>",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/evil_genius_labs",
"requirements": ["pyevilgenius==1.0.0"],
"codeowners": ["@balloob"],
"iot_class": "local_polling"
}
| 131 |
711 | <filename>manager/api/beans/src/main/java/io/apiman/manager/api/beans/orgs/OrganizationBasedCompositeId.java
/*
* Copyright 2014 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apiman.manager.api.beans.orgs;
import java.io.Serializable;
/**
* Composite key for entities that are owned by an organization.
*
* @author <EMAIL>
*/
public class OrganizationBasedCompositeId implements Serializable {
private static final long serialVersionUID = 7313295981342740517L;
private OrganizationBean organization;
private String id;
/**
* Constructor.
*/
public OrganizationBasedCompositeId() {
}
/**
* Constructor.
* @param organization the organization
* @param id the id
*/
public OrganizationBasedCompositeId(OrganizationBean organization, String id) {
this.setOrganization(organization);
this.setId(id);
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the organization
*/
public OrganizationBean getOrganization() {
return organization;
}
/**
* @param organization the organization to set
*/
public void setOrganization(OrganizationBean organization) {
this.organization = organization;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((organization == null) ? 0 : organization.getId().hashCode());
return result;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OrganizationBasedCompositeId other = (OrganizationBasedCompositeId) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (organization == null) {
if (other.organization != null)
return false;
} else if (!organization.getId().equals(other.organization.getId()))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
@SuppressWarnings("nls")
public String toString() {
return "OrganizationBasedCompositeId [organization=" + organization + ", id=" + id + "]";
}
}
| 1,283 |
1,201 | <filename>tirelessTracker/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp<gh_stars>1000+
/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_IMPL_CLAMPED_HEX_DUMP_HPP
#define REALM_IMPL_CLAMPED_HEX_DUMP_HPP
#include <realm/util/hex_dump.hpp>
#include <realm/binary_data.hpp>
namespace realm {
namespace _impl {
/// Limit the amount of dumped data to 1024 bytes. For use in connection with
/// logging.
inline std::string clamped_hex_dump(BinaryData blob)
{
bool was_clipped = false;
std::size_t max_size = 1024;
std::size_t size_2 = blob.size();
if (size_2 > max_size) {
size_2 = max_size;
was_clipped = true;
}
std::string str = util::hex_dump(blob.data(), size_2); // Throws
if (was_clipped)
str += "..."; // Throws
return str;
}
} // namespace _impl
} // namespace realm
#endif // REALM_IMPL_CLAMPED_HEX_DUMP_HPP
| 526 |
361 | #include "FlowTrackEditor.h"
#include "FlowSection.h"
#include "MovieScene/MovieSceneFlowRepeaterSection.h"
#include "MovieScene/MovieSceneFlowTrack.h"
#include "MovieScene/MovieSceneFlowTriggerSection.h"
#include "Framework/MultiBox/MultiBoxBuilder.h"
#include "UObject/Package.h"
#include "ISequencerSection.h"
#include "DetailLayoutBuilder.h"
#include "DetailCategoryBuilder.h"
#include "Sections/MovieSceneEventSection.h"
#include "SequencerUtilities.h"
#include "MovieSceneSequenceEditor.h"
#define LOCTEXT_NAMESPACE "FFlowTrackEditor"
TSharedRef<ISequencerTrackEditor> FFlowTrackEditor::CreateTrackEditor(TSharedRef<ISequencer> InSequencer)
{
return MakeShareable(new FFlowTrackEditor(InSequencer));
}
TSharedRef<ISequencerSection> FFlowTrackEditor::MakeSectionInterface(UMovieSceneSection& SectionObject, UMovieSceneTrack& Track, FGuid ObjectBinding)
{
if (SectionObject.IsA<UMovieSceneFlowTriggerSection>())
{
return MakeShared<FFlowTriggerSection>(SectionObject, GetSequencer());
}
if (SectionObject.IsA<UMovieSceneFlowRepeaterSection>())
{
return MakeShared<FFlowRepeaterSection>(SectionObject, GetSequencer());
}
return MakeShared<FSequencerSection>(SectionObject);
}
FFlowTrackEditor::FFlowTrackEditor(TSharedRef<ISequencer> InSequencer)
: FMovieSceneTrackEditor(InSequencer)
{
}
void FFlowTrackEditor::AddFlowSubMenu(FMenuBuilder& MenuBuilder)
{
MenuBuilder.AddMenuEntry(
LOCTEXT("AddNewTriggerSection", "Flow Trigger"),
LOCTEXT("AddNewTriggerSectionTooltip", "Adds a new section that can trigger a Flow event at a specific time"),
FSlateIcon(),
FUIAction(
FExecuteAction::CreateRaw(this, &FFlowTrackEditor::HandleAddFlowTrackMenuEntryExecute, UMovieSceneFlowTriggerSection::StaticClass())
)
);
MenuBuilder.AddMenuEntry(
LOCTEXT("AddNewRepeaterSection", "Flow Repeater"),
LOCTEXT("AddNewRepeaterSectionTooltip", "Adds a new section that triggers a Flow event every time it's evaluated"),
FSlateIcon(),
FUIAction(
FExecuteAction::CreateRaw(this, &FFlowTrackEditor::HandleAddFlowTrackMenuEntryExecute, UMovieSceneFlowRepeaterSection::StaticClass())
)
);
}
void FFlowTrackEditor::BuildAddTrackMenu(FMenuBuilder& MenuBuilder)
{
UMovieSceneSequence* RootMovieSceneSequence = GetSequencer()->GetRootMovieSceneSequence();
FMovieSceneSequenceEditor* SequenceEditor = FMovieSceneSequenceEditor::Find(RootMovieSceneSequence);
if (SequenceEditor && SequenceEditor->SupportsEvents(RootMovieSceneSequence))
{
MenuBuilder.AddSubMenu(
LOCTEXT("AddTrack", "Flow Track"),
LOCTEXT("AddTooltip", "Adds a new flow track that can trigger events in the Flow graph."),
FNewMenuDelegate::CreateRaw(this, &FFlowTrackEditor::AddFlowSubMenu),
false,
FSlateIcon(FEditorStyle::GetStyleSetName(), "Sequencer.Tracks.Event")
);
}
}
TSharedPtr<SWidget> FFlowTrackEditor::BuildOutlinerEditWidget(const FGuid& ObjectBinding, UMovieSceneTrack* Track, const FBuildEditWidgetParams& Params)
{
check(Track);
const TSharedPtr<ISequencer> SequencerPtr = GetSequencer();
if (!SequencerPtr.IsValid())
{
return SNullWidget::NullWidget;
}
TWeakObjectPtr<UMovieSceneTrack> WeakTrack = Track;
const int32 RowIndex = Params.TrackInsertRowIndex;
auto SubMenuCallback = [this, WeakTrack, RowIndex]
{
FMenuBuilder MenuBuilder(true, nullptr);
UMovieSceneTrack* TrackPtr = WeakTrack.Get();
if (TrackPtr)
{
MenuBuilder.AddMenuEntry(
LOCTEXT("AddNewTriggerSection", "Flow Trigger"),
LOCTEXT("AddNewTriggerSectionTooltip", "Adds a new section that can trigger a Flow event at a specific time"),
FSlateIcon(),
FUIAction(FExecuteAction::CreateSP(this, &FFlowTrackEditor::CreateNewSection, TrackPtr, RowIndex + 1, UMovieSceneFlowTriggerSection::StaticClass(), true))
);
MenuBuilder.AddMenuEntry(
LOCTEXT("AddNewRepeaterSection", "Flow Repeater"),
LOCTEXT("AddNewRepeaterSectionTooltip", "Adds a new section that triggers a Flow event every time it's evaluated"),
FSlateIcon(),
FUIAction(FExecuteAction::CreateSP(this, &FFlowTrackEditor::CreateNewSection, TrackPtr, RowIndex + 1, UMovieSceneFlowRepeaterSection::StaticClass(), true))
);
}
else
{
MenuBuilder.AddWidget(SNew(STextBlock).Text(LOCTEXT("InvalidTrack", "Track is no longer valid")), FText(), true);
}
return MenuBuilder.MakeWidget();
};
return SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Center)
[
FSequencerUtilities::MakeAddButton(LOCTEXT("AddSection", "Section"), FOnGetContent::CreateLambda(SubMenuCallback), Params.NodeIsHovered, GetSequencer())
];
}
bool FFlowTrackEditor::SupportsType(TSubclassOf<UMovieSceneTrack> Type) const
{
return (Type == UMovieSceneFlowTrack::StaticClass());
}
bool FFlowTrackEditor::SupportsSequence(UMovieSceneSequence* InSequence) const
{
static UClass* LevelSequenceClass = FindObject<UClass>(ANY_PACKAGE, TEXT("LevelSequence"), true);
return InSequence && LevelSequenceClass && InSequence->GetClass()->IsChildOf(LevelSequenceClass);
}
const FSlateBrush* FFlowTrackEditor::GetIconBrush() const
{
return FEditorStyle::GetBrush("Sequencer.Tracks.Event");
}
void FFlowTrackEditor::HandleAddFlowTrackMenuEntryExecute(UClass* SectionType)
{
UMovieScene* FocusedMovieScene = GetFocusedMovieScene();
if (FocusedMovieScene == nullptr)
{
return;
}
if (FocusedMovieScene->IsReadOnly())
{
return;
}
const FScopedTransaction Transaction(LOCTEXT("AddFlowTrack_Transaction", "Add Flow Track"));
FocusedMovieScene->Modify();
TArray<UMovieSceneFlowTrack*> NewTracks;
UMovieSceneFlowTrack* NewMasterTrack = FocusedMovieScene->AddMasterTrack<UMovieSceneFlowTrack>();
NewTracks.Add(NewMasterTrack);
if (GetSequencer().IsValid())
{
GetSequencer()->OnAddTrack(NewMasterTrack, FGuid());
}
check(NewTracks.Num() != 0);
for (UMovieSceneFlowTrack* NewTrack : NewTracks)
{
CreateNewSection(NewTrack, 0, SectionType, false);
NewTrack->SetDisplayName(LOCTEXT("TrackName", "Flow Events"));
}
}
void FFlowTrackEditor::CreateNewSection(UMovieSceneTrack* Track, int32 RowIndex, UClass* SectionType, bool bSelect) const
{
TSharedPtr<ISequencer> SequencerPtr = GetSequencer();
if (SequencerPtr.IsValid())
{
UMovieScene* FocusedMovieScene = GetFocusedMovieScene();
const FQualifiedFrameTime CurrentTime = SequencerPtr->GetLocalTime();
FScopedTransaction Transaction(LOCTEXT("CreateNewFlowSectionTransactionText", "Add Flow Section"));
UMovieSceneSection* NewSection = NewObject<UMovieSceneSection>(Track, SectionType);
check(NewSection);
int32 OverlapPriority = 0;
for (UMovieSceneSection* Section : Track->GetAllSections())
{
if (Section->GetRowIndex() >= RowIndex)
{
Section->SetRowIndex(Section->GetRowIndex() + 1);
}
OverlapPriority = FMath::Max(Section->GetOverlapPriority() + 1, OverlapPriority);
}
Track->Modify();
if (SectionType == UMovieSceneFlowTriggerSection::StaticClass())
{
NewSection->SetRange(TRange<FFrameNumber>::All());
}
else
{
TRange<FFrameNumber> NewSectionRange;
if (CurrentTime.Time.FrameNumber < FocusedMovieScene->GetPlaybackRange().GetUpperBoundValue())
{
NewSectionRange = TRange<FFrameNumber>(CurrentTime.Time.FrameNumber, FocusedMovieScene->GetPlaybackRange().GetUpperBoundValue());
}
else
{
const float DefaultLengthInSeconds = 5.f;
NewSectionRange = TRange<FFrameNumber>(CurrentTime.Time.FrameNumber, CurrentTime.Time.FrameNumber + (DefaultLengthInSeconds * SequencerPtr->GetFocusedTickResolution()).FloorToFrame());
}
NewSection->SetRange(NewSectionRange);
}
NewSection->SetOverlapPriority(OverlapPriority);
NewSection->SetRowIndex(RowIndex);
Track->AddSection(*NewSection);
Track->UpdateEasing();
if (bSelect)
{
SequencerPtr->EmptySelection();
SequencerPtr->SelectSection(NewSection);
SequencerPtr->ThrobSectionSelection();
}
SequencerPtr->NotifyMovieSceneDataChanged(EMovieSceneDataChangeType::MovieSceneStructureItemAdded);
}
}
#undef LOCTEXT_NAMESPACE
| 2,697 |
1,080 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from neutron_lib.callbacks import exceptions
from neutron.api.rpc.callbacks import exceptions as rpc_exc
from neutron.api.rpc.callbacks import resource_manager
from neutron.tests.unit.services.qos import base
IS_VALID_RESOURCE_TYPE = (
'neutron.api.rpc.callbacks.resources.is_valid_resource_type')
class ResourceCallbacksManagerTestCaseMixin(object):
def test_register_fails_on_invalid_type(self):
self.assertRaises(
exceptions.Invalid,
self.mgr.register, lambda: None, 'TYPE')
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_clear_unregisters_all_callbacks(self, *mocks):
self.mgr.register(lambda: None, 'TYPE1')
self.mgr.register(lambda: None, 'TYPE2')
self.mgr.clear()
self.assertEqual([], self.mgr.get_subscribed_types())
def test_unregister_fails_on_invalid_type(self):
self.assertRaises(
exceptions.Invalid,
self.mgr.unregister, lambda: None, 'TYPE')
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_unregister_fails_on_unregistered_callback(self, *mocks):
self.assertRaises(
rpc_exc.CallbackNotFound,
self.mgr.unregister, lambda: None, 'TYPE')
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_unregister_unregisters_callback(self, *mocks):
callback = lambda: None
self.mgr.register(callback, 'TYPE')
self.mgr.unregister(callback, 'TYPE')
self.assertEqual([], self.mgr.get_subscribed_types())
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test___init___does_not_reset_callbacks(self, *mocks):
callback = lambda: None
self.mgr.register(callback, 'TYPE')
resource_manager.ProducerResourceCallbacksManager()
self.assertEqual(['TYPE'], self.mgr.get_subscribed_types())
class ProducerResourceCallbacksManagerTestCase(
base.BaseQosTestCase, ResourceCallbacksManagerTestCaseMixin):
def setUp(self):
super(ProducerResourceCallbacksManagerTestCase, self).setUp()
self.mgr = self.prod_mgr
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_register_registers_callback(self, *mocks):
callback = lambda: None
self.mgr.register(callback, 'TYPE')
self.assertEqual(callback, self.mgr.get_callback('TYPE'))
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_register_fails_on_multiple_calls(self, *mocks):
self.mgr.register(lambda: None, 'TYPE')
self.assertRaises(
rpc_exc.CallbacksMaxLimitReached,
self.mgr.register, lambda: None, 'TYPE')
def test_get_callback_fails_on_invalid_type(self):
self.assertRaises(
exceptions.Invalid,
self.mgr.get_callback, 'TYPE')
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_get_callback_fails_on_unregistered_callback(
self, *mocks):
self.assertRaises(
rpc_exc.CallbackNotFound,
self.mgr.get_callback, 'TYPE')
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_get_callback_returns_proper_callback(self, *mocks):
callback1 = lambda: None
callback2 = lambda: None
self.mgr.register(callback1, 'TYPE1')
self.mgr.register(callback2, 'TYPE2')
self.assertEqual(callback1, self.mgr.get_callback('TYPE1'))
self.assertEqual(callback2, self.mgr.get_callback('TYPE2'))
class ConsumerResourceCallbacksManagerTestCase(
base.BaseQosTestCase, ResourceCallbacksManagerTestCaseMixin):
def setUp(self):
super(ConsumerResourceCallbacksManagerTestCase, self).setUp()
self.mgr = self.cons_mgr
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_register_registers_callback(self, *mocks):
callback = lambda: None
self.mgr.register(callback, 'TYPE')
self.assertEqual({callback}, self.mgr.get_callbacks('TYPE'))
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_register_succeeds_on_multiple_calls(self, *mocks):
callback1 = lambda: None
callback2 = lambda: None
self.mgr.register(callback1, 'TYPE')
self.mgr.register(callback2, 'TYPE')
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_get_callbacks_fails_on_unregistered_callback(self, *mocks):
self.assertRaises(
rpc_exc.CallbackNotFound,
self.mgr.get_callbacks, 'TYPE')
@mock.patch(IS_VALID_RESOURCE_TYPE, return_value=True)
def test_get_callbacks_returns_proper_callbacks(self, *mocks):
callback1 = lambda: None
callback2 = lambda: None
self.mgr.register(callback1, 'TYPE1')
self.mgr.register(callback2, 'TYPE2')
self.assertEqual(set([callback1]), self.mgr.get_callbacks('TYPE1'))
self.assertEqual(set([callback2]), self.mgr.get_callbacks('TYPE2'))
| 2,300 |
416 | <filename>src/main/java/com/tencentcloudapi/youmall/v20180228/models/NetworkHistoryInfo.java
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.youmall.v20180228.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class NetworkHistoryInfo extends AbstractModel{
/**
* 总数
*/
@SerializedName("Count")
@Expose
private Long Count;
/**
* 集团id
*/
@SerializedName("CompanyId")
@Expose
private String CompanyId;
/**
* 店铺id
*/
@SerializedName("ShopId")
@Expose
private Long ShopId;
/**
* 店铺省份
*/
@SerializedName("Province")
@Expose
private String Province;
/**
* 店铺城市
*/
@SerializedName("City")
@Expose
private String City;
/**
* 店铺名称
*/
@SerializedName("ShopName")
@Expose
private String ShopName;
/**
* 网络信息
*/
@SerializedName("Infos")
@Expose
private NetworkInfo [] Infos;
/**
* Get 总数
* @return Count 总数
*/
public Long getCount() {
return this.Count;
}
/**
* Set 总数
* @param Count 总数
*/
public void setCount(Long Count) {
this.Count = Count;
}
/**
* Get 集团id
* @return CompanyId 集团id
*/
public String getCompanyId() {
return this.CompanyId;
}
/**
* Set 集团id
* @param CompanyId 集团id
*/
public void setCompanyId(String CompanyId) {
this.CompanyId = CompanyId;
}
/**
* Get 店铺id
* @return ShopId 店铺id
*/
public Long getShopId() {
return this.ShopId;
}
/**
* Set 店铺id
* @param ShopId 店铺id
*/
public void setShopId(Long ShopId) {
this.ShopId = ShopId;
}
/**
* Get 店铺省份
* @return Province 店铺省份
*/
public String getProvince() {
return this.Province;
}
/**
* Set 店铺省份
* @param Province 店铺省份
*/
public void setProvince(String Province) {
this.Province = Province;
}
/**
* Get 店铺城市
* @return City 店铺城市
*/
public String getCity() {
return this.City;
}
/**
* Set 店铺城市
* @param City 店铺城市
*/
public void setCity(String City) {
this.City = City;
}
/**
* Get 店铺名称
* @return ShopName 店铺名称
*/
public String getShopName() {
return this.ShopName;
}
/**
* Set 店铺名称
* @param ShopName 店铺名称
*/
public void setShopName(String ShopName) {
this.ShopName = ShopName;
}
/**
* Get 网络信息
* @return Infos 网络信息
*/
public NetworkInfo [] getInfos() {
return this.Infos;
}
/**
* Set 网络信息
* @param Infos 网络信息
*/
public void setInfos(NetworkInfo [] Infos) {
this.Infos = Infos;
}
public NetworkHistoryInfo() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public NetworkHistoryInfo(NetworkHistoryInfo source) {
if (source.Count != null) {
this.Count = new Long(source.Count);
}
if (source.CompanyId != null) {
this.CompanyId = new String(source.CompanyId);
}
if (source.ShopId != null) {
this.ShopId = new Long(source.ShopId);
}
if (source.Province != null) {
this.Province = new String(source.Province);
}
if (source.City != null) {
this.City = new String(source.City);
}
if (source.ShopName != null) {
this.ShopName = new String(source.ShopName);
}
if (source.Infos != null) {
this.Infos = new NetworkInfo[source.Infos.length];
for (int i = 0; i < source.Infos.length; i++) {
this.Infos[i] = new NetworkInfo(source.Infos[i]);
}
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "Count", this.Count);
this.setParamSimple(map, prefix + "CompanyId", this.CompanyId);
this.setParamSimple(map, prefix + "ShopId", this.ShopId);
this.setParamSimple(map, prefix + "Province", this.Province);
this.setParamSimple(map, prefix + "City", this.City);
this.setParamSimple(map, prefix + "ShopName", this.ShopName);
this.setParamArrayObj(map, prefix + "Infos.", this.Infos);
}
}
| 2,530 |
532 | <gh_stars>100-1000
from .hdbscan_ import HDBSCAN, hdbscan
from .robust_single_linkage_ import RobustSingleLinkage, robust_single_linkage
from .validity import validity_index
from .prediction import approximate_predict, membership_vector, all_points_membership_vectors
| 81 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.