max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
852 | #ifndef __RecoParticleFlow_Benchmark_Matchers__
#define __RecoParticleFlow_Benchmark_Matchers__
#include "DataFormats/Math/interface/deltaR.h"
#include "DataFormats/MuonReco/interface/MuonSelectors.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/EDGetToken.h"
#include <iostream>
#include <vector>
namespace PFB {
template <typename C, typename M>
void match(const C &candCollection,
const M &matchedCandCollection,
std::vector<int> &matchIndices,
bool matchCharge = false,
float dRMax = -1) {
// compute distance to each candidate in the matchedCandCollection.
float dR2Max = 0;
if (dRMax > 0)
dR2Max = dRMax * dRMax;
matchIndices.clear();
matchIndices.resize(candCollection.size(), -1);
for (unsigned i = 0; i < candCollection.size(); ++i) {
static const double bigNumber = 1e14;
double dR2min = bigNumber;
int jMin = -1;
for (unsigned jm = 0; jm < matchedCandCollection.size(); ++jm) {
if (matchCharge && candCollection[i].charge() != matchedCandCollection[jm].charge())
continue;
double dR2 = reco::deltaR2(candCollection[i], matchedCandCollection[jm]);
if (dR2 < dR2min) {
dR2min = dR2;
jMin = jm;
}
}
if ((dR2Max > 0 && dR2min < dR2Max) || dRMax <= 0) {
matchIndices[i] = jMin;
/* std::cout<<"match "<<dR2min<<std::endl; */
}
// store the closest match, no cut on deltaR.
}
}
// needed by muon matching
// template< typename C, typename M, typename MM>
template <typename C, typename M>
void match(const C &candCollection,
const M &matchedCandCollection,
std::vector<int> &matchIndices,
const edm::ParameterSet ¶meterSet,
// const MM& muonMatchedCandCollection,
edm::View<reco::Muon> muonMatchedCandCollection,
bool matchCharge = false,
float dRMax = -1) {
// compute distance to each candidate in the matchedCandCollection.
float dR2Max = 0;
if (dRMax > 0)
dR2Max = dRMax * dRMax;
matchIndices.clear();
matchIndices.resize(candCollection.size(), -1);
for (unsigned i = 0; i < candCollection.size(); ++i) {
static const double bigNumber = 1e14;
double dR2min = bigNumber;
int jMin = -1;
for (unsigned jm = 0; jm < matchedCandCollection.size(); ++jm) {
if (parameterSet.getParameter<bool>("slimmedLikeSelection")) {
if (!(muonMatchedCandCollection[jm].pt() > parameterSet.getParameter<double>("ptBase") ||
muonMatchedCandCollection[jm].isPFMuon() ||
(muonMatchedCandCollection[jm].pt() > parameterSet.getParameter<double>("ptNotPF") &&
(muonMatchedCandCollection[jm].isGlobalMuon() || muonMatchedCandCollection[jm].isStandAloneMuon() ||
muonMatchedCandCollection[jm].numberOfMatches() > 0 ||
muon::isGoodMuon(muonMatchedCandCollection[jm], muon::RPCMuLoose)))))
continue;
}
if (matchCharge && candCollection[i].charge() != matchedCandCollection[jm].charge())
continue;
double dR2 = reco::deltaR2(candCollection[i], matchedCandCollection[jm]);
if (dR2 < dR2min) {
dR2min = dR2;
jMin = jm;
}
}
if ((dR2Max > 0 && dR2min < dR2Max) || dRMax <= 0) {
matchIndices[i] = jMin;
/* std::cout<<"match "<<dR2min<<std::endl; */
}
// store the closest match, no cut on deltaR.
}
}
} // namespace PFB
#endif
| 1,672 |
591 | <reponame>howyu88/vnpy2
/*!
@file
@copyright <NAME> and <NAME> 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_ALGORITHMS_NONE_HPP
#define BOOST_BRIGAND_ALGORITHMS_NONE_HPP
#include <brigand/algorithms/all.hpp>
#include <brigand/algorithms/detail/non_null.hpp>
#include <brigand/functions/lambda/apply.hpp>
#include <brigand/types/bool.hpp>
namespace brigand
{
#if defined(BRIGAND_COMP_MSVC_2013) || defined(BRIGAND_COMP_CUDA) || defined(BRIGAND_COMP_INTEL)
namespace detail
{
template <typename Sequence, typename Pred>
struct none_impl
{
template <typename T>
struct nope
{
using that = brigand::apply<Pred, T>;
using type = bool_<!that::value>;
};
using type = all<Sequence, nope<_1>>;
};
}
#else
namespace detail
{
template <typename Sequence, typename Predicate>
struct none_impl : bool_<true>
{
};
template <template <class...> class Sequence, typename Predicate, typename T, typename... Ts>
struct none_impl<Sequence<T, Ts...>, Predicate>
{
static constexpr all_same tester{
static_cast< ::brigand::apply<Predicate, T> *>(nullptr),
static_cast< ::brigand::apply<Predicate, Ts> *>(nullptr)...};
using type = bool_<(::brigand::apply<Predicate, T>::value == 0 && tester.value)>;
};
template <template <class...> class Sequence, template <typename...> class F, typename T,
typename... Ts>
struct none_impl<Sequence<T, Ts...>, bind<F, _1>>
{
static constexpr all_same tester{static_cast<F<T> *>(nullptr),
static_cast<F<Ts> *>(nullptr)...};
using type = bool_<(F<T>::value == 0 && tester.value)>;
};
template <template <class...> class Sequence, template <typename...> class F, typename T,
typename... Ts>
struct none_impl<Sequence<T, Ts...>, F<_1>>
{
static constexpr all_same tester{static_cast<typename F<T>::type *>(nullptr),
static_cast<typename F<Ts>::type *>(nullptr)...};
using type = bool_<(F<T>::type::value == 0 && tester.value)>;
};
}
#endif
// Is a predicate true for no type ?
template <typename Sequence, typename Predicate = detail::non_null>
using none = typename detail::none_impl<Sequence, Predicate>::type;
}
#endif
| 1,086 |
329 | <reponame>zviri/pdftotree
from typing import Tuple
TOLERANCE = 5
def doOverlap(bbox1, bbox2):
"""
:param bbox1: bounding box of the first rectangle
:param bbox2: bounding box of the second rectangle
:return: 1 if the two rectangles overlap
"""
if bbox1[2] < bbox2[0] or bbox2[2] < bbox1[0]:
return False
if bbox1[3] < bbox2[1] or bbox2[3] < bbox1[1]:
return False
return True
def isContained(bbox1, bbox2, tol=TOLERANCE):
"""
:param bbox1: bounding box of the first rectangle
:param bbox2: bounding box of the second rectangle
:return: True if bbox1 is contaned in bbox2
"""
if bbox1[0] > bbox2[0] - tol and bbox1[1] > bbox2[1] - tol:
if bbox1[2] < bbox2[2] + tol and bbox1[3] < bbox2[3] + tol:
return True
return False
def mergeBboxes(bbox1, bbox2):
"""
:param bbox1: (top, left, bottom, right)
:param bbox2: (top, left, bottom, right)
:return: Merge bounding boxes
"""
if isContained(bbox1, bbox2):
return bbox2
elif isContained(bbox2, bbox1):
return bbox1
else:
return (
min(bbox1[0], bbox2[0]),
min(bbox1[1], bbox2[1]),
max(bbox1[2], bbox2[2]),
max(bbox1[3], bbox2[3]),
)
def get_rectangles(vertical_lines, horizontal_lines):
"""
:param vertical_lines: list of vertical lines coordinates
:param horizontal_lines: list of horizontal lines coordinates
:return: List of bounding boxes for tables
"""
rectangles = []
i = 0
j = 0
while i < len(horizontal_lines) and j < len(vertical_lines):
if int(horizontal_lines[i][0]) == vertical_lines[j][0]:
if int(horizontal_lines[i][1]) == int(vertical_lines[j][1]):
h = horizontal_lines[i]
v = vertical_lines[j]
rectangles += [(v[0], h[1], v[2], h[3])]
i += 1
j += 1
elif int(horizontal_lines[i][1]) < int(vertical_lines[j][1]):
i += 1
else:
j += 1
elif int(horizontal_lines[i][0]) < int(vertical_lines[j][0]):
i += 1
else:
j += 1
rectangles = [
r
for r in rectangles
if ((r[2] - r[0]) > TOLERANCE and (r[3] - r[1]) > TOLERANCE)
]
return rectangles
def get_outer_bounding_boxes(rectangles):
"""
:param rectangles: list of bounding boxes (top, left, bottom, right)
:return: outer bounding boxes (only the largest bbox when bboxes intersect)
"""
if len(rectangles) == 0:
return []
outer_bboxes = [rectangles[0]]
for bbox2 in rectangles[1:]:
overlap_indexes = []
for i, bbox1 in enumerate(outer_bboxes): # TODO: optimize this !!
if doOverlap(bbox1, bbox2):
overlap_indexes.append(i)
for i in overlap_indexes:
bbox2 = mergeBboxes(bbox2, outer_bboxes[i])
for i in sorted(overlap_indexes, reverse=True):
del outer_bboxes[i]
outer_bboxes.append(bbox2)
return outer_bboxes
def get_intersection(bbox1, bbox2):
"""
:param bbox1: (page, width, height, top, left, bottom, right)
:param bbox2: (page, width, height, top, left, bottom, right)
:return: intersection if bboxes are in the same page and intersect
"""
intersection = []
page_1, page_width, page_height, top_1, left_1, bottom_1, right_1 = bbox1
page_2, _, _, top_2, left_2, bottom_2, right_2 = bbox2
if page_1 == page_2:
if doOverlap(
(top_1, left_1, bottom_1, right_1), (top_2, left_2, bottom_2, right_2)
):
intersection += [
(
page_1,
page_width,
page_height,
max(top_1, top_2),
max(left_1, left_2),
min(bottom_1, bottom_2),
min(right_1, right_2),
)
]
return intersection
def compute_iou(bbox1, bbox2):
"""
:param bbox1: (page, width, height, top, left, bottom, right)
:param bbox2: (page, width, height, top, left, bottom, right)
:return: intersection over union if bboxes are in the same page and intersect
"""
top_1, left_1, bottom_1, right_1 = bbox1
top_2, left_2, bottom_2, right_2 = bbox2
if doOverlap(
(top_1, left_1, bottom_1, right_1), (top_2, left_2, bottom_2, right_2)
):
intersection = (min(bottom_1, bottom_2) - max(top_1, top_2)) * (
min(right_1, right_2) - max(left_1, left_2)
)
union = (
(bottom_1 - top_1) * (right_1 - left_1)
+ (bottom_2 - top_2) * (right_2 - left_2)
- intersection
)
return float(intersection) / float(union)
return 0.0
def bbox2str(bbox: Tuple[float, float, float, float]) -> str:
"""Return a string representation suited for hOCR.
:param bbox: a bounding box (left, top, right, bottom)
:return: a string representation for hOCR
"""
(x0, y0, x1, y1) = bbox
return f"bbox {int(x0)} {int(y0)} {int(x1)} {int(y1)}"
| 2,571 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.ai.textanalytics.implementation;
import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics;
import com.azure.ai.textanalytics.util.RecognizeCustomEntitiesResultCollection;
/**
* The helper class to set the non-public properties of an {@link RecognizeCustomEntitiesResultCollection} instance.
*/
public final class RecognizeCustomEntitiesResultCollectionPropertiesHelper {
private static RecognizeCustomEntitiesResultCollectionAccessor accessor;
private RecognizeCustomEntitiesResultCollectionPropertiesHelper() { }
/**
* Type defining the methods to set the non-public properties of an {@link RecognizeCustomEntitiesResultCollection}
* instance.
*/
public interface RecognizeCustomEntitiesResultCollectionAccessor {
void setProjectName(RecognizeCustomEntitiesResultCollection resultCollection, String projectName);
void setDeploymentName(RecognizeCustomEntitiesResultCollection resultCollection, String deploymentName);
void setStatistics(RecognizeCustomEntitiesResultCollection resultCollection,
TextDocumentBatchStatistics statistics);
}
/**
* The method called from {@link RecognizeCustomEntitiesResultCollection} to set it's accessor.
*
* @param recognizeCustomEntitiesResultCollectionAccessor The accessor.
*/
public static void setAccessor(
final RecognizeCustomEntitiesResultCollectionAccessor recognizeCustomEntitiesResultCollectionAccessor) {
accessor = recognizeCustomEntitiesResultCollectionAccessor;
}
public static void setProjectName(RecognizeCustomEntitiesResultCollection resultCollection, String projectName) {
accessor.setProjectName(resultCollection, projectName);
}
public static void setDeploymentName(RecognizeCustomEntitiesResultCollection resultCollection,
String deploymentName) {
accessor.setDeploymentName(resultCollection, deploymentName);
}
public static void setStatistics(RecognizeCustomEntitiesResultCollection resultCollection,
TextDocumentBatchStatistics statistics) {
accessor.setStatistics(resultCollection, statistics);
}
}
| 644 |
394 | <gh_stars>100-1000
/*
* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.msf4j;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Represents a transport session.
*/
public class Session implements Serializable {
private static final long serialVersionUID = -3945729418329160933L;
private transient SessionManager sessionManager;
private String id;
private long creationTime;
private long lastAccessedTime;
private int maxInactiveInterval;
private boolean isValid = true;
private boolean isNew = true;
private Map<String, Object> attributes = new ConcurrentHashMap<>();
public Session() {
}
public Session(String id, int maxInactiveInterval) {
this.id = id;
this.maxInactiveInterval = maxInactiveInterval;
creationTime = System.currentTimeMillis();
lastAccessedTime = creationTime;
}
long getCreationTime() {
return creationTime;
}
String getId() {
return id;
}
void setMaxInactiveInterval(int interval) {
this.maxInactiveInterval = interval;
}
int getMaxInactiveInterval() {
return maxInactiveInterval;
}
public Object getAttribute(String name) {
checkValidity();
return attributes.get(name);
}
public Set<String> getAttributeNames() {
checkValidity();
return attributes.keySet();
}
public void setAttribute(String name, Object value) {
checkValidity();
attributes.put(name, value);
sessionManager.updateSession(this);
}
public void removeAttribute(String name) {
checkValidity();
sessionManager.updateSession(this);
attributes.remove(name);
}
private void checkValidity() {
if (!isValid) {
throw new IllegalStateException("Session is invalid");
}
}
public void invalidate() {
sessionManager.invalidateSession(this);
attributes.clear();
isValid = false;
}
boolean isValid() {
return isValid;
}
boolean isNew() {
return isNew;
}
boolean getIsNew() {
return isNew;
}
public void setNew(boolean isNew) {
this.isNew = isNew;
}
Session setAccessed() {
checkValidity();
lastAccessedTime = System.currentTimeMillis();
return this;
}
long getLastAccessedTime() {
return lastAccessedTime;
}
public void setManager(SessionManager sessionManager) {
this.sessionManager = sessionManager;
}
}
| 1,204 |
1,581 | <gh_stars>1000+
//
// PullToRefreshExampleViewController.h
// AppDevKit
//
// Created by <NAME> on 12/6/15.
// Copyright © 2015, Yahoo Inc.
// Licensed under the terms of the BSD License.
// Please see the LICENSE file in the project root for terms.
//
#import <UIKit/UIKit.h>
@interface PullToRefreshExampleViewController : UIViewController
@end
| 119 |
975 | from .http_proxy import HttpProxy, HttpUpstreamProxy
from .socks_proxy import SocksUpstreamProxy
__all__ = [
"HttpProxy", "HttpUpstreamProxy",
"SocksUpstreamProxy",
]
| 63 |
665 | import time
import array
import board
import busio
import audiobusio
import displayio
from adafruit_st7789 import ST7789
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text import label
#---| User Configuration |---------------------------
SAMPLERATE = 16000
SAMPLES = 1024
THRESHOLD = 100
MIN_DELTAS = 5
DELAY = 0.2
# octave = 1 2 3 4 5 6 7 8
NOTES = { "C" : (33, 65, 131, 262, 523, 1047, 2093, 4186),
"D" : (37, 73, 147, 294, 587, 1175, 2349, 4699),
"E" : (41, 82, 165, 330, 659, 1319, 2637, 5274),
"F" : (44, 87, 175, 349, 698, 1397, 2794, 5588),
"G" : (49, 98, 196, 392, 785, 1568, 3136, 6272),
"A" : (55, 110, 220, 440, 880, 1760, 3520, 7040),
"B" : (62, 123, 247, 494, 988, 1976, 3951, 7902)}
#----------------------------------------------------
# Create a buffer to record into
samples = array.array('H', [0] * SAMPLES)
# Setup the mic input
mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK,
board.MICROPHONE_DATA,
sample_rate=SAMPLERATE,
bit_depth=16)
# Setup TFT Gizmo
displayio.release_displays()
spi = busio.SPI(board.SCL, MOSI=board.SDA)
tft_cs = board.RX
tft_dc = board.TX
tft_backlight = board.A3
display_bus = displayio.FourWire(spi, command=tft_dc, chip_select=tft_cs)
display = ST7789(display_bus, width=240, height=240, rowstart=80,
backlight_pin=tft_backlight, rotation=180)
# Setup the various text labels
note_font = bitmap_font.load_font("/monoMMM_5_90.bdf")
note_text = label.Label(note_font, text="A", color=0xFFFFFF)
note_text.x = 90
note_text.y = 100
oct_font = bitmap_font.load_font("/monoMMM_5_24.bdf")
oct_text = label.Label(oct_font, text=" ", color=0x00FFFF)
oct_text.x = 180
oct_text.y = 150
freq_font = oct_font
freq_text = label.Label(freq_font, text="f = 1234.5", color=0xFFFF00)
freq_text.x = 20
freq_text.y = 220
# Add everything to the display group
splash = displayio.Group()
splash.append(note_text)
splash.append(oct_text)
splash.append(freq_text)
display.show(splash)
while True:
# Get raw mic data
mic.record(samples, SAMPLES)
# Compute DC offset (mean) and threshold level
mean = int(sum(samples) / len(samples) + 0.5)
threshold = mean + THRESHOLD
# Compute deltas between mean crossing points
# (this bit by <NAME>)
deltas = []
last_xing_point = None
crossed_threshold = False
for i in range(SAMPLES-1):
sample = samples[i]
if sample > threshold:
crossed_threshold = True
if crossed_threshold and sample < mean:
if last_xing_point:
deltas.append(i - last_xing_point)
last_xing_point = i
crossed_threshold = False
# Try again if not enough deltas
if len(deltas) < MIN_DELTAS:
continue
# Average the deltas
mean = sum(deltas) / len(deltas)
# Compute frequency
freq = SAMPLERATE / mean
print("crossings: {} mean: {} freq: {} ".format(len(deltas), mean, freq))
freq_text.text = "f = {:6.1f}".format(freq)
# Find corresponding note
for note in NOTES:
for octave, note_freq in enumerate(NOTES[note]):
if note_freq * 0.97 <= freq <= note_freq * 1.03:
print("Note: {}{}".format(note, octave + 1))
note_text.text = note
oct_text.text = "{}".format(octave + 1)
time.sleep(DELAY)
| 1,605 |
310 | <reponame>dreeves/usesthis
{
"name": "EOS C500 Mark II",
"description": "A digital cinema camera.",
"url": "https://www.usa.canon.com/internet/portal/us/home/products/details/cameras/cinema-eos/cinema-eos-c500-mark-ii"
}
| 95 |
312 | <filename>core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeGraphQueryResultTest.java
/*******************************************************************************
* Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.sail.nativerdf;
import java.io.IOException;
import org.eclipse.rdf4j.repository.GraphQueryResultTest;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
public class NativeGraphQueryResultTest extends GraphQueryResultTest {
@Rule
public final TemporaryFolder tmpDir = new TemporaryFolder();
@Override
protected Repository newRepository() throws IOException {
return new SailRepository(new NativeStore(tmpDir.getRoot(), "spoc"));
}
}
| 333 |
450 | <gh_stars>100-1000
import exceptions
class Data:
class DataError(exceptions.ValueError): pass
def __init__(self, value):
self.value = value
def get_value(self):
return self.value
| 81 |
597 | package com.xiaojukeji.kafka.manager.web.api.versionone.thirdpart;
import com.xiaojukeji.kafka.manager.common.entity.Result;
import com.xiaojukeji.kafka.manager.common.entity.ResultStatus;
import com.xiaojukeji.kafka.manager.common.entity.dto.op.topic.TopicCreationDTO;
import com.xiaojukeji.kafka.manager.common.entity.dto.op.topic.TopicDeletionDTO;
import com.xiaojukeji.kafka.manager.openapi.common.dto.ConsumeHealthDTO;
import com.xiaojukeji.kafka.manager.openapi.common.dto.OffsetResetDTO;
import com.xiaojukeji.kafka.manager.web.config.BaseTest;
import com.xiaojukeji.kafka.manager.web.config.ConfigConstant;
import com.xiaojukeji.kafka.manager.web.config.CustomDataSource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.*;
/**
* @author xuguang
* @Date 2022/2/24
*/
public class ThirdPartConsumerControllerTest extends BaseTest {
@BeforeClass
public void init() {
super.init();
String url = baseUrl + "/api/v1/op/topics";
createCommonTopic(url);
}
@AfterClass
public void afterTest() {
// 删除Topic成功
String url = baseUrl + "/api/v1/op/topics";
deleteTopics(url);
}
private void createCommonTopic(String url) {
// 创建Topic
TopicCreationDTO creationDTO = CustomDataSource.getTopicCreationDTO(configMap);
HttpEntity<TopicCreationDTO> httpEntity = new HttpEntity<>(creationDTO, httpHeaders);
ResponseEntity<Result> result = testRestTemplate.exchange(url, HttpMethod.POST, httpEntity, Result.class);
Assert.assertEquals(result.getStatusCodeValue(), HttpStatus.OK.value());
Assert.assertNotNull(result.getBody());
Assert.assertEquals(result.getBody().getCode(), ResultStatus.SUCCESS.getCode());
}
private void deleteTopics(String url) {
// 删除创建的topic
TopicDeletionDTO topicDeletionDTO = CustomDataSource.getTopicDeletionDTO(configMap);
HttpEntity<List<TopicDeletionDTO>> httpEntity2 = new HttpEntity<>(Arrays.asList(topicDeletionDTO), httpHeaders);
ResponseEntity<Result> result2 = testRestTemplate.exchange(url, HttpMethod.DELETE, httpEntity2, Result.class);
Assert.assertEquals(result2.getStatusCodeValue(), HttpStatus.OK.value());
Assert.assertNotNull(result2.getBody());
Assert.assertEquals(result2.getBody().getCode(), ResultStatus.SUCCESS.getCode());
}
@Test(description = "测c消费组健康")
public void consumerHealthTest() {
ConsumeHealthDTO consumeHealthDTO = new ConsumeHealthDTO();
consumeHealthDTO.setClusterId(physicalClusterId);
consumeHealthDTO.setTopicNameList(Arrays.asList(configMap.get(ConfigConstant.TOPIC_NAME)));
consumeHealthDTO.setConsumerGroup("test");
consumeHealthDTO.setMaxDelayTime(System.currentTimeMillis());
String url = baseUrl + "/api/v1/third-part/clusters/consumer-health";
HttpEntity<ConsumeHealthDTO> httpEntity = new HttpEntity<>(consumeHealthDTO, httpHeaders);
ResponseEntity<Result> result = testRestTemplate.exchange(url, HttpMethod.POST, httpEntity, Result.class);
Assert.assertEquals(result.getStatusCodeValue(), HttpStatus.OK.value());
Assert.assertNotNull(result.getBody());
Assert.assertEquals(result.getBody().getCode(), ResultStatus.SUCCESS.getCode());
}
@Test(description = "测试重置消费组")
public void resetOffsetTest() {
}
private void resetOffset() {
OffsetResetDTO offsetResetDTO = new OffsetResetDTO();
offsetResetDTO.setClusterId(physicalClusterId);
offsetResetDTO.setTopicName(configMap.get(ConfigConstant.TOPIC_NAME));
offsetResetDTO.setConsumerGroup("test");
offsetResetDTO.setLocation("broker");
offsetResetDTO.setOffsetResetType(0);
offsetResetDTO.setAppId(configMap.get(ConfigConstant.APPID));
offsetResetDTO.setOperator(ConfigConstant.ADMIN_USER);
offsetResetDTO.setPassword(<PASSWORD>);
offsetResetDTO.setSubscribeReset(true);
offsetResetDTO.setPartitionOffsetDTOList(new ArrayList<>());
offsetResetDTO.setTimestamp(System.currentTimeMillis());
offsetResetDTO.setSystemCode("kafka-manager");
String url = "/api/v1/third-part/consumers/offsets";
HttpEntity<OffsetResetDTO> httpEntity = new HttpEntity<>(offsetResetDTO, httpHeaders);
ResponseEntity<Result> result = testRestTemplate.exchange(url, HttpMethod.PUT, httpEntity, Result.class);
Assert.assertEquals(result.getStatusCodeValue(), HttpStatus.OK.value());
Assert.assertNotNull(result.getBody());
Assert.assertEquals(result.getBody().getCode(), ResultStatus.PARAM_ILLEGAL.getCode());
}
@Test(description = "测试查询消费组的消费详情")
public void getConsumeDetailTest() {
String url = baseUrl + "/api/v1/third-part/{physicalClusterId}" +
"/consumers/{consumerGroup}/topics/{topicName}/consume-details?location=broker";
HttpEntity<String> httpEntity = new HttpEntity<>("", httpHeaders);
Map<String, Object> urlVariables = new HashMap<>();
urlVariables.put("physicalClusterId", physicalClusterId);
urlVariables.put("consumerGroup", "test");
urlVariables.put("topicName", configMap.get(ConfigConstant.TOPIC_NAME));
ResponseEntity<Result> result = testRestTemplate.exchange(url, HttpMethod.GET, httpEntity, Result.class, urlVariables);
Assert.assertEquals(result.getStatusCodeValue(), HttpStatus.OK.value());
Assert.assertNotNull(result.getBody());
Assert.assertEquals(result.getBody().getCode(), ResultStatus.OPERATION_FAILED.getCode());
}
}
| 2,342 |
1,444 | package mage.cards.s;
import mage.MageInt;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.keyword.SpectacleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class SpikewheelAcrobat extends CardImpl {
public SpikewheelAcrobat(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{R}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.ROGUE);
this.power = new MageInt(5);
this.toughness = new MageInt(2);
// Spectacle {2}{R}
this.addAbility(new SpectacleAbility(this, new ManaCostsImpl("{2}{R}")));
}
private SpikewheelAcrobat(final SpikewheelAcrobat card) {
super(card);
}
@Override
public SpikewheelAcrobat copy() {
return new SpikewheelAcrobat(this);
}
}
| 390 |
575 | <gh_stars>100-1000
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/download/public/common/download_stats.h"
#include <map>
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/download/public/common/download_interrupt_reasons.h"
#include "components/safe_browsing/buildflags.h"
#include "net/http/http_content_disposition.h"
#include "net/http/http_util.h"
// TODO(crbug/1056278): Launch this on Fuchsia. We should also consider serving
// an empty FileTypePolicies to platforms without Safe Browsing to remove the
// BUILDFLAGs and nogncheck here.
#if (BUILDFLAG(FULL_SAFE_BROWSING) || BUILDFLAG(SAFE_BROWSING_DB_REMOTE)) && \
!defined(OS_FUCHSIA)
#include "components/safe_browsing/core/file_type_policies.h" // nogncheck
#endif
namespace download {
namespace {
// All possible error codes from the network module. Note that the error codes
// are all positive (since histograms expect positive sample values).
const int kAllInterruptReasonCodes[] = {
#define INTERRUPT_REASON(label, value) (value),
#include "components/download/public/common/download_interrupt_reason_values.h"
#undef INTERRUPT_REASON
};
// These values are based on net::HttpContentDisposition::ParseResult values.
// Values other than HEADER_PRESENT and IS_VALID are only measured if |IS_VALID|
// is true.
enum ContentDispositionCountTypes {
// Count of downloads which had a Content-Disposition headers. The total
// number of downloads is measured by UNTHROTTLED_COUNT.
CONTENT_DISPOSITION_HEADER_PRESENT = 0,
// Either 'filename' or 'filename*' attributes were valid and
// yielded a non-empty filename.
CONTENT_DISPOSITION_IS_VALID,
// The following enum values correspond to
// net::HttpContentDisposition::ParseResult.
CONTENT_DISPOSITION_HAS_DISPOSITION_TYPE,
CONTENT_DISPOSITION_HAS_UNKNOWN_TYPE,
CONTENT_DISPOSITION_HAS_NAME, // Obsolete; kept for UMA compatiblity.
CONTENT_DISPOSITION_HAS_FILENAME,
CONTENT_DISPOSITION_HAS_EXT_FILENAME,
CONTENT_DISPOSITION_HAS_NON_ASCII_STRINGS,
CONTENT_DISPOSITION_HAS_PERCENT_ENCODED_STRINGS,
CONTENT_DISPOSITION_HAS_RFC2047_ENCODED_STRINGS,
CONTENT_DISPOSITION_HAS_NAME_ONLY, // Obsolete; kept for UMA compatiblity.
CONTENT_DISPOSITION_HAS_SINGLE_QUOTED_FILENAME,
CONTENT_DISPOSITION_LAST_ENTRY
};
// The maximum size in KB for the file size metric, file size larger than this
// will be kept in overflow bucket.
const int64_t kMaxFileSizeKb = 4 * 1024 * 1024; /* 4GB. */
const int64_t kHighBandwidthBytesPerSecond = 30 * 1024 * 1024;
// Helper method to calculate the bandwidth given the data length and time.
int64_t CalculateBandwidthBytesPerSecond(size_t length,
base::TimeDelta elapsed_time) {
int64_t elapsed_time_ms = elapsed_time.InMilliseconds();
if (0 == elapsed_time_ms)
elapsed_time_ms = 1;
return 1000 * static_cast<int64_t>(length) / elapsed_time_ms;
}
// Helper method to record the bandwidth for a given metric.
void RecordBandwidthMetric(const std::string& metric, int bandwidth) {
base::UmaHistogramCustomCounts(metric, bandwidth, 1, 50 * 1000 * 1000, 50);
}
// Records a histogram with download source suffix.
std::string CreateHistogramNameWithSuffix(const std::string& name,
DownloadSource download_source) {
std::string suffix;
switch (download_source) {
case DownloadSource::UNKNOWN:
suffix = "UnknownSource";
break;
case DownloadSource::NAVIGATION:
suffix = "Navigation";
break;
case DownloadSource::DRAG_AND_DROP:
suffix = "DragAndDrop";
break;
case DownloadSource::FROM_RENDERER:
suffix = "FromRenderer";
break;
case DownloadSource::EXTENSION_API:
suffix = "ExtensionAPI";
break;
case DownloadSource::EXTENSION_INSTALLER:
suffix = "ExtensionInstaller";
break;
case DownloadSource::INTERNAL_API:
suffix = "InternalAPI";
break;
case DownloadSource::WEB_CONTENTS_API:
suffix = "WebContentsAPI";
break;
case DownloadSource::OFFLINE_PAGE:
suffix = "OfflinePage";
break;
case DownloadSource::CONTEXT_MENU:
suffix = "ContextMenu";
break;
case DownloadSource::RETRY:
suffix = "Retry";
break;
}
return name + "." + suffix;
}
void RecordConnectionType(
const std::string& name,
net::NetworkChangeNotifier::ConnectionType connection_type,
DownloadSource download_source) {
using ConnectionType = net::NetworkChangeNotifier::ConnectionType;
base::UmaHistogramExactLinear(name, connection_type,
ConnectionType::CONNECTION_LAST + 1);
base::UmaHistogramExactLinear(
CreateHistogramNameWithSuffix(name, download_source), connection_type,
ConnectionType::CONNECTION_LAST + 1);
}
} // namespace
void RecordDownloadCount(DownloadCountTypes type) {
UMA_HISTOGRAM_ENUMERATION("Download.Counts", type,
DOWNLOAD_COUNT_TYPES_LAST_ENTRY);
}
void RecordDownloadCountWithSource(DownloadCountTypes type,
DownloadSource download_source) {
RecordDownloadCount(type);
std::string name =
CreateHistogramNameWithSuffix("Download.Counts", download_source);
base::UmaHistogramEnumeration(name, type, DOWNLOAD_COUNT_TYPES_LAST_ENTRY);
}
void RecordNewDownloadStarted(
net::NetworkChangeNotifier::ConnectionType connection_type,
DownloadSource download_source) {
RecordDownloadCountWithSource(NEW_DOWNLOAD_COUNT, download_source);
RecordConnectionType("Download.NetworkConnectionType.StartNew",
connection_type, download_source);
}
void RecordDownloadCompleted(
int64_t download_len,
bool is_parallelizable,
net::NetworkChangeNotifier::ConnectionType connection_type,
DownloadSource download_source) {
RecordDownloadCountWithSource(COMPLETED_COUNT, download_source);
int64_t max = 1024 * 1024 * 1024; // One Terabyte.
download_len /= 1024; // In Kilobytes
UMA_HISTOGRAM_CUSTOM_COUNTS("Download.DownloadSize", download_len, 1, max,
256);
if (is_parallelizable) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Download.DownloadSize.Parallelizable",
download_len, 1, max, 256);
}
RecordConnectionType("Download.NetworkConnectionType.Complete",
connection_type, download_source);
}
void RecordDownloadInterrupted(DownloadInterruptReason reason,
int64_t received,
int64_t total,
bool is_parallelizable,
bool is_parallel_download_enabled,
DownloadSource download_source) {
RecordDownloadCountWithSource(INTERRUPTED_COUNT, download_source);
if (is_parallelizable) {
RecordParallelizableDownloadCount(INTERRUPTED_COUNT,
is_parallel_download_enabled);
}
std::vector<base::HistogramBase::Sample> samples =
base::CustomHistogram::ArrayToCustomEnumRanges(kAllInterruptReasonCodes);
UMA_HISTOGRAM_CUSTOM_ENUMERATION("Download.InterruptedReason", reason,
samples);
std::string name = CreateHistogramNameWithSuffix("Download.InterruptedReason",
download_source);
base::HistogramBase* counter = base::CustomHistogram::FactoryGet(
name, samples, base::HistogramBase::kUmaTargetedHistogramFlag);
counter->Add(reason);
if (is_parallel_download_enabled) {
UMA_HISTOGRAM_CUSTOM_ENUMERATION(
"Download.InterruptedReason.ParallelDownload", reason, samples);
}
// The maximum should be 2^kBuckets, to have the logarithmic bucket
// boundaries fall on powers of 2.
static const int kBuckets = 30;
static const int64_t kMaxKb = 1 << kBuckets; // One Terabyte, in Kilobytes.
int64_t delta_bytes = total - received;
bool unknown_size = total <= 0;
int64_t received_kb = received / 1024;
if (is_parallel_download_enabled) {
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Download.InterruptedReceivedSizeK.ParallelDownload", received_kb, 1,
kMaxKb, kBuckets);
}
if (!unknown_size) {
if (delta_bytes == 0) {
RecordDownloadCountWithSource(INTERRUPTED_AT_END_COUNT, download_source);
if (is_parallelizable) {
RecordParallelizableDownloadCount(INTERRUPTED_AT_END_COUNT,
is_parallel_download_enabled);
}
}
}
}
void RecordDownloadResumption(DownloadInterruptReason reason,
bool user_resume) {
std::vector<base::HistogramBase::Sample> samples =
base::CustomHistogram::ArrayToCustomEnumRanges(kAllInterruptReasonCodes);
UMA_HISTOGRAM_CUSTOM_ENUMERATION("Download.Resume.LastReason", reason,
samples);
base::UmaHistogramBoolean("Download.Resume.UserResume", user_resume);
}
void RecordAutoResumeCountLimitReached(DownloadInterruptReason reason) {
base::UmaHistogramBoolean("Download.Resume.AutoResumeLimitReached", true);
std::vector<base::HistogramBase::Sample> samples =
base::CustomHistogram::ArrayToCustomEnumRanges(kAllInterruptReasonCodes);
UMA_HISTOGRAM_CUSTOM_ENUMERATION(
"Download.Resume.AutoResumeLimitReached.LastReason", reason, samples);
}
void RecordDangerousDownloadAccept(DownloadDangerType danger_type,
const base::FilePath& file_path) {
UMA_HISTOGRAM_ENUMERATION("Download.UserValidatedDangerousDownload",
danger_type, DOWNLOAD_DANGER_TYPE_MAX);
#if (BUILDFLAG(FULL_SAFE_BROWSING) || BUILDFLAG(SAFE_BROWSING_DB_REMOTE)) && \
!defined(OS_FUCHSIA)
// This can only be recorded for certain platforms, since the enum used for
// file types is provided by safe_browsing::FileTypePolicies.
if (danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE) {
base::UmaHistogramSparse(
"Download.DangerousFile.DownloadValidatedByType",
safe_browsing::FileTypePolicies::GetInstance()->UmaValueForFile(
file_path));
}
#endif
}
namespace {
int GetMimeTypeMatch(const std::string& mime_type_string,
std::map<std::string, int> mime_type_map) {
for (const auto& entry : mime_type_map) {
if (entry.first == mime_type_string) {
return entry.second;
}
}
return 0;
}
static std::map<std::string, DownloadContent>
getMimeTypeToDownloadContentMap() {
return {
{"application/octet-stream", DownloadContent::OCTET_STREAM},
{"binary/octet-stream", DownloadContent::OCTET_STREAM},
{"application/pdf", DownloadContent::PDF},
{"application/msword", DownloadContent::DOCUMENT},
{"application/"
"vnd.openxmlformats-officedocument.wordprocessingml.document",
DownloadContent::DOCUMENT},
{"application/rtf", DownloadContent::DOCUMENT},
{"application/vnd.oasis.opendocument.text", DownloadContent::DOCUMENT},
{"application/vnd.google-apps.document", DownloadContent::DOCUMENT},
{"application/vnd.ms-excel", DownloadContent::SPREADSHEET},
{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
DownloadContent::SPREADSHEET},
{"application/vnd.oasis.opendocument.spreadsheet",
DownloadContent::SPREADSHEET},
{"application/vnd.google-apps.spreadsheet", DownloadContent::SPREADSHEET},
{"application/vns.ms-powerpoint", DownloadContent::PRESENTATION},
{"application/"
"vnd.openxmlformats-officedocument.presentationml.presentation",
DownloadContent::PRESENTATION},
{"application/vnd.oasis.opendocument.presentation",
DownloadContent::PRESENTATION},
{"application/vnd.google-apps.presentation",
DownloadContent::PRESENTATION},
{"application/zip", DownloadContent::ARCHIVE},
{"application/x-gzip", DownloadContent::ARCHIVE},
{"application/x-rar-compressed", DownloadContent::ARCHIVE},
{"application/x-tar", DownloadContent::ARCHIVE},
{"application/x-bzip", DownloadContent::ARCHIVE},
{"application/x-bzip2", DownloadContent::ARCHIVE},
{"application/x-7z-compressed", DownloadContent::ARCHIVE},
{"application/x-exe", DownloadContent::EXECUTABLE},
{"application/java-archive", DownloadContent::EXECUTABLE},
{"application/vnd.apple.installer+xml", DownloadContent::EXECUTABLE},
{"application/x-csh", DownloadContent::EXECUTABLE},
{"application/x-sh", DownloadContent::EXECUTABLE},
{"application/x-apple-diskimage", DownloadContent::DMG},
{"application/x-chrome-extension", DownloadContent::CRX},
{"application/xhtml+xml", DownloadContent::WEB},
{"application/xml", DownloadContent::WEB},
{"application/javascript", DownloadContent::WEB},
{"application/json", DownloadContent::WEB},
{"application/typescript", DownloadContent::WEB},
{"application/vnd.mozilla.xul+xml", DownloadContent::WEB},
{"application/vnd.amazon.ebook", DownloadContent::EBOOK},
{"application/epub+zip", DownloadContent::EBOOK},
{"application/vnd.android.package-archive", DownloadContent::APK}};
}
// NOTE: Keep in sync with DownloadImageType in
// tools/metrics/histograms/enums.xml.
enum DownloadImage {
DOWNLOAD_IMAGE_UNRECOGNIZED = 0,
DOWNLOAD_IMAGE_GIF = 1,
DOWNLOAD_IMAGE_JPEG = 2,
DOWNLOAD_IMAGE_PNG = 3,
DOWNLOAD_IMAGE_TIFF = 4,
DOWNLOAD_IMAGE_ICON = 5,
DOWNLOAD_IMAGE_WEBP = 6,
DOWNLOAD_IMAGE_PSD = 7,
DOWNLOAD_IMAGE_SVG = 8,
DOWNLOAD_IMAGE_MAX = 9,
};
static std::map<std::string, int> getMimeTypeToDownloadImageMap() {
return {{"image/gif", DOWNLOAD_IMAGE_GIF},
{"image/jpeg", DOWNLOAD_IMAGE_JPEG},
{"image/png", DOWNLOAD_IMAGE_PNG},
{"image/tiff", DOWNLOAD_IMAGE_TIFF},
{"image/vnd.microsoft.icon", DOWNLOAD_IMAGE_ICON},
{"image/x-icon", DOWNLOAD_IMAGE_ICON},
{"image/webp", DOWNLOAD_IMAGE_WEBP},
{"image/vnd.adobe.photoshop", DOWNLOAD_IMAGE_PSD},
{"image/svg+xml", DOWNLOAD_IMAGE_SVG}};
}
void RecordDownloadImageType(const std::string& mime_type_string) {
DownloadImage download_image = DownloadImage(
GetMimeTypeMatch(mime_type_string, getMimeTypeToDownloadImageMap()));
UMA_HISTOGRAM_ENUMERATION("Download.ContentType.Image", download_image,
DOWNLOAD_IMAGE_MAX);
}
/** Text categories **/
// NOTE: Keep in sync with DownloadTextType in
// tools/metrics/histograms/enums.xml.
enum DownloadText {
DOWNLOAD_TEXT_UNRECOGNIZED = 0,
DOWNLOAD_TEXT_PLAIN = 1,
DOWNLOAD_TEXT_CSS = 2,
DOWNLOAD_TEXT_CSV = 3,
DOWNLOAD_TEXT_HTML = 4,
DOWNLOAD_TEXT_CALENDAR = 5,
DOWNLOAD_TEXT_MAX = 6,
};
static std::map<std::string, int> getMimeTypeToDownloadTextMap() {
return {{"text/plain", DOWNLOAD_TEXT_PLAIN},
{"text/css", DOWNLOAD_TEXT_CSS},
{"text/csv", DOWNLOAD_TEXT_CSV},
{"text/html", DOWNLOAD_TEXT_HTML},
{"text/calendar", DOWNLOAD_TEXT_CALENDAR}};
}
void RecordDownloadTextType(const std::string& mime_type_string) {
DownloadText download_text = DownloadText(
GetMimeTypeMatch(mime_type_string, getMimeTypeToDownloadTextMap()));
UMA_HISTOGRAM_ENUMERATION("Download.ContentType.Text", download_text,
DOWNLOAD_TEXT_MAX);
}
/* Audio categories */
// NOTE: Keep in sync with DownloadAudioType in
// tools/metrics/histograms/enums.xml.
enum DownloadAudio {
DOWNLOAD_AUDIO_UNRECOGNIZED = 0,
DOWNLOAD_AUDIO_AAC = 1,
DOWNLOAD_AUDIO_MIDI = 2,
DOWNLOAD_AUDIO_OGA = 3,
DOWNLOAD_AUDIO_WAV = 4,
DOWNLOAD_AUDIO_WEBA = 5,
DOWNLOAD_AUDIO_3GP = 6,
DOWNLOAD_AUDIO_3G2 = 7,
DOWNLOAD_AUDIO_MP3 = 8,
DOWNLOAD_AUDIO_MAX = 9,
};
static std::map<std::string, int> getMimeTypeToDownloadAudioMap() {
return {
{"audio/aac", DOWNLOAD_AUDIO_AAC}, {"audio/midi", DOWNLOAD_AUDIO_MIDI},
{"audio/ogg", DOWNLOAD_AUDIO_OGA}, {"audio/x-wav", DOWNLOAD_AUDIO_WAV},
{"audio/webm", DOWNLOAD_AUDIO_WEBA}, {"audio/3gpp", DOWNLOAD_AUDIO_3GP},
{"audio/3gpp2", DOWNLOAD_AUDIO_3G2}, {"audio/mp3", DOWNLOAD_AUDIO_MP3}};
}
void RecordDownloadAudioType(const std::string& mime_type_string) {
DownloadAudio download_audio = DownloadAudio(
GetMimeTypeMatch(mime_type_string, getMimeTypeToDownloadAudioMap()));
UMA_HISTOGRAM_ENUMERATION("Download.ContentType.Audio", download_audio,
DOWNLOAD_AUDIO_MAX);
}
/* Video categories */
// NOTE: Keep in sync with DownloadVideoType in
// tools/metrics/histograms/enums.xml.
enum DownloadVideo {
DOWNLOAD_VIDEO_UNRECOGNIZED = 0,
DOWNLOAD_VIDEO_AVI = 1,
DOWNLOAD_VIDEO_MPEG = 2,
DOWNLOAD_VIDEO_OGV = 3,
DOWNLOAD_VIDEO_WEBM = 4,
DOWNLOAD_VIDEO_3GP = 5,
DOWNLOAD_VIDEO_3G2 = 6,
DOWNLOAD_VIDEO_MP4 = 7,
DOWNLOAD_VIDEO_MOV = 8,
DOWNLOAD_VIDEO_WMV = 9,
DOWNLOAD_VIDEO_MAX = 10,
};
static std::map<std::string, int> getMimeTypeToDownloadVideoMap() {
return {{"video/x-msvideo", DOWNLOAD_VIDEO_AVI},
{"video/mpeg", DOWNLOAD_VIDEO_MPEG},
{"video/ogg", DOWNLOAD_VIDEO_OGV},
{"video/webm", DOWNLOAD_VIDEO_WEBM},
{"video/3gpp", DOWNLOAD_VIDEO_3GP},
{"video/3ggp2", DOWNLOAD_VIDEO_3G2},
{"video/mp4", DOWNLOAD_VIDEO_MP4},
{"video/quicktime", DOWNLOAD_VIDEO_MOV},
{"video/x-ms-wmv", DOWNLOAD_VIDEO_WMV}};
}
void RecordDownloadVideoType(const std::string& mime_type_string) {
DownloadVideo download_video = DownloadVideo(
GetMimeTypeMatch(mime_type_string, getMimeTypeToDownloadVideoMap()));
UMA_HISTOGRAM_ENUMERATION("Download.ContentType.Video", download_video,
DOWNLOAD_VIDEO_MAX);
}
// These histograms summarize download mime-types. The same data is recorded in
// a few places, as they exist to sanity-check and understand other metrics.
const char* const kDownloadMetricsVerificationNameItemSecure =
"Download.InsecureBlocking.Verification.Item.Secure";
const char* const kDownloadMetricsVerificationNameItemInsecure =
"Download.InsecureBlocking.Verification.Item.Insecure";
const char* const kDownloadMetricsVerificationNameItemOther =
"Download.InsecureBlocking.Verification.Item.Other";
const char* const kDownloadMetricsVerificationNameManagerSecure =
"Download.InsecureBlocking.Verification.Manager.Secure";
const char* const kDownloadMetricsVerificationNameManagerInsecure =
"Download.InsecureBlocking.Verification.Manager.Insecure";
const char* const kDownloadMetricsVerificationNameManagerOther =
"Download.InsecureBlocking.Verification.Manager.Other";
const char* GetDownloadValidationMetricName(
const DownloadMetricsCallsite& callsite,
const DownloadConnectionSecurity& state) {
DCHECK(callsite == DownloadMetricsCallsite::kDownloadItem ||
callsite == DownloadMetricsCallsite::kMixContentDownloadBlocking);
switch (state) {
case DOWNLOAD_SECURE:
case DOWNLOAD_TARGET_BLOB:
case DOWNLOAD_TARGET_DATA:
case DOWNLOAD_TARGET_FILE:
if (callsite == DownloadMetricsCallsite::kDownloadItem)
return kDownloadMetricsVerificationNameItemSecure;
return kDownloadMetricsVerificationNameManagerSecure;
case DOWNLOAD_TARGET_INSECURE:
case DOWNLOAD_REDIRECT_INSECURE:
case DOWNLOAD_REDIRECT_TARGET_INSECURE:
if (callsite == DownloadMetricsCallsite::kDownloadItem)
return kDownloadMetricsVerificationNameItemInsecure;
return kDownloadMetricsVerificationNameManagerInsecure;
case DOWNLOAD_TARGET_OTHER:
case DOWNLOAD_TARGET_FILESYSTEM:
case DOWNLOAD_TARGET_FTP:
if (callsite == DownloadMetricsCallsite::kDownloadItem)
return kDownloadMetricsVerificationNameItemOther;
return kDownloadMetricsVerificationNameManagerOther;
case DOWNLOAD_CONNECTION_SECURITY_MAX:
NOTREACHED();
}
NOTREACHED();
return nullptr;
}
} // namespace
DownloadContent DownloadContentFromMimeType(const std::string& mime_type_string,
bool record_content_subcategory) {
DownloadContent download_content = DownloadContent::UNRECOGNIZED;
for (const auto& entry : getMimeTypeToDownloadContentMap()) {
if (entry.first == mime_type_string) {
download_content = entry.second;
}
}
// Do partial matches.
if (download_content == DownloadContent::UNRECOGNIZED) {
if (base::StartsWith(mime_type_string, "text/",
base::CompareCase::SENSITIVE)) {
download_content = DownloadContent::TEXT;
if (record_content_subcategory)
RecordDownloadTextType(mime_type_string);
} else if (base::StartsWith(mime_type_string, "image/",
base::CompareCase::SENSITIVE)) {
download_content = DownloadContent::IMAGE;
if (record_content_subcategory)
RecordDownloadImageType(mime_type_string);
} else if (base::StartsWith(mime_type_string, "audio/",
base::CompareCase::SENSITIVE)) {
download_content = DownloadContent::AUDIO;
if (record_content_subcategory)
RecordDownloadAudioType(mime_type_string);
} else if (base::StartsWith(mime_type_string, "video/",
base::CompareCase::SENSITIVE)) {
download_content = DownloadContent::VIDEO;
if (record_content_subcategory)
RecordDownloadVideoType(mime_type_string);
} else if (base::StartsWith(mime_type_string, "font/",
base::CompareCase::SENSITIVE)) {
download_content = DownloadContent::FONT;
}
}
return download_content;
}
void RecordDownloadMimeType(const std::string& mime_type_string) {
DownloadContent download_content =
DownloadContentFromMimeType(mime_type_string, true);
UMA_HISTOGRAM_ENUMERATION("Download.Start.ContentType", download_content,
DownloadContent::MAX);
}
void RecordDownloadMimeTypeForNormalProfile(
const std::string& mime_type_string) {
UMA_HISTOGRAM_ENUMERATION(
"Download.Start.ContentType.NormalProfile",
DownloadContentFromMimeType(mime_type_string, false),
DownloadContent::MAX);
}
void RecordOpensOutstanding(int size) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Download.OpensOutstanding", size, 1 /*min*/,
(1 << 10) /*max*/, 64 /*num_buckets*/);
}
void RecordFileBandwidth(size_t length,
base::TimeDelta elapsed_time) {
RecordBandwidthMetric("Download.BandwidthOverallBytesPerSecond",
CalculateBandwidthBytesPerSecond(length, elapsed_time));
}
void RecordParallelizableDownloadCount(DownloadCountTypes type,
bool is_parallel_download_enabled) {
std::string histogram_name = is_parallel_download_enabled
? "Download.Counts.ParallelDownload"
: "Download.Counts.ParallelizableDownload";
base::UmaHistogramEnumeration(histogram_name, type,
DOWNLOAD_COUNT_TYPES_LAST_ENTRY);
}
void RecordParallelDownloadRequestCount(int request_count) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Download.ParallelDownloadRequestCount",
request_count, 1, 10, 11);
}
void RecordParallelRequestCreationFailure(DownloadInterruptReason reason) {
base::UmaHistogramSparse("Download.ParallelDownload.CreationFailureReason",
reason);
}
void RecordParallelizableDownloadStats(
size_t bytes_downloaded_with_parallel_streams,
base::TimeDelta time_with_parallel_streams,
size_t bytes_downloaded_without_parallel_streams,
base::TimeDelta time_without_parallel_streams,
bool uses_parallel_requests) {
RecordParallelizableDownloadAverageStats(
bytes_downloaded_with_parallel_streams +
bytes_downloaded_without_parallel_streams,
time_with_parallel_streams + time_without_parallel_streams);
int64_t bandwidth_without_parallel_streams = 0;
if (bytes_downloaded_without_parallel_streams > 0) {
bandwidth_without_parallel_streams = CalculateBandwidthBytesPerSecond(
bytes_downloaded_without_parallel_streams,
time_without_parallel_streams);
if (uses_parallel_requests) {
RecordBandwidthMetric(
"Download.ParallelizableDownloadBandwidth."
"WithParallelRequestsSingleStream",
bandwidth_without_parallel_streams);
} else {
RecordBandwidthMetric(
"Download.ParallelizableDownloadBandwidth."
"WithoutParallelRequests",
bandwidth_without_parallel_streams);
}
}
if (!uses_parallel_requests)
return;
if (bytes_downloaded_with_parallel_streams > 0) {
int64_t bandwidth_with_parallel_streams = CalculateBandwidthBytesPerSecond(
bytes_downloaded_with_parallel_streams, time_with_parallel_streams);
RecordBandwidthMetric(
"Download.ParallelizableDownloadBandwidth."
"WithParallelRequestsMultipleStreams",
bandwidth_with_parallel_streams);
}
}
void RecordParallelizableDownloadAverageStats(
int64_t bytes_downloaded,
const base::TimeDelta& time_span) {
if (time_span.is_zero() || bytes_downloaded <= 0)
return;
int64_t average_bandwidth =
CalculateBandwidthBytesPerSecond(bytes_downloaded, time_span);
int64_t file_size_kb = bytes_downloaded / 1024;
RecordBandwidthMetric("Download.ParallelizableDownloadBandwidth",
average_bandwidth);
UMA_HISTOGRAM_CUSTOM_COUNTS("Download.Parallelizable.FileSize", file_size_kb,
1, kMaxFileSizeKb, 50);
if (average_bandwidth > kHighBandwidthBytesPerSecond) {
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Download.Parallelizable.FileSize.HighDownloadBandwidth", file_size_kb,
1, kMaxFileSizeKb, 50);
}
}
void RecordSavePackageEvent(SavePackageEvent event) {
UMA_HISTOGRAM_ENUMERATION("Download.SavePackage", event,
SAVE_PACKAGE_LAST_ENTRY);
}
DownloadConnectionSecurity CheckDownloadConnectionSecurity(
const GURL& download_url,
const std::vector<GURL>& url_chain) {
DownloadConnectionSecurity state = DOWNLOAD_TARGET_OTHER;
if (download_url.SchemeIsHTTPOrHTTPS()) {
bool is_final_download_secure = download_url.SchemeIsCryptographic();
bool is_redirect_chain_secure = true;
if (url_chain.size() > std::size_t(1)) {
for (std::size_t i = std::size_t(0); i < url_chain.size() - 1; i++) {
if (!url_chain[i].SchemeIsCryptographic()) {
is_redirect_chain_secure = false;
break;
}
}
}
state = is_final_download_secure
? is_redirect_chain_secure ? DOWNLOAD_SECURE
: DOWNLOAD_REDIRECT_INSECURE
: is_redirect_chain_secure ? DOWNLOAD_TARGET_INSECURE
: DOWNLOAD_REDIRECT_TARGET_INSECURE;
} else if (download_url.SchemeIsBlob()) {
state = DOWNLOAD_TARGET_BLOB;
} else if (download_url.SchemeIs(url::kDataScheme)) {
state = DOWNLOAD_TARGET_DATA;
} else if (download_url.SchemeIsFile()) {
state = DOWNLOAD_TARGET_FILE;
} else if (download_url.SchemeIsFileSystem()) {
state = DOWNLOAD_TARGET_FILESYSTEM;
} else if (download_url.SchemeIs(url::kFtpScheme)) {
state = DOWNLOAD_TARGET_FTP;
}
return state;
}
void RecordDownloadValidationMetrics(DownloadMetricsCallsite callsite,
DownloadConnectionSecurity state,
DownloadContent file_type) {
base::UmaHistogramEnumeration(
GetDownloadValidationMetricName(callsite, state), file_type,
DownloadContent::MAX);
}
void RecordDownloadHttpResponseCode(int response_code,
bool is_background_mode) {
int status_code = net::HttpUtil::MapStatusCodeForHistogram(response_code);
std::vector<int> status_codes = net::HttpUtil::GetStatusCodesForHistogram();
UMA_HISTOGRAM_CUSTOM_ENUMERATION("Download.HttpResponseCode", status_code,
status_codes);
if (is_background_mode) {
UMA_HISTOGRAM_CUSTOM_ENUMERATION(
"Download.HttpResponseCode.BackgroundDownload", status_code,
status_codes);
}
}
void RecordInProgressDBCount(InProgressDBCountTypes type) {
UMA_HISTOGRAM_ENUMERATION("Download.InProgressDB.Counts", type);
}
void RecordDuplicateInProgressDownloadIdCount(int count) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Download.DuplicateInProgressDownloadIdCount",
count, 1, 10, 11);
}
void RecordResumptionRestartReason(DownloadInterruptReason reason) {
base::UmaHistogramSparse("Download.ResumptionRestart.Reason", reason);
}
void RecordDownloadManagerCreationTimeSinceStartup(
base::TimeDelta elapsed_time) {
base::UmaHistogramLongTimes("Download.DownloadManager.CreationDelay",
elapsed_time);
}
void RecordDownloadManagerMemoryUsage(size_t bytes_used) {
base::UmaHistogramMemoryKB("Download.DownloadManager.MemoryUsage",
bytes_used / 1000);
}
void RecordDownloadLaterEvent(DownloadLaterEvent event) {
base::UmaHistogramEnumeration("Download.Later.Events", event);
}
#if defined(OS_ANDROID)
void RecordBackgroundTargetDeterminationResult(
BackgroudTargetDeterminationResultTypes type) {
base::UmaHistogramEnumeration(
"MobileDownload.Background.TargetDeterminationResult", type);
}
#endif // defined(OS_ANDROID)
#if defined(OS_WIN)
void RecordWinFileMoveError(int os_error) {
base::UmaHistogramSparse("Download.WinFileMoveError", os_error);
}
#endif // defined(OS_WIN)
} // namespace download
| 12,051 |
410 | <filename>Giveme5W1H/examples/datasets/bbc/data/nodate/_50925424df5333e6032217a02669f9ec31f2cb4c8be41b60d7c8b161.json
{
"dId": "50925424df5333e6032217a02669f9ec31f2cb4c8be41b60d7c8b161",
"title": "Brown shrugs off economy fears",
"text": "<NAME> is to freeze petrol duty increases, fund a \u00a31bn package to avoid big council tax rises and boost childcare and maternity leave.\n\nIn an upbeat pre-Budget report, he slightly increased borrowing but insisted economic targets would be met. The chancellor also hailed the longest period of growth in UK \"industrial history\" but denied he was \"gloating\". But <NAME>, for the Tories, attacked government red tape and debt, dubbing Mr Brown \"Sir Wastealot\".\n\nThe shadow chancellor said <NAME>'s \"golden rule\" had \"turned to dross in his hands\" and said he was borrowing to spend, not invest, with predicted debt over the coming years totalling \u00a3170bn. Mr Letwin told MPs: \"The tide is going out on the chancellor's credibility. He is spending, borrowing and taxing so much because he is not getting value for taxpayer's money.\"\n\nVincent Cable, for the Liberal Democrats, accused Mr Brown of ducking tough choices.\n\nHe said: \"Last week the prime minister gave us the politics of fear; this week the chancellor has offered the economics of complacency. \"There are serious challenges ahead from the falling dollar and from the rapid downturn in the UK housing market and rising personal debt. But they have not been confronted.\" <NAME> rejected the Lib Dem's call to open up the government's books to the National Audit Office, saying decisions on tax and spending should be made by ministers. Some economists say his forecasts on public finances are wishful thinking. BBC economic editor <NAME> said the figures were plausible but also a gamble.\n\nMr Brown's insistence he was not \"gloating\" was a pointed rebuttal of a warning from new European Commissioner <NAME>. In his speech, he set out a 10-year childcare strategy for if Labour wins the next election.\n\nIt includes a \u00a3285m cash injection to extend paid maternity leave from six months to nine, with parents able to transfer leave from the mother to the father. He also promised to increase free nursery education for three and four-year-olds to 15 hours from April 2007. And funds would be provided to keep schools open from 0800 to 1800GMT to look after children while their parents were at work. Taken together, the measures would create a \"welfare state that is truly family-friendly for the first time in its history\", said <NAME>. He also announced a cash hand-out for older pensioners, with payments of \u00a350 for the over-70s as part of the winter fuel allowance. In a move ministers say should keep council tax rises below 5% next year, the chancellor said he was providing an extra \u00a31bn for local councils. The money is expected to come from government departments such as health and education.\n\n<NAME> said he was set to meet his two fiscal rules - to borrow only to invest and keep debt \"low and sustainable\" - both in this economic cycle and the next. Borrowing figures for 2003/4 are \u00a335bn - \u00a32.5bn less than the \u00a337.5bn predicted in March's budget, as already announced by the Office for National Statistics. Borrowing is tipped to fall to \u00a331bn by 2005/06 - but that is still \u00a32bn more than <NAME> predicted in his March budget. Inflation would be 1.75% next year and 2% in the years to follow, Mr Brown forecast. He also pledged an extra \u00a3105m for security and counter-terrorism. Business groups have welcomed efforts to improve competitiveness and invest more in skills and innovation. But there worries about the costs of more family-friendly working. <NAME>, from the Federation of Small Businesses, said: \"The proposals on maternity leave have clearly been made with a general election in mind and with little thought to the impact on small employers.\"",
"description": "",
"category": "politics",
"filename": "128.txt"
} | 1,003 |
837 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
import time
from urllib.parse import urlparse
import requests
from utils import *
# 全局配置
config = getYmlConfig()
session = requests.session()
user = config['user']
# Cpdaily-Extension
extension = {
"lon": user['lon'],
"model": "PCRT00",
"appVersion": "8.0.8",
"systemVersion": "4.4.4",
"userId": user['username'],
"systemName": "android",
"lat": user['lat'],
"deviceId": str(uuid.uuid1())
}
CpdailyInfo = DESEncrypt(json.dumps(extension))
# 获取今日校园api
def getCpdailyApis(user, debug=False):
apis = {}
schools = requests.get(url='https://www.cpdaily.com/v6/config/guest/tenant/list', verify=not debug).json()['data']
flag = True
for one in schools:
if one['name'] == user['school']:
if one['joinType'] == 'NONE':
log(user['school'] + ' 未加入今日校园')
exit(-1)
flag = False
params = {
'ids': one['id']
}
apis['tenantId'] = one['id']
res = requests.get(url='https://www.cpdaily.com/v6/config/guest/tenant/info', params=params,
verify=not debug)
data = res.json()['data'][0]
joinType = data['joinType']
idsUrl = data['idsUrl']
ampUrl = data['ampUrl']
ampUrl2 = data['ampUrl2']
if 'campusphere' in ampUrl or 'cpdaily' in ampUrl:
parse = urlparse(ampUrl)
host = parse.netloc
apis[
'login-url'] = idsUrl + '/login?service=' + parse.scheme + r"%3A%2F%2F" + host + r'%2Fportal%2Flogin'
apis['host'] = host
if 'campusphere' in ampUrl2 or 'cpdaily' in ampUrl2:
parse = urlparse(ampUrl2)
host = parse.netloc
apis[
'login-url'] = idsUrl + '/login?service=' + parse.scheme + r"%3A%2F%2F" + host + r'%2Fportal%2Flogin'
apis['host'] = host
if joinType == 'NOTCLOUD':
res = requests.get(url=apis['login-url'], verify=not debug)
if urlparse(apis['login-url']).netloc != urlparse(res.url):
apis['login-url'] = res.url
break
if user['school'] == '云南财经大学':
apis[
'login-url'] = 'http://idas.ynufe.edu.cn/authserver/login?service=https%3A%2F%2Fynufe.cpdaily.com%2Fportal%2Flogin'
if flag:
log(user['school'] + ' 未找到该院校信息,请检查是否是学校全称错误')
exit(-1)
log(apis)
return apis
apis = getCpdailyApis(user)
host = apis['host']
# 获取验证码
def getMessageCode():
log('正在获取验证码。。。')
headers = {
'SessionToken': '<PASSWORD>=',
'clientType': 'cpdaily_student',
'tenantId': apis['tenantId'],
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.4.4; PCRT00 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Safari/537.36 okhttp/3.8.1',
'deviceType': '1',
'CpdailyStandAlone': '0',
'CpdailyInfo': CpdailyInfo,
'RetrofitHeader': '8.0.8',
'Cache-Control': 'max-age=0',
'Content-Type': 'application/json; charset=UTF-8',
'Host': 'www.cpdaily.com',
'Connection': 'Keep-Alive',
'Accept-Encoding': 'gzip',
}
params = {
'mobile': DESEncrypt(str(user['tellphone']))
}
url = 'https://www.cpdaily.com/v6/auth/authentication/mobile/messageCode'
res = session.post(url=url, headers=headers, data=json.dumps(params))
errMsg = res.json()['errMsg']
if errMsg != None:
log(errMsg)
exit(-1)
log('获取验证码成功。。。')
# 手机号登陆
def mobileLogin(code):
log('正在验证验证码。。。')
headers = {
'SessionToken': '<PASSWORD>=',
'clientType': 'cpdaily_student',
'tenantId': apis['tenantId'],
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.4.4; PCRT00 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Safari/537.36 okhttp/3.8.1',
'deviceType': '1',
'CpdailyStandAlone': '0',
'CpdailyInfo': CpdailyInfo,
'RetrofitHeader': '8.0.8',
'Cache-Control': 'max-age=0',
'Content-Type': 'application/json; charset=UTF-8',
'Host': 'www.cpdaily.com',
'Connection': 'Keep-Alive',
'Accept-Encoding': 'gzip',
}
params = {
'loginToken': str(code),
'loginId': str(user['tellphone'])
}
url = 'https://www.cpdaily.com/v6/auth/authentication/mobileLogin'
res = session.post(url=url, headers=headers, data=json.dumps(params))
errMsg = res.json()['errMsg']
if errMsg != None:
log(errMsg)
exit(-1)
log('验证码验证成功。。。')
return res.json()['data']
# 验证登陆信息
def validation(data):
log('正在验证登陆信息。。。')
sessionToken = data['sessionToken']
tgc = data['tgc']
headers = {
'SessionToken': DESEncrypt(sessionToken),
'clientType': 'cpdaily_student',
'tenantId': apis['tenantId'],
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.4.4; PCRT00 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Safari/537.36 okhttp/3.8.1',
'deviceType': '1',
'CpdailyStandAlone': '0',
'CpdailyInfo': CpdailyInfo,
'RetrofitHeader': '8.0.8',
'Cache-Control': 'max-age=0',
'Content-Type': 'application/json; charset=UTF-8',
'Host': 'www.cpdaily.com',
'Connection': 'Keep-Alive',
'Accept-Encoding': 'gzip',
'Cookie': 'sessionToken=' + sessionToken
}
params = {
'tgc': DESEncrypt(tgc)
}
url = 'https://www.cpdaily.com/v6/auth/authentication/validation'
res = session.post(url=url, headers=headers, data=json.dumps(params))
errMsg = res.json()['errMsg']
if errMsg != None:
log(errMsg)
exit(-1)
log('验证登陆信息成功。。。')
return res.json()['data']
# 更新acw_tc
def updateACwTc(data):
log('正在更新acw_tc。。。')
sessionToken = data['sessionToken']
tgc = data['tgc']
amp = {
'AMP1': [{
'value': sessionToken,
'name': 'sessionToken'
}],
'AMP2': [{
'value': sessionToken,
'name': 'sessionToken'
}]
}
headers = {
'TGC': DESEncrypt(tgc),
'AmpCookies': DESEncrypt(json.dumps(amp)),
'SessionToken': DESEncrypt(sessionToken),
'clientType': 'cpdaily_student',
'tenantId': apis['tenantId'],
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.4.4; PCRT00 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Safari/537.36 okhttp/3.8.1',
'deviceType': '1',
'CpdailyStandAlone': '0',
'CpdailyInfo': CpdailyInfo,
'RetrofitHeader': '8.0.8',
'Cache-Control': 'max-age=0',
'Host': host,
'Connection': 'Keep-Alive',
'Accept-Encoding': 'gzip'
}
url = 'https://{host}/wec-portal-mobile/client/userStoreAppList'.format(host=host)
# 清除cookies
# session.cookies.clear()
session.get(url=url, headers=headers, allow_redirects=False)
log('更新acw_tc成功。。。')
# 获取MOD_AUTH_CAS
def getModAuthCas(data):
log('正在获取MOD_AUTH_CAS。。。')
sessionToken = data['sessionToken']
headers = {
'Host': host,
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.4.4; PCRT00 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Safari/537.36 cpdaily/8.0.8 wisedu/8.0.8',
'Accept-Encoding': 'gzip,deflate',
'Accept-Language': 'zh-CN,en-US;q=0.8',
'X-Requested-With': 'com.wisedu.cpdaily'
}
url = 'https://{host}/wec-counselor-collector-apps/stu/mobile/index.html?timestamp='.format(host=host) + str(
int(round(time.time() * 1000)))
res = session.get(url=url, headers=headers, allow_redirects=False)
location = res.headers['location']
# print(location)
headers2 = {
'Host': 'www.cpdaily.com',
'Connection': 'keep-alive',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.4.4; PCRT00 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Safari/537.36 cpdaily/8.0.8 wisedu/8.0.8',
'Accept-Encoding': 'gzip,deflate',
'Accept-Language': 'zh-CN,en-US;q=0.8',
'Cookie': 'clientType=cpdaily_student; tenantId=' + apis['tenantId'] + '; sessionToken=' + sessionToken,
}
res = session.get(url=location, headers=headers2, allow_redirects=False)
location = res.headers['location']
# print(location)
session.get(url=location, headers=headers)
cookies = requests.utils.dict_from_cookiejar(session.cookies)
if 'MOD_AUTH_CAS' not in cookies:
log('获取MOD_AUTH_CAS失败。。。')
exit(-1)
log('获取MOD_AUTH_CAS成功。。。')
# 通过手机号和验证码进行登陆
def login():
# 1. 获取验证码
getMessageCode()
code = input("请输入验证码:")
# 2. 手机号登陆
data = mobileLogin(code)
# 3. 验证登陆信息
data = validation(data)
# 4. 更新acw_tc
updateACwTc(data)
# 5. 获取mod_auth_cas
getModAuthCas(data)
print('==============sessionToken填写到index.py==============')
sessionToken = data['sessionToken']
print(sessionToken)
print('==============CpdailyInfo填写到index.py==============')
print(CpdailyInfo)
print('==============Cookies填写到index.py==============')
print(requests.utils.dict_from_cookiejar(session.cookies))
if __name__ == '__main__':
login()
| 5,004 |
320 | <filename>build/3rdparty_libraries.py
# Prints which 3rd party libraries are desired for the given configuration.
from components import requiredLibrariesFor
from configurations import getConfiguration
from libraries import allDependencies, librariesByName
from packages import iterDownloadablePackages
def main(platform, linkMode):
configuration = getConfiguration(linkMode)
components = configuration.iterDesiredComponents()
# Compute the set of all directly and indirectly required libraries,
# then filter out system libraries.
thirdPartyLibs = set(
makeName
for makeName in allDependencies(requiredLibrariesFor(components))
if not librariesByName[makeName].isSystemLibrary(platform)
)
print(' '.join(sorted(thirdPartyLibs)))
if __name__ == '__main__':
import sys
if len(sys.argv) == 3:
try:
main(*sys.argv[1 : ])
except ValueError as ex:
print(ex, file=sys.stderr)
sys.exit(2)
else:
print(
'Usage: python3 3rdparty_libraries.py TARGET_OS LINK_MODE',
file=sys.stderr
)
sys.exit(2)
| 337 |
377 | """Script demonstrating the use of `gym_pybullet_drones`' Gym interface.
Class TakeoffAviary is used as a learning env for the A2C and PPO algorithms.
Example
-------
In a terminal, run as:
$ python learn.py
Notes
-----
The boolean argument --rllib switches between `stable-baselines3` and `ray[rllib]`.
This is a minimal working example integrating `gym-pybullet-drones` with
reinforcement learning libraries `stable-baselines3` and `ray[rllib]`.
It is not meant as a good/effective learning example.
"""
import time
import argparse
import gym
import numpy as np
from stable_baselines3 import A2C
from stable_baselines3.a2c import MlpPolicy
from stable_baselines3.common.env_checker import check_env
import ray
from ray.tune import register_env
from ray.rllib.agents import ppo
from gym_pybullet_drones.utils.Logger import Logger
from gym_pybullet_drones.envs.single_agent_rl.TakeoffAviary import TakeoffAviary
from gym_pybullet_drones.utils.utils import sync, str2bool
if __name__ == "__main__":
#### Define and parse (optional) arguments for the script ##
parser = argparse.ArgumentParser(description='Single agent reinforcement learning example script using TakeoffAviary')
parser.add_argument('--rllib', default=False, type=str2bool, help='Whether to use RLlib PPO in place of stable-baselines A2C (default: False)', metavar='')
ARGS = parser.parse_args()
#### Check the environment's spaces ########################
env = gym.make("takeoff-aviary-v0")
print("[INFO] Action space:", env.action_space)
print("[INFO] Observation space:", env.observation_space)
check_env(env,
warn=True,
skip_render_check=True
)
#### Train the model #######################################
if not ARGS.rllib:
model = A2C(MlpPolicy,
env,
verbose=1
)
model.learn(total_timesteps=10000) # Typically not enough
else:
ray.shutdown()
ray.init(ignore_reinit_error=True)
register_env("takeoff-aviary-v0", lambda _: TakeoffAviary())
config = ppo.DEFAULT_CONFIG.copy()
config["num_workers"] = 2
config["framework"] = "torch"
config["env"] = "takeoff-aviary-v0"
agent = ppo.PPOTrainer(config)
for i in range(3): # Typically not enough
results = agent.train()
print("[INFO] {:d}: episode_reward max {:f} min {:f} mean {:f}".format(i,
results["episode_reward_max"],
results["episode_reward_min"],
results["episode_reward_mean"]
)
)
policy = agent.get_policy()
ray.shutdown()
#### Show (and record a video of) the model's performance ##
env = TakeoffAviary(gui=True,
record=False
)
logger = Logger(logging_freq_hz=int(env.SIM_FREQ/env.AGGR_PHY_STEPS),
num_drones=1
)
obs = env.reset()
start = time.time()
for i in range(3*env.SIM_FREQ):
if not ARGS.rllib:
action, _states = model.predict(obs,
deterministic=True
)
else:
action, _states, _dict = policy.compute_single_action(obs)
obs, reward, done, info = env.step(action)
logger.log(drone=0,
timestamp=i/env.SIM_FREQ,
state=np.hstack([obs[0:3], np.zeros(4), obs[3:15], np.resize(action, (4))]),
control=np.zeros(12)
)
if i%env.SIM_FREQ == 0:
env.render()
print(done)
sync(i, start, env.TIMESTEP)
if done:
obs = env.reset()
env.close()
logger.plot()
| 2,059 |
2,151 | // 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_SUBRESOURCE_FILTER_CONTENT_RENDERER_AD_DELAY_RENDERER_METADATA_PROVIDER_H_
#define COMPONENTS_SUBRESOURCE_FILTER_CONTENT_RENDERER_AD_DELAY_RENDERER_METADATA_PROVIDER_H_
#include "base/macros.h"
#include "components/subresource_filter/content/common/ad_delay_throttle.h"
#include "content/public/renderer/url_loader_throttle_provider.h"
namespace blink {
class WebURLRequest;
} // namespace blink
namespace subresource_filter {
class AdDelayRendererMetadataProvider
: public AdDelayThrottle::MetadataProvider {
public:
explicit AdDelayRendererMetadataProvider(
const blink::WebURLRequest& request,
content::URLLoaderThrottleProviderType type,
int render_frame_id);
~AdDelayRendererMetadataProvider() override;
// AdDelayThrottle::MetadataProvider:
bool IsAdRequest() override;
bool RequestIsInNonIsolatedSubframe() override;
private:
static bool IsSubframeAndNonIsolated(
content::URLLoaderThrottleProviderType type,
int render_frame_id);
const bool is_ad_request_ = false;
const bool is_non_isolated_ = false;
DISALLOW_COPY_AND_ASSIGN(AdDelayRendererMetadataProvider);
};
} // namespace subresource_filter
#endif // COMPONENTS_SUBRESOURCE_FILTER_CONTENT_RENDERER_AD_DELAY_RENDERER_METADATA_PROVIDER_H_
| 518 |
307 | <filename>bonecp/src/test/java/com/jolbox/bonecp/reportedIssues/BoneCpDataSourceTest.java
/**
* Copyright 2010 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jolbox.bonecp.reportedIssues;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import com.jolbox.bonecp.BoneCPDataSource;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Ignore
@RunWith(MockitoJUnitRunner.class)
public class BoneCpDataSourceTest {
@Mock
private Driver dummyDriver;
private BoneCPDataSource testDataSource;
@Before
public void setUp() throws Exception {
when(dummyDriver.acceptsURL(anyString())).thenReturn(true);
when(dummyDriver.connect(anyString(), any(Properties.class))).thenAnswer(new Answer<Connection>() {
public Connection answer(InvocationOnMock invocationOnMock) throws Throwable {
// Thread.sleep(500);
System.out.println("Creating dummy connection for: " + invocationOnMock.getArguments()[0]);
return mock(Connection.class);
}
});
DriverManager.registerDriver(dummyDriver);
testDataSource = new BoneCPDataSource();
testDataSource.setJdbcUrl("jdbc://dummy:url");
testDataSource.setPartitionCount(1);
testDataSource.setMinConnectionsPerPartition(1);
testDataSource.setMaxConnectionsPerPartition(6);
testDataSource.setConnectionTimeoutInMs(5000);
}
/**
* This test fails on multi core machines
*
* @throws Exception
*/
@Test
public void testConnectionTimeoutOnDataSourceWithOutSync() throws Exception {
exec(false);
}
/**
* This test passes because of the explicit lock on testDataSource
*
* @throws Exception
*/
@Test
public void testConnectionTimeoutOnDataSourceWithSync() throws Exception {
exec(true);
}
private void exec(boolean syncDataSource) throws Exception {
List<OracleDbThread> dbThreads = new ArrayList<OracleDbThread>();
int poolMaxCount = testDataSource.getMaxConnectionsPerPartition() * testDataSource.getPartitionCount();
int connectionsToClaim = poolMaxCount;
CountDownLatch connectionLatch = new CountDownLatch(connectionsToClaim);
CountDownLatch executionLatch = new CountDownLatch(connectionsToClaim);
CountDownLatch releaseLatch = new CountDownLatch(1);
System.out.println("Max number of connections allowed : " + poolMaxCount);
System.out.println("Connection timeout in ms : " + testDataSource.getConnectionTimeoutInMs());
//threads to consume all the connections
for (int i = 0; i < connectionsToClaim; i++) {
dbThreads.add(startThread(i, connectionLatch, executionLatch, releaseLatch, syncDataSource));
}
//wait for all the connections to be consumed
try {
connectionLatch.await();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught while waiting for connections");
throw e;
}
//next thread will get a wait for connection timeout
System.out.println("next thread will get a wait for connection timeout");
OracleDbThread dbThread = runNoThread(poolMaxCount);
//release the blocked threads
System.out.println("release the blocked threads");
releaseLatch.countDown();
//wait for the threads to complete
System.out.println("wait for the threads to complete");
try {
executionLatch.await();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught while waiting for execute");
throw e;
}
System.out.println("all execution complete");
for (OracleDbThread oracleDbThread : dbThreads) {
assertTrue(oracleDbThread.hadConnection.get());
}
assertFalse(dbThread.hadConnection.get());
}
private OracleDbThread startThread(int threadNum, CountDownLatch connectionLatch, CountDownLatch executionLatch, CountDownLatch releaseLatch, boolean syncDataSource) throws Exception {
OracleDbThread dbThread = new OracleDbThread(testDataSource, threadNum + 1, connectionLatch, executionLatch, releaseLatch, syncDataSource);
Thread thread = new Thread(dbThread);
thread.start();
return dbThread;
}
private OracleDbThread runNoThread(int threadNum) throws Exception {
OracleDbThread thread = new OracleDbThread(testDataSource, threadNum + 1, null, null, null, false);
thread.run();
return thread;
}
public class OracleDbThread implements Runnable {
private final BoneCPDataSource custDataSource;
private final int threadNum;
private final AtomicBoolean hadConnection = new AtomicBoolean(false);
private final CountDownLatch connectionLatch;
private final CountDownLatch executionLatch;
private CountDownLatch releaseLatch;
private boolean syncDataSource;
public OracleDbThread(BoneCPDataSource custDataSource, int threadNum, CountDownLatch connectionLatch
, CountDownLatch executionLatch, CountDownLatch releaseLatch, boolean syncDataSource) {
this.custDataSource = custDataSource;
this.threadNum = threadNum;
this.connectionLatch = connectionLatch;
this.executionLatch = executionLatch;
this.releaseLatch = releaseLatch;
this.syncDataSource = syncDataSource;
}
public void run() {
try {
System.out.println("About to consume connection " + threadNum);
Connection connection;
if(syncDataSource) {
synchronized (custDataSource) {
connection = custDataSource.getConnection();
}
} else {
connection = custDataSource.getConnection();
}
hadConnection.set(true);
System.out.println("consume connection OK " + threadNum);
if (connectionLatch != null) {
connectionLatch.countDown();
}
if (releaseLatch != null) {
System.out.println("about to wait till release " + threadNum);
releaseLatch.await();
System.out.println("Release " + threadNum);
}
connection.close();
if (executionLatch != null) {
executionLatch.countDown();
}
} catch (SQLException e) {
if (connectionLatch != null) {
connectionLatch.countDown();
}
if (executionLatch != null) {
executionLatch.countDown();
}
System.out.println(e.getMessage() + " saw an exception in thread " + threadNum);
} catch (InterruptedException e) {
if (connectionLatch != null) {
connectionLatch.countDown();
}
if (executionLatch != null) {
executionLatch.countDown();
}
System.out.println("thread sleep exception in thread " + threadNum);
e.printStackTrace();
}
}
}
}
| 3,516 |
1,200 | #ifndef CarreraConsumer_H
#define CarreraConsumer_H
#include "SimpleCarreraClient.h"
#include "ServiceDiscoveryService.h"
#include <string>
#include <map>
#include <vector>
#include <pthread.h>
#include <thrift/concurrency/Thread.h>
#include <thrift/concurrency/Mutex.h>
#include <boost/shared_ptr.hpp>
#include <mutex>
#include <condition_variable>
#include <thread>
#include "CarreraConfig.h"
#include <spdlog.h>
#include <spdlog/sinks/rotating_file_sink.h>
#include "CarreraDefine.h"
using boost::shared_ptr;
using CarreraServiceDiscovery::ServiceDiscoveryServiceClient;
using CarreraServiceDiscovery::ClientMeta;
using CarreraServiceDiscovery::ServiceMeta;
namespace CarreraConsumer {
static const std::map<std::string, int> EMPTY_EXTRA_CONCURRENCY;
class CarreraException : std::exception {
public:
CarreraException(const char *msg) {
msg_ = msg;
}
private:
const char *msg_;
virtual const char *what() const throw() {
return msg_;
}
};
class CarreraConsumer {
private:
CarreraConfig config_;
ProcessorBase* p;
std::map<std::string, int> extraConcurrency;
std::map<pthread_t, SimpleCarreraClient *> clientThreadMap;
bool validateParams();
bool createSimpleClient(const std::string &_host, int port, int clientNum, const std::string &topic = EMPTY_STRING);
public:
void SetProcessor(ProcessorBase* pro){
p = pro;
}
/* Param user guide:
* 1. _serverList: consumer proxy ip:port list, use ';' for multi, e.g. : "127.0.0.1:9713;127.0.0.2:9713;..."
* 2. _groupName: consumer group name
* 3. p: call back function for each message. User should implement this function, it is defined in SimpleCarrraClient.h:
* typedef bool (*processor)(const Message &message, const Context &context);
* // return true if successfully consumed the message, false if failed.
* 4. _clientNumPerServer: thread number to connect to each consumer proxy.
* 5. _retryInterval: the interval to sleep if there is no message now. unit is ms.
* 6. _submitMaxRetries: max retry times to submit consume result to proxy to update the offset.
* 7. _socketTimeout: connect and r/w socket time out to proxy. unit is ms.
* 8. _maxLingerTime: not used yet, for future used in long poll mode.
* 9. _maxBatchSize: max batched message number per pull request.
* 10._extraConcurrency: extra thread connect to each proxy for specified topic, e.g. <"test-0", 2>, it means
* besides _clientNumPerServer threads, it will create 2 more threads to consume topic "test-0" to each proxy.
*
*/
CarreraConsumer(std::string &_serverList, std::string &_groupName, ProcessorBase* p,
int _clientNumPerServer = 2, int _retryInterval = 100,
int _submitMaxRetries = 3, int _socketTimeout = 5000,
int _maxLingerTime = 100, int _maxBatchSize = 8,
const std::map<std::string, int> &_extraConcurrency = EMPTY_EXTRA_CONCURRENCY);
CarreraConsumer (CarreraConfig & config, ProcessorBase * p_) : config_ (config)
{
p = p_;
}
virtual ~CarreraConsumer();
void stop();
void startConsume();
void waitFinish();
};
class CarreraSdCconsumer {
public:
CarreraSdCconsumer(std::string &groupName, std::string &idc, std::string &sd_server)
: groupName_(groupName), idc_(idc), sd_server_(sd_server) {
logger_ = spdlog::get(DEFAULT_LOGGER);
if (logger_ == nullptr) {
auto logger = spdlog::rotating_logger_mt(DEFAULT_LOGGER, "./carrera_consumer.log", DEFAULT_LOG_FILE_MAX_SIZE, DEFAULT_LOG_FILE_NUM);
logger->flush_on(spdlog::level::warn);
logger_ = spdlog::get(DEFAULT_LOGGER);
}
};
virtual ~CarreraSdCconsumer(){};
void SetSdServers(std::string &sd_server) {
sd_server_ = sd_server;
}
std::string &GetSdServer() {
return sd_server_;
}
void SetCarreraConfig(CarreraConfig &config) {
config_ = config;
}
void SetProcessor(ProcessorBase* pro){
p = pro;
}
void StartConsume();
void UpdateServiceMeta();
void Stop();
private:
std::shared_ptr<spdlog::logger> logger_;
volatile int state = 0; // 0:init, 1:started 2: stopped
std::mutex mutex_client_;
std::shared_ptr<CarreraConsumer> client_;
std::shared_ptr<ServiceDiscoveryServiceClient> sd_client_;
apache::thrift::concurrency::Mutex mutex_;
std::string groupName_;
std::string idc_;
std::string sd_server_;
ProcessorBase* p;
CarreraConfig config_;
ClientMeta sd_client_meta_;
ServiceMeta sd_service_meta_;
int sd_client_timeout_ = 5000;
std::thread bg_thread;
std::mutex bg_mutex;
std::condition_variable bg_cond;
void buildClientMeta();
std::shared_ptr<ServiceDiscoveryServiceClient> createSdClient();
bool fetchMeta(ServiceMeta &meta);
void updateCarreraConfig(CarreraConfig &newConfig, ServiceMeta &meta, CarreraConfig &carreraConfig);
bool needUpdate(const ServiceMeta &oldServiceMeta, const ServiceMeta &newServiceMeta);
void updateClient(std::shared_ptr<CarreraConsumer>& client);
};
void start_sd_pull_thread(CarreraSdCconsumer &sdClient);
} // namespace
#endif
| 2,450 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-88xw-p4fq-6x82",
"modified": "2022-04-30T18:18:13Z",
"published": "2022-04-30T18:18:13Z",
"aliases": [
"CVE-2001-1532"
],
"details": "WebX stores authentication information in the HTTP_REFERER variable, which is included in URL links within bulletin board messages posted by users, which could allow remote attackers to hijack user sessions.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2001-1532"
},
{
"type": "WEB",
"url": "http://www.iss.net/security_center/static/7458.php"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/223799"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 385 |
777 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ios/chrome/browser/ios_chrome_field_trials.h"
#include "base/metrics/field_trial.h"
#include "components/ntp_tiles/field_trial.h"
#include "components/version_info/version_info.h"
#include "ios/chrome/common/channel_info.h"
void SetupIOSFieldTrials() {
// Activate the iOS tab eviction dynamic field trials.
base::FieldTrialList::FindValue("TabEviction");
// Setup a field trial for a first run experiment on Popular sites.
ntp_tiles::SetUpFirstLaunchFieldTrial(GetChannel() ==
version_info::Channel::STABLE);
}
| 257 |
354 | <filename>libs/krabs/kernel_guids.hpp
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma once
#include <guiddef.h>
#include "compiler_check.hpp"
namespace krabs { namespace guids {
DEFINE_GUID ( /* 45d8cccd-539f-4b72-a8b7-5c683142609a */
alpc,
0x45d8cccd,
0x539f,
0x4b72,
0xa8, 0xb7, 0x5c, 0x68, 0x31, 0x42, 0x60, 0x9a
);
DEFINE_GUID ( /* 13976d09-a327-438c-950b-7f03192815c7 */
debug,
0x13976d09,
0xa327,
0x438c,
0x95, 0x0b, 0x7f, 0x03, 0x19, 0x28, 0x15, 0xc7
);
DEFINE_GUID ( /* 3d6fa8d4-fe05-11d0-9dda-00c04fd7ba7c */
disk_io,
0x3d6fa8d4,
0xfe05,
0x11d0,
0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c
);
DEFINE_GUID ( /* 01853a65-418f-4f36-aefc-dc0f1d2fd235 */
event_trace_config,
0x01853a65,
0x418f,
0x4f36,
0xae, 0xfc, 0xdc, 0x0f, 0x1d, 0x2f, 0xd2, 0x35
);
DEFINE_GUID ( /* 90cbdc39-4a3e-11d1-84f4-0000f80464e3 */
file_io,
0x90cbdc39,
0x4a3e,
0x11d1,
0x84, 0xf4, 0x00, 0x00, 0xf8, 0x04, 0x64, 0xe3
);
DEFINE_GUID ( /* 2cb15d1d-5fc1-11d2-abe1-00a0c911f518 */
image_load,
0x2cb15d1d,
0x5fc1,
0x11d2,
0xab, 0xe1, 0x00, 0xa0, 0xc9, 0x11, 0xf5, 0x18
);
DEFINE_GUID ( /* 3d6fa8d3-fe05-11d0-9dda-00c04fd7ba7c */
page_fault,
0x3d6fa8d3,
0xfe05,
0x11d0,
0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c
);
DEFINE_GUID ( /* ce1dbfb4-137e-4da6-87b0-3f59aa102cbc */
perf_info,
0xce1dbfb4,
0x137e,
0x4da6,
0x87, 0xb0, 0x3f, 0x59, 0xaa, 0x10, 0x2c, 0xbc
);
DEFINE_GUID ( /* 3d6fa8d0-fe05-11d0-9dda-00c04fd7ba7c */
process,
0x3d6fa8d0,
0xfe05,
0x11d0,
0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c
);
DEFINE_GUID ( /* AE53722E-C863-11d2-8659-00C04FA321A1 */
registry,
0xae53722e,
0xc863,
0x11d2,
0x86, 0x59, 0x0, 0xc0, 0x4f, 0xa3, 0x21, 0xa1
);
DEFINE_GUID ( /* d837ca92-12b9-44a5-ad6a-3a65b3578aa8 */
split_io,
0xd837ca92,
0x12b9,
0x44a5,
0xad, 0x6a, 0x3a, 0x65, 0xb3, 0x57, 0x8a, 0xa8
);
DEFINE_GUID ( /* 9a280ac0-c8e0-11d1-84e2-00c04fb998a2 */
tcp_ip,
0x9a280ac0,
0xc8e0,
0x11d1,
0x84, 0xe2, 0x00, 0xc0, 0x4f, 0xb9, 0x98, 0xa2
);
DEFINE_GUID ( /* 3d6fa8d1-fe05-11d0-9dda-00c04fd7ba7c */
thread,
0x3d6fa8d1,
0xfe05,
0x11d0,
0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c
);
DEFINE_GUID ( /* bf3a50c5-a9c9-4988-a005-2df0b7c80f80 */
udp_ip,
0xbf3a50c5,
0xa9c9,
0x4988,
0xa0, 0x05, 0x2d, 0xf0, 0xb7, 0xc8, 0x0f, 0x80
);
DEFINE_GUID ( /* 9e814aad-3204-11d2-9a82-006008a86939 */
system_trace,
0x9e814aad,
0x3204,
0x11d2,
0x9a, 0x82, 0x00, 0x60, 0x08, 0xa8, 0x69, 0x39);
} /* namespace guids */ } /* namespace krabs */
| 1,829 |
481 | <reponame>datapane/datapane
# flake8: noqa isort:skip
import os
import sys
from pathlib import Path
from unittest import mock
import subprocess
import pytest
if not (sys.platform == "linux" and sys.version_info.minor >= 7):
pytest.skip("skipping linux-only 3.7+ tests", allow_module_level=True)
import datapane as dp
from datapane.client.api.runtime import _report
from datapane.client.scripts import build_bundle, DatapaneCfg
from datapane.common.config import RunnerConfig
from datapane.common import SDict, SSDict
from datapane.runner import __main__ as m
from datapane.runner.exec_script import exec_mod
from datapane.runner.typedefs import RunResult
# disabled for now - may re-enable when we support local
# running/rendering with our runner calling into user code
pytestmark = pytest.mark.skipif(
not (sys.platform == "linux" and sys.version_info.minor >= 7),
reason="Only supported on Linux/py3.7+",
)
def test_make_env():
res = m.make_env(os.environ)
assert "PATH" in res
assert "PWD" not in res
def test_exec(datadir: Path, monkeypatch, capsys):
"""Test running an isolated code snippet"""
monkeypatch.chdir(datadir)
res = exec_mod(Path("sample_module.py"), init_state={"x": 4})
# print(res)
assert "x" in res
assert res["x"] == 4
assert res["y"] == 4
assert res["foo"]() == "my_df"
# run_path makes res static due to sandboxing
# module is no longer "alive", it's a script that's finished executing
assert res["y"] != 5
assert res["__name__"] == "__datapane__"
(out, err) = capsys.readouterr()
assert out == "x is 4\nin foo\nmy_df\n5\n"
class MockScript(dp.Script):
"""Use custom mock class to disable constructor but keep other methods"""
script = ""
id = "a"
requirements = ["pytil"]
pre_commands = ["echo PRE1", "echo PRE2"]
post_commands = ["echo POST1", "echo POST2"]
api_version = dp.__version__
def __init__(self, *a, **kw):
pass
@classmethod
def get(cls, *a, **kw):
return cls()
@classmethod
def by_id(cls, id_or_url: str):
return cls()
def mock_report_upload(self, **kwargs):
"""Mock creating a report object"""
report = mock.Mock()
report.id = "ABC"
_report.append(report)
return mock.DEFAULT
@mock.patch("datapane.client.api.Script", new=MockScript)
def _runner(params: SDict, env: SSDict, script: Path, sdist: Path = Path(".")) -> RunResult:
with mock.patch.object(MockScript, "script", new_callable=mock.PropertyMock) as ep, mock.patch.object(
MockScript, "download_pkg"
) as dp:
# setup script object
ep.return_value = script
dp.return_value = sdist
# main fn
x = RunnerConfig(script_id="ZBAmDk1", config=params, env=env)
res = m.run_api(x)
return res
# TODO - fix exception handling stacktraces
@mock.patch("datapane.runner.exec_script.setup_script", autospec=True)
@mock.patch("datapane.client.api.Report.upload", autospec=True, side_effect=mock_report_upload)
def test_run_single_script(rc, isc, datadir: Path, monkeypatch, capfd):
"""Test running an isolated code snippet with params
NOTE - we can simplify by calling exec_script.run directly, doesn't test as much of API however
"""
monkeypatch.chdir(datadir)
# monkeypatch.setenv("DATAPANE_ON_DATAPANE", "true")
monkeypatch.setenv("DATAPANE_BY_DATAPANE", "true")
monkeypatch.setenv("ENV_VAR", "env value")
@mock.patch("datapane.runner.exec_script.script_env", autospec=True)
def f(val: str, script_env):
# test twice to ensure stateful params are handled correctly
res = _runner({"p1": val}, {"ENV_VAR": "env_value"}, Path("dp_script.py"))
# (out, err) = capsys.readouterr()
(out, err) = capfd.readouterr()
assert "on datapane" not in out
assert "by datapane" in out
# asserts
isc.assert_called()
(rc_args, rc_kwargs) = rc.call_args
assert rc_kwargs["description"] == "Description"
_r: dp.Report = rc_args[0]
_blocks = _r.pages[0].blocks[0].blocks
assert isinstance(_blocks, list)
assert len(_blocks) == 3
assert val in _blocks[0].content
assert res.report_id == "ABC"
# pre/post commands
assert "PRE2" in out
assert "POST2" in out
f("HELLO")
f("WORLD")
@mock.patch("datapane.client.api.Report.upload", autospec=True, side_effect=mock_report_upload)
def test_run_bundle(rc, datadir: Path, monkeypatch, capsys):
monkeypatch.chdir(datadir)
# monkeypatch.setenv("DATAPANE_ON_DATAPANE", "true")
monkeypatch.setenv("DATAPANE_BY_DATAPANE", "true")
# TODO - we should prob use a pre-built sdist here...
dp_config = DatapaneCfg.create_initial(config_file=Path("dp_test_mod.yaml"))
with build_bundle(dp_config) as sdist:
# whl_file = build_bundle(dp_config, sdist, shared_datadir, username="test", version=1)
try:
# NOTE - need to pass in all params as we're not setting defaults via dp-server
res = _runner(
{"p1": "VAL", "p2": "xyz", "p3": True}, {"ENV_VAR": "env_value"}, dp_config.script, sdist=sdist
)
finally:
subprocess.run([sys.executable, "-m", "pip", "uninstall", "--yes", "pytil"], check=True)
# asserts
(out, err) = capsys.readouterr()
assert "ran script" in out
assert "p2=xyz" in out
assert "WORLD" in out
assert dp.Result.get() == "hello , world!"
assert res.report_id is None
| 2,259 |
1,472 | import json
from os import stat
JSONDecodeError = json.decoder.JSONDecodeError if hasattr(
json.decoder, "JSONDecodeError") else ValueError
class MuxError(Exception):
""" Mutex error """
class MuxConnectError(MuxError, ConnectionError):
""" Error when MessageType: Connect """
class WDAError(Exception):
""" base wda error """
class WDABadGateway(WDAError):
""" bad gateway """
class WDAEmptyResponseError(WDAError):
""" response body is empty """
class WDAElementNotFoundError(WDAError):
""" element not found """
class WDAElementNotDisappearError(WDAError):
""" element not disappera """
class WDARequestError(WDAError):
def __init__(self, status, value):
self.status = status
self.value = value
def __str__(self):
return 'WDARequestError(status=%d, value=%s)' % (self.status,
self.value)
class WDAKeyboardNotPresentError(WDARequestError):
# {'error': 'invalid element state',
# 'message': 'Error Domain=com.facebook.WebDriverAgent Code=1
# "The on-screen keyboard must be present to send keys"
# UserInfo={NSLocalizedDescription=The on-screen keyboard must be present to send keys}',
# 'traceback': ''})
@staticmethod
def check(v: dict):
if v.get('error') == 'invalid element state' and \
'keyboard must be present to send keys' in v.get('message', ''):
return True
return False
class WDAInvalidSessionIdError(WDARequestError):
"""
"value" : {
"error" : "invalid session id",
"message" : "Session does not exist",
"""
@staticmethod
def check(v: dict):
if v.get('error') == 'invalid session id':
return True
return False
class WDAPossiblyCrashedError(WDARequestError):
@staticmethod
def check(v: dict):
if "possibly crashed" in v.get('message', ''):
return True
return False
class WDAUnknownError(WDARequestError):
""" error: unknown error, message: *** - """
@staticmethod
def check(v: dict):
return v.get("error") == "unknown error"
class WDAStaleElementReferenceError(WDARequestError):
""" error: 'stale element reference' """
@staticmethod
def check(v: dict):
return v.get("error") == 'stale element reference'
| 937 |
1,275 | <reponame>maiot-io/zenml
# Copyright (c) ZenML GmbH 2021. 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 inspect
from abc import abstractmethod
from typing import Dict
from zenml.core.repo import Repository
from zenml.exceptions import PipelineInterfaceError
from zenml.logger import get_logger
from zenml.stacks.base_stack import BaseStack
from zenml.utils.analytics_utils import RUN_PIPELINE, track
logger = get_logger(__name__)
PIPELINE_INNER_FUNC_NAME: str = "connect"
PARAM_ENABLE_CACHE: str = "enable_cache"
class BasePipelineMeta(type):
"""Pipeline Metaclass responsible for validating the pipeline definition."""
def __new__(mcs, name, bases, dct):
"""Ensures that all function arguments are either a `Step`
or an `Input`."""
cls = super().__new__(mcs, name, bases, dct)
cls.NAME = name
cls.STEP_SPEC = dict()
connect_spec = inspect.getfullargspec(
getattr(cls, PIPELINE_INNER_FUNC_NAME)
)
connect_args = connect_spec.args
if connect_args and connect_args[0] == "self":
connect_args.pop(0)
for arg in connect_args:
arg_type = connect_spec.annotations.get(arg, None)
cls.STEP_SPEC.update({arg: arg_type})
return cls
class BasePipeline(metaclass=BasePipelineMeta):
"""Base ZenML pipeline."""
def __init__(self, *args, **kwargs):
self.__stack = Repository().get_active_stack()
self.enable_cache = getattr(self, PARAM_ENABLE_CACHE)
self.pipeline_name = self.__class__.__name__
self.__steps = dict()
logger.info(f"Creating pipeline: {self.pipeline_name}")
logger.info(
f'Cache {"enabled" if self.enable_cache else "disabled"} for '
f"pipeline `{self.pipeline_name}`"
)
if args:
raise PipelineInterfaceError(
"You can only use keyword arguments while you are creating an "
"instance of a pipeline."
)
for k, v in kwargs.items():
if k in self.STEP_SPEC:
self.__steps.update({k: v})
else:
raise PipelineInterfaceError(
f"The argument {k} is an unknown argument. Needs to be "
f"one of {self.STEP_SPEC.keys()}"
)
@abstractmethod
def connect(self, *args, **kwargs):
"""Function that connects inputs and outputs of the pipeline steps."""
@property
def name(self) -> str:
"""Name of pipeline is always equal to self.NAME"""
return self.NAME
@property
def stack(self) -> BaseStack:
"""Returns the stack for this pipeline."""
return self.__stack
@stack.setter
def stack(self, stack: BaseStack):
"""Setting the stack property is not allowed. This method always
raises a PipelineInterfaceError.
"""
raise PipelineInterfaceError(
"The stack will be automatically inferred from your environment. "
"Please do no attempt to manually change it."
)
@property
def steps(self) -> Dict:
"""Returns a dictionary of pipeline steps."""
return self.__steps
@steps.setter
def steps(self, steps: Dict):
"""Setting the steps property is not allowed. This method always
raises a PipelineInterfaceError.
"""
raise PipelineInterfaceError("Cannot set steps manually!")
@track(event=RUN_PIPELINE)
def run(self):
"""Runs the pipeline using the orchestrator of the pipeline stack."""
logger.info(
f"Using orchestrator `{self.stack.orchestrator_name}` for "
f"pipeline `{self.pipeline_name}`. Running pipeline.."
)
return self.stack.orchestrator.run(self)
| 1,769 |
870 | <gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.core.clientImpl;
import java.util.List;
import java.util.Map;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.TimedOutException;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.dataImpl.KeyExtent;
import org.apache.hadoop.io.Text;
/**
* Throws a {@link TimedOutException} if the specified timeout duration elapses between two failed
* TabletLocator calls.
* <p>
* This class is safe to cache locally.
*/
public class TimeoutTabletLocator extends SyncingTabletLocator {
private long timeout;
private Long firstFailTime = null;
private void failed() {
if (firstFailTime == null) {
firstFailTime = System.currentTimeMillis();
} else if (System.currentTimeMillis() - firstFailTime > timeout) {
throw new TimedOutException("Failed to obtain metadata");
}
}
private void succeeded() {
firstFailTime = null;
}
public TimeoutTabletLocator(long timeout, final ClientContext context, final TableId table) {
super(context, table);
this.timeout = timeout;
}
@Override
public TabletLocation locateTablet(ClientContext context, Text row, boolean skipRow,
boolean retry) throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
try {
TabletLocation ret = super.locateTablet(context, row, skipRow, retry);
if (ret == null)
failed();
else
succeeded();
return ret;
} catch (AccumuloException ae) {
failed();
throw ae;
}
}
@Override
public <T extends Mutation> void binMutations(ClientContext context, List<T> mutations,
Map<String,TabletServerMutations<T>> binnedMutations, List<T> failures)
throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
try {
super.binMutations(context, mutations, binnedMutations, failures);
if (failures.size() == mutations.size())
failed();
else
succeeded();
} catch (AccumuloException ae) {
failed();
throw ae;
}
}
@Override
public List<Range> binRanges(ClientContext context, List<Range> ranges,
Map<String,Map<KeyExtent,List<Range>>> binnedRanges)
throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
try {
List<Range> ret = super.binRanges(context, ranges, binnedRanges);
if (ranges.size() == ret.size())
failed();
else
succeeded();
return ret;
} catch (AccumuloException ae) {
failed();
throw ae;
}
}
}
| 1,206 |
945 | /*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkQuadEdgeMesh.h"
int
itkQuadEdgeMeshDeleteEdgeTest(int, char *[])
{
using PixelType = double;
using MeshType = itk::QuadEdgeMesh<PixelType, 3>;
std::string indent = " ";
MeshType::Pointer mesh = MeshType::New();
// Points
MeshType::PointType p0, p1, p2, p3, p4, p5;
p0[0] = 0.00000000000000;
p0[1] = 0.00000000000000;
p0[2] = 5.0;
p1[0] = 0.00000000000000;
p1[1] = 10.00000000000000;
p1[2] = 0.0;
p2[0] = -9.51056516295153;
p2[1] = 3.09016994374947;
p2[2] = 0.0;
p3[0] = -5.87785252292473;
p3[1] = -8.09016994374947;
p3[2] = 0.0;
p4[0] = 5.87785252292473;
p4[1] = -8.09016994374948;
p4[2] = 0.0;
p5[0] = 9.51056516295154;
p5[1] = 3.09016994374947;
p5[2] = 0.0;
MeshType::PointIdentifier pid0 = mesh->AddPoint(p0);
MeshType::PointIdentifier pid1 = mesh->AddPoint(p1);
MeshType::PointIdentifier pid2 = mesh->AddPoint(p2);
MeshType::PointIdentifier pid3 = mesh->AddPoint(p3);
MeshType::PointIdentifier pid4 = mesh->AddPoint(p4);
MeshType::PointIdentifier pid5 = mesh->AddPoint(p5);
// Cells in a proper way
mesh->AddEdge(pid3, pid4);
mesh->AddEdge(pid4, pid0);
mesh->AddEdge(pid0, pid3);
mesh->AddFaceTriangle(pid3, pid4, pid0);
mesh->AddEdge(pid4, pid5);
mesh->AddEdge(pid5, pid0);
mesh->AddFaceTriangle(pid4, pid5, pid0);
mesh->AddEdge(pid5, pid1);
mesh->AddEdge(pid1, pid0);
mesh->AddFaceTriangle(pid5, pid1, pid0);
mesh->AddEdge(pid1, pid2);
mesh->AddEdge(pid2, pid0);
mesh->AddEdge(pid2, pid3);
int EdgesBefore = mesh->ComputeNumberOfEdges();
// Deleting two arbitrary edges:
mesh->DeleteEdge(pid3, pid4);
mesh->DeleteEdge(pid0, pid5);
std::cout << indent << "Trying to remove only two edges...";
if (EdgesBefore - mesh->ComputeNumberOfEdges() == 2)
{
std::cout << "OK." << std::endl;
return (EXIT_SUCCESS);
}
std::cout << "FAILED." << std::endl;
return (EXIT_FAILURE);
}
| 1,027 |
938 | <reponame>SusionSuc/DevTools
/*
* Tencent is pleased to support the open source community by making wechat-matrix available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.susion.rabbit.helper;
import java.util.regex.Pattern;
/**
* Created by jinqiuchen on 17/7/4.
*/
public final class Util {
private Util() {
}
public static boolean isNullOrNil(String str) {
return str == null || str.isEmpty();
}
public static String nullAsNil(String str) {
return str == null ? "" : str;
}
public static boolean isNumber(String str) {
Pattern pattern = Pattern.compile("\\d+");
return pattern.matcher(str).matches();
}
public static String byteArrayToHex(byte[] data) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
char[] str = new char[data.length * 2];
int k = 0;
for (int i = 0; i < data.length; i++) {
byte byte0 = data[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
public static String formatByteUnit(long bytes) {
if (bytes >= 1024 * 1024) {
return String.format("%.2fMB", bytes / (1.0 * 1024 * 1024));
} else if (bytes >= 1024) {
return String.format("%.2fKB", bytes / (1.0 * 1024));
} else {
return String.format("%dBytes", bytes);
}
}
/*
* Copyright (C) 2011 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.
*/
public static String globToRegexp(String glob) {
StringBuilder sb = new StringBuilder(glob.length() * 2);
int begin = 0;
sb.append('^');
for (int i = 0, n = glob.length(); i < n; i++) {
char c = glob.charAt(i);
if (c == '*') {
begin = appendQuoted(sb, glob, begin, i) + 1;
if (i < n - 1 && glob.charAt(i + 1) == '*') {
i++;
begin++;
}
sb.append(".*?");
} else if (c == '?') {
begin = appendQuoted(sb, glob, begin, i) + 1;
sb.append(".?");
}
}
appendQuoted(sb, glob, begin, glob.length());
sb.append('$');
return sb.toString();
}
private static int appendQuoted(StringBuilder sb, String s, int from, int to) {
if (to > from) {
boolean isSimple = true;
for (int i = from; i < to; i++) {
char c = s.charAt(i);
if (!Character.isLetterOrDigit(c) && c != '/' && c != ' ') {
isSimple = false;
break;
}
}
if (isSimple) {
for (int i = from; i < to; i++) {
sb.append(s.charAt(i));
}
return to;
}
sb.append(Pattern.quote(s.substring(from, to)));
}
return to;
}
}
| 1,841 |
1,511 | <filename>tests/cluecode/data/ics/iptables-extensions/libxt_connmark.c
/* Shared library add-on to iptables to add connmark matching support.
*
* (C) 2002,2004 MARA Systems AB <http://www.marasystems.com>
* by <NAME> <<EMAIL>>
* | 82 |
714 | <reponame>martbelko/OpenXLSX
#include <OpenXLSX.hpp>
#include <iostream>
using namespace std;
using namespace OpenXLSX;
int main()
{
cout << "********************************************************************************\n";
cout << "DEMO PROGRAM #02: Formulas\n";
cout << "********************************************************************************\n";
XLDocument doc;
doc.create("./Demo02.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
// Similar cell values, which are represented by XLCellValue objects, formulas are represented
// by XLFormula objects. They can be accessed through the XLCell interface using the .formula()
// member function. It should be noted, however, that the functionality of XLFormula is somewhat
// limited. Excel often uses 'shared' formulas, where the same formula is applied to several
// cells. XLFormula cannot handle shared formulas. Also, it cannot handle array formulas. This,
// in effect, means that XLFormula is not very useful for reading formulas from existing spread-
// sheets, but should rather be used to add or overwrite formulas to spreadsheets.
wks.cell("A1").value() = "Number:";
wks.cell("B1").value() = 1;
wks.cell("C1").value() = 2;
wks.cell("D1").value() = 3;
// Formulas can be added to a cell using the .formula() method on an XLCell object. The formula can
// be added by creating a separate XLFormula object, or (as shown below) by assigning a string
// holding the formula;
// Nota that OpenXLSX does not calculate the results of a formula. If you add a formula
// to a spreadsheet using OpenXLSX, you have to open the spreadsheet in the Excel application
// in order to see the results of the calculation.
wks.cell("A2").value() = "Calculation:";
wks.cell("B2").formula() = "SQRT(B1)";
wks.cell("C2").formula() = "EXP(C1)";
wks.cell("D2").formula() = "LN(D1)";
// The XLFormula object can be retrieved using the .formula() member function.
// The XLFormula .get() method can be used to get the formula string.
XLFormula B2 = wks.cell("B2").formula();
XLFormula C2 = wks.cell("C2").formula();
XLFormula D2 = wks.cell("D2").formula();
cout << "Formula in B2: " << B2.get() << endl;
cout << "Formula in C2: " << C2.get() << endl;
cout << "Formula in D2: " << D2.get() << endl << endl;
// Alternatively, the XLFormula object can be implicitly converted to a string object.
std::string B2string = wks.cell("B2").formula();
std::string C2string = wks.cell("C2").formula();
std::string D2string = wks.cell("D2").formula();
cout << "Formula in B2: " << B2string << endl;
cout << "Formula in C2: " << C2string << endl;
cout << "Formula in D2: " << D2string << endl << endl;
doc.save();
doc.close();
return 0;
} | 969 |
369 | /** @file
@brief Header
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
@author
<NAME>
*/
// Copyright 2015 Sensics, Inc.
// TypePack is part of OSVR-Core.
//
// Incorporates code from "meta":
// Copyright <NAME> 2014-2015
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/meta
//
#ifndef INCLUDED_T_h_GUID_7DC620D4_E3EA_4FB4_0C0E_9E9F512138EB
#define INCLUDED_T_h_GUID_7DC620D4_E3EA_4FB4_0C0E_9E9F512138EB
// Internal Includes
// - none
// Library/third-party includes
// - none
// Standard includes
// - none
namespace osvr {
namespace typepack {
/// @brief A convenience alias template to extract the nested `type` within
/// the supplied `T`.
///
/// The name was chosen to parallel how the traits in C++14 (like
/// `std::enable_if`) have been complemented by aliases ending in `_t` (like
/// `std::enable_if_t<COND>` being equivalent to `typename
/// std::enable_if<COND>::type`)
///
/// Note that the name is `t_`, unlike in `meta` where the semi-illegal name
/// `_t` is used. (Leading underscores are between risky and not permitted.)
template <typename T> using t_ = typename T::type;
} // namespace typepack
} // namespace osvr
#endif // INCLUDED_T_h_GUID_7DC620D4_E3EA_4FB4_0C0E_9E9F512138EB
| 568 |
1,444 | <reponame>GabrielSturtevant/mage<gh_stars>1000+
package mage.cards.f;
import java.util.UUID;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.DamageMultiEffect;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.effects.common.TapTargetEffect;
import mage.cards.CardSetInfo;
import mage.cards.SplitCard;
import mage.constants.CardType;
import mage.constants.SpellAbilityType;
import mage.target.TargetPermanent;
import mage.target.common.TargetAnyTargetAmount;
public final class FireIce extends SplitCard {
public FireIce(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{1}{R}", "{1}{U}", SpellAbilityType.SPLIT);
// Fire
// Fire deals 2 damage divided as you choose among one or two target creatures and/or players.
Effect effect = new DamageMultiEffect(2);
effect.setText("Fire deals 2 damage divided as you choose among one or two target creatures and/or players");
getLeftHalfCard().getSpellAbility().addEffect(effect);
getLeftHalfCard().getSpellAbility().addTarget(new TargetAnyTargetAmount(2));
// Ice
// Tap target permanent.
// Draw a card.
getRightHalfCard().getSpellAbility().addEffect(new TapTargetEffect());
getRightHalfCard().getSpellAbility().addTarget(new TargetPermanent());
getRightHalfCard().getSpellAbility().addEffect(new DrawCardSourceControllerEffect(1));
}
private FireIce(final FireIce card) {
super(card);
}
@Override
public FireIce copy() {
return new FireIce(this);
}
}
| 562 |
903 | /*
* 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.lucene.analysis.ko;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.util.Locale;
import java.util.Map;
import org.apache.lucene.analysis.TokenizerFactory;
import org.apache.lucene.analysis.ko.KoreanTokenizer.DecompoundMode;
import org.apache.lucene.analysis.ko.dict.UserDictionary;
import org.apache.lucene.util.AttributeFactory;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.ResourceLoader;
import org.apache.lucene.util.ResourceLoaderAware;
/**
* Factory for {@link KoreanTokenizer}.
*
* <pre class="prettyprint">
* <fieldType name="text_ko" class="solr.TextField">
* <analyzer>
* <tokenizer class="solr.KoreanTokenizerFactory"
* decompoundMode="discard"
* userDictionary="user.txt"
* userDictionaryEncoding="UTF-8"
* outputUnknownUnigrams="false"
* discardPunctuation="true"
* />
* </analyzer>
* </fieldType>
* </pre>
*
* <p>Supports the following attributes:
*
* <ul>
* <li>userDictionary: User dictionary path.
* <li>userDictionaryEncoding: User dictionary encoding.
* <li>decompoundMode: Decompound mode. Either 'none', 'discard', 'mixed'. Default is discard. See
* {@link DecompoundMode}
* <li>outputUnknownUnigrams: If true outputs unigrams for unknown words.
* <li>discardPunctuation: true if punctuation tokens should be dropped from the output.
* </ul>
*
* @lucene.experimental
* @since 7.4.0
* @lucene.spi {@value #NAME}
*/
public class KoreanTokenizerFactory extends TokenizerFactory implements ResourceLoaderAware {
/** SPI name */
public static final String NAME = "korean";
private static final String USER_DICT_PATH = "userDictionary";
private static final String USER_DICT_ENCODING = "userDictionaryEncoding";
private static final String DECOMPOUND_MODE = "decompoundMode";
private static final String OUTPUT_UNKNOWN_UNIGRAMS = "outputUnknownUnigrams";
private static final String DISCARD_PUNCTUATION = "discardPunctuation";
private final String userDictionaryPath;
private final String userDictionaryEncoding;
private UserDictionary userDictionary;
private final KoreanTokenizer.DecompoundMode mode;
private final boolean outputUnknownUnigrams;
private final boolean discardPunctuation;
/** Creates a new KoreanTokenizerFactory */
public KoreanTokenizerFactory(Map<String, String> args) {
super(args);
userDictionaryPath = args.remove(USER_DICT_PATH);
userDictionaryEncoding = args.remove(USER_DICT_ENCODING);
mode =
KoreanTokenizer.DecompoundMode.valueOf(
get(args, DECOMPOUND_MODE, KoreanTokenizer.DEFAULT_DECOMPOUND.toString())
.toUpperCase(Locale.ROOT));
outputUnknownUnigrams = getBoolean(args, OUTPUT_UNKNOWN_UNIGRAMS, false);
discardPunctuation = getBoolean(args, DISCARD_PUNCTUATION, true);
if (!args.isEmpty()) {
throw new IllegalArgumentException("Unknown parameters: " + args);
}
}
/** Default ctor for compatibility with SPI */
public KoreanTokenizerFactory() {
throw defaultCtorException();
}
@Override
public void inform(ResourceLoader loader) throws IOException {
if (userDictionaryPath != null) {
try (InputStream stream = loader.openResource(userDictionaryPath)) {
String encoding = userDictionaryEncoding;
if (encoding == null) {
encoding = IOUtils.UTF_8;
}
CharsetDecoder decoder =
Charset.forName(encoding)
.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
Reader reader = new InputStreamReader(stream, decoder);
userDictionary = UserDictionary.open(reader);
}
} else {
userDictionary = null;
}
}
@Override
public KoreanTokenizer create(AttributeFactory factory) {
return new KoreanTokenizer(
factory, userDictionary, mode, outputUnknownUnigrams, discardPunctuation);
}
}
| 1,753 |
325 | package com.box.l10n.mojito.service.tm;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.stereotype.Component;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class PluralNameParser {
LoadingCache<String, Pattern> patternCache;
public PluralNameParser() {
patternCache = CacheBuilder.newBuilder()
.maximumSize(10)
.build(CacheLoader.from(separtor -> getPattern(separtor)));
}
public String getPrefix(String name, String separator) {
Pattern pattern = patternCache.getUnchecked(separator);
return Optional.of(pattern.matcher(name))
.filter(Matcher::matches)
.map(m -> m.group(1))
.orElse(name);
}
Pattern getPattern(String separator) {
return Pattern.compile("(.*)" + separator + "(zero|one|two|few|many|other)");
}
public String toPluralName(String prefix, String name, String separator){
return String.format("%s%s%s", prefix, separator, name);
}
}
| 478 |
610 | <filename>tools/invert.cpp
#include <algorithm>
#include <thread>
#include <vector>
#include "CLI/CLI.hpp"
#include "gsl/span"
#include "pstl/algorithm"
#include "pstl/execution"
#include "spdlog/spdlog.h"
#include "tbb/global_control.h"
#include "tbb/task_group.h"
#include "app.hpp"
#include "binary_collection.hpp"
#include "invert.hpp"
#include "util/util.hpp"
int main(int argc, char** argv)
{
CLI::App app{"Constructs an inverted index from a forward index."};
pisa::InvertArgs args(&app);
CLI11_PARSE(app, argc, argv);
tbb::global_control control(tbb::global_control::max_allowed_parallelism, args.threads() + 1);
spdlog::info("Number of worker threads: {}", args.threads());
try {
pisa::invert::invert_forward_index(
args.input_basename(),
args.output_basename(),
args.batch_size(),
args.threads(),
args.term_count());
return 0;
} catch (pisa::io::NoSuchFile err) {
spdlog::error("{}", err.what());
return 1;
}
}
| 467 |
482 | <gh_stars>100-1000
package io.cattle.platform.util.resource;
import java.io.IOException;
import java.net.URL;
import java.util.List;
public interface ResourceLoader {
List<URL> getResources(String path) throws IOException;
}
| 76 |
777 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_WEBSHARE_SHARE_SERVICE_IMPL_H_
#define CHROME_BROWSER_WEBSHARE_SHARE_SERVICE_IMPL_H_
#include <string>
#include "base/gtest_prod_util.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "third_party/WebKit/public/platform/modules/webshare/webshare.mojom.h"
class GURL;
// Desktop implementation of the ShareService Mojo service.
class ShareServiceImpl : public blink::mojom::ShareService {
public:
ShareServiceImpl() = default;
~ShareServiceImpl() override = default;
static void Create(mojo::InterfaceRequest<ShareService> request);
// blink::mojom::ShareService overrides:
void Share(const std::string& title,
const std::string& text,
const GURL& share_url,
const ShareCallback& callback) override;
private:
FRIEND_TEST_ALL_PREFIXES(ShareServiceImplUnittest, ReplacePlaceholders);
// Opens a new tab and navigates to |target_url|.
// Virtual for testing purposes.
virtual void OpenTargetURL(const GURL& target_url);
// Writes to |url_template_filled|, a copy of |url_template| with all
// instances of "{title}", "{text}", and "{url}" replaced with
// |title|, |text|, and |url| respectively.
// Replaces instances of "{X}" where "X" is any string besides "title",
// "text", and "url", with an empty string, for forwards compatibility.
// Returns false, if there are badly nested placeholders.
// This includes any case in which two "{" occur before a "}", or a "}"
// occurs with no preceding "{".
static bool ReplacePlaceholders(base::StringPiece url_template,
base::StringPiece title,
base::StringPiece text,
const GURL& share_url,
std::string* url_template_filled);
DISALLOW_COPY_AND_ASSIGN(ShareServiceImpl);
};
#endif // CHROME_BROWSER_WEBSHARE_SHARE_SERVICE_IMPL_H_
| 782 |
1,664 | /*
* 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.ambari.server.controller.ivory;
import java.util.List;
/**
* Ivory service.
*/
public interface IvoryService {
// ----- Feed operations ---------------------------------------------------
/**
* Submit a feed.
*
* @param feed the feed
*/
void submitFeed(Feed feed);
/**
* Get a feed for the given name.
*
* @param feedName the feed name
*
* @return a feed that matches the given name; null if none is found
*/
Feed getFeed(String feedName);
/**
* Get all the known feed names.
*
* @return a list of feed names; may not be null
*/
List<String> getFeedNames();
/**
* Update a feed based on the given {@link Feed} object.
*
* @param feed the feed object
*/
void updateFeed(Feed feed);
/**
* Suspend the feed with the given feed name.
*
* @param feedName the feed name
*/
void suspendFeed(String feedName);
/**
* Resume the feed with the given feed name.
*
* @param feedName the feed name
*/
void resumeFeed(String feedName);
/**
* Schedule the feed with the given feed name.
*
* @param feedName the feed name
*/
void scheduleFeed(String feedName);
/**
* Delete the feed with the given feed name.
*
* @param feedName the feed name
*/
void deleteFeed(String feedName);
// ----- Cluster operations ------------------------------------------------
/**
* Submit a cluster.
*
* @param cluster the cluster
*/
void submitCluster(Cluster cluster);
/**
* Get a cluster for the given name.
*
* @param clusterName the cluster name
*
* @return a cluster that matches the given name; null if none is found
*/
Cluster getCluster(String clusterName);
/**
* Get all the known cluster names.
*
* @return a list of cluster names; may not be null
*/
List<String> getClusterNames();
/**
* Update a cluster based on the given {@link Cluster} object.
*
* @param cluster the cluster
*/
void updateCluster(Cluster cluster);
/**
* Delete the cluster with the given name.
*
* @param clusterName the cluster name
*/
void deleteCluster(String clusterName);
// ----- Instance operations -----------------------------------------------
/**
* Get all the instances for a given feed.
*
* @param feedName the feed name
*
* @return the list of instances for the given feed
*/
List<Instance> getInstances(String feedName); //read
/**
* Suspend the instance for the given feed name and id.
*
* @param feedName the feed name
* @param instanceId the id
*/
void suspendInstance(String feedName, String instanceId);
/**
* Resume the instance for the given feed name and id.
*
* @param feedName the feed name
* @param instanceId the id
*/
void resumeInstance(String feedName, String instanceId);
/**
* Kill the instance for the given feed name and id.
*
* @param feedName the feed name
* @param instanceId the id
*/
void killInstance(String feedName, String instanceId);
}
| 1,174 |
3,084 | <gh_stars>1000+
// Copyright (C) Microsoft Corporation, All Rights Reserved.
//
// Abstract:
// This module contains the implementation of entry and exit point of activity sample driver.
//
// Environment:
// Windows User-Mode Driver Framework (UMDF)
#pragma once
WDF_EXTERN_C_START
DRIVER_INITIALIZE DriverEntry;
EVT_WDF_DRIVER_UNLOAD OnDriverUnload;
WDF_EXTERN_C_END | 151 |
809 | <gh_stars>100-1000
/**
* @file
*
* @date Oct 15, 2013
* @author: <NAME>
*/
#ifndef THREAD_CANCEL_ENABLE_H_
#define THREAD_CANCEL_ENABLE_H_
#define CLEANUPS_QUANTITY \
OPTION_MODULE_GET(embox__kernel__thread__thread_cancel_enable, \
NUMBER, cleanups_quantity)
struct thread_cleanup {
void (*routine)(void *);
void *arg;
};
struct thread_cancel {
unsigned int type;
unsigned int state;
unsigned int counter;
struct thread_cleanup cleanups[CLEANUPS_QUANTITY];
};
typedef struct thread_cancel thread_cancel_t;
#endif /* THREAD_CANCEL_ENABLE_H_ */
| 226 |
890 | /*
*
* Copyright 2019 Asylo 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.
*
*/
#include "asylo/util/binary_search.h"
#include <limits>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace asylo {
namespace {
TEST(BinarySearchTest, ConstantsSearchTest) {
auto less_than_seventeen = [](size_t x) { return x < 17; };
EXPECT_EQ(BinarySearch(less_than_seventeen), 16);
auto always_false = [](size_t x) { return false; };
EXPECT_EQ(BinarySearch(always_false), 0);
auto less_than_one = [](size_t x) { return x < 1; };
EXPECT_EQ(BinarySearch(less_than_one), 0);
auto less_than_sixty_four = [](size_t x) { return x < 64; };
EXPECT_EQ(BinarySearch(less_than_sixty_four), 63);
auto less_than_a_lot = [](size_t x) { return x < 99999; };
EXPECT_EQ(BinarySearch(less_than_a_lot), 99998);
auto always_true = [](size_t x) { return true; };
EXPECT_EQ(BinarySearch(always_true),
std::numeric_limits<std::ptrdiff_t>::max());
}
} // namespace
} // namespace asylo
| 540 |
739 | <gh_stars>100-1000
{
"id": "575756b5-b3e7-4333-9667-61f540e5dd5e",
"name": "<NAME>",
"img": "https://res.cloudinary.com/jthouk/image/upload/w_200,c_fill,ar_1:1,g_auto,r_max/v1582802281/Profiles/IMG_0600_swphdi.png",
"email":"",
"links": {
"website": "https://jt.houk.space",
"linkedin": "https://www.linkedin.com/in/jt-houk",
"github": "https://github.com/HoukasaurusRex"
},
"jobTitle": "Senior Full Stack Developer",
"location": {
"city": "Beijing",
"state": "Beijing",
"country": "China"
}
}
| 253 |
1,273 | <filename>src/main/java/org/broadinstitute/hellbender/tools/spark/PileupSpark.java
package org.broadinstitute.hellbender.tools.spark;
import htsjdk.tribble.Feature;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.BetaFeature;
import org.broadinstitute.barclay.argparser.Hidden;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.barclay.help.DocumentedFeature;
import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions;
import org.broadinstitute.hellbender.cmdline.programgroups.CoverageAnalysisProgramGroup;
import org.broadinstitute.hellbender.engine.AlignmentContext;
import org.broadinstitute.hellbender.engine.FeatureContext;
import org.broadinstitute.hellbender.engine.FeatureInput;
import org.broadinstitute.hellbender.engine.ReferenceContext;
import org.broadinstitute.hellbender.engine.filters.ReadFilter;
import org.broadinstitute.hellbender.engine.filters.ReadFilterLibrary;
import org.broadinstitute.hellbender.engine.filters.WellformedReadFilter;
import org.broadinstitute.hellbender.engine.spark.LocusWalkerContext;
import org.broadinstitute.hellbender.utils.pileup.PileupElement;
import org.broadinstitute.hellbender.utils.pileup.ReadPileup;
import org.broadinstitute.hellbender.engine.spark.LocusWalkerSpark;
import scala.Tuple3;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Prints read alignments in {@code samtools} pileup format. The tool leverages the Spark framework
* for faster operation.
*
* <p>This tool emulates the functionality of {@code samtools pileup}. It prints the alignments in a format that is very similar
* to the {@code samtools} pileup format; see the <a href="http://samtools.sourceforge.net/pileup.shtml">Samtools Pileup format
* documentation</a> for more details about the original format. The output comprises one line per genomic position, listing the
* chromosome name, coordinate, reference base, bases from reads, and corresponding base qualities from reads.
* In addition to these default fields,
* additional information can be added to the output as extra columns.</p>
*
* <h3>Usage example</h3>
* <pre>
* gatk PileupSpark \
* -R reference.fasta \
* -I input.bam \
* -O output.txt
* </pre>
*
* <h4>Emulated command:</h4>
* <pre>
* samtools pileup -f reference.fasta input.bam
* </pre>
*
* <h4>Typical output format</h4>
* <pre>
* chr1 257 A CAA '&=
* chr1 258 C TCC A:=
* chr1 259 C CCC )A=
* chr1 260 C ACC (=<
* chr1 261 T TCT '44
* chr1 262 A AAA '?:
* chr1 263 A AGA 1'6
* chr1 264 C TCC 987
* chr1 265 C CCC (@(
* chr1 266 C GCC ''=
* chr1 267 T AAT 7%>
* </pre>
* <p>
* This tool can be run without explicitly specifying Spark options.
* That is to say, the given example command without Spark options will run locally.
* See <a href ="https://software.broadinstitute.org/gatk/documentation/article?id=10060">Tutorial#10060</a>
* for an example of how to set up and run a Spark tool on a cloud Spark cluster.
* </p>
*
* @author <NAME> (<EMAIL>DGS)
*/
@CommandLineProgramProperties(
summary = "Prints read alignments in samtools pileup format. The tool leverages the Spark framework for " +
"faster operationThe output comprises one line per genomic position, listing the chromosome name, " +
"coordinate, reference base, read bases, and read qualities. In addition to these default fields, " +
"additional information can be added to the output as extra columns.",
oneLineSummary = "Prints read alignments in samtools pileup format",
programGroup = CoverageAnalysisProgramGroup.class)
@DocumentedFeature
@BetaFeature
public final class PileupSpark extends LocusWalkerSpark {
private static final long serialVersionUID = 1L;
private static final String VERBOSE_DELIMITER = "@"; // it's ugly to use "@" but it's literally the only usable character not allowed in read names
@Override
public boolean requiresReads() { return true; }
@Argument(
shortName = StandardArgumentDefinitions.OUTPUT_SHORT_NAME,
fullName = StandardArgumentDefinitions.OUTPUT_LONG_NAME,
doc="The output directory to which the scattered output will be written."
)
protected String outputFile;
/**
* In addition to the standard pileup output, adds 'verbose' output too. The verbose output contains the number of
* spanning deletions, and for each read in the pileup it has the read name, offset in the base string, read length,
* and read mapping quality. These per read items are delimited with an '@' character.
*/
@Argument(
fullName = "show-verbose",
shortName = "verbose",
doc = "Add extra informative columns to the pileup output. The verbose output contains the number of " +
"spanning deletions, and for each read in the pileup it has the read name, offset in the base " +
"string, read length, and read mapping quality. These per read items are delimited with an '@' " +
"character.",
optional = true
)
public boolean showVerbose = false;
/**
* This enables annotating the pileup to show overlaps with metadata from a Feature file(s). For example, if the
* user provide a VCF and there is a SNP at a given location covered by the pileup, the pileup output at that
* position will be annotated with the corresponding source Feature identifier.
*/
@Argument(
fullName = "metadata",
shortName = "metadata",
doc = "Features file(s) containing metadata. The overlapping sites will be annotated with the corresponding" +
" source Feature identifier.",
optional = true
)
public List<FeatureInput<Feature>> metadata = new ArrayList<>();
/**
* Adds the length of the insert each base comes from to the output pileup. Here, "insert" refers to the DNA insert
* produced during library generation before sequencing.
*/
@Argument(
fullName = "output-insert-length",
shortName = "output-insert-length",
doc = "If enabled, inserts lengths will be added to the output pileup.",
optional = true
)
public boolean outputInsertLength = false;
@Override
public List<ReadFilter> getDefaultReadFilters() {
List<ReadFilter> filterList = new ArrayList<>(5);
filterList.add(ReadFilterLibrary.MAPPED);
filterList.add(ReadFilterLibrary.NOT_DUPLICATE);
filterList.add(ReadFilterLibrary.PASSES_VENDOR_QUALITY_CHECK);
filterList.add(ReadFilterLibrary.NOT_SECONDARY_ALIGNMENT);
filterList.add(new WellformedReadFilter());
return filterList;
}
@Override
protected void processAlignments(JavaRDD<LocusWalkerContext> rdd, JavaSparkContext ctx) {
JavaRDD<String> lines = rdd.map(pileupFunction(metadata, outputInsertLength, showVerbose));
if (numReducers != 0) {
lines = lines.coalesce(numReducers);
}
lines.saveAsTextFile(outputFile);
}
private static Function<LocusWalkerContext, String> pileupFunction(List<FeatureInput<Feature>> metadata,
boolean outputInsertLength, boolean showVerbose) {
return (Function<LocusWalkerContext, String>) context -> {
AlignmentContext alignmentContext = context.getAlignmentContext();
ReferenceContext referenceContext = context.getReferenceContext();
FeatureContext featureContext = context.getFeatureContext();
final String features = getFeaturesString(featureContext, metadata);
final ReadPileup basePileup = alignmentContext.getBasePileup();
final StringBuilder s = new StringBuilder();
s.append(String.format("%s %s",
basePileup.getPileupString((referenceContext.hasBackingDataSource()) ? (char) referenceContext.getBase() : 'N'),
features));
if (outputInsertLength) {
s.append(" ").append(insertLengthOutput(basePileup));
}
if (showVerbose) {
s.append(" ").append(createVerboseOutput(basePileup));
}
s.append("\n");
return s.toString();
};
}
private static String getFeaturesString(final FeatureContext featureContext, List<FeatureInput<Feature>> metadata) {
String featuresString = featureContext.getValues(metadata).stream()
.map(Feature::toString).collect(Collectors.joining(", "));
if (!featuresString.isEmpty()) {
featuresString = "[Feature(s): " + featuresString + "]";
}
return featuresString;
}
private static String insertLengthOutput(final ReadPileup pileup) {
return pileup.getReads().stream()
.map(r -> String.valueOf(r.getFragmentLength()))
.collect(Collectors.joining(","));
}
private static String createVerboseOutput(final ReadPileup pileup) {
final StringBuilder sb = new StringBuilder();
boolean isFirst = true;
sb.append(pileup.getNumberOfElements(PileupElement::isDeletion));
sb.append(" ");
for (final PileupElement p : pileup) {
if (isFirst) {
isFirst = false;
} else {
sb.append(",");
}
sb.append(p.getRead().getName());
sb.append(VERBOSE_DELIMITER);
sb.append(p.getOffset());
sb.append(VERBOSE_DELIMITER);
sb.append(p.getRead().getLength());
sb.append(VERBOSE_DELIMITER);
sb.append(p.getRead().getMappingQuality());
}
return sb.toString();
}
}
| 3,817 |
689 | /*
* Copyright (C) Advanced Micro Devices, Inc. 2019. ALL RIGHTS RESERVED.
* See file LICENSE for terms.
*/
#ifndef UCT_ROCM_COPY_IFACE_H
#define UCT_ROCM_COPY_IFACE_H
#include <uct/base/uct_iface.h>
#include <hsa.h>
#define UCT_ROCM_COPY_TL_NAME "rocm_cpy"
typedef uint64_t uct_rocm_copy_iface_addr_t;
typedef struct uct_rocm_copy_iface {
uct_base_iface_t super;
uct_rocm_copy_iface_addr_t id;
hsa_signal_t hsa_signal;
struct {
size_t d2h_thresh;
size_t h2d_thresh;
} config;
} uct_rocm_copy_iface_t;
typedef struct uct_rocm_copy_iface_config {
uct_iface_config_t super;
size_t d2h_thresh;
size_t h2d_thresh;
} uct_rocm_copy_iface_config_t;
#endif
| 456 |
3,215 | <filename>tests/fixtures/ubuntu-18.04/blkid-ip-udev-multi.json
[{"id_fs_uuid": "011527a0-c72a-4c00-a50e-ee90da26b6e2", "id_fs_uuid_enc": "011527a0-c72a-4c00-a50e-ee90da26b6e2", "id_fs_version": "1.0", "id_fs_type": "ext4", "id_fs_usage": "filesystem", "id_iolimit_minimum_io_size": 512, "id_iolimit_physical_sector_size": 512, "id_iolimit_logical_sector_size": 512, "id_part_entry_scheme": "gpt", "id_part_entry_uuid": "744589e8-5711-4750-9984-c34d66f93879", "id_part_entry_type": "0fc63daf-8483-4772-8e79-3d69d8477de4", "id_part_entry_number": 2, "id_part_entry_offset": 4096, "id_part_entry_size": 41936896, "id_part_entry_disk": "8:0"}, {"id_iolimit_minimum_io_size": 512, "id_iolimit_physical_sector_size": 512, "id_iolimit_logical_sector_size": 512, "id_part_entry_scheme": "gpt", "id_part_entry_uuid": "e0614271-c211-4324-a5bc-8e6bcb66da43", "id_part_entry_type": "21686148-6449-6e6f-744e-656564454649", "id_part_entry_number": 1, "id_part_entry_offset": 2048, "id_part_entry_size": 2048, "id_part_entry_disk": "8:0"}]
| 490 |
777 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PRINTING_BACKEND_CUPS_IPP_UTIL_H_
#define PRINTING_BACKEND_CUPS_IPP_UTIL_H_
#include <vector>
#include "base/strings/string_piece.h"
#include "printing/backend/cups_printer.h"
#include "printing/backend/print_backend.h"
namespace printing {
extern const char kIppCollate[];
extern const char kIppCopies[];
extern const char kIppColor[];
extern const char kIppMedia[];
extern const char kIppDuplex[];
extern const char kCollated[];
extern const char kUncollated[];
// Returns the default ColorModel for |printer|.
ColorModel DefaultColorModel(const CupsOptionProvider& printer);
// Returns the set of supported ColorModels for |printer|.
std::vector<ColorModel> SupportedColorModels(const CupsOptionProvider& printer);
// Returns the default paper setting for |printer|.
PrinterSemanticCapsAndDefaults::Paper DefaultPaper(
const CupsOptionProvider& printer);
// Returns the list of papers supported by the |printer|.
std::vector<PrinterSemanticCapsAndDefaults::Paper> SupportedPapers(
const CupsOptionProvider& printer);
// Retrieves the supported number of copies from |printer| and writes the
// extremities of the range into |lower_bound| and |upper_bound|. Values are
// set to -1 if there is an error.
void CopiesRange(const CupsOptionProvider& printer,
int* lower_bound,
int* upper_bound);
// Returns true if |printer| can do collation.
bool CollateCapable(const CupsOptionProvider& printer);
// Returns true if |printer| has collation enabled by default.
bool CollateDefault(const CupsOptionProvider& printer);
// Populates the |printer_info| object with attributes retrived using IPP from
// |printer|.
void CapsAndDefaultsFromPrinter(const CupsOptionProvider& printer,
PrinterSemanticCapsAndDefaults* printer_info);
} // namespace printing
#endif // PRINTING_BACKEND_CUPS_IPP_UTIL_H_
| 675 |
696 | <reponame>hwang-pku/Strata
/*
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.product.swap;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static com.opengamma.strata.collect.TestHelper.date;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.product.PortfolioItemSummary;
import com.opengamma.strata.product.PortfolioItemType;
import com.opengamma.strata.product.ProductType;
import com.opengamma.strata.product.TradeInfo;
/**
* Test.
*/
public class SwapTradeTest {
private static final ReferenceData REF_DATA = ReferenceData.standard();
private static final TradeInfo TRADE_INFO = TradeInfo.of(date(2014, 6, 30));
private static final Swap SWAP1 = Swap.of(MockSwapLeg.MOCK_GBP1, MockSwapLeg.MOCK_USD1);
private static final Swap SWAP2 = Swap.of(MockSwapLeg.MOCK_GBP1);
//-------------------------------------------------------------------------
@Test
public void test_of() {
SwapTrade test = SwapTrade.of(TRADE_INFO, SWAP1);
assertThat(test.getInfo()).isEqualTo(TRADE_INFO);
assertThat(test.getProduct()).isEqualTo(SWAP1);
assertThat(test.withInfo(TRADE_INFO).getInfo()).isEqualTo(TRADE_INFO);
}
@Test
public void test_builder() {
SwapTrade test = SwapTrade.builder()
.product(SWAP1)
.build();
assertThat(test.getInfo()).isEqualTo(TradeInfo.empty());
assertThat(test.getProduct()).isEqualTo(SWAP1);
}
//-------------------------------------------------------------------------
@Test
public void test_summarize() {
SwapTrade trade = SwapTrade.of(TRADE_INFO, SWAP1);
PortfolioItemSummary expected = PortfolioItemSummary.builder()
.id(TRADE_INFO.getId().orElse(null))
.portfolioItemType(PortfolioItemType.TRADE)
.productType(ProductType.SWAP)
.currencies(Currency.GBP, Currency.EUR, Currency.USD)
.description(
"7M Pay [GBP-LIBOR-3M, EUR/GBP-ECB, EUR-EONIA] / Rec [GBP-LIBOR-3M, EUR/GBP-ECB, EUR-EONIA] : 15Jan12-15Aug12")
.build();
assertThat(trade.summarize()).isEqualTo(expected);
}
//-------------------------------------------------------------------------
@Test
public void test_resolve() {
SwapTrade test = SwapTrade.of(TRADE_INFO, SWAP1);
assertThat(test.resolve(REF_DATA).getInfo()).isEqualTo(TRADE_INFO);
assertThat(test.resolve(REF_DATA).getProduct()).isEqualTo(SWAP1.resolve(REF_DATA));
}
//-------------------------------------------------------------------------
@Test
public void coverage() {
SwapTrade test = SwapTrade.builder()
.info(TRADE_INFO)
.product(SWAP1)
.build();
coverImmutableBean(test);
SwapTrade test2 = SwapTrade.builder()
.product(SWAP2)
.build();
coverBeanEquals(test, test2);
}
@Test
public void test_serialization() {
SwapTrade test = SwapTrade.builder()
.info(TRADE_INFO)
.product(SWAP1)
.build();
assertSerialization(test);
}
}
| 1,253 |
923 | <filename>Yet-Another-EfficientDet-Pytorch/efficientdet/utils.py
import itertools
import torch
import torch.nn as nn
import numpy as np
class BBoxTransform(nn.Module):
def forward(self, anchors, regression):
"""
decode_box_outputs adapted from https://github.com/google/automl/blob/master/efficientdet/anchors.py
Args:
anchors: [batchsize, boxes, (y1, x1, y2, x2)]
regression: [batchsize, boxes, (dy, dx, dh, dw)]
Returns:
"""
y_centers_a = (anchors[..., 0] + anchors[..., 2]) / 2
x_centers_a = (anchors[..., 1] + anchors[..., 3]) / 2
ha = anchors[..., 2] - anchors[..., 0]
wa = anchors[..., 3] - anchors[..., 1]
w = regression[..., 3].exp() * wa
h = regression[..., 2].exp() * ha
y_centers = regression[..., 0] * ha + y_centers_a
x_centers = regression[..., 1] * wa + x_centers_a
ymin = y_centers - h / 2.
xmin = x_centers - w / 2.
ymax = y_centers + h / 2.
xmax = x_centers + w / 2.
return torch.stack([xmin, ymin, xmax, ymax], dim=2)
class ClipBoxes(nn.Module):
def __init__(self):
super(ClipBoxes, self).__init__()
def forward(self, boxes, img):
batch_size, num_channels, height, width = img.shape
boxes[:, :, 0] = torch.clamp(boxes[:, :, 0], min=0)
boxes[:, :, 1] = torch.clamp(boxes[:, :, 1], min=0)
boxes[:, :, 2] = torch.clamp(boxes[:, :, 2], max=width - 1)
boxes[:, :, 3] = torch.clamp(boxes[:, :, 3], max=height - 1)
return boxes
class Anchors(nn.Module):
"""
adapted and modified from https://github.com/google/automl/blob/master/efficientdet/anchors.py by Zylo117
"""
def __init__(self, anchor_scale=4., pyramid_levels=None, **kwargs):
super().__init__()
self.anchor_scale = anchor_scale
if pyramid_levels is None:
self.pyramid_levels = [3, 4, 5, 6, 7]
self.strides = kwargs.get('strides', [2 ** x for x in self.pyramid_levels])
self.scales = np.array(kwargs.get('scales', [2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)]))
self.ratios = kwargs.get('ratios', [(1.0, 1.0), (1.4, 0.7), (0.7, 1.4)])
self.last_anchors = {}
self.last_shape = None
def forward(self, image, dtype=torch.float32):
"""Generates multiscale anchor boxes.
Args:
image_size: integer number of input image size. The input image has the
same dimension for width and height. The image_size should be divided by
the largest feature stride 2^max_level.
anchor_scale: float number representing the scale of size of the base
anchor to the feature stride 2^level.
anchor_configs: a dictionary with keys as the levels of anchors and
values as a list of anchor configuration.
Returns:
anchor_boxes: a numpy array with shape [N, 4], which stacks anchors on all
feature levels.
Raises:
ValueError: input size must be the multiple of largest feature stride.
"""
image_shape = image.shape[2:]
if image_shape == self.last_shape and image.device in self.last_anchors:
return self.last_anchors[image.device]
if self.last_shape is None or self.last_shape != image_shape:
self.last_shape = image_shape
if dtype == torch.float16:
dtype = np.float16
else:
dtype = np.float32
boxes_all = []
for stride in self.strides:
boxes_level = []
for scale, ratio in itertools.product(self.scales, self.ratios):
if image_shape[1] % stride != 0:
raise ValueError('input size must be divided by the stride.')
base_anchor_size = self.anchor_scale * stride * scale
anchor_size_x_2 = base_anchor_size * ratio[0] / 2.0
anchor_size_y_2 = base_anchor_size * ratio[1] / 2.0
x = np.arange(stride / 2, image_shape[1], stride)
y = np.arange(stride / 2, image_shape[0], stride)
xv, yv = np.meshgrid(x, y)
xv = xv.reshape(-1)
yv = yv.reshape(-1)
# y1,x1,y2,x2
boxes = np.vstack((yv - anchor_size_y_2, xv - anchor_size_x_2,
yv + anchor_size_y_2, xv + anchor_size_x_2))
boxes = np.swapaxes(boxes, 0, 1)
boxes_level.append(np.expand_dims(boxes, axis=1))
# concat anchors on the same level to the reshape NxAx4
boxes_level = np.concatenate(boxes_level, axis=1)
boxes_all.append(boxes_level.reshape([-1, 4]))
anchor_boxes = np.vstack(boxes_all)
anchor_boxes = torch.from_numpy(anchor_boxes.astype(dtype)).to(image.device)
anchor_boxes = anchor_boxes.unsqueeze(0)
# save it for later use to reduce overhead
self.last_anchors[image.device] = anchor_boxes
return anchor_boxes
| 2,403 |
692 | void
test_estimator ()
{
gsl_vector_view c;
gsl_matrix_view cov;
gsl_vector_view x;
double y, y_err;
double cov_ij[25] = {
4.271520, -0.526675, 0.957930, 0.267750, -0.103610,
-0.526675, 5.701680, -0.098080, 0.641845, 0.429780,
0.957930, -0.098080, 4.584790, 0.375865, 1.510810,
0.267750, 0.641845, 0.375865, 4.422720, 0.392210,
-0.103610, 0.429780, 1.510810, 0.392210, 5.782750
};
double c_i[5] = {
-0.627020, 0.848674, 0.216877, -0.057883, 0.596668
};
double x_i[5] = {
0.99932, 0.23858, 0.19797, 1.44008, -0.15335
};
double y_expected = -5.56037032230000e-01;
double yerr_expected = 3.91891123349318e+00;
cov = gsl_matrix_view_array(cov_ij, 5, 5);
c = gsl_vector_view_array(c_i, 5);
x = gsl_vector_view_array(x_i, 5);
gsl_multifit_linear_est(&x.vector , &c.vector, &cov.matrix, &y, &y_err);
gsl_test_rel (y, y_expected, 256*GSL_DBL_EPSILON, "gsl_multifit_linear_est y");
gsl_test_rel (y_err, yerr_expected, 256*GSL_DBL_EPSILON, "gsl_multifit_linear_est yerr");
}
| 595 |
56,632 | <gh_stars>1000+
from __future__ import print_function
import sys
import cv2 as cv
## [global_variables]
use_mask = False
img = None
templ = None
mask = None
image_window = "Source Image"
result_window = "Result window"
match_method = 0
max_Trackbar = 5
## [global_variables]
def main(argv):
if (len(sys.argv) < 3):
print('Not enough parameters')
print('Usage:\nmatch_template_demo.py <image_name> <template_name> [<mask_name>]')
return -1
## [load_image]
global img
global templ
img = cv.imread(sys.argv[1], cv.IMREAD_COLOR)
templ = cv.imread(sys.argv[2], cv.IMREAD_COLOR)
if (len(sys.argv) > 3):
global use_mask
use_mask = True
global mask
mask = cv.imread( sys.argv[3], cv.IMREAD_COLOR )
if ((img is None) or (templ is None) or (use_mask and (mask is None))):
print('Can\'t read one of the images')
return -1
## [load_image]
## [create_windows]
cv.namedWindow( image_window, cv.WINDOW_AUTOSIZE )
cv.namedWindow( result_window, cv.WINDOW_AUTOSIZE )
## [create_windows]
## [create_trackbar]
trackbar_label = 'Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED'
cv.createTrackbar( trackbar_label, image_window, match_method, max_Trackbar, MatchingMethod )
## [create_trackbar]
MatchingMethod(match_method)
## [wait_key]
cv.waitKey(0)
return 0
## [wait_key]
def MatchingMethod(param):
global match_method
match_method = param
## [copy_source]
img_display = img.copy()
## [copy_source]
## [match_template]
method_accepts_mask = (cv.TM_SQDIFF == match_method or match_method == cv.TM_CCORR_NORMED)
if (use_mask and method_accepts_mask):
result = cv.matchTemplate(img, templ, match_method, None, mask)
else:
result = cv.matchTemplate(img, templ, match_method)
## [match_template]
## [normalize]
cv.normalize( result, result, 0, 1, cv.NORM_MINMAX, -1 )
## [normalize]
## [best_match]
_minVal, _maxVal, minLoc, maxLoc = cv.minMaxLoc(result, None)
## [best_match]
## [match_loc]
if (match_method == cv.TM_SQDIFF or match_method == cv.TM_SQDIFF_NORMED):
matchLoc = minLoc
else:
matchLoc = maxLoc
## [match_loc]
## [imshow]
cv.rectangle(img_display, matchLoc, (matchLoc[0] + templ.shape[0], matchLoc[1] + templ.shape[1]), (0,0,0), 2, 8, 0 )
cv.rectangle(result, matchLoc, (matchLoc[0] + templ.shape[0], matchLoc[1] + templ.shape[1]), (0,0,0), 2, 8, 0 )
cv.imshow(image_window, img_display)
cv.imshow(result_window, result)
## [imshow]
pass
if __name__ == "__main__":
main(sys.argv[1:])
| 1,225 |
1,585 | /*
* Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2005 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2011-2012 Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2015 Research Organization for Information Science
* and Technology (RIST). All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "ompi_config.h"
#include "ompi/mpi/fortran/mpif-h/bindings.h"
#if OMPI_BUILD_MPI_PROFILING
#if OPAL_HAVE_WEAK_SYMBOLS
#pragma weak PMPI_COMM_JOIN = ompi_comm_join_f
#pragma weak pmpi_comm_join = ompi_comm_join_f
#pragma weak pmpi_comm_join_ = ompi_comm_join_f
#pragma weak pmpi_comm_join__ = ompi_comm_join_f
#pragma weak PMPI_Comm_join_f = ompi_comm_join_f
#pragma weak PMPI_Comm_join_f08 = ompi_comm_join_f
#else
OMPI_GENERATE_F77_BINDINGS (PMPI_COMM_JOIN,
pmpi_comm_join,
pmpi_comm_join_,
pmpi_comm_join__,
pompi_comm_join_f,
(MPI_Fint *fd, MPI_Fint *intercomm, MPI_Fint *ierr),
(fd, intercomm, ierr) )
#endif
#endif
#if OPAL_HAVE_WEAK_SYMBOLS
#pragma weak MPI_COMM_JOIN = ompi_comm_join_f
#pragma weak mpi_comm_join = ompi_comm_join_f
#pragma weak mpi_comm_join_ = ompi_comm_join_f
#pragma weak mpi_comm_join__ = ompi_comm_join_f
#pragma weak MPI_Comm_join_f = ompi_comm_join_f
#pragma weak MPI_Comm_join_f08 = ompi_comm_join_f
#else
#if ! OMPI_BUILD_MPI_PROFILING
OMPI_GENERATE_F77_BINDINGS (MPI_COMM_JOIN,
mpi_comm_join,
mpi_comm_join_,
mpi_comm_join__,
ompi_comm_join_f,
(MPI_Fint *fd, MPI_Fint *intercomm, MPI_Fint *ierr),
(fd, intercomm, ierr) )
#else
#define ompi_comm_join_f pompi_comm_join_f
#endif
#endif
void ompi_comm_join_f(MPI_Fint *fd, MPI_Fint *intercomm, MPI_Fint *ierr)
{
int c_ierr;
MPI_Comm c_intercomm;
c_ierr = PMPI_Comm_join(OMPI_FINT_2_INT(*fd), &c_intercomm);
if (NULL != ierr) *ierr = OMPI_INT_2_FINT(c_ierr);
if (MPI_SUCCESS == c_ierr) {
*intercomm = PMPI_Comm_c2f(c_intercomm);
}
}
| 1,492 |
2,151 | /*
* Copyright (c) 2018 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/video_coding/codecs/multiplex/include/multiplex_encoded_image_packer.h"
#include <cstring>
#include "modules/rtp_rtcp/source/byte_io.h"
namespace webrtc {
int PackHeader(uint8_t* buffer, MultiplexImageHeader header) {
int offset = 0;
ByteWriter<uint8_t>::WriteBigEndian(buffer + offset, header.component_count);
offset += sizeof(uint8_t);
ByteWriter<uint16_t>::WriteBigEndian(buffer + offset, header.image_index);
offset += sizeof(uint16_t);
ByteWriter<uint32_t>::WriteBigEndian(buffer + offset,
header.first_component_header_offset);
offset += sizeof(uint32_t);
RTC_DCHECK_EQ(offset, kMultiplexImageHeaderSize);
return offset;
}
MultiplexImageHeader UnpackHeader(uint8_t* buffer) {
MultiplexImageHeader header;
int offset = 0;
header.component_count = ByteReader<uint8_t>::ReadBigEndian(buffer + offset);
offset += sizeof(uint8_t);
header.image_index = ByteReader<uint16_t>::ReadBigEndian(buffer + offset);
offset += sizeof(uint16_t);
header.first_component_header_offset =
ByteReader<uint32_t>::ReadBigEndian(buffer + offset);
offset += sizeof(uint32_t);
RTC_DCHECK_EQ(offset, kMultiplexImageHeaderSize);
return header;
}
int PackFrameHeader(uint8_t* buffer,
MultiplexImageComponentHeader frame_header) {
int offset = 0;
ByteWriter<uint32_t>::WriteBigEndian(
buffer + offset, frame_header.next_component_header_offset);
offset += sizeof(uint32_t);
ByteWriter<uint8_t>::WriteBigEndian(buffer + offset,
frame_header.component_index);
offset += sizeof(uint8_t);
ByteWriter<uint32_t>::WriteBigEndian(buffer + offset,
frame_header.bitstream_offset);
offset += sizeof(uint32_t);
ByteWriter<uint32_t>::WriteBigEndian(buffer + offset,
frame_header.bitstream_length);
offset += sizeof(uint32_t);
ByteWriter<uint8_t>::WriteBigEndian(buffer + offset, frame_header.codec_type);
offset += sizeof(uint8_t);
ByteWriter<uint8_t>::WriteBigEndian(buffer + offset, frame_header.frame_type);
offset += sizeof(uint8_t);
RTC_DCHECK_EQ(offset, kMultiplexImageComponentHeaderSize);
return offset;
}
MultiplexImageComponentHeader UnpackFrameHeader(uint8_t* buffer) {
MultiplexImageComponentHeader frame_header;
int offset = 0;
frame_header.next_component_header_offset =
ByteReader<uint32_t>::ReadBigEndian(buffer + offset);
offset += sizeof(uint32_t);
frame_header.component_index =
ByteReader<uint8_t>::ReadBigEndian(buffer + offset);
offset += sizeof(uint8_t);
frame_header.bitstream_offset =
ByteReader<uint32_t>::ReadBigEndian(buffer + offset);
offset += sizeof(uint32_t);
frame_header.bitstream_length =
ByteReader<uint32_t>::ReadBigEndian(buffer + offset);
offset += sizeof(uint32_t);
frame_header.codec_type = static_cast<VideoCodecType>(
ByteReader<uint8_t>::ReadBigEndian(buffer + offset));
offset += sizeof(uint8_t);
frame_header.frame_type = static_cast<FrameType>(
ByteReader<uint8_t>::ReadBigEndian(buffer + offset));
offset += sizeof(uint8_t);
RTC_DCHECK_EQ(offset, kMultiplexImageComponentHeaderSize);
return frame_header;
}
void PackBitstream(uint8_t* buffer, MultiplexImageComponent image) {
memcpy(buffer, image.encoded_image._buffer, image.encoded_image._length);
}
MultiplexImage::MultiplexImage(uint16_t picture_index, uint8_t frame_count)
: image_index(picture_index), component_count(frame_count) {}
EncodedImage MultiplexEncodedImagePacker::PackAndRelease(
const MultiplexImage& multiplex_image) {
MultiplexImageHeader header;
std::vector<MultiplexImageComponentHeader> frame_headers;
header.component_count = multiplex_image.component_count;
header.image_index = multiplex_image.image_index;
int header_offset = kMultiplexImageHeaderSize;
header.first_component_header_offset = header_offset;
int bitstream_offset = header_offset + kMultiplexImageComponentHeaderSize *
header.component_count;
const std::vector<MultiplexImageComponent>& images =
multiplex_image.image_components;
EncodedImage combined_image = images[0].encoded_image;
for (size_t i = 0; i < images.size(); i++) {
MultiplexImageComponentHeader frame_header;
header_offset += kMultiplexImageComponentHeaderSize;
frame_header.next_component_header_offset =
(i == images.size() - 1) ? 0 : header_offset;
frame_header.component_index = images[i].component_index;
frame_header.bitstream_offset = bitstream_offset;
const size_t padding =
EncodedImage::GetBufferPaddingBytes(images[i].codec_type);
frame_header.bitstream_length =
static_cast<uint32_t>(images[i].encoded_image._length + padding);
bitstream_offset += frame_header.bitstream_length;
frame_header.codec_type = images[i].codec_type;
frame_header.frame_type = images[i].encoded_image._frameType;
// As long as one component is delta frame, we have to mark the combined
// frame as delta frame, because it is necessary for all components to be
// key frame so as to decode the whole image without previous frame data.
// Thus only when all components are key frames, we can mark the combined
// frame as key frame.
if (frame_header.frame_type == FrameType::kVideoFrameDelta) {
combined_image._frameType = FrameType::kVideoFrameDelta;
}
frame_headers.push_back(frame_header);
}
combined_image._length = combined_image._size = bitstream_offset;
combined_image._buffer = new uint8_t[combined_image._length];
// header
header_offset = PackHeader(combined_image._buffer, header);
RTC_DCHECK_EQ(header.first_component_header_offset,
kMultiplexImageHeaderSize);
// Frame Header
for (size_t i = 0; i < images.size(); i++) {
int relative_offset = PackFrameHeader(
combined_image._buffer + header_offset, frame_headers[i]);
RTC_DCHECK_EQ(relative_offset, kMultiplexImageComponentHeaderSize);
header_offset = frame_headers[i].next_component_header_offset;
RTC_DCHECK_EQ(header_offset,
(i == images.size() - 1)
? 0
: (kMultiplexImageHeaderSize +
kMultiplexImageComponentHeaderSize * (i + 1)));
}
// Bitstreams
for (size_t i = 0; i < images.size(); i++) {
PackBitstream(combined_image._buffer + frame_headers[i].bitstream_offset,
images[i]);
delete[] images[i].encoded_image._buffer;
}
return combined_image;
}
MultiplexImage MultiplexEncodedImagePacker::Unpack(
const EncodedImage& combined_image) {
const MultiplexImageHeader& header = UnpackHeader(combined_image._buffer);
MultiplexImage multiplex_image(header.image_index, header.component_count);
std::vector<MultiplexImageComponentHeader> frame_headers;
int header_offset = header.first_component_header_offset;
while (header_offset > 0) {
frame_headers.push_back(
UnpackFrameHeader(combined_image._buffer + header_offset));
header_offset = frame_headers.back().next_component_header_offset;
}
RTC_DCHECK_LE(frame_headers.size(), header.component_count);
for (size_t i = 0; i < frame_headers.size(); i++) {
MultiplexImageComponent image_component;
image_component.component_index = frame_headers[i].component_index;
image_component.codec_type = frame_headers[i].codec_type;
EncodedImage encoded_image = combined_image;
encoded_image._timeStamp = combined_image._timeStamp;
encoded_image._frameType = frame_headers[i].frame_type;
encoded_image._size =
static_cast<size_t>(frame_headers[i].bitstream_length);
const size_t padding =
EncodedImage::GetBufferPaddingBytes(image_component.codec_type);
encoded_image._length = encoded_image._size - padding;
encoded_image._buffer =
combined_image._buffer + frame_headers[i].bitstream_offset;
image_component.encoded_image = encoded_image;
multiplex_image.image_components.push_back(image_component);
}
return multiplex_image;
}
} // namespace webrtc
| 3,117 |
806 | package com.fihtdc.push_system.lib.app;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import com.fihtdc.push_system.lib.app.IFihPushReceiveService.Stub;
import com.fihtdc.push_system.lib.common.PushMessageContract;
import com.fihtdc.push_system.lib.common.PushProp;
import com.fihtdc.push_system.lib.utils.PushMessageUtil;
public abstract class FihPushReceiveService extends Service {
private final Stub mBinder = new C01031();
/* renamed from: com.fihtdc.push_system.lib.app.FihPushReceiveService$1 */
class C01031 extends Stub {
C01031() {
}
public Bundle getPushInfos() throws RemoteException {
return FihPushReceiveService.this.getPushInfos();
}
public void newPushMessage(Bundle datas) throws RemoteException {
if (!FihPushReceiveService.this.newPushMessage(datas) && PushMessageContract.TYPE_MESSAGE.equals(datas.getString(PushMessageContract.MESSAGE_KEY_TYPE))) {
PushMessageUtil.showNotification(FihPushReceiveService.this.getApplicationContext(), datas, FihPushReceiveService.this.getDefaultNotificationSmallIcon(), FihPushReceiveService.this.getDefaultNotificationBigIcon());
}
}
public Bundle getApplicationInfo() throws RemoteException {
Bundle info = new Bundle();
try {
info.putString(PushProp.KEY_APP_INFO_ACCESS_ID, FihPushReceiveService.this.getAccessId());
info.putString(PushProp.KEY_APP_INFO_ACCESS_KEY, FihPushReceiveService.this.getAccessKey());
info.putString(PushProp.KEY_APP_INFO_SECRET_kEY, FihPushReceiveService.this.getSecretKey());
} catch (Throwable t) {
t.printStackTrace();
}
return info;
}
}
public abstract String getAccessId();
public abstract String getAccessKey();
public abstract int getDefaultNotificationSmallIcon();
public abstract Bundle getPushInfos();
public abstract String getSecretKey();
public abstract boolean newPushMessage(Bundle bundle);
public Bitmap getDefaultNotificationBigIcon() {
return null;
}
public IBinder onBind(Intent intent) {
return this.mBinder;
}
}
| 909 |
1,131 | <gh_stars>1000+
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.cloudstack.server.auth;
import static java.lang.String.format;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;
import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.bouncycastle.crypto.PBEParametersGenerator;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Base64;
import com.cloud.server.auth.UserAuthenticator;
import com.cloud.user.UserAccount;
import com.cloud.user.dao.UserAccountDao;
import com.cloud.utils.ConstantTimeComparator;
import com.cloud.utils.Pair;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.exception.CloudRuntimeException;
public class PBKDF2UserAuthenticator extends AdapterBase implements UserAuthenticator {
public static final Logger s_logger = Logger.getLogger(PBKDF2UserAuthenticator.class);
private static final int s_saltlen = 64;
private static final int s_rounds = 100000;
private static final int s_keylen = 512;
@Inject
private UserAccountDao _userAccountDao;
@Override
public Pair<Boolean, UserAuthenticator.ActionOnFailedAuthentication> authenticate(String username, String password, Long domainId, Map<String, Object[]> requestParameters) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Retrieving user: " + username);
}
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
s_logger.debug("Username or Password cannot be empty");
return new Pair<Boolean, ActionOnFailedAuthentication>(false, null);
}
boolean isValidUser = false;
UserAccount user = this._userAccountDao.getUserAccount(username, domainId);
if (user != null) {
isValidUser = true;
} else {
s_logger.debug("Unable to find user with " + username + " in domain " + domainId);
}
byte[] salt = new byte[0];
int rounds = s_rounds;
try {
if (isValidUser) {
String[] storedPassword = user.getPassword().split(":");
if ((storedPassword.length != 3) || (!StringUtils.isNumeric(storedPassword[2]))) {
s_logger.warn("The stored password for " + username + " isn't in the right format for this authenticator");
isValidUser = false;
} else {
// Encoding format = <salt>:<password hash>:<rounds>
salt = decode(storedPassword[0]);
rounds = Integer.parseInt(storedPassword[2]);
}
}
boolean result = false;
if (isValidUser && validateCredentials(password, salt)) {
result = ConstantTimeComparator.compareStrings(user.getPassword(), encode(password, salt, rounds));
}
UserAuthenticator.ActionOnFailedAuthentication action = null;
if ((!result) && (isValidUser)) {
action = UserAuthenticator.ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT;
}
return new Pair(Boolean.valueOf(result), action);
} catch (NumberFormatException e) {
throw new CloudRuntimeException("Unable to hash password", e);
} catch (NoSuchAlgorithmException e) {
throw new CloudRuntimeException("Unable to hash password", e);
} catch (UnsupportedEncodingException e) {
throw new CloudRuntimeException("Unable to hash password", e);
} catch (InvalidKeySpecException e) {
throw new CloudRuntimeException("Unable to hash password", e);
}
}
@Override
public String encode(String password)
{
try
{
return encode(password, makeSalt(), s_rounds);
} catch (NoSuchAlgorithmException e) {
throw new CloudRuntimeException("Unable to hash password", e);
} catch (UnsupportedEncodingException e) {
throw new CloudRuntimeException("Unable to hash password", e);
} catch (InvalidKeySpecException e) {
s_logger.error("Exception in EncryptUtil.createKey ", e);
throw new CloudRuntimeException("Unable to hash password", e);
}
}
public String encode(String password, byte[] salt, int rounds)
throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException {
PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator();
generator.init(PBEParametersGenerator.PKCS5PasswordToBytes(
password.toCharArray()),
salt,
rounds);
return format("%s:%s:%d", encode(salt),
encode(((KeyParameter)generator.generateDerivedParameters(s_keylen)).getKey()), rounds);
}
public static byte[] makeSalt() throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[s_saltlen];
sr.nextBytes(salt);
return salt;
}
private static boolean validateCredentials(String plainPassword, byte[] hash) {
return !(plainPassword == null || plainPassword.isEmpty() || hash == null || hash.length == 0);
}
private static String encode(byte[] input) throws UnsupportedEncodingException {
return new String(Base64.encode(input), "UTF-8");
}
private static byte[] decode(String input) throws UnsupportedEncodingException {
return Base64.decode(input.getBytes("UTF-8"));
}
}
| 2,481 |
1,062 | //
// Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <objc/NSObject.h>
@interface MCImageJunkMetadata : NSObject
{
unsigned long long _pixelCount; // 8 = 0x8
unsigned long long _byteCount; // 16 = 0x10
BOOL _isAnimated; // 24 = 0x18
long long _type; // 32 = 0x20
unsigned long long _frameCount; // 40 = 0x28
double _density; // 48 = 0x30
struct CGSize _size; // 56 = 0x38
}
+ (id)lsmMarkerForImageDensityCategory:(long long)arg1; // IMP=0x00000000000531d0
+ (id)lsmMarkerForImageSizeCategory:(long long)arg1; // IMP=0x000000000005306c
+ (id)stringForImageType:(long long)arg1; // IMP=0x0000000000052f0c
@property(nonatomic) BOOL isAnimated; // @synthesize isAnimated=_isAnimated;
@property(nonatomic) double density; // @synthesize density=_density;
@property(nonatomic) unsigned long long frameCount; // @synthesize frameCount=_frameCount;
@property(nonatomic) struct CGSize size; // @synthesize size=_size;
@property(nonatomic) long long type; // @synthesize type=_type;
- (id)description; // IMP=0x0000000000053609
@property(readonly, nonatomic) long long densityCategory;
@property(readonly, nonatomic) long long sizeCategory;
@property(nonatomic) unsigned long long pixelCount;
@property(nonatomic) unsigned long long byteCount;
- (void)_computeDensity; // IMP=0x0000000000053452
- (id)init; // IMP=0x0000000000053439
- (id)initWithImage:(id)arg1 name:(id)arg2 type:(long long)arg3; // IMP=0x0000000000053334
@end
| 570 |
4,054 | <gh_stars>1000+
package org.eclipse.fx.drift.internal;
import java.time.Duration;
import java.util.LinkedList;
import java.util.Queue;
public class FPSCounter {
long lastFrame;
Queue<Long> framesTimes = new LinkedList<>();
double avgFps;
public void frame() {
long lastFrameDur = System.nanoTime() - lastFrame;
if (framesTimes.size() > 10) framesTimes.poll();
framesTimes.offer(lastFrameDur);
lastFrame = System.nanoTime();
//double avgTime = framesTimes.stream().mapToLong(l -> l).average().orElse(0);
//System.err.println(String.format("%5.3ffps", Duration.ofSeconds(1).toNanos() / avgTime));
}
public double avgTime() {
return framesTimes.stream().mapToLong(l -> l).average().orElse(0);
}
public double avgFps() {
return Duration.ofSeconds(1).toNanos() / avgTime();
}
}
| 306 |
450 | #include <pspsdk.h>
#include <psppower.h>
#include <pspkernel.h>
#include <pspsuspend.h>
#include <pspsysevent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include "../kernel/kernel.h"
//#define DEBUG_MALLOC_P5
#ifdef DEBUG_MALLOC_P5
unsigned int malloc_p5_memory_used = 0;
#endif
struct PspSysEventHandler malloc_p5_sysevent_handler_struct;
// From: http://forums.ps2dev.org/viewtopic.php?p=70854#70854
int malloc_p5_sysevent_handler(int ev_id, char* ev_name, void* param, int* result)
{
if (ev_id == 0x100) // PSP_SYSEVENT_SUSPEND_QUERY
return -1;
return 0;
}
int malloc_p5_initialized = 0;
int malloc_p5_init()
{
// Unlock memory partition 5
void* pointer = NULL;
int returnsize = 0;
int result = sceKernelVolatileMemLock(0, &pointer, &returnsize);
if (result == 0)
{
printf("sceKernelVolatileMemLock(%d, %d) = %d\n", (unsigned int)pointer, returnsize, result);
// Register sysevent handler to prevent suspend mode because p5 memory cannot be resumed
memset(&malloc_p5_sysevent_handler_struct, 0, sizeof(struct PspSysEventHandler));
malloc_p5_sysevent_handler_struct.size = sizeof(struct PspSysEventHandler);
malloc_p5_sysevent_handler_struct.name = "p5_suspend_handler";
malloc_p5_sysevent_handler_struct.handler = &malloc_p5_sysevent_handler;
malloc_p5_sysevent_handler_struct.type_mask = 0x0000FF00;
kernel_sceKernelRegisterSysEventHandler(&malloc_p5_sysevent_handler_struct);
malloc_p5_initialized = 1;
}
else
malloc_p5_initialized = 0;
return malloc_p5_initialized;
}
int malloc_p5_shutdown()
{
if (malloc_p5_initialized)
{
if (sceKernelVolatileMemUnlock(0) == 0)
{
kernel_sceKernelUnregisterSysEventHandler(&malloc_p5_sysevent_handler_struct);
malloc_p5_initialized = 0;
}
}
return !malloc_p5_initialized;
}
void* malloc(size_t size)
{
if (!malloc_p5_initialized)
return (void*)_malloc_r(NULL, size);
void* result = (void*)_malloc_r(NULL, size);
#ifdef DEBUG_MALLOC_P5
struct mallinfo info = _mallinfo_r(NULL);
printf("used memory %d of %d - %d\n", info.usmblks + info.uordblks, info.arena, malloc_p5_memory_used);
#endif
if (result)
return result;
SceUID uid = sceKernelAllocPartitionMemory(5, "", PSP_SMEM_Low, size + 8, NULL);
if (uid >= 0)
{
#ifdef DEBUG_MALLOC_P5
printf("getting memory from p5 %d %d\n", size, uid);
malloc_p5_memory_used += size;
#endif
unsigned int* pointer = (unsigned int*)sceKernelGetBlockHeadAddr(uid);
*pointer = uid;
*(pointer + 4) = size;
return (void*)(pointer + 8);
}
else
{
#ifdef DEBUG_MALLOC_P5
printf("*****failed to allocate %d byte from p5\n", size);
#endif
return NULL;
}
}
void* calloc(size_t num, size_t size)
{
if (!malloc_p5_initialized)
return (void*)_calloc_r(NULL, num, size);
void* result = malloc(num * size);
if (result)
memset(result, 0, num * size);
return result;
}
void* realloc(void* ptr, size_t size)
{
if (!malloc_p5_initialized)
return (void*)_realloc_r(NULL, ptr, size);
if (!ptr)
return malloc(size);
if (ptr >= (void*)0x08800000)
{
void* result = (void*)_realloc_r(NULL, ptr, size);
return result;
}
else
{
unsigned int oldsize = (unsigned int)*((SceUID*)ptr - 4);
#ifdef DEBUG_MALLOC_P5
printf("realloc p5 memory %d %d\n", oldsize, size);
malloc_p5_memory_used += (size - oldsize);
#endif
void* target = malloc(size);
if (target)
{
memcpy(target, ptr, oldsize);
free(ptr);
return target;
}
}
return NULL;
}
void free(void* ptr)
{
if (!malloc_p5_initialized)
{
_free_r(NULL, ptr);
return;
}
if (!ptr)
return;
if (ptr >= (void*)0x08800000)
_free_r(NULL, ptr);
else
{
#ifdef DEBUG_MALLOC_P5
printf("freeing p5 memory %d\n", (unsigned int)*((SceUID*)ptr - 8));
malloc_p5_memory_used -= *((SceUID*)ptr - 4);
#endif
sceKernelFreePartitionMemory(*((SceUID*)ptr - 8));
}
}
| 1,718 |
3,102 | // Check that -no-integrated-as works when -target i386-pc-win32-macho or
// -target x86_64-pc-win32-macho is specified.
// RUN: %clang -### -c -target i386-pc-win32-macho -no-integrated-as %s 2> %t1
// RUN: FileCheck -check-prefix=X86 < %t1 %s
// RUN: %clang -### -c -target x86_64-pc-win32-macho -no-integrated-as %s 2> %t2
// RUN: FileCheck -check-prefix=X86_64 < %t2 %s
//
// X86: "-cc1"
// X86-NOT: "-cc1as"
// X86: "-arch"
// X86: "i386"
//
// X86_64: "-cc1"
// X86_64-NOT: "-cc1as"
// X86_64: "-arch"
// X86_64: "x86_64"
| 252 |
623 | <filename>java/com/google/gerrit/entities/converter/PatchSetProtoConverter.java
// Copyright (C) 2018 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.entities.converter;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.Immutable;
import com.google.gerrit.entities.Account;
import com.google.gerrit.entities.PatchSet;
import com.google.gerrit.proto.Entities;
import com.google.protobuf.Parser;
import java.time.Instant;
import java.util.List;
import org.eclipse.jgit.lib.ObjectId;
@Immutable
public enum PatchSetProtoConverter implements ProtoConverter<Entities.PatchSet, PatchSet> {
INSTANCE;
private final ProtoConverter<Entities.PatchSet_Id, PatchSet.Id> patchSetIdConverter =
PatchSetIdProtoConverter.INSTANCE;
private final ProtoConverter<Entities.ObjectId, ObjectId> objectIdConverter =
ObjectIdProtoConverter.INSTANCE;
private final ProtoConverter<Entities.Account_Id, Account.Id> accountIdConverter =
AccountIdProtoConverter.INSTANCE;
@Override
public Entities.PatchSet toProto(PatchSet patchSet) {
Entities.PatchSet.Builder builder =
Entities.PatchSet.newBuilder()
.setId(patchSetIdConverter.toProto(patchSet.id()))
.setCommitId(objectIdConverter.toProto(patchSet.commitId()))
.setUploaderAccountId(accountIdConverter.toProto(patchSet.uploader()))
.setCreatedOn(patchSet.createdOn().toEpochMilli());
List<String> groups = patchSet.groups();
if (!groups.isEmpty()) {
builder.setGroups(PatchSet.joinGroups(groups));
}
patchSet.pushCertificate().ifPresent(builder::setPushCertificate);
patchSet.description().ifPresent(builder::setDescription);
return builder.build();
}
@Override
public PatchSet fromProto(Entities.PatchSet proto) {
PatchSet.Builder builder =
PatchSet.builder()
.id(patchSetIdConverter.fromProto(proto.getId()))
.groups(
proto.hasGroups() ? PatchSet.splitGroups(proto.getGroups()) : ImmutableList.of());
if (proto.hasPushCertificate()) {
builder.pushCertificate(proto.getPushCertificate());
}
if (proto.hasDescription()) {
builder.description(proto.getDescription());
}
// The following fields used to theoretically be nullable in PatchSet, but in practice no
// production codepath should have ever serialized an instance that was missing one of these
// fields.
//
// However, since some protos may theoretically be missing these fields, we need to support
// them. Populate specific sentinel values for each field as documented in the PatchSet javadoc.
// Callers that encounter one of these sentinels will likely fail, for example by failing to
// look up the zeroId. They would have also failed back when the fields were nullable, for
// example with NPE; the current behavior just fails slightly differently.
builder
.commitId(
proto.hasCommitId()
? objectIdConverter.fromProto(proto.getCommitId())
: ObjectId.zeroId())
.uploader(
proto.hasUploaderAccountId()
? accountIdConverter.fromProto(proto.getUploaderAccountId())
: Account.id(0))
.createdOn(
proto.hasCreatedOn() ? Instant.ofEpochMilli(proto.getCreatedOn()) : Instant.EPOCH);
return builder.build();
}
@Override
public Parser<Entities.PatchSet> getParser() {
return Entities.PatchSet.parser();
}
}
| 1,438 |
945 | <reponame>the-gates-of-Zion/zero-shot-gcn
from __future__ import print_function
import argparse
import json
import numpy as np
import os
import pickle as pkl
import scipy.io as sio
import time
def test_imagenet_zero(fc_file_pred, has_train=1):
with open(classids_file_retrain) as fp:
classids = json.load(fp)
with open(word2vec_file, 'rb') as fp:
word2vec_feat = pkl.load(fp)
testlist = []
testlabels = []
with open(vallist_folder) as fp:
for line in fp:
fname, lbl = line.split()
assert int(lbl) >= 1000
# feat_name = os.path.join(feat_folder, fname.replace('.JPEG', '.mat'))
feat_name = os.path.join(feat_folder, fname.replace('.JPEG', '.npz'))
if not os.path.exists(feat_name):
print('not feature', feat_name)
continue
testlist.append(feat_name)
testlabels.append(int(lbl))
with open(fc_file_pred, 'rb') as fp:
fc_layers_pred = pkl.load(fp)
fc_layers_pred = np.array(fc_layers_pred)
print('fc output', fc_layers_pred.shape)
# remove invalid classes(wv = 0)
valid_clss = np.zeros(22000)
cnt_zero_wv = 0
for j in range(len(classids)):
if classids[j][1] == 1:
twv = word2vec_feat[j]
twv = twv / (np.linalg.norm(twv) + 1e-6)
if np.linalg.norm(twv) == 0:
cnt_zero_wv = cnt_zero_wv + 1
continue
valid_clss[classids[j][0]] = 1
# process 'train' classes. they are possible candidates during inference
cnt_zero_wv = 0
labels_train, word2vec_train = [], []
fc_now = []
for j in range(len(classids)):
tfc = fc_layers_pred[j]
if has_train:
if classids[j][0] < 0:
continue
else:
if classids[j][1] == 0:
continue
if classids[j][0] >= 0:
twv = word2vec_feat[j]
if np.linalg.norm(twv) == 0:
cnt_zero_wv = cnt_zero_wv + 1
continue
labels_train.append(classids[j][0])
word2vec_train.append(twv)
feat_len = len(tfc)
tfc = tfc[feat_len - fc_dim: feat_len]
fc_now.append(tfc)
fc_now = np.array(fc_now)
print('skip candidate class due to no word embedding: %d / %d:' % (cnt_zero_wv, len(labels_train) + cnt_zero_wv))
print('candidate class shape: ', fc_now.shape)
fc_now = fc_now.T
labels_train = np.array(labels_train)
print('train + test class: ', len(labels_train))
topKs = [1]
top_retrv = [1, 2, 5, 10, 20]
hit_count = np.zeros((len(topKs), len(top_retrv)))
cnt_valid = 0
t = time.time()
for j in range(len(testlist)):
featname = testlist[j]
if valid_clss[testlabels[j]] == 0:
continue
cnt_valid = cnt_valid + 1
# matfeat = sio.loadmat(featname)
matfeat = np.load(featname)
matfeat = matfeat['feat']
scores = np.dot(matfeat, fc_now).squeeze()
scores = scores - scores.max()
scores = np.exp(scores)
scores = scores / scores.sum()
ids = np.argsort(-scores)
for k in range(len(topKs)):
for k2 in range(len(top_retrv)):
current_len = top_retrv[k2]
for sort_id in range(current_len):
lbl = labels_train[ids[sort_id]]
if lbl == testlabels[j]:
hit_count[k][k2] = hit_count[k][k2] + 1
break
if j % 10000 == 0:
inter = time.time() - t
print('processing %d / %d ' % (j, len(testlist)), ', Estimated time: ', inter / (j-1) * (len(testlist) - j))
hit_count = hit_count / cnt_valid
fout = open(fc_file_pred + '_result_pred_zero.txt', 'w')
for j in range(len(topKs)):
outstr = ''
for k in range(len(top_retrv)):
outstr = outstr + ' ' + str(hit_count[j][k])
print(outstr)
print('total: %d', cnt_valid)
fout.write(outstr + '\n')
fout.close()
return hit_count
# global var
data_dir = '../data/list/'
classids_file_retrain = ""
word2vec_file = ""
vallist_folder = ""
fc_dim = 0
wv_dim = 0
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--model', type=str, default='model/wordnet_google_glove_feat_2048_1024_512_300',
help='path of model to test')
parser.add_argument('--feat', type=str, default='../feats/res50/',
help='path of fc feature')
parser.add_argument('--hop', type=str, default='2',
help='choice of unseen set: 2,3,all, separate with comma')
parser.add_argument('--wv', type=str, default='glove',
help='word embedding type: [glove, google, fasttext]')
parser.add_argument('--train', type=str, default='0,1',
help='contain train class or not')
parser.add_argument('--fc', type=str, default='res50',
help='choice: [inception,res50]')
args = parser.parse_args()
print('-----------info-----------')
print(args)
print('--------------------------')
if not os.path.exists(args.model):
print('model does not exist: %s' % args.model)
raise NotImplementedError
if args.feat == None:
print('please specify feature folder as --feat $path')
feat_folder = args.feat
if args.fc == 'inception':
fc_dim = 1024
elif args.fc == 'res50':
fc_dim = 2048
else:
print('args.fc supports google (for Inception-v1)/ res50 (for Resnet-50)')
raise ValueError
if args.wv == 'glove':
word2vec_file = '../data/word_embedding_model/glove_word2vec_wordnet.pkl'
elif args.wv == 'google':
word2vec_file = '../data/word_embedding_model/google_word2vec_wordnet.pkl'
elif args.wv == 'fasttext':
word2vec_file = '../data/word_embedding_model/fasttext_word2vec_wordnet.pkl'
else:
print('args.wv supports glove (for GloVe) / fast (for FastText)')
raise ValueError
hop_set = args.hop.split(',')
train_set = args.train.split(',')
results = []
result_pool = []
for hop in hop_set:
for has_train in train_set:
args.hop = hop
args.train = int(has_train)
param = 'Test Set: '
if args.hop == '2':
vallist_folder = os.path.join(data_dir, 'img-2-hops.txt')
classids_file_retrain = os.path.join(data_dir, 'corresp-2-hops.json')
param += '2-hops'
elif args.hop == '3':
vallist_folder = os.path.join(data_dir, 'img-3-hops.txt')
classids_file_retrain = os.path.join(data_dir, 'corresp-3-hops.json')
param += '3-hops'
elif args.hop == 'all':
vallist_folder = os.path.join(data_dir, 'img-all.txt')
classids_file_retrain = os.path.join(data_dir, 'corresp-all.json')
param += 'All'
if int(has_train) == 1:
param += ' (+ 1K)'
param += ' ,with word embedding %s' % args.wv
print('\nEvaluating %s ...\nPlease be patient for it takes a few minutes...' % param)
res = test_imagenet_zero(fc_file_pred=args.model, has_train=args.train)
output = ['{:.1f}'.format(i * 100) for i in res[0]]
result_pool.append(output)
results.append((args.model, output, param))
print('----------------------')
print('model : ', args.model)
print('param : ', param)
print('result: ', output)
print('----------------------')
print('\n======== summary: ========')
for i in range(len(results)):
print('%s: ' % str(results[i][2]))
print('%s' % str(results[i][1]))
print('for model %s' % args.model)
| 4,008 |
2,724 | <filename>src/sap.ui.fl/test/sap/ui/fl/qunit/testResources/condenser/mixIndexNonIndexNonExisting.json
[
{
"id": "id_1576562312431_44_renameField",
"changeType": "renameField",
"reference": "sap.ui.rta.test.Component",
"content": {
"originalControlType": "sap.ui.comp.smartform.GroupElement"
},
"selector": {
"id": "idMain1--Victim",
"idIsLocal": true
},
"texts": {
"fieldLabel": {
"value": "Just a button",
"type": "XFLD"
}
},
"creation": "2019-12-17T06:03:58.188Z"
},
{
"id": "id_1576562369568_54_renameField",
"changeType": "renameField",
"reference": "sap.ui.rta.test.Component",
"content": {
"originalControlType": "sap.ui.comp.smartform.GroupElement"
},
"selector": {
"id": "idMain1--Victim",
"idIsLocal": true
},
"texts": {
"fieldLabel": {
"value": "Don't rely on me",
"type": "XFLD"
}
},
"creation": "2019-12-17T06:03:58.192Z"
},
{
"id": "id_1580042266646_00_notAvailable",
"changeType": "rename",
"reference": "sap.ui.rta.test.Component",
"content": {
"originalControlType": "sap.ui.comp.smartform.GroupElement"
},
"selector": {
"id": "idMain1--notAvailable",
"idIsLocal": true
},
"texts": {
"fieldLabel": {
"value": "Doc Number",
"type": "XFLD"
}
},
"creation": "2020-01-26T12:40:25.530Z"
},
{
"id": "id_1579503257763_40_moveControls",
"changeType": "moveControls",
"reference": "sap.ui.rta.test.Component",
"content": {
"movedElements": [
{
"selector": {
"id": "idMain1--GeneralLedgerDocument.CompanyCode",
"idIsLocal": true
},
"sourceIndex": 2,
"targetIndex": 0
}
],
"source": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
},
"target": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
}
},
"selector": {
"id": "idMain1--MainForm",
"idIsLocal": true
},
"creation": "2020-01-20T06:54:42.759Z"
},
{
"id": "id_1579503260976_41_moveControls",
"changeType": "moveControls",
"reference": "sap.ui.rta.test.Component",
"content": {
"movedElements": [
{
"selector": {
"id": "idMain1--GeneralLedgerDocument.Name",
"idIsLocal": true
},
"sourceIndex": 1,
"targetIndex": 2
}
],
"source": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
},
"target": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
}
},
"selector": {
"id": "idMain1--MainForm",
"idIsLocal": true
},
"creation": "2020-01-20T06:54:42.760Z"
},
{
"id": "id_1579503265425_42_moveControls",
"changeType": "moveControls",
"reference": "sap.ui.rta.test.Component",
"content": {
"movedElements": [
{
"selector": {
"id": "idMain1--GeneralLedgerDocument.CompanyCode",
"idIsLocal": true
},
"sourceIndex": 0,
"targetIndex": 1
}
],
"source": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
},
"target": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
}
},
"selector": {
"id": "idMain1--MainForm",
"idIsLocal": true
},
"creation": "2020-01-20T06:54:42.761Z"
},
{
"id": "id_1580042266646_01_notAvailable",
"changeType": "rename",
"reference": "sap.ui.rta.test.Component",
"content": {
"originalControlType": "sap.ui.comp.smartform.GroupElement"
},
"selector": {
"id": "idMain1--notAvailable",
"idIsLocal": true
},
"texts": {
"fieldLabel": {
"value": "Doc Number",
"type": "XFLD"
}
},
"creation": "2020-01-26T12:40:25.530Z"
},
{
"id": "id_1579503267482_43_moveControls",
"changeType": "moveControls",
"reference": "sap.ui.rta.test.Component",
"content": {
"movedElements": [
{
"selector": {
"id": "idMain1--GeneralLedgerDocument.Name",
"idIsLocal": true
},
"sourceIndex": 2,
"targetIndex": 1
}
],
"source": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
},
"target": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
}
},
"selector": {
"id": "idMain1--MainForm",
"idIsLocal": true
},
"creation": "2020-01-20T06:54:42.762Z"
}
] | 2,561 |
918 | /*
* 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.gobblin.cluster;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import org.apache.gobblin.annotation.Alias;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.runtime.api.TaskEventMetadataGenerator;
@Alias("helixtask")
public class HelixTaskEventMetadataGenerator implements TaskEventMetadataGenerator {
public static final String HELIX_INSTANCE_KEY = "helixInstance";
public static final String HOST_NAME_KEY = "containerNode";
public static final String HELIX_JOB_ID_KEY = "helixJobId";
public static final String HELIX_TASK_ID_KEY = "helixTaskId";
public static final String CONTAINER_ID_KEY = "containerId";
/**
* Generate a map of additional metadata for the specified event name. For tasks running in Gobblin cluster
* we add container info such as containerId, host name where the task is running to each event.
*
* @param taskState
* @param eventName the event name used to determine which additional metadata should be emitted
* @return {@link Map} with the additional metadata
*/
@Override
public Map<String, String> getMetadata(State taskState, String eventName) {
String helixInstanceName = taskState.getProp(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_KEY, "");
String helixJobId = taskState.getProp(GobblinClusterConfigurationKeys.HELIX_JOB_ID_KEY, "");
String helixTaskId = taskState.getProp(GobblinClusterConfigurationKeys.HELIX_TASK_ID_KEY, "");
String hostName = taskState.getProp(GobblinClusterConfigurationKeys.TASK_RUNNER_HOST_NAME_KEY, "");
String containerId = taskState.getProp(GobblinClusterConfigurationKeys.CONTAINER_ID_KEY, "");
return ImmutableMap.of(HELIX_INSTANCE_KEY, helixInstanceName, HOST_NAME_KEY, hostName, HELIX_JOB_ID_KEY, helixJobId,
HELIX_TASK_ID_KEY, helixTaskId, CONTAINER_ID_KEY, containerId);
}
}
| 815 |
1,658 | /*
Copyright 2015 shizhefei(LuckyJayce)
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.shizhefei.test.controllers;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.shizhefei.test.controllers.mvchelpers.CoolActivity;
import com.shizhefei.test.controllers.mvchelpers.NormalActivity;
import com.shizhefei.test.controllers.mvchelpers.PullrefshActivity;
import com.shizhefei.test.controllers.mvchelpers.SwipeRefreshActivity;
import com.shizhefei.test.controllers.mvchelpers.UltraActivity;
import com.shizhefei.test.controllers.other.BookDetailActivity;
import com.shizhefei.test.controllers.other.MultiTypeActivity;
import com.shizhefei.test.controllers.other.UltraRecyclerViewActivity;
import com.shizhefei.test.controllers.other.Volley_OKHttp_GridViewActivity;
import com.shizhefei.test.controllers.task.ListTaskActivity;
import com.shizhefei.view.mvc.demo.R;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 测试用例
*
* @param view
*/
public void onClickTestCase(View view) {
ProxyActivity.startActivity(this, TestCaseFragment.class, "测试用例");
}
/**
* MVCPullrefshHelper的Demo
*
* @param view
*/
public void onClickDemo10(View view) {
startActivity(new Intent(getApplicationContext(), CoolActivity.class));
}
/**
* MVCPullrefshHelper的Demo
*
* @param view
*/
public void onClickDemo(View view) {
startActivity(new Intent(getApplicationContext(), PullrefshActivity.class));
}
/**
* MVCUltraHelper的Demo
*
* @param view
*/
public void onClickDemo2(View view) {
startActivity(new Intent(getApplicationContext(), UltraActivity.class));
}
/**
* MVCSwipeRefreshHelper的Demo
*
* @param view
*/
public void onClickDemo3(View view) {
startActivity(new Intent(getApplicationContext(), SwipeRefreshActivity.class));
}
/**
* 不具有下拉刷新的非ListView界面
*
* @param view
*/
public void onClickDemo4(View view) {
startActivity(new Intent(getApplicationContext(), BookDetailActivity.class));
}
/**
* 不具有下拉刷新的非ListView界面
*
* @param view
*/
public void onClickDemo5(View view) {
startActivity(new Intent(getApplicationContext(), NormalActivity.class));
}
/**
* Ultra的RecyclerView界面
*
* @param view
*/
public void onClickDemo6(View view) {
startActivity(new Intent(getApplicationContext(), UltraRecyclerViewActivity.class));
}
/**
* Volley和OKhttp网络请求\nandroid-async-http网络请求\n
* GridView界面
*
* @param view
*/
public void onClickDemo8(View view) {
startActivity(new Intent(getApplicationContext(), Volley_OKHttp_GridViewActivity.class));
}
/**
* 结合MultiType达到大道至简的境界
*
* @param view
*/
public void onClickDemo9(View view) {
startActivity(new Intent(getApplicationContext(), MultiTypeActivity.class));
}
/**
* 带有缓存的Task列表
*
* @param view
*/
public void onClickTask3(View view) {
startActivity(new Intent(getApplicationContext(), ListTaskActivity.class));
}
}
| 1,603 |
813 | <gh_stars>100-1000
"""Utility functions for testing only."""
from contextlib import contextmanager
from multiprocessing import Process
import time
from bowtie import View
from bowtie._component import Component
def reset_uuid():
"""Reset the uuid counter for components."""
# pylint: disable=protected-access
Component._NEXT_UUID = 0
View._NEXT_UUID = 0
@contextmanager
def server_check(app):
"""Context manager for testing Bowtie apps and verifying no errors happened."""
process = Process(target=app._serve) # pylint: disable=protected-access
process.start()
time.sleep(5)
yield process
process.terminate()
| 207 |
2,399 | //
// SJClipsSaveResultToAlbumHandler.h
// SJVideoPlayer
//
// Created by 畅三江 on 2019/1/20.
// Copyright © 2019 畅三江. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol SJVideoPlayerClipsResult;
NS_ASSUME_NONNULL_BEGIN
typedef enum : NSUInteger {
SJClipsSaveResultToAlbumFailedReasonAuthDenied,
} SJClipsSaveResultToAlbumFailedReason;
@protocol SJClipsSaveResultFailed <NSObject>
@property (nonatomic, readonly) SJClipsSaveResultToAlbumFailedReason reason;
- (NSString *)toString;
@end
@protocol SJClipsSaveResultToAlbumHandler <NSObject>
- (void)saveResult:(id<SJVideoPlayerClipsResult>)result completionHandler:(void(^)(BOOL r, id<SJClipsSaveResultFailed> failed))completionHandler;
@end
@interface SJClipsSaveResultToAlbumHandler : NSObject<SJClipsSaveResultToAlbumHandler>
@end
NS_ASSUME_NONNULL_END
| 305 |
7,137 | <filename>server-core/src/main/java/io/onedev/server/web/util/LoadableDetachableDataProvider.java
package io.onedev.server.web.util;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
@SuppressWarnings("serial")
public abstract class LoadableDetachableDataProvider<T, S> extends SortableDataProvider<T, S> {
private Long size;
@Override
public final long size() {
if (size == null)
size = calcSize();
return size;
}
@Override
public void detach() {
size = null;
}
protected abstract long calcSize();
}
| 191 |
3,556 | <reponame>peng4217/scylla<filename>tests/test_loggings.py
import logging
def test_basic_logging(caplog):
caplog.set_level(logging.INFO)
logging.info('foo')
assert 'foo' in caplog.text
| 84 |
2,728 | <reponame>adityasingh1993/azure-core<filename>tests/async_tests/test_rest_trio_transport.py
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for
# license information.
# -------------------------------------------------------------------------
from azure.core.pipeline.transport import TrioRequestsTransport
from azure.core.rest import HttpRequest
from azure.core.rest._requests_trio import RestTrioRequestsTransportResponse
from rest_client_async import AsyncTestRestClient
from utils import readonly_checks
import pytest
@pytest.fixture
async def client(port):
async with TrioRequestsTransport() as transport:
async with AsyncTestRestClient(port, transport=transport) as client:
yield client
@pytest.mark.trio
async def test_async_gen_data(client, port):
class AsyncGen:
def __init__(self):
self._range = iter([b"azerty"])
def __aiter__(self):
return self
async def __anext__(self):
try:
return next(self._range)
except StopIteration:
raise StopAsyncIteration
request = HttpRequest('GET', 'http://localhost:{}/basic/anything'.format(port), content=AsyncGen())
response = await client.send_request(request)
assert response.json()['data'] == "azerty"
@pytest.mark.trio
async def test_send_data(port, client):
request = HttpRequest('PUT', 'http://localhost:{}/basic/anything'.format(port), content=b"azerty")
response = await client.send_request(request)
assert response.json()['data'] == "azerty"
@pytest.mark.trio
async def test_readonly(client):
"""Make sure everything that is readonly is readonly"""
response = await client.send_request(HttpRequest("GET", "/health"))
response.raise_for_status()
assert isinstance(response, RestTrioRequestsTransportResponse)
from azure.core.pipeline.transport import TrioRequestsTransportResponse
readonly_checks(response, old_response_class=TrioRequestsTransportResponse)
@pytest.mark.trio
async def test_decompress_compressed_header(client):
# expect plain text
request = HttpRequest("GET", "/encoding/gzip")
response = await client.send_request(request)
content = await response.read()
assert content == b"hello world"
assert response.content == content
assert response.text() == "hello world"
@pytest.mark.trio
async def test_decompress_compressed_header_stream(client):
# expect plain text
request = HttpRequest("GET", "/encoding/gzip")
response = await client.send_request(request, stream=True)
content = await response.read()
assert content == b"hello world"
assert response.content == content
assert response.text() == "hello world"
@pytest.mark.trio
async def test_decompress_compressed_header_stream_body_content(client):
# expect plain text
request = HttpRequest("GET", "/encoding/gzip")
response = await client.send_request(request, stream=True)
await response.read()
content = response.content
assert content == response.body()
| 1,070 |
1,604 | import sys, re, json
from xml.etree import ElementTree
def insert_n(s, nb):
sout = ""
def sub(g):
if g.group(2):
a, b = int(g.group(1)), int(g.group(2)[1:])
return nb[-a - 1:-b or None]
else:
a = int(g.group(1))
return nb[-a - 1]
s = re.sub(r'n\[(\d+)(:\d+)?\]', sub, s)
s = "".join(s.split(":"))
return int(s.replace("0b", ""), 2)
def parse_one(regs, xml):
t = ElementTree.parse(xml)
for reg in t.findall('registers/register'):
data = {}
name = reg.find('reg_short_name').text
fullname = reg.find('reg_long_name').text
if name.startswith("S3_"):
continue
array = reg.find('reg_array')
start = end = 0
if array:
start = int(array.find("reg_array_start").text)
end = int(array.find("reg_array_end").text)
encs = {}
for am in reg.findall('access_mechanisms/access_mechanism'):
accessor = am.attrib["accessor"]
if not accessor.startswith("MSRregister ") and not accessor.startswith("MRS "):
continue
regname = accessor.split(" ", 1)[1]
enc = {}
for e in am.findall("encoding/enc"):
enc[e.attrib["n"]] = e.attrib["v"]
enc = enc["op0"], enc["op1"], enc["CRn"], enc["CRm"], enc["op2"]
if regname in encs:
assert encs[regname] == enc
encs[regname] = enc
if not encs:
continue
fieldsets = []
width = None
for fields_elem in reg.findall('reg_fieldsets/fields'):
fieldset = {}
if (instance_elem := fields_elem.find('fields_instance')) is not None:
fieldset["instance"] = instance_elem.text
fields = []
set_width = int(fields_elem.attrib["length"])
if width is None:
width = set_width
else:
assert width == set_width
single_field = False
for f in fields_elem.findall('field'):
if f.attrib.get("rwtype", None) in ("RES0", "RES1", "RAZ", "RAZ/WI", "RAO/WI", "UNKNOWN"):
continue
msb, lsb = int(f.find('field_msb').text), int(f.find('field_lsb').text)
assert not single_field
if msb == width - 1 and lsb == 0:
continue
if (name_elem := f.find('field_name')) is not None:
name = name_elem.text
else:
assert not fields
continue
field = {
"name": name,
"msb": msb,
"lsb": lsb,
}
fields.append(field)
fields.sort(key=lambda x: x["lsb"], reverse=True)
fieldset["fields"] = fields
fieldsets.append(fieldset)
for idx, n in enumerate(range(start, end + 1)):
nb = "{0:064b}".format(n)[::-1]
for name, enc in sorted(encs.items()):
enc = tuple(insert_n(i, nb) for i in enc)
data = {
"index": idx,
"name": name.replace("<n>", "%d" % n),
"fullname": fullname,
"enc": enc,
"fieldsets": fieldsets,
}
if width is not None:
data["width"] = width
yield data
if __name__ == "__main__":
regs = []
for i in sys.argv[1:]:
regs.extend(parse_one(regs, i))
json.dump(regs, sys.stdout)
| 2,070 |
1,561 | <filename>include/ode/ode/fluid_dynamics/fluid_dynamics.h
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001-2003 <NAME>. *
* All rights reserved. Email: <EMAIL> Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) The GNU Lesser General Public License as published by the Free *
* Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
#ifndef _ODE_FLUID_DYNAMICS_H_
#define _ODE_FLUID_DYNAMICS_H_
#include <ode/common.h>
#include <ode/fluid_dynamics/common_fluid_dynamics.h>
#include <ode/fluid_dynamics/immersion.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup immerse Immersion Detection
*
* ODE has two main components: a dynamics simulation engine and a collision
* detection engine. The collision engine is given information about the
* shape of each body. At each time step it figures out which bodies touch
* each other and passes the resulting contact point information (rigid body vs. rigid body) or immersion information (rigid body vs. fluid) to the user.
* The user in turn creates contact joints between bodies.
*
* Using ODE's collision detection is optional - an alternative collision
* detection system can be used as long as it can supply the right kinds of
* contact information.
*/
/* ************************************************************************ */
/* general functions */
/**
* @brief Set the fluid associated with a placeable geom.
*
* @param geom the geom to connect
* @param fluid the fluid to attach to the geom
* @ingroup immerse
*/
ODE_API void dGeomSetFluid (dGeomID geom, dFluidID fluid);
/**
* @brief Get the fluid associated with a placeable geom.
* @param geom the geom to query.
* @sa dGeomSetFluid
* @ingroup immerse
*/
ODE_API dFluidID dGeomGetFluid (dGeomID geom);
/**
* @brief Get the geom area.
* @param geom the geom to query.
* @ingroup immerse
*/
ODE_API dReal dGeomGetArea (dGeomID geom);
/**
* @brief Get the geom volume.
* @param geom the geom to query.
* @ingroup immerse
*/
ODE_API dReal dGeomGetVolume (dGeomID geom);
/**
* @brief Get the geom immersion plane.
* @param geom the geom to query.
* @param plane the returned plane.
* @ingroup immerse
*/
ODE_API void dGeomGetImmersionPlane(dGeomID geom, dVector4 plane);
/**
* @brief return 1 if the point is below the immersion plane of the geom, 0 otherwise
* @param geom the geom to query.
* @param x the X coordinate of the point.
* @param y the Y coordinate of the point.
* @param z the Z coordinate of the point.
* @ingroup immerse
*/
ODE_API int dGeomIsBelowImmersionPlane(dGeomID geom, dReal x, dReal y, dReal z);
/**
* @brief Determines whether the given point is inside the geom
*
* @param geom the geom to query.
* @param x the X coordinate of the point.
* @param y the Y coordinate of the point.
* @param z the Z coordinate of the point.
*
* @sa dGeomIsInside
* @ingroup immerse_geom
*/
ODE_API int dGeomIsInside (dGeomID geom, dReal x, dReal y, dReal z);
/**
* @brief Get the geom flags
* @param geom the geom to query.
* @ingroup immerse
*/
ODE_API int dGeomGetFlags (dGeomID geom);
/* ************************************************************************ */
/* immersion detection */
/**
*
* @brief Given two geoms o1 and o2 that potentially intersect,
* generate contact information for them.
*
* Internally, this just calls the correct class-specific collision
* functions for o1 and o2.
*
* @param o1 The first geom to test.
* @param o2 The second geom to test.
*
* @param flags The flags specify how immmersion should be generated
* In the future it may be used to select from different
* immersion generation strategies.
*
* @param contact Points to an dImmersionGeom structure.
*
* @returns If the geoms intersect, this function returns 1, else 0.
*
* @remarks This function does not care if o1 and o2 are in the same space or not
* (or indeed if they are in any space at all).
*
* @ingroup immerse
*/
ODE_API int dImmerse (dGeomID o1, dGeomID o2, int flags, dImmersionGeom *immersion);
/**
* @brief Retrieves the volume of a sphere geom.
*
* @param box the box to query.
*
* @sa dGeomBoxGetVolume
* @ingroup immerse_box
*/
ODE_API dReal dGeomBoxGetVolume (dGeomID box);
/**
* @brief Retrieves the area of a box geom.
*
* @param box the box to query.
*
* @sa dGeomBoxGetArea
* @ingroup immerse_box
*/
ODE_API dReal dGeomBoxGetArea (dGeomID box);
/**
* @brief Retrieves the tangent plane to a box geom at a given point.
*
* @param box the box to query.
* @param x the X coordinate of the point.
* @param y the Y coordinate of the point.
* @param z the Z coordinate of the point.
* @param plane the tangent plane.
*
* @sa dGeomBoxGetTangentPlane
* @ingroup immerse_box
*/
ODE_API void dGeomBoxGetTangentPlane (dGeomID box, dReal x, dReal y, dReal z, dVector4 plane);
/**
* @brief Retrieves plane equation of a given box face.
*
* @param box the box to query.
* @param faceIndex the face index (in the range {-1, -2, -3, 1, 2, 3}).
* @param plane the face plane.
*
* @sa dGeomBoxGetFacePlane
* @ingroup immerse_box
*/
ODE_API void dGeomBoxGetFacePlane (dGeomID box, int faceIndex, dVector4 plane);
/**
* @brief Retrieves the immersion plane used for a fluid bounded by a box.
*
* @param box the box to query.
* @param plane the immersion plane.
*
* @sa dGeomCylinderGetImmersionPlane
* @ingroup immerse_box
*/
ODE_API void dGeomBoxGetImmersionPlane (dGeomID box, dVector4 plane);
/**
* @brief Retrieves the volume of a cylinder geom.
*
* @param cylinder the cylinder to query.
*
* @sa dGeomCylinderGetVolume
* @ingroup immerse_capsule
*/
ODE_API dReal dGeomCapsuleGetVolume (dGeomID capsule);
/**
* @brief Retrieves the area of a capsule geom.
*
* @param capsule the capsule to query.
*
* @sa dGeomCapsuleGetArea
* @ingroup immerse_capsule
*/
ODE_API dReal dGeomCapsuleGetArea (dGeomID capsule);
/**
* @brief Retrieves the tangent plane to a capsule geom at a given point.
*
* @param capsule the capsule to query.
* @param x the X coordinate of the point.
* @param y the Y coordinate of the point.
* @param z the Z coordinate of the point.
* @param plane the tangent plane.
*
* @sa dGeomCapsuleGetTangentPlane
* @ingroup immerse_capsule
*/
ODE_API void dGeomCapsuleGetTangentPlane (dGeomID capsule, dReal x, dReal y, dReal z, dVector4 plane);
/**
* @brief Retrieves the immersion plane used for a fluid bounded by a capsule.
*
* @param capsule the capsule to query.
* @param plane the immersion plane.
*
* @sa dGeomCapsuleGetImmersionPlane
* @ingroup immerse_capsule
*/
ODE_API void dGeomCapsuleGetImmersionPlane (dGeomID capsule, dVector4 plane);
/**
* @brief Retrieves the volume of a cylinder geom.
*
* @param cylinder the cylinder to query.
*
* @sa dGeomCylinderGetVolume
* @ingroup immerse_cylinder
*/
ODE_API dReal dGeomCylinderGetVolume (dGeomID cylinder);
/**
* @brief Retrieves the area of a cylinder geom.
*
* @param cylinder the cylinder to query.
*
* @sa dGeomCylinderGetArea
* @ingroup immerse_cylinder
*/
ODE_API dReal dGeomCylinderGetArea (dGeomID cylinder);
/**
* @brief Retrieves the tangent plane to a cylinder geom at a given point.
*
* @param cylinder the cylinder to query.
* @param x the X coordinate of the point.
* @param y the Y coordinate of the point.
* @param z the Z coordinate of the point.
* @param plane the tangent plane.
*
* @sa dGeomCylinderGetTangentPlane
* @ingroup immerse_cylinder
*/
ODE_API void dGeomCylinderGetTangentPlane (dGeomID cylinder, dReal x, dReal y, dReal z, dVector4 plane);
/**
* @brief Retrieves plane equation of a given cylinder disk.
*
* @param cylinder the cylinder to query.
* @param faceIndex the disk index (in the range {-1, 1}).
* @param plane the disk plane (not normalized).
*
* @sa dGeomCylinderGetFacePlane
* @ingroup immerse_cylinder
*/
ODE_API void dGeomCylinderGetDiskPlane (dGeomID cylinder, int diskIndex, dVector4 plane);
/**
* @brief Retrieves the immersion plane used for a fluid bounded by a cylinder.
*
* @param cylinder the cylinder to query.
* @param plane the immersion plane.
*
* @sa dGeomCylinderGetImmersionPlane
* @ingroup immerse_cylinder
*/
ODE_API void dGeomCylinderGetImmersionPlane (dGeomID cylinder, dVector4 plane);
/**
* @brief Retrieves the depth of the given point in the cylinder (negative if the point is outside, else min(distance to the caps, distance to the body) >= 0)
*
* @param cylinder the cylinder to query.
* @param x the X coordinate of the point.
* @param y the Y coordinate of the point.
* @param z the Z coordinate of the point.
*
* @sa dGeomCylinderIsInside
* @ingroup immerse_cylinder
*/
ODE_API dReal dGeomCylinderPointDepth (dGeomID cylinder, dReal x, dReal y, dReal z);
/**
* @brief Retrieves the volume of a sphere geom.
*
* @param sphere the sphere to query.
*
* @sa dGeomSphereGetVolume
* @ingroup immerse_sphere
*/
ODE_API dReal dGeomSphereGetVolume (dGeomID sphere);
/**
* @brief Retrieves the area of a sphere geom.
*
* @param sphere the sphere to query.
*
* @sa dGeomSphereGetArea
* @ingroup immerse_sphere
*/
ODE_API dReal dGeomSphereGetArea (dGeomID sphere);
/**
* @brief Retrieves the tangent plane to a sphere geom at a given point.
*
* @param sphere the sphere to query.
* @param x the X coordinate of the point.
* @param y the Y coordinate of the point.
* @param z the Z coordinate of the point.
* @param plane the tangent plane.
*
* @sa dGeomSphereGetTangentPlane
* @ingroup immerse_sphere
*/
ODE_API void dGeomSphereGetTangentPlane (dGeomID sphere, dReal x, dReal y, dReal z, dVector4 plane);
/**
* @brief Retrieves the immersion plane used for a fluid bounded by a sphere.
*
* @param cylinder the sphere to query.
* @param plane the immersion plane.
*
* @sa dGeomSphereGetImmersionPlane
* @ingroup immerse_sphere
*/
ODE_API void dGeomSphereGetImmersionPlane (dGeomID sphere, dVector4 plane);
/**
* @brief Retrieves the volume of a trimesh geom.
*
* @param trimesh the trimesh to query.
*
* @sa dGeomTriMeshGetVolume
* @ingroup immerse_trimesh
*/
ODE_API dReal dGeomTriMeshGetVolume (dGeomID trimesh);
/**
* @brief Retrieves the area of a trimesh geom.
*
* @param trimesh the trimesh to query.
*
* @sa dGeomTriMeshGetArea
* @ingroup immerse_trimesh
*/
ODE_API dReal dGeomTriMeshGetArea (dGeomID trimesh);
/**
* @brief Retrieves the center of mass of a trimesh geom.
*
* @param trimesh the trimesh to query.
* @param c the trimesh's center of mass.
*
* @sa dGeomTriMeshGetCenterOfMass
* @ingroup immerse_trimesh
*/
ODE_API void dGeomTriMeshGetCenterOfMass (dGeomID trimesh, dVector3 c);
/**
* @brief Retrieves the center of mass of a trimesh geom expressed in relative coordinates.
*
* @param trimesh the trimesh to query.
*
* @sa dGeomTriMeshGetRelCenterOfMass
* @ingroup immerse_trimesh
*/
ODE_API const dReal *dGeomTriMeshGetRelCenterOfMass (dGeomID trimesh);
/**
* @brief Retrieves the inertia matrix of a trimesh geom with density 1.
*
* @param trimesh the trimesh to query.
*
* @sa dGeomTriMeshGetInertiaMatrix
* @ingroup immerse_trimesh
*/
ODE_API const dReal *dGeomTriMeshGetInertiaMatrix (dGeomID trimesh);
/**
* @brief Retrieves the immersion plane used for a fluid bounded by a trimesh.
*
* @param cylinder the trimesh to query.
* @param plane the immersion plane.
*
* @sa dGeomTriMeshGetImmersionPlane
* @ingroup immerse_trimesh
*/
ODE_API void dGeomTriMeshGetImmersionPlane (dGeomID trimesh, dVector4 plane);
/**
* @brief Retrieves plane equation of a given trimesh's bounding plane.
*
* @param trimesh the trimesh to query.
* @param planeIndex the bounding plane index (in the range {-1, -2, -3, 1, 2, 3}).
* @param plane the bounding plane.
*
* @sa dGeomTriMeshGetFacePlane
* @ingroup immerse_trimesh
*/
ODE_API void dGeomTriMeshGetBoundingPlane (dGeomID trimesh, int planeIndex, dVector4 plane);
/**
* @brief Calculate the depth of the a given point within a trimesh.
*
* @param trimesh the trimesh to query.
* @param x the X coordinate of the point.
* @param y the Y coordinate of the point.
* @param z the Z coordinate of the point.
*
* @returns The depth of the point. Points inside the trimesh will have a
* positive depth, points outside it will have a negative depth, and points
* on the surface will have a depth of zero.
*
* @ingroup collide_trimesh
*/
ODE_API dReal dGeomTriMeshPointDepth (dGeomID trimesh, dReal x, dReal y, dReal z);
typedef int dImmerserFn (dGeomID o1, dGeomID o2,
int flags, dImmersionGeom *immersion);
typedef dImmerserFn * dGetImmerserFnFn (int num);
#ifdef __cplusplus
}
#endif
#endif
| 5,137 |
553 | <filename>Example/MUKit/ImageCache/Cells/FlyImageTableViewCell.h
//
// FlyImageTableViewCell.h
// Demo
//
// Created by <NAME> on 4/14/16.
// Copyright © 2016 NorrisTong. All rights reserved.
//
#import "BaseTableViewCell.h"
@interface FlyImageTableViewCell : BaseTableViewCell
@end
| 102 |
377 | /**
* Copyright 2012 Impetus Infotech.
*
* 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.impetus.kundera.persistence.context;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.graph.Node;
import com.impetus.kundera.graph.NodeLink;
import com.impetus.kundera.graph.ObjectGraph;
import com.impetus.kundera.graph.ObjectGraphUtils;
import com.impetus.kundera.lifecycle.states.ManagedState;
import com.impetus.kundera.metadata.model.EntityMetadata;
import com.impetus.kundera.persistence.PersistenceDelegator;
import com.impetus.kundera.property.PropertyAccessorHelper;
import com.impetus.kundera.utils.ObjectUtils;
/**
* Base class for all cache required in persistence context
*
* @author amresh.singh
*/
public class CacheBase
{
private static Logger log = LoggerFactory.getLogger(CacheBase.class);
private Map<String, Node> nodeMappings;
private Set<Node> headNodes;
private com.impetus.kundera.cache.Cache l2Cache;
private PersistenceCache persistenceCache;
public CacheBase(com.impetus.kundera.cache.Cache l2Cache, PersistenceCache pc)
{
this.headNodes = new HashSet<Node>();
this.nodeMappings = new ConcurrentHashMap<String, Node>();
this.l2Cache = l2Cache;
this.persistenceCache = pc;
}
public Node getNodeFromCache(String nodeId, PersistenceDelegator pd)
{
Node node = nodeMappings.get(nodeId);
// if not present in first level cache, check from second level cache.
return node != null ? node : lookupL2Cache(nodeId, pd);
}
public Node getNodeFromCache(Object entity, EntityMetadata entityMetadata, PersistenceDelegator pd)
{
if (entity == null)
{
throw new IllegalArgumentException("Entity is null, can't check whether it's in persistence context");
}
Object primaryKey = PropertyAccessorHelper.getId(entity, entityMetadata);
if (primaryKey == null)
{
throw new IllegalArgumentException("Primary key not set into entity");
}
String nodeId = ObjectGraphUtils.getNodeId(primaryKey, entity.getClass());
return getNodeFromCache(nodeId, pd);
}
public synchronized void addNodeToCache(Node node)
{
// Make a deep copy of Node data and and set into node
// Original data object is now detached from Node and is possibly
// referred by user code
Object nodeDataCopy = ObjectUtils.deepCopy(node.getData(), node.getPersistenceDelegator().getKunderaMetadata());
node.setData(nodeDataCopy);
/*
* check if this node already exists in cache node mappings If yes,
* update parents and children links Otherwise, just simply add the node
* to cache node mappings
*/
processNodeMapping(node);
if (l2Cache != null)
{
l2Cache.put(node.getNodeId(), node.getData());
}
}
public void processNodeMapping(Node node)
{
if (nodeMappings.containsKey(node.getNodeId()))
{
Node existingNode = nodeMappings.get(node.getNodeId());
if (existingNode.getParents() != null)
{
if (node.getParents() == null)
{
node.setParents(new HashMap<NodeLink, Node>());
}
node.getParents().putAll(existingNode.getParents());
}
if (existingNode.getChildren() != null)
{
if (node.getChildren() == null)
{
node.setChildren(new HashMap<NodeLink, Node>());
}
node.getChildren().putAll(existingNode.getChildren());
}
nodeMappings.put(node.getNodeId(), node);
logCacheEvent("ADDED TO ", node.getNodeId());
}
else
{
logCacheEvent("ADDED TO ", node.getNodeId());
nodeMappings.put(node.getNodeId(), node);
}
// If it's a head node, add this to the list of head nodes in
// Persistence Cache
if (node.isHeadNode())
{
node.getPersistenceCache().getMainCache().addHeadNode(node);
}
}
public synchronized void removeNodeFromCache(Node node)
{
if (getHeadNodes().contains(node))
{
getHeadNodes().remove(node);
}
if (nodeMappings.get(node.getNodeId()) != null)
{
nodeMappings.remove(node.getNodeId());
}
evictFroml2Cache(node);
logCacheEvent("REMOVED FROM ", node.getNodeId());
node = null; // Eligible for GC
}
public void addGraphToCache(ObjectGraph graph, PersistenceCache persistenceCache)
{
// Add each node in the graph to cache
for (String key : graph.getNodeMapping().keySet())
{
Node thisNode = graph.getNodeMapping().get(key);
addNodeToCache(thisNode);
// Remove all those head nodes in persistence cache, that are there
// in Graph as a non-head node
if (!thisNode.isHeadNode() && persistenceCache.getMainCache().getHeadNodes().contains(thisNode))
{
persistenceCache.getMainCache().getHeadNodes().remove(thisNode);
}
}
// Add head Node to list of head nodes
addHeadNode(graph.getHeadNode());
}
private void logCacheEvent(String eventType, String nodeId)
{
if (log.isDebugEnabled())
{
log.debug("Node: " + nodeId + ":: " + eventType + " Persistence Context");
}
}
/**
* @param nodeMappings
* the nodeMappings to set
*/
public void setNodeMappings(Map<String, Node> nodeMappings)
{
this.nodeMappings = nodeMappings;
}
public synchronized void addHeadNode(Node headNode)
{
headNodes.add(headNode);
}
public int size()
{
return nodeMappings.size();
}
public Collection<Node> getAllNodes()
{
return nodeMappings.values();
}
/**
*
*/
public void clear()
{
if (this.nodeMappings != null)
{
this.nodeMappings.clear();
}
if (this.headNodes != null)
{
this.headNodes.clear();
}
if (this.l2Cache != null)
{
l2Cache.evictAll();
}
}
/**
* @return the headNodes
*/
public Set<Node> getHeadNodes()
{
return Collections.synchronizedSet(headNodes);
}
private Node lookupL2Cache(String nodeId, PersistenceDelegator pd)
{
Node node = null;
if (l2Cache != null)
{
Object entity = l2Cache.get(nodeId);
if (entity != null)
{
node = new Node(nodeId, entity.getClass(), new ManagedState(), this.persistenceCache,
nodeId.substring(nodeId.indexOf("$") + 1), pd);
node.setData(entity);
}
}
return node;
}
private void evictFroml2Cache(Node node)
{
if (l2Cache != null)
{
this.l2Cache.evict(node.getDataClass(), node.getNodeId());
}
}
}
| 3,442 |
1,734 | <reponame>Knase23/Starcraft2AiTesting
#include "sc2api/sc2_score.h"
#include <iostream>
#include <cassert>
#include "s2clientprotocol/sc2api.pb.h"
namespace sc2 {
CategoryScoreDetails::CategoryScoreDetails() :
none(0.0f),
army(0.0f),
economy(0.0f),
technology(0.0f),
upgrade(0.0f) {
}
VitalScoreDetails::VitalScoreDetails() :
life(0.0f),
shields(0.0f),
energy(0.0f) {
}
ScoreDetails::ScoreDetails() :
idle_production_time(0.0f),
idle_worker_time(0.0f),
total_value_units(0.0f),
total_value_structures(0.0f),
killed_value_units(0.0f),
killed_value_structures(0.0f),
collected_minerals(0.0f),
collected_vespene(0.0f),
collection_rate_minerals(0.0f),
collection_rate_vespene(0.0f),
spent_minerals(0.0f),
spent_vespene(0.0f) {
}
Score::Score() :
score_type(ScoreType::Melee),
score(0) {
}
bool Score::IsEqual(const Score& other_score) const {
if (score != other_score.score) {
return false;
}
for (int i = 0; i < float_count_; ++i) {
if (RawFloats()[i] != other_score.RawFloats()[i]) {
return false;
}
}
return true;
}
}
| 570 |
918 | /*
* 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.gobblin.cluster;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.google.common.util.concurrent.AbstractScheduledService;
import com.google.common.util.concurrent.AtomicDouble;
import com.sun.management.OperatingSystemMXBean;
import com.typesafe.config.Config;
import lombok.Data;
import lombok.Getter;
import org.apache.gobblin.metrics.ContextAwareGauge;
import org.apache.gobblin.metrics.RootMetricContext;
import org.apache.gobblin.util.ConfigUtils;
/**
* A utility class that periodically emits system level metrics that report the health of the container.
* Reported metrics include CPU/Memory usage of the JVM, system load etc.
*
* <p>
* This class extends the {@link AbstractScheduledService} so it can be used with a
* {@link com.google.common.util.concurrent.ServiceManager} that manages the lifecycle of
* a {@link ContainerHealthMetricsService}.
* </p>
*/
public class ContainerHealthMetricsService extends AbstractScheduledService {
//Container metrics service configurations
private static final String CONTAINER_METRICS_SERVICE_REPORTING_INTERVAL_SECONDS = "container.health.metrics.service.reportingIntervalSeconds";
private static final Long DEFAULT_CONTAINER_METRICS_REPORTING_INTERVAL = 30L;
private static final Set<String> YOUNG_GC_TYPES = new HashSet<>(3);
private static final Set<String> OLD_GC_TYPES = new HashSet<String>(3);
static {
// young generation GC names
YOUNG_GC_TYPES.add("PS Scavenge");
YOUNG_GC_TYPES.add("ParNew");
YOUNG_GC_TYPES.add("G1 Young Generation");
// old generation GC names
OLD_GC_TYPES.add("PS MarkSweep");
OLD_GC_TYPES.add("ConcurrentMarkSweep");
OLD_GC_TYPES.add("G1 Old Generation");
}
private final long metricReportingInterval;
private final OperatingSystemMXBean operatingSystemMXBean;
private final MemoryMXBean memoryMXBean;
private final List<GarbageCollectorMXBean> garbageCollectorMXBeans;
@Getter
private GcStats lastGcStats;
@Getter
private GcStats currentGcStats;
//Heap stats
AtomicDouble processCpuLoad = new AtomicDouble(0);
AtomicDouble systemCpuLoad = new AtomicDouble(0);
AtomicDouble systemLoadAvg = new AtomicDouble(0);
AtomicDouble committedVmemSize = new AtomicDouble(0);
AtomicDouble processCpuTime = new AtomicDouble(0);
AtomicDouble freeSwapSpaceSize = new AtomicDouble(0);
AtomicDouble numAvailableProcessors = new AtomicDouble(0);
AtomicDouble totalPhysicalMemSize = new AtomicDouble(0);
AtomicDouble totalSwapSpaceSize = new AtomicDouble(0);
AtomicDouble freePhysicalMemSize = new AtomicDouble(0);
AtomicDouble processHeapUsedSize = new AtomicDouble(0);
//GC stats and counters
AtomicDouble minorGcCount = new AtomicDouble(0);
AtomicDouble majorGcCount = new AtomicDouble(0);
AtomicDouble unknownGcCount = new AtomicDouble(0);
AtomicDouble minorGcDuration = new AtomicDouble(0);
AtomicDouble majorGcDuration = new AtomicDouble(0);
AtomicDouble unknownGcDuration = new AtomicDouble(0);
public ContainerHealthMetricsService(Config config) {
this.metricReportingInterval = ConfigUtils.getLong(config, CONTAINER_METRICS_SERVICE_REPORTING_INTERVAL_SECONDS, DEFAULT_CONTAINER_METRICS_REPORTING_INTERVAL);
this.operatingSystemMXBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
this.memoryMXBean = ManagementFactory.getMemoryMXBean();
this.garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
this.lastGcStats = new GcStats();
this.currentGcStats = new GcStats();
//Build all the gauges and register them with the metrics registry.
List<ContextAwareGauge<Double>> systemMetrics = buildGaugeList();
systemMetrics.forEach(metric -> RootMetricContext.get().register(metric));
}
@Data
public static class GcStats {
long minorCount;
double minorDuration;
long majorCount;
double majorDuration;
long unknownCount;
double unknownDuration;
}
/**
* Run one iteration of the scheduled task. If any invocation of this method throws an exception,
* the service will transition to the {@link com.google.common.util.concurrent.Service.State#FAILED} state and this method will no
* longer be called.
*/
@Override
protected void runOneIteration() throws Exception {
this.processCpuLoad.set(this.operatingSystemMXBean.getProcessCpuLoad());
this.systemCpuLoad.set(this.operatingSystemMXBean.getSystemCpuLoad());
this.systemLoadAvg.set(this.operatingSystemMXBean.getSystemLoadAverage());
this.committedVmemSize.set(this.operatingSystemMXBean.getCommittedVirtualMemorySize());
this.processCpuTime.set(this.operatingSystemMXBean.getProcessCpuTime());
this.freeSwapSpaceSize.set(this.operatingSystemMXBean.getFreeSwapSpaceSize());
this.numAvailableProcessors.set(this.operatingSystemMXBean.getAvailableProcessors());
this.totalPhysicalMemSize.set(this.operatingSystemMXBean.getTotalPhysicalMemorySize());
this.totalSwapSpaceSize.set(this.operatingSystemMXBean.getTotalSwapSpaceSize());
this.freePhysicalMemSize.set(this.operatingSystemMXBean.getFreePhysicalMemorySize());
this.processHeapUsedSize.set(this.memoryMXBean.getHeapMemoryUsage().getUsed());
//Get the new GC stats
this.currentGcStats = collectGcStats();
// Since GC Beans report accumulated counts/durations, we need to subtract the previous values to obtain the counts/durations
// since the last measurement time.
this.minorGcCount.set(this.currentGcStats.getMinorCount() - this.lastGcStats.getMinorCount());
this.minorGcDuration.set(this.currentGcStats.getMinorDuration() - this.lastGcStats.getMinorDuration());
this.majorGcCount.set(this.currentGcStats.getMajorCount() - this.lastGcStats.getMajorCount());
this.majorGcDuration.set(this.currentGcStats.getMajorDuration() - this.lastGcStats.getMajorDuration());
this.unknownGcCount.set(this.currentGcStats.getUnknownCount() - this.lastGcStats.getUnknownCount());
this.unknownGcDuration.set(this.currentGcStats.getUnknownDuration() - this.lastGcStats.getUnknownDuration());
//Update last collected stats
this.lastGcStats = this.currentGcStats;
}
protected List<ContextAwareGauge<Double>> buildGaugeList() {
List<ContextAwareGauge<Double>> gaugeList = new ArrayList<>();
gaugeList.add(createGauge(ContainerHealthMetrics.PROCESS_CPU_LOAD, this.processCpuLoad));
gaugeList.add(createGauge(ContainerHealthMetrics.SYSTEM_CPU_LOAD, this.systemCpuLoad));
gaugeList.add(createGauge(ContainerHealthMetrics.SYSTEM_LOAD_AVG, this.systemLoadAvg));
gaugeList.add(createGauge(ContainerHealthMetrics.COMMITTED_VMEM_SIZE, this.committedVmemSize));
gaugeList.add(createGauge(ContainerHealthMetrics.PROCESS_CPU_TIME, this.processCpuTime));
gaugeList.add(createGauge(ContainerHealthMetrics.FREE_SWAP_SPACE_SIZE, this.freeSwapSpaceSize));
gaugeList.add(createGauge(ContainerHealthMetrics.NUM_AVAILABLE_PROCESSORS, this.numAvailableProcessors));
gaugeList.add(createGauge(ContainerHealthMetrics.TOTAL_PHYSICAL_MEM_SIZE, this.totalPhysicalMemSize));
gaugeList.add(createGauge(ContainerHealthMetrics.TOTAL_SWAP_SPACE_SIZE, this.totalSwapSpaceSize));
gaugeList.add(createGauge(ContainerHealthMetrics.FREE_PHYSICAL_MEM_SIZE, this.freePhysicalMemSize));
gaugeList.add(createGauge(ContainerHealthMetrics.PROCESS_HEAP_USED_SIZE, this.processHeapUsedSize));
gaugeList.add(createGauge(ContainerHealthMetrics.MINOR_GC_COUNT, this.minorGcCount));
gaugeList.add(createGauge(ContainerHealthMetrics.MINOR_GC_DURATION, this.minorGcDuration));
gaugeList.add(createGauge(ContainerHealthMetrics.MAJOR_GC_COUNT, this.majorGcCount));
gaugeList.add(createGauge(ContainerHealthMetrics.MAJOR_GC_DURATION, this.majorGcDuration));
gaugeList.add(createGauge(ContainerHealthMetrics.UNKNOWN_GC_COUNT, this.unknownGcCount));
gaugeList.add(createGauge(ContainerHealthMetrics.UNKNOWN_GC_DURATION, this.unknownGcDuration));
return gaugeList;
}
private ContextAwareGauge<Double> createGauge(String name, AtomicDouble metric) {
return RootMetricContext.get().newContextAwareGauge(name, () -> metric.get());
}
private GcStats collectGcStats() {
//Collect GC stats by iterating over all GC beans.
GcStats gcStats = new GcStats();
for (GarbageCollectorMXBean garbageCollectorMXBean: this.garbageCollectorMXBeans) {
long count = garbageCollectorMXBean.getCollectionCount();
double duration = (double) garbageCollectorMXBean.getCollectionTime();
if (count >= 0) {
if (YOUNG_GC_TYPES.contains(garbageCollectorMXBean.getName())) {
gcStats.setMinorCount(gcStats.getMinorCount() + count);
gcStats.setMinorDuration(gcStats.getMinorDuration() + duration);
}
else if (OLD_GC_TYPES.contains(garbageCollectorMXBean.getName())) {
gcStats.setMajorCount(gcStats.getMajorCount() + count);
gcStats.setMajorDuration(gcStats.getMajorDuration() + duration);
} else {
gcStats.setUnknownCount(gcStats.getUnknownCount() + count);
gcStats.setUnknownDuration(gcStats.getUnknownDuration() + duration);
}
}
}
return gcStats;
}
/**
* Returns the {@link Scheduler} object used to configure this service. This method will only be
* called once.
*/
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedRateSchedule(0, this.metricReportingInterval, TimeUnit.SECONDS);
}
}
| 3,464 |
1,083 | <filename>src/dale/Form/Literal/Literal.h
#ifndef DALE_FORM_LITERAL
#define DALE_FORM_LITERAL
#include "../../Context/Context.h"
#include "../../Node/Node.h"
#include "../../Units/Units.h"
namespace dale {
/*! Convert an integer token into a parse result.
* @param ctx The context.
* @param wanted_type The type of the integer.
* @param block The current basic block.
* @param t The integer token.
* @param pr The parse result for the integer.
*/
void FormIntegerLiteralParse(Context *ctx, Type *wanted_type,
llvm::BasicBlock *block, Token *t,
ParseResult *pr);
/*! Convert a floating point token into a parse result.
* @param ctx The context.
* @param wanted_type The type of the floating point value.
* @param block The current basic block.
* @param t The floating point token.
* @param pr The parse result for the floating point value.
*/
void FormFloatingPointLiteralParse(Context *ctx, Type *wanted_type,
llvm::BasicBlock *block, Token *t,
ParseResult *pr);
/*! Convert a string literal token into a parse result.
* @param units The units context.
* @param ctx The context.
* @param block The current basic block.
* @param t The string literal node.
* @param pr The parse result for the string literal.
*/
void FormStringLiteralParse(Units *units, Context *ctx,
llvm::BasicBlock *block, Node *node,
ParseResult *pr);
/*! Convert a boolean string literal token into a parse result.
* @param ctx The context.
* @param block The current basic block.
* @param t The boolean literal node.
* @param pr The parse result for the boolean literal.
*/
void FormBoolLiteralParse(Context *ctx, llvm::BasicBlock *block,
Node *node, ParseResult *pr);
/*! Convert a char literal token into a parse result.
* @param ctx The context.
* @param block The current basic block.
* @param t The char literal node.
* @param pr The parse result for the char literal.
*/
void FormCharLiteralParse(Context *ctx, llvm::BasicBlock *block,
Node *node, ParseResult *pr);
/*! Convert any type of literal into a parse result.
* @param units The units context.
* @param type The type of the literal.
* @param t The literal node.
* @param pr The parse result for the literal.
*
* This can also be used to parse arrays and structs.
*/
bool FormLiteralParse(Units *units, Type *type, Node *node,
ParseResult *pr);
}
#endif
| 984 |
2,757 | <filename>2021/quals/rev-polymorph/targets/make_all_builds.py
#!/usr/bin/python3
# Copyright 2021 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.
# Author: <NAME>
import subprocess
import random
import os
import pathlib
import shutil
# -DCTR=1 -DBADSTUFF_3=1 -DBADDATA_1=1 -DRAND_3=1 -DDEFENSE_5=1
num_builds = 18
badstuff_rand = random.Random(123)
baddata_rand = random.Random(252)
rand_rand = random.Random(323)
defense_rand = random.Random(234)
crypto_rand = random.Random(55)
opt_rand = random.Random(621)
target_rand = random.Random(751)
xorstr_rand = random.Random(8)
sbox_rand = random.Random(9)
def gen_baddata(rand):
return f"-DBADDATA_{rand.randint(1, 3)}=1 "
def gen_badstuff(rand):
badstuff = rand.choice([1, 2, 3])
if badstuff == 1:
badvalue = 1
elif badstuff == 2:
badvalue = rand.randint(0, 2)
elif badstuff == 3:
badvalue = rand.randint(1, 2)
return f"-DBADSTUFF_{badstuff}={badvalue} "
def gen_rand(rand):
return f"-DRAND_{rand.randint(1, 3)}={rand.randint(1, 94508123)} "
def gen_crypto(rand):
choice = rand.choice(["CTR", "ECB", "CBC"])
return f"-D{choice}=1 "
def gen_opt(rand):
x = rand.choice(["-O0", "-O1", "-O2", "-O3", "-Ofast", "-Os"])
return x
def gen_target(rand):
#choices = []
choices = ["polymorph", "polymorph_static", "polymorph_static_packed", "polymorph_dynamic_packed"]
choices *= 3
choices += ["polymorph_python", "polymorph_zsh"]
choices += ["polymorph_static_python", "polymorph_static_zsh"]
choices += ["polymorph_dynamic_packed_python", "polymorph_dynamic_packed_zsh"]
return rand.choice(choices)
def gen_defense(rand):
ret = ""
while len(ret) == 0:
if rand.randint(0, 4) == 0:
ret += f"-DDEFENSE_1=1 "
if rand.randint(0, 4) == 0:
ret += f"-DDEFENSE_2=1 "
if rand.randint(0, 4) == 0:
ret += f"-DDEFENSE_3=1 "
if rand.randint(0, 4) == 0:
ret += f"-DDEFENSE_4=1 "
if rand.randint(0, 4) == 0:
ret += f"-DDEFENSE_5=1 "
return ret
def gen_xorstr(rand):
val = rand.randint(0, 2**32-1)
return f"-DCOMPILER_SEED={val} "
def gen_sbox(rand):
val = rand.randint(0, 2**64-1).to_bytes(8, "little")
val0 = val[0]
val1 = val[1]
val2 = val[2]
val3 = val[3]
val4 = val[4]
val5 = val[5]
val6 = val[6]
val7 = val[7]
val = int.from_bytes(val, "little")
return f"-DSBOX_XOR_FILTER={val}ULL -DSBOX_XOR_FILTER_0={val0} -DSBOX_XOR_FILTER_1={val1} -DSBOX_XOR_FILTER_2={val2} -DSBOX_XOR_FILTER_3={val3} -DSBOX_XOR_FILTER_4={val4} -DSBOX_XOR_FILTER_5={val5} -DSBOX_XOR_FILTER_6={val6} -DSBOX_XOR_FILTER_7={val7}"
def make(command, environ=os.environ):
subprocess.run(
["make"] + command,
env=environ, check=True)
def build():
make(["clean"])
badstuff = gen_badstuff(badstuff_rand)
baddata = gen_baddata(baddata_rand)
rand = gen_rand(rand_rand)
defense = gen_defense(defense_rand)
crypto = gen_crypto(crypto_rand)
opt = gen_opt(opt_rand)
target = gen_target(target_rand)
xorstr = gen_xorstr(xorstr_rand)
sbox = gen_sbox(sbox_rand)
cxx = f"g++ {badstuff}{baddata}{rand}{defense}{crypto}{xorstr}{sbox}"
print(cxx)
environ = {**os.environ, "CXX": cxx, "POLYMORPH_OPT": opt}
make([target], environ=environ)
return target
def mv(fro, to):
subprocess.run(
["mv", fro, to], check=True)
pathlib.Path("./build").mkdir(parents=True, exist_ok=True)
for i in range(num_builds):
polymorph = build()
mv(polymorph, f"build/polymorph{i}")
make(["clean"])
| 1,652 |
5,169 | {
"name": "iOS_SDK_Test",
"version": "1.0.0",
"summary": "iOS_SDK_Test for CocoaPod Testing",
"description": " A longer description of iOS_SDK_Test in Markdown format.\n\n * Think: Why did you write this? What is the focus? What does it do?\n * CocoaPods will be using this to generate tags, and improve search results.\n * Try to keep it short, snappy and to the point.\n * Finally, don't worry about the indent, CocoaPods strips it!\n",
"homepage": "https://github.com/OptimalTest/iOS_SDK_Test",
"license": {
"type": "MIT",
"file": "FILE_LICENSE"
},
"authors": {
"OptimalTest": "<EMAIL>"
},
"platforms": {
"ios": "8.1"
},
"source": {
"git": "https://github.com/OptimalTest/iOS_SDK_Test.git",
"commit": "<PASSWORD>",
"tag": "1.0.0"
},
"source_files": [
"OptimalApplePay/PaymentKit/*.{h,m}",
"OptimalApplePay/MockPassKItLib/*.{h,m}"
],
"exclude_files": "Classes/Exclude",
"resources": "OptimalApplePay/MockPassKItLib/OPAYMockPaymentSummaryViewController.xib",
"frameworks": [
"Foundation",
"UIKit",
"PassKit"
]
}
| 538 |
622 | <reponame>ahakingdom/Rusthon
from runtime import *
'''
__getattr__, @property, and class attributes
'''
class A:
X = 'A'
## not allowed - will raise SyntaxError at compile time ##
def __getattr__(self, name):
if name == 'hello':
return 100
elif name == 'world':
return 200
else:
return 300
class B(A):
Y = 'B'
@property
def y(self):
return self._y
class C( B ):
Z = 'C'
def __init__(self, x,y,z):
self.x = x
self._y = y
self._z = z
@property
def z(self):
return self._z
def main():
a = C(1,2,3)
## GOTCHA: this is not allowed in Rusthon,
## class variables can only be used on the classes,
## not on the instances.
#assert( a.X == 'A' )
#assert( a.Y == 'B' )
#assert( a.Z == 'C' )
assert( A.X == 'A' )
assert( B.Y == 'B' )
assert( C.Z == 'C' )
assert( a.x == 1 )
#assert( a.y == 2 ) ## TODO fix me
assert( a.z == 3 )
## GOTCHA: __getattr__ is not allowed in Rusthon
#b = a.hello
#assert( b == 100 )
#assert( a.world == 200 )
#assert( a.XXX == 300 )
main()
| 443 |
679 | <filename>main/comphelper/source/streaming/streamsection.cxx
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#include <comphelper/streamsection.hxx>
#include <osl/diagnose.h>
namespace comphelper
{
//-------------------------------------------------------------------------
OStreamSection::OStreamSection(const staruno::Reference< stario::XDataInputStream >& _rxInput)
:m_xMarkStream(_rxInput, ::com::sun::star::uno::UNO_QUERY)
,m_xInStream(_rxInput)
,m_nBlockStart(-1)
,m_nBlockLen(-1)
{
OSL_ENSURE(m_xInStream.is() && m_xMarkStream.is(), "OStreamSection::OStreamSection : invalid argument !");
if (m_xInStream.is() && m_xMarkStream.is())
{
m_nBlockLen = _rxInput->readLong();
m_nBlockStart = m_xMarkStream->createMark();
}
}
//-------------------------------------------------------------------------
OStreamSection::OStreamSection(const staruno::Reference< stario::XDataOutputStream >& _rxOutput, sal_Int32 _nPresumedLength)
:m_xMarkStream(_rxOutput, ::com::sun::star::uno::UNO_QUERY)
,m_xOutStream(_rxOutput)
,m_nBlockStart(-1)
,m_nBlockLen(-1)
{
OSL_ENSURE(m_xOutStream.is() && m_xMarkStream.is(), "OStreamSection::OStreamSection : invalid argument !");
if (m_xOutStream.is() && m_xMarkStream.is())
{
m_nBlockStart = m_xMarkStream->createMark();
// a placeholder where we will write the overall length (within the destructor)
if (_nPresumedLength > 0)
m_nBlockLen = _nPresumedLength + sizeof(m_nBlockLen);
// as the caller did not consider - of course - the placeholder we are going to write
else
m_nBlockLen = 0;
m_xOutStream->writeLong(m_nBlockLen);
}
}
//-------------------------------------------------------------------------
OStreamSection::~OStreamSection()
{
try
{ // don't allow any exceptions to leave this block, this may be called during the stack unwinding of an exception
// handling routing
if (m_xInStream.is() && m_xMarkStream.is())
{ // we're working on an input stream
m_xMarkStream->jumpToMark(m_nBlockStart);
m_xInStream->skipBytes(m_nBlockLen);
m_xMarkStream->deleteMark(m_nBlockStart);
}
else if (m_xOutStream.is() && m_xMarkStream.is())
{
sal_Int32 nRealBlockLength = m_xMarkStream->offsetToMark(m_nBlockStart) - sizeof(m_nBlockLen);
if (m_nBlockLen && (m_nBlockLen == nRealBlockLength))
// nothing to do : the estimation the caller gave us (in the ctor) was correct
m_xMarkStream->deleteMark(m_nBlockStart);
else
{ // the estimation was wrong (or we didn't get one)
m_nBlockLen = nRealBlockLength;
m_xMarkStream->jumpToMark(m_nBlockStart);
m_xOutStream->writeLong(m_nBlockLen);
m_xMarkStream->jumpToFurthest();
m_xMarkStream->deleteMark(m_nBlockStart);
}
}
}
catch(const staruno::Exception&)
{
}
}
// -----------------------------------------------------------------------------
sal_Int32 OStreamSection::available()
{
sal_Int32 nBytes = 0;
try
{ // don't allow any exceptions to leave this block, this may be called during the stack unwinding of an exception
if (m_xInStream.is() && m_xMarkStream.is())
nBytes = m_xMarkStream->offsetToMark(m_nBlockStart) - sizeof(m_nBlockLen);
}
catch(const staruno::Exception&)
{
}
return nBytes;
}
// -----------------------------------------------------------------------------
} // namespace comphelper
| 1,393 |
1,306 | /*
* Copyright (C) 2012 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.
*/
#ifndef ART_COMPILER_LLVM_IR_BUILDER_H_
#define ART_COMPILER_LLVM_IR_BUILDER_H_
#include "backend_types.h"
#include "dex/compiler_enums.h"
#include "intrinsic_helper.h"
#include "md_builder.h"
#include "runtime_support_builder.h"
#include "runtime_support_llvm_func.h"
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Type.h>
#include <llvm/Support/NoFolder.h>
#include <stdint.h>
namespace art {
namespace llvm {
class InserterWithDexOffset : public ::llvm::IRBuilderDefaultInserter<true> {
public:
InserterWithDexOffset() : node_(NULL) {}
void InsertHelper(::llvm::Instruction *I, const ::llvm::Twine &Name,
::llvm::BasicBlock *BB,
::llvm::BasicBlock::iterator InsertPt) const {
::llvm::IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
if (node_ != NULL) {
I->setMetadata("DexOff", node_);
}
}
void SetDexOffset(::llvm::MDNode* node) {
node_ = node;
}
private:
::llvm::MDNode* node_;
};
typedef ::llvm::IRBuilder<true, ::llvm::ConstantFolder, InserterWithDexOffset> LLVMIRBuilder;
// NOTE: Here we define our own LLVMIRBuilder type alias, so that we can
// switch "preserveNames" template parameter easily.
class IRBuilder : public LLVMIRBuilder {
public:
//--------------------------------------------------------------------------
// General
//--------------------------------------------------------------------------
IRBuilder(::llvm::LLVMContext& context, ::llvm::Module& module,
IntrinsicHelper& intrinsic_helper);
//--------------------------------------------------------------------------
// Extend load & store for TBAA
//--------------------------------------------------------------------------
::llvm::LoadInst* CreateLoad(::llvm::Value* ptr, ::llvm::MDNode* tbaa_info) {
::llvm::LoadInst* inst = LLVMIRBuilder::CreateLoad(ptr);
inst->setMetadata(::llvm::LLVMContext::MD_tbaa, tbaa_info);
return inst;
}
::llvm::StoreInst* CreateStore(::llvm::Value* val, ::llvm::Value* ptr, ::llvm::MDNode* tbaa_info) {
::llvm::StoreInst* inst = LLVMIRBuilder::CreateStore(val, ptr);
inst->setMetadata(::llvm::LLVMContext::MD_tbaa, tbaa_info);
return inst;
}
::llvm::AtomicCmpXchgInst*
CreateAtomicCmpXchgInst(::llvm::Value* ptr, ::llvm::Value* cmp, ::llvm::Value* val,
::llvm::MDNode* tbaa_info) {
::llvm::AtomicCmpXchgInst* inst =
LLVMIRBuilder::CreateAtomicCmpXchg(ptr, cmp, val, ::llvm::Acquire);
inst->setMetadata(::llvm::LLVMContext::MD_tbaa, tbaa_info);
return inst;
}
//--------------------------------------------------------------------------
// Extend memory barrier
//--------------------------------------------------------------------------
void CreateMemoryBarrier(MemBarrierKind barrier_kind) {
#if ANDROID_SMP
// TODO: select atomic ordering according to given barrier kind.
CreateFence(::llvm::SequentiallyConsistent);
#endif
}
//--------------------------------------------------------------------------
// TBAA
//--------------------------------------------------------------------------
// TODO: After we design the non-special TBAA info, re-design the TBAA interface.
::llvm::LoadInst* CreateLoad(::llvm::Value* ptr, TBAASpecialType special_ty) {
return CreateLoad(ptr, mdb_.GetTBAASpecialType(special_ty));
}
::llvm::StoreInst* CreateStore(::llvm::Value* val, ::llvm::Value* ptr, TBAASpecialType special_ty) {
DCHECK_NE(special_ty, kTBAAConstJObject) << "ConstJObject is read only!";
return CreateStore(val, ptr, mdb_.GetTBAASpecialType(special_ty));
}
::llvm::LoadInst* CreateLoad(::llvm::Value* ptr, TBAASpecialType special_ty, JType j_ty) {
return CreateLoad(ptr, mdb_.GetTBAAMemoryJType(special_ty, j_ty));
}
::llvm::StoreInst* CreateStore(::llvm::Value* val, ::llvm::Value* ptr,
TBAASpecialType special_ty, JType j_ty) {
DCHECK_NE(special_ty, kTBAAConstJObject) << "ConstJObject is read only!";
return CreateStore(val, ptr, mdb_.GetTBAAMemoryJType(special_ty, j_ty));
}
::llvm::LoadInst* LoadFromObjectOffset(::llvm::Value* object_addr,
int64_t offset,
::llvm::Type* type,
TBAASpecialType special_ty) {
return LoadFromObjectOffset(object_addr, offset, type, mdb_.GetTBAASpecialType(special_ty));
}
void StoreToObjectOffset(::llvm::Value* object_addr,
int64_t offset,
::llvm::Value* new_value,
TBAASpecialType special_ty) {
DCHECK_NE(special_ty, kTBAAConstJObject) << "ConstJObject is read only!";
StoreToObjectOffset(object_addr, offset, new_value, mdb_.GetTBAASpecialType(special_ty));
}
::llvm::LoadInst* LoadFromObjectOffset(::llvm::Value* object_addr,
int64_t offset,
::llvm::Type* type,
TBAASpecialType special_ty, JType j_ty) {
return LoadFromObjectOffset(object_addr, offset, type, mdb_.GetTBAAMemoryJType(special_ty, j_ty));
}
void StoreToObjectOffset(::llvm::Value* object_addr,
int64_t offset,
::llvm::Value* new_value,
TBAASpecialType special_ty, JType j_ty) {
DCHECK_NE(special_ty, kTBAAConstJObject) << "ConstJObject is read only!";
StoreToObjectOffset(object_addr, offset, new_value, mdb_.GetTBAAMemoryJType(special_ty, j_ty));
}
::llvm::AtomicCmpXchgInst*
CompareExchangeObjectOffset(::llvm::Value* object_addr,
int64_t offset,
::llvm::Value* cmp_value,
::llvm::Value* new_value,
TBAASpecialType special_ty) {
DCHECK_NE(special_ty, kTBAAConstJObject) << "ConstJObject is read only!";
return CompareExchangeObjectOffset(object_addr, offset, cmp_value, new_value,
mdb_.GetTBAASpecialType(special_ty));
}
void SetTBAA(::llvm::Instruction* inst, TBAASpecialType special_ty) {
inst->setMetadata(::llvm::LLVMContext::MD_tbaa, mdb_.GetTBAASpecialType(special_ty));
}
//--------------------------------------------------------------------------
// Static Branch Prediction
//--------------------------------------------------------------------------
// Import the orignal conditional branch
using LLVMIRBuilder::CreateCondBr;
::llvm::BranchInst* CreateCondBr(::llvm::Value *cond,
::llvm::BasicBlock* true_bb,
::llvm::BasicBlock* false_bb,
ExpectCond expect) {
::llvm::BranchInst* branch_inst = CreateCondBr(cond, true_bb, false_bb);
if (false) {
// TODO: http://b/8511695 Restore branch weight metadata
branch_inst->setMetadata(::llvm::LLVMContext::MD_prof, mdb_.GetBranchWeights(expect));
}
return branch_inst;
}
//--------------------------------------------------------------------------
// Pointer Arithmetic Helper Function
//--------------------------------------------------------------------------
::llvm::IntegerType* getPtrEquivIntTy() {
return getInt32Ty();
}
size_t getSizeOfPtrEquivInt() {
return 4;
}
::llvm::ConstantInt* getSizeOfPtrEquivIntValue() {
return getPtrEquivInt(getSizeOfPtrEquivInt());
}
::llvm::ConstantInt* getPtrEquivInt(int64_t i) {
return ::llvm::ConstantInt::get(getPtrEquivIntTy(), i);
}
::llvm::Value* CreatePtrDisp(::llvm::Value* base,
::llvm::Value* offset,
::llvm::PointerType* ret_ty) {
::llvm::Value* base_int = CreatePtrToInt(base, getPtrEquivIntTy());
::llvm::Value* result_int = CreateAdd(base_int, offset);
::llvm::Value* result = CreateIntToPtr(result_int, ret_ty);
return result;
}
::llvm::Value* CreatePtrDisp(::llvm::Value* base,
::llvm::Value* bs,
::llvm::Value* count,
::llvm::Value* offset,
::llvm::PointerType* ret_ty) {
::llvm::Value* block_offset = CreateMul(bs, count);
::llvm::Value* total_offset = CreateAdd(block_offset, offset);
return CreatePtrDisp(base, total_offset, ret_ty);
}
::llvm::LoadInst* LoadFromObjectOffset(::llvm::Value* object_addr,
int64_t offset,
::llvm::Type* type,
::llvm::MDNode* tbaa_info) {
// Convert offset to ::llvm::value
::llvm::Value* llvm_offset = getPtrEquivInt(offset);
// Calculate the value's address
::llvm::Value* value_addr = CreatePtrDisp(object_addr, llvm_offset, type->getPointerTo());
// Load
return CreateLoad(value_addr, tbaa_info);
}
void StoreToObjectOffset(::llvm::Value* object_addr,
int64_t offset,
::llvm::Value* new_value,
::llvm::MDNode* tbaa_info) {
// Convert offset to ::llvm::value
::llvm::Value* llvm_offset = getPtrEquivInt(offset);
// Calculate the value's address
::llvm::Value* value_addr = CreatePtrDisp(object_addr,
llvm_offset,
new_value->getType()->getPointerTo());
// Store
CreateStore(new_value, value_addr, tbaa_info);
}
::llvm::AtomicCmpXchgInst* CompareExchangeObjectOffset(::llvm::Value* object_addr,
int64_t offset,
::llvm::Value* cmp_value,
::llvm::Value* new_value,
::llvm::MDNode* tbaa_info) {
// Convert offset to ::llvm::value
::llvm::Value* llvm_offset = getPtrEquivInt(offset);
// Calculate the value's address
::llvm::Value* value_addr = CreatePtrDisp(object_addr,
llvm_offset,
new_value->getType()->getPointerTo());
// Atomic compare and exchange
return CreateAtomicCmpXchgInst(value_addr, cmp_value, new_value, tbaa_info);
}
//--------------------------------------------------------------------------
// Runtime Helper Function
//--------------------------------------------------------------------------
RuntimeSupportBuilder& Runtime() {
return *runtime_support_;
}
// TODO: Deprecate
::llvm::Function* GetRuntime(runtime_support::RuntimeId rt) {
return runtime_support_->GetRuntimeSupportFunction(rt);
}
// TODO: Deprecate
void SetRuntimeSupport(RuntimeSupportBuilder* runtime_support) {
// Can only set once. We can't do this on constructor, because RuntimeSupportBuilder needs
// IRBuilder.
if (runtime_support_ == NULL && runtime_support != NULL) {
runtime_support_ = runtime_support;
}
}
//--------------------------------------------------------------------------
// Type Helper Function
//--------------------------------------------------------------------------
::llvm::Type* getJType(char shorty_jty) {
return getJType(GetJTypeFromShorty(shorty_jty));
}
::llvm::Type* getJType(JType jty);
::llvm::Type* getJVoidTy() {
return getVoidTy();
}
::llvm::IntegerType* getJBooleanTy() {
return getInt8Ty();
}
::llvm::IntegerType* getJByteTy() {
return getInt8Ty();
}
::llvm::IntegerType* getJCharTy() {
return getInt16Ty();
}
::llvm::IntegerType* getJShortTy() {
return getInt16Ty();
}
::llvm::IntegerType* getJIntTy() {
return getInt32Ty();
}
::llvm::IntegerType* getJLongTy() {
return getInt64Ty();
}
::llvm::Type* getJFloatTy() {
return getFloatTy();
}
::llvm::Type* getJDoubleTy() {
return getDoubleTy();
}
::llvm::PointerType* getJObjectTy() {
return java_object_type_;
}
::llvm::PointerType* getJMethodTy() {
return java_method_type_;
}
::llvm::PointerType* getJThreadTy() {
return java_thread_type_;
}
::llvm::Type* getArtFrameTy() {
return art_frame_type_;
}
::llvm::PointerType* getJEnvTy() {
return jenv_type_;
}
::llvm::Type* getJValueTy() {
// NOTE: JValue is an union type, which may contains boolean, byte, char,
// short, int, long, float, double, Object. However, LLVM itself does
// not support union type, so we have to return a type with biggest size,
// then bitcast it before we use it.
return getJLongTy();
}
::llvm::StructType* getShadowFrameTy(uint32_t vreg_size);
//--------------------------------------------------------------------------
// Constant Value Helper Function
//--------------------------------------------------------------------------
::llvm::ConstantInt* getJBoolean(bool is_true) {
return (is_true) ? getTrue() : getFalse();
}
::llvm::ConstantInt* getJByte(int8_t i) {
return ::llvm::ConstantInt::getSigned(getJByteTy(), i);
}
::llvm::ConstantInt* getJChar(int16_t i) {
return ::llvm::ConstantInt::getSigned(getJCharTy(), i);
}
::llvm::ConstantInt* getJShort(int16_t i) {
return ::llvm::ConstantInt::getSigned(getJShortTy(), i);
}
::llvm::ConstantInt* getJInt(int32_t i) {
return ::llvm::ConstantInt::getSigned(getJIntTy(), i);
}
::llvm::ConstantInt* getJLong(int64_t i) {
return ::llvm::ConstantInt::getSigned(getJLongTy(), i);
}
::llvm::Constant* getJFloat(float f) {
return ::llvm::ConstantFP::get(getJFloatTy(), f);
}
::llvm::Constant* getJDouble(double d) {
return ::llvm::ConstantFP::get(getJDoubleTy(), d);
}
::llvm::ConstantPointerNull* getJNull() {
return ::llvm::ConstantPointerNull::get(getJObjectTy());
}
::llvm::Constant* getJZero(char shorty_jty) {
return getJZero(GetJTypeFromShorty(shorty_jty));
}
::llvm::Constant* getJZero(JType jty) {
switch (jty) {
case kVoid:
LOG(FATAL) << "Zero is not a value of void type";
return NULL;
case kBoolean:
return getJBoolean(false);
case kByte:
return getJByte(0);
case kChar:
return getJChar(0);
case kShort:
return getJShort(0);
case kInt:
return getJInt(0);
case kLong:
return getJLong(0);
case kFloat:
return getJFloat(0.0f);
case kDouble:
return getJDouble(0.0);
case kObject:
return getJNull();
default:
LOG(FATAL) << "Unknown java type: " << jty;
return NULL;
}
}
private:
::llvm::Module* module_;
MDBuilder mdb_;
::llvm::PointerType* java_object_type_;
::llvm::PointerType* java_method_type_;
::llvm::PointerType* java_thread_type_;
::llvm::PointerType* jenv_type_;
::llvm::StructType* art_frame_type_;
RuntimeSupportBuilder* runtime_support_;
IntrinsicHelper& intrinsic_helper_;
};
} // namespace llvm
} // namespace art
#endif // ART_COMPILER_LLVM_IR_BUILDER_H_
| 6,675 |
803 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "CcLayerUnit.hxx"
// Shouldn't _countof() be included in cc.hxx
#include <stdlib.h>
CUnitTest( CcCountofReturnsCorrectSize, 0x0, "Tests the _countof() operator." );
ERR CcCountofReturnsCorrectSize::ErrTest()
{
ERR err = JET_errSuccess;
BYTE rgb[10];
ULONG rgul[7];
QWORD rgqw[3];
void * rgpv[8];
TestCheck( 10 == sizeof(rgb) );
TestCheck( 10 == _countof(rgb) );
TestCheck( 28 == sizeof(rgul) );
TestCheck( 7 == _countof(rgul) );
TestCheck( 24 == sizeof(rgqw) );
TestCheck( 3 == _countof(rgqw) );
#ifdef _WIN64
TestCheck( 64 == sizeof(rgpv) );
#else
TestCheck( 32 == sizeof(rgpv) );
#endif
TestCheck( 8 == _countof(rgpv) );
HandleError:
return err;
}
CUnitTest( CcOffsetOfReturnsCorrectOffsets, btcfForceStackTrash, "" );
ERR CcOffsetOfReturnsCorrectOffsets::ErrTest()
{
ERR err = JET_errSuccess;
typedef struct _AStructForImplicitInit {
ULONG ulOne;
QWORD qwTwo;
LONG lZero;
QWORD lZeroToo;
} AStructForImplicitInit;
TestCheck( 0 == OffsetOf( AStructForImplicitInit, ulOne ) );
TestCheck( 8 == OffsetOf( AStructForImplicitInit, qwTwo ) ); // note: skips one for alignment
TestCheck( 16 == OffsetOf( AStructForImplicitInit, lZero ) );
TestCheck( 24 == OffsetOf( AStructForImplicitInit, lZeroToo ) );
HandleError:
return err;
}
| 608 |
682 | /**CFile****************************************************************
FileName [sfmDec.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [SAT-based optimization using internal don't-cares.]
Synopsis [SAT-based decomposition.]
Author [<NAME>]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - June 20, 2005.]
Revision [$Id: sfmDec.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
***********************************************************************/
#include "sfmInt.h"
#include "misc/st/st.h"
#include "map/mio/mio.h"
#include "base/abc/abc.h"
#include "misc/util/utilTruth.h"
#include "opt/dau/dau.h"
#include "map/mio/exp.h"
#include "map/scl/sclCon.h"
#include "base/main/main.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
typedef struct Sfm_Dec_t_ Sfm_Dec_t;
struct Sfm_Dec_t_
{
// external
Sfm_Par_t * pPars; // parameters
Sfm_Lib_t * pLib; // library
Sfm_Tim_t * pTim; // timing
Sfm_Mit_t * pMit; // timing
Abc_Ntk_t * pNtk; // network
// library
Vec_Int_t vGateSizes; // fanin counts
Vec_Wrd_t vGateFuncs; // gate truth tables
Vec_Wec_t vGateCnfs; // gate CNFs
Vec_Ptr_t vGateHands; // gate handles
int GateConst0; // special gates
int GateConst1; // special gates
int GateBuffer; // special gates
int GateInvert; // special gates
int GateAnd[4]; // special gates
int GateOr[4]; // special gates
// objects
int nDivs; // the number of divisors
int nMffc; // the number of divisors
int AreaMffc; // the area of gates in MFFC
int DelayMin; // temporary min delay
int iTarget; // target node
int iUseThis; // next cofactoring var to try
int DeltaCrit; // critical delta
int AreaInv; // inverter area
int DelayInv; // inverter delay
Mio_Gate_t * pGateInv; // inverter
word uCareSet; // computed careset
Vec_Int_t vObjRoots; // roots of the window
Vec_Int_t vObjGates; // functionality
Vec_Wec_t vObjFanins; // fanin IDs
Vec_Int_t vObjMap; // object map
Vec_Int_t vObjDec; // decomposition
Vec_Int_t vObjMffc; // MFFC nodes
Vec_Int_t vObjInMffc; // inputs of MFFC nodes
Vec_Wrd_t vObjSims; // simulation patterns
Vec_Wrd_t vObjSims2; // simulation patterns
Vec_Ptr_t vMatchGates; // matched gates
Vec_Ptr_t vMatchFans; // matched fanins
// solver
sat_solver * pSat; // reusable solver
Vec_Wec_t vClauses; // CNF clauses for the node
Vec_Int_t vImpls[2]; // onset/offset implications
Vec_Wrd_t vSets[2]; // onset/offset patterns
int nPats[2]; // CEX count
int nPatWords[2];// CEX words
int nDivWords; // div words
int nDivWordsAlloc; // div words
word TtElems[SFM_SUPP_MAX][SFM_WORD_MAX];
word * pTtElems[SFM_SUPP_MAX];
word * pDivWords[SFM_SUPP_MAX];
// temporary
Vec_Int_t vNewNodes;
Vec_Int_t vGateTfi;
Vec_Int_t vGateTfo;
Vec_Int_t vGateCut;
Vec_Int_t vGateTemp;
Vec_Int_t vGateMffc;
Vec_Int_t vCands;
word Copy[4];
int nSuppVars;
// statistics
abctime timeLib;
abctime timeWin;
abctime timeCnf;
abctime timeSat;
abctime timeSatSat;
abctime timeSatUnsat;
abctime timeEval;
abctime timeTime;
abctime timeOther;
abctime timeStart;
abctime timeTotal;
int nTotalNodesBeg;
int nTotalEdgesBeg;
int nTotalNodesEnd;
int nTotalEdgesEnd;
int nNodesTried;
int nNodesChanged;
int nNodesConst0;
int nNodesConst1;
int nNodesBuf;
int nNodesInv;
int nNodesAndOr;
int nNodesResyn;
int nSatCalls;
int nSatCallsSat;
int nSatCallsUnsat;
int nSatCallsOver;
int nTimeOuts;
int nNoDecs;
int nEfforts;
int nMaxDivs;
int nMaxWin;
word nAllDivs;
word nAllWin;
int nLuckySizes[SFM_SUPP_MAX+1];
int nLuckyGates[SFM_SUPP_MAX+1];
};
#define SFM_MASK_PI 1 // supp(node) is contained in supp(TFI(pivot))
#define SFM_MASK_INPUT 2 // supp(node) does not overlap with supp(TFI(pivot))
#define SFM_MASK_FANIN 4 // the same as above (pointed to by node with SFM_MASK_PI | SFM_MASK_INPUT)
#define SFM_MASK_MFFC 8 // MFFC nodes, including the target node
#define SFM_MASK_PIVOT 16 // the target node
static inline Sfm_Dec_t * Sfm_DecMan( Abc_Obj_t * p ) { return (Sfm_Dec_t *)p->pNtk->pData; }
static inline word Sfm_DecObjSim( Sfm_Dec_t * p, Abc_Obj_t * pObj ) { return Vec_WrdEntry(&p->vObjSims, Abc_ObjId(pObj)); }
static inline word Sfm_DecObjSim2( Sfm_Dec_t * p, Abc_Obj_t * pObj ) { return Vec_WrdEntry(&p->vObjSims2, Abc_ObjId(pObj)); }
static inline word * Sfm_DecDivPats( Sfm_Dec_t * p, int d, int c ) { return Vec_WrdEntryP(&p->vSets[c], d*SFM_SIM_WORDS); }
static inline int Sfm_ManReadObjDelay( Sfm_Dec_t * p, int Id ) { return p->pMit ? Sfm_MitReadObjDelay(p->pMit, Id) : Sfm_TimReadObjDelay(p->pTim, Id); }
static inline int Sfm_ManReadNtkDelay( Sfm_Dec_t * p ) { return p->pMit ? Sfm_MitReadNtkDelay(p->pMit) : Sfm_TimReadNtkDelay(p->pTim); }
static inline int Sfm_ManReadNtkMinSlack( Sfm_Dec_t * p ) { return p->pMit ? Sfm_MitReadNtkMinSlack(p->pMit) : 0; }
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis [Setup parameter structure.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Sfm_ParSetDefault3( Sfm_Par_t * pPars )
{
memset( pPars, 0, sizeof(Sfm_Par_t) );
pPars->nTfoLevMax = 100; // the maximum fanout levels
pPars->nTfiLevMax = 100; // the maximum fanin levels
pPars->nFanoutMax = 10; // the maximum number of fanouts
pPars->nMffcMin = 1; // the maximum MFFC size
pPars->nMffcMax = 3; // the maximum MFFC size
pPars->nVarMax = 6; // the maximum variable count
pPars->nDecMax = 1; // the maximum number of decompositions
pPars->nWinSizeMax = 0; // the maximum window size
pPars->nGrowthLevel = 0; // the maximum allowed growth in level
pPars->nBTLimit = 0; // the maximum number of conflicts in one SAT run
pPars->nTimeWin = 1; // the size of timing window in percents
pPars->DeltaCrit = 0; // delta delay in picoseconds
pPars->fUseAndOr = 0; // enable internal detection of AND/OR gates
pPars->fZeroCost = 0; // enable zero-cost replacement
pPars->fMoreEffort = 0; // enables using more effort
pPars->fUseSim = 0; // enable simulation
pPars->fArea = 0; // performs optimization for area
pPars->fVerbose = 0; // enable basic stats
pPars->fVeryVerbose = 0; // enable detailed stats
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Sfm_Dec_t * Sfm_DecStart( Sfm_Par_t * pPars, Mio_Library_t * pLib, Abc_Ntk_t * pNtk )
{
extern void Sfm_LibPreprocess( Mio_Library_t * pLib, Vec_Int_t * vGateSizes, Vec_Wrd_t * vGateFuncs, Vec_Wec_t * vGateCnfs, Vec_Ptr_t * vGateHands );
Sfm_Dec_t * p = ABC_CALLOC( Sfm_Dec_t, 1 ); int i;
p->timeStart = Abc_Clock();
p->pPars = pPars;
p->pNtk = pNtk;
p->pSat = sat_solver_new();
p->pGateInv = Mio_LibraryReadInv( pLib );
p->AreaInv = Scl_Flt2Int(Mio_GateReadArea(p->pGateInv));
p->DelayInv = Scl_Flt2Int(Mio_GateReadDelayMax(p->pGateInv));
p->DeltaCrit = pPars->DeltaCrit ? Scl_Flt2Int((float)pPars->DeltaCrit) : 5 * Scl_Flt2Int(Mio_LibraryReadDelayInvMax(pLib)) / 2;
p->timeLib = Abc_Clock();
p->pLib = Sfm_LibPrepare( pPars->nVarMax, 1, !pPars->fArea, pPars->fVerbose, pPars->fLibVerbose );
p->timeLib = Abc_Clock() - p->timeLib;
if ( !pPars->fArea )
{
if ( Abc_FrameReadLibScl() )
p->pMit = Sfm_MitStart( pLib, (SC_Lib *)Abc_FrameReadLibScl(), Scl_ConReadMan(), pNtk, p->DeltaCrit );
if ( p->pMit == NULL )
p->pTim = Sfm_TimStart( pLib, Scl_ConReadMan(), pNtk, p->DeltaCrit );
}
if ( pPars->fVeryVerbose )
// if ( pPars->fVerbose )
Sfm_LibPrint( p->pLib );
pNtk->pData = p;
// enter library
assert( Abc_NtkIsMappedLogic(pNtk) );
Sfm_LibPreprocess( pLib, &p->vGateSizes, &p->vGateFuncs, &p->vGateCnfs, &p->vGateHands );
p->GateConst0 = Mio_GateReadValue( Mio_LibraryReadConst0(pLib) );
p->GateConst1 = Mio_GateReadValue( Mio_LibraryReadConst1(pLib) );
p->GateBuffer = Mio_GateReadValue( Mio_LibraryReadBuf(pLib) );
p->GateInvert = Mio_GateReadValue( Mio_LibraryReadInv(pLib) );
// elementary truth tables
for ( i = 0; i < SFM_SUPP_MAX; i++ )
p->pTtElems[i] = p->TtElems[i];
Abc_TtElemInit( p->pTtElems, SFM_SUPP_MAX );
p->iUseThis = -1;
return p;
}
void Sfm_DecStop( Sfm_Dec_t * p )
{
Abc_Ntk_t * pNtk = p->pNtk;
Abc_Obj_t * pObj; int i;
Abc_NtkForEachNode( pNtk, pObj, i )
if ( (int)pObj->Level != Abc_ObjLevelNew(pObj) )
printf( "Level count mismatch at node %d.\n", i );
Sfm_LibStop( p->pLib );
if ( p->pTim ) Sfm_TimStop( p->pTim );
if ( p->pMit ) Sfm_MitStop( p->pMit );
// divisors
for ( i = 0; i < SFM_SUPP_MAX; i++ )
ABC_FREE( p->pDivWords[i] );
// library
Vec_IntErase( &p->vGateSizes );
Vec_WrdErase( &p->vGateFuncs );
Vec_WecErase( &p->vGateCnfs );
Vec_PtrErase( &p->vGateHands );
// objects
Vec_IntErase( &p->vObjRoots );
Vec_IntErase( &p->vObjGates );
Vec_WecErase( &p->vObjFanins );
Vec_IntErase( &p->vObjMap );
Vec_IntErase( &p->vObjDec );
Vec_IntErase( &p->vObjMffc );
Vec_IntErase( &p->vObjInMffc );
Vec_WrdErase( &p->vObjSims );
Vec_WrdErase( &p->vObjSims2 );
Vec_PtrErase( &p->vMatchGates );
Vec_PtrErase( &p->vMatchFans );
// solver
sat_solver_delete( p->pSat );
Vec_WecErase( &p->vClauses );
Vec_IntErase( &p->vImpls[0] );
Vec_IntErase( &p->vImpls[1] );
Vec_WrdErase( &p->vSets[0] );
Vec_WrdErase( &p->vSets[1] );
// temporary
Vec_IntErase( &p->vNewNodes );
Vec_IntErase( &p->vGateTfi );
Vec_IntErase( &p->vGateTfo );
Vec_IntErase( &p->vGateCut );
Vec_IntErase( &p->vGateTemp );
Vec_IntErase( &p->vGateMffc );
Vec_IntErase( &p->vCands );
ABC_FREE( p );
pNtk->pData = NULL;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline word Sfm_ObjSimulate( Abc_Obj_t * pObj )
{
Sfm_Dec_t * p = Sfm_DecMan( pObj );
Vec_Int_t * vExpr = Mio_GateReadExpr( (Mio_Gate_t *)pObj->pData );
Abc_Obj_t * pFanin; int i; word uFanins[6];
assert( Abc_ObjFaninNum(pObj) <= 6 );
Abc_ObjForEachFanin( pObj, pFanin, i )
uFanins[i] = Sfm_DecObjSim( p, pFanin );
return Exp_Truth6( Abc_ObjFaninNum(pObj), vExpr, uFanins );
}
static inline word Sfm_ObjSimulate2( Abc_Obj_t * pObj )
{
Sfm_Dec_t * p = Sfm_DecMan( pObj );
Vec_Int_t * vExpr = Mio_GateReadExpr( (Mio_Gate_t *)pObj->pData );
Abc_Obj_t * pFanin; int i; word uFanins[6];
Abc_ObjForEachFanin( pObj, pFanin, i )
if ( (pFanin->iTemp & SFM_MASK_PIVOT) )
uFanins[i] = Sfm_DecObjSim2( p, pFanin );
else
uFanins[i] = Sfm_DecObjSim( p, pFanin );
return Exp_Truth6( Abc_ObjFaninNum(pObj), vExpr, uFanins );
}
static inline void Sfm_NtkSimulate( Abc_Ntk_t * pNtk )
{
Vec_Ptr_t * vNodes;
Abc_Obj_t * pObj; int i; word uTemp;
Sfm_Dec_t * p = Sfm_DecMan( Abc_NtkPi(pNtk, 0) );
Vec_WrdFill( &p->vObjSims, 2*Abc_NtkObjNumMax(pNtk), 0 );
Vec_WrdFill( &p->vObjSims2, 2*Abc_NtkObjNumMax(pNtk), 0 );
Gia_ManRandomW(1);
assert( p->pPars->fUseSim );
Abc_NtkForEachCi( pNtk, pObj, i )
{
Vec_WrdWriteEntry( &p->vObjSims, Abc_ObjId(pObj), (uTemp = Gia_ManRandomW(0)) );
//printf( "Inpt = %5d : ", Abc_ObjId(pObj) );
//Extra_PrintBinary( stdout, (unsigned *)&uTemp, 64 );
//printf( "\n" );
}
vNodes = Abc_NtkDfs( pNtk, 1 );
Vec_PtrForEachEntry( Abc_Obj_t *, vNodes, pObj, i )
{
Vec_WrdWriteEntry( &p->vObjSims, Abc_ObjId(pObj), (uTemp = Sfm_ObjSimulate(pObj)) );
//printf( "Obj = %5d : ", Abc_ObjId(pObj) );
//Extra_PrintBinary( stdout, (unsigned *)&uTemp, 64 );
//printf( "\n" );
}
Vec_PtrFree( vNodes );
}
static inline void Sfm_ObjSimulateNode( Abc_Obj_t * pObj )
{
Sfm_Dec_t * p = Sfm_DecMan( pObj );
if ( !p->pPars->fUseSim )
return;
Vec_WrdWriteEntry( &p->vObjSims, Abc_ObjId(pObj), Sfm_ObjSimulate(pObj) );
if ( (pObj->iTemp & SFM_MASK_PIVOT) )
Vec_WrdWriteEntry( &p->vObjSims2, Abc_ObjId(pObj), Sfm_ObjSimulate2(pObj) );
}
static inline void Sfm_ObjFlipNode( Abc_Obj_t * pObj )
{
Sfm_Dec_t * p = Sfm_DecMan( pObj );
if ( !p->pPars->fUseSim )
return;
Vec_WrdWriteEntry( &p->vObjSims2, Abc_ObjId(pObj), ~Sfm_DecObjSim(p, pObj) );
}
static inline word Sfm_ObjFindCareSet( Abc_Ntk_t * pNtk, Vec_Int_t * vRoots )
{
Sfm_Dec_t * p = Sfm_DecMan( Abc_NtkPi(pNtk, 0) );
Abc_Obj_t * pObj; int i; word Res = 0;
if ( !p->pPars->fUseSim )
return 0;
Abc_NtkForEachObjVec( vRoots, pNtk, pObj, i )
Res |= Sfm_DecObjSim(p, pObj) ^ Sfm_DecObjSim2(p, pObj);
return Res;
}
static inline void Sfm_ObjSetupSimInfo( Abc_Obj_t * pObj )
{
Sfm_Dec_t * p = Sfm_DecMan( pObj ); int i;
p->nPats[0] = p->nPats[1] = 0;
p->nPatWords[0] = p->nPatWords[1] = 0;
Vec_WrdFill( &p->vSets[0], p->nDivs*SFM_SIM_WORDS, 0 );
Vec_WrdFill( &p->vSets[1], p->nDivs*SFM_SIM_WORDS, 0 );
// alloc divwords
p->nDivWords = Abc_Bit6WordNum( 4 * p->nDivs );
if ( p->nDivWordsAlloc < p->nDivWords )
{
p->nDivWordsAlloc = Abc_MaxInt( 16, p->nDivWords );
for ( i = 0; i < SFM_SUPP_MAX; i++ )
p->pDivWords[i] = ABC_REALLOC( word, p->pDivWords[i], p->nDivWordsAlloc );
}
memset( p->pDivWords[0], 0, sizeof(word) * p->nDivWords );
// collect simulation info
if ( p->pPars->fUseSim && p->uCareSet != 0 )
{
word uCareSet = p->uCareSet;
word uValues = Sfm_DecObjSim(p, pObj);
int c, d, i, Indexes[2][64];
assert( p->iTarget == pObj->iTemp );
assert( p->pPars->fUseSim );
// find what patterns go to on-set/off-set
for ( i = 0; i < 64; i++ )
if ( (uCareSet >> i) & 1 )
{
c = !((uValues >> i) & 1);
Indexes[c][p->nPats[c]++] = i;
}
for ( c = 0; c < 2; c++ )
p->nPatWords[c] = 1 + (p->nPats[c] >> 6);
// write patterns
for ( d = 0; d < p->nDivs; d++ )
{
word uSim = Vec_WrdEntry( &p->vObjSims, Vec_IntEntry(&p->vObjMap, d) );
for ( c = 0; c < 2; c++ )
for ( i = 0; i < p->nPats[c]; i++ )
if ( (uSim >> Indexes[c][i]) & 1 )
Abc_TtSetBit( Sfm_DecDivPats(p, d, c), i );
}
//printf( "Node %d : Onset = %d. Offset = %d.\n", pObj->Id, p->nPats[0], p->nPats[1] );
}
}
static inline void Sfm_ObjSetdownSimInfo( Abc_Obj_t * pObj )
{
int nPatKeep = 32;
Sfm_Dec_t * p = Sfm_DecMan( pObj );
int c, d; word uSim, uSims[2], uMask;
if ( !p->pPars->fUseSim )
return;
for ( d = 0; d < p->nDivs; d++ )
{
uSim = Vec_WrdEntry( &p->vObjSims, Vec_IntEntry(&p->vObjMap, d) );
for ( c = 0; c < 2; c++ )
{
uMask = Abc_Tt6Mask( Abc_MinInt(p->nPats[c], nPatKeep) );
uSims[c] = (Sfm_DecDivPats(p, d, c)[0] & uMask) | (uSim & ~uMask);
uSim >>= 32;
}
uSim = (uSims[0] & 0xFFFFFFFF) | (uSims[1] << 32);
Vec_WrdWriteEntry( &p->vObjSims, Vec_IntEntry(&p->vObjMap, d), uSim );
}
}
/*
void Sfm_ObjSetdownSimInfo( Abc_Obj_t * pObj )
{
int nPatKeep = 32;
Sfm_Dec_t * p = Sfm_DecMan( pObj );
word uSim, uMaskKeep[2];
int c, d, nKeeps[2];
for ( c = 0; c < 2; c++ )
{
nKeeps[c] = Abc_MaxInt(p->nPats[c], nPatKeep);
uMaskKeep[c] = Abc_Tt6Mask( nKeeps[c] );
}
for ( d = 0; d < p->nDivs; d++ )
{
uSim = Vec_WrdEntry( &p->vObjSims, Vec_IntEntry(&p->vObjMap, d) ) << (nKeeps[0] + nKeeps[1]);
uSim |= (Vec_WrdEntry(&p->vSets[0], d) & uMaskKeep[0]) | ((Vec_WrdEntry(&p->vSets[1], d) & uMaskKeep[1]) << nKeeps[0]);
Vec_WrdWriteEntry( &p->vObjSims, Vec_IntEntry(&p->vObjMap, d), uSim );
}
}
*/
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Sfm_DecPrepareSolver( Sfm_Dec_t * p )
{
Vec_Int_t * vRoots = &p->vObjRoots;
Vec_Int_t * vFaninVars = &p->vGateTemp;
Vec_Int_t * vLevel, * vClause;
int i, k, Gate, iObj, RetValue;
int nTfiSize = p->iTarget + 1; // including node
int nWinSize = Vec_IntSize(&p->vObjGates);
int nSatVars = 2 * nWinSize - nTfiSize;
assert( nWinSize == Vec_IntSize(&p->vObjGates) );
assert( p->iTarget < nWinSize );
// create SAT solver
sat_solver_restart( p->pSat );
sat_solver_setnvars( p->pSat, nSatVars + Vec_IntSize(vRoots) );
// add CNF clauses for the TFI
Vec_IntForEachEntry( &p->vObjGates, Gate, i )
{
if ( Gate == -1 )
continue;
// generate CNF
vLevel = Vec_WecEntry( &p->vObjFanins, i );
Vec_IntPush( vLevel, i );
Sfm_TranslateCnf( &p->vClauses, (Vec_Str_t *)Vec_WecEntry(&p->vGateCnfs, Gate), vLevel, -1 );
Vec_IntPop( vLevel );
// add clauses
Vec_WecForEachLevel( &p->vClauses, vClause, k )
{
if ( Vec_IntSize(vClause) == 0 )
break;
RetValue = sat_solver_addclause( p->pSat, Vec_IntArray(vClause), Vec_IntArray(vClause) + Vec_IntSize(vClause) );
if ( RetValue == 0 )
return 0;
}
}
// add CNF clauses for the TFO
Vec_IntForEachEntryStart( &p->vObjGates, Gate, i, nTfiSize )
{
assert( Gate != -1 );
vLevel = Vec_WecEntry( &p->vObjFanins, i );
Vec_IntClear( vFaninVars );
Vec_IntForEachEntry( vLevel, iObj, k )
Vec_IntPush( vFaninVars, iObj <= p->iTarget ? iObj : iObj + nWinSize - nTfiSize );
Vec_IntPush( vFaninVars, i + nWinSize - nTfiSize );
// generate CNF
Sfm_TranslateCnf( &p->vClauses, (Vec_Str_t *)Vec_WecEntry(&p->vGateCnfs, Gate), vFaninVars, p->iTarget );
// add clauses
Vec_WecForEachLevel( &p->vClauses, vClause, k )
{
if ( Vec_IntSize(vClause) == 0 )
break;
RetValue = sat_solver_addclause( p->pSat, Vec_IntArray(vClause), Vec_IntArray(vClause) + Vec_IntSize(vClause) );
if ( RetValue == 0 )
return 0;
}
}
if ( nTfiSize < nWinSize )
{
// create XOR clauses for the roots
Vec_IntClear( vFaninVars );
Vec_IntForEachEntry( vRoots, iObj, i )
{
Vec_IntPush( vFaninVars, Abc_Var2Lit(nSatVars, 0) );
sat_solver_add_xor( p->pSat, iObj, iObj + nWinSize - nTfiSize, nSatVars++, 0 );
}
// make OR clause for the last nRoots variables
RetValue = sat_solver_addclause( p->pSat, Vec_IntArray(vFaninVars), Vec_IntLimit(vFaninVars) );
if ( RetValue == 0 )
return 0;
assert( nSatVars == sat_solver_nvars(p->pSat) );
}
else assert( Vec_IntSize(vRoots) == 1 );
// finalize
RetValue = sat_solver_simplify( p->pSat );
return 1;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Sfm_DecFindCost( Sfm_Dec_t * p, int c, int iLit, word * pMask )
{
word * pPats = Sfm_DecDivPats( p, Abc_Lit2Var(iLit), !c );
return Abc_TtCountOnesVecMask( pPats, pMask, p->nPatWords[!c], Abc_LitIsCompl(iLit) );
}
void Sfm_DecPrint( Sfm_Dec_t * p, word Masks[2][SFM_SIM_WORDS] )
{
int c, i, k, Entry;
for ( c = 0; c < 2; c++ )
{
Vec_Int_t * vLevel = Vec_WecEntry( &p->vObjFanins, p->iTarget );
printf( "%s-SET of object %d (divs = %d) with gate \"%s\" and fanins: ",
c ? "OFF": "ON", p->iTarget, p->nDivs,
Mio_GateReadName((Mio_Gate_t *)Vec_PtrEntry(&p->vGateHands, Vec_IntEntry(&p->vObjGates,p->iTarget))) );
Vec_IntForEachEntry( vLevel, Entry, i )
printf( "%d ", Entry );
printf( "\n" );
printf( "Implications: " );
Vec_IntForEachEntry( &p->vImpls[c], Entry, i )
printf( "%s%d(%d) ", Abc_LitIsCompl(Entry)? "!":"", Abc_Lit2Var(Entry), Sfm_DecFindCost(p, c, Entry, Masks[!c]) );
printf( "\n" );
printf( " " );
for ( i = 0; i < p->nDivs; i++ )
printf( "%d", (i / 10) % 10 );
printf( "\n" );
printf( " " );
for ( i = 0; i < p->nDivs; i++ )
printf( "%d", i % 10 );
printf( "\n" );
for ( k = 0; k < p->nPats[c]; k++ )
{
printf( "%2d : ", k );
for ( i = 0; i < p->nDivs; i++ )
printf( "%d", Abc_TtGetBit(Sfm_DecDivPats(p, i, c), k) );
printf( "\n" );
}
//printf( "\n" );
}
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Sfm_DecVarCost( Sfm_Dec_t * p, word Masks[2][SFM_SIM_WORDS], int d, int Counts[2][2] )
{
int c;
for ( c = 0; c < 2; c++ )
{
word * pPats = Sfm_DecDivPats( p, d, c );
int Num = Abc_TtCountOnesVec( Masks[c], p->nPatWords[c] );
Counts[c][1] = Abc_TtCountOnesVecMask( pPats, Masks[c], p->nPatWords[c], 0 );
Counts[c][0] = Num - Counts[c][1];
assert( Counts[c][0] >= 0 && Counts[c][1] >= 0 );
}
//printf( "%5d %5d %5d %5d \n", Counts[0][0], Counts[0][1], Counts[1][0], Counts[1][1] );
}
int Sfm_DecFindBestVar2( Sfm_Dec_t * p, word Masks[2][SFM_SIM_WORDS] )
{
int Counts[2][2];
int d, VarBest = -1, CostBest = ABC_INFINITY, Cost;
for ( d = 0; d < p->nDivs; d++ )
{
Sfm_DecVarCost( p, Masks, d, Counts );
if ( (Counts[0][0] < Counts[0][1]) == (Counts[1][0] < Counts[1][1]) )
continue;
Cost = Abc_MinInt(Counts[0][0], Counts[0][1]) + Abc_MinInt(Counts[1][0], Counts[1][1]);
if ( CostBest > Cost )
{
CostBest = Cost;
VarBest = d;
}
}
return VarBest;
}
int Sfm_DecFindBestVar( Sfm_Dec_t * p, word Masks[2][SFM_SIM_WORDS] )
{
int c, i, iLit, Var = -1, Cost, CostMin = ABC_INFINITY;
for ( c = 0; c < 2; c++ )
{
Vec_IntForEachEntry( &p->vImpls[c], iLit, i )
{
if ( Vec_IntSize(&p->vImpls[c]) > 1 && Vec_IntFind(&p->vObjDec, Abc_Lit2Var(iLit)) >= 0 )
continue;
Cost = Sfm_DecFindCost( p, c, iLit, Masks[!c] );
if ( CostMin > Cost )
{
CostMin = Cost;
Var = Abc_Lit2Var(iLit);
}
}
}
return Var;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Sfm_DecMffcArea( Abc_Ntk_t * pNtk, Vec_Int_t * vMffc )
{
Abc_Obj_t * pObj;
int i, nAreaMffc = 0;
Abc_NtkForEachObjVec( vMffc, pNtk, pObj, i )
nAreaMffc += Scl_Flt2Int(Mio_GateReadArea((Mio_Gate_t *)pObj->pData));
return nAreaMffc;
}
int Sfm_MffcDeref_rec( Abc_Obj_t * pObj )
{
Abc_Obj_t * pFanin;
int i, Area = Scl_Flt2Int(Mio_GateReadArea((Mio_Gate_t *)pObj->pData));
Abc_ObjForEachFanin( pObj, pFanin, i )
{
assert( pFanin->vFanouts.nSize > 0 );
if ( --pFanin->vFanouts.nSize == 0 && !Abc_ObjIsCi(pFanin) )
Area += Sfm_MffcDeref_rec( pFanin );
}
return Area;
}
int Sfm_MffcRef_rec( Abc_Obj_t * pObj, Vec_Int_t * vMffc )
{
Abc_Obj_t * pFanin;
int i, Area = Scl_Flt2Int(Mio_GateReadArea((Mio_Gate_t *)pObj->pData));
Abc_ObjForEachFanin( pObj, pFanin, i )
{
if ( pFanin->vFanouts.nSize++ == 0 && !Abc_ObjIsCi(pFanin) )
Area += Sfm_MffcRef_rec( pFanin, vMffc );
}
if ( vMffc )
Vec_IntPush( vMffc, Abc_ObjId(pObj) );
return Area;
}
int Sfm_DecMffcAreaReal( Abc_Obj_t * pPivot, Vec_Int_t * vCut, Vec_Int_t * vMffc )
{
Abc_Ntk_t * pNtk = pPivot->pNtk;
Abc_Obj_t * pObj;
int i, Area1, Area2;
assert( Abc_ObjIsNode(pPivot) );
if ( vMffc )
Vec_IntClear( vMffc );
Abc_NtkForEachObjVec( vCut, pNtk, pObj, i )
pObj->vFanouts.nSize++;
Area1 = Sfm_MffcDeref_rec( pPivot );
Area2 = Sfm_MffcRef_rec( pPivot, vMffc );
Abc_NtkForEachObjVec( vCut, pNtk, pObj, i )
pObj->vFanouts.nSize--;
assert( Area1 == Area2 );
return Area1;
}
void Sfm_DecPrepareVec( Vec_Int_t * vMap, int * pNodes, int nNodes, Vec_Int_t * vCut )
{
int i;
Vec_IntClear( vCut );
for ( i = 0; i < nNodes; i++ )
Vec_IntPush( vCut, Vec_IntEntry(vMap, pNodes[i]) );
}
int Sfm_DecComputeFlipInvGain( Sfm_Dec_t * p, Abc_Obj_t * pPivot, int * pfNeedInv )
{
Abc_Obj_t * pFanout;
Mio_Gate_t * pGate, * pGateNew;
int i, Handle, fNeedInv = 0, Gain = 0;
Abc_ObjForEachFanout( pPivot, pFanout, i )
{
if ( !Abc_ObjIsNode(pFanout) )
{
fNeedInv = 1;
continue;
}
pGate = (Mio_Gate_t*)pFanout->pData;
if ( Abc_ObjFaninNum(pFanout) == 1 && Mio_GateIsInv(pGate) )
{
Gain += p->AreaInv;
continue;
}
Handle = Sfm_LibFindComplInputGate( &p->vGateFuncs, Mio_GateReadValue(pGate), Abc_ObjFaninNum(pFanout), Abc_NodeFindFanin(pFanout, pPivot), NULL );
if ( Handle == -1 )
{
fNeedInv = 1;
continue;
}
pGateNew = (Mio_Gate_t *)Vec_PtrEntry( &p->vGateHands, Handle );
Gain += Scl_Flt2Int(Mio_GateReadArea(pGate)) - Scl_Flt2Int(Mio_GateReadArea(pGateNew));
}
if ( fNeedInv )
Gain -= p->AreaInv;
if ( pfNeedInv )
*pfNeedInv = fNeedInv;
return Gain;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Sfm_DecCombineDec( Sfm_Dec_t * p, word * pTruth0, word * pTruth1, int * pSupp0, int * pSupp1, int nSupp0, int nSupp1, word * pTruth, int * pSupp, int Var )
{
Vec_Int_t vVec0 = { 2*SFM_SUPP_MAX, nSupp0, pSupp0 };
Vec_Int_t vVec1 = { 2*SFM_SUPP_MAX, nSupp1, pSupp1 };
Vec_Int_t vVec = { 2*SFM_SUPP_MAX, 0, pSupp };
int nWords0 = Abc_TtWordNum(nSupp0);
int nSupp, iSuppVar;
// check the case of equal cofactors
if ( nSupp0 == nSupp1 && !memcmp(pSupp0, pSupp1, sizeof(int)*nSupp0) && !memcmp(pTruth0, pTruth1, sizeof(word)*nWords0) )
{
memcpy( pSupp, pSupp0, sizeof(int)*nSupp0 );
memcpy( pTruth, pTruth0, sizeof(word)*nWords0 );
Abc_TtStretch6( pTruth, nSupp0, p->pPars->nVarMax );
return nSupp0;
}
// merge support variables
Vec_IntTwoMerge2Int( &vVec0, &vVec1, &vVec );
Vec_IntPushOrder( &vVec, Var );
nSupp = Vec_IntSize( &vVec );
if ( nSupp > p->pPars->nVarMax )
return -2;
// expand truth tables
Abc_TtStretch6( pTruth0, nSupp0, nSupp );
Abc_TtStretch6( pTruth1, nSupp1, nSupp );
Abc_TtExpand( pTruth0, nSupp, pSupp0, nSupp0, pSupp, nSupp );
Abc_TtExpand( pTruth1, nSupp, pSupp1, nSupp1, pSupp, nSupp );
// perform operation
iSuppVar = Vec_IntFind( &vVec, Var );
Abc_TtMux( pTruth, p->pTtElems[iSuppVar], pTruth1, pTruth0, Abc_TtWordNum(nSupp) );
Abc_TtStretch6( pTruth, nSupp, p->pPars->nVarMax );
return nSupp;
}
int Sfm_DecPeformDec_rec( Sfm_Dec_t * p, word * pTruth, int * pSupp, int * pAssump, int nAssump, word Masks[2][SFM_SIM_WORDS], int fCofactor, int nSuppAdd )
{
int nBTLimit = p->pPars->nBTLimit;
// int fVerbose = p->pPars->fVeryVerbose;
int c, i, d, iLit, status, Var = -1;
word * pDivWords = p->pDivWords[nAssump];
abctime clk;
assert( nAssump <= SFM_SUPP_MAX );
if ( p->pPars->fVeryVerbose )
{
printf( "\nObject %d\n", p->iTarget );
printf( "Divs = %d. Nodes = %d. Mffc = %d. Mffc area = %.2f. ", p->nDivs, Vec_IntSize(&p->vObjGates), p->nMffc, Scl_Int2Flt(p->AreaMffc) );
printf( "Pat0 = %d. Pat1 = %d. ", p->nPats[0], p->nPats[1] );
printf( "\n" );
if ( nAssump )
{
printf( "Cofactor: " );
for ( i = 0; i < nAssump; i++ )
printf( " %s%d", Abc_LitIsCompl(pAssump[i])? "!":"", Abc_Lit2Var(pAssump[i]) );
printf( "\n" );
}
}
// check constant
for ( c = 0; c < 2; c++ )
{
if ( !Abc_TtIsConst0(Masks[c], p->nPatWords[c]) ) // there are some patterns
continue;
p->nSatCalls++;
pAssump[nAssump] = Abc_Var2Lit( p->iTarget, c );
clk = Abc_Clock();
status = sat_solver_solve( p->pSat, pAssump, pAssump + nAssump + 1, nBTLimit, 0, 0, 0 );
if ( status == l_Undef )
{
p->nTimeOuts++;
return -2;
}
if ( status == l_False )
{
p->nSatCallsUnsat++;
p->timeSatUnsat += Abc_Clock() - clk;
Abc_TtConst( pTruth, Abc_TtWordNum(p->pPars->nVarMax), c );
if ( p->pPars->fVeryVerbose )
printf( "Found constant %d.\n", c );
return 0;
}
assert( status == l_True );
p->nSatCallsSat++;
p->timeSatSat += Abc_Clock() - clk;
if ( p->nPats[c] == 64*SFM_SIM_WORDS )
{
p->nSatCallsOver++;
continue;//return -2;//continue;
}
for ( i = 0; i < p->nDivs; i++ )
if ( sat_solver_var_value(p->pSat, i) )
Abc_TtSetBit( Sfm_DecDivPats(p, i, c), p->nPats[c] );
p->nPatWords[c] = 1 + (p->nPats[c] >> 6);
Abc_TtSetBit( Masks[c], p->nPats[c]++ );
}
if ( p->iUseThis != -1 )
{
Var = p->iUseThis;
p->iUseThis = -1;
goto cofactor;
}
// check implications
Vec_IntClear( &p->vImpls[0] );
Vec_IntClear( &p->vImpls[1] );
for ( d = 0; d < p->nDivs; d++ )
{
int Impls[2] = {-1, -1};
for ( c = 0; c < 2; c++ )
{
word * pPats = Sfm_DecDivPats( p, d, c );
int fHas0s = Abc_TtIntersect( pPats, Masks[c], p->nPatWords[c], 1 );
int fHas1s = Abc_TtIntersect( pPats, Masks[c], p->nPatWords[c], 0 );
if ( fHas0s && fHas1s )
continue;
pAssump[nAssump] = Abc_Var2Lit( p->iTarget, c );
pAssump[nAssump+1] = Abc_Var2Lit( d, fHas1s ); // if there are 1s, check if 0 is SAT
clk = Abc_Clock();
if ( Abc_TtGetBit( pDivWords, 4*d+2*c+fHas1s ) )
{
p->nSatCallsUnsat--;
status = l_False;
}
else
{
p->nSatCalls++;
status = sat_solver_solve( p->pSat, pAssump, pAssump + nAssump + 2, nBTLimit, 0, 0, 0 );
}
if ( status == l_Undef )
{
p->nTimeOuts++;
return -2;
}
if ( status == l_False )
{
p->nSatCallsUnsat++;
p->timeSatUnsat += Abc_Clock() - clk;
Impls[c] = Abc_LitNot(pAssump[nAssump+1]);
Vec_IntPush( &p->vImpls[c], Abc_LitNot(pAssump[nAssump+1]) );
Abc_TtSetBit( pDivWords, 4*d+2*c+fHas1s );
continue;
}
assert( status == l_True );
p->nSatCallsSat++;
p->timeSatSat += Abc_Clock() - clk;
if ( p->nPats[c] == 64*SFM_SIM_WORDS )
{
p->nSatCallsOver++;
continue;//return -2;//continue;
}
// record this status
for ( i = 0; i < p->nDivs; i++ )
if ( sat_solver_var_value(p->pSat, i) )
Abc_TtSetBit( Sfm_DecDivPats(p, i, c), p->nPats[c] );
p->nPatWords[c] = 1 + (p->nPats[c] >> 6);
Abc_TtSetBit( Masks[c], p->nPats[c]++ );
}
if ( Impls[0] == -1 || Impls[1] == -1 )
continue;
if ( Impls[0] == Impls[1] )
{
Vec_IntPop( &p->vImpls[0] );
Vec_IntPop( &p->vImpls[1] );
continue;
}
assert( Abc_Lit2Var(Impls[0]) == Abc_Lit2Var(Impls[1]) );
// found buffer/inverter
Abc_TtUnit( pTruth, Abc_TtWordNum(p->pPars->nVarMax), Abc_LitIsCompl(Impls[0]) );
pSupp[0] = Abc_Lit2Var(Impls[0]);
if ( p->pPars->fVeryVerbose )
printf( "Found variable %s%d.\n", Abc_LitIsCompl(Impls[0]) ? "!":"", pSupp[0] );
return 1;
}
if ( nSuppAdd > p->pPars->nVarMax - 2 )
{
if ( p->pPars->fVeryVerbose )
printf( "The number of assumption is more than MFFC size.\n" );
return -2;
}
// try using all implications at once
if ( p->pPars->fUseAndOr )
for ( c = 0; c < 2; c++ )
{
if ( Vec_IntSize(&p->vImpls[!c]) < 2 )
continue;
p->nSatCalls++;
pAssump[nAssump] = Abc_Var2Lit( p->iTarget, c );
assert( Vec_IntSize(&p->vImpls[!c]) < SFM_WIN_MAX-10 );
Vec_IntForEachEntry( &p->vImpls[!c], iLit, i )
pAssump[nAssump+1+i] = iLit;
clk = Abc_Clock();
status = sat_solver_solve( p->pSat, pAssump, pAssump + nAssump+1+i, nBTLimit, 0, 0, 0 );
if ( status == l_Undef )
{
p->nTimeOuts++;
return -2;
}
if ( status == l_False )
{
int * pFinal, nFinal = sat_solver_final( p->pSat, &pFinal );
p->nSatCallsUnsat++;
p->timeSatUnsat += Abc_Clock() - clk;
if ( nFinal + nSuppAdd > 6 )
continue;
// collect only relevant literals
for ( i = d = 0; i < nFinal; i++ )
if ( Vec_IntFind(&p->vImpls[!c], Abc_LitNot(pFinal[i])) >= 0 )
pSupp[d++] = Abc_LitNot(pFinal[i]);
nFinal = d;
// create AND/OR gate
assert( nFinal <= 6 );
if ( c )
{
*pTruth = ~(word)0;
for ( i = 0; i < nFinal; i++ )
{
*pTruth &= Abc_LitIsCompl(pSupp[i]) ? ~s_Truths6[i] : s_Truths6[i];
pSupp[i] = Abc_Lit2Var(pSupp[i]);
}
}
else
{
*pTruth = 0;
for ( i = 0; i < nFinal; i++ )
{
*pTruth |= Abc_LitIsCompl(pSupp[i]) ? s_Truths6[i] : ~s_Truths6[i];
pSupp[i] = Abc_Lit2Var(pSupp[i]);
}
}
Abc_TtStretch6( pTruth, nFinal, p->pPars->nVarMax );
p->nNodesAndOr++;
if ( p->pPars->fVeryVerbose )
printf( "Found %d-input AND/OR gate.\n", nFinal );
return nFinal;
}
assert( status == l_True );
p->nSatCallsSat++;
p->timeSatSat += Abc_Clock() - clk;
if ( p->nPats[c] == 64*SFM_SIM_WORDS )
{
p->nSatCallsOver++;
continue;//return -2;//continue;
}
for ( i = 0; i < p->nDivs; i++ )
if ( sat_solver_var_value(p->pSat, i) )
Abc_TtSetBit( Sfm_DecDivPats(p, i, c), p->nPats[c] );
p->nPatWords[c] = 1 + (p->nPats[c] >> 6);
Abc_TtSetBit( Masks[c], p->nPats[c]++ );
}
// find the best cofactoring variable
// if ( !fCofactor || Vec_IntSize(&p->vImpls[0]) + Vec_IntSize(&p->vImpls[1]) > 2 )
Var = Sfm_DecFindBestVar( p, Masks );
// if ( Var == -1 )
// Var = Sfm_DecFindBestVar2( p, Masks );
/*
{
int Lit0 = Vec_IntSize(&p->vImpls[0]) ? Vec_IntEntry(&p->vImpls[0], 0) : -1;
int Lit1 = Vec_IntSize(&p->vImpls[1]) ? Vec_IntEntry(&p->vImpls[1], 0) : -1;
if ( Lit0 == -1 && Lit1 >= 0 )
Var = Abc_Lit2Var(Lit1);
else if ( Lit1 == -1 && Lit0 >= 0 )
Var = Abc_Lit2Var(Lit0);
else if ( Lit0 >= 0 && Lit1 >= 0 )
{
if ( Lit0 < Lit1 )
Var = Abc_Lit2Var(Lit0);
else
Var = Abc_Lit2Var(Lit1);
}
}
*/
if ( Var == -1 && fCofactor )
{
//for ( Var = p->nDivs - 1; Var >= 0; Var-- )
Vec_IntForEachEntryReverse( &p->vObjInMffc, Var, i )
if ( Vec_IntFind(&p->vObjDec, Var) == -1 )
break;
// if ( i == Vec_IntSize(&p->vObjInMffc) )
if ( i == -1 )
Var = -1;
fCofactor = 0;
}
if ( p->pPars->fVeryVerbose )
{
Sfm_DecPrint( p, Masks );
printf( "Best var %d\n", Var );
printf( "\n" );
}
cofactor:
// cofactor the problem
if ( Var >= 0 )
{
word uTruth[2][SFM_WORD_MAX], MasksNext[2][SFM_SIM_WORDS];
int w, Supp[2][2*SFM_SUPP_MAX], nSupp[2] = {0};
Vec_IntPush( &p->vObjDec, Var );
for ( i = 0; i < 2; i++ )
{
for ( c = 0; c < 2; c++ )
{
Abc_TtAndSharp( MasksNext[c], Masks[c], Sfm_DecDivPats(p, Var, c), p->nPatWords[c], !i );
for ( w = p->nPatWords[c]; w < SFM_SIM_WORDS; w++ )
MasksNext[c][w] = 0;
}
pAssump[nAssump] = Abc_Var2Lit( Var, !i );
memcpy( p->pDivWords[nAssump+1], p->pDivWords[nAssump], sizeof(word) * p->nDivWords );
nSupp[i] = Sfm_DecPeformDec_rec( p, uTruth[i], Supp[i], pAssump, nAssump+1, MasksNext, fCofactor, (i ? nSupp[0] : 0) + nSuppAdd + 1 );
if ( nSupp[i] == -2 )
return -2;
}
// combine solutions
return Sfm_DecCombineDec( p, uTruth[0], uTruth[1], Supp[0], Supp[1], nSupp[0], nSupp[1], pTruth, pSupp, Var );
}
return -2;
}
int Sfm_DecPeformDec2( Sfm_Dec_t * p, Abc_Obj_t * pObj )
{
word uTruth[SFM_DEC_MAX][SFM_WORD_MAX], Masks[2][SFM_SIM_WORDS];
int pSupp[SFM_DEC_MAX][2*SFM_SUPP_MAX];
int nSupp[SFM_DEC_MAX], pAssump[SFM_WIN_MAX];
int fVeryVerbose = p->pPars->fPrintDecs || p->pPars->fVeryVerbose;
int nDecs = Abc_MaxInt(p->pPars->nDecMax, 1);
//int fNeedInv, AreaGainInv = Sfm_DecComputeFlipInvGain(p, pObj, &fNeedInv);
int i, RetValue, Prev = 0, iBest = -1, AreaThis, AreaNew;//, AreaNewInv;
int GainThis, GainBest = -1, iLibObj, iLibObjBest = -1;
assert( p->pPars->fArea == 1 );
//printf( "AreaGainInv = %8.2f ", Scl_Int2Flt(AreaGainInv) );
//Sfm_DecPrint( p, NULL );
if ( fVeryVerbose )
printf( "\nNode %4d : MFFC %2d\n", p->iTarget, p->nMffc );
assert( p->pPars->nDecMax <= SFM_DEC_MAX );
Sfm_ObjSetupSimInfo( pObj );
Vec_IntClear( &p->vObjDec );
for ( i = 0; i < nDecs; i++ )
{
// reduce the variable array
if ( Vec_IntSize(&p->vObjDec) > Prev )
Vec_IntShrink( &p->vObjDec, Prev );
Prev = Vec_IntSize(&p->vObjDec) + 1;
// perform decomposition
Abc_TtMask( Masks[0], SFM_SIM_WORDS, p->nPats[0] );
Abc_TtMask( Masks[1], SFM_SIM_WORDS, p->nPats[1] );
nSupp[i] = Sfm_DecPeformDec_rec( p, uTruth[i], pSupp[i], pAssump, 0, Masks, 1, 0 );
if ( nSupp[i] == -2 )
{
if ( fVeryVerbose )
printf( "Dec %d: Pat0 = %2d Pat1 = %2d NO DEC.\n", i, p->nPats[0], p->nPats[1] );
continue;
}
if ( fVeryVerbose )
printf( "Dec %d: Pat0 = %2d Pat1 = %2d Supp = %d ", i, p->nPats[0], p->nPats[1], nSupp[i] );
if ( fVeryVerbose )
Dau_DsdPrintFromTruth( uTruth[i], nSupp[i] );
if ( nSupp[i] < 2 )
{
p->nSuppVars = nSupp[i];
Abc_TtCopy( p->Copy, uTruth[i], SFM_WORD_MAX, 0 );
RetValue = Sfm_LibImplementSimple( p->pLib, uTruth[i], pSupp[i], nSupp[i], &p->vObjGates, &p->vObjFanins );
assert( nSupp[i] <= p->pPars->nVarMax );
p->nLuckySizes[nSupp[i]]++;
assert( RetValue <= 2 );
p->nLuckyGates[RetValue]++;
//printf( "\n" );
return RetValue;
}
p->nSuppVars = nSupp[i];
Abc_TtCopy( p->Copy, uTruth[i], SFM_WORD_MAX, 0 );
AreaNew = Sfm_LibFindAreaMatch( p->pLib, uTruth[i], nSupp[i], &iLibObj );
/*
uTruth[i][0] = ~uTruth[i][0];
AreaNewInv = Sfm_LibFindAreaMatch( p->pLib, uTruth[i], nSupp[i], NULL );
uTruth[i][0] = ~uTruth[i][0];
if ( AreaNew > 0 && AreaNewInv > 0 && AreaNew - AreaNewInv + AreaGainInv > 0 )
printf( "AreaNew = %8.2f AreaNewInv = %8.2f Gain = %8.2f Total = %8.2f\n",
Scl_Int2Flt(AreaNew), Scl_Int2Flt(AreaNewInv), Scl_Int2Flt(AreaNew - AreaNewInv), Scl_Int2Flt(AreaNew - AreaNewInv + AreaGainInv) );
else
printf( "\n" );
*/
if ( AreaNew == -1 )
continue;
// compute area savings
Sfm_DecPrepareVec( &p->vObjMap, pSupp[i], nSupp[i], &p->vGateCut );
AreaThis = Sfm_DecMffcAreaReal(pObj, &p->vGateCut, NULL);
assert( p->AreaMffc <= AreaThis );
if ( p->pPars->fZeroCost ? (AreaNew > AreaThis) : (AreaNew >= AreaThis) )
continue;
// find the best gain
GainThis = AreaThis - AreaNew;
assert( GainThis >= 0 );
if ( GainBest < GainThis )
{
GainBest = GainThis;
iLibObjBest = iLibObj;
iBest = i;
}
}
Sfm_ObjSetdownSimInfo( pObj );
if ( iBest == -1 )
{
if ( fVeryVerbose )
printf( "Best : NO DEC.\n" );
p->nNoDecs++;
//printf( "\n" );
return -2;
}
if ( fVeryVerbose )
printf( "Best %d: %d ", iBest, nSupp[iBest] );
if ( fVeryVerbose )
Dau_DsdPrintFromTruth( uTruth[iBest], nSupp[iBest] );
// implement
assert( iLibObjBest >= 0 );
RetValue = Sfm_LibImplementGatesArea( p->pLib, pSupp[iBest], nSupp[iBest], iLibObjBest, &p->vObjGates, &p->vObjFanins );
assert( nSupp[iBest] <= p->pPars->nVarMax );
p->nLuckySizes[nSupp[iBest]]++;
assert( RetValue <= 2 );
p->nLuckyGates[RetValue]++;
return 1;
}
int Sfm_DecPeformDec3( Sfm_Dec_t * p, Abc_Obj_t * pObj )
{
word uTruth[SFM_DEC_MAX][SFM_WORD_MAX], Masks[2][SFM_SIM_WORDS];
int pSupp[SFM_DEC_MAX][2*SFM_SUPP_MAX];
int nSupp[SFM_DEC_MAX], pAssump[SFM_WIN_MAX];
int fVeryVerbose = p->pPars->fPrintDecs || p->pPars->fVeryVerbose;
int nDecs = Abc_MaxInt(p->pPars->nDecMax, 1);
int i, k, DelayOrig = 0, DelayMin, GainMax, AreaMffc, nMatches, iBest = -1, RetValue, Prev = 0;
Mio_Gate_t * pGate1Best = NULL, * pGate2Best = NULL;
char * pFans1Best = NULL, * pFans2Best = NULL;
assert( p->pPars->fArea == 0 );
p->DelayMin = 0;
//Sfm_DecPrint( p, NULL );
if ( fVeryVerbose )
printf( "\nNode %4d : MFFC %2d\n", p->iTarget, p->nMffc );
// set limit on search for decompositions in delay-model
assert( p->pPars->nDecMax <= SFM_DEC_MAX );
Sfm_ObjSetupSimInfo( pObj );
Vec_IntClear( &p->vObjDec );
for ( i = 0; i < nDecs; i++ )
{
GainMax = 0;
DelayMin = DelayOrig = Sfm_ManReadObjDelay( p, Abc_ObjId(pObj) );
// reduce the variable array
if ( Vec_IntSize(&p->vObjDec) > Prev )
Vec_IntShrink( &p->vObjDec, Prev );
Prev = Vec_IntSize(&p->vObjDec) + 1;
// perform decomposition
Abc_TtMask( Masks[0], SFM_SIM_WORDS, p->nPats[0] );
Abc_TtMask( Masks[1], SFM_SIM_WORDS, p->nPats[1] );
nSupp[i] = Sfm_DecPeformDec_rec( p, uTruth[i], pSupp[i], pAssump, 0, Masks, 1, 0 );
if ( nSupp[i] == -2 )
{
if ( fVeryVerbose )
printf( "Dec %d: Pat0 = %2d Pat1 = %2d NO DEC.\n", i, p->nPats[0], p->nPats[1] );
continue;
}
if ( fVeryVerbose )
printf( "Dec %d: Pat0 = %2d Pat1 = %2d Supp = %d ", i, p->nPats[0], p->nPats[1], nSupp[i] );
if ( fVeryVerbose )
Dau_DsdPrintFromTruth( uTruth[i], nSupp[i] );
if ( p->pTim && nSupp[i] == 1 && uTruth[i][0] == ABC_CONST(0x5555555555555555) && DelayMin <= p->DelayInv + Sfm_ManReadObjDelay(p, Vec_IntEntry(&p->vObjMap, pSupp[i][0])) )
{
if ( fVeryVerbose )
printf( "Dec %d: Pat0 = %2d Pat1 = %2d NO DEC.\n", i, p->nPats[0], p->nPats[1] );
continue;
}
if ( p->pMit && nSupp[i] == 1 && uTruth[i][0] == ABC_CONST(0x5555555555555555) )
{
if ( fVeryVerbose )
printf( "Dec %d: Pat0 = %2d Pat1 = %2d NO DEC.\n", i, p->nPats[0], p->nPats[1] );
continue;
}
if ( nSupp[i] < 2 )
{
p->nSuppVars = nSupp[i];
Abc_TtCopy( p->Copy, uTruth[i], SFM_WORD_MAX, 0 );
RetValue = Sfm_LibImplementSimple( p->pLib, uTruth[i], pSupp[i], nSupp[i], &p->vObjGates, &p->vObjFanins );
assert( nSupp[i] <= p->pPars->nVarMax );
p->nLuckySizes[nSupp[i]]++;
assert( RetValue <= 2 );
p->nLuckyGates[RetValue]++;
return RetValue;
}
// get MFFC
Sfm_DecPrepareVec( &p->vObjMap, pSupp[i], nSupp[i], &p->vGateCut ); // returns cut in p->vGateCut
AreaMffc = Sfm_DecMffcAreaReal(pObj, &p->vGateCut, &p->vGateMffc ); // returns MFFC in p->vGateMffc
// try the delay
p->nSuppVars = nSupp[i];
Abc_TtCopy( p->Copy, uTruth[i], SFM_WORD_MAX, 0 );
nMatches = Sfm_LibFindDelayMatches( p->pLib, uTruth[i], pSupp[i], nSupp[i], &p->vMatchGates, &p->vMatchFans );
for ( k = 0; k < nMatches; k++ )
{
abctime clk = Abc_Clock();
Mio_Gate_t * pGate1 = (Mio_Gate_t *)Vec_PtrEntry( &p->vMatchGates, 2*k+0 );
Mio_Gate_t * pGate2 = (Mio_Gate_t *)Vec_PtrEntry( &p->vMatchGates, 2*k+1 );
int AreaNew = Scl_Flt2Int( Mio_GateReadArea(pGate1) + (pGate2 ? Mio_GateReadArea(pGate2) : 0.0) );
char * pFans1 = (char *)Vec_PtrEntry( &p->vMatchFans, 2*k+0 );
char * pFans2 = (char *)Vec_PtrEntry( &p->vMatchFans, 2*k+1 );
Vec_Int_t vFanins = { nSupp[i], nSupp[i], pSupp[i] };
// skip identical gate
//if ( pGate2 == NULL && pGate1 == (Mio_Gate_t *)pObj->pData )
// continue;
if ( p->pMit )
{
int Gain = Sfm_MitEvalRemapping( p->pMit, &p->vGateMffc, pObj, &vFanins, &p->vObjMap, pGate1, pFans1, pGate2, pFans2 );
if ( p->pPars->DelAreaRatio && AreaNew > AreaMffc && (Gain / (AreaNew - AreaMffc)) < p->pPars->DelAreaRatio )
continue;
if ( GainMax < Gain )
{
GainMax = Gain;
pGate1Best = pGate1;
pGate2Best = pGate2;
pFans1Best = pFans1;
pFans2Best = pFans2;
iBest = i;
}
}
else
{
int Delay = Sfm_TimEvalRemapping( p->pTim, &vFanins, &p->vObjMap, pGate1, pFans1, pGate2, pFans2 );
if ( p->pPars->DelAreaRatio && AreaNew > AreaMffc && (Delay / (AreaNew - AreaMffc)) < p->pPars->DelAreaRatio )
continue;
if ( DelayMin > Delay )
{
DelayMin = Delay;
pGate1Best = pGate1;
pGate2Best = pGate2;
pFans1Best = pFans1;
pFans2Best = pFans2;
iBest = i;
}
}
p->timeEval += Abc_Clock() - clk;
}
}
//printf( "Gain max = %d.\n", GainMax );
Sfm_ObjSetdownSimInfo( pObj );
if ( iBest == -1 )
{
if ( fVeryVerbose )
printf( "Best : NO DEC.\n" );
p->nNoDecs++;
return -2;
}
if ( fVeryVerbose )
printf( "Best %d: %d ", iBest, nSupp[iBest] );
// if ( fVeryVerbose )
// Dau_DsdPrintFromTruth( uTruth[iBest], nSupp[iBest] );
RetValue = Sfm_LibImplementGatesDelay( p->pLib, pSupp[iBest], pGate1Best, pGate2Best, pFans1Best, pFans2Best, &p->vObjGates, &p->vObjFanins );
assert( nSupp[iBest] <= p->pPars->nVarMax );
p->nLuckySizes[nSupp[iBest]]++;
assert( RetValue <= 2 );
p->nLuckyGates[RetValue]++;
p->DelayMin = DelayMin;
return 1;
}
/**Function*************************************************************
Synopsis [Incremental level update.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Abc_NtkUpdateIncLevel_rec( Abc_Obj_t * pObj )
{
Abc_Obj_t * pFanout;
int i, LevelNew = Abc_ObjLevelNew(pObj);
if ( LevelNew == Abc_ObjLevel(pObj) && Abc_ObjIsNode(pObj) && Abc_ObjFaninNum(pObj) > 0 )
return;
pObj->Level = LevelNew;
if ( !Abc_ObjIsCo(pObj) )
Abc_ObjForEachFanout( pObj, pFanout, i )
Abc_NtkUpdateIncLevel_rec( pFanout );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Abc_NtkDfsCheck_rec( Abc_Obj_t * pObj, Abc_Obj_t * pPivot )
{
Abc_Obj_t * pFanin; int i;
if ( pObj == pPivot )
return 0;
if ( Abc_NodeIsTravIdCurrent( pObj ) )
return 1;
Abc_NodeSetTravIdCurrent( pObj );
if ( Abc_ObjIsCi(pObj) )
return 1;
assert( Abc_ObjIsNode(pObj) );
Abc_ObjForEachFanin( pObj, pFanin, i )
if ( !Abc_NtkDfsCheck_rec(pFanin, pPivot) )
return 0;
return 1;
}
void Abc_NtkDfsReverseOne_rec( Abc_Obj_t * pObj, Vec_Int_t * vTfo, int nLevelMax, int nFanoutMax )
{
Abc_Obj_t * pFanout; int i;
if ( Abc_NodeIsTravIdCurrent( pObj ) )
return;
Abc_NodeSetTravIdCurrent( pObj );
if ( Abc_ObjIsCo(pObj) || Abc_ObjLevel(pObj) > nLevelMax )
return;
assert( Abc_ObjIsNode( pObj ) );
if ( Abc_ObjFanoutNum(pObj) <= nFanoutMax )
{
Abc_ObjForEachFanout( pObj, pFanout, i )
if ( Abc_ObjIsCo(pFanout) || Abc_ObjLevel(pFanout) > nLevelMax )
break;
if ( i == Abc_ObjFanoutNum(pObj) )
Abc_ObjForEachFanout( pObj, pFanout, i )
Abc_NtkDfsReverseOne_rec( pFanout, vTfo, nLevelMax, nFanoutMax );
}
Vec_IntPush( vTfo, Abc_ObjId(pObj) );
pObj->iTemp = 0;
}
int Abc_NtkDfsOne_rec( Abc_Obj_t * pObj, Vec_Int_t * vTfi, int nLevelMin, int CiLabel )
{
Abc_Obj_t * pFanin; int i;
if ( Abc_NodeIsTravIdCurrent( pObj ) )
return pObj->iTemp;
Abc_NodeSetTravIdCurrent( pObj );
if ( Abc_ObjIsCi(pObj) || (Abc_ObjLevel(pObj) < nLevelMin && Abc_ObjFaninNum(pObj) > 0) )
{
Vec_IntPush( vTfi, Abc_ObjId(pObj) );
return (pObj->iTemp = CiLabel);
}
assert( Abc_ObjIsNode(pObj) );
pObj->iTemp = Abc_ObjFaninNum(pObj) ? 0 : CiLabel;
Abc_ObjForEachFanin( pObj, pFanin, i )
pObj->iTemp |= Abc_NtkDfsOne_rec( pFanin, vTfi, nLevelMin, CiLabel );
Vec_IntPush( vTfi, Abc_ObjId(pObj) );
Sfm_ObjSimulateNode( pObj );
return pObj->iTemp;
}
void Sfm_DecAddNode( Abc_Obj_t * pObj, Vec_Int_t * vMap, Vec_Int_t * vGates, int fSkip, int fVeryVerbose )
{
if ( fVeryVerbose )
printf( "%d:%d(%d) ", Vec_IntSize(vMap), Abc_ObjId(pObj), pObj->iTemp );
if ( fVeryVerbose )
Abc_ObjPrint( stdout, pObj );
Vec_IntPush( vMap, Abc_ObjId(pObj) );
Vec_IntPush( vGates, fSkip ? -1 : Mio_GateReadValue((Mio_Gate_t *)pObj->pData) );
}
static inline int Sfm_DecNodeIsMffc( Abc_Obj_t * p, int nLevelMin )
{
return Abc_ObjIsNode(p) && Abc_ObjFanoutNum(p) == 1 && Abc_NodeIsTravIdCurrent(p) && (Abc_ObjLevel(p) >= nLevelMin || Abc_ObjFaninNum(p) == 0);
}
static inline int Sfm_DecNodeIsMffcInput( Abc_Obj_t * p, int nLevelMin, Sfm_Tim_t * pTim, Abc_Obj_t * pPivot )
{
return Abc_NodeIsTravIdCurrent(p) && Sfm_TimNodeIsNonCritical(pTim, pPivot, p);
}
static inline int Sfm_DecNodeIsMffcInput2( Abc_Obj_t * p, int nLevelMin, Sfm_Mit_t * pMit, Abc_Obj_t * pPivot )
{
return Abc_NodeIsTravIdCurrent(p) && Sfm_MitNodeIsNonCritical(pMit, pPivot, p);
}
void Sfm_DecMarkMffc( Abc_Obj_t * pPivot, int nLevelMin, int nMffcMax, int fVeryVerbose, Vec_Int_t * vMffc, Vec_Int_t * vInMffc, Sfm_Tim_t * pTim, Sfm_Mit_t * pMit )
{
Abc_Obj_t * pFanin, * pFanin2, * pFanin3, * pObj; int i, k, n;
assert( nMffcMax > 0 );
Vec_IntFill( vMffc, 1, Abc_ObjId(pPivot) );
if ( pMit != NULL )
{
pPivot->iTemp |= SFM_MASK_MFFC;
pPivot->iTemp |= SFM_MASK_PIVOT;
// collect MFFC inputs (these are low-delay nodes close to the pivot)
Vec_IntClear(vInMffc);
Abc_ObjForEachFanin( pPivot, pFanin, i )
if ( Sfm_DecNodeIsMffcInput2(pFanin, nLevelMin, pMit, pPivot) )
Vec_IntPushUnique( vInMffc, Abc_ObjId(pFanin) );
Abc_ObjForEachFanin( pPivot, pFanin, i )
Abc_ObjForEachFanin( pFanin, pFanin2, k )
if ( Sfm_DecNodeIsMffcInput2(pFanin2, nLevelMin, pMit, pPivot) )
Vec_IntPushUnique( vInMffc, Abc_ObjId(pFanin2) );
Abc_ObjForEachFanin( pPivot, pFanin, i )
Abc_ObjForEachFanin( pFanin, pFanin2, k )
Abc_ObjForEachFanin( pFanin2, pFanin3, n )
if ( Sfm_DecNodeIsMffcInput2(pFanin3, nLevelMin, pMit, pPivot) )
Vec_IntPushUnique( vInMffc, Abc_ObjId(pFanin3) );
}
else if ( pTim != NULL )
{
pPivot->iTemp |= SFM_MASK_MFFC;
pPivot->iTemp |= SFM_MASK_PIVOT;
// collect MFFC inputs (these are low-delay nodes close to the pivot)
Vec_IntClear(vInMffc);
Abc_ObjForEachFanin( pPivot, pFanin, i )
if ( Sfm_DecNodeIsMffcInput(pFanin, nLevelMin, pTim, pPivot) )
Vec_IntPushUnique( vInMffc, Abc_ObjId(pFanin) );
Abc_ObjForEachFanin( pPivot, pFanin, i )
Abc_ObjForEachFanin( pFanin, pFanin2, k )
if ( Sfm_DecNodeIsMffcInput(pFanin2, nLevelMin, pTim, pPivot) )
Vec_IntPushUnique( vInMffc, Abc_ObjId(pFanin2) );
Abc_ObjForEachFanin( pPivot, pFanin, i )
Abc_ObjForEachFanin( pFanin, pFanin2, k )
Abc_ObjForEachFanin( pFanin2, pFanin3, n )
if ( Sfm_DecNodeIsMffcInput(pFanin3, nLevelMin, pTim, pPivot) )
Vec_IntPushUnique( vInMffc, Abc_ObjId(pFanin3) );
/*
printf( "Node %d: (%.2f) ", pPivot->Id, Scl_Int2Flt(Sfm_ManReadObjDelay(p, Abc_ObjId(pPivot))) );
Abc_ObjForEachFanin( pPivot, pFanin, i )
printf( "%d: %.2f ", Abc_ObjLevel(pFanin), Scl_Int2Flt(Sfm_ManReadObjDelay(p, Abc_ObjId(pFanin))) );
printf( "\n" );
printf( "Node %d: ", pPivot->Id );
Abc_NtkForEachObjVec( vInMffc, pPivot->pNtk, pObj, i )
printf( "%d: %.2f ", Abc_ObjLevel(pObj), Scl_Int2Flt(Sfm_ManReadObjDelay(p, Abc_ObjId(pObj))) );
printf( "\n" );
*/
}
else
{
// collect MFFC
Abc_ObjForEachFanin( pPivot, pFanin, i )
if ( Sfm_DecNodeIsMffc(pFanin, nLevelMin) && Vec_IntSize(vMffc) < nMffcMax )
Vec_IntPushUnique( vMffc, Abc_ObjId(pFanin) );
Abc_ObjForEachFanin( pPivot, pFanin, i )
if ( Sfm_DecNodeIsMffc(pFanin, nLevelMin) && Vec_IntSize(vMffc) < nMffcMax )
Abc_ObjForEachFanin( pFanin, pFanin2, k )
if ( Sfm_DecNodeIsMffc(pFanin2, nLevelMin) && Vec_IntSize(vMffc) < nMffcMax )
Vec_IntPushUnique( vMffc, Abc_ObjId(pFanin2) );
Abc_ObjForEachFanin( pPivot, pFanin, i )
if ( Sfm_DecNodeIsMffc(pFanin, nLevelMin) && Vec_IntSize(vMffc) < nMffcMax )
Abc_ObjForEachFanin( pFanin, pFanin2, k )
if ( Sfm_DecNodeIsMffc(pFanin2, nLevelMin) && Vec_IntSize(vMffc) < nMffcMax )
Abc_ObjForEachFanin( pFanin2, pFanin3, n )
if ( Sfm_DecNodeIsMffc(pFanin3, nLevelMin) && Vec_IntSize(vMffc) < nMffcMax )
Vec_IntPushUnique( vMffc, Abc_ObjId(pFanin3) );
// mark MFFC
assert( Vec_IntSize(vMffc) <= nMffcMax );
Abc_NtkForEachObjVec( vMffc, pPivot->pNtk, pObj, i )
pObj->iTemp |= SFM_MASK_MFFC;
pPivot->iTemp |= SFM_MASK_PIVOT;
// collect MFFC inputs
Vec_IntClear(vInMffc);
Abc_NtkForEachObjVec( vMffc, pPivot->pNtk, pObj, i )
Abc_ObjForEachFanin( pObj, pFanin, k )
if ( Abc_NodeIsTravIdCurrent(pFanin) && pFanin->iTemp == SFM_MASK_PI )
Vec_IntPushUnique( vInMffc, Abc_ObjId(pFanin) );
// printf( "Node %d: ", pPivot->Id );
// Abc_ObjForEachFanin( pPivot, pFanin, i )
// printf( "%d ", Abc_ObjFanoutNum(pFanin) );
// printf( "\n" );
// Abc_NtkForEachObjVec( vInMffc, pPivot->pNtk, pObj, i )
// printf( "%d ", Abc_ObjFanoutNum(pObj) );
// printf( "\n" );
}
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Sfm_DecExtract( Abc_Ntk_t * pNtk, Sfm_Par_t * pPars, Abc_Obj_t * pPivot, Vec_Int_t * vRoots, Vec_Int_t * vGates, Vec_Wec_t * vFanins, Vec_Int_t * vMap, Vec_Int_t * vTfi, Vec_Int_t * vTfo, Vec_Int_t * vMffc, Vec_Int_t * vInMffc, Sfm_Tim_t * pTim, Sfm_Mit_t * pMit )
{
int fVeryVerbose = 0;//pPars->fVeryVerbose;
Vec_Int_t * vLevel;
Abc_Obj_t * pObj, * pFanin;
int nLevelMax = pPivot->Level + pPars->nTfoLevMax;
int nLevelMin = pPivot->Level - pPars->nTfiLevMax;
int i, k, nTfiSize, nDivs = -1;
assert( Abc_ObjIsNode(pPivot) );
if ( fVeryVerbose )
printf( "\n\nTarget %d\n", Abc_ObjId(pPivot) );
// collect TFO nodes
Vec_IntClear( vTfo );
Abc_NtkIncrementTravId( pNtk );
Abc_NtkDfsReverseOne_rec( pPivot, vTfo, nLevelMax, pPars->nFanoutMax );
// count internal fanouts
Abc_NtkForEachObjVec( vTfo, pNtk, pObj, i )
Abc_ObjForEachFanin( pObj, pFanin, k )
pFanin->iTemp++;
// compute roots
Vec_IntClear( vRoots );
Abc_NtkForEachObjVec( vTfo, pNtk, pObj, i )
if ( pObj->iTemp != Abc_ObjFanoutNum(pObj) )
Vec_IntPush( vRoots, Abc_ObjId(pObj) );
assert( Vec_IntSize(vRoots) > 0 );
// collect TFI and mark nodes
Vec_IntClear( vTfi );
Abc_NtkIncrementTravId( pNtk );
Abc_NtkDfsOne_rec( pPivot, vTfi, nLevelMin, SFM_MASK_PI );
nTfiSize = Vec_IntSize(vTfi);
Sfm_ObjFlipNode( pPivot );
// additinally mark MFFC
Sfm_DecMarkMffc( pPivot, nLevelMin, pPars->nMffcMax, fVeryVerbose, vMffc, vInMffc, pTim, pMit );
assert( Vec_IntSize(vMffc) <= pPars->nMffcMax );
if ( fVeryVerbose )
printf( "Mffc size = %d. Mffc area = %.2f. InMffc size = %d.\n", Vec_IntSize(vMffc), Scl_Int2Flt(Sfm_DecMffcArea(pNtk, vMffc)), Vec_IntSize(vInMffc) );
// collect TFI(TFO)
Abc_NtkForEachObjVec( vRoots, pNtk, pObj, i )
Abc_NtkDfsOne_rec( pObj, vTfi, nLevelMin, SFM_MASK_INPUT );
// mark input-only nodes pointed to by mixed nodes
Abc_NtkForEachObjVecStart( vTfi, pNtk, pObj, i, nTfiSize )
if ( pObj->iTemp != SFM_MASK_INPUT )
Abc_ObjForEachFanin( pObj, pFanin, k )
if ( pFanin->iTemp == SFM_MASK_INPUT )
pFanin->iTemp = SFM_MASK_FANIN;
// collect nodes supported only on TFI fanins and not MFFC
if ( fVeryVerbose )
printf( "\nDivs:\n" );
Vec_IntClear( vMap );
Vec_IntClear( vGates );
Abc_NtkForEachObjVec( vTfi, pNtk, pObj, i )
if ( pObj->iTemp == SFM_MASK_PI )
Sfm_DecAddNode( pObj, vMap, vGates, Abc_ObjIsCi(pObj) || (Abc_ObjLevel(pObj) < nLevelMin && Abc_ObjFaninNum(pObj) > 0), fVeryVerbose );
nDivs = Vec_IntSize(vMap);
// add other nodes that are not in TFO and not in MFFC
if ( fVeryVerbose )
printf( "\nSides:\n" );
Abc_NtkForEachObjVec( vTfi, pNtk, pObj, i )
if ( pObj->iTemp == (SFM_MASK_PI | SFM_MASK_INPUT) || pObj->iTemp == SFM_MASK_FANIN )
Sfm_DecAddNode( pObj, vMap, vGates, pObj->iTemp == SFM_MASK_FANIN, fVeryVerbose );
// reorder nodes acording to delay
if ( pMit )
{
int nDivsNew, nOldSize = Vec_IntSize(vMap);
Vec_IntClear( vTfo );
Vec_IntAppend( vTfo, vMap );
nDivsNew = Sfm_MitSortArrayByArrival( pMit, vTfo, Abc_ObjId(pPivot) );
// collect again
Vec_IntClear( vMap );
Vec_IntClear( vGates );
Abc_NtkForEachObjVec( vTfo, pNtk, pObj, i )
Sfm_DecAddNode( pObj, vMap, vGates, Abc_ObjIsCi(pObj) || (Abc_ObjLevel(pObj) < nLevelMin && Abc_ObjFaninNum(pObj) > 0) || pObj->iTemp == SFM_MASK_FANIN, 0 );
assert( nOldSize == Vec_IntSize(vMap) );
// update divisor count
nDivs = nDivsNew;
}
else if ( pTim )
{
int nDivsNew, nOldSize = Vec_IntSize(vMap);
Vec_IntClear( vTfo );
Vec_IntAppend( vTfo, vMap );
nDivsNew = Sfm_TimSortArrayByArrival( pTim, vTfo, Abc_ObjId(pPivot) );
// collect again
Vec_IntClear( vMap );
Vec_IntClear( vGates );
Abc_NtkForEachObjVec( vTfo, pNtk, pObj, i )
Sfm_DecAddNode( pObj, vMap, vGates, Abc_ObjIsCi(pObj) || (Abc_ObjLevel(pObj) < nLevelMin && Abc_ObjFaninNum(pObj) > 0) || pObj->iTemp == SFM_MASK_FANIN, 0 );
assert( nOldSize == Vec_IntSize(vMap) );
// update divisor count
nDivs = nDivsNew;
}
// add the TFO nodes
if ( fVeryVerbose )
printf( "\nTFO:\n" );
Abc_NtkForEachObjVec( vTfi, pNtk, pObj, i )
if ( pObj->iTemp >= SFM_MASK_MFFC )
Sfm_DecAddNode( pObj, vMap, vGates, 0, fVeryVerbose );
assert( Vec_IntSize(vMap) == Vec_IntSize(vGates) );
if ( fVeryVerbose )
printf( "\n" );
// create node IDs
Vec_WecClear( vFanins );
Abc_NtkForEachObjVec( vMap, pNtk, pObj, i )
{
pObj->iTemp = i;
vLevel = Vec_WecPushLevel( vFanins );
if ( Vec_IntEntry(vGates, i) >= 0 )
Abc_ObjForEachFanin( pObj, pFanin, k )
Vec_IntPush( vLevel, pFanin->iTemp );
}
// compute care set
Sfm_DecMan(pPivot)->uCareSet = Sfm_ObjFindCareSet(pPivot->pNtk, vRoots);
//printf( "care = %5d : ", Abc_ObjId(pPivot) );
//Extra_PrintBinary( stdout, (unsigned *)&Sfm_DecMan(pPivot)->uCareSet, 64 );
//printf( "\n" );
// remap roots
Abc_NtkForEachObjVec( vRoots, pNtk, pObj, i )
Vec_IntWriteEntry( vRoots, i, pObj->iTemp );
// remap inputs to MFFC
Abc_NtkForEachObjVec( vInMffc, pNtk, pObj, i )
Vec_IntWriteEntry( vInMffc, i, pObj->iTemp );
/*
// check
Abc_NtkForEachObjVec( vMap, pNtk, pObj, i )
{
if ( i == nDivs )
break;
Abc_NtkIncrementTravId( pNtk );
assert( Abc_NtkDfsCheck_rec(pObj, pPivot) );
}
*/
return nDivs;
}
Abc_Obj_t * Sfm_DecInsert( Abc_Ntk_t * pNtk, Abc_Obj_t * pPivot, int Limit, Vec_Int_t * vGates, Vec_Wec_t * vFanins, Vec_Int_t * vMap, Vec_Ptr_t * vGateHandles, int GateBuf, int GateInv, Vec_Wrd_t * vFuncs, Vec_Int_t * vNewNodes, Sfm_Mit_t * pMit )
{
Abc_Obj_t * pObjNew = NULL;
Vec_Int_t * vLevel;
int i, k, iObj, Gate;
if ( vNewNodes )
Vec_IntClear( vNewNodes );
// assuming that new gates are appended at the end
assert( Limit < Vec_IntSize(vGates) );
assert( Limit == Vec_IntSize(vMap) );
if ( Limit + 1 == Vec_IntSize(vGates) )
{
Gate = Vec_IntEntryLast(vGates);
if ( Gate == GateBuf )
{
iObj = Vec_WecEntryEntry( vFanins, Limit, 0 );
pObjNew = Abc_NtkObj( pNtk, Vec_IntEntry(vMap, iObj) );
// transfer load
if ( pMit )
Sfm_MitTransferLoad( pMit, pObjNew, pPivot );
// replace logic cone
Abc_ObjReplace( pPivot, pObjNew );
// update level
pObjNew->Level = 0;
Abc_NtkUpdateIncLevel_rec( pObjNew );
if ( vNewNodes )
Vec_IntPush( vNewNodes, Abc_ObjId(pObjNew) );
return pObjNew;
}
else if ( vNewNodes == NULL && Gate == GateInv )
{
// check if fanouts can be updated
Abc_Obj_t * pFanout;
Abc_ObjForEachFanout( pPivot, pFanout, i )
if ( !Abc_ObjIsNode(pFanout) || Sfm_LibFindComplInputGate(vFuncs, Mio_GateReadValue((Mio_Gate_t*)pFanout->pData), Abc_ObjFaninNum(pFanout), Abc_NodeFindFanin(pFanout, pPivot), NULL) == -1 )
break;
// update fanouts
if ( i == Abc_ObjFanoutNum(pPivot) )
{
Abc_ObjForEachFanout( pPivot, pFanout, i )
{
int iFanin = Abc_NodeFindFanin(pFanout, pPivot), iFaninNew = -1;
int iGate = Mio_GateReadValue((Mio_Gate_t*)pFanout->pData);
int iGateNew = Sfm_LibFindComplInputGate( vFuncs, iGate, Abc_ObjFaninNum(pFanout), iFanin, &iFaninNew );
assert( iGateNew >= 0 && iGateNew != iGate && iFaninNew >= 0 );
pFanout->pData = Vec_PtrEntry( vGateHandles, iGateNew );
//assert( iFanin == iFaninNew );
// swap fanins
if ( iFanin != iFaninNew )
{
int * pArray = Vec_IntArray( &pFanout->vFanins );
ABC_SWAP( int, pArray[iFanin], pArray[iFaninNew] );
}
}
iObj = Vec_WecEntryEntry( vFanins, Limit, 0 );
pObjNew = Abc_NtkObj( pNtk, Vec_IntEntry(vMap, iObj) );
Abc_ObjReplace( pPivot, pObjNew );
// update level
pObjNew->Level = 0;
Abc_NtkUpdateIncLevel_rec( pObjNew );
return pObjNew;
}
}
}
// introduce new gates
Vec_IntForEachEntryStart( vGates, Gate, i, Limit )
{
vLevel = Vec_WecEntry( vFanins, i );
pObjNew = Abc_NtkCreateNode( pNtk );
Vec_IntForEachEntry( vLevel, iObj, k )
Abc_ObjAddFanin( pObjNew, Abc_NtkObj(pNtk, Vec_IntEntry(vMap, iObj)) );
pObjNew->pData = Vec_PtrEntry( vGateHandles, Gate );
assert( Abc_ObjFaninNum(pObjNew) == Mio_GateReadPinNum((Mio_Gate_t *)pObjNew->pData) );
Vec_IntPush( vMap, Abc_ObjId(pObjNew) );
if ( vNewNodes )
Vec_IntPush( vNewNodes, Abc_ObjId(pObjNew) );
}
// transfer load
if ( pMit )
{
Sfm_MitTimingGrow( pMit );
Sfm_MitTransferLoad( pMit, pObjNew, pPivot );
}
// replace logic cone
Abc_ObjReplace( pPivot, pObjNew );
// update level
Abc_NtkForEachObjVecStart( vMap, pNtk, pObjNew, i, Limit )
Abc_NtkUpdateIncLevel_rec( pObjNew );
return pObjNew;
}
void Sfm_DecPrintStats( Sfm_Dec_t * p )
{
int i;
printf( "Node = %d. Try = %d. Change = %d. Const0 = %d. Const1 = %d. Buf = %d. Inv = %d. Gate = %d. AndOr = %d. Effort = %d. NoDec = %d.\n",
p->nTotalNodesBeg, p->nNodesTried, p->nNodesChanged, p->nNodesConst0, p->nNodesConst1, p->nNodesBuf, p->nNodesInv, p->nNodesResyn, p->nNodesAndOr, p->nEfforts, p->nNoDecs );
printf( "MaxDiv = %d. MaxWin = %d. AveDiv = %d. AveWin = %d. Calls = %d. (Sat = %d. Unsat = %d.) Over = %d. T/O = %d.\n",
p->nMaxDivs, p->nMaxWin, (int)(p->nAllDivs/Abc_MaxInt(1, p->nNodesTried)), (int)(p->nAllWin/Abc_MaxInt(1, p->nNodesTried)), p->nSatCalls, p->nSatCallsSat, p->nSatCallsUnsat, p->nSatCallsOver, p->nTimeOuts );
p->timeTotal = Abc_Clock() - p->timeStart;
p->timeOther = p->timeTotal - p->timeLib - p->timeWin - p->timeCnf - p->timeSat - p->timeTime;
ABC_PRTP( "Lib ", p->timeLib , p->timeTotal );
ABC_PRTP( "Win ", p->timeWin , p->timeTotal );
ABC_PRTP( "Cnf ", p->timeCnf , p->timeTotal );
ABC_PRTP( "Sat ", p->timeSat-p->timeEval, p->timeTotal );
ABC_PRTP( " Sat ", p->timeSatSat, p->timeTotal );
ABC_PRTP( " Unsat", p->timeSatUnsat, p->timeTotal );
ABC_PRTP( "Eval ", p->timeEval , p->timeTotal );
ABC_PRTP( "Timing", p->timeTime , p->timeTotal );
ABC_PRTP( "Other ", p->timeOther, p->timeTotal );
ABC_PRTP( "ALL ", p->timeTotal, p->timeTotal );
printf( "Cone sizes: " );
for ( i = 0; i <= SFM_SUPP_MAX; i++ )
if ( p->nLuckySizes[i] )
printf( "%d=%d ", i, p->nLuckySizes[i] );
printf( " " );
printf( "Gate sizes: " );
for ( i = 0; i <= SFM_SUPP_MAX; i++ )
if ( p->nLuckyGates[i] )
printf( "%d=%d ", i, p->nLuckyGates[i] );
printf( "\n" );
printf( "Reduction: " );
printf( "Nodes %6d out of %6d (%6.2f %%) ", p->nTotalNodesBeg-p->nTotalNodesEnd, p->nTotalNodesBeg, 100.0*(p->nTotalNodesBeg-p->nTotalNodesEnd)/Abc_MaxInt(1, p->nTotalNodesBeg) );
printf( "Edges %6d out of %6d (%6.2f %%) ", p->nTotalEdgesBeg-p->nTotalEdgesEnd, p->nTotalEdgesBeg, 100.0*(p->nTotalEdgesBeg-p->nTotalEdgesEnd)/Abc_MaxInt(1, p->nTotalEdgesBeg) );
printf( "\n" );
}
void Abc_NtkCountStats( Sfm_Dec_t * p, int Limit )
{
int Gate, nGates = Vec_IntSize(&p->vObjGates);
if ( nGates == Limit )
return;
Gate = Vec_IntEntryLast(&p->vObjGates);
if ( nGates > Limit + 1 )
p->nNodesResyn++;
else if ( Gate == p->GateConst0 )
p->nNodesConst0++;
else if ( Gate == p->GateConst1 )
p->nNodesConst1++;
else if ( Gate == p->GateBuffer )
p->nNodesBuf++;
else if ( Gate == p->GateInvert )
p->nNodesInv++;
else
p->nNodesResyn++;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Abc_Obj_t * Abc_NtkAreaOptOne( Sfm_Dec_t * p, int i )
{
abctime clk;
Abc_Ntk_t * pNtk = p->pNtk;
Sfm_Par_t * pPars = p->pPars;
Abc_Obj_t * pObj = Abc_NtkObj( p->pNtk, i );
int Limit, RetValue;
if ( pPars->nMffcMin > 1 && Abc_NodeMffcLabel(pObj) < pPars->nMffcMin )
return NULL;
if ( pPars->iNodeOne && i != pPars->iNodeOne )
return NULL;
if ( pPars->iNodeOne )
pPars->fVeryVerbose = (int)(i == pPars->iNodeOne);
p->nNodesTried++;
clk = Abc_Clock();
p->nDivs = Sfm_DecExtract( pNtk, pPars, pObj, &p->vObjRoots, &p->vObjGates, &p->vObjFanins, &p->vObjMap, &p->vGateTfi, &p->vGateTfo, &p->vObjMffc, &p->vObjInMffc, NULL, NULL );
p->timeWin += Abc_Clock() - clk;
if ( pPars->nWinSizeMax && pPars->nWinSizeMax < Vec_IntSize(&p->vObjGates) )
return NULL;
p->nMffc = Vec_IntSize(&p->vObjMffc);
p->AreaMffc = Sfm_DecMffcArea(pNtk, &p->vObjMffc);
p->nMaxDivs = Abc_MaxInt( p->nMaxDivs, p->nDivs );
p->nAllDivs += p->nDivs;
p->iTarget = pObj->iTemp;
Limit = Vec_IntSize( &p->vObjGates );
p->nMaxWin = Abc_MaxInt( p->nMaxWin, Limit );
p->nAllWin += Limit;
clk = Abc_Clock();
RetValue = Sfm_DecPrepareSolver( p );
p->timeCnf += Abc_Clock() - clk;
if ( !RetValue )
return NULL;
clk = Abc_Clock();
RetValue = Sfm_DecPeformDec2( p, pObj );
if ( pPars->fMoreEffort && RetValue < 0 )
{
int Var, i;
Vec_IntForEachEntryReverse( &p->vObjInMffc, Var, i )
{
p->iUseThis = Var;
RetValue = Sfm_DecPeformDec2( p, pObj );
p->iUseThis = -1;
if ( RetValue < 0 )
{
//printf( "Node %d: Not found among %d.\n", Abc_ObjId(pObj), Vec_IntSize(&p->vObjInMffc) );
}
else
{
p->nEfforts++;
if ( p->pPars->fVerbose )
{
//printf( "Node %5d: (%2d out of %2d) Gate=%s ", Abc_ObjId(pObj), i, Vec_IntSize(&p->vObjInMffc), Mio_GateReadName((Mio_Gate_t*)pObj->pData) );
//Dau_DsdPrintFromTruth( p->Copy, p->nSuppVars );
}
break;
}
}
}
if ( p->pPars->fVeryVerbose )
printf( "\n\n" );
p->timeSat += Abc_Clock() - clk;
if ( RetValue < 0 )
return NULL;
p->nNodesChanged++;
Abc_NtkCountStats( p, Limit );
return Sfm_DecInsert( pNtk, pObj, Limit, &p->vObjGates, &p->vObjFanins, &p->vObjMap, &p->vGateHands, p->GateBuffer, p->GateInvert, &p->vGateFuncs, NULL, p->pMit );
}
void Abc_NtkAreaOpt( Sfm_Dec_t * p )
{
Abc_Obj_t * pObj;
int i, nStop = Abc_NtkObjNumMax(p->pNtk);
Abc_NtkForEachNode( p->pNtk, pObj, i )
{
if ( i >= nStop || (p->pPars->nNodesMax && i > p->pPars->nNodesMax) )
break;
Abc_NtkAreaOptOne( p, i );
}
}
void Abc_NtkAreaOpt2( Sfm_Dec_t * p )
{
Abc_Obj_t * pObj, * pObjNew, * pFanin;
int i, k, nStop = Abc_NtkObjNumMax(p->pNtk);
Vec_Ptr_t * vFront = Vec_PtrAlloc( 1000 );
Abc_NtkForEachObj( p->pNtk, pObj, i )
assert( pObj->fMarkB == 0 );
// start the queue of nodes to be tried
Abc_NtkForEachCo( p->pNtk, pObj, i )
if ( Abc_ObjIsNode(Abc_ObjFanin0(pObj)) && !Abc_ObjFanin0(pObj)->fMarkB )
{
Abc_ObjFanin0(pObj)->fMarkB = 1;
Vec_PtrPush( vFront, Abc_ObjFanin0(pObj) );
}
// process nodes in this order
Vec_PtrForEachEntry( Abc_Obj_t *, vFront, pObj, i )
{
if ( Abc_ObjIsNone(pObj) )
continue;
pObjNew = Abc_NtkAreaOptOne( p, Abc_ObjId(pObj) );
if ( pObjNew != NULL )
{
if ( !Abc_ObjIsNode(pObjNew) || Abc_ObjFaninNum(pObjNew) == 0 || pObjNew->fMarkB )
continue;
if ( (int)Abc_ObjId(pObjNew) < nStop )
{
pObjNew->fMarkB = 1;
Vec_PtrPush( vFront, pObjNew );
continue;
}
}
else
pObjNew = pObj;
Abc_ObjForEachFanin( pObjNew, pFanin, k )
if ( Abc_ObjIsNode(pFanin) && Abc_ObjFaninNum(pObjNew) > 0 && !pFanin->fMarkB )
{
pFanin->fMarkB = 1;
Vec_PtrPush( vFront, pFanin );
}
}
Abc_NtkForEachObj( p->pNtk, pObj, i )
pObj->fMarkB = 0;
Vec_PtrFree( vFront );
}
void Abc_NtkDelayOpt( Sfm_Dec_t * p )
{
Abc_Ntk_t * pNtk = p->pNtk;
Sfm_Par_t * pPars = p->pPars; int n;
Abc_NtkCleanMarkABC( pNtk );
for ( n = 0; pPars->nNodesMax == 0 || n < pPars->nNodesMax; n++ )
{
Abc_Obj_t * pObj, * pObjNew; abctime clk;
int i = 0, Limit, RetValue;
// collect nodes
if ( pPars->iNodeOne )
Vec_IntFill( &p->vCands, 1, pPars->iNodeOne );
else if ( p->pTim && !Sfm_TimPriorityNodes(p->pTim, &p->vCands, p->pPars->nTimeWin) )
break;
else if ( p->pMit && !Sfm_MitPriorityNodes(p->pMit, &p->vCands, p->pPars->nTimeWin) )
break;
// try improving delay for the nodes according to the priority
Abc_NtkForEachObjVec( &p->vCands, p->pNtk, pObj, i )
{
int OldId = Abc_ObjId(pObj);
int DelayOld = Sfm_ManReadObjDelay(p, OldId);
assert( pObj->fMarkA == 0 );
p->nNodesTried++;
clk = Abc_Clock();
p->nDivs = Sfm_DecExtract( pNtk, pPars, pObj, &p->vObjRoots, &p->vObjGates, &p->vObjFanins, &p->vObjMap, &p->vGateTfi, &p->vGateTfo, &p->vObjMffc, &p->vObjInMffc, p->pTim, p->pMit );
p->timeWin += Abc_Clock() - clk;
if ( p->nDivs < 2 || (pPars->nWinSizeMax && pPars->nWinSizeMax < Vec_IntSize(&p->vObjGates)) )
{
pObj->fMarkA = 1;
continue;
}
p->nMffc = Vec_IntSize(&p->vObjMffc);
p->AreaMffc = Sfm_DecMffcArea(pNtk, &p->vObjMffc);
p->nMaxDivs = Abc_MaxInt( p->nMaxDivs, p->nDivs );
p->nAllDivs += p->nDivs;
p->iTarget = pObj->iTemp;
Limit = Vec_IntSize( &p->vObjGates );
p->nMaxWin = Abc_MaxInt( p->nMaxWin, Limit );
p->nAllWin += Limit;
clk = Abc_Clock();
RetValue = Sfm_DecPrepareSolver( p );
p->timeCnf += Abc_Clock() - clk;
if ( !RetValue )
{
pObj->fMarkA = 1;
continue;
}
clk = Abc_Clock();
RetValue = Sfm_DecPeformDec3( p, pObj );
if ( pPars->fMoreEffort && RetValue < 0 )
{
int Var, i;
Vec_IntForEachEntryReverse( &p->vObjInMffc, Var, i )
{
p->iUseThis = Var;
RetValue = Sfm_DecPeformDec3( p, pObj );
p->iUseThis = -1;
if ( RetValue < 0 )
{
//printf( "Node %d: Not found among %d.\n", Abc_ObjId(pObj), Vec_IntSize(&p->vObjInMffc) );
}
else
{
p->nEfforts++;
if ( p->pPars->fVerbose )
{
//printf( "Node %5d: (%2d out of %2d) Gate=%s ", Abc_ObjId(pObj), i, Vec_IntSize(&p->vObjInMffc), Mio_GateReadName((Mio_Gate_t*)pObj->pData) );
//Dau_DsdPrintFromTruth( p->Copy, p->nSuppVars );
}
break;
}
}
}
if ( p->pPars->fVeryVerbose )
printf( "\n\n" );
p->timeSat += Abc_Clock() - clk;
if ( RetValue < 0 )
{
pObj->fMarkA = 1;
continue;
}
assert( Vec_IntSize(&p->vObjGates) - Limit > 0 );
assert( Vec_IntSize(&p->vObjGates) - Limit <= 2 );
p->nNodesChanged++;
Abc_NtkCountStats( p, Limit );
// reduce load due to removed MFFC
if ( p->pMit ) Sfm_MitUpdateLoad( p->pMit, &p->vGateMffc, 0 ); // assuming &p->vGateMffc contains MFFC
Sfm_DecInsert( pNtk, pObj, Limit, &p->vObjGates, &p->vObjFanins, &p->vObjMap, &p->vGateHands, p->GateBuffer, p->GateInvert, &p->vGateFuncs, &p->vNewNodes, p->pMit );
// increase load due to added new nodes
if ( p->pMit ) Sfm_MitUpdateLoad( p->pMit, &p->vNewNodes, 1 ); // assuming &p->vNewNodes contains new nodes
clk = Abc_Clock();
if ( p->pMit )
Sfm_MitUpdateTiming( p->pMit, &p->vNewNodes );
else
Sfm_TimUpdateTiming( p->pTim, &p->vNewNodes );
p->timeTime += Abc_Clock() - clk;
pObjNew = Abc_NtkObj( pNtk, Abc_NtkObjNumMax(pNtk)-1 );
assert( p->pMit || p->DelayMin == 0 || p->DelayMin == Sfm_ManReadObjDelay(p, Abc_ObjId(pObjNew)) );
// report
if ( pPars->fDelayVerbose )
printf( "Node %5d %5d : I =%3d. Cand = %5d (%6.2f %%) Old =%8.2f. New =%8.2f. Final =%8.2f. WNS =%8.2f.\n",
OldId, Abc_NtkObjNumMax(p->pNtk), i, Vec_IntSize(&p->vCands), 100.0 * Vec_IntSize(&p->vCands) / Abc_NtkNodeNum(p->pNtk),
Scl_Int2Flt(DelayOld), Scl_Int2Flt(Sfm_ManReadObjDelay(p, Abc_ObjId(pObjNew))),
Scl_Int2Flt(Sfm_ManReadNtkDelay(p)), Scl_Int2Flt(Sfm_ManReadNtkMinSlack(p)) );
break;
}
if ( pPars->iNodeOne )
break;
}
Abc_NtkCleanMarkABC( pNtk );
}
void Abc_NtkPerformMfs3( Abc_Ntk_t * pNtk, Sfm_Par_t * pPars )
{
Sfm_Dec_t * p = Sfm_DecStart( pPars, (Mio_Library_t *)pNtk->pManFunc, pNtk );
if ( pPars->fVerbose )
{
printf( "Remapping parameters: " );
if ( pPars->nTfoLevMax )
printf( "TFO = %d. ", pPars->nTfoLevMax );
if ( pPars->nTfiLevMax )
printf( "TFI = %d. ", pPars->nTfiLevMax );
if ( pPars->nFanoutMax )
printf( "FanMax = %d. ", pPars->nFanoutMax );
if ( pPars->nWinSizeMax )
printf( "WinMax = %d. ", pPars->nWinSizeMax );
if ( pPars->nBTLimit )
printf( "Confl = %d. ", pPars->nBTLimit );
if ( pPars->nMffcMin && pPars->fArea )
printf( "MffcMin = %d. ", pPars->nMffcMin );
if ( pPars->nMffcMax && pPars->fArea )
printf( "MffcMax = %d. ", pPars->nMffcMax );
if ( pPars->nDecMax )
printf( "DecMax = %d. ", pPars->nDecMax );
if ( pPars->iNodeOne )
printf( "Pivot = %d. ", pPars->iNodeOne );
if ( !pPars->fArea )
printf( "Win = %d. ", pPars->nTimeWin );
if ( !pPars->fArea )
printf( "Delta = %.2f ps. ", Scl_Int2Flt(p->DeltaCrit) );
if ( pPars->fArea )
printf( "0-cost = %s. ", pPars->fZeroCost ? "yes" : "no" );
printf( "Effort = %s. ", pPars->fMoreEffort ? "yes" : "no" );
printf( "Sim = %s. ", pPars->fUseSim ? "yes" : "no" );
printf( "\n" );
}
// preparation steps
Abc_NtkLevel( pNtk );
if ( p->pPars->fUseSim )
Sfm_NtkSimulate( pNtk );
// record statistics
if ( pPars->fVerbose ) p->nTotalNodesBeg = Abc_NtkNodeNum(pNtk);
if ( pPars->fVerbose ) p->nTotalEdgesBeg = Abc_NtkGetTotalFanins(pNtk);
// perform optimization
if ( pPars->fArea )
{
if ( pPars->fAreaRev )
Abc_NtkAreaOpt2( p );
else
Abc_NtkAreaOpt( p );
}
else
Abc_NtkDelayOpt( p );
// record statistics
if ( pPars->fVerbose ) p->nTotalNodesEnd = Abc_NtkNodeNum(pNtk);
if ( pPars->fVerbose ) p->nTotalEdgesEnd = Abc_NtkGetTotalFanins(pNtk);
// print stats and quit
if ( pPars->fVerbose )
Sfm_DecPrintStats( p );
if ( pPars->fLibVerbose )
Sfm_LibPrint( p->pLib );
Sfm_DecStop( p );
if ( pPars->fArea )
{
extern void Abc_NtkChangePerform( Abc_Ntk_t * pNtk, int fVerbose );
Abc_NtkChangePerform( pNtk, pPars->fVerbose );
}
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
| 45,891 |
66,985 | <reponame>techAi007/spring-boot<filename>spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/jetty/AbstractJettyMetricsBinder.java
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.metrics.web.jetty;
import org.eclipse.jetty.server.Server;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.boot.web.context.WebServerApplicationContext;
import org.springframework.boot.web.embedded.jetty.JettyWebServer;
import org.springframework.boot.web.server.WebServer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
/**
* Base class for binding Jetty metrics in response to an {@link ApplicationStartedEvent}.
*
* @author <NAME>
* @since 2.6.0
*/
public abstract class AbstractJettyMetricsBinder implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
Server server = findServer(event.getApplicationContext());
if (server != null) {
bindMetrics(server);
}
}
private Server findServer(ApplicationContext applicationContext) {
if (applicationContext instanceof WebServerApplicationContext) {
WebServer webServer = ((WebServerApplicationContext) applicationContext).getWebServer();
if (webServer instanceof JettyWebServer) {
return ((JettyWebServer) webServer).getServer();
}
}
return null;
}
protected abstract void bindMetrics(Server server);
}
| 602 |
852 | #include "CondCore/DBCommon/interface/DBWriter.h"
#include "CondCore/IOVService/interface/IOV.h"
#include "CondCore/MetaDataService/interface/MetaData.h"
#include "FWCore/Framework/interface/IOVSyncValue.h"
#include "SealKernel/Service.h"
#include "POOLCore/POOLContext.h"
#include "SealKernel/Context.h"
#include <string>
#include <iostream>
#include "CalibCalorimetry/HcalAlgos/interface/HcalDbServiceHardcode.h"
#include "CondFormats/HcalObjects/interface/HcalPedestals.h"
#include "CondFormats/HcalObjects/interface/HcalPedestalWidths.h"
#include "CondFormats/HcalObjects/interface/HcalGains.h"
#include "CondFormats/HcalObjects/interface/HcalGainWidths.h"
#include "DataFormats/HcalDetId/interface/HcalDetId.h"
#include "Geometry/CaloTopology/interface/HcalTopology.h"
bool validHcalCell (const HcalDetId& fCell) {
if (fCell.iphi () <=0) return false;
int absEta = abs (fCell.ieta ());
int phi = fCell.iphi ();
int depth = fCell.depth ();
HcalSubdetector det = fCell.subdet ();
// phi ranges
if ((absEta >= 40 && phi > 18) ||
(absEta >= 21 && phi > 36) ||
phi > 72) return false;
if (absEta <= 0) return false;
else if (absEta <= 14) return (depth == 1 || depth == 4) && det == HcalBarrel;
else if (absEta == 15) return (depth == 1 || depth == 2 || depth == 4) && det == HcalBarrel;
else if (absEta == 16) return depth >= 1 && depth <= 2 && det == HcalBarrel || depth == 3 && det == HcalEndcap;
else if (absEta == 17) return depth == 1 && det == HcalEndcap;
else if (absEta <= 26) return depth >= 1 && depth <= 2 && det == HcalEndcap;
else if (absEta <= 28) return depth >= 1 && depth <= 3 && det == HcalEndcap;
else if (absEta == 29) return depth >= 1 && depth <= 2 && (det == HcalEndcap || det == HcalForward);
else if (absEta <= 41) return depth >= 1 && depth <= 2 && det == HcalForward;
else return false;
}
int main (int argn, char** argv){
std::string contact ("sqlite_file:hcal_default_calib.db");
if (argn > 1) {
contact = std::string (argv [1]);
}
std::cout << " Using DB connection: " << contact << std::endl;
// std::string contact("oracle://cmscald/ratnikov");
// std::string contact("sqlite_file:hcal_default_calib.db");
pool::POOLContext::loadComponent( "SEAL/Services/MessageService" );
pool::POOLContext::loadComponent( "POOL/Services/EnvironmentAuthenticationService" );
cond::DBWriter w(contact);
w.startTransaction();
HcalPedestals* pedestals=new HcalPedestals;
HcalPedestalWidths* pedestalWidths=new HcalPedestalWidths;
HcalGains* gains=new HcalGains;
HcalGainWidths* gainWidths=new HcalGainWidths;
int counter = 0;
HcalTopology topology;
for (int eta = -50; eta < 50; eta++) {
for (int phi = 0; phi < 100; phi++) {
for (int depth = 1; depth < 5; depth++) {
for (int det = 1; det < 5; det++) {
HcalDetId cell ((HcalSubdetector) det, eta, phi, depth);
if (topology.valid(cell)) {
uint32_t cellId = cell.rawId();
HcalDbServiceHardcode srv;
pedestals->addValue (cellId, srv.pedestals (cell));
pedestalWidths->addValue (cellId, srv.pedestalErrors (cell));
gains->addValue (cellId, srv.gains (cell));
gainWidths->addValue (cellId, srv.gainErrors (cell));
counter++;
std::cout << counter << " Added channel ID " << cellId
<< " eta/phi/depth/det: " << eta << '/' << phi << '/' << depth << '/' << det << std::endl;
}
}
}
}
}
pedestals->sort ();
pedestalWidths->sort ();
gains->sort ();
gainWidths->sort ();
std::string pedtok=w.write<HcalPedestals> (pedestals, "HcalPedestals");//pool::Ref takes the ownership of ped1
std::string pedWtok=w.write<HcalPedestalWidths> (pedestalWidths, "HcalPedestalWidths");//pool::Ref takes the ownership of ped1
std::string gaintok=w.write<HcalGains> (gains, "HcalGains");//pool::Ref takes the ownership of ped1
std::string gainWtok=w.write<HcalGainWidths> (gainWidths, "HcalGainWidths");//pool::Ref takes the ownership of ped1
cond::IOV* iov=new cond::IOV;
// this is cludge until IOV parameters are defined unsigned consistently with IOVSyncValue
edm::IOVSyncValue endtime = edm::IOVSyncValue (edm::EventID(0x7FFFFFFF, 0x7FFFFFFF), edm::Timestamp::endOfTime());
iov->iov.insert (std::make_pair (endtime.eventID().run(), pedtok));
std::string iovToken1 = w.write<cond::IOV> (iov,"IOV");
iov=new cond::IOV;
iov->iov.insert (std::make_pair (endtime.eventID().run(), pedWtok));
std::string iovToken2 = w.write<cond::IOV> (iov,"IOV");
iov=new cond::IOV;
iov->iov.insert (std::make_pair (endtime.eventID().run(), gaintok));
std::string iovToken3 = w.write<cond::IOV> (iov,"IOV");
iov=new cond::IOV;
iov->iov.insert (std::make_pair (endtime.eventID().run(), gainWtok));
std::string iovToken4 = w.write<cond::IOV> (iov,"IOV");
std::cout << "\n\n==============================================" << std::endl;
std::cout << "Pedestals token -> " << pedtok << std::endl;
std::cout << "Pedestal Widths token-> " << pedWtok << std::endl;
std::cout << "Gains token -> " << gaintok << std::endl;
std::cout << "GainWidths token -> " << gainWtok << std::endl;
std::cout << "IOV tokens -> " << iovToken1 << std::endl
<< " " << iovToken2 << std::endl
<< " " << iovToken3 << std::endl
<< " " << iovToken4 << std::endl;
w.commitTransaction();
//register the iovToken to the metadata service
cond::MetaData metadata_svc(contact);
metadata_svc.addMapping("HcalPedestals_default_v1", iovToken1);
metadata_svc.addMapping("HcalPedestalWidths_default_v1", iovToken2);
metadata_svc.addMapping("HcalGains_default_v1", iovToken3);
metadata_svc.addMapping("HcalGainWidths_default_v1", iovToken4);
}
| 2,320 |
653 | <filename>llvm/tools/llvm-reduce/deltas/ReduceSpecialGlobals.cpp
//===- ReduceSpecialGlobals.cpp - Specialized Delta Pass ------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements a function which calls the Generic Delta pass in order
// to reduce special globals, like @llvm.used, in the provided Module.
//
// For more details about special globals, see
// https://llvm.org/docs/LangRef.html#intrinsic-global-variables
//
//===----------------------------------------------------------------------===//
#include "ReduceSpecialGlobals.h"
#include "Delta.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/GlobalValue.h"
using namespace llvm;
static StringRef SpecialGlobalNames[] = {"llvm.used", "llvm.compiler.used"};
/// Removes all special globals aren't inside any of the
/// desired Chunks.
static void extractSpecialGlobalsFromModule(Oracle &O, Module &Program) {
for (StringRef Name : SpecialGlobalNames) {
if (auto *Used = Program.getNamedGlobal(Name)) {
Used->replaceAllUsesWith(UndefValue::get(Used->getType()));
Used->eraseFromParent();
}
}
}
/// Counts the amount of special globals and prints their
/// respective name & index
static int countSpecialGlobals(Module &Program) {
// TODO: Silence index with --quiet flag
errs() << "----------------------------\n";
errs() << "Special Globals Index Reference:\n";
int Count = 0;
for (StringRef Name : SpecialGlobalNames) {
if (auto *Used = Program.getNamedGlobal(Name))
errs() << "\t" << ++Count << ": " << Used->getName() << "\n";
}
errs() << "----------------------------\n";
return Count;
}
void llvm::reduceSpecialGlobalsDeltaPass(TestRunner &Test) {
errs() << "*** Reducing Special Globals ...\n";
int Functions = countSpecialGlobals(Test.getProgram());
runDeltaPass(Test, Functions, extractSpecialGlobalsFromModule);
errs() << "----------------------------\n";
}
| 677 |
611 | // DejaLu
// Copyright (c) 2015 <NAME>. All rights reserved.
#ifndef __dejalu__HMMailDBAddFolderOperation__
#define __dejalu__HMMailDBAddFolderOperation__
#include <MailCore/MailCore.h>
#include "HMMailDBOperation.h"
#ifdef __cplusplus
namespace hermes {
class MailDBAddFolderOperation : public MailDBOperation {
public:
MailDBAddFolderOperation();
virtual ~MailDBAddFolderOperation();
virtual mailcore::String * path();
virtual void setPath(mailcore::String * path);
virtual int64_t folderID();
// Implements Operation.
virtual void main();
private:
mailcore::String * mPath;
int64_t mFolderID;
};
}
#endif
#endif /* defined(__dejalu__HMMailDBAddFolderOperation__) */
| 350 |
679 | <filename>main/odk/examples/DevelopersGuide/Database/CodeSamples.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.
*
*************************************************************/
import java.io.*;
import com.sun.star.comp.helper.RegistryServiceFactory;
import com.sun.star.comp.servicemanager.ServiceManager;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XSingleServiceFactory;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lang.XComponent;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.XNameAccess;
import com.sun.star.container.XNameContainer;
import com.sun.star.sdbc.*;
import com.sun.star.sdb.*;
import com.sun.star.sdbcx.*;
import com.sun.star.frame.*;
public class CodeSamples
{
public static XComponentContext xContext;
public static XMultiComponentFactory xMCF;
public static void main(String argv[]) throws java.lang.Exception
{
try {
// get the remote office component context
xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
System.out.println("Connected to a running office ...");
xMCF = xContext.getServiceManager();
}
catch(Exception e) {
System.err.println("ERROR: can't get a component context from a running office ...");
e.printStackTrace();
System.exit(1);
}
try{
createQuerydefinition( );
printQueryColumnNames( );
XConnection con = openConnectionWithDriverManager();
if ( con != null ) {
{
SalesMan sm = new SalesMan( con );
try {
sm.dropSalesManTable( ); // doesn't matter here
}
catch(com.sun.star.uno.Exception e)
{
}
sm.createSalesManTable( );
sm.insertDataIntoSalesMan( );
sm.updateSalesMan( );
sm.retrieveSalesManData( );
}
{
Sales sm = new Sales( con );
try {
sm.dropSalesTable( ); // doesn't matter here
}
catch(com.sun.star.uno.Exception e)
{
}
sm.createSalesTable( );
sm.insertDataIntoSales( );
sm.updateSales( );
sm.retrieveSalesData( );
sm.displayColumnNames( );
}
displayTableStructure( con );
}
// printDataSources();
}
catch(Exception e)
{
System.err.println(e);
e.printStackTrace();
}
System.exit(0);
}
// check if the connection is not null aand dispose it later on.
public static void checkConnection(XConnection con) throws com.sun.star.uno.Exception
{
if(con != null)
{
System.out.println("Connection was created!");
// now we dispose the connection to close it
XComponent xComponent = (XComponent)UnoRuntime.queryInterface(XComponent.class,con);
if(xComponent != null)
{
// connections must be disposed
xComponent.dispose();
System.out.println("Connection disposed!");
}
}
else
System.out.println("Connection could not be created!");
}
// uses the driver manager to create a new connection and dispose it.
public static XConnection openConnectionWithDriverManager() throws com.sun.star.uno.Exception
{
XConnection con = null;
// create the DriverManager
Object driverManager =
xMCF.createInstanceWithContext("com.sun.star.sdbc.DriverManager",
xContext);
// query for the interface
com.sun.star.sdbc.XDriverManager xDriverManager;
xDriverManager = (XDriverManager)UnoRuntime.queryInterface(XDriverManager.class,driverManager);
if(xDriverManager != null)
{
// first create the needed url
String url = "jdbc:mysql://localhost:3306/TestTables";
// second create the necessary properties
com.sun.star.beans.PropertyValue [] props = new com.sun.star.beans.PropertyValue[]
{
new com.sun.star.beans.PropertyValue("user",0,"test1",com.sun.star.beans.PropertyState.DIRECT_VALUE),
new com.sun.star.beans.PropertyValue("password",0,"<PASSWORD>",com.sun.star.beans.PropertyState.DIRECT_VALUE),
new com.sun.star.beans.PropertyValue("JavaDriverClass",0,"org.gjt.mm.mysql.Driver",com.sun.star.beans.PropertyState.DIRECT_VALUE)
};
// now create a connection to mysql
con = xDriverManager.getConnectionWithInfo(url,props);
}
return con;
}
// uses the driver directly to create a new connection and dispose it.
public static XConnection openConnectionWithDriver() throws com.sun.star.uno.Exception
{
XConnection con = null;
// create the Driver with the implementation name
Object aDriver =
xMCF.createInstanceWithContext("org.openoffice.comp.drivers.MySQL.Driver",
xContext);
// query for the interface
com.sun.star.sdbc.XDriver xDriver;
xDriver = (XDriver)UnoRuntime.queryInterface(XDriver.class,aDriver);
if(xDriver != null)
{
// first create the needed url
String url = "jdbc:mysql://localhost:3306/TestTables";
// second create the necessary properties
com.sun.star.beans.PropertyValue [] props = new com.sun.star.beans.PropertyValue[]
{
new com.sun.star.beans.PropertyValue("user",0,"test1",com.sun.star.beans.PropertyState.DIRECT_VALUE),
new com.sun.star.beans.PropertyValue("password",0,"<PASSWORD>",com.sun.star.beans.PropertyState.DIRECT_VALUE),
new com.sun.star.beans.PropertyValue("JavaDriverClass",0,"org.gjt.mm.mysql.Driver",com.sun.star.beans.PropertyState.DIRECT_VALUE)
};
// now create a connection to mysql
con = xDriver.connect(url,props);
}
return con;
}
// print all available datasources
public static void printDataSources() throws com.sun.star.uno.Exception
{
// create a DatabaseContext and print all DataSource names
XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface(
XNameAccess.class,
xMCF.createInstanceWithContext("com.sun.star.sdb.DatabaseContext",
xContext));
String aNames [] = xNameAccess.getElementNames();
for(int i=0;i<aNames.length;++i)
System.out.println(aNames[i]);
}
// displays the structure of the first table
public static void displayTableStructure(XConnection con) throws com.sun.star.uno.Exception
{
XDatabaseMetaData dm = con.getMetaData();
XResultSet rsTables = dm.getTables(null,"%","SALES",null);
XRow rowTB = (XRow)UnoRuntime.queryInterface(XRow.class, rsTables);
while ( rsTables.next() )
{
String catalog = rowTB.getString( 1 );
if ( rowTB.wasNull() )
catalog = null;
String schema = rowTB.getString( 2 );
if ( rowTB.wasNull() )
schema = null;
String table = rowTB.getString( 3 );
String type = rowTB.getString( 4 );
System.out.println("Catalog: " + catalog + " Schema: " + schema + " Table: " + table + " Type: " + type);
System.out.println("------------------ Columns ------------------");
XResultSet rsColumns = dm.getColumns(catalog,schema,table,"%");
XRow rowCL = (XRow)UnoRuntime.queryInterface(XRow.class, rsColumns);
while ( rsColumns.next() )
{
System.out.println("Column: " + rowCL.getString( 4 ) + " Type: " + rowCL.getInt( 5 ) + " TypeName: " + rowCL.getString( 6 ) );
}
}
}
// quote the given name
public static String quoteTableName(XConnection con, String sCatalog, String sSchema, String sTable) throws com.sun.star.uno.Exception
{
XDatabaseMetaData dbmd = con.getMetaData();
String sQuoteString = dbmd.getIdentifierQuoteString();
String sSeparator = ".";
String sComposedName = "";
String sCatalogSep = dbmd.getCatalogSeparator();
if (0 != sCatalog.length() && dbmd.isCatalogAtStart() && 0 != sCatalogSep.length())
{
sComposedName += sCatalog;
sComposedName += dbmd.getCatalogSeparator();
}
if (0 != sSchema.length())
{
sComposedName += sSchema;
sComposedName += sSeparator;
sComposedName += sTable;
}
else
{
sComposedName += sTable;
}
if (0 != sCatalog.length() && !dbmd.isCatalogAtStart() && 0 != sCatalogSep.length())
{
sComposedName += dbmd.getCatalogSeparator();
sComposedName += sCatalog;
}
return sComposedName;
}
// creates a new query definition
public static void createQuerydefinition() throws com.sun.star.uno.Exception
{
XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface(
XNameAccess.class,
xMCF.createInstanceWithContext("com.sun.star.sdb.DatabaseContext",
xContext));
// we use the first datasource
XQueryDefinitionsSupplier xQuerySup = (XQueryDefinitionsSupplier)
UnoRuntime.queryInterface(XQueryDefinitionsSupplier.class,
xNameAccess.getByName( "Bibliography" ));
XNameAccess xQDefs = xQuerySup.getQueryDefinitions();
// create new query definition
XSingleServiceFactory xSingleFac = (XSingleServiceFactory)
UnoRuntime.queryInterface(XSingleServiceFactory.class, xQDefs);
XPropertySet xProp = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class,xSingleFac.createInstance());
xProp.setPropertyValue("Command","SELECT * FROM biblio");
xProp.setPropertyValue("EscapeProcessing",new Boolean(true));
XNameContainer xCont = (XNameContainer) UnoRuntime.queryInterface(XNameContainer.class, xQDefs);
try
{
if ( xCont.hasByName("Query1") )
xCont.removeByName("Query1");
}
catch(com.sun.star.uno.Exception e)
{}
xCont.insertByName("Query1",xProp);
XDocumentDataSource xDs = (XDocumentDataSource)UnoRuntime.queryInterface(XDocumentDataSource.class, xQuerySup);
XStorable xStore = (XStorable)UnoRuntime.queryInterface(XStorable.class,xDs.getDatabaseDocument());
xStore.store();
}
// prints all column names from Query1
public static void printQueryColumnNames() throws com.sun.star.uno.Exception
{
XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface(
XNameAccess.class,
xMCF.createInstanceWithContext("com.sun.star.sdb.DatabaseContext",
xContext));
// we use the first datasource
XDataSource xDS = (XDataSource)UnoRuntime.queryInterface(
XDataSource.class, xNameAccess.getByName( "Bibliography" ));
XConnection con = xDS.getConnection("","");
XQueriesSupplier xQuerySup = (XQueriesSupplier)
UnoRuntime.queryInterface(XQueriesSupplier.class, con);
XNameAccess xQDefs = xQuerySup.getQueries();
XColumnsSupplier xColsSup = (XColumnsSupplier) UnoRuntime.queryInterface(
XColumnsSupplier.class,xQDefs.getByName("Query1"));
XNameAccess xCols = xColsSup.getColumns();
String aNames [] = xCols.getElementNames();
for(int i=0;i<aNames.length;++i)
System.out.println(aNames[i]);
}
}
| 4,538 |
2,151 | <gh_stars>1000+
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import flask
import mock
import os
import ssl
import threading
import time
import unittest
from Crypto import PublicKey
from jwkest import ecc
from jwkest import jwk
from test import token_utils
from google.api import auth
from google.api.auth import suppliers
from google.api.auth import tokens
class IntegrationTest(unittest.TestCase):
_CURRENT_TIME = int(time.time())
_PORT = 8080
_ISSUER = "https://localhost:%d" % _PORT
_PROVIDER_ID = "localhost"
_INVALID_X509_PATH = "invalid-x509"
_JWKS_PATH = "jwks"
_SERVICE_NAME = "<EMAIL>"
_X509_PATH = "x509"
_JWT_CLAIMS = {
"aud": ["https://aud1.local.host", "https://aud2.local.host"],
"exp": _CURRENT_TIME + 60,
"email": "<EMAIL>",
"iss": _ISSUER,
"sub": "subject-id"
}
_ec_jwk = jwk.ECKey(use="sig").load_key(ecc.P256)
_rsa_key = jwk.RSAKey(use="sig").load_key(PublicKey.RSA.generate(1024))
_ec_jwk.kid = "ec-key-id"
_rsa_key.kid = "rsa-key-id"
_mock_timer = mock.MagicMock()
_jwks = jwk.KEYS()
_jwks._keys.append(_ec_jwk)
_jwks._keys.append(_rsa_key)
_AUTH_TOKEN = token_utils.generate_auth_token(_JWT_CLAIMS, _jwks._keys,
alg="RS256", kid=_rsa_key.kid)
@classmethod
def setUpClass(cls):
dirname = os.path.dirname(os.path.realpath(__file__))
cls._cert_file = os.path.join(dirname, "ssl.cert")
cls._key_file = os.path.join(dirname, "ssl.key")
os.environ["REQUESTS_CA_BUNDLE"] = cls._cert_file
rest_server = cls._RestServer()
rest_server.start()
def setUp(self):
self._provider_ids = {}
self._configs = {}
self._authenticator = auth.create_authenticator(self._provider_ids,
self._configs)
self._auth_info = mock.MagicMock()
self._auth_info.is_provider_allowed.return_value = True
self._auth_info.get_allowed_audiences.return_value = [
"https://aud1.local.host"
]
def test_verify_auth_token_with_jwks(self):
url = get_url(IntegrationTest._JWKS_PATH)
self._provider_ids[self._ISSUER] = self._PROVIDER_ID
self._configs[IntegrationTest._ISSUER] = suppliers.IssuerUriConfig(False,
url)
user_info = self._authenticator.authenticate(IntegrationTest._AUTH_TOKEN,
self._auth_info,
IntegrationTest._SERVICE_NAME)
self._assert_user_info_equals(tokens.UserInfo(IntegrationTest._JWT_CLAIMS),
user_info)
def test_authenticate_auth_token_with_bad_signature(self):
new_rsa_key = jwk.RSAKey(use="sig").load_key(PublicKey.RSA.generate(2048))
kid = IntegrationTest._rsa_key.kid
new_rsa_key.kid = kid
new_jwks = jwk.KEYS()
new_jwks._keys.append(new_rsa_key)
auth_token = token_utils.generate_auth_token(IntegrationTest._JWT_CLAIMS,
new_jwks._keys, alg="RS256",
kid=kid)
url = get_url(IntegrationTest._JWKS_PATH)
self._provider_ids[self._ISSUER] = self._PROVIDER_ID
self._configs[IntegrationTest._ISSUER] = suppliers.IssuerUriConfig(False,
url)
message = "Signature verification failed"
with self.assertRaisesRegexp(suppliers.UnauthenticatedException, message):
self._authenticator.authenticate(auth_token, self._auth_info,
IntegrationTest._SERVICE_NAME)
def test_verify_auth_token_with_x509(self):
url = get_url(IntegrationTest._X509_PATH)
self._provider_ids[self._ISSUER] = self._PROVIDER_ID
self._configs[IntegrationTest._ISSUER] = suppliers.IssuerUriConfig(False,
url)
user_info = self._authenticator.authenticate(IntegrationTest._AUTH_TOKEN,
self._auth_info,
IntegrationTest._SERVICE_NAME)
self._assert_user_info_equals(tokens.UserInfo(IntegrationTest._JWT_CLAIMS),
user_info)
def test_verify_auth_token_with_invalid_x509(self):
url = get_url(IntegrationTest._INVALID_X509_PATH)
self._provider_ids[self._ISSUER] = self._PROVIDER_ID
self._configs[IntegrationTest._ISSUER] = suppliers.IssuerUriConfig(False,
url)
message = "Cannot load X.509 certificate"
with self.assertRaisesRegexp(suppliers.UnauthenticatedException, message):
self._authenticator.authenticate(IntegrationTest._AUTH_TOKEN,
self._auth_info,
IntegrationTest._SERVICE_NAME)
def test_openid_discovery(self):
self._provider_ids[self._ISSUER] = self._PROVIDER_ID
self._configs[IntegrationTest._ISSUER] = suppliers.IssuerUriConfig(True,
None)
user_info = self._authenticator.authenticate(IntegrationTest._AUTH_TOKEN,
self._auth_info,
IntegrationTest._SERVICE_NAME)
self._assert_user_info_equals(tokens.UserInfo(IntegrationTest._JWT_CLAIMS),
user_info)
def test_openid_discovery_failed(self):
self._provider_ids[self._ISSUER] = self._PROVIDER_ID
self._configs[IntegrationTest._ISSUER] = suppliers.IssuerUriConfig(False,
None)
message = ("Cannot find the `jwks_uri` for issuer %s" %
IntegrationTest._ISSUER)
with self.assertRaisesRegexp(suppliers.UnauthenticatedException, message):
self._authenticator.authenticate(IntegrationTest._AUTH_TOKEN,
self._auth_info,
IntegrationTest._SERVICE_NAME)
def test_authenticate_with_malformed_auth_code(self):
with self.assertRaisesRegexp(suppliers.UnauthenticatedException,
"Cannot decode the auth token"):
self._authenticator.authenticate("invalid-auth-code", self._auth_info,
IntegrationTest._SERVICE_NAME)
def test_authenticate_with_disallowed_issuer(self):
url = get_url(IntegrationTest._JWKS_PATH)
self._configs[IntegrationTest._ISSUER] = suppliers.IssuerUriConfig(False,
url)
message = "Unknown issuer: " + self._ISSUER
with self.assertRaisesRegexp(suppliers.UnauthenticatedException, message):
self._authenticator.authenticate(IntegrationTest._AUTH_TOKEN,
self._auth_info,
IntegrationTest._SERVICE_NAME)
def test_authenticate_with_unknown_issuer(self):
message = ("Cannot find the `jwks_uri` for issuer %s: "
"either the issuer is unknown") % IntegrationTest._ISSUER
with self.assertRaisesRegexp(suppliers.UnauthenticatedException, message):
self._authenticator.authenticate(IntegrationTest._AUTH_TOKEN,
self._auth_info,
IntegrationTest._SERVICE_NAME)
def test_authenticate_with_invalid_audience(self):
url = get_url(IntegrationTest._JWKS_PATH)
self._provider_ids[self._ISSUER] = self._PROVIDER_ID
self._configs[IntegrationTest._ISSUER] = suppliers.IssuerUriConfig(False,
url)
self._auth_info.get_allowed_audiences.return_value = []
with self.assertRaisesRegexp(suppliers.UnauthenticatedException,
"Audiences not allowed"):
self._authenticator.authenticate(IntegrationTest._AUTH_TOKEN,
self._auth_info,
IntegrationTest._SERVICE_NAME)
@mock.patch("time.time", _mock_timer)
def test_authenticate_with_expired_auth_token(self):
url = get_url(IntegrationTest._JWKS_PATH)
self._provider_ids[self._ISSUER] = self._PROVIDER_ID
self._configs[IntegrationTest._ISSUER] = suppliers.IssuerUriConfig(False,
url)
IntegrationTest._mock_timer.return_value = 0
# Create an auth token that expires in 10 seconds.
jwt_claims = copy.deepcopy(IntegrationTest._JWT_CLAIMS)
jwt_claims["exp"] = time.time() + 10
auth_token = token_utils.generate_auth_token(jwt_claims,
IntegrationTest._jwks._keys,
alg="RS256",
kid=IntegrationTest._rsa_key.kid)
# Verify that the auth token can be authenticated successfully.
self._authenticator.authenticate(IntegrationTest._AUTH_TOKEN,
self._auth_info,
IntegrationTest._SERVICE_NAME)
# Advance the timer by 20 seconds and make sure the token is expired.
IntegrationTest._mock_timer.return_value += 20
message = "The auth token has already expired"
with self.assertRaisesRegexp(suppliers.UnauthenticatedException, message):
self._authenticator.authenticate(auth_token, self._auth_info,
IntegrationTest._SERVICE_NAME)
def test_invalid_openid_discovery_url(self):
issuer = "https://invalid.issuer"
self._provider_ids[self._ISSUER] = self._PROVIDER_ID
self._configs[issuer] = suppliers.IssuerUriConfig(True, None)
jwt_claims = copy.deepcopy(IntegrationTest._JWT_CLAIMS)
jwt_claims["iss"] = issuer
auth_token = token_utils.generate_auth_token(jwt_claims,
IntegrationTest._jwks._keys,
alg="RS256",
kid=IntegrationTest._rsa_key.kid)
message = "Cannot discover the jwks uri"
with self.assertRaisesRegexp(suppliers.UnauthenticatedException, message):
self._authenticator.authenticate(auth_token, self._auth_info,
IntegrationTest._SERVICE_NAME)
def test_invalid_jwks_uri(self):
url = "https://invalid.jwks.uri"
self._provider_ids[self._ISSUER] = self._PROVIDER_ID
self._configs[IntegrationTest._ISSUER] = suppliers.IssuerUriConfig(False,
url)
message = "Cannot retrieve valid verification keys from the `jwks_uri`"
with self.assertRaisesRegexp(suppliers.UnauthenticatedException, message):
self._authenticator.authenticate(IntegrationTest._AUTH_TOKEN,
self._auth_info,
IntegrationTest._SERVICE_NAME)
def _assert_user_info_equals(self, expected, actual):
self.assertEqual(expected.audiences, actual.audiences)
self.assertEqual(expected.email, actual.email)
self.assertEqual(expected.subject_id, actual.subject_id)
self.assertEqual(expected.issuer, actual.issuer)
class _RestServer(object):
def __init__(self):
app = flask.Flask("integration-test-server")
@app.route("/" + IntegrationTest._JWKS_PATH)
def get_json_web_key_set(): # pylint: disable=unused-variable
return IntegrationTest._jwks.dump_jwks()
@app.route("/" + IntegrationTest._X509_PATH)
def get_x509_certificates(): # pylint: disable=unused-variable
cert = IntegrationTest._rsa_key.key.publickey().exportKey("PEM")
return flask.jsonify({IntegrationTest._rsa_key.kid: cert})
@app.route("/" + IntegrationTest._INVALID_X509_PATH)
def get_invalid_x509_certificates(): # pylint: disable=unused-variable
return flask.jsonify({IntegrationTest._rsa_key.kid: "invalid cert"})
@app.route("/.well-known/openid-configuration")
def get_openid_configuration(): # pylint: disable=unused-variable
return flask.jsonify({"jwks_uri": get_url(IntegrationTest._JWKS_PATH)})
self._application = app
def start(self):
def run_app():
ssl_context = (IntegrationTest._cert_file, IntegrationTest._key_file)
self._application.run(port=IntegrationTest._PORT,
ssl_context=ssl_context)
thread = threading.Thread(target=run_app, args=())
thread.daemon = True
thread.start()
def get_url(path):
return "https://localhost:%d/%s" % (IntegrationTest._PORT, path)
| 6,524 |
1,020 | <reponame>icse18-refactorings/RoboBinding
package org.robobinding.widget.ratingbar;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.robobinding.property.ValueModel;
import org.robobinding.util.RandomValues;
import org.robobinding.viewattribute.ValueModelUtils;
import org.robobinding.widget.ratingbar.RatingAttribute.IntegerRatingAttribute;
import org.robolectric.annotation.Config;
/**
*
* @since 1.0
* @version $Revision: 1.0 $
* @author <NAME>
*/
@Config(manifest = Config.NONE)
public class IntegerRatingAttributeTest extends AbstractRatingBarAttributeTest {
private static final int NUM_STARS_TO_SHOW = 5;
private IntegerRatingAttribute attribute;
private int newRating;
@Before
public void prepareRatingBar() {
attribute = new IntegerRatingAttribute();
view.setNumStars(NUM_STARS_TO_SHOW);
newRating = RandomValues.nextIntegerGreaterThanZero(NUM_STARS_TO_SHOW);
}
@Test
public void whenUpdateView_thenViewShouldReflectChanges() {
attribute.updateView(view, newRating, null);
assertThat(view.getRating(), equalTo((float) newRating));
}
@Test
public void whenObserveChangesOnTheView_thenValueModelShouldReceiveTheChange() {
IntegerRatingAttribute attribute = new IntegerRatingAttribute();
ValueModel<Integer> valueModel = ValueModelUtils.create();
attribute.observeChangesOnTheView(viewAddOn, valueModel, view);
view.setRating(newRating);
assertThat((float) valueModel.getValue(), equalTo(view.getRating()));
}
@Test
public void whenObserveChangesOnTheView_thenRegisterWithMulticastListener() {
IntegerRatingAttribute attribute = new IntegerRatingAttribute();
attribute.observeChangesOnTheView(viewAddOn, null, view);
assertTrue(viewAddOn.addOnRatingBarChangeListenerInvoked);
}
}
| 592 |
11,356 | // Copyright <NAME> 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#ifndef BOOST_HANA_TEST_LAWS_RING_HPP
#define BOOST_HANA_TEST_LAWS_RING_HPP
#include <boost/hana/assert.hpp>
#include <boost/hana/bool.hpp>
#include <boost/hana/concept/comparable.hpp>
#include <boost/hana/concept/constant.hpp>
#include <boost/hana/concept/monoid.hpp>
#include <boost/hana/concept/ring.hpp>
#include <boost/hana/core/when.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/functional/capture.hpp>
#include <boost/hana/lazy.hpp>
#include <boost/hana/mult.hpp>
#include <boost/hana/not_equal.hpp>
#include <boost/hana/one.hpp>
#include <boost/hana/plus.hpp>
#include <boost/hana/power.hpp>
#include <boost/hana/value.hpp>
#include <laws/base.hpp>
namespace boost { namespace hana { namespace test {
template <typename R, typename = when<true>>
struct TestRing : TestRing<R, laws> {
using TestRing<R, laws>::TestRing;
};
template <typename R>
struct TestRing<R, laws> {
template <typename Xs>
TestRing(Xs xs) {
hana::for_each(xs, hana::capture(xs)([](auto xs, auto x) {
static_assert(Ring<decltype(x)>{}, "");
foreach2(xs, hana::capture(x)([](auto x, auto y, auto z) {
// associativity
BOOST_HANA_CHECK(hana::equal(
hana::mult(x, hana::mult(y, z)),
hana::mult(hana::mult(x, y), z)
));
// distributivity
BOOST_HANA_CHECK(hana::equal(
hana::mult(x, hana::plus(y, z)),
hana::plus(hana::mult(x, y), hana::mult(x, z))
));
}));
// right identity
BOOST_HANA_CHECK(hana::equal(
hana::mult(x, one<R>()), x
));
// left identity
BOOST_HANA_CHECK(hana::equal(
hana::mult(one<R>(), x), x
));
// power
BOOST_HANA_CHECK(hana::equal(
hana::power(x, int_c<0>),
one<R>()
));
BOOST_HANA_CHECK(hana::equal(
hana::power(x, int_c<1>),
x
));
BOOST_HANA_CHECK(hana::equal(
hana::power(x, int_c<2>),
hana::mult(x, x)
));
BOOST_HANA_CHECK(hana::equal(
hana::power(x, int_c<3>),
hana::mult(hana::mult(x, x), x)
));
BOOST_HANA_CHECK(hana::equal(
hana::power(x, int_c<4>),
hana::mult(hana::mult(hana::mult(x, x), x), x)
));
BOOST_HANA_CHECK(hana::equal(
hana::power(x, int_c<5>),
hana::mult(hana::mult(hana::mult(hana::mult(x, x), x), x), x)
));
}));
}
};
template <typename C>
struct TestRing<C, when<Constant<C>::value>>
: TestRing<C, laws>
{
template <typename Xs>
TestRing(Xs xs) : TestRing<C, laws>{xs} {
BOOST_HANA_CHECK(hana::equal(
hana::value(one<C>()),
one<typename C::value_type>()
));
foreach2(xs, [](auto x, auto y) {
BOOST_HANA_CHECK(hana::equal(
hana::mult(hana::value(x), hana::value(y)),
hana::value(hana::mult(x, y))
));
});
}
};
}}} // end namespace boost::hana::test
#endif // !BOOST_HANA_TEST_LAWS_RING_HPP
| 2,274 |
513 | /*
* The MIT License
*
* Copyright (C) 2017-2019 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "pmem.h"
#include "patomic.h"
#include "pcondvariable.h"
#include "plist.h"
#include "pmutex.h"
#include "puthread.h"
#include "puthread-private.h"
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#include <proto/exec.h>
#include <proto/dos.h>
#define PUTHREAD_AMIGA_MAX_TLS_KEYS 128
#define PUTHREAD_AMIGA_MIN_STACK 524288
#define PUTHREAD_AMIGA_MAX_CLEANS 4
typedef struct {
pboolean in_use;
PDestroyFunc free_func;
} PUThreadTLSKey;
typedef struct {
pint id;
struct Task *task;
jmp_buf jmpbuf;
ppointer tls_values[PUTHREAD_AMIGA_MAX_TLS_KEYS];
} PUThreadInfo;
struct PUThread_ {
PUThreadBase base;
PUThreadFunc proxy;
PCondVariable *join_cond;
struct Task *task;
};
typedef pint puthread_key_t;
struct PUThreadKey_ {
puthread_key_t key;
PDestroyFunc free_func;
};
static PMutex *pp_uthread_glob_mutex = NULL;
static PList *pp_uthread_list = NULL;
static pint pp_uthread_last_id = 0;
static PUThreadTLSKey pp_uthread_tls_keys[PUTHREAD_AMIGA_MAX_TLS_KEYS];
static pint pp_uthread_get_amiga_priority (PUThreadPriority prio);
static puthread_key_t pp_uthread_get_tls_key (PUThreadKey *key);
static pint pp_uthread_find_next_id (void);
static PUThreadInfo * pp_uthread_find_thread_info (struct Task *task);
static PUThreadInfo * pp_uthread_find_or_create_thread_info (struct Task *task);
static pint pp_uthread_amiga_proxy (void);
static pint
pp_uthread_get_amiga_priority (PUThreadPriority prio)
{
/* Priority limit is [-128, 127] */
switch (prio) {
case P_UTHREAD_PRIORITY_INHERIT:
return 0;
case P_UTHREAD_PRIORITY_IDLE:
return -128;
case P_UTHREAD_PRIORITY_LOWEST:
return -50;
case P_UTHREAD_PRIORITY_LOW:
return -25;
case P_UTHREAD_PRIORITY_NORMAL:
return 0;
case P_UTHREAD_PRIORITY_HIGH:
return 25;
case P_UTHREAD_PRIORITY_HIGHEST:
return 50;
case P_UTHREAD_PRIORITY_TIMECRITICAL:
return 127;
default:
return 0;
}
}
static puthread_key_t
pp_uthread_get_tls_key (PUThreadKey *key)
{
puthread_key_t thread_key;
pint key_idx;
thread_key = (puthread_key_t) p_atomic_int_get (&key->key);
if (P_LIKELY (thread_key >= 0))
return thread_key;
p_mutex_lock (pp_uthread_glob_mutex);
if (key->key >= 0) {
p_mutex_unlock (pp_uthread_glob_mutex);
return key->key;
}
/* Find free TLS key index */
for (key_idx = 0; key_idx < PUTHREAD_AMIGA_MAX_TLS_KEYS; ++key_idx) {
if (P_LIKELY (pp_uthread_tls_keys[key_idx].in_use == FALSE)) {
pp_uthread_tls_keys[key_idx].in_use = TRUE;
pp_uthread_tls_keys[key_idx].free_func = key->free_func;
break;
}
}
if (key_idx == PUTHREAD_AMIGA_MAX_TLS_KEYS) {
p_mutex_unlock (pp_uthread_glob_mutex);
P_ERROR ("PUThread::pp_uthread_get_tls_key: all slots for TLS keys are used");
return -1;
}
key->key = key_idx;
p_mutex_unlock (pp_uthread_glob_mutex);
return key_idx;
}
/* Must be used only inside a protected critical region */
static pint
pp_uthread_find_next_id (void)
{
PList *cur_list;
PUThreadInfo *thread_info;
pboolean have_dup;
pboolean was_found = FALSE;
pint cur_id = pp_uthread_last_id;
pint of_counter = 0;
while (was_found == FALSE && of_counter < 2) {
have_dup = FALSE;
cur_id = (cur_id == P_MAXINT32) ? 0 : cur_id + 1;
if (cur_id == 0)
++of_counter;
for (cur_list = pp_uthread_list; cur_list != NULL; cur_list = cur_list->next) {
thread_info = (PUThreadInfo *) cur_list->data;
if (thread_info->id == cur_id) {
have_dup = TRUE;
break;
}
}
if (have_dup == FALSE)
was_found = TRUE;
}
if (P_UNLIKELY (of_counter == 2))
return -1;
pp_uthread_last_id = cur_id;
return cur_id;
}
/* Must be used only inside a protected critical region */
static PUThreadInfo *
pp_uthread_find_thread_info (struct Task *task)
{
PList *cur_list;
PUThreadInfo *thread_info;
for (cur_list = pp_uthread_list; cur_list != NULL; cur_list = cur_list->next) {
thread_info = (PUThreadInfo *) cur_list->data;
if (thread_info->task == task)
return thread_info;
}
return NULL;
}
/* Must be used only inside a protected critical region */
static PUThreadInfo *
pp_uthread_find_or_create_thread_info (struct Task *task)
{
PUThreadInfo *thread_info;
pint task_id;
thread_info = pp_uthread_find_thread_info (task);
if (thread_info == NULL) {
/* Call is from a forein thread */
task_id = pp_uthread_find_next_id ();
if (P_UNLIKELY (task_id == -1)) {
/* Beyond the limit of the number of threads */
P_ERROR ("PUThread::pp_uthread_find_or_create_thread_info: no free thread slots left");
return NULL;
}
if (P_UNLIKELY ((thread_info = p_malloc0 (sizeof (PUThreadInfo))) == NULL)) {
P_ERROR ("PUThread::pp_uthread_find_or_create_thread_info: failed to allocate memory");
return NULL;
}
thread_info->id = task_id;
thread_info->task = task;
pp_uthread_list = p_list_append (pp_uthread_list, thread_info);
}
return thread_info;
}
static pint
pp_uthread_amiga_proxy (void)
{
PUThread *thread;
PUThreadInfo *thread_info;
struct Task *task;
PDestroyFunc dest_func;
ppointer dest_data;
pboolean need_pass;
pint i;
pint clean_counter;
/* Wait for outer routine to finish data initialization */
p_mutex_lock (pp_uthread_glob_mutex);
task = IExec->FindTask (NULL);
thread = (PUThread *) (task->tc_UserData);
thread_info = pp_uthread_find_thread_info (task);
p_mutex_unlock (pp_uthread_glob_mutex);
IExec->SetTaskPri (task, pp_uthread_get_amiga_priority (thread->base.prio));
if (!setjmp (thread_info->jmpbuf))
thread->proxy (thread);
/* Clean up TLS values */
p_mutex_lock (pp_uthread_glob_mutex);
need_pass = TRUE;
clean_counter = 0;
while (need_pass && clean_counter < PUTHREAD_AMIGA_MAX_CLEANS) {
need_pass = FALSE;
for (i = 0; i < PUTHREAD_AMIGA_MAX_TLS_KEYS; ++i) {
if (pp_uthread_tls_keys[i].in_use == TRUE) {
dest_func = pp_uthread_tls_keys[i].free_func;
dest_data = thread_info->tls_values[i];
if (dest_func != NULL && dest_data != NULL) {
/* Destructor may do some trick with TLS as well */
thread_info->tls_values[i] = NULL;
p_mutex_unlock (pp_uthread_glob_mutex);
(dest_func) (dest_data);
p_mutex_lock (pp_uthread_glob_mutex);
need_pass = TRUE;
}
}
}
++clean_counter;
}
pp_uthread_list = p_list_remove (pp_uthread_list, thread_info);
p_free (thread_info);
p_mutex_unlock (pp_uthread_glob_mutex);
/* Signal to possible waiter */
p_cond_variable_broadcast (thread->join_cond);
}
void
p_uthread_init_internal (void)
{
if (P_LIKELY (pp_uthread_glob_mutex == NULL)) {
pp_uthread_glob_mutex = p_mutex_new ();
pp_uthread_list = NULL;
pp_uthread_last_id = 0;
memset (pp_uthread_tls_keys, 0, sizeof (PUThreadTLSKey) * PUTHREAD_AMIGA_MAX_TLS_KEYS);
}
}
void
p_uthread_shutdown_internal (void)
{
PList *cur_list;
PUThreadInfo *thread_info;
PDestroyFunc dest_func;
ppointer dest_data;
pboolean need_pass;
pint i;
pint clean_counter;
/* Perform destructors */
p_mutex_lock (pp_uthread_glob_mutex);
need_pass = TRUE;
clean_counter = 0;
while (need_pass && clean_counter < PUTHREAD_AMIGA_MAX_CLEANS) {
need_pass = FALSE;
for (i = 0; i < PUTHREAD_AMIGA_MAX_TLS_KEYS; ++i) {
if (pp_uthread_tls_keys[i].in_use == FALSE)
continue;
dest_func = pp_uthread_tls_keys[i].free_func;
if (dest_func == NULL)
continue;
for (cur_list = pp_uthread_list; cur_list != NULL; cur_list = cur_list->next) {
thread_info = (PUThreadInfo *) cur_list->data;
dest_data = thread_info->tls_values[i];
if (dest_data != NULL) {
/* Destructor may do some trick with TLS as well */
thread_info->tls_values[i] = NULL;
p_mutex_unlock (pp_uthread_glob_mutex);
(dest_func) (dest_data);
p_mutex_lock (pp_uthread_glob_mutex);
need_pass = TRUE;
}
}
}
}
/* Clean the list */
p_list_foreach (pp_uthread_list, (PFunc) p_free, NULL);
p_list_free (pp_uthread_list);
pp_uthread_list = NULL;
p_mutex_unlock (pp_uthread_glob_mutex);
if (P_LIKELY (pp_uthread_glob_mutex != NULL)) {
p_mutex_free (pp_uthread_glob_mutex);
pp_uthread_glob_mutex = NULL;
}
}
void
p_uthread_win32_thread_detach (void)
{
}
void
p_uthread_free_internal (PUThread *thread)
{
if (thread->join_cond != NULL)
p_cond_variable_free (thread->join_cond);
p_free (thread);
}
PUThread *
p_uthread_create_internal (PUThreadFunc func,
pboolean joinable,
PUThreadPriority prio,
psize stack_size)
{
PUThread *ret;
PUThreadInfo *thread_info;
struct Task *task;
pint task_id;
if (P_UNLIKELY ((ret = p_malloc0 (sizeof (PUThread))) == NULL)) {
P_ERROR ("PUThread::p_uthread_create_internal: failed to allocate memory");
return NULL;
}
if (P_UNLIKELY ((ret->join_cond = p_cond_variable_new ()) == NULL)) {
P_ERROR ("PUThread::p_uthread_create_internal: failed to allocate condvar");
p_uthread_free_internal (ret);
return NULL;
}
if (P_UNLIKELY ((thread_info = p_malloc0 (sizeof (PUThreadInfo))) == NULL)) {
P_ERROR ("PUThread::p_uthread_create_internal: failed to allocate memory (2)");
p_uthread_free_internal (ret);
return NULL;
}
p_mutex_lock (pp_uthread_glob_mutex);
task_id = pp_uthread_find_next_id ();
if (P_UNLIKELY (task_id == -1)) {
p_mutex_unlock (pp_uthread_glob_mutex);
P_ERROR ("PUThread::p_uthread_create_internal: no free thread slots left");
p_uthread_free_internal (ret);
p_free (thread_info);
return NULL;
}
ret->proxy = func;
ret->base.prio = prio;
ret->base.joinable = joinable;
if (stack_size < PUTHREAD_AMIGA_MIN_STACK)
stack_size = PUTHREAD_AMIGA_MIN_STACK;
task = (struct Task *) IDOS->CreateNewProcTags (NP_Entry, pp_uthread_amiga_proxy,
NP_StackSize, stack_size,
NP_UserData, ret,
NP_Child, TRUE,
TAG_END);
if (P_UNLIKELY (task == NULL)) {
p_mutex_unlock (pp_uthread_glob_mutex);
P_ERROR ("PUThread::p_uthread_create_internal: CreateTaskTags() failed");
p_uthread_free_internal (ret);
p_free (thread_info);
return NULL;
}
thread_info->task = task;
thread_info->id = task_id;
pp_uthread_list = p_list_append (pp_uthread_list, thread_info);
ret->task = task;
p_mutex_unlock (pp_uthread_glob_mutex);
return ret;
}
void
p_uthread_exit_internal (void)
{
PUThreadInfo *thread_info;
p_mutex_lock (pp_uthread_glob_mutex);
thread_info = pp_uthread_find_thread_info (IExec->FindTask (NULL));
p_mutex_unlock (pp_uthread_glob_mutex);
if (P_UNLIKELY (thread_info == NULL)) {
P_WARNING ("PUThread::p_uthread_exit_internal: trying to exit from foreign thread");
return;
}
longjmp (thread_info->jmpbuf, 1);
}
void
p_uthread_wait_internal (PUThread *thread)
{
PUThreadInfo *thread_info;
p_mutex_lock (pp_uthread_glob_mutex);
thread_info = pp_uthread_find_thread_info (thread->task);
if (thread_info == NULL) {
p_mutex_unlock (pp_uthread_glob_mutex);
return;
}
p_cond_variable_wait (thread->join_cond, pp_uthread_glob_mutex);
p_mutex_unlock (pp_uthread_glob_mutex);
}
void
p_uthread_set_name_internal (PUThread *thread)
{
struct Task *task = thread->task;
task->tc_Node.ln_Name = thread->base.name;
}
P_LIB_API void
p_uthread_yield (void)
{
BYTE old_prio;
struct Task *task;
task = IExec->FindTask (NULL);
old_prio = IExec->SetTaskPri (task, -10);
IExec->SetTaskPri (task, old_prio);
}
P_LIB_API pboolean
p_uthread_set_priority (PUThread *thread,
PUThreadPriority prio)
{
if (P_UNLIKELY (thread == NULL))
return FALSE;
IExec->SetTaskPri (thread->task, pp_uthread_get_amiga_priority (prio));
thread->base.prio = prio;
return TRUE;
}
P_LIB_API P_HANDLE
p_uthread_current_id (void)
{
PUThreadInfo *thread_info;
p_mutex_lock (pp_uthread_glob_mutex);
thread_info = pp_uthread_find_or_create_thread_info (IExec->FindTask (NULL));
p_mutex_unlock (pp_uthread_glob_mutex);
if (P_UNLIKELY (thread_info == NULL))
P_WARNING ("PUThread::p_uthread_current_id: failed to integrate foreign thread");
return (thread_info == NULL) ? NULL : (P_HANDLE) ((psize) thread_info->id);
}
P_LIB_API PUThreadKey *
p_uthread_local_new (PDestroyFunc free_func)
{
PUThreadKey *ret;
if (P_UNLIKELY ((ret = p_malloc0 (sizeof (PUThreadKey))) == NULL)) {
P_ERROR ("PUThread::p_uthread_local_new: failed to allocate memory");
return NULL;
}
ret->key = -1;
ret->free_func = free_func;
return ret;
}
P_LIB_API void
p_uthread_local_free (PUThreadKey *key)
{
if (P_UNLIKELY (key == NULL))
return;
p_free (key);
}
P_LIB_API ppointer
p_uthread_get_local (PUThreadKey *key)
{
PUThreadInfo *thread_info;
puthread_key_t tls_key;
ppointer value = NULL;
if (P_UNLIKELY (key == NULL))
return NULL;
if (P_UNLIKELY ((tls_key = pp_uthread_get_tls_key (key)) == -1))
return NULL;
p_mutex_lock (pp_uthread_glob_mutex);
thread_info = pp_uthread_find_thread_info (IExec->FindTask (NULL));
if (P_LIKELY (thread_info != NULL))
value = thread_info->tls_values[tls_key];
p_mutex_unlock (pp_uthread_glob_mutex);
return value;
}
P_LIB_API void
p_uthread_set_local (PUThreadKey *key,
ppointer value)
{
PUThreadInfo *thread_info;
puthread_key_t tls_key;
if (P_UNLIKELY (key == NULL))
return;
tls_key = pp_uthread_get_tls_key (key);
if (P_LIKELY (tls_key != -1)) {
p_mutex_lock (pp_uthread_glob_mutex);
thread_info = pp_uthread_find_or_create_thread_info (IExec->FindTask (NULL));
if (P_LIKELY (thread_info != NULL)) {
if (P_LIKELY (pp_uthread_tls_keys[tls_key].in_use == TRUE))
thread_info->tls_values[tls_key] = value;
}
p_mutex_unlock (pp_uthread_glob_mutex);
}
}
P_LIB_API void
p_uthread_replace_local (PUThreadKey *key,
ppointer value)
{
PUThreadInfo *thread_info;
puthread_key_t tls_key;
ppointer old_value;
if (P_UNLIKELY (key == NULL))
return;
tls_key = pp_uthread_get_tls_key (key);
if (P_UNLIKELY (tls_key == -1))
return;
p_mutex_lock (pp_uthread_glob_mutex);
if (P_LIKELY (pp_uthread_tls_keys[tls_key].in_use == TRUE)) {
thread_info = pp_uthread_find_or_create_thread_info (IExec->FindTask (NULL));
if (P_LIKELY (thread_info != NULL)) {
old_value = thread_info->tls_values[tls_key];
if (old_value != NULL && key->free_func != NULL)
key->free_func (old_value);
thread_info->tls_values[tls_key] = value;
}
}
p_mutex_unlock (pp_uthread_glob_mutex);
}
| 6,662 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-78qc-3rq5-vcqr",
"modified": "2022-02-05T00:00:41Z",
"published": "2022-02-03T00:00:20Z",
"aliases": [
"CVE-2021-41018"
],
"details": "A improper neutralization of special elements used in an os command ('os command injection') in Fortinet FortiWeb version 6.4.1 and below, 6.3.15 and below allows attacker to execute unauthorized code or commands via crafted HTTP requests.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41018"
},
{
"type": "WEB",
"url": "https://fortiguard.com/advisory/FG-IR-21-166"
}
],
"database_specific": {
"cwe_ids": [
"CWE-78"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 362 |
1,056 | <filename>ide/xml.schema.model/test/unit/src/org/netbeans/modules/xml/schema/model/KeyRefTest.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.
*/
/*
* KeyRefTest.java
*
* Created on November 6, 2005, 9:02 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.netbeans.modules.xml.schema.model;
import java.util.Collection;
import junit.framework.TestCase;
/**
*
* @author rico
*/
public class KeyRefTest extends TestCase{
public static final String TEST_XSD = "resources/KeyRef.xsd";
/** Creates a new instance of KeyRefTest */
public KeyRefTest(String testcase) {
super(testcase);
}
Schema schema = null;
protected void setUp() throws Exception {
SchemaModel model = Util.loadSchemaModel(TEST_XSD);
schema = model.getSchema();
}
protected void tearDown() throws Exception {
TestCatalogModel.getDefault().clearDocumentPool();
}
public void testKeyRef(){
Collection<GlobalElement> elements = schema.getElements();
GlobalElement elem = elements.iterator().next();
LocalType localType = elem.getInlineType();
assertTrue("localType instanceof LocalComplexType",
localType instanceof LocalComplexType);
LocalComplexType lct = (LocalComplexType)localType;
ComplexTypeDefinition ctd = lct.getDefinition();
assertTrue("ComplextTypeDefinition instanceof Sequence",
ctd instanceof Sequence);
Sequence seq = (Sequence)ctd;
java.util.List <SequenceDefinition> seqDefs = seq.getContent();
SequenceDefinition seqDef = seqDefs.iterator().next();
assertTrue("SequenceDefinition instanceof LocalElement",
seqDef instanceof LocalElement);
LocalElement le = (LocalElement)seqDef;
Collection<Constraint> constraints = le.getConstraints();
Constraint constraint = constraints.iterator().next();
assertTrue("Constraint instanceof KeyRef", constraint instanceof KeyRef);
KeyRef keyRef = (KeyRef)constraint;
Constraint key = keyRef.getReferer();
System.out.println("key: " + key.getName());
assertEquals("Referred key", "pNumKey", key.getName());
}
}
| 1,043 |
335 | {
"word": "Orchestra",
"definitions": [
"A group of instrumentalists, especially one combining string, woodwind, brass, and percussion sections and playing classical music.",
"The part of a theatre where the orchestra plays, typically in front of the stage and on a lower level.",
"The stalls in a theatre.",
"The semicircular space in front of an ancient Greek theatre stage where the chorus danced and sang."
],
"parts-of-speech": "Noun"
} | 152 |
860 | <filename>src/test/gls/ch06/s05/JName1Test.java<gh_stars>100-1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package gls.ch06.s05;
import gls.ch06.s05.testClasses.Tt1cgi;
import gls.ch06.s05.testClasses.Tt1cgo;
import gls.ch06.s05.testClasses.Tt1gi;
import gls.ch06.s05.testClasses.Tt1go;
import groovy.lang.Closure;
import junit.framework.TestCase;
/*
* Copyright 2005 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* @author <NAME>
*/
public class JName1Test extends TestCase {
public void testObjectSupportNameHandling() {
final Tt1go obj = new Tt1go(); // Test subclass of GroovyObjectSupport
final String newX = "new x";
final String newX1 = "new x1";
final String newX2 = "new x2";
final String newX3 = "new x3";
assertTrue(obj.getProperty("x") == obj.getX());
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == obj.x);
assertTrue(obj.invokeMethod("x", new Object[]{}) == obj.x());
obj.setProperty("x", newX);
obj.getMetaClass().setAttribute(obj, "x", newX1);
assertTrue(obj.getProperty("x") == newX);
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == newX1);
obj.setX(newX2);
obj.x = newX3;
assertTrue(obj.getProperty("x") == newX2);
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == newX3);
}
public void testObjectSupportNameHandling1() {
final Tt1go obj = new Tt1go() {
}; // repeat test with subclass
final String newX = "new x";
final String newX1 = "new x1";
final String newX2 = "new x2";
final String newX3 = "new x3";
assertTrue(obj.getProperty("x") == obj.getX());
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == obj.x);
assertTrue(obj.invokeMethod("x", new Object[]{}) == obj.x());
obj.setProperty("x", newX);
obj.getMetaClass().setAttribute(obj, "x", newX1);
assertTrue(obj.getProperty("x") == newX);
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == newX1);
obj.setX(newX2);
obj.x = newX3;
assertTrue(obj.getProperty("x") == newX2);
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == newX3);
}
public void testObjectSupportNameHandlingWitnClosureValues() {
final Tt1cgo obj = new Tt1cgo(); // Test subclass of GroovyObjectSupport
final Closure newX = new Closure(null) {
public Object doCall(final Object params) {
return "new x";
}
};
final Closure newX1 = new Closure(null) {
public Object doCall(final Object params) {
return "new x1";
}
};
final Closure newX2 = new Closure(null) {
public Object doCall(final Object params) {
return "new x2";
}
};
final Closure newX3 = new Closure(null) {
public Object doCall(final Object params) {
return "new x3";
}
};
assertTrue(((Closure) obj.getProperty("x")).call() == obj.getX().call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == obj.x.call());
assertTrue(obj.invokeMethod("x", new Object[]{}) == obj.x());
obj.setProperty("x", newX);
obj.getMetaClass().setAttribute(obj, "x", newX1);
assertTrue(((Closure) obj.getProperty("x")).call() == newX.call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == newX1.call());
obj.setX(newX2);
obj.x = newX3;
assertTrue(((Closure) obj.getProperty("x")).call() == newX2.call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == newX3.call());
}
public void testObjectSupportNameHandlingWitnClosureValuesi() {
final Tt1cgo obj = new Tt1cgo() {
}; // repeat test with subclass
final Closure newX = new Closure(null) {
public Object doCall(final Object params) {
return "new x";
}
};
final Closure newX1 = new Closure(null) {
public Object doCall(final Object params) {
return "new x1";
}
};
final Closure newX2 = new Closure(null) {
public Object doCall(final Object params) {
return "new x2";
}
};
final Closure newX3 = new Closure(null) {
public Object doCall(final Object params) {
return "new x3";
}
};
assertTrue(((Closure) obj.getProperty("x")).call() == obj.getX().call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == obj.x.call());
assertTrue(obj.invokeMethod("x", new Object[]{}) == obj.x());
obj.setProperty("x", newX);
obj.getMetaClass().setAttribute(obj, "x", newX1);
assertTrue(((Closure) obj.getProperty("x")).call() == newX.call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == newX1.call());
obj.setX(newX2);
obj.x = newX3;
assertTrue(((Closure) obj.getProperty("x")).call() == newX2.call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == newX3.call());
}
public void testMetaClassNameHandling() {
final Tt1gi obj = new Tt1gi(); // Test class implementing GroovyObject
final String newX = "new x";
final String newX1 = "new x1";
final String newX2 = "new x2";
final String newX3 = "new x3";
assertTrue("dynamic property".equals(obj.getProperty("x")));
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == obj.x);
assertTrue("dynamic method".equals(obj.invokeMethod("x", new Object[]{})));
obj.setProperty("x", newX);
obj.getMetaClass().setAttribute(obj, "x", newX1);
assertTrue("dynamic property".equals(obj.getProperty("x")));
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == newX1);
obj.setX(newX2);
obj.x = newX3;
assertTrue("dynamic property".equals(obj.getProperty("x")));
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == newX3);
}
public void testMetaClassNameHandling1() {
final Tt1gi obj = new Tt1gi() {
}; // repeat test with subclass
final String newX = "new x";
final String newX1 = "new x1";
final String newX2 = "new x2";
final String newX3 = "new x3";
assertTrue("dynamic property".equals(obj.getProperty("x")));
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == obj.x);
assertTrue("dynamic method".equals(obj.invokeMethod("x", new Object[]{})));
obj.setProperty("x", newX);
obj.getMetaClass().setAttribute(obj, "x", newX1);
assertTrue("dynamic property".equals(obj.getProperty("x")));
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == newX1);
obj.setX(newX2);
obj.x = newX3;
assertTrue("dynamic property".equals(obj.getProperty("x")));
assertTrue(obj.getMetaClass().getAttribute(obj, "x") == newX3);
}
public void testMetaClassNameHandlingWithClosures() {
final Tt1cgi obj = new Tt1cgi(); // Test class implementing GroovyObject
final Closure newX = new Closure(null) {
public Object doCall(final Object params) {
return "new x";
}
};
final Closure newX1 = new Closure(null) {
public Object doCall(final Object params) {
return "new x1";
}
};
final Closure newX2 = new Closure(null) {
public Object doCall(final Object params) {
return "new x2";
}
};
final Closure newX3 = new Closure(null) {
public Object doCall(final Object params) {
return "new x3";
}
};
assertTrue(((Closure) obj.getProperty("x")).call() == obj.getX().call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == obj.x.call());
assertTrue(obj.invokeMethod("x", new Object[]{}) == obj.x());
obj.setProperty("x", newX);
obj.getMetaClass().setAttribute(obj, "x", newX1);
assertTrue(((Closure) obj.getProperty("x")).call() == newX.call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == newX1.call());
obj.setX(newX2);
obj.x = newX3;
assertTrue(((Closure) obj.getProperty("x")).call() == newX2.call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == newX3.call());
}
public void testMetaClassNameHandlingWithClosures1() {
final Tt1cgi obj = new Tt1cgi() {
}; // repeat test with subclass
final Closure newX = new Closure(null) {
public Object doCall(final Object params) {
return "new x";
}
};
final Closure newX1 = new Closure(null) {
public Object doCall(final Object params) {
return "new x1";
}
};
final Closure newX2 = new Closure(null) {
public Object doCall(final Object params) {
return "new x2";
}
};
final Closure newX3 = new Closure(null) {
public Object doCall(final Object params) {
return "new x3";
}
};
assertTrue(((Closure) obj.getProperty("x")).call() == obj.getX().call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == obj.x.call());
assertTrue(obj.invokeMethod("x", new Object[]{}) == obj.x());
obj.setProperty("x", newX);
obj.getMetaClass().setAttribute(obj, "x", newX1);
assertTrue(((Closure) obj.getProperty("x")).call() == newX.call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == newX1.call());
obj.setX(newX2);
obj.x = newX3;
assertTrue(((Closure) obj.getProperty("x")).call() == newX2.call());
assertTrue(((Closure) obj.getMetaClass().getAttribute(obj, "x")).call() == newX3.call());
}
}
| 5,000 |
460 | package com.microsoft.playwright;
import org.junit.jupiter.api.Test;
import java.net.MalformedURLException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class TestBrowserContextBaseUrl extends TestBase {
@Test
void shouldConstructANewURLWhenABaseURLInBrowserNewContextIsPassedToPageGoto() throws MalformedURLException {
try (BrowserContext context = browser.newContext(new Browser.NewContextOptions().setBaseURL(server.PREFIX))) {
Page page = context.newPage();
assertEquals(server.EMPTY_PAGE, page.navigate("/empty.html").url());
}
}
@Test
void shouldConstructANewURLWhenABaseURLInBrowserNewPageIsPassedToPageGoto() {
try (Page page = browser.newPage(new Browser.NewPageOptions().setBaseURL(server.PREFIX))) {
assertEquals(server.EMPTY_PAGE, page.navigate("/empty.html").url());
}
}
@Test
void shouldConstructTheURLsCorrectlyWhenABaseURLWithoutATrailingSlashInBrowserNewPageIsPassedToPageGoto() {
try (Page page = browser.newPage(new Browser.NewPageOptions().setBaseURL(server.PREFIX + "/url-construction"))) {
assertEquals(server.PREFIX + "/mypage.html", page.navigate("mypage.html").url());
assertEquals(server.PREFIX + "/mypage.html", page.navigate("./mypage.html").url());
assertEquals(server.PREFIX + "/mypage.html", page.navigate("/mypage.html").url());
}
}
@Test
void shouldConstructTheURLsCorrectlyWhenABaseURLWithATrailingSlashInBrowserNewPageIsPassedToPageGoto() {
try (Page page = browser.newPage(new Browser.NewPageOptions().setBaseURL(server.PREFIX + "/url-construction/"))) {
assertEquals(server.PREFIX + "/url-construction/mypage.html", page.navigate("mypage.html").url());
assertEquals(server.PREFIX + "/url-construction/mypage.html", page.navigate("./mypage.html").url());
assertEquals(server.PREFIX + "/mypage.html", page.navigate("/mypage.html").url());
assertEquals(server.PREFIX + "/url-construction/", page.navigate(".").url());
assertEquals(server.PREFIX + "/", page.navigate("/").url());
}
}
@Test
void shouldNotConstructANewURLWhenValidURLsArePassed() {
try (Page page = browser.newPage(new Browser.NewPageOptions().setBaseURL("http://microsoft.com"))) {
assertEquals(server.EMPTY_PAGE, page.navigate(server.EMPTY_PAGE).url());
page.navigate("data:text/html,Hello world");
assertEquals("data:text/html,Hello world", page.evaluate("window.location.href"));
page.navigate("about:blank");
assertEquals("about:blank", page.evaluate("window.location.href"));
}
}
@Test
void shouldBeAbleToMatchAURLRelativeToItsGivenURLWithUrlMatcher() {
try (Page page = browser.newPage(new Browser.NewPageOptions().setBaseURL(server.PREFIX + "/foobar/"))) {
page.navigate("/kek/index.html");
page.waitForURL("/kek/index.html");
assertEquals(server.PREFIX + "/kek/index.html", page.url());
page.route("./kek/index.html", route -> route.fulfill(new Route.FulfillOptions().setBody("base-url-matched-route")));
Request[] request = {null};
Response response = page.waitForResponse("./kek/index.html", () -> {
request[0] = page.waitForRequest("./kek/index.html", () -> {
page.navigate("./kek/index.html");
});
});
assertNotNull(request[0]);
assertNotNull(response);
assertEquals(server.PREFIX + "/foobar/kek/index.html", request[0].url());
assertEquals(server.PREFIX + "/foobar/kek/index.html", response.url());
assertEquals("base-url-matched-route", response.text());
}
}
}
| 1,357 |
854 | __________________________________________________________________________________________________
class Solution {
public int minKnightMoves(int x, int y) {
return (int)knightDistance(x, y);
}
public long knightDistance(long r, long c)
{
r = Math.abs(r); c = Math.abs(c);
if(r + c == 0)return 0;
if(r + c == 1)return 3;
if(r == 2 && c == 2)return 4;
long step = Math.max((r+1)/2, (c+1)/2);
step = Math.max(step, (r+c+2)/3);
step += (step^r^c)&1;
return step;
}
}
__________________________________________________________________________________________________
__________________________________________________________________________________________________
| 228 |
419 | <gh_stars>100-1000
/* Copyright (C) 2016 RDA Technologies Limited and/or its affiliates("RDA").
* All rights reserved.
*
* This software is supplied "AS IS" without any warranties.
* RDA assumes no responsibility or liability for the use of the software,
* conveys no license or title under any patent, copyright, or mask work
* right to the product. RDA reserves the right to make changes in the
* software without notification. RDA also make no representation or
* warranty that such application will be suitable for the specified use
* without further testing or modification.
*/
#include "stdint.h"
#include "stdbool.h"
#include "api_hal_gouda.h"
#include "lcd_config_params.h"
#include "api_debug.h"
#include "api_os.h"
#include "api_sys.h"
#include "hal_iomux.h"
#include "lcd.h"
// =============================================================================
//
// -----------------------------------------------------------------------------
// =============================================================================
//
// =============================================================================
// MACROS
// =============================================================================
#define LCM_WR_REG(Addr, Data) { while(hal_GoudaWriteReg(Addr, Data)!= HAL_ERR_NO);}
#define LCM_WR_DAT(Data) { while(hal_GoudaWriteData(Data) != HAL_ERR_NO);}
#define LCM_WR_CMD(Cmd) { while(hal_GoudaWriteCmd(Cmd) != HAL_ERR_NO);}
// =============================================================================
// GLOBAL VARIABLES
// =============================================================================
const HAL_GOUDA_LCD_CONFIG_T g_tgtLcddCfg = {
{.cs = HAL_GOUDA_LCD_CS_0,
.outputFormat = HAL_GOUDA_LCD_OUTPUT_FORMAT_16_bit_RGB565,
.cs0Polarity = false,
.cs1Polarity = false,
.rsPolarity = false,
.wrPolarity = false,
.rdPolarity = false,
.resetb = true}
};
bool g_lcddRotate = false;
// wheter lcddp_GoudaBlitHandler() has to close ovl layer 0
bool g_lcddAutoCloseLayer = false;
// Sleep status of the LCD
bool g_lcddInSleep = false;
// =============================================================================
// FUNCTIONS
// =============================================================================
// Lock to protect the access to the LCD screen during a DMA access.
// When 1, access is allowed. When 0, it is denied.
static volatile uint32_t g_lcddLock = 0;
// =============================================================================
// lcdd_MutexFree
// -----------------------------------------------------------------------------
/// Free a previously taken mutex. The ownership of the mutex is not checked.
/// Only free a mutex you have previously got.
/// @param
// =============================================================================
static void lcdd_MutexFree(void)
{
// Writing is an atomic operation
g_lcddLock = 1;
}
// =============================================================================
// lcdd_MutexGet
// -----------------------------------------------------------------------------
/// This function enter in critical section, read the value of the mutex and,
/// if this is a '1', returns '1' and set the mutex to 0. If this is a '0',
/// it does nothing. Then, in both cases, it exists the Critical Section.
///
/// @param
/// @return '1' if the mutex was taken, '0' otherwise.
// =============================================================================
static uint32_t lcdd_MutexGet(void)
{
uint32_t status;
uint32_t result;
status = SYS_EnterCriticalSection();
if (g_lcddLock == 1)
{
// Take the mutex
g_lcddLock = 0;
result = 1;
}
else
{
// Too bad ...
result = 0;
}
SYS_ExitCriticalSection(status);
return result;
}
static void (*pOnBlt)(void*) = NULL;
// =============================================================================
// lcddp_GoudaBlitHandler
// -----------------------------------------------------------------------------
/// This function frees the lock to access the screen. It is set as the user
/// handler called by the DMA driver at the end of the writings on the screen.
// =============================================================================
void lcddp_GoudaBlitHandler(void)
{
lcdd_MutexFree();
if(g_lcddAutoCloseLayer)
{
hal_GoudaOvlLayerClose(HAL_GOUDA_OVL_LAYER_ID0);
g_lcddAutoCloseLayer = false;
}
if(pOnBlt)
pOnBlt(NULL);
}
// =============================================================================
// lcddp_Init
// -----------------------------------------------------------------------------
/// This function initializes LCD registers after powering on or waking up.
// =============================================================================
static void lcddp_Init(void)
{
//************* Start Initial Sequence **********//
LCM_WR_CMD(0x11); //Exit Sleep
OS_Sleep(50);
LCM_WR_CMD(0xCB); //AP[2:0]
LCM_WR_DAT (0x01);
LCM_WR_CMD(0xC0); //Power control
LCM_WR_DAT (0x26); //VRH[5:0]
LCM_WR_DAT (0x08); //VC[2:0]
LCM_WR_CMD(0xC1); //Power control
LCM_WR_DAT (0x10); //SAP[2:0];BT[3:0]
LCM_WR_CMD(0xC5); //VCM control
LCM_WR_DAT (0x35);
LCM_WR_DAT (0x3E);
LCM_WR_CMD(0x36); // Memory Access Control
LCM_WR_DAT (0x48);
LCM_WR_CMD(0xB1); // Frame Rate Control
LCM_WR_DAT (0x00);
LCM_WR_DAT (0x16);
LCM_WR_CMD(0xB6); // Display Function Control
LCM_WR_DAT (0x0A);
LCM_WR_DAT (0x82);
LCM_WR_CMD(0xC7); // VCOM Control , VMF[6:0]
LCM_WR_DAT (0xB5);
LCM_WR_CMD(0xF2); // 3Gamma Function Disable
LCM_WR_DAT (0x00);
LCM_WR_CMD(0x26); //Gamma curve selected
LCM_WR_DAT (0x01);
LCM_WR_CMD(0x3A);
LCM_WR_DAT (0x55);
LCM_WR_CMD(0xE0); //Set Gamma
LCM_WR_DAT (0x1F);
LCM_WR_DAT (0x1A);
LCM_WR_DAT (0x18);
LCM_WR_DAT (0x0A);
LCM_WR_DAT (0x0F);
LCM_WR_DAT (0x06);
LCM_WR_DAT (0x45);
LCM_WR_DAT (0x87);
LCM_WR_DAT (0x32);
LCM_WR_DAT (0x0A);
LCM_WR_DAT (0x07);
LCM_WR_DAT (0x02);
LCM_WR_DAT (0x07);
LCM_WR_DAT (0x05);
LCM_WR_DAT (0x00);
LCM_WR_CMD(0XE1); //Set Gamma
LCM_WR_DAT (0x00);
LCM_WR_DAT (0x25);
LCM_WR_DAT (0x27);
LCM_WR_DAT (0x05);
LCM_WR_DAT (0x10);
LCM_WR_DAT (0x09);
LCM_WR_DAT (0x3A);
LCM_WR_DAT (0x78);
LCM_WR_DAT (0x4D);
LCM_WR_DAT (0x05);
LCM_WR_DAT (0x18);
LCM_WR_DAT (0x0D);
LCM_WR_DAT (0x38);
LCM_WR_DAT (0x3A);
LCM_WR_DAT (0x1F);
LCM_WR_CMD(0x29); //Display on
}
// ============================================================================
// lcddp_Open
// ----------------------------------------------------------------------------
/// Open the LCDD driver.
/// It must be called before any call to any other function of this driver.
/// This function is to be called only once.
/// @return #LCD_ERROR_NONE or #LCDD_ERR_DEVICE_NOT_FOUND.
// ============================================================================
static LCD_Error_t lcddp_Open(void)
{
hwp_iomux->pad_LCD_RSTB_cfg = IOMUX_PAD_LCD_RSTB_SEL(IOMUX_PAD_LCD_RSTB_SEL_FUN_LCD_RSTB_SEL);
hwp_iomux->pad_SPI_LCD_CS_cfg = IOMUX_PAD_SPI_LCD_CS_SEL(IOMUX_PAD_SPI_LCD_CS_SEL_FUN_SPI_LCD_CS_SEL);
hwp_iomux->pad_SPI_LCD_SCK_cfg = IOMUX_PAD_SPI_LCD_SCK_SEL(IOMUX_PAD_SPI_LCD_SCK_SEL_FUN_SPI_LCD_SCK_SEL);
hwp_iomux->pad_SPI_LCD_DIO_cfg = IOMUX_PAD_SPI_LCD_DIO_SEL(IOMUX_PAD_SPI_LCD_DIO_SEL_FUN_SPI_LCD_DIO_SEL);
hwp_iomux->pad_SPI_LCD_SDC_cfg = IOMUX_PAD_SPI_LCD_SDC_SEL(IOMUX_PAD_SPI_LCD_SDC_SEL_FUN_SPI_LCD_SDC_SEL);
Trace(1,"ili9341 lcddp_Open");
hal_GoudaSerialOpen(LCDD_SPI_LINE_TYPE, LCDD_SPI_FREQ, &g_tgtLcddCfg, 0);
// hal_GoudaSetBlock(1);//block wait for op complete
// Init code
OS_Sleep(50);
lcddp_Init();
g_lcddInSleep = false;
return LCD_ERROR_NONE;
}
// ============================================================================
// lcddp_Close
// ----------------------------------------------------------------------------
/// Close the LCDD driver
/// No other functions of this driver should be called after a call to
/// #lcddp_Close.
/// @return #LCD_ERROR_NONE or #LCDD_ERR_DEVICE_NOT_FOUND.
// ============================================================================
LCD_Error_t lcddp_Close(void)
{
hal_GoudaClose();
return LCD_ERROR_NONE;
}
// ============================================================================
// lcddp_SetContrast
// ----------------------------------------------------------------------------
/// Set the contrast of the 'main'LCD screen.
/// @param contrast Value to set the contrast to.
/// @return #LCD_ERROR_NONE, #LCD_ERROR_NONET_OPENED or
/// #LCD_ERROR_INVALID_PARAMETER.
// ============================================================================
LCD_Error_t lcddp_SetContrast(uint32_t contrast)
{
//#warning This function is not implemented yet
return LCD_ERROR_NONE;
}
// ============================================================================
// lcddp_Sleep
// ----------------------------------------------------------------------------
/// Set the main LCD screen in sleep mode.
/// @return #LCD_ERROR_NONE or #LCD_ERROR_NONET_OPENED
// ============================================================================
LCD_Error_t lcddp_Sleep(void)
{
while (0 == lcdd_MutexGet())
{
OS_Sleep(LCDD_TIME_MUTEX_RETRY);
Trace(1,"LCDD: Sleep while another LCD operation in progress. Sleep %d ticks",
LCDD_TIME_MUTEX_RETRY);
}
if (g_lcddInSleep)
{
lcdd_MutexFree();
return LCD_ERROR_NONE;
}
LCM_WR_CMD(0x0028); // Display off
LCM_WR_CMD(0x0010); // Enter Standby mode
Trace(1,"lcddp_Sleep: calling hal_GoudaClose");
hal_GoudaClose();
g_lcddInSleep = true;
lcdd_MutexFree();
return LCD_ERROR_NONE;
}
// ============================================================================
// lcddp_PartialOn
// ----------------------------------------------------------------------------
/// Set the Partial mode of the LCD
/// @param vsa : Vertical Start Active
/// @param vea : Vertical End Active
/// @return #LCD_ERROR_NONE, #LCD_ERROR_NONET_OPENED
// ============================================================================
LCD_Error_t lcddp_PartialOn(uint16_t vsa, uint16_t vea)
{
return LCD_ERROR_NONE;
}
// ============================================================================
// lcddp_PartialOff
// ----------------------------------------------------------------------------
/// return to Normal Mode
/// @return #LCD_ERROR_NONE, #LCD_ERROR_NONET_OPENED
// ============================================================================
LCD_Error_t lcddp_PartialOff(void)
{
return LCD_ERROR_NONE;
}
// ============================================================================
// lcddp_BlitRoi2Win
// ----------------------------------------------------------------------------
// Private function to transfer data to the LCD
// ============================================================================
void lcddp_BlitRoi2Win(const HAL_GOUDA_WINDOW_T* pRoi, const HAL_GOUDA_WINDOW_T* pActiveWin)
{
HAL_GOUDA_LCD_CMD_T cmd[13];
if(!((pRoi->tlPX < pRoi->brPX) && (pRoi->tlPY < pRoi->brPY)))
{
Trace(1,"lcddp_BlitRoi2Win: Invalid Roi x:%d < %d, y:%d < %d",pRoi->tlPX, pRoi->brPX, pRoi->tlPY, pRoi->brPY);
lcddp_GoudaBlitHandler();
return;
}
// building set roi sequence:
if(g_lcddRotate)
{
LCM_WR_CMD(0x2a); //Set Column Address
LCM_WR_DAT(pActiveWin->tlPX>>8);
LCM_WR_DAT(pActiveWin->tlPX&0x00ff);
LCM_WR_DAT(pActiveWin->brPX>>8);
LCM_WR_DAT(pActiveWin->brPX&0x00ff);
LCM_WR_CMD(0x2b); //Set Page Address
LCM_WR_DAT(pActiveWin->tlPY>>8);
LCM_WR_DAT(pActiveWin->tlPY&0x00ff);
LCM_WR_DAT(pActiveWin->brPY>>8);
LCM_WR_DAT(pActiveWin->brPY&0x00ff);
}
else
{
LCM_WR_CMD(0x2a); //Set Column Address
LCM_WR_DAT(pActiveWin->tlPX>>8);
LCM_WR_DAT(pActiveWin->tlPX&0x00ff);
LCM_WR_DAT(pActiveWin->brPX>>8);
LCM_WR_DAT(pActiveWin->brPX&0x00ff);
LCM_WR_CMD(0x2b); //Set Page Address
LCM_WR_DAT(pActiveWin->tlPY>>8);
LCM_WR_DAT(pActiveWin->tlPY&0x00ff);
LCM_WR_DAT(pActiveWin->brPY>>8);
LCM_WR_DAT(pActiveWin->brPY&0x00ff);
//LCM_WR_CMD(0x2c); //WRITE ram Data display
}
// Send command after which the data we sent
// are recognized as pixels.
LCM_WR_CMD(0x2c);
while (HAL_ERR_NO != hal_GoudaBlitRoi(pRoi, 0, cmd, lcddp_GoudaBlitHandler));
}
// ============================================================================
// lcddp_Blit16
// ----------------------------------------------------------------------------
/// This function provides the basic bit-block transfer capabilities.
/// This function copies the data (such as characters/bmp) on the LCD directly
/// as a (rectangular) block. The data is drawn in the active window.
/// The buffer has to be properly aligned (@todo define properly 'properly')
///
/// @param pPixelData Pointer to the buffer holding the data to be displayed
/// as a block. The dimension of this block are the one of the #pDestRect
/// parameter
/// @return #LCD_ERROR_NONE, #LCD_ERROR_RESOURCE_BUSY or #LCD_ERROR_NONET_OPENED.
// ============================================================================
LCD_Error_t lcddp_Blit16(const LCD_FBW_t* frameBufferWin, uint16_t startX, uint16_t startY)
{
// LCDD_ASSERT((frameBufferWin->fb.width&1) == 0, "LCDD: FBW must have an even number "
// "of pixels per line. Odd support is possible at the price of a huge "
// "performance lost");
// Active window coordinates.
HAL_GOUDA_WINDOW_T inputWin;
HAL_GOUDA_WINDOW_T activeWin;
if (0 == lcdd_MutexGet())
{
return LCD_ERROR_RESOURCE_BUSY;
}
else
{
if (g_lcddInSleep)
{
lcdd_MutexFree();
return LCD_ERROR_NONE;
}
// Set Input window
inputWin.tlPX = frameBufferWin->roi.x;
inputWin.brPX = frameBufferWin->roi.x + frameBufferWin->roi.width - 1;
inputWin.tlPY = frameBufferWin->roi.y;
inputWin.brPY = frameBufferWin->roi.y + frameBufferWin->roi.height - 1;
// Set Active window
activeWin.tlPX = startX;
activeWin.brPX = startX + frameBufferWin->roi.width - 1;
activeWin.tlPY = startY;
activeWin.brPY = startY + frameBufferWin->roi.height - 1;
// Check parameters
// ROI must be within the screen boundary
// ROI must be within the Frame buffer
// Color format must be 16 bits
bool badParam = false;
if (g_lcddRotate)
{
if ( (activeWin.tlPX >= LCDD_DISP_Y) ||
(activeWin.brPX >= LCDD_DISP_Y) ||
(activeWin.tlPY >= LCDD_DISP_X) ||
(activeWin.brPY >= LCDD_DISP_X)
)
{
badParam = true;
}
}
else
{
if ( (activeWin.tlPX >= LCDD_DISP_X) ||
(activeWin.brPX >= LCDD_DISP_X) ||
(activeWin.tlPY >= LCDD_DISP_Y) ||
(activeWin.brPY >= LCDD_DISP_Y)
)
{
badParam = true;
}
}
if (!badParam)
{
if ( (frameBufferWin->roi.width > frameBufferWin->fb.width) ||
(frameBufferWin->roi.height > frameBufferWin->fb.height) ||
(frameBufferWin->fb.colorFormat != LCD_COLOR_FORMAT_RGB_565)
)
{
badParam = true;;
}
}
if (badParam)
{
lcdd_MutexFree();
return LCD_ERROR_INVALID_PARAMETER;
}
// this will allow to keep LCDD interface for blit while using gouda
// directly for configuring layers
if (frameBufferWin->fb.buffer != NULL)
{
HAL_GOUDA_OVL_LAYER_DEF_T def;
// configure ovl layer 0 as buffer
def.addr = (uint32_t*)frameBufferWin->fb.buffer; // what about aligment ?
def.fmt = HAL_GOUDA_IMG_FORMAT_RGB565; //TODO convert from .colorFormat
//def.stride = frameBufferWin->fb.width * 2;
def.stride = 0; // let hal gouda decide
def.pos.tlPX = 0;
def.pos.tlPY = 0;
def.pos.brPX = frameBufferWin->fb.width - 1;
def.pos.brPY = frameBufferWin->fb.height - 1;
def.alpha = 255;
def.cKeyEn = false;
// open the layer
hal_GoudaOvlLayerClose(HAL_GOUDA_OVL_LAYER_ID0);
hal_GoudaOvlLayerOpen(HAL_GOUDA_OVL_LAYER_ID0, &def);
// tell the end handler not to close the layer when we are done
g_lcddAutoCloseLayer = false;
}
// gouda is doing everything ;)
lcddp_BlitRoi2Win(&inputWin, &activeWin);
return LCD_ERROR_NONE;
}
}
// ============================================================================
// lcddp_WakeUp
// ----------------------------------------------------------------------------
/// Wake the main LCD screen out of sleep mode
/// @return #LCD_ERROR_NONE, #LCD_ERROR_NONET_OPENED
// ============================================================================
LCD_Error_t lcddp_WakeUp(void)
{
if (0 == lcdd_MutexGet())
{
OS_Sleep(LCDD_TIME_MUTEX_RETRY);
Trace(1,"LCDD: Wakeup while another LCD operation in progress. Sleep %d ticks",
LCDD_TIME_MUTEX_RETRY);
}
if (!g_lcddInSleep)
{
lcdd_MutexFree();
return LCD_ERROR_NONE;
}
Trace(1,"lcddp_WakeUp: calling hal_GoudaOpen");
hal_GoudaSerialOpen(LCDD_SPI_LINE_TYPE, LCDD_SPI_FREQ, &g_tgtLcddCfg, 0);
#if 0
LCM_WR_REG(0x0010, 0x0000); // SAP, BT[3:0], AP, DSTB, SLP, STB
LCM_WR_REG(0x0011, 0x0007); // DC1[2:0], DC0[2:0], VC[2:0]
LCM_WR_REG(0x0012, 0x0000); // VREG1OUT voltage
LCM_WR_REG(0x0013, 0x0000); // VDV[4:0] for VCOM amplitude
sxr_Sleep(100 MS_WAITING); // Delay 50ms
LCM_WR_REG(0x0010, 0x1290); // SAP, BT[3:0], AP, DSTB, SLP, STB
LCM_WR_REG(0x0011, 0x0227); // R11h=0x0221 at VCI=3.3V, DC1[2:0], DC0[2:0], VC[2:0]
OS_Sleep(50); // Delay 50ms
LCM_WR_REG(0x0012, 0x0091); // External reference voltage= Vci
OS_Sleep(50); // Delay 50ms
LCM_WR_REG(0x0013, 0x1c00); // VDV[4:0] for VCOM amplitude
LCM_WR_REG(0x0029, 0x003b); // VCM[5:0] for VCOMH
OS_Sleep(50); // Delay 50ms
LCM_WR_REG(0x0007, 0x0133); // 262K color and display ON
#else
// Init code
OS_Sleep(50); // Delay 50 ms
lcddp_Init();
#endif
g_lcddInSleep = false;
lcdd_MutexFree();
// Set a comfortable background color to avoid screen flash
LCD_FBW_t frameBufferWin;
frameBufferWin.fb.buffer = NULL;
frameBufferWin.fb.colorFormat = LCD_COLOR_FORMAT_RGB_565;
frameBufferWin.roi.x=0;
frameBufferWin.roi.y=0;
if (g_lcddRotate)
{
frameBufferWin.roi.width = LCDD_DISP_Y;
frameBufferWin.roi.height = LCDD_DISP_X;
frameBufferWin.fb.width = LCDD_DISP_Y;
frameBufferWin.fb.height = LCDD_DISP_X;
}
else
{
frameBufferWin.roi.width = LCDD_DISP_X;
frameBufferWin.roi.height = LCDD_DISP_Y;
frameBufferWin.fb.width = LCDD_DISP_X;
frameBufferWin.fb.height = LCDD_DISP_Y;
}
lcddp_Blit16(&frameBufferWin,frameBufferWin.roi.x,frameBufferWin.roi.y);
return LCD_ERROR_NONE;
}
// ============================================================================
// lcddp_SetStandbyMode
// ----------------------------------------------------------------------------
/// Set the main LCD in standby mode or exit from it
/// @param standbyMode If \c true, go in standby mode.
/// If \c false, cancel standby mode.
/// @return #LCD_ERROR_NONE, #LCD_ERROR_NONET_OPENED or
/// #LCD_ERROR_INVALID_PARAMETER.
// ============================================================================
LCD_Error_t lcddp_SetStandbyMode(bool standbyMode)
{
if (standbyMode)
{
lcddp_Sleep();
}
else
{
lcddp_WakeUp();
}
return LCD_ERROR_NONE;
}
// ============================================================================
// lcddp_GetScreenInfo
// ----------------------------------------------------------------------------
/// Get information about the main LCD device.
/// @param screenInfo Pointer to the structure where the information
/// obtained will be stored
/// @return #LCD_ERROR_NONE, #LCD_ERROR_NONET_OPENED or
/// #LCD_ERROR_INVALID_PARAMETER.
// ============================================================================
LCD_Error_t lcddp_GetScreenInfo(LCD_Screen_Info_t* screenInfo)
{
screenInfo->width = LCDD_DISP_X;
screenInfo->height = LCDD_DISP_Y;
screenInfo->bitdepth = LCD_COLOR_FORMAT_RGB_565;
screenInfo->nReserved = 0;
return LCD_ERROR_NONE;
}
// ============================================================================
// lcddp_SetPixel16
// ----------------------------------------------------------------------------
/// Draw a 16-bit pixel a the specified position.
/// @param x X coordinate of the point to set.
/// @param y Y coordinate of the point to set.
/// @param pixelData 16-bit pixel data to draw.
/// @return #LCD_ERROR_NONE, #LCD_ERROR_RESOURCE_BUSY or #LCD_ERROR_NONET_OPENED.
// ============================================================================
LCD_Error_t lcddp_SetPixel16(uint16_t x, uint16_t y, uint16_t pixelData)
{
if (0 == lcdd_MutexGet())
{
return LCD_ERROR_RESOURCE_BUSY;
}
else
{
if (g_lcddInSleep)
{
lcdd_MutexFree();
return LCD_ERROR_NONE;
}
LCM_WR_CMD(0x2a); //Set Column Address
LCM_WR_DAT(x>>8);
LCM_WR_DAT(x&0x00ff);
LCM_WR_DAT(x>>8);
LCM_WR_DAT(x&0x00ff);
LCM_WR_CMD(0x2b); //Set Page Address
LCM_WR_DAT(y>>8);
LCM_WR_DAT(y&0x00ff);
LCM_WR_DAT(y>>8);
LCM_WR_DAT(y&0x00ff);
LCM_WR_REG(0x2c, pixelData);
lcdd_MutexFree();
return LCD_ERROR_NONE;
}
}
// ============================================================================
// lcddp_FillRect16
// ----------------------------------------------------------------------------
/// This function performs a fill of the active window with some color.
/// @param bgColor Color with which to fill the rectangle. It is a 16-bit
/// data, as the one of #lcddp_SetPixel16
/// @return #LCD_ERROR_NONE, #LCD_ERROR_RESOURCE_BUSY or #LCD_ERROR_NONET_OPENED.
// ============================================================================
LCD_Error_t lcddp_FillRect16(const LCD_ROI_t* regionOfInterrest, uint16_t bgColor)
{
// Active window coordinates.
HAL_GOUDA_WINDOW_T activeWin;
if (0 == lcdd_MutexGet())
{
return LCD_ERROR_RESOURCE_BUSY;
}
else
{
if (g_lcddInSleep)
{
lcdd_MutexFree();
return LCD_ERROR_NONE;
}
// Set Active window
activeWin.tlPX = regionOfInterrest->x;
activeWin.brPX = regionOfInterrest->x + regionOfInterrest->width - 1;
activeWin.tlPY = regionOfInterrest->y;
activeWin.brPY = regionOfInterrest->y + regionOfInterrest->height - 1;
// Check parameters
// ROI must be within the screen boundary
bool badParam = false;
if (g_lcddRotate)
{
if ( (activeWin.tlPX >= LCDD_DISP_Y) ||
(activeWin.brPX >= LCDD_DISP_Y) ||
(activeWin.tlPY >= LCDD_DISP_X) ||
(activeWin.brPY >= LCDD_DISP_X)
)
{
badParam = true;
}
}
else
{
if ( (activeWin.tlPX >= LCDD_DISP_X) ||
(activeWin.brPX >= LCDD_DISP_X) ||
(activeWin.tlPY >= LCDD_DISP_Y) ||
(activeWin.brPY >= LCDD_DISP_Y)
)
{
badParam = true;
}
}
if (badParam)
{
lcdd_MutexFree();
return LCD_ERROR_INVALID_PARAMETER;
}
hal_GoudaSetBgColor(bgColor);
lcddp_BlitRoi2Win(&activeWin,&activeWin);
return LCD_ERROR_NONE;
}
}
// ============================================================================
// lcddp_Busy
// ----------------------------------------------------------------------------
/// This function is not implemented for the ebc version of the driver
// ============================================================================
bool lcddp_Busy(void)
{
return hal_GoudaIsActive();
}
// ============================================================================
// lcddp_SetDirRotation
// ----------------------------------------------------------------------------
///
// ============================================================================
bool lcddp_SetDirRotation(void)
{
while (0 == lcdd_MutexGet())
{
OS_Sleep(LCDD_TIME_MUTEX_RETRY);
}
g_lcddRotate = true;
if (g_lcddInSleep)
{
lcdd_MutexFree();
return true;
}
LCM_WR_CMD(0x36); // Memory Access Control
LCM_WR_DAT (0x28);
lcdd_MutexFree();
return true;
}
// ============================================================================
// lcddp_SetDirDefault
// ----------------------------------------------------------------------------
///
// ============================================================================
bool lcddp_SetDirDefault(void)
{
while (0 == lcdd_MutexGet())
{
OS_Sleep(LCDD_TIME_MUTEX_RETRY);
}
g_lcddRotate = false;
if (g_lcddInSleep)
{
lcdd_MutexFree();
return true;
}
LCM_WR_CMD(0x36); // Memory Access Control
LCM_WR_DAT (0x48);
lcdd_MutexFree();
return true;
}
char* lcddp_GetStringId(void)
{
static char ili9341_id_str[] = "ili9341\n";
return ili9341_id_str;
}
bool lcddp_CheckProductId()
{
#ifdef LCD_NO_PRODUCT_ID
return true;
#else
uint16_t productIds[4];
uint16_t productId=0;
hal_GoudaSerialOpen(LCDD_SPI_LINE_TYPE, LCDD_SPI_FREQ, &g_tgtLcddCfg, 0);
OS_Sleep(20);
hal_GoudaReadData(0xd3,productIds,4);
productId=productIds[2]<<8;
productId=(productId&0xff00)|(productIds[3]&0xff);
hal_GoudaClose();
Trace(1,"ili9341(0x%x): lcd read id is 0x%x ", LCD_ILI9341_ID, productId);
if(productId == LCD_ILI9341_ID)
return true;
else
return false;
#endif
}
// ============================================================================
// lcdd_ili9341_RegInit
// ----------------------------------------------------------------------------
/// register the right lcd driver, according to lcddp_CheckProductId
/// @return #true, #false
// ============================================================================
// PUBLIC bool lcdd_ili9341_RegInit(LCDD_REG_T *pLcdDrv)
// {
// if( lcddp_CheckProductId())
// {
// pLcdDrv->lcdd_Open=lcddp_Open;
// pLcdDrv->lcdd_Close=lcddp_Close;
// pLcdDrv->lcdd_SetContrast=lcddp_SetContrast;
// pLcdDrv->lcdd_SetStandbyMode=lcddp_SetStandbyMode;
// pLcdDrv->lcdd_PartialOn=lcddp_PartialOn;
// pLcdDrv->lcdd_PartialOff=lcddp_PartialOff;
// pLcdDrv->lcdd_Blit16=lcddp_Blit16;
// pLcdDrv->lcdd_Busy=lcddp_Busy;
// pLcdDrv->lcdd_FillRect16=lcddp_FillRect16;
// pLcdDrv->lcdd_GetScreenInfo=lcddp_GetScreenInfo;
// pLcdDrv->lcdd_WakeUp=lcddp_WakeUp;
// pLcdDrv->lcdd_SetPixel16=lcddp_SetPixel16;
// pLcdDrv->lcdd_Sleep=lcddp_Sleep;
// pLcdDrv->lcdd_SetDirRotation=lcddp_SetDirRotation;
// pLcdDrv->lcdd_SetDirDefault=lcddp_SetDirDefault;
// pLcdDrv->lcdd_GetStringId=lcdd_get_id_string;
// pLcdDrv->lcdd_GoudaBltHdl = lcddp_GoudaBlitHandler;
// return true;
// }
// return false;
// }
LCD_Error_t lcddp_SetBrightness(uint8_t brightness)
{
return LCD_ERROR_NONE;
}
uint16_t lcddp_GetLcdId()
{
return 0x0000;
}
#include "lcd.h"
LCD_Error_t LCD_ili9341_Register(LCD_OP_t* reg,void(*onBlit)(void*))
{
// if( lcddp_CheckProductId())
{
reg->Open = lcddp_Open;
reg->Close = lcddp_Close;
reg->SetContrast = lcddp_SetContrast;
reg->SetBrightness = lcddp_SetBrightness;
reg->SetStandbyMode = lcddp_SetStandbyMode;
reg->Sleep = lcddp_Sleep;
reg->PartialOn = lcddp_PartialOn;
reg->PartialOff = lcddp_PartialOff;
reg->WakeUp = lcddp_WakeUp;
reg->GetScreenInfo = lcddp_GetScreenInfo;
reg->SetPixel16 = lcddp_SetPixel16;
reg->FillRect16 = lcddp_FillRect16;
reg->Blit16 = lcddp_Blit16;
reg->Busy = lcddp_Busy;
reg->SetDirRotation = lcddp_SetDirRotation;
reg->SetDirDefault = lcddp_SetDirDefault;
reg->GetStringId = lcddp_GetStringId;
reg->GetLcdId = lcddp_GetLcdId;
// reg->OnBlt = pOnBlit;
pOnBlt = onBlit;
}
lcdd_MutexFree();
return LCD_ERROR_NONE;
}
| 12,733 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.