max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
407 |
#include "gui/channel_manager/channel_item.h"
#define MAX_CHANNEL_ENTIRES 1000
namespace hal
{
ChannelItem::ChannelItem(QString name)
: mName(name)
{
}
QVariant ChannelItem::data(int column) const
{
switch (column)
{
case 0:
return mName;
default:
return QVariant();
}
}
const QString ChannelItem::name() const
{
return mName;
}
const QList<ChannelEntry*>* ChannelItem::getList() const
{
return &mLogEntries;
}
QReadWriteLock* ChannelItem::getLock()
{
return &mLock;
}
void ChannelItem::appendEntry(ChannelEntry* entry)
{
if (mLogEntries.size() == MAX_CHANNEL_ENTIRES)
mLogEntries.removeFirst();
mLogEntries.append(entry);
}
}
| 412 |
707 |
#pragma once
// DO NOT EDIT. File generated by script update_inlinedoc.py.
#define automaton___reduce___doc \
"__reduce__()\n" \
"\n" \
"Return pickle-able data for this automaton instance."
#define automaton___sizeof___doc \
"Return the approximate size in bytes occupied by the\n" \
"Automaton instance in memory excluding the size of\n" \
"associated objects when the Automaton is created with\n" \
"Automaton() or Automaton(ahocorasick.STORE_ANY)."
#define automaton_add_word_doc \
"add_word(key, [value]) -> boolean\n" \
"\n" \
"Add a key string to the dict-like trie and associate this\n" \
"key with a value. value is optional or mandatory depending\n" \
"how the Automaton instance was created. Return True if the\n" \
"word key is inserted and did not exists in the trie or False\n" \
"otherwise. The value associated with an existing word is\n" \
"replaced.\n" \
"\n" \
"The value is either mandatory or optional:\n" \
"- If the Automaton was created without argument (the\n" \
" default) as Automaton() or with\n" \
" Automaton(ahocorasik.STORE_ANY) then the value is required\n" \
" and can be any Python object.\n" \
"- If the Automaton was created with\n" \
" Automaton(ahocorasik.STORE_INTS) then the value is\n" \
" optional. If provided it must be an integer, otherwise it\n" \
" defaults to len(automaton) which is therefore the order\n" \
" index in which keys are added to the trie.\n" \
"- If the Automaton was created with\n" \
" Automaton(ahocorasik.STORE_LENGTH) then associating a\n" \
" value is not allowed - len(word) is saved automatically as\n" \
" a value instead.\n" \
"\n" \
"Calling add_word() invalidates all iterators only if the new\n" \
"key did not exist in the trie so far (i.e. the method\n" \
"returned True)."
#define automaton_clear_doc \
"clear()\n" \
"\n" \
"Remove all keys from the trie. This method invalidates all\n" \
"iterators."
#define automaton_constructor_doc \
"Automaton(value_type=ahocorasick.STORE_ANY, [key_type])\n" \
"\n" \
"Create a new empty Automaton. Both value_type and key_type\n" \
"are optional.\n" \
"\n" \
"value_type is one of these constants:\n" \
"- ahocorasick.STORE_ANY [default] : The associated value can\n" \
" be any Python object.\n" \
"- ahocorasick.STORE_LENGTH : The length of an added string\n" \
" key is automatically used as the associated value stored\n" \
" in the trie for that key.\n" \
"- ahocorasick.STORE_INTS : The associated value must be a\n" \
" 32-bit integer.\n" \
"\n" \
"key_type defines the type of data that can be stored in an\n" \
"automaton; it is one of these constants and defines type of\n" \
"data might be stored:\n" \
"- ahocorasick.KEY_STRING [default] : string\n" \
"- ahocorasick.KEY_SEQUENCE : sequences of integers; The size\n" \
" of integer depends the version and platform Python, but\n" \
" for versions of Python >= 3.3, it is guaranteed to be\n" \
" 32-bits."
#define automaton_dump_doc \
"dump()\n" \
"\n" \
"Return a three-tuple of lists describing the Automaton as a\n" \
"graph of nodes, edges, failure links.\n" \
"- nodes: each item is a pair (node id, end of word marker)\n" \
"- edges: each item is a triple (node id, label char, child\n" \
" node id)\n" \
"- failure links: each item is a pair (source node id, node\n" \
" if connected by fail node)\n" \
"\n" \
"For each of these, the node id is a unique number and a\n" \
"label is a number."
#define automaton_exists_doc \
"exists(key) -> boolean\n" \
"\n" \
"Return True if the key is present in the trie. Same as using\n" \
"the 'in' keyword."
#define automaton_find_all_doc \
"find_all(string, callback, [start, [end]])\n" \
"\n" \
"Perform the Aho-Corasick search procedure using the provided\n" \
"input string and iterate over the matching tuples\n" \
"(end_index, value) for keys found in string. Invoke the\n" \
"callback callable for each matching tuple.\n" \
"\n" \
"The callback callable must accept two positional arguments:\n" \
"- end_index is the end index in the input string where a\n" \
"trie key string was found. - value is the value associated\n" \
"with the found key string.\n" \
"\n" \
"The start and end optional arguments can be used to limit\n" \
"the search to an input string slice as in string[start:end].\n" \
"\n" \
"Equivalent to a loop on iter() calling a callable at each\n" \
"iteration."
#define automaton_get_doc \
"get(key[, default])\n" \
"\n" \
"Return the value associated with the key string.\n" \
"\n" \
"Raise a KeyError exception if the key is not in the trie and\n" \
"no default is provided.\n" \
"\n" \
"Return the optional default value if provided and the key is\n" \
"not in the trie."
#define automaton_get_stats_doc \
"get_stats() -> dict\n" \
"\n" \
"Return a dictionary containing Automaton statistics.\n" \
"- nodes_count - total number of nodes\n" \
"- words_count - number of distinct words (same as\n" \
" len(automaton))\n" \
"- longest_word - length of the longest word\n" \
"- links_count - number of edges\n" \
"- sizeof_node - size of single node in bytes\n" \
"- total_size - total size of trie in bytes (about\n" \
" nodes_count * size_of node + links_count * size of\n" \
" pointer)."
#define automaton_items_doc \
"items([prefix, [wildcard, [how]]])\n" \
"\n" \
"Return an iterator on tuples of (key, value). Keys are\n" \
"matched optionally to the prefix using the same logic and\n" \
"arguments as in the keys() method."
#define automaton_iter_doc \
"iter(string, [start, [end]], ignore_white_space=False)\n" \
"\n" \
"Perform the Aho-Corasick search procedure using the provided\n" \
"input string.\n" \
"\n" \
"Return an iterator of tuples (end_index, value) for keys\n" \
"found in string where:\n" \
"- end_index is the end index in the input string where a\n" \
" trie key string was found.\n" \
"- value is the value associated with the found key string.\n" \
"\n" \
"The start and end optional arguments can be used to limit\n" \
"the search to an input string slice as in string[start:end].\n" \
"\n" \
"The ignore_white_space optional arguments can be used to\n" \
"ignore white spaces from input string."
#define automaton_iter_long_doc \
"iter_long(string, [start, [end]])\n" \
"\n" \
"Perform the modified Aho-Corasick search procedure which\n" \
"matches the longest words from set.\n" \
"\n" \
"Return an iterator of tuples (end_index, value) for keys\n" \
"found in string where:\n" \
"- end_index is the end index in the input string where a\n" \
" trie key string was found.\n" \
"- value is the value associated with the found key string.\n" \
"\n" \
"The start and end optional arguments can be used to limit\n" \
"the search to an input string slice as in string[start:end]."
#define automaton_keys_doc \
"keys([prefix, [wildcard, [how]]])\n" \
"\n" \
"Return an iterator on keys. If the optional prefix string is\n" \
"provided, only yield keys starting with this prefix.\n" \
"\n" \
"If the optional wildcard is provided as a single character\n" \
"string, then the prefix is treated as a simple pattern using\n" \
"this character as a wildcard.\n" \
"\n" \
"The optional how argument is used to control how strings are\n" \
"matched using one of these possible values:\n" \
"- ahocorasick.MATCH_EXACT_LENGTH (default) Yield matches\n" \
" that have the same exact length as the prefix length.\n" \
"- ahocorasick.MATCH_AT_LEAST_PREFIX Yield matches that have\n" \
" a length greater or equal to the prefix length.\n" \
"- ahocorasick.MATCH_AT_MOST_PREFIX Yield matches that have a\n" \
" length lesser or equal to the prefix length."
#define automaton_len_doc \
"len() -> integer\n" \
"\n" \
"Return the number of distinct keys added to the trie."
#define automaton_longest_prefix_doc \
"longest_prefix(string) => integer\n" \
"\n" \
"Return the length of the longest prefix of string that\n" \
"exists in the trie."
#define automaton_make_automaton_doc \
"make_automaton()\n" \
"\n" \
"Finalize and create the Aho-Corasick automaton based on the\n" \
"keys already added to the trie. This does not require\n" \
"additional memory. After successful creation the\n" \
"Automaton.kind attribute is set to ahocorasick.AHOCORASICK."
#define automaton_match_doc \
"match(key) -> bool\n" \
"\n" \
"Return True if there is a prefix (or key) equal to key\n" \
"present in the trie.\n" \
"\n" \
"For example if the key 'example' has been added to the trie,\n" \
"then calls to match('e'), match('ex'), ..., match('exampl')\n" \
"or match('example') all return True. But exists() is True\n" \
"only when calling exists('example')."
#define automaton_pop_doc \
"pop(word)\n" \
"\n" \
"Remove given word from a trie and return associated values.\n" \
"Raise a KeyError if the word was not found."
#define automaton_remove_word_doc \
"remove_word(word) -> bool\n" \
"\n" \
"Remove given word from a trie. Return True if words was\n" \
"found, False otherwise."
#define automaton_save_doc \
"save(path, serializer)\n" \
"\n" \
"Save content of automaton in an on-disc file.\n" \
"\n" \
"Serializer is a callable object that is used when automaton\n" \
"store type is STORE_ANY. This method converts a python\n" \
"object into bytes; it can be pickle.dumps."
#define automaton_search_iter_doc \
"This class is not available directly but instances of\n" \
"AutomatonSearchIter are returned by the iter() method of an\n" \
"Automaton. This iterator can be manipulated through its\n" \
"set() method."
#define automaton_search_iter_set_doc \
"set(string, reset=False)\n" \
"\n" \
"Set a new string to search. When the reset argument is False\n" \
"(default) then the Aho-Corasick procedure is continued and\n" \
"the internal state of the Automaton and end index of the\n" \
"string being searched are not reset. This allow to search\n" \
"for large strings in multiple smaller chunks."
#define automaton_values_doc \
"values([prefix, [wildcard, [how]]])\n" \
"\n" \
"Return an iterator on values associated with each keys. Keys\n" \
"are matched optionally to the prefix using the same logic\n" \
"and arguments as in the keys() method."
#define module_doc \
"pyahocorasick is a fast and memory efficient library for\n" \
"exact or approximate multi-pattern string search meaning\n" \
"that you can find multiple key strings occurrences at once\n" \
"in some input text."
#define module_load_doc \
"load(path, deserializer) => Automaton\n" \
"\n" \
"Load automaton previously stored on disc using save method.\n" \
"\n" \
"Deserializer is a callable object which converts bytes back\n" \
"into python object; it can be pickle.loads."
| 3,810 |
1,076 |
////////////////////////////////////////////////////////////////////////////////
// /
// 2012-2019 (c) Baical /
// /
// This library is free software; you can redistribute it and/or /
// modify it under the terms of the GNU Lesser General Public /
// License as published by the Free Software Foundation; either /
// version 3.0 of the License, or (at your option) any later version. /
// /
// This library is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU /
// Lesser General Public License for more details. /
// /
// You should have received a copy of the GNU Lesser General Public /
// License along with this library. /
// /
////////////////////////////////////////////////////////////////////////////////
#ifndef IPSHARED_LIB_H
#define IPSHARED_LIB_H
#include "GTypes.h"
#include "Length.h"
#include "PString.h"
#include "WString.h"
#include "SharedLib.h"
#include "PAtomic.h"
class CPSharedLib
: public CSharedLib
{
protected:
HMODULE m_pDll;
public:
CPSharedLib(const tXCHAR *i_pPath)
: CSharedLib(i_pPath)
, m_pDll(NULL)
{
m_pDll = LoadLibraryW(i_pPath);
if (m_pDll)
{
m_bState = TRUE;
}
}
void *GetFunction(const tACHAR *i_pName)
{
return (void*)(GetProcAddress(m_pDll, i_pName));
}
virtual ~CPSharedLib()
{
if (m_pDll)
{
FreeLibrary(m_pDll);
m_pDll = NULL;
}
}
};
#endif //IPSHARED_LIB_H
| 1,228 |
453 |
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#ifndef LIB_EXTRAS_ENC_EXR_H_
#define LIB_EXTRAS_ENC_EXR_H_
// Encodes OpenEXR images in memory.
#include "lib/extras/packed_image.h"
#include "lib/jxl/base/data_parallel.h"
#include "lib/jxl/base/padded_bytes.h"
#include "lib/jxl/base/span.h"
#include "lib/jxl/base/status.h"
#include "lib/jxl/codec_in_out.h"
#include "lib/jxl/color_encoding_internal.h"
namespace jxl {
namespace extras {
// Transforms from io->c_current to `c_desired` (with the transfer function set
// to linear as that is the OpenEXR convention) and encodes into `bytes`.
Status EncodeImageEXR(const CodecInOut* io, const ColorEncoding& c_desired,
ThreadPool* pool, PaddedBytes* bytes);
} // namespace extras
} // namespace jxl
#endif // LIB_EXTRAS_ENC_EXR_H_
| 366 |
1,131 |
//
// 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.cloud.hypervisor.xenserver.resource.wrapper.xenbase;
import java.net.URI;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.UpgradeSnapshotCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.resource.ResourceWrapper;
import com.xensource.xenapi.Connection;
@ResourceWrapper(handles = UpgradeSnapshotCommand.class)
public final class CitrixUpgradeSnapshotCommandWrapper extends CommandWrapper<UpgradeSnapshotCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixUpgradeSnapshotCommandWrapper.class);
@Override
public Answer execute(final UpgradeSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
final String secondaryStorageUrl = command.getSecondaryStorageUrl();
final String backedUpSnapshotUuid = command.getSnapshotUuid();
final Long volumeId = command.getVolumeId();
final Long accountId = command.getAccountId();
final Long templateId = command.getTemplateId();
final Long tmpltAcountId = command.getTmpltAccountId();
final String version = command.getVersion();
if (!version.equals("2.1")) {
return new Answer(command, true, "success");
}
try {
final Connection conn = citrixResourceBase.getConnection();
final URI uri = new URI(secondaryStorageUrl);
final String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
final String snapshotPath = secondaryStorageMountPath + "/snapshots/" + accountId + "/" + volumeId + "/" + backedUpSnapshotUuid + ".vhd";
final String templatePath = secondaryStorageMountPath + "/template/tmpl/" + tmpltAcountId + "/" + templateId;
citrixResourceBase.upgradeSnapshot(conn, templatePath, snapshotPath);
return new Answer(command, true, "success");
} catch (final Exception e) {
final String details = "upgrading snapshot " + backedUpSnapshotUuid + " failed due to " + e.toString();
s_logger.error(details, e);
}
return new Answer(command, false, "failure");
}
}
| 995 |
1,475 |
<filename>geode-core/src/main/java/org/apache/geode/internal/logging/log4j/LogMarker.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.logging.log4j;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.apache.geode.annotations.Immutable;
/**
* This collection of {@link org.apache.logging.log4j.Marker} objects offer finer control of
* logging. The majority of these markers are concerned with TRACE level logging, the intent of
* which should be consistently clear by ending in *_VERBOSE. Additionally, these markers, even
* with the TRACE level active, will be disabled in the default Log4j2 configuration
* provided by {@code main/resources/log4j2.xml}
*
* <p>
* Some additional markers exist for log levels more coarse than TRACE or DEBUG.
* These markers end in *_MARKER for clear distinction from the *_VERBOSE markers.
*/
public interface LogMarker {
// Non-verbose parent markers
@Immutable
Marker CONFIG_MARKER = MarkerManager.getMarker("CONFIG_MARKER");
@Immutable
Marker DISK_STORE_MONITOR_MARKER = MarkerManager.getMarker("DISK_STORE_MONITOR_MARKER");
@Immutable
Marker DISTRIBUTION_MARKER = MarkerManager.getMarker("DISTRIBUTION_MARKER");
@Immutable
Marker DLS_MARKER = MarkerManager.getMarker("DLS_MARKER");
@Immutable
Marker DM_MARKER = MarkerManager.getMarker("DM").addParents(DISTRIBUTION_MARKER);
@Immutable
Marker SERIALIZER_MARKER = MarkerManager.getMarker("SERIALIZER_MARKER");
@Immutable
Marker STATISTICS_MARKER = MarkerManager.getMarker("STATISTICS_MARKER");
// Verbose parent markers
/** @deprecated Use GEODE_VERBOSE */
@Immutable
Marker GEMFIRE_VERBOSE = MarkerManager.getMarker("GEMFIRE_VERBOSE");
@Immutable
Marker GEODE_VERBOSE = MarkerManager.getMarker("GEODE_VERBOSE").setParents(GEMFIRE_VERBOSE);
// Verbose child markers. Every marker below should
// (a) end in *_VERBOSE and (b) have at least one *_VERBOSE parent
@Immutable
Marker BRIDGE_SERVER_VERBOSE =
MarkerManager.getMarker("BRIDGE_SERVER_VERBOSE").addParents(GEODE_VERBOSE);
@Immutable
Marker CACHE_XML_PARSER_VERBOSE =
MarkerManager.getMarker("CACHE_XML_PARSER_VERBOSE").addParents(GEODE_VERBOSE);
@Immutable
Marker DISK_STORE_MONITOR_VERBOSE = MarkerManager.getMarker("DISK_STORE_MONITOR_VERBOSE")
.addParents(DISK_STORE_MONITOR_MARKER, GEODE_VERBOSE);
@Immutable
Marker DLS_VERBOSE = MarkerManager.getMarker("DLS_VERBOSE").addParents(DLS_MARKER, GEODE_VERBOSE);
@Immutable
Marker PERSIST_VERBOSE = MarkerManager.getMarker("PERSIST_VERBOSE").addParents(GEODE_VERBOSE);
@Immutable
Marker PERSIST_ADVISOR_VERBOSE =
MarkerManager.getMarker("PERSIST_ADVISOR_VERBOSE").addParents(PERSIST_VERBOSE);
@Immutable
Marker PERSIST_RECOVERY_VERBOSE =
MarkerManager.getMarker("PERSIST_RECOVERY_VERBOSE").addParents(PERSIST_VERBOSE);
@Immutable
Marker PERSIST_WRITES_VERBOSE =
MarkerManager.getMarker("PERSIST_WRITES_VERBOSE").addParents(PERSIST_VERBOSE);
@Immutable
Marker RVV_VERBOSE = MarkerManager.getMarker("RVV_VERBOSE").addParents(GEODE_VERBOSE);
@Immutable
Marker TOMBSTONE_VERBOSE = MarkerManager.getMarker("TOMBSTONE_VERBOSE").addParents(GEODE_VERBOSE);
@Immutable
Marker TOMBSTONE_COUNT_VERBOSE =
MarkerManager.getMarker("TOMBSTONE_COUNT_VERBOSE").addParents(TOMBSTONE_VERBOSE);
@Immutable
Marker LRU_VERBOSE = MarkerManager.getMarker("LRU_VERBOSE").addParents(GEODE_VERBOSE);
@Immutable
Marker LRU_CLOCK_VERBOSE = MarkerManager.getMarker("LRU_CLOCK_VERBOSE").addParents(LRU_VERBOSE);
@Immutable
Marker LRU_TOMBSTONE_COUNT_VERBOSE = MarkerManager.getMarker("LRU_TOMBSTONE_COUNT_VERBOSE")
.addParents(LRU_VERBOSE, TOMBSTONE_COUNT_VERBOSE);
@Immutable
Marker SERIALIZER_VERBOSE =
MarkerManager.getMarker("SERIALIZER_VERBOSE").addParents(SERIALIZER_MARKER, GEODE_VERBOSE);
@Immutable
Marker SERIALIZER_ANNOUNCE_TYPE_WRITTEN_VERBOSE = MarkerManager
.getMarker("SERIALIZER_ANNOUNCE_TYPE_WRITTEN_VERBOSE").addParents(SERIALIZER_VERBOSE);
@Immutable
Marker SERIALIZER_WRITE_DSFID_VERBOSE =
MarkerManager.getMarker("SERIALIZER_WRITE_DSFID_VERBOSE").addParents(SERIALIZER_VERBOSE);
@Immutable
Marker STATISTICS_VERBOSE =
MarkerManager.getMarker("STATISTICS_VERBOSE").addParents(STATISTICS_MARKER, GEODE_VERBOSE);
@Immutable
Marker STATE_FLUSH_OP_VERBOSE =
MarkerManager.getMarker("STATE_FLUSH_OP_VERBOSE").addParents(GEODE_VERBOSE);
@Immutable
Marker DISTRIBUTION_STATE_FLUSH_VERBOSE =
MarkerManager.getMarker("DISTRIBUTION_STATE_FLUSH_VERBOSE").addParents(DISTRIBUTION_MARKER,
STATE_FLUSH_OP_VERBOSE);
@Immutable
Marker DISTRIBUTION_BRIDGE_SERVER_VERBOSE =
MarkerManager.getMarker("DISTRIBUTION_BRIDGE_SERVER_VERBOSE").addParents(DISTRIBUTION_MARKER,
BRIDGE_SERVER_VERBOSE);
@Immutable
Marker DISTRIBUTION_ADVISOR_VERBOSE = MarkerManager.getMarker("DISTRIBUTION_ADVISOR_VERBOSE")
.addParents(DISTRIBUTION_MARKER, GEODE_VERBOSE);
@Immutable
Marker DM_VERBOSE =
MarkerManager.getMarker("DM_VERBOSE").addParents(DISTRIBUTION_MARKER, GEODE_VERBOSE);
@Immutable
Marker DM_BRIDGE_SERVER_VERBOSE = MarkerManager.getMarker("DM_BRIDGE_SERVER_VERBOSE")
.addParents(DM_VERBOSE, BRIDGE_SERVER_VERBOSE);
@Immutable
Marker EVENT_ID_TO_STRING_VERBOSE =
MarkerManager.getMarker("EVENT_ID_TO_STRING_VERBOSE").addParents(DM_BRIDGE_SERVER_VERBOSE);
@Immutable
Marker INITIAL_IMAGE_VERBOSE =
MarkerManager.getMarker("INITIAL_IMAGE_VERBOSE").addParents(GEODE_VERBOSE);
@Immutable
Marker INITIAL_IMAGE_VERSIONED_VERBOSE =
MarkerManager.getMarker("INITIAL_IMAGE_VERSIONED_VERBOSE").addParents(INITIAL_IMAGE_VERBOSE);
@Immutable
Marker MANAGED_ENTITY_VERBOSE =
MarkerManager.getMarker("MANAGED_ENTITY_VERBOSE").addParents(GEODE_VERBOSE);
@Immutable
Marker VERSION_TAG_VERBOSE =
MarkerManager.getMarker("VERSION_TAG_VERBOSE").addParents(GEODE_VERBOSE);
@Immutable
Marker VERSIONED_OBJECT_LIST_VERBOSE =
MarkerManager.getMarker("VERSIONED_OBJECT_LIST_VERBOSE").addParents(GEODE_VERBOSE);
}
| 2,643 |
851 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from utils.init_weights import init_weights, normalized_columns_initializer
from core.model import Model
class EmptyModel(Model):
def __init__(self, args):
super(EmptyModel, self).__init__(args)
self._reset()
def _init_weights(self):
pass
def print_model(self):
self.logger.warning("<-----------------------------------> Model")
self.logger.warning(self)
def _reset(self): # NOTE: should be called at each child's __init__
self._init_weights()
self.type(self.dtype) # put on gpu if possible
self.print_model()
def forward(self, input):
pass
| 319 |
642 |
#pragma once
#include "Control.h"
namespace AxiomModel {
constexpr size_t GRAPH_CONTROL_CURVE_COUNT = 16;
struct GraphControlTimeState {
uint32_t currentTimeSamples;
uint8_t currentState;
};
struct GraphControlCurveStorage {
uint8_t curveCount;
double curveStartVals[GRAPH_CONTROL_CURVE_COUNT + 1];
double curveEndPositions[GRAPH_CONTROL_CURVE_COUNT];
double curveTension[GRAPH_CONTROL_CURVE_COUNT];
uint8_t curveStates[GRAPH_CONTROL_CURVE_COUNT + 1];
};
struct GraphControlCurveState {
uint8_t *curveCount;
double *curveStartVals;
double *curveEndPositions;
double *curveTension;
uint8_t *curveStates;
};
class GraphControl : public Control {
public:
AxiomCommon::Event<float> zoomChanged;
AxiomCommon::Event<float> scrollChanged;
AxiomCommon::Event<> stateChanged;
AxiomCommon::Event<> timeChanged;
GraphControl(const QUuid &uuid, const QUuid &parentUuid, QPoint pos, QSize size, bool selected, QString name,
bool showName, const QUuid &exposerUuid, const QUuid &exposingUuid,
std::unique_ptr<GraphControlCurveStorage> savedState, ModelRoot *root);
static std::unique_ptr<GraphControl> create(const QUuid &uuid, const QUuid &parentUuid, QPoint pos, QSize size,
bool selected, QString name, bool showName,
const QUuid &exposerUuid, const QUuid &exposingUuid,
std::unique_ptr<GraphControlCurveStorage> savedState,
ModelRoot *root);
QString debugName() override;
void doRuntimeUpdate() override;
GraphControlTimeState *getTimeState() const;
GraphControlCurveState *getCurveState();
float zoom() const { return _zoom; }
void setZoom(float zoom);
float scroll() const { return _scroll; }
void setScroll(float scroll);
std::optional<uint8_t> determineInsertIndex(double time);
void insertPoint(uint8_t index, double time, double val, double tension, uint8_t curveState);
void movePoint(uint8_t index, double time, double value);
void setPointTag(uint8_t index, uint8_t tag);
void setCurveTension(uint8_t index, double tension);
void removePoint(uint8_t index);
void saveState() override;
void restoreState() override;
MaximCompiler::ControlInitializer getInitializer() override;
private:
float _zoom = 0;
float _scroll = 0;
size_t _lastStateHash = 0;
uint32_t _lastTime = 0;
std::unique_ptr<GraphControlCurveStorage> _savedStorage;
GraphControlCurveState _currentState;
void setSavedStorage(std::unique_ptr<GraphControlCurveStorage> storage);
};
}
| 1,339 |
348 |
{"nom":"Gageac-et-Rouillac","circ":"2ème circonscription","dpt":"Dordogne","inscrits":393,"abs":189,"votants":204,"blancs":0,"nuls":5,"exp":199,"res":[{"nuance":"REM","nom":"<NAME>","voix":64},{"nuance":"FN","nom":"<NAME>","voix":41},{"nuance":"ECO","nom":"Mme <NAME>","voix":29},{"nuance":"LR","nom":"Mme <NAME>","voix":23},{"nuance":"FI","nom":"Mme <NAME>","voix":17},{"nuance":"COM","nom":"M. <NAME>","voix":13},{"nuance":"ECO","nom":"Mme <NAME>","voix":6},{"nuance":"DIV","nom":"M. <NAME>","voix":3},{"nuance":"DLF","nom":"M. <NAME>","voix":2},{"nuance":"EXG","nom":"Mme <NAME>","voix":1},{"nuance":"EXD","nom":"M. <NAME>","voix":0}]}
| 263 |
1,443 |
{
"copyright": "<NAME>",
"url": "http://robert-kummer.de",
"email": "<EMAIL>",
"gravatar": true,
"format": "html",
"theme": "default"
}
| 65 |
764 |
{"symbol": "NRP","address": "0x3918C42F14F2eB1168365F911f63E540E5A306b5","overview":{"en": ""},"email": "<EMAIL>","website": "https://www.nrp.world/","state": "NORMAL","links": {"blog": "https://medium.com/@info_87830/neural-protocol-nrp-airdrop-ico-37ab1923c9cb","twitter": "https://www.twitter.com/neuralprotocol","telegram": "https://t.me/neuralprotocol","github": "https://github.com/neuralprotocol"}}
| 160 |
1,757 |
<reponame>xiaoheiyo/nonebot2
r"""
权限
====
每个 ``Matcher`` 拥有一个 ``Permission`` ,其中是 **异步** ``PermissionChecker`` 的集合,只要有一个 ``PermissionChecker`` 检查结果为 ``True`` 时就会继续运行。
\:\:\:tip 提示
``PermissionChecker`` 既可以是 async function 也可以是 sync function
\:\:\:
"""
import asyncio
from typing import TYPE_CHECKING, Union, Callable, NoReturn, Optional, Awaitable
from nonebot.utils import run_sync
from nonebot.typing import T_PermissionChecker
if TYPE_CHECKING:
from nonebot.adapters import Bot, Event
class Permission:
"""
:说明:
``Matcher`` 规则类,当事件传递时,在 ``Matcher`` 运行前进行检查。
:示例:
.. code-block:: python
Permission(async_function) | sync_function
# 等价于
from nonebot.utils import run_sync
Permission(async_function, run_sync(sync_function))
"""
__slots__ = ("checkers",)
def __init__(
self, *checkers: Callable[["Bot", "Event"],
Awaitable[bool]]) -> None:
"""
:参数:
* ``*checkers: Callable[[Bot, Event], Awaitable[bool]]``: **异步** PermissionChecker
"""
self.checkers = set(checkers)
"""
:说明:
存储 ``PermissionChecker``
:类型:
* ``Set[Callable[[Bot, Event], Awaitable[bool]]]``
"""
async def __call__(self, bot: "Bot", event: "Event") -> bool:
"""
:说明:
检查是否满足某个权限
:参数:
* ``bot: Bot``: Bot 对象
* ``event: Event``: Event 对象
:返回:
- ``bool``
"""
if not self.checkers:
return True
results = await asyncio.gather(
*map(lambda c: c(bot, event), self.checkers))
return any(results)
def __and__(self, other) -> NoReturn:
raise RuntimeError("And operation between Permissions is not allowed.")
def __or__(
self, other: Optional[Union["Permission",
T_PermissionChecker]]) -> "Permission":
checkers = self.checkers.copy()
if other is None:
return self
elif isinstance(other, Permission):
checkers |= other.checkers
elif asyncio.iscoroutinefunction(other):
checkers.add(other) # type: ignore
else:
checkers.add(run_sync(other))
return Permission(*checkers)
async def _message(bot: "Bot", event: "Event") -> bool:
return event.get_type() == "message"
async def _notice(bot: "Bot", event: "Event") -> bool:
return event.get_type() == "notice"
async def _request(bot: "Bot", event: "Event") -> bool:
return event.get_type() == "request"
async def _metaevent(bot: "Bot", event: "Event") -> bool:
return event.get_type() == "meta_event"
MESSAGE = Permission(_message)
"""
- **说明**: 匹配任意 ``message`` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 message type 的 Matcher。
"""
NOTICE = Permission(_notice)
"""
- **说明**: 匹配任意 ``notice`` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 notice type 的 Matcher。
"""
REQUEST = Permission(_request)
"""
- **说明**: 匹配任意 ``request`` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 request type 的 Matcher。
"""
METAEVENT = Permission(_metaevent)
"""
- **说明**: 匹配任意 ``meta_event`` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 meta_event type 的 Matcher。
"""
def USER(*user: str, perm: Optional[Permission] = None):
"""
:说明:
``event`` 的 ``session_id`` 在白名单内且满足 perm
:参数:
* ``*user: str``: 白名单
* ``perm: Optional[Permission]``: 需要同时满足的权限
"""
async def _user(bot: "Bot", event: "Event") -> bool:
return bool(event.get_session_id() in user and
(perm is None or await perm(bot, event)))
return Permission(_user)
async def _superuser(bot: "Bot", event: "Event") -> bool:
return (event.get_type() == "message" and
event.get_user_id() in bot.config.superusers)
SUPERUSER = Permission(_superuser)
"""
- **说明**: 匹配任意超级用户消息类型事件
"""
| 2,197 |
1,199 |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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.
"""Convert SCAN txt format to standard TSV format."""
from absl import app
from absl import flags
from language.nqg.tasks import tsv_utils
from tensorflow.io import gfile
FLAGS = flags.FLAGS
flags.DEFINE_string("input", "", "Input txt file.")
flags.DEFINE_string("output", "", "Output tsv file.")
def load_examples(filename):
"""Load SCAN examples from original data file."""
examples = []
with gfile.GFile(filename, "r") as input_file:
for line in input_file:
splits = line.split("OUT:")
# Trim "IN:" prefix.
input_string = splits[0][3:].strip()
output_string = splits[1].strip()
examples.append((input_string, output_string))
return examples
def main(unused_argv):
examples = load_examples(FLAGS.input)
tsv_utils.write_tsv(examples, FLAGS.output)
if __name__ == "__main__":
app.run(main)
| 473 |
32,544 |
<filename>patterns/dipmodular/com.baeldung.dip.daoimplementations/module-info.java
module com.baeldung.dip.daoimplementations {
requires com.baeldung.dip.entities;
requires com.baeldung.dip.daos;
provides com.baeldung.dip.daos.CustomerDao with com.baeldung.dip.daoimplementations.SimpleCustomerDao;
exports com.baeldung.dip.daoimplementations;
}
| 153 |
892 |
<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-wjvr-2hjg-6rhj",
"modified": "2022-04-05T00:00:39Z",
"published": "2022-03-30T00:00:24Z",
"aliases": [
"CVE-2022-28143"
],
"details": "A cross-site request forgery (CSRF) vulnerability in Jenkins Proxmox Plugin 0.7.0 and earlier allows attackers to connect to an attacker-specified host using attacker-specified username and password (perform a connection test), disable SSL/TLS validation for the entire Jenkins controller JVM as part of the connection test (see CVE-2022-28142), and test a rollback with attacker-specified parameters.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:N"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-28143"
},
{
"type": "WEB",
"url": "https://www.jenkins.io/security/advisory/2022-03-29/#SECURITY-2082"
},
{
"type": "WEB",
"url": "http://www.openwall.com/lists/oss-security/2022/03/29/1"
}
],
"database_specific": {
"cwe_ids": [
"CWE-352"
],
"severity": "MODERATE",
"github_reviewed": false
}
}
| 550 |
4,262 |
/*
* 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.camel.component.netty.http;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslHandler;
import org.apache.camel.CamelContext;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.netty.NettyConsumer;
import org.apache.camel.component.netty.ServerInitializerFactory;
import org.apache.camel.component.netty.http.handlers.HttpInboundStreamHandler;
import org.apache.camel.component.netty.http.handlers.HttpOutboundStreamHandler;
import org.apache.camel.component.netty.ssl.SSLEngineFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A shared {@link HttpServerInitializerFactory} for a shared Netty HTTP server.
*
* @see NettySharedHttpServer
*/
public class HttpServerSharedInitializerFactory extends HttpServerInitializerFactory {
private static final Logger LOG = LoggerFactory.getLogger(HttpServerSharedInitializerFactory.class);
private final NettySharedHttpServerBootstrapConfiguration configuration;
private final HttpServerConsumerChannelFactory channelFactory;
private final CamelContext camelContext;
private SSLContext sslContext;
public HttpServerSharedInitializerFactory(NettySharedHttpServerBootstrapConfiguration configuration,
HttpServerConsumerChannelFactory channelFactory,
CamelContext camelContext) {
this.configuration = configuration;
this.channelFactory = channelFactory;
// fallback and use default resolver
this.camelContext = camelContext;
try {
this.sslContext = createSSLContext();
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
if (sslContext != null) {
LOG.info("Created SslContext {}", sslContext);
}
}
@Override
public ServerInitializerFactory createPipelineFactory(NettyConsumer nettyConsumer) {
throw new UnsupportedOperationException("Should not call this operation");
}
@Override
protected void initChannel(Channel ch) throws Exception {
// create a new pipeline
ChannelPipeline pipeline = ch.pipeline();
SslHandler sslHandler = configureServerSSLOnDemand();
if (sslHandler != null) {
LOG.debug("Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}", sslHandler);
pipeline.addLast("ssl", sslHandler);
}
pipeline.addLast("decoder", new HttpRequestDecoder(4096, configuration.getMaxHeaderSize(), 8192));
pipeline.addLast("encoder", new HttpResponseEncoder());
if (configuration.isChunked()) {
pipeline.addLast("inbound-streamer", new HttpInboundStreamHandler());
pipeline.addLast("aggregator", new HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
pipeline.addLast("outbound-streamer", new HttpOutboundStreamHandler());
}
if (configuration.isCompression()) {
pipeline.addLast("deflater", new HttpContentCompressor());
}
pipeline.addLast("handler", channelFactory.getChannelHandler());
}
private SSLContext createSSLContext() throws Exception {
if (!configuration.isSsl()) {
return null;
}
SSLContext answer;
// create ssl context once
if (configuration.getSslContextParameters() != null) {
answer = configuration.getSslContextParameters().createSSLContext(null);
} else {
if (configuration.getKeyStoreFile() == null && configuration.getKeyStoreResource() == null) {
LOG.debug("keystorefile is null");
}
if (configuration.getTrustStoreFile() == null && configuration.getTrustStoreResource() == null) {
LOG.debug("truststorefile is null");
}
if (configuration.getPassphrase() == null) {
LOG.debug("passphrase is null");
}
char[] pw = configuration.getPassphrase() != null ? configuration.getPassphrase().toCharArray() : null;
SSLEngineFactory sslEngineFactory;
if (configuration.getKeyStoreFile() != null || configuration.getTrustStoreFile() != null) {
sslEngineFactory = new SSLEngineFactory();
answer = sslEngineFactory.createSSLContext(camelContext,
configuration.getKeyStoreFormat(),
configuration.getSecurityProvider(),
"file:" + configuration.getKeyStoreFile().getPath(),
"file:" + configuration.getTrustStoreFile().getPath(),
pw);
} else {
sslEngineFactory = new SSLEngineFactory();
answer = sslEngineFactory.createSSLContext(camelContext,
configuration.getKeyStoreFormat(),
configuration.getSecurityProvider(),
configuration.getKeyStoreResource(),
configuration.getTrustStoreResource(),
pw);
}
}
return answer;
}
private SslHandler configureServerSSLOnDemand() {
if (!configuration.isSsl()) {
return null;
}
if (configuration.getSslHandler() != null) {
return configuration.getSslHandler();
} else if (sslContext != null) {
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
engine.setNeedClientAuth(configuration.isNeedClientAuth());
if (configuration.getSslContextParameters() == null) {
// just set the enabledProtocols if the SslContextParameter doesn't set
engine.setEnabledProtocols(configuration.getEnabledProtocols().split(","));
}
return new SslHandler(engine);
}
return null;
}
}
| 2,769 |
11,775 |
<filename>jib-cli/src/main/java/com/google/cloud/tools/jib/cli/buildfile/Layers.java
/*
* Copyright 2020 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.tools.jib.cli.buildfile;
import com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath;
import com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer;
import com.google.cloud.tools.jib.api.buildplan.FileEntry;
import com.google.cloud.tools.jib.api.buildplan.FilePermissions;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Verify;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** Class to convert between different layer representations. */
class Layers {
private Layers() {}
/**
* Convert a layer spec to a list of layer objects.
*
* <p>Does not handle missing directories for files added via this method. We can either prefill
* directories here, or allow passing of the file entry information directly to the reproducible
* layer builder
*
* @param buildRoot the directory to resolve relative paths, usually the directory where the build
* config file is located
* @param layersSpec a layersSpec containing configuration for all layers
* @return a {@link List} of {@link FileEntriesLayer} to use as part of a jib container build
* @throws IOException if traversing a directory fails
*/
static List<FileEntriesLayer> toLayers(Path buildRoot, LayersSpec layersSpec) throws IOException {
List<FileEntriesLayer> layers = new ArrayList<>();
FilePropertiesStack filePropertiesStack = new FilePropertiesStack();
// base properties
layersSpec.getProperties().ifPresent(filePropertiesStack::push);
for (LayerSpec entry : layersSpec.getEntries()) {
// each loop is a new layer
if (entry instanceof FileLayerSpec) {
FileEntriesLayer.Builder layerBuiler = FileEntriesLayer.builder();
FileLayerSpec fileLayer = (FileLayerSpec) entry;
layerBuiler.setName(fileLayer.getName());
// layer properties
fileLayer.getProperties().ifPresent(filePropertiesStack::push);
for (CopySpec copySpec : ((FileLayerSpec) entry).getFiles()) {
// copy spec properties
copySpec.getProperties().ifPresent(filePropertiesStack::push);
// relativize all paths to the buildRoot location
Path rawSrc = copySpec.getSrc();
Path src = rawSrc.isAbsolute() ? rawSrc : buildRoot.resolve(rawSrc);
AbsoluteUnixPath dest = copySpec.getDest();
if (!Files.isDirectory(src) && !Files.isRegularFile(src)) {
throw new UnsupportedOperationException(
"Cannot create FileLayers from non-file, non-directory: " + src.toString());
}
if (Files.isRegularFile(src)) { // regular file
if (!copySpec.getExcludes().isEmpty() || !copySpec.getIncludes().isEmpty()) {
throw new UnsupportedOperationException(
"Cannot apply includes/excludes on single file copy directives.");
}
layerBuiler.addEntry(
src,
copySpec.isDestEndsWithSlash() ? dest.resolve(src.getFileName()) : dest,
filePropertiesStack.getFilePermissions(),
filePropertiesStack.getModificationTime(),
filePropertiesStack.getOwnership());
} else if (Files.isDirectory(src)) { // directory
List<PathMatcher> excludes =
copySpec.getExcludes().stream()
.map(Layers::toPathMatcher)
.collect(Collectors.toList());
List<PathMatcher> includes =
copySpec.getIncludes().stream()
.map(Layers::toPathMatcher)
.collect(Collectors.toList());
try (Stream<Path> dirWalk = Files.walk(src)) {
List<Path> filtered =
dirWalk
// filter out against excludes
.filter(path -> excludes.stream().noneMatch(exclude -> exclude.matches(path)))
.filter(
path -> {
// if there are no includes directives, include everything
if (includes.isEmpty()) {
return true;
}
// if there are includes directives, only include those specified
for (PathMatcher matcher : includes) {
if (matcher.matches(path)) {
return true;
}
}
return false;
})
.collect(Collectors.toList());
BiFunction<Path, FilePermissions, FileEntry> newEntry =
(file, permission) ->
new FileEntry(
file,
dest.resolve(src.relativize(file)),
permission,
filePropertiesStack.getModificationTime(),
filePropertiesStack.getOwnership());
Set<Path> addedDirectories = new HashSet<>();
for (Path path : filtered) {
if (!Files.isDirectory(path) && !Files.isRegularFile(path)) {
throw new UnsupportedOperationException(
"Cannot create FileLayers from non-file, non-directory: " + src.toString());
}
if (Files.isDirectory(path)) {
addedDirectories.add(path);
layerBuiler.addEntry(
newEntry.apply(path, filePropertiesStack.getDirectoryPermissions()));
} else if (Files.isRegularFile(path)) {
if (!path.startsWith(src)) {
// if we end up in a situation where the file added is somehow outside of the
// tree then we do not know how to properly handle it at the moment. It could
// be from a link scenario that we do not understand.
throw new IllegalStateException(
src.toString() + " is not a parent of " + path.toString());
}
Path parent = Verify.verifyNotNull(path.getParent());
while (true) {
if (addedDirectories.contains(parent)) {
break;
}
layerBuiler.addEntry(
newEntry.apply(parent, filePropertiesStack.getDirectoryPermissions()));
addedDirectories.add(parent);
if (parent.equals(src)) {
break;
}
parent = Verify.verifyNotNull(parent.getParent());
}
layerBuiler.addEntry(
newEntry.apply(path, filePropertiesStack.getFilePermissions()));
}
}
}
}
copySpec.getProperties().ifPresent(ignored -> filePropertiesStack.pop());
}
fileLayer.getProperties().ifPresent(ignored -> filePropertiesStack.pop());
// TODO: add logging/handling for empty layers
layers.add(layerBuiler.build());
} else {
throw new UnsupportedOperationException("Only FileLayers are supported at this time.");
}
}
layersSpec.getProperties().ifPresent(ignored -> filePropertiesStack.pop());
return layers;
}
@VisibleForTesting
static PathMatcher toPathMatcher(String glob) {
return FileSystems.getDefault()
.getPathMatcher(
"glob:" + ((glob.endsWith("/") || glob.endsWith("\\")) ? glob + "**" : glob));
}
}
| 3,857 |
3,513 |
<filename>src/SHADERed/UI/Debug/AutoUI.cpp<gh_stars>1000+
#include <SHADERed/UI/Debug/AutoUI.h>
#include <SHADERed/Objects/Settings.h>
#include <imgui/imgui.h>
namespace ed {
void DebugAutoUI::OnEvent(const SDL_Event& e)
{
}
void DebugAutoUI::Update(float delta)
{
if (m_update) {
m_value.resize(m_expr.size());
for (int i = 0; i < m_expr.size(); i++) {
spvm_result_t resType = nullptr;
spvm_result_t exprVal = m_data->Debugger.Immediate(std::string(m_expr[i]), resType);
if (exprVal != nullptr && resType != nullptr) {
std::stringstream ss;
m_data->Debugger.GetVariableValueAsString(ss, m_data->Debugger.GetVMImmediate(), resType, exprVal->members, exprVal->member_count, "");
m_value[i] = ss.str();
} else
m_value[i] = "ERROR";
}
m_update = false;
}
// Main window
ImGui::BeginChild("##auto_viewarea", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);
if (ImGui::BeginTable("##auto_tbl", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollFreezeTopRow | ImGuiTableFlags_ScrollY)) {
ImGui::TableSetupColumn("Expression");
ImGui::TableSetupColumn("Value");
ImGui::TableAutoHeaders();
ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0, 0, 0, 0));
for (size_t i = 0; i < m_value.size(); i++) {
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
ImGui::Text("%s", m_expr[i].c_str());
ImGui::TableSetColumnIndex(1);
ImGui::Text("%s", m_value[i].c_str());
}
ImGui::PopStyleColor();
ImGui::EndTable();
}
if (ImGui::GetScrollY() >= ImGui::GetScrollMaxY())
ImGui::SetScrollHereY(1.0f);
ImGui::EndChild();
}
}
| 735 |
21,382 |
<reponame>linyiyue/ray<filename>src/ray/object_manager/plasma/get_request_queue.h<gh_stars>1000+
// Copyright 2017 The Ray 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.
#pragma once
#include "ray/common/asio/instrumented_io_context.h"
#include "ray/common/id.h"
#include "ray/object_manager/plasma/connection.h"
#include "ray/object_manager/plasma/object_lifecycle_manager.h"
namespace plasma {
struct GetRequest;
using ObjectReadyCallback = std::function<void(
const ObjectID &object_id, const std::shared_ptr<GetRequest> &get_request)>;
using AllObjectReadyCallback =
std::function<void(const std::shared_ptr<GetRequest> &get_request)>;
struct GetRequest {
GetRequest(instrumented_io_context &io_context,
const std::shared_ptr<ClientInterface> &client,
const std::vector<ObjectID> &object_ids, bool is_from_worker,
int64_t num_unique_objects_to_wait_for);
/// The client that called get.
std::shared_ptr<ClientInterface> client;
/// The object IDs involved in this request. This is used in the reply.
std::vector<ObjectID> object_ids;
/// The object information for the objects in this request. This is used in
/// the reply.
absl::flat_hash_map<ObjectID, PlasmaObject> objects;
/// The minimum number of objects to wait for in this request.
const int64_t num_unique_objects_to_wait_for;
/// The number of object requests in this wait request that are already
/// satisfied.
int64_t num_unique_objects_satisfied;
/// Whether or not the request comes from the core worker. It is used to track the size
/// of total objects that are consumed by core worker.
const bool is_from_worker;
void AsyncWait(int64_t timeout_ms,
std::function<void(const boost::system::error_code &)> on_timeout);
void CancelTimer();
/// Mark that the get request is removed.
void MarkRemoved();
bool IsRemoved() const;
private:
/// The timer that will time out and cause this wait to return to
/// the client if it hasn't already returned.
boost::asio::steady_timer timer_;
/// Whether or not if this get request is removed.
/// Once the get request is removed, any operation on top of the get request shouldn't
/// happen.
bool is_removed_ = false;
};
class GetRequestQueue {
public:
GetRequestQueue(instrumented_io_context &io_context,
IObjectLifecycleManager &object_lifecycle_mgr,
ObjectReadyCallback object_callback,
AllObjectReadyCallback all_objects_callback)
: io_context_(io_context),
object_lifecycle_mgr_(object_lifecycle_mgr),
object_satisfied_callback_(object_callback),
all_objects_satisfied_callback_(all_objects_callback) {}
/// Add a get request to get request queue. Note this will call callback functions
/// directly if all objects has been satisfied, otherwise store the request
/// in queue.
/// \param client the client where the request comes from.
/// \param object_ids the object ids to get.
/// \param timeout_ms timeout in millisecond, -1 is used to indicate that no timer
/// should be set. \param is_from_worker whether the get request from a worker or not.
/// \param object_callback the callback function called once any object has been
/// satisfied. \param all_objects_callback the callback function called when all objects
/// has been satisfied.
void AddRequest(const std::shared_ptr<ClientInterface> &client,
const std::vector<ObjectID> &object_ids, int64_t timeout_ms,
bool is_from_worker);
/// Remove all of the GetRequests for a given client.
///
/// \param client The client whose GetRequests should be removed.
void RemoveGetRequestsForClient(const std::shared_ptr<ClientInterface> &client);
/// Handle a sealed object, should be called when an object sealed. Mark
/// the object satisfied and call object callbacks.
/// \param object_id the object_id to mark.
void MarkObjectSealed(const ObjectID &object_id);
private:
/// Remove a GetRequest and clean up the relevant data structures.
///
/// \param get_request The GetRequest to remove.
void RemoveGetRequest(const std::shared_ptr<GetRequest> &get_request);
/// Only for tests.
bool IsGetRequestExist(const ObjectID &object_id);
int64_t GetRequestCount(const ObjectID &object_id);
/// Called when objects satisfied. Call get request callback function and
/// remove get request in queue.
/// \param get_request the get request to be completed.
void OnGetRequestCompleted(const std::shared_ptr<GetRequest> &get_request);
instrumented_io_context &io_context_;
/// A hash table mapping object IDs to a vector of the get requests that are
/// waiting for the object to arrive.
absl::flat_hash_map<ObjectID, std::vector<std::shared_ptr<GetRequest>>>
object_get_requests_;
IObjectLifecycleManager &object_lifecycle_mgr_;
ObjectReadyCallback object_satisfied_callback_;
AllObjectReadyCallback all_objects_satisfied_callback_;
friend struct GetRequestQueueTest;
};
} // namespace plasma
| 1,717 |
3,682 |
<filename>python-sqlite-sqlalchemy/project/examples/example_3/app/albums/routes.py
from flask import Blueprint, render_template, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms import HiddenField
from wtforms.validators import InputRequired, ValidationError
from app import db
from app.models import Artist, Album
# Setup the Blueprint
albums_bp = Blueprint(
"albums_bp", __name__, template_folder="templates", static_folder="static"
)
def does_album_exist(form, field):
album = (
db.session.query(Album)
.join(Artist)
.filter(Artist.name == form.artist.data)
.filter(Album.title == field.data)
.one_or_none()
)
if album is not None:
raise ValidationError("Album already exists", field.data)
class CreateAlbumForm(FlaskForm):
artist = HiddenField("artist")
title = StringField(
label="Albums's Name", validators=[InputRequired(), does_album_exist]
)
@albums_bp.route("/albums", methods=["GET", "POST"])
@albums_bp.route("/albums/<int:artist_id>", methods=["GET", "POST"])
def albums(artist_id=None):
form = CreateAlbumForm()
# did we get an artist id?
if artist_id is not None:
# Get the artist
artist = (
db.session.query(Artist)
.filter(Artist.artist_id == artist_id)
.one_or_none()
)
form.artist.data = artist.name
# otherwise, no artist
else:
artist = None
# Is the form valid?
if form.validate_on_submit():
# Create new Album
album = Album(title=form.title.data)
artist.albums.append(album)
db.session.add(artist)
db.session.commit()
return redirect(url_for("albums_bp.albums", artist_id=artist_id))
# Start the query for albums
query = db.session.query(Album)
# Display the albums for the artist passed?
if artist_id is not None:
query = query.filter(Album.artist_id == artist_id)
albums = query.order_by(Album.title).all()
return render_template(
"albums.html", artist=artist, albums=albums, form=form
)
| 857 |
1,338 |
/*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Hewlett-Packard Company makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*
* Copyright (c) 1996,1997
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*/
/* NOTE: This is an internal header file, included by other STL headers.
* You should not attempt to use it directly.
*/
#ifndef __SGI_STL_INTERNAL_UNINITIALIZED_H
#define __SGI_STL_INTERNAL_UNINITIALIZED_H
__STL_BEGIN_NAMESPACE
// uninitialized_copy
// Valid if copy construction is equivalent to assignment, and if the
// destructor is trivial.
template <class _InputIter, class _ForwardIter>
inline _ForwardIter
__uninitialized_copy_aux(_InputIter __first, _InputIter __last,
_ForwardIter __result,
__true_type)
{
return copy(__first, __last, __result);
}
template <class _InputIter, class _ForwardIter>
_ForwardIter
__uninitialized_copy_aux(_InputIter __first, _InputIter __last,
_ForwardIter __result,
__false_type)
{
_ForwardIter __cur = __result;
__STL_TRY {
for ( ; __first != __last; ++__first, ++__cur)
construct(&*__cur, *__first);
return __cur;
}
__STL_UNWIND(destroy(__result, __cur));
}
template <class _InputIter, class _ForwardIter, class _Tp>
inline _ForwardIter
__uninitialized_copy(_InputIter __first, _InputIter __last,
_ForwardIter __result, _Tp*)
{
typedef typename __type_traits<_Tp>::is_POD_type _Is_POD;
return __uninitialized_copy_aux(__first, __last, __result, _Is_POD());
}
template <class _InputIter, class _ForwardIter>
inline _ForwardIter
uninitialized_copy(_InputIter __first, _InputIter __last,
_ForwardIter __result)
{
return __uninitialized_copy(__first, __last, __result,
__VALUE_TYPE(__result));
}
inline char* uninitialized_copy(const char* __first, const char* __last,
char* __result) {
memmove(__result, __first, __last - __first);
return __result + (__last - __first);
}
inline wchar_t*
uninitialized_copy(const wchar_t* __first, const wchar_t* __last,
wchar_t* __result)
{
memmove(__result, __first, sizeof(wchar_t) * (__last - __first));
return __result + (__last - __first);
}
// uninitialized_copy_n (not part of the C++ standard)
template <class _InputIter, class _Size, class _ForwardIter>
pair<_InputIter, _ForwardIter>
__uninitialized_copy_n(_InputIter __first, _Size __count,
_ForwardIter __result,
input_iterator_tag)
{
_ForwardIter __cur = __result;
__STL_TRY {
for ( ; __count > 0 ; --__count, ++__first, ++__cur)
construct(&*__cur, *__first);
return pair<_InputIter, _ForwardIter>(__first, __cur);
}
__STL_UNWIND(destroy(__result, __cur));
}
template <class _RandomAccessIter, class _Size, class _ForwardIter>
inline pair<_RandomAccessIter, _ForwardIter>
__uninitialized_copy_n(_RandomAccessIter __first, _Size __count,
_ForwardIter __result,
random_access_iterator_tag) {
_RandomAccessIter __last = __first + __count;
return pair<_RandomAccessIter, _ForwardIter>(
__last,
uninitialized_copy(__first, __last, __result));
}
template <class _InputIter, class _Size, class _ForwardIter>
inline pair<_InputIter, _ForwardIter>
__uninitialized_copy_n(_InputIter __first, _Size __count,
_ForwardIter __result) {
return __uninitialized_copy_n(__first, __count, __result,
__ITERATOR_CATEGORY(__first));
}
template <class _InputIter, class _Size, class _ForwardIter>
inline pair<_InputIter, _ForwardIter>
uninitialized_copy_n(_InputIter __first, _Size __count,
_ForwardIter __result) {
return __uninitialized_copy_n(__first, __count, __result,
__ITERATOR_CATEGORY(__first));
}
// Valid if copy construction is equivalent to assignment, and if the
// destructor is trivial.
template <class _ForwardIter, class _Tp>
inline void
__uninitialized_fill_aux(_ForwardIter __first, _ForwardIter __last,
const _Tp& __x, __true_type)
{
fill(__first, __last, __x);
}
template <class _ForwardIter, class _Tp>
void
__uninitialized_fill_aux(_ForwardIter __first, _ForwardIter __last,
const _Tp& __x, __false_type)
{
_ForwardIter __cur = __first;
__STL_TRY {
for ( ; __cur != __last; ++__cur)
construct(&*__cur, __x);
}
__STL_UNWIND(destroy(__first, __cur));
}
template <class _ForwardIter, class _Tp, class _Tp1>
inline void __uninitialized_fill(_ForwardIter __first,
_ForwardIter __last, const _Tp& __x, _Tp1*)
{
typedef typename __type_traits<_Tp1>::is_POD_type _Is_POD;
__uninitialized_fill_aux(__first, __last, __x, _Is_POD());
}
template <class _ForwardIter, class _Tp>
inline void uninitialized_fill(_ForwardIter __first,
_ForwardIter __last,
const _Tp& __x)
{
__uninitialized_fill(__first, __last, __x, __VALUE_TYPE(__first));
}
// Valid if copy construction is equivalent to assignment, and if the
// destructor is trivial.
template <class _ForwardIter, class _Size, class _Tp>
inline _ForwardIter
__uninitialized_fill_n_aux(_ForwardIter __first, _Size __n,
const _Tp& __x, __true_type)
{
return fill_n(__first, __n, __x);
}
template <class _ForwardIter, class _Size, class _Tp>
_ForwardIter
__uninitialized_fill_n_aux(_ForwardIter __first, _Size __n,
const _Tp& __x, __false_type)
{
_ForwardIter __cur = __first;
__STL_TRY {
for ( ; __n > 0; --__n, ++__cur)
construct(&*__cur, __x);
return __cur;
}
__STL_UNWIND(destroy(__first, __cur));
}
template <class _ForwardIter, class _Size, class _Tp, class _Tp1>
inline _ForwardIter
__uninitialized_fill_n(_ForwardIter __first, _Size __n, const _Tp& __x, _Tp1*)
{
typedef typename __type_traits<_Tp1>::is_POD_type _Is_POD;
return __uninitialized_fill_n_aux(__first, __n, __x, _Is_POD());
}
template <class _ForwardIter, class _Size, class _Tp>
inline _ForwardIter
uninitialized_fill_n(_ForwardIter __first, _Size __n, const _Tp& __x)
{
return __uninitialized_fill_n(__first, __n, __x, __VALUE_TYPE(__first));
}
// Extensions: __uninitialized_copy_copy, __uninitialized_copy_fill,
// __uninitialized_fill_copy.
// __uninitialized_copy_copy
// Copies [first1, last1) into [result, result + (last1 - first1)), and
// copies [first2, last2) into
// [result, result + (last1 - first1) + (last2 - first2)).
template <class _InputIter1, class _InputIter2, class _ForwardIter>
inline _ForwardIter
__uninitialized_copy_copy(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_ForwardIter __result)
{
_ForwardIter __mid = uninitialized_copy(__first1, __last1, __result);
__STL_TRY {
return uninitialized_copy(__first2, __last2, __mid);
}
__STL_UNWIND(destroy(__result, __mid));
}
// __uninitialized_fill_copy
// Fills [result, mid) with x, and copies [first, last) into
// [mid, mid + (last - first)).
template <class _ForwardIter, class _Tp, class _InputIter>
inline _ForwardIter
__uninitialized_fill_copy(_ForwardIter __result, _ForwardIter __mid,
const _Tp& __x,
_InputIter __first, _InputIter __last)
{
uninitialized_fill(__result, __mid, __x);
__STL_TRY {
return uninitialized_copy(__first, __last, __mid);
}
__STL_UNWIND(destroy(__result, __mid));
}
// __uninitialized_copy_fill
// Copies [first1, last1) into [first2, first2 + (last1 - first1)), and
// fills [first2 + (last1 - first1), last2) with x.
template <class _InputIter, class _ForwardIter, class _Tp>
inline void
__uninitialized_copy_fill(_InputIter __first1, _InputIter __last1,
_ForwardIter __first2, _ForwardIter __last2,
const _Tp& __x)
{
_ForwardIter __mid2 = uninitialized_copy(__first1, __last1, __first2);
__STL_TRY {
uninitialized_fill(__mid2, __last2, __x);
}
__STL_UNWIND(destroy(__first2, __mid2));
}
__STL_END_NAMESPACE
#endif /* __SGI_STL_INTERNAL_UNINITIALIZED_H */
// Local Variables:
// mode:C++
// End:
| 3,736 |
1,253 |
def decimal_to_binary(n):
if n > 1: decimal_to_binary(n//2)
print(n % 2, end = '')
try: decimal_to_binary(int(input("Enter an Integer to Covert into Binary: ")))
except ValueError: print("Input is not an integer.")
print()
| 84 |
541 |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.rest;
import static com.jayway.jsonpath.JsonPath.read;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath;
import static junit.framework.TestCase.assertEquals;
import static org.dspace.app.rest.matcher.MetadataMatcher.matchMetadata;
import static org.dspace.app.rest.matcher.MetadataMatcher.matchMetadataNotEmpty;
import static org.dspace.app.rest.matcher.MetadataMatcher.matchMetadataStringEndsWith;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.springframework.data.rest.webmvc.RestMediaTypes.TEXT_URI_LIST_VALUE;
import static org.springframework.http.MediaType.parseMediaType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.dspace.app.rest.converter.CommunityConverter;
import org.dspace.app.rest.matcher.CollectionMatcher;
import org.dspace.app.rest.matcher.CommunityMatcher;
import org.dspace.app.rest.matcher.HalMatcher;
import org.dspace.app.rest.matcher.MetadataMatcher;
import org.dspace.app.rest.matcher.PageMatcher;
import org.dspace.app.rest.model.CommunityRest;
import org.dspace.app.rest.model.GroupRest;
import org.dspace.app.rest.model.MetadataRest;
import org.dspace.app.rest.model.MetadataValueRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.test.AbstractControllerIntegrationTest;
import org.dspace.app.rest.test.MetadataPatchSuite;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.authorize.service.ResourcePolicyService;
import org.dspace.builder.CollectionBuilder;
import org.dspace.builder.CommunityBuilder;
import org.dspace.builder.EPersonBuilder;
import org.dspace.builder.GroupBuilder;
import org.dspace.builder.ResourcePolicyBuilder;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.service.CommunityService;
import org.dspace.core.Constants;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.eperson.service.GroupService;
import org.dspace.services.ConfigurationService;
import org.hamcrest.Matchers;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
/**
* Integration Tests against the /api/core/communities endpoint (including any subpaths)
*/
public class CommunityRestRepositoryIT extends AbstractControllerIntegrationTest {
@Autowired
CommunityConverter communityConverter;
@Autowired
CommunityService communityService;
@Autowired
AuthorizeService authorizeService;
@Autowired
ResourcePolicyService resoucePolicyService;
@Autowired
private ConfigurationService configurationService;
@Autowired
private GroupService groupService;
private Community topLevelCommunityA;
private Community subCommunityA;
private Community communityB;
private Community communityC;
private Collection collectionA;
private EPerson topLevelCommunityAAdmin;
private EPerson subCommunityAAdmin;
private EPerson collectionAdmin;
private EPerson submitter;
@Test
public void createTest() throws Exception {
ObjectMapper mapper = new ObjectMapper();
CommunityRest comm = new CommunityRest();
CommunityRest commNoembeds = new CommunityRest();
// We send a name but the created community should set this to the title
comm.setName("Test Top-Level Community");
commNoembeds.setName("Test Top-Level Community Full");
MetadataRest metadataRest = new MetadataRest();
MetadataValueRest description = new MetadataValueRest();
description.setValue("<p>Some cool HTML code here</p>");
metadataRest.put("dc.description", description);
MetadataValueRest abs = new MetadataValueRest();
abs.setValue("Sample top-level community created via the REST API");
metadataRest.put("dc.description.abstract", abs);
MetadataValueRest contents = new MetadataValueRest();
contents.setValue("<p>HTML News</p>");
metadataRest.put("dc.description.tableofcontents", contents);
MetadataValueRest copyright = new MetadataValueRest();
copyright.setValue("Custom Copyright Text");
metadataRest.put("dc.rights", copyright);
MetadataValueRest title = new MetadataValueRest();
title.setValue("Title Text");
metadataRest.put("dc.title", title);
comm.setMetadata(metadataRest);
commNoembeds.setMetadata(metadataRest);
String authToken = getAuthToken(admin.getEmail(), password);
// Capture the UUID of the created Community (see andDo() below)
AtomicReference<UUID> idRef = new AtomicReference<>();
AtomicReference<UUID> idRefNoEmbeds = new AtomicReference<>();
AtomicReference<String> handle = new AtomicReference<>();
try {
getClient(authToken).perform(post("/api/core/communities")
.content(mapper.writeValueAsBytes(comm))
.contentType(contentType)
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isCreated())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", CommunityMatcher.matchNonAdminEmbeds()))
.andExpect(jsonPath("$", Matchers.allOf(
hasJsonPath("$.id", not(empty())),
hasJsonPath("$.uuid", not(empty())),
hasJsonPath("$.name", is("Title Text")),
hasJsonPath("$.handle", not(empty())),
hasJsonPath("$.type", is("community")),
hasJsonPath("$._links.collections.href", not(empty())),
hasJsonPath("$._links.logo.href", not(empty())),
hasJsonPath("$._links.subcommunities.href", not(empty())),
hasJsonPath("$._links.self.href", not(empty())),
hasJsonPath("$.metadata", Matchers.allOf(
matchMetadata("dc.description", "<p>Some cool HTML code here</p>"),
matchMetadata("dc.description.abstract",
"Sample top-level community created via the REST API"),
matchMetadata("dc.description.tableofcontents", "<p>HTML News</p>"),
matchMetadata("dc.rights", "Custom Copyright Text"),
matchMetadata("dc.title", "Title Text")
)
)
)))
// capture "handle" returned in JSON response and check against the metadata
.andDo(result -> handle.set(
read(result.getResponse().getContentAsString(), "$.handle")))
.andExpect(jsonPath("$",
hasJsonPath("$.metadata", Matchers.allOf(
matchMetadataNotEmpty("dc.identifier.uri"),
matchMetadataStringEndsWith("dc.identifier.uri", handle.get())
)
)))
// capture "id" returned in JSON response
.andDo(result -> idRef
.set(UUID.fromString(read(result.getResponse().getContentAsString(), "$.id"))));
getClient(authToken).perform(post("/api/core/communities")
.content(mapper.writeValueAsBytes(commNoembeds))
.contentType(contentType))
.andExpect(status().isCreated())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", HalMatcher.matchNoEmbeds()))
.andDo(result -> idRefNoEmbeds
.set(UUID.fromString(read(result.getResponse().getContentAsString(), "$.id"))));
} finally {
// Delete the created community (cleanup after ourselves!)
CommunityBuilder.deleteCommunity(idRef.get());
CommunityBuilder.deleteCommunity(idRefNoEmbeds.get());
}
}
@Test
public void createSubCommunityUnAuthorizedTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
// Create a parent community to POST a new sub-community to
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
context.restoreAuthSystemState();
ObjectMapper mapper = new ObjectMapper();
CommunityRest comm = new CommunityRest();
// We send a name but the created community should set this to the title
comm.setName("Test Sub-Level Community");
// Anonymous user tries to create a community.
// Should fail because user is not authenticated. Error 401.
getClient().perform(post("/api/core/communities")
.content(mapper.writeValueAsBytes(comm))
.param("parent", parentCommunity.getID().toString())
.contentType(contentType))
.andExpect(status().isUnauthorized());
// Non-admin Eperson tries to create a community.
// Should fail because user doesn't have permissions. Error 403.
String authToken = getAuthToken(eperson.getEmail(), password);
getClient(authToken).perform(post("/api/core/communities")
.content(mapper.writeValueAsBytes(comm))
.param("parent", parentCommunity.getID().toString())
.contentType(contentType))
.andExpect(status().isForbidden());
}
@Test
public void createSubCommunityAuthorizedTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
// Create a parent community to POST a new sub-community to
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
// ADD authorization on parent community
context.setCurrentUser(eperson);
authorizeService.addPolicy(context, parentCommunity, Constants.ADD, eperson);
context.restoreAuthSystemState();
String authToken = getAuthToken(eperson.getEmail(), password);
ObjectMapper mapper = new ObjectMapper();
CommunityRest comm = new CommunityRest();
// We send a name but the created community should set this to the title
comm.setName("Test Sub-Level Community");
comm.setMetadata(new MetadataRest()
.put("dc.description",
new MetadataValueRest("<p>Some cool HTML code here</p>"))
.put("dc.description.abstract",
new MetadataValueRest("Sample top-level community created via the REST API"))
.put("dc.description.tableofcontents",
new MetadataValueRest("<p>HTML News</p>"))
.put("dc.rights",
new MetadataValueRest("Custom Copyright Text"))
.put("dc.title",
new MetadataValueRest("Title Text")));
// Capture the UUID and Handle of the created Community (see andDo() below)
AtomicReference<UUID> idRef = new AtomicReference<>();
AtomicReference<String> handle = new AtomicReference<>();
try {
getClient(authToken).perform(post("/api/core/communities")
.content(mapper.writeValueAsBytes(comm))
.param("parent", parentCommunity.getID().toString())
.contentType(contentType))
.andExpect(status().isCreated())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", Matchers.allOf(
hasJsonPath("$.id", not(empty())),
hasJsonPath("$.uuid", not(empty())),
hasJsonPath("$.name", is("Title Text")),
hasJsonPath("$.handle", not(empty())),
hasJsonPath("$.type", is("community")),
hasJsonPath("$._links.collections.href", not(empty())),
hasJsonPath("$._links.logo.href", not(empty())),
hasJsonPath("$._links.subcommunities.href", not(empty())),
hasJsonPath("$._links.self.href", not(empty())),
hasJsonPath("$.metadata", Matchers.allOf(
MetadataMatcher.matchMetadata("dc.description",
"<p>Some cool HTML code here</p>"),
MetadataMatcher.matchMetadata("dc.description.abstract",
"Sample top-level community created via the REST API"),
MetadataMatcher.matchMetadata("dc.description.tableofcontents",
"<p>HTML News</p>"),
MetadataMatcher.matchMetadata("dc.rights",
"Custom Copyright Text"),
MetadataMatcher.matchMetadata("dc.title",
"Title Text")
)
)
)))
// capture "handle" returned in JSON response and check against the metadata
.andDo(result -> handle.set(
read(result.getResponse().getContentAsString(), "$.handle")))
.andExpect(jsonPath("$",
hasJsonPath("$.metadata", Matchers.allOf(
matchMetadataNotEmpty("dc.identifier.uri"),
matchMetadataStringEndsWith("dc.identifier.uri", handle.get())
)
)))
// capture "id" returned in JSON response
.andDo(result -> idRef
.set(UUID.fromString(read(result.getResponse().getContentAsString(), "$.id"))));
} finally {
// Delete the created community (cleanup after ourselves!)
CommunityBuilder.deleteCommunity(idRef.get());
}
}
@Test
public void createUnauthorizedTest() throws Exception {
context.turnOffAuthorisationSystem();
ObjectMapper mapper = new ObjectMapper();
CommunityRest comm = new CommunityRest();
comm.setName("Test Top-Level Community");
MetadataRest metadataRest = new MetadataRest();
MetadataValueRest title = new MetadataValueRest();
title.setValue("Title Text");
metadataRest.put("dc.title", title);
comm.setMetadata(metadataRest);
context.restoreAuthSystemState();
// Anonymous user tries to create a community.
// Should fail because user is not authenticated. Error 401.
getClient().perform(post("/api/core/communities")
.content(mapper.writeValueAsBytes(comm))
.contentType(contentType))
.andExpect(status().isUnauthorized());
// Non-admin Eperson tries to create a community.
// Should fail because user doesn't have permissions. Error 403.
String authToken = getAuthToken(eperson.getEmail(), password);
getClient(authToken).perform(post("/api/core/communities")
.content(mapper.writeValueAsBytes(comm))
.contentType(contentType))
.andExpect(status().isForbidden());
}
@Test
public void findAllTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities")
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle()),
CommunityMatcher
.matchCommunityEntryNonAdminEmbeds(child1.getName(), child1.getID(), child1.getHandle())
)))
.andExpect(jsonPath("$._links.self.href", Matchers.containsString("/api/core/communities")))
.andExpect(jsonPath("$.page.size", is(20)))
.andExpect(jsonPath("$.page.totalElements", is(2)))
;
}
@Test
public void findOneTestWithEmbedsNoPageSize() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with 10 sub-communities
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child0 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 0")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 1")
.build();
Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 2")
.build();
Community child3 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 3")
.build();
Community child4 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 4")
.build();
Community child5 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 5")
.build();
Community child6 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 6")
.build();
Community child7 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 7")
.build();
Community child8 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 8")
.build();
Community child9 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 9")
.build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/" + parentCommunity.getID())
.param("embed", "subcommunities"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", CommunityMatcher.matchCommunity(parentCommunity)))
.andExpect(
jsonPath("$._embedded.subcommunities._embedded.subcommunities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunity(child0),
CommunityMatcher.matchCommunity(child1),
CommunityMatcher.matchCommunity(child2),
CommunityMatcher.matchCommunity(child3),
CommunityMatcher.matchCommunity(child4),
CommunityMatcher.matchCommunity(child5),
CommunityMatcher.matchCommunity(child6),
CommunityMatcher.matchCommunity(child7),
CommunityMatcher.matchCommunity(child8),
CommunityMatcher.matchCommunity(child9)
)))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID())))
.andExpect(jsonPath("$._embedded.subcommunities.page.size", is(20)))
.andExpect(jsonPath("$._embedded.subcommunities.page.totalElements", is(10)));
}
@Test
public void findOneTestWithEmbedsWithPageSize() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with 10 sub-communities
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child0 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 0")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 1")
.build();
Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 2")
.build();
Community child3 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 3")
.build();
Community child4 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 4")
.build();
Community child5 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 5")
.build();
Community child6 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 6")
.build();
Community child7 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 7")
.build();
Community child8 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 8")
.build();
Community child9 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 9")
.build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/" + parentCommunity.getID())
.param("embed", "subcommunities")
.param("embed.size", "subcommunities=5"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", CommunityMatcher.matchCommunity(parentCommunity)))
.andExpect(
jsonPath("$._embedded.subcommunities._embedded.subcommunities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunity(child0),
CommunityMatcher.matchCommunity(child1),
CommunityMatcher.matchCommunity(child2),
CommunityMatcher.matchCommunity(child3),
CommunityMatcher.matchCommunity(child4)
)))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID())))
.andExpect(jsonPath("$._embedded.subcommunities.page.size", is(5)))
.andExpect(jsonPath("$._embedded.subcommunities.page.totalElements", is(10)));
}
@Test
public void findOneTestWithEmbedsWithInvalidPageSize() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with 10 sub-communities
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child0 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 0")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 1")
.build();
Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 2")
.build();
Community child3 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 3")
.build();
Community child4 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 4")
.build();
Community child5 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 5")
.build();
Community child6 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 6")
.build();
Community child7 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 7")
.build();
Community child8 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 8")
.build();
Community child9 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 9")
.build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/" + parentCommunity.getID())
.param("embed", "subcommunities")
.param("embed.size", "subcommunities=invalidPage"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", CommunityMatcher.matchCommunity(parentCommunity)))
.andExpect(
jsonPath("$._embedded.subcommunities._embedded.subcommunities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunity(child0),
CommunityMatcher.matchCommunity(child1),
CommunityMatcher.matchCommunity(child2),
CommunityMatcher.matchCommunity(child3),
CommunityMatcher.matchCommunity(child4),
CommunityMatcher.matchCommunity(child5),
CommunityMatcher.matchCommunity(child6),
CommunityMatcher.matchCommunity(child7),
CommunityMatcher.matchCommunity(child8),
CommunityMatcher.matchCommunity(child9)
)))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID())))
.andExpect(jsonPath("$._embedded.subcommunities.page.size", is(20)))
.andExpect(jsonPath("$._embedded.subcommunities.page.totalElements", is(10)));
}
@Test
public void findAllNoDuplicatesOnMultipleCommunityTitlesTest() throws Exception {
context.turnOffAuthorisationSystem();
List<String> titles = Arrays.asList("First title", "Second title", "Third title", "Fourth title");
parentCommunity = CommunityBuilder.createCommunity(context)
.withName(titles.get(0))
.withTitle(titles.get(1))
.withTitle(titles.get(2))
.withTitle(titles.get(3))
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities").param("size", "2")
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunityEntryMultipleTitles(titles, parentCommunity.getID(),
parentCommunity.getHandle()),
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(child1.getName(), child1.getID(),
child1.getHandle())
)))
.andExpect(jsonPath("$._links.self.href", Matchers.containsString("/api/core/communities")))
.andExpect(jsonPath("$.page.totalElements", is(2)))
.andExpect(jsonPath("$.page.totalPages", is(1)));
}
@Test
public void findAllNoDuplicatesOnMultipleCommunityTitlesPaginationTest() throws Exception {
context.turnOffAuthorisationSystem();
List<String> titles = Arrays.asList("First title", "Second title", "Third title", "Fourth title");
parentCommunity = CommunityBuilder.createCommunity(context)
.withName(titles.get(0))
.withTitle(titles.get(1))
.withTitle(titles.get(2))
.withTitle(titles.get(3))
.build();
Community childCommunity = CommunityBuilder.createSubCommunity(context, parentCommunity).withName("test")
.build();
Community secondParentCommunity = CommunityBuilder.createCommunity(context).withName("testing").build();
Community thirdParentCommunity = CommunityBuilder.createCommunity(context).withName("testingTitleTwo").build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities").param("size", "2")
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunityEntryMultipleTitles(titles, parentCommunity.getID(),
parentCommunity.getHandle()),
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(childCommunity.getName(),
childCommunity.getID(),
childCommunity.getHandle())
)))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities")))
.andExpect(jsonPath("$.page", PageMatcher.pageEntryWithTotalPagesAndElements(0, 2,
2, 4)));
getClient().perform(get("/api/core/communities").param("size", "2").param("page", "1")
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(secondParentCommunity.getName(),
secondParentCommunity.getID(),
secondParentCommunity.getHandle()),
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(thirdParentCommunity.getName(),
thirdParentCommunity.getID(),
thirdParentCommunity.getHandle())
)))
.andExpect(jsonPath("$._links.self.href", Matchers.containsString("/api/core/communities")))
.andExpect(jsonPath("$.page", PageMatcher.pageEntryWithTotalPagesAndElements(1, 2,
2, 4)));
}
@Test
public void findAllNoNameCommunityIsReturned() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context).withName("test").build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities")
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.contains(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle())
)))
.andExpect(jsonPath("$._links.self.href", Matchers.containsString("/api/core/communities")))
.andExpect(jsonPath("$.page.totalElements", is(1)));
}
@Test
public void findAllCommunitiesAreReturnedInCorrectOrder() throws Exception {
// The hibernate query for finding all communities is "SELECT ... ORDER BY STR(dc_title.value)"
// So the communities should be returned in alphabetical order
context.turnOffAuthorisationSystem();
List<String> orderedTitles = Arrays.asList("Abc", "Bcd", "Cde");
Community community1 = CommunityBuilder.createCommunity(context)
.withName(orderedTitles.get(0))
.build();
Community community2 = CommunityBuilder.createCommunity(context)
.withName(orderedTitles.get(1))
.build();
Community community3 = CommunityBuilder.createCommunity(context)
.withName(orderedTitles.get(2))
.build();
context.restoreAuthSystemState();
ObjectMapper mapper = new ObjectMapper();
MvcResult result = getClient().perform(get("/api/core/communities")).andReturn();
String response = result.getResponse().getContentAsString();
JSONArray communities = new JSONObject(response).getJSONObject("_embedded").getJSONArray("communities");
List<String> responseTitles = StreamSupport.stream(communities.spliterator(), false)
.map(JSONObject.class::cast)
.map(x -> x.getString("name"))
.collect(Collectors.toList());
assertEquals(orderedTitles, responseTitles);
}
@Test
public void findAllPaginationTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities")
.param("size", "1")
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.contains(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle())
)))
.andExpect(jsonPath("$._embedded.communities", Matchers.not(
Matchers.contains(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(child1.getName(), child1.getID(),
child1.getHandle())
)
)))
.andExpect(jsonPath("$._links.first.href", Matchers.allOf(
Matchers.containsString("/api/core/communities?"),
Matchers.containsString("page=0"), Matchers.containsString("size=1"))))
.andExpect(jsonPath("$._links.self.href", Matchers.allOf(
Matchers.containsString("/api/core/communities?"),
Matchers.containsString("size=1"))))
.andExpect(jsonPath("$._links.next.href", Matchers.allOf(
Matchers.containsString("/api/core/communities?"),
Matchers.containsString("page=1"), Matchers.containsString("size=1"))))
.andExpect(jsonPath("$._links.last.href", Matchers.allOf(
Matchers.containsString("/api/core/communities?"),
Matchers.containsString("page=1"), Matchers.containsString("size=1"))))
.andExpect(jsonPath("$.page.size", is(1)))
.andExpect(jsonPath("$.page.totalPages", is(2)))
.andExpect(jsonPath("$.page.number", is(0)))
.andExpect(jsonPath("$.page.totalElements", is(2)))
;
getClient().perform(get("/api/core/communities")
.param("size", "1")
.param("page", "1")
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.contains(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(child1.getName(), child1.getID(),
child1.getHandle())
)))
.andExpect(jsonPath("$._embedded.communities", Matchers.not(
Matchers.contains(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle())
)
)))
.andExpect(jsonPath("$._links.first.href", Matchers.allOf(
Matchers.containsString("/api/core/communities?"),
Matchers.containsString("page=0"), Matchers.containsString("size=1"))))
.andExpect(jsonPath("$._links.prev.href", Matchers.allOf(
Matchers.containsString("/api/core/communities?"),
Matchers.containsString("page=0"), Matchers.containsString("size=1"))))
.andExpect(jsonPath("$._links.self.href", Matchers.allOf(
Matchers.containsString("/api/core/communities?"),
Matchers.containsString("page=1"), Matchers.containsString("size=1"))))
.andExpect(jsonPath("$._links.last.href", Matchers.allOf(
Matchers.containsString("/api/core/communities?"),
Matchers.containsString("page=1"), Matchers.containsString("size=1"))))
.andExpect(jsonPath("$.page.number", is(1)))
.andExpect(jsonPath("$.page.totalPages", is(2)))
.andExpect(jsonPath("$.page.size", is(1)))
.andExpect(jsonPath("$.page.totalElements", is(2)))
;
}
@Test
public void findAllUnAuthenticatedTest() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 2")
.build();
resoucePolicyService.removePolicies(context, parentCommunity, Constants.READ);
resoucePolicyService.removePolicies(context, child1, Constants.READ);
context.restoreAuthSystemState();
// anonymous can see only public communities
getClient().perform(get("/api/core/communities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.contains(
CommunityMatcher.matchCommunity(child2))))
.andExpect(jsonPath("$.page.totalElements", is(1)));
}
@Test
public void findAllForbiddenTest() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 2")
.build();
resoucePolicyService.removePolicies(context, parentCommunity, Constants.READ);
resoucePolicyService.removePolicies(context, child1, Constants.READ);
context.restoreAuthSystemState();
String tokenEperson = getAuthToken(eperson.getEmail(), password);
getClient(tokenEperson).perform(get("/api/core/communities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.contains(
CommunityMatcher.matchCommunity(child2))))
.andExpect(jsonPath("$.page.totalElements", is(1)));
}
@Test
public void findAllGrantAccessAdminsTest() throws Exception {
context.turnOffAuthorisationSystem();
EPerson parentAdmin = EPersonBuilder.createEPerson(context)
.withEmail("<EMAIL>")
.withPassword("<PASSWORD>")
.build();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withAdminGroup(parentAdmin)
.build();
EPerson child1Admin = EPersonBuilder.createEPerson(context)
.withEmail("<EMAIL>")
.withPassword("<PASSWORD>")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 1")
.withAdminGroup(child1Admin)
.build();
Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 2")
.build();
resoucePolicyService.removePolicies(context, parentCommunity, Constants.READ);
resoucePolicyService.removePolicies(context, child1, Constants.READ);
context.restoreAuthSystemState();
String tokenParentAdmin = getAuthToken(parentAdmin.getEmail(), "<PASSWORD>");
getClient(tokenParentAdmin).perform(get("/api/core/communities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunity(parentCommunity),
CommunityMatcher.matchCommunity(child1),
CommunityMatcher.matchCommunity(child2))))
.andExpect(jsonPath("$.page.totalElements", is(3)));
String tokenChild1Admin = getAuthToken(child1Admin.getEmail(), "<PASSWORD>");
getClient(tokenChild1Admin).perform(get("/api/core/communities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunity(child1),
CommunityMatcher.matchCommunity(child2))))
.andExpect(jsonPath("$.page.totalElements", is(2)));
}
@Test
public void findOneTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
context.restoreAuthSystemState();
// When full projection is requested, response should include expected properties, links, and embeds.
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", CommunityMatcher.matchNonAdminEmbeds()))
.andExpect(jsonPath("$", CommunityMatcher.matchCommunityEntry(
parentCommunity.getName(), parentCommunity.getID(), parentCommunity.getHandle())));
// When no projection is requested, response should include expected properties, links, and no embeds.
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", HalMatcher.matchNoEmbeds()))
.andExpect(jsonPath("$", CommunityMatcher.matchLinks(parentCommunity.getID())))
.andExpect(jsonPath("$", CommunityMatcher.matchProperties(
parentCommunity.getName(), parentCommunity.getID(), parentCommunity.getHandle())));
}
@Test
public void findOneFullProjectionTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
context.restoreAuthSystemState();
String adminToken = getAuthToken(admin.getEmail(), password);
getClient(adminToken).perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("projection", "full"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", CommunityMatcher.matchCommunityEntryFullProjection(
parentCommunity.getName(), parentCommunity.getID(), parentCommunity.getHandle())));
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("projection", "full"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", Matchers.not(CommunityMatcher.matchCommunityEntryFullProjection(
parentCommunity.getName(), parentCommunity.getID(), parentCommunity.getHandle()))));
}
@Test
public void findOneUnAuthenticatedTest() throws Exception {
context.turnOffAuthorisationSystem();
Community privateCommunity = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Private Community")
.build();
resoucePolicyService.removePolicies(context, privateCommunity, Constants.READ);
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/" + privateCommunity.getID().toString()))
.andExpect(status().isUnauthorized());
}
@Test
public void findOneForbiddenTest() throws Exception {
context.turnOffAuthorisationSystem();
Community privateCommunity = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Private Community")
.build();
resoucePolicyService.removePolicies(context, privateCommunity, Constants.READ);
context.restoreAuthSystemState();
String tokenEperson = getAuthToken(eperson.getEmail(), password);
getClient(tokenEperson).perform(get("/api/core/communities/" + privateCommunity.getID().toString()))
.andExpect(status().isForbidden());
}
@Test
public void findOneGrantAccessAdminsTest() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withAdminGroup(eperson)
.build();
EPerson privateCommunityAdmin = EPersonBuilder.createEPerson(context)
.withEmail("<EMAIL>")
.withPassword("<PASSWORD>")
.build();
Community privateCommunity = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.withAdminGroup(privateCommunityAdmin)
.build();
EPerson privateCommunityAdmin2 = EPersonBuilder.createEPerson(context)
.withEmail("<EMAIL>")
.withPassword("<PASSWORD>")
.build();
Community privateCommunity2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 2")
.withAdminGroup(privateCommunityAdmin2)
.build();
resoucePolicyService.removePolicies(context, privateCommunity, Constants.READ);
context.restoreAuthSystemState();
String tokenParentComunityAdmin = getAuthToken(eperson.getEmail(), password);
getClient(tokenParentComunityAdmin).perform(get("/api/core/communities/" + privateCommunity.getID().toString()))
.andExpect(status().isOk())
.andExpect(jsonPath("$", Matchers.is(CommunityMatcher.matchCommunity(privateCommunity))));
String tokenCommunityAdmin = getAuthToken(privateCommunityAdmin.getEmail(), "<PASSWORD>");
getClient(tokenCommunityAdmin).perform(get("/api/core/communities/" + privateCommunity.getID().toString()))
.andExpect(status().isOk())
.andExpect(jsonPath("$", Matchers.is(CommunityMatcher.matchCommunity(privateCommunity))));
String tokenComunityAdmin2 = getAuthToken(privateCommunityAdmin2.getEmail(), "<PASSWORD>");
getClient(tokenComunityAdmin2).perform(get("/api/core/communities/"
+ privateCommunity.getID().toString()))
.andExpect(status().isForbidden());
}
@Test
public void findOneRelsTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle())
)))
.andExpect(jsonPath("$", Matchers.not(
Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(child1.getName(), child1.getID(),
child1.getHandle())
)
)))
.andExpect(jsonPath("$._links.self.href", Matchers
.containsString("/api/core/communities/" + parentCommunity.getID().toString())))
.andExpect(jsonPath("$._links.logo.href", Matchers
.containsString("/api/core/communities/" + parentCommunity.getID().toString() + "/logo")))
.andExpect(jsonPath("$._links.collections.href", Matchers
.containsString("/api/core/communities/" + parentCommunity.getID().toString() + "/collections")))
.andExpect(jsonPath("$._links.subcommunities.href", Matchers
.containsString("/api/core/communities/" + parentCommunity.getID().toString() +
"/subcommunities")))
;
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString() + "/logo"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType));
getClient().perform(get("/api/core/communities/" + child1.getID().toString() + "/logo"))
.andExpect(status().isNoContent());
//Main community has no collections
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString() + "/collections"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.page.totalElements", is(0)));
getClient().perform(get("/api/core/communities/" + child1.getID().toString() + "/collections"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType));
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString() + "/subcommunities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType));
//child1 subcommunity has no subcommunities, therefore contentType is not set
getClient().perform(get("/api/core/communities/" + child1.getID().toString() + "/subcommunities"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.page.totalElements", is(0)));
}
@Test
public void findAllSearchTop() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.build();
Community parentCommunity2 = CommunityBuilder.createCommunity(context)
.withName("Parent Community 2")
.withLogo("SomeTest")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Community child12 = CommunityBuilder.createSubCommunity(context, child1)
.withName("Sub Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/search/top")
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle()),
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity2.getName(),
parentCommunity2.getID(),
parentCommunity2.getHandle())
)))
.andExpect(jsonPath("$._embedded.communities", Matchers.not(Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(child1.getName(), child1.getID(),
child1.getHandle()),
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(child12.getName(), child12.getID(),
child12.getHandle())
))))
.andExpect(
jsonPath("$._links.self.href", Matchers.containsString("/api/core/communities/search/top")))
.andExpect(jsonPath("$.page.size", is(20)))
.andExpect(jsonPath("$.page.totalElements", is(2)))
;
}
@Test
public void findAllSubCommunities() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.build();
Community parentCommunity2 = CommunityBuilder.createCommunity(context)
.withName("Parent Community 2")
.withLogo("SomeTest")
.build();
Community parentCommunityChild1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Community parentCommunityChild2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community2")
.build();
Community parentCommunityChild2Child1 = CommunityBuilder.createSubCommunity(context, parentCommunityChild2)
.withName("Sub Sub Community")
.build();
Community parentCommunity2Child1 = CommunityBuilder.createSubCommunity(context, parentCommunity2)
.withName("Sub2 Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, parentCommunityChild1)
.withName("Collection 1")
.build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString() + "/subcommunities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
//Checking that these communities are present
.andExpect(jsonPath("$._embedded.subcommunities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunity(parentCommunityChild1),
CommunityMatcher.matchCommunity(parentCommunityChild2)
)))
//Checking that these communities are not present
.andExpect(jsonPath("$._embedded.subcommunities", Matchers.not(Matchers.anyOf(
CommunityMatcher.matchCommunity(parentCommunity),
CommunityMatcher.matchCommunity(parentCommunity2),
CommunityMatcher.matchCommunity(parentCommunity2Child1),
CommunityMatcher.matchCommunity(parentCommunityChild2Child1)
))))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID().toString())))
.andExpect(jsonPath("$.page.size", is(20)))
.andExpect(jsonPath("$.page.totalElements", is(2)));
getClient().perform(get("/api/core/communities/" + parentCommunityChild2.getID().toString() + "/subcommunities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
//Checking that these communities are present
.andExpect(jsonPath("$._embedded.subcommunities", Matchers.contains(
CommunityMatcher.matchCommunity(parentCommunityChild2Child1)
)))
//Checking that these communities are not present
.andExpect(jsonPath("$._embedded.subcommunities", Matchers.not(Matchers.anyOf(
CommunityMatcher.matchCommunity(parentCommunity),
CommunityMatcher.matchCommunity(parentCommunity2),
CommunityMatcher.matchCommunity(parentCommunity2Child1),
CommunityMatcher.matchCommunity(parentCommunityChild2Child1),
CommunityMatcher.matchCommunity(parentCommunityChild1)
))))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities/" + parentCommunityChild2.getID().toString())))
.andExpect(jsonPath("$.page.size", is(20)))
.andExpect(jsonPath("$.page.totalElements", is(1)));
getClient().perform(get("/api/core/communities/"
+ parentCommunityChild2Child1.getID().toString() + "/subcommunities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities/" + parentCommunityChild2Child1.getID().toString())))
.andExpect(jsonPath("$.page.size", is(20)))
.andExpect(jsonPath("$.page.totalElements", is(0)));
}
@Test
public void findAllSubCommunitiesUnAuthenticatedTest() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.build();
Community communityChild1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Community communityChild2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community2")
.build();
Community communityChild2Child1 = CommunityBuilder.createSubCommunity(context, communityChild2)
.withName("Sub Community2")
.build();
resoucePolicyService.removePolicies(context, communityChild2, Constants.READ);
context.restoreAuthSystemState();
// anonymous can NOT see the private communities
getClient().perform(get("/api/core/communities/" + communityChild2.getID().toString() + "/subcommunities"))
.andExpect(status().isUnauthorized());
// anonymous can see only public communities
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString() + "/subcommunities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.subcommunities", Matchers.contains(
CommunityMatcher.matchCommunity(communityChild1))))
.andExpect(jsonPath("$.page.totalElements", is(1)));
// admin can see all communities
String tokenAdmin = getAuthToken(admin.getEmail(), password);
getClient(tokenAdmin).perform(get("/api/core/communities/"
+ parentCommunity.getID().toString() + "/subcommunities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.subcommunities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunity(communityChild1),
CommunityMatcher.matchCommunity(communityChild2))))
.andExpect(jsonPath("$.page.totalElements", is(2)));
}
@Test
public void findAllSubCommunitiesForbiddenTest() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.build();
Community communityChild1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Community communityChild2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community2")
.build();
Community communityChild2Child1 = CommunityBuilder.createSubCommunity(context, communityChild2)
.withName("Sub Community2")
.build();
resoucePolicyService.removePolicies(context, communityChild2, Constants.READ);
context.restoreAuthSystemState();
String tokenEperson = getAuthToken(eperson.getEmail(), password);
getClient(tokenEperson).perform(get("/api/core/communities/"
+ parentCommunity.getID().toString() + "/subcommunities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.subcommunities", Matchers.contains(
CommunityMatcher.matchCommunity(communityChild1))))
.andExpect(jsonPath("$.page.totalElements", is(1)));
getClient(tokenEperson).perform(get("/api/core/communities/"
+ communityChild2.getID().toString() + "/subcommunities"))
.andExpect(status().isForbidden());
}
@Test
public void findAllSubCommunitiesGrantAccessAdminsTest() throws Exception {
context.turnOffAuthorisationSystem();
EPerson parentComAdmin = EPersonBuilder.createEPerson(context)
.withEmail("<EMAIL>")
.withPassword("<PASSWORD>")
.build();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.withAdminGroup(parentComAdmin)
.build();
EPerson child1Admin = EPersonBuilder.createEPerson(context)
.withEmail("<EMAIL>")
.withPassword("<PASSWORD>")
.build();
Community communityChild1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.withAdminGroup(child1Admin)
.build();
EPerson child2Admin = EPersonBuilder.createEPerson(context)
.withEmail("<EMAIL>")
.withPassword("<PASSWORD>")
.build();
Community communityChild2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community2")
.withAdminGroup(child2Admin)
.build();
Community ommunityChild1Child1 = CommunityBuilder.createSubCommunity(context, communityChild1)
.withName("Sub1 Community 1")
.build();
Community сommunityChild2Child1 = CommunityBuilder.createSubCommunity(context, communityChild2)
.withName("Sub2 Community 1")
.build();
resoucePolicyService.removePolicies(context, parentCommunity, Constants.READ);
resoucePolicyService.removePolicies(context, communityChild1, Constants.READ);
resoucePolicyService.removePolicies(context, communityChild2, Constants.READ);
context.restoreAuthSystemState();
String tokenParentAdmin = getAuthToken(parentComAdmin.getEmail(), "<PASSWORD>");
getClient(tokenParentAdmin).perform(get("/api/core/communities/"
+ parentCommunity.getID().toString() + "/subcommunities"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.subcommunities", Matchers.containsInAnyOrder(
CommunityMatcher.matchCommunity(communityChild1),
CommunityMatcher.matchCommunity(communityChild2))))
.andExpect(jsonPath("$.page.totalElements", is(2)));
String tokenChild1Admin = getAuthToken(child1Admin.getEmail(), "<PASSWORD>");
getClient(tokenChild1Admin).perform(get("/api/core/communities/"
+ parentCommunity.getID().toString() + "/subcommunities"))
.andExpect(status().isForbidden());
String tokenChild2Admin = getAuthToken(child2Admin.getEmail(), "<PASSWORD>");
getClient(tokenChild2Admin).perform(get("/api/core/communities/"
+ communityChild1.getID().toString() + "/subcommunities"))
.andExpect(status().isForbidden());
}
@Test
public void findAllCollectionsUnAuthenticatedTest() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection child1Col1 = CollectionBuilder.createCollection(context, child1)
.withName("Collection 1 child 1")
.build();
Collection child1Col2 = CollectionBuilder.createCollection(context, child1)
.withName("Collection 2 child 1")
.build();
Collection child2Col1 = CollectionBuilder.createCollection(context, child2)
.withName("Collection 1 child 2")
.build();
resoucePolicyService.removePolicies(context, child1Col2, Constants.READ);
resoucePolicyService.removePolicies(context, child2, Constants.READ);
context.restoreAuthSystemState();
// anonymous can see only public communities
getClient().perform(get("/api/core/communities/" + child1.getID().toString() + "/collections"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.collections", Matchers.contains(CollectionMatcher
.matchCollection(child1Col1))))
.andExpect(jsonPath("$.page.totalElements", is(1)));
// anonymous can NOT see the private communities
getClient().perform(get("/api/core/communities/" + child2.getID().toString() + "/collections"))
.andExpect(status().isUnauthorized());
}
@Test
public void findAllCollectionsForbiddenTest() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 1")
.build();
Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 2")
.build();
Collection child1Col1 = CollectionBuilder.createCollection(context, child1)
.withName("Collection 1 child 1")
.build();
Collection child1Col2 = CollectionBuilder.createCollection(context, child1)
.withName("Collection 2 child 1")
.build();
Collection child2Col1 = CollectionBuilder.createCollection(context, child2)
.withName("Collection 1 child 2")
.build();
resoucePolicyService.removePolicies(context, child1Col2, Constants.READ);
resoucePolicyService.removePolicies(context, child2, Constants.READ);
context.restoreAuthSystemState();
String tokenAdmin = getAuthToken(admin.getEmail(), password);
getClient(tokenAdmin).perform(get("/api/core/communities/" + child1.getID().toString() + "/collections"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.collections", Matchers.containsInAnyOrder(
CollectionMatcher.matchCollection(child1Col1),
CollectionMatcher.matchCollection(child1Col2))))
.andExpect(jsonPath("$.page.totalElements", is(2)));
getClient(tokenAdmin).perform(get("/api/core/communities/" + child2.getID().toString() + "/collections"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.collections", Matchers.contains(
CollectionMatcher.matchCollection(child2Col1))))
.andExpect(jsonPath("$.page.totalElements", is(1)));
String tokenEperson = getAuthToken(eperson.getEmail(), password);
getClient(tokenEperson).perform(get("/api/core/communities/" + child2.getID().toString() + "/collections"))
.andExpect(status().isForbidden());
}
@Test
public void findAllCollectionsGrantAccessAdminsTest() throws Exception {
context.turnOffAuthorisationSystem();
EPerson parentAdmin = EPersonBuilder.createEPerson(context)
.withEmail("<EMAIL>")
.withPassword("<PASSWORD>")
.build();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.withAdminGroup(parentAdmin)
.build();
EPerson child1Admin = EPersonBuilder.createEPerson(context)
.withEmail("<EMAIL>")
.withPassword("<PASSWORD>")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.withAdminGroup(child1Admin)
.build();
EPerson child2Admin = EPersonBuilder.createEPerson(context)
.withEmail("<EMAIL>")
.withPassword("<PASSWORD>")
.build();
Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.withAdminGroup(child2Admin)
.build();
Collection child1Col1 = CollectionBuilder.createCollection(context, child1)
.withName("Child 1 Collection 1")
.build();
Collection child1Col2 = CollectionBuilder.createCollection(context, child1)
.withName("Child 1 Collection 2")
.build();
Collection child2Col1 = CollectionBuilder.createCollection(context, child2)
.withName("Child 2 Collection 1")
.build();
resoucePolicyService.removePolicies(context, child1Col2, Constants.READ);
resoucePolicyService.removePolicies(context, child2, Constants.READ);
context.restoreAuthSystemState();
String tokenParentAdmin = getAuthToken(parentAdmin.getEmail(), "<PASSWORD>");
getClient(tokenParentAdmin).perform(get("/api/core/communities/" + child1.getID().toString() + "/collections"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.collections", Matchers.containsInAnyOrder(
CollectionMatcher.matchCollection(child1Col1),
CollectionMatcher.matchCollection(child1Col2))))
.andExpect(jsonPath("$.page.totalElements", is(2)));
getClient(tokenParentAdmin).perform(get("/api/core/communities/" + child2.getID().toString() + "/collections"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.collections", Matchers.contains(
CollectionMatcher.matchCollection(child2Col1))))
.andExpect(jsonPath("$.page.totalElements", is(1)));
String tokenChild2Admin = getAuthToken(child2Admin.getEmail(), "<PASSWORD>");
getClient(tokenChild2Admin).perform(get("/api/core/communities/" + child1.getID().toString() + "/collections"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.collections", Matchers.contains(
CollectionMatcher.matchCollection(child1Col1))))
.andExpect(jsonPath("$.page.totalElements", is(1)));
}
@Test
public void findAllSubCommunitiesWithUnexistentUUID() throws Exception {
getClient().perform(get("/api/core/communities/" + UUID.randomUUID().toString() + "/subcommunities"))
.andExpect(status().isNotFound());
}
@Test
public void findOneTestWrongUUID() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/" + UUID.randomUUID())).andExpect(status().isNotFound());
}
@Test
public void updateTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle())
)))
.andExpect(jsonPath("$", Matchers.not(
Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(child1.getName(), child1.getID(),
child1.getHandle())
)
)))
.andExpect(jsonPath("$._links.self.href", Matchers.containsString("/api/core/communities")))
;
String token = getAuthToken(admin.getEmail(), password);
context.turnOffAuthorisationSystem();
ObjectMapper mapper = new ObjectMapper();
CommunityRest communityRest = communityConverter.convert(parentCommunity, Projection.DEFAULT);
communityRest.setMetadata(new MetadataRest()
.put("dc.title", new MetadataValueRest("Electronic theses and dissertations")));
context.restoreAuthSystemState();
getClient(token).perform(put("/api/core/communities/" + parentCommunity.getID().toString())
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsBytes(communityRest)))
.andExpect(status().isOk())
;
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds("Electronic theses and dissertations",
parentCommunity.getID(),
parentCommunity.getHandle())
)))
.andExpect(jsonPath("$._links.self.href", Matchers.containsString("/api/core/communities")))
;
}
@Test
public void deleteTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.build();
Community parentCommunity2 = CommunityBuilder.createCommunity(context)
.withName("Parent Community 2")
.withLogo("SomeTest")
.build();
Community parentCommunityChild1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Community parentCommunityChild2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community2")
.build();
Community parentCommunityChild2Child1 = CommunityBuilder.createSubCommunity(context, parentCommunityChild2)
.withName("Sub Sub Community")
.build();
Community parentCommunity2Child1 = CommunityBuilder.createSubCommunity(context, parentCommunity2)
.withName("Sub2 Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, parentCommunityChild1)
.withName("Collection 1")
.build();
String token = getAuthToken(admin.getEmail(), password);
context.restoreAuthSystemState();
getClient(token).perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle())
)))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities")));
getClient(token).perform(delete("/api/core/communities/" + parentCommunity.getID().toString()))
.andExpect(status().isNoContent())
;
getClient(token).perform(get("/api/core/communities/" + parentCommunity.getID().toString()))
.andExpect(status().isNotFound())
;
getClient(token).perform(get("/api/core/communities/" + parentCommunityChild1.getID().toString()))
.andExpect(status().isNotFound())
;
}
@Test
public void deleteTestUnAuthorized() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.build();
Community parentCommunity2 = CommunityBuilder.createCommunity(context)
.withName("Parent Community 2")
.withLogo("SomeTest")
.build();
Community parentCommunityChild1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Community parentCommunityChild2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community2")
.build();
Community parentCommunityChild2Child1 = CommunityBuilder.createSubCommunity(context, parentCommunityChild2)
.withName("Sub Sub Community")
.build();
Community parentCommunity2Child1 = CommunityBuilder.createSubCommunity(context, parentCommunity2)
.withName("Sub2 Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, parentCommunityChild1)
.withName("Collection 1")
.build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle())
)))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities")));
getClient().perform(delete("/api/core/communities/" + parentCommunity.getID().toString()))
.andExpect(status().isUnauthorized())
;
}
@Test
public void deleteCommunityEpersonWithDeleteRightsTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
context.setCurrentUser(eperson);
authorizeService.addPolicy(context, parentCommunity, Constants.DELETE, eperson);
String token = getAuthToken(eperson.getEmail(), password);
context.restoreAuthSystemState();
getClient(token).perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle())
)))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities")));
getClient(token).perform(delete("/api/core/communities/" + parentCommunity.getID().toString()))
.andExpect(status().isNoContent())
;
getClient(token).perform(get("/api/core/communities/" + parentCommunity.getID().toString()))
.andExpect(status().isNotFound())
;
authorizeService.removePoliciesActionFilter(context, eperson, Constants.DELETE);
}
@Test
public void updateCommunityEpersonWithWriteRightsTest() throws Exception {
//We turn off the authorization system in order to create the structure as defined below
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and one collection.
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(parentCommunity.getName(),
parentCommunity.getID(),
parentCommunity.getHandle())
)))
.andExpect(jsonPath("$", Matchers.not(
Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds(child1.getName(), child1.getID(),
child1.getHandle())
)
)))
.andExpect(jsonPath("$._links.self.href", Matchers.containsString("/api/core/communities")))
;
context.turnOffAuthorisationSystem();
ObjectMapper mapper = new ObjectMapper();
CommunityRest communityRest = communityConverter.convert(parentCommunity, Projection.DEFAULT);
communityRest.setMetadata(new MetadataRest()
.put("dc.title", new MetadataValueRest("Electronic theses and dissertations")));
context.setCurrentUser(eperson);
authorizeService.addPolicy(context, parentCommunity, Constants.WRITE, eperson);
context.restoreAuthSystemState();
String token = getAuthToken(eperson.getEmail(), password);
getClient(token).perform(put("/api/core/communities/" + parentCommunity.getID().toString())
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsBytes(communityRest)))
.andExpect(status().isOk())
;
getClient().perform(get("/api/core/communities/" + parentCommunity.getID().toString())
.param("embed", CommunityMatcher.getNonAdminEmbeds()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", Matchers.is(
CommunityMatcher.matchCommunityEntryNonAdminEmbeds("Electronic theses and dissertations",
parentCommunity.getID(),
parentCommunity.getHandle())
)))
.andExpect(jsonPath("$._links.self.href", Matchers.containsString("/api/core/communities")))
;
authorizeService.removePoliciesActionFilter(context, eperson, Constants.DELETE);
}
@Test
public void patchCommunityMetadataAuthorized() throws Exception {
runPatchMetadataTests(admin, 200);
}
@Test
public void patchCommunityMetadataUnauthorized() throws Exception {
runPatchMetadataTests(eperson, 403);
}
private void runPatchMetadataTests(EPerson asUser, int expectedStatus) throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context).withName("Community").build();
context.restoreAuthSystemState();
String token = getAuthToken(asUser.getEmail(), password);
new MetadataPatchSuite().runWith(getClient(token), "/api/core/communities/"
+ parentCommunity.getID(), expectedStatus);
}
@Test
public void createTestInvalidParentCommunityBadRequest() throws Exception {
context.turnOffAuthorisationSystem();
ObjectMapper mapper = new ObjectMapper();
CommunityRest comm = new CommunityRest();
// We send a name but the created community should set this to the title
comm.setName("Test Top-Level Community");
MetadataRest metadataRest = new MetadataRest();
MetadataValueRest description = new MetadataValueRest();
description.setValue("<p>Some cool HTML code here</p>");
metadataRest.put("dc.description", description);
MetadataValueRest abs = new MetadataValueRest();
abs.setValue("Sample top-level community created via the REST API");
metadataRest.put("dc.description.abstract", abs);
MetadataValueRest contents = new MetadataValueRest();
contents.setValue("<p>HTML News</p>");
metadataRest.put("dc.description.tableofcontents", contents);
MetadataValueRest copyright = new MetadataValueRest();
copyright.setValue("Custom Copyright Text");
metadataRest.put("dc.rights", copyright);
MetadataValueRest title = new MetadataValueRest();
title.setValue("Title Text");
metadataRest.put("dc.title", title);
comm.setMetadata(metadataRest);
context.restoreAuthSystemState();
String authToken = getAuthToken(admin.getEmail(), password);
getClient(authToken).perform(post("/api/core/communities")
.param("parent", "123")
.content(mapper.writeValueAsBytes(comm))
.contentType(contentType))
.andExpect(status().isBadRequest());
}
public void setUpAuthorizedSearch() throws Exception {
super.setUp();
context.turnOffAuthorisationSystem();
topLevelCommunityAAdmin = EPersonBuilder.createEPerson(context)
.withNameInMetadata("Jhon", "Brown")
.withEmail("<EMAIL>")
.withPassword(password)
.build();
topLevelCommunityA = CommunityBuilder.createCommunity(context)
.withName("The name of this community is topLevelCommunityA")
.withAdminGroup(topLevelCommunityAAdmin)
.build();
subCommunityAAdmin = EPersonBuilder.createEPerson(context)
.withNameInMetadata("Jhon", "Brown")
.withEmail("<EMAIL>")
.withPassword(password)
.build();
subCommunityA = CommunityBuilder.createCommunity(context)
.withName("The name of this sub-community is subCommunityA")
.withAdminGroup(subCommunityAAdmin)
.addParentCommunity(context, topLevelCommunityA)
.build();
submitter = EPersonBuilder.createEPerson(context)
.withNameInMetadata("Jhon", "Brown")
.withEmail("<EMAIL>")
.withPassword(password)
.build();
collectionAdmin = EPersonBuilder.createEPerson(context)
.withNameInMetadata("Jhon", "Brown")
.withEmail("<EMAIL>")
.withPassword(password)
.build();
collectionA = CollectionBuilder.createCollection(context, subCommunityA)
.withName("The name of this collection is collectionA")
.withAdminGroup(collectionAdmin)
.withSubmitterGroup(submitter)
.build();
context.restoreAuthSystemState();
configurationService.setProperty(
"org.dspace.app.rest.authorization.AlwaysThrowExceptionFeature.turnoff", "true");
}
@Test
public void testAdminAuthorizedSearch() throws Exception {
setUpAuthorizedSearch();
context.turnOffAuthorisationSystem();
communityB = CommunityBuilder.createCommunity(context)
.withName("topLevelCommunityB is a very original name")
.withAdminGroup(admin)
.build();
communityC = CommunityBuilder.createCommunity(context)
.withName("the last community is topLevelCommunityC")
.build();
context.restoreAuthSystemState();
String token = getAuthToken(admin.getEmail(), password);
// Verify the site admin gets all communities
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(topLevelCommunityA.getName(), topLevelCommunityA.getID(),
topLevelCommunityA.getHandle()),
CommunityMatcher.matchProperties(subCommunityA.getName(), subCommunityA.getID(),
subCommunityA.getHandle()),
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle()),
CommunityMatcher.matchProperties(communityC.getName(), communityC.getID(), communityC.getHandle())
)));
// Verify the search only shows dso's which according to the query
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityB.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle())
)));
}
@Test
public void testCommunityAdminAuthorizedSearch() throws Exception {
setUpAuthorizedSearch();
context.turnOffAuthorisationSystem();
communityB = CommunityBuilder.createCommunity(context)
.withName("topLevelCommunityB is a very original name")
.withAdminGroup(topLevelCommunityAAdmin)
.build();
communityC = CommunityBuilder.createCommunity(context)
.withName("the last community is named topLevelCommunityC")
.build();
context.restoreAuthSystemState();
String token = getAuthToken(topLevelCommunityAAdmin.getEmail(), password);
// Verify the community admin gets all the communities he's admin for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(topLevelCommunityA.getName(), topLevelCommunityA.getID(),
topLevelCommunityA.getHandle()),
CommunityMatcher.matchProperties(subCommunityA.getName(), subCommunityA.getID(),
subCommunityA.getHandle()),
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle())
)));
// Verify the search only shows dso's which according to the query
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityB.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle())
)));
// Verify that a query doesn't show dso's which the user doesn't have rights for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityC.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
}
@Test
public void testSubCommunityAdminAuthorizedSearch() throws Exception {
setUpAuthorizedSearch();
/**
* The Community/Collection structure for this test:
*
* topLevelCommunityA
* ├── subCommunityA
* | └── collectionA
* ├── communityB
* └── communityC
*/
context.turnOffAuthorisationSystem();
communityB = CommunityBuilder.createCommunity(context)
.withName("topLevelCommunityB is a very original name")
.addParentCommunity(context, topLevelCommunityA)
.withAdminGroup(subCommunityAAdmin)
.build();
communityC = CommunityBuilder.createCommunity(context)
.withName("the last community is topLevelCommunityC")
.addParentCommunity(context, topLevelCommunityA)
.build();
context.restoreAuthSystemState();
String token = getAuthToken(subCommunityAAdmin.getEmail(), password);
// Verify the community admin gets all the communities he's admin for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(subCommunityA.getName(), subCommunityA.getID(),
subCommunityA.getHandle()),
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle())
)));
// Verify the search only shows dso's which according to the query
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityB.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle())
)));
// Verify that a query doesn't show dso's which the user doesn't have rights for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityC.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
}
@Test
public void testCollectionAdminAuthorizedSearch() throws Exception {
setUpAuthorizedSearch();
context.turnOffAuthorisationSystem();
communityB = CommunityBuilder.createCommunity(context)
.withName("topLevelCommunityB is a very original name")
.addParentCommunity(context, topLevelCommunityA)
.build();
communityC = CommunityBuilder.createCommunity(context)
.withName("the last community is topLevelCommunityC")
.addParentCommunity(context, topLevelCommunityA)
.build();
context.restoreAuthSystemState();
String token = getAuthToken(collectionAdmin.getEmail(), password);
// Verify the collection admin doesn't have any matches for communities
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
// Verify the search only shows dso's which according to the query
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityB.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
// Verify that a query doesn't show dso's which the user doesn't have rights for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityC.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
}
@Test
public void testSubmitterAuthorizedSearch() throws Exception {
setUpAuthorizedSearch();
context.turnOffAuthorisationSystem();
communityB = CommunityBuilder.createCommunity(context)
.withName("topLevelCommunityB is a very original name")
.addParentCommunity(context, topLevelCommunityA)
.build();
communityC = CommunityBuilder.createCommunity(context)
.withName("the last community is topLevelCommunityC")
.addParentCommunity(context, topLevelCommunityA)
.build();
context.restoreAuthSystemState();
String token = getAuthToken(submitter.getEmail(), password);
// Verify the submitter doesn't have any matches for communities
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
// Verify the search only shows dso's which according to the query
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityB.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
// Verify that a query doesn't show dso's which the user doesn't have rights for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityC.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
}
@Test
public void testSubGroupOfAdminGroupAuthorizedSearch() throws Exception {
setUpAuthorizedSearch();
context.turnOffAuthorisationSystem();
GroupBuilder.createGroup(context)
.withName("adminSubGroup")
.withParent(groupService.findByName(context, Group.ADMIN))
.addMember(eperson)
.build();
communityB = CommunityBuilder.createCommunity(context)
.withName("topLevelCommunityB is a very original name")
.build();
communityC = CommunityBuilder.createCommunity(context)
.withName("the last community is topLevelCommunityC")
.build();
context.restoreAuthSystemState();
String token = getAuthToken(eperson.getEmail(), password);
// Verify the site admins' subgroups members get all communities
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(topLevelCommunityA.getName(), topLevelCommunityA.getID(),
topLevelCommunityA.getHandle()),
CommunityMatcher.matchProperties(subCommunityA.getName(), subCommunityA.getID(),
subCommunityA.getHandle()),
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle()),
CommunityMatcher.matchProperties(communityC.getName(), communityC.getID(), communityC.getHandle())
)));
// Verify the search only shows dso's which according to the query
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityB.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle())
)));
}
@Test
public void testSubGroupOfCommunityAdminGroupAuthorizedSearch() throws Exception {
setUpAuthorizedSearch();
context.turnOffAuthorisationSystem();
GroupBuilder.createGroup(context)
.withName("communityAdminSubGroup")
.withParent(groupService.findByName(context, "COMMUNITY_" + topLevelCommunityA.getID() + "_ADMIN"))
.addMember(eperson)
.build();
communityB = CommunityBuilder.createCommunity(context)
.withName("topLevelCommunityB is a very original name")
.build();
communityC = CommunityBuilder.createCommunity(context)
.withName("the last community is topLevelCommunityC")
.build();
ResourcePolicyBuilder.createResourcePolicy(context)
.withDspaceObject(communityB)
.withAction(Constants.ADMIN)
.withGroup(groupService.findByName(context, "COMMUNITY_" + topLevelCommunityA.getID() + "_ADMIN"))
.build();
context.restoreAuthSystemState();
String token = getAuthToken(eperson.getEmail(), password);
// Verify the community admins' subgroup users get all the communities he's admin for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(topLevelCommunityA.getName(), topLevelCommunityA.getID(),
topLevelCommunityA.getHandle()),
CommunityMatcher.matchProperties(subCommunityA.getName(), subCommunityA.getID(),
subCommunityA.getHandle()),
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle())
)));
// Verify the search only shows dso's which according to the query
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityB.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle())
)));
// Verify that a query doesn't show dso's which the user doesn't have rights for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityC.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
}
@Test
public void testSubGroupOfSubCommunityAdminGroupAuthorizedSearch() throws Exception {
setUpAuthorizedSearch();
context.turnOffAuthorisationSystem();
GroupBuilder.createGroup(context)
.withName("communityAdminSubGroup")
.withParent(groupService.findByName(context, "COMMUNITY_" + subCommunityA.getID() + "_ADMIN"))
.addMember(eperson)
.build();
communityB = CommunityBuilder.createCommunity(context)
.withName("topLevelCommunityB is a very original name")
.addParentCommunity(context, topLevelCommunityA)
.build();
communityC = CommunityBuilder.createCommunity(context)
.withName("the last community is topLevelCommunityC")
.addParentCommunity(context, topLevelCommunityA)
.build();
ResourcePolicyBuilder.createResourcePolicy(context)
.withDspaceObject(communityB)
.withAction(Constants.ADMIN)
.withGroup(groupService.findByName(context, "COMMUNITY_" + subCommunityA.getID() + "_ADMIN"))
.build();
context.restoreAuthSystemState();
String token = getAuthToken(eperson.getEmail(), password);
// Verify the sub-community admins' subgroup users get all the communities he's admin for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(subCommunityA.getName(), subCommunityA.getID(),
subCommunityA.getHandle()),
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle())
)));
// Verify the search only shows dso's which according to the query
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityB.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.containsInAnyOrder(
CommunityMatcher.matchProperties(communityB.getName(), communityB.getID(), communityB.getHandle())
)));
// Verify that a query doesn't show dso's which the user doesn't have rights for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityC.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
}
@Test
public void testSubGroupOfCollectionAdminGroupAuthorizedSearch() throws Exception {
setUpAuthorizedSearch();
context.turnOffAuthorisationSystem();
GroupBuilder.createGroup(context)
.withName("collectionAdminSubGroup")
.withParent(groupService.findByName(context, "COLLECTION_" + collectionA.getID() + "_ADMIN"))
.addMember(eperson)
.build();
communityB = CommunityBuilder.createCommunity(context)
.withName("topLevelCommunityB is a very original name")
.addParentCommunity(context, topLevelCommunityA)
.build();
Collection collectionB = CollectionBuilder.createCollection(context, communityB)
.withName("collectionB")
.build();
ResourcePolicyBuilder.createResourcePolicy(context)
.withDspaceObject(collectionB)
.withAction(Constants.ADMIN)
.withGroup(groupService.findByName(context, "COLLECTION_" + collectionA.getID() + "_ADMIN"))
.build();
communityC = CommunityBuilder.createCommunity(context)
.withName("the last community is topLevelCommunityC")
.addParentCommunity(context, topLevelCommunityA)
.build();
context.restoreAuthSystemState();
String token = getAuthToken(eperson.getEmail(), password);
// Verify the collection admins' subgroup members don't have any matches for communities
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
// Verify the search only shows dso's which according to the query
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityB.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
// Verify that a query doesn't show dso's which the user doesn't have rights for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityC.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
}
@Test
public void testSubGroupOfSubmitterGroupAuthorizedSearch() throws Exception {
setUpAuthorizedSearch();
context.turnOffAuthorisationSystem();
GroupBuilder.createGroup(context)
.withName("collectionAdminSubGroup")
.withParent(groupService.findByName(context, "COLLECTION_" + collectionA.getID() + "_SUBMIT"))
.addMember(eperson)
.build();
communityB = CommunityBuilder.createCommunity(context)
.withName("topLevelCommunityB is a very original name")
.addParentCommunity(context, topLevelCommunityA)
.build();
Collection collectionB = CollectionBuilder.createCollection(context, communityB)
.withName("collectionB")
.build();
ResourcePolicyBuilder.createResourcePolicy(context)
.withDspaceObject(collectionB)
.withAction(Constants.ADD)
.withGroup(groupService.findByName(context, "COLLECTION_" + collectionA.getID() + "_SUBMIT"))
.build();
communityC = CommunityBuilder.createCommunity(context)
.withName("the last community is topLevelCommunityC")
.addParentCommunity(context, topLevelCommunityA)
.build();
context.restoreAuthSystemState();
String token = getAuthToken(eperson.getEmail(), password);
// Verify an ePerson in a subgroup of submitter group doesn't have any matches for communities
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
// Verify the search only shows dso's which according to the query
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityB.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
// Verify that a query doesn't show dso's which the user doesn't have rights for
getClient(token).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", communityC.getName()))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities").doesNotExist());
}
@Test
public void testAdminAuthorizedSearchUnauthenticated() throws Exception {
// Verify a non-authenticated user can't use this function
getClient().perform(get("/api/core/communities/search/findAdminAuthorized"))
.andExpect(status().isUnauthorized());
}
@Test
public void findAllSearchTopEmbeddedPaginationTest() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.withLogo("ThisIsSomeDummyText")
.build();
Collection col = CollectionBuilder.createCollection(context, parentCommunity)
.withName("Collection 1").build();
Collection col2 = CollectionBuilder.createCollection(context, parentCommunity)
.withName("Collection 2").build();
CommunityBuilder.createCommunity(context)
.withName("Parent Community 2")
.withLogo("SomeTest").build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community").build();
Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community 2").build();
context.restoreAuthSystemState();
getClient().perform(get("/api/core/communities/search/top")
.param("size", "1")
.param("embed", "subcommunities")
.param("embed", "collections")
.param("embed.size", "subcommunities=1")
.param("embed.size", "collections=1"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.contains(
CommunityMatcher.matchCommunity(parentCommunity))))
// Verify subcommunities
.andExpect(jsonPath("$._embedded.communities[0]._embedded.subcommunities._embedded.subcommunities",
Matchers.contains(CommunityMatcher.matchCommunity(child1))))
.andExpect(jsonPath("$._embedded.communities[0]._embedded.subcommunities._links.self.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID()
+ "/subcommunities?size=1")))
.andExpect(jsonPath("$._embedded.communities[0]._embedded.subcommunities._links.next.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID()
+ "/subcommunities?page=1&size=1")))
.andExpect(jsonPath("$._embedded.communities[0]._embedded.subcommunities._links.last.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID()
+ "/subcommunities?page=1&size=1")))
// Verify collections
.andExpect(jsonPath("$._embedded.communities[0]._embedded.collections._embedded.collections",
Matchers.contains(CollectionMatcher.matchCollection(col))))
.andExpect(jsonPath("$._embedded.communities[0]._embedded.collections._links.self.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID()
+ "/collections?size=1")))
.andExpect(jsonPath("$._embedded.communities[0]._embedded.collections._links.next.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID()
+ "/collections?page=1&size=1")))
.andExpect(jsonPath("$._embedded.communities[0]._embedded.collections._links.last.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID()
+ "/collections?page=1&size=1")))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities/search/top?size=1")))
.andExpect(jsonPath("$._links.first.href",
Matchers.containsString("/api/core/communities/search/top?page=0&size=1")))
.andExpect(jsonPath("$._links.next.href",
Matchers.containsString("/api/core/communities/search/top?page=1&size=1")))
.andExpect(jsonPath("$._links.last.href",
Matchers.containsString("/api/core/communities/search/top?page=1&size=1")))
.andExpect(jsonPath("$.page.size", is(1)))
.andExpect(jsonPath("$.page.totalPages", is(2)))
.andExpect(jsonPath("$.page.totalElements", is(2)));
getClient().perform(get("/api/core/communities/search/top")
.param("size", "1")
.param("embed", "subcommunities")
.param("embed", "collections")
.param("embed.size", "subcommunities=2")
.param("embed.size", "collections=2"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$._embedded.communities", Matchers.contains(
CommunityMatcher.matchCommunity(parentCommunity))))
// Verify subcommunities
.andExpect(jsonPath("$._embedded.communities[0]._embedded.subcommunities._embedded.subcommunities",
Matchers.containsInAnyOrder(CommunityMatcher.matchCommunity(child1),
CommunityMatcher.matchCommunity(child2)
)))
.andExpect(jsonPath("$._embedded.communities[0]._embedded.subcommunities._links.self.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID()
+ "/subcommunities?size=2")))
// Verify collections
.andExpect(jsonPath("$._embedded.communities[0]._embedded.collections._embedded.collections",
Matchers.containsInAnyOrder(CollectionMatcher.matchCollection(col),
CollectionMatcher.matchCollection(col2)
)))
.andExpect(jsonPath("$._embedded.communities[0]._embedded.collections._links.self.href",
Matchers.containsString("/api/core/communities/" + parentCommunity.getID()
+ "/collections?size=2")))
.andExpect(jsonPath("$._links.self.href",
Matchers.containsString("/api/core/communities/search/top?size=1")))
.andExpect(jsonPath("$._links.first.href",
Matchers.containsString("/api/core/communities/search/top?page=0&size=1")))
.andExpect(jsonPath("$._links.next.href",
Matchers.containsString("/api/core/communities/search/top?page=1&size=1")))
.andExpect(jsonPath("$._links.last.href",
Matchers.containsString("/api/core/communities/search/top?page=1&size=1")))
.andExpect(jsonPath("$.page.size", is(1)))
.andExpect(jsonPath("$.page.totalPages", is(2)))
.andExpect(jsonPath("$.page.totalElements", is(2)));
}
@Test
public void removeComAdminGroupToCheckReindexingTest() throws Exception {
context.turnOffAuthorisationSystem();
Community rootCommunity = CommunityBuilder.createCommunity(context)
.withName("Root Community")
.build();
Community subCommunity = CommunityBuilder.createSubCommunity(context, rootCommunity)
.withName("MyTestCom")
.withAdminGroup(eperson)
.build();
context.restoreAuthSystemState();
String epersonToken = getAuthToken(eperson.getEmail(), password);
getClient(epersonToken).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", "MyTestCom"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.contains(CommunityMatcher
.matchProperties(subCommunity.getName(),
subCommunity.getID(),
subCommunity.getHandle())
)))
.andExpect(jsonPath("$.page.totalElements", is(1)));
String token = getAuthToken(admin.getEmail(), password);
getClient(token).perform(delete("/api/core/communities/" + subCommunity.getID() + "/adminGroup"))
.andExpect(status().isNoContent());
getClient(epersonToken).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", "MyTestCom"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded").doesNotExist())
.andExpect(jsonPath("$.page.totalElements", is(0)));
}
@Test
public void addComAdminGroupToCheckReindexingTest() throws Exception {
context.turnOffAuthorisationSystem();
Community rootCommunity = CommunityBuilder.createCommunity(context)
.withName("Root Community")
.build();
Community subCommunity = CommunityBuilder.createSubCommunity(context, rootCommunity)
.withName("MyTestCom")
.build();
context.restoreAuthSystemState();
String epersonToken = getAuthToken(eperson.getEmail(), password);
getClient(epersonToken).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", "MyTestCom"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded").doesNotExist())
.andExpect(jsonPath("$.page.totalElements", is(0)));
AtomicReference<UUID> idRef = new AtomicReference<>();
ObjectMapper mapper = new ObjectMapper();
GroupRest groupRest = new GroupRest();
String token = getAuthToken(admin.getEmail(), password);
getClient(token).perform(post("/api/core/communities/" + subCommunity.getID() + "/adminGroup")
.content(mapper.writeValueAsBytes(groupRest))
.contentType(contentType))
.andExpect(status().isCreated())
.andDo(result -> idRef.set(
UUID.fromString(read(result.getResponse().getContentAsString(), "$.id")))
);
String adminToken = getAuthToken(admin.getEmail(), password);
getClient(adminToken).perform(post("/api/eperson/groups/" + idRef.get() + "/epersons")
.contentType(parseMediaType(TEXT_URI_LIST_VALUE))
.content(REST_SERVER_URL + "eperson/groups/" + eperson.getID()
));
getClient(epersonToken).perform(get("/api/core/communities/search/findAdminAuthorized")
.param("query", "MyTestCom"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.communities", Matchers.contains(CommunityMatcher
.matchProperties(subCommunity.getName(),
subCommunity.getID(),
subCommunity.getHandle())
)))
.andExpect(jsonPath("$.page.totalElements", is(1)));
}
}
| 69,293 |
1,673 |
<reponame>C-Chads/cc65
#include <stdio.h>
unsigned char failures = 0;
int main(void)
{
int i;
i = 0;
if ((i > 1) && (i < 3)) {
failures++;
}
printf("failures: %u\n", failures);
return failures;
}
| 95 |
1,236 |
<reponame>jasonfeihe/BitFunnel<filename>NativeJIT/inc/NativeJIT/ExecutionPreconditionTest.h
// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include "NativeJIT/CodeGen/X64CodeGenerator.h"
#include "NativeJIT/ExpressionTree.h"
#include "NativeJIT/Nodes/ConditionalNode.h"
#include "NativeJIT/Nodes/ImmediateNode.h"
namespace NativeJIT
{
// A base class for statements that check whether a precondition for executing
// the full expression has been met and cause a fixed value to be returned
// if not.
class ExecutionPreconditionTest : private NonCopyable
{
public:
// Executes its test and allows the regular flow to continue if test's
// condition is satisfied. Otherwise, places an alternative fixed value
// into the return register and jumps to function's epilog.
virtual void Evaluate(ExpressionTree& tree) = 0;
};
// A class implementing a statement that causes the function either to start
// executing if a precondition has been met or to return an immediate value
// otherwise.
//
// DESIGN NOTE: something similar can be achieved with the If() node-based
// expression at the root of the expression tree, but that may be very
// inefficient: the expression tree will pre-evaluate nodes with multiple
// parents first and then start evaluating the expression. Almost all of the
// pre-evaluated nodes are irrelevant to the early return test, so their X64
// code may be executed needlessly at runtime. This is an issue in cases
// when the function is executed a large number of times for different
// inputs where the vast majority of them is expected to return early.
template <typename T, JccType JCC>
class ExecuteOnlyIfStatement : public ExecutionPreconditionTest
{
public:
ExecuteOnlyIfStatement(FlagExpressionNode<JCC>& condition,
ImmediateNode<T>& otherwiseValue);
//
// Overrides of ExecutionPreconditionTest.
//
virtual void Evaluate(ExpressionTree& tree) override;
private:
FlagExpressionNode<JCC>& m_condition;
ImmediateNode<T>& m_otherwiseValue;
};
//
// Template definitions for ExecuteOnlyIfStatement.
//
template <typename T, JccType JCC>
ExecuteOnlyIfStatement<T, JCC>::ExecuteOnlyIfStatement(
FlagExpressionNode<JCC>& condition,
ImmediateNode<T>& otherwiseValue)
: m_condition(condition),
m_otherwiseValue(otherwiseValue)
{
m_otherwiseValue.IncrementParentCount();
// Use the CodeGenFlags()-related call.
m_condition.IncrementFlagsParentCount();
}
template <typename T, JccType JCC>
void ExecuteOnlyIfStatement<T, JCC>::Evaluate(ExpressionTree& tree)
{
X64CodeGenerator& code = tree.GetCodeGenerator();
Label continueWithRegularFlow = code.AllocateLabel();
// Evaluate the condition to update the CPU flags. If condition is
// satisfied, continue with the regular flow.
m_condition.CodeGenFlags(tree);
code.EmitConditionalJump<JCC>(continueWithRegularFlow);
// Otherwise, return early with the constant value: move the constant
// into the return register and jump to epilog.
auto resultRegister = tree.GetResultRegister<T>();
// IMPORTANT: CodeGen() for ImmediateNode will not cause any registers
// to be spilled or modified. Otherwise, NativeJIT's view of the register
// allocation would get out of sync with the actual state due to the
// conditional jump above. See the comment in
// ConditionalNode::CodeGenValue for more details.
auto otherwiseValue = m_otherwiseValue.CodeGen(tree);
// Move the value into the result register unless already there.
if (!(otherwiseValue.GetStorageClass() == StorageClass::Direct
&& otherwiseValue.GetDirectRegister() == resultRegister))
{
CodeGenHelpers::Emit<OpCode::Mov>(tree.GetCodeGenerator(),
resultRegister,
otherwiseValue);
}
// There are no issues to jumping directly to the start of epilog with
// no regard for the instructions generated before Evaluate() as there
// is nothing in them that would need to be undone. Most notably, the
// stack pointer is supposed to be kept constant during evaluation
// of the function (except temporarily for function calls).
code.Jmp(tree.GetStartOfEpilogue());
code.PlaceLabel(continueWithRegularFlow);
}
}
| 1,934 |
19,438 |
<filename>Kernel/RTC.cpp
/*
* Copyright (c) 2018-2020, <NAME> <<EMAIL>>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Time.h>
#include <Kernel/Arch/x86/IO.h>
#include <Kernel/CMOS.h>
#include <Kernel/RTC.h>
namespace RTC {
static time_t s_boot_time;
void initialize()
{
s_boot_time = now();
}
time_t boot_time()
{
return s_boot_time;
}
static bool update_in_progress()
{
return CMOS::read(0x0a) & 0x80;
}
static u8 bcd_to_binary(u8 bcd)
{
return (bcd & 0x0F) + ((bcd >> 4) * 10);
}
static bool try_to_read_registers(unsigned& year, unsigned& month, unsigned& day, unsigned& hour, unsigned& minute, unsigned& second)
{
// Note: Let's wait 0.01 seconds until we stop trying to query the RTC CMOS
size_t time_passed_in_milliseconds = 0;
bool update_in_progress_ended_successfully = false;
while (time_passed_in_milliseconds < 100) {
if (!update_in_progress()) {
update_in_progress_ended_successfully = true;
break;
}
IO::delay(1000);
time_passed_in_milliseconds++;
}
if (!update_in_progress_ended_successfully) {
year = 1970;
month = 1;
day = 1;
hour = 0;
minute = 0;
second = 0;
return false;
}
u8 status_b = CMOS::read(0x0b);
second = CMOS::read(0x00);
minute = CMOS::read(0x02);
hour = CMOS::read(0x04);
day = CMOS::read(0x07);
month = CMOS::read(0x08);
year = CMOS::read(0x09);
bool is_pm = hour & 0x80;
if (!(status_b & 0x04)) {
second = bcd_to_binary(second);
minute = bcd_to_binary(minute);
hour = bcd_to_binary(hour & 0x7F);
day = bcd_to_binary(day);
month = bcd_to_binary(month);
year = bcd_to_binary(year);
}
if (!(status_b & 0x02)) {
// In the 12 hour clock, midnight and noon are 12, not 0. Map it to 0.
hour %= 12;
if (is_pm)
hour += 12;
}
year += 2000;
return true;
}
time_t now()
{
auto check_registers_against_preloaded_values = [](unsigned year, unsigned month, unsigned day, unsigned hour, unsigned minute, unsigned second) {
unsigned checked_year, checked_month, checked_day, checked_hour, checked_minute, checked_second;
if (!try_to_read_registers(checked_year, checked_month, checked_day, checked_hour, checked_minute, checked_second))
return false;
return checked_year == year && checked_month == month && checked_day == day && checked_hour == hour && checked_minute == minute && checked_second == second;
};
unsigned year, month, day, hour, minute, second;
bool did_read_rtc_sucessfully = false;
for (size_t attempt = 0; attempt < 5; attempt++) {
if (!try_to_read_registers(year, month, day, hour, minute, second))
break;
if (check_registers_against_preloaded_values(year, month, day, hour, minute, second)) {
did_read_rtc_sucessfully = true;
break;
}
}
dmesgln("RTC: {} Year: {}, month: {}, day: {}, hour: {}, minute: {}, second: {}", (did_read_rtc_sucessfully ? "" : "(failed to read)"), year, month, day, hour, minute, second);
time_t days_since_epoch = years_to_days_since_epoch(year) + day_of_year(year, month, day);
return ((days_since_epoch * 24 + hour) * 60 + minute) * 60 + second;
}
}
| 1,465 |
379 |
<filename>src/main/java/com/sixt/service/framework/util/ReflectionUtil.java
/**
* Copyright 2016-2017 Sixt GmbH & Co. Autovermietung KG
* 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.sixt.service.framework.util;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class ReflectionUtil {
//hacky and dirty, augment if you find the need...
public static Class<?> findSubClassParameterType(Object instance, int parameterIndex)
throws ClassNotFoundException {
if (instance instanceof MockMethodHandler) {
if (parameterIndex == 0) {
return ((MockMethodHandler) instance).getRequestType();
} else {
return ((MockMethodHandler) instance).getResponseType();
}
}
Class<?> clazz = instance.getClass();
Type[] genericInterfaces = clazz.getGenericInterfaces();
if (genericInterfaces.length > 0) {
return retrieveGenericParameterTypes(genericInterfaces, parameterIndex);
} else if (clazz.getSuperclass() != null) {
return retrieveGenericParameterTypes(
clazz.getSuperclass().getGenericInterfaces(),
parameterIndex
);
} else {
return null;
}
}
private static Class<?> retrieveGenericParameterTypes(
final Type[] genericInterfaces,
final Integer parameterIndex
) throws ClassNotFoundException {
int count = 0;
for (Type genericInterface : genericInterfaces) {
if (genericInterface instanceof ParameterizedType) {
Type[] genericTypes = ((ParameterizedType) genericInterface).getActualTypeArguments();
for (Type genericType : genericTypes) {
if (parameterIndex == count) {
return Class.forName(genericType.getTypeName());
} else {
count++;
}
}
}
}
return null;
}
}
| 1,014 |
2,151 |
/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// Make sure that the PRI format string macros are defined
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include <stdarg.h>
#include "SkJSONWriter.h"
void SkJSONWriter::appendS64(int64_t value) {
this->beginValue();
this->appendf("%" PRId64, value);
}
void SkJSONWriter::appendU64(uint64_t value) {
this->beginValue();
this->appendf("%" PRIu64, value);
}
void SkJSONWriter::appendHexU64(uint64_t value) {
this->beginValue();
this->appendf("\"0x%" PRIx64 "\"", value);
}
void SkJSONWriter::appendf(const char* fmt, ...) {
const int kBufferSize = 1024;
char buffer[kBufferSize];
va_list argp;
va_start(argp, fmt);
#ifdef SK_BUILD_FOR_WIN
int length = _vsnprintf_s(buffer, kBufferSize, _TRUNCATE, fmt, argp);
#else
int length = vsnprintf(buffer, kBufferSize, fmt, argp);
#endif
SkASSERT(length >= 0 && length < kBufferSize);
va_end(argp);
this->write(buffer, length);
}
| 438 |
313 |
<reponame>740326093/-
//
// YBLMessageDetailViewController.h
// 手机云采
//
// Created by 乔同新 on 2017/8/1.
// Copyright © 2017年 乔同新. All rights reserved.
//
#import "YBLMainViewController.h"
#import "YBLMessageDetailViewModel.h"
@interface YBLMessageDetailViewController : YBLMainViewController
@property (nonatomic, strong) YBLMessageDetailViewModel *viewModel;
@end
| 149 |
1,176 |
<gh_stars>1000+
// Copyright (c) 2014 <NAME>.
// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// See the LICENSE file.
#ifndef THRUST_SHELL_BROWSER_UI_VIEWS_MENU_LAYOUT_H_
#define THRUST_SHELL_BROWSER_UI_VIEWS_MENU_LAYOUT_H_
#include "ui/views/layout/fill_layout.h"
namespace thrust_shell {
class MenuLayout : public views::FillLayout {
public:
explicit MenuLayout(int menu_height);
virtual ~MenuLayout();
/****************************************************************************/
/* LAYOUTMANAGER IMPLEMENTATION */
/****************************************************************************/
virtual void Layout(views::View* host) OVERRIDE;
virtual gfx::Size GetPreferredSize(const views::View* host) const OVERRIDE;
virtual int GetPreferredHeightForWidth(
const views::View* host, int width) const OVERRIDE;
private:
bool HasMenu(const views::View* host) const;
int menu_height_;
DISALLOW_COPY_AND_ASSIGN(MenuLayout);
};
} // namespace thrust_shell
#endif // THRUST_SHELL_BROWSER_UI_VIEWS_MENU_LAYOUT_H_
| 341 |
7,137 |
<filename>server-core/src/main/java/io/onedev/server/rest/jersey/ResourceConfigProvider.java
package io.onedev.server.rest.jersey;
import javax.inject.Provider;
import org.glassfish.jersey.server.ResourceConfig;
public class ResourceConfigProvider implements Provider<ResourceConfig> {
@Override
public ResourceConfig get() {
return ResourceConfig.forApplicationClass(JerseyApplication.class);
}
}
| 122 |
998 |
<filename>Source/Voxel/Private/VoxelRender/PhysicsCooker/VoxelAsyncPhysicsCooker_PhysX.cpp
// Copyright 2021 Phyronnaz
#include "VoxelRender/PhysicsCooker/VoxelAsyncPhysicsCooker_PhysX.h"
#include "VoxelRender/VoxelProcMeshBuffers.h"
#include "VoxelRender/VoxelProceduralMeshComponent.h"
#include "VoxelPhysXHelpers.h"
#include "VoxelWorldRootComponent.h"
#include "IPhysXCookingModule.h"
#include "PhysicsPublic.h"
#include "PhysicsEngine/BodySetup.h"
#include "PhysicsEngine/PhysicsSettings.h"
#if WITH_PHYSX && PHYSICS_INTERFACE_PHYSX
inline IPhysXCooking* GetPhysXCooking()
{
static IPhysXCookingModule* PhysXCookingModule = nullptr;
if (!PhysXCookingModule)
{
PhysXCookingModule = GetPhysXCookingModule();
}
return PhysXCookingModule->GetPhysXCooking();
}
static const FName PhysXFormat = FPlatformProperties::GetPhysicsFormat();
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
FVoxelAsyncPhysicsCooker_PhysX::FVoxelAsyncPhysicsCooker_PhysX(UVoxelProceduralMeshComponent* Component)
: IVoxelAsyncPhysicsCooker(Component)
, PhysXCooking(GetPhysXCooking())
{
}
class UMRMeshComponent
{
public:
static void FinishCreatingPhysicsMeshes(UBodySetup& Body, const TArray<physx::PxConvexMesh*>& ConvexMeshes, const TArray<physx::PxConvexMesh*>& ConvexMeshesNegX, const TArray<physx::PxTriangleMesh*>& TriMeshes)
{
Body.FinishCreatingPhysicsMeshes_PhysX(ConvexMeshes, ConvexMeshesNegX, TriMeshes);
}
};
bool FVoxelAsyncPhysicsCooker_PhysX::Finalize(
UBodySetup& BodySetup,
TVoxelSharedPtr<FVoxelSimpleCollisionData>& OutSimpleCollisionData,
FVoxelProceduralMeshComponentMemoryUsage& OutMemoryUsage)
{
VOXEL_FUNCTION_COUNTER();
if (ErrorCounter.GetValue() > 0)
{
return false;
}
{
VOXEL_SCOPE_COUNTER("FinishCreatingPhysicsMeshes");
UMRMeshComponent::FinishCreatingPhysicsMeshes(BodySetup, {}, {}, CookResult.TriangleMeshes);
}
OutSimpleCollisionData = CookResult.SimpleCollisionData;
OutMemoryUsage.TriangleMeshes = CookResult.TriangleMeshesMemoryUsage;
return true;
}
void FVoxelAsyncPhysicsCooker_PhysX::CookMesh()
{
if (CollisionTraceFlag != ECollisionTraceFlag::CTF_UseComplexAsSimple)
{
CreateSimpleCollision();
}
if (CollisionTraceFlag != ECollisionTraceFlag::CTF_UseSimpleAsComplex)
{
CreateTriMesh();
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FVoxelAsyncPhysicsCooker_PhysX::CreateTriMesh()
{
VOXEL_ASYNC_FUNCTION_COUNTER();
TArray<FVector> Vertices;
TArray<FTriIndices> Indices;
TArray<uint16> MaterialIndices;
// Copy data from buffers
{
VOXEL_ASYNC_SCOPE_COUNTER("Copy data from buffers");
{
int32 NumIndices = 0;
int32 NumVertices = 0;
for (auto& Buffer : Buffers)
{
NumIndices += Buffer->GetNumIndices();
NumVertices += Buffer->GetNumVertices();
}
VOXEL_ASYNC_SCOPE_COUNTER("Reserve");
Vertices.Reserve(NumVertices);
Indices.Reserve(NumIndices);
MaterialIndices.Reserve(NumIndices);
}
int32 VertexOffset = 0;
for (int32 SectionIndex = 0; SectionIndex < Buffers.Num(); SectionIndex++)
{
auto& Buffer = *Buffers[SectionIndex];
const auto Get = [](auto& Array, int32 Index) -> auto&
{
#if VOXEL_DEBUG
return Array[Index];
#else
return Array.GetData()[Index];
#endif
};
// Copy vertices
{
auto& PositionBuffer = Buffer.VertexBuffers.PositionVertexBuffer;
const int32 Offset = Vertices.Num();
check(PositionBuffer.GetNumVertices() <= uint32(Vertices.GetSlack()));
Vertices.AddUninitialized(PositionBuffer.GetNumVertices());
VOXEL_ASYNC_SCOPE_COUNTER("Copy vertices");
for (uint32 Index = 0; Index < PositionBuffer.GetNumVertices(); Index++)
{
Get(Vertices, Offset + Index) = PositionBuffer.VertexPosition(Index);
}
}
// Copy triangle data
{
auto& IndexBuffer = Buffer.IndexBuffer;
ensure(Indices.Num() == MaterialIndices.Num());
const int32 Offset = Indices.Num();
ensure(IndexBuffer.GetNumIndices() % 3 == 0);
const int32 NumTriangles = IndexBuffer.GetNumIndices() / 3;
check(NumTriangles <= Indices.GetSlack());
check(NumTriangles <= MaterialIndices.GetSlack());
Indices.AddUninitialized(NumTriangles);
MaterialIndices.AddUninitialized(NumTriangles);
{
VOXEL_ASYNC_SCOPE_COUNTER("Copy triangles");
const auto Lambda = [&](const auto* RESTRICT Data)
{
for (int32 Index = 0; Index < NumTriangles; Index++)
{
// Need to add base offset for indices
FTriIndices TriIndices;
TriIndices.v0 = Data[3 * Index + 0] + VertexOffset;
TriIndices.v1 = Data[3 * Index + 1] + VertexOffset;
TriIndices.v2 = Data[3 * Index + 2] + VertexOffset;
checkVoxelSlow(3 * Index + 2 < IndexBuffer.GetNumIndices());
Get(Indices, Offset + Index) = TriIndices;
}
};
if (IndexBuffer.Is32Bit())
{
Lambda(IndexBuffer.GetData_32());
}
else
{
Lambda(IndexBuffer.GetData_16());
}
}
// Also store material info
{
VOXEL_ASYNC_SCOPE_COUNTER("Copy material info");
for (int32 Index = 0; Index < NumTriangles; Index++)
{
Get(MaterialIndices, Offset + Index) = SectionIndex;
}
}
}
VertexOffset = Vertices.Num();
}
}
physx::PxTriangleMesh* TriangleMesh = nullptr;
constexpr bool bFlipNormals = true; // Always true due to the order of the vertices (clock wise vs not)
const bool bSuccess = PhysXCooking->CreateTriMesh(
PhysXFormat,
GetCookFlags(),
Vertices,
Indices,
MaterialIndices,
bFlipNormals,
TriangleMesh);
CookResult.TriangleMeshes.Add(TriangleMesh);
if (TriangleMesh)
{
CookResult.TriangleMeshesMemoryUsage += FVoxelPhysXHelpers::GetAllocatedSize(*TriangleMesh);
}
if (!bSuccess)
{
// Happens sometimes
LOG_VOXEL(Warning, TEXT("Failed to cook TriMesh. Num vertices: %d; Num triangles: %d"), Vertices.Num(), Indices.Num());
ErrorCounter.Increment();
}
}
void FVoxelAsyncPhysicsCooker_PhysX::CreateSimpleCollision()
{
VOXEL_ASYNC_FUNCTION_COUNTER();
if (Buffers.Num() == 1 && Buffers[0]->GetNumVertices() < 4) return;
CookResult.SimpleCollisionData = MakeVoxelShared<FVoxelSimpleCollisionData>();
FVoxelSimpleCollisionData& SimpleCollisionData = *CookResult.SimpleCollisionData;
SimpleCollisionData.Bounds = FBox(ForceInit);
if (bSimpleCubicCollision)
{
VOXEL_ASYNC_SCOPE_COUNTER("BoxElems");
TArray<FKBoxElem>& BoxElems = SimpleCollisionData.BoxElems;
for (auto& Buffer : Buffers)
{
for (FBox Cube : Buffer->CollisionCubes)
{
Cube = Cube.TransformBy(LocalToRoot);
SimpleCollisionData.Bounds += Cube;
FKBoxElem& BoxElem = BoxElems.Emplace_GetRef();
BoxElem.Center = Cube.GetCenter();
BoxElem.X = Cube.GetExtent().X * 2;
BoxElem.Y = Cube.GetExtent().Y * 2;
BoxElem.Z = Cube.GetExtent().Z * 2;
}
}
}
else
{
VOXEL_ASYNC_SCOPE_COUNTER("ConvexElems");
TArray<FKConvexElem>& ConvexElems = SimpleCollisionData.ConvexElems;
FBox Box(ForceInit);
for (auto& Buffer : Buffers)
{
auto& PositionBuffer = Buffer->VertexBuffers.PositionVertexBuffer;
for (uint32 Index = 0; Index < PositionBuffer.GetNumVertices(); Index++)
{
Box += PositionBuffer.VertexPosition(Index);
}
}
const int32 ChunkSize = MESHER_CHUNK_SIZE << LOD;
const FIntVector Size =
FVoxelUtilities::ComponentMax(
FIntVector(1),
FVoxelUtilities::CeilToInt(Box.GetSize() / ChunkSize * NumConvexHullsPerAxis));
if (!ensure(Size.GetMax() <= 64)) return;
ConvexElems.SetNum(Size.X * Size.Y * Size.Z);
for (auto& Buffer : Buffers)
{
auto& PositionBuffer = Buffer->VertexBuffers.PositionVertexBuffer;
for (uint32 Index = 0; Index < PositionBuffer.GetNumVertices(); Index++)
{
const FVector Vertex = PositionBuffer.VertexPosition(Index);
FIntVector MainPosition;
const auto Lambda = [&](int32 OffsetX, int32 OffsetY, int32 OffsetZ)
{
const FVector Offset = FVector(OffsetX, OffsetY, OffsetZ) * (1 << LOD); // 1 << LOD: should be max distance between the vertices
FIntVector Position = FVoxelUtilities::FloorToInt((Vertex + Offset - Box.Min) / ChunkSize * NumConvexHullsPerAxis);
Position = FVoxelUtilities::Clamp(Position, FIntVector(0), Size - 1);
// Avoid adding too many duplicates by checking we're not in the center
if (OffsetX == 0 && OffsetY == 0 && OffsetZ == 0)
{
MainPosition = Position;
}
else
{
if (Position == MainPosition)
{
return;
}
}
ConvexElems[Position.X + Size.X * Position.Y + Size.X * Size.Y * Position.Z].VertexData.Add(Vertex);
};
Lambda(0, 0, 0);
// Iterate possible neighbors to avoid holes between hulls
Lambda(+1, 0, 0);
Lambda(-1, 0, 0);
Lambda(0, +1, 0);
Lambda(0, -1, 0);
Lambda(0, 0, +1);
Lambda(0, 0, -1);
}
}
constexpr int32 Threshold = 8;
// Merge the hulls until they are big enough
// This moves the vertices to the end
for (int32 Index = 0; Index < ConvexElems.Num() - 1; Index++)
{
auto& Element = ConvexElems[Index];
if (Element.VertexData.Num() < Threshold)
{
ConvexElems[Index + 1].VertexData.Append(Element.VertexData);
Element.VertexData.Reset();
}
}
// Remove all empty hulls
ConvexElems.RemoveAll([](auto& Element) { return Element.VertexData.Num() == 0; });
if (!ensure(ConvexElems.Num() > 0)) return;
// Then merge backwards while the last hull isn't big enough
while (ConvexElems.Last().VertexData.Num() < Threshold && ConvexElems.Num() > 1)
{
ConvexElems[ConvexElems.Num() - 2].VertexData.Append(ConvexElems.Last().VertexData);
ConvexElems.Pop();
}
// Transform from component space to root component space, as the root is going to hold the convex meshes,
// and update bounds
for (auto& Element : ConvexElems)
{
ensure(Element.VertexData.Num() >= 4);
for (auto& Vertex : Element.VertexData)
{
Vertex = LocalToRoot.TransformPosition(Vertex);
}
Element.UpdateElemBox();
SimpleCollisionData.Bounds += Element.ElemBox;
}
// Finally, create the physx data
for (FKConvexElem& Element : ConvexElems)
{
VOXEL_ASYNC_SCOPE_COUNTER("CreateConvex");
PxConvexMesh* Mesh = nullptr;
const EPhysXCookingResult Result = PhysXCooking->CreateConvex(PhysXFormat, GetCookFlags(), Element.VertexData, Mesh);
switch (Result)
{
case EPhysXCookingResult::Failed:
{
LOG_VOXEL(Warning, TEXT("Failed to cook convex"));
ErrorCounter.Increment();
break;
}
case EPhysXCookingResult::SucceededWithInflation:
{
LOG_VOXEL(Warning, TEXT("Cook convex failed but succeeded with inflation"));
break;
}
case EPhysXCookingResult::Succeeded: break;
default: ensure(false);
}
SimpleCollisionData.ConvexMeshes.Add(Mesh);
}
}
}
EPhysXMeshCookFlags FVoxelAsyncPhysicsCooker_PhysX::GetCookFlags() const
{
EPhysXMeshCookFlags CookFlags = EPhysXMeshCookFlags::Default;
if (!bCleanCollisionMesh)
{
CookFlags |= EPhysXMeshCookFlags::DeformableMesh;
}
// TODO try and bench CookFlags |= EPhysXMeshCookFlags::DisableActiveEdgePrecompute;
// TODO: option/check perf
CookFlags |= EPhysXMeshCookFlags::FastCook;
return CookFlags;
}
#endif
| 5,894 |
465 |
<reponame>NetsanetGeb/marmaray
/*
* Copyright (c) 2019 Uber Technologies, Inc.
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package com.uber.marmaray.common.configuration;
import com.uber.marmaray.common.util.KafkaTestHelper;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestKafkaSourceConfiguration {
@Test
public void constructorWithStartDate() {
final SimpleDateFormat dateFormat = new SimpleDateFormat(KafkaSourceConfiguration.KAFKA_START_DATE_FORMAT);
final String startDate = dateFormat.format(new Date());
final KafkaSourceConfiguration kafkaConfig = KafkaTestHelper.getKafkaSourceConfiguration(
"topic-name", "broker-address", startDate);
final long expectedStartDateEpoch = DateTime.parse(startDate, DateTimeFormat.forPattern(
KafkaSourceConfiguration.KAFKA_START_DATE_FORMAT).withZoneUTC()).toDate().getTime();
Assert.assertEquals(kafkaConfig.getStartTime(), expectedStartDateEpoch);
}
@Test
public void constructorWithStartTime() {
// If both start_date and start_time are specified, start_time should take precedence.
final SimpleDateFormat dateFormat = new SimpleDateFormat(KafkaSourceConfiguration.KAFKA_START_DATE_FORMAT);
final String startDate = dateFormat.format(new Date());
final String startDateAsEpoch = String.valueOf(DateTime.parse(startDate, DateTimeFormat.forPattern(
KafkaSourceConfiguration.KAFKA_START_DATE_FORMAT).withZoneUTC()).toDate().getTime());
final String startTime = String.valueOf(Long.valueOf(startDateAsEpoch) - 500);
final KafkaSourceConfiguration kafkaConfig = KafkaTestHelper.getKafkaSourceConfiguration(
"topic-name", "broker-address", startDate, startTime);
Assert.assertEquals(kafkaConfig.getStartTime(), (long) Long.valueOf(startTime));
}
@Test(expected = RuntimeException.class)
public void constructorWithInvalidStartDate() {
KafkaTestHelper.getKafkaSourceConfiguration(
"topic-name", "broker-address", "1970-01-01");
}
@Test(expected = RuntimeException.class)
public void constructorWithInvalidStartTime() {
final SimpleDateFormat dateFormat = new SimpleDateFormat(KafkaSourceConfiguration.KAFKA_START_DATE_FORMAT);
final String startDate = dateFormat.format(new Date());
// The start_date is valid, but the start_time is not.
KafkaTestHelper.getKafkaSourceConfiguration(
"topic-name", "broker-address", startDate, "1000000");
}
}
| 1,233 |
575 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_OFFLINE_ITEMS_COLLECTION_CORE_FILTERED_OFFLINE_ITEM_OBSERVER_H_
#define COMPONENTS_OFFLINE_ITEMS_COLLECTION_CORE_FILTERED_OFFLINE_ITEM_OBSERVER_H_
#include <map>
#include <memory>
#include "base/macros.h"
#include "base/observer_list.h"
#include "base/scoped_observation.h"
#include "components/offline_items_collection/core/offline_content_provider.h"
#include "components/offline_items_collection/core/offline_item.h"
namespace offline_items_collection {
// Provides clients the ability to register observers interested only in the
// updates for a single offline item.
class FilteredOfflineItemObserver : public OfflineContentProvider::Observer {
public:
// Observer for a single offline item.
class Observer {
public:
virtual void OnItemRemoved(const ContentId& id) = 0;
virtual void OnItemUpdated(
const OfflineItem& item,
const base::Optional<UpdateDelta>& update_delta) = 0;
protected:
virtual ~Observer() = default;
};
FilteredOfflineItemObserver(OfflineContentProvider* provider);
~FilteredOfflineItemObserver() override;
void AddObserver(const ContentId& id, Observer* observer);
void RemoveObserver(const ContentId& id, Observer* observer);
private:
using ObserverValue = base::ObserverList<Observer>::Unchecked;
using ObserversMap = std::map<ContentId, std::unique_ptr<ObserverValue>>;
// OfflineContentProvider::Observer implementation.
void OnItemsAdded(
const OfflineContentProvider::OfflineItemList& items) override;
void OnItemRemoved(const ContentId& id) override;
void OnItemUpdated(const OfflineItem& item,
const base::Optional<UpdateDelta>& update_delta) override;
void OnContentProviderGoingDown() override;
OfflineContentProvider* provider_;
base::ScopedObservation<OfflineContentProvider,
OfflineContentProvider::Observer>
observation_{this};
ObserversMap observers_;
DISALLOW_COPY_AND_ASSIGN(FilteredOfflineItemObserver);
};
} // namespace offline_items_collection
#endif // COMPONENTS_OFFLINE_ITEMS_COLLECTION_CORE_FILTERED_OFFLINE_ITEM_OBSERVER_H_
| 758 |
4,816 |
/**
* @file include/retdec/serdes/object.h
* @brief Object (de)serialization.
* @copyright (c) 2019 Avast Software, licensed under the MIT license
*/
#ifndef RETDEC_SERDES_OBJECT_H
#define RETDEC_SERDES_OBJECT_H
#include <rapidjson/document.h>
namespace retdec {
namespace common {
class Object;
} // namespace common
namespace serdes {
template <typename Writer>
void serialize(Writer& writer, const common::Object& o);
void deserialize(const rapidjson::Value& val, common::Object& o);
} // namespace serdes
} // namespace retdec
#endif
| 181 |
7,482 |
<gh_stars>1000+
/*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_specification.h"
#include "fsl_card.h"
/*******************************************************************************
* Variables
******************************************************************************/
SDK_ALIGN(uint32_t g_sdmmc[SDK_SIZEALIGN(SDMMC_GLOBAL_BUFFER_SIZE, SDMMC_DATA_BUFFER_ALIGN_CAHCE)],
MAX(SDMMC_DATA_BUFFER_ALIGN_CAHCE, HOST_DMA_BUFFER_ADDR_ALIGN));
/*******************************************************************************
* Code
******************************************************************************/
void SDMMC_Delay(uint32_t num)
{
volatile uint32_t i, j;
for (i = 0U; i < num; i++)
{
for (j = 0U; j < 10000U; j++)
{
__asm("nop");
}
}
}
status_t SDMMC_SelectCard(HOST_TYPE *base, HOST_TRANSFER_FUNCTION transfer, uint32_t relativeAddress, bool isSelected)
{
assert(transfer);
HOST_TRANSFER content = {0};
HOST_COMMAND command = {0};
command.index = kSDMMC_SelectCard;
if (isSelected)
{
command.argument = relativeAddress << 16U;
command.responseType = kCARD_ResponseTypeR1;
}
else
{
command.argument = 0U;
command.responseType = kCARD_ResponseTypeNone;
}
content.command = &command;
content.data = NULL;
if ((kStatus_Success != transfer(base, &content)) || (command.response[0U] & kSDMMC_R1ErrorAllFlag))
{
return kStatus_SDMMC_TransferFailed;
}
/* Wait until card to transfer state */
return kStatus_Success;
}
status_t SDMMC_SendApplicationCommand(HOST_TYPE *base, HOST_TRANSFER_FUNCTION transfer, uint32_t relativeAddress)
{
assert(transfer);
HOST_TRANSFER content = {0};
HOST_COMMAND command = {0};
command.index = kSDMMC_ApplicationCommand;
command.argument = (relativeAddress << 16U);
command.responseType = kCARD_ResponseTypeR1;
content.command = &command;
content.data = 0U;
if ((kStatus_Success != transfer(base, &content)) || (command.response[0U] & kSDMMC_R1ErrorAllFlag))
{
return kStatus_SDMMC_TransferFailed;
}
if (!(command.response[0U] & kSDMMC_R1ApplicationCommandFlag))
{
return kStatus_SDMMC_CardNotSupport;
}
return kStatus_Success;
}
status_t SDMMC_SetBlockCount(HOST_TYPE *base, HOST_TRANSFER_FUNCTION transfer, uint32_t blockCount)
{
assert(transfer);
HOST_TRANSFER content = {0};
HOST_COMMAND command = {0};
command.index = kSDMMC_SetBlockCount;
command.argument = blockCount;
command.responseType = kCARD_ResponseTypeR1;
content.command = &command;
content.data = 0U;
if ((kStatus_Success != transfer(base, &content)) || (command.response[0U] & kSDMMC_R1ErrorAllFlag))
{
return kStatus_SDMMC_TransferFailed;
}
return kStatus_Success;
}
status_t SDMMC_GoIdle(HOST_TYPE *base, HOST_TRANSFER_FUNCTION transfer)
{
assert(transfer);
HOST_TRANSFER content = {0};
HOST_COMMAND command = {0};
command.index = kSDMMC_GoIdleState;
content.command = &command;
content.data = 0U;
if (kStatus_Success != transfer(base, &content))
{
return kStatus_SDMMC_TransferFailed;
}
return kStatus_Success;
}
status_t SDMMC_SetBlockSize(HOST_TYPE *base, HOST_TRANSFER_FUNCTION transfer, uint32_t blockSize)
{
assert(transfer);
HOST_TRANSFER content = {0};
HOST_COMMAND command = {0};
command.index = kSDMMC_SetBlockLength;
command.argument = blockSize;
command.responseType = kCARD_ResponseTypeR1;
content.command = &command;
content.data = 0U;
if ((kStatus_Success != transfer(base, &content)) || (command.response[0U] & kSDMMC_R1ErrorAllFlag))
{
return kStatus_SDMMC_TransferFailed;
}
return kStatus_Success;
}
status_t SDMMC_SetCardInactive(HOST_TYPE *base, HOST_TRANSFER_FUNCTION transfer)
{
assert(transfer);
HOST_TRANSFER content = {0};
HOST_COMMAND command = {0};
command.index = kSDMMC_GoInactiveState;
command.argument = 0U;
command.responseType = kCARD_ResponseTypeNone;
content.command = &command;
content.data = 0U;
if ((kStatus_Success != transfer(base, &content)))
{
return kStatus_SDMMC_TransferFailed;
}
return kStatus_Success;
}
status_t SDMMC_SwitchVoltage(HOST_TYPE *base, HOST_TRANSFER_FUNCTION transfer)
{
assert(transfer);
HOST_TRANSFER content = {0};
HOST_COMMAND command = {0};
command.index = kSD_VoltageSwitch;
command.argument = 0U;
command.responseType = kCARD_ResponseTypeR1;
content.command = &command;
content.data = NULL;
if (kStatus_Success != transfer(base, &content))
{
return kStatus_SDMMC_TransferFailed;
}
/* disable card clock */
HOST_ENABLE_CARD_CLOCK(base, false);
/* check data line and cmd line status */
if ((GET_HOST_STATUS(base) &
(CARD_DATA1_STATUS_MASK | CARD_DATA2_STATUS_MASK | CARD_DATA3_STATUS_MASK | CARD_DATA0_NOT_BUSY)) != 0U)
{
return kStatus_SDMMC_SwitchVoltageFail;
}
/* host switch to 1.8V */
HOST_SWITCH_VOLTAGE180V(base, true);
SDMMC_Delay(100U);
/*enable sd clock*/
HOST_ENABLE_CARD_CLOCK(base, true);
/*enable force clock on*/
HOST_FORCE_SDCLOCK_ON(base, true);
/* dealy 1ms,not exactly correct when use while */
SDMMC_Delay(10U);
/*disable force clock on*/
HOST_FORCE_SDCLOCK_ON(base, false);
/* check data line and cmd line status */
if ((GET_HOST_STATUS(base) &
(CARD_DATA1_STATUS_MASK | CARD_DATA2_STATUS_MASK | CARD_DATA3_STATUS_MASK | CARD_DATA0_NOT_BUSY)) == 0U)
{
return kStatus_SDMMC_SwitchVoltageFail;
}
return kStatus_Success;
}
status_t SDMMC_ExecuteTuning(HOST_TYPE *base, HOST_TRANSFER_FUNCTION transfer, uint32_t tuningCmd, uint32_t blockSize)
{
HOST_TRANSFER content = {0U};
HOST_COMMAND command = {0U};
HOST_DATA data = {0U};
uint32_t buffer[32U] = {0U};
bool tuningError = true;
command.index = tuningCmd;
command.argument = 0U;
command.responseType = kCARD_ResponseTypeR1;
data.blockSize = blockSize;
data.blockCount = 1U;
data.rxData = buffer;
/* add this macro for adpter to different driver */
HOST_ENABLE_TUNING_FLAG(data);
content.command = &command;
content.data = &data;
/* enable the standard tuning */
HOST_EXECUTE_STANDARD_TUNING_ENABLE(base, true);
while (true)
{
/* send tuning block */
if ((kStatus_Success != transfer(base, &content)))
{
return kStatus_SDMMC_TransferFailed;
}
SDMMC_Delay(1U);
/*wait excute tuning bit clear*/
if ((HOST_EXECUTE_STANDARD_TUNING_STATUS(base) != 0U))
{
continue;
}
/* if tuning error , re-tuning again */
if ((HOST_CHECK_TUNING_ERROR(base) != 0U) && tuningError)
{
tuningError = false;
/* enable the standard tuning */
HOST_EXECUTE_STANDARD_TUNING_ENABLE(base, true);
HOST_ADJUST_TUNING_DELAY(base, HOST_STANDARD_TUNING_START);
}
else
{
break;
}
}
/* delay to wait the host controller stable */
SDMMC_Delay(100U);
/* check tuning result*/
if (HOST_EXECUTE_STANDARD_TUNING_RESULT(base) == 0U)
{
return kStatus_SDMMC_TuningFail;
}
HOST_AUTO_STANDARD_RETUNING_TIMER(base);
return kStatus_Success;
}
| 3,245 |
324 |
<gh_stars>100-1000
import typer
from tiktokpy import TikTokPy
from tiktokpy.cli.utils import coro
app = typer.Typer()
@app.command()
@coro
async def login():
async with TikTokPy() as bot:
await bot.login_session()
@app.callback()
def callback():
pass
| 110 |
1,444 |
<filename>Mage.Sets/src/mage/cards/r/RuinationRioter.java
package mage.cards.r;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.DiesSourceTriggeredAbility;
import mage.abilities.dynamicvalue.DynamicValue;
import mage.abilities.dynamicvalue.common.CardsInControllerGraveyardCount;
import mage.abilities.effects.common.DamageTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.filter.StaticFilters;
import mage.target.common.TargetAnyTarget;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class RuinationRioter extends CardImpl {
private static final DynamicValue xValue = new CardsInControllerGraveyardCount(StaticFilters.FILTER_CARD_LAND);
public RuinationRioter(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{R}{G}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.BERSERKER);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// When Ruination Rioter dies, you may have it deal damage to any target equal to the number of land cards in your graveyard.
Ability ability = new DiesSourceTriggeredAbility(
new DamageTargetEffect(xValue).setText("you may have it deal damage to any target " +
"equal to the number of land cards in your graveyard."), true
);
ability.addTarget(new TargetAnyTarget());
this.addAbility(ability);
}
private RuinationRioter(final RuinationRioter card) {
super(card);
}
@Override
public RuinationRioter copy() {
return new RuinationRioter(this);
}
}
| 641 |
4,283 |
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.logging;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.logging.impl.LoggingServiceImpl;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.IsolatedLoggingRule;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static com.hazelcast.test.IsolatedLoggingRule.LOGGING_TYPE_JDK;
import static org.junit.Assert.assertEquals;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class JdkLoggerLevelChangeTest extends HazelcastTestSupport {
@Rule
public final IsolatedLoggingRule isolatedLoggingRule = new IsolatedLoggingRule();
private LoggingServiceImpl loggingService;
private TestHandler handler;
private ILogger logger;
@Before
public void before() {
isolatedLoggingRule.setLoggingType(LOGGING_TYPE_JDK);
HazelcastInstance instance = createHazelcastInstance();
loggingService = (LoggingServiceImpl) instance.getLoggingService();
handler = new TestHandler();
Logger.getLogger(JdkLoggerLevelChangeTest.class.getName()).addHandler(handler);
logger = loggingService.getLogger(JdkLoggerLevelChangeTest.class.getName());
}
@Test
public void test() {
assertEquals(0, handler.hits);
logger.finest("foo");
assertEquals(0, handler.hits);
logger.severe("foo");
assertEquals(1, handler.hits);
loggingService.setLevel(Level.OFF);
logger.severe("foo");
assertEquals(2, handler.hits);
loggingService.setLevel(Level.FINEST);
logger.finest("foo");
assertEquals(3, handler.hits);
loggingService.resetLevel();
logger.finest("foo");
assertEquals(3, handler.hits);
logger.severe("foo");
assertEquals(4, handler.hits);
}
private static class TestHandler extends Handler {
public int hits;
@Override
public void publish(LogRecord record) {
if (JdkLoggerLevelChangeTest.class.getName().equals(record.getLoggerName())) {
hits += 1;
}
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
}
}
}
| 1,181 |
891 |
<reponame>eregon/jnr-ffi
/*
* Copyright (C) 2008-2010 <NAME>
*
* This file is part of the JNR 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 jnr.ffi.provider;
import jnr.ffi.mapper.FunctionMapper;
/**
* An implementation of {@link FunctionMapper} that just returns the same name as input
*/
public class IdentityFunctionMapper implements FunctionMapper {
private static final class SingletonHolder {
public static final FunctionMapper INSTANCE = new IdentityFunctionMapper();
}
public static FunctionMapper getInstance() {
return SingletonHolder.INSTANCE;
}
public String mapFunctionName(String functionName, Context context) {
return functionName;
}
}
| 363 |
9,088 |
<filename>src/providers/console-logging-provider.h
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#pragma once
#include <napa/providers/logging.h>
#include <stdio.h>
namespace napa {
namespace providers {
/// <summary> A logging provider that logs to the standard console. </summary>
class ConsoleLoggingProvider : public LoggingProvider {
public:
virtual void LogMessage(
const char* section,
Verboseness level,
const char* traceId,
const char* file,
int line,
const char* message) override {
if (section == nullptr || section[0] == '\0') {
printf("%s [%s:%d]\n", message, file, line);
} else {
printf("[%s] %s [%s:%d]\n", section, message, file, line);
}
}
virtual bool IsLogEnabled(const char* section, Verboseness level) override {
return true;
}
virtual void Destroy() override {
// Don't actually delete. We're a lifetime process object.
}
};
}
}
| 494 |
892 |
{
"schema_version": "1.2.0",
"id": "GHSA-c93f-9f7g-fv7h",
"modified": "2022-05-13T01:19:17Z",
"published": "2022-05-13T01:19:17Z",
"aliases": [
"CVE-2018-16789"
],
"details": "libhttp/url.c in shellinabox through 2.20 has an implementation flaw in the HTTP request parsing logic. By sending a crafted multipart/form-data HTTP request, an attacker could exploit this to force shellinaboxd into an infinite loop, exhausting available CPU resources and taking the service down.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2018-16789"
},
{
"type": "WEB",
"url": "https://github.com/shellinabox/shellinabox/commit/4f0ecc31ac6f985e0dd3f5a52cbfc0e9251f6361"
},
{
"type": "WEB",
"url": "https://code.google.com/archive/p/shellinabox/issues"
},
{
"type": "WEB",
"url": "http://packetstormsecurity.com/files/149978/Shell-In-A-Box-2.2.0-Denial-Of-Service.html"
},
{
"type": "WEB",
"url": "http://seclists.org/fulldisclosure/2018/Oct/50"
}
],
"database_specific": {
"cwe_ids": [
"CWE-835"
],
"severity": "HIGH",
"github_reviewed": false
}
}
| 651 |
446 |
<gh_stars>100-1000
from typing import Any, Callable, Generator, List
from random import randint
def preprocess_char_based(sentence: List[str]) -> List[str]:
return list(" ".join(sentence))
def preprocess_add_noise(sentence: List[str]) -> List[str]:
sent = sentence[:]
length = len(sentence)
if length > 1:
for _ in range(length // 2):
swap = randint(0, length - 2)
sent[swap] = sent[swap + 1]
sent[swap + 1] = sent[swap]
return sent
# TODO refactor post-processors to work on sentence level
def postprocess_char_based(sentences: List[List[str]]) -> List[List[str]]:
result = []
for sentence in sentences:
joined = "".join(sentence)
tokenized = joined.split(" ")
result.append(tokenized)
return result
def untruecase(
sentences: List[List[str]]) -> Generator[List[str], None, None]:
for sentence in sentences:
if sentence:
yield [sentence[0].capitalize()] + sentence[1:]
else:
yield []
def pipeline(processors: List[Callable]) -> Callable:
"""Concatenate processors."""
def process(data: Any) -> Any:
for processor in processors:
data = processor(data)
return data
return process
| 520 |
1,442 |
<filename>poincare/include/poincare/empty_context.h
#ifndef POINCARE_EMPTY_CONTEXT_H
#define POINCARE_EMPTY_CONTEXT_H
#include <poincare/context.h>
#include <poincare/expression.h>
#include <assert.h>
namespace Poincare {
class EmptyContext : public Context {
public:
// Context
SymbolAbstractType expressionTypeForIdentifier(const char * identifier, int length) override { return SymbolAbstractType::None; }
void setExpressionForSymbolAbstract(const Expression & expression, const SymbolAbstract & symbol) override { assert(false); }
const Expression expressionForSymbolAbstract(const SymbolAbstract & symbol, bool clone, float unknownSymbolValue = NAN) override { return Expression(); }
};
}
#endif
| 207 |
971 |
#pragma once
#include "execution/sql/value.h"
namespace noisepage::execution::sql {
/**
* Utility class to handle mini runners functions
*/
class EXPORT MiniRunnersFunctions {
public:
// Delete to force only static functions
MiniRunnersFunctions() = delete;
/**
* Emit tuples
* @param ctx ExecutionContext
* @param num_tuples Number tuples
* @param num_cols Number columns
* @param num_int_cols Number ints
* @param num_real_cols Number reals
*/
static void EmitTuples(noisepage::execution::exec::ExecutionContext *ctx, const Integer &num_tuples,
const Integer &num_cols, const Integer &num_int_cols, const Integer &num_real_cols) {
if (num_tuples.val_ < 2) return;
// We are already in an output slot
auto *output_buffer = ctx->OutputBufferNew();
static_assert(sizeof(Integer) == sizeof(Real));
for (auto row = 0; row < num_tuples.val_ - 1; row++) {
auto output_alloc = output_buffer->AllocOutputSlot();
auto j = 0;
for (auto icol = 0; icol < num_int_cols.val_; icol++) {
reinterpret_cast<Integer *>(output_alloc)[j] = execution::sql::Integer(row);
j++;
}
for (auto rcol = 0; rcol < num_real_cols.val_; rcol++) {
reinterpret_cast<Real *>(output_alloc)[j] = execution::sql::Real(row * 1.0);
j++;
}
}
// Destroy the OutputBuffer
output_buffer->Finalize();
auto *pool = output_buffer->GetMemoryPool();
output_buffer->~OutputBuffer();
pool->Deallocate(output_buffer, sizeof(exec::OutputBuffer));
}
};
} // namespace noisepage::execution::sql
| 626 |
1,346 |
<filename>Trakttv.bundle/Contents/Libraries/Shared/plugin/scrobbler/main.py
from plugin.core.constants import ACTIVITY_MODE
from plugin.core.helpers.thread import module
from plugin.core.method_manager import MethodManager
from plugin.preferences import Preferences
from plugin.scrobbler.methods import Logging, WebSocket
@module(start=True, blocking=True)
class Scrobbler(object):
methods = MethodManager([
WebSocket,
Logging
])
started = []
@classmethod
def start(cls, blocking=False):
enabled = ACTIVITY_MODE.get(Preferences.get('activity.mode'))
# Start methods
cls.started = cls.methods.start(enabled)
| 241 |
571 |
<gh_stars>100-1000
/***************************************************************************
Copyright 2016 Ufora 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.
****************************************************************************/
#include "PyObjectWalker.hpp"
#include "ClassOrFunctionInfo.hpp"
#include "FileDescription.hpp"
#include "FreeVariableResolver.hpp"
#include "PyObjectUtils.hpp"
#include "exceptions/PyforaErrors.hpp"
#include <cassert>
#include <stdexcept>
#include <vector>
namespace {
bool _isPrimitive(const PyObject* pyObject)
{
return Py_None == pyObject or
PyInt_Check(pyObject) or
PyFloat_Check(pyObject) or
PyString_Check(pyObject) or
PyBool_Check(pyObject);
}
bool _allPrimitives(const PyObject* pyList)
{
// precondition: the argument must be a PyList
Py_ssize_t size = PyList_GET_SIZE(pyList);
for (Py_ssize_t ix = 0; ix < size; ++ix)
{
if (not _isPrimitive(PyList_GET_ITEM(pyList, ix)))
return false;
}
return true;
}
} // anonymous namespace
PyObjectWalker::PyObjectWalker(
const PyObjectPtr& purePythonClassMapping,
BinaryObjectRegistry& objectRegistry,
const PyObjectPtr& excludePredicateFun,
const PyObjectPtr& excludeList,
const PyObjectPtr& terminalValueFilter,
const PyObjectPtr& traceback_type,
const PyObjectPtr& pythonTracebackToJsonFun) :
mPureImplementationMappings(purePythonClassMapping),
mExcludePredicateFun(excludePredicateFun),
mExcludeList(excludeList),
mTracebackType(traceback_type),
mPythonTracebackToJsonFun(pythonTracebackToJsonFun),
mObjectRegistry(objectRegistry),
mFreeVariableResolver(excludeList, terminalValueFilter)
{
_initPythonSingletonToName();
_initRemotePythonObjectClass();
_initPackedHomogenousDataClass();
_initFutureClass();
_initPyforaWithBlockClass();
_initUnconvertibleClass();
_initPyforaConnectHack();
}
void PyObjectWalker::_initPyforaWithBlockClass()
{
PyObjectPtr withBlockModule = PyObjectPtr::unincremented(
PyImport_ImportModule("pyfora.PyforaWithBlock"));
if (withBlockModule == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_initPyforaWithBlockClass: " +
PyObjectUtils::exc_string()
);
}
mPyforaWithBlockClass = PyObjectPtr::unincremented(
PyObject_GetAttrString(
withBlockModule.get(),
"PyforaWithBlock"
)
);
if (mPyforaWithBlockClass == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_initPyforaWithBlockClass: " +
PyObjectUtils::exc_string()
);
}
}
void PyObjectWalker::_initFutureClass()
{
PyObjectPtr futureModule = PyObjectPtr::unincremented(
PyImport_ImportModule("pyfora.Future"));
if (futureModule == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_initFutureClass: " +
PyObjectUtils::exc_string()
);
}
mFutureClass = PyObjectPtr::unincremented(
PyObject_GetAttrString(futureModule.get(), "Future"));
if (mFutureClass == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_initFutureClass: " +
PyObjectUtils::exc_string()
);
}
}
void PyObjectWalker::_initPackedHomogenousDataClass()
{
PyObjectPtr typeDescriptionModule = PyObjectPtr::unincremented(
PyImport_ImportModule("pyfora.TypeDescription"));
if (typeDescriptionModule == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_initPackedHomogenousDataClass: " +
PyObjectUtils::exc_string()
);
}
mPackedHomogenousDataClass = PyObjectPtr::unincremented(
PyObject_GetAttrString(typeDescriptionModule.get(),
"PackedHomogenousData")
);
if (mPackedHomogenousDataClass == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_initPackedHomogenousDataClass: " +
PyObjectUtils::exc_string()
);
}
}
void PyObjectWalker::_initRemotePythonObjectClass()
{
PyObjectPtr remotePythonObjectModule = PyObjectPtr::unincremented(
PyImport_ImportModule("pyfora.RemotePythonObject"));
if (remotePythonObjectModule == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_initRemotePythonObjectClass: " +
PyObjectUtils::exc_string()
);
}
mRemotePythonObjectClass = PyObjectPtr::unincremented(
PyObject_GetAttrString(remotePythonObjectModule.get(),
"RemotePythonObject")
);
if (mRemotePythonObjectClass == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_initRemotePythonObjectClass: " +
PyObjectUtils::exc_string()
);
}
}
void PyObjectWalker::_initPythonSingletonToName()
{
PyObjectPtr namedSingletonsModule = PyObjectPtr::unincremented(
PyImport_ImportModule("pyfora.NamedSingletons"));
if (namedSingletonsModule == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_initPythonSingletonToName: " +
PyObjectUtils::exc_string()
);
}
PyObjectPtr pythonSingletonToName = PyObjectPtr::unincremented(
PyObject_GetAttrString(
namedSingletonsModule.get(),
"pythonSingletonToName"
)
);
if (pythonSingletonToName == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_initPythonSingletonToName: " +
PyObjectUtils::exc_string()
);
}
if (not PyDict_Check(pythonSingletonToName.get())) {
throw std::runtime_error(
"py err in PyObjectWalker::_initPythonSingletonToName: " +
PyObjectUtils::exc_string()
);
}
PyObject * key, * value;
Py_ssize_t pos = 0;
char* string = nullptr;
Py_ssize_t length = 0;
while (PyDict_Next(pythonSingletonToName.get(), &pos, &key, &value)) {
if (PyString_AsStringAndSize(value, &string, &length) == -1) {
throw std::runtime_error(
"py err in PyObjectWalker::_initPythonSingletonToName: " +
PyObjectUtils::exc_string()
);
}
Py_INCREF(key);
mPythonSingletonToName[key] = std::string(string, length);
}
}
void PyObjectWalker::_initUnconvertibleClass() {
PyObjectPtr unconvertibleModule = PyObjectPtr::unincremented(
PyImport_ImportModule("pyfora.Unconvertible"));
if (unconvertibleModule == nullptr) {
throw std::runtime_error(
"py error getting unconvertibleModule in "
"PyObjectWalker::_initUnconvertibleClass: " +
PyObjectUtils::exc_string()
);
}
mUnconvertibleClass = PyObjectPtr::unincremented(PyObject_GetAttrString(
unconvertibleModule.get(),
"Unconvertible"
));
if (mUnconvertibleClass == nullptr) {
throw std::runtime_error(
"py error getting unconvertibleModule in "
"PyObjectWalker::_initUnconvertibleClass " +
PyObjectUtils::exc_string()
);
}
}
void PyObjectWalker::_initPyforaConnectHack() {
PyObjectPtr pyforaModule = PyObjectPtr::unincremented(
PyImport_ImportModule("pyfora"));
if (pyforaModule == nullptr) {
throw std::runtime_error(
"py error in PyObjectWalker::_initPyforaConnectHack: " +
PyObjectUtils::exc_string()
);
}
mPyforaConnectHack = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyforaModule.get(), "connect"));
if (mPyforaConnectHack == nullptr) {
throw std::runtime_error(
"py error getting pyfora.connect in "
"PyObjectWalker::_initPyforaConnectHack: " +
PyObjectUtils::exc_string()
);
}
}
PyObjectWalker::~PyObjectWalker()
{
for (const auto& p: mPyObjectToObjectId) {
Py_DECREF(p.first);
}
for (const auto& p: mPythonSingletonToName) {
Py_DECREF(p.first);
}
}
int64_t PyObjectWalker::_allocateId(PyObject* pyObject) {
int64_t objectId = mObjectRegistry.allocateObject();
Py_INCREF(pyObject);
mPyObjectToObjectId[pyObject] = objectId;
return objectId;
}
PyObjectWalker::WalkResult PyObjectWalker::walkPyObject(PyObject* pyObject)
{
WalkResult tr;
{
auto it = mPyObjectToObjectId.find(pyObject);
if (it != mPyObjectToObjectId.end()) {
tr.set<int64_t>(it->second);
return tr;
}
}
{
auto it = mConvertedObjectCache.find(
PyObjectUtils::builtin_id(pyObject)
);
if (it != mConvertedObjectCache.end()) {
pyObject = it->second.get();
}
}
bool wasReplaced = false;
if (mPureImplementationMappings.canMap(pyObject)) {
pyObject = _pureInstanceReplacement(pyObject);
assert (pyObject != nullptr);
wasReplaced = true;
}
int64_t objectId = _allocateId(pyObject);
if (pyObject == mPyforaConnectHack.get()) {
_registerUnconvertible(objectId, Py_None);
tr.set<int64_t>(objectId);
return tr;
}
PyforaErrorOrNull res = _walkPyObject(pyObject, objectId);
if (res) {
_registerUnconvertible(objectId, pyObject);
}
if (wasReplaced) {
Py_DECREF(pyObject);
}
tr.set<int64_t>(objectId);
return tr;
}
int64_t PyObjectWalker::walkFileDescription(const FileDescription& fileDescription)
{
auto it = mConvertedFiles.find(fileDescription.filename);
if (it != mConvertedFiles.end()) {
return it->second;
}
int64_t objectId = mObjectRegistry.allocateObject();
mObjectRegistry.defineFile(objectId,
fileDescription.filetext,
fileDescription.filename
);
mConvertedFiles[fileDescription.filename] = objectId;
return objectId;
}
namespace {
std::string _rootNameOfVarWithPosition(PyObject* varWithPosition)
{
//VarWithPosition(var=('x',), pos=PositionInFile(lineno=519, col_offset=19))
PyObjectPtr varMember = PyObjectPtr::unincremented(
PyObject_GetAttrString(varWithPosition, "var"));
if (varMember == nullptr) {
throw std::runtime_error(
"py error in PyObjectWalker::<anonymous>::_rootNameOfVarWithPosition "
"getting var member: " +
PyObjectUtils::format_exc()
);
}
if (not PyTuple_Check(varMember.get())) {
throw std::runtime_error(
"PyObjectWalker::<anonymous>::_rootNameOfVarWithPosition "
"expects var member to be a tuple"
);
}
if (PyTuple_GET_SIZE(varMember.get()) == 0) {
throw std::runtime_error(
"PyObjectWalker::<anonymous>::_rootNameOfVarWithPosition "
"expects its var member tuple to have length at least one"
);
}
// borrowed reference
PyObject* rootName = PyTuple_GET_ITEM(varMember.get(), 0);
if (not PyString_Check(rootName)) {
throw std::runtime_error(
"PyObjectWalker::<anonymous>::_rootNameOfVarWithPosition expects "
"its var member tuple to contain strings"
);
}
return std::string(PyString_AS_STRING(rootName),
PyString_GET_SIZE(rootName));
}
std::pair<int64_t, int64_t> _lineAndColumn(PyObject* varWithPosition)
{
//VarWithPosition(var=('x',), pos=PositionInFile(lineno=519, col_offset=19))
PyObjectPtr posMember = PyObjectPtr::unincremented(
PyObject_GetAttrString(varWithPosition, "pos"));
if (posMember == nullptr) {
throw std::runtime_error(
"py error in PyObjectWalker::<anonymous>::_rootNameOfVarWithPosition "
"getting pos member: " + PyObjectUtils::format_exc()
);
}
PyObjectPtr lineno = PyObjectPtr::unincremented(
PyObject_GetAttrString(posMember.get(), "lineno")
);
PyObjectPtr col_offset = PyObjectPtr::unincremented(
PyObject_GetAttrString(posMember.get(), "col_offset")
);
if (lineno == nullptr) {
throw std::runtime_error(
"py error in PyObjectWalker::<anonymous>::_rootNameOfVarWithPosition "
"getting lineno member: " + PyObjectUtils::format_exc()
);
}
if (col_offset == nullptr) {
throw std::runtime_error(
"py error in PyObjectWalker::<anonymous>::_rootNameOfVarWithPosition "
"getting col_offset member: " + PyObjectUtils::format_exc()
);
}
if (not PyInt_Check(lineno.get())) {
throw std::runtime_error(
"PyObjectWalker::<anonymous>::_rootNameOfVarWithPosition expects "
"lineno to be an int"
);
}
if (not PyInt_Check(col_offset.get())) {
throw std::runtime_error(
"PyObjectWalker::<anonymous>::_rootNameOfVarWithPosition expects "
"col_offset to be an int"
);
}
int64_t linenoCpp = PyInt_AS_LONG(lineno.get());
int64_t col_offset_cpp = PyInt_AS_LONG(col_offset.get());
return std::make_pair(linenoCpp, col_offset_cpp);
}
}
int64_t PyObjectWalker::walkUnresolvedVarWithPosition(PyObject* varWithPosition)
{
//VarWithPosition(var=('x',), pos=PositionInFile(lineno=519, col_offset=19))
std::string rootNameCpp = _rootNameOfVarWithPosition(varWithPosition);
std::pair<int64_t, int64_t> lineAndCol = _lineAndColumn(varWithPosition);
int64_t objectId = mObjectRegistry.allocateObject();
mObjectRegistry.defineUnresolvedVarWithPosition(
objectId,
rootNameCpp,
lineAndCol.first,
lineAndCol.second);
return objectId;
}
PyObject* PyObjectWalker::_pureInstanceReplacement(const PyObject* pyObject)
{
PyObject* pureInstance = mPureImplementationMappings.mappableInstanceToPure(
pyObject);
if (pureInstance == nullptr) {
return nullptr;
}
mConvertedObjectCache[PyObjectUtils::builtin_id(pyObject)] =
PyObjectPtr::unincremented(pureInstance);
return pureInstance;
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_walkPyObject(PyObject* pyObject, int64_t objectId) {
if (PyObject_IsInstance(pyObject, mRemotePythonObjectClass.get()))
{
return _registerRemotePythonObject(objectId, pyObject);
}
else if (PyObject_IsInstance(pyObject, mPackedHomogenousDataClass.get()))
{
return _registerPackedHomogenousData(objectId, pyObject);
}
else if (PyObject_IsInstance(pyObject, mFutureClass.get()))
{
return _registerFuture(objectId, pyObject);
}
else if (PyObject_IsInstance(pyObject, PyExc_Exception)
and _classIsNamedSingleton(pyObject))
{
return _registerBuiltinExceptionInstance(objectId, pyObject);
}
else if (_isTypeOrBuiltinFunctionAndInNamedSingletons(pyObject))
{
return _registerTypeOrBuiltinFunctionNamedSingleton(objectId, pyObject);
}
else if (PyObject_IsInstance(pyObject, mTracebackType.get()))
{
return _registerStackTraceAsJson(objectId, pyObject);
}
else if (PyObject_IsInstance(pyObject, mPyforaWithBlockClass.get()))
{
return _registerPyforaWithBlock(objectId, pyObject);
}
else if (PyObject_IsInstance(pyObject, mUnconvertibleClass.get()))
{
PyObjectPtr objectThatsNotConvertible = PyObjectPtr::unincremented(
PyObject_GetAttrString(
pyObject,
"objectThatsNotConvertible"
));
if (objectThatsNotConvertible == nullptr) {
throw std::runtime_error(
"expected Unconvertible instances to have an "
"`objectThatsNotConvertible` member"
);
}
return _registerUnconvertible(objectId, objectThatsNotConvertible.get());
}
else if (PyTuple_Check(pyObject))
{
return _registerTuple(objectId, pyObject);
}
else if (PyList_Check(pyObject))
{
return _registerList(objectId, pyObject);
}
else if (PyDict_Check(pyObject))
{
return _registerDict(objectId, pyObject);
}
else if (_isPrimitive(pyObject))
{
_registerPrimitive(objectId, pyObject);
return {};
}
else if (PyFunction_Check(pyObject))
{
return _registerFunction(objectId, pyObject);
}
else if (mPyforaInspectModule.isclass(pyObject))
{
return _registerClass(objectId, pyObject);
}
else if (PyMethod_Check(pyObject))
{
return _registerInstanceMethod(objectId, pyObject);
}
else if (mPyforaInspectModule.isclassinstance(pyObject))
{
return _registerClassInstance(objectId, pyObject);
}
else {
throw std::runtime_error("PyObjectWalker couldn't handle a PyObject: " +
PyObjectUtils::repr_string(pyObject));
}
}
bool PyObjectWalker::_classIsNamedSingleton(PyObject* pyObject) const
{
PyObjectPtr __class__attr = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyObject, "__class__"));
if (__class__attr == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_classIsNamedSingleton: " +
PyObjectUtils::exc_string()
);
}
bool tr = (mPythonSingletonToName.find(__class__attr.get()) !=
mPythonSingletonToName.end());
return tr;
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerRemotePythonObject(int64_t objectId,
PyObject* pyObject) const
{
PyObjectPtr _pyforaComputedValueArg_attr = PyObjectPtr::unincremented(
PyObject_GetAttrString(
pyObject,
"_pyforaComputedValueArg"
));
if (_pyforaComputedValueArg_attr == nullptr) {
throw std::runtime_error(
"py error getting _pyforaComputedValueArg "
"in PyObjectWalker::_registerRemotePythonObject: " +
PyObjectUtils::exc_string()
);
}
PyObjectPtr res = PyObjectPtr::unincremented(
PyObject_CallFunctionObjArgs(
_pyforaComputedValueArg_attr.get(),
nullptr
));
if (res == nullptr) {
throw std::runtime_error(
"py error calling _pyforaComputedValueArg "
"in PyObjectWalker::_registerRemotePythonObject: " +
PyObjectUtils::exc_string()
);
}
mObjectRegistry.defineRemotePythonObject(
objectId,
res.get()
);
return {};
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerUnconvertible(int64_t objectId,
const PyObject* pyObject) const
{
PyObjectPtr modulePathOrNone = PyObjectPtr::unincremented(
mModuleLevelObjectIndex.getPathToObject(pyObject));
if (modulePathOrNone == nullptr) {
throw std::runtime_error("error getting modulePathOrNone"
"in PyObjectWalker::_registerUnconvertible");
}
mObjectRegistry.defineUnconvertible(objectId, modulePathOrNone.get());
return {};
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerPackedHomogenousData(int64_t objectId,
PyObject* pyObject) const
{
mObjectRegistry.definePackedHomogenousData(objectId, pyObject);
return {};
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerFuture(int64_t objectId, PyObject* pyObject)
{
PyObjectPtr result_attr = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyObject, "result"));
if (result_attr == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_registerFuture: " +
PyObjectUtils::exc_string()
);
}
PyObjectPtr res = PyObjectPtr::unincremented(
PyObject_CallFunctionObjArgs(result_attr.get(), nullptr));
if (res == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_registerFuture: " +
PyObjectUtils::exc_string()
);
}
return _walkPyObject(res.get(), objectId);
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerBuiltinExceptionInstance(
int64_t objectId,
PyObject* pyException)
{
PyObjectPtr __class__attr = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyException, "__class__"));
if (__class__attr == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_registerBuiltinExceptionInstance: " +
PyObjectUtils::exc_string()
);
}
auto it = mPythonSingletonToName.find(__class__attr.get());
if (it == mPythonSingletonToName.end()) {
throw std::runtime_error(
"it's supposed to be a precondition to this function that this not happen");
}
PyObjectPtr args_attr = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyException, "args"));
if (args_attr == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_registerBuiltinExceptionInstance: " +
PyObjectUtils::exc_string()
);
}
WalkResult argsIdOrErr = walkPyObject(args_attr.get());
if (argsIdOrErr.is<int64_t>()) {
mObjectRegistry.defineBuiltinExceptionInstance(objectId,
it->second,
argsIdOrErr.get<int64_t>());
return {};
}
else {
return argsIdOrErr.get<std::shared_ptr<PyforaError>>();
}
}
bool PyObjectWalker::_isTypeOrBuiltinFunctionAndInNamedSingletons(PyObject* pyObject) const
{
if (not PyType_Check(pyObject) and not PyCFunction_Check(pyObject)) {
return false;
}
return mPythonSingletonToName.find(pyObject) != mPythonSingletonToName.end();
}
std::string PyObjectWalker::_fileText(const PyObject* fileNamePyObj) const
{
PyObjectPtr lines = PyObjectPtr::unincremented(
mPyforaInspectModule.getlines(fileNamePyObj));
if (lines == nullptr) {
throw std::runtime_error(
"error calling getlines");
}
if (not PyList_Check(lines.get())) {
throw std::runtime_error("expected a list");
}
std::ostringstream oss;
for (Py_ssize_t ix = 0; ix < PyList_GET_SIZE(lines.get()); ++ix)
{
// borrowed reference. no need to decref
PyObject* item = PyList_GET_ITEM(lines.get(), ix);
if (PyString_Check(item)) {
oss.write(PyString_AS_STRING(item), PyString_GET_SIZE(item));
}
else if (PyUnicode_Check(item)) {
PyObjectPtr pyString = PyObjectPtr::unincremented(
PyUnicode_AsASCIIString(item));
if (pyString == nullptr) {
throw std::runtime_error("error getting string from unicode: " +
PyObjectUtils::exc_string());
}
oss.write(PyString_AS_STRING(pyString.get()),
PyString_GET_SIZE(pyString.get()));
}
else {
throw std::runtime_error(
"all elements in lines should be str or unicode");
}
}
return oss.str();
}
std::string PyObjectWalker::_fileText(const std::string& filename) const
{
PyObjectPtr fileNamePyObj = PyObjectPtr::unincremented(
PyString_FromStringAndSize(
filename.data(),
filename.size()));
if (fileNamePyObj == nullptr) {
throw std::runtime_error("couldn't create a python string out of a std::string");
}
std::string tr = _fileText(fileNamePyObj.get());
return tr;
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerTypeOrBuiltinFunctionNamedSingleton(
int64_t objectId,
PyObject* pyObject) const
{
auto it = mPythonSingletonToName.find(pyObject);
if (it == mPythonSingletonToName.end()) {
throw std::runtime_error(
"this shouldn't happen if _isTypeOrBuiltinFunctionAndInNamedSingletons "
"returned true"
);
}
mObjectRegistry.defineNamedSingleton(objectId, it->second);
return {};
}
namespace {
int64_t _getWithBlockLineNumber(PyObject* withBlock)
{
int64_t lineno;
PyObjectPtr pyLineNumber = PyObjectPtr::unincremented(
PyObject_GetAttrString(withBlock, "lineNumber"));
if (pyLineNumber == nullptr) {
throw std::runtime_error("error getting lineNumber attr in _registerPyforaWithBlock");
}
if (not PyInt_Check(pyLineNumber.get())) {
throw std::runtime_error(
"py err in PyObjectWalker::_getWithBlockLineNumber: " +
PyObjectUtils::exc_string()
);
}
lineno = PyInt_AS_LONG(pyLineNumber.get());
return lineno;
}
}
std::shared_ptr<PyforaError> PyObjectWalker::_handleUnresolvedFreeVariableException(
const PyObject* filename)
{
PyObject * exception, * v, * tb;
PyErr_Fetch(&exception, &v, &tb);
if (exception == nullptr) {
throw std::runtime_error("expected an Exception to be set.");
}
PyErr_NormalizeException(&exception, &v, &tb);
if (PyObject_IsInstance(
v,
mUnresolvedFreeVariableExceptions.getUnresolvedFreeVariableExceptionClass()))
{
// borrowed reference.
PyObject* unresolvedFreeVariableExceptionWithTrace =
mUnresolvedFreeVariableExceptions.getUnresolvedFreeVariableExceptionWithTrace(
v,
filename
);
if (unresolvedFreeVariableExceptionWithTrace == nullptr) {
Py_DECREF(exception);
Py_DECREF(v);
Py_DECREF(tb);
throw std::runtime_error(
"py error getting "
"unresolvedFreeVariableExceptionWithTrace in "
"PyObjectWalker::<anonymous namespace>::"
"_handleUnresolvedFreeVariableException: " +
PyObjectUtils::exc_string()
);
}
throw UnresolvedFreeVariableExceptionWithTrace(
PyObjectPtr::unincremented(unresolvedFreeVariableExceptionWithTrace)
);
}
else {
PyErr_Restore(exception, v, tb);
throw std::runtime_error(
"PyObjectWalker::<anonymous namespace>::"
"_handleUnresolvedFreeVariableException: " +
PyObjectUtils::format_exc());
}
}
PyObject* PyObjectWalker::_pythonTracebackToJson(const PyObject* pyObject) const
{
return PyObject_CallFunctionObjArgs(
mPythonTracebackToJsonFun.get(),
pyObject,
nullptr);
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerStackTraceAsJson(int64_t objectId,
const PyObject* pyObject) const
{
PyObjectPtr pythonTraceBackAsJson = PyObjectPtr::unincremented(
_pythonTracebackToJson(pyObject));
if (pythonTraceBackAsJson == nullptr) {
throw std::runtime_error(
"py error in PyObjectWalker:_registerStackTraceAsJson: " +
PyObjectUtils::exc_string()
);
}
mObjectRegistry.defineStacktrace(objectId, pythonTraceBackAsJson.get());
return {};
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerPyforaWithBlock(
int64_t objectId,
PyObject* pyObject)
{
int64_t lineno = _getWithBlockLineNumber(pyObject);
PyObjectPtr withBlockFun = PyObjectPtr::unincremented(
_withBlockFun(pyObject, lineno));
if (withBlockFun == nullptr) {
throw std::runtime_error(
"error getting with block ast functionDef"
" in PyObjectWalker::_registerPyforaWithBlock: " +
PyObjectUtils::exc_string());
}
if (mPyAstUtilModule.hasReturnInOuterScope(withBlockFun.get())) {
std::ostringstream err_oss;
err_oss << "return statement not supported in pyfora with-block (line ";
err_oss << mPyAstUtilModule.getReturnLocationsInOuterScope(withBlockFun.get());
err_oss << ")";
throw BadWithBlockError(err_oss.str());
}
if (mPyAstUtilModule.hasYieldInOuterScope(withBlockFun.get())) {
std::ostringstream err_oss;
err_oss << "yield expression not supported in pyfora with-block (line ";
err_oss << mPyAstUtilModule.getYieldLocationsInOuterScope(withBlockFun.get());
err_oss << ")";
throw BadWithBlockError(err_oss.str());
}
PyObjectPtr chainsWithPositions = PyObjectPtr::unincremented(
_freeMemberAccessChainsWithPositions(withBlockFun.get()));
if (chainsWithPositions == nullptr) {
throw std::runtime_error(
"py error getting freeMemberAccessChainsWithPositions "
"in PyObjectWalker::_registerPyforaWithBlock: "+
PyObjectUtils::exc_string());
}
PyObjectPtr boundVariables = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyObject, "boundVariables"));
if (boundVariables == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_registerPyforaWithBlock: " +
PyObjectUtils::exc_string()
);
}
_augmentChainsWithBoundValuesInScope(
pyObject,
withBlockFun.get(),
boundVariables.get(),
chainsWithPositions.get());
PyObject* pyConvertedObjectCache = _getPyConvertedObjectCache();
if (pyConvertedObjectCache == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_registerPyforaWithBlock: " +
PyObjectUtils::exc_string()
);
}
ResolutionResult resolutions =
mFreeVariableResolver.resolveFreeVariableMemberAccessChains(
chainsWithPositions.get(),
boundVariables.get(),
pyConvertedObjectCache);
PyObjectPtr filename = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyObject, "sourceFileName"));
if (filename == nullptr) {
throw std::runtime_error(
"py error getting sourceFileName attr "
"in PyObjectWalker::_registerPyforaWithBlock: "
+ PyObjectUtils::exc_string()
);
}
variant<
std::map<FreeVariableMemberAccessChain, int64_t>,
std::shared_ptr<PyforaError>> processedResolutionsOrErr =
_processFreeVariableMemberAccessChainResolutions(
resolutions
);
int64_t sourceFileId = walkFileDescription(
FileDescription::cachedFromArgs(
PyObjectUtils::std_string(filename.get()),
_fileText(filename.get())
)
);
if (processedResolutionsOrErr.is<std::map<FreeVariableMemberAccessChain, int64_t>>())
{
mObjectRegistry.defineWithBlock(
objectId,
processedResolutionsOrErr.get<
std::map<FreeVariableMemberAccessChain, int64_t>>(),
sourceFileId,
lineno);
return {};
}
else {
return processedResolutionsOrErr.get<std::shared_ptr<PyforaError>>();
}
}
void PyObjectWalker::_augmentChainsWithBoundValuesInScope(
PyObject* pyObject,
PyObject* withBlockFun,
PyObject* boundVariables,
PyObject* chainsWithPositions) const
{
if (not PySet_Check(chainsWithPositions)) {
throw std::runtime_error("expected chainsWithPositions to be a set");
}
PyObjectPtr boundValuesInScopeWithPositions = PyObjectPtr::unincremented(
mPyAstFreeVariableAnalysesModule.collectBoundValuesInScope(withBlockFun, true));
if (boundValuesInScopeWithPositions == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_augmentChainsWithBoundValuesInScope: " +
PyObjectUtils::exc_string()
);
}
PyObjectPtr unboundLocals = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyObject, "unboundLocals"));
if (unboundLocals == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_augmentChainsWithBoundValuesInScope: " +
PyObjectUtils::exc_string()
);
}
PyObjectPtr iterator = PyObjectPtr::unincremented(
PyObject_GetIter(boundValuesInScopeWithPositions.get()));
if (iterator == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_augmentChainsWithBoundValuesInScope: " +
PyObjectUtils::exc_string()
);
}
PyObjectPtr item;
while ((item = PyObjectPtr::unincremented(PyIter_Next(iterator.get())))) {
if (!PyTuple_Check(item.get())) {
throw std::runtime_error(
"py err in PyObjectWalker::_augmentChainsWithBoundValuesInScope: " +
PyObjectUtils::exc_string()
);
}
if (PyTuple_GET_SIZE(item.get()) != 2) {
throw std::runtime_error(
"py err in PyObjectWalker::_augmentChainsWithBoundValuesInScope: " +
PyObjectUtils::exc_string()
);
}
PyObject* val = PyTuple_GET_ITEM(item.get(), 0);
PyObject* pos = PyTuple_GET_ITEM(item.get(), 1);
if (not PyObjectUtils::in(unboundLocals.get(), val) and
PyObjectUtils::in(boundVariables, val))
{
PyObjectPtr varWithPosition = PyObjectPtr::unincremented(
mPyAstFreeVariableAnalysesModule.varWithPosition(val, pos));
if (varWithPosition == nullptr) {
throw std::runtime_error("couldn't get VarWithPosition");
}
if (PySet_Add(chainsWithPositions, varWithPosition.get()) != 0) {
throw std::runtime_error("error adding to a set");
}
}
}
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerTuple(int64_t objectId, PyObject* pyTuple)
{
std::vector<int64_t> memberIds;
Py_ssize_t size = PyTuple_GET_SIZE(pyTuple);
for (Py_ssize_t ix = 0; ix < size; ++ix)
{
WalkResult res = walkPyObject(PyTuple_GET_ITEM(pyTuple, ix));
if (res.is<int64_t>()) {
memberIds.push_back(
res.get<int64_t>()
);
}
else {
return res.get<std::shared_ptr<PyforaError>>();
}
}
mObjectRegistry.defineTuple(objectId, memberIds);
return {};
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerList(int64_t objectId, PyObject* pyList)
{
if (_allPrimitives(pyList))
{
return _registerListOfPrimitives(objectId, pyList);
}
else {
return _registerListGeneric(objectId, pyList);
}
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerListOfPrimitives(int64_t objectId, PyObject* pyList) const
{
mObjectRegistry.definePrimitive(objectId, pyList);
return {};
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerListGeneric(int64_t objectId, const PyObject* pyList)
{
std::vector<int64_t> memberIds;
Py_ssize_t size = PyList_GET_SIZE(pyList);
for (Py_ssize_t ix = 0; ix < size; ++ix)
{
WalkResult res = walkPyObject(PyList_GET_ITEM(pyList, ix));
if (res.is<int64_t>()) {
memberIds.push_back(
res.get<int64_t>()
);
}
else {
return res.get<std::shared_ptr<PyforaError>>();
}
}
mObjectRegistry.defineList(objectId, memberIds);
return {};
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerDict(int64_t objectId, PyObject* pyDict)
{
std::vector<int64_t> keyIds;
std::vector<int64_t> valueIds;
PyObject* key;
PyObject* value;
Py_ssize_t pos = 0;
while (PyDict_Next(pyDict, &pos, &key, &value)) {
WalkResult res = walkPyObject(key);
if (res.is<int64_t>()) {
keyIds.push_back(
res.get<int64_t>()
);
}
else {
return res.get<std::shared_ptr<PyforaError>>();
}
res = walkPyObject(value);
if (res.is<int64_t>()) {
valueIds.push_back(
res.get<int64_t>()
);
}
else {
return res.get<std::shared_ptr<PyforaError>>();
}
}
mObjectRegistry.defineDict(objectId, keyIds, valueIds);
return {};
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerFunction(int64_t objectId, PyObject* pyObject)
{
auto infoOrException = _classOrFunctionInfo(pyObject, true);
if (infoOrException.is<ClassOrFunctionInfo>()) {
ClassOrFunctionInfo info = infoOrException.get<ClassOrFunctionInfo>();
mObjectRegistry.defineFunction(
objectId,
info.sourceFileId(),
info.lineNumber(),
info.freeVariableMemberAccessChainsToId()
);
return {};
}
else {
return infoOrException.get<std::shared_ptr<PyforaError>>();
}
}
namespace {
// precondition: obj should be a function or class
void _checkForInlineForaName(PyObject* obj) {
PyObjectPtr __name__attr = PyObjectPtr::unincremented(
PyObject_GetAttrString(obj, "__name__"));
if (__name__attr == nullptr) {
throw std::runtime_error(
"expected to find a __name__attr "
"in PyObjectWalker::<anonymous namespace>::"
"_checkForInlineForaName: " +
PyObjectUtils::exc_string()
);
}
if (not PyString_Check(__name__attr.get())) {
throw std::runtime_error(
"expected __name__ attr to be a string"
);
}
std::string __name__attr_as_string = std::string(
PyString_AS_STRING(__name__attr.get()),
PyString_GET_SIZE(__name__attr.get())
);
if (__name__attr_as_string == "__inline_fora") {
throw PythonToForaConversionError("in pfora, `__inline_fora` is a reserved word");
}
}
}
variant<ClassOrFunctionInfo, std::shared_ptr<PyforaError>>
PyObjectWalker::_classOrFunctionInfo(PyObject* obj, bool isFunction)
{
variant<ClassOrFunctionInfo, std::shared_ptr<PyforaError>> tr;
// old PyObjectWalker checks for __inline_fora here
_checkForInlineForaName(obj);
variant<PyObjectPtr, std::shared_ptr<PyforaError>> textAndFilenameOrErr =
mPyAstUtilModule.sourceFilenameAndText(obj);
PyObjectPtr textAndFilename;
if (textAndFilenameOrErr.is<PyObjectPtr>()) {
textAndFilename = textAndFilenameOrErr.get<PyObjectPtr>();
}
else {
tr.set<std::shared_ptr<PyforaError>>(
textAndFilenameOrErr.get<std::shared_ptr<PyforaError>>()
);
return tr;
}
assert (textAndFilenameOrErr != nullptr);
if (textAndFilename == nullptr) {
throw std::runtime_error(
"error calling sourceFilenameAndText: " + PyObjectUtils::exc_string()
);
}
if (not PyTuple_Check(textAndFilename.get())) {
throw std::runtime_error("expected sourceFilenameAndText to return a tuple");
}
if (PyTuple_GET_SIZE(textAndFilename.get()) != 2) {
throw std::runtime_error(
"expected sourceFilenameAndText to return a tuple of length 2"
);
}
// borrowed reference
PyObject* text = PyTuple_GET_ITEM(textAndFilename.get(), 0);
// borrowed reference
PyObject* filename = PyTuple_GET_ITEM(textAndFilename.get(), 1);
variant<long, std::shared_ptr<PyforaError>> startingSourceLineOrErr =
mPyAstUtilModule.startingSourceLine(obj);
long startingSourceLine;
if (startingSourceLineOrErr.is<long>()) {
startingSourceLine = startingSourceLineOrErr.get<long>();
}
else {
tr.set<std::shared_ptr<PyforaError>>(
startingSourceLineOrErr.get<std::shared_ptr<PyforaError>>()
);
return tr;
}
PyObjectPtr sourceAst = PyObjectPtr::unincremented(
mPyAstUtilModule.pyAstFromText(text));
if (sourceAst == nullptr) {
throw std::runtime_error(
"an error occured calling pyAstFromText: " + PyObjectUtils::exc_string()
+ "\nfilename = " + PyObjectUtils::str_string(filename)
+ "\ntext = " + PyObjectUtils::str_string(text)
);
}
PyObjectPtr pyAst;
if (isFunction) {
pyAst = PyObjectPtr::unincremented(
mPyAstUtilModule.functionDefOrLambdaAtLineNumber(
sourceAst.get(),
startingSourceLine));
}
else {
pyAst = PyObjectPtr::unincremented(
mPyAstUtilModule.classDefAtLineNumber(sourceAst.get(),
startingSourceLine));
}
if (pyAst == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_classOrFunctionInfo: " +
PyObjectUtils::exc_string()
);
}
variant<ResolutionResult, std::shared_ptr<PyforaError>> resolutionsOrErr =
_computeAndResolveFreeVariableMemberAccessChainsInAst(obj, pyAst.get());
if (resolutionsOrErr.is<std::shared_ptr<PyforaError>>()) {
tr.set<std::shared_ptr<PyforaError>>(
resolutionsOrErr.get<std::shared_ptr<PyforaError>>()
);
return tr;
}
ResolutionResult resolutions = resolutionsOrErr.get<ResolutionResult>();
variant<
std::map<FreeVariableMemberAccessChain, int64_t>,
std::shared_ptr<PyforaError>> processedResolutionsOrErr =
_processFreeVariableMemberAccessChainResolutions(
resolutions
);
if (processedResolutionsOrErr.is<std::map<FreeVariableMemberAccessChain, int64_t>>())
{
int64_t fileId = walkFileDescription(
FileDescription::cachedFromArgs(
PyObjectUtils::std_string(filename),
PyObjectUtils::std_string(text)
)
);
// can we setup perfect forwarding for variant?
tr.set<ClassOrFunctionInfo>(
ClassOrFunctionInfo(
fileId,
startingSourceLine,
processedResolutionsOrErr.get<
std::map<FreeVariableMemberAccessChain, int64_t>
>()
)
);
return tr;
}
else {
tr.set<std::shared_ptr<PyforaError>>(
processedResolutionsOrErr.get<std::shared_ptr<PyforaError>>()
);
return tr;
}
}
variant<std::map<FreeVariableMemberAccessChain, int64_t>,
std::shared_ptr<PyforaError>>
PyObjectWalker::_processFreeVariableMemberAccessChainResolutions(
const ResolutionResult& resolutions
)
{
variant<std::map<FreeVariableMemberAccessChain, int64_t>,
std::shared_ptr<PyforaError>> tr;
std::map<FreeVariableMemberAccessChain, int64_t> cppResolutions;
PyObject* resolvedChainsDict = resolutions.resolvedChainsDict.get();
auto res = _processResolvedChainsDict(resolvedChainsDict, cppResolutions);
if (res) {
tr.set<std::shared_ptr<PyforaError>>(*res);
return tr;
}
PyObject* unresolvedChainsSet = resolutions.unresolvedChainsSet.get();
res = _processUnresolvedChainsSet(unresolvedChainsSet, cppResolutions);
if (res) {
tr.set<std::shared_ptr<PyforaError>>(*res);
return tr;
}
tr.set<std::map<FreeVariableMemberAccessChain, int64_t>>(cppResolutions);
return tr;
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_processResolvedChainsDict(
PyObject* resolvedChainsDict,
std::map<FreeVariableMemberAccessChain, int64_t>& ioResolutions
)
{
if (not PyDict_Check(resolvedChainsDict)) {
throw std::runtime_error(
"PyObjectWalker::_processResolvedChainsDict expects a dict argument"
);
}
PyObject * key, * value;
Py_ssize_t pos = 0;
while (PyDict_Next(resolvedChainsDict, &pos, &key, &value)) {
/*
Values should be length-two tuples: (resolution, location)
*/
if (not PyTuple_Check(value)) {
throw std::runtime_error("expected tuple values");
}
if (PyTuple_GET_SIZE(value) != 2) {
throw std::runtime_error("expected values to be tuples of length 2");
}
PyObject* resolution = PyTuple_GET_ITEM(value, 0);
auto resolutionIdOrErr = walkPyObject(resolution);
if (resolutionIdOrErr.is<std::shared_ptr<PyforaError>>()) {
return resolutionIdOrErr.get<std::shared_ptr<PyforaError>>();
}
ioResolutions[toChain(key)] = resolutionIdOrErr.get<int64_t>();
}
return {};
}
PyObjectWalker::PyforaErrorOrNull PyObjectWalker::_processUnresolvedChainsSet(
PyObject* unresolvedChainsSet,
std::map<FreeVariableMemberAccessChain, int64_t>& ioResolutions
)
{
if (not PySet_Check(unresolvedChainsSet)) {
throw std::runtime_error(
"PyObjectWalker::_processResolvedChainsSet expects a set argument"
);
}
PyObjectPtr iterator = PyObjectPtr::unincremented(
PyObject_GetIter(unresolvedChainsSet));
if (iterator == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_processResolvedChainsSet: " +
PyObjectUtils::exc_string()
);
}
PyObjectPtr item;
while ((item = PyObjectPtr::unincremented(PyIter_Next(iterator.get())))) {
int64_t objectId = walkUnresolvedVarWithPosition(item.get());
PyObjectPtr pyChain = PyObjectPtr::unincremented(
PyObject_GetAttrString(
item.get(),
"var"
)
);
if (pyChain == nullptr) {
throw std::runtime_error(
"PyObjectWalker::_processResolvedChainsSet py error: " +
PyObjectUtils::format_exc()
);
}
ioResolutions[toChain(pyChain.get())] = objectId;
}
return {};
}
PyObject* PyObjectWalker::_getPyConvertedObjectCache() const
{
PyObject* tr = PyDict_New();
if (tr == nullptr) {
return nullptr;
}
for (const auto& p: mConvertedObjectCache)
{
PyObjectPtr pyLong = PyObjectPtr::unincremented(PyLong_FromLong(p.first));
if (pyLong == nullptr) {
Py_DECREF(tr);
throw std::runtime_error("error getting python long from C long");
}
if (PyDict_SetItem(tr, pyLong.get(), p.second.get()) != 0) {
return nullptr;
}
}
return tr;
}
variant<ResolutionResult, std::shared_ptr<PyforaError>>
PyObjectWalker::_computeAndResolveFreeVariableMemberAccessChainsInAst(
const PyObject* pyObject,
const PyObject* pyAst
) const
{
variant<ResolutionResult, std::shared_ptr<PyforaError>> tr;
PyObjectPtr chainsWithPositions = PyObjectPtr::unincremented(
_freeMemberAccessChainsWithPositions(pyAst));
if (chainsWithPositions == nullptr) {
tr.set<std::shared_ptr<PyforaError>>(
std::shared_ptr<PyforaError>(
new PyforaError(
"py error getting free member access chains in PyObjectWalker::"
"_computeAndResolveFreeVariableMemberAccessChainsInAst: " +
PyObjectUtils::format_exc()
)
)
);
return tr;
}
PyObjectPtr pyConvertedObjectCache = PyObjectPtr::unincremented(
_getPyConvertedObjectCache());
if (pyConvertedObjectCache == nullptr) {
throw std::runtime_error(
"py error getting converted object cache in PyObjectWalker::"
"_computeAndResolveFreeVariableMemberAccessChainsInAst: " +
PyObjectUtils::format_exc()
);
}
tr.set<ResolutionResult>(
mFreeVariableResolver.resolveFreeVariableMemberAccessChainsInAst(
pyObject,
pyAst,
chainsWithPositions.get(),
pyConvertedObjectCache.get()
)
);
return tr;
}
PyObject* PyObjectWalker::_freeMemberAccessChainsWithPositions(
const PyObject* pyAst
) const
{
return mPyAstFreeVariableAnalysesModule.getFreeMemberAccessChainsWithPositions(
pyAst,
false,
true,
mExcludePredicateFun.get()
);
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerClass(int64_t objectId, PyObject* pyObject)
{
auto infoOrException = _classOrFunctionInfo(pyObject, false);
if (infoOrException.is<ClassOrFunctionInfo>()) {
ClassOrFunctionInfo info = infoOrException.get<ClassOrFunctionInfo>();
PyObjectPtr bases = PyObjectPtr::unincremented(
PyObject_GetAttrString(
pyObject,
"__bases__"));
if (bases == nullptr) {
throw std::runtime_error(
"couldn't get __bases__ member of an object we expected to be a class"
);
}
if (not PyTuple_Check(bases.get())) {
throw std::runtime_error("expected bases to be a list");
}
std::vector<int64_t> baseClassIds;
for (Py_ssize_t ix = 0; ix < PyTuple_GET_SIZE(bases.get()); ++ix)
{
PyObject* item = PyTuple_GET_ITEM(bases.get(), ix);
auto it = mPyObjectToObjectId.find(item);
if (it == mPyObjectToObjectId.end()) {
return std::shared_ptr<PyforaError>(
new PyforaError(
"expected each base class to have a registered id"
". class = " + PyObjectUtils::str_string(pyObject)
)
);
}
baseClassIds.push_back(it->second);
}
mObjectRegistry.defineClass(
objectId,
info.sourceFileId(),
info.lineNumber(),
info.freeVariableMemberAccessChainsToId(),
baseClassIds);
return {};
}
else {
return infoOrException.get<std::shared_ptr<PyforaError>>();
}
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerClassInstance(int64_t objectId, PyObject* pyObject)
{
PyObjectPtr classObject = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyObject, "__class__"));
if (classObject == nullptr) {
throw std::runtime_error(
"py err in PyObjectWalker::_registerClassInstance: " +
PyObjectUtils::exc_string()
);
}
auto classIdOrErr = walkPyObject(classObject.get());
if (classIdOrErr.is<std::shared_ptr<PyforaError>>()) {
return classIdOrErr.get<std::shared_ptr<PyforaError>>();
}
int64_t classId = classIdOrErr.get<int64_t>();
if (mObjectRegistry.isUnconvertible(classId)) {
PyObjectPtr modulePathOrNone = PyObjectPtr::unincremented(
mModuleLevelObjectIndex.getPathToObject(pyObject));
if (modulePathOrNone == nullptr) {
throw std::runtime_error(
"py error in PyObjectWalker::_registerClassInstance: " +
PyObjectUtils::exc_string()
);
}
mObjectRegistry.defineUnconvertible(
objectId,
modulePathOrNone.get()
);
return {};
}
PyObjectPtr dataMemberNames;
{
auto dataMemberNamesOrErr = _getDataMemberNames(pyObject, classObject.get());
if (not dataMemberNamesOrErr.is<PyObjectPtr>()) {
return dataMemberNamesOrErr.get<std::shared_ptr<PyforaError>>();
}
dataMemberNames = dataMemberNamesOrErr.get<PyObjectPtr>();
}
if (dataMemberNames == nullptr) {
throw std::runtime_error("py error in _registerClassInstance:" +
PyObjectUtils::exc_string()
);
}
if (not PyList_Check(dataMemberNames.get())) {
throw std::runtime_error("py error in _registerClassInstance:" +
PyObjectUtils::exc_string()
);
}
std::map<std::string, int64_t> classMemberNameToClassMemberId;
for (Py_ssize_t ix = 0; ix < PyList_GET_SIZE(dataMemberNames.get()); ++ix)
{
// borrowed reference
PyObject* dataMemberName = PyList_GET_ITEM(dataMemberNames.get(), ix);
if (not PyString_Check(dataMemberName)) {
throw std::runtime_error("py error in _registerClassInstance:" +
PyObjectUtils::exc_string()
);
}
PyObjectPtr dataMember = PyObjectPtr::unincremented(
PyObject_GetAttr(pyObject, dataMemberName));
if (dataMember == nullptr) {
throw std::runtime_error("py error in _registerClassInstance:" +
PyObjectUtils::exc_string()
);
}
auto dataMemberIdOrErr = walkPyObject(dataMember.get());
if (dataMemberIdOrErr.is<std::shared_ptr<PyforaError>>()) {
return dataMemberIdOrErr.get<std::shared_ptr<PyforaError>>();
}
int64_t dataMemberId = dataMemberIdOrErr.get<int64_t>();
classMemberNameToClassMemberId[
std::string(
PyString_AS_STRING(dataMemberName),
PyString_GET_SIZE(dataMemberName)
)
] = dataMemberId;
}
mObjectRegistry.defineClassInstance(
objectId,
classId,
classMemberNameToClassMemberId);
return {};
}
variant<PyObjectPtr, std::shared_ptr<PyforaError>>
PyObjectWalker::_getDataMemberNames(PyObject* pyObject, PyObject* classObject) const
{
if (PyObject_HasAttrString(pyObject, "__dict__"))
{
variant<PyObjectPtr, std::shared_ptr<PyforaError>> tr;
PyObjectPtr __dict__attr = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyObject, "__dict__"));
if (__dict__attr == nullptr) {
tr.set<PyObjectPtr>(PyObjectPtr());
return tr;
}
if (not PyDict_Check(__dict__attr.get())) {
PyErr_SetString(
PyExc_TypeError,
"expected __dict__ attr to be a dict"
);
tr.set<PyObjectPtr>(PyObjectPtr());
return tr;
}
PyObject* keys = PyDict_Keys(__dict__attr.get());
if (keys == nullptr) {
tr.set<PyObjectPtr>(PyObjectPtr());
return tr;
}
if (not PyList_Check(keys)) {
PyErr_SetString(
PyExc_TypeError,
"expected keys to be a list"
);
tr.set<PyObjectPtr>(PyObjectPtr());
return tr;
}
tr.set<PyObjectPtr>(PyObjectPtr::unincremented(keys));
return tr;
}
else {
return mPyAstUtilModule.collectDataMembersSetInInit(classObject);
}
}
PyObject* PyObjectWalker::_withBlockFun(PyObject* withBlock, int64_t lineno) const
{
PyObjectPtr sourceText = PyObjectPtr::unincremented(
PyObject_GetAttrString(withBlock, "sourceText"));
if (sourceText == nullptr) {
return nullptr;
}
PyObjectPtr sourceTree = PyObjectPtr::unincremented(
mPyAstUtilModule.pyAstFromText(sourceText.get()));
if (sourceTree == nullptr) {
return nullptr;
}
PyObjectPtr withBlockAst = PyObjectPtr::unincremented(
mPyAstUtilModule.withBlockAtLineNumber(
sourceTree.get(),
lineno));
if (withBlockAst == nullptr) {
return nullptr;
}
PyObjectPtr body = PyObjectPtr::unincremented(
PyObject_GetAttrString(withBlockAst.get(), "body"));
if (body == nullptr) {
return nullptr;
}
PyObjectPtr argsTuple = PyObjectPtr::unincremented(Py_BuildValue("()"));
if (argsTuple == nullptr) {
return nullptr;
}
PyObjectPtr ast_args = PyObjectPtr::unincremented(_defaultAstArgs());
if (ast_args == nullptr) {
return nullptr;
}
PyObjectPtr decorator_list = PyObjectPtr::unincremented(PyList_New(0));
if (decorator_list == nullptr) {
return nullptr;
}
PyObject* kwds = Py_BuildValue("{s:s, s:O, s:O, s:O, s:i, s:i}",
"name", "",
"args", ast_args.get(),
"body", body.get(),
"decorator_list", decorator_list.get(),
"lineno", lineno,
"col_offset", 0);
if (kwds == nullptr) {
return nullptr;
}
return mAstModule.FunctionDef(argsTuple.get(), kwds);
}
PyObject* PyObjectWalker::_defaultAstArgs() const
{
PyObjectPtr args = PyObjectPtr::unincremented(PyTuple_New(0));
if (args == nullptr) {
return nullptr;
}
PyObjectPtr emptyList = PyObjectPtr::unincremented(PyList_New(0));
if (emptyList == nullptr) {
return nullptr;
}
PyObjectPtr kwargs = PyObjectPtr::unincremented(
Py_BuildValue("{s:O, s:O, s:s, s:s}",
"args", emptyList.get(),
"defaults", emptyList.get(),
"kwarg", nullptr,
"vararg", nullptr));
if (kwargs == nullptr) {
return nullptr;
}
return mAstModule.arguments(args.get(), kwargs.get());
}
PyObjectWalker::PyforaErrorOrNull
PyObjectWalker::_registerInstanceMethod(int64_t objectId, PyObject* pyObject)
{
PyObjectPtr __self__attr = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyObject, "__self__"));
if (__self__attr == nullptr) {
throw std::runtime_error(
"expected to have a __self__ attr on instancemethods"
);
}
PyObjectPtr __name__attr = PyObjectPtr::unincremented(
PyObject_GetAttrString(pyObject, "__name__"));
if (__name__attr == nullptr) {
throw std::runtime_error(
"expected to have a __name__ attr on instancemethods"
);
}
if (not PyString_Check(__name__attr.get())) {
throw std::runtime_error(
"expected __name__ attr to be a string"
);
}
auto instanceIdOrErr = walkPyObject(__self__attr.get());
if (instanceIdOrErr.is<int64_t>()) {
mObjectRegistry.defineInstanceMethod(
objectId,
instanceIdOrErr.get<int64_t>(),
PyObjectUtils::std_string(__name__attr.get())
);
return {};
}
else {
return instanceIdOrErr.get<std::shared_ptr<PyforaError>>();
}
}
FreeVariableMemberAccessChain PyObjectWalker::toChain(const PyObject* obj)
{
if (not PyTuple_Check(obj)) {
throw std::runtime_error("expected FVMAC to be tuples ");
}
std::vector<std::string> variables;
for (Py_ssize_t ix = 0; ix < PyTuple_GET_SIZE(obj); ++ix) {
PyObject* item = PyTuple_GET_ITEM(obj, ix);
if (not PyString_Check(item)) {
throw std::runtime_error("expected FVMAC elements to be strings");
}
variables.push_back(PyObjectUtils::std_string(item));
}
return FreeVariableMemberAccessChain(variables);
}
UnresolvedFreeVariableExceptions
PyObjectWalker::unresolvedFreeVariableExceptionsModule() const
{
return mUnresolvedFreeVariableExceptions;
}
| 28,342 |
16,989 |
<filename>src/main/java/com/google/devtools/build/lib/rules/proto/ProtoLangToolchainProvider.java<gh_stars>1000+
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.proto;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import javax.annotation.Nullable;
// Note: AutoValue v1.4-rc1 has AutoValue.CopyAnnotations which makes it work with Starlark. No need
// to un-AutoValue this class to expose it to Starlark.
/**
* Specifies how to generate language-specific code from .proto files. Used by LANG_proto_library
* rules.
*/
@AutoValue
@AutoCodec
public abstract class ProtoLangToolchainProvider implements TransitiveInfoProvider {
public abstract String commandLine();
@Nullable
public abstract FilesToRunProvider pluginExecutable();
@Nullable
public abstract TransitiveInfoCollection runtime();
/**
* Returns a list of {@link ProtoSource}s that are already provided by the protobuf runtime (i.e.
* for which {@code <lang>_proto_library} should not generate bindings.
*/
public abstract ImmutableList<ProtoSource> providedProtoSources();
/**
* This makes the blacklisted_protos member available in the provider. It can be removed after
* users are migrated and a sufficient time for Bazel rules to migrate has elapsed.
*/
@Deprecated
public NestedSet<Artifact> blacklistedProtos() {
return forbiddenProtos();
}
// TODO(yannic): Remove after migrating all users to `providedProtoSources()`.
@Deprecated
public abstract NestedSet<Artifact> forbiddenProtos();
@AutoCodec.Instantiator
public static ProtoLangToolchainProvider createForDeserialization(
String commandLine,
FilesToRunProvider pluginExecutable,
TransitiveInfoCollection runtime,
ImmutableList<ProtoSource> providedProtoSources,
NestedSet<Artifact> blacklistedProtos) {
return new AutoValue_ProtoLangToolchainProvider(
commandLine, pluginExecutable, runtime, providedProtoSources, blacklistedProtos);
}
public static ProtoLangToolchainProvider create(
String commandLine,
FilesToRunProvider pluginExecutable,
TransitiveInfoCollection runtime,
ImmutableList<ProtoSource> providedProtoSources) {
NestedSetBuilder<Artifact> blacklistedProtos = NestedSetBuilder.stableOrder();
for (ProtoSource protoSource : providedProtoSources) {
blacklistedProtos.add(protoSource.getOriginalSourceFile());
}
return new AutoValue_ProtoLangToolchainProvider(
commandLine, pluginExecutable, runtime, providedProtoSources, blacklistedProtos.build());
}
}
| 1,094 |
333 |
<reponame>genisysram/jackson-dataformats-text<filename>properties/src/main/java/com/fasterxml/jackson/dataformat/javaprop/util/JPropNode.java
package com.fasterxml.jackson.dataformat.javaprop.util;
import java.util.*;
/**
* Value in an ordered tree presentation built from an arbitrarily ordered
* set of flat input values. Since either index- OR name-based access is to
* be supported (similar to, say, Javascript objects) -- but only one, not both --
* storage is bit of a hybrid. In addition, branches may also have values.
* So, code does bit coercion as necessary, trying to maintain something
* consistent and usable at all times, without failure.
*/
public class JPropNode
{
/**
* Value for the path, for leaf nodes; usually null for branches.
* If both children and value exists, typically need to construct
* bogus value with empty String key.
*/
protected String _value;
/**
* Child entries with integral number index, if any.
*/
protected TreeMap<Integer, JPropNode> _byIndex;
/**
* Child entries accessed with String property name, if any.
*/
protected Map<String, JPropNode> _byName;
protected boolean _hasContents = false;
public JPropNode setValue(String v) {
// should we care about overwrite?
_value = v;
return this;
}
public JPropNode addByIndex(int index) {
// if we already have named entries, coerce into name
if (_byName != null) {
return addByName(String.valueOf(index));
}
_hasContents = true;
if (_byIndex == null) {
_byIndex = new TreeMap<>();
}
Integer key = Integer.valueOf(index);
JPropNode n = _byIndex.get(key);
if (n == null) {
n = new JPropNode();
_byIndex.put(key, n);
}
return n;
}
public JPropNode addByName(String name) {
// if former index entries, first coerce them
_hasContents = true;
if (_byIndex != null) {
if (_byName == null) {
_byName = new LinkedHashMap<>();
}
for (Map.Entry<Integer, JPropNode> entry : _byIndex.entrySet()) {
_byName.put(entry.getKey().toString(), entry.getValue());
}
_byIndex = null;
}
if (_byName == null) {
_byName = new LinkedHashMap<>();
} else {
JPropNode old = _byName.get(name);
if (old != null) {
return old;
}
}
JPropNode result = new JPropNode();
_byName.put(name, result);
return result;
}
public boolean isLeaf() {
return !_hasContents && (_value != null);
}
public boolean isArray() {
return _byIndex != null;
}
public String getValue() {
return _value;
}
public Iterator<JPropNode> arrayContents() {
// should never be called if `_byIndex` is null, hence no checks
return _byIndex.values().iterator();
}
/**
* Child entries accessed with String property name, if any.
*/
public Iterator<Map.Entry<String, JPropNode>> objectContents() {
if (_byName == null) { // only value, most likely
return Collections.emptyIterator();
}
return _byName.entrySet().iterator();
}
/**
* Helper method, mostly for debugging/testing, to convert structure contained
* into simple List/Map/String equivalent.
*/
public Object asRaw() {
if (isArray()) {
List<Object> result = new ArrayList<>();
if (_value != null) {
result.add(_value);
}
for (JPropNode v : _byIndex.values()) {
result.add(v.asRaw());
}
return result;
}
if (_byName != null) {
Map<String,Object> result = new LinkedHashMap<>();
if (_value != null) {
result.put("", _value);
}
for (Map.Entry<String, JPropNode> entry : _byName.entrySet()) {
result.put(entry.getKey(), entry.getValue().asRaw());
}
return result;
}
return _value;
}
}
| 1,849 |
52,316 |
r"""Fixer for unicode.
* Changes unicode to str and unichr to chr.
* If "...\u..." is not unicode literal change it into "...\\u...".
* Change u"..." into "...".
"""
from ..pgen2 import token
from .. import fixer_base
_mapping = {"unichr" : "chr", "unicode" : "str"}
class FixUnicode(fixer_base.BaseFix):
BM_compatible = True
PATTERN = "STRING | 'unicode' | 'unichr'"
def start_tree(self, tree, filename):
super(FixUnicode, self).start_tree(tree, filename)
self.unicode_literals = 'unicode_literals' in tree.future_features
def transform(self, node, results):
if node.type == token.NAME:
new = node.clone()
new.value = _mapping[node.value]
return new
elif node.type == token.STRING:
val = node.value
if not self.unicode_literals and val[0] in '\'"' and '\\' in val:
val = r'\\'.join([
v.replace('\\u', r'\\u').replace('\\U', r'\\U')
for v in val.split(r'\\')
])
if val[0] in 'uU':
val = val[1:]
if val == node.value:
return node
new = node.clone()
new.value = val
return new
| 620 |
615 |
#include <iostream>
#include "meta/index/vocabulary_map.h"
using namespace meta;
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " filename" << std::endl;
return 1;
}
index::vocabulary_map map{argv[1]};
for (term_id tid{0}; tid < map.size(); ++tid)
std::cout << map.find_term(tid) << std::endl;
}
| 181 |
1,019 |
/**
* Copyright 2015-现在 广州市领课网络科技有限公司
*/
package com.roncoo.education.course.common.es;
import com.roncoo.education.util.base.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 分页
*
* @author wujing
* @param <T>
*/
public final class EsPageUtil<T extends Serializable> implements Serializable {
private static final Logger logger = LoggerFactory.getLogger(EsPageUtil.class);
private static final long serialVersionUID = 1L;
private EsPageUtil() {
}
public static <T extends Serializable> Page<T> transform(org.springframework.data.domain.Page<?> page, Class<T> classType) {
Page<T> pb = new Page<>();
try {
pb.setList(copyList(page.getContent(), classType));
} catch (Exception e) {
logger.error("transform error", e);
}
pb.setPageCurrent(page.getPageable().getPageNumber() + 1);
pb.setPageSize(page.getPageable().getPageSize());
pb.setTotalCount((int) page.getTotalElements());
pb.setTotalPage(page.getTotalPages());
return pb;
}
/**
* @param source
* @param clazz
* @return
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
*/
public static <T> List<T> copyList(List<?> source, Class<T> clazz) {
if (source == null || source.size() == 0) {
return Collections.emptyList();
}
List<T> res = new ArrayList<>(source.size());
for (Object o : source) {
try {
T t = clazz.newInstance();
res.add(t);
BeanUtils.copyProperties(o, t);
} catch (Exception e) {
logger.error("copyList error", e);
}
}
return res;
}
}
| 690 |
766 |
<filename>src/http.hpp
#pragma once
#include "stl.hpp"
#include "interface/http.hpp"
#include "interface/http_callback.hpp"
#include "single_thread_task_runner.hpp"
namespace mx3 {
struct HttpResponse {
bool error;
uint16_t http_code;
string data;
};
class Http final {
public:
Http(shared_ptr<mx3_gen::Http> http_impl, const shared_ptr<SingleThreadTaskRunner> & runner);
void get(const string& url, function<void(HttpResponse)>);
private:
class Request final : public mx3_gen::HttpCallback {
public:
Request(function<void(HttpResponse)> cb, const shared_ptr<SingleThreadTaskRunner> & on_thread);
virtual void on_network_error();
virtual void on_success(int16_t http_code, const string& data);
void _cb_with(HttpResponse resp);
private:
const shared_ptr<SingleThreadTaskRunner> m_cb_thread;
const function<void(HttpResponse)> m_cb;
};
const shared_ptr<SingleThreadTaskRunner> m_cb_thread;
const shared_ptr<mx3_gen::Http> m_http;
};
}
| 405 |
1,210 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making GameAISDK available.
This source code file is licensed under the GNU General Public License Version 3.
For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
"""
from .menu_debug import MenuDebug
from .menu_plugin import MenuPlugin
from .menu_scene import MenuScene
from .menu_project import MenuProject
from .menu_ui import MenuUI
from .menu_ai import MenuAI
from .menu_run import MenuRun
from .menu_applications import MenuApplications
from .menu_utils import MenuPackLog
class OpMenu(object):
def __init__(self, menu):
self.__menu = menu
self.__menu_list = []
self.__menu_list.append(MenuProject(menu))
self.__menu_list.append(MenuUI(menu))
self.__menu_list.append(MenuScene(menu))
self.__menu_list.append(MenuAI(menu))
self.__menu_list.append(MenuRun(menu))
self.__menu_list.append(MenuPlugin(menu))
self.__menu_list.append(MenuDebug(menu))
self.__menu_list.append(MenuApplications(menu))
self.__menu_list.append(MenuPackLog(menu))
def define_action(self):
for sub_menu in self.__menu_list:
sub_menu.define_action()
def set_slot(self, left_tree=None, right_tree=None):
for sub_menu in self.__menu_list:
sub_menu.set_slot(left_tree, right_tree)
| 562 |
456 |
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2004-2020 <NAME>
// All rights reserved.
#include <djvUI/Menu.h>
#include <djvUI/Action.h>
#include <djvUI/DrawUtil.h>
#include <djvUI/EventSystem.h>
#include <djvUI/ITooltipWidget.h>
#include <djvUI/IconSystem.h>
#include <djvUI/LayoutUtil.h>
#include <djvUI/MenuButton.h>
#include <djvUI/Overlay.h>
#include <djvUI/ScrollWidget.h>
#include <djvUI/Shortcut.h>
#include <djvUI/ShortcutData.h>
#include <djvUI/Window.h>
#include <djvRender2D/FontSystem.h>
#include <djvRender2D/Render.h>
#include <djvImage/Data.h>
#include <djvSystem/Context.h>
#include <djvSystem/TextSystem.h>
#include <djvCore/String.h>
using namespace djv::Core;
namespace djv
{
namespace UI
{
namespace
{
class MenuWidget : public Widget
{
DJV_NON_COPYABLE(MenuWidget);
protected:
void _init(const std::shared_ptr<System::Context>&);
MenuWidget();
public:
static std::shared_ptr<MenuWidget> create(const std::shared_ptr<System::Context>&);
void setActions(const std::map<size_t, std::shared_ptr<Action> >&);
void setCloseCallback(const std::function<void(void)>&);
protected:
void _preLayoutEvent(System::Event::PreLayout&) override;
void _layoutEvent(System::Event::Layout&) override;
void _paintEvent(System::Event::Paint&) override;
void _pointerEnterEvent(System::Event::PointerEnter&) override;
void _pointerLeaveEvent(System::Event::PointerLeave&) override;
void _pointerMoveEvent(System::Event::PointerMove&) override;
void _buttonPressEvent(System::Event::ButtonPress&) override;
void _buttonReleaseEvent(System::Event::ButtonRelease&) override;
std::shared_ptr<ITooltipWidget> _createTooltip(const glm::vec2& pos) override;
void _initEvent(System::Event::Init&) override;
void _updateEvent(System::Event::Update&) override;
private:
struct Item
{
ButtonType buttonType = ButtonType::First;
bool checked = false;
std::shared_ptr<Image::Data> icon;
std::string text;
std::string font;
Render2D::Font::FontInfo fontInfo;
Render2D::Font::Metrics fontMetrics;
glm::vec2 textSize = glm::vec2(0.F, 0.F);
std::vector<std::shared_ptr<Render2D::Font::Glyph> > textGlyphs;
std::string shortcutLabel;
glm::vec2 shortcutSize = glm::vec2(0.F, 0.F);
std::vector<std::shared_ptr<Render2D::Font::Glyph> > shortcutGlyphs;
bool enabled = true;
glm::vec2 size = glm::vec2(0.F, 0.F);
Math::BBox2f geom = Math::BBox2f(0.F, 0.F, 0.F, 0.F);
};
std::shared_ptr<Item> _getItem(const glm::vec2&) const;
void _itemsUpdate();
void _textUpdate();
std::shared_ptr<Render2D::Font::FontSystem> _fontSystem;
std::map<size_t, std::shared_ptr<Action> > _actions;
bool _hasIcons = false;
bool _hasShortcuts = false;
std::map<size_t, std::shared_ptr<Item> > _items;
std::map<std::shared_ptr<Action>, std::shared_ptr<Item> > _actionToItem;
std::map<std::shared_ptr<Item>, std::shared_ptr<Action> > _itemToAction;
std::map<std::shared_ptr<Item>, bool> _hasIcon;
std::map<std::shared_ptr<Item>, std::future<std::shared_ptr<Image::Data> > > _iconFutures;
std::map<std::shared_ptr<Item>, std::future<Render2D::Font::Metrics> > _fontMetricsFutures;
std::map<std::shared_ptr<Item>, std::future<glm::vec2> > _textSizeFutures;
std::map<std::shared_ptr<Item>, std::future<std::vector<std::shared_ptr<Render2D::Font::Glyph> > > > _textGlyphsFutures;
std::map<std::shared_ptr<Item>, std::future<glm::vec2> > _shortcutSizeFutures;
std::map<std::shared_ptr<Item>, std::future<std::vector<std::shared_ptr<Render2D::Font::Glyph> > > > _shortcutGlyphsFutures;
std::map<System::Event::PointerID, std::shared_ptr<Item> > _hoveredItems;
std::pair<System::Event::PointerID, std::shared_ptr<Item> > _pressed;
glm::vec2 _pressedPos = glm::vec2(0.F, 0.F);
std::function<void(void)> _closeCallback;
std::map<std::shared_ptr<Item>, std::shared_ptr<Observer::Value<ButtonType> > > _buttonTypeObservers;
std::map<std::shared_ptr<Item>, std::shared_ptr<Observer::Value<bool> > > _checkedObservers;
std::map<std::shared_ptr<Item>, std::shared_ptr<Observer::Value<std::string> > > _iconObservers;
std::map<std::shared_ptr<Item>, std::shared_ptr<Observer::Value<std::string> > > _textObservers;
std::map<std::shared_ptr<Item>, std::shared_ptr<Observer::Value<std::string> > > _fontObservers;
std::map<std::shared_ptr<Item>, std::shared_ptr<Observer::List<std::shared_ptr<Shortcut> > > > _shortcutsObservers;
std::map<std::shared_ptr<Item>, std::shared_ptr<Observer::Value<bool> > > _enabledObservers;
bool _textUpdateRequest = false;
};
void MenuWidget::_init(const std::shared_ptr<System::Context>& context)
{
Widget::_init(context);
setClassName("djv::UI::MenuWidget");
_fontSystem = context->getSystemT<Render2D::Font::FontSystem>();
}
MenuWidget::MenuWidget()
{}
std::shared_ptr<MenuWidget> MenuWidget::create(const std::shared_ptr<System::Context>& context)
{
auto out = std::shared_ptr<MenuWidget>(new MenuWidget);
out->_init(context);
return out;
}
void MenuWidget::setActions(const std::map<size_t, std::shared_ptr<Action> >& actions)
{
_actions = actions;
_itemsUpdate();
}
void MenuWidget::setCloseCallback(const std::function<void(void)>& value)
{
_closeCallback = value;
}
void MenuWidget::_preLayoutEvent(System::Event::PreLayout&)
{
const auto& style = _getStyle();
const float m = style->getMetric(MetricsRole::MarginInside);
const float s = style->getMetric(MetricsRole::Spacing);
const float b = style->getMetric(MetricsRole::Border);
const float is = style->getMetric(MetricsRole::Icon);
glm::vec2 textSize(0.F, 0.F);
glm::vec2 shortcutSize(0.F, 0.F);
for (const auto& i : _items)
{
const auto j = _itemToAction.find(i.second);
if (j != _itemToAction.end() && j->second)
{
textSize.x = std::max(textSize.x, i.second->textSize.x);
textSize.y = std::max(textSize.y, i.second->textSize.y);
}
if (!i.second->shortcutLabel.empty())
{
shortcutSize.x = std::max(shortcutSize.x, i.second->shortcutSize.x);
shortcutSize.y = std::max(shortcutSize.y, i.second->shortcutSize.y);
}
}
glm::vec2 itemSize(0.F, 0.F);
const glm::vec2 checkBoxSize = getCheckBoxSize(style);
itemSize.x += checkBoxSize.x + m * 2.F;
itemSize.y = std::max(itemSize.y, checkBoxSize.y + m * 2.F);
if (_hasIcons)
{
itemSize.x += is;
itemSize.y = std::max(itemSize.y, is);
}
itemSize.x += textSize.x + m * 2.F;
itemSize.y = std::max(itemSize.y, textSize.y + m * 2.F);
if (_hasShortcuts)
{
itemSize.x += s + shortcutSize.x + m * 2.F;
itemSize.y = std::max(itemSize.y, shortcutSize.y + m * 2.F);
}
std::map<size_t, glm::vec2> sizes;
for (auto& i : _items)
{
glm::vec2 size(0.F, 0.F);
const auto j = _itemToAction.find(i.second);
if (j != _itemToAction.end() && j->second)
{
size = itemSize + m * 2.F;
}
else
{
size = glm::vec2(b, b);
}
i.second->size = size;
sizes[i.first] = size;
}
glm::vec2 size(0.F, 0.F);
for (const auto& i : sizes)
{
size.x = std::max(size.x, i.second.x);
size.y += i.second.y;
}
_setMinimumSize(size + b * 2.F);
}
void MenuWidget::_layoutEvent(System::Event::Layout&)
{
const auto& style = _getStyle();
const float b = style->getMetric(MetricsRole::Border);
const Math::BBox2f g = getGeometry().margin(-b);
float y = g.min.y;
for (auto& i : _items)
{
i.second->geom.min.x = g.min.x;
i.second->geom.min.y = y;
i.second->geom.max.x = g.max.x;
i.second->geom.max.y = y + i.second->size.y;
y += i.second->size.y;
}
}
void MenuWidget::_paintEvent(System::Event::Paint& event)
{
Widget::_paintEvent(event);
const auto& style = _getStyle();
const float s = style->getMetric(MetricsRole::Spacing);
const float m = style->getMetric(MetricsRole::MarginInside);
const float b = style->getMetric(MetricsRole::Border);
const float is = style->getMetric(MetricsRole::Icon);
const Math::BBox2f& g = getGeometry();
const auto& render = _getRender();
render->setFillColor(style->getColor(ColorRole::Border));
drawBorder(render, g, b);
const Math::BBox2f g2 = g.margin(-b);
for (const auto& i : _items)
{
if (i.second->enabled)
{
if (i.second == _pressed.second)
{
render->setFillColor(style->getColor(ColorRole::Pressed));
render->drawRect(i.second->geom);
}
else
{
for (const auto& hovered : _hoveredItems)
{
if (i.second == hovered.second)
{
render->setFillColor(style->getColor(ColorRole::Hovered));
render->drawRect(i.second->geom);
break;
}
}
}
}
}
for (const auto& i : _items)
{
float x = i.second->geom.min.x + m;
float y = 0.F;
render->setAlphaMult(i.second->enabled ? 1.F : style->getPalette().getDisabledMult());
const glm::vec2 checkBoxSize = getCheckBoxSize(style);
switch (i.second->buttonType)
{
case ButtonType::Toggle:
case ButtonType::Radio:
case ButtonType::Exclusive:
{
const Math::BBox2f checkBoxGeometry(
x + m,
floorf(i.second->geom.min.y + ceilf(i.second->size.y / 2.F - checkBoxSize.y / 2.F)),
checkBoxSize.x,
checkBoxSize.y);
drawCheckBox(render, style, checkBoxGeometry, i.second->checked);
break;
}
default: break;
}
x += checkBoxSize.x + m * 2.F;
if (_hasIcons)
{
render->setFillColor(style->getColor(ColorRole::Foreground));
if (i.second->icon)
{
y = i.second->geom.min.y + ceilf(i.second->size.y / 2.F - is / 2.F);
render->drawFilledImage(i.second->icon, glm::vec2(x, y));
}
x += is;
}
render->setFillColor(style->getColor(ColorRole::Foreground));
const auto j = _itemToAction.find(i.second);
if (j != _itemToAction.end() && j->second)
{
y = i.second->geom.min.y + ceilf(i.second->size.y / 2.F) - ceilf(i.second->fontMetrics.lineHeight / 2.F) + i.second->fontMetrics.ascender;
render->drawText(i.second->textGlyphs, glm::vec2(x + m, y));
x += i.second->textSize.x + m * 2.F;
if (!i.second->shortcutLabel.empty())
{
x = g2.max.x - i.second->shortcutSize.x - m;
render->drawText(i.second->shortcutGlyphs, glm::vec2(x, y));
}
}
else
{
render->setFillColor(style->getColor(ColorRole::Border));
render->drawRect(i.second->geom);
}
render->setAlphaMult(1.F);
}
}
void MenuWidget::_pointerEnterEvent(System::Event::PointerEnter& event)
{
event.accept();
const auto& pointerInfo = event.getPointerInfo();
if (auto item = _getItem(pointerInfo.projectedPos))
{
_hoveredItems[pointerInfo.id] = item;
}
_redraw();
}
void MenuWidget::_pointerLeaveEvent(System::Event::PointerLeave& event)
{
event.accept();
const auto& pointerInfo = event.getPointerInfo();
const auto i = _hoveredItems.find(pointerInfo.id);
if (i != _hoveredItems.end())
{
_hoveredItems.erase(i);
}
_redraw();
}
void MenuWidget::_pointerMoveEvent(System::Event::PointerMove& event)
{
event.accept();
const auto& pointerInfo = event.getPointerInfo();
const auto id = pointerInfo.id;
const auto& pos = pointerInfo.projectedPos;
if (id == _pressed.first)
{
const float distance = glm::length(pos - _pressedPos);
const auto& style = _getStyle();
const bool accepted = distance < style->getMetric(MetricsRole::Drag);
event.setAccepted(accepted);
if (!accepted)
{
_pressed.first = 0;
_pressed.second = nullptr;
_redraw();
}
}
else
{
if (auto item = _getItem(pos))
{
if (_hoveredItems[id] != item)
{
_hoveredItems[id] = item;
_redraw();
}
}
}
}
void MenuWidget::_buttonPressEvent(System::Event::ButtonPress& event)
{
if (_pressed.second)
return;
const auto& pointerInfo = event.getPointerInfo();
const auto id = pointerInfo.id;
const auto& pos = pointerInfo.projectedPos;
if (auto item = _getItem(pos))
{
if (item->enabled)
{
event.accept();
_pressed.first = id;
_pressed.second = item;
_pressedPos = pos;
_redraw();
}
}
}
void MenuWidget::_buttonReleaseEvent(System::Event::ButtonRelease& event)
{
const auto& pointerInfo = event.getPointerInfo();
const auto id = pointerInfo.id;
const auto& pos = pointerInfo.projectedPos;
if (_pressed.second)
{
const auto i = _itemToAction.find(_pressed.second);
if (i != _itemToAction.end())
{
i->second->doClick();
if (_closeCallback)
{
_closeCallback();
}
}
_pressed.first = 0;
_pressed.second = nullptr;
if (auto item = _getItem(pos))
{
_hoveredItems[id] = item;
_redraw();
}
}
}
std::shared_ptr<ITooltipWidget> MenuWidget::_createTooltip(const glm::vec2& pos)
{
std::shared_ptr<ITooltipWidget> out;
std::string text;
for (const auto& i : _items)
{
if (i.second->geom.contains(pos))
{
const auto j = _itemToAction.find(i.second);
if (j != _itemToAction.end())
{
text = j->second->observeTooltip()->get();
break;
}
}
}
if (!text.empty())
{
out = _createTooltipDefault();
out->setTooltip(text);
}
return out;
}
void MenuWidget::_initEvent(System::Event::Init& event)
{
if (event.getData().resize || event.getData().font)
{
_itemsUpdate();
}
}
void MenuWidget::_updateEvent(System::Event::Update&)
{
if (_textUpdateRequest)
{
_textUpdate();
}
for (auto& i : _iconFutures)
{
if (i.second.valid() &&
i.second.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
{
try
{
i.first->icon = i.second.get();
_resize();
}
catch (const std::exception& e)
{
_log(e.what(), System::LogLevel::Error);
}
}
}
for (auto& i : _fontMetricsFutures)
{
if (i.second.valid() &&
i.second.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
{
try
{
i.first->fontMetrics = i.second.get();
_resize();
}
catch (const std::exception& e)
{
_log(e.what(), System::LogLevel::Error);
}
}
}
for (auto& i : _textSizeFutures)
{
if (i.second.valid() &&
i.second.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
{
try
{
i.first->textSize = i.second.get();
_resize();
}
catch (const std::exception& e)
{
_log(e.what(), System::LogLevel::Error);
}
}
}
for (auto& i : _textGlyphsFutures)
{
if (i.second.valid() &&
i.second.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
{
try
{
i.first->textGlyphs = i.second.get();
_resize();
}
catch (const std::exception& e)
{
_log(e.what(), System::LogLevel::Error);
}
}
}
for (auto& i : _shortcutSizeFutures)
{
if (i.second.valid() &&
i.second.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
{
try
{
i.first->shortcutSize = i.second.get();
_resize();
}
catch (const std::exception& e)
{
_log(e.what(), System::LogLevel::Error);
}
}
}
for (auto& i : _shortcutGlyphsFutures)
{
if (i.second.valid() &&
i.second.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
{
try
{
i.first->shortcutGlyphs = i.second.get();
_resize();
}
catch (const std::exception& e)
{
_log(e.what(), System::LogLevel::Error);
}
}
}
}
std::shared_ptr<MenuWidget::Item> MenuWidget::_getItem(const glm::vec2& pos) const
{
std::shared_ptr<MenuWidget::Item> out;
for (const auto& i : _items)
{
const auto j = _itemToAction.find(i.second);
if (i.second->geom.contains(pos) && j != _itemToAction.end() && j->second)
{
out = i.second;
break;
}
}
return out;
}
void MenuWidget::_itemsUpdate()
{
_hasIcons = false;
_hasShortcuts = false;
_items.clear();
_actionToItem.clear();
_itemToAction.clear();
_hasIcon.clear();
_iconFutures.clear();
_fontMetricsFutures.clear();
_textSizeFutures.clear();
_textGlyphsFutures.clear();
_shortcutSizeFutures.clear();
_shortcutGlyphsFutures.clear();
_buttonTypeObservers.clear();
_checkedObservers.clear();
_iconObservers.clear();
_textObservers.clear();
_fontObservers.clear();
_shortcutsObservers.clear();
_enabledObservers.clear();
auto weak = std::weak_ptr<MenuWidget>(std::dynamic_pointer_cast<MenuWidget>(shared_from_this()));
auto contextWeak = getContext();
for (const auto& i : _actions)
{
auto item = std::shared_ptr<Item>(new Item);
if (i.second)
{
_buttonTypeObservers[item] = Observer::Value<ButtonType>::create(
i.second->observeButtonType(),
[item, weak](ButtonType value)
{
if (auto widget = weak.lock())
{
item->buttonType = value;
widget->_redraw();
}
});
_checkedObservers[item] = Observer::Value<bool>::create(
i.second->observeChecked(),
[item, weak](bool value)
{
if (auto widget = weak.lock())
{
item->checked = value;
widget->_redraw();
}
});
_iconObservers[item] = Observer::Value<std::string>::create(
i.second->observeIcon(),
[item, weak](const std::string& value)
{
if (auto widget = weak.lock())
{
widget->_hasIcon[item] = !value.empty();
widget->_hasIcons = false;
for (const auto& i : widget->_hasIcon)
{
widget->_hasIcons |= i.second;
}
if (widget->_hasIcon[item])
{
if (auto context = widget->getContext().lock())
{
auto iconSystem = context->getSystemT<IconSystem>();
auto style = widget->_getStyle();
widget->_iconFutures[item] = iconSystem->getIcon(value, style->getMetric(MetricsRole::Icon));
widget->_resize();
}
}
}
});
_textObservers[item] = Observer::Value<std::string>::create(
i.second->observeText(),
[item, weak](const std::string& value)
{
if (auto widget = weak.lock())
{
item->text = value;
widget->_textUpdateRequest = true;
}
});
_fontObservers[item] = Observer::Value<std::string>::create(
i.second->observeFont(),
[item, weak](const std::string& value)
{
if (auto widget = weak.lock())
{
item->font = value;
widget->_textUpdateRequest = true;
}
});
_shortcutsObservers[item] = Observer::List<std::shared_ptr<Shortcut> >::create(
i.second->observeShortcuts(),
[item, weak, contextWeak](const std::vector<std::shared_ptr<Shortcut> >& value)
{
if (auto context = contextWeak.lock())
{
if (auto widget = weak.lock())
{
auto textSystem = context->getSystemT<System::TextSystem>();
std::vector<std::string> labels;
for (const auto& i : value)
{
const auto& shortcut = i->observeShortcut()->get();
if (shortcut.isValid())
{
labels.push_back(getText(shortcut.key, shortcut.modifiers, textSystem));
}
}
item->shortcutLabel = String::join(labels, ", ");
widget->_textUpdateRequest = true;
}
}
});
_enabledObservers[item] = Observer::Value<bool>::create(
i.second->observeEnabled(),
[item, weak](bool value)
{
if (auto widget = weak.lock())
{
item->enabled = value;
widget->_redraw();
}
});
}
_items[i.first] = item;
_actionToItem[i.second] = item;
_itemToAction[item] = i.second;
}
_textUpdate();
}
void MenuWidget::_textUpdate()
{
_textUpdateRequest = false;
const auto& style = _getStyle();
auto textSystem = _getTextSystem();
_hasShortcuts = false;
for (auto& i : _items)
{
i.second->fontInfo = i.second->font.empty() ?
style->getFontInfo(Render2D::Font::faceDefault, MetricsRole::FontMedium) :
style->getFontInfo(i.second->font, Render2D::Font::faceDefault, MetricsRole::FontMedium);
_fontMetricsFutures[i.second] = _fontSystem->getMetrics(i.second->fontInfo);
_textSizeFutures[i.second] = _fontSystem->measure(i.second->text, i.second->fontInfo);
_textGlyphsFutures[i.second] = _fontSystem->getGlyphs(i.second->text, i.second->fontInfo);
_shortcutSizeFutures[i.second] = _fontSystem->measure(i.second->shortcutLabel, i.second->fontInfo);
_shortcutGlyphsFutures[i.second] = _fontSystem->getGlyphs(i.second->shortcutLabel, i.second->fontInfo);
_hasShortcuts |= i.second->shortcutLabel.size() > 0;
}
}
class MenuPopupWidget : public Widget
{
DJV_NON_COPYABLE(MenuPopupWidget);
protected:
void _init(const std::shared_ptr<System::Context>&);
MenuPopupWidget();
public:
static std::shared_ptr<MenuPopupWidget> create(const std::shared_ptr<System::Context>&);
void setActions(const std::map<size_t, std::shared_ptr<Action> >&);
MetricsRole getMinimumSizeRole() const;
void setMinimumSizeRole(MetricsRole);
void setCloseCallback(const std::function<void(void)>&);
protected:
void _preLayoutEvent(System::Event::PreLayout&) override;
void _layoutEvent(System::Event::Layout&) override;
void _buttonPressEvent(System::Event::ButtonPress&) override;
void _buttonReleaseEvent(System::Event::ButtonRelease&) override;
private:
std::shared_ptr<ScrollWidget> _scrollWidget;
std::shared_ptr<MenuWidget> _menuWidget;
};
void MenuPopupWidget::_init(const std::shared_ptr<System::Context>& context)
{
Widget::_init(context);
setClassName("djv::UI::MenuPopupWidget");
setPointerEnabled(true);
_menuWidget = MenuWidget::create(context);
_scrollWidget = ScrollWidget::create(ScrollType::Vertical, context);
_scrollWidget->setBorder(false);
_scrollWidget->addChild(_menuWidget);
addChild(_scrollWidget);
}
MenuPopupWidget::MenuPopupWidget()
{}
std::shared_ptr<MenuPopupWidget> MenuPopupWidget::create(const std::shared_ptr<System::Context>& context)
{
auto out = std::shared_ptr< MenuPopupWidget>(new MenuPopupWidget);
out->_init(context);
return out;
}
void MenuPopupWidget::setActions(const std::map<size_t, std::shared_ptr<Action> >& actions)
{
_menuWidget->setActions(actions);
}
MetricsRole MenuPopupWidget::getMinimumSizeRole() const
{
return _scrollWidget->getMinimumSizeRole();
}
void MenuPopupWidget::setMinimumSizeRole(MetricsRole value)
{
_scrollWidget->setMinimumSizeRole(value);
}
void MenuPopupWidget::setCloseCallback(const std::function<void(void)>& callback)
{
_menuWidget->setCloseCallback(callback);
}
void MenuPopupWidget::_buttonPressEvent(System::Event::ButtonPress& event)
{
event.accept();
}
void MenuPopupWidget::_buttonReleaseEvent(System::Event::ButtonRelease& event)
{
event.accept();
}
void MenuPopupWidget::_preLayoutEvent(System::Event::PreLayout&)
{
_setMinimumSize(_scrollWidget->getMinimumSize());
}
void MenuPopupWidget::_layoutEvent(System::Event::Layout&)
{
const Math::BBox2f& g = getGeometry();
_scrollWidget->setGeometry(g);
}
class MenuLayout : public Widget
{
DJV_NON_COPYABLE(MenuLayout);
protected:
void _init(const std::shared_ptr<System::Context>&);
MenuLayout();
public:
static std::shared_ptr<MenuLayout> create(const std::shared_ptr<System::Context>&);
void setPos(const std::shared_ptr<MenuPopupWidget>&, const glm::vec2&);
void setButton(const std::shared_ptr<MenuPopupWidget>&, const std::weak_ptr<Button::Menu>&);
protected:
void _layoutEvent(System::Event::Layout&) override;
void _paintEvent(System::Event::Paint&) override;
void _childRemovedEvent(System::Event::ChildRemoved&) override;
private:
std::map<std::shared_ptr<MenuPopupWidget>, glm::vec2> _widgetToPos;
std::map<std::shared_ptr<MenuPopupWidget>, std::weak_ptr<Button::Menu> > _widgetToButton;
std::map<std::shared_ptr<MenuPopupWidget>, Popup> _widgetToPopup;
};
void MenuLayout::_init(const std::shared_ptr<System::Context>& context)
{
Widget::_init(context);
setClassName("djv::UI::MenuLayout");
}
MenuLayout::MenuLayout()
{}
std::shared_ptr<MenuLayout> MenuLayout::create(const std::shared_ptr<System::Context>& context)
{
auto out = std::shared_ptr<MenuLayout>(new MenuLayout);
out->_init(context);
return out;
}
void MenuLayout::setPos(const std::shared_ptr<MenuPopupWidget>& widget, const glm::vec2& pos)
{
_widgetToPos[widget] = pos;
}
void MenuLayout::setButton(const std::shared_ptr<MenuPopupWidget>& widget, const std::weak_ptr<Button::Menu>& button)
{
_widgetToButton[widget] = button;
}
void MenuLayout::_layoutEvent(System::Event::Layout&)
{
const auto& style = _getStyle();
const Math::BBox2f& g = getMargin().bbox(getGeometry(), style);
for (const auto& i : _widgetToPos)
{
const auto& pos = i.second;
const auto& minimumSize = i.first->getMinimumSize();
Popup popup = Popup::BelowRight;
auto j = _widgetToPopup.find(i.first);
if (j != _widgetToPopup.end())
{
popup = j->second;
}
else
{
popup = Layout::getPopup(popup, g, pos, minimumSize);
_widgetToPopup[i.first] = popup;
}
const Math::BBox2f popupGeometry = Layout::getPopupGeometry(popup, pos, minimumSize);
i.first->setGeometry(popupGeometry.intersect(g));
}
for (const auto& i : _widgetToButton)
{
if (auto button = i.second.lock())
{
const auto& buttonBBox = button->getGeometry();
const auto& minimumSize = i.first->getMinimumSize();
Popup popup = Popup::BelowRight;
auto j = _widgetToPopup.find(i.first);
if (j != _widgetToPopup.end())
{
popup = j->second;
}
else
{
popup = Layout::getPopup(popup, g, buttonBBox, minimumSize);
}
const Math::BBox2f popupGeometry = Layout::getPopupGeometry(popup, buttonBBox, minimumSize);
i.first->setGeometry(popupGeometry.intersect(g));
}
}
}
void MenuLayout::_paintEvent(System::Event::Paint& event)
{
Widget::_paintEvent(event);
const auto& style = _getStyle();
const float sh = style->getMetric(MetricsRole::Shadow);
const auto& render = _getRender();
render->setFillColor(style->getColor(ColorRole::Shadow));
for (const auto& i : getChildWidgets())
{
Math::BBox2f g = i->getGeometry();
g.min.x -= sh;
g.max.x += sh;
g.max.y += sh;
if (g.isValid())
{
render->drawShadow(g, sh);
}
}
}
void MenuLayout::_childRemovedEvent(System::Event::ChildRemoved& event)
{
if (auto widget = std::dynamic_pointer_cast<MenuPopupWidget>(event.getChild()))
{
const auto i = _widgetToPos.find(widget);
if (i != _widgetToPos.end())
{
_widgetToPos.erase(i);
}
const auto j = _widgetToButton.find(widget);
if (j != _widgetToButton.end())
{
_widgetToButton.erase(j);
}
const auto k = _widgetToPopup.find(widget);
if (k != _widgetToPopup.end())
{
_widgetToPopup.erase(k);
}
}
}
} // namespace
struct Menu::Private
{
std::shared_ptr<Observer::ValueSubject<std::string> > icon;
std::shared_ptr<Observer::ValueSubject<std::string> > text;
std::map<size_t, std::shared_ptr<Action> > actions;
size_t count = 0;
MetricsRole minimumSizeRole = MetricsRole::ScrollArea;
ColorRole backgroundColorRole = ColorRole::Background;
std::shared_ptr<MenuPopupWidget> popupWidget;
std::shared_ptr<MenuLayout> layout;
std::shared_ptr<Layout::Overlay> overlay;
std::shared_ptr<Window> window;
std::function<void(void)> closeCallback;
void createOverlay();
};
void Menu::_init(const std::shared_ptr<System::Context>& context)
{
IObject::_init(context);
DJV_PRIVATE_PTR();
p.icon = Observer::ValueSubject<std::string>::create();
p.text = Observer::ValueSubject<std::string>::create();
}
Menu::Menu() :
_p(new Private)
{}
Menu::~Menu()
{
DJV_PRIVATE_PTR();
if (p.window)
{
p.window->close();
}
}
std::shared_ptr<Menu> Menu::create(const std::shared_ptr<System::Context>& context)
{
auto out = std::shared_ptr<Menu>(new Menu);
out->_init(context);
return out;
}
std::shared_ptr<Observer::IValueSubject<std::string> > Menu::observeIcon() const
{
return _p->icon;
}
void Menu::setIcon(const std::string& value)
{
_p->icon->setIfChanged(value);
}
std::shared_ptr<Observer::IValueSubject<std::string> > Menu::observeText() const
{
return _p->text;
}
void Menu::setText(const std::string& value)
{
_p->text->setIfChanged(value);
}
void Menu::addAction(const std::shared_ptr<Action>& action)
{
DJV_PRIVATE_PTR();
p.actions[p.count++] = action;
}
void Menu::removeAction(const std::shared_ptr<Action>& action)
{
DJV_PRIVATE_PTR();
auto i = p.actions.begin();
while (i != p.actions.end())
{
if (i->second == action)
{
i = p.actions.erase(i);
}
else
{
++i;
}
}
}
void Menu::clearActions()
{
DJV_PRIVATE_PTR();
p.actions.clear();
}
void Menu::addSeparator()
{
DJV_PRIVATE_PTR();
p.actions[p.count++] = nullptr;
}
MetricsRole Menu::getMinimumSizeRole() const
{
return _p->minimumSizeRole;
}
ColorRole Menu::getBackgroundColorRole() const
{
return _p->backgroundColorRole;
}
void Menu::setMinimumSizeRole(MetricsRole value)
{
_p->minimumSizeRole = value;
}
void Menu::setBackgroundColorRole(ColorRole value)
{
DJV_PRIVATE_PTR();
if (value == p.backgroundColorRole)
return;
p.backgroundColorRole = value;
if (p.popupWidget)
{
p.popupWidget->setBackgroundColorRole(p.backgroundColorRole);
}
}
std::shared_ptr<Widget> Menu::popup(const glm::vec2& pos)
{
DJV_PRIVATE_PTR();
std::shared_ptr<Widget> out;
_createWidgets();
if (p.popupWidget)
{
p.layout->setPos(p.popupWidget, pos);
}
p.overlay->show();
p.window->show();
out = p.overlay;
return out;
}
std::shared_ptr<Widget> Menu::popup(const std::weak_ptr<Button::Menu>& button)
{
DJV_PRIVATE_PTR();
std::shared_ptr<Widget> out;
_createWidgets();
if (p.popupWidget)
{
p.layout->setButton(p.popupWidget, button);
}
p.overlay->show();
p.window->show();
out = p.overlay;
return out;
}
std::shared_ptr<Widget> Menu::popup(const std::weak_ptr<Button::Menu>& button, const std::weak_ptr<Widget>& anchor)
{
DJV_PRIVATE_PTR();
std::shared_ptr<Widget> out;
_createWidgets();
if (p.popupWidget)
{
p.layout->setButton(p.popupWidget, button);
}
p.overlay->show();
p.window->show();
out = p.overlay;
return out;
}
bool Menu::isOpen() const
{
return _p->overlay.get();
}
void Menu::close()
{
DJV_PRIVATE_PTR();
if (p.window)
{
p.popupWidget.reset();
p.layout.reset();
p.overlay.reset();
p.window->close();
p.window.reset();
if (p.closeCallback)
{
p.closeCallback();
}
}
}
void Menu::setCloseCallback(const std::function<void(void)>& callback)
{
_p->closeCallback = callback;
}
void Menu::_createWidgets()
{
DJV_PRIVATE_PTR();
if (auto context = getContext().lock())
{
if (p.window)
{
p.window->close();
p.window.reset();
}
if (p.count)
{
p.popupWidget = MenuPopupWidget::create(context);
p.popupWidget->setActions(p.actions);
p.popupWidget->setMinimumSizeRole(p.minimumSizeRole);
p.popupWidget->setBackgroundColorRole(p.backgroundColorRole);
}
p.layout = MenuLayout::create(context);
p.layout->setMargin(Layout::Margin(MetricsRole::None, MetricsRole::None, MetricsRole::Margin, MetricsRole::Margin));
if (p.popupWidget)
{
p.layout->addChild(p.popupWidget);
}
p.overlay = Layout::Overlay::create(context);
p.overlay->setFadeIn(false);
p.overlay->setBackgroundColorRole(ColorRole::None);
p.overlay->addChild(p.layout);
p.window = Window::create(context);
p.window->setBackgroundColorRole(ColorRole::None);
p.window->addChild(p.overlay);
auto weak = std::weak_ptr<Menu>(std::dynamic_pointer_cast<Menu>(shared_from_this()));
if (p.popupWidget)
{
p.popupWidget->setCloseCallback(
[weak]
{
if (auto menu = weak.lock())
{
menu->close();
}
});
}
p.overlay->setCloseCallback(
[weak]
{
if (auto menu = weak.lock())
{
menu->close();
}
});
}
}
} // namespace UI
} // namespace djv
| 29,503 |
2,151 |
//===- RegionInfo.h - SESE region analysis ----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Calculate a program structure tree built out of single entry single exit
// regions.
// The basic ideas are taken from "The Program Structure Tree - <NAME>,
// <NAME>, <NAME> - 1994", however enriched with ideas from "The
// Refined Process Structure Tree - <NAME>, <NAME>, Jana
// Koehler - 2009".
// The algorithm to calculate these data structures however is completely
// different, as it takes advantage of existing information already available
// in (Post)dominace tree and dominance frontier passes. This leads to a simpler
// and in practice hopefully better performing algorithm. The runtime of the
// algorithms described in the papers above are both linear in graph size,
// O(V+E), whereas this algorithm is not, as the dominance frontier information
// itself is not, but in practice runtime seems to be in the order of magnitude
// of dominance tree calculation.
//
// WARNING: LLVM is generally very concerned about compile time such that
// the use of additional analysis passes in the default
// optimization sequence is avoided as much as possible.
// Specifically, if you do not need the RegionInfo, but dominance
// information could be sufficient please base your work only on
// the dominator tree. Most passes maintain it, such that using
// it has often near zero cost. In contrast RegionInfo is by
// default not available, is not maintained by existing
// transformations and there is no intention to do so.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_ANALYSIS_REGIONINFO_H
#define LLVM_ANALYSIS_REGIONINFO_H
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/PassManager.h"
#include <map>
#include <memory>
#include <set>
namespace llvm {
// Class to be specialized for different users of RegionInfo
// (i.e. BasicBlocks or MachineBasicBlocks). This is only to avoid needing to
// pass around an unreasonable number of template parameters.
template <class FuncT_>
struct RegionTraits {
// FuncT
// BlockT
// RegionT
// RegionNodeT
// RegionInfoT
typedef typename FuncT_::UnknownRegionTypeError BrokenT;
};
class DominatorTree;
class DominanceFrontier;
class Loop;
class LoopInfo;
struct PostDominatorTree;
class raw_ostream;
class Region;
template <class RegionTr>
class RegionBase;
class RegionNode;
class RegionInfo;
template <class RegionTr>
class RegionInfoBase;
template <>
struct RegionTraits<Function> {
typedef Function FuncT;
typedef BasicBlock BlockT;
typedef Region RegionT;
typedef RegionNode RegionNodeT;
typedef RegionInfo RegionInfoT;
typedef DominatorTree DomTreeT;
typedef DomTreeNode DomTreeNodeT;
typedef DominanceFrontier DomFrontierT;
typedef PostDominatorTree PostDomTreeT;
typedef Instruction InstT;
typedef Loop LoopT;
typedef LoopInfo LoopInfoT;
static unsigned getNumSuccessors(BasicBlock *BB) {
return BB->getTerminator()->getNumSuccessors();
}
};
/// @brief Marker class to iterate over the elements of a Region in flat mode.
///
/// The class is used to either iterate in Flat mode or by not using it to not
/// iterate in Flat mode. During a Flat mode iteration all Regions are entered
/// and the iteration returns every BasicBlock. If the Flat mode is not
/// selected for SubRegions just one RegionNode containing the subregion is
/// returned.
template <class GraphType>
class FlatIt {};
/// @brief A RegionNode represents a subregion or a BasicBlock that is part of a
/// Region.
template <class Tr>
class RegionNodeBase {
friend class RegionBase<Tr>;
public:
typedef typename Tr::BlockT BlockT;
typedef typename Tr::RegionT RegionT;
private:
RegionNodeBase(const RegionNodeBase &) = delete;
const RegionNodeBase &operator=(const RegionNodeBase &) = delete;
/// This is the entry basic block that starts this region node. If this is a
/// BasicBlock RegionNode, then entry is just the basic block, that this
/// RegionNode represents. Otherwise it is the entry of this (Sub)RegionNode.
///
/// In the BBtoRegionNode map of the parent of this node, BB will always map
/// to this node no matter which kind of node this one is.
///
/// The node can hold either a Region or a BasicBlock.
/// Use one bit to save, if this RegionNode is a subregion or BasicBlock
/// RegionNode.
PointerIntPair<BlockT *, 1, bool> entry;
/// @brief The parent Region of this RegionNode.
/// @see getParent()
RegionT *parent;
protected:
/// @brief Create a RegionNode.
///
/// @param Parent The parent of this RegionNode.
/// @param Entry The entry BasicBlock of the RegionNode. If this
/// RegionNode represents a BasicBlock, this is the
/// BasicBlock itself. If it represents a subregion, this
/// is the entry BasicBlock of the subregion.
/// @param isSubRegion If this RegionNode represents a SubRegion.
inline RegionNodeBase(RegionT *Parent, BlockT *Entry,
bool isSubRegion = false)
: entry(Entry, isSubRegion), parent(Parent) {}
public:
/// @brief Get the parent Region of this RegionNode.
///
/// The parent Region is the Region this RegionNode belongs to. If for
/// example a BasicBlock is element of two Regions, there exist two
/// RegionNodes for this BasicBlock. Each with the getParent() function
/// pointing to the Region this RegionNode belongs to.
///
/// @return Get the parent Region of this RegionNode.
inline RegionT *getParent() const { return parent; }
/// @brief Get the entry BasicBlock of this RegionNode.
///
/// If this RegionNode represents a BasicBlock this is just the BasicBlock
/// itself, otherwise we return the entry BasicBlock of the Subregion
///
/// @return The entry BasicBlock of this RegionNode.
inline BlockT *getEntry() const { return entry.getPointer(); }
/// @brief Get the content of this RegionNode.
///
/// This can be either a BasicBlock or a subregion. Before calling getNodeAs()
/// check the type of the content with the isSubRegion() function call.
///
/// @return The content of this RegionNode.
template <class T> inline T *getNodeAs() const;
/// @brief Is this RegionNode a subregion?
///
/// @return True if it contains a subregion. False if it contains a
/// BasicBlock.
inline bool isSubRegion() const { return entry.getInt(); }
};
//===----------------------------------------------------------------------===//
/// @brief A single entry single exit Region.
///
/// A Region is a connected subgraph of a control flow graph that has exactly
/// two connections to the remaining graph. It can be used to analyze or
/// optimize parts of the control flow graph.
///
/// A <em> simple Region </em> is connected to the remaining graph by just two
/// edges. One edge entering the Region and another one leaving the Region.
///
/// An <em> extended Region </em> (or just Region) is a subgraph that can be
/// transform into a simple Region. The transformation is done by adding
/// BasicBlocks that merge several entry or exit edges so that after the merge
/// just one entry and one exit edge exists.
///
/// The \e Entry of a Region is the first BasicBlock that is passed after
/// entering the Region. It is an element of the Region. The entry BasicBlock
/// dominates all BasicBlocks in the Region.
///
/// The \e Exit of a Region is the first BasicBlock that is passed after
/// leaving the Region. It is not an element of the Region. The exit BasicBlock,
/// postdominates all BasicBlocks in the Region.
///
/// A <em> canonical Region </em> cannot be constructed by combining smaller
/// Regions.
///
/// Region A is the \e parent of Region B, if B is completely contained in A.
///
/// Two canonical Regions either do not intersect at all or one is
/// the parent of the other.
///
/// The <em> Program Structure Tree</em> is a graph (V, E) where V is the set of
/// Regions in the control flow graph and E is the \e parent relation of these
/// Regions.
///
/// Example:
///
/// \verbatim
/// A simple control flow graph, that contains two regions.
///
/// 1
/// / |
/// 2 |
/// / \ 3
/// 4 5 |
/// | | |
/// 6 7 8
/// \ | /
/// \ |/ Region A: 1 -> 9 {1,2,3,4,5,6,7,8}
/// 9 Region B: 2 -> 9 {2,4,5,6,7}
/// \endverbatim
///
/// You can obtain more examples by either calling
///
/// <tt> "opt -regions -analyze anyprogram.ll" </tt>
/// or
/// <tt> "opt -view-regions-only anyprogram.ll" </tt>
///
/// on any LLVM file you are interested in.
///
/// The first call returns a textual representation of the program structure
/// tree, the second one creates a graphical representation using graphviz.
template <class Tr>
class RegionBase : public RegionNodeBase<Tr> {
typedef typename Tr::FuncT FuncT;
typedef typename Tr::BlockT BlockT;
typedef typename Tr::RegionInfoT RegionInfoT;
typedef typename Tr::RegionT RegionT;
typedef typename Tr::RegionNodeT RegionNodeT;
typedef typename Tr::DomTreeT DomTreeT;
typedef typename Tr::LoopT LoopT;
typedef typename Tr::LoopInfoT LoopInfoT;
typedef typename Tr::InstT InstT;
typedef GraphTraits<BlockT *> BlockTraits;
typedef GraphTraits<Inverse<BlockT *>> InvBlockTraits;
typedef typename BlockTraits::ChildIteratorType SuccIterTy;
typedef typename InvBlockTraits::ChildIteratorType PredIterTy;
friend class RegionInfoBase<Tr>;
RegionBase(const RegionBase &) = delete;
const RegionBase &operator=(const RegionBase &) = delete;
// Information necessary to manage this Region.
RegionInfoT *RI;
DomTreeT *DT;
// The exit BasicBlock of this region.
// (The entry BasicBlock is part of RegionNode)
BlockT *exit;
typedef std::vector<std::unique_ptr<RegionT>> RegionSet;
// The subregions of this region.
RegionSet children;
typedef std::map<BlockT *, std::unique_ptr<RegionNodeT>> BBNodeMapT;
// Save the BasicBlock RegionNodes that are element of this Region.
mutable BBNodeMapT BBNodeMap;
/// Check if a BB is in this Region. This check also works
/// if the region is incorrectly built. (EXPENSIVE!)
void verifyBBInRegion(BlockT *BB) const;
/// Walk over all the BBs of the region starting from BB and
/// verify that all reachable basic blocks are elements of the region.
/// (EXPENSIVE!)
void verifyWalk(BlockT *BB, std::set<BlockT *> *visitedBB) const;
/// Verify if the region and its children are valid regions (EXPENSIVE!)
void verifyRegionNest() const;
public:
/// @brief Create a new region.
///
/// @param Entry The entry basic block of the region.
/// @param Exit The exit basic block of the region.
/// @param RI The region info object that is managing this region.
/// @param DT The dominator tree of the current function.
/// @param Parent The surrounding region or NULL if this is a top level
/// region.
RegionBase(BlockT *Entry, BlockT *Exit, RegionInfoT *RI, DomTreeT *DT,
RegionT *Parent = nullptr);
/// Delete the Region and all its subregions.
~RegionBase();
/// @brief Get the entry BasicBlock of the Region.
/// @return The entry BasicBlock of the region.
BlockT *getEntry() const {
return RegionNodeBase<Tr>::getEntry();
}
/// @brief Replace the entry basic block of the region with the new basic
/// block.
///
/// @param BB The new entry basic block of the region.
void replaceEntry(BlockT *BB);
/// @brief Replace the exit basic block of the region with the new basic
/// block.
///
/// @param BB The new exit basic block of the region.
void replaceExit(BlockT *BB);
/// @brief Recursively replace the entry basic block of the region.
///
/// This function replaces the entry basic block with a new basic block. It
/// also updates all child regions that have the same entry basic block as
/// this region.
///
/// @param NewEntry The new entry basic block.
void replaceEntryRecursive(BlockT *NewEntry);
/// @brief Recursively replace the exit basic block of the region.
///
/// This function replaces the exit basic block with a new basic block. It
/// also updates all child regions that have the same exit basic block as
/// this region.
///
/// @param NewExit The new exit basic block.
void replaceExitRecursive(BlockT *NewExit);
/// @brief Get the exit BasicBlock of the Region.
/// @return The exit BasicBlock of the Region, NULL if this is the TopLevel
/// Region.
BlockT *getExit() const { return exit; }
/// @brief Get the parent of the Region.
/// @return The parent of the Region or NULL if this is a top level
/// Region.
RegionT *getParent() const {
return RegionNodeBase<Tr>::getParent();
}
/// @brief Get the RegionNode representing the current Region.
/// @return The RegionNode representing the current Region.
RegionNodeT *getNode() const {
return const_cast<RegionNodeT *>(
reinterpret_cast<const RegionNodeT *>(this));
}
/// @brief Get the nesting level of this Region.
///
/// An toplevel Region has depth 0.
///
/// @return The depth of the region.
unsigned getDepth() const;
/// @brief Check if a Region is the TopLevel region.
///
/// The toplevel region represents the whole function.
bool isTopLevelRegion() const { return exit == nullptr; }
/// @brief Return a new (non-canonical) region, that is obtained by joining
/// this region with its predecessors.
///
/// @return A region also starting at getEntry(), but reaching to the next
/// basic block that forms with getEntry() a (non-canonical) region.
/// NULL if such a basic block does not exist.
RegionT *getExpandedRegion() const;
/// @brief Return the first block of this region's single entry edge,
/// if existing.
///
/// @return The BasicBlock starting this region's single entry edge,
/// else NULL.
BlockT *getEnteringBlock() const;
/// @brief Return the first block of this region's single exit edge,
/// if existing.
///
/// @return The BasicBlock starting this region's single exit edge,
/// else NULL.
BlockT *getExitingBlock() const;
/// @brief Is this a simple region?
///
/// A region is simple if it has exactly one exit and one entry edge.
///
/// @return True if the Region is simple.
bool isSimple() const;
/// @brief Returns the name of the Region.
/// @return The Name of the Region.
std::string getNameStr() const;
/// @brief Return the RegionInfo object, that belongs to this Region.
RegionInfoT *getRegionInfo() const { return RI; }
/// PrintStyle - Print region in difference ways.
enum PrintStyle { PrintNone, PrintBB, PrintRN };
/// @brief Print the region.
///
/// @param OS The output stream the Region is printed to.
/// @param printTree Print also the tree of subregions.
/// @param level The indentation level used for printing.
void print(raw_ostream &OS, bool printTree = true, unsigned level = 0,
PrintStyle Style = PrintNone) const;
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
/// @brief Print the region to stderr.
void dump() const;
#endif
/// @brief Check if the region contains a BasicBlock.
///
/// @param BB The BasicBlock that might be contained in this Region.
/// @return True if the block is contained in the region otherwise false.
bool contains(const BlockT *BB) const;
/// @brief Check if the region contains another region.
///
/// @param SubRegion The region that might be contained in this Region.
/// @return True if SubRegion is contained in the region otherwise false.
bool contains(const RegionT *SubRegion) const {
// Toplevel Region.
if (!getExit())
return true;
return contains(SubRegion->getEntry()) &&
(contains(SubRegion->getExit()) ||
SubRegion->getExit() == getExit());
}
/// @brief Check if the region contains an Instruction.
///
/// @param Inst The Instruction that might be contained in this region.
/// @return True if the Instruction is contained in the region otherwise
/// false.
bool contains(const InstT *Inst) const { return contains(Inst->getParent()); }
/// @brief Check if the region contains a loop.
///
/// @param L The loop that might be contained in this region.
/// @return True if the loop is contained in the region otherwise false.
/// In case a NULL pointer is passed to this function the result
/// is false, except for the region that describes the whole function.
/// In that case true is returned.
bool contains(const LoopT *L) const;
/// @brief Get the outermost loop in the region that contains a loop.
///
/// Find for a Loop L the outermost loop OuterL that is a parent loop of L
/// and is itself contained in the region.
///
/// @param L The loop the lookup is started.
/// @return The outermost loop in the region, NULL if such a loop does not
/// exist or if the region describes the whole function.
LoopT *outermostLoopInRegion(LoopT *L) const;
/// @brief Get the outermost loop in the region that contains a basic block.
///
/// Find for a basic block BB the outermost loop L that contains BB and is
/// itself contained in the region.
///
/// @param LI A pointer to a LoopInfo analysis.
/// @param BB The basic block surrounded by the loop.
/// @return The outermost loop in the region, NULL if such a loop does not
/// exist or if the region describes the whole function.
LoopT *outermostLoopInRegion(LoopInfoT *LI, BlockT *BB) const;
/// @brief Get the subregion that starts at a BasicBlock
///
/// @param BB The BasicBlock the subregion should start.
/// @return The Subregion if available, otherwise NULL.
RegionT *getSubRegionNode(BlockT *BB) const;
/// @brief Get the RegionNode for a BasicBlock
///
/// @param BB The BasicBlock at which the RegionNode should start.
/// @return If available, the RegionNode that represents the subregion
/// starting at BB. If no subregion starts at BB, the RegionNode
/// representing BB.
RegionNodeT *getNode(BlockT *BB) const;
/// @brief Get the BasicBlock RegionNode for a BasicBlock
///
/// @param BB The BasicBlock for which the RegionNode is requested.
/// @return The RegionNode representing the BB.
RegionNodeT *getBBNode(BlockT *BB) const;
/// @brief Add a new subregion to this Region.
///
/// @param SubRegion The new subregion that will be added.
/// @param moveChildren Move the children of this region, that are also
/// contained in SubRegion into SubRegion.
void addSubRegion(RegionT *SubRegion, bool moveChildren = false);
/// @brief Remove a subregion from this Region.
///
/// The subregion is not deleted, as it will probably be inserted into another
/// region.
/// @param SubRegion The SubRegion that will be removed.
RegionT *removeSubRegion(RegionT *SubRegion);
/// @brief Move all direct child nodes of this Region to another Region.
///
/// @param To The Region the child nodes will be transferred to.
void transferChildrenTo(RegionT *To);
/// @brief Verify if the region is a correct region.
///
/// Check if this is a correctly build Region. This is an expensive check, as
/// the complete CFG of the Region will be walked.
void verifyRegion() const;
/// @brief Clear the cache for BB RegionNodes.
///
/// After calling this function the BasicBlock RegionNodes will be stored at
/// different memory locations. RegionNodes obtained before this function is
/// called are therefore not comparable to RegionNodes abtained afterwords.
void clearNodeCache();
/// @name Subregion Iterators
///
/// These iterators iterator over all subregions of this Region.
//@{
typedef typename RegionSet::iterator iterator;
typedef typename RegionSet::const_iterator const_iterator;
iterator begin() { return children.begin(); }
iterator end() { return children.end(); }
const_iterator begin() const { return children.begin(); }
const_iterator end() const { return children.end(); }
//@}
/// @name BasicBlock Iterators
///
/// These iterators iterate over all BasicBlocks that are contained in this
/// Region. The iterator also iterates over BasicBlocks that are elements of
/// a subregion of this Region. It is therefore called a flat iterator.
//@{
template <bool IsConst>
class block_iterator_wrapper
: public df_iterator<
typename std::conditional<IsConst, const BlockT, BlockT>::type *> {
typedef df_iterator<
typename std::conditional<IsConst, const BlockT, BlockT>::type *> super;
public:
typedef block_iterator_wrapper<IsConst> Self;
typedef typename super::value_type value_type;
// Construct the begin iterator.
block_iterator_wrapper(value_type Entry, value_type Exit)
: super(df_begin(Entry)) {
// Mark the exit of the region as visited, so that the children of the
// exit and the exit itself, i.e. the block outside the region will never
// be visited.
super::Visited.insert(Exit);
}
// Construct the end iterator.
block_iterator_wrapper() : super(df_end<value_type>((BlockT *)nullptr)) {}
/*implicit*/ block_iterator_wrapper(super I) : super(I) {}
// FIXME: Even a const_iterator returns a non-const BasicBlock pointer.
// This was introduced for backwards compatibility, but should
// be removed as soon as all users are fixed.
BlockT *operator*() const {
return const_cast<BlockT *>(super::operator*());
}
};
typedef block_iterator_wrapper<false> block_iterator;
typedef block_iterator_wrapper<true> const_block_iterator;
block_iterator block_begin() { return block_iterator(getEntry(), getExit()); }
block_iterator block_end() { return block_iterator(); }
const_block_iterator block_begin() const {
return const_block_iterator(getEntry(), getExit());
}
const_block_iterator block_end() const { return const_block_iterator(); }
typedef iterator_range<block_iterator> block_range;
typedef iterator_range<const_block_iterator> const_block_range;
/// @brief Returns a range view of the basic blocks in the region.
inline block_range blocks() {
return block_range(block_begin(), block_end());
}
/// @brief Returns a range view of the basic blocks in the region.
///
/// This is the 'const' version of the range view.
inline const_block_range blocks() const {
return const_block_range(block_begin(), block_end());
}
//@}
/// @name Element Iterators
///
/// These iterators iterate over all BasicBlock and subregion RegionNodes that
/// are direct children of this Region. It does not iterate over any
/// RegionNodes that are also element of a subregion of this Region.
//@{
typedef df_iterator<RegionNodeT *, df_iterator_default_set<RegionNodeT *>,
false, GraphTraits<RegionNodeT *>>
element_iterator;
typedef df_iterator<const RegionNodeT *,
df_iterator_default_set<const RegionNodeT *>, false,
GraphTraits<const RegionNodeT *>>
const_element_iterator;
element_iterator element_begin();
element_iterator element_end();
iterator_range<element_iterator> elements() {
return make_range(element_begin(), element_end());
}
const_element_iterator element_begin() const;
const_element_iterator element_end() const;
iterator_range<const_element_iterator> elements() const {
return make_range(element_begin(), element_end());
}
//@}
};
/// Print a RegionNode.
template <class Tr>
inline raw_ostream &operator<<(raw_ostream &OS, const RegionNodeBase<Tr> &Node);
//===----------------------------------------------------------------------===//
/// @brief Analysis that detects all canonical Regions.
///
/// The RegionInfo pass detects all canonical regions in a function. The Regions
/// are connected using the parent relation. This builds a Program Structure
/// Tree.
template <class Tr>
class RegionInfoBase {
typedef typename Tr::BlockT BlockT;
typedef typename Tr::FuncT FuncT;
typedef typename Tr::RegionT RegionT;
typedef typename Tr::RegionInfoT RegionInfoT;
typedef typename Tr::DomTreeT DomTreeT;
typedef typename Tr::DomTreeNodeT DomTreeNodeT;
typedef typename Tr::PostDomTreeT PostDomTreeT;
typedef typename Tr::DomFrontierT DomFrontierT;
typedef GraphTraits<BlockT *> BlockTraits;
typedef GraphTraits<Inverse<BlockT *>> InvBlockTraits;
typedef typename BlockTraits::ChildIteratorType SuccIterTy;
typedef typename InvBlockTraits::ChildIteratorType PredIterTy;
friend class RegionInfo;
friend class MachineRegionInfo;
typedef DenseMap<BlockT *, BlockT *> BBtoBBMap;
typedef DenseMap<BlockT *, RegionT *> BBtoRegionMap;
RegionInfoBase();
virtual ~RegionInfoBase();
RegionInfoBase(const RegionInfoBase &) = delete;
const RegionInfoBase &operator=(const RegionInfoBase &) = delete;
RegionInfoBase(RegionInfoBase &&Arg)
: DT(std::move(Arg.DT)), PDT(std::move(Arg.PDT)), DF(std::move(Arg.DF)),
TopLevelRegion(std::move(Arg.TopLevelRegion)),
BBtoRegion(std::move(Arg.BBtoRegion)) {
Arg.wipe();
}
RegionInfoBase &operator=(RegionInfoBase &&RHS) {
DT = std::move(RHS.DT);
PDT = std::move(RHS.PDT);
DF = std::move(RHS.DF);
TopLevelRegion = std::move(RHS.TopLevelRegion);
BBtoRegion = std::move(RHS.BBtoRegion);
RHS.wipe();
return *this;
}
DomTreeT *DT;
PostDomTreeT *PDT;
DomFrontierT *DF;
/// The top level region.
RegionT *TopLevelRegion;
private:
/// Map every BB to the smallest region, that contains BB.
BBtoRegionMap BBtoRegion;
/// \brief Wipe this region tree's state without releasing any resources.
///
/// This is essentially a post-move helper only. It leaves the object in an
/// assignable and destroyable state, but otherwise invalid.
void wipe() {
DT = nullptr;
PDT = nullptr;
DF = nullptr;
TopLevelRegion = nullptr;
BBtoRegion.clear();
}
// Check whether the entries of BBtoRegion for the BBs of region
// SR are correct. Triggers an assertion if not. Calls itself recursively for
// subregions.
void verifyBBMap(const RegionT *SR) const;
// Returns true if BB is in the dominance frontier of
// entry, because it was inherited from exit. In the other case there is an
// edge going from entry to BB without passing exit.
bool isCommonDomFrontier(BlockT *BB, BlockT *entry, BlockT *exit) const;
// Check if entry and exit surround a valid region, based on
// dominance tree and dominance frontier.
bool isRegion(BlockT *entry, BlockT *exit) const;
// Saves a shortcut pointing from entry to exit.
// This function may extend this shortcut if possible.
void insertShortCut(BlockT *entry, BlockT *exit, BBtoBBMap *ShortCut) const;
// Returns the next BB that postdominates N, while skipping
// all post dominators that cannot finish a canonical region.
DomTreeNodeT *getNextPostDom(DomTreeNodeT *N, BBtoBBMap *ShortCut) const;
// A region is trivial, if it contains only one BB.
bool isTrivialRegion(BlockT *entry, BlockT *exit) const;
// Creates a single entry single exit region.
RegionT *createRegion(BlockT *entry, BlockT *exit);
// Detect all regions starting with bb 'entry'.
void findRegionsWithEntry(BlockT *entry, BBtoBBMap *ShortCut);
// Detects regions in F.
void scanForRegions(FuncT &F, BBtoBBMap *ShortCut);
// Get the top most parent with the same entry block.
RegionT *getTopMostParent(RegionT *region);
// Build the region hierarchy after all region detected.
void buildRegionsTree(DomTreeNodeT *N, RegionT *region);
// Update statistic about created regions.
virtual void updateStatistics(RegionT *R) = 0;
// Detect all regions in function and build the region tree.
void calculate(FuncT &F);
public:
static bool VerifyRegionInfo;
static typename RegionT::PrintStyle printStyle;
void print(raw_ostream &OS) const;
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void dump() const;
#endif
void releaseMemory();
/// @brief Get the smallest region that contains a BasicBlock.
///
/// @param BB The basic block.
/// @return The smallest region, that contains BB or NULL, if there is no
/// region containing BB.
RegionT *getRegionFor(BlockT *BB) const;
/// @brief Set the smallest region that surrounds a basic block.
///
/// @param BB The basic block surrounded by a region.
/// @param R The smallest region that surrounds BB.
void setRegionFor(BlockT *BB, RegionT *R);
/// @brief A shortcut for getRegionFor().
///
/// @param BB The basic block.
/// @return The smallest region, that contains BB or NULL, if there is no
/// region containing BB.
RegionT *operator[](BlockT *BB) const;
/// @brief Return the exit of the maximal refined region, that starts at a
/// BasicBlock.
///
/// @param BB The BasicBlock the refined region starts.
BlockT *getMaxRegionExit(BlockT *BB) const;
/// @brief Find the smallest region that contains two regions.
///
/// @param A The first region.
/// @param B The second region.
/// @return The smallest region containing A and B.
RegionT *getCommonRegion(RegionT *A, RegionT *B) const;
/// @brief Find the smallest region that contains two basic blocks.
///
/// @param A The first basic block.
/// @param B The second basic block.
/// @return The smallest region that contains A and B.
RegionT *getCommonRegion(BlockT *A, BlockT *B) const {
return getCommonRegion(getRegionFor(A), getRegionFor(B));
}
/// @brief Find the smallest region that contains a set of regions.
///
/// @param Regions A vector of regions.
/// @return The smallest region that contains all regions in Regions.
RegionT *getCommonRegion(SmallVectorImpl<RegionT *> &Regions) const;
/// @brief Find the smallest region that contains a set of basic blocks.
///
/// @param BBs A vector of basic blocks.
/// @return The smallest region that contains all basic blocks in BBS.
RegionT *getCommonRegion(SmallVectorImpl<BlockT *> &BBs) const;
RegionT *getTopLevelRegion() const { return TopLevelRegion; }
/// @brief Clear the Node Cache for all Regions.
///
/// @see Region::clearNodeCache()
void clearNodeCache() {
if (TopLevelRegion)
TopLevelRegion->clearNodeCache();
}
void verifyAnalysis() const;
};
class Region;
class RegionNode : public RegionNodeBase<RegionTraits<Function>> {
public:
inline RegionNode(Region *Parent, BasicBlock *Entry, bool isSubRegion = false)
: RegionNodeBase<RegionTraits<Function>>(Parent, Entry, isSubRegion) {}
bool operator==(const Region &RN) const {
return this == reinterpret_cast<const RegionNode *>(&RN);
}
};
class Region : public RegionBase<RegionTraits<Function>> {
public:
Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo *RI, DominatorTree *DT,
Region *Parent = nullptr);
~Region();
bool operator==(const RegionNode &RN) const {
return &RN == reinterpret_cast<const RegionNode *>(this);
}
};
class RegionInfo : public RegionInfoBase<RegionTraits<Function>> {
public:
typedef RegionInfoBase<RegionTraits<Function>> Base;
explicit RegionInfo();
~RegionInfo() override;
RegionInfo(RegionInfo &&Arg)
: Base(std::move(static_cast<Base &>(Arg))) {}
RegionInfo &operator=(RegionInfo &&RHS) {
Base::operator=(std::move(static_cast<Base &>(RHS)));
return *this;
}
/// Handle invalidation explicitly.
bool invalidate(Function &F, const PreservedAnalyses &PA,
FunctionAnalysisManager::Invalidator &);
// updateStatistics - Update statistic about created regions.
void updateStatistics(Region *R) final;
void recalculate(Function &F, DominatorTree *DT, PostDominatorTree *PDT,
DominanceFrontier *DF);
#ifndef NDEBUG
/// @brief Opens a viewer to show the GraphViz visualization of the regions.
///
/// Useful during debugging as an alternative to dump().
void view();
/// @brief Opens a viewer to show the GraphViz visualization of this region
/// without instructions in the BasicBlocks.
///
/// Useful during debugging as an alternative to dump().
void viewOnly();
#endif
};
class RegionInfoPass : public FunctionPass {
RegionInfo RI;
public:
static char ID;
explicit RegionInfoPass();
~RegionInfoPass() override;
RegionInfo &getRegionInfo() { return RI; }
const RegionInfo &getRegionInfo() const { return RI; }
/// @name FunctionPass interface
//@{
bool runOnFunction(Function &F) override;
void releaseMemory() override;
void verifyAnalysis() const override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
void print(raw_ostream &OS, const Module *) const override;
void dump() const;
//@}
};
/// \brief Analysis pass that exposes the \c RegionInfo for a function.
class RegionInfoAnalysis : public AnalysisInfoMixin<RegionInfoAnalysis> {
friend AnalysisInfoMixin<RegionInfoAnalysis>;
static AnalysisKey Key;
public:
typedef RegionInfo Result;
RegionInfo run(Function &F, FunctionAnalysisManager &AM);
};
/// \brief Printer pass for the \c RegionInfo.
class RegionInfoPrinterPass : public PassInfoMixin<RegionInfoPrinterPass> {
raw_ostream &OS;
public:
explicit RegionInfoPrinterPass(raw_ostream &OS);
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
};
/// \brief Verifier pass for the \c RegionInfo.
struct RegionInfoVerifierPass : PassInfoMixin<RegionInfoVerifierPass> {
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
};
template <>
template <>
inline BasicBlock *
RegionNodeBase<RegionTraits<Function>>::getNodeAs<BasicBlock>() const {
assert(!isSubRegion() && "This is not a BasicBlock RegionNode!");
return getEntry();
}
template <>
template <>
inline Region *
RegionNodeBase<RegionTraits<Function>>::getNodeAs<Region>() const {
assert(isSubRegion() && "This is not a subregion RegionNode!");
auto Unconst = const_cast<RegionNodeBase<RegionTraits<Function>> *>(this);
return reinterpret_cast<Region *>(Unconst);
}
template <class Tr>
inline raw_ostream &operator<<(raw_ostream &OS,
const RegionNodeBase<Tr> &Node) {
typedef typename Tr::BlockT BlockT;
typedef typename Tr::RegionT RegionT;
if (Node.isSubRegion())
return OS << Node.template getNodeAs<RegionT>()->getNameStr();
else
return OS << Node.template getNodeAs<BlockT>()->getName();
}
extern template class RegionBase<RegionTraits<Function>>;
extern template class RegionNodeBase<RegionTraits<Function>>;
extern template class RegionInfoBase<RegionTraits<Function>>;
} // End llvm namespace
#endif
| 10,661 |
2,023 |
<filename>recipes/Python/576616_FactorialLambda/recipe-576616.py
#On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of <NAME>.
#Author : <NAME>
#Date : 13/01/09
#version :2.4
import random
class NegativeNumberError(ArithmeticError):
""" attempted imporper operation on negative number"""
pass
class ZeroNumberException(ArithmeticError):
""" attempted operation on zero with an agreed solution"""
pass
def errors(number):
""" Raises NegativeNumberError if number less than 0, and
raises ZeroNumberException if number is equal to 0."""
if number < 0:
raise NegativeNumberError,\
"\n<The number must be greater or equal to 0 \n"
elif number == 0:
raise ZeroNumberException,\
"\n<It is agreed per convention that 0!= 1 \n"
elif number >0:
pass
return number
while 1:
#get users answer to use Factorial program or exit the while loop
Answer = raw_input("\n<Would you like to use Factorial program, yes or no?:\t")
if Answer == "yes":
print '\n\t\t\t','','\5'*49
print '\t\t\t\t Welcome to Factorial n! Program'
print '\t\t\t','','\5'*49,'\n'
try:
#get users entered numbers and compute factorial
userValue = float(raw_input('<Please enter a number :\t'))
errors(userValue)
Y=random.randrange(int(userValue)+1)
mult = lambda d:reduce(lambda x,y:x*y,range(1,int(Y)+1))
print '\n<A random list of factorial between 0 and %s will be displayed' % int(userValue)
print '\n\t\t',str(0)+'!=',int(1),'\n'
for Y in range(1,int(Y)+1):
print '\n\t\t',str(Y)+'!=',mult(int(Y)),'\n'
#Factorial raise ValueError if input is not numerical
except ValueError:
print "\n<The entered value is not a number"
#Factorial raises Negative number exception
except NegativeNumberError,exception:
print exception
#Factorial raises zero number exception
except ZeroNumberException,exception:
print exception
elif Answer == "no":
break
#############################################################################
#c:\hp\bin\Python>python "C:\Documents\Programs\classes\Factorial7
#
#<Would you like to use Factorial program, yes or no?: yes
#
# ?????????????????????????????????????????????????
# Welcome to Factorial n! Program
# ?????????????????????????????????????????????????
#
#<Please enter a number : 7
#
#<A random list of factorial between 0 and 7 will be displayed
#
# 0!= 1
#
#
# 1!= 1
#
#
# 2!= 2
#
#
#<Would you like to use Factorial program, yes or no?: yes
#
# ?????????????????????????????????????????????????
# Welcome to Factorial n! Program
# ?????????????????????????????????????????????????
#
#<Please enter a number : -7
#
#"\n<The number must be greater or equal to 0 \n"
#
#
#<Would you like to use Factorial program, yes or no?: yes
#
# ?????????????????????????????????????????????????
# Welcome to Factorial n! Program
# ?????????????????????????????????????????????????
#
#<Please enter a number : 0
#
#<It is agreed per convention that 0!= 1
#
#
#<Would you like to use Factorial program, yes or no?: yes
#
# ?????????????????????????????????????????????????
# Welcome to Factorial n! Program
# ?????????????????????????????????????????????????
#
#<Please enter a number : test
#
#<The entered value is not a number
#
#<Would you like to use Factorial program, yes or no?: yes
#
# ?????????????????????????????????????????????????
# Welcome to Factorial n! Program
# ?????????????????????????????????????????????????
#
#<Please enter a number : 7
#
#<A random list of factorial between 0 and 7 will be displayed
#
# 0!= 1
#
#
# 1!= 1
#
#
# 2!= 2
#
#
# 3!= 6
#
#
# 4!= 24
#
#
# 5!= 120
#
#
#<Would you like to use Factorial program, yes or no?: no
#
#c:\hp\bin\Python>
########################### Factorial ref FT (2 D A Missr)
#########################################################################################
#Version : Python 3.2
#import random
#from functools import reduce
#class NegativeNumberError(ArithmeticError):
# """ attempted imporper operation on negative number"""
#
# pass
#class ZeroNumberException(ArithmeticError):
# """ attempted operation on zero with an agreed solution"""
#
# pass
#
#def errors(number):
# """ Raises NegativeNumberError if number less than 0, and
# raises ZeroNumberException if number is equal to 0."""
#
# if number < 0:
# raise NegativeNumberError("\n<The number must be greater or equal to 0 \n")
# elif number == 0:
# raise ZeroNumberException("\n<It is agreed per convention that 0!= 1 \n")
# elif number >0:
# pass
#
# return number
#while 1:
# #get users answer to use Factorial program or exit the while loop
# Answer = input("\n<Would you like to use Factorial program, yes or no?:\t")
# if Answer == "yes":
#
# print('\n\t\t\t','','\5'*49)
# print('\t\t\t\t Welcome to Factorial n! Program')
# print('\t\t\t','','\5'*49,'\n')
#
# try:
# #get users entered numbers and coompute factorial
# userValue = float(input('<Please enter a number :\t'))
#
# errors(userValue)
# Y=random.randrange(int(userValue)+1)
# mult = lambda d:reduce(lambda x,y:x*y,list(range(1,int(Y)+1)))
#
# print('\n<A random list of factorial between 0 and %s will be displayed' % #int(userValue))
# print('\n\t\t',str(0)+'!=',int(1),'\n')
# for Y in range(1,int(Y)+1):
# print('\n\t\t',str(Y)+'!=',mult(int(Y)),'\n')
#
# #Factorial raise ValueError if input is not numerical
# except ValueError:
# print("\n<The entered value is not a number")
#
# #Factorial raises Negative number exception
# except NegativeNumberError as exception:
# print(exception)
#
# #Factorial raises zero number exception
# except ZeroNumberException as exception:
# print(exception)
#
# elif Answer == "no":
# break
| 3,090 |
521 |
/* Copyright (c) 2001, Stanford University
* All rights reserved.
*
* See the file LICENSE.txt for information on redistributing this software.
*/
#ifndef CR_STATE_FOG_H
#define CR_STATE_FOG_H
#include "state/cr_statetypes.h"
#include <iprt/cdefs.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
CRbitvalue dirty[CR_MAX_BITARRAY];
CRbitvalue color[CR_MAX_BITARRAY];
CRbitvalue index[CR_MAX_BITARRAY];
CRbitvalue density[CR_MAX_BITARRAY];
CRbitvalue start[CR_MAX_BITARRAY];
CRbitvalue end[CR_MAX_BITARRAY];
CRbitvalue mode[CR_MAX_BITARRAY];
CRbitvalue enable[CR_MAX_BITARRAY];
#ifdef CR_NV_fog_distance
CRbitvalue fogDistanceMode[CR_MAX_BITARRAY];
#endif
#ifdef CR_EXT_fog_coord
CRbitvalue fogCoordinateSource[CR_MAX_BITARRAY];
#endif
} CRFogBits;
typedef struct {
GLcolorf color;
GLint index;
GLfloat density;
GLfloat start;
GLfloat end;
GLint mode;
GLboolean enable;
#ifdef CR_NV_fog_distance
GLenum fogDistanceMode;
#endif
#ifdef CR_EXT_fog_coord
GLenum fogCoordinateSource;
#endif
} CRFogState;
DECLEXPORT(void) crStateFogInit(CRContext *ctx);
DECLEXPORT(void) crStateFogDiff(CRFogBits *bb, CRbitvalue *bitID,
CRContext *fromCtx, CRContext *toCtx);
DECLEXPORT(void) crStateFogSwitch(CRFogBits *bb, CRbitvalue *bitID,
CRContext *fromCtx, CRContext *toCtx);
#ifdef __cplusplus
}
#endif
#endif /* CR_STATE_FOG_H */
| 635 |
2,151 |
<filename>core/java/android/net/WifiLinkQualityInfo.java
/*
* Copyright (C) 2013 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 android.net;
import android.os.Parcel;
/**
* Class that represents useful attributes of wifi network links
* such as the upload/download throughput or error rate etc.
* @hide
*/
public class WifiLinkQualityInfo extends LinkQualityInfo {
/* Indicates Wifi network type such as b/g etc*/
private int mType = UNKNOWN_INT;
private String mBssid;
/* Rssi found by scans */
private int mRssi = UNKNOWN_INT;
/* packet statistics */
private long mTxGood = UNKNOWN_LONG;
private long mTxBad = UNKNOWN_LONG;
/**
* Implement the Parcelable interface.
* @hide
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags, OBJECT_TYPE_WIFI_LINK_QUALITY_INFO);
dest.writeInt(mType);
dest.writeInt(mRssi);
dest.writeLong(mTxGood);
dest.writeLong(mTxBad);
dest.writeString(mBssid);
}
/* Un-parceling helper */
/**
* @hide
*/
public static WifiLinkQualityInfo createFromParcelBody(Parcel in) {
WifiLinkQualityInfo li = new WifiLinkQualityInfo();
li.initializeFromParcel(in);
li.mType = in.readInt();
li.mRssi = in.readInt();
li.mTxGood = in.readLong();
li.mTxBad = in.readLong();
li.mBssid = in.readString();
return li;
}
/**
* returns Wifi network type
* @return network type or {@link android.net.LinkQualityInfo#UNKNOWN_INT}
*/
public int getType() {
return mType;
}
/**
* @hide
*/
public void setType(int type) {
mType = type;
}
/**
* returns BSSID of the access point
* @return the BSSID, in the form of a six-byte MAC address: {@code XX:XX:XX:XX:XX:XX} or null
*/
public String getBssid() {
return mBssid;
}
/**
* @hide
*/
public void setBssid(String bssid) {
mBssid = bssid;
}
/**
* returns RSSI of the network in raw form
* @return un-normalized RSSI or {@link android.net.LinkQualityInfo#UNKNOWN_INT}
*/
public int getRssi() {
return mRssi;
}
/**
* @hide
*/
public void setRssi(int rssi) {
mRssi = rssi;
}
/**
* returns number of packets transmitted without error
* @return number of packets or {@link android.net.LinkQualityInfo#UNKNOWN_LONG}
*/
public long getTxGood() {
return mTxGood;
}
/**
* @hide
*/
public void setTxGood(long txGood) {
mTxGood = txGood;
}
/**
* returns number of transmitted packets that encountered errors
* @return number of packets or {@link android.net.LinkQualityInfo#UNKNOWN_LONG}
*/
public long getTxBad() {
return mTxBad;
}
/**
* @hide
*/
public void setTxBad(long txBad) {
mTxBad = txBad;
}
}
| 1,455 |
1,331 |
package javapayload.stage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
public class DummyStage implements Stage {
public void start(DataInputStream in, OutputStream rawOut, String[] parameters) throws Exception {
byte[] buffer = new byte[in.readInt()];
in.readFully(buffer);
DataOutputStream out = new DataOutputStream(rawOut);
out.write(buffer);
out.writeInt(parameters.length);
for (int i = 0; i < parameters.length; i++) {
out.writeUTF(parameters[i]);
}
in.close();
out.close();
}
}
| 251 |
2,180 |
<reponame>luckydzj/LogiKM
package com.xiaojukeji.kafka.manager.kcm.common.entry.ao;
import com.xiaojukeji.kafka.manager.common.entity.Result;
import java.util.List;
/**
* @author zengqiao
* @date 20/5/20
*/
public class CreationTaskData {
private String uuid;
private Long clusterId;
private List<String> hostList;
private List<String> pauseList;
private String taskType;
private String kafkaPackageName;
private String kafkaPackageMd5;
private String kafkaPackageUrl;
private String serverPropertiesName;
private String serverPropertiesMd5;
private String serverPropertiesUrl;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public Long getClusterId() {
return clusterId;
}
public void setClusterId(Long clusterId) {
this.clusterId = clusterId;
}
public List<String> getHostList() {
return hostList;
}
public void setHostList(List<String> hostList) {
this.hostList = hostList;
}
public List<String> getPauseList() {
return pauseList;
}
public void setPauseList(List<String> pauseList) {
this.pauseList = pauseList;
}
public String getTaskType() {
return taskType;
}
public void setTaskType(String taskType) {
this.taskType = taskType;
}
public String getKafkaPackageName() {
return kafkaPackageName;
}
public void setKafkaPackageName(String kafkaPackageName) {
this.kafkaPackageName = kafkaPackageName;
}
public String getKafkaPackageMd5() {
return kafkaPackageMd5;
}
public void setKafkaPackageMd5(String kafkaPackageMd5) {
this.kafkaPackageMd5 = kafkaPackageMd5;
}
public String getKafkaPackageUrl() {
return kafkaPackageUrl;
}
public void setKafkaPackageUrl(String kafkaPackageUrl) {
this.kafkaPackageUrl = kafkaPackageUrl;
}
public String getServerPropertiesName() {
return serverPropertiesName;
}
public void setServerPropertiesName(String serverPropertiesName) {
this.serverPropertiesName = serverPropertiesName;
}
public String getServerPropertiesMd5() {
return serverPropertiesMd5;
}
public void setServerPropertiesMd5(String serverPropertiesMd5) {
this.serverPropertiesMd5 = serverPropertiesMd5;
}
public String getServerPropertiesUrl() {
return serverPropertiesUrl;
}
public void setServerPropertiesUrl(String serverPropertiesUrl) {
this.serverPropertiesUrl = serverPropertiesUrl;
}
@Override
public String toString() {
return "CreationTaskData{" +
"uuid='" + uuid + '\'' +
", clusterId=" + clusterId +
", hostList=" + hostList +
", pauseList=" + pauseList +
", taskType='" + taskType + '\'' +
", kafkaPackageName='" + kafkaPackageName + '\'' +
", kafkaPackageMd5='" + kafkaPackageMd5 + '\'' +
", kafkaPackageUrl='" + kafkaPackageUrl + '\'' +
", serverPropertiesName='" + serverPropertiesName + '\'' +
", serverPropertiesMd5='" + serverPropertiesMd5 + '\'' +
", serverPropertiesUrl='" + serverPropertiesUrl + '\'' +
'}';
}
}
| 1,455 |
348 |
//
// FKFlickrPeopleGetGroups.h
// FlickrKit
//
// Generated by FKAPIBuilder.
// Copyright (c) 2013 DevedUp Ltd. All rights reserved. http://www.devedup.com
//
// DO NOT MODIFY THIS FILE - IT IS MACHINE GENERATED
#import "FKFlickrAPIMethod.h"
typedef NS_ENUM(NSInteger, FKFlickrPeopleGetGroupsError) {
FKFlickrPeopleGetGroupsError_UserNotFound = 1, /* The user id passed did not match a Flickr user. */
FKFlickrPeopleGetGroupsError_SSLIsRequired = 95, /* SSL is required to access the Flickr API. */
FKFlickrPeopleGetGroupsError_InvalidSignature = 96, /* The passed signature was invalid. */
FKFlickrPeopleGetGroupsError_MissingSignature = 97, /* The call required signing but no signature was sent. */
FKFlickrPeopleGetGroupsError_LoginFailedOrInvalidAuthToken = 98, /* The login details or auth token passed were invalid. */
FKFlickrPeopleGetGroupsError_UserNotLoggedInOrInsufficientPermissions = 99, /* The method requires user authentication but the user was not logged in, or the authenticated method call did not have the required permissions. */
FKFlickrPeopleGetGroupsError_InvalidAPIKey = 100, /* The API key passed was not valid or has expired. */
FKFlickrPeopleGetGroupsError_ServiceCurrentlyUnavailable = 105, /* The requested service is temporarily unavailable. */
FKFlickrPeopleGetGroupsError_WriteOperationFailed = 106, /* The requested operation failed due to a temporary issue. */
FKFlickrPeopleGetGroupsError_FormatXXXNotFound = 111, /* The requested response format was not found. */
FKFlickrPeopleGetGroupsError_MethodXXXNotFound = 112, /* The requested method was not found. */
FKFlickrPeopleGetGroupsError_InvalidSOAPEnvelope = 114, /* The SOAP envelope send in the request could not be parsed. */
FKFlickrPeopleGetGroupsError_InvalidXMLRPCMethodCall = 115, /* The XML-RPC request document could not be parsed. */
FKFlickrPeopleGetGroupsError_BadURLFound = 116, /* One or more arguments contained a URL that has been used for abuse on Flickr. */
};
/*
Returns the list of groups a user is a member of.
The admin attribute indicates whether the user is an administrator of the group. The eighteenplus attribute indicates if the group is visible to members over 18 only. The invite_only attribute indicates whether a user can join the group without administrator approval.
Response:
<groups>
<group nsid="17274427@N00" name="Cream of the Crop - Please read the rules" iconfarm="1" iconserver="1" admin="0" eighteenplus="0" invitation_only="0" members="11935" pool_count="12522" />
<group nsid="20083316@N00" name="Apple" iconfarm="1" iconserver="1" admin="0" eighteenplus="0" invitation_only="0" members="11776" pool_count="62438" />
<group nsid="34427469792@N01" name="FlickrCentral" iconfarm="1" iconserver="1" admin="0" eighteenplus="0" invitation_only="0" members="168055" pool_count="5280930" />
<group nsid="37718678610@N01" name="Typography and Lettering" iconfarm="1" iconserver="1" admin="0" eighteenplus="0" invitation_only="0" members="17318" pool_count="130169" />
</groups>
*/
@interface FKFlickrPeopleGetGroups : NSObject <FKFlickrAPIMethod>
/* The NSID of the user to fetch groups for. */
@property (nonatomic, copy) NSString *user_id; /* (Required) */
/* A comma-delimited list of extra information to fetch for each returned record. Currently supported fields are: <code>privacy</code>, <code>throttle</code>, <code>restrictions</code> */
@property (nonatomic, copy) NSString *extras;
@end
| 1,039 |
1,755 |
<reponame>LongerVisionUSA/VTK
/*=========================================================================
Program: Visualization Toolkit
Module: vtkWrapPythonEnum.c
Copyright (c) <NAME>, <NAME>, <NAME>
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkWrapPythonEnum.h"
#include "vtkWrap.h"
#include "vtkWrapText.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* -------------------------------------------------------------------- */
/* check whether an enum type will be wrapped */
int vtkWrapPython_IsEnumWrapped(HierarchyInfo* hinfo, const char* enumname)
{
int rval = 0;
HierarchyEntry* entry;
if (hinfo && enumname)
{
entry = vtkParseHierarchy_FindEntry(hinfo, enumname);
if (entry && entry->IsEnum && !vtkParseHierarchy_GetProperty(entry, "WRAPEXCLUDE"))
{
rval = 1;
}
}
return rval;
}
/* -------------------------------------------------------------------- */
/* find and mark all enum parameters by setting IsEnum=1 */
void vtkWrapPython_MarkAllEnums(NamespaceInfo* contents, HierarchyInfo* hinfo)
{
FunctionInfo* currentFunction;
int i, j, n, m, ii, nn;
ClassInfo* data;
ValueInfo* val;
nn = contents->NumberOfClasses;
for (ii = 0; ii < nn; ii++)
{
data = contents->Classes[ii];
n = data->NumberOfFunctions;
for (i = 0; i < n; i++)
{
currentFunction = data->Functions[i];
if (!currentFunction->IsExcluded && currentFunction->Access == VTK_ACCESS_PUBLIC)
{
/* we start with the return value */
val = currentFunction->ReturnValue;
m = vtkWrap_CountWrappedParameters(currentFunction);
/* the -1 is for the return value */
for (j = (val ? -1 : 0); j < m; j++)
{
if (j >= 0)
{
val = currentFunction->Parameters[j];
}
if (vtkWrap_IsEnumMember(data, val) || vtkWrapPython_IsEnumWrapped(hinfo, val->Class))
{
val->IsEnum = 1;
}
}
}
}
}
}
/* -------------------------------------------------------------------- */
/* generate a wrapped enum type (no anonymous enums, only named enums) */
void vtkWrapPython_AddEnumType(FILE* fp, const char* indent, const char* dictvar,
const char* objvar, const char* scope, EnumInfo* cls)
{
ValueInfo* val;
int j;
if (cls->IsDeprecated)
{
fprintf(fp, " /* Deprecated %s */\n", (cls->DeprecatedReason ? cls->DeprecatedReason : ""));
}
fprintf(fp, "%sPyType_Ready(&Py%s%s%s_Type);\n", indent, (scope ? scope : ""), (scope ? "_" : ""),
cls->Name);
if (cls->NumberOfConstants)
{
fprintf(fp,
"%s// members of %s%s%s\n"
"%s{\n"
"%s PyObject *enumval;\n"
"%s PyObject *enumdict = PyDict_New();\n"
"%s Py%s%s%s_Type.tp_dict = enumdict;\n"
"\n",
indent, (scope ? scope : ""), (scope ? "::" : ""), cls->Name, indent, indent, indent, indent,
(scope ? scope : ""), (scope ? "_" : ""), cls->Name);
fprintf(fp,
"%s typedef %s%s%s cxx_enum_type;\n"
"%s static const struct {\n"
"%s const char *name; cxx_enum_type value;\n"
"%s } constants[%d] = {\n",
indent, (scope ? scope : ""), (scope ? "::" : ""), cls->Name, indent, indent, indent,
cls->NumberOfConstants);
for (j = 0; j < cls->NumberOfConstants; j++)
{
val = cls->Constants[j];
fprintf(fp, "%s { \"%s%s\", cxx_enum_type::%s },%s\n", indent, val->Name,
(vtkWrapText_IsPythonKeyword(val->Name) ? "_" : ""), val->Name,
((val->Attributes & VTK_PARSE_DEPRECATED) ? " /* deprecated */" : ""));
}
fprintf(fp,
"%s };\n"
"\n",
indent);
fprintf(fp,
"%s for (int c = 0; c < %d; c++)\n"
"%s {\n"
"%s enumval = Py%s%s%s_FromEnum(constants[c].value);\n"
"%s if (enumval)\n"
"%s {\n"
"%s PyDict_SetItemString(enumdict, constants[c].name, enumval);\n"
"%s Py_DECREF(enumval);\n"
"%s }\n"
"%s }\n",
indent, cls->NumberOfConstants, indent, indent, (scope ? scope : ""), (scope ? "_" : ""),
cls->Name, indent, indent, indent, indent, indent, indent);
fprintf(fp,
"%s}\n"
"\n",
indent);
}
fprintf(fp,
"%sPyVTKEnum_Add(&Py%s%s%s_Type, \"%s%s%s\");\n"
"\n",
indent, (scope ? scope : ""), (scope ? "_" : ""), cls->Name, (scope ? scope : ""),
(scope ? "." : ""), cls->Name);
fprintf(fp,
"%s%s = (PyObject *)&Py%s%s%s_Type;\n"
"%sif (PyDict_SetItemString(%s, \"%s\", %s) != 0)\n"
"%s{\n"
"%s Py_DECREF(%s);\n"
"%s}\n",
indent, objvar, (scope ? scope : ""), (scope ? "_" : ""), cls->Name, indent, dictvar, cls->Name,
objvar, indent, indent, objvar, indent);
}
/* -------------------------------------------------------------------- */
/* write out an enum type object */
void vtkWrapPython_GenerateEnumType(
FILE* fp, const char* module, const char* classname, EnumInfo* data)
{
char enumname[512];
char tpname[512];
if (classname)
{
/* join with "_" for identifier, and with "." for type name */
sprintf(enumname, "%.200s_%.200s", classname, data->Name);
sprintf(tpname, "%.200s.%.200s", classname, data->Name);
}
else
{
sprintf(enumname, "%.200s", data->Name);
sprintf(tpname, "%.200s", data->Name);
}
/* generate all functions and protocols needed for the type */
/* generate the TypeObject */
fprintf(fp,
"#ifdef VTK_PYTHON_NEEDS_DEPRECATION_WARNING_SUPPRESSION\n"
"#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n"
"#endif\n"
"\n"
"static PyTypeObject Py%s_Type = {\n"
" PyVarObject_HEAD_INIT(&PyType_Type, 0)\n"
" PYTHON_PACKAGE_SCOPE \"%s.%s\", // tp_name\n"
" sizeof(PyIntObject), // tp_basicsize\n"
" 0, // tp_itemsize\n"
" nullptr, // tp_dealloc\n"
"#if PY_VERSION_HEX >= 0x03080000\n"
" 0, // tp_vectorcall_offset\n"
"#else\n"
" nullptr, // tp_print\n"
"#endif\n"
" nullptr, // tp_getattr\n"
" nullptr, // tp_setattr\n"
" nullptr, // tp_compare\n"
" nullptr, // tp_repr\n",
enumname, module, tpname);
fprintf(fp,
" nullptr, // tp_as_number\n"
" nullptr, // tp_as_sequence\n"
" nullptr, // tp_as_mapping\n"
" nullptr, // tp_hash\n"
" nullptr, // tp_call\n"
" nullptr, // tp_str\n"
" nullptr, // tp_getattro\n"
" nullptr, // tp_setattro\n"
" nullptr, // tp_as_buffer\n"
" Py_TPFLAGS_DEFAULT, // tp_flags\n"
" nullptr, // tp_doc\n"
" nullptr, // tp_traverse\n"
" nullptr, // tp_clear\n"
" nullptr, // tp_richcompare\n"
" 0, // tp_weaklistoffset\n");
fprintf(fp,
" nullptr, // tp_iter\n"
" nullptr, // tp_iternext\n"
" nullptr, // tp_methods\n"
" nullptr, // tp_members\n"
" nullptr, // tp_getset\n"
" &PyInt_Type, // tp_base\n"
" nullptr, // tp_dict\n"
" nullptr, // tp_descr_get\n"
" nullptr, // tp_descr_set\n"
" 0, // tp_dictoffset\n"
" nullptr, // tp_init\n"
" nullptr, // tp_alloc\n"
" nullptr, // tp_new\n"
" PyObject_Del, // tp_free\n"
" nullptr, // tp_is_gc\n");
/* fields set by python itself */
fprintf(fp,
" nullptr, // tp_bases\n"
" nullptr, // tp_mro\n"
" nullptr, // tp_cache\n"
" nullptr, // tp_subclasses\n"
" nullptr, // tp_weaklist\n");
/* internal struct members */
fprintf(fp,
" VTK_WRAP_PYTHON_SUPPRESS_UNINITIALIZED\n"
"};\n"
"\n");
/* conversion method: construct from enum value */
fprintf(fp,
"template<class T>\n"
"PyObject *Py%s_FromEnum(T val)\n"
"{\n"
" return PyVTKEnum_New(&Py%s_Type, static_cast<int>(val));\n"
"}\n"
"\n",
enumname, enumname);
}
/* generate code that adds all public enum types to a python dict */
void vtkWrapPython_AddPublicEnumTypes(
FILE* fp, const char* indent, const char* dictvar, const char* objvar, NamespaceInfo* data)
{
char text[1024];
const char* pythonname = data->Name;
int i;
if (data->Name)
{
/* convert C++ class names to a python-friendly format */
vtkWrapText_PythonName(data->Name, text);
pythonname = text;
}
for (i = 0; i < data->NumberOfEnums; i++)
{
if (!data->Enums[i]->IsExcluded && data->Enums[i]->Access == VTK_ACCESS_PUBLIC)
{
vtkWrapPython_AddEnumType(fp, indent, dictvar, objvar, pythonname, data->Enums[i]);
fprintf(fp, "\n");
}
}
}
| 3,896 |
1,338 |
<reponame>Kirishikesan/haiku<filename>src/bin/draggers.cpp
/*
* Copyright 2016, <NAME>, <<EMAIL>>. All rights reserved.
* Distributed under the terms of the MIT License.
*/
/*
* draggers - show/hide draggers from CLI
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Application.h>
#include <Dragger.h>
int usage(int ret)
{
fprintf(stderr, "draggers [show|hide]\n");
fprintf(stderr, "Shows/sets draggers state\n");
return ret;
}
int main(int argc, char **argv)
{
int i;
BApplication app("application/x-vnd.Haiku-draggers");
if (argc < 2) {
printf("%s\n", BDragger::AreDraggersDrawn()?"shown":"hidden");
return EXIT_SUCCESS;
}
for (i = 1; i < argc; i++) {
if (!strncmp(argv[i], "-h", 2)) {
return usage(EXIT_SUCCESS);
}
if (!strcmp(argv[i], "1")
|| !strncmp(argv[i], "en", 2)
|| !strncmp(argv[i], "sh", 2)
|| !strncmp(argv[i], "on", 2))
BDragger::ShowAllDraggers();
else if (!strcmp(argv[i], "0")
|| !strncmp(argv[i], "di", 2)
|| !strncmp(argv[i], "hi", 2)
|| !strncmp(argv[i], "of", 2))
BDragger::HideAllDraggers();
else
return usage(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
| 529 |
1,478 |
/**
* @file unit-cppapi-util.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2021 TileDB, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @section DESCRIPTION
*
* Util Tests for C++ API.
*/
#include "catch.hpp"
#include "tiledb/sm/cpp_api/utils.h"
using namespace tiledb;
TEST_CASE("C++ API: Utils", "[cppapi]") {
std::vector<char> buf = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'};
std::vector<uint64_t> offsets = {0, 5};
SECTION("Group by cell, offset") {
auto ret = group_by_cell<char, std::string>(offsets, buf);
REQUIRE(ret.size() == 2);
CHECK(ret[0] == "abcde");
CHECK(ret[1] == "fghi");
}
SECTION("Group by cell, fixed") {
CHECK_THROWS(group_by_cell<2>(buf));
auto ret = group_by_cell<3>(buf);
CHECK(ret.size() == 3);
CHECK(std::string(ret[0].begin(), ret[0].end()) == "abc");
CHECK(std::string(ret[1].begin(), ret[1].end()) == "def");
CHECK(std::string(ret[2].begin(), ret[2].end()) == "ghi");
}
SECTION("Group by cell, dynamic") {
CHECK_THROWS(group_by_cell(buf, 2));
auto ret = group_by_cell(buf, 3);
CHECK(ret.size() == 3);
CHECK(std::string(ret[0].begin(), ret[0].end()) == "abc");
CHECK(std::string(ret[1].begin(), ret[1].end()) == "def");
CHECK(std::string(ret[2].begin(), ret[2].end()) == "ghi");
}
SECTION("Group by cell, int values") {
std::vector<int32_t> buf = {1, 2, 3, 4, 5};
std::vector<uint64_t> offsets = {0, 3 * sizeof(int)};
auto ret = group_by_cell(offsets, buf, offsets.size(), buf.size());
CHECK(ret.size() == 2);
CHECK(ret[0].size() == 3);
CHECK((ret[0][0] == 1 && ret[0][1] == 2 && ret[0][2] == 3));
CHECK(ret[1].size() == 2);
CHECK((ret[1][0] == 4 && ret[1][1] == 5));
}
SECTION("Unpack var buffer") {
auto grouped = group_by_cell(buf, 3);
auto ungrouped = ungroup_var_buffer(grouped);
CHECK(ungrouped.first.size() == 3);
CHECK(ungrouped.first[0] == 0);
CHECK(ungrouped.first[1] == 3);
CHECK(ungrouped.first[2] == 6);
CHECK(ungrouped.second.size() == 9);
for (int i = 0; i < 9; i++) {
CHECK(ungrouped.second[i] == buf[i]);
}
}
SECTION("Ungroup-group is idempotent") {
std::vector<std::vector<int32_t>> grouped = {{1, 2, 3}, {4, 5}};
auto ungrouped = ungroup_var_buffer(grouped);
CHECK(ungrouped.first.size() == 2);
CHECK(ungrouped.first[0] == 0);
CHECK(ungrouped.first[1] == 3 * sizeof(int32_t));
CHECK(ungrouped.second.size() == 5);
for (int i = 0; i < 5; i++)
CHECK(ungrouped.second[i] == i + 1);
auto ret = group_by_cell(
ungrouped.first,
ungrouped.second,
ungrouped.first.size(),
ungrouped.second.size());
CHECK(ret.size() == 2);
CHECK(ret[0].size() == 3);
CHECK((ret[0][0] == 1 && ret[0][1] == 2 && ret[0][2] == 3));
CHECK(ret[1].size() == 2);
CHECK((ret[1][0] == 4 && ret[1][1] == 5));
}
SECTION("Flatten") {
std::vector<std::string> v = {"a", "bb", "ccc"};
auto f = flatten(v);
CHECK(f.size() == 6);
CHECK(std::string(f.begin(), f.end()) == "abbccc");
std::vector<std::vector<double>> d = {{1.2, 2.1}, {2.3, 3.2}, {3.4, 4.3}};
auto f2 = flatten(d);
CHECK(f2.size() == 6);
CHECK(f2[0] == 1.2);
CHECK(f2[1] == 2.1);
CHECK(f2[2] == 2.3);
CHECK(f2[3] == 3.2);
CHECK(f2[4] == 3.4);
CHECK(f2[5] == 4.3);
}
}
| 1,850 |
5,937 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//+-----------------------------------------------------------------------------
//
//
// $TAG ENGR
// $Module: win_mil_graphics_d3d
// $Keywords:
//
// $Description:
// Contains HW Startup/Shutdown routine implementations
//
// $ENDTAG
//
//------------------------------------------------------------------------------
#include "precomp.hpp"
//+-----------------------------------------------------------------------------
//
// Function:
// HwStartup
//
// Synopsis:
// Initialize global resources needed by HW code
//
//------------------------------------------------------------------------------
HRESULT
HwStartup()
{
HRESULT hr = S_OK;
IFC(CD3DDeviceManager::Create());
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Function:
// HwShutdown
//
// Synopsis:
// Release global resources needed by HW code
//
//------------------------------------------------------------------------------
void
HwShutdown()
{
CD3DDeviceManager::Delete();
}
| 333 |
1,474 |
<reponame>schminkel/FlatLaf
/*
* Copyright 2020 FormDev Software GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.formdev.flatlaf.icons;
import java.awt.Graphics2D;
/**
* "iconify" icon for windows (frames and dialogs).
*
* @author <NAME>
*/
public class FlatWindowIconifyIcon
extends FlatWindowAbstractIcon
{
public FlatWindowIconifyIcon() {
}
@Override
protected void paintIconAt1x( Graphics2D g, int x, int y, int width, int height, double scaleFactor ) {
int iw = (int) (10 * scaleFactor);
int ih = (int) scaleFactor;
int ix = x + ((width - iw) / 2);
int iy = y + ((height - ih) / 2);
g.fillRect( ix, iy, iw, ih );
}
}
| 382 |
8,772 |
{
"dependencies": "discovery-profile,pac4j-webflow,oidc,simple-mfa",
"properties": [
"--cas.service-registry.core.init-from-json=true",
"--cas.authn.pac4j.cas[0].login-url=https://localhost:8444/cas/login",
"--cas.authn.pac4j.cas[0].protocol=CAS30",
"--cas.authn.pac4j.cas[0].client-name=CasClient",
"--cas.authn.oidc.core.issuer=https://localhost:8443/cas/oidc",
"--cas.authn.oidc.jwks.jwks-file=file:/tmp/keystore.jwks",
"--cas.authn.attribute-repository.stub.attributes.phone=13477464523",
"--cas.authn.attribute-repository.stub.attributes.mail=<EMAIL>",
"--cas.monitor.endpoints.endpoint.defaults.access=ANONYMOUS",
"--management.endpoints.web.exposure.include=discoveryProfile",
"--management.endpoint.health.show-details=always",
"--management.endpoints.enabled-by-default=true"
]
}
| 373 |
12,824 |
<filename>test/files/neg/t10260/D.java
public class D<T> {}
| 25 |
566 |
#include <oci.h>
#include <stdlib.h>
| 17 |
619 |
from django.test import TestCase
from localflavor.md import forms
from .forms import MDPlaceForm
class MDLocalFlavorTests(TestCase):
def setUp(self):
self.data = {
'idno': '1231231231231',
'company_type_1': 'SRL',
'company_type_2': 'II',
'license_plate': 'KBC 123',
}
def _get_form(self):
return MDPlaceForm(self.data)
def _get_model(self):
form = self._get_form()
if form.is_valid():
return form.save()
def test_MDIDNOField(self):
error_format = ['Enter a valid IDNO number.']
valid = {
'2006042220032': '2006042220032',
}
invalid = {
'1111': error_format,
'foo': error_format,
}
self.assertFieldOutput(forms.MDIDNOField, valid, invalid)
def test_MDLicensePlateField(self):
error_format = ['Enter a valid license plate.']
valid = {
'abj 123': 'abj 123',
'K BC 123': 'K BC 123',
'FL BC 123': 'FL BC 123',
'RM P 001': 'RM P 001',
'RM G 001': 'RM G 001',
'RM A 123': 'RM A 123',
'CD 112 AA': 'CD 112 AA',
'TC 113 AA': 'TC 113 AA',
'CD 111 A': 'CD 111 A',
'RM 1123': 'RM 1123',
'MIC 1234': 'MIC 1234',
'MAI 1234': 'MAI 1234',
'H 1234': 'H 1234',
'FA 1234': 'FA 1234',
'DG 1234': 'DG 1234',
'SP 123': 'SP 123',
}
invalid = {
'KK BC 123': error_format,
'KKBC 123': error_format,
'TC 113 AAA': error_format,
'MAI 112': error_format,
'SP 1121': error_format,
'SP11211234': error_format,
}
self.assertFieldOutput(forms.MDLicensePlateField, valid, invalid)
def test_MD_model(self):
model = self._get_model()
self.assertEqual(model.idno, '1231231231231')
self.assertEqual(model.company_type_1, 'SRL')
self.assertEqual(model.company_type_2, 'II')
self.assertEqual(model.license_plate, 'KBC 123')
model.clean_fields()
def test_get_display_methods(self):
model = self._get_model()
self.assertEqual(model.get_company_type_1_display(), 'Societate cu răspundere limitată')
self.assertEqual(model.get_company_type_2_display(), 'Întreprindere Individuală')
def test_MDCompanyTypeSelect(self):
form = forms.MDCompanyTypesSelect()
expected = '''
<select name="companies">
<option value="II">Întreprindere Individuală</option>
<option value="SA">Societate pe acţiuni</option>
<option value="SNC">Societate în nume colectiv</option>
<option value="SC">Societatea în comandită</option>
<option value="CP">Cooperativa de producţie</option>
<option value="CI">Cooperativa de întreprinzători</option>
<option value="SRL" selected="selected">Societate cu răspundere limitată</option>
<option value="GT">Gospodăria ţărănească</option>
</select>'''
companies_form = form.render('companies', 'SRL')
self.assertHTMLEqual(expected, companies_form)
def test_MDRegionSelect(self):
form = forms.MDRegionSelect()
expected = '''<option value="C" selected>Chișinău</option>'''
companies_form = form.render('regions', 'C')
self.assertTrue(expected in companies_form)
| 1,756 |
460 |
<reponame>ybayart/norminette<gh_stars>100-1000
void tata(const char xc);
void tata(const t_struct *a);
void tata(const char w);
int main(int toto, int c, int v)
{
if (i --)
while (1)
{
return ;
}
else
return ;
}
void toto(void)
{
return ;
}
| 128 |
794 |
[
{
"name": "Current pkg",
"description": "应用切换时,使用Toast显示当前应用的当前应用包名(仅做示例,请自行优化)",
"priority": 2,
"condition": "frontPkgChanged == true",
"actions": [
"ui.showShortToast(activity.getFrontAppPackage());"
]
}
]
| 165 |
3,747 |
<filename>tests/python/kaolin/metrics/test_voxelgrid.py
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
import torch
from kaolin.utils.testing import FLOAT_DTYPES, ALL_DEVICES
from kaolin.metrics import voxelgrid as vg_metrics
@pytest.mark.parametrize('dtype', FLOAT_DTYPES)
@pytest.mark.parametrize('device', ALL_DEVICES)
class TestIoU:
def test_handmade_input(self, device, dtype):
pred = torch.tensor([[[[0, 1, 1],
[1, 0, 0],
[1, 0, 0]],
[[0, 0, 1],
[0, 1, 1],
[1, 1, 1]],
[[1, 0, 0],
[0, 1, 1],
[0, 0, 1]]],
[[[1, 0, 0],
[1, 0, 1],
[1, 0, 0]],
[[1, 0, 0],
[0, 1, 0],
[0, 1, 0]],
[[0, 1, 0],
[0, 1, 1],
[0, 0, 1]]]], dtype=dtype, device=device)
gt = torch.tensor([[[[0, 0, 0],
[0, 0, 1],
[1, 0, 1]],
[[1, 1, 1],
[0, 1, 1],
[1, 1, 1]],
[[1, 0, 0],
[1, 1, 0],
[0, 1, 0]]],
[[[1, 0, 1],
[0, 1, 1],
[1, 0, 1]],
[[0, 1, 0],
[1, 1, 1],
[0, 0, 1]],
[[1, 0, 0],
[1, 0, 0],
[1, 1, 1]]]], dtype=dtype, device=device)
expected = torch.tensor((0.4500, 0.2273), device=device, dtype=torch.float)
output = vg_metrics.iou(pred, gt)
assert torch.allclose(expected, output, atol=1e-4)
| 1,718 |
716 |
/*
* 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 F_EXP_RTE_H_
#define F_EXP_RTE_H_
#include "gbldefs.h"
#include "global.h"
#include "symtab.h"
#include "expand.h"
/**
\brief ...
*/
bool bindC_function_return_struct_in_registers(int func_sym);
/**
\brief ...
*/
int charaddr(SPTR sym);
/**
\brief ...
*/
int charlen(SPTR sym);
/**
\brief ...
*/
int exp_alloca(ILM *ilmp);
/**
\brief ...
*/
int gen_arg_ili(void);
/**
\brief ...
*/
SPTR getdumlen(void);
/// Create a symbol representing the length of a passed-length character
/// argument in the host subprogram.
SPTR gethost_dumlen(int arg, ISZ_T address);
/**
\brief ...
*/
int is_passbyval_dummy(int sptr);
/**
\brief ...
*/
int needlen(int sym, int func);
/**
\brief ...
*/
void add_arg_ili(int ilix, int nme, int dtype);
/**
\brief ...
*/
void chk_terminal_func(int entbih, int exitbih);
/**
\brief ...
*/
void end_arg_ili(void);
/**
\brief ...
*/
void exp_agoto(ILM *ilmp, int curilm);
/**
\brief ...
*/
void expand_smove(int destilm, int srcilm, DTYPE dtype);
/**
\brief ...
*/
void exp_build_agoto(int *tab, int mx);
/**
\brief ...
*/
void exp_call(ILM_OP opc, ILM *ilmp, int curilm);
/**
\brief ...
*/
void exp_cgoto(ILM *ilmp, int curilm);
/**
\brief ...
*/
void exp_end(ILM *ilmp, int curilm, bool is_func);
/**
\brief ...
*/
void exp_fstring(ILM_OP opc, ILM *ilmp, int curilm);
/**
\brief ...
*/
void exp_header(SPTR sym);
/**
\brief ...
*/
void exp_qjsr(const char *ext, DTYPE res_dtype, ILM *ilmp, int curilm);
/**
\brief ...
*/
void exp_remove_gsmove(void);
/**
\brief ...
*/
void exp_reset_argregs(int ir, int fr);
/**
\brief ...
*/
void exp_szero(ILM *ilmp, int curilm, int to, int from, int dtype);
/**
\brief ...
*/
void exp_zqjsr(char *ext, int res_dtype, ILM *ilmp, int curilm);
/**
\brief ...
*/
void init_arg_ili(int n);
/** \brief Checks to see if a procedure has character dummy arguments.
*
* \param func is the procedure we are checking.
*
* \return true if the procedure has character dummy arguments, else false.
*/
bool func_has_char_args(SPTR func);
/// \brief Process referenced symbols, assigning them locations
void AssignAddresses(void);
#endif
| 1,008 |
473 |
<reponame>pingjuiliao/cb-multios
#include "cgc_string.h"
#include "cgc_stdint.h"
cgc_size_t cgc_strlen( const char *str )
{
cgc_size_t len = 0;
while ( *str++ != '\0' )
len++;
return len;
}
void cgc_bzero(void *s, cgc_size_t n) {
while (n) {
((char *)s)[--n] = '\0';
}
((char *)s)[n] = '\0';
}
void *cgc_memset( void *ptr, int value, cgc_size_t num )
{
void *ptr_temp = ptr;
uint8_t set_value_byte = (uint8_t)value;
uint32_t set_value_dword = (set_value_byte << 24) | (set_value_byte << 16) | (set_value_byte << 8) | set_value_byte;
while ( num >= 4 )
{
*((uint32_t*)ptr++) = set_value_dword;
num-=4;
}
while ( num > 0 )
{
*((uint8_t*)ptr++) = set_value_byte;
num--;
}
return (ptr_temp);
}
| 391 |
777 |
<gh_stars>100-1000
/*
* Copyright (C) 1999 <NAME> (<EMAIL>)
* (C) 1999 <NAME> (<EMAIL>)
* Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "core/layout/LayoutInline.h"
#include "core/dom/Fullscreen.h"
#include "core/dom/StyleEngine.h"
#include "core/layout/HitTestResult.h"
#include "core/layout/LayoutBlock.h"
#include "core/layout/LayoutFullScreen.h"
#include "core/layout/LayoutGeometryMap.h"
#include "core/layout/LayoutTheme.h"
#include "core/layout/LayoutView.h"
#include "core/layout/api/LineLayoutBoxModel.h"
#include "core/layout/line/InlineTextBox.h"
#include "core/paint/BoxPainter.h"
#include "core/paint/InlinePainter.h"
#include "core/paint/ObjectPainter.h"
#include "core/paint/PaintLayer.h"
#include "core/style/StyleInheritedData.h"
#include "platform/geometry/FloatQuad.h"
#include "platform/geometry/Region.h"
#include "platform/geometry/TransformState.h"
namespace blink {
struct SameSizeAsLayoutInline : public LayoutBoxModelObject {
virtual ~SameSizeAsLayoutInline() {}
LayoutObjectChildList m_children;
LineBoxList m_lineBoxes;
};
static_assert(sizeof(LayoutInline) == sizeof(SameSizeAsLayoutInline),
"LayoutInline should stay small");
LayoutInline::LayoutInline(Element* element) : LayoutBoxModelObject(element) {
setChildrenInline(true);
}
void LayoutInline::willBeDestroyed() {
// Make sure to destroy anonymous children first while they are still
// connected to the rest of the tree, so that they will properly dirty line
// boxes that they are removed from. Effects that do :before/:after only on
// hover could crash otherwise.
children()->destroyLeftoverChildren();
// Destroy our continuation before anything other than anonymous children.
// The reason we don't destroy it before anonymous children is that they may
// have continuations of their own that are anonymous children of our
// continuation.
LayoutBoxModelObject* continuation = this->continuation();
if (continuation) {
continuation->destroy();
setContinuation(nullptr);
}
if (!documentBeingDestroyed()) {
if (firstLineBox()) {
// We can't wait for LayoutBoxModelObject::destroy to clear the selection,
// because by then we will have nuked the line boxes.
// FIXME: The FrameSelection should be responsible for this when it
// is notified of DOM mutations.
if (isSelectionBorder())
view()->clearSelection();
// If line boxes are contained inside a root, that means we're an inline.
// In that case, we need to remove all the line boxes so that the parent
// lines aren't pointing to deleted children. If the first line box does
// not have a parent that means they are either already disconnected or
// root lines that can just be destroyed without disconnecting.
if (firstLineBox()->parent()) {
for (InlineFlowBox* box = firstLineBox(); box; box = box->nextLineBox())
box->remove();
}
} else if (parent()) {
parent()->dirtyLinesFromChangedChild(this);
}
}
m_lineBoxes.deleteLineBoxes();
LayoutBoxModelObject::willBeDestroyed();
}
LayoutInline* LayoutInline::inlineElementContinuation() const {
LayoutBoxModelObject* continuation = this->continuation();
if (!continuation || continuation->isInline())
return toLayoutInline(continuation);
return toLayoutBlockFlow(continuation)->inlineElementContinuation();
}
void LayoutInline::updateFromStyle() {
LayoutBoxModelObject::updateFromStyle();
// FIXME: Is this still needed. Was needed for run-ins, since run-in is
// considered a block display type.
setInline(true);
// FIXME: Support transforms and reflections on inline flows someday.
setHasTransformRelatedProperty(false);
setHasReflection(false);
}
static LayoutObject* inFlowPositionedInlineAncestor(LayoutObject* p) {
while (p && p->isLayoutInline()) {
if (p->isInFlowPositioned())
return p;
p = p->parent();
}
return nullptr;
}
static void updateInFlowPositionOfAnonymousBlockContinuations(
LayoutObject* block,
const ComputedStyle& newStyle,
const ComputedStyle& oldStyle,
LayoutObject* containingBlockOfEndOfContinuation) {
for (; block && block != containingBlockOfEndOfContinuation &&
block->isAnonymousBlock();
block = block->nextSibling()) {
LayoutBlockFlow* blockFlow = toLayoutBlockFlow(block);
if (!blockFlow->isAnonymousBlockContinuation())
continue;
// If we are no longer in-flow positioned but our descendant block(s) still
// have an in-flow positioned ancestor then their containing anonymous block
// should keep its in-flow positioning.
if (oldStyle.hasInFlowPosition() &&
inFlowPositionedInlineAncestor(blockFlow->inlineElementContinuation()))
continue;
RefPtr<ComputedStyle> newBlockStyle =
ComputedStyle::clone(block->styleRef());
newBlockStyle->setPosition(newStyle.position());
block->setStyle(newBlockStyle);
}
}
void LayoutInline::styleDidChange(StyleDifference diff,
const ComputedStyle* oldStyle) {
LayoutBoxModelObject::styleDidChange(diff, oldStyle);
// Ensure that all of the split inlines pick up the new style. We only do this
// if we're an inline, since we don't want to propagate a block's style to the
// other inlines. e.g., <font>foo <h4>goo</h4> moo</font>. The <font> inlines
// before and after the block share the same style, but the block doesn't need
// to pass its style on to anyone else.
const ComputedStyle& newStyle = styleRef();
LayoutInline* continuation = inlineElementContinuation();
LayoutInline* endOfContinuation = nullptr;
for (LayoutInline* currCont = continuation; currCont;
currCont = currCont->inlineElementContinuation()) {
LayoutBoxModelObject* nextCont = currCont->continuation();
currCont->setContinuation(nullptr);
currCont->setStyle(mutableStyle());
currCont->setContinuation(nextCont);
endOfContinuation = currCont;
}
if (continuation && oldStyle) {
ASSERT(endOfContinuation);
LayoutObject* block = containingBlock()->nextSibling();
// If an inline's in-flow positioning has changed then any descendant blocks
// will need to change their styles accordingly.
if (block && block->isAnonymousBlock() &&
newStyle.position() != oldStyle->position() &&
(newStyle.hasInFlowPosition() || oldStyle->hasInFlowPosition()))
updateInFlowPositionOfAnonymousBlockContinuations(
block, newStyle, *oldStyle, endOfContinuation->containingBlock());
}
if (!alwaysCreateLineBoxes()) {
bool alwaysCreateLineBoxesNew =
hasSelfPaintingLayer() || hasBoxDecorationBackground() ||
newStyle.hasPadding() || newStyle.hasMargin() || newStyle.hasOutline();
if (oldStyle && alwaysCreateLineBoxesNew) {
dirtyLineBoxes(false);
setNeedsLayoutAndFullPaintInvalidation(
LayoutInvalidationReason::StyleChange);
}
setAlwaysCreateLineBoxes(alwaysCreateLineBoxesNew);
}
// If we are changing to/from static, we need to reposition
// out-of-flow positioned descendants.
if (oldStyle && oldStyle->position() != newStyle.position() &&
(newStyle.position() == StaticPosition ||
oldStyle->position() == StaticPosition)) {
LayoutBlock* absContainingBlock = nullptr;
if (oldStyle->position() == StaticPosition) {
absContainingBlock = containingBlockForAbsolutePosition();
} else {
// When position was not static, containingBlockForAbsolutePosition
// for our children is our existing containingBlock.
absContainingBlock = containingBlock();
}
if (absContainingBlock)
absContainingBlock->removePositionedObjects(this, NewContainingBlock);
}
propagateStyleToAnonymousChildren();
}
void LayoutInline::updateAlwaysCreateLineBoxes(bool fullLayout) {
// Once we have been tainted once, just assume it will happen again. This way
// effects like hover highlighting that change the background color will only
// cause a layout on the first rollover.
if (alwaysCreateLineBoxes())
return;
const ComputedStyle& parentStyle = parent()->styleRef();
LayoutInline* parentLayoutInline =
parent()->isLayoutInline() ? toLayoutInline(parent()) : 0;
bool checkFonts = document().inNoQuirksMode();
bool alwaysCreateLineBoxesNew =
(parentLayoutInline && parentLayoutInline->alwaysCreateLineBoxes()) ||
(parentLayoutInline &&
parentStyle.verticalAlign() != EVerticalAlign::Baseline) ||
style()->verticalAlign() != EVerticalAlign::Baseline ||
style()->getTextEmphasisMark() != TextEmphasisMarkNone ||
(checkFonts &&
(!styleRef().hasIdenticalAscentDescentAndLineGap(parentStyle) ||
parentStyle.lineHeight() != styleRef().lineHeight()));
if (!alwaysCreateLineBoxesNew && checkFonts &&
document().styleEngine().usesFirstLineRules()) {
// Have to check the first line style as well.
const ComputedStyle& firstLineParentStyle = parent()->styleRef(true);
const ComputedStyle& childStyle = styleRef(true);
alwaysCreateLineBoxesNew =
!firstLineParentStyle.hasIdenticalAscentDescentAndLineGap(childStyle) ||
childStyle.verticalAlign() != EVerticalAlign::Baseline ||
firstLineParentStyle.lineHeight() != childStyle.lineHeight();
}
if (alwaysCreateLineBoxesNew) {
if (!fullLayout)
dirtyLineBoxes(false);
setAlwaysCreateLineBoxes();
}
}
LayoutRect LayoutInline::localCaretRect(InlineBox* inlineBox,
int,
LayoutUnit* extraWidthToEndOfLine) {
if (firstChild()) {
// This condition is possible if the LayoutInline is at an editing boundary,
// i.e. the VisiblePosition is:
// <LayoutInline editingBoundary=true>|<LayoutText>
// </LayoutText></LayoutInline>
// FIXME: need to figure out how to make this return a valid rect, note that
// there are no line boxes created in the above case.
return LayoutRect();
}
DCHECK(!inlineBox);
if (extraWidthToEndOfLine)
*extraWidthToEndOfLine = LayoutUnit();
LayoutRect caretRect =
localCaretRectForEmptyElement(borderAndPaddingWidth(), LayoutUnit());
if (InlineBox* firstBox = firstLineBox())
caretRect.moveBy(firstBox->location());
return caretRect;
}
void LayoutInline::addChild(LayoutObject* newChild, LayoutObject* beforeChild) {
// Any table-part dom child of an inline element has anonymous wrappers in the
// layout tree so we need to climb up to the enclosing anonymous table wrapper
// and add the new child before that.
// TODO(rhogan): If newChild is a table part we want to insert it into the
// same table as beforeChild.
while (beforeChild && beforeChild->isTablePart())
beforeChild = beforeChild->parent();
if (continuation())
return addChildToContinuation(newChild, beforeChild);
return addChildIgnoringContinuation(newChild, beforeChild);
}
static LayoutBoxModelObject* nextContinuation(LayoutObject* layoutObject) {
if (layoutObject->isInline() && !layoutObject->isAtomicInlineLevel())
return toLayoutInline(layoutObject)->continuation();
return toLayoutBlockFlow(layoutObject)->inlineElementContinuation();
}
LayoutBoxModelObject* LayoutInline::continuationBefore(
LayoutObject* beforeChild) {
if (beforeChild && beforeChild->parent() == this)
return this;
LayoutBoxModelObject* curr = nextContinuation(this);
LayoutBoxModelObject* nextToLast = this;
LayoutBoxModelObject* last = this;
while (curr) {
if (beforeChild && beforeChild->parent() == curr) {
if (curr->slowFirstChild() == beforeChild)
return last;
return curr;
}
nextToLast = last;
last = curr;
curr = nextContinuation(curr);
}
if (!beforeChild && !last->slowFirstChild())
return nextToLast;
return last;
}
void LayoutInline::addChildIgnoringContinuation(LayoutObject* newChild,
LayoutObject* beforeChild) {
// Make sure we don't append things after :after-generated content if we have
// it.
if (!beforeChild && isAfterContent(lastChild()))
beforeChild = lastChild();
if (!newChild->isInline() && !newChild->isFloatingOrOutOfFlowPositioned() &&
!newChild->isTablePart()) {
// We are placing a block inside an inline. We have to perform a split of
// this inline into continuations. This involves creating an anonymous
// block box to hold |newChild|. We then make that block box a continuation
// of this inline. We take all of the children after |beforeChild| and put
// them in a clone of this object.
RefPtr<ComputedStyle> newStyle =
ComputedStyle::createAnonymousStyleWithDisplay(
containingBlock()->styleRef(), EDisplay::Block);
// If inside an inline affected by in-flow positioning the block needs to be
// affected by it too. Giving the block a layer like this allows it to
// collect the x/y offsets from inline parents later.
if (LayoutObject* positionedAncestor = inFlowPositionedInlineAncestor(this))
newStyle->setPosition(positionedAncestor->style()->position());
LayoutBlockFlow* newBox = LayoutBlockFlow::createAnonymous(&document());
newBox->setStyle(std::move(newStyle));
LayoutBoxModelObject* oldContinuation = continuation();
setContinuation(newBox);
splitFlow(beforeChild, newBox, newChild, oldContinuation);
return;
}
LayoutBoxModelObject::addChild(newChild, beforeChild);
newChild->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
LayoutInvalidationReason::ChildChanged);
}
LayoutInline* LayoutInline::clone() const {
LayoutInline* cloneInline = new LayoutInline(node());
cloneInline->setStyle(mutableStyle());
cloneInline->setIsInsideFlowThread(isInsideFlowThread());
return cloneInline;
}
void LayoutInline::moveChildrenToIgnoringContinuation(
LayoutInline* to,
LayoutObject* startChild) {
LayoutObject* child = startChild;
while (child) {
LayoutObject* currentChild = child;
child = currentChild->nextSibling();
to->addChildIgnoringContinuation(
children()->removeChildNode(this, currentChild), nullptr);
}
}
void LayoutInline::splitInlines(LayoutBlockFlow* fromBlock,
LayoutBlockFlow* toBlock,
LayoutBlockFlow* middleBlock,
LayoutObject* beforeChild,
LayoutBoxModelObject* oldCont) {
ASSERT(isDescendantOf(fromBlock));
// If we're splitting the inline containing the fullscreened element,
// |beforeChild| may be the layoutObject for the fullscreened element.
// However, that layoutObject is wrapped in a LayoutFullScreen, so |this| is
// not its parent. Since the splitting logic expects |this| to be the parent,
// set |beforeChild| to be the LayoutFullScreen.
if (Fullscreen* fullscreen = Fullscreen::fromIfExists(document())) {
const Element* fullscreenElement = fullscreen->fullscreenElement();
if (fullscreenElement && beforeChild &&
beforeChild->node() == fullscreenElement)
beforeChild = fullscreen->fullScreenLayoutObject();
}
// FIXME: Because splitting is O(n^2) as tags nest pathologically, we cap the
// depth at which we're willing to clone.
// There will eventually be a better approach to this problem that will let us
// nest to a much greater depth (see bugzilla bug 13430) but for now we have a
// limit. This *will* result in incorrect rendering, but the alternative is to
// hang forever.
const unsigned cMaxSplitDepth = 200;
Vector<LayoutInline*> inlinesToClone;
LayoutInline* topMostInline = this;
for (LayoutObject* o = this; o != fromBlock; o = o->parent()) {
topMostInline = toLayoutInline(o);
if (inlinesToClone.size() < cMaxSplitDepth)
inlinesToClone.push_back(topMostInline);
// Keep walking up the chain to ensure |topMostInline| is a child of
// |fromBlock|, to avoid assertion failure when |fromBlock|'s children are
// moved to |toBlock| below.
}
// Create a new clone of the top-most inline in |inlinesToClone|.
LayoutInline* topMostInlineToClone = inlinesToClone.back();
LayoutInline* cloneInline = topMostInlineToClone->clone();
// Now we are at the block level. We need to put the clone into the |toBlock|.
toBlock->children()->appendChildNode(toBlock, cloneInline);
// Now take all the children after |topMostInline| and remove them from the
// |fromBlock| and put them into the toBlock.
fromBlock->moveChildrenTo(toBlock, topMostInline->nextSibling(), nullptr,
true);
LayoutInline* currentParent = topMostInlineToClone;
LayoutInline* cloneInlineParent = cloneInline;
// Clone the inlines from top to down to ensure any new object will be added
// into a rooted tree.
// Note that we have already cloned the top-most one, so the loop begins from
// size - 2 (except if we have reached |cMaxDepth| in which case we sacrifice
// correct rendering for performance).
for (int i = static_cast<int>(inlinesToClone.size()) - 2; i >= 0; --i) {
// Hook the clone up as a continuation of |currentInline|.
LayoutBoxModelObject* oldCont = currentParent->continuation();
currentParent->setContinuation(cloneInline);
cloneInline->setContinuation(oldCont);
// Create a new clone.
LayoutInline* current = inlinesToClone[i];
cloneInline = current->clone();
// Insert our |cloneInline| as the first child of |cloneInlineParent|.
cloneInlineParent->addChildIgnoringContinuation(cloneInline, nullptr);
// Now we need to take all of the children starting from the first child
// *after* |current| and append them all to the |cloneInlineParent|.
currentParent->moveChildrenToIgnoringContinuation(cloneInlineParent,
current->nextSibling());
currentParent = current;
cloneInlineParent = cloneInline;
}
// The last inline to clone is |this|, and the current |cloneInline| is cloned
// from |this|.
ASSERT(this == inlinesToClone.front());
// Hook |cloneInline| up as the continuation of the middle block.
cloneInline->setContinuation(oldCont);
middleBlock->setContinuation(cloneInline);
// Now take all of the children from |beforeChild| to the end and remove
// them from |this| and place them in the clone.
moveChildrenToIgnoringContinuation(cloneInline, beforeChild);
}
void LayoutInline::splitFlow(LayoutObject* beforeChild,
LayoutBlockFlow* newBlockBox,
LayoutObject* newChild,
LayoutBoxModelObject* oldCont) {
LayoutBlockFlow* block = toLayoutBlockFlow(containingBlock());
LayoutBlockFlow* pre = nullptr;
// Delete our line boxes before we do the inline split into continuations.
block->deleteLineBoxTree();
bool reusedAnonymousBlock = false;
if (block->isAnonymousBlock()) {
LayoutBlock* outerContainingBlock = block->containingBlock();
if (outerContainingBlock && outerContainingBlock->isLayoutBlockFlow() &&
!outerContainingBlock->createsAnonymousWrapper()) {
// We can reuse this block and make it the preBlock of the next
// continuation.
block->removePositionedObjects(nullptr);
block->removeFloatingObjects();
pre = block;
block = toLayoutBlockFlow(outerContainingBlock);
reusedAnonymousBlock = true;
}
}
// No anonymous block available for use. Make one.
if (!reusedAnonymousBlock)
pre = toLayoutBlockFlow(block->createAnonymousBlock());
LayoutBlockFlow* post = toLayoutBlockFlow(pre->createAnonymousBlock());
LayoutObject* boxFirst =
!reusedAnonymousBlock ? block->firstChild() : pre->nextSibling();
if (!reusedAnonymousBlock)
block->children()->insertChildNode(block, pre, boxFirst);
block->children()->insertChildNode(block, newBlockBox, boxFirst);
block->children()->insertChildNode(block, post, boxFirst);
block->setChildrenInline(false);
if (!reusedAnonymousBlock) {
LayoutObject* o = boxFirst;
while (o) {
LayoutObject* no = o;
o = no->nextSibling();
pre->children()->appendChildNode(
pre, block->children()->removeChildNode(block, no));
no->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
LayoutInvalidationReason::AnonymousBlockChange);
}
}
splitInlines(pre, post, newBlockBox, beforeChild, oldCont);
// We already know the newBlockBox isn't going to contain inline kids, so
// avoid wasting time in makeChildrenNonInline by just setting this explicitly
// up front.
newBlockBox->setChildrenInline(false);
newBlockBox->addChild(newChild);
// Always just do a full layout in order to ensure that line boxes (especially
// wrappers for images) get deleted properly. Because objects moves from the
// pre block into the post block, we want to make new line boxes instead of
// leaving the old line boxes around.
pre->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
LayoutInvalidationReason::AnonymousBlockChange);
block->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
LayoutInvalidationReason::AnonymousBlockChange);
post->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
LayoutInvalidationReason::AnonymousBlockChange);
}
void LayoutInline::addChildToContinuation(LayoutObject* newChild,
LayoutObject* beforeChild) {
// A continuation always consists of two potential candidates: an inline or an
// anonymous block box holding block children.
LayoutBoxModelObject* flow = continuationBefore(beforeChild);
ASSERT(!beforeChild || beforeChild->parent()->isAnonymousBlock() ||
beforeChild->parent()->isLayoutInline());
LayoutBoxModelObject* beforeChildParent = nullptr;
if (beforeChild) {
beforeChildParent = toLayoutBoxModelObject(beforeChild->parent());
} else {
LayoutBoxModelObject* cont = nextContinuation(flow);
if (cont)
beforeChildParent = cont;
else
beforeChildParent = flow;
}
// TODO(rhogan): Should we treat out-of-flows and floats as through they're
// inline below?
if (newChild->isFloatingOrOutOfFlowPositioned())
return beforeChildParent->addChildIgnoringContinuation(newChild,
beforeChild);
// A table part will be wrapped by an inline anonymous table when it is added
// to the layout tree, so treat it as inline when deciding where to add it.
bool childInline = newChild->isInline() || newChild->isTablePart();
bool bcpInline = beforeChildParent->isInline();
bool flowInline = flow->isInline();
if (flow == beforeChildParent)
return flow->addChildIgnoringContinuation(newChild, beforeChild);
// The goal here is to match up if we can, so that we can coalesce and create
// the minimal # of continuations needed for the inline.
if (childInline == bcpInline || (beforeChild && beforeChild->isInline()))
return beforeChildParent->addChildIgnoringContinuation(newChild,
beforeChild);
if (flowInline == childInline) {
// Just treat like an append.
return flow->addChildIgnoringContinuation(newChild, 0);
}
return beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
}
void LayoutInline::paint(const PaintInfo& paintInfo,
const LayoutPoint& paintOffset) const {
InlinePainter(*this).paint(paintInfo, paintOffset);
}
template <typename GeneratorContext>
void LayoutInline::generateLineBoxRects(GeneratorContext& yield) const {
if (!alwaysCreateLineBoxes()) {
generateCulledLineBoxRects(yield, this);
} else if (InlineFlowBox* curr = firstLineBox()) {
for (; curr; curr = curr->nextLineBox())
yield(LayoutRect(curr->location(), curr->size()));
}
}
static inline void computeItemTopHeight(const LayoutInline* container,
const RootInlineBox& rootBox,
LayoutUnit* top,
LayoutUnit* height) {
bool firstLine = rootBox.isFirstLineStyle();
const SimpleFontData* fontData =
rootBox.getLineLayoutItem().style(firstLine)->font().primaryFont();
const SimpleFontData* containerFontData =
container->style(firstLine)->font().primaryFont();
DCHECK(fontData && containerFontData);
if (!fontData || !containerFontData) {
*top = LayoutUnit();
*height = LayoutUnit();
return;
}
auto metrics = fontData->getFontMetrics();
auto containerMetrics = containerFontData->getFontMetrics();
*top = rootBox.logicalTop() + (metrics.ascent() - containerMetrics.ascent());
*height = LayoutUnit(containerMetrics.height());
}
template <typename GeneratorContext>
void LayoutInline::generateCulledLineBoxRects(
GeneratorContext& yield,
const LayoutInline* container) const {
if (!culledInlineFirstLineBox())
return;
bool isHorizontal = style()->isHorizontalWritingMode();
LayoutUnit logicalTop, logicalHeight;
for (LayoutObject* curr = firstChild(); curr; curr = curr->nextSibling()) {
if (curr->isFloatingOrOutOfFlowPositioned())
continue;
// We want to get the margin box in the inline direction, and then use our
// font ascent/descent in the block direction (aligned to the root box's
// baseline).
if (curr->isBox()) {
LayoutBox* currBox = toLayoutBox(curr);
if (currBox->inlineBoxWrapper()) {
RootInlineBox& rootBox = currBox->inlineBoxWrapper()->root();
computeItemTopHeight(container, rootBox, &logicalTop, &logicalHeight);
if (isHorizontal) {
yield(LayoutRect(
currBox->inlineBoxWrapper()->x() - currBox->marginLeft(),
logicalTop, currBox->size().width() + currBox->marginWidth(),
logicalHeight));
} else {
yield(LayoutRect(logicalTop, currBox->inlineBoxWrapper()->y() -
currBox->marginTop(),
logicalHeight,
currBox->size().height() + currBox->marginHeight()));
}
}
} else if (curr->isLayoutInline()) {
// If the child doesn't need line boxes either, then we can recur.
LayoutInline* currInline = toLayoutInline(curr);
if (!currInline->alwaysCreateLineBoxes()) {
currInline->generateCulledLineBoxRects(yield, container);
} else {
for (InlineFlowBox* childLine = currInline->firstLineBox(); childLine;
childLine = childLine->nextLineBox()) {
RootInlineBox& rootBox = childLine->root();
computeItemTopHeight(container, rootBox, &logicalTop, &logicalHeight);
LayoutUnit logicalWidth =
childLine->logicalWidth() + childLine->marginLogicalWidth();
if (isHorizontal) {
yield(LayoutRect(
LayoutUnit(childLine->x() - childLine->marginLogicalLeft()),
logicalTop, logicalWidth, logicalHeight));
} else {
yield(LayoutRect(
logicalTop,
LayoutUnit(childLine->y() - childLine->marginLogicalLeft()),
logicalHeight, logicalWidth));
}
}
}
} else if (curr->isText()) {
LayoutText* currText = toLayoutText(curr);
for (InlineTextBox* childText = currText->firstTextBox(); childText;
childText = childText->nextTextBox()) {
RootInlineBox& rootBox = childText->root();
computeItemTopHeight(container, rootBox, &logicalTop, &logicalHeight);
if (isHorizontal)
yield(LayoutRect(childText->x(), logicalTop,
childText->logicalWidth(), logicalHeight));
else
yield(LayoutRect(logicalTop, childText->y(), logicalHeight,
childText->logicalWidth()));
}
}
}
}
namespace {
class AbsoluteRectsGeneratorContext {
public:
AbsoluteRectsGeneratorContext(Vector<IntRect>& rects,
const LayoutPoint& accumulatedOffset)
: m_rects(rects), m_accumulatedOffset(accumulatedOffset) {}
void operator()(const LayoutRect& rect) {
IntRect intRect = enclosingIntRect(rect);
intRect.move(m_accumulatedOffset.x().toInt(),
m_accumulatedOffset.y().toInt());
m_rects.push_back(intRect);
}
private:
Vector<IntRect>& m_rects;
const LayoutPoint& m_accumulatedOffset;
};
} // unnamed namespace
void LayoutInline::absoluteRects(Vector<IntRect>& rects,
const LayoutPoint& accumulatedOffset) const {
AbsoluteRectsGeneratorContext context(rects, accumulatedOffset);
generateLineBoxRects(context);
if (rects.isEmpty())
context(LayoutRect());
if (const LayoutBoxModelObject* continuation = this->continuation()) {
if (continuation->isBox()) {
const LayoutBox* box = toLayoutBox(continuation);
continuation->absoluteRects(
rects,
toLayoutPoint(accumulatedOffset - containingBlock()->location() +
box->locationOffset()));
} else {
continuation->absoluteRects(
rects,
toLayoutPoint(accumulatedOffset - containingBlock()->location()));
}
}
}
namespace {
class AbsoluteQuadsGeneratorContext {
public:
AbsoluteQuadsGeneratorContext(const LayoutInline* layoutObject,
Vector<FloatQuad>& quads,
MapCoordinatesFlags mode)
: m_quads(quads), m_geometryMap(mode) {
m_geometryMap.pushMappingsToAncestor(layoutObject, 0);
}
void operator()(const FloatRect& rect) {
m_quads.push_back(m_geometryMap.absoluteRect(rect));
}
void operator()(const LayoutRect& rect) { operator()(FloatRect(rect)); }
private:
Vector<FloatQuad>& m_quads;
LayoutGeometryMap m_geometryMap;
};
} // unnamed namespace
void LayoutInline::absoluteQuadsForSelf(Vector<FloatQuad>& quads,
MapCoordinatesFlags mode) const {
AbsoluteQuadsGeneratorContext context(this, quads, mode);
generateLineBoxRects(context);
if (quads.isEmpty())
context(FloatRect());
}
LayoutPoint LayoutInline::firstLineBoxTopLeft() const {
if (InlineBox* firstBox = firstLineBoxIncludingCulling())
return firstBox->location();
return LayoutPoint();
}
LayoutUnit LayoutInline::offsetLeft(const Element* parent) const {
return adjustedPositionRelativeTo(firstLineBoxTopLeft(), parent).x();
}
LayoutUnit LayoutInline::offsetTop(const Element* parent) const {
return adjustedPositionRelativeTo(firstLineBoxTopLeft(), parent).y();
}
static LayoutUnit computeMargin(const LayoutInline* layoutObject,
const Length& margin) {
if (margin.isFixed())
return LayoutUnit(margin.value());
if (margin.isPercentOrCalc())
return minimumValueForLength(
margin,
std::max(LayoutUnit(),
layoutObject->containingBlock()->availableLogicalWidth()));
return LayoutUnit();
}
LayoutRectOutsets LayoutInline::marginBoxOutsets() const {
return LayoutRectOutsets(marginTop(), marginRight(), marginBottom(),
marginLeft());
}
LayoutUnit LayoutInline::marginLeft() const {
return computeMargin(this, style()->marginLeft());
}
LayoutUnit LayoutInline::marginRight() const {
return computeMargin(this, style()->marginRight());
}
LayoutUnit LayoutInline::marginTop() const {
return computeMargin(this, style()->marginTop());
}
LayoutUnit LayoutInline::marginBottom() const {
return computeMargin(this, style()->marginBottom());
}
LayoutUnit LayoutInline::marginStart(const ComputedStyle* otherStyle) const {
return computeMargin(
this, style()->marginStartUsing(otherStyle ? otherStyle : style()));
}
LayoutUnit LayoutInline::marginEnd(const ComputedStyle* otherStyle) const {
return computeMargin(
this, style()->marginEndUsing(otherStyle ? otherStyle : style()));
}
LayoutUnit LayoutInline::marginBefore(const ComputedStyle* otherStyle) const {
return computeMargin(
this, style()->marginBeforeUsing(otherStyle ? otherStyle : style()));
}
LayoutUnit LayoutInline::marginAfter(const ComputedStyle* otherStyle) const {
return computeMargin(
this, style()->marginAfterUsing(otherStyle ? otherStyle : style()));
}
LayoutUnit LayoutInline::marginOver() const {
return computeMargin(this, style()->marginOver());
}
LayoutUnit LayoutInline::marginUnder() const {
return computeMargin(this, style()->marginUnder());
}
bool LayoutInline::nodeAtPoint(HitTestResult& result,
const HitTestLocation& locationInContainer,
const LayoutPoint& accumulatedOffset,
HitTestAction hitTestAction) {
return m_lineBoxes.hitTest(LineLayoutBoxModel(this), result,
locationInContainer, accumulatedOffset,
hitTestAction);
}
namespace {
class HitTestCulledInlinesGeneratorContext {
public:
HitTestCulledInlinesGeneratorContext(Region& region,
const HitTestLocation& location)
: m_intersected(false), m_region(region), m_location(location) {}
void operator()(const FloatRect& rect) {
if (m_location.intersects(rect)) {
m_intersected = true;
m_region.unite(enclosingIntRect(rect));
}
}
void operator()(const LayoutRect& rect) {
if (m_location.intersects(rect)) {
m_intersected = true;
m_region.unite(enclosingIntRect(rect));
}
}
bool intersected() const { return m_intersected; }
private:
bool m_intersected;
Region& m_region;
const HitTestLocation& m_location;
};
} // unnamed namespace
bool LayoutInline::hitTestCulledInline(
HitTestResult& result,
const HitTestLocation& locationInContainer,
const LayoutPoint& accumulatedOffset) {
ASSERT(!alwaysCreateLineBoxes());
if (!visibleToHitTestRequest(result.hitTestRequest()))
return false;
HitTestLocation adjustedLocation(locationInContainer,
-toLayoutSize(accumulatedOffset));
Region regionResult;
HitTestCulledInlinesGeneratorContext context(regionResult, adjustedLocation);
generateCulledLineBoxRects(context, this);
if (context.intersected()) {
updateHitTestResult(result, adjustedLocation.point());
if (result.addNodeToListBasedTestResult(node(), adjustedLocation,
regionResult) == StopHitTesting)
return true;
}
return false;
}
PositionWithAffinity LayoutInline::positionForPoint(const LayoutPoint& point) {
// FIXME: Does not deal with relative positioned inlines (should it?)
// If there are continuations, test them first because our containing block
// will not check them.
LayoutBoxModelObject* continuation = this->continuation();
while (continuation) {
if (continuation->isInline() || continuation->slowFirstChild())
return continuation->positionForPoint(point);
continuation = toLayoutBlockFlow(continuation)->inlineElementContinuation();
}
if (firstLineBoxIncludingCulling()) {
// This inline actually has a line box. We must have clicked in the
// border/padding of one of these boxes. We
// should try to find a result by asking our containing block.
return containingBlock()->positionForPoint(point);
}
return LayoutBoxModelObject::positionForPoint(point);
}
namespace {
class LinesBoundingBoxGeneratorContext {
public:
LinesBoundingBoxGeneratorContext(FloatRect& rect) : m_rect(rect) {}
void operator()(const FloatRect& rect) { m_rect.uniteIfNonZero(rect); }
void operator()(const LayoutRect& rect) { operator()(FloatRect(rect)); }
private:
FloatRect& m_rect;
};
} // unnamed namespace
LayoutRect LayoutInline::linesBoundingBox() const {
if (!alwaysCreateLineBoxes()) {
ASSERT(!firstLineBox());
FloatRect floatResult;
LinesBoundingBoxGeneratorContext context(floatResult);
generateCulledLineBoxRects(context, this);
return enclosingLayoutRect(floatResult);
}
LayoutRect result;
// See <rdar://problem/5289721>, for an unknown reason the linked list here is
// sometimes inconsistent, first is non-zero and last is zero. We have been
// unable to reproduce this at all (and consequently unable to figure ot why
// this is happening). The assert will hopefully catch the problem in debug
// builds and help us someday figure out why. We also put in a redundant
// check of lastLineBox() to avoid the crash for now.
ASSERT(!firstLineBox() ==
!lastLineBox()); // Either both are null or both exist.
if (firstLineBox() && lastLineBox()) {
// Return the width of the minimal left side and the maximal right side.
LayoutUnit logicalLeftSide;
LayoutUnit logicalRightSide;
for (InlineFlowBox* curr = firstLineBox(); curr;
curr = curr->nextLineBox()) {
if (curr == firstLineBox() || curr->logicalLeft() < logicalLeftSide)
logicalLeftSide = curr->logicalLeft();
if (curr == firstLineBox() || curr->logicalRight() > logicalRightSide)
logicalRightSide = curr->logicalRight();
}
bool isHorizontal = style()->isHorizontalWritingMode();
LayoutUnit x = isHorizontal ? logicalLeftSide : firstLineBox()->x();
LayoutUnit y = isHorizontal ? firstLineBox()->y() : logicalLeftSide;
LayoutUnit width = isHorizontal ? logicalRightSide - logicalLeftSide
: lastLineBox()->logicalBottom() - x;
LayoutUnit height = isHorizontal ? lastLineBox()->logicalBottom() - y
: logicalRightSide - logicalLeftSide;
result = LayoutRect(x, y, width, height);
}
return result;
}
InlineBox* LayoutInline::culledInlineFirstLineBox() const {
for (LayoutObject* curr = firstChild(); curr; curr = curr->nextSibling()) {
if (curr->isFloatingOrOutOfFlowPositioned())
continue;
// We want to get the margin box in the inline direction, and then use our
// font ascent/descent in the block direction (aligned to the root box's
// baseline).
if (curr->isBox())
return toLayoutBox(curr)->inlineBoxWrapper();
if (curr->isLayoutInline()) {
LayoutInline* currInline = toLayoutInline(curr);
InlineBox* result = currInline->firstLineBoxIncludingCulling();
if (result)
return result;
} else if (curr->isText()) {
LayoutText* currText = toLayoutText(curr);
if (currText->firstTextBox())
return currText->firstTextBox();
}
}
return nullptr;
}
InlineBox* LayoutInline::culledInlineLastLineBox() const {
for (LayoutObject* curr = lastChild(); curr; curr = curr->previousSibling()) {
if (curr->isFloatingOrOutOfFlowPositioned())
continue;
// We want to get the margin box in the inline direction, and then use our
// font ascent/descent in the block direction (aligned to the root box's
// baseline).
if (curr->isBox())
return toLayoutBox(curr)->inlineBoxWrapper();
if (curr->isLayoutInline()) {
LayoutInline* currInline = toLayoutInline(curr);
InlineBox* result = currInline->lastLineBoxIncludingCulling();
if (result)
return result;
} else if (curr->isText()) {
LayoutText* currText = toLayoutText(curr);
if (currText->lastTextBox())
return currText->lastTextBox();
}
}
return nullptr;
}
LayoutRect LayoutInline::culledInlineVisualOverflowBoundingBox() const {
FloatRect floatResult;
LinesBoundingBoxGeneratorContext context(floatResult);
generateCulledLineBoxRects(context, this);
LayoutRect result(enclosingLayoutRect(floatResult));
bool isHorizontal = style()->isHorizontalWritingMode();
for (LayoutObject* curr = firstChild(); curr; curr = curr->nextSibling()) {
if (curr->isFloatingOrOutOfFlowPositioned())
continue;
// For overflow we just have to propagate by hand and recompute it all.
if (curr->isBox()) {
LayoutBox* currBox = toLayoutBox(curr);
if (!currBox->hasSelfPaintingLayer() && currBox->inlineBoxWrapper()) {
LayoutRect logicalRect =
currBox->logicalVisualOverflowRectForPropagation(styleRef());
if (isHorizontal) {
logicalRect.moveBy(currBox->location());
result.uniteIfNonZero(logicalRect);
} else {
logicalRect.moveBy(currBox->location());
result.uniteIfNonZero(logicalRect.transposedRect());
}
}
} else if (curr->isLayoutInline()) {
// If the child doesn't need line boxes either, then we can recur.
LayoutInline* currInline = toLayoutInline(curr);
if (!currInline->alwaysCreateLineBoxes())
result.uniteIfNonZero(
currInline->culledInlineVisualOverflowBoundingBox());
else if (!currInline->hasSelfPaintingLayer())
result.uniteIfNonZero(currInline->visualOverflowRect());
} else if (curr->isText()) {
LayoutText* currText = toLayoutText(curr);
result.uniteIfNonZero(currText->visualOverflowRect());
}
}
return result;
}
LayoutRect LayoutInline::linesVisualOverflowBoundingBox() const {
if (!alwaysCreateLineBoxes())
return culledInlineVisualOverflowBoundingBox();
if (!firstLineBox() || !lastLineBox())
return LayoutRect();
// Return the width of the minimal left side and the maximal right side.
LayoutUnit logicalLeftSide = LayoutUnit::max();
LayoutUnit logicalRightSide = LayoutUnit::min();
for (InlineFlowBox* curr = firstLineBox(); curr; curr = curr->nextLineBox()) {
logicalLeftSide =
std::min(logicalLeftSide, curr->logicalLeftVisualOverflow());
logicalRightSide =
std::max(logicalRightSide, curr->logicalRightVisualOverflow());
}
RootInlineBox& firstRootBox = firstLineBox()->root();
RootInlineBox& lastRootBox = lastLineBox()->root();
LayoutUnit logicalTop =
firstLineBox()->logicalTopVisualOverflow(firstRootBox.lineTop());
LayoutUnit logicalWidth = logicalRightSide - logicalLeftSide;
LayoutUnit logicalHeight =
lastLineBox()->logicalBottomVisualOverflow(lastRootBox.lineBottom()) -
logicalTop;
LayoutRect rect(logicalLeftSide, logicalTop, logicalWidth, logicalHeight);
if (!style()->isHorizontalWritingMode())
rect = rect.transposedRect();
return rect;
}
LayoutRect LayoutInline::absoluteVisualRect() const {
if (!continuation()) {
LayoutRect rect = visualOverflowRect();
mapToVisualRectInAncestorSpace(view(), rect);
return rect;
}
FloatRect floatResult;
LinesBoundingBoxGeneratorContext context(floatResult);
LayoutInline* endContinuation = inlineElementContinuation();
while (LayoutInline* nextContinuation =
endContinuation->inlineElementContinuation())
endContinuation = nextContinuation;
for (LayoutBlock* currBlock = containingBlock();
currBlock && currBlock->isAnonymousBlock();
currBlock = toLayoutBlock(currBlock->nextSibling())) {
for (LayoutObject* curr = currBlock->firstChild(); curr;
curr = curr->nextSibling()) {
LayoutRect rect(curr->localVisualRect());
context(FloatRect(rect));
if (curr == endContinuation) {
LayoutRect rect(enclosingIntRect(floatResult));
mapToVisualRectInAncestorSpace(view(), rect);
return rect;
}
}
}
return LayoutRect();
}
LayoutRect LayoutInline::localVisualRect() const {
// If we don't create line boxes, we don't have any invalidations to do.
if (!alwaysCreateLineBoxes())
return LayoutRect();
if (style()->visibility() != EVisibility::kVisible)
return LayoutRect();
return visualOverflowRect();
}
LayoutRect LayoutInline::visualOverflowRect() const {
LayoutRect overflowRect = linesVisualOverflowBoundingBox();
LayoutUnit outlineOutset(style()->outlineOutsetExtent());
if (outlineOutset) {
Vector<LayoutRect> rects;
if (document().inNoQuirksMode()) {
// We have already included outline extents of line boxes in
// linesVisualOverflowBoundingBox(), so the following just add outline
// rects for children and continuations.
addOutlineRectsForChildrenAndContinuations(
rects, LayoutPoint(), outlineRectsShouldIncludeBlockVisualOverflow());
} else {
// In non-standard mode, because the difference in
// LayoutBlock::minLineHeightForReplacedObject(),
// linesVisualOverflowBoundingBox() may not cover outline rects of lines
// containing replaced objects.
addOutlineRects(rects, LayoutPoint(),
outlineRectsShouldIncludeBlockVisualOverflow());
}
if (!rects.isEmpty()) {
LayoutRect outlineRect = unionRectEvenIfEmpty(rects);
outlineRect.inflate(outlineOutset);
overflowRect.unite(outlineRect);
}
}
return overflowRect;
}
bool LayoutInline::mapToVisualRectInAncestorSpace(
const LayoutBoxModelObject* ancestor,
LayoutRect& rect,
VisualRectFlags visualRectFlags) const {
if (ancestor == this)
return true;
LayoutObject* container = this->container();
ASSERT(container == parent());
if (!container)
return true;
if (style()->hasInFlowPosition() && layer()) {
// Apply the in-flow position offset when invalidating a rectangle. The
// layer is translated, but the layout box isn't, so we need to do this to
// get the right dirty rect. Since this is called from LayoutObject::
// setStyle, the relative position flag on the LayoutObject has been
// cleared, so use the one on the style().
rect.move(layer()->offsetForInFlowPosition());
}
LayoutBox* containerBox =
container->isBox() ? toLayoutBox(container) : nullptr;
if (containerBox && container != ancestor &&
!containerBox->mapScrollingContentsRectToBoxSpace(rect, visualRectFlags))
return false;
// TODO(wkorman): Generalize Ruby specialization and/or document more clearly.
if (containerBox && !isRuby())
containerBox->flipForWritingMode(rect);
return container->mapToVisualRectInAncestorSpace(ancestor, rect,
visualRectFlags);
}
LayoutSize LayoutInline::offsetFromContainer(
const LayoutObject* container) const {
ASSERT(container == this->container());
LayoutSize offset;
if (isInFlowPositioned())
offset += offsetForInFlowPosition();
if (container->hasOverflowClip())
offset -= toLayoutBox(container)->scrolledContentOffset();
return offset;
}
PaintLayerType LayoutInline::layerTypeRequired() const {
return isInFlowPositioned() || createsGroup() || hasClipPath() ||
style()->shouldCompositeForCurrentAnimations() ||
style()->hasCompositorProxy() || style()->containsPaint()
? NormalPaintLayer
: NoPaintLayer;
}
void LayoutInline::childBecameNonInline(LayoutObject* child) {
// We have to split the parent flow.
LayoutBlockFlow* newBox =
toLayoutBlockFlow(containingBlock()->createAnonymousBlock());
LayoutBoxModelObject* oldContinuation = continuation();
setContinuation(newBox);
LayoutObject* beforeChild = child->nextSibling();
children()->removeChildNode(this, child);
splitFlow(beforeChild, newBox, child, oldContinuation);
}
void LayoutInline::updateHitTestResult(HitTestResult& result,
const LayoutPoint& point) {
if (result.innerNode())
return;
Node* n = node();
LayoutPoint localPoint(point);
if (n) {
if (isInlineElementContinuation()) {
// We're in the continuation of a split inline. Adjust our local point to
// be in the coordinate space of the principal layoutObject's containing
// block. This will end up being the innerNode.
LayoutBlock* firstBlock = n->layoutObject()->containingBlock();
// Get our containing block.
LayoutBox* block = containingBlock();
localPoint.moveBy(block->location() - firstBlock->locationOffset());
}
result.setNodeAndPosition(n, localPoint);
}
}
void LayoutInline::dirtyLineBoxes(bool fullLayout) {
if (fullLayout) {
m_lineBoxes.deleteLineBoxes();
return;
}
if (!alwaysCreateLineBoxes()) {
// We have to grovel into our children in order to dirty the appropriate
// lines.
for (LayoutObject* curr = firstChild(); curr; curr = curr->nextSibling()) {
if (curr->isFloatingOrOutOfFlowPositioned())
continue;
if (curr->isBox() && !curr->needsLayout()) {
LayoutBox* currBox = toLayoutBox(curr);
if (currBox->inlineBoxWrapper())
currBox->inlineBoxWrapper()->root().markDirty();
} else if (!curr->selfNeedsLayout()) {
if (curr->isLayoutInline()) {
LayoutInline* currInline = toLayoutInline(curr);
for (InlineFlowBox* childLine = currInline->firstLineBox(); childLine;
childLine = childLine->nextLineBox())
childLine->root().markDirty();
} else if (curr->isText()) {
LayoutText* currText = toLayoutText(curr);
for (InlineTextBox* childText = currText->firstTextBox(); childText;
childText = childText->nextTextBox())
childText->root().markDirty();
}
}
}
} else {
m_lineBoxes.dirtyLineBoxes();
}
}
InlineFlowBox* LayoutInline::createInlineFlowBox() {
return new InlineFlowBox(LineLayoutItem(this));
}
InlineFlowBox* LayoutInline::createAndAppendInlineFlowBox() {
setAlwaysCreateLineBoxes();
InlineFlowBox* flowBox = createInlineFlowBox();
m_lineBoxes.appendLineBox(flowBox);
return flowBox;
}
LayoutUnit LayoutInline::lineHeight(
bool firstLine,
LineDirectionMode /*direction*/,
LinePositionMode /*linePositionMode*/) const {
if (firstLine && document().styleEngine().usesFirstLineRules()) {
const ComputedStyle* s = style(firstLine);
if (s != style())
return LayoutUnit(s->computedLineHeight());
}
return LayoutUnit(style()->computedLineHeight());
}
int LayoutInline::baselinePosition(FontBaseline baselineType,
bool firstLine,
LineDirectionMode direction,
LinePositionMode linePositionMode) const {
ASSERT(linePositionMode == PositionOnContainingLine);
const SimpleFontData* fontData = style(firstLine)->font().primaryFont();
DCHECK(fontData);
if (!fontData)
return -1;
const FontMetrics& fontMetrics = fontData->getFontMetrics();
return (fontMetrics.ascent(baselineType) +
(lineHeight(firstLine, direction, linePositionMode) -
fontMetrics.height()) /
2)
.toInt();
}
LayoutSize LayoutInline::offsetForInFlowPositionedInline(
const LayoutBox& child) const {
// FIXME: This function isn't right with mixed writing modes.
ASSERT(isInFlowPositioned());
if (!isInFlowPositioned())
return LayoutSize();
// When we have an enclosing relpositioned inline, we need to add in the
// offset of the first line box from the rest of the content, but only in the
// cases where we know we're positioned relative to the inline itself.
LayoutSize logicalOffset;
LayoutUnit inlinePosition;
LayoutUnit blockPosition;
if (firstLineBox()) {
inlinePosition = firstLineBox()->logicalLeft();
blockPosition = firstLineBox()->logicalTop();
} else {
inlinePosition = layer()->staticInlinePosition();
blockPosition = layer()->staticBlockPosition();
}
// Per http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width an
// absolute positioned box with a static position should locate itself as
// though it is a normal flow box in relation to its containing block. If this
// relative-positioned inline has a negative offset we need to compensate for
// it so that we align the positioned object with the edge of its containing
// block.
if (child.style()->hasStaticInlinePosition(
style()->isHorizontalWritingMode()))
logicalOffset.setWidth(
std::max(LayoutUnit(), -offsetForInFlowPosition().width()));
else
logicalOffset.setWidth(inlinePosition);
if (!child.style()->hasStaticBlockPosition(
style()->isHorizontalWritingMode()))
logicalOffset.setHeight(blockPosition);
return style()->isHorizontalWritingMode() ? logicalOffset
: logicalOffset.transposedSize();
}
void LayoutInline::imageChanged(WrappedImagePtr, const IntRect*) {
if (!parent())
return;
// FIXME: We can do better.
setShouldDoFullPaintInvalidation();
}
namespace {
class AbsoluteLayoutRectsGeneratorContext {
public:
AbsoluteLayoutRectsGeneratorContext(Vector<LayoutRect>& rects,
const LayoutPoint& accumulatedOffset)
: m_rects(rects), m_accumulatedOffset(accumulatedOffset) {}
void operator()(const FloatRect& rect) { operator()(LayoutRect(rect)); }
void operator()(const LayoutRect& rect) {
LayoutRect layoutRect(rect);
layoutRect.moveBy(m_accumulatedOffset);
m_rects.push_back(layoutRect);
}
private:
Vector<LayoutRect>& m_rects;
const LayoutPoint& m_accumulatedOffset;
};
} // unnamed namespace
void LayoutInline::addOutlineRects(
Vector<LayoutRect>& rects,
const LayoutPoint& additionalOffset,
IncludeBlockVisualOverflowOrNot includeBlockOverflows) const {
AbsoluteLayoutRectsGeneratorContext context(rects, additionalOffset);
generateLineBoxRects(context);
addOutlineRectsForChildrenAndContinuations(rects, additionalOffset,
includeBlockOverflows);
}
void LayoutInline::addOutlineRectsForChildrenAndContinuations(
Vector<LayoutRect>& rects,
const LayoutPoint& additionalOffset,
IncludeBlockVisualOverflowOrNot includeBlockOverflows) const {
addOutlineRectsForNormalChildren(rects, additionalOffset,
includeBlockOverflows);
addOutlineRectsForContinuations(rects, additionalOffset,
includeBlockOverflows);
}
void LayoutInline::addOutlineRectsForContinuations(
Vector<LayoutRect>& rects,
const LayoutPoint& additionalOffset,
IncludeBlockVisualOverflowOrNot includeBlockOverflows) const {
if (LayoutBoxModelObject* continuation = this->continuation()) {
if (continuation->isInline())
continuation->addOutlineRects(
rects,
additionalOffset + (continuation->containingBlock()->location() -
containingBlock()->location()),
includeBlockOverflows);
else
continuation->addOutlineRects(
rects, additionalOffset + (toLayoutBox(continuation)->location() -
containingBlock()->location()),
includeBlockOverflows);
}
}
FloatRect LayoutInline::localBoundingBoxRectForAccessibility() const {
Vector<LayoutRect> rects;
addOutlineRects(rects, LayoutPoint(), IncludeBlockVisualOverflow);
return FloatRect(unionRect(rects));
}
void LayoutInline::computeSelfHitTestRects(
Vector<LayoutRect>& rects,
const LayoutPoint& layerOffset) const {
AbsoluteLayoutRectsGeneratorContext context(rects, layerOffset);
generateLineBoxRects(context);
}
void LayoutInline::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions) {
// Convert the style regions to absolute coordinates.
if (style()->visibility() != EVisibility::kVisible)
return;
if (style()->getDraggableRegionMode() == DraggableRegionNone)
return;
AnnotatedRegionValue region;
region.draggable = style()->getDraggableRegionMode() == DraggableRegionDrag;
region.bounds = LayoutRect(linesBoundingBox());
LayoutObject* container = containingBlock();
if (!container)
container = this;
FloatPoint absPos = container->localToAbsolute();
region.bounds.setX(LayoutUnit(absPos.x() + region.bounds.x()));
region.bounds.setY(LayoutUnit(absPos.y() + region.bounds.y()));
regions.push_back(region);
}
void LayoutInline::invalidateDisplayItemClients(
PaintInvalidationReason invalidationReason) const {
ObjectPaintInvalidator paintInvalidator(*this);
paintInvalidator.invalidateDisplayItemClient(*this, invalidationReason);
for (InlineFlowBox* box = firstLineBox(); box; box = box->nextLineBox())
paintInvalidator.invalidateDisplayItemClient(*box, invalidationReason);
}
// TODO(lunalu): Not to just dump 0, 0 as the x and y here
LayoutRect LayoutInline::debugRect() const {
IntRect linesBox = enclosingIntRect(linesBoundingBox());
return LayoutRect(IntRect(0, 0, linesBox.width(), linesBox.height()));
}
} // namespace blink
| 20,185 |
349 |
<reponame>mapoto/alexa-skills-kit-sdk-for-java
/*
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
the specific language governing permissions and limitations under the License.
*/
package com.amazon.ask.response.template.loader.impl;
import static org.slf4j.LoggerFactory.getLogger;
import com.amazon.ask.response.template.TemplateContentData;
import com.amazon.ask.response.template.loader.TemplateCache;
import org.slf4j.Logger;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
/**
* {@inheritDoc}.
*
* {@link TemplateCache} implementation to cache {@link TemplateContentData} using LRU replacement policy based on access order.
* If no capacity specified, use default value of 5 MB.
* If no time to live threshold specified, use default value of 1 day.
*/
public class ConcurrentLRUTemplateCache implements TemplateCache {
/**
* Default cache capacity.
*/
private static final long DEFAULT_CAPACITY = 1000 * 1000 * 5;
/**
* Default TTL for a cache entry.
*/
private static final long DEFAULT_TIME_TO_LIVE_THRESHOLD = 1000 * 60 * 60 * 24;
/**
* Initial cache queue capacity.
*/
private static final int INITIAL_QUEUE_CAPACITY = 11;
/**
* Logger to log information used for debugging purposes.
*/
private static final Logger LOGGER = getLogger(ConcurrentLRUTemplateCache.class);
/**
* Custom capacity.
*/
protected final long capacity;
/**
* Custom TTL.
*/
protected final long timeToLiveThreshold;
/**
* Template data map.
*/
protected final Map<String, AccessOrderedTemplateContentData> templateDataMap;
/**
* Template order queue.
*/
protected final Queue<AccessOrderedTemplateContentData> templateOrderQueue;
/**
* Counter to estimate current cache occupancy.
*/
private AtomicInteger capacityCounter;
/**
* Map to store locks on cache units.
*/
private Map<String, Object> locksMap;
/**
* Constructor for ConcurrentLRUTemplateCache.
* @param capacity custom capacity.
* @param timeToLiveThreshold custom TTL.
*/
protected ConcurrentLRUTemplateCache(final long capacity, final long timeToLiveThreshold) {
this.capacity = capacity;
this.timeToLiveThreshold = timeToLiveThreshold;
this.templateDataMap = new ConcurrentHashMap<>();
this.templateOrderQueue = new PriorityBlockingQueue<>(INITIAL_QUEUE_CAPACITY,
(AccessOrderedTemplateContentData data1, AccessOrderedTemplateContentData data2) ->
(int) (data1.getAccessTimestamp() - data2.getAccessTimestamp()));
this.capacityCounter = new AtomicInteger(0);
this.locksMap = new ConcurrentHashMap<>();
}
/**
* Static method which builds an instance of Builder.
* @return {@link Builder}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Get cache size.
*
* @return cache size
*/
public int size() {
int cacheSize = templateDataMap.size();
return cacheSize;
}
/**
* Check whether cache is empty.
*
* @return true if cache is empty
*/
public boolean isEmpty() {
return templateDataMap.isEmpty();
}
/**
* Get cache current capacity.
* @return cache current capacity
*/
public int getCurrentCapacity() {
return this.capacityCounter.get();
}
/**
* {@inheritDoc}
*
* If template size is larger than total cache capacity, no caching.
* If there's not enough capacity for new entry, remove eldest ones until have capacity to insert.
*/
@Override
synchronized public void put(final String identifier, final TemplateContentData templateContentData) {
if (!locksMap.containsKey(identifier)) {
locksMap.put(identifier, new Object());
}
Object lock = locksMap.get(identifier);
synchronized (lock) {
int size = templateContentData.getTemplateContent().length;
if (size > capacity) {
LOGGER.warn(String.format("No caching for template with size: %s larger than total capacity: %s.", size, capacity));
return;
}
if (templateDataMap.containsKey(identifier)) {
LOGGER.info(String.format("Try to put the same template with identifier: %s into cache, removing duplicate entry in queue.",
identifier));
templateOrderQueue.remove(templateDataMap.get(identifier));
}
while (size + capacityCounter.get() > capacity) {
AccessOrderedTemplateContentData eldest = templateOrderQueue.poll();
TemplateContentData eldestTemplate = eldest.getTemplateContentData();
templateDataMap.remove(eldestTemplate.getIdentifier());
deductAndGet(eldestTemplate.getTemplateContent().length);
}
AccessOrderedTemplateContentData data = AccessOrderedTemplateContentData.builder()
.withTemplateContentData(templateContentData)
.build();
templateOrderQueue.offer(data);
templateDataMap.put(identifier, data);
capacityCounter.addAndGet(size);
}
}
/**
* {@inheritDoc}
*
* @return {@link TemplateContentData} if exists and it is fresh, otherwise return null
*/
@Override
public TemplateContentData get(final String identifier) {
Object lock = locksMap.get(identifier);
if (lock != null) {
synchronized (lock) {
AccessOrderedTemplateContentData data = templateDataMap.get(identifier);
if ((data != null) && templateOrderQueue.contains(data)) {
templateOrderQueue.remove(data);
if (isFresh(data)) {
TemplateContentData templateContentData = data.getTemplateContentData();
templateOrderQueue.offer(data);
return templateContentData;
}
templateDataMap.remove(identifier);
deductAndGet(data.getTemplateContentData().getTemplateContent().length);
LOGGER.warn(String.format("Template: %s is out of date, removing.", identifier));
}
}
}
return null;
}
/**
* Validates a cache entry.
* @param data Template content data.
* @return true is a cache entry is valid.
*/
private boolean isFresh(final AccessOrderedTemplateContentData data) {
long current = System.currentTimeMillis();
long dataTimestamp = data.getAccessTimestamp();
return (current - dataTimestamp) < timeToLiveThreshold;
}
/**
* Get current cache remaining capacity.
* @param delta difference between initial size and current size.
* @return remaining capacity.
*/
private int deductAndGet(final int delta) {
return capacityCounter.addAndGet(Math.negateExact(delta));
}
/**
* Concurrent LRU Template Cache Builder.
*/
public static class Builder {
/**
* Custom cache capacity.
*/
private long capacity = DEFAULT_CAPACITY;
/**
* Custom TTL.
*/
private long timeToLiveThreshold = DEFAULT_TIME_TO_LIVE_THRESHOLD;
/**
* Add custom cache capacity to ConcurrentLRUTemplateCache.
* @param capacity custom capacity.
* @return {@link Builder}.
*/
public Builder withCapacity(final long capacity) {
this.capacity = capacity;
return this;
}
/**
* Add custom TTL to ConcurrentLRUTemplateCache.
* @param liveTimeThreshold custom TTL.
* @return {@link Builder}.
*/
public Builder withLiveTimeThreshold(final long liveTimeThreshold) {
this.timeToLiveThreshold = liveTimeThreshold;
return this;
}
/**
* Builder method to build an instance of ConcurrentLRUTemplateCache.
* @return {@link ConcurrentLRUTemplateCache}.
*/
public ConcurrentLRUTemplateCache build() {
return new ConcurrentLRUTemplateCache(this.capacity, this.timeToLiveThreshold);
}
}
}
| 3,516 |
2,486 |
<reponame>priya1puresoftware/python-slack-sdk
import json
from typing import Optional, Dict, Any, Sequence
from urllib.parse import parse_qsl
def parse_body(body: str, content_type: Optional[str]) -> Dict[str, Any]:
if not body:
return {}
if (
content_type is not None and content_type == "application/json"
) or body.startswith("{"):
return json.loads(body)
else:
if "payload" in body: # This is not JSON format yet
params = dict(parse_qsl(body))
if params.get("payload") is not None:
return json.loads(params.get("payload"))
else:
return {}
else:
return dict(parse_qsl(body))
def extract_is_enterprise_install(payload: Dict[str, Any]) -> Optional[bool]:
if "is_enterprise_install" in payload:
is_enterprise_install = payload.get("is_enterprise_install")
return is_enterprise_install is not None and (
is_enterprise_install is True or is_enterprise_install == "true"
)
return False
def extract_enterprise_id(payload: Dict[str, Any]) -> Optional[str]:
if payload.get("enterprise") is not None:
org = payload.get("enterprise")
if isinstance(org, str):
return org
elif "id" in org:
return org.get("id") # type: ignore
if payload.get("authorizations") is not None and len(payload["authorizations"]) > 0:
# To make Events API handling functioning also for shared channels,
# we should use .authorizations[0].enterprise_id over .enterprise_id
return extract_enterprise_id(payload["authorizations"][0])
if "enterprise_id" in payload:
return payload.get("enterprise_id")
if payload.get("team") is not None and "enterprise_id" in payload["team"]:
# In the case where the type is view_submission
return payload["team"].get("enterprise_id")
if payload.get("event") is not None:
return extract_enterprise_id(payload["event"])
return None
def extract_team_id(payload: Dict[str, Any]) -> Optional[str]:
if payload.get("team") is not None:
team = payload.get("team")
if isinstance(team, str):
return team
elif team and "id" in team:
return team.get("id")
if payload.get("authorizations") is not None and len(payload["authorizations"]) > 0:
# To make Events API handling functioning also for shared channels,
# we should use .authorizations[0].team_id over .team_id
return extract_team_id(payload["authorizations"][0])
if "team_id" in payload:
return payload.get("team_id")
if payload.get("event") is not None:
return extract_team_id(payload["event"])
if payload.get("user") is not None:
return payload.get("user")["team_id"]
return None
def extract_user_id(payload: Dict[str, Any]) -> Optional[str]:
if payload.get("user") is not None:
user = payload.get("user")
if isinstance(user, str):
return user
elif "id" in user:
return user.get("id") # type: ignore
if "user_id" in payload:
return payload.get("user_id")
if payload.get("event") is not None:
return extract_user_id(payload["event"])
return None
def extract_content_type(headers: Dict[str, Sequence[str]]) -> Optional[str]:
content_type: Optional[str] = headers.get("content-type", [None])[0]
if content_type:
return content_type.split(";")[0]
return None
| 1,440 |
1,540 |
package test.retryAnalyzer.issue2148;
import static org.assertj.core.api.Assertions.assertThat;
import org.testng.TestNG;
import org.testng.annotations.Test;
import org.testng.xml.XmlSuite.FailurePolicy;
import test.SimpleBaseTest;
public class IssueTest extends SimpleBaseTest {
@Test(description = "GITHUB-2148")
public void ensureTestsAreRetriedWhenConfigFailurePolicySetToContinue() {
TestNG testng = create(ExceptionAfterMethodTestSample.class);
testng.setConfigFailurePolicy(FailurePolicy.CONTINUE);
testng.run();
String[] expected =
new String[] {
"Before Method [testMethod] #1",
"Test Method [testMethod] #1",
"Before Method [testMethod] #1",
"Before Method [testMethod] #2",
"Test Method [testMethod] #2",
"Before Method [testMethod] #2"
};
assertThat(ExceptionAfterMethodTestSample.logs).containsExactly(expected);
}
}
| 349 |
617 |
<reponame>qinFamily/Oceanus
/**
* Copyright 2011-2013 FoundationDB, 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.
*/
/* The original from which this derives bore the following: */
/*
Derby - Class org.apache.derby.impl.sql.compile.ConcatenationOperatorNode
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.bj58.sql.parser;
import com.bj58.sql.types.ValueClassName;
/**
* This node represents a concatenation operator
*
*/
public class ConcatenationOperatorNode extends BinaryOperatorNode
{
/**
* Initializer for a ConcatenationOperatorNode
*
* @param leftOperand
* The left operand of the concatenation
* @param rightOperand
* The right operand of the concatenation
*/
public void init(Object leftOperand, Object rightOperand) {
super.init(leftOperand, rightOperand, "||", "concatenate",
ValueClassName.ConcatableDataValue, ValueClassName.ConcatableDataValue);
}
}
| 672 |
60,067 |
#include <ATen/native/vulkan/ops/Common.h>
namespace at {
namespace native {
namespace vulkan {
namespace ops {
uint32_t batch_size(const Tensor& tensor) {
const IntArrayRef sizes = tensor.sizes();
const uint32_t dims = sizes.size();
if (dims < 4) {
return 1;
}
return sizes[dims - 4];
}
uint32_t channels_size(const Tensor& tensor) {
const IntArrayRef sizes = tensor.sizes();
const uint32_t dims = sizes.size();
if (dims < 3) {
return 1;
}
return sizes[dims - 3];
}
uint32_t height_size(const Tensor& tensor) {
const IntArrayRef sizes = tensor.sizes();
const uint32_t dims = sizes.size();
if (dims < 2) {
return 1;
}
return sizes[dims - 2];
}
uint32_t width_size(const Tensor& tensor) {
const IntArrayRef sizes = tensor.sizes();
const uint32_t dims = sizes.size();
if (dims < 1) {
return 1;
}
return sizes[dims - 1];
}
api::Shader::WorkGroup adaptive_work_group_size(const api::Shader::WorkGroup& global_work_group) {
api::Shader::WorkGroup local_group_size = {4, 4, 4};
if (global_work_group.data[2u] == 1) {
if (global_work_group.data[1u] < 8) {
local_group_size.data[0u] = 16;
local_group_size.data[1u] = 4;
local_group_size.data[2u] = 1;
}
else {
local_group_size.data[0u] = 8;
local_group_size.data[1u] = 8;
local_group_size.data[2u] = 1;
}
}
return local_group_size;
}
} // namespace ops
} // namespace vulkan
} // namespace native
} // namespace at
| 619 |
1,682 |
/*
Copyright (c) 2012 LinkedIn Corp.
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.
*/
/**
* $Id: $
*/
package com.linkedin.restli.client;
import com.linkedin.common.callback.Callback;
import com.linkedin.common.callback.FutureCallback;
import com.linkedin.common.util.None;
import com.linkedin.data.DataMap;
import com.linkedin.data.template.RecordTemplate;
import com.linkedin.r2.RemoteInvocationException;
import com.linkedin.r2.message.RequestContext;
import com.linkedin.r2.message.rest.RestException;
import com.linkedin.r2.message.rest.RestRequest;
import com.linkedin.r2.message.rest.RestResponse;
import com.linkedin.r2.message.rest.RestResponseBuilder;
import com.linkedin.r2.transport.common.Client;
import com.linkedin.restli.common.ContentType;
import com.linkedin.restli.common.EmptyRecord;
import com.linkedin.restli.common.ErrorDetails;
import com.linkedin.restli.common.ErrorResponse;
import com.linkedin.restli.common.ProtocolVersion;
import com.linkedin.restli.common.ResourceSpecImpl;
import com.linkedin.restli.common.RestConstants;
import com.linkedin.restli.internal.client.EntityResponseDecoder;
import com.linkedin.restli.internal.common.AllProtocolVersions;
import com.linkedin.restli.internal.common.DataMapConverter;
import com.linkedin.restli.internal.common.TestConstants;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.activation.MimeTypeParseException;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* @author <NAME>
* @version $Revision: $
*/
public class RestClientTest
{
private static final RequestContext DEFAULT_REQUEST_CONTEXT = new RequestContext();
static
{
DEFAULT_REQUEST_CONTEXT.putLocalAttr("__attr1", "1");
}
@SuppressWarnings("deprecation")
@Test
public void testEmptyErrorResponse()
{
RestResponse response = new RestResponseBuilder().setStatus(200).build();
RestLiResponseException e = new RestLiResponseException(response, null, new ErrorResponse());
Assert.assertNull(e.getServiceErrorMessage());
Assert.assertNull(e.getErrorDetails());
Assert.assertNull(e.getErrorDetailsRecord());
Assert.assertNull(e.getErrorSource());
Assert.assertFalse(e.hasServiceErrorCode());
Assert.assertNull(e.getServiceErrorStackTrace());
Assert.assertNull(e.getServiceExceptionClass());
Assert.assertNull(e.getCode());
Assert.assertNull(e.getDocUrl());
Assert.assertNull(e.getRequestId());
Assert.assertNull(e.getErrorDetailType());
}
@Test
public void testShutdown()
{
Client client = EasyMock.createMock(Client.class);
@SuppressWarnings("unchecked")
Callback<None> callback = EasyMock.createMock(Callback.class);
Capture<Callback<None>> callbackCapture = EasyMock.newCapture();
// Underlying client's shutdown should be invoked with correct callback
client.shutdown(EasyMock.capture(callbackCapture));
EasyMock.replay(client);
// No methods should be invoked on the callback
EasyMock.replay(callback);
RestClient restClient = new RestClient(client, "d2://");
restClient.shutdown(callback);
EasyMock.verify(client);
EasyMock.verify(callback);
EasyMock.reset(callback);
None none = None.none();
callback.onSuccess(none);
EasyMock.replay(callback);
Callback<None> captured = callbackCapture.getValue();
captured.onSuccess(none);
EasyMock.verify(callback);
}
private enum SendRequestOption
{
REQUEST_NO_CONTEXT(false, false),
REQUEST_WITH_CONTEXT(false, true),
REQUESTBUILDER_NO_CONTEXT(true, false),
REQUESTBUILDER_WITH_CONTEXT(true, true);
private SendRequestOption(boolean requestBuilder, boolean context)
{
_requestBuilder = requestBuilder;
_context = context;
}
private final boolean _requestBuilder;
private final boolean _context;
}
private enum GetResponseOption
{
GET,
GET_RESPONSE,
GET_RESPONSE_EXPLICIT_NO_THROW,
GET_RESPONSE_EXPLICIT_THROW,
GET_RESPONSE_ENTITY,
GET_RESPONSE_ENTITY_EXPLICIT_NO_THROW,
GET_RESPONSE_ENTITY_EXPLICIT_THROW,
}
private enum TimeoutOption
{
NO_TIMEOUT(null, null),
THIRTY_SECONDS(30L, TimeUnit.SECONDS);
private TimeoutOption(Long l, TimeUnit timeUnit)
{
_l = l;
_timeUnit = timeUnit;
}
private final Long _l;
private final TimeUnit _timeUnit;
}
private enum ContentTypeOption
{
JSON(ContentType.JSON),
LICOR_TEXT(ContentType.LICOR_TEXT),
LICOR_BINARY(ContentType.LICOR_BINARY),
PROTOBUF(ContentType.PROTOBUF),
PROTOBUF2(ContentType.PROTOBUF2),
PSON(ContentType.PSON),
SMILE(ContentType.SMILE);
ContentTypeOption(ContentType contentType)
{
_contentType = contentType;
}
private final ContentType _contentType;
}
@DataProvider(name = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestOptions")
private Object[][] sendRequestOptions()
{
Object[][] result = new Object[SendRequestOption.values().length *
TimeoutOption.values().length *
ContentTypeOption.values().length *
2][];
int i = 0;
for (SendRequestOption sendRequestOption : SendRequestOption.values())
{
for (TimeoutOption timeoutOption : TimeoutOption.values())
{
for (ContentTypeOption contentTypeOption : ContentTypeOption.values())
{
result[i++] = new Object[] {
sendRequestOption,
timeoutOption,
ProtocolVersionOption.USE_LATEST_IF_AVAILABLE,
AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(),
RestConstants.HEADER_LINKEDIN_ERROR_RESPONSE,
contentTypeOption._contentType
};
result[i++] = new Object[] {
sendRequestOption,
timeoutOption,
ProtocolVersionOption.FORCE_USE_NEXT,
AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion(),
RestConstants.HEADER_RESTLI_ERROR_RESPONSE,
contentTypeOption._contentType
};
}
}
}
return result;
}
@DataProvider(name = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestAndGetResponseOptions")
private Object[][] sendRequestAndGetResponseOptions()
{
Object[][] result = new Object[SendRequestOption.values().length *
GetResponseOption.values().length *
TimeoutOption.values().length *
ContentTypeOption.values().length *
2][];
int i = 0;
for (SendRequestOption sendRequestOption : SendRequestOption.values())
{
for (GetResponseOption getResponseOption : GetResponseOption.values() )
{
for (TimeoutOption timeoutOption : TimeoutOption.values())
{
for (ContentTypeOption contentTypeOption : ContentTypeOption.values())
{
result[i++] = new Object[]{
sendRequestOption,
getResponseOption,
timeoutOption,
ProtocolVersionOption.USE_LATEST_IF_AVAILABLE,
AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(),
RestConstants.HEADER_LINKEDIN_ERROR_RESPONSE,
contentTypeOption._contentType};
result[i++] =
new Object[]{
sendRequestOption,
getResponseOption,
timeoutOption,
ProtocolVersionOption.FORCE_USE_NEXT,
AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion(),
RestConstants.HEADER_RESTLI_ERROR_RESPONSE,
contentTypeOption._contentType};
}
}
}
}
return result;
}
@DataProvider(name = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestAndNoThrowGetResponseOptions")
private Object[][] sendRequestAndNoThrowGetResponseOptions()
{
Object[][] result = new Object[SendRequestOption.values().length *
TimeoutOption.values().length *
ContentTypeOption.values().length *
4][];
int i = 0;
for (SendRequestOption sendRequestOption : SendRequestOption.values())
{
for (TimeoutOption timeoutOption : TimeoutOption.values())
{
for (ContentTypeOption contentTypeOption : ContentTypeOption.values())
{
result[i++] = new Object[] {
sendRequestOption,
GetResponseOption.GET_RESPONSE_ENTITY_EXPLICIT_NO_THROW,
timeoutOption,
ProtocolVersionOption.USE_LATEST_IF_AVAILABLE,
AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(),
RestConstants.HEADER_LINKEDIN_ERROR_RESPONSE,
contentTypeOption._contentType
};
result[i++] = new Object[] {
sendRequestOption,
GetResponseOption.GET_RESPONSE_ENTITY_EXPLICIT_NO_THROW,
timeoutOption,
ProtocolVersionOption.FORCE_USE_NEXT,
AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion(),
RestConstants.HEADER_RESTLI_ERROR_RESPONSE,
contentTypeOption._contentType
};
result[i++] = new Object[] {
sendRequestOption,
GetResponseOption.GET_RESPONSE_EXPLICIT_NO_THROW,
timeoutOption,
ProtocolVersionOption.USE_LATEST_IF_AVAILABLE,
AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(),
RestConstants.HEADER_LINKEDIN_ERROR_RESPONSE,
contentTypeOption._contentType
};
result[i++] = new Object[] {
sendRequestOption,
GetResponseOption.GET_RESPONSE_EXPLICIT_NO_THROW,
timeoutOption,
ProtocolVersionOption.FORCE_USE_NEXT,
AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion(),
RestConstants.HEADER_RESTLI_ERROR_RESPONSE,
contentTypeOption._contentType
};
}
}
}
return result;
}
@SuppressWarnings("deprecation")
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestAndGetResponseOptions")
public void testRestLiResponseFuture(SendRequestOption sendRequestOption,
GetResponseOption getResponseOption,
TimeoutOption timeoutOption,
ProtocolVersionOption versionOption,
ProtocolVersion protocolVersion,
String errorResponseHeaderName,
ContentType contentType)
throws ExecutionException, RemoteInvocationException,
TimeoutException, InterruptedException, IOException
{
final String ERR_KEY = "someErr";
final String ERR_VALUE = "WHOOPS!";
final String ERR_MSG = "whoops2";
final int HTTP_CODE = 200;
final int APP_CODE = 666;
final String CODE = "INVALID_INPUT";
final String DOC_URL = "https://example.com/errors/invalid-input";
final String REQUEST_ID = "abc123";
RestClient client = mockClient(ERR_KEY, ERR_VALUE, ERR_MSG, HTTP_CODE, APP_CODE, CODE, DOC_URL, REQUEST_ID,
protocolVersion, errorResponseHeaderName);
Request<ErrorResponse> request = mockRequest(ErrorResponse.class, versionOption, contentType);
RequestBuilder<Request<ErrorResponse>> requestBuilder = mockRequestBuilder(request);
ResponseFuture<ErrorResponse> future = sendRequest(sendRequestOption,
determineErrorHandlingBehavior(getResponseOption),
client,
request,
requestBuilder);
Response<ErrorResponse> response = getOkResponse(getResponseOption, future, timeoutOption);
ErrorResponse e = response.getEntity();
Assert.assertNull(response.getError());
Assert.assertFalse(response.hasError());
Assert.assertEquals(HTTP_CODE, response.getStatus());
Assert.assertEquals(ERR_VALUE, e.getErrorDetails().data().getString(ERR_KEY));
Assert.assertEquals(APP_CODE, e.getServiceErrorCode().intValue());
Assert.assertEquals(ERR_MSG, e.getMessage());
Assert.assertEquals(CODE, e.getCode());
Assert.assertEquals(DOC_URL, e.getDocUrl());
Assert.assertEquals(REQUEST_ID, e.getRequestId());
Assert.assertEquals(EmptyRecord.class.getCanonicalName(), e.getErrorDetailType());
}
@SuppressWarnings("deprecation")
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestAndGetResponseOptions")
public void testRestLiResponseExceptionFuture(SendRequestOption sendRequestOption,
GetResponseOption getResponseOption,
TimeoutOption timeoutOption,
ProtocolVersionOption versionOption,
ProtocolVersion protocolVersion,
String errorResponseHeaderName,
ContentType contentType)
throws RemoteInvocationException, TimeoutException, InterruptedException, IOException
{
final String ERR_KEY = "someErr";
final String ERR_VALUE = "WHOOPS!";
final String ERR_MSG = "whoops2";
final int HTTP_CODE = 400;
final int APP_CODE = 666;
final String CODE = "INVALID_INPUT";
final String DOC_URL = "https://example.com/errors/invalid-input";
final String REQUEST_ID = "abc123";
RestClient client = mockClient(ERR_KEY, ERR_VALUE, ERR_MSG, HTTP_CODE, APP_CODE, CODE, DOC_URL, REQUEST_ID,
protocolVersion, errorResponseHeaderName);
Request<EmptyRecord> request = mockRequest(EmptyRecord.class, versionOption, contentType);
RequestBuilder<Request<EmptyRecord>> requestBuilder = mockRequestBuilder(request);
ResponseFuture<EmptyRecord> future = sendRequest(sendRequestOption,
determineErrorHandlingBehavior(getResponseOption),
client,
request,
requestBuilder);
RestLiResponseException e = getErrorResponse(getResponseOption, future, timeoutOption);
if (getResponseOption == GetResponseOption.GET_RESPONSE_ENTITY_EXPLICIT_NO_THROW)
{
Assert.assertNull(e);
}
else
{
Assert.assertEquals(HTTP_CODE, e.getStatus());
Assert.assertEquals(ERR_VALUE, e.getErrorDetails().get(ERR_KEY));
Assert.assertEquals(APP_CODE, e.getServiceErrorCode());
Assert.assertEquals(ERR_MSG, e.getServiceErrorMessage());
Assert.assertEquals(CODE, e.getCode());
Assert.assertEquals(DOC_URL, e.getDocUrl());
Assert.assertEquals(REQUEST_ID, e.getRequestId());
Assert.assertEquals(EmptyRecord.class.getCanonicalName(), e.getErrorDetailType());
Assert.assertNotNull(e.getErrorDetailsRecord());
Assert.assertTrue(e.getErrorDetailsRecord() instanceof EmptyRecord);
}
}
@SuppressWarnings("deprecation")
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestAndNoThrowGetResponseOptions")
public void testRestLiResponseExceptionFutureNoThrow(SendRequestOption sendRequestOption,
GetResponseOption getResponseOption,
TimeoutOption timeoutOption,
ProtocolVersionOption versionOption,
ProtocolVersion protocolVersion,
String errorResponseHeaderName,
ContentType contentType)
throws RemoteInvocationException, ExecutionException, TimeoutException, InterruptedException, IOException
{
final String ERR_KEY = "someErr";
final String ERR_VALUE = "WHOOPS!";
final String ERR_MSG = "whoops2";
final int HTTP_CODE = 400;
final int APP_CODE = 666;
final String CODE = "INVALID_INPUT";
final String DOC_URL = "https://example.com/errors/invalid-input";
final String REQUEST_ID = "abc123";
RestClient client = mockClient(ERR_KEY, ERR_VALUE, ERR_MSG, HTTP_CODE, APP_CODE, CODE, DOC_URL, REQUEST_ID,
protocolVersion, errorResponseHeaderName);
Request<EmptyRecord> request = mockRequest(EmptyRecord.class, versionOption, contentType);
RequestBuilder<Request<EmptyRecord>> requestBuilder = mockRequestBuilder(request);
ResponseFuture<EmptyRecord> future = sendRequest(sendRequestOption,
determineErrorHandlingBehavior(getResponseOption),
client,
request,
requestBuilder);
Response<EmptyRecord> response = getOkResponse(getResponseOption, future, timeoutOption);
Assert.assertTrue(response.hasError());
RestLiResponseException e = response.getError();
Assert.assertNotNull(e);
Assert.assertEquals(HTTP_CODE, e.getStatus());
Assert.assertEquals(ERR_VALUE, e.getErrorDetails().get(ERR_KEY));
Assert.assertEquals(APP_CODE, e.getServiceErrorCode());
Assert.assertEquals(ERR_MSG, e.getServiceErrorMessage());
Assert.assertEquals(CODE, e.getCode());
Assert.assertEquals(DOC_URL, e.getDocUrl());
Assert.assertEquals(REQUEST_ID, e.getRequestId());
Assert.assertEquals(EmptyRecord.class.getCanonicalName(), e.getErrorDetailType());
Assert.assertNotNull(e.getErrorDetailsRecord());
Assert.assertTrue(e.getErrorDetailsRecord() instanceof EmptyRecord);
}
@SuppressWarnings("deprecation")
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestOptions")
public void testRestLiResponseExceptionCallback(SendRequestOption option,
TimeoutOption timeoutOption,
ProtocolVersionOption versionOption,
ProtocolVersion protocolVersion,
String errorResponseHeaderName,
ContentType contentType)
throws ExecutionException, TimeoutException, InterruptedException, RestLiDecodingException
{
final String ERR_KEY = "someErr";
final String ERR_VALUE = "WHOOPS!";
final String ERR_MSG = "whoops2";
final int HTTP_CODE = 400;
final int APP_CODE = 666;
final String CODE = "INVALID_INPUT";
final String DOC_URL = "https://example.com/errors/invalid-input";
final String REQUEST_ID = "abc123";
RestClient client = mockClient(ERR_KEY, ERR_VALUE, ERR_MSG, HTTP_CODE, APP_CODE, CODE, DOC_URL, REQUEST_ID,
protocolVersion, errorResponseHeaderName);
Request<EmptyRecord> request = mockRequest(EmptyRecord.class, versionOption, contentType);
RequestBuilder<Request<EmptyRecord>> requestBuilder = mockRequestBuilder(request);
FutureCallback<Response<EmptyRecord>> callback = new FutureCallback<>();
try
{
sendRequest(option, client, request, requestBuilder, callback);
Long l = timeoutOption._l;
TimeUnit timeUnit = timeoutOption._timeUnit;
Response<EmptyRecord> response = l == null ? callback.get() : callback.get(l, timeUnit);
Assert.fail("Should have thrown");
}
catch (ExecutionException e)
{
// New
Throwable cause = e.getCause();
Assert.assertTrue(cause instanceof RestLiResponseException, "Expected RestLiResponseException not " + cause.getClass().getName());
RestLiResponseException rlre = (RestLiResponseException)cause;
Assert.assertEquals(HTTP_CODE, rlre.getStatus());
Assert.assertEquals(ERR_VALUE, rlre.getErrorDetails().get(ERR_KEY));
Assert.assertEquals(APP_CODE, rlre.getServiceErrorCode());
Assert.assertEquals(ERR_MSG, rlre.getServiceErrorMessage());
Assert.assertEquals(CODE, rlre.getCode());
Assert.assertEquals(DOC_URL, rlre.getDocUrl());
Assert.assertEquals(REQUEST_ID, rlre.getRequestId());
Assert.assertEquals(EmptyRecord.class.getCanonicalName(), rlre.getErrorDetailType());
Assert.assertNotNull(rlre.getErrorDetailsRecord());
Assert.assertTrue(rlre.getErrorDetailsRecord() instanceof EmptyRecord);
// Old
Assert.assertTrue(cause instanceof RestException, "Expected RestException not " + cause.getClass().getName());
RestException re = (RestException)cause;
RestResponse r = re.getResponse();
ErrorResponse er = new EntityResponseDecoder<>(ErrorResponse.class).decodeResponse(r).getEntity();
Assert.assertEquals(HTTP_CODE, r.getStatus());
Assert.assertEquals(ERR_VALUE, er.getErrorDetails().data().getString(ERR_KEY));
Assert.assertEquals(APP_CODE, er.getServiceErrorCode().intValue());
Assert.assertEquals(ERR_MSG, er.getMessage());
}
}
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestOptions")
public void testRestLiRemoteInvocationException(SendRequestOption option,
TimeoutOption timeoutOption,
ProtocolVersionOption versionOption,
ProtocolVersion protocolVersion,
String errorResponseHeaderName,
ContentType contentType)
throws ExecutionException, TimeoutException, InterruptedException, RestLiDecodingException
{
final int HTTP_CODE = 404;
final String ERR_MSG = "WHOOPS!";
RestClient client = mockClient(HTTP_CODE, ERR_MSG, protocolVersion);
Request<EmptyRecord> request = mockRequest(EmptyRecord.class, versionOption, contentType);
RequestBuilder<Request<EmptyRecord>> requestBuilder = mockRequestBuilder(request);
FutureCallback<Response<EmptyRecord>> callback = new FutureCallback<>();
try
{
sendRequest(option, client, request, requestBuilder, callback);
Long l = timeoutOption._l;
TimeUnit timeUnit = timeoutOption._timeUnit;
Response<EmptyRecord> response = l == null ? callback.get() : callback.get(l, timeUnit);
Assert.fail("Should have thrown");
}
catch (ExecutionException e)
{
Throwable cause = e.getCause();
Assert.assertTrue(cause instanceof RemoteInvocationException,
"Expected RemoteInvocationException not " + cause.getClass().getName());
RemoteInvocationException rlre = (RemoteInvocationException)cause;
Assert.assertTrue(rlre.getMessage().startsWith("Received error " + HTTP_CODE + " from server"));
Throwable rlCause = rlre.getCause();
Assert.assertTrue(rlCause instanceof RestException, "Expected RestException not " + rlCause.getClass().getName());
RestException rle = (RestException) rlCause;
Assert.assertEquals(ERR_MSG, rle.getResponse().getEntity().asString("UTF-8"));
Assert.assertEquals(HTTP_CODE, rle.getResponse().getStatus());
}
}
private ErrorHandlingBehavior determineErrorHandlingBehavior(GetResponseOption getResponseOption)
{
switch (getResponseOption)
{
case GET:
case GET_RESPONSE:
case GET_RESPONSE_ENTITY:
return null;
case GET_RESPONSE_EXPLICIT_NO_THROW:
case GET_RESPONSE_ENTITY_EXPLICIT_NO_THROW:
return ErrorHandlingBehavior.TREAT_SERVER_ERROR_AS_SUCCESS;
case GET_RESPONSE_EXPLICIT_THROW:
case GET_RESPONSE_ENTITY_EXPLICIT_THROW:
return ErrorHandlingBehavior.FAIL_ON_ERROR;
default:
throw new IllegalStateException();
}
}
private <T extends RecordTemplate> ResponseFuture<T> sendRequest(SendRequestOption option,
ErrorHandlingBehavior errorHandlingBehavior,
RestClient client,
Request<T> request,
RequestBuilder<Request<T>> requestBuilder)
{
switch (option)
{
case REQUEST_NO_CONTEXT:
if (errorHandlingBehavior == null)
{
return client.sendRequest(request);
}
else
{
return client.sendRequest(request, errorHandlingBehavior);
}
case REQUEST_WITH_CONTEXT:
if (errorHandlingBehavior == null)
{
return client.sendRequest(request, DEFAULT_REQUEST_CONTEXT);
}
else
{
return client.sendRequest(request, DEFAULT_REQUEST_CONTEXT, errorHandlingBehavior);
}
case REQUESTBUILDER_NO_CONTEXT:
if (errorHandlingBehavior == null)
{
return client.sendRequest(requestBuilder);
}
else
{
return client.sendRequest(requestBuilder, errorHandlingBehavior);
}
case REQUESTBUILDER_WITH_CONTEXT:
if (errorHandlingBehavior == null)
{
return client.sendRequest(requestBuilder, DEFAULT_REQUEST_CONTEXT);
}
else
{
return client.sendRequest(requestBuilder, DEFAULT_REQUEST_CONTEXT, errorHandlingBehavior);
}
default:
throw new IllegalStateException();
}
}
private <T extends RecordTemplate> void sendRequest(SendRequestOption option,
RestClient client,
Request<T> request,
RequestBuilder<Request<T>> requestBuilder,
Callback<Response<T>> callback)
{
switch (option)
{
case REQUEST_NO_CONTEXT:
client.sendRequest(request, callback);
break;
case REQUEST_WITH_CONTEXT:
client.sendRequest(request, DEFAULT_REQUEST_CONTEXT, callback);
break;
case REQUESTBUILDER_NO_CONTEXT:
client.sendRequest(requestBuilder, callback);
break;
case REQUESTBUILDER_WITH_CONTEXT:
client.sendRequest(requestBuilder, DEFAULT_REQUEST_CONTEXT, callback);
break;
default:
throw new IllegalStateException();
}
}
private <T extends RecordTemplate> Response<T> getOkResponse(GetResponseOption option,
ResponseFuture<T> future,
TimeoutOption timeoutOption)
throws ExecutionException, InterruptedException, TimeoutException, RemoteInvocationException
{
Response<T> result = null;
T entity;
Long l = timeoutOption._l;
TimeUnit timeUnit = timeoutOption._timeUnit;
switch (option)
{
case GET:
result = l == null ? future.get() : future.get(l, timeUnit);
break;
case GET_RESPONSE:
case GET_RESPONSE_EXPLICIT_NO_THROW:
case GET_RESPONSE_EXPLICIT_THROW:
result = l == null ? future.getResponse() : future.getResponse(l, timeUnit);
break;
case GET_RESPONSE_ENTITY:
case GET_RESPONSE_ENTITY_EXPLICIT_NO_THROW:
case GET_RESPONSE_ENTITY_EXPLICIT_THROW:
entity = l == null ? future.getResponseEntity() : future.getResponseEntity(l, timeUnit);
result = future.getResponse();
Assert.assertSame(entity, result.getEntity());
break;
default:
throw new IllegalStateException();
}
return result;
}
private <T extends RecordTemplate> RestLiResponseException getErrorResponse(GetResponseOption option,
ResponseFuture<T> future,
TimeoutOption timeoutOption)
throws InterruptedException, TimeoutException, RemoteInvocationException
{
Response<T> response = null;
T entity;
RestLiResponseException result = null;
Long l = timeoutOption._l;
TimeUnit timeUnit = timeoutOption._timeUnit;
switch (option)
{
case GET:
try
{
response = l == null ? future.get() : future.get(l, timeUnit);
Assert.fail("Should have thrown");
}
catch (ExecutionException e)
{
Throwable cause = e.getCause();
Assert.assertTrue(cause instanceof RestException, "Expected RestLiResponseException not " + cause.getClass().getName());
result = (RestLiResponseException) cause;
}
break;
case GET_RESPONSE:
case GET_RESPONSE_EXPLICIT_THROW:
try
{
response = l == null ? future.getResponse() : future.getResponse(l, timeUnit);
Assert.fail("Should have thrown");
}
catch (RestLiResponseException e)
{
result = e;
}
break;
case GET_RESPONSE_EXPLICIT_NO_THROW:
response = l == null ? future.getResponse() : future.getResponse(l, timeUnit);
result = response.getError();
break;
case GET_RESPONSE_ENTITY:
case GET_RESPONSE_ENTITY_EXPLICIT_THROW:
try
{
entity = l == null ? future.getResponseEntity() : future.getResponseEntity(l, timeUnit);
Assert.fail("Should have thrown");
}
catch (RestLiResponseException e)
{
result = e;
}
break;
case GET_RESPONSE_ENTITY_EXPLICIT_NO_THROW:
entity = l == null ? future.getResponseEntity() : future.getResponseEntity(l, timeUnit);
break;
default:
throw new IllegalStateException();
}
return result;
}
private <T extends RecordTemplate> RequestBuilder<Request<T>> mockRequestBuilder(final Request<T> request)
{
return new RequestBuilder<Request<T>>()
{
@Override
public Request<T> build()
{
return request;
}
};
}
private <T extends RecordTemplate> Request<T> mockRequest(Class<T> clazz,
ProtocolVersionOption versionOption, ContentType contentType)
{
RestliRequestOptions restliRequestOptions = new RestliRequestOptionsBuilder()
.setProtocolVersionOption(versionOption)
.setContentType(contentType)
.setAcceptTypes(Collections.singletonList(contentType))
.build();
return new GetRequest<>(Collections.<String, String>emptyMap(),
Collections.<HttpCookie>emptyList(),
clazz,
null,
new DataMap(),
Collections.<String, Class<?>>emptyMap(),
new ResourceSpecImpl(),
"/foo",
Collections.<String, Object>emptyMap(),
restliRequestOptions);
}
private static class MyMockClient extends MockClient
{
private RequestContext _requestContext;
private MyMockClient(int httpCode, Map<String, String> headers, byte[] bytes)
{
super(httpCode, headers, bytes);
}
@Override
public void restRequest(RestRequest request, RequestContext requestContext,
Callback<RestResponse> callback)
{
Assert.assertNotNull(requestContext);
_requestContext = requestContext;
super.restRequest(request, requestContext, callback);
}
@Override
protected Map<String, String> headers()
{
Map<String, String> headers = new HashMap<>(super.headers());
for (Map.Entry<String, Object> attr : _requestContext.getLocalAttrs().entrySet())
{
if (!attr.getKey().startsWith("__attr"))
{
continue;
}
headers.put(attr.getKey(), attr.getValue().toString());
}
return headers;
}
}
@SuppressWarnings("deprecation")
private RestClient mockClient(String errKey,
String errValue,
String errMsg,
int httpCode,
int appCode,
String code,
String docUrl,
String requestId,
ProtocolVersion protocolVersion,
String errorResponseHeaderName)
{
ErrorResponse er = new ErrorResponse();
DataMap errMap = new DataMap();
errMap.put(errKey, errValue);
er.setErrorDetails(new ErrorDetails(errMap));
er.setErrorDetailType(EmptyRecord.class.getCanonicalName());
er.setStatus(httpCode);
er.setMessage(errMsg);
er.setServiceErrorCode(appCode);
er.setCode(code);
er.setDocUrl(docUrl);
er.setRequestId(requestId);
Map<String,String> headers = new HashMap<>();
headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString());
headers.put(errorResponseHeaderName, RestConstants.HEADER_VALUE_ERROR);
byte[] mapBytes;
try
{
mapBytes = DataMapConverter.getContentType(headers).getCodec().mapToBytes(er.data());
}
catch (IOException | MimeTypeParseException e)
{
throw new RuntimeException(e);
}
return new RestClient(new MyMockClient(httpCode, headers, mapBytes), "http://localhost");
}
private RestClient mockClient(int httpCode, String errDetails, ProtocolVersion protocolVersion)
{
byte[] mapBytes;
try
{
mapBytes = errDetails.getBytes("UTF8");
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
Map<String,String> headers = new HashMap<>();
headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString());
return new RestClient(new MyMockClient(httpCode, headers, mapBytes), "http://localhost");
}
}
| 15,519 |
347 |
<reponame>hbraha/ovirt-engine<filename>frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/table/ColumnContextPopup.java<gh_stars>100-1000
package org.ovirt.engine.ui.common.widget.table;
import org.ovirt.engine.ui.common.widget.PopupPanel;
/**
* {@link PopupPanel} adapted for use with {@link ColumnContextMenu}.
*
* @param <T>
* Table row data type.
*/
public class ColumnContextPopup<T> extends PopupPanel {
private final ColumnContextMenu<T> contextMenu;
public ColumnContextPopup(ColumnController<T> controller) {
super(true);
this.contextMenu = new ColumnContextMenu<>(controller);
setWidget(contextMenu);
}
public ColumnContextMenu<T> getContextMenu() {
return contextMenu;
}
}
| 290 |
460 |
<filename>testsuite/testsuite-cdi-jaxws/src/main/java/org/wildfly/swarm/cdi/jaxws/test/GreeterServiceImpl.java
/**
* Copyright 2017 Red Hat, Inc, and individual contributors.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.wildfly.swarm.cdi.jaxws.test;
import javax.inject.Inject;
import javax.jws.WebService;
@WebService(serviceName = "GreeterService", portName = "Greeter", name = "Greeter",
endpointInterface = "org.wildfly.swarm.cdi.jaxws.test.GreeterService",
targetNamespace = "http://wildfly-swarm.io/Greeter")
public class GreeterServiceImpl implements GreeterService {
@Inject
private Greeter greeter;
@Override
public String hello() {
return greeter.hello();
}
}
| 407 |
432 |
<gh_stars>100-1000
/* CVS socket client stuff.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. */
#ifndef SOCKET_CLIENT_H__
#define SOCKET_CLIENT_H__ 1
#if defined SOCK_ERRNO || defined SOCK_STRERROR
# include <sys/socket.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <netdb.h>
#endif
struct buffer *socket_buffer_initialize
(int, int, void (*) (struct buffer *));
/* If SOCK_ERRNO is defined, then send()/recv() and other socket calls
do not set errno, but that this macro should be used to obtain an
error code. This probably doesn't make sense unless
NO_SOCKET_TO_FD is also defined. */
#ifndef SOCK_ERRNO
# define SOCK_ERRNO errno
#endif
/* If SOCK_STRERROR is defined, then the error codes returned by
socket operations are not known to strerror, and this macro must be
used instead to convert those error codes to strings. */
#ifndef SOCK_STRERROR
# define SOCK_STRERROR strerror
# include <string.h>
# ifndef strerror
extern char *strerror (int);
# endif
#endif /* ! SOCK_STRERROR */
#endif /* SOCKET_CLIENT_H__ */
| 485 |
568 |
package com.novoda.monkey;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MonkeyRunnerActivity extends AppCompatActivity {
private boolean showingAlternativeBackgroundColor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monkey_runner);
}
public void toggleBackgroundColor(View view) {
if (showingAlternativeBackgroundColor) {
showDefaultBackgroundColor();
} else {
showAlternativeBackgroundColor();
}
showingAlternativeBackgroundColor = !showingAlternativeBackgroundColor;
}
private void showDefaultBackgroundColor() {
getWindow().setBackgroundDrawableResource(android.R.color.holo_green_light);
}
private void showAlternativeBackgroundColor() {
getWindow().setBackgroundDrawableResource(android.R.color.holo_blue_light);
}
}
| 338 |
509 |
<gh_stars>100-1000
{
"name": "string-trace",
"version": "1.0.0",
"main": "index.js",
"repository": "https://github.com/mattzeunert/fromjs.git",
"author": "<NAME> <<EMAIL>>",
"license": "MIT",
"scripts": {
"compile-core": "cd packages/core;tsc --project tsconfig-core-main.json",
"compile-core-watch": "cd packages/core;tsc --watch --project tsconfig-core-main.json",
"compile-proxy-instrumenter": "cd packages/proxy-instrumenter;tsc",
"compile-proxy-instrumenter-watch": "cd packages/proxy-instrumenter;tsc --watch",
"compile-backend": "cd packages/backend;tsc",
"compile-backend-watch": "cd packages/backend;tsc --watch",
"compile-cli": "cd packages/cli;tsc",
"compile-cli-watch": "cd packages/cli;tsc --watch",
"test": "jest",
"test-watch": "jest --config=jest.config.dev.js --watch",
"test-debug": "node --inspect=36654 ./node_modules/.bin/jest --config=jest.config.dev.js --runInBand",
"cli": "VERIFY=true nodemon --max_old_space_size=8000 --ignore packages/ui --ignore logs.json --ignore 'fromjs-session/*' --ignore 'node-test-compiled/*' packages/cli/dist/cli.js -- --openBrowser no",
"cli-debug": "VERIFY=true nodemon --max_old_space_size=8000 --inspect=36655 --ignore logs.json --ignore fromjs-session packages/cli/dist/cli.js -- --openBrowser no",
"cli-browser": "`node packages/cli/dist/cli.js --openBrowser only`",
"cli-like-published": "node packages/cli/dist/cli.js",
"compile-all": "npm run compile-core;npm run compile-proxy-instrumenter; npm run compile-backend; npm run compile-cli",
"compile-all-watch": "echo \"doing sequential non watch compile first to prepare\";npm run compile-all;npm run compile-core-watch & npm run compile-proxy-instrumenter-watch & npm run compile-backend-watch & npm run compile-cli-watch"
},
"dependencies": {
"@babel/core": "^7.2.0",
"@types/jest": "^23.3.10",
"axios": "^0.19.2",
"jest": "^25.3.0",
"lerna": "^3.6.0",
"node-fetch": "^2.6.0",
"prettier": "^1.12.1",
"pretty-bytes": "^5.3.0",
"typescript": "^3.8.3"
},
"devDependencies": {
"@babel/preset-env": "^7.2.0",
"error-stack-parser": "^2.0.1",
"stacktrace-gps": "^3.0.2",
"tslint": "^5.10.0"
}
}
| 930 |
605 |
package com.sohu.tv.mq.cloud.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.sohu.tv.mq.cloud.bo.ProducerStat;
import com.sohu.tv.mq.cloud.bo.ProducerTotalStat;
import com.sohu.tv.mq.cloud.common.MemoryMQConsumer;
import com.sohu.tv.mq.cloud.util.DateUtil;
import com.sohu.tv.mq.cloud.util.Result;
import com.sohu.tv.mq.stats.InvokeStats.InvokeStatsResult;
import com.sohu.tv.mq.stats.dto.ClientStats;
/**
* 客户端统计消费
*
* @author yongfeigao
* @date 2018年9月12日
*/
@Component
public class ClientStatsConsumer implements MemoryMQConsumer<ClientStats> {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private ProducerTotalStatService producerTotalStatService;
@Autowired
private ProducerStatService producerStatService;
@Override
public void consume(ClientStats clientStats) throws Exception {
ProducerTotalStat producerTotalStat = generateProducerTotalStat(clientStats);
Result<Integer> result = producerTotalStatService.save(producerTotalStat);
long id = producerTotalStat.getId();
if(id == 0) {
// 有异常
if(result.getException() != null) {
if(!(result.getException() instanceof DuplicateKeyException)
&& !(result.getException() instanceof DataIntegrityViolationException)) {
// 数据库错误,可以进行重试
throw result.getException();
} else {
// 数据重复,重试一次
if(clientStats.getClient().indexOf("@") == -1) {
clientStats.setClient(clientStats.getClient() + "@1");
consume(clientStats);
return;
}
}
}
logger.error("save producerTotalStat:{} err", producerTotalStat);
return;
}
// 生成ProducerStat
List<ProducerStat> list = generateProducerStat(id, clientStats);
if(list != null && list.size() > 0) {
result = producerStatService.save(list);
if(result.isNotOK()) {
if(result.getException() != null) {
logger.error("save producerStat:{} err", list, result.getException());
} else {
logger.error("save producerStat:{} err", list);
}
}
}
}
/**
* 生成ProducerTotalStat
* @param clientStats
* @return
*/
private ProducerTotalStat generateProducerTotalStat(ClientStats clientStats) {
// 对象拼装
ProducerTotalStat producerTotalStat = new ProducerTotalStat();
producerTotalStat.setAvg(clientStats.getAvg());
producerTotalStat.setClient(clientStats.getClient());
producerTotalStat.setCount(clientStats.getCounts());
producerTotalStat.setPercent90(clientStats.getPercent90());
producerTotalStat.setPercent99(clientStats.getPercent99());
producerTotalStat.setProducer(clientStats.getProducer());
producerTotalStat.setStatTime(clientStats.getStatsTime());
Date now = new Date();
producerTotalStat.setCreateDate(NumberUtils.toInt(DateUtil.formatYMD(now)));
producerTotalStat.setCreateTime(DateUtil.getFormat(DateUtil.HHMM).format(now));
if(clientStats.getExceptionMap() != null && clientStats.getExceptionMap().size() > 0) {
producerTotalStat.setException(JSON.toJSONString(clientStats.getExceptionMap()));
}
return producerTotalStat;
}
/**
* 生成ProducerStat
* @param clientStats
* @return
*/
private List<ProducerStat> generateProducerStat(long id, ClientStats clientStats) {
Map<String, InvokeStatsResult> map = clientStats.getDetailInvoke();
if(map == null) {
return null;
}
List<ProducerStat> producerStatList = new ArrayList<ProducerStat>();
for(Entry<String, InvokeStatsResult> entry : map.entrySet()) {
ProducerStat producerStat = new ProducerStat();
producerStat.setBroker(entry.getKey());
producerStat.setAvg(entry.getValue().getAvgTime());
producerStat.setCount(entry.getValue().getTimes());
producerStat.setMax(entry.getValue().getMaxTime());
producerStat.setTotalId(id);
// 处理异常记录
Map<String, Integer> exceptionMap = entry.getValue().getExceptionMap();
if(exceptionMap != null) {
producerStat.setException(JSON.toJSONString(exceptionMap));
}
producerStatList.add(producerStat);
}
return producerStatList;
}
}
| 2,415 |
1,085 |
<filename>lib/tool_shed/util/repository_content_util.py
import os
import shutil
import tool_shed.repository_types.util as rt_util
from tool_shed.util import (
commit_util,
xml_util,
)
def upload_tar(trans, rdah, tdah, repository, tar, uploaded_file, upload_point, remove_repo_files_not_in_tar,
commit_message, new_repo_alert):
# Upload a tar archive of files.
undesirable_dirs_removed = 0
undesirable_files_removed = 0
check_results = commit_util.check_archive(repository, tar)
if check_results.invalid:
tar.close()
uploaded_file.close()
message = '{} Invalid paths were: {}'.format(
' '.join(check_results.errors), ', '.join(check_results.invalid))
return False, message, [], '', undesirable_dirs_removed, undesirable_files_removed
else:
repository.hg_repo
repo_dir = repository.repo_path(trans.app)
if upload_point is not None:
full_path = os.path.abspath(os.path.join(repo_dir, upload_point))
else:
full_path = os.path.abspath(repo_dir)
undesirable_files_removed = len(check_results.undesirable_files)
undesirable_dirs_removed = len(check_results.undesirable_dirs)
filenames_in_archive = [ti.name for ti in check_results.valid]
# Extract the uploaded tar to the load_point within the repository hierarchy.
tar.extractall(path=full_path, members=check_results.valid)
tar.close()
uploaded_file.close()
for filename in filenames_in_archive:
uploaded_file_name = os.path.join(full_path, filename)
if os.path.split(uploaded_file_name)[-1] == rt_util.REPOSITORY_DEPENDENCY_DEFINITION_FILENAME:
# Inspect the contents of the file to see if toolshed or changeset_revision attributes
# are missing and if so, set them appropriately.
altered, root_elem, error_message = rdah.handle_tag_attributes(uploaded_file_name)
if error_message:
return False, error_message, [], '', [], []
elif altered:
tmp_filename = xml_util.create_and_write_tmp_file(root_elem)
shutil.move(tmp_filename, uploaded_file_name)
elif os.path.split(uploaded_file_name)[-1] == rt_util.TOOL_DEPENDENCY_DEFINITION_FILENAME:
# Inspect the contents of the file to see if toolshed or changeset_revision
# attributes are missing and if so, set them appropriately.
altered, root_elem, error_message = tdah.handle_tag_attributes(uploaded_file_name)
if error_message:
return False, error_message, [], '', [], []
if altered:
tmp_filename = xml_util.create_and_write_tmp_file(root_elem)
shutil.move(tmp_filename, uploaded_file_name)
return commit_util.handle_directory_changes(trans.app,
trans.request.host,
trans.user.username,
repository,
full_path,
filenames_in_archive,
remove_repo_files_not_in_tar,
new_repo_alert,
commit_message,
undesirable_dirs_removed,
undesirable_files_removed)
| 1,901 |
1,133 |
#!/usr/bin/env python3
import isce
import datetime
import isceobj
import numpy as np
from iscesys.Component.Component import Component
from iscesys.Traits import datetimeType
####List of parameters
IMAGING_MODE = Component.Parameter('mode',
public_name = 'imaging mode',
default = 'TOPS',
type = str,
mandatory = False,
doc = 'Imaging mode')
FOLDER = Component.Parameter('folder',
public_name = 'folder',
default = None,
type = str,
mandatory = True,
doc = 'Folder corresponding to single swath of TOPS SLC')
SPACECRAFT_NAME = Component.Parameter('spacecraftName',
public_name='spacecraft name',
default=None,
type = str,
mandatory = True,
doc = 'Name of the space craft')
MISSION = Component.Parameter('mission',
public_name = 'mission',
default = None,
type = str,
mandatory = True,
doc = 'Mission name')
PROCESSING_FACILITY = Component.Parameter('processingFacility',
public_name='processing facility',
default=None,
type = str,
mandatory = False,
doc = 'Processing facility information')
PROCESSING_SYSTEM = Component.Parameter('processingSystem',
public_name='processing system',
default=None,
type = str,
mandatory = False,
doc = 'Processing system information')
PROCESSING_SYSTEM_VERSION = Component.Parameter('processingSoftwareVersion',
public_name='processing software version',
default=None,
type = str,
mandatory = False,
doc = 'Processing system software version')
ASCENDING_NODE_TIME = Component.Parameter('ascendingNodeTime',
public_name='ascending node time',
default=None,
type=datetimeType,
mandatory=True,
doc='Ascending node time corresponding to the acquisition')
NUMBER_BURSTS = Component.Parameter('numberOfBursts',
public_name = 'number of bursts',
default = None,
type = int,
mandatory = True,
doc = 'Number of bursts in the product')
####List of facilities
BURSTS = Component.Facility('bursts',
public_name='bursts',
module = 'iscesys.Component',
factory = 'createTraitSeq',
args=('burst',),
mandatory = False,
doc = 'Trait sequence of burst SLCs')
class TOPSSwathSLCProduct(Component):
"""A class to represent a burst SLC along a radar track"""
family = 'topsswathslc'
logging_name = 'isce.tops.swath.slc'
facility_list = (BURSTS,)
parameter_list = (IMAGING_MODE,
FOLDER,
SPACECRAFT_NAME,
MISSION,
PROCESSING_FACILITY,
PROCESSING_SYSTEM,
PROCESSING_SYSTEM_VERSION,
ASCENDING_NODE_TIME,
NUMBER_BURSTS
)
facility_list = (BURSTS,)
def __init__(self,name=''):
super(TOPSSwathSLCProduct, self).__init__(family=self.__class__.family, name=name)
return None
@property
def sensingStart(self):
return self.bursts[0].sensingStart
@property
def sensingStop(self):
return self.bursts[-1].sensingStop
@property
def sensingMid(self):
return self.sensingStart + 0.5 * (self.sensingStop - self.sensingStart)
@property
def startingRange(self):
return self.bursts[0].startingRange
@property
def farRange(self):
return self.bursts[0].farRange
@property
def midRange(self):
return 0.5 * (self.startingRange + self.farRange)
@property
def orbit(self):
'''
For now all bursts have same state vectors.
This will be the case till we build mechanisms for bursts to share metadata.
'''
return self.bursts[0].orbit
def getBbox(self ,hgtrange=[-500,9000]):
'''
Bounding box estimate.
'''
ts = [self.sensingStart, self.sensingStop]
rngs = [self.startingRange, self.farRange]
pos = []
for ht in hgtrange:
for tim in ts:
for rng in rngs:
llh = self.orbit.rdr2geo(tim, rng, height=ht)
pos.append(llh)
pos = np.array(pos)
bbox = [np.min(pos[:,0]), np.max(pos[:,0]), np.min(pos[:,1]), np.max(pos[:,1])]
return bbox
####Functions to assist with deramping
def computeAzimuthCarrier(self, burst, offset=0.0, position=None):
'''
Returns the ramp function as a numpy array.
'''
Vs = np.linalg.norm(burst.orbit.interpolateOrbit(burst.sensingMid, method='hermite').getVelocity())
Ks = 2 * Vs * burst.azimuthSteeringRate / burst.radarWavelength
if position is None:
rng = np.arange(burst.numberOfSamples) * burst.rangePixelSize + burst.startingRange
## Seems to work best for basebanding data
eta =( np.arange(0, burst.numberOfLines) - (burst.numberOfLines//2)) * burst.azimuthTimeInterval + offset * burst.azimuthTimeInterval
f_etac = burst.doppler(rng)
Ka = burst.azimuthFMRate(rng)
eta_ref = (burst.doppler(burst.startingRange) / burst.azimuthFMRate(burst.startingRange) ) - (f_etac / Ka)
# eta_ref *= 0.0
Kt = Ks / (1.0 - Ks/Ka)
carr = np.pi * Kt[None,:] * ((eta[:,None] - eta_ref[None,:])**2)
else:
####y and x need to be zero index
y,x = position
eta = (y - (burst.numberOfLines//2)) * burst.azimuthTimeInterval + offset * burst.azimuthTimeInterval
rng = burst.startingRange + x * burst.rangePixelSize
f_etac = burst.doppler(rng)
Ka = burst.azimuthFMRate(rng)
eta_ref = (burst.doppler(burst.startingRange) / burst.azimuthFMRate(burst.startingRange)) - (f_etac / Ka)
# eta_ref *= 0.0
Kt = Ks / (1.0 - Ks/Ka)
carr = np.pi * Kt * ((eta - eta_ref)**2)
return carr
def computeRamp(self, burst, offset=0.0, position=None):
'''
Compute the phase ramp.
'''
cJ = np.complex64(1.0j)
carr = self.computeAzimuthCarrier(burst,offset=offset, position=position)
ramp = np.exp(-cJ * carr)
return ramp
####Functions to help with finding overlap between products
def getBurstOffset(self, sframe):
'''
Identify integer burst offset between 2 products.
Compare the mid frames to start. Returns the integer offset between frame indices.
'''
if (len(sframe.bursts) < len(self.bursts)):
return -sframe.getBurstOffset(self)
checkBursts = [0.5, 0.25, 0.75, 0, 1]
offset = []
for bfrac in checkBursts:
mind = int(self.numberOfBursts * bfrac)
mind = np.clip(mind, 0, self.numberOfBursts - 1)
frame = self.bursts[mind]
tmid = frame.sensingMid
sv = frame.orbit.interpolateOrbit(tmid, method='hermite')
mpos = np.array(sv.getPosition())
mvel = np.array(sv.getVelocity())
mdist = 0.2 * np.linalg.norm(mvel) * frame.azimuthTimeInterval * frame.numberOfLines
arr = []
for burst in sframe.bursts:
tmid = burst.sensingMid
sv = burst.orbit.interpolateOrbit(tmid, method='hermite')
dr = np.array(sv.getPosition()) - mpos
alongtrackdist = np.abs(np.dot(dr, mvel)) / np.linalg.norm(mvel)
arr.append(alongtrackdist)
arr = np.array(arr)
ind = np.argmin(arr)
if arr[ind] < mdist:
return ind-mind
raise Exception('Could not determine a suitable burst offset')
return
def getCommonBurstLimits(self, sFrame):
'''
Get range of min to max bursts w.r.t another swath product.
minBurst, maxBurst can together be put into a slice object.
'''
burstoffset = self.getBurstOffset(sFrame)
print('Estimated burst offset: ', burstoffset)
minBurst = max(0, -burstoffset)
maxBurst = min(self.numberOfBursts, sFrame.numberOfBursts - burstoffset)
return burstoffset, minBurst, maxBurst
def estimateAzimuthCarrierPolynomials(self, burst, offset=0.0,
xstep=500, ystep=50,
azorder=5, rgorder=3, plot=False):
'''
Estimate a polynomial that represents the carrier on a given burst. To be used with resampling.
'''
from isceobj.Util.Poly2D import Poly2D
####TOPS steering component of the azimuth carrier
x = np.arange(0, burst.numberOfSamples,xstep,dtype=np.int)
y = np.arange(0, burst.numberOfLines, ystep, dtype=np.int)
xx,yy = np.meshgrid(x,y)
data = self.computeAzimuthCarrier(burst, offset=offset, position=(yy,xx))
###Compute the doppler component of the azimuth carrier
dop = burst.doppler
dpoly = Poly2D()
dpoly._meanRange = (dop._mean - burst.startingRange)/ burst.rangePixelSize
dpoly._normRange = dop._norm / burst.rangePixelSize
coeffs = [2*np.pi*val*burst.azimuthTimeInterval for val in dop._coeffs]
zcoeffs = [0. for val in coeffs]
dpoly.initPoly(rangeOrder=dop._order, azimuthOrder=0)
dpoly.setCoeffs([coeffs])
####Need to account for 1-indexing in Fortran code
poly = Poly2D()
poly.initPoly(rangeOrder = rgorder, azimuthOrder = azorder)
poly.polyfit(xx.flatten()+1, yy.flatten()+1, data.flatten()) #, maxOrder=True)
poly.createPoly2D() # Cpointer created
###Run some diagnostics to raise warning
fit = poly(yy+1,xx+1)
diff = data - fit
maxdiff = np.max(np.abs(diff))
print('Misfit radians - Max: {0} , Min : {1} '.format(np.max(diff), np.min(diff)))
if (maxdiff > 0.01):
print('Warning: The azimuth carrier polynomial may not be accurate enough')
if plot: ####For debugging only
import matplotlib.pyplot as plt
plt.figure('Original')
plt.imshow(data)
plt.colorbar()
plt.figure('Fit')
plt.imshow(fit)
plt.colorbar()
plt.figure('diff')
plt.imshow(diff)
plt.colorbar()
plt.show()
return poly, dpoly
| 4,931 |
14,668 |
// 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.
package org.chromium.chrome.browser.tab.state;
import static org.mockito.Mockito.doReturn;
import androidx.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.UiThreadTest;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.JniMocker;
import org.chromium.chrome.browser.endpoint_fetcher.EndpointFetcher;
import org.chromium.chrome.browser.endpoint_fetcher.EndpointFetcherJni;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.optimization_guide.OptimizationGuideBridge;
import org.chromium.chrome.browser.optimization_guide.OptimizationGuideBridgeJni;
import org.chromium.chrome.browser.page_annotations.PageAnnotationsService;
import org.chromium.chrome.browser.page_annotations.PageAnnotationsServiceFactory;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.tab.MockTab;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.test.ChromeBrowserTestRule;
import org.chromium.chrome.test.util.browser.Features;
import org.chromium.chrome.test.util.browser.Features.EnableFeatures;
import org.chromium.components.optimization_guide.OptimizationGuideDecision;
import org.chromium.components.optimization_guide.proto.HintsProto;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import java.util.concurrent.Semaphore;
/**
* Test relating to {@link ShoppingPersistedTabData} and {@link PageAnnotationService}
*/
@RunWith(BaseJUnit4ClassRunner.class)
@EnableFeatures({ChromeFeatureList.COMMERCE_PRICE_TRACKING + "<Study"})
@CommandLineFlags.
Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, "force-fieldtrials=Study/Group"})
public class ShoppingPersistedTabDataWithPASTest {
@Rule
public final ChromeBrowserTestRule mBrowserTestRule = new ChromeBrowserTestRule();
@Rule
public JniMocker mMocker = new JniMocker();
@Rule
public TestRule mProcessor = new Features.InstrumentationProcessor();
@Mock
protected EndpointFetcher.Natives mEndpointFetcherJniMock;
@Mock
protected OptimizationGuideBridge.Natives mOptimizationGuideBridgeJniMock;
@Mock
protected Profile mProfileMock;
@Mock
protected PageAnnotationsServiceFactory mServiceFactoryMock;
@Mock
protected PageAnnotationsService mPageAnnotationsServiceMock;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mMocker.mock(EndpointFetcherJni.TEST_HOOKS, mEndpointFetcherJniMock);
mMocker.mock(OptimizationGuideBridgeJni.TEST_HOOKS, mOptimizationGuideBridgeJniMock);
// Ensure native pointer is initialized
doReturn(1L).when(mOptimizationGuideBridgeJniMock).init();
ShoppingPersistedTabDataTestUtils.mockOptimizationGuideResponse(
mOptimizationGuideBridgeJniMock,
HintsProto.OptimizationType.SHOPPING_PAGE_PREDICTOR.getNumber(),
OptimizationGuideDecision.TRUE, null);
doReturn(mPageAnnotationsServiceMock).when(mServiceFactoryMock).getForLastUsedProfile();
TestThreadUtils.runOnUiThreadBlocking(() -> {
ShoppingPersistedTabData.onDeferredStartup();
PersistedTabDataConfiguration.setUseTestConfig(true);
Profile.setLastUsedProfileForTesting(mProfileMock);
ShoppingPersistedTabData.sPageAnnotationsServiceFactory = mServiceFactoryMock;
});
}
@SmallTest
@Test
@CommandLineFlags.
Add({"force-fieldtrial-params=Study.Group:price_tracking_with_optimization_guide/false"})
public void testShoppingBloomFilterNotShoppingWebsite() {
ShoppingPersistedTabDataWithPASTestUtils.mockPageAnnotationsResponse(
mPageAnnotationsServiceMock,
ShoppingPersistedTabDataWithPASTestUtils.MockPageAnnotationsResponse
.BUYABLE_PRODUCT_INITIAL);
ShoppingPersistedTabDataTestUtils.mockOptimizationGuideResponse(
mOptimizationGuideBridgeJniMock,
HintsProto.OptimizationType.SHOPPING_PAGE_PREDICTOR.getNumber(),
OptimizationGuideDecision.FALSE, null);
Tab tab = ShoppingPersistedTabDataTestUtils.createTabOnUiThread(
ShoppingPersistedTabDataTestUtils.TAB_ID,
ShoppingPersistedTabDataTestUtils.IS_INCOGNITO);
Semaphore semaphore = new Semaphore(0);
TestThreadUtils.runOnUiThreadBlocking(() -> {
ShoppingPersistedTabData.from(
tab, (shoppingPersistedTabData) -> { semaphore.release(); });
});
ShoppingPersistedTabDataTestUtils.acquireSemaphore(semaphore);
ShoppingPersistedTabDataWithPASTestUtils.verifyGetPageAnnotationsCalled(
mPageAnnotationsServiceMock, 0);
}
@SmallTest
@Test
public void testShoppingBloomFilterShoppingWebsite() {
for (@OptimizationGuideDecision int decision :
new int[] {OptimizationGuideDecision.TRUE, OptimizationGuideDecision.UNKNOWN}) {
ShoppingPersistedTabDataWithPASTestUtils.mockPageAnnotationsResponse(
mPageAnnotationsServiceMock,
ShoppingPersistedTabDataWithPASTestUtils.MockPageAnnotationsResponse
.BUYABLE_PRODUCT_INITIAL);
ShoppingPersistedTabDataTestUtils.mockOptimizationGuideResponse(
mOptimizationGuideBridgeJniMock,
HintsProto.OptimizationType.SHOPPING_PAGE_PREDICTOR.getNumber(), decision,
null);
MockTab tab = (MockTab) ShoppingPersistedTabDataTestUtils.createTabOnUiThread(
ShoppingPersistedTabDataTestUtils.TAB_ID,
ShoppingPersistedTabDataTestUtils.IS_INCOGNITO);
tab.setGurlOverrideForTesting(ShoppingPersistedTabDataTestUtils.DEFAULT_GURL);
Semaphore semaphore = new Semaphore(0);
TestThreadUtils.runOnUiThreadBlocking(() -> {
ShoppingPersistedTabData.from(
tab, (shoppingPersistedTabData) -> { semaphore.release(); });
});
ShoppingPersistedTabDataTestUtils.acquireSemaphore(semaphore);
ShoppingPersistedTabDataWithPASTestUtils.verifyGetPageAnnotationsCalled(
mPageAnnotationsServiceMock, 1);
}
}
@UiThreadTest
@SmallTest
@Test
public void testSPTDSavingEnabledUponSuccessfulProductUpdateResponse() {
final Semaphore semaphore = new Semaphore(0);
Tab tab = ShoppingPersistedTabDataTestUtils.createTabOnUiThread(
ShoppingPersistedTabDataTestUtils.TAB_ID,
ShoppingPersistedTabDataTestUtils.IS_INCOGNITO);
ShoppingPersistedTabDataWithPASTestUtils.mockPageAnnotationsResponse(
mPageAnnotationsServiceMock,
ShoppingPersistedTabDataWithPASTestUtils.MockPageAnnotationsResponse
.BUYABLE_PRODUCT_AND_PRODUCT_UPDATE);
TestThreadUtils.runOnUiThreadBlocking(() -> {
ShoppingPersistedTabData.from(tab, (shoppingPersistedTabData) -> {
Assert.assertTrue(shoppingPersistedTabData.mIsTabSaveEnabledSupplier.get());
semaphore.release();
});
});
ShoppingPersistedTabDataTestUtils.acquireSemaphore(semaphore);
}
@UiThreadTest
@SmallTest
@Test
public void testSPTDNullUponUnsuccessfulResponse() {
final Semaphore semaphore = new Semaphore(0);
Tab tab = ShoppingPersistedTabDataTestUtils.createTabOnUiThread(
ShoppingPersistedTabDataTestUtils.TAB_ID,
ShoppingPersistedTabDataTestUtils.IS_INCOGNITO);
ShoppingPersistedTabDataWithPASTestUtils.mockPageAnnotationsResponse(
mPageAnnotationsServiceMock,
ShoppingPersistedTabDataWithPASTestUtils.MockPageAnnotationsResponse
.BUYABLE_PRODUCT_EMPTY);
TestThreadUtils.runOnUiThreadBlocking(() -> {
ShoppingPersistedTabData.from(tab, (shoppingPersistedTabData) -> {
Assert.assertNull(shoppingPersistedTabData);
semaphore.release();
});
});
ShoppingPersistedTabDataTestUtils.acquireSemaphore(semaphore);
}
}
| 3,609 |
1,444 |
package mage.abilities.effects.common.combat;
import mage.abilities.Ability;
import mage.abilities.effects.RequirementEffect;
import mage.constants.Duration;
import mage.game.Game;
import mage.game.permanent.Permanent;
/**
*
* @author LevelX2
*/
public class BlocksIfAbleSourceEffect extends RequirementEffect {
public BlocksIfAbleSourceEffect(Duration duration) {
super(duration);
staticText = "{this} blocks each combat if able.";
}
public BlocksIfAbleSourceEffect(final BlocksIfAbleSourceEffect effect) {
super(effect);
}
@Override
public BlocksIfAbleSourceEffect copy() {
return new BlocksIfAbleSourceEffect(this);
}
@Override
public boolean applies(Permanent permanent, Ability source, Game game) {
Permanent creature = game.getPermanent(source.getSourceId());
return creature != null && creature.getId().equals(permanent.getId());
}
@Override
public boolean mustAttack(Game game) {
return false;
}
@Override
public boolean mustBlock(Game game) {
return false;
}
@Override
public boolean mustBlockAny(Game game) {
return true;
}
}
| 416 |
4,283 |
<filename>hazelcast/src/test/java/com/hazelcast/map/merge/MapSplitBrainStressTest.java
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.map.merge;
import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.LifecycleEvent;
import com.hazelcast.core.LifecycleListener;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.map.IMap;
import com.hazelcast.spi.merge.PassThroughMergePolicy;
import com.hazelcast.test.ChangeLoggingRule;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.SplitBrainTestSupport;
import com.hazelcast.test.annotation.NightlyTest;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import static java.lang.String.format;
import static org.junit.Assert.assertEquals;
/**
* Runs several iterations of a split-brain and split-brain healing cycle on a constant data set.
* <p>
* There are {@value #MAP_COUNT} maps which are filled with {@value #ENTRY_COUNT} entries each.
* The configured pass through merge policy will trigger the split-brain healing and some merge code,
* but will not change any data.
*/
@RunWith(HazelcastSerialClassRunner.class)
@Category(NightlyTest.class)
public class MapSplitBrainStressTest extends SplitBrainTestSupport {
@ClassRule
public static ChangeLoggingRule changeLoggingRule
= new ChangeLoggingRule("log4j2-trace-map-split-brain-stress.xml");
static final int ITERATION_COUNT = 50;
static final int MAP_COUNT = 100;
static final int ENTRY_COUNT = 100;
static final int FIRST_BRAIN_SIZE = 3;
static final int SECOND_BRAIN_SIZE = 2;
static final Class<PassThroughMergePolicy> MERGE_POLICY = PassThroughMergePolicy.class;
static final int TEST_TIMEOUT_IN_MILLIS = 15 * 60 * 1000;
static final String MAP_NAME_PREFIX = MapSplitBrainStressTest.class.getSimpleName() + "-";
static final ILogger LOGGER = Logger.getLogger(MapSplitBrainStressTest.class);
final Map<HazelcastInstance, UUID> listenerRegistry = new ConcurrentHashMap<>();
final Map<Integer, String> mapNames = new ConcurrentHashMap<>();
MergeLifecycleListener mergeLifecycleListener;
int iteration = 1;
@Override
protected Config config() {
Config config = super.config();
config.getMapConfig(MAP_NAME_PREFIX + "*")
.getMergePolicyConfig()
.setPolicy(MERGE_POLICY.getName());
return config;
}
@Override
protected int[] brains() {
return new int[]{FIRST_BRAIN_SIZE, SECOND_BRAIN_SIZE};
}
@Override
protected int iterations() {
return ITERATION_COUNT;
}
@Test(timeout = TEST_TIMEOUT_IN_MILLIS)
@Override
public void testSplitBrain() throws Exception {
super.testSplitBrain();
}
@Override
protected void onBeforeSplitBrainCreated(HazelcastInstance[] instances) {
LOGGER.info("Starting iteration " + iteration);
if (iteration == 1) {
for (int mapIndex = 0; mapIndex < MAP_COUNT; mapIndex++) {
LOGGER.info("Filling map " + mapIndex + "/" + MAP_COUNT + " with " + ENTRY_COUNT + " entries");
String mapName = MAP_NAME_PREFIX + randomMapName();
mapNames.put(mapIndex, mapName);
IMap<Integer, Integer> mapOnFirstBrain = instances[0].getMap(mapName);
for (int key = 0; key < ENTRY_COUNT; key++) {
mapOnFirstBrain.put(key, key);
}
}
}
}
@Override
protected void onAfterSplitBrainCreated(HazelcastInstance[] firstBrain, HazelcastInstance[] secondBrain) {
mergeLifecycleListener = new MergeLifecycleListener(secondBrain.length);
for (HazelcastInstance instance : secondBrain) {
UUID listener = instance.getLifecycleService().addLifecycleListener(mergeLifecycleListener);
listenerRegistry.put(instance, listener);
}
assertEquals(FIRST_BRAIN_SIZE, firstBrain.length);
assertEquals(SECOND_BRAIN_SIZE, secondBrain.length);
}
@Override
protected void onAfterSplitBrainHealed(HazelcastInstance[] instances) {
// wait until merge completes
mergeLifecycleListener.await();
for (Map.Entry<HazelcastInstance, UUID> entry : listenerRegistry.entrySet()) {
entry.getKey().getLifecycleService().removeLifecycleListener(entry.getValue());
}
int expectedClusterSize = FIRST_BRAIN_SIZE + SECOND_BRAIN_SIZE;
assertEquals("expected cluster size " + expectedClusterSize, expectedClusterSize, instances.length);
for (int mapIndex = 0; mapIndex < MAP_COUNT; mapIndex++) {
String mapName = mapNames.get(mapIndex);
IMap<Integer, Integer> map = instances[0].getMap(mapName);
assertEquals(format("expected %d entries in map %d/%d (iteration %d)",
ENTRY_COUNT, mapIndex, MAP_COUNT, iteration),
ENTRY_COUNT, map.size());
for (int key = 0; key < ENTRY_COUNT; key++) {
int value = map.get(key);
assertEquals(format("expected value %d for key %d in map %d/%d (iteration %d)",
value, key, mapIndex, MAP_COUNT, iteration),
key, value);
}
}
iteration++;
}
private static class MergeLifecycleListener implements LifecycleListener {
private final CountDownLatch latch;
MergeLifecycleListener(int mergingClusterSize) {
latch = new CountDownLatch(mergingClusterSize);
}
@Override
public void stateChanged(LifecycleEvent event) {
if (event.getState() == LifecycleEvent.LifecycleState.MERGED) {
latch.countDown();
}
}
public void await() {
assertOpenEventually(latch);
}
}
}
| 2,612 |
435 |
{
"copyright_text": null,
"description": "TL;DR\n\nWhen you go full Big Data at public data and become a citzen.\n-------------------------------------------------------------\n\nAudience type: developers, data scientists of any level of expertise.\n\nAfter a political coup Brazil drowned in scandals and political\ndisbelief. That was the final straw for us.\n\nWe created a bot persona who uses Machine Learning to analyze public\nspending, launching our own data journalism investigations. As expected\nwe use the internet publicize our findings and icing on it was to use\nTwitter to directly engage the public and politicians under the topic of\nsuspicious expenses.\n\nCome with me and I\u2019ll show some figures from Brazilian corruption, share\nsome code and cherry-pick the best of our toolbox to deal with public\ndata and machine learning. I\u2019ll introduce our public dashboard that\nmakes visualization and browsing government data easy peasy. And surely\nwe can take a look in some tweets from Rosie, the robot, and how some\npoliticians are now vociferating with a ROBOT on social media.\n\nAnd you guessed it right: everything is open-source and our mission is\nto create a global community to bring democracy to the A.I. age.\n\nin \\_\\_on **sabato 21 aprile** at 18:30 `**See\nschedule** </p3/schedule/pycon9/>`__\n",
"duration": 2246,
"language": "eng",
"recorded": "2018-04-21",
"related_urls": [
{
"label": "Conference schedule",
"url": "https://www.pycon.it/p3/schedule/pycon9/"
}
],
"speakers": [
"<NAME>"
],
"tags": [
"machine-learning",
"Python",
"agile",
"Data Mining",
"bigdata",
"data-visualization",
"OpenSource",
"data-analysis",
"e-gov",
"data"
],
"thumbnail_url": "https://i.ytimg.com/vi/JiJ5a4CXRF8/maxresdefault.jpg",
"title": "Using Python to bring democracy to the A.I. age",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=JiJ5a4CXRF8"
}
]
}
| 672 |
1,444 |
package mage.cards.l;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.BecomesBlockedAllTriggeredAbility;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.Effect;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.SacrificeEffect;
import mage.abilities.effects.common.continuous.BoostAllEffect;
import mage.abilities.keyword.MenaceAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.filter.FilterPermanent;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.mageobject.AbilityPredicate;
import mage.filter.predicate.permanent.BlockingAttackerIdPredicate;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.targetpointer.FixedTarget;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class LabyrinthRaptor extends CardImpl {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("a creature you control with menace");
static {
filter.add(new AbilityPredicate(MenaceAbility.class));
filter.add(TargetController.YOU.getControllerPredicate());
}
private static final FilterCreaturePermanent filter2 = filter.copy();
static {
filter2.setMessage("creatures you control with menace");
}
public LabyrinthRaptor(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{B}{R}");
this.subtype.add(SubType.NIGHTMARE);
this.subtype.add(SubType.DINOSAUR);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Menace
this.addAbility(new MenaceAbility());
// Whenever a creature you control with menace becomes blocked, defending player sacrifices a creature blocking it.
this.addAbility(new BecomesBlockedAllTriggeredAbility(
new LabyrinthRaptorEffect(), false, filter, true
));
// {B}{R}: Creatures you control with menace get +1/+0 until end of turn.
this.addAbility(new SimpleActivatedAbility(new BoostAllEffect(
1, 0, Duration.EndOfTurn, filter2, false
), new ManaCostsImpl("{B}{R}")));
}
private LabyrinthRaptor(final LabyrinthRaptor card) {
super(card);
}
@Override
public LabyrinthRaptor copy() {
return new LabyrinthRaptor(this);
}
}
class LabyrinthRaptorEffect extends OneShotEffect {
LabyrinthRaptorEffect() {
super(Outcome.Benefit);
staticText = "defending player sacrifices a creature blocking it";
}
private LabyrinthRaptorEffect(final LabyrinthRaptorEffect effect) {
super(effect);
}
@Override
public LabyrinthRaptorEffect copy() {
return new LabyrinthRaptorEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Permanent permanent = getTargetPointer().getFirstTargetPermanentOrLKI(game, source);
if (permanent == null) {
return false;
}
Player player = game.getPlayer(game.getCombat().getDefendingPlayerId(permanent.getId(), game));
if (player == null) {
return false;
}
FilterPermanent filterPermanent = new FilterPermanent("creature blocking " + permanent.getIdName());
filterPermanent.add(new BlockingAttackerIdPredicate(permanent.getId()));
Effect effect = new SacrificeEffect(filterPermanent, 1, "");
effect.setTargetPointer(new FixedTarget(player.getId(), game));
return effect.apply(game, source);
}
}
| 1,324 |
6,098 |
package hex;
/**
* Created by tomasnykodym on 1/5/16.
*/
public interface GLMMetrics {
double residual_deviance(); //naming is pythonic because its user-facing via grid search sort criterion
double null_deviance();
long residual_degrees_of_freedom();
long null_degrees_of_freedom();
}
| 100 |
568 |
<gh_stars>100-1000
//
// Copyright (c) 2009, <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include <cstring>
#include <rl/math/Constants.h>
#include "Dc1394Camera.h"
namespace rl
{
namespace hal
{
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_MONO8;
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_YUV411;
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_YUV422;
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_YUV444;
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_RGB8;
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_MONO16;
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_RGB16;
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_MONO16S;
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_RGB16S;
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_RAW8;
constexpr Dc1394Camera::ColorCoding Dc1394Camera::COLOR_CODING_RAW16;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_BRIGHTNESS;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_EXPOSURE;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_SHARPNESS;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_WHITE_BALANCE;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_HUE;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_SATURATION;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_GAMMA;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_SHUTTER;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_GAIN;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_IRIS;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_FOCUS;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_TEMPERATURE;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_TRIGGER;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_TRIGGER_DELAY;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_WHITE_SHADING;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_FRAME_RATE;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_ZOOM;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_PAN;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_TILT;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_OPTICAL_FILTER;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_CAPTURE_SIZE;
constexpr Dc1394Camera::Feature Dc1394Camera::FEATURE_CAPTURE_QUALITY;
constexpr Dc1394Camera::FeatureMode Dc1394Camera::FEATURE_MODE_MANUAL;
constexpr Dc1394Camera::FeatureMode Dc1394Camera::FEATURE_MODE_AUTO;
constexpr Dc1394Camera::FeatureMode Dc1394Camera::FEATURE_MODE_ONE_PUSH_AUTO;
constexpr Dc1394Camera::Framerate Dc1394Camera::FRAMERATE_1_875;
constexpr Dc1394Camera::Framerate Dc1394Camera::FRAMERATE_3_75;
constexpr Dc1394Camera::Framerate Dc1394Camera::FRAMERATE_7_5;
constexpr Dc1394Camera::Framerate Dc1394Camera::FRAMERATE_15;
constexpr Dc1394Camera::Framerate Dc1394Camera::FRAMERATE_30;
constexpr Dc1394Camera::Framerate Dc1394Camera::FRAMERATE_60;
constexpr Dc1394Camera::Framerate Dc1394Camera::FRAMERATE_120;
constexpr Dc1394Camera::Framerate Dc1394Camera::FRAMERATE_240;
constexpr Dc1394Camera::IsoSpeed Dc1394Camera::ISO_SPEED_100;
constexpr Dc1394Camera::IsoSpeed Dc1394Camera::ISO_SPEED_200;
constexpr Dc1394Camera::IsoSpeed Dc1394Camera::ISO_SPEED_400;
constexpr Dc1394Camera::IsoSpeed Dc1394Camera::ISO_SPEED_800;
constexpr Dc1394Camera::IsoSpeed Dc1394Camera::ISO_SPEED_1600;
constexpr Dc1394Camera::IsoSpeed Dc1394Camera::ISO_SPEED_3200;
constexpr Dc1394Camera::OperationMode Dc1394Camera::OPERATION_MODE_LEGACY;
constexpr Dc1394Camera::OperationMode Dc1394Camera::OPERATION_MODE_1394B;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_160x120_YUV444;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_320x240_YUV422;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_640x480_YUV411;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_640x480_YUV422;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_640x480_RGB8;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_640x480_MONO8;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_640x480_MONO16;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_800x600_YUV422;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_800x600_RGB8;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_800x600_MONO8;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1024x768_YUV422;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1024x768_RGB8;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1024x768_MONO8;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_800x600_MONO16;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1024x768_MONO16;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1280x960_YUV422;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1280x960_RGB8;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1280x960_MONO8;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1600x1200_YUV422;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1600x1200_RGB8;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1600x1200_MONO8;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1280x960_MONO16;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_1600x1200_MONO16;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_EXIF;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_FORMAT7_0;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_FORMAT7_1;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_FORMAT7_2;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_FORMAT7_3;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_FORMAT7_4;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_FORMAT7_5;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_FORMAT7_6;
constexpr Dc1394Camera::VideoMode Dc1394Camera::VIDEO_MODE_FORMAT7_7;
Dc1394Camera::Dc1394Camera(const unsigned int& node) :
Camera(),
CyclicDevice(::std::chrono::nanoseconds::zero()),
buffer(8),
camera(nullptr),
cameras(0),
colorCoding(ColorCoding::raw8),
dc1394(::dc1394_new()),
frame(),
framerate(static_cast<Framerate>(DC1394_FRAMERATE_MIN)),
height(DC1394_USE_MAX_AVAIL),
left(0),
node(node),
speed(IsoSpeed::i400),
top(0),
videoMode(VideoMode::v640x480_rgb8),
width(DC1394_USE_MAX_AVAIL)
{
}
Dc1394Camera::~Dc1394Camera()
{
if (nullptr != this->dc1394)
{
::dc1394_free(this->dc1394);
}
}
void
Dc1394Camera::close()
{
if (nullptr != this->camera)
{
::dc1394_camera_free(this->camera);
}
}
unsigned int
Dc1394Camera::getBitsPerPixel() const
{
switch (this->videoMode)
{
case VideoMode::v640x480_mono8:
case VideoMode::v800x600_mono8:
case VideoMode::v1024x768_mono8:
case VideoMode::v1280x960_mono8:
case VideoMode::v1600x1200_mono8:
return 8;
break;
case VideoMode::v640x480_yuv411:
return 12;
break;
case VideoMode::v640x480_mono16:
case VideoMode::v800x600_mono16:
case VideoMode::v1024x768_mono16:
case VideoMode::v1280x960_mono16:
case VideoMode::v1600x1200_mono16:
case VideoMode::v320x240_yuv422:
case VideoMode::v640x480_yuv422:
case VideoMode::v800x600_yuv422:
case VideoMode::v1024x768_yuv422:
case VideoMode::v1280x960_yuv422:
case VideoMode::v1600x1200_yuv422:
return 16;
break;
case VideoMode::v640x480_rgb8:
case VideoMode::v800x600_rgb8:
case VideoMode::v1024x768_rgb8:
case VideoMode::v1280x960_rgb8:
case VideoMode::v1600x1200_rgb8:
case VideoMode::v160x120_yuv444:
return 24;
break;
case VideoMode::format7_0:
case VideoMode::format7_1:
case VideoMode::format7_2:
case VideoMode::format7_3:
case VideoMode::format7_4:
case VideoMode::format7_5:
case VideoMode::format7_6:
case VideoMode::format7_7:
switch (this->colorCoding)
{
case ColorCoding::mono8:
case ColorCoding::raw8:
return 8;
break;
case ColorCoding::yuv411:
return 12;
break;
case ColorCoding::mono16:
case ColorCoding::mono16s:
case ColorCoding::raw16:
case ColorCoding::yuv422:
return 16;
break;
case ColorCoding::rgb8:
case ColorCoding::yuv444:
return 24;
break;
case ColorCoding::rgb16:
case ColorCoding::rgb16s:
return 48;
break;
default:
break;
}
break;
default:
break;
}
return 0;
}
unsigned int
Dc1394Camera::getColorCodingDepth() const
{
switch (this->videoMode)
{
case VideoMode::v640x480_mono8:
case VideoMode::v800x600_mono8:
case VideoMode::v1024x768_mono8:
case VideoMode::v1280x960_mono8:
case VideoMode::v1600x1200_mono8:
case VideoMode::v640x480_rgb8:
case VideoMode::v800x600_rgb8:
case VideoMode::v1024x768_rgb8:
case VideoMode::v1280x960_rgb8:
case VideoMode::v1600x1200_rgb8:
case VideoMode::v640x480_yuv411:
case VideoMode::v320x240_yuv422:
case VideoMode::v640x480_yuv422:
case VideoMode::v800x600_yuv422:
case VideoMode::v1024x768_yuv422:
case VideoMode::v1280x960_yuv422:
case VideoMode::v1600x1200_yuv422:
case VideoMode::v160x120_yuv444:
return 8;
break;
case VideoMode::v640x480_mono16:
case VideoMode::v800x600_mono16:
case VideoMode::v1024x768_mono16:
case VideoMode::v1280x960_mono16:
case VideoMode::v1600x1200_mono16:
return 16;
break;
case VideoMode::format7_0:
case VideoMode::format7_1:
case VideoMode::format7_2:
case VideoMode::format7_3:
case VideoMode::format7_4:
case VideoMode::format7_5:
case VideoMode::format7_6:
case VideoMode::format7_7:
switch (this->colorCoding)
{
case ColorCoding::mono8:
case ColorCoding::raw8:
case ColorCoding::rgb8:
case ColorCoding::yuv411:
case ColorCoding::yuv422:
case ColorCoding::yuv444:
return 8;
break;
case ColorCoding::mono16:
case ColorCoding::mono16s:
case ColorCoding::raw16:
case ColorCoding::rgb16:
case ColorCoding::rgb16s:
return 16;
break;
default:
break;
}
break;
default:
break;
}
return 0;
}
unsigned int
Dc1394Camera::getHeight() const
{
unsigned int width;
unsigned int height;
::dc1394error_t error = ::dc1394_get_image_size_from_video_mode(this->camera, static_cast<::dc1394video_mode_t>(this->videoMode), &width, &height);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return height;
}
bool
Dc1394Camera::getFeatureAbsoluteControl(const Feature& feature) const
{
::dc1394bool_t hasAbsoluteControl;
::dc1394error_t error = ::dc1394_feature_has_absolute_control(this->camera, static_cast<::dc1394feature_t>(feature), &hasAbsoluteControl);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return hasAbsoluteControl;
}
void
Dc1394Camera::getFeatureBoundaries(const Feature& feature, unsigned int& min, unsigned int& max) const
{
::dc1394error_t error = ::dc1394_feature_get_boundaries(this->camera, static_cast<::dc1394feature_t>(feature), &min, &max);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
void
Dc1394Camera::getFeatureBoundariesAbsolute(const Feature& feature, float& min, float& max) const
{
::dc1394error_t error = ::dc1394_feature_get_absolute_boundaries(this->camera, static_cast<::dc1394feature_t>(feature), &min, &max);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
Dc1394Camera::FeatureMode
Dc1394Camera::getFeatureMode(const Feature& feature) const
{
::dc1394feature_mode_t mode;
::dc1394error_t error = ::dc1394_feature_get_mode(this->camera, static_cast<::dc1394feature_t>(feature), &mode);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return static_cast<FeatureMode>(mode);
}
void
Dc1394Camera::getFeatureModes(const Feature& feature, bool& hasManual, bool& hasAuto, bool& hasOnePushAuto) const
{
::dc1394feature_modes_t modes;
::dc1394error_t error = ::dc1394_feature_get_modes(this->camera, static_cast<::dc1394feature_t>(feature), &modes);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
hasManual = false;
hasAuto = false;
hasOnePushAuto = false;
for (::std::size_t i = 0; i < modes.num; ++i)
{
if (::DC1394_FEATURE_MODE_MANUAL == modes.modes[i])
{
hasManual = true;
}
else if (::DC1394_FEATURE_MODE_AUTO == modes.modes[i])
{
hasAuto = true;
}
else if (::DC1394_FEATURE_MODE_ONE_PUSH_AUTO == modes.modes[i])
{
hasOnePushAuto = true;
}
}
}
unsigned int
Dc1394Camera::getFeatureValue(const Feature& feature) const
{
unsigned int value;
::dc1394error_t error = ::dc1394_feature_get_value(this->camera, static_cast<::dc1394feature_t>(feature), &value);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return value;
}
float
Dc1394Camera::getFeatureValueAbsolute(const Feature& feature) const
{
float value;
::dc1394error_t error = ::dc1394_feature_get_absolute_value(this->camera, static_cast<::dc1394feature_t>(feature), &value);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return value;
}
void
Dc1394Camera::getFormat7(VideoMode& videoMode, ColorCoding& colorCoding, unsigned int& left, unsigned int& top, unsigned int& width, unsigned int& height) const
{
colorCoding = this->colorCoding;
height = this->height;
left = this->left;
top = this->top;
videoMode = this->videoMode;
width = this->width;
}
void
Dc1394Camera::getFormat7MaximumImageSize(const unsigned int& mode, unsigned int& width, unsigned& height) const
{
::dc1394error_t error = ::dc1394_format7_get_max_image_size(this->camera, static_cast<::dc1394video_mode_t>(mode), &width, &height);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
Dc1394Camera::Framerate
Dc1394Camera::getFramerate() const
{
Framerate framerate;
::dc1394error_t error = ::dc1394_video_get_framerate(this->camera, reinterpret_cast<::dc1394framerate_t*>(&framerate));
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return framerate;
}
unsigned int
Dc1394Camera::getNode() const
{
return this->node;
}
int
Dc1394Camera::getNumCameras() const
{
return this->cameras;
}
Dc1394Camera::OperationMode
Dc1394Camera::getOperationMode() const
{
OperationMode operationMode;
::dc1394error_t error = ::dc1394_video_get_operation_mode(this->camera, reinterpret_cast<::dc1394operation_mode_t*>(&operationMode));
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return operationMode;
}
unsigned int
Dc1394Camera::getSize() const
{
unsigned int width;
unsigned int height;
::dc1394error_t error = ::dc1394_get_image_size_from_video_mode(this->camera, static_cast<::dc1394video_mode_t>(this->videoMode), &width, &height);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return width * height * this->getBitsPerPixel() / 8;
}
Dc1394Camera::IsoSpeed
Dc1394Camera::getSpeed() const
{
IsoSpeed speed;
::dc1394error_t error = ::dc1394_video_get_iso_speed(this->camera, reinterpret_cast<::dc1394speed_t*>(&speed));
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return speed;
}
::std::chrono::nanoseconds
Dc1394Camera::getUpdateRate() const
{
double framerate;
switch (this->framerate)
{
case Framerate::f1_875:
framerate = 1.875;
break;
case Framerate::f3_75:
framerate = 3.75;
break;
case Framerate::f7_5:
framerate = 7.5;
break;
case Framerate::f15:
framerate = 15.0;
break;
case Framerate::f30:
framerate = 30.0;
break;
case Framerate::f60:
framerate = 60.0;
break;
case Framerate::f120:
framerate = 120.0;
break;
case Framerate::f240:
framerate = 240.0;
break;
default:
return ::std::chrono::nanoseconds::zero();
break;
}
return ::std::chrono::duration_cast<::std::chrono::nanoseconds>(
::std::chrono::duration<double>(1.0 / framerate * ::rl::math::constants::unit2nano)
);
}
Dc1394Camera::VideoMode
Dc1394Camera::getVideoMode() const
{
VideoMode videoMode;
::dc1394error_t error = ::dc1394_video_get_mode(this->camera, reinterpret_cast<::dc1394video_mode_t*>(&videoMode));
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return videoMode;
}
unsigned int
Dc1394Camera::getWidth() const
{
unsigned int width;
unsigned int height;
::dc1394error_t error = ::dc1394_get_image_size_from_video_mode(this->camera, static_cast<::dc1394video_mode_t>(this->videoMode), &width, &height);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return width;
}
void
Dc1394Camera::grab(unsigned char* image)
{
::dc1394error_t error = ::dc1394_capture_dequeue(this->camera, ::DC1394_CAPTURE_POLICY_WAIT, &this->frame);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
::std::memcpy(image, this->frame->image, this->getSize());
error = ::dc1394_capture_enqueue(this->camera, this->frame);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
bool
Dc1394Camera::hasFeatureAbsoluteControl(const Feature& feature) const
{
::dc1394bool_t hasAbsoluteControl;
::dc1394error_t error = ::dc1394_feature_has_absolute_control(this->camera, static_cast<::dc1394feature_t>(feature), &hasAbsoluteControl);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return hasAbsoluteControl;
}
bool
Dc1394Camera::isFeatureEnabled(const Feature& feature) const
{
::dc1394switch_t isFeatureOn;
::dc1394error_t error = ::dc1394_feature_get_power(this->camera, static_cast<::dc1394feature_t>(feature), &isFeatureOn);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return isFeatureOn;
}
bool
Dc1394Camera::isFeaturePresent(const Feature& feature) const
{
::dc1394bool_t isFeaturePresent;
::dc1394error_t error = ::dc1394_feature_is_present(this->camera, static_cast<::dc1394feature_t>(feature), &isFeaturePresent);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return isFeaturePresent;
}
bool
Dc1394Camera::isFeatureReadable(const Feature& feature) const
{
::dc1394bool_t canReadOut;
::dc1394error_t error = ::dc1394_feature_is_readable(this->camera, static_cast<::dc1394feature_t>(feature), &canReadOut);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return canReadOut;
}
bool
Dc1394Camera::isFeatureSwitchable(const Feature& feature) const
{
::dc1394bool_t canTurnOnOff;
::dc1394error_t error = ::dc1394_feature_is_switchable(this->camera, static_cast<::dc1394feature_t>(feature), &canTurnOnOff);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
return canTurnOnOff;
}
void
Dc1394Camera::open()
{
::dc1394camera_list_t* list;
::dc1394error_t error = ::dc1394_camera_enumerate(this->dc1394, &list);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
this->cameras = list->num;
this->camera = ::dc1394_camera_new(this->dc1394, list->ids[this->node].guid);
::dc1394_camera_free_list(list);
}
void
Dc1394Camera::reset()
{
::dc1394error_t error = ::dc1394_camera_reset(this->camera);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
void
Dc1394Camera::setFeatureAbsoluteControl(const Feature& feature, const bool& doOn)
{
}
void
Dc1394Camera::setFeatureEnabled(const Feature& feature, const bool& doOn)
{
::dc1394error_t error = ::dc1394_feature_set_power(this->camera, static_cast<::dc1394feature_t>(feature), static_cast<::dc1394switch_t>(doOn));
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
void
Dc1394Camera::setFeatureMode(const Feature& feature, const FeatureMode& mode)
{
::dc1394error_t error = ::dc1394_feature_set_mode(this->camera, static_cast<::dc1394feature_t>(feature), static_cast<::dc1394feature_mode_t>(mode));
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
void
Dc1394Camera::setFeatureValue(const Feature& feature, const unsigned int& value)
{
::dc1394error_t error = ::dc1394_feature_set_value(this->camera, static_cast<::dc1394feature_t>(feature), value);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
void
Dc1394Camera::setFeatureValueAbsolute(const Feature& feature, const float& value)
{
::dc1394error_t error = ::dc1394_feature_set_absolute_value(this->camera, static_cast<::dc1394feature_t>(feature), value);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
void
Dc1394Camera::setFormat7(const VideoMode& videoMode, const ColorCoding& colorCoding, const unsigned int& left, const unsigned int& top, const unsigned int& width, const unsigned int& height)
{
::dc1394error_t error = ::dc1394_format7_set_roi(
this->camera,
static_cast<::dc1394video_mode_t>(videoMode),
static_cast<::dc1394color_coding_t>(colorCoding),
DC1394_QUERY_FROM_CAMERA,
left,
top,
width,
height
);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
this->colorCoding = colorCoding;
this->height = height;
this->left = left;
this->top = top;
this->videoMode = videoMode;
this->width = width;
}
void
Dc1394Camera::setFramerate(const Framerate& framerate)
{
::dc1394error_t error = ::dc1394_video_set_framerate(this->camera, static_cast<::dc1394framerate_t>(framerate));
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
this->framerate = framerate;
}
void
Dc1394Camera::setNode(const unsigned int& node)
{
this->node = node;
}
void
Dc1394Camera::setOperationMode(const OperationMode& mode)
{
::dc1394error_t error = ::dc1394_video_set_operation_mode(this->camera, static_cast<::dc1394operation_mode_t>(mode));
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
void
Dc1394Camera::setSpeed(const IsoSpeed& speed)
{
::dc1394error_t error = ::dc1394_video_set_iso_speed(this->camera, static_cast<::dc1394speed_t>(speed));
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
this->speed = speed;
}
void
Dc1394Camera::setVideoMode(const VideoMode& videoMode)
{
::dc1394error_t error = ::dc1394_video_set_mode(this->camera, static_cast<::dc1394video_mode_t>(videoMode));
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
this->videoMode = videoMode;
}
void
Dc1394Camera::start()
{
::dc1394error_t error = ::dc1394_capture_setup(this->camera, this->buffer, 0);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
error = ::dc1394_camera_set_power(this->camera, ::DC1394_ON);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
error = ::dc1394_video_set_transmission(this->camera, ::DC1394_ON);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
void
Dc1394Camera::step()
{
}
void
Dc1394Camera::stop()
{
::dc1394error_t error = ::dc1394_video_set_transmission(this->camera, ::DC1394_OFF);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
error = ::dc1394_camera_set_power(this->camera, ::DC1394_OFF);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
error = ::dc1394_capture_stop(this->camera);
if (::DC1394_SUCCESS != error)
{
throw Exception(error);
}
}
Dc1394Camera::Exception::Exception(const ::dc1394error_t& error) :
DeviceException(""),
error(error)
{
}
Dc1394Camera::Exception::~Exception() throw()
{
}
::dc1394error_t
Dc1394Camera::Exception::getError() const
{
return this->error;
}
const char*
Dc1394Camera::Exception::what() const throw()
{
switch (this->error)
{
case ::DC1394_FAILURE:
return "Failure.";
break;
default:
return ::dc1394_error_get_string(this->error);
break;
}
}
}
}
| 11,637 |
3,102 |
// NotFramework.h
#import "NotInModule.h"
| 17 |
348 |
<filename>docs/data/leg-t2/069/06913299.json
{"nom":"Colombier-Saugnieu","circ":"13ème circonscription","dpt":"Rhône","inscrits":1868,"abs":1175,"votants":693,"blancs":36,"nuls":11,"exp":646,"res":[{"nuance":"LR","nom":"<NAME>","voix":378},{"nuance":"REM","nom":"<NAME>","voix":268}]}
| 118 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.